query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Merges two lists together. @param one first list @param two second list @return merged lists
[ "private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) {\n final Set<Point2D> oneSet = new HashSet<Point2D>(one);\n for (Point2D item : two) {\n if (!oneSet.contains(item)) {\n one.add(item);\n }\n }\n return one;\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 base_responses enable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface enableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tenableresources[i] = new Interface();\n\t\t\t\tenableresources[i].id = id[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}", "public void setConnectTimeout(int millis) {\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t}", "public TransformersSubRegistration getServerRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST, SERVER);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }", "public JsonNode wbSetLabel(String id, String site, String title,\n\t\t\tString newEntity, String language, String value,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting a label\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (value != null) {\n\t\t\tparameters.put(\"value\", value);\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetlabel\", id, site, title, newEntity,\n\t\t\t\tparameters, summary, baserevid, bot);\n\t\treturn response;\n\t}", "public static void copyStream(final InputStream src, OutputStream dest) throws IOException {\r\n byte[] buffer = new byte[1024];\r\n int read;\r\n while ((read = src.read(buffer)) > -1) {\r\n dest.write(buffer, 0, read);\r\n }\r\n dest.flush();\r\n }", "void fileWritten() throws ConfigurationPersistenceException {\n if (!doneBootup.get() || interactionPolicy.isReadOnly()) {\n return;\n }\n try {\n FilePersistenceUtils.copyFile(mainFile, lastFile);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\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 Cluster vacateZone(Cluster currentCluster, int dropZoneId) {\n Cluster returnCluster = Cluster.cloneCluster(currentCluster);\n // Go over each node in the zone being dropped\n for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) {\n // For each node grab all the partitions it hosts\n for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) {\n // Now for each partition find a new home..which would be a node\n // in one of the existing zones\n int finalZoneId = -1;\n int finalNodeId = -1;\n int adjacentPartitionId = partitionId;\n do {\n adjacentPartitionId = (adjacentPartitionId + 1)\n % currentCluster.getNumberOfPartitions();\n finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId();\n finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId();\n if(adjacentPartitionId == partitionId) {\n logger.error(\"PartitionId \" + partitionId + \"stays unchanged \\n\");\n } else {\n logger.info(\"PartitionId \" + partitionId\n + \" goes together with partition \" + adjacentPartitionId\n + \" on node \" + finalNodeId + \" in zone \" + finalZoneId);\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n finalNodeId,\n Lists.newArrayList(partitionId));\n }\n } while(finalZoneId == dropZoneId);\n }\n }\n return returnCluster;\n }" ]
Extracts calendar data from a ConceptDraw PROJECT file. @param cdp ConceptDraw PROJECT file
[ "private void readCalendars(Document cdp)\n {\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n readCalendar(calendar);\n }\n\n for (Calendar calendar : cdp.getCalendars().getCalendar())\n {\n ProjectCalendar child = m_calendarMap.get(calendar.getID());\n ProjectCalendar parent = m_calendarMap.get(calendar.getBaseCalendarID());\n if (parent == null)\n {\n m_projectFile.setDefaultCalendar(child);\n }\n else\n {\n child.setParent(parent);\n }\n }\n }" ]
[ "public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }", "@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal);\n }", "public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }", "public static base_responses add(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager addresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpmanager();\n\t\t\t\taddresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\taddresources[i].netmask = resources[i].netmask;\n\t\t\t\taddresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"classes.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Image\"\n\t\t\t\t\t+ \",Number of direct instances\"\n\t\t\t\t\t+ \",Number of direct subclasses\" + \",Direct superclasses\"\n\t\t\t\t\t+ \",All superclasses\" + \",Related properties\");\n\n\t\t\tList<Entry<EntityIdValue, ClassRecord>> list = new ArrayList<>(\n\t\t\t\t\tthis.classRecords.entrySet());\n\t\t\tCollections.sort(list, new ClassUsageRecordComparator());\n\t\t\tfor (Entry<EntityIdValue, ClassRecord> entry : list) {\n\t\t\t\tif (entry.getValue().itemCount > 0\n\t\t\t\t\t\t|| entry.getValue().subclassCount > 0) {\n\t\t\t\t\tprintClassRecord(out, entry.getValue(), entry.getKey());\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public Gallery lookupGallery(String galleryId) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GALLERY);\r\n parameters.put(\"url\", galleryId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element galleryElement = response.getPayload();\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"secret\"));\r\n\r\n gallery.setTitle(XMLUtilities.getChildValue(galleryElement, \"title\"));\r\n gallery.setDesc(XMLUtilities.getChildValue(galleryElement, \"description\"));\r\n return gallery;\r\n }", "public static boolean blockAligned( int blockLength , DSubmatrixD1 A ) {\n if( A.col0 % blockLength != 0 )\n return false;\n if( A.row0 % blockLength != 0 )\n return false;\n\n if( A.col1 % blockLength != 0 && A.col1 != A.original.numCols ) {\n return false;\n }\n\n if( A.row1 % blockLength != 0 && A.row1 != A.original.numRows) {\n return false;\n }\n\n return true;\n }", "public void setOptions(Doc p) {\n\tif (p == null)\n\t return;\n\n\tfor (Tag tag : p.tags(\"opt\"))\n\t setOption(StringUtil.tokenize(tag.text()));\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -hide parameter.\n * @return true if the string matches.\n */\n public boolean matchesHideExpression(String s) {\n\tfor (Pattern hidePattern : hidePatterns) {\n\t // micro-optimization because the \"all pattern\" is heavily used in UmlGraphDoc\n\t if(hidePattern == allPattern)\n\t\treturn true;\n\t \n\t Matcher m = hidePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n /**\n * Check if the supplied string matches an entity specified\n * with the -include parameter.\n * @return true if the string matches.\n */\n public boolean matchesIncludeExpression(String s) {\n\tfor (Pattern includePattern : includePatterns) {\n\t Matcher m = includePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -collpackages parameter.\n * @return true if the string matches.\n */\n public boolean matchesCollPackageExpression(String s) {\n\tfor (Pattern collPattern : collPackages) {\n\t Matcher m = collPattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n // ---------------------------------------------------------------- \n // OptionProvider methods\n // ---------------------------------------------------------------- \n \n public Options getOptionsFor(ClassDoc cd) {\n\tOptions localOpt = getGlobalOptions();\n\tlocalOpt.setOptions(cd);\n\treturn localOpt;\n }\n\n public Options getOptionsFor(String name) {\n\treturn getGlobalOptions();\n }\n\n public Options getGlobalOptions() {\n\treturn (Options) clone();\n }\n\n public void overrideForClass(Options opt, ClassDoc cd) {\n\t// nothing to do\n }" ]
note this string is used by hashCode
[ "@Override\n\tpublic String toNormalizedWildcardString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedWildcardString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedWildcardString = result = toNormalizedString(IPv6StringCache.wildcardNormalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedWildcardString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private void remove() {\n if (removing) {\n return;\n }\n if (deactiveNotifications.size() == 0) {\n return;\n }\n removing = true;\n final NotificationPopupView view = deactiveNotifications.get(0);\n final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) {\n\n @Override\n public void onUpdate(double progress) {\n super.onUpdate(progress);\n for (int i = 0; i < activeNotifications.size(); i++) {\n NotificationPopupView v = activeNotifications.get(i);\n final int left = v.getPopupLeft();\n final int top = (int) (((i + 1) * SPACING) - (progress * SPACING));\n v.setPopupPosition(left,\n top);\n }\n }\n\n @Override\n public void onComplete() {\n super.onComplete();\n view.hide();\n deactiveNotifications.remove(view);\n activeNotifications.remove(view);\n removing = false;\n remove();\n }\n };\n fadeOutAnimation.run(500);\n }", "public static systemcollectionparam get(nitro_service service) throws Exception{\n\t\tsystemcollectionparam obj = new systemcollectionparam();\n\t\tsystemcollectionparam[] response = (systemcollectionparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "static int excessArgumentsMatchesVargsParameter(Parameter[] params, ClassNode[] args) {\n // we already know parameter length is bigger zero and last is a vargs\n // the excess arguments are all put in an array for the vargs call\n // so check against the component type\n int dist = 0;\n ClassNode vargsBase = params[params.length - 1].getType().getComponentType();\n for (int i = params.length; i < args.length; i++) {\n if (!isAssignableTo(args[i],vargsBase)) return -1;\n else if (!args[i].equals(vargsBase)) dist+=getDistance(args[i], vargsBase);\n }\n return dist;\n }", "private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}", "public FieldType getFieldTypeFromVarDataKey(Integer key)\n {\n FieldType result = null;\n for (Entry<FieldType, FieldMap.FieldItem> entry : m_map.entrySet())\n {\n if (entry.getValue().getFieldLocation() == FieldLocation.VAR_DATA && entry.getValue().getVarDataKey().equals(key))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "public static base_response add(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser addresource = new systemuser();\n\t\taddresource.username = resource.username;\n\t\taddresource.password = resource.password;\n\t\taddresource.externalauth = resource.externalauth;\n\t\taddresource.promptstring = resource.promptstring;\n\t\taddresource.timeout = resource.timeout;\n\t\treturn addresource.add_resource(client);\n\t}", "public void add(Map<String, Object> map) throws SQLException {\n if (withinDataSetBatch) {\n if (batchData.size() == 0) {\n batchKeys = map.keySet();\n } else {\n if (!map.keySet().equals(batchKeys)) {\n throw new IllegalArgumentException(\"Inconsistent keys found for batch add!\");\n }\n }\n batchData.add(map);\n return;\n }\n int answer = executeUpdate(buildListQuery(map), new ArrayList<Object>(map.values()));\n if (answer != 1) {\n LOG.warning(\"Should have updated 1 row not \" + answer + \" when trying to add: \" + map);\n }\n }", "public static void copy(byte[] in, OutputStream out) throws IOException {\n\t\tAssert.notNull(in, \"No input byte array specified\");\n\t\tAssert.notNull(out, \"No OutputStream specified\");\n\t\tout.write(in);\n\t}", "private void saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }" ]
Use this API to fetch filterpolicy_csvserver_binding resources of given name .
[ "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 List<CmsUser> getVisibleUser() {\n\n if (!m_fullyLoaded) {\n return m_users;\n }\n if (size() == m_users.size()) {\n return m_users;\n }\n List<CmsUser> directs = new ArrayList<CmsUser>();\n for (CmsUser user : m_users) {\n if (!m_indirects.contains(user)) {\n directs.add(user);\n }\n }\n return directs;\n }", "private Set<T> findMatching(R resolvable) {\n Set<T> result = new HashSet<T>();\n for (T bean : getAllBeans(resolvable)) {\n if (matches(resolvable, bean)) {\n result.add(bean);\n }\n }\n return result;\n }", "public byte[] serialize() throws PersistenceBrokerException\r\n {\r\n // Identity is serialized and written to an ObjectOutputStream\r\n // This ObjectOutputstream is compressed by a GZIPOutputStream\r\n // and finally written to a ByteArrayOutputStream.\r\n // the resulting byte[] is returned\r\n try\r\n {\r\n final ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n final GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n final ObjectOutputStream oos = new ObjectOutputStream(gos);\r\n oos.writeObject(this);\r\n oos.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }\r\n catch (Exception ignored)\r\n {\r\n throw new PersistenceBrokerException(ignored);\r\n }\r\n }", "private void useSearchService() throws Exception {\n\n System.out.println(\"Searching...\");\n\n WebClient wc = WebClient.create(\"http://localhost:\" + port + \"/services/personservice/search\");\n WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);\n wc.accept(MediaType.APPLICATION_XML);\n \n // Moves to \"/services/personservice/search\"\n wc.path(\"person\");\n \n SearchConditionBuilder builder = SearchConditionBuilder.instance(); \n \n System.out.println(\"Find people with the name Fred or Lorraine:\");\n \n String query = builder.is(\"name\").equalTo(\"Fred\").or()\n .is(\"name\").equalTo(\"Lorraine\")\n .query();\n findPersons(wc, query);\n \n System.out.println(\"Find all people who are no more than 30 years old\");\n query = builder.is(\"age\").lessOrEqualTo(30)\n \t\t.query();\n \n findPersons(wc, query);\n \n System.out.println(\"Find all people who are older than 28 and whose father name is John\");\n query = builder.is(\"age\").greaterThan(28)\n \t\t.and(\"fatherName\").equalTo(\"John\")\n \t\t.query();\n \n findPersons(wc, query);\n\n System.out.println(\"Find all people who have children with name Fred\");\n query = builder.is(\"childName\").equalTo(\"Fred\")\n \t\t.query();\n \n findPersons(wc, query);\n \n //Moves to \"/services/personservice/personinfo\"\n wc.reset().accept(MediaType.APPLICATION_XML);\n wc.path(\"personinfo\");\n \n System.out.println(\"Find all people younger than 40 using JPA2 Tuples\");\n query = builder.is(\"age\").lessThan(40).query();\n \n // Use URI path component to capture the query expression\n wc.path(query);\n \n \n Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);\n for (PersonInfo pi : personInfos) {\n \tSystem.out.println(\"ID : \" + pi.getId());\n }\n\n wc.close();\n }", "public static void normalizeF( DMatrixRMaj A ) {\n double val = normF(A);\n\n if( val == 0 )\n return;\n\n int size = A.getNumElements();\n\n for( int i = 0; i < size; i++) {\n A.div(i , val);\n }\n }", "public static int serialize(final File directory, String name, Object obj) {\n try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) {\n return serialize(stream, obj);\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }", "@Override public void close() throws IOException\n {\n long skippedLast = 0;\n if (m_remaining > 0)\n {\n skippedLast = skip(m_remaining);\n while (m_remaining > 0 && skippedLast > 0)\n {\n skippedLast = skip(m_remaining);\n }\n }\n }", "protected ObjectPool setupPool(JdbcConnectionDescriptor jcd)\r\n {\r\n log.info(\"Create new ObjectPool for DBCP connections:\" + jcd);\r\n\r\n try\r\n {\r\n ClassHelper.newInstance(jcd.getDriver());\r\n }\r\n catch (InstantiationException e)\r\n {\r\n log.fatal(\"Unable to instantiate the driver class: \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n catch (IllegalAccessException e)\r\n {\r\n log.fatal(\"IllegalAccessException while instantiating the driver class: \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n log.fatal(\"Could not find the driver class : \" + jcd.getDriver() + \" in ConnectionFactoryDBCImpl!\" , e);\r\n }\r\n\r\n // Get the configuration for the connection pool\r\n GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();\r\n\r\n // Get the additional abandoned configuration\r\n AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();\r\n\r\n // Create the ObjectPool that serves as the actual pool of connections.\r\n final ObjectPool connectionPool = createConnectionPool(conf, ac);\r\n\r\n // Create a DriverManager-based ConnectionFactory that\r\n // the connectionPool will use to create Connection instances\r\n final org.apache.commons.dbcp.ConnectionFactory connectionFactory;\r\n connectionFactory = createConnectionFactory(jcd);\r\n\r\n // Create PreparedStatement object pool (if any)\r\n KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd);\r\n\r\n // Set validation query and auto-commit mode\r\n final String validationQuery;\r\n final boolean defaultAutoCommit;\r\n final boolean defaultReadOnly = false;\r\n validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery();\r\n defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE);\r\n\r\n //\r\n // Now we'll create the PoolableConnectionFactory, which wraps\r\n // the \"real\" Connections created by the ConnectionFactory with\r\n // the classes that implement the pooling functionality.\r\n //\r\n final PoolableConnectionFactory poolableConnectionFactory;\r\n poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,\r\n connectionPool,\r\n statementPoolFactory,\r\n validationQuery,\r\n defaultReadOnly,\r\n defaultAutoCommit,\r\n ac);\r\n return poolableConnectionFactory.getPool();\r\n }", "public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) {\n MVCArray res = buildArcPoints(center, start, end);\n if (ArcType.ROUND.equals(arcType)) {\n res.push(center);\n }\n return new PolygonOptions().paths(res);\n }" ]
Set the weekdays at which the event should take place. @param weekDays the weekdays at which the event should take place.
[ "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 }" ]
[ "public static String getAt(GString text, Range range) {\n return getAt(text.toString(), range);\n }", "public static authenticationradiuspolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnglobal_binding obj = new authenticationradiuspolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnglobal_binding response[] = (authenticationradiuspolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void executorShutDown(ExecutorService executorService, long timeOutSec) {\n try {\n executorService.shutdown();\n executorService.awaitTermination(timeOutSec, TimeUnit.SECONDS);\n } catch(Exception e) {\n logger.warn(\"Error while stoping executor service.\", e);\n }\n }", "private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}", "public void cache(String key, Object obj, int expiration) {\n H.Session session = this.session;\n if (null != session) {\n session.cache(key, obj, expiration);\n } else {\n app().cache().put(key, obj, expiration);\n }\n }", "private Map<UUID, List<DateRange>> processDayTypes(List<MapRow> types)\n {\n Map<UUID, List<DateRange>> map = new HashMap<UUID, List<DateRange>>();\n for (MapRow row : types)\n {\n List<DateRange> ranges = new ArrayList<DateRange>();\n for (MapRow range : row.getRows(\"TIME_RANGES\"))\n {\n ranges.add(new DateRange(range.getDate(\"START\"), range.getDate(\"END\")));\n }\n map.put(row.getUUID(\"UUID\"), ranges);\n }\n\n return map;\n }", "public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}", "public void handleEvent(Event event) {\n LOG.fine(\"ContentLengthHandler called\");\n\n //if maximum length is shorter then <cut><![CDATA[ ]]></cut> it's not possible to cut the content\n if(CUT_START_TAG.length() + CUT_END_TAG.length() > length) {\n LOG.warning(\"Trying to cut content. But length is shorter then needed for \"\n + CUT_START_TAG + CUT_END_TAG + \". So content is skipped.\");\n event.setContent(\"\");\n return;\n }\n\n int currentLength = length - CUT_START_TAG.length() - CUT_END_TAG.length();\n\n if (event.getContent() != null && event.getContent().length() > length) {\n LOG.fine(\"cutting content to \" + currentLength\n + \" characters. Original length was \"\n + event.getContent().length());\n LOG.fine(\"Content before cutting: \" + event.getContent());\n event.setContent(CUT_START_TAG\n + event.getContent().substring(0, currentLength) + CUT_END_TAG);\n LOG.fine(\"Content after cutting: \" + event.getContent());\n }\n }", "private void parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }" ]
Returns the type of the current member which is the type in the case of a field, the return type for a getter method, or the type of the parameter for a setter method. @return The member type @exception XDocletException if an error occurs
[ "public static XClass getMemberType() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getType();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getType();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getType();\r\n }\r\n }\r\n return null;\r\n }" ]
[ "public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)\n throws InterruptedException, IOException {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());\n return new LargeFileUpload().\n upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);\n }", "public static List<Sentence> splitSentences(CharSequence text) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.splitSentences(text)\n );\n }", "public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }", "protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) {\n\n if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) {\n return StreamRequestHandlerState.WRITING;\n } else {\n logger.info(\"Finished fetch \" + itemTag + \" for store '\" + storageEngine.getName()\n + \"' with partitions \" + partitionIds);\n progressInfoMessage(\"Fetch \" + itemTag + \" (end of scan)\");\n\n return StreamRequestHandlerState.COMPLETE;\n }\n }", "public boolean addDescriptor() {\n\n saveLocalization();\n IndexedContainer oldContainer = m_container;\n try {\n createAndLockDescriptorFile();\n unmarshalDescriptor();\n updateBundleDescriptorContent();\n m_hasMasterMode = true;\n m_container = createContainer();\n m_editorState.put(EditMode.DEFAULT, getDefaultState());\n m_editorState.put(EditMode.MASTER, getMasterState());\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n if (m_descContent != null) {\n m_descContent = null;\n }\n if (m_descFile != null) {\n m_descFile = null;\n }\n if (m_desc != null) {\n try {\n m_cms.deleteResource(m_desc, CmsResourceDeleteMode.valueOf(1));\n } catch (CmsException ex) {\n LOG.error(ex.getLocalizedMessage(), ex);\n }\n m_desc = null;\n }\n m_hasMasterMode = false;\n m_container = oldContainer;\n return false;\n }\n m_removeDescriptorOnCancel = true;\n return true;\n }", "private static boolean isAssignableFrom(Type from, ParameterizedType to,\n\t\t\tMap<String, Type> typeVarMap) {\n\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// First figure out the class and any type information.\n\t\tClass<?> clazz = getRawType(from);\n\t\tParameterizedType ptype = null;\n\t\tif (from instanceof ParameterizedType) {\n\t\t\tptype = (ParameterizedType) from;\n\t\t}\n\n\t\t// Load up parameterized variable info if it was parameterized.\n\t\tif (ptype != null) {\n\t\t\tType[] tArgs = ptype.getActualTypeArguments();\n\t\t\tTypeVariable<?>[] tParams = clazz.getTypeParameters();\n\t\t\tfor (int i = 0; i < tArgs.length; i++) {\n\t\t\t\tType arg = tArgs[i];\n\t\t\t\tTypeVariable<?> var = tParams[i];\n\t\t\t\twhile (arg instanceof TypeVariable) {\n\t\t\t\t\tTypeVariable<?> v = (TypeVariable<?>) arg;\n\t\t\t\t\targ = typeVarMap.get(v.getName());\n\t\t\t\t}\n\t\t\t\ttypeVarMap.put(var.getName(), arg);\n\t\t\t}\n\n\t\t\t// check if they are equivalent under our current mapping.\n\t\t\tif (typeEquals(ptype, to, typeVarMap)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tfor (Type itype : clazz.getGenericInterfaces()) {\n\t\t\tif (isAssignableFrom(itype, to, new HashMap<String, Type>(\n\t\t\t\t\ttypeVarMap))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// Interfaces didn't work, try the superclass.\n\t\tType sType = clazz.getGenericSuperclass();\n\t\tif (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "public static BsonDocument copyOfDocument(final BsonDocument document) {\n final BsonDocument newDocument = new BsonDocument();\n for (final Map.Entry<String, BsonValue> kv : document.entrySet()) {\n newDocument.put(kv.getKey(), kv.getValue());\n }\n return newDocument;\n }", "private String dbProp(String name) {\n\n String dbType = m_setupBean.getDatabase();\n Object prop = m_setupBean.getDatabaseProperties().get(dbType).get(dbType + \".\" + name);\n if (prop == null) {\n return \"\";\n }\n return prop.toString();\n }" ]
Given an AVRO serializer definition, validates if all the avro schemas are valid i.e parseable. @param avroSerDef
[ "public static void validateAllAvroSchemas(SerializerDefinition avroSerDef) {\n Map<Integer, String> schemaVersions = avroSerDef.getAllSchemaInfoVersions();\n if(schemaVersions.size() < 1) {\n throw new VoldemortException(\"No schema specified\");\n }\n for(Map.Entry<Integer, String> entry: schemaVersions.entrySet()) {\n Integer schemaVersionNumber = entry.getKey();\n String schemaStr = entry.getValue();\n try {\n Schema.parse(schemaStr);\n } catch(Exception e) {\n throw new VoldemortException(\"Unable to parse Avro schema version :\"\n + schemaVersionNumber + \", schema string :\"\n + schemaStr);\n }\n }\n }" ]
[ "public void setPatternScheme(final boolean isWeekDayBased) {\n\n if (isWeekDayBased ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isWeekDayBased) {\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n } else {\n m_model.setWeekDay(null);\n m_model.setWeekOfMonth(null);\n }\n m_model.setMonth(getPatternDefaultValues().getMonth());\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }", "public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }", "private void cleanStaleFiles(File backupDir, AsyncOperationStatus status) {\n String[] filesInEnv = env.getHome().list();\n String[] filesInBackupDir = backupDir.list();\n if(filesInEnv != null && filesInBackupDir != null) {\n HashSet<String> envFileSet = new HashSet<String>();\n for(String file: filesInEnv)\n envFileSet.add(file);\n // delete all files in backup which are currently not in environment\n for(String file: filesInBackupDir) {\n if(file.endsWith(BDB_EXT) && !envFileSet.contains(file)) {\n status.setStatus(\"Deleting stale jdb file :\" + file);\n File staleJdbFile = new File(backupDir, file);\n staleJdbFile.delete();\n }\n }\n }\n }", "public static autoscaleaction[] get(nitro_service service) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tautoscaleaction[] response = (autoscaleaction[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }", "public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }", "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }", "public static TimeZone get(String suffix) {\n if(SUFFIX_TIMEZONES.containsKey(suffix)) {\n return SUFFIX_TIMEZONES.get(suffix);\n }\n log.warn(\"Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York\", suffix);\n return SUFFIX_TIMEZONES.get(\"\");\n }", "public AsciiTable setPaddingBottom(int paddingBottom) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
Returns the real value object.
[ "public Object getRealValue()\r\n {\r\n if(valueRealSubject != null)\r\n {\r\n return valueRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareValueRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareValueRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise value with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return valueRealSubject;\r\n }" ]
[ "public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }", "public static final Bytes of(String s) {\n Objects.requireNonNull(s);\n if (s.isEmpty()) {\n return EMPTY;\n }\n byte[] data = s.getBytes(StandardCharsets.UTF_8);\n return new Bytes(data, s);\n }", "public int getGeoPerms() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GEO_PERMS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n int perm = -1;\r\n Element personElement = response.getPayload();\r\n String geoPerms = personElement.getAttribute(\"geoperms\");\r\n try {\r\n perm = Integer.parseInt(geoPerms);\r\n } catch (NumberFormatException e) {\r\n throw new FlickrException(\"0\", \"Unable to parse geoPermission\");\r\n }\r\n return perm;\r\n }", "public static Map<String, Map<String, Metadata>> parseAndPopulateMetadataMap(JsonObject jsonObject) {\n Map<String, Map<String, Metadata>> metadataMap = new HashMap<String, Map<String, Metadata>>();\n //Parse all templates\n for (JsonObject.Member templateMember : jsonObject) {\n if (templateMember.getValue().isNull()) {\n continue;\n } else {\n String templateName = templateMember.getName();\n Map<String, Metadata> scopeMap = metadataMap.get(templateName);\n //If templateName doesn't yet exist then create an entry with empty scope map\n if (scopeMap == null) {\n scopeMap = new HashMap<String, Metadata>();\n metadataMap.put(templateName, scopeMap);\n }\n //Parse all scopes in a template\n for (JsonObject.Member scopeMember : templateMember.getValue().asObject()) {\n String scope = scopeMember.getName();\n Metadata metadataObject = new Metadata(scopeMember.getValue().asObject());\n scopeMap.put(scope, metadataObject);\n }\n }\n\n }\n return metadataMap;\n }", "@SuppressWarnings({})\n public synchronized void removeStoreFromSession(List<String> storeNameToRemove) {\n\n logger.info(\"closing the Streaming session for a few stores\");\n\n commitToVoldemort(storeNameToRemove);\n cleanupSessions(storeNameToRemove);\n\n }", "public static <T extends Comparable<? super T>> List<T> sort(Iterable<T> iterable) {\n\t\tList<T> asList = Lists.newArrayList(iterable);\n\t\tif (iterable instanceof SortedSet<?>) {\n\t\t\tif (((SortedSet<T>) iterable).comparator() == null) {\n\t\t\t\treturn asList;\n\t\t\t}\n\t\t}\n\t\treturn ListExtensions.sortInplace(asList);\n\t}", "public static vpnvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_auditnslogpolicy_binding obj = new vpnvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_auditnslogpolicy_binding response[] = (vpnvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setDuration(float start, float end)\n {\n for (GVRAnimation anim : mAnimations)\n {\n anim.setDuration(start,end);\n }\n }", "@Override\n public void close() {\n status = TrStatus.CLOSED;\n try {\n node.close();\n } catch (IOException e) {\n log.error(\"Failed to close ephemeral node\");\n throw new IllegalStateException(e);\n }\n }" ]
Calls the provided metric getter on all the tracked environments and obtains their values @param metricGetterName @return
[ "private List<Long> collectLongMetric(String metricGetterName) {\n List<Long> vals = new ArrayList<Long>();\n for(BdbEnvironmentStats envStats: environmentStatsTracked) {\n vals.add((Long) ReflectUtils.callMethod(envStats,\n BdbEnvironmentStats.class,\n metricGetterName,\n new Class<?>[0],\n new Object[0]));\n }\n return vals;\n }" ]
[ "public static int getStatusBarHeight(Context context, boolean force) {\n int result = 0;\n int resourceId = context.getResources().getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n result = context.getResources().getDimensionPixelSize(resourceId);\n }\n\n int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);\n //if our dimension is 0 return 0 because on those devices we don't need the height\n if (dimenResult == 0 && !force) {\n return 0;\n } else {\n //if our dimens is > 0 && the result == 0 use the dimenResult else the result;\n return result == 0 ? dimenResult : result;\n }\n }", "public static String encode(String component) {\n if (component != null) {\n try {\n return URLEncoder.encode(component, UTF_8.name());\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"JVM must support UTF-8\", e);\n }\n }\n return null;\n }", "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 }", "private void handleIncomingMessage(SerialMessage incomingMessage) {\n\t\t\n\t\tlogger.debug(\"Incoming message to process\");\n\t\tlogger.debug(incomingMessage.toString());\n\t\t\n\t\tswitch (incomingMessage.getMessageType()) {\n\t\t\tcase Request:\n\t\t\t\thandleIncomingRequestMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase Response:\n\t\t\t\thandleIncomingResponseMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unsupported incomingMessageType: 0x%02X\", incomingMessage.getMessageType());\n\t\t}\n\t}", "@Override\r\n\tpublic boolean check(EmbeddedBrowser browser) {\r\n\t\tString js =\r\n\t\t\t\t\"try{ if(\" + expression + \"){return '1';}else{\" + \"return '0';}}catch(e){\"\r\n\t\t\t\t\t\t+ \" return '0';}\";\r\n\t\ttry {\r\n\t\t\tObject object = browser.executeJavaScript(js);\r\n\t\t\tif (object == null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn object.toString().equals(\"1\");\r\n\t\t} catch (CrawljaxException e) {\r\n\t\t\t// Exception is caught, check failed so return false;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}", "public static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\r\n public V get(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V deltaResult = deltaMap.get(key);\r\n if (deltaResult == null) {\r\n return originalMap.get(key);\r\n }\r\n if (deltaResult == nullValue) {\r\n return null;\r\n }\r\n if (deltaResult == removedValue) {\r\n return null;\r\n }\r\n return deltaResult;\r\n }", "@Override public ProjectFile read(String accessDatabaseFileName) throws MPXJException\n {\n try\n {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n String url = \"jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=\" + accessDatabaseFileName;\n m_connection = DriverManager.getConnection(url);\n m_projectID = Integer.valueOf(1);\n return (read());\n }\n\n catch (ClassNotFoundException ex)\n {\n throw new MPXJException(\"Failed to load JDBC driver\", ex);\n }\n\n catch (SQLException ex)\n {\n throw new MPXJException(\"Failed to create connection\", ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n }\n }", "protected void processDescriptions(List<MonolingualTextValue> descriptions) {\n for(MonolingualTextValue description : descriptions) {\n \tNameWithUpdate currentValue = newDescriptions.get(description.getLanguageCode());\n \t// only mark the description as added if the value we are writing is different from the current one\n \tif (currentValue == null || !currentValue.value.equals(description)) {\n \t\tnewDescriptions.put(description.getLanguageCode(),\n new NameWithUpdate(description, true));\n \t}\n }\n }" ]
Read arguments from a file. Newline delimited, UTF-8 encoded. No fanciness to avoid dependencies.
[ "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 String stripThreadName(String threadId)\n {\n if (threadId == null)\n {\n return null;\n }\n else\n {\n int index = threadId.lastIndexOf('@');\n return index >= 0 ? threadId.substring(0, index) : threadId;\n }\n }", "public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "private void addSuperClasses(Integer directSuperClass,\n\t\t\tClassRecord subClassRecord) {\n\t\tif (subClassRecord.superClasses.contains(directSuperClass)) {\n\t\t\treturn;\n\t\t}\n\t\tsubClassRecord.superClasses.add(directSuperClass);\n\t\tClassRecord superClassRecord = getClassRecord(directSuperClass);\n\t\tif (superClassRecord == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (Integer superClass : superClassRecord.directSuperClasses) {\n\t\t\taddSuperClasses(superClass, subClassRecord);\n\t\t}\n\t}", "protected void addEnumList(String key, List<? extends Enum> list) {\n optionsMap.put(key, list.stream().map(i -> i.toString()).collect(Collectors.toList()));\n }", "List<MwDumpFile> findDumpsLocally(DumpContentType dumpContentType) {\n\n\t\tString directoryPattern = WmfDumpFile.getDumpFileDirectoryName(\n\t\t\t\tdumpContentType, \"*\");\n\n\t\tList<String> dumpFileDirectories;\n\t\ttry {\n\t\t\tdumpFileDirectories = this.dumpfileDirectoryManager\n\t\t\t\t\t.getSubdirectories(directoryPattern);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Unable to access dump directory: \" + e.toString());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String directory : dumpFileDirectories) {\n\t\t\tString dateStamp = WmfDumpFile\n\t\t\t\t\t.getDateStampFromDumpFileDirectoryName(dumpContentType,\n\t\t\t\t\t\t\tdirectory);\n\t\t\tif (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) {\n\t\t\t\tWmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, dumpfileDirectoryManager,\n\t\t\t\t\t\tdumpContentType);\n\t\t\t\tif (dumpFile.isAvailable()) {\n\t\t\t\t\tresult.add(dumpFile);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.error(\"Incomplete local dump file data. Maybe delete \"\n\t\t\t\t\t\t\t+ dumpFile.getDumpfileDirectory()\n\t\t\t\t\t\t\t+ \" to attempt fresh download.\");\n\t\t\t\t}\n\t\t\t} // else: silently ignore directories that don't match\n\t\t}\n\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\n\t\tlogger.info(\"Found \" + result.size() + \" local dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}", "private static String firstFoundTableName(PersistenceBroker brokerForClass, ClassDescriptor cld)\r\n {\r\n String name = null;\r\n if (!cld.isInterface() && cld.getFullTableName() != null)\r\n {\r\n return cld.getFullTableName();\r\n }\r\n if (cld.isExtent())\r\n {\r\n Collection extentClasses = cld.getExtentClasses();\r\n for (Iterator iterator = extentClasses.iterator(); iterator.hasNext();)\r\n {\r\n name = firstFoundTableName(brokerForClass, brokerForClass.getClassDescriptor((Class) iterator.next()));\r\n // System.out.println(\"## \" + cld.getClassNameOfObject()+\" - name: \"+name);\r\n if (name != null) break;\r\n }\r\n }\r\n return name;\r\n }", "private void initFieldFactories() {\n\n if (m_model.hasMasterMode()) {\n TranslateTableFieldFactory masterFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER));\n masterFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.MASTER, masterFieldFactory);\n }\n TranslateTableFieldFactory defaultFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT));\n defaultFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, defaultFieldFactory);\n\n }", "private boolean moreDates(Calendar calendar, List<Date> dates)\n {\n boolean result;\n if (m_finishDate == null)\n {\n int occurrences = NumberHelper.getInt(m_occurrences);\n if (occurrences < 1)\n {\n occurrences = 1;\n }\n result = dates.size() < occurrences;\n }\n else\n {\n result = calendar.getTimeInMillis() <= m_finishDate.getTime();\n }\n return result;\n }", "public static CssSel sel(String selector, String value) {\n\treturn j.sel(selector, value);\n }" ]
Obtain the realm used for authentication. This realm name applies to both the user and the groups. @return The name of the realm used for authentication.
[ "public String getRealm() {\n if (UNDEFINED.equals(realm)) {\n Principal principal = securityIdentity.getPrincipal();\n String realm = null;\n if (principal instanceof RealmPrincipal) {\n realm = ((RealmPrincipal)principal).getRealm();\n }\n this.realm = realm;\n\n }\n\n return this.realm;\n }" ]
[ "public E get(int i) {\r\n if (i < 0 || i >= objects.size())\r\n throw new ArrayIndexOutOfBoundsException(\"Index \" + i + \r\n \" outside the bounds [0,\" + \r\n size() + \")\");\r\n return objects.get(i);\r\n }", "public boolean detectBlackBerryTouch() {\r\n\r\n if (detectBlackBerry()\r\n && ((userAgent.indexOf(deviceBBStorm) != -1)\r\n || (userAgent.indexOf(deviceBBTorch) != -1)\r\n || (userAgent.indexOf(deviceBBBoldTouch) != -1)\r\n || (userAgent.indexOf(deviceBBCurveTouch) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }", "private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, boolean logDetails) {\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\tdatabaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter);\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"dropping table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"DROP TABLE \");\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(' ');\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t}", "@SuppressForbidden(\"legitimate sysstreams.\")\n private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, \n CommandlineJava commandline, \n TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) {\n try {\n String tempDir = commandline.getSystemProperties().getVariablesVector().stream()\n .filter(v -> v.getKey().equals(\"java.io.tmpdir\"))\n .map(v -> v.getValue())\n .findAny()\n .orElse(null);\n\n final LocalSlaveStreamHandler streamHandler = \n new LocalSlaveStreamHandler(\n eventBus, testsClassLoader, System.err, eventStream, \n sysout, syserr, heartbeat, streamsBuffer);\n\n // Add certain properties to allow identification of the forked JVM from within\n // the subprocess. This can be used for policy files etc.\n final Path cwd = getWorkingDirectory(slaveInfo, tempDir);\n\n Variable v = new Variable();\n v.setKey(CHILDVM_SYSPROP_CWD);\n v.setFile(cwd.toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SYSPROP_TEMPDIR);\n v.setFile(getTempDir().toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID);\n v.setValue(Integer.toString(slaveInfo.id));\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT);\n v.setValue(Integer.toString(slaveInfo.slaves));\n commandline.addSysproperty(v);\n\n // Emit command line before -stdin to avoid confusion.\n slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline());\n log(\"Forked child JVM at '\" + cwd.toAbsolutePath().normalize() + \n \"', command (may need escape sequences for your shell):\\n\" + \n slaveInfo.slaveCommandLine, Project.MSG_VERBOSE);\n\n final Execute execute = new Execute();\n execute.setCommandline(commandline.getCommandline());\n execute.setVMLauncher(true);\n execute.setWorkingDirectory(cwd.toFile());\n execute.setStreamHandler(streamHandler);\n execute.setNewenvironment(newEnvironment);\n if (env.getVariables() != null)\n execute.setEnvironment(env.getVariables());\n log(\"Starting JVM J\" + slaveInfo.id, Project.MSG_DEBUG);\n execute.execute();\n return execute;\n } catch (IOException e) {\n throw new BuildException(\"Could not start the child process. Run ant with -verbose to get\" +\n \t\t\" the execution details.\", e);\n }\n }", "public void mark() {\n final long currentTimeMillis = clock.currentTimeMillis();\n\n synchronized (queue) {\n if (queue.size() == capacity) {\n /*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */\n queue.removeFirst();\n }\n queue.addLast(currentTimeMillis);\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 }", "public static nsrpcnode[] get(nitro_service service) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tnsrpcnode[] response = (nsrpcnode[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void allRelation(Options opt, RelationType rt, ClassDoc from) {\n\tString tagname = rt.lower;\n\tfor (Tag tag : from.tags(tagname)) {\n\t String t[] = tokenize(tag.text()); // l-src label l-dst target\n\t t = t.length == 1 ? new String[] { \"-\", \"-\", \"-\", t[0] } : t; // Shorthand\n\t if (t.length != 4) {\n\t\tSystem.err.println(\"Error in \" + from + \"\\n\" + tagname + \" expects four fields (l-src label l-dst target): \" + tag.text());\n\t\treturn;\n\t }\n\t ClassDoc to = from.findClass(t[3]);\n\t if (to != null) {\n\t\tif(hidden(to))\n\t\t continue;\n\t\trelation(opt, rt, from, to, t[0], t[1], t[2]);\n\t } else {\n\t\tif(hidden(t[3]))\n\t\t continue;\n\t\trelation(opt, rt, from, from.toString(), to, t[3], t[0], t[1], t[2]);\n\t }\n\t}\n }", "public List<BoxTaskAssignment.Info> getAssignments() {\n URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTaskAssignment.Info> assignments = new ArrayList<BoxTaskAssignment.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject assignmentJSON = value.asObject();\n BoxTaskAssignment assignment = new BoxTaskAssignment(this.getAPI(), assignmentJSON.get(\"id\").asString());\n BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON);\n assignments.add(info);\n }\n\n return assignments;\n }" ]
Send an announcement packet so the other devices see us as being part of the DJ Link network and send us updates.
[ "private void sendAnnouncement(InetAddress broadcastAddress) {\n try {\n DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,\n broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);\n socket.get().send(announcement);\n Thread.sleep(getAnnounceInterval());\n } catch (Throwable t) {\n logger.warn(\"Unable to send announcement packet, shutting down\", t);\n stop();\n }\n }" ]
[ "public void setFrustum(Matrix4f projMatrix)\n {\n if (projMatrix != null)\n {\n if (mProjMatrix == null)\n {\n mProjMatrix = new float[16];\n }\n mProjMatrix = projMatrix.get(mProjMatrix, 0);\n mScene.setPickVisible(false);\n if (mCuller != null)\n {\n mCuller.set(projMatrix);\n }\n else\n {\n mCuller = new FrustumIntersection(projMatrix);\n }\n }\n mProjection = projMatrix;\n }", "public static <T> boolean addAll(Collection<T> self, Iterator<T> items) {\n boolean changed = false;\n while (items.hasNext()) {\n T next = items.next();\n if (self.add(next)) changed = true;\n }\n return changed;\n }", "private String determineAndCacheOuterMostNullEmbeddable(String column, String[] path) {\n\t\tString embeddable = path[0];\n\t\t// process each embeddable from less specific to most specific\n\t\t// exclude path leaves as it's a column and not an embeddable\n\t\tfor ( int index = 0; index < path.length - 1; index++ ) {\n\t\t\tSet<String> columnsOfEmbeddable = getColumnsOfEmbeddableAndComputeEmbeddableNullness( embeddable );\n\n\t\t\tif ( nullEmbeddables.contains( embeddable ) ) {\n\t\t\t\t// the current embeddable only has null columns; cache that info for all the columns\n\t\t\t\tfor ( String columnOfEmbeddable : columnsOfEmbeddable ) {\n\t\t\t\t\tcolumnToOuterMostNullEmbeddableCache.put( columnOfEmbeddable, embeddable );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmaybeCacheOnNonNullEmbeddable( path, index, columnsOfEmbeddable );\n\t\t\t}\n\t\t\t// a more specific null embeddable might be present, carry on\n\t\t\tembeddable += \".\" + path[index + 1];\n\t\t}\n\t\treturn columnToOuterMostNullEmbeddableCache.get( column );\n\t}", "public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}", "private boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) {\n Class<?> superClass = clazz.getSuperclass();\n while (superClass != null) {\n if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) {\n // if superclass is abstract, we need to dig deeper\n for (Method method : superClass.getDeclaredMethods()) {\n if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType)\n && !Reflections.isAbstract(method)) {\n // this is the case we are after -> methods have same signature and the one in super class has actual implementation\n return true;\n }\n }\n }\n superClass = superClass.getSuperclass();\n }\n return false;\n }", "public static <T> Collection<T> diff(Collection<T> list1, Collection<T> list2) {\r\n Collection<T> diff = new ArrayList<T>();\r\n for (T t : list1) {\r\n if (!list2.contains(t)) {\r\n diff.add(t);\r\n }\r\n }\r\n return diff;\r\n }", "@Override\n public void onClick(View v) {\n String tag = (String) v.getTag();\n mContentTextView.setText(String.format(\"%s clicked.\", tag));\n mMenuDrawer.setActiveView(v);\n }", "public boolean forall(PixelPredicate predicate) {\n return Arrays.stream(points()).allMatch(p -> predicate.test(p.x, p.y, pixel(p)));\n }", "public ConfigBuilder withMasterName(final String masterName) {\n if (masterName == null || \"\".equals(masterName)) {\n throw new IllegalArgumentException(\"masterName is null or empty: \" + masterName);\n }\n this.masterName = masterName;\n return this;\n }" ]
Sends the collected dependencies over to the master and record them.
[ "@Override\n public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener)\n throws InterruptedException, IOException {\n build.executeAsync(new BuildCallable<Void, IOException>() {\n // record is transient, so needs to make a copy first\n private final Set<MavenDependency> d = dependencies;\n\n public Void call(MavenBuild build) throws IOException, InterruptedException {\n // add the action\n //TODO: [by yl] These actions are persisted into the build.xml of each build run - we need another\n //context to store these actions\n build.getActions().add(new MavenDependenciesRecord(build, d));\n return null;\n }\n });\n return true;\n }" ]
[ "private void readProjectExtendedAttributes(Project project)\n {\n Project.ExtendedAttributes attributes = project.getExtendedAttributes();\n if (attributes != null)\n {\n for (Project.ExtendedAttributes.ExtendedAttribute ea : attributes.getExtendedAttribute())\n {\n readFieldAlias(ea);\n }\n }\n }", "public void processClass(String template, Properties attributes) throws XDocletException\r\n {\r\n if (!_model.hasClass(getCurrentClass().getQualifiedName()))\r\n {\r\n // we only want to output the log message once\r\n LogHelper.debug(true, OjbTagsHandler.class, \"processClass\", \"Type \"+getCurrentClass().getQualifiedName());\r\n }\r\n\r\n ClassDescriptorDef classDef = ensureClassDef(getCurrentClass());\r\n String attrName;\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n classDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n _curClassDef = classDef;\r\n generate(template);\r\n _curClassDef = null;\r\n }", "public synchronized GeoInterface getGeoInterface() {\r\n if (geoInterface == null) {\r\n geoInterface = new GeoInterface(apiKey, sharedSecret, transport);\r\n }\r\n return geoInterface;\r\n }", "public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }", "@Override\n public void fire(StepStartedEvent event) {\n for (LifecycleListener listener : listeners) {\n try {\n listener.fire(event);\n } catch (Exception e) {\n logError(listener, e);\n }\n }\n }", "public static void doPublish(final Jedis jedis, final String namespace, final String channel, final String jobJson) {\n jedis.publish(JesqueUtils.createKey(namespace, CHANNEL, channel), jobJson);\n }", "public void putEvents(List<Event> events) {\n Exception lastException;\n List<EventType> eventTypes = new ArrayList<EventType>();\n for (Event event : events) {\n EventType eventType = EventMapper.map(event);\n eventTypes.add(eventType);\n }\n\n int i = 0;\n lastException = null;\n while (i < numberOfRetries) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n lastException = e;\n i++;\n }\n if(i < numberOfRetries) {\n try {\n Thread.sleep(delayBetweenRetry);\n } catch (InterruptedException e) {\n break;\n }\n }\n }\n\n if (i == numberOfRetries) {\n throw new MonitoringException(\"1104\", \"Could not send events to monitoring service after \"\n + numberOfRetries + \" retries.\", lastException, events);\n }\n }", "public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {\n\t\tthis.connectionTimeoutInMs = TimeUnit.MILLISECONDS.convert(connectionTimeout, timeUnit);\n\t}", "public void setMaintenanceMode(String appName, boolean enable) {\n connection.execute(new AppUpdate(appName, enable), apiKey);\n }" ]
Performs the update to the persistent configuration model. This default implementation simply removes the targeted resource. @param context the operation context @param operation the operation @throws OperationFailedException if there is a problem updating the model
[ "protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException {\n // verify that the resource exist before removing it\n context.readResource(PathAddress.EMPTY_ADDRESS, false);\n Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS);\n recordCapabilitiesAndRequirements(context, operation, resource);\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable,\n final Collection<ControlFlowBlock> controlFlowBlocks) {\n return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks));\n }", "private static JSONObject parseStencilSet(StencilSet stencilSet) throws JSONException {\n if (stencilSet != null) {\n JSONObject stencilSetObject = new JSONObject();\n\n stencilSetObject.put(\"url\",\n stencilSet.getUrl().toString());\n stencilSetObject.put(\"namespace\",\n stencilSet.getNamespace().toString());\n\n return stencilSetObject;\n }\n\n return new JSONObject();\n }", "public static String[] randomResourceNames(String prefix, int maxLen, int count) {\n String[] names = new String[count];\n ResourceNamer resourceNamer = SdkContext.getResourceNamerFactory().createResourceNamer(\"\");\n for (int i = 0; i < count; i++) {\n names[i] = resourceNamer.randomName(prefix, maxLen);\n }\n return names;\n }", "public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType,\n Class<V> valueType) {\n return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(),\n valueType));\n }", "public PropertiesEnvelope getUserProperties(String userId, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = getUserPropertiesWithHttpInfo(userId, aid);\n return resp.getData();\n }", "protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {\n CompletableFuture<T> futureValue = getValue();\n\n if (futureValue == null) {\n logger.error(\"Could not retrieve value \" + this.getClass().getName());\n return null;\n }\n\n return futureValue\n .exceptionally(\n t -> {\n logger.error(\"Could not retrieve value \" + this.getClass().getName(), t);\n return null;\n })\n .thenApply(\n value -> {\n JsonArrayBuilder perms = Json.createArrayBuilder();\n if (isWritable) {\n perms.add(\"pw\");\n }\n if (isReadable) {\n perms.add(\"pr\");\n }\n if (isEventable) {\n perms.add(\"ev\");\n }\n JsonObjectBuilder builder =\n Json.createObjectBuilder()\n .add(\"iid\", instanceId)\n .add(\"type\", shortType)\n .add(\"perms\", perms.build())\n .add(\"format\", format)\n .add(\"ev\", false)\n .add(\"description\", description);\n setJsonValue(builder, value);\n return builder;\n });\n }", "public static String getXPathExpression(Node node) {\n\t\tObject xpathCache = node.getUserData(FULL_XPATH_CACHE);\n\t\tif (xpathCache != null) {\n\t\t\treturn xpathCache.toString();\n\t\t}\n\t\tNode parent = node.getParentNode();\n\n\t\tif ((parent == null) || parent.getNodeName().contains(\"#document\")) {\n\t\t\tString xPath = \"/\" + node.getNodeName() + \"[1]\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tif (node.hasAttributes() && node.getAttributes().getNamedItem(\"id\") != null) {\n\t\t\tString xPath = \"//\" + node.getNodeName() + \"[@id = '\"\n\t\t\t\t\t+ node.getAttributes().getNamedItem(\"id\").getNodeValue() + \"']\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tStringBuffer buffer = new StringBuffer();\n\n\t\tif (parent != node) {\n\t\t\tbuffer.append(getXPathExpression(parent));\n\t\t\tbuffer.append(\"/\");\n\t\t}\n\n\t\tbuffer.append(node.getNodeName());\n\n\t\tList<Node> mySiblings = getSiblings(parent, node);\n\n\t\tfor (int i = 0; i < mySiblings.size(); i++) {\n\t\t\tNode el = mySiblings.get(i);\n\n\t\t\tif (el.equals(node)) {\n\t\t\t\tbuffer.append('[').append(Integer.toString(i + 1)).append(']');\n\t\t\t\t// Found so break;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tString xPath = buffer.toString();\n\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\treturn xPath;\n\t}", "protected boolean equivalentClaims(Claim claim1, Claim claim2) {\n\t\treturn claim1.getMainSnak().equals(claim2.getMainSnak())\n\t\t\t\t&& isSameSnakSet(claim1.getAllQualifiers(),\n\t\t\t\t\t\tclaim2.getAllQualifiers());\n\t}" ]
Extracts the java class name from the schema info @param schemaInfo the schema info, a string like: java=java.lang.String @return the name of the class extracted from the schema info
[ "public static String getJavaClassFromSchemaInfo(String schemaInfo) {\n final String ONLY_JAVA_CLIENTS_SUPPORTED = \"Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=foo.Bar</schema-info> where foo.Bar is the fully qualified name of the message.\";\n\n if(StringUtils.isEmpty(schemaInfo))\n throw new IllegalArgumentException(\"This serializer requires a non-empty schema-info.\");\n\n String[] languagePairs = StringUtils.split(schemaInfo, ',');\n if(languagePairs.length > 1)\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n String[] javaPair = StringUtils.split(languagePairs[0], '=');\n if(javaPair.length != 2 || !javaPair[0].trim().equals(\"java\"))\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n return javaPair[1].trim();\n }" ]
[ "private void processResources() throws IOException\n {\n CompanyReader reader = new CompanyReader(m_data.getTableData(\"Companies\"));\n reader.read();\n for (MapRow companyRow : reader.getRows())\n {\n // TODO: need to sort by type as well as by name!\n for (MapRow resourceRow : sort(companyRow.getRows(\"RESOURCES\"), \"NAME\"))\n {\n processResource(resourceRow);\n }\n }\n }", "public String getResourcePath()\n {\n switch (resourceType)\n {\n case ANDROID_ASSETS: return assetPath;\n\n case ANDROID_RESOURCE: return resourceFilePath;\n\n case LINUX_FILESYSTEM: return filePath;\n\n case NETWORK: return url.getPath();\n\n case INPUT_STREAM: return inputStreamName;\n\n default: return null;\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 base_response delete(nitro_service client, String Dnssuffix) throws Exception {\n\t\tdnssuffix deleteresource = new dnssuffix();\n\t\tdeleteresource.Dnssuffix = Dnssuffix;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }", "private static void updateSniffingLoggersLevel(Logger logger) {\n\n\t\tInputStream settingIS = FoundationLogger.class\n\t\t\t\t.getResourceAsStream(\"/sniffingLogger.xml\");\n\t\tif (settingIS == null) {\n\t\t\tlogger.debug(\"file sniffingLogger.xml not found in classpath\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\t\tDocument document = builder.build(settingIS);\n\t\t\t\tsettingIS.close();\n\t\t\t\tElement rootElement = document.getRootElement();\n\t\t\t\tList<Element> sniffingloggers = rootElement\n\t\t\t\t\t\t.getChildren(\"sniffingLogger\");\n\t\t\t\tfor (Element sniffinglogger : sniffingloggers) {\n\t\t\t\t\tString loggerName = sniffinglogger.getAttributeValue(\"id\");\n\t\t\t\t\tLogger.getLogger(loggerName).setLevel(Level.TRACE);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t\t\"cannot load the sniffing logger configuration file. error is: \"\n\t\t\t\t\t\t\t\t+ e, e);\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Problem parsing sniffingLogger.xml\", e);\n\t\t\t}\n\t\t}\n\n\t}", "private void reportException(Exception e) {\n\t\tlogger.error(\"Failed to write JSON export: \" + e.toString());\n\t\tthrow new RuntimeException(e.toString(), e);\n\t}", "public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}", "public Weld addPackages(boolean scanRecursively, Class<?>... packageClasses) {\n for (Class<?> packageClass : packageClasses) {\n addPackage(scanRecursively, packageClass);\n }\n return this;\n }" ]
Use this API to fetch all the vpnsessionaction resources that are configured on netscaler.
[ "public static vpnsessionaction[] get(nitro_service service) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tvpnsessionaction[] response = (vpnsessionaction[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public double getBearing(LatLong end) {\n if (this.equals(end)) {\n return 0;\n }\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n double lat2 = end.latToRadians();\n double lon2 = end.longToRadians();\n\n double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),\n Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)\n * Math.cos(lat2) * Math.cos(lon1 - lon2));\n\n if (angle < 0.0) {\n angle += Math.PI * 2.0;\n }\n if (angle > Math.PI) {\n angle -= Math.PI * 2.0;\n }\n\n return Math.toDegrees(angle);\n }", "private void initModeSwitch(final EditMode current) {\n\n FormLayout modes = new FormLayout();\n modes.setHeight(\"100%\");\n modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);\n\n m_modeSelect = new ComboBox();\n m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));\n\n // add Modes\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));\n\n // set current mode as selected\n m_modeSelect.setValue(current);\n\n m_modeSelect.setNewItemsAllowed(false);\n m_modeSelect.setTextInputAllowed(false);\n m_modeSelect.setNullSelectionAllowed(false);\n\n m_modeSelect.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void valueChange(ValueChangeEvent event) {\n\n m_listener.handleModeChange((EditMode)event.getProperty().getValue());\n\n }\n });\n\n modes.addComponent(m_modeSelect);\n m_modeSwitch = modes;\n }", "public static vrid_nsip6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvrid_nsip6_binding obj = new vrid_nsip6_binding();\n\t\tobj.set_id(id);\n\t\tvrid_nsip6_binding response[] = (vrid_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void fireEventForNonWebModules(Type eventType, Object event, Annotation... qualifiers) {\n try {\n BeanDeploymentModules modules = deploymentManager.getServices().get(BeanDeploymentModules.class);\n if (modules != null) {\n // fire event for non-web modules\n // web modules are handled by HttpContextLifecycle\n for (BeanDeploymentModule module : modules) {\n if (!module.isWebModule()) {\n module.fireEvent(eventType, event, qualifiers);\n }\n }\n }\n } catch (Exception ignored) {\n }\n }", "public HiveShellContainer evaluateStatement(List<? extends Script> scripts, Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable {\n container = null;\n FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault());\n try {\n LOGGER.info(\"Setting up {} in {}\", getName(), temporaryFolder.getRoot().getAbsolutePath());\n container = createHiveServerContainer(scripts, target, temporaryFolder);\n base.evaluate();\n return container;\n } finally {\n tearDown();\n }\n }", "protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}", "public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }", "protected static boolean isTargetOp( TokenList.Token token , Symbol[] ops ) {\n Symbol c = token.symbol;\n for (int i = 0; i < ops.length; i++) {\n if( c == ops[i])\n return true;\n }\n return false;\n }", "public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }" ]
Writes a resource's cost rate tables. @param xml MSPDI resource @param mpx MPXJ resource
[ "private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\n }" ]
[ "public static void configure(Job conf, SimpleConfiguration config) {\n try {\n FluoConfiguration fconfig = new FluoConfiguration(config);\n try (Environment env = new Environment(fconfig)) {\n long ts =\n env.getSharedResources().getTimestampTracker().allocateTimestamp().getTxTimestamp();\n conf.getConfiguration().setLong(TIMESTAMP_CONF_KEY, ts);\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n config.save(baos);\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n AccumuloInputFormat.setZooKeeperInstance(conf, fconfig.getAccumuloInstance(),\n fconfig.getAccumuloZookeepers());\n AccumuloInputFormat.setConnectorInfo(conf, fconfig.getAccumuloUser(),\n new PasswordToken(fconfig.getAccumuloPassword()));\n AccumuloInputFormat.setInputTableName(conf, env.getTable());\n AccumuloInputFormat.setScanAuthorizations(conf, env.getAuthorizations());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public ThumborUrlBuilder trim(TrimPixelColor value, int colorTolerance) {\n if (colorTolerance < 0 || colorTolerance > 442) {\n throw new IllegalArgumentException(\"Color tolerance must be between 0 and 442.\");\n }\n if (colorTolerance > 0 && value == null) {\n throw new IllegalArgumentException(\"Trim pixel color value must not be null.\");\n }\n isTrim = true;\n trimPixelColor = value;\n trimColorTolerance = colorTolerance;\n return this;\n }", "protected EntityKey getEntityKey(Tuple tuple, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {\n\t\tObject[] columnValues = new Object[ associatedEntityKeyMetadata.getAssociationKeyColumns().length];\n\t\tint i = 0;\n\n\t\tfor ( String associationKeyColumn : associatedEntityKeyMetadata.getAssociationKeyColumns() ) {\n\t\t\tcolumnValues[i] = tuple.get( associationKeyColumn );\n\t\t\ti++;\n\t\t}\n\n\t\treturn new EntityKey( associatedEntityKeyMetadata.getEntityKeyMetadata(), columnValues );\n\t}", "@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public void setSourceUrl(String newUrl, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVERS +\n \" SET \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newUrl);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private void populateEntityMap() throws SQLException\n {\n for (Row row : getRows(\"select * from z_primarykey\"))\n {\n m_entityMap.put(row.getString(\"Z_NAME\"), row.getInteger(\"Z_ENT\"));\n }\n }", "public String checkIn(byte[] data) {\n String id = UUID.randomUUID().toString();\n dataMap.put(id, data);\n return id;\n }", "public void addDependency(final Dependency dependency) {\n if(dependency != null && !dependencies.contains(dependency)){\n this.dependencies.add(dependency);\n }\n }", "public static final String printDuration(Duration duration)\n {\n String result = null;\n if (duration != null)\n {\n result = duration.getDuration() + \" \" + printTimeUnits(duration.getUnits());\n }\n return result;\n }" ]
Uses the iterator to run through the dao and retain only the items that are in the passed in collection. This will remove the items from the associated database table as well. @return Returns true of the collection was changed at all otherwise false.
[ "@Override\n\tpublic boolean retainAll(Collection<?> collection) {\n\t\tif (dao == null) {\n\t\t\treturn false;\n\t\t}\n\t\tboolean changed = false;\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tT data = iterator.next();\n\t\t\t\tif (!collection.contains(data)) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn changed;\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}" ]
[ "private static void updateBaseCalendarNames(List<Pair<ProjectCalendar, BigInteger>> baseCalendars, HashMap<BigInteger, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, BigInteger> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n BigInteger baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n\n }", "@JmxOperation(description = \"swapFiles changes this store to use the new data directory\")\n public void swapFiles(String newStoreDirectory) {\n logger.info(\"Swapping files for store '\" + getName() + \"' to \" + newStoreDirectory);\n File newVersionDir = new File(newStoreDirectory);\n\n if(!newVersionDir.exists())\n throw new VoldemortException(\"File \" + newVersionDir.getAbsolutePath()\n + \" does not exist.\");\n\n if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))\n throw new VoldemortException(\"Invalid version folder name '\"\n + newVersionDir\n + \"'. Either parent directory is incorrect or format(version-n) is incorrect\");\n\n // retrieve previous version for (a) check if last write is winning\n // (b) if failure, rollback use\n File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n if(previousVersionDir == null)\n throw new VoldemortException(\"Could not find any latest directory to swap with in store '\"\n + getName() + \"'\");\n\n long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);\n long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);\n if(newVersionId == -1 || previousVersionId == -1)\n throw new VoldemortException(\"Unable to parse folder names (\" + newVersionDir.getName()\n + \",\" + previousVersionDir.getName()\n + \") since format(version-n) is incorrect\");\n\n // check if we're greater than latest since we want last write to win\n if(previousVersionId > newVersionId) {\n logger.info(\"No swap required since current latest version \" + previousVersionId\n + \" is greater than swap version \" + newVersionId);\n deleteBackups();\n return;\n }\n\n logger.info(\"Acquiring write lock on '\" + getName() + \"':\");\n fileModificationLock.writeLock().lock();\n boolean success = false;\n try {\n close();\n logger.info(\"Opening primary files for store '\" + getName() + \"' at \"\n + newStoreDirectory);\n\n // open the latest store\n open(newVersionDir);\n success = true;\n } finally {\n try {\n // we failed to do the swap, attempt a rollback to last version\n if(!success)\n rollback(previousVersionDir);\n\n } finally {\n fileModificationLock.writeLock().unlock();\n if(success)\n logger.info(\"Swap operation completed successfully on store \" + getName()\n + \", releasing lock.\");\n else\n logger.error(\"Swap operation failed.\");\n }\n }\n\n // okay we have released the lock and the store is now open again, it is\n // safe to do a potentially slow delete if we have one too many backups\n deleteBackups();\n }", "public RowColumn following() {\n if (row.equals(Bytes.EMPTY)) {\n return RowColumn.EMPTY;\n } else if (col.equals(Column.EMPTY)) {\n return new RowColumn(followingBytes(row));\n } else if (!col.isQualifierSet()) {\n return new RowColumn(row, new Column(followingBytes(col.getFamily())));\n } else if (!col.isVisibilitySet()) {\n return new RowColumn(row, new Column(col.getFamily(), followingBytes(col.getQualifier())));\n } else {\n return new RowColumn(row,\n new Column(col.getFamily(), col.getQualifier(), followingBytes(col.getVisibility())));\n }\n }", "public static base_response convert(nitro_service client, sslpkcs8 resource) throws Exception {\n\t\tsslpkcs8 convertresource = new sslpkcs8();\n\t\tconvertresource.pkcs8file = resource.pkcs8file;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.keyform = resource.keyform;\n\t\tconvertresource.password = resource.password;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}", "public MessageSet read(long readOffset, long size) throws IOException {\n return new FileMessageSet(channel, this.offset + readOffset, //\n Math.min(this.offset + readOffset + size, highWaterMark()), false, new AtomicBoolean(false));\n }", "public static CurrencySymbolPosition getSymbolPosition(int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:\n default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }", "private void beforeBatch(BatchBackend backend) {\n\t\tif ( this.purgeAtStart ) {\n\t\t\t// purgeAll for affected entities\n\t\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\t\tfor ( IndexedTypeIdentifier type : targetedTypes ) {\n\t\t\t\t// needs do be in-sync work to make sure we wait for the end of it.\n\t\t\t\tbackend.doWorkInSync( new PurgeAllLuceneWork( tenantId, type ) );\n\t\t\t}\n\t\t\tif ( this.optimizeAfterPurge ) {\n\t\t\t\tbackend.optimize( targetedTypes );\n\t\t\t}\n\t\t}\n\t}", "public static <E> String serialize(Map<String, E> map, Class<E> jsonObjectClass) throws IOException {\n return mapperFor(jsonObjectClass).serialize(map);\n }", "public static tunnelip_stats[] get(nitro_service service) throws Exception{\n\t\ttunnelip_stats obj = new tunnelip_stats();\n\t\ttunnelip_stats[] response = (tunnelip_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}" ]
Creates an element that represents a single page. @return the resulting DOM element
[ "protected Element createPageElement()\n {\n String pstyle = \"\";\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n /*System.out.println(\"x1 \" + layout.getLowerLeftX());\n System.out.println(\"y1 \" + layout.getLowerLeftY());\n System.out.println(\"x2 \" + layout.getUpperRightX());\n System.out.println(\"y2 \" + layout.getUpperRightY());\n System.out.println(\"rot \" + pdpage.findRotation());*/\n \n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n pstyle = \"width:\" + w + UNIT + \";\" + \"height:\" + h + UNIT + \";\";\n pstyle += \"overflow:hidden;\";\n }\n else\n log.warn(\"No media box found\");\n \n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"page_\" + (pagecnt++));\n el.setAttribute(\"class\", \"page\");\n el.setAttribute(\"style\", pstyle);\n return el;\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 void setWeekDay(String dayString) {\n\n final WeekDay day = WeekDay.valueOf(dayString);\n if (m_model.getWeekDay() != day) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(day);\n onValueChange();\n }\n });\n }\n\n }", "public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }", "private static Iterator<String> splitIntoDocs(Reader r) {\r\n if (TREAT_FILE_AS_ONE_DOCUMENT) {\r\n return Collections.singleton(IOUtils.slurpReader(r)).iterator();\r\n } else {\r\n Collection<String> docs = new ArrayList<String>();\r\n ObjectBank<String> ob = ObjectBank.getLineIterator(r);\r\n StringBuilder current = new StringBuilder();\r\n for (String line : ob) {\r\n if (docPattern.matcher(line).lookingAt()) {\r\n // Start new doc, store old one if non-empty\r\n if (current.length() > 0) {\r\n docs.add(current.toString());\r\n current = new StringBuilder();\r\n }\r\n }\r\n current.append(line);\r\n current.append('\\n');\r\n }\r\n if (current.length() > 0) {\r\n docs.add(current.toString());\r\n }\r\n return docs.iterator();\r\n }\r\n }", "protected Boolean checkBoolean(Object val, Boolean def) {\n return (val == null) ? def : (Boolean) val;\n }", "public static boolean promoteAndCheckResponse(Promotion promotion, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber) throws IOException {\n // If failFast is true, perform dry run first\n if (promotion.isFailFast()) {\n promotion.setDryRun(true);\n listener.getLogger().println(\"Performing dry run promotion (no changes are made during dry run) ...\");\n HttpResponse dryResponse = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(dryResponse, true, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully.\\nPerforming promotion ...\");\n }\n\n // Perform promotion\n promotion.setDryRun(false);\n HttpResponse response = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(response, false, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Promotion completed successfully!\");\n\n return true;\n }", "public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }", "public static base_response delete(nitro_service client, String jsoncontenttypevalue) throws Exception {\n\t\tappfwjsoncontenttype deleteresource = new appfwjsoncontenttype();\n\t\tdeleteresource.jsoncontenttypevalue = jsoncontenttypevalue;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "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 }" ]
Write a relation list field to the JSON file. @param fieldName field name @param value field value
[ "private void writeRelationList(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n List<Relation> list = (List<Relation>) value;\n if (!list.isEmpty())\n {\n m_writer.writeStartList(fieldName);\n for (Relation relation : list)\n {\n m_writer.writeStartObject(null);\n writeIntegerField(\"task_unique_id\", relation.getTargetTask().getUniqueID());\n writeDurationField(\"lag\", relation.getLag());\n writeStringField(\"type\", relation.getType());\n m_writer.writeEndObject();\n }\n m_writer.writeEndList();\n }\n }" ]
[ "public void applyPatterns(String[] patterns)\n {\n m_formats = new SimpleDateFormat[patterns.length];\n for (int index = 0; index < patterns.length; index++)\n {\n m_formats[index] = new SimpleDateFormat(patterns[index]);\n }\n }", "@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\n }", "public ScopedToken getLowerScopedToken(List<String> scopes, String resource) {\n assert (scopes != null);\n assert (scopes.size() > 0);\n URL url = null;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n StringBuilder spaceSeparatedScopes = new StringBuilder();\n for (int i = 0; i < scopes.size(); i++) {\n spaceSeparatedScopes.append(scopes.get(i));\n if (i < scopes.size() - 1) {\n spaceSeparatedScopes.append(\" \");\n }\n }\n\n String urlParameters = null;\n\n if (resource != null) {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s&resource=%s\",\n this.getAccessToken(), spaceSeparatedScopes, resource);\n } else {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s\",\n this.getAccessToken(), spaceSeparatedScopes);\n }\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n ScopedToken token = new ScopedToken(jsonObject);\n token.setObtainedAt(System.currentTimeMillis());\n token.setExpiresIn(jsonObject.get(\"expires_in\").asLong() * 1000);\n return token;\n }", "protected void markStatementsForInsertion(\n\t\t\tStatementDocument currentDocument, List<Statement> addStatements) {\n\t\tfor (Statement statement : addStatements) {\n\t\t\taddStatement(statement, true);\n\t\t}\n\n\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\tif (this.toKeep.containsKey(sg.getProperty())) {\n\t\t\t\tfor (Statement statement : sg) {\n\t\t\t\t\tif (!this.toDelete.contains(statement.getStatementId())) {\n\t\t\t\t\t\taddStatement(statement, false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public boolean merge(AbstractTransition another) {\n if (!isCompatible(another)) {\n return false;\n }\n if (another.mId != null) {\n if (mId == null) {\n mId = another.mId;\n } else {\n StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());\n sb.append(mId);\n sb.append(\"_MERGED_\");\n sb.append(another.mId);\n mId = sb.toString();\n }\n }\n mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;\n mSetupList.addAll(another.mSetupList);\n Collections.sort(mSetupList, new Comparator<S>() {\n @Override\n public int compare(S lhs, S rhs) {\n if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {\n AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;\n AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;\n float startLeft = left.mReverse ? left.mEnd : left.mStart;\n float startRight = right.mReverse ? right.mEnd : right.mStart;\n return (int) ((startRight - startLeft) * 1000);\n }\n return 0;\n }\n });\n\n return true;\n }", "public static final Object getObject(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getObject(key));\n }", "public static base_response unlink(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey unlinkresource = new sslcertkey();\n\t\tunlinkresource.certkey = resource.certkey;\n\t\treturn unlinkresource.perform_operation(client,\"unlink\");\n\t}", "public static String getParentIdFromAgent(Launcher launcher, final String imageID, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getParentId(imageID, host);\n }\n });\n }", "public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }" ]
This method retrieves the next token and returns a constant representing the type of token found. @return token type value
[ "public int nextToken() throws IOException\n {\n int c;\n int nextc = -1;\n boolean quoted = false;\n int result = m_next;\n if (m_next != 0)\n {\n m_next = 0;\n }\n\n m_buffer.setLength(0);\n\n while (result == 0)\n {\n if (nextc != -1)\n {\n c = nextc;\n nextc = -1;\n }\n else\n {\n c = read();\n }\n\n switch (c)\n {\n case TT_EOF:\n {\n if (m_buffer.length() != 0)\n {\n result = TT_WORD;\n m_next = TT_EOF;\n }\n else\n {\n result = TT_EOF;\n }\n break;\n }\n\n case TT_EOL:\n {\n int length = m_buffer.length();\n\n if (length != 0 && m_buffer.charAt(length - 1) == '\\r')\n {\n --length;\n m_buffer.setLength(length);\n }\n\n if (length == 0)\n {\n result = TT_EOL;\n }\n else\n {\n result = TT_WORD;\n m_next = TT_EOL;\n }\n\n break;\n }\n\n default:\n {\n if (c == m_quote)\n {\n if (quoted == false && startQuotedIsValid(m_buffer))\n {\n quoted = true;\n }\n else\n {\n if (quoted == false)\n {\n m_buffer.append((char) c);\n }\n else\n {\n nextc = read();\n if (nextc == m_quote)\n {\n m_buffer.append((char) c);\n nextc = -1;\n }\n else\n {\n quoted = false;\n }\n }\n }\n }\n else\n {\n if (c == m_delimiter && quoted == false)\n {\n result = TT_WORD;\n }\n else\n {\n m_buffer.append((char) c);\n }\n }\n }\n }\n }\n\n m_type = result;\n\n return (result);\n }" ]
[ "private float MIN(float first, float second, float third) {\r\n\r\n float min = Integer.MAX_VALUE;\r\n if (first < min) {\r\n min = first;\r\n }\r\n if (second < min) {\r\n min = second;\r\n }\r\n if (third < min) {\r\n min = third;\r\n }\r\n return min;\r\n }", "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n final Set<DeviceAnnouncement> lastDevices = getCurrentDevices();\n socket.get().close();\n socket.set(null);\n devices.clear();\n firstDeviceTime.set(0);\n // Report the loss of all our devices, on the proper thread, outside our lock\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeviceAnnouncement announcement : lastDevices) {\n deliverLostAnnouncement(announcement);\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "public String toMixedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.mixedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.mixedString = result = toNormalizedString(IPv6StringCache.mixedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toMixedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "public GroovyConstructorDoc[] constructors() {\n Collections.sort(constructors);\n return constructors.toArray(new GroovyConstructorDoc[constructors.size()]);\n }", "public ViewGroup getContentContainer() {\n if (mDragMode == MENU_DRAG_CONTENT) {\n return mContentContainer;\n } else {\n return (ViewGroup) findViewById(android.R.id.content);\n }\n }", "@SuppressWarnings({\"UnusedDeclaration\"})\n public void doIndex(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {\n req.getView(this, chooseAction()).forward(req, resp);\n }", "public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {\n\t\tsslpkcs12 convertresource = new sslpkcs12();\n\t\tconvertresource.outfile = resource.outfile;\n\t\tconvertresource.Import = resource.Import;\n\t\tconvertresource.pkcs12file = resource.pkcs12file;\n\t\tconvertresource.des = resource.des;\n\t\tconvertresource.des3 = resource.des3;\n\t\tconvertresource.export = resource.export;\n\t\tconvertresource.certfile = resource.certfile;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.password = resource.password;\n\t\tconvertresource.pempassphrase = resource.pempassphrase;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query, boolean lazy) throws PersistenceBrokerException\r\n {\r\n ManageableCollection result;\r\n\r\n try\r\n {\r\n // BRJ: return empty Collection for null query\r\n if (query == null)\r\n {\r\n result = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n else\r\n {\r\n if (lazy)\r\n {\r\n result = pb.getProxyFactory().createCollectionProxy(pb.getPBKey(), query, collectionClass);\r\n }\r\n else\r\n {\r\n result = getCollectionByQuery(collectionClass, query.getSearchClass(), query);\r\n }\r\n }\r\n return result;\r\n }\r\n catch (Exception e)\r\n {\r\n if(e instanceof PersistenceBrokerException)\r\n {\r\n throw (PersistenceBrokerException) e;\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n }\r\n }", "@Override\n public boolean decompose(DMatrixRBlock A) {\n if( A.numCols != A.numRows )\n throw new IllegalArgumentException(\"A must be square\");\n\n this.T = A;\n\n if( lower )\n return decomposeLower();\n else\n return decomposeUpper();\n }" ]
Begin writing a named list attribute. @param name attribute name
[ "public void writeStartList(String name) throws IOException\n {\n writeComma();\n writeNewLineIndent();\n writeName(name);\n writeNewLineIndent();\n m_writer.write(\"[\");\n increaseIndent();\n }" ]
[ "private void readCalendars(Project ganttProject)\n {\n m_mpxjCalendar = m_projectFile.addCalendar();\n m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n Calendars gpCalendar = ganttProject.getCalendars();\n setWorkingDays(m_mpxjCalendar, gpCalendar);\n setExceptions(m_mpxjCalendar, gpCalendar);\n m_eventManager.fireCalendarReadEvent(m_mpxjCalendar);\n }", "private int findAvailablePortNumber( Integer portNumberStartingPoint, List<Integer> reservedPorts )\n {\n assert portNumberStartingPoint != null;\n int candidate = portNumberStartingPoint;\n while ( reservedPorts.contains( candidate ) )\n {\n candidate++;\n }\n return candidate;\n }", "private static <D extends DatastoreConfiguration<G>, G extends GlobalContext<?, ?>> AppendableConfigurationContext invokeOptionConfigurator(\n\t\t\tOptionConfigurator configurator) {\n\n\t\tConfigurableImpl configurable = new ConfigurableImpl();\n\t\tconfigurator.configure( configurable );\n\t\treturn configurable.getContext();\n\t}", "public static boolean validate(final String ip) {\n Matcher matcher = pattern.matcher(ip);\n return matcher.matches();\n }", "public AiTextureInfo getTextureInfo(AiTextureType type, int index) {\n return new AiTextureInfo(type, index, getTextureFile(type, index), \n getTextureUVIndex(type, index), getBlendFactor(type, index), \n getTextureOp(type, index), getTextureMapModeW(type, index), \n getTextureMapModeW(type, index), \n getTextureMapModeW(type, index));\n }", "public void setLocale(String locale) {\n\n try {\n m_locale = LocaleUtils.toLocale(locale);\n } catch (IllegalArgumentException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_TAG_INVALID_LOCALE_1, \"cms:navigation\"), e);\n m_locale = null;\n }\n }", "public static nspbr6_stats get(nitro_service service, String name) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tobj.set_name(name);\n\t\tnspbr6_stats response = (nspbr6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "private void readTableBlock(int startIndex, int blockLength)\n {\n for (int index = startIndex; index < (startIndex + blockLength - 11); index++)\n {\n if (matchPattern(TABLE_BLOCK_PATTERNS, index))\n {\n int offset = index + 7;\n int nameLength = FastTrackUtility.getInt(m_buffer, offset);\n offset += 4;\n String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();\n FastTrackTableType type = REQUIRED_TABLES.get(name);\n if (type != null)\n {\n m_currentTable = new FastTrackTable(type, this);\n m_tables.put(type, m_currentTable);\n }\n else\n {\n m_currentTable = null;\n }\n m_currentFields.clear();\n break;\n }\n }\n }", "public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }" ]
Indicates if a set of types are all proxyable @param types The types to test @return True if proxyable, false otherwise
[ "public static boolean isTypesProxyable(Iterable<? extends Type> types, ServiceRegistry services) {\n return getUnproxyableTypesException(types, services) == null;\n }" ]
[ "public static ProtocolConnectionManager create(final Connection connection, final ConnectionOpenHandler openHandler) {\n return create(new EstablishedConnection(connection, openHandler));\n }", "@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }", "public void stopListenting() {\n if (channel != null) {\n log.info(\"closing server channel\");\n channel.close().syncUninterruptibly();\n channel = null;\n }\n }", "public static DoubleMatrix cholesky(DoubleMatrix A) {\n DoubleMatrix result = A.dup();\n int info = NativeBlas.dpotrf('U', A.rows, result.data, 0, A.rows);\n if (info < 0) {\n throw new LapackArgumentException(\"DPOTRF\", -info);\n } else if (info > 0) {\n throw new LapackPositivityException(\"DPOTRF\", \"Minor \" + info + \" was negative. Matrix must be positive definite.\");\n }\n clearLower(result);\n return result;\n }", "@Override\n public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n if (this.options.verbose) {\n this.out.println(\n Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));\n//\t\t\tnew Exception(\"TRACE BINARY\").printStackTrace(System.out);\n//\t\t System.out.println();\n }\n LookupEnvironment env = packageBinding.environment;\n env.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);\n }", "public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }", "public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }", "public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) {\n\n BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection(boxConfig.getEnterpriseId(),\n boxConfig.getClientId(), boxConfig.getClientSecret(), boxConfig.getJWTEncryptionPreferences());\n\n return connection;\n }", "public boolean removeWriter(Object key, Object resourceId)\r\n {\r\n boolean result = false;\r\n ObjectLocks objectLocks = null;\r\n synchronized(locktable)\r\n {\r\n objectLocks = (ObjectLocks) locktable.get(resourceId);\r\n if(objectLocks != null)\r\n {\r\n /**\r\n * MBAIRD, last one out, close the door and turn off the lights.\r\n * if no locks (readers or writers) exist for this object, let's remove\r\n * it from the locktable.\r\n */\r\n LockEntry entry = objectLocks.getWriter();\r\n if(entry != null && entry.isOwnedBy(key))\r\n {\r\n objectLocks.setWriter(null);\r\n result = true;\r\n\r\n // no need to check if writer is null, we just set it.\r\n if(objectLocks.getReaders().size() == 0)\r\n {\r\n locktable.remove(resourceId);\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }" ]
Writes long strings to output stream as several chunks. @param stream stream to write to. @param str string to be written. @throws IOException if something went wrong
[ "public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException {\n try (DataOutputStream dataStream = new DataOutputStream(stream)) {\n int len = str.length();\n if (len < SINGLE_UTF_CHUNK_SIZE) {\n dataStream.writeUTF(str);\n } else {\n int startIndex = 0;\n int endIndex;\n do {\n endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE;\n if (endIndex > len) {\n endIndex = len;\n }\n dataStream.writeUTF(str.substring(startIndex, endIndex));\n startIndex += SINGLE_UTF_CHUNK_SIZE;\n } while (endIndex < len);\n }\n }\n }" ]
[ "public static String minus(CharSequence self, Object target) {\n String s = self.toString();\n String text = DefaultGroovyMethods.toString(target);\n int index = s.indexOf(text);\n if (index == -1) return s;\n int end = index + text.length();\n if (s.length() > end) {\n return s.substring(0, index) + s.substring(end);\n }\n return s.substring(0, index);\n }", "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}", "public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{\n\n\t\tString alias = _subjectMap.get(getSubjectForHostname(hostname));\n\n\t\tif(alias != null) {\n\t\t\treturn (X509Certificate)_ks.getCertificate(alias);\n\t\t}\n return getMappedCertificateForHostname(hostname);\n\t}", "private void writeTask(Task task) throws IOException\n {\n writeFields(null, task, TaskField.values());\n for (Task child : task.getChildTasks())\n {\n writeTask(child);\n }\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}", "@Override\n public List<String> getDefaultProviderChain() {\n List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());\n Collections.sort(result);\n return result;\n }", "public List<MapRow> readTable(Class<? extends TableReader> readerClass) throws IOException\n {\n TableReader reader;\n\n try\n {\n reader = readerClass.getConstructor(StreamReader.class).newInstance(this);\n }\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n return readTable(reader);\n }", "private String buildAliasKey(String aPath, List hintClasses)\r\n {\r\n if (hintClasses == null || hintClasses.isEmpty())\r\n {\r\n return aPath;\r\n }\r\n \r\n StringBuffer buf = new StringBuffer(aPath);\r\n for (Iterator iter = hintClasses.iterator(); iter.hasNext();)\r\n {\r\n Class hint = (Class) iter.next();\r\n buf.append(\" \");\r\n buf.append(hint.getName());\r\n }\r\n return buf.toString();\r\n }", "private static void checkPreconditions(final String regex, final String replacement) {\n\t\tif( regex == null ) {\n\t\t\tthrow new NullPointerException(\"regex should not be null\");\n\t\t} else if( regex.length() == 0 ) {\n\t\t\tthrow new IllegalArgumentException(\"regex should not be empty\");\n\t\t}\n\t\t\n\t\tif( replacement == null ) {\n\t\t\tthrow new NullPointerException(\"replacement should not be null\");\n\t\t}\n\t}" ]
Confirms that both clusters have the same number of total partitions. @param lhs @param rhs
[ "public static void validateClusterPartitionCounts(final Cluster lhs, final Cluster rhs) {\n if(lhs.getNumberOfPartitions() != rhs.getNumberOfPartitions())\n throw new VoldemortException(\"Total number of partitions should be equal [ lhs cluster (\"\n + lhs.getNumberOfPartitions()\n + \") not equal to rhs cluster (\"\n + rhs.getNumberOfPartitions() + \") ]\");\n }" ]
[ "public void addIn(Object attribute, Query subQuery)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }", "private void writeResource(Resource mpxj)\n {\n ResourceType xml = m_factory.createResourceType();\n m_apibo.getResource().add(xml);\n\n xml.setAutoComputeActuals(Boolean.TRUE);\n xml.setCalculateCostFromUnits(Boolean.TRUE);\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getResourceCalendar()));\n xml.setCurrencyObjectId(DEFAULT_CURRENCY_ID);\n xml.setDefaultUnitsPerTime(Double.valueOf(1.0));\n xml.setEmailAddress(mpxj.getEmailAddress());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(RESOURCE_ID_PREFIX + mpxj.getUniqueID());\n xml.setIsActive(Boolean.TRUE);\n xml.setMaxUnitsPerTime(getPercentage(mpxj.getMaxUnits()));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(mpxj.getParentID());\n xml.setResourceNotes(mpxj.getNotes());\n xml.setResourceType(getResourceType(mpxj));\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.RESOURCE, mpxj));\n }", "private ProjectFile readFile(String inputFile) throws MPXJException\n {\n ProjectReader reader = new UniversalProjectReader();\n ProjectFile projectFile = reader.read(inputFile);\n if (projectFile == null)\n {\n throw new IllegalArgumentException(\"Unsupported file type\");\n }\n return projectFile;\n }", "public void saveFile(File file, String type)\n {\n if (file != null)\n {\n m_treeController.saveFile(file, type);\n }\n }", "public static boolean isFloat(CharSequence self) {\n try {\n Float.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public static double blackModelSwaptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble swapAnnuity)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t}", "private void writePriorityField(String fieldName, Object value) throws IOException\n {\n m_writer.writeNameValuePair(fieldName, ((Priority) value).getValue());\n }", "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 }", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\n }" ]
Resolve Java control character sequences to the actual character value. Optionally handle unicode escape sequences, too.
[ "public String convertFromJavaString(String string, boolean useUnicode) {\n\t\tint firstEscapeSequence = string.indexOf('\\\\');\n\t\tif (firstEscapeSequence == -1) {\n\t\t\treturn string;\n\t\t}\n\t\tint length = string.length();\n\t\tStringBuilder result = new StringBuilder(length);\n\t\tappendRegion(string, 0, firstEscapeSequence, result);\n\t\treturn convertFromJavaString(string, useUnicode, firstEscapeSequence, result);\n\t}" ]
[ "@Pure\n\tpublic static <K, V> Pair<K, V> of(K k, V v) {\n\t\treturn new Pair<K, V>(k, v);\n\t}", "public StatementBuilder withQualifierValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\twithQualifier(factory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}", "@Api\n\tpublic static void configureNoCaching(HttpServletResponse response) {\n\t\t// HTTP 1.0 header:\n\t\tresponse.setHeader(HTTP_EXPIRES_HEADER, HTTP_EXPIRES_HEADER_NOCACHE_VALUE);\n\t\tresponse.setHeader(HTTP_CACHE_PRAGMA, HTTP_CACHE_PRAGMA_VALUE);\n\n\t\t// HTTP 1.1 header:\n\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, HTTP_CACHE_CONTROL_HEADER_NOCACHE_VALUE);\n\t}", "public static String convertToFileSystemChar(String name) {\n String erg = \"\";\n Matcher m = Pattern.compile(\"[a-z0-9 _#&@\\\\[\\\\(\\\\)\\\\]\\\\-\\\\.]\", Pattern.CASE_INSENSITIVE).matcher(name);\n while (m.find()) {\n erg += name.substring(m.start(), m.end());\n }\n if (erg.length() > 200) {\n erg = erg.substring(0, 200);\n System.out.println(\"cut filename: \" + erg);\n }\n return erg;\n }", "public Set<String> getSupportedUriSchemes() {\n Set<String> schemes = new HashSet<>();\n\n for (ConfigFileLoaderPlugin loaderPlugin: this.getLoaderPlugins()) {\n schemes.add(loaderPlugin.getUriScheme());\n }\n\n return schemes;\n }", "public static byte[] domainControllerDataToByteBuffer(List<DomainControllerData> data) throws Exception {\n final ByteArrayOutputStream out_stream = new ByteArrayOutputStream(512);\n byte[] result;\n try (DataOutputStream out = new DataOutputStream(out_stream)) {\n Iterator<DomainControllerData> iter = data.iterator();\n while (iter.hasNext()) {\n DomainControllerData dcData = iter.next();\n dcData.writeTo(out);\n if (iter.hasNext()) {\n S3Util.writeString(SEPARATOR, out);\n }\n }\n result = out_stream.toByteArray();\n }\n return result;\n }", "protected void appendStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) {\n\t\tif (isVarcharFieldWidthSupported()) {\n\t\t\tsb.append(\"VARCHAR(\").append(fieldWidth).append(')');\n\t\t} else {\n\t\t\tsb.append(\"VARCHAR\");\n\t\t}\n\t}", "public void synchTransaction(SimpleFeatureStore featureStore) {\n\t\t// check if transaction is active, otherwise do nothing (auto-commit mode)\n\t\tif (TransactionSynchronizationManager.isActualTransactionActive()) {\n\t\t\tDataAccess<SimpleFeatureType, SimpleFeature> dataStore = featureStore.getDataStore();\n\t\t\tif (!transactions.containsKey(dataStore)) {\n\t\t\t\tTransaction transaction = null;\n\t\t\t\tif (dataStore instanceof JDBCDataStore) {\n\t\t\t\t\tJDBCDataStore jdbcDataStore = (JDBCDataStore) dataStore;\n\t\t\t\t\ttransaction = jdbcDataStore.buildTransaction(DataSourceUtils\n\t\t\t\t\t\t\t.getConnection(jdbcDataStore.getDataSource()));\n\t\t\t\t} else {\n\t\t\t\t\ttransaction = new DefaultTransaction();\n\t\t\t\t}\n\t\t\t\ttransactions.put(dataStore, transaction);\n\t\t\t}\n\t\t\tfeatureStore.setTransaction(transactions.get(dataStore));\n\t\t}\n\t}", "public 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 }" ]
Sets the currently edited locale. @param locale the locale to set.
[ "void setLanguage(final Locale locale) {\n\n if (!m_languageSelect.getValue().equals(locale)) {\n m_languageSelect.setValue(locale);\n }\n }" ]
[ "public Where<T, ID> le(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public PagedList<V> convert(final PagedList<U> uList) {\n if (uList == null || uList.isEmpty()) {\n return new PagedList<V>() {\n @Override\n public Page<V> nextPage(String s) throws RestException, IOException {\n return null;\n }\n };\n }\n Page<U> uPage = uList.currentPage();\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return new PagedList<V>(vPage) {\n @Override\n public Page<V> nextPage(String nextPageLink) throws RestException, IOException {\n Page<U> uPage = uList.nextPage(nextPageLink);\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return vPage;\n }\n };\n }", "public static boolean isPrimitiveWrapperArray(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));\n\t}", "public void link(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds, Object referencedObject, boolean insert)\n {\n // MBAIRD: we have 'disassociated' this object from the referenced object,\n // the object represented by the reference descriptor is now null, so set\n // the fk in the target object to null.\n // arminw: if an insert was done and ref object was null, we should allow\n // to pass FK fields of main object (maybe only the FK fields are set)\n if (referencedObject == null)\n {\n /*\n arminw:\n if update we set FK fields to 'null', because reference was disassociated\n We do nothing on insert, maybe only the FK fields of main object (without\n materialization of the reference object) are set by the user\n */\n if(!insert)\n {\n unlinkFK(targetObject, cld, rds);\n }\n }\n else\n {\n setFKField(targetObject, cld, rds, referencedObject);\n }\n }", "@Override\n public void begin(String namespace, String name, Attributes attributes) throws Exception {\n\n // not now: 6.0.0\n // digester.setLogger(CmsLog.getLog(digester.getClass()));\n\n // Push an array to capture the parameter values if necessary\n if (m_paramCount > 0) {\n Object[] parameters = new Object[m_paramCount];\n for (int i = 0; i < parameters.length; i++) {\n parameters[i] = null;\n }\n getDigester().pushParams(parameters);\n }\n }", "public static void putUnsignedInt(ByteBuffer buffer, int index, long value) {\n buffer.putInt(index, (int) (value & 0xffffffffL));\n }", "public ThumborUrlBuilder buildImage(String image) {\n if (image == null || image.length() == 0) {\n throw new IllegalArgumentException(\"Image must not be blank.\");\n }\n return new ThumborUrlBuilder(host, key, image);\n }", "public static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader) throws SQLException {\n\t\tList<DatabaseTableConfig<?>> list = new ArrayList<DatabaseTableConfig<?>>();\n\t\twhile (true) {\n\t\t\tDatabaseTableConfig<?> config = DatabaseTableConfigLoader.fromReader(reader);\n\t\t\tif (config == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlist.add(config);\n\t\t}\n\t\treturn list;\n\t}", "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 }" ]
Places the real component of the input matrix into the output matrix. @param input Complex matrix. Not modified. @param output real matrix. Modified.
[ "public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }" ]
[ "protected void printCenter(String format, Object... args) {\n String text = S.fmt(format, args);\n info(S.center(text, 80));\n }", "@Deprecated\n @SuppressWarnings(\"deprecation\")\n protected void registerAddOperation(final ManagementResourceRegistration registration, final OperationStepHandler handler, OperationEntry.Flag... flags) {\n if (handler instanceof DescriptionProvider) {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n (DescriptionProvider) handler, OperationEntry.EntryType.PUBLIC,flags)\n , handler);\n\n } else {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n new DefaultResourceAddDescriptionProvider(registration, descriptionResolver, orderedChild),\n OperationEntry.EntryType.PUBLIC,\n flags)\n , handler);\n }\n }", "public boolean shouldCompress(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkSuffixes(uri, zipSuffixes);\n\t}", "private ProjectCalendar getResourceCalendar(Integer calendarID)\n {\n ProjectCalendar result = null;\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_calMap.get(calendarID);\n if (calendar != null)\n {\n //\n // If the resource is linked to a base calendar, derive\n // a default calendar from the base calendar.\n //\n if (!calendar.isDerived())\n {\n ProjectCalendar resourceCalendar = m_project.addCalendar();\n resourceCalendar.setParent(calendar);\n resourceCalendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n result = resourceCalendar;\n }\n else\n {\n //\n // Primavera seems to allow a calendar to be shared between resources\n // whereas in the MS Project model there is a one-to-one\n // relationship. If we find a shared calendar, take a copy of it\n //\n if (calendar.getResource() == null)\n {\n result = calendar;\n }\n else\n {\n ProjectCalendar copy = m_project.addCalendar();\n copy.copy(calendar);\n result = copy;\n }\n }\n }\n }\n\n return result;\n }", "@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "private void toNextDate(Calendar date, int interval) {\n\n long previousDate = date.getTimeInMillis();\n if (!m_weekOfMonthIterator.hasNext()) {\n date.add(Calendar.MONTH, interval);\n m_weekOfMonthIterator = m_weeksOfMonth.iterator();\n }\n toCorrectDateWithDay(date, m_weekOfMonthIterator.next());\n if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.\n toNextDate(date);\n }\n\n }", "public static Method getBridgeMethodTarget(Method someMethod) {\n TraitBridge annotation = someMethod.getAnnotation(TraitBridge.class);\n if (annotation==null) {\n return null;\n }\n Class aClass = annotation.traitClass();\n String desc = annotation.desc();\n for (Method method : aClass.getDeclaredMethods()) {\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes());\n if (desc.equals(methodDescriptor)) {\n return method;\n }\n }\n return null;\n }", "private boolean somethingMayHaveChanged(PhaseInterceptorChain pic) {\n Iterator<Interceptor<? extends Message>> it = pic.iterator();\n Interceptor<? extends Message> last = null;\n while (it.hasNext()) {\n Interceptor<? extends Message> cur = it.next();\n if (cur == this) {\n if (last instanceof DemoInterceptor) {\n return false;\n }\n return true;\n }\n last = cur;\n }\n return true;\n }", "public final void warn(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.WARN, pObject, null);\r\n\t}" ]
Pretty prints the given source code. @param code source code to format @param options formatter options @param lineEnding desired line ending @return formatted source code
[ "public static String format(final String code, final Properties options, final LineEnding lineEnding) {\n\t\tCheck.notEmpty(code, \"code\");\n\t\tCheck.notEmpty(options, \"options\");\n\t\tCheck.notNull(lineEnding, \"lineEnding\");\n\n\t\tfinal CodeFormatter formatter = ToolFactory.createCodeFormatter(options);\n\t\tfinal String lineSeparator = LineEnding.find(lineEnding, code);\n\t\tTextEdit te = null;\n\t\ttry {\n\t\t\tte = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);\n\t\t} catch (final Exception formatFailed) {\n\t\t\tLOG.warn(\"Formatting failed\", formatFailed);\n\t\t}\n\n\t\tString formattedCode = code;\n\t\tif (te == null) {\n\t\t\tLOG.info(\"Code cannot be formatted. Possible cause is unmatched source/target/compliance version.\");\n\t\t} else {\n\n\t\t\tfinal IDocument doc = new Document(code);\n\t\t\ttry {\n\t\t\t\tte.apply(doc);\n\t\t\t} catch (final Exception e) {\n\t\t\t\tLOG.warn(e.getLocalizedMessage(), e);\n\t\t\t}\n\t\t\tformattedCode = doc.get();\n\t\t}\n\t\treturn formattedCode;\n\t}" ]
[ "protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JDBC DriverManager\r\n final String driver = jcd.getDriver();\r\n final String url = getDbURL(jcd);\r\n try\r\n {\r\n // loads the driver - NB call to newInstance() added to force initialisation\r\n ClassHelper.getClass(driver, true);\r\n final String user = jcd.getUserName();\r\n final String password = jcd.getPassWord();\r\n final Properties properties = getJdbcProperties(jcd, user, password);\r\n if (properties.isEmpty())\r\n {\r\n if (user == null)\r\n {\r\n retval = DriverManager.getConnection(url);\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, user, password);\r\n }\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, properties);\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n throw new LookupException(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n }\r\n catch (ClassNotFoundException cnfEx)\r\n {\r\n log.error(cnfEx);\r\n throw new LookupException(\"A class was not found\", cnfEx);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Instantiation of jdbc driver failed\", e);\r\n throw new LookupException(\"Instantiation of jdbc driver failed\", e);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DriverManager: \"+retval);\r\n return retval;\r\n }", "public 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 }", "public void unlock() {\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 lockObject = new JsonObject();\n lockObject.add(\"lock\", JsonObject.NULL);\n\n request.setBody(lockObject.toString());\n request.send();\n }", "public static tunneltrafficpolicy get(nitro_service service, String name) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\tobj.set_name(name);\n\t\ttunneltrafficpolicy response = (tunneltrafficpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void deleteShovel(String vhost, String shovelname) {\n\t this.deleteIgnoring404(uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(shovelname)));\n }", "private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,\n\t\t\tQueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {\n\t\tJoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);\n\t\tif (localColumnName == null) {\n\t\t\tmatchJoinedFields(joinInfo, joinedQueryBuilder);\n\t\t} else {\n\t\t\tmatchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);\n\t\t}\n\t\tif (joinList == null) {\n\t\t\tjoinList = new ArrayList<JoinInfo>();\n\t\t}\n\t\tjoinList.add(joinInfo);\n\t}", "public Iterable<RowKey> getKeys() {\n\t\tif ( currentState.isEmpty() ) {\n\t\t\tif ( cleared ) {\n\t\t\t\t// if the association has been cleared and the currentState is empty, we consider that there are no rows.\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// otherwise, the snapshot rows are the current ones\n\t\t\t\treturn snapshot.getRowKeys();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// It may be a bit too large in case of removals, but that's fine for now\n\t\t\tSet<RowKey> keys = CollectionHelper.newLinkedHashSet( cleared ? currentState.size() : snapshot.size() + currentState.size() );\n\n\t\t\tif ( !cleared ) {\n\t\t\t\t// we add the snapshot RowKeys only if the association has not been cleared\n\t\t\t\tfor ( RowKey rowKey : snapshot.getRowKeys() ) {\n\t\t\t\t\tkeys.add( rowKey );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tkeys.add( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tkeys.remove( op.getKey() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn keys;\n\t\t}\n\t}", "public static boolean uniform(Color color, Pixel[] pixels) {\n return Arrays.stream(pixels).allMatch(p -> p.toInt() == color.toRGB().toInt());\n }", "public void leave(String groupId, Boolean deletePhotos) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LEAVE);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"delete_photos\", deletePhotos);\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 }" ]
Get the currently selected opacity. @return The int value of the currently selected opacity.
[ "public int getOpacity() {\n\t\tint opacity = Math\n\t\t\t\t.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));\n\t\tif (opacity < 5) {\n\t\t\treturn 0x00;\n\t\t} else if (opacity > 250) {\n\t\t\treturn 0xFF;\n\t\t} else {\n\t\t\treturn opacity;\n\t\t}\n\t}" ]
[ "@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }", "public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }", "public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }", "public static AT_Row createRule(TableRowType type, TableRowStyle style){\r\n\t\tValidate.notNull(type);\r\n\t\tValidate.validState(type!=TableRowType.UNKNOWN);\r\n\t\tValidate.validState(type!=TableRowType.CONTENT);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn type;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\t\t};\r\n\t}", "void recordPreparedOperation(final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> preparedOperation) {\n recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(preparedOperation));\n }", "private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\n }", "@Override\n public void setExpectedMaxSize( int numRows , int numCols ) {\n super.setExpectedMaxSize(numRows,numCols);\n\n // if the matrix that is being decomposed is smaller than the block we really don't\n // see the B matrix.\n if( numRows < blockWidth)\n B = new DMatrixRMaj(0,0);\n else\n B = new DMatrixRMaj(blockWidth,maxWidth);\n\n chol = new CholeskyBlockHelper_DDRM(blockWidth);\n }", "public void cleanup() {\n List<String> keys = new ArrayList<>(created.keySet());\n keys.sort(String::compareTo);\n for (String key : keys) {\n created.remove(key)\n .stream()\n .sorted(Comparator.comparing(HasMetadata::getKind))\n .forEach(metadata -> {\n log.info(String.format(\"Deleting %s : %s\", key, metadata.getKind()));\n deleteWithRetries(metadata);\n });\n }\n }", "static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}" ]
Close tracks when the JVM shuts down. @return this
[ "public RedwoodConfiguration neatExit(){\r\n tasks.add(new Runnable() { public void run() {\r\n Runtime.getRuntime().addShutdownHook(new Thread(){\r\n @Override public void run(){ Redwood.stop(); }\r\n });\r\n }});\r\n return this;\r\n }" ]
[ "public static aaauser_binding get(nitro_service service, String username) throws Exception{\n\t\taaauser_binding obj = new aaauser_binding();\n\t\tobj.set_username(username);\n\t\taaauser_binding response = (aaauser_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static base_response add(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy addresource = new spilloverpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.comment = resource.comment;\n\t\treturn addresource.add_resource(client);\n\t}", "public static int cudnnCreatePersistentRNNPlan(\n cudnnRNNDescriptor rnnDesc, \n int minibatch, \n int dataType, \n cudnnPersistentRNNPlan plan)\n {\n return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan));\n }", "public static base_response update(nitro_service client, callhome resource) throws Exception {\n\t\tcallhome updateresource = new callhome();\n\t\tupdateresource.emailaddress = resource.emailaddress;\n\t\tupdateresource.proxymode = resource.proxymode;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.port = resource.port;\n\t\treturn updateresource.update_resource(client);\n\t}", "@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 Jar setJarPrefix(Path file) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (file != null && jarPrefixStr != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixStr + \")\");\n this.jarPrefixFile = file;\n return this;\n }", "public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {\r\n\t\treturn new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),\r\n\t\t\t\tgetBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}", "private void renderAsLI(Writer writer, ProjectModel project, Iterator<Link> links, boolean wrap) throws IOException\n {\n if (!links.hasNext())\n return;\n\n if (wrap)\n writer.append(\"<ul>\");\n while (links.hasNext())\n {\n Link link = links.next();\n writer.append(\"<li>\");\n renderLink(writer, project, link);\n writer.append(\"</li>\");\n }\n if (wrap)\n writer.append(\"</ul>\");\n }", "@Nonnull\n public BiMap<String, String> getInputMapper() {\n final BiMap<String, String> inputMapper = this.processor.getInputMapperBiMap();\n if (inputMapper == null) {\n return HashBiMap.create();\n }\n return inputMapper;\n }" ]
Whether the specified JavaBeans property exists on the given type or not. @param clazz the type of interest @param property the JavaBeans property name @param elementType the element type to check, must be either {@link ElementType#FIELD} or {@link ElementType#METHOD}. @return {@code true} if the specified property exists, {@code false} otherwise
[ "public static boolean propertyExists(Class<?> clazz, String property, ElementType elementType) {\n\t\tif ( ElementType.FIELD.equals( elementType ) ) {\n\t\t\treturn getDeclaredField( clazz, property ) != null;\n\t\t}\n\t\telse {\n\t\t\tString capitalizedPropertyName = capitalize( property );\n\n\t\t\tMethod method = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() != void.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tmethod = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() == boolean.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}" ]
[ "public static responderpolicy get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tobj.set_name(name);\n\t\tresponderpolicy response = (responderpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static String subscriptionFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).subscriptionId() : null;\n }", "public static <S extends Matrix, D extends Matrix> LinearSolver<S,D> safe(LinearSolver<S,D> solver ) {\n if( solver.modifiesA() || solver.modifiesB() ) {\n if( solver instanceof LinearSolverDense ) {\n return new LinearSolverSafe((LinearSolverDense)solver);\n } else if( solver instanceof LinearSolverSparse ) {\n return new LinearSolverSparseSafe((LinearSolverSparse)solver);\n } else {\n throw new IllegalArgumentException(\"Unknown solver type\");\n }\n } else {\n return solver;\n }\n }", "public FloatBuffer getFloatVec(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 FloatBuffer data = buffer.asFloatBuffer();\n if (!NativeVertexBuffer.getFloatVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }", "public synchronized void submitOperation(int requestId, AsyncOperation operation) {\n if(this.operations.containsKey(requestId))\n throw new VoldemortException(\"Request \" + requestId\n + \" already submitted to the system\");\n\n this.operations.put(requestId, operation);\n scheduler.scheduleNow(operation);\n logger.debug(\"Handling async operation \" + requestId);\n }", "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }", "public void add( int row , int col , double value ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds\");\n }\n\n data[ row * numCols + col ] += value;\n }", "protected synchronized int loadSize() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n return broker.getCount(getQuery());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }" ]
Build a Pk-Query base on the ClassDescriptor. @param cld @return a select by PK query
[ "private static Query buildQuery(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n Criteria crit = new Criteria();\r\n\r\n for(int i = 0; i < pkFields.length; i++)\r\n {\r\n crit.addEqualTo(pkFields[i].getAttributeName(), null);\r\n }\r\n return new QueryByCriteria(cld.getClassOfObject(), crit);\r\n }" ]
[ "public void addPieSlice(PieModel _Slice) {\n highlightSlice(_Slice);\n mPieData.add(_Slice);\n mTotalValue += _Slice.getValue();\n onDataChanged();\n }", "private void process(String input, String output) throws MPXJException, IOException\n {\n //\n // Extract the project data\n //\n MPPReader reader = new MPPReader();\n m_project = reader.read(input);\n\n String varDataFileName;\n String projectDirName;\n int mppFileType = NumberHelper.getInt(m_project.getProjectProperties().getMppFileType());\n switch (mppFileType)\n {\n case 8:\n {\n projectDirName = \" 1\";\n varDataFileName = \"FixDeferFix 0\";\n break;\n }\n\n case 9:\n {\n projectDirName = \" 19\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 12:\n {\n projectDirName = \" 112\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 14:\n {\n projectDirName = \" 114\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported file type \" + mppFileType);\n }\n }\n\n //\n // Load the raw file\n //\n FileInputStream is = new FileInputStream(input);\n POIFSFileSystem fs = new POIFSFileSystem(is);\n is.close();\n\n //\n // Locate the root of the project file system\n //\n DirectoryEntry root = fs.getRoot();\n m_projectDir = (DirectoryEntry) root.getEntry(projectDirName);\n\n //\n // Process Tasks\n //\n Map<String, String> replacements = new HashMap<String, String>();\n for (Task task : m_project.getTasks())\n {\n mapText(task.getName(), replacements);\n }\n processReplacements(((DirectoryEntry) m_projectDir.getEntry(\"TBkndTask\")), varDataFileName, replacements, true);\n\n //\n // Process Resources\n //\n replacements.clear();\n for (Resource resource : m_project.getResources())\n {\n mapText(resource.getName(), replacements);\n mapText(resource.getInitials(), replacements);\n }\n processReplacements((DirectoryEntry) m_projectDir.getEntry(\"TBkndRsc\"), varDataFileName, replacements, true);\n\n //\n // Process project properties\n //\n replacements.clear();\n ProjectProperties properties = m_project.getProjectProperties();\n mapText(properties.getProjectTitle(), replacements);\n processReplacements(m_projectDir, \"Props\", replacements, true);\n\n replacements.clear();\n mapText(properties.getProjectTitle(), replacements);\n mapText(properties.getSubject(), replacements);\n mapText(properties.getAuthor(), replacements);\n mapText(properties.getKeywords(), replacements);\n mapText(properties.getComments(), replacements);\n processReplacements(root, \"\\005SummaryInformation\", replacements, false);\n\n replacements.clear();\n mapText(properties.getManager(), replacements);\n mapText(properties.getCompany(), replacements);\n mapText(properties.getCategory(), replacements);\n processReplacements(root, \"\\005DocumentSummaryInformation\", replacements, false);\n\n //\n // Write the replacement raw file\n //\n FileOutputStream os = new FileOutputStream(output);\n fs.writeFilesystem(os);\n os.flush();\n os.close();\n fs.close();\n }", "public static List<Integer> getStolenPrimaryPartitions(final Cluster currentCluster,\n final Cluster finalCluster,\n final int stealNodeId) {\n List<Integer> finalList = new ArrayList<Integer>(finalCluster.getNodeById(stealNodeId)\n .getPartitionIds());\n\n List<Integer> currentList = new ArrayList<Integer>();\n if(currentCluster.hasNodeWithId(stealNodeId)) {\n currentList = currentCluster.getNodeById(stealNodeId).getPartitionIds();\n } else {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Current cluster does not contain stealer node (cluster : [[[\"\n + currentCluster + \"]]], node id \" + stealNodeId + \")\");\n }\n }\n finalList.removeAll(currentList);\n\n return finalList;\n }", "@RequestMapping(value=\"/soy/compileJs\", method=GET)\n public ResponseEntity<String> compile(@RequestParam(required = false, value=\"hash\", defaultValue = \"\") final String hash,\n @RequestParam(required = true, value = \"file\") final String[] templateFileNames,\n @RequestParam(required = false, value = \"locale\") String locale,\n @RequestParam(required = false, value = \"disableProcessors\", defaultValue = \"false\") String disableProcessors,\n final HttpServletRequest request) throws IOException {\n return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale);\n }", "public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }", "public void registerDropPasteWorker(DropPasteWorkerInterface worker)\r\n {\r\n this.dropPasteWorkerSet.add(worker);\r\n defaultDropTarget.setDefaultActions( \r\n defaultDropTarget.getDefaultActions() \r\n | worker.getAcceptableActions(defaultDropTarget.getComponent())\r\n );\r\n }", "@UiThread\n protected void expandView() {\n setExpanded(true);\n onExpansionToggled(false);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentExpanded(getAdapterPosition());\n }\n }", "public By getWebDriverBy() {\n\n\t\tswitch (how) {\n\t\t\tcase name:\n\t\t\t\treturn By.name(this.value);\n\n\t\t\tcase xpath:\n\t\t\t\t// Work around HLWK driver bug\n\t\t\t\treturn By.xpath(this.value.replaceAll(\"/BODY\\\\[1\\\\]/\", \"/BODY/\"));\n\n\t\t\tcase id:\n\t\t\t\treturn By.id(this.value);\n\n\t\t\tcase tag:\n\t\t\t\treturn By.tagName(this.value);\n\n\t\t\tcase text:\n\t\t\t\treturn By.linkText(this.value);\n\n\t\t\tcase partialText:\n\t\t\t\treturn By.partialLinkText(this.value);\n\n\t\t\tdefault:\n\t\t\t\treturn null;\n\n\t\t}\n\n\t}", "@Override\n public void close() {\n status = TrStatus.CLOSED;\n try {\n node.close();\n } catch (IOException e) {\n log.error(\"Failed to close ephemeral node\");\n throw new IllegalStateException(e);\n }\n }" ]
Returns a builder that is initialized with the given path. @param path the path to initialize with @return the new {@code UriComponentsBuilder}
[ "public static UriComponentsBuilder fromPath(String path) {\n\t\tUriComponentsBuilder builder = new UriComponentsBuilder();\n\t\tbuilder.path(path);\n\t\treturn builder;\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 }", "@Override\n public List<JobInstance> getJobs(Query query)\n {\n return JqmClientFactory.getClient().getJobs(query);\n }", "public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) {\n if(timeout < 0)\n throw new IllegalArgumentException(\"The timeout must be a non-negative number.\");\n this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit);\n return this;\n }", "public double getYield(double bondPrice, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenYield(0.0,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}", "public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}", "public static java.sql.Date rollYears(java.util.Date startDate, int years) {\n return rollDate(startDate, Calendar.YEAR, years);\n }", "public static void checkDirectory(File directory) {\n if (!(directory.exists() || directory.mkdirs())) {\n throw new ReportGenerationException(\n String.format(\"Can't create data directory <%s>\", directory.getAbsolutePath())\n );\n }\n }", "public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) {\n int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N;\n\n if( upper ) {\n return triangleUpper(N,0,nz,-1,1,rand);\n } else {\n return triangleLower(N,0,nz,-1,1,rand);\n }\n }", "public static BoxCollaborationWhitelist.Info create(final BoxAPIConnection api, String domain,\n WhitelistDirection direction) {\n\n URL url = COLLABORATION_WHITELIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"domain\", domain)\n .add(\"direction\", direction.toString());\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelist domainWhitelist =\n new BoxCollaborationWhitelist(api, responseJSON.get(\"id\").asString());\n\n return domainWhitelist.new Info(responseJSON);\n }" ]
Populate time ranges. @param ranges time ranges from a Synchro table @param container time range container
[ "private void processRanges(List<DateRange> ranges, ProjectCalendarDateRanges container)\n {\n if (ranges != null)\n {\n for (DateRange range : ranges)\n {\n container.addRange(range);\n }\n }\n }" ]
[ "public static boolean isArray(Type type) {\n return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray());\n }", "public static List<String> getLayersDigests(String manifestContent) throws IOException {\n List<String> dockerLayersDependencies = new ArrayList<String>();\n\n JsonNode manifest = Utils.mapper().readTree(manifestContent);\n JsonNode schemaVersion = manifest.get(\"schemaVersion\");\n if (schemaVersion == null) {\n throw new IllegalStateException(\"Could not find 'schemaVersion' in manifest\");\n }\n\n boolean isSchemeVersion1 = schemaVersion.asInt() == 1;\n JsonNode fsLayers = getFsLayers(manifest, isSchemeVersion1);\n for (JsonNode fsLayer : fsLayers) {\n JsonNode blobSum = getBlobSum(isSchemeVersion1, fsLayer);\n dockerLayersDependencies.add(blobSum.asText());\n }\n dockerLayersDependencies.add(getConfigDigest(manifestContent));\n\n //Add manifest sha1\n String manifestSha1 = Hashing.sha1().hashString(manifestContent, Charsets.UTF_8).toString();\n dockerLayersDependencies.add(\"sha1:\" + manifestSha1);\n\n return dockerLayersDependencies;\n }", "protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }", "protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) {\n \tMap<String, TermImpl> updatedValues = new HashMap<>();\n \tfor(NameWithUpdate update : updates.values()) {\n if (!update.write) {\n continue;\n }\n updatedValues.put(update.value.getLanguageCode(), monolingualToJackson(update.value));\n \t}\n \treturn updatedValues;\n }", "public double totalCount() {\r\n if (depth() == 1) {\r\n return total; // I think this one is always OK. Not very principled here, though.\r\n } else {\r\n double result = 0.0;\r\n for (K o: topLevelKeySet()) {\r\n result += conditionalizeOnce(o).totalCount();\r\n }\r\n return result;\r\n }\r\n }", "public static String constructResourceId(\n final String subscriptionId,\n final String resourceGroupName,\n final String resourceProviderNamespace,\n final String resourceType,\n final String resourceName,\n final String parentResourcePath) {\n String prefixedParentPath = parentResourcePath;\n if (parentResourcePath != null && !parentResourcePath.isEmpty()) {\n prefixedParentPath = \"/\" + parentResourcePath;\n }\n return String.format(\n \"/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s\",\n subscriptionId,\n resourceGroupName,\n resourceProviderNamespace,\n prefixedParentPath,\n resourceType,\n resourceName);\n }", "@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}", "public Resource addReference(Reference reference) {\n\t\tResource resource = this.rdfWriter.getUri(Vocabulary.getReferenceUri(reference));\n\n\t\tthis.referenceQueue.add(reference);\n\t\tthis.referenceSubjectQueue.add(resource);\n\n\t\treturn resource;\n\t}", "public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,\n IllegalAccessException, IllegalArgumentException, InvocationTargetException,\n NoSuchMethodException, SecurityException {\n URLClassLoader sysloader = (URLClassLoader) loader;\n Class<?> sysclass = URLClassLoader.class;\n\n Method method =\n sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});\n method.setAccessible(true);\n method.invoke(sysloader, new Object[] {url});\n\n }" ]
Join the Collection of Strings using the specified delimter and optionally quoting each @param s The String collection @param delimiter the delimiter String @param doQuote whether or not to quote the Strings @return The joined String
[ "public static String join(Collection<String> s, String delimiter, boolean doQuote) {\r\n StringBuffer buffer = new StringBuffer();\r\n Iterator<String> iter = s.iterator();\r\n while (iter.hasNext()) {\r\n if (doQuote) {\r\n buffer.append(\"\\\"\" + iter.next() + \"\\\"\");\r\n } else {\r\n buffer.append(iter.next());\r\n }\r\n if (iter.hasNext()) {\r\n buffer.append(delimiter);\r\n }\r\n }\r\n return buffer.toString();\r\n }" ]
[ "public static CrashReport fromJson(String json) throws IllegalArgumentException {\n try {\n return new CrashReport(json);\n } catch (JSONException je) {\n throw new IllegalArgumentException(je.toString());\n }\n }", "private void normalizeSelectedCategories() {\r\n\r\n Collection<String> normalizedCategories = new ArrayList<String>(m_selectedCategories.size());\r\n for (CmsTreeItem item : m_categories.values()) {\r\n if (item.getCheckBox().isChecked()) {\r\n normalizedCategories.add(item.getId());\r\n }\r\n }\r\n m_selectedCategories = normalizedCategories;\r\n\r\n }", "public static void openFavoriteDialog(CmsFileExplorer explorer) {\n\n try {\n CmsExplorerFavoriteContext context = new CmsExplorerFavoriteContext(A_CmsUI.getCmsObject(), explorer);\n CmsFavoriteDialog dialog = new CmsFavoriteDialog(context, new CmsFavoriteDAO(A_CmsUI.getCmsObject()));\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setContent(dialog);\n window.setCaption(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_FAVORITES_DIALOG_TITLE_0));\n A_CmsUI.get().addWindow(window);\n window.center();\n } catch (CmsException e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }", "public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"classes.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Image\"\n\t\t\t\t\t+ \",Number of direct instances\"\n\t\t\t\t\t+ \",Number of direct subclasses\" + \",Direct superclasses\"\n\t\t\t\t\t+ \",All superclasses\" + \",Related properties\");\n\n\t\t\tList<Entry<EntityIdValue, ClassRecord>> list = new ArrayList<>(\n\t\t\t\t\tthis.classRecords.entrySet());\n\t\t\tCollections.sort(list, new ClassUsageRecordComparator());\n\t\t\tfor (Entry<EntityIdValue, ClassRecord> entry : list) {\n\t\t\t\tif (entry.getValue().itemCount > 0\n\t\t\t\t\t\t|| entry.getValue().subclassCount > 0) {\n\t\t\t\t\tprintClassRecord(out, entry.getValue(), entry.getKey());\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n if (jobTypes == null) {\n throw new IllegalArgumentException(\"jobTypes must not be null\");\n }\n for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) {\n try {\n checkJobType(entry.getKey(), entry.getValue());\n } catch (IllegalArgumentException iae) {\n throw new IllegalArgumentException(\"jobTypes contained invalid value\", iae);\n }\n }\n }", "public Task<Void> sendResetPasswordEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n sendResetPasswordEmailInternal(email);\n return null;\n }\n });\n }", "public static base_response update(nitro_service client, route6 resource) throws Exception {\n\t\troute6 updateresource = new route6();\n\t\tupdateresource.network = resource.network;\n\t\tupdateresource.gateway = resource.gateway;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.distance = resource.distance;\n\t\tupdateresource.cost = resource.cost;\n\t\tupdateresource.advertise = resource.advertise;\n\t\tupdateresource.msr = resource.msr;\n\t\tupdateresource.monitor = resource.monitor;\n\t\tupdateresource.td = resource.td;\n\t\treturn updateresource.update_resource(client);\n\t}", "private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation,\n ModelNode host) {\n final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR));\n if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) {\n //We have a composite operation resulting from a transformation to redeploy affected deployments\n //See redeploying deployments affected by an overlay.\n ModelNode serverOp = operation.clone();\n Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>();\n for (ModelNode step : serverOp.get(STEPS).asList()) {\n ModelNode newStep = step.clone();\n String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue();\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies);\n for(ServerIdentity server : servers) {\n if(!composite.containsKey(server)) {\n composite.put(server, Operations.CompositeOperationBuilder.create());\n }\n composite.get(server).addStep(newStep);\n }\n if(!servers.isEmpty()) {\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n }\n }\n if(!composite.isEmpty()) {\n Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>();\n for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) {\n result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation());\n }\n return result;\n }\n return Collections.emptyMap();\n }\n final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies);\n return Collections.singletonMap(allServers, operation.clone());\n }" ]
Resolve an operation transformer entry. @param address the address @param operationName the operation name @param placeholderResolver a placeholder resolver used to resolve children of a placeholder registration @return the transformer entry
[ "public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }" ]
[ "@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }", "private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) {\n if (mn==null) {\n return;\n }\n ClassNode declaringClass = mn.getDeclaringClass();\n ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();\n if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) {\n int mods = mn.getModifiers();\n boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule();\n String packageName = declaringClass.getPackageName();\n if (packageName==null) {\n packageName = \"\";\n }\n if ((Modifier.isPrivate(mods) && sameModule)\n || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) {\n addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn);\n }\n }\n }", "public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }", "private boolean isOrdinal(int paramType) {\n\t\tswitch ( paramType ) {\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.NUMERIC:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\tcase Types.BIGINT:\n\t\t\tcase Types.DECIMAL: //for Oracle Driver\n\t\t\tcase Types.DOUBLE: //for Oracle Driver\n\t\t\tcase Types.FLOAT: //for Oracle Driver\n\t\t\t\treturn true;\n\t\t\tcase Types.CHAR:\n\t\t\tcase Types.LONGVARCHAR:\n\t\t\tcase Types.VARCHAR:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\tthrow new HibernateException( \"Unable to persist an Enum in a column of SQL Type: \" + paramType );\n\t\t}\n\t}", "public ValueContainer[] getValuesForObject(FieldDescriptor[] fields, Object obj, boolean convertToSql, boolean assignAutoincrement) throws PersistenceBrokerException\r\n {\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fd = fields[i];\r\n Object cv = fd.getPersistentField().get(obj);\r\n\r\n /*\r\n handle autoincrement attributes if\r\n - is a autoincrement field\r\n - field represents a 'null' value, is nullified\r\n and generate a new value\r\n */\r\n if(assignAutoincrement && fd.isAutoIncrement() && representsNull(fd, cv))\r\n {\r\n /*\r\n setAutoIncrementValue returns a value that is\r\n properly typed for the java-world. This value\r\n needs to be converted to it's corresponding\r\n sql type so that the entire result array contains\r\n objects that are properly typed for sql.\r\n */\r\n cv = setAutoIncrementValue(fd, obj);\r\n }\r\n if(convertToSql)\r\n {\r\n // apply type and value conversion\r\n cv = fd.getFieldConversion().javaToSql(cv);\r\n }\r\n // create ValueContainer\r\n result[i] = new ValueContainer(cv, fd.getJdbcType());\r\n }\r\n return result;\r\n }", "Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }", "@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new MultiInstanceWorkloadStrategy(factory, name, arguments, endpointRegistry, execService));\n }\n }", "private static Class getClassForClassNode(ClassNode type) {\r\n // todo hamlet - move to a different \"InferenceUtil\" object\r\n Class primitiveType = getPrimitiveType(type);\r\n if (primitiveType != null) {\r\n return primitiveType;\r\n } else if (classNodeImplementsType(type, String.class)) {\r\n return String.class;\r\n } else if (classNodeImplementsType(type, ReentrantLock.class)) {\r\n return ReentrantLock.class;\r\n } else if (type.getName() != null && type.getName().endsWith(\"[]\")) {\r\n return Object[].class; // better type inference could be done, but oh well\r\n }\r\n return null;\r\n }", "private int runCommitScript() {\n\n if (m_checkout && !m_fetchAndResetBeforeImport) {\n m_logStream.println(\"Skipping script....\");\n return 0;\n }\n try {\n m_logStream.flush();\n String commandParam;\n if (m_resetRemoteHead) {\n commandParam = resetRemoteHeadScriptCommand();\n } else if (m_resetHead) {\n commandParam = resetHeadScriptCommand();\n } else if (m_checkout) {\n commandParam = checkoutScriptCommand();\n } else {\n commandParam = checkinScriptCommand();\n }\n String[] cmd = {\"bash\", \"-c\", commandParam};\n m_logStream.println(\"Calling the script as follows:\");\n m_logStream.println();\n m_logStream.println(cmd[0] + \" \" + cmd[1] + \" \" + cmd[2]);\n ProcessBuilder builder = new ProcessBuilder(cmd);\n m_logStream.close();\n m_logStream = null;\n Redirect redirect = Redirect.appendTo(new File(DEFAULT_LOGFILE_PATH));\n builder.redirectOutput(redirect);\n builder.redirectError(redirect);\n Process scriptProcess = builder.start();\n int exitCode = scriptProcess.waitFor();\n scriptProcess.getOutputStream().close();\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, true));\n return exitCode;\n } catch (InterruptedException | IOException e) {\n e.printStackTrace(m_logStream);\n return -1;\n }\n\n }" ]
Returns number of dependencies layers in the image. @param imageContent @return @throws IOException
[ "public static int getNumberOfDependentLayers(String imageContent) throws IOException {\n JsonNode history = Utils.mapper().readTree(imageContent).get(\"history\");\n if (history == null) {\n throw new IllegalStateException(\"Could not find 'history' tag\");\n }\n\n int layersNum = history.size();\n boolean newImageLayers = true;\n for (int i = history.size() - 1; i >= 0; i--) {\n\n if (newImageLayers) {\n layersNum--;\n }\n\n JsonNode layer = history.get(i);\n JsonNode emptyLayer = layer.get(\"empty_layer\");\n if (!newImageLayers && emptyLayer != null) {\n layersNum--;\n }\n\n if (layer.get(\"created_by\") == null) {\n continue;\n }\n String createdBy = layer.get(\"created_by\").textValue();\n if (createdBy.contains(\"ENTRYPOINT\") || createdBy.contains(\"MAINTAINER\")) {\n newImageLayers = false;\n }\n }\n return layersNum;\n }" ]
[ "@SuppressWarnings(\"WeakerAccess\")\n public ByteBuffer getRawData() {\n if (rawData != null) {\n rawData.rewind();\n return rawData.slice();\n }\n return null;\n }", "public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) {\n return find(project, type) != null;\n }", "private void nodeProperties(Options opt) {\n\tOptions def = opt.getGlobalOptions();\n\tif (opt.nodeFontName != def.nodeFontName)\n\t w.print(\",fontname=\\\"\" + opt.nodeFontName + \"\\\"\");\n\tif (opt.nodeFontColor != def.nodeFontColor)\n\t w.print(\",fontcolor=\\\"\" + opt.nodeFontColor + \"\\\"\");\n\tif (opt.nodeFontSize != def.nodeFontSize)\n\t w.print(\",fontsize=\" + fmt(opt.nodeFontSize));\n\tw.print(opt.shape.style);\n\tw.println(\"];\");\n }", "public static ScheduledExecutorService newScheduledDaemonThreadPool(int corePoolSize) {\n return Executors.newScheduledThreadPool(corePoolSize, r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }", "public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }", "public static Class getClass(String name) throws ClassNotFoundException\r\n {\r\n try\r\n {\r\n return Class.forName(name);\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ClassNotFoundException(name);\r\n }\r\n }", "public PhotoList<Photo> getNotInSet(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\", PhotosInterface.METHOD_GET_NOT_IN_SET);\r\n\r\n RequestContext requestContext = RequestContext.getRequestContext();\r\n\r\n List<String> extras = requestContext.getExtras();\r\n if (extras.size() > 0) {\r\n parameters.put(\"extras\", StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n 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 static base_response update(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 updateresource = new nspbr6();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.msr = resource.msr;\n\t\tupdateresource.monitor = resource.monitor;\n\t\tupdateresource.nexthop = resource.nexthop;\n\t\tupdateresource.nexthopval = resource.nexthopval;\n\t\tupdateresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }" ]
Verify store definitions are congruent with cluster definition. @param cluster @param storeDefs
[ "public static void validateClusterStores(final Cluster cluster,\n final List<StoreDefinition> storeDefs) {\n // Constructing a StoreRoutingPlan has the (desirable in this\n // case) side-effect of verifying that the store definition is congruent\n // with the cluster definition. If there are issues, exceptions are\n // thrown.\n for(StoreDefinition storeDefinition: storeDefs) {\n new StoreRoutingPlan(cluster, storeDefinition);\n }\n return;\n }" ]
[ "public UpdateBuilder<T, ID> updateColumnExpression(String columnName, String expression) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetExpression(columnName, fieldType, expression));\n\t\treturn this;\n\t}", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerWidget(View widget) {\n prepareWidget(widget);\n\n if (widget instanceof AlgoliaResultsListener) {\n AlgoliaResultsListener listener = (AlgoliaResultsListener) widget;\n if (!this.resultListeners.contains(listener)) {\n this.resultListeners.add(listener);\n }\n searcher.registerResultListener(listener);\n }\n if (widget instanceof AlgoliaErrorListener) {\n AlgoliaErrorListener listener = (AlgoliaErrorListener) widget;\n if (!this.errorListeners.contains(listener)) {\n this.errorListeners.add(listener);\n }\n searcher.registerErrorListener(listener);\n }\n if (widget instanceof AlgoliaSearcherListener) {\n AlgoliaSearcherListener listener = (AlgoliaSearcherListener) widget;\n listener.initWithSearcher(searcher);\n }\n }", "public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) {\n return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types);\n }", "public static byte[] hashPath(MessageDigest messageDigest, Path path) throws IOException {\n try (InputStream in = getRecursiveContentStream(path)) {\n return hashContent(messageDigest, in);\n }\n }", "protected void print(String text) {\n String tableStart = format(PARAMETER_TABLE_START, PARAMETER_TABLE_START);\n String tableEnd = format(PARAMETER_TABLE_END, PARAMETER_TABLE_END);\n boolean containsTable = text.contains(tableStart) && text.contains(tableEnd);\n String textToPrint = containsTable ? transformPrintingTable(text, tableStart, tableEnd) : text;\n print(output, textToPrint\n .replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format(\"parameterValueStart\", EMPTY))\n .replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format(\"parameterValueEnd\", EMPTY))\n .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format(\"parameterValueNewline\", NL)));\n }", "public static base_responses delete(nitro_service client, String network[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (network != null && network.length > 0) {\n\t\t\troute6 deleteresources[] = new route6[network.length];\n\t\t\tfor (int i=0;i<network.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = network[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) {\n return requestMetadataInternal(track, trackType, false);\n }", "public static void acceptsNodeMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id list\")\n .withRequiredArg()\n .describedAs(\"node-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }", "public static boolean start(RootDoc root) {\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", running the standard doclet\");\n\tStandard.start(root);\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", altering javadocs\");\n\ttry {\n\t String outputFolder = findOutputPath(root.options());\n\n Options opt = UmlGraph.buildOptions(root);\n\t opt.setOptions(root.options());\n\t // in javadoc enumerations are always printed\n\t opt.showEnumerations = true;\n\t opt.relativeLinksForSourcePackages = true;\n\t // enable strict matching for hide expressions\n\t opt.strictMatching = true;\n//\t root.printNotice(opt.toString());\n\n\t generatePackageDiagrams(root, opt, outputFolder);\n\t generateContextDiagrams(root, opt, outputFolder);\n\t} catch(Throwable t) {\n\t root.printWarning(\"Error: \" + t.toString());\n\t t.printStackTrace();\n\t return false;\n\t}\n\treturn true;\n }" ]
Input method, called by a Subscriber indicating its intent into receive notification about a given topic. @param sr DTO containing the info given by the protocol
[ "public void subscriptionRequestReceived(SubscriptionRequest sr) throws SubscriptionException {\n\n LOG.info(\"Subscriber -> (Hub), new subscription request received.\", sr.getCallback());\n\n try {\n\n verifySubscriberRequestedSubscription(sr);\n\n if (\"subscribe\".equals(sr.getMode())) {\n LOG.info(\"Adding callback {} to the topic {}\", sr.getCallback(), sr.getTopic());\n addCallbackToTopic(sr.getCallback(), sr.getTopic());\n } else if (\"unsubscribe\".equals(sr.getMode())) {\n LOG.info(\"Removing callback {} from the topic {}\", sr.getCallback(), sr.getTopic());\n removeCallbackToTopic(sr.getCallback(), sr.getTopic());\n }\n\n } catch (Exception e) {\n throw new SubscriptionException(e);\n }\n\n }" ]
[ "public static boolean isTemplatePath(String string) {\n int sz = string.length();\n if (sz == 0) {\n return true;\n }\n for (int i = 0; i < sz; ++i) {\n char c = string.charAt(i);\n switch (c) {\n case ' ':\n case '\\t':\n case '\\b':\n case '<':\n case '>':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '!':\n case '@':\n case '#':\n case '*':\n case '?':\n case '%':\n case '|':\n case ',':\n case ':':\n case ';':\n case '^':\n case '&':\n return false;\n }\n }\n return true;\n }", "protected ClassDescriptor getClassDescriptor()\r\n {\r\n ClassDescriptor cld = (ClassDescriptor) m_classDescriptor.get();\r\n if(cld == null)\r\n {\r\n throw new OJBRuntimeException(\"Requested ClassDescriptor instance was already GC by JVM\");\r\n }\r\n return cld;\r\n }", "private int[] changeColor() {\n int[] changedPixels = new int[pixels.length];\n double frequenz = 2 * Math.PI / 1020;\n\n for (int i = 0; i < pixels.length; i++) {\n int argb = pixels[i];\n int a = (argb >> 24) & 0xff;\n int r = (argb >> 16) & 0xff;\n int g = (argb >> 8) & 0xff;\n int b = argb & 0xff;\n\n r = (int) (255 * Math.sin(frequenz * r));\n b = (int) (-255 * Math.cos(frequenz * b) + 255);\n\n changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;\n }\n\n return changedPixels;\n }", "public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\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 static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }", "public static ipset_nsip_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip_binding obj = new ipset_nsip_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip_binding response[] = (ipset_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Task<Void> sendResetPasswordEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n sendResetPasswordEmailInternal(email);\n return null;\n }\n });\n }", "private void checkExtents(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap processedClasses = new HashMap();\r\n InheritanceHelper helper = new InheritanceHelper();\r\n ClassDescriptorDef curExtent;\r\n boolean canBeRemoved;\r\n\r\n for (Iterator it = classDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curExtent = (ClassDescriptorDef)it.next();\r\n canBeRemoved = false;\r\n if (classDef.getName().equals(curExtent.getName()))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies itself as an extent-class\");\r\n }\r\n else if (processedClasses.containsKey(curExtent))\r\n {\r\n canBeRemoved = true;\r\n }\r\n else\r\n {\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(curExtent, classDef.getName(), false))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies an extent-class \"+curExtent.getName()+\" that is not a sub-type of it\");\r\n }\r\n // now we check whether we already have an extent for a base-class of this extent-class\r\n for (Iterator processedIt = processedClasses.keySet().iterator(); processedIt.hasNext();)\r\n {\r\n if (helper.isSameOrSubTypeOf(curExtent, ((ClassDescriptorDef)processedIt.next()).getName(), false))\r\n {\r\n canBeRemoved = true;\r\n break;\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n // won't happen because we don't use lookup of the actual classes\r\n }\r\n }\r\n if (canBeRemoved)\r\n {\r\n it.remove();\r\n }\r\n processedClasses.put(curExtent, null);\r\n }\r\n }" ]
Checks to see if all the diagonal elements in the matrix are positive. @param a A matrix. Not modified. @return true if all the diagonal elements are positive, false otherwise.
[ "public static boolean isDiagonalPositive( DMatrixRMaj a ) {\n for( int i = 0; i < a.numRows; i++ ) {\n if( !(a.get(i,i) >= 0) )\n return false;\n }\n return true;\n }" ]
[ "public static String ptb2Text(String ptbText) {\r\n StringBuilder sb = new StringBuilder(ptbText.length()); // probably an overestimate\r\n PTB2TextLexer lexer = new PTB2TextLexer(new StringReader(ptbText));\r\n try {\r\n for (String token; (token = lexer.next()) != null; ) {\r\n sb.append(token);\r\n }\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n return sb.toString();\r\n }", "public float rotateToFaceCamera(final Widget widget) {\n final float yaw = getMainCameraRigYaw();\n GVRTransform t = getMainCameraRig().getHeadTransform();\n widget.rotateWithPivot(t.getRotationW(), 0, t.getRotationY(), 0, 0, 0, 0);\n return yaw;\n }", "private Server setUpServer() {\n Server server = new Server(port);\n ResourceHandler handler = new ResourceHandler();\n handler.setDirectoriesListed(true);\n handler.setWelcomeFiles(new String[]{\"index.html\"});\n handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString());\n HandlerList handlers = new HandlerList();\n handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});\n server.setStopAtShutdown(true);\n server.setHandler(handlers);\n return server;\n }", "@Override\n\tpublic String toNormalizedWildcardString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedWildcardString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedWildcardString = result = toNormalizedString(IPv6StringCache.wildcardNormalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedWildcardString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "private boolean hasBidirectionalAssociation(Class clazz)\r\n {\r\n ClassDescriptor cdesc;\r\n Collection refs;\r\n boolean hasBidirAssc;\r\n\r\n if (_withoutBidirAssc.contains(clazz))\r\n {\r\n return false;\r\n }\r\n\r\n if (_withBidirAssc.contains(clazz))\r\n {\r\n return true;\r\n }\r\n\r\n // first time we meet this class, let's look at metadata\r\n cdesc = _pb.getClassDescriptor(clazz);\r\n refs = cdesc.getObjectReferenceDescriptors();\r\n hasBidirAssc = false;\r\n REFS_CYCLE:\r\n for (Iterator it = refs.iterator(); it.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor ord;\r\n ClassDescriptor relCDesc;\r\n Collection relRefs;\r\n\r\n ord = (ObjectReferenceDescriptor) it.next();\r\n relCDesc = _pb.getClassDescriptor(ord.getItemClass());\r\n relRefs = relCDesc.getObjectReferenceDescriptors();\r\n for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor relOrd;\r\n\r\n relOrd = (ObjectReferenceDescriptor) relIt.next();\r\n if (relOrd.getItemClass().equals(clazz))\r\n {\r\n hasBidirAssc = true;\r\n break REFS_CYCLE;\r\n }\r\n }\r\n }\r\n if (hasBidirAssc)\r\n {\r\n _withBidirAssc.add(clazz);\r\n }\r\n else\r\n {\r\n _withoutBidirAssc.add(clazz);\r\n }\r\n\r\n return hasBidirAssc;\r\n }", "public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }", "public StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }", "public static String getOjbClassName(ResultSet rs)\r\n {\r\n try\r\n {\r\n return rs.getString(OJB_CLASS_COLUMN);\r\n }\r\n catch (SQLException e)\r\n {\r\n return null;\r\n }\r\n }", "@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n if(requestObject != null) {\n\n // Dropping dead requests from going to next handler\n long now = System.currentTimeMillis();\n if(requestObject.getRequestOriginTimeInMs() + requestObject.getRoutingTimeoutInMs() <= now) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUEST_TIMEOUT,\n \"current time: \"\n + now\n + \"\\torigin time: \"\n + requestObject.getRequestOriginTimeInMs()\n + \"\\ttimeout in ms: \"\n + requestObject.getRoutingTimeoutInMs());\n return;\n } else {\n Store store = getStore(requestValidator.getStoreName(),\n requestValidator.getParsedRoutingType());\n if(store != null) {\n VoldemortStoreRequest voldemortStoreRequest = new VoldemortStoreRequest(requestObject,\n store,\n parseZoneId());\n Channels.fireMessageReceived(ctx, voldemortStoreRequest);\n } else {\n logger.error(\"Error when getting store. Non Existing store name.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store name. Critical error.\");\n return;\n\n }\n }\n }\n }" ]
Obtains a local date in Coptic calendar system from the era, year-of-era and day-of-year fields. @param era the Coptic era, not null @param yearOfEra the year-of-era @param dayOfYear the day-of-year @return the Coptic local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code CopticEra}
[ "@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
[ "public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceType\n termsOfServiceType) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (termsOfServiceType != null) {\n builder.appendParam(\"tos_type\", termsOfServiceType.toString());\n }\n\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject termsOfServiceJSON = value.asObject();\n BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get(\"id\").asString());\n BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);\n termsOfServices.add(info);\n }\n\n return termsOfServices;\n }", "public ProjectCalendarWeek addWorkWeek()\n {\n ProjectCalendarWeek week = new ProjectCalendarWeek();\n week.setParent(this);\n m_workWeeks.add(week);\n m_weeksSorted = false;\n clearWorkingDateCache();\n return week;\n }", "private void checkTexRange(AiTextureType type, int index) {\n if (index < 0 || index > m_numTextures.get(type)) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size: \" +\n m_numTextures.get(type));\n }\n }", "protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) {\n\n ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder();\n extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader()));\n if (isDevModeEnabled) {\n extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), \"N/A\"));\n }\n\n final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build();\n final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);\n final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB);\n\n final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(),\n Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY)));\n\n if (Jandex.isJandexAvailable(resourceLoader)) {\n try {\n Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER);\n strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context)));\n } catch (Exception e) {\n throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e);\n }\n } else {\n strategy.registerHandler(new ServletContextBeanArchiveHandler(context));\n }\n strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context));\n Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery();\n\n String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION);\n\n if (isolation == null || Boolean.valueOf(isolation)) {\n CommonLogger.LOG.archiveIsolationEnabled();\n } else {\n CommonLogger.LOG.archiveIsolationDisabled();\n Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();\n flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives));\n beanDeploymentArchives = flatDeployment;\n }\n\n for (BeanDeploymentArchive archive : beanDeploymentArchives) {\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n }\n\n CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) {\n @Override\n protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive();\n archive.getServices().add(EEModuleDescriptor.class, eeModule);\n return archive;\n }\n };\n\n if (strategy.getClassFileServices() != null) {\n deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices());\n }\n return deployment;\n }", "public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\n }", "public void setSpeed(float newValue) {\n if (newValue < 0) newValue = 0;\n this.pitch.setValue( newValue );\n this.speed.setValue( newValue );\n }", "public static Observable<Void> mapToVoid(Observable<?> fromObservable) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<Void>());\n } else {\n return Observable.empty();\n }\n }", "private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {\n this.stats.startTime = System.currentTimeMillis();\n try {\n // build and record parsed units\n reportProgress(Messages.compilation_beginningToCompile);\n\n if (this.options.complianceLevel >= ClassFileConstants.JDK9) {\n // in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:\n sortModuleDeclarationsFirst(sourceUnits);\n }\n if (this.annotationProcessorManager == null) {\n beginToCompile(sourceUnits);\n } else {\n ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs\n try {\n beginToCompile(sourceUnits);\n if (!lastRound) {\n processAnnotations();\n }\n if (!this.options.generateClassFiles) {\n // -proc:only was set on the command line\n return;\n }\n } catch (SourceTypeCollisionException e) {\n backupAptProblems();\n reset();\n // a generated type was referenced before it was created\n // the compiler either created a MissingType or found a BinaryType for it\n // so add the processor's generated files & start over,\n // but remember to only pass the generated files to the annotation processor\n int originalLength = originalUnits.length;\n int newProcessedLength = e.newAnnotationProcessorUnits.length;\n ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];\n System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);\n System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);\n this.annotationProcessorStartIndex = originalLength;\n compile(combinedUnits, e.isLastRound);\n return;\n }\n }\n // Restore the problems before the results are processed and cleaned up.\n restoreAptProblems();\n processCompiledUnits(0, lastRound);\n } catch (AbortCompilation e) {\n this.handleInternalException(e, null);\n }\n if (this.options.verbose) {\n if (this.totalUnits > 1) {\n this.out.println(\n Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));\n } else {\n this.out.println(\n Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));\n }\n }\n }", "@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\n }" ]
URL-encodes a given string using ISO-8859-1, which may work better with web pages and umlauts compared to UTF-8. No UnsupportedEncodingException to handle as it is dealt with in this method.
[ "public static String encodeUrlIso(String stringToEncode) {\n try {\n return URLEncoder.encode(stringToEncode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }" ]
[ "public void login(Object userIdentifier) {\n session().put(config().sessionKeyUsername(), userIdentifier);\n app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));\n }", "public static vpnclientlessaccesspolicy[] get(nitro_service service) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "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 unset(nitro_service client, sslparameter resource, String[] args) throws Exception{\n\t\tsslparameter unsetresource = new sslparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private static int getColumnWidth(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n if (Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) {\n return 70;\n } else if (type == Boolean.class) {\n return 10;\n } else if (Number.class.isAssignableFrom(type)) {\n return 60;\n } else if (type == String.class) {\n return 100;\n } else if (Date.class.isAssignableFrom(type)) {\n return 50;\n } else {\n return 50;\n }\n }", "public static Boolean compareSingleClientConfigAvro(String configAvro1, String configAvro2) {\n Properties props1 = readSingleClientConfigAvro(configAvro1);\n Properties props2 = readSingleClientConfigAvro(configAvro2);\n if(props1.equals(props2)) {\n return true;\n } else {\n return false;\n }\n }", "public int getOpacity() {\n\t\tint opacity = Math\n\t\t\t\t.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));\n\t\tif (opacity < 5) {\n\t\t\treturn 0x00;\n\t\t} else if (opacity > 250) {\n\t\t\treturn 0xFF;\n\t\t} else {\n\t\t\treturn opacity;\n\t\t}\n\t}", "public static gslbldnsentries[] get(nitro_service service) throws Exception{\n\t\tgslbldnsentries obj = new gslbldnsentries();\n\t\tgslbldnsentries[] response = (gslbldnsentries[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }" ]
Determines the offset code of a forward contract from the name of a forward curve. This method will extract a group of one or more digits together with the first letter behind them, if any. If there are multiple groups of digits in the name, this method will extract the last. If there is no number in the string, this method will return null. @param curveName The name of the curve. @return The offset code as String
[ "public static String getOffsetCodeFromCurveName(String curveName) {\r\n\t\tif(curveName == null || curveName.length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tString[] splits = curveName.split(\"(?<=\\\\D)(?=\\\\d)\");\r\n\t\tString offsetCode = splits[splits.length-1];\r\n\t\tif(!Character.isDigit(offsetCode.charAt(0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\toffsetCode = offsetCode.split(\"(?<=[A-Za-z])(?=.)\", 2)[0];\r\n\t\toffsetCode = offsetCode.replaceAll( \"[\\\\W_]\", \"\" );\r\n\t\treturn offsetCode;\r\n\t}" ]
[ "public synchronized int get(byte[] dst, int off, int len) {\n if (available == 0) {\n return 0;\n }\n\n // limit is last index to read + 1\n int limit = idxGet < idxPut ? idxPut : capacity;\n int count = Math.min(limit - idxGet, len);\n System.arraycopy(buffer, idxGet, dst, off, count);\n idxGet += count;\n\n if (idxGet == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxPut);\n if (count2 > 0) {\n System.arraycopy(buffer, 0, dst, off + count, count2);\n idxGet = count2;\n count += count2;\n } else {\n idxGet = 0;\n }\n }\n available -= count;\n return count;\n }", "@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }", "public static long getTxInfoCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(TX_INFO_CACHE_WEIGHT, TX_INFO_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\"Cache size must be positive for \" + TX_INFO_CACHE_WEIGHT);\n }\n return size;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getTotalVisits() {\n EventDetail ed = getLocalDataStore().getEventDetail(Constants.APP_LAUNCHED_EVENT);\n if (ed != null) return ed.getCount();\n\n return 0;\n }", "@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n if(requestObject != null) {\n\n // Dropping dead requests from going to next handler\n long now = System.currentTimeMillis();\n if(requestObject.getRequestOriginTimeInMs() + requestObject.getRoutingTimeoutInMs() <= now) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUEST_TIMEOUT,\n \"current time: \"\n + now\n + \"\\torigin time: \"\n + requestObject.getRequestOriginTimeInMs()\n + \"\\ttimeout in ms: \"\n + requestObject.getRoutingTimeoutInMs());\n return;\n } else {\n Store store = getStore(requestValidator.getStoreName(),\n requestValidator.getParsedRoutingType());\n if(store != null) {\n VoldemortStoreRequest voldemortStoreRequest = new VoldemortStoreRequest(requestObject,\n store,\n parseZoneId());\n Channels.fireMessageReceived(ctx, voldemortStoreRequest);\n } else {\n logger.error(\"Error when getting store. Non Existing store name.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store name. Critical error.\");\n return;\n\n }\n }\n }\n }", "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 }", "@SuppressWarnings(\"unchecked\")\n @Nonnull\n public final java.util.Optional<Style> getStyle(final String styleName) {\n final String styleRef = this.styles.get(styleName);\n Optional<Style> style;\n if (styleRef != null) {\n style = (Optional<Style>) this.styleParser\n .loadStyle(getConfiguration(), this.httpRequestFactory, styleRef);\n } else {\n style = Optional.empty();\n }\n return or(style, this.configuration.getStyle(styleName));\n }", "public static double elementMax( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a max.\n // Otherwise zero needs to be considered\n double max = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val > max ) {\n max = val;\n }\n }\n\n return max;\n }", "CapabilityRegistry createShadowCopy() {\n CapabilityRegistry result = new CapabilityRegistry(forServer, this);\n readLock.lock();\n try {\n try {\n result.writeLock.lock();\n copy(this, result);\n } finally {\n result.writeLock.unlock();\n }\n } finally {\n readLock.unlock();\n }\n return result;\n }" ]
Retrieves the registar linked to the bus. Creates a new registar is not present. @param bus @return
[ "protected SingleBusLocatorRegistrar getRegistrar(Bus bus) {\n SingleBusLocatorRegistrar registrar = busRegistrars.get(bus);\n if (registrar == null) {\n check(locatorClient, \"serviceLocator\", \"registerService\");\n registrar = new SingleBusLocatorRegistrar(bus);\n registrar.setServiceLocator(locatorClient);\n registrar.setEndpointPrefix(endpointPrefix);\n Map<String, String> endpointPrefixes = new HashMap<String, String>();\n endpointPrefixes.put(\"HTTP\", endpointPrefixHttp);\n endpointPrefixes.put(\"HTTPS\", endpointPrefixHttps);\n registrar.setEndpointPrefixes(endpointPrefixes);\n busRegistrars.put(bus, registrar);\n addLifeCycleListener(bus);\n }\n return registrar;\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 spilloverpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tspilloverpolicy_stats[] response = (spilloverpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }", "private void readCalendar(Gantt gantt)\n {\n Gantt.Calendar ganttCalendar = gantt.getCalendar();\n m_projectFile.getProjectProperties().setWeekStartDay(ganttCalendar.getWeekStart());\n\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setName(\"Standard\");\n m_projectFile.setDefaultCalendar(calendar);\n\n String workingDays = ganttCalendar.getWorkDays();\n calendar.setWorkingDay(Day.SUNDAY, workingDays.charAt(0) == '1');\n calendar.setWorkingDay(Day.MONDAY, workingDays.charAt(1) == '1');\n calendar.setWorkingDay(Day.TUESDAY, workingDays.charAt(2) == '1');\n calendar.setWorkingDay(Day.WEDNESDAY, workingDays.charAt(3) == '1');\n calendar.setWorkingDay(Day.THURSDAY, workingDays.charAt(4) == '1');\n calendar.setWorkingDay(Day.FRIDAY, workingDays.charAt(5) == '1');\n calendar.setWorkingDay(Day.SATURDAY, workingDays.charAt(6) == '1');\n\n for (int i = 1; i <= 7; i++)\n {\n Day day = Day.getInstance(i);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n if (calendar.isWorkingDay(day))\n {\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n\n for (Gantt.Holidays.Holiday holiday : gantt.getHolidays().getHoliday())\n {\n ProjectCalendarException exception = calendar.addCalendarException(holiday.getDate(), holiday.getDate());\n exception.setName(holiday.getContent());\n }\n }", "public static nsacl6[] get(nitro_service service, String acl6name[]) throws Exception{\n\t\tif (acl6name !=null && acl6name.length>0) {\n\t\t\tnsacl6 response[] = new nsacl6[acl6name.length];\n\t\t\tnsacl6 obj[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++) {\n\t\t\t\tobj[i] = new nsacl6();\n\t\t\t\tobj[i].set_acl6name(acl6name[i]);\n\t\t\t\tresponse[i] = (nsacl6) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private Client getClientFromResultSet(ResultSet result) throws Exception {\n Client client = new Client();\n client.setId(result.getInt(Constants.GENERIC_ID));\n client.setUUID(result.getString(Constants.CLIENT_CLIENT_UUID));\n client.setFriendlyName(result.getString(Constants.CLIENT_FRIENDLY_NAME));\n client.setProfile(ProfileService.getInstance().findProfile(result.getInt(Constants.GENERIC_PROFILE_ID)));\n client.setIsActive(result.getBoolean(Constants.CLIENT_IS_ACTIVE));\n client.setActiveServerGroup(result.getInt(Constants.CLIENT_ACTIVESERVERGROUP));\n return client;\n }", "private String writeSchemata(File dir) throws IOException\r\n {\r\n writeCompressedTexts(dir, _torqueSchemata);\r\n\r\n StringBuffer includes = new StringBuffer();\r\n\r\n for (Iterator it = _torqueSchemata.keySet().iterator(); it.hasNext();)\r\n {\r\n includes.append((String)it.next());\r\n if (it.hasNext())\r\n {\r\n includes.append(\",\");\r\n }\r\n }\r\n return includes.toString();\r\n }", "public boolean isMaskCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\tif(!isMultiple()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn super.isMaskCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}", "public static File writeStreamToTempFile(InputStream inputStream, String tempFileSuffix) throws IOException\n {\n FileOutputStream outputStream = null;\n\n try\n {\n File file = File.createTempFile(\"mpxj\", tempFileSuffix);\n outputStream = new FileOutputStream(file);\n byte[] buffer = new byte[1024];\n while (true)\n {\n int bytesRead = inputStream.read(buffer);\n if (bytesRead == -1)\n {\n break;\n }\n outputStream.write(buffer, 0, bytesRead);\n }\n return file;\n }\n\n finally\n {\n if (outputStream != null)\n {\n outputStream.close();\n }\n }\n }" ]
Use this API to Import sslfipskey resources.
[ "public static base_responses Import(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey Importresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tImportresources[i] = new sslfipskey();\n\t\t\t\tImportresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\tImportresources[i].key = resources[i].key;\n\t\t\t\tImportresources[i].inform = resources[i].inform;\n\t\t\t\tImportresources[i].wrapkeyname = resources[i].wrapkeyname;\n\t\t\t\tImportresources[i].iv = resources[i].iv;\n\t\t\t\tImportresources[i].exponent = resources[i].exponent;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, Importresources,\"Import\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "protected void appendWhereClause(FieldDescriptor[] fields, StringBuffer stmt) throws PersistenceBrokerException\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n\r\n stmt.append(fmd.getColumnName());\r\n stmt.append(\" = ? \");\r\n if(i < fields.length - 1)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n }\r\n }", "private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}", "public static protocolhttpband[] get(nitro_service service, protocolhttpband_args args) throws Exception{\n\t\tprotocolhttpband obj = new protocolhttpband();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tprotocolhttpband[] response = (protocolhttpband[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}", "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 }", "@Override\n\tpublic void handlePopups() {\n\t\t/*\n\t\t * try { executeJavaScript(\"window.alert = function(msg){return true;};\" +\n\t\t * \"window.confirm = function(msg){return true;};\" +\n\t\t * \"window.prompt = function(msg){return true;};\"); } catch (CrawljaxException e) {\n\t\t * LOGGER.error(\"Handling of PopUp windows failed\", e); }\n\t\t */\n\n\t\t/* Workaround: Popups handling currently not supported in PhantomJS. */\n\t\tif (browser instanceof PhantomJSDriver) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (ExpectedConditions.alertIsPresent().apply(browser) != null) {\n\t\t\ttry {\n\t\t\t\tbrowser.switchTo().alert().accept();\n\t\t\t\tLOGGER.info(\"Alert accepted\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"Handling of PopUp windows failed\");\n\t\t\t}\n\t\t}\n\t}", "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 void setJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n checkJobTypes(jobTypes);\n this.jobTypes.clear();\n this.jobTypes.putAll(jobTypes);\n }", "public static int getLineNumber(Member member) {\n\n if (!(member instanceof Method || member instanceof Constructor)) {\n // We are not able to get this info for fields\n return 0;\n }\n\n // BCEL is an optional dependency, if we cannot load it, simply return 0\n if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) {\n return 0;\n }\n\n String classFile = member.getDeclaringClass().getName().replace('.', '/');\n ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader());\n InputStream in = null;\n\n try {\n URL classFileUrl = classFileResourceLoader.getResource(classFile + \".class\");\n\n if (classFileUrl == null) {\n // The class file is not available\n return 0;\n }\n in = classFileUrl.openStream();\n\n ClassParser cp = new ClassParser(in, classFile);\n JavaClass javaClass = cp.parse();\n\n // First get all declared methods and constructors\n // Note that in bytecode constructor is translated into a method\n org.apache.bcel.classfile.Method[] methods = javaClass.getMethods();\n org.apache.bcel.classfile.Method match = null;\n\n String signature;\n String name;\n if (member instanceof Method) {\n signature = DescriptorUtils.methodDescriptor((Method) member);\n name = member.getName();\n } else if (member instanceof Constructor) {\n signature = DescriptorUtils.makeDescriptor((Constructor<?>) member);\n name = INIT_METHOD_NAME;\n } else {\n return 0;\n }\n\n for (org.apache.bcel.classfile.Method method : methods) {\n // Matching method must have the same name, modifiers and signature\n if (method.getName().equals(name)\n && member.getModifiers() == method.getModifiers()\n && method.getSignature().equals(signature)) {\n match = method;\n }\n }\n if (match != null) {\n // If a method is found, try to obtain the optional LineNumberTable attribute\n LineNumberTable lineNumberTable = match.getLineNumberTable();\n if (lineNumberTable != null) {\n int line = lineNumberTable.getSourceLine(0);\n return line == -1 ? 0 : line;\n }\n }\n // No suitable method found\n return 0;\n\n } catch (Throwable t) {\n return 0;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (Exception e) {\n return 0;\n }\n }\n }\n }" ]
Set the background color. If you don't set the background color, the default is an opaque black: {@link Color#BLACK}, 0xff000000. @param color An Android 32-bit (ARGB) {@link Color}, such as you get from {@link Resources#getColor(int)}
[ "public void setBackgroundColor(int color) {\n setBackgroundColorR(Colors.byteToGl(Color.red(color)));\n setBackgroundColorG(Colors.byteToGl(Color.green(color)));\n setBackgroundColorB(Colors.byteToGl(Color.blue(color)));\n setBackgroundColorA(Colors.byteToGl(Color.alpha(color)));\n }" ]
[ "public ItemRequest<Story> findById(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"GET\");\n }", "public void fillRectangle(Rectangle rect, Color color) {\n\t\ttemplate.saveState();\n\t\tsetFill(color);\n\t\ttemplate.rectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight());\n\t\ttemplate.fill();\n\t\ttemplate.restoreState();\n\t}", "protected PatchEntry resolveForElement(final PatchElement element) throws PatchingException {\n assert state == State.NEW;\n final PatchElementProvider provider = element.getProvider();\n final String layerName = provider.getName();\n final LayerType layerType = provider.getLayerType();\n\n final Map<String, PatchEntry> map;\n if (layerType == LayerType.Layer) {\n map = layers;\n } else {\n map = addOns;\n }\n PatchEntry entry = map.get(layerName);\n if (entry == null) {\n final InstallationManager.MutablePatchingTarget target = modification.resolve(layerName, layerType);\n if (target == null) {\n throw PatchLogger.ROOT_LOGGER.noSuchLayer(layerName);\n }\n entry = new PatchEntry(target, element);\n map.put(layerName, entry);\n }\n // Maintain the most recent element\n entry.updateElement(element);\n return entry;\n }", "public void updateExceptions() {\n\n m_exceptionsList.setDates(m_model.getExceptions());\n if (m_model.getExceptions().size() > 0) {\n m_exceptionsPanel.setVisible(true);\n } else {\n m_exceptionsPanel.setVisible(false);\n }\n }", "public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "void releaseTransaction(@NotNull final Thread thread, final int permits) {\n try (CriticalSection ignored = criticalSection.enter()) {\n int currentThreadPermits = getThreadPermits(thread);\n if (permits > currentThreadPermits) {\n throw new ExodusException(\"Can't release more permits than it was acquired\");\n }\n acquiredPermits -= permits;\n currentThreadPermits -= permits;\n if (currentThreadPermits == 0) {\n threadPermits.remove(thread);\n } else {\n threadPermits.put(thread, currentThreadPermits);\n }\n notifyNextWaiters();\n }\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 static base_response update(nitro_service client, cacheselector resource) throws Exception {\n\t\tcacheselector updateresource = new cacheselector();\n\t\tupdateresource.selectorname = resource.selectorname;\n\t\tupdateresource.rule = resource.rule;\n\t\treturn updateresource.update_resource(client);\n\t}", "public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) {\n if(timeout < 0)\n throw new IllegalArgumentException(\"The timeout must be a non-negative number.\");\n this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit);\n return this;\n }" ]
Creates a scheduled thread pool where each thread has the daemon property set to true. This allows the program to quit without explicitly calling shutdown on the pool @param corePoolSize the number of threads to keep in the pool, even if they are idle @return a newly created scheduled thread pool
[ "public static ScheduledExecutorService newScheduledDaemonThreadPool(int corePoolSize) {\n return Executors.newScheduledThreadPool(corePoolSize, r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }" ]
[ "public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) {\n final String type = jedis.type(key);\n return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type));\n }", "public static int findSpace(String haystack, int begin) {\r\n int space = haystack.indexOf(' ', begin);\r\n int nbsp = haystack.indexOf('\\u00A0', begin);\r\n if (space == -1 && nbsp == -1) {\r\n return -1;\r\n } else if (space >= 0 && nbsp >= 0) {\r\n return Math.min(space, nbsp);\r\n } else {\r\n // eg one is -1, and the other is >= 0\r\n return Math.max(space, nbsp);\r\n }\r\n }", "public void trace(String msg) {\n\t\tlogIfEnabled(Level.TRACE, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}", "public Where<T, ID> gt(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.GREATER_THAN_OPERATION));\n\t\treturn this;\n\t}", "private I_CmsSearchIndex getIndex() {\n\n I_CmsSearchIndex index = null;\n // get the configured index or the selected index\n if (isInitialCall()) {\n // the search form is in the initial state\n // get the configured index\n index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName());\n } else {\n // the search form is not in the inital state, the submit button was used already or the\n // search index was changed already\n // get the selected index in the search dialog\n index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter(\"indexName.0\"));\n }\n return index;\n }", "public List<Formation> listFormation(String appName) {\n return connection.execute(new FormationList(appName), apiKey);\n }", "boolean applyDomainModel(ModelNode result) {\n if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {\n return false;\n }\n final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();\n return callback.applyDomainModel(bootOperations);\n }", "private TreeMap<Integer, Integer> createResourceMap(FieldMap fieldMap, FixedMeta rscFixedMeta, FixedData rscFixedData)\n {\n TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer>();\n int itemCount = rscFixedMeta.getAdjustedItemCount();\n\n for (int loop = 0; loop < itemCount; loop++)\n {\n byte[] data = rscFixedData.getByteArrayValue(loop);\n if (data == null || data.length < fieldMap.getMaxFixedDataSize(0))\n {\n continue;\n }\n\n Integer uniqueID = Integer.valueOf(MPPUtility.getShort(data, 0));\n resourceMap.put(uniqueID, Integer.valueOf(loop));\n }\n\n return (resourceMap);\n }", "public String processIndexDescriptor(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n IndexDescriptorDef indexDef = _curClassDef.getIndexDescriptor(name);\r\n String attrName;\r\n \r\n if (indexDef == null)\r\n { \r\n indexDef = new IndexDescriptorDef(name);\r\n _curClassDef.addIndexDescriptor(indexDef);\r\n }\r\n\r\n if ((indexDef.getName() == null) || (indexDef.getName().length() == 0))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_NAME_MISSING,\r\n new String[]{_curClassDef.getName()}));\r\n }\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n indexDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }" ]
Assign FK values and store entries in indirection table for all objects referenced by given object. @param obj real object with 1:n reference @param cod {@link CollectionDescriptor} of referenced 1:n objects @param insert flag signal insert operation, false signals update operation
[ "public void linkMtoN(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkMtoN(true, obj, cod, referencedObjects, insert);\n }" ]
[ "public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }", "public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> iterators) {\n Preconditions.checkArgumentNotNull(iterators, \"iterators\");\n return new CombinedIterator<T>(iterators);\n }", "@SuppressWarnings(\"WeakerAccess\")\n public boolean isPlaying() {\n if (packetBytes.length >= 212) {\n return (packetBytes[STATUS_FLAGS] & PLAYING_FLAG) > 0;\n } else {\n final PlayState1 state = getPlayState1();\n return state == PlayState1.PLAYING || state == PlayState1.LOOPING ||\n (state == PlayState1.SEARCHING && getPlayState2() == PlayState2.MOVING);\n }\n }", "@Api\n\tpublic void restoreSecurityContext(SavedAuthorization savedAuthorization) {\n\t\tList<Authentication> auths = new ArrayList<Authentication>();\n\t\tif (null != savedAuthorization) {\n\t\t\tfor (SavedAuthentication sa : savedAuthorization.getAuthentications()) {\n\t\t\t\tAuthentication auth = new Authentication();\n\t\t\t\tauth.setSecurityServiceId(sa.getSecurityServiceId());\n\t\t\t\tauth.setAuthorizations(sa.getAuthorizations());\n\t\t\t\tauths.add(auth);\n\t\t\t}\n\t\t}\n\t\tsetAuthentications(null, auths);\n\t\tuserInfoInit();\n\t}", "private void writeProperties() throws IOException\n {\n writeAttributeTypes(\"property_types\", ProjectField.values());\n writeFields(\"property_values\", m_projectFile.getProjectProperties(), ProjectField.values());\n }", "private Object toReference(int type, Object referent, int hash)\r\n {\r\n switch (type)\r\n {\r\n case HARD:\r\n return referent;\r\n case SOFT:\r\n return new SoftRef(hash, referent, queue);\r\n case WEAK:\r\n return new WeakRef(hash, referent, queue);\r\n default:\r\n throw new Error();\r\n }\r\n }", "public static appfwhtmlerrorpage get(nitro_service service, String name) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tobj.set_name(name);\n\t\tappfwhtmlerrorpage response = (appfwhtmlerrorpage) obj.get_resource(service);\n\t\treturn response;\n\t}", "final protected void putChar(char c) {\n final int clen = _internalBuffer.length;\n if (clen == _bufferPosition) {\n final char[] next = new char[2 * clen + 1];\n\n System.arraycopy(_internalBuffer, 0, next, 0, _bufferPosition);\n _internalBuffer = next;\n }\n\n _internalBuffer[_bufferPosition++] = c;\n }", "public EventBus emitSync(String event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }" ]
Converts the positions to a 2D double array @return 2d double array [i][j], i=Time index, j=coordinate index
[ "public double[][] getPositionsAsArray(){\n\t\tdouble[][] posAsArr = new double[size()][3];\n\t\tfor(int i = 0; i < size(); i++){\n\t\t\tif(get(i)!=null){\n\t\t\t\tposAsArr[i][0] = get(i).x;\n\t\t\t\tposAsArr[i][1] = get(i).y;\n\t\t\t\tposAsArr[i][2] = get(i).z;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tposAsArr[i] = null;\n\t\t\t}\n\t\t}\n\t\treturn posAsArr;\n\t}" ]
[ "public static Session getSession(final ServerSetup setup, Properties mailProps) {\r\n Properties props = setup.configureJavaMailSessionProperties(mailProps, false);\r\n\r\n log.debug(\"Mail session properties are {}\", props);\r\n\r\n return Session.getInstance(props, null);\r\n }", "public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final BsonValue documentId\n ) {\n final ChangeEvent<BsonDocument> event;\n nsLock.readLock().lock();\n try {\n event = this.events.get(documentId);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.remove(documentId);\n return event;\n } finally {\n nsLock.writeLock().unlock();\n }\n }", "public static void acceptsUrl(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"bootstrap url\")\n .withRequiredArg()\n .describedAs(\"url\")\n .ofType(String.class);\n }", "public String p(double value ) {\n return UtilEjml.fancyString(value,format,false,length,significant);\n }", "protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,\r\n int[][] labels, int offset) {\r\n for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {\r\n int dataIndex = i + offset;\r\n List<CRFDatum<Collection<String>, String>> document = processedData.get(i);\r\n int dsize = document.size();\r\n labels[dataIndex] = new int[dsize];\r\n data[dataIndex] = new int[dsize][][];\r\n for (int j = 0; j < dsize; j++) {\r\n CRFDatum<Collection<String>, String> crfDatum = document.get(j);\r\n // add label, they are offset by extra context\r\n labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());\r\n // add features\r\n List<Collection<String>> cliques = crfDatum.asFeatures();\r\n int csize = cliques.size();\r\n data[dataIndex][j] = new int[csize][];\r\n for (int k = 0; k < csize; k++) {\r\n Collection<String> features = cliques.get(k);\r\n\r\n // Debug only: Remove\r\n // if (j < windowSize) {\r\n // System.err.println(\"addProcessedData: Features Size: \" +\r\n // features.size());\r\n // }\r\n\r\n data[dataIndex][j][k] = new int[features.size()];\r\n\r\n int m = 0;\r\n try {\r\n for (String feature : features) {\r\n // System.err.println(\"feature \" + feature);\r\n // if (featureIndex.indexOf(feature)) ;\r\n if (featureIndex == null) {\r\n System.out.println(\"Feature is NULL!\");\r\n }\r\n data[dataIndex][j][k][m] = featureIndex.indexOf(feature);\r\n m++;\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n System.err.printf(\"[index=%d, j=%d, k=%d, m=%d]\\n\", dataIndex, j, k, m);\r\n System.err.println(\"data.length \" + data.length);\r\n System.err.println(\"data[dataIndex].length \" + data[dataIndex].length);\r\n System.err.println(\"data[dataIndex][j].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k][m] \" + data[dataIndex][j][k][m]);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }", "private ProjectCalendar getResourceCalendar(Integer calendarID)\n {\n ProjectCalendar result = null;\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_calMap.get(calendarID);\n if (calendar != null)\n {\n //\n // If the resource is linked to a base calendar, derive\n // a default calendar from the base calendar.\n //\n if (!calendar.isDerived())\n {\n ProjectCalendar resourceCalendar = m_project.addCalendar();\n resourceCalendar.setParent(calendar);\n resourceCalendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n result = resourceCalendar;\n }\n else\n {\n //\n // Primavera seems to allow a calendar to be shared between resources\n // whereas in the MS Project model there is a one-to-one\n // relationship. If we find a shared calendar, take a copy of it\n //\n if (calendar.getResource() == null)\n {\n result = calendar;\n }\n else\n {\n ProjectCalendar copy = m_project.addCalendar();\n copy.copy(calendar);\n result = copy;\n }\n }\n }\n }\n\n return result;\n }", "public final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\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 }" ]
This method extracts resource data from a GanttProject file. @param ganttProject parent node for resources
[ "private void readResources(Project ganttProject)\n {\n Resources resources = ganttProject.getResources();\n readResourceCustomPropertyDefinitions(resources);\n readRoleDefinitions(ganttProject);\n\n for (net.sf.mpxj.ganttproject.schema.Resource gpResource : resources.getResource())\n {\n readResource(gpResource);\n }\n }" ]
[ "private Object readMetadataFromXML(InputSource source, Class target)\r\n throws MalformedURLException, ParserConfigurationException, SAXException, IOException\r\n {\r\n // TODO: make this configurable\r\n boolean validate = false;\r\n \r\n // get a xml reader instance:\r\n SAXParserFactory factory = SAXParserFactory.newInstance();\r\n log.info(\"RepositoryPersistor using SAXParserFactory : \" + factory.getClass().getName());\r\n if (validate)\r\n {\r\n factory.setValidating(true);\r\n }\r\n SAXParser p = factory.newSAXParser();\r\n XMLReader reader = p.getXMLReader();\r\n if (validate)\r\n {\r\n reader.setErrorHandler(new OJBErrorHandler());\r\n }\r\n\r\n Object result;\r\n if (DescriptorRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n DescriptorRepository repository = new DescriptorRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new RepositoryXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n result = repository;\r\n }\r\n else if (ConnectionRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n ConnectionRepository repository = new ConnectionRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n //LoggerFactory.getBootLogger().info(\"loading XML took \" + (stop - start) + \" msecs\");\r\n result = repository;\r\n }\r\n else\r\n throw new MetadataException(\"Could not build a repository instance for '\" + target +\r\n \"', using source \" + source);\r\n return result;\r\n }", "public static Optional<Variable> freshBuilder(SourceBuilder code, Datatype datatype) {\n if (!datatype.getBuilderFactory().isPresent()) {\n return Optional.empty();\n }\n return Optional.of(code.scope().computeIfAbsent(Declaration.FRESH_BUILDER, () -> {\n Variable defaults = new Variable(\"defaults\");\n code.addLine(\"%s %s = %s;\",\n datatype.getGeneratedBuilder(),\n defaults,\n datatype.getBuilderFactory().get()\n .newBuilder(datatype.getBuilder(), TypeInference.INFERRED_TYPES));\n return defaults;\n }));\n }", "public static String get(Properties props, String name, String defval) {\n String value = props.getProperty(name);\n if (value == null)\n value = defval;\n return value;\n }", "public void enqueue(SerialMessage serialMessage) {\n\t\tthis.sendQueue.add(serialMessage);\n\t\tlogger.debug(\"Enqueueing message. Queue length = {}\", this.sendQueue.size());\n\t}", "public final OutputFormat getOutputFormat(final PJsonObject specJson) {\n final String format = specJson.getString(MapPrinterServlet.JSON_OUTPUT_FORMAT);\n final boolean mapExport =\n this.configuration.getTemplate(specJson.getString(Constants.JSON_LAYOUT_KEY)).isMapExport();\n final String beanName =\n format + (mapExport ? MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING : OUTPUT_FORMAT_BEAN_NAME_ENDING);\n\n if (!this.outputFormat.containsKey(beanName)) {\n throw new RuntimeException(\"Format '\" + format + \"' with mapExport '\" + mapExport\n + \"' is not supported.\");\n }\n\n return this.outputFormat.get(beanName);\n }", "public void mergeSubsystem(final GlobalTransformerRegistry registry, String subsystemName, ModelVersion version) {\n final PathElement element = PathElement.pathElement(SUBSYSTEM, subsystemName);\n registry.mergeSubtree(this, PathAddress.EMPTY_ADDRESS.append(element), version);\n }", "@Override\r\n public void processOutput(Map<String, String> resultsMap) {\r\n queue.add(resultsMap);\n\r\n if (queue.size() > 10000) {\r\n log.info(\"Queue size \" + queue.size() + \", waiting\");\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ex) {\r\n log.info(\"Interrupted \", ex);\r\n }\r\n }\r\n }", "protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }", "public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) {\n\n\t\t/*\n\t\t * The internal data structure is not optimal here (a map would make more sense here),\n\t\t * if the user does not require access to the products, we would allow non-unique symbols.\n\t\t * Hence we store both in two side by side vectors.\n\t\t */\n\t\tfor(int i=0; i<calibrationProductsSymbols.size(); i++) {\n\t\t\tString calibrationProductSymbol = calibrationProductsSymbols.get(i);\n\t\t\tif(calibrationProductSymbol.equals(symbol)) {\n\t\t\t\treturn calibrationProducts.get(i);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}" ]
Retrieve column font details from a block of property data. @param data property data @param offset offset into property data @param fontBases map of font bases @return ColumnFontStyle instance
[ "protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }" ]
[ "private synchronized void freeClient(Client client) {\n int current = useCounts.get(client);\n if (current > 0) {\n timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now.\n useCounts.put(client, current - 1);\n if ((current == 1) && (idleLimit.get() == 0)) {\n closeClient(client); // This was the last use, and we are supposed to immediately close idle clients.\n }\n } else {\n logger.error(\"Ignoring attempt to free a client that is not allocated: {}\", client);\n }\n }", "public boolean isIPv4Compatible() {\n\t\treturn getSegment(0).isZero() && getSegment(1).isZero() && getSegment(2).isZero() &&\n\t\t\t\tgetSegment(3).isZero() && getSegment(4).isZero() && getSegment(5).isZero();\n\t}", "public void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) {\n\t\tthis.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); \n\t}", "@Deprecated\n public void parseAndSetParameter(String value, ModelNode operation, XMLStreamReader reader) throws XMLStreamException {\n //we use manual parsing here, and not #getParser().. to preserve backward compatibility.\n if (value != null) {\n for (String element : value.split(\",\")) {\n parseAndAddParameterElement(element.trim(), operation, reader);\n }\n }\n }", "public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }", "public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {\n assertNumericArgument(corePoolSize, true);\n assertNumericArgument(maximumPoolSize, true);\n assertNumericArgument(corePoolSize + maximumPoolSize, false);\n assertNumericArgument(keepAliveTime, true);\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.keepAliveTime = unit.toMillis(keepAliveTime);\n return this;\n }", "final void dispatchToAppender(final LoggingEvent customLoggingEvent) {\n // wrap the LoggingEvent in a FileRollEvent to prevent recursion bug\n final FoundationFileRollingAppender appender = this.getSource();\n if (appender != null) {\n appender.append(new FileRollEvent(customLoggingEvent, this));\n }\n }", "@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }", "public void build(Point3d[] points, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (points.length < nump) {\n throw new IllegalArgumentException(\"Point array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(points, nump);\n buildHull();\n }" ]
Converts from an Accumulo Key to a Fluo RowColumn @param key Key @return RowColumn
[ "public static RowColumn toRowColumn(Key key) {\n if (key == null) {\n return RowColumn.EMPTY;\n }\n if ((key.getRow() == null) || key.getRow().getLength() == 0) {\n return RowColumn.EMPTY;\n }\n Bytes row = ByteUtil.toBytes(key.getRow());\n if ((key.getColumnFamily() == null) || key.getColumnFamily().getLength() == 0) {\n return new RowColumn(row);\n }\n Bytes cf = ByteUtil.toBytes(key.getColumnFamily());\n if ((key.getColumnQualifier() == null) || key.getColumnQualifier().getLength() == 0) {\n return new RowColumn(row, new Column(cf));\n }\n Bytes cq = ByteUtil.toBytes(key.getColumnQualifier());\n if ((key.getColumnVisibility() == null) || key.getColumnVisibility().getLength() == 0) {\n return new RowColumn(row, new Column(cf, cq));\n }\n Bytes cv = ByteUtil.toBytes(key.getColumnVisibility());\n return new RowColumn(row, new Column(cf, cq, cv));\n }" ]
[ "public static synchronized void registerDao(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\taddDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);\n\t}", "private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\n }\n }", "public static base_responses restore(nitro_service client, appfwprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwprofile restoreresources[] = new appfwprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trestoreresources[i] = new appfwprofile();\n\t\t\t\trestoreresources[i].archivename = resources[i].archivename;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, restoreresources,\"restore\");\n\t\t}\n\t\treturn result;\n\t}", "private void reportException(Exception e) {\n\t\tlogger.error(\"Failed to write JSON export: \" + e.toString());\n\t\tthrow new RuntimeException(e.toString(), e);\n\t}", "private FullTypeSignature getTypeSignature(Class<?> clazz) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tif (clazz.isArray()) {\r\n\t\t\tsb.append(clazz.getName());\r\n\t\t} else if (clazz.isPrimitive()) {\r\n\t\t\tsb.append(primitiveTypesMap.get(clazz).toString());\r\n\t\t} else {\r\n\t\t\tsb.append('L').append(clazz.getName()).append(';');\r\n\t\t}\r\n\t\treturn TypeSignatureFactory.getTypeSignature(sb.toString(), false);\r\n\r\n\t}", "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }", "public void updateBitmapShader() {\n\t\tif (image == null)\n\t\t\treturn;\n\n\t\tshader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\n\t\tif(canvasSize != image.getWidth() || canvasSize != image.getHeight()) {\n\t\t\tMatrix matrix = new Matrix();\n\t\t\tfloat scale = (float) canvasSize / (float) image.getWidth();\n\t\t\tmatrix.setScale(scale, scale);\n\t\t\tshader.setLocalMatrix(matrix);\n\t\t}\n\t}", "public static aaaparameter get(nitro_service service) throws Exception{\n\t\taaaparameter obj = new aaaparameter();\n\t\taaaparameter[] response = (aaaparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }" ]
page breaks should be near the bottom of the band, this method used while adding subreports which has the "start on new page" option. @param band
[ "protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}" ]
[ "public ArrayList getFields(String fieldNames) throws NoSuchFieldException\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new NoSuchFieldException(name);\r\n }\r\n result.add(fieldDef);\r\n }\r\n return result;\r\n }", "public List<Ticket> checkTickets(Set<String> tickets) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CHECK_TICKETS);\r\n\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = tickets.iterator();\r\n while (it.hasNext()) {\r\n if (sb.length() > 0) {\r\n sb.append(\",\");\r\n }\r\n Object obj = it.next();\r\n if (obj instanceof Ticket) {\r\n sb.append(((Ticket) obj).getTicketId());\r\n } else {\r\n sb.append(obj);\r\n }\r\n }\r\n parameters.put(\"tickets\", sb.toString());\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n // <uploader>\r\n // <ticket id=\"128\" complete=\"1\" photoid=\"2995\" />\r\n // <ticket id=\"129\" complete=\"0\" />\r\n // <ticket id=\"130\" complete=\"2\" />\r\n // <ticket id=\"131\" invalid=\"1\" />\r\n // </uploader>\r\n\r\n List<Ticket> list = new ArrayList<Ticket>();\r\n Element uploaderElement = response.getPayload();\r\n NodeList ticketNodes = uploaderElement.getElementsByTagName(\"ticket\");\r\n int n = ticketNodes.getLength();\r\n for (int i = 0; i < n; i++) {\r\n Element ticketElement = (Element) ticketNodes.item(i);\r\n String id = ticketElement.getAttribute(\"id\");\r\n String complete = ticketElement.getAttribute(\"complete\");\r\n boolean invalid = \"1\".equals(ticketElement.getAttribute(\"invalid\"));\r\n String photoId = ticketElement.getAttribute(\"photoid\");\r\n Ticket info = new Ticket();\r\n info.setTicketId(id);\r\n info.setInvalid(invalid);\r\n info.setStatus(Integer.parseInt(complete));\r\n info.setPhotoId(photoId);\r\n list.add(info);\r\n }\r\n return list;\r\n }", "public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }", "public long getTimeRemainingInMillis()\n {\n long batchTime = System.currentTimeMillis() - startTime;\n double timePerIteration = (double) batchTime / (double) worked.get();\n return (long) (timePerIteration * (total - worked.get()));\n }", "private void updateArt(TrackMetadataUpdate update, AlbumArt art) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), art); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), art);\n }\n }\n }\n deliverAlbumArtUpdate(update.player, art);\n }", "@Override\r\n public void processOutput(Map<String, String> resultsMap) {\r\n queue.add(resultsMap);\n\r\n if (queue.size() > 10000) {\r\n log.info(\"Queue size \" + queue.size() + \", waiting\");\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ex) {\r\n log.info(\"Interrupted \", ex);\r\n }\r\n }\r\n }", "public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\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 }", "protected final boolean isPatternValid() {\n\n switch (getPatternType()) {\n case DAILY:\n return isEveryWorkingDay() || isIntervalValid();\n case WEEKLY:\n return isIntervalValid() && isWeekDaySet();\n case MONTHLY:\n return isIntervalValid() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case YEARLY:\n return isMonthSet() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case INDIVIDUAL:\n case NONE:\n return true;\n default:\n return false;\n }\n }" ]
Extract data for a single resource assignment. @param task parent task @param row Synchro resource assignment
[ "private void processResourceAssignment(Task task, MapRow row)\n {\n Resource resource = m_resourceMap.get(row.getUUID(\"RESOURCE_UUID\"));\n task.addResourceAssignment(resource);\n }" ]
[ "public static base_response link(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey linkresource = new sslcertkey();\n\t\tlinkresource.certkey = resource.certkey;\n\t\tlinkresource.linkcertkeyname = resource.linkcertkeyname;\n\t\treturn linkresource.perform_operation(client,\"link\");\n\t}", "public void foreach(PixelFunction fn) {\n Arrays.stream(points()).forEach(p -> fn.apply(p.x, p.y, pixel(p)));\n }", "public T[] toArray(T[] tArray) {\n List<T> array = new ArrayList<T>(100);\n for (Iterator<T> it = iterator(); it.hasNext();) {\n T val = it.next();\n if (val != null) array.add(val);\n }\n return array.toArray(tArray);\n }", "public ConfigBuilder withMasterName(final String masterName) {\n if (masterName == null || \"\".equals(masterName)) {\n throw new IllegalArgumentException(\"masterName is null or empty: \" + masterName);\n }\n this.masterName = masterName;\n return this;\n }", "@Override\n public void process(TestCaseResult context) {\n context.getParameters().add(new Parameter()\n .withName(getName())\n .withValue(getValue())\n .withKind(ParameterKind.valueOf(getKind()))\n );\n }", "public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {\n Class<?> javaClass = annotatedType.getJavaClass();\n return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)\n && Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)\n && hasSimpleCdiConstructor(annotatedType);\n }", "public void addExportedPackages(String... exportedPackages) {\n\t\tString oldBundles = mainAttributes.get(EXPORT_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 : exportedPackages)\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(EXPORT_PACKAGE, result);\n\t}", "public static <T> NewSessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager) {\n EnhancedAnnotatedType<T> type = beanManager.getServices().get(ClassTransformer.class).getEnhancedAnnotatedType(ejbDescriptor.getBeanClass(), beanManager.getId());\n return new NewSessionBean<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifierForNew(ejbDescriptor)), beanManager);\n }", "public static void ensureXPathNotNull(Node node, String expression) {\n if (node == null) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }" ]
Converts an image in BINARY mode to RGB mode @param img image @return new MarvinImage instance in RGB mode
[ "public static MarvinImage binaryToRgb(MarvinImage img) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_RGB);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n if (img.getBinaryColor(x, y)) {\n resultImage.setIntColor(x, y, 0, 0, 0);\n } else {\n resultImage.setIntColor(x, y, 255, 255, 255);\n }\n }\n }\n return resultImage;\n }" ]
[ "public boolean getBoxBound(float[] corners)\n {\n int rc;\n if ((corners == null) || (corners.length != 6) ||\n ((rc = NativeVertexBuffer.getBoundingVolume(getNative(), corners)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy box bound into array provided\");\n }\n return rc != 0;\n }", "public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {\n \n int width = originalImage.getWidth();\n \n int height = originalImage.getHeight();\n \n int widthPercent = (widthOut * 100) / width;\n \n int newHeight = (height * widthPercent) / 100;\n \n BufferedImage resizedImage =\n new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);\n g.dispose();\n \n return resizedImage;\n }", "private String getSubQuerySQL(Query subQuery)\r\n {\r\n ClassDescriptor cld = getRoot().cld.getRepository().getDescriptorFor(subQuery.getSearchClass());\r\n String sql;\r\n\r\n if (subQuery instanceof QueryBySQL)\r\n {\r\n sql = ((QueryBySQL) subQuery).getSql();\r\n }\r\n else\r\n {\r\n sql = new SqlSelectStatement(this, m_platform, cld, subQuery, m_logger).getStatement();\r\n }\r\n\r\n return sql;\r\n }", "public static <E> Set<E> diff(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n for (E o : s1) {\r\n if (!s2.contains(o)) {\r\n s.add(o);\r\n }\r\n }\r\n return s;\r\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 appfwprofile_excluderescontenttype_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_excluderescontenttype_binding obj = new appfwprofile_excluderescontenttype_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_excluderescontenttype_binding response[] = (appfwprofile_excluderescontenttype_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public AT_Row setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "protected boolean appendWhereStatement(StringBuilder sb, List<ArgumentHolder> argList, WhereOperation operation)\n\t\t\tthrows SQLException {\n\t\tif (where == null) {\n\t\t\treturn operation == WhereOperation.FIRST;\n\t\t}\n\t\toperation.appendBefore(sb);\n\t\twhere.appendSql((addTableName ? getTableName() : null), sb, argList);\n\t\toperation.appendAfter(sb);\n\t\treturn false;\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n protected void clearRmiTargetsMap(ClassLoaderLeakPreventor preventor, Map<?, ?> rmiTargetsMap) {\n try {\n final Field cclField = preventor.findFieldOfClass(\"sun.rmi.transport.Target\", \"ccl\");\n preventor.debug(\"Looping \" + rmiTargetsMap.size() + \" RMI Targets to find leaks\");\n for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {\n Object target = iter.next(); // sun.rmi.transport.Target\n ClassLoader ccl = (ClassLoader) cclField.get(target);\n if(preventor.isClassLoaderOrChild(ccl)) {\n preventor.warn(\"Removing RMI Target: \" + target);\n iter.remove();\n }\n }\n }\n catch (Exception ex) {\n preventor.error(ex);\n }\n }" ]
Trade the request token for an access token, this is step three of authorization. @param oAuthRequestToken this is the token returned by the {@link AuthInterface#getRequestToken} call. @param verifier
[ "@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }" ]
[ "@SuppressFBWarnings(value = \"DMI_COLLECTION_OF_URLS\", justification = \"Only local URLs involved\")\n private Map<ConfigurationKey, Object> readFileProperties(Set<URL> files) {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n for (URL file : files) {\n ConfigurationLogger.LOG.readingPropertiesFile(file);\n Properties fileProperties = loadProperties(file);\n for (String name : fileProperties.stringPropertyNames()) {\n processKeyValue(found, name, fileProperties.getProperty(name));\n }\n }\n return found;\n }", "public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }", "public CustomHeadersInterceptor addHeader(String name, String value) {\n if (!this.headers.containsKey(name)) {\n this.headers.put(name, new ArrayList<String>());\n }\n this.headers.get(name).add(value);\n return this;\n }", "public static boolean matches(Map<String, Object> nodeProperties, String[] keyColumnNames, Object[] keyColumnValues) {\n\t\tfor ( int i = 0; i < keyColumnNames.length; i++ ) {\n\t\t\tString property = keyColumnNames[i];\n\t\t\tObject expectedValue = keyColumnValues[i];\n\t\t\tboolean containsProperty = nodeProperties.containsKey( property );\n\t\t\tif ( containsProperty ) {\n\t\t\t\tObject actualValue = nodeProperties.get( property );\n\t\t\t\tif ( !sameValue( expectedValue, actualValue ) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( expectedValue != null ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public synchronized void doneTask(int stealerId, int donorId) {\n removeNodesFromWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting--;\n doneSignal.countDown();\n // Try and schedule more tasks now that resources may be available to do\n // so.\n scheduleMoreTasks();\n }", "public MessageSet read(long offset, int length) throws IOException {\n List<LogSegment> views = segments.getView();\n LogSegment found = findRange(views, offset, views.size());\n if (found == null) {\n if (logger.isTraceEnabled()) {\n logger.trace(format(\"NOT FOUND MessageSet from Log[%s], offset=%d, length=%d\", name, offset, length));\n }\n return MessageSet.Empty;\n }\n return found.getMessageSet().read(offset - found.start(), length);\n }", "public static nd6ravariables[] get(nitro_service service, Long vlan[]) throws Exception{\n\t\tif (vlan !=null && vlan.length>0) {\n\t\t\tnd6ravariables response[] = new nd6ravariables[vlan.length];\n\t\t\tnd6ravariables obj[] = new nd6ravariables[vlan.length];\n\t\t\tfor (int i=0;i<vlan.length;i++) {\n\t\t\t\tobj[i] = new nd6ravariables();\n\t\t\t\tobj[i].set_vlan(vlan[i]);\n\t\t\t\tresponse[i] = (nd6ravariables) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public static boolean isValidFqcn(String str) {\n if (isNullOrEmpty(str)) {\n return false;\n }\n final String[] parts = str.split(\"\\\\.\");\n if (parts.length < 2) {\n return false;\n }\n for (String part : parts) {\n if (!isValidJavaIdentifier(part)) {\n return false;\n }\n }\n return true;\n }", "private void initDurationPanel() {\n\n m_durationPrefixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_PREFIX_0));\n m_durationAfterPostfixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_POSTFIX_0));\n m_seriesEndDate.setDateOnly(true);\n m_seriesEndDate.setAllowInvalidValue(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n m_seriesEndDate.getTextField().addFocusHandler(new FocusHandler() {\n\n public void onFocus(FocusEvent event) {\n\n if (handleChange()) {\n onSeriesEndDateFocus(event);\n }\n\n }\n });\n }" ]
Decide whether failure should trigger a rollback. @param cause the cause of the failure, or {@code null} if failure is not the result of catching a throwable @return the result action
[ "private ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }" ]
[ "public void setRequestType(int pathId, Integer requestType) {\n if (requestType == null) {\n requestType = Constants.REQUEST_TYPE_GET;\n }\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_REQUEST_TYPE + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, requestType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }", "public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {\n\n context.init();\n\n HiveConf hiveConf = context.getHiveConf();\n\n // merge test case properties with hive conf before HiveServer is started.\n for (Map.Entry<String, String> property : testConfig.entrySet()) {\n hiveConf.set(property.getKey(), property.getValue());\n }\n\n try {\n hiveServer2 = new HiveServer2();\n hiveServer2.init(hiveConf);\n\n // Locate the ClIService in the HiveServer2\n for (Service service : hiveServer2.getServices()) {\n if (service instanceof CLIService) {\n client = (CLIService) service;\n }\n }\n\n Preconditions.checkNotNull(client, \"ClIService was not initialized by HiveServer2\");\n\n sessionHandle = client.openSession(\"noUser\", \"noPassword\", null);\n\n SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();\n currentSessionState = sessionState;\n currentSessionState.setHiveVariables(hiveVars);\n } catch (Exception e) {\n throw new IllegalStateException(\"Failed to create HiveServer :\" + e.getMessage(), e);\n }\n\n // Ping hive server before we do anything more with it! If validation\n // is switched on, this will fail if metastorage is not set up properly\n pingHiveServer();\n }", "private void getMultipleValues(Method method, Object object, Map<String, String> map)\n {\n try\n {\n int index = 1;\n while (true)\n {\n Object value = filterValue(method.invoke(object, Integer.valueOf(index)));\n if (value != null)\n {\n map.put(getPropertyName(method, index), String.valueOf(value));\n }\n ++index;\n }\n }\n catch (Exception ex)\n {\n // Reached the end of the valid indexes\n }\n }", "public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }", "private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) {\n\t\treturn pattern.matcher(chars).matches();\n\t}", "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }", "public <V> V getObject(final String key, final Class<V> type) {\n final Object obj = this.values.get(key);\n return type.cast(obj);\n }", "public Number getOvertimeCost()\n {\n Number cost = (Number) getCachedValue(AssignmentField.OVERTIME_COST);\n if (cost == null)\n {\n Number actual = getActualOvertimeCost();\n Number remaining = getRemainingOvertimeCost();\n if (actual != null && remaining != null)\n {\n cost = NumberHelper.getDouble(actual.doubleValue() + remaining.doubleValue());\n set(AssignmentField.OVERTIME_COST, cost);\n }\n }\n return (cost);\n }" ]
Reads the CSS and JavaScript files from the JAR file and writes them to the output directory. @param outputDirectory Where to put the resources. @throws IOException If the resources can't be read or written.
[ "private void copyResources(File outputDirectory) throws IOException\n {\n copyClasspathResource(outputDirectory, \"reportng.css\", \"reportng.css\");\n copyClasspathResource(outputDirectory, \"reportng.js\", \"reportng.js\");\n // If there is a custom stylesheet, copy that.\n File customStylesheet = META.getStylesheetPath();\n\n if (customStylesheet != null)\n {\n if (customStylesheet.exists())\n {\n copyFile(outputDirectory, customStylesheet, CUSTOM_STYLE_FILE);\n }\n else\n {\n // If not found, try to read the file as a resource on the classpath\n // useful when reportng is called by a jarred up library\n InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(customStylesheet.getPath());\n if (stream != null)\n {\n copyStream(outputDirectory, stream, CUSTOM_STYLE_FILE);\n }\n }\n }\n }" ]
[ "public int getPrivacy() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PRIVACY);\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 personElement = response.getPayload();\r\n return Integer.parseInt(personElement.getAttribute(\"privacy\"));\r\n }", "private static void attachToContent(Activity activity, MenuDrawer menuDrawer) {\n /**\n * Do not call mActivity#setContentView.\n * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to\n * MenuDrawer#setContentView, which then again would call Activity#setContentView.\n */\n ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);\n content.removeAllViews();\n content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }", "public Collection values()\r\n {\r\n if (values != null) return values;\r\n values = new AbstractCollection()\r\n {\r\n public int size()\r\n {\r\n return size;\r\n }\r\n\r\n public void clear()\r\n {\r\n ReferenceMap.this.clear();\r\n }\r\n\r\n public Iterator iterator()\r\n {\r\n return new ValueIterator();\r\n }\r\n };\r\n return values;\r\n }", "public static base_response delete(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec deleteresource = new dnsaaaarec();\n\t\tdeleteresource.hostname = resource.hostname;\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private Set<QualifierInstance> getRequiredQualifiers(EnhancedAnnotatedParameter<?, ? super X> enhancedDisposedParameter) {\n Set<Annotation> disposedParameterQualifiers = enhancedDisposedParameter.getMetaAnnotations(Qualifier.class);\n if (disposedParameterQualifiers.isEmpty()) {\n disposedParameterQualifiers = Collections.<Annotation> singleton(Default.Literal.INSTANCE);\n }\n return beanManager.getServices().get(MetaAnnotationStore.class).getQualifierInstances(disposedParameterQualifiers);\n }", "public static int cudnnActivationForward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnActivationForwardNative(handle, activationDesc, alpha, xDesc, x, beta, yDesc, y));\n }", "private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) {\n try {\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying domain level boot operations provided by master\");\n SyncModelParameters parameters =\n new SyncModelParameters(domainController, ignoredDomainResourceRegistry,\n hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository);\n final SyncDomainModelOperationHandler handler =\n new SyncDomainModelOperationHandler(hostInfo, parameters);\n final ModelNode operation = APPLY_DOMAIN_MODEL.clone();\n operation.get(DOMAIN_MODEL).set(bootOperations);\n\n final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler);\n\n final String outcome = result.get(OUTCOME).asString();\n final boolean success = SUCCESS.equals(outcome);\n\n // check if anything we synced triggered reload-required or restart-required.\n // if they did we log a warning on the synced slave.\n if (result.has(RESPONSE_HEADERS)) {\n final ModelNode headers = result.get(RESPONSE_HEADERS);\n if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired();\n }\n if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired();\n }\n }\n if (!success) {\n ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode();\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc);\n return false;\n } else {\n return true;\n }\n } catch (Exception e) {\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e);\n return false;\n }\n }", "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 }", "public static String find(CharSequence self, CharSequence regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure closure) {\n return find(self.toString(), Pattern.compile(regex.toString()), closure);\n }" ]
Register the ChangeHandler to become notified if the user changes the slider. The Handler is called when the user releases the mouse only at the end of the slide operation.
[ "@Override\n public HandlerRegistration addChangeHandler(final ChangeHandler handler) {\n return getRangeInputElement().addDomHandler(handler, ChangeEvent.getType());\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 void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public int addServerRedirectToProfile(String region, String srcUrl, String destUrl, String hostHeader,\n int profileId, int clientId) throws Exception {\n int serverId = -1;\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n serverId = addServerRedirect(region, srcUrl, destUrl, hostHeader, profileId, client.getActiveServerGroup());\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return serverId;\n }", "private List<String> getMavenModules(MavenModuleSetBuild mavenBuild) throws IOException, InterruptedException {\n FilePath pathToModuleRoot = mavenBuild.getModuleRoot();\n FilePath pathToPom = new FilePath(pathToModuleRoot, mavenBuild.getProject().getRootPOM(null));\n return pathToPom.act(new MavenModulesExtractor());\n }", "public static base_response delete(nitro_service client, String jsoncontenttypevalue) throws Exception {\n\t\tappfwjsoncontenttype deleteresource = new appfwjsoncontenttype();\n\t\tdeleteresource.jsoncontenttypevalue = jsoncontenttypevalue;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static int getXPathLocation(String dom, String xpath) {\n\t\tString dom_lower = dom.toLowerCase();\n\t\tString xpath_lower = xpath.toLowerCase();\n\t\tString[] elements = xpath_lower.split(\"/\");\n\t\tint pos = 0;\n\t\tint temp;\n\t\tint number;\n\t\tfor (String element : elements) {\n\t\t\tif (!element.isEmpty() && !element.startsWith(\"@\") && !element.contains(\"()\")) {\n\t\t\t\tif (element.contains(\"[\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnumber =\n\t\t\t\t\t\t\t\tInteger.parseInt(element.substring(element.indexOf(\"[\") + 1,\n\t\t\t\t\t\t\t\t\t\telement.indexOf(\"]\")));\n\t\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnumber = 1;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < number; i++) {\n\t\t\t\t\t// find new open element\n\t\t\t\t\ttemp = dom_lower.indexOf(\"<\" + stripEndSquareBrackets(element), pos);\n\n\t\t\t\t\tif (temp > -1) {\n\t\t\t\t\t\tpos = temp + 1;\n\n\t\t\t\t\t\t// if depth>1 then goto end of current element\n\t\t\t\t\t\tif (number > 1 && i < number - 1) {\n\t\t\t\t\t\t\tpos =\n\t\t\t\t\t\t\t\t\tgetCloseElementLocation(dom_lower, pos,\n\t\t\t\t\t\t\t\t\t\t\tstripEndSquareBrackets(element));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pos - 1;\n\t}", "public CancelIndicator newCancelIndicator(final ResourceSet rs) {\n CancelIndicator _xifexpression = null;\n if ((rs instanceof XtextResourceSet)) {\n final boolean cancelationAllowed = (this.cancelationAllowed.get()).booleanValue();\n final int current = ((XtextResourceSet)rs).getModificationStamp();\n final CancelIndicator _function = () -> {\n return (cancelationAllowed && (((XtextResourceSet)rs).isOutdated() || (current != ((XtextResourceSet)rs).getModificationStamp())));\n };\n return _function;\n } else {\n _xifexpression = CancelIndicator.NullImpl;\n }\n return _xifexpression;\n }", "Object readResolve() throws ObjectStreamException {\n Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);\n if (bean == null) {\n throw BeanLogger.LOG.proxyDeserializationFailure(beanId);\n }\n return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);\n }", "void recover() {\n final List<NamespaceSynchronizationConfig> nsConfigs = new ArrayList<>();\n for (final MongoNamespace ns : this.syncConfig.getSynchronizedNamespaces()) {\n nsConfigs.add(this.syncConfig.getNamespaceConfig(ns));\n }\n\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n }\n try {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n try {\n recoverNamespace(nsConfig);\n } finally {\n nsConfig.getLock().writeLock().unlock();\n }\n }\n } finally {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().unlock();\n }\n }\n }" ]
Lookup an object instance from JNDI context. @param jndiName JNDI lookup name @return Matching object or <em>null</em> if none found.
[ "public static Object lookup(String jndiName)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"lookup(\"+jndiName+\") was called\");\r\n try\r\n {\r\n return getContext().lookup(jndiName);\r\n }\r\n catch (NamingException e)\r\n {\r\n throw new OJBRuntimeException(\"Lookup failed for: \" + jndiName, e);\r\n }\r\n catch(OJBRuntimeException e)\r\n {\r\n throw e;\r\n }\r\n }" ]
[ "public void delete(Vertex vtx) {\n if (vtx.prev == null) {\n head = vtx.next;\n } else {\n vtx.prev.next = vtx.next;\n }\n if (vtx.next == null) {\n tail = vtx.prev;\n } else {\n vtx.next.prev = vtx.prev;\n }\n }", "public Replication targetOauth(String consumerSecret,\r\n String consumerKey, String tokenSecret, String token) {\r\n this.replication = replication.targetOauth(consumerSecret, consumerKey,\r\n tokenSecret, token);\r\n return this;\r\n }", "private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }", "private void writeDayTypes(Calendars calendars)\n {\n DayTypes dayTypes = m_factory.createDayTypes();\n calendars.setDayTypes(dayTypes);\n List<DayType> typeList = dayTypes.getDayType();\n\n DayType dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"0\");\n dayType.setName(\"Working\");\n dayType.setDescription(\"A default working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"1\");\n dayType.setName(\"Nonworking\");\n dayType.setDescription(\"A default non working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"2\");\n dayType.setName(\"Use base\");\n dayType.setDescription(\"Use day from base calendar\");\n }", "static void writePatch(final Patch rollbackPatch, final File file) throws IOException {\n final File parent = file.getParentFile();\n if (!parent.isDirectory()) {\n if (!parent.mkdirs() && !parent.exists()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath());\n }\n }\n try {\n try (final OutputStream os = new FileOutputStream(file)){\n PatchXml.marshal(os, rollbackPatch);\n }\n } catch (XMLStreamException e) {\n throw new IOException(e);\n }\n }", "public static final long getLong(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "public static String convertToSQL92(char escape, char multi, char single, String pattern)\n\t\t\tthrows IllegalArgumentException {\n\t\tif ((escape == '\\'') || (multi == '\\'') || (single == '\\'')) {\n\t\t\tthrow new IllegalArgumentException(\"do not use single quote (') as special char!\");\n\t\t}\n\t\t\n\t\tStringBuilder result = new StringBuilder(pattern.length() + 5);\n\t\tint i = 0;\n\t\twhile (i < pattern.length()) {\n\t\t\tchar chr = pattern.charAt(i);\n\t\t\tif (chr == escape) {\n\t\t\t\t// emit the next char and skip it\n\t\t\t\tif (i != (pattern.length() - 1)) {\n\t\t\t\t\tresult.append(pattern.charAt(i + 1));\n\t\t\t\t}\n\t\t\t\ti++; // skip next char\n\t\t\t} else if (chr == single) {\n\t\t\t\tresult.append('_');\n\t\t\t} else if (chr == multi) {\n\t\t\t\tresult.append('%');\n\t\t\t} else if (chr == '\\'') {\n\t\t\t\tresult.append('\\'');\n\t\t\t\tresult.append('\\'');\n\t\t\t} else {\n\t\t\t\tresult.append(chr);\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\n\t\treturn result.toString();\n\t}", "private void addCriteria(List<GenericCriteria> list, byte[] block)\n {\n byte[] leftBlock = getChildBlock(block);\n byte[] rightBlock1 = getListNextBlock(leftBlock);\n byte[] rightBlock2 = getListNextBlock(rightBlock1);\n TestOperator operator = TestOperator.getInstance(MPPUtility.getShort(block, 0) - 0x3E7);\n FieldType leftValue = getFieldType(leftBlock);\n Object rightValue1 = getValue(leftValue, rightBlock1);\n Object rightValue2 = rightBlock2 == null ? null : getValue(leftValue, rightBlock2);\n\n GenericCriteria criteria = new GenericCriteria(m_properties);\n criteria.setLeftValue(leftValue);\n criteria.setOperator(operator);\n criteria.setRightValue(0, rightValue1);\n criteria.setRightValue(1, rightValue2);\n list.add(criteria);\n\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = leftValue.getFieldTypeClass() == FieldTypeClass.TASK;\n m_criteriaType[1] = !m_criteriaType[0];\n }\n\n if (m_fields != null)\n {\n m_fields.add(leftValue);\n }\n\n processBlock(list, getListNextBlock(block));\n }", "public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }" ]
Return the authorization URL which is used to perform the authorization_code based OAuth2 flow. @param clientID the client ID to use with the connection. @param redirectUri the URL to which Box redirects the browser when authentication completes. @param state the text string that you choose. Box sends the same string to your redirect URL when authentication is complete. @param scopes this optional parameter identifies the Box scopes available to the application once it's authenticated. @return the authorization URL
[ "public static URL getAuthorizationURL(String clientID, URI redirectUri, String state, List<String> scopes) {\n URLTemplate template = new URLTemplate(AUTHORIZATION_URL);\n QueryStringBuilder queryBuilder = new QueryStringBuilder().appendParam(\"client_id\", clientID)\n .appendParam(\"response_type\", \"code\")\n .appendParam(\"redirect_uri\", redirectUri.toString())\n .appendParam(\"state\", state);\n\n if (scopes != null && !scopes.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n int size = scopes.size() - 1;\n int i = 0;\n while (i < size) {\n builder.append(scopes.get(i));\n builder.append(\" \");\n i++;\n }\n builder.append(scopes.get(i));\n\n queryBuilder.appendParam(\"scope\", builder.toString());\n }\n\n return template.buildWithQuery(\"\", queryBuilder.toString());\n }" ]
[ "public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n List<Versioned<V>> versionedValues;\n long startTime = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"PUT requested for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + startTime\n + \" . Nested GET and PUT VERSION requests to follow ---\");\n }\n\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent put might be faster such that all the\n // steps might finish within the allotted time\n requestWrapper.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(requestWrapper);\n Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues);\n\n long endTime = System.currentTimeMillis();\n if(versioned == null)\n versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock());\n else\n versioned.setObject(requestWrapper.getRawValue());\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime);\n if(timeLeft <= 0) {\n throw new StoreTimeoutException(\"PUT request timed out\");\n }\n CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(),\n versioned,\n timeLeft);\n putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs());\n Version result = putVersionedWithCustomTimeout(putVersionedRequestObject);\n long endTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT response received for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + endTimeInMs);\n }\n return result;\n }", "public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }", "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "public <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return Observable.just(event).delay(milliseconds, TimeUnit.MILLISECONDS, Schedulers.immediate());\n }", "public static boolean isKeyUsed(final Jedis jedis, final String key) {\n return !NONE.equalsIgnoreCase(jedis.type(key));\n }", "private float MIN(float first, float second, float third) {\r\n\r\n float min = Integer.MAX_VALUE;\r\n if (first < min) {\r\n min = first;\r\n }\r\n if (second < min) {\r\n min = second;\r\n }\r\n if (third < min) {\r\n min = third;\r\n }\r\n return min;\r\n }", "private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }", "public UpdateBuilder<T, ID> updateColumnValue(String columnName, Object value) throws SQLException {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new SQLException(\"Can't update foreign colletion field: \" + columnName);\n\t\t}\n\t\taddUpdateColumnToList(columnName, new SetValue(columnName, fieldType, value));\n\t\treturn this;\n\t}", "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 }" ]
Demonstrates how to add an override to an existing path
[ "public static void addOverrideToPath() throws Exception {\n Client client = new Client(\"ProfileName\", false);\n\n // Use the fully qualified name for a plugin override.\n client.addMethodToResponseOverride(\"Test Path\", \"com.groupon.odo.sample.Common.delay\");\n\n // The third argument is the ordinal - the nth instance of this override added to this path\n // The final arguments count and type are determined by the override. \"delay\" used in this sample\n // has a single int argument - # of milliseconds delay to simulate\n client.setMethodArguments(\"Test Path\", \"com.groupon.odo.sample.Common.delay\", 1, \"100\");\n }" ]
[ "private void checkExistingTracks() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n checkIfSignatureReady(entry.getKey().player);\n }\n }\n }\n });\n }", "public static ServerSetup[] verbose(ServerSetup[] serverSetups) {\r\n ServerSetup[] copies = new ServerSetup[serverSetups.length];\r\n for (int i = 0; i < serverSetups.length; i++) {\r\n copies[i] = serverSetups[i].createCopy().setVerbose(true);\r\n }\r\n return copies;\r\n }", "void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}", "private CmsMessageBundleEditorTypes.BundleType initBundleType() {\n\n String resourceTypeName = OpenCms.getResourceManager().getResourceType(m_resource).getTypeName();\n return CmsMessageBundleEditorTypes.BundleType.toBundleType(resourceTypeName);\n }", "public int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }", "public boolean add(final String member, final double score) {\n return doWithJedis(new JedisCallable<Boolean>() {\n @Override\n public Boolean call(Jedis jedis) {\n return jedis.zadd(getKey(), score, member) > 0;\n }\n });\n }", "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 String formatDateTime(Context context, ReadablePartial time, int flags) {\n return android.text.format.DateUtils.formatDateTime(context, toMillis(time), flags | FORMAT_UTC);\n }", "private void processDays(ProjectCalendar calendar) throws Exception\n {\n // Default all days to non-working\n for (Day day : Day.values())\n {\n calendar.setWorkingDay(day, false);\n }\n\n List<Row> rows = getRows(\"select * from zcalendarrule where zcalendar1=? and z_ent=?\", calendar.getUniqueID(), m_entityMap.get(\"CalendarWeekDayRule\"));\n for (Row row : rows)\n {\n Day day = row.getDay(\"ZWEEKDAY\");\n String timeIntervals = row.getString(\"ZTIMEINTERVALS\");\n if (timeIntervals == null)\n {\n calendar.setWorkingDay(day, false);\n }\n else\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n NodeList nodes = getNodeList(timeIntervals, m_dayTimeIntervals);\n calendar.setWorkingDay(day, nodes.getLength() > 0);\n\n for (int loop = 0; loop < nodes.getLength(); loop++)\n {\n NamedNodeMap attributes = nodes.item(loop).getAttributes();\n Date startTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"startTime\").getTextContent());\n Date endTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"endTime\").getTextContent());\n\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }" ]
Traces the duration between origin time in the http Request and time just before being processed by the fat client @param operationType @param originTimeInMS - origin time in the Http Request @param requestReceivedTimeInMs - System Time in ms @param keyString
[ "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }" ]
[ "public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }", "private String getRelativePomPath(MavenModule mavenModule, MavenModuleSetBuild mavenBuild) {\n String relativePath = mavenModule.getRelativePath();\n if (StringUtils.isBlank(relativePath)) {\n return POM_NAME;\n }\n\n // If this is the root module, return the root pom path.\n if (mavenModule.getModuleName().toString().\n equals(mavenBuild.getProject().getRootModule().getModuleName().toString())) {\n return mavenBuild.getProject().getRootPOM(null);\n }\n\n // to remove the project folder name if exists\n // keeps only the name of the module\n String modulePath = relativePath.substring(relativePath.indexOf(\"/\") + 1);\n for (String moduleName : mavenModules) {\n if (moduleName.contains(modulePath)) {\n return createPomPath(relativePath, moduleName);\n }\n }\n\n // In case this module is not in the parent pom\n return relativePath + \"/\" + POM_NAME;\n }", "public static void populateSubject(final LinkedHashMap<String, CommonProfile> profiles) {\n if (profiles != null && profiles.size() > 0) {\n final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);\n try {\n if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, false));\n } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, true));\n }\n } catch (final HttpAction e) {\n throw new TechnicalException(e);\n }\n }\n }", "private String randomString(String[] s) {\n if (s == null || s.length <= 0) return \"\";\n return s[this.random.nextInt(s.length)];\n }", "private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }", "public String login(Authentication authentication) {\n\t\tString token = getToken();\n\t\treturn login(token, authentication);\n\t}", "private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }", "private Number calculateDurationPercentComplete(Row row)\n {\n double result = 0;\n double targetDuration = row.getDuration(\"target_drtn_hr_cnt\").getDuration();\n double remainingDuration = row.getDuration(\"remain_drtn_hr_cnt\").getDuration();\n\n if (targetDuration == 0)\n {\n if (remainingDuration == 0)\n {\n if (\"TK_Complete\".equals(row.getString(\"status_code\")))\n {\n result = 100;\n }\n }\n }\n else\n {\n if (remainingDuration < targetDuration)\n {\n result = ((targetDuration - remainingDuration) * 100) / targetDuration;\n }\n }\n\n return NumberHelper.getDouble(result);\n }", "public String getUnicodeString(Integer id, Integer type)\n {\n return (getUnicodeString(m_meta.getOffset(id, type)));\n }" ]
Resets the generator state.
[ "public final void reset()\n {\n for (int i = 0; i < permutationIndices.length; i++)\n {\n permutationIndices[i] = i;\n }\n remainingPermutations = totalPermutations;\n }" ]
[ "public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }", "protected void printCenter(String format, Object... args) {\n String text = S.fmt(format, args);\n info(S.center(text, 80));\n }", "public static int lookupShaper(String name) {\r\n if (name == null) {\r\n return NOWORDSHAPE;\r\n } else if (name.equalsIgnoreCase(\"dan1\")) {\r\n return WORDSHAPEDAN1;\r\n } else if (name.equalsIgnoreCase(\"chris1\")) {\r\n return WORDSHAPECHRIS1;\r\n } else if (name.equalsIgnoreCase(\"dan2\")) {\r\n return WORDSHAPEDAN2;\r\n } else if (name.equalsIgnoreCase(\"dan2useLC\")) {\r\n return WORDSHAPEDAN2USELC;\r\n } else if (name.equalsIgnoreCase(\"dan2bio\")) {\r\n return WORDSHAPEDAN2BIO;\r\n } else if (name.equalsIgnoreCase(\"dan2bioUseLC\")) {\r\n return WORDSHAPEDAN2BIOUSELC;\r\n } else if (name.equalsIgnoreCase(\"jenny1\")) {\r\n return WORDSHAPEJENNY1;\r\n } else if (name.equalsIgnoreCase(\"jenny1useLC\")) {\r\n return WORDSHAPEJENNY1USELC;\r\n } else if (name.equalsIgnoreCase(\"chris2\")) {\r\n return WORDSHAPECHRIS2;\r\n } else if (name.equalsIgnoreCase(\"chris2useLC\")) {\r\n return WORDSHAPECHRIS2USELC;\r\n } else if (name.equalsIgnoreCase(\"chris3\")) {\r\n return WORDSHAPECHRIS3;\r\n } else if (name.equalsIgnoreCase(\"chris3useLC\")) {\r\n return WORDSHAPECHRIS3USELC;\r\n } else if (name.equalsIgnoreCase(\"chris4\")) {\r\n return WORDSHAPECHRIS4;\r\n } else if (name.equalsIgnoreCase(\"digits\")) {\r\n return WORDSHAPEDIGITS;\r\n } else {\r\n return NOWORDSHAPE;\r\n }\r\n }", "public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }", "public void deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService,\n\t\t\tURL schemaOverrideResource) {\n\t\t// user defined schema\n\t\tif ( schemaOverrideService != null || schemaOverrideResource != null ) {\n\t\t\tcachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema();\n\t\t}\n\n\t\t// or generate them\n\t\tgenerateProtoschema();\n\n\t\ttry {\n\t\t\tprotobufCache.put( generatedProtobufName, cachedSchema );\n\t\t\tString errors = protobufCache.get( generatedProtobufName + \".errors\" );\n\t\t\tif ( errors != null ) {\n\t\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, errors );\n\t\t\t}\n\t\t\tLOG.successfulSchemaDeploy( generatedProtobufName );\n\t\t}\n\t\tcatch (HotRodClientException hrce) {\n\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, hrce );\n\t\t}\n\t\tif ( schemaCapture != null ) {\n\t\t\tschemaCapture.put( generatedProtobufName, cachedSchema );\n\t\t}\n\t}", "private static int calculateBeginLine(RuleViolation pmdViolation) {\n int minLine = Math.min(pmdViolation.getBeginLine(), pmdViolation.getEndLine());\n return minLine > 0 ? minLine : calculateEndLine(pmdViolation);\n }", "public static void applyMultiIconTo(Drawable icon, int iconColor, Drawable selectedIcon, int selectedIconColor, boolean tinted, ImageView imageView) {\n //if we have an icon then we want to set it\n if (icon != null) {\n //if we got a different color for the selectedIcon we need a StateList\n if (selectedIcon != null) {\n if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, selectedIcon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(UIUtils.getIconStateList(icon, selectedIcon));\n }\n } else if (tinted) {\n imageView.setImageDrawable(new PressedEffectStateListDrawable(icon, iconColor, selectedIconColor));\n } else {\n imageView.setImageDrawable(icon);\n }\n //make sure we display the icon\n imageView.setVisibility(View.VISIBLE);\n } else {\n //hide the icon\n imageView.setVisibility(View.GONE);\n }\n }", "public static transformpolicylabel[] get(nitro_service service) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\ttransformpolicylabel[] response = (transformpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }" ]
Checks if the specified max levels is correct. @param userMaxLevels the maximum number of levels in the tree @param defaultMaxLevels the default max number of levels @return the validated max levels
[ "public static int validateGeohashMaxLevels(Integer userMaxLevels, int defaultMaxLevels) {\n int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels;\n if (maxLevels < 1 || maxLevels > GeohashPrefixTree.getMaxLevelsPossible()) {\n throw new IndexException(\"max_levels must be in range [1, {}], but found {}\",\n GeohashPrefixTree.getMaxLevelsPossible(),\n maxLevels);\n }\n return maxLevels;\n }" ]
[ "private void checkAndAddForbiddenStrings(final List<String> forbiddenSubStrings) {\n\t\tfor( String forbidden : forbiddenSubStrings ) {\n\t\t\tif( forbidden == null ) {\n\t\t\t\tthrow new NullPointerException(\"forbidden substring should not be null\");\n\t\t\t}\n\t\t\tthis.forbiddenSubStrings.add(forbidden);\n\t\t}\n\t}", "public ReferenceBuilder withPropertyValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\tgetSnakList(propertyIdValue).add(\n\t\t\t\tfactory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}", "@Beta\n public MSICredentials withObjectId(String objectId) {\n this.objectId = objectId;\n this.clientId = null;\n this.identityId = null;\n return this;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }", "private void validateAsMongoDBFieldName(String fieldName) {\n\t\tif ( fieldName.startsWith( \"$\" ) ) {\n\t\t\tthrow log.fieldNameHasInvalidDollarPrefix( fieldName );\n\t\t}\n\t\telse if ( fieldName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.fieldNameContainsNULCharacter( fieldName );\n\t\t}\n\t}", "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }", "public void awaitStartupCompletion() {\n try {\n Object obj = startedStatusQueue.take();\n if(obj instanceof Throwable)\n throw new VoldemortException((Throwable) obj);\n } catch(InterruptedException e) {\n // this is okay, if we are interrupted we can stop waiting\n }\n }", "private static void addProperties(EndpointReferenceType epr, SLProperties props) {\n MetadataType metadata = WSAEndpointReferenceUtils.getSetMetadata(epr);\n ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter.toServiceLocatorPropertiesType(props);\n\n JAXBElement<ServiceLocatorPropertiesType>\n slp = SL_OBJECT_FACTORY.createServiceLocatorProperties(jaxbProps);\n metadata.getAny().add(slp);\n }", "protected void postLayoutChild(final int dataIndex) {\n if (!mContainer.isDynamic()) {\n boolean visibleInLayout = !mViewPort.isClippingEnabled() || inViewPort(dataIndex);\n ViewPortVisibility visibility = visibleInLayout ?\n ViewPortVisibility.FULLY_VISIBLE : ViewPortVisibility.INVISIBLE;\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onLayout: child with dataId [%d] viewportVisibility = %s\",\n dataIndex, visibility);\n\n Widget childWidget = mContainer.get(dataIndex);\n if (childWidget != null) {\n childWidget.setViewPortVisibility(visibility);\n }\n }\n }" ]
Add image in the document. @param context PDF context @param imageResult image @throws BadElementException PDF construction problem @throws IOException PDF construction problem
[ "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 synchronized void abortTransaction() throws TransactionNotInProgressException\n {\n if(isInTransaction())\n {\n fireBrokerEvent(BEFORE_ROLLBACK_EVENT);\n setInTransaction(false);\n clearRegistrationLists();\n referencesBroker.removePrefetchingListeners();\n /*\n arminw:\n check if we in local tx, before do local rollback\n Necessary, because ConnectionManager may do a rollback by itself\n or in managed environments the used connection is already be closed\n */\n if(connectionManager.isInLocalTransaction()) this.connectionManager.localRollback();\n fireBrokerEvent(AFTER_ROLLBACK_EVENT);\n }\n }", "static String tokenize(PageMetadata<?, ?> pageMetadata) {\n try {\n Gson g = getGsonWithKeyAdapter(pageMetadata.pageRequestParameters);\n return new String(Base64.encodeBase64URLSafe(g.toJson(new PaginationToken\n (pageMetadata)).getBytes(\"UTF-8\")),\n Charset.forName(\"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n //all JVMs should support UTF-8\n throw new RuntimeException(e);\n }\n }", "@Deprecated\n @SuppressWarnings(\"deprecation\")\n protected void registerAddOperation(final ManagementResourceRegistration registration, final OperationStepHandler handler, OperationEntry.Flag... flags) {\n if (handler instanceof DescriptionProvider) {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n (DescriptionProvider) handler, OperationEntry.EntryType.PUBLIC,flags)\n , handler);\n\n } else {\n registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,\n new DefaultResourceAddDescriptionProvider(registration, descriptionResolver, orderedChild),\n OperationEntry.EntryType.PUBLIC,\n flags)\n , handler);\n }\n }", "private void stopDone() {\n synchronized (stopLock) {\n final StopContext stopContext = this.stopContext;\n this.stopContext = null;\n if (stopContext != null) {\n stopContext.complete();\n }\n stopLock.notifyAll();\n }\n }", "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}", "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }", "public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}", "public Build getBuildInfo(String appName, String buildId) {\n return connection.execute(new BuildInfo(appName, buildId), apiKey);\n }", "public synchronized ControlPoint getControlPoint(final String deploymentName, final String entryPointName) {\n ControlPointIdentifier id = new ControlPointIdentifier(deploymentName, entryPointName);\n ControlPoint ep = entryPoints.get(id);\n if (ep == null) {\n ep = new ControlPoint(this, deploymentName, entryPointName, trackIndividualControlPoints);\n entryPoints.put(id, ep);\n }\n ep.increaseReferenceCount();\n return ep;\n }" ]
Return a new File object based on the baseDir and the segments. This method does not perform any operation on the file system.
[ "public static File newFile(File baseDir, String... segments) {\n File f = baseDir;\n for (String segment : segments) {\n f = new File(f, segment);\n }\n return f;\n }" ]
[ "protected static void appendHandler(Class<? extends LogRecordHandler> parent, LogRecordHandler child){\r\n List<LogRecordHandler> toAdd = new LinkedList<LogRecordHandler>();\r\n //--Find Parents\r\n for(LogRecordHandler term : handlers){\r\n if(parent.isAssignableFrom(term.getClass())){\r\n toAdd.add(term);\r\n }\r\n }\r\n //--Add Handler\r\n for(LogRecordHandler p : toAdd){\r\n appendHandler(p, child);\r\n }\r\n }", "private static int[] getMode3PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n int[] postcodeNums = new int[postcode.length()];\r\n\r\n postcode = postcode.toUpperCase();\r\n for (int i = 0; i < postcodeNums.length; i++) {\r\n postcodeNums[i] = postcode.charAt(i);\r\n if (postcode.charAt(i) >= 'A' && postcode.charAt(i) <= 'Z') {\r\n // (Capital) letters shifted to Code Set A values\r\n postcodeNums[i] -= 64;\r\n }\r\n if (postcodeNums[i] == 27 || postcodeNums[i] == 31 || postcodeNums[i] == 33 || postcodeNums[i] >= 59) {\r\n // Not a valid postal code character, use space instead\r\n postcodeNums[i] = 32;\r\n }\r\n // Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital\r\n // letters in Code Set A (e.g. LF becomes 'J')\r\n }\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNums[5] & 0x03) << 4) | 3;\r\n primary[1] = ((postcodeNums[4] & 0x03) << 4) | ((postcodeNums[5] & 0x3c) >> 2);\r\n primary[2] = ((postcodeNums[3] & 0x03) << 4) | ((postcodeNums[4] & 0x3c) >> 2);\r\n primary[3] = ((postcodeNums[2] & 0x03) << 4) | ((postcodeNums[3] & 0x3c) >> 2);\r\n primary[4] = ((postcodeNums[1] & 0x03) << 4) | ((postcodeNums[2] & 0x3c) >> 2);\r\n primary[5] = ((postcodeNums[0] & 0x03) << 4) | ((postcodeNums[1] & 0x3c) >> 2);\r\n primary[6] = ((postcodeNums[0] & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }", "private void animateIndicatorInvalidate() {\n if (mIndicatorScroller.computeScrollOffset()) {\n mIndicatorOffset = mIndicatorScroller.getCurr();\n invalidate();\n\n if (!mIndicatorScroller.isFinished()) {\n postOnAnimation(mIndicatorRunnable);\n return;\n }\n }\n\n completeAnimatingIndicator();\n }", "private void ensurePrecisionAndScale(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, null);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, null);\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION))\r\n {\r\n String defaultPrecision = JdbcTypeHelper.getDefaultPrecisionFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultPrecision != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no precision setting though its jdbc type requires it (in most databases); using default precision of \"+defaultPrecision);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, defaultPrecision);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, \"1\");\r\n }\r\n }\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n String defaultScale = JdbcTypeHelper.getDefaultScaleFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultScale != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no scale setting though its jdbc type requires it (in most databases); using default scale of \"+defaultScale);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, defaultScale);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION) || fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, \"0\");\r\n }\r\n }\r\n }", "private void initHasMasterMode() throws CmsException {\n\n if (hasDescriptor()\n && m_cms.hasPermissions(m_desc, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {\n m_hasMasterMode = true;\n } else {\n m_hasMasterMode = false;\n }\n }", "public CmsJspDateSeriesBean getToDateSeries() {\n\n if (m_dateSeries == null) {\n m_dateSeries = new CmsJspDateSeriesBean(this, m_cms.getRequestContext().getLocale());\n }\n return m_dateSeries;\n }", "public ItemRequest<Task> removeTag(String task) {\n \n String path = String.format(\"/tasks/%s/removeTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "private void writeTask(Task task) throws IOException\n {\n writeFields(null, task, TaskField.values());\n for (Task child : task.getChildTasks())\n {\n writeTask(child);\n }\n }", "public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }" ]
Returns the log message id used by this checker. This is used to group it so that all attributes failing a type of rejction end up in the same error message. This default implementation uses the formatted log message with an empty attribute map as the id. @return the log message id
[ "public String getRejectionLogMessageId() {\n String id = logMessageId;\n if (id == null) {\n id = getRejectionLogMessage(Collections.<String, ModelNode>emptyMap());\n }\n logMessageId = id;\n return logMessageId;\n }" ]
[ "public Map<String,Object> getAttributeValues()\n throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {\n\n HashSet<String> attributeSet = new HashSet<String>();\n\n for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {\n attributeSet.add(attributeInfo.getName());\n }\n\n AttributeList attributeList =\n mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));\n\n Map<String, Object> attributeValueMap = new TreeMap<String, Object>();\n for (Attribute attribute : attributeList.asList()) {\n attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));\n }\n\n return attributeValueMap;\n }", "public void putEvents(List<Event> events) {\n Exception lastException;\n List<EventType> eventTypes = new ArrayList<EventType>();\n for (Event event : events) {\n EventType eventType = EventMapper.map(event);\n eventTypes.add(eventType);\n }\n\n int i = 0;\n lastException = null;\n while (i < numberOfRetries) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n lastException = e;\n i++;\n }\n if(i < numberOfRetries) {\n try {\n Thread.sleep(delayBetweenRetry);\n } catch (InterruptedException e) {\n break;\n }\n }\n }\n\n if (i == numberOfRetries) {\n throw new MonitoringException(\"1104\", \"Could not send events to monitoring service after \"\n + numberOfRetries + \" retries.\", lastException, events);\n }\n }", "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 Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }", "public void show() {\n if (!(container instanceof RootPanel)) {\n if (!(container instanceof MaterialDialog)) {\n container.getElement().getStyle().setPosition(Style.Position.RELATIVE);\n }\n div.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);\n }\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.HIDDEN);\n }\n if (type == LoaderType.CIRCULAR) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.LOADER_WRAPPER);\n div.add(preLoader);\n } else if (type == LoaderType.PROGRESS) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.PROGRESS_WRAPPER);\n progress.getElement().getStyle().setProperty(\"margin\", \"auto\");\n div.add(progress);\n }\n container.add(div);\n }", "public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {\r\n for (T item : items) {\r\n collection.add(item);\r\n }\r\n }", "public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static String[] allLowerCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toLowerCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}", "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 }" ]
Given the alias of the entity and the path to the relationship it will return the alias of the component. @param entityAlias the alias of the entity @param propertyPathWithoutAlias the path to the property without the alias @return the alias the relationship or null
[ "public String findAlias(String entityAlias, List<String> propertyPathWithoutAlias) {\n\t\tRelationshipAliasTree aliasTree = relationshipAliases.get( entityAlias );\n\t\tif ( aliasTree == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tRelationshipAliasTree associationAlias = aliasTree;\n\t\tfor ( int i = 0; i < propertyPathWithoutAlias.size(); i++ ) {\n\t\t\tassociationAlias = associationAlias.findChild( propertyPathWithoutAlias.get( i ) );\n\t\t\tif ( associationAlias == null ) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn associationAlias.getAlias();\n\t}" ]
[ "@Inline(value = \"$1.remove($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\t//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());\n\t\tfinal K key = entry.getKey();\n\t\tfinal V storedValue = map.get(entry.getKey());\n\t if (!Objects.equal(storedValue, entry.getValue())\n\t\t\t|| (storedValue == null && !map.containsKey(key))) {\n\t return false;\n \t}\n \tmap.remove(key);\n\t return true;\n\t}", "public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }", "boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));\n }", "protected void parseRequest(HttpServletRequest request,\n HttpServletResponse response) {\n requestParams = new HashMap<String, Object>();\n listFiles = new ArrayList<FileItemStream>();\n listFileStreams = new ArrayList<ByteArrayOutputStream>();\n\n // Parse the request\n if (ServletFileUpload.isMultipartContent(request)) {\n // multipart request\n try {\n ServletFileUpload upload = new ServletFileUpload();\n FileItemIterator iter = upload.getItemIterator(request);\n while (iter.hasNext()) {\n FileItemStream item = iter.next();\n String name = item.getFieldName();\n InputStream stream = item.openStream();\n if (item.isFormField()) {\n requestParams.put(name,\n Streams.asString(stream));\n } else {\n String fileName = item.getName();\n if (fileName != null && !\"\".equals(fileName.trim())) {\n listFiles.add(item);\n\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n IOUtils.copy(stream,\n os);\n listFileStreams.add(os);\n }\n }\n }\n } catch (Exception e) {\n logger.error(\"Unexpected error parsing multipart content\",\n e);\n }\n } else {\n // not a multipart\n for (Object mapKey : request.getParameterMap().keySet()) {\n String mapKeyString = (String) mapKey;\n\n if (mapKeyString.endsWith(\"[]\")) {\n // multiple values\n String values[] = request.getParameterValues(mapKeyString);\n List<String> listeValues = new ArrayList<String>();\n for (String value : values) {\n listeValues.add(value);\n }\n requestParams.put(mapKeyString,\n listeValues);\n } else {\n // single value\n String value = request.getParameter(mapKeyString);\n requestParams.put(mapKeyString,\n value);\n }\n }\n }\n }", "@Nonnull\n public static Builder builder(Revapi revapi) {\n List<String> knownExtensionIds = new ArrayList<>();\n\n addExtensionIds(revapi.getPipelineConfiguration().getApiAnalyzerTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getTransformTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getFilterTypes(), knownExtensionIds);\n addExtensionIds(revapi.getPipelineConfiguration().getReporterTypes(), knownExtensionIds);\n\n return new Builder(knownExtensionIds);\n }", "static List<NamedArgument> getNamedArgs( ExtensionContext context ) {\n List<NamedArgument> namedArgs = new ArrayList<>();\n\n if( context.getTestMethod().get().getParameterCount() > 0 ) {\n try {\n if( context.getClass().getCanonicalName().equals( METHOD_EXTENSION_CONTEXT ) ) {\n Field field = context.getClass().getSuperclass().getDeclaredField( \"testDescriptor\" );\n Object testDescriptor = ReflectionUtil.getFieldValueOrNull( field, context, ERROR );\n if( testDescriptor != null\n && testDescriptor.getClass().getCanonicalName().equals( TEST_TEMPLATE_INVOCATION_TEST_DESCRIPTOR ) ) {\n Object invocationContext = ReflectionUtil.getFieldValueOrNull( \"invocationContext\", testDescriptor, ERROR );\n if( invocationContext != null\n && invocationContext.getClass().getCanonicalName().equals( PARAMETERIZED_TEST_INVOCATION_CONTEXT ) ) {\n Object arguments = ReflectionUtil.getFieldValueOrNull( \"arguments\", invocationContext, ERROR );\n List<Object> args = Arrays.asList( (Object[]) arguments );\n namedArgs = ParameterNameUtil.mapArgumentsWithParameterNames( context.getTestMethod().get(), args );\n }\n }\n }\n } catch( Exception e ) {\n log.warn( ERROR, e );\n }\n }\n\n return namedArgs;\n }", "public static Organization unserializeOrganization(final String organization) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(organization, Organization.class);\n }", "public V internalNonBlockingGet(K key) throws Exception {\n Pool<V> resourcePool = getResourcePoolForKey(key);\n return attemptNonBlockingCheckout(key, resourcePool);\n }", "void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }" ]
Print a date. @param value Date instance @return string representation of a date
[ "public static final String printDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }" ]
[ "protected static void statistics(int from, int to) {\r\n\t// check that primes contain no accidental errors\r\n\tfor (int i=0; i<primeCapacities.length-1; i++) {\r\n\t\tif (primeCapacities[i] >= primeCapacities[i+1]) throw new RuntimeException(\"primes are unsorted or contain duplicates; detected at \"+i+\"@\"+primeCapacities[i]);\r\n\t}\r\n\t\r\n\tdouble accDeviation = 0.0;\r\n\tdouble maxDeviation = - 1.0;\r\n\r\n\tfor (int i=from; i<=to; i++) {\r\n\t\tint primeCapacity = nextPrime(i);\r\n\t\t//System.out.println(primeCapacity);\r\n\t\tdouble deviation = (primeCapacity - i) / (double)i;\r\n\t\t\r\n\t\tif (deviation > maxDeviation) {\r\n\t\t\tmaxDeviation = deviation;\r\n\t\t\tSystem.out.println(\"new maxdev @\"+i+\"@dev=\"+maxDeviation);\r\n\t\t}\r\n\r\n\t\taccDeviation += deviation;\r\n\t}\r\n\tlong width = 1 + (long)to - (long)from;\r\n\t\r\n\tdouble meanDeviation = accDeviation/width;\r\n\tSystem.out.println(\"Statistics for [\"+ from + \",\"+to+\"] are as follows\");\r\n\tSystem.out.println(\"meanDeviation = \"+(float)meanDeviation*100+\" %\");\r\n\tSystem.out.println(\"maxDeviation = \"+(float)maxDeviation*100+\" %\");\r\n}", "public <T extends Widget & Checkable> void clearChecks() {\n List<T> children = getCheckableChildren();\n for (T c : children) {\n c.setChecked(false);\n }\n }", "public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\n }", "public void strokeRoundRectangle(Rectangle rect, Color color, float linewidth, float r) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.roundRectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight(), r);\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}", "public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }", "public void delete(Vertex vtx) {\n if (vtx.prev == null) {\n head = vtx.next;\n } else {\n vtx.prev.next = vtx.next;\n }\n if (vtx.next == null) {\n tail = vtx.prev;\n } else {\n vtx.next.prev = vtx.prev;\n }\n }", "protected PatchEntry resolveForElement(final PatchElement element) throws PatchingException {\n assert state == State.NEW;\n final PatchElementProvider provider = element.getProvider();\n final String layerName = provider.getName();\n final LayerType layerType = provider.getLayerType();\n\n final Map<String, PatchEntry> map;\n if (layerType == LayerType.Layer) {\n map = layers;\n } else {\n map = addOns;\n }\n PatchEntry entry = map.get(layerName);\n if (entry == null) {\n final InstallationManager.MutablePatchingTarget target = modification.resolve(layerName, layerType);\n if (target == null) {\n throw PatchLogger.ROOT_LOGGER.noSuchLayer(layerName);\n }\n entry = new PatchEntry(target, element);\n map.put(layerName, entry);\n }\n // Maintain the most recent element\n entry.updateElement(element);\n return entry;\n }", "public static void registerDeploymentResource(final DeploymentResourceSupport deploymentResourceSupport, final LoggingConfigurationService service) {\n final PathElement base = PathElement.pathElement(\"configuration\", service.getConfiguration());\n deploymentResourceSupport.getDeploymentSubModel(LoggingExtension.SUBSYSTEM_NAME, base);\n final LogContextConfiguration configuration = service.getValue();\n // Register the child resources if the configuration is not null in cases where a log4j configuration was used\n if (configuration != null) {\n registerDeploymentResource(deploymentResourceSupport, base, HANDLER, configuration.getHandlerNames());\n registerDeploymentResource(deploymentResourceSupport, base, LOGGER, configuration.getLoggerNames());\n registerDeploymentResource(deploymentResourceSupport, base, FORMATTER, configuration.getFormatterNames());\n registerDeploymentResource(deploymentResourceSupport, base, FILTER, configuration.getFilterNames());\n registerDeploymentResource(deploymentResourceSupport, base, POJO, configuration.getPojoNames());\n registerDeploymentResource(deploymentResourceSupport, base, ERROR_MANAGER, configuration.getErrorManagerNames());\n }\n }", "public static void getHistory() throws Exception{\n Client client = new Client(\"ProfileName\", false);\n\n // Obtain the 100 history entries starting from offset 0\n History[] history = client.refreshHistory(100, 0);\n\n client.clearHistory();\n }" ]
Gets the value of the task property. <p> This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for the task property. <p> For example, to add a new item, do as follows: <pre> getTask().add(newItem); </pre> <p> Objects of the following type(s) are allowed in the list {@link GanttDesignerRemark.Task }
[ "public List<GanttDesignerRemark.Task> getTask()\n {\n if (task == null)\n {\n task = new ArrayList<GanttDesignerRemark.Task>();\n }\n return this.task;\n }" ]
[ "public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\n }\n }", "public double response( double[] sample ) {\n if( sample.length != A.numCols )\n throw new IllegalArgumentException(\"Expected input vector to be in sample space\");\n\n DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);\n DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);\n\n CommonOps_DDRM.mult(V_t,s,dots);\n\n return NormOps_DDRM.normF(dots);\n }", "public static String padLeft(String str, int totalChars, char ch) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0, num = totalChars - str.length(); i < num; i++) {\r\n sb.append(ch);\r\n }\r\n sb.append(str);\r\n return sb.toString();\r\n }", "private static void createList( int data[], int k , int level , List<int[]> ret )\n {\n data[k] = level;\n\n if( level < data.length-1 ) {\n for( int i = 0; i < data.length; i++ ) {\n if( data[i] == -1 ) {\n createList(data,i,level+1,ret);\n }\n }\n } else {\n int []copy = new int[data.length];\n System.arraycopy(data,0,copy,0,data.length);\n ret.add(copy);\n }\n data[k] = -1;\n }", "public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }", "protected void setJsonValue(JsonObjectBuilder builder, T value) {\n // I don't like this - there should really be a way to construct a disconnected JSONValue...\n if (value instanceof Boolean) {\n builder.add(\"value\", (Boolean) value);\n } else if (value instanceof Double) {\n builder.add(\"value\", (Double) value);\n } else if (value instanceof Integer) {\n builder.add(\"value\", (Integer) value);\n } else if (value instanceof Long) {\n builder.add(\"value\", (Long) value);\n } else if (value instanceof BigInteger) {\n builder.add(\"value\", (BigInteger) value);\n } else if (value instanceof BigDecimal) {\n builder.add(\"value\", (BigDecimal) value);\n } else if (value == null) {\n builder.addNull(\"value\");\n } else {\n builder.add(\"value\", value.toString());\n }\n }", "public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\n\t\tint timeIndex\t= model.getTimeIndex(startTime);\n\t\t// Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves\n\t\tArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>();\n\t\tint firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime);\n\t\tdouble firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex);\n\t\tif(firstLiborTime>startTime) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime));\n\t\t}\n\t\t// Vector of times for the forward curve\n\t\tdouble[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)];\n\t\ttimes[0]=0;\n\t\tint indexOffset = firstLiborTime==startTime ? 0 : 1;\n\t\tfor(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(timeIndex,i));\n\t\t\ttimes[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime;\n\t\t}\n\n\t\tRandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]);\n\t\treturn ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex));\n\n\t}", "private static MonolingualTextValue toTerm(MonolingualTextValue term) {\n\t\treturn term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText());\n\t}", "public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}" ]
Check whether the URL start with one of the given prefixes. @param uri URI @param patterns possible prefixes @return true when URL starts with one of the prefixes
[ "public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}" ]
[ "protected Element createTextElement(float width)\n {\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"p\" + (textcnt++));\n el.setAttribute(\"class\", \"p\");\n String style = curstyle.toString();\n style += \"width:\" + width + UNIT + \";\";\n el.setAttribute(\"style\", style);\n return el;\n }", "static int lastArgMatchesVarg(Parameter[] params, ClassNode... args) {\n if (!isVargs(params)) return -1;\n // case length ==0 handled already\n // we have now two cases,\n // the argument is wrapped in the vargs array or\n // the argument is an array that can be used for the vargs part directly\n // we test only the wrapping part, since the non wrapping is done already\n ClassNode lastParamType = params[params.length - 1].getType();\n ClassNode ptype = lastParamType.getComponentType();\n ClassNode arg = args[args.length - 1];\n if (isNumberType(ptype) && isNumberType(arg) && !ptype.equals(arg)) return -1;\n return isAssignableTo(arg, ptype)?Math.min(getDistance(arg, lastParamType), getDistance(arg, ptype)):-1;\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<BritishCutoverDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<BritishCutoverDate>) super.zonedDateTime(temporal);\n }", "public static String readFlowId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String flowId = null;\n Header hdFlowId = ((SoapMessage)message).getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n if (hdFlowId.getObject() instanceof String) {\n flowId = (String)hdFlowId.getObject();\n } else if (hdFlowId.getObject() instanceof Node) {\n Node headerNode = (Node)hdFlowId.getObject();\n flowId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found FlowId soap header but value is not a String or a Node! Value: \"\n + hdFlowId.getObject().toString());\n }\n }\n return flowId;\n }", "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 <T> T get(String key, Class<T> type) {\n Object value = this.data.get(key);\n if (value != null && type.isAssignableFrom(value.getClass())) {\n return (T) value;\n }\n return null;\n }", "public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }", "public int getFixedDataOffset(FieldType type)\n {\n int result;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFixedDataOffset();\n }\n else\n {\n result = -1;\n }\n return result;\n }", "private List<T> computePagedList(List<T> result, HeaderAndBody httpResponse, JSONObject where, Pipe<T> requestingPipe) {\n ReadFilter previousRead = null;\n ReadFilter nextRead = null;\n\n if (PageConfig.MetadataLocations.WEB_LINKING.equals(pageConfig.getMetadataLocation())) {\n String webLinksRaw = \"\";\n final String relHeader = \"rel\";\n final String nextIdentifier = pageConfig.getNextIdentifier();\n final String prevIdentifier = pageConfig.getPreviousIdentifier();\n try {\n webLinksRaw = getWebLinkHeader(httpResponse);\n if (webLinksRaw == null) { // no paging, return result\n return result;\n }\n List<WebLink> webLinksParsed = WebLinkParser.parse(webLinksRaw);\n for (WebLink link : webLinksParsed) {\n if (nextIdentifier.equals(link.getParameters().get(relHeader))) {\n nextRead = new ReadFilter();\n nextRead.setLinkUri(new URI(link.getUri()));\n } else if (prevIdentifier.equals(link.getParameters().get(relHeader))) {\n previousRead = new ReadFilter();\n previousRead.setLinkUri(new URI(link.getUri()));\n }\n\n }\n } catch (URISyntaxException ex) {\n Log.e(TAG, webLinksRaw + \" did not contain a valid context URI\", ex);\n throw new RuntimeException(ex);\n } catch (ParseException ex) {\n Log.e(TAG, webLinksRaw + \" could not be parsed as a web link header\", ex);\n throw new RuntimeException(ex);\n }\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.HEADERS)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.BODY)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else {\n throw new IllegalStateException(\"Not supported\");\n }\n if (nextRead != null) {\n nextRead.setWhere(where);\n }\n\n if (previousRead != null) {\n previousRead.setWhere(where);\n }\n\n return new WrappingPagedList<T>(requestingPipe, result, nextRead, previousRead);\n }" ]
Gets a JavaMail Session for given server type such as IMAP and additional props for JavaMail. @param setup the setup type, such as <code>ServerSetup.IMAP</code> @param mailProps additional mail properties. @return the JavaMail session.
[ "public static Session getSession(final ServerSetup setup, Properties mailProps) {\r\n Properties props = setup.configureJavaMailSessionProperties(mailProps, false);\r\n\r\n log.debug(\"Mail session properties are {}\", props);\r\n\r\n return Session.getInstance(props, null);\r\n }" ]
[ "@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 void copyTo(Gradient g) {\n\t\tg.numKnots = numKnots;\n\t\tg.map = (int[])map.clone();\n\t\tg.xKnots = (int[])xKnots.clone();\n\t\tg.yKnots = (int[])yKnots.clone();\n\t\tg.knotTypes = (byte[])knotTypes.clone();\n\t}", "public void setDynamicValue(String attribute, String value) {\n\n if (null == m_dynamicValues) {\n m_dynamicValues = new ConcurrentHashMap<String, String>();\n }\n m_dynamicValues.put(attribute, value);\n }", "public RedwoodConfiguration showOnlyChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } });\r\n return this;\r\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"classes.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\t// Add direct subclass information:\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Integer superClass : classEntry.getValue().directSuperClasses) {\n\t\t\t\t\tthis.classRecords.get(superClass).nonemptyDirectSubclasses\n\t\t\t\t\t\t\t.add(classEntry.getKey().toString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tint countNoLabel = 0;\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (classEntry.getValue().label == null) {\n\t\t\t\t\tcountNoLabel++;\n\t\t\t\t}\n\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + classEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, classEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" class items.\");\n\t\t\tSystem.out.println(\" -- class items with missing label: \"\n\t\t\t\t\t+ countNoLabel);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public static XClass getMemberType() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getType();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getType();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getType();\r\n }\r\n }\r\n return null;\r\n }", "public static boolean isFolderExist(String directoryPath) {\r\n if (StringUtils.isEmpty(directoryPath)) {\r\n return false;\r\n }\r\n\r\n File dire = new File(directoryPath);\r\n return (dire.exists() && dire.isDirectory());\r\n }", "public void setAngle(float angle) {\n this.angle = angle;\n float cos = (float) Math.cos(angle);\n float sin = (float) Math.sin(angle);\n m00 = cos;\n m01 = sin;\n m10 = -sin;\n m11 = cos;\n }", "void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }" ]
given is at the begining, of is at the end
[ "public float conditionalLogProb(int[] given, int of) {\r\n if (given.length != windowSize - 1) {\r\n System.err.println(\"error computing conditional log prob\");\r\n System.exit(0);\r\n }\r\n int[] label = indicesFront(given);\r\n float[] masses = new float[label.length];\r\n for (int i = 0; i < masses.length; i++) {\r\n masses[i] = table[label[i]];\r\n }\r\n float z = ArrayMath.logSum(masses);\r\n\r\n return table[indexOf(given, of)] - z;\r\n }" ]
[ "public final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }", "public synchronized void hide() {\n if (focusedQuad != null) {\n\n mDefocusAnimationFactory.create(focusedQuad)\n .setRequestLayoutOnTargetChange(false)\n .start().finish();\n\n focusedQuad = null;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"hide Picker!\");\n }", "public boolean hasDeploymentSubsystemModel(final String subsystemName) {\n final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);\n final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);\n return root.hasChild(subsystem);\n }", "public static void Shuffle(double[] array, long seed) {\n Random random = new Random();\n if (seed != 0) random.setSeed(seed);\n\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n double temp = array[index];\n array[index] = array[i];\n array[i] = temp;\n }\n }", "public String getSQL92LikePattern() throws IllegalArgumentException {\n\t\tif (escape.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> escape char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardSingle.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardSingle char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardMulti.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardMulti char should be of length exactly 1\");\n\t\t}\n\t\treturn LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),\n\t\t\t\tisMatchingCase(), pattern);\n\t}", "public WebSocketContext sendToPeers(String message, boolean excludeSelf) {\n return sendToConnections(message, url, manager.urlRegistry(), excludeSelf);\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 }", "private Event createEvent(Endpoint endpoint, EventTypeEnum type) {\n\n Event event = new Event();\n MessageInfo messageInfo = new MessageInfo();\n Originator originator = new Originator();\n event.setMessageInfo(messageInfo);\n event.setOriginator(originator);\n\n Date date = new Date();\n event.setTimestamp(date);\n event.setEventType(type);\n\n messageInfo.setPortType(\n endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString());\n\n String transportType = null;\n if (endpoint.getBinding() instanceof SoapBinding) {\n SoapBinding soapBinding = (SoapBinding)endpoint.getBinding();\n if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) {\n SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo();\n transportType = soapBindingInfo.getTransportURI();\n }\n }\n messageInfo.setTransportType((transportType != null) ? transportType : \"Unknown transport type\");\n\n originator.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n originator.setIp(inetAddress.getHostAddress());\n originator.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n originator.setHostname(\"Unknown hostname\");\n originator.setIp(\"Unknown ip address\");\n }\n\n String address = endpoint.getEndpointInfo().getAddress();\n event.getCustomInfo().put(\"address\", address);\n\n return event;\n }", "public static int getActionBarHeight(Context context) {\n int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);\n if (actionBarHeight == 0) {\n actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);\n }\n return actionBarHeight;\n }" ]
Generate and return the list of statements to drop a database table.
[ "private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, boolean logDetails) {\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\tdatabaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter);\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"dropping table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"DROP TABLE \");\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(' ');\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t}" ]
[ "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 }", "private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "public static <T extends Number> int[] asArray(final T... array) {\n int[] b = new int[array.length];\n for (int i = 0; i < b.length; i++) {\n b[i] = array[i].intValue();\n }\n return b;\n }", "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }", "public void bindBundleToSceneObject(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject)\n throws IOException, GVRScriptException\n {\n bindHelper(scriptBundle, rootSceneObject, BIND_MASK_SCENE_OBJECTS);\n }", "public static <T> T createProxy(final Class<T> proxyInterface) {\n\t\tif( proxyInterface == null ) {\n\t\t\tthrow new NullPointerException(\"proxyInterface should not be null\");\n\t\t}\n\t\treturn proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(),\n\t\t\tnew Class[] { proxyInterface }, new BeanInterfaceProxy()));\n\t}", "public static base_response delete(nitro_service client, String username) throws Exception {\n\t\tsystemuser deleteresource = new systemuser();\n\t\tdeleteresource.username = username;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\n }", "public String getUncPath() {\n getUncPath0();\n if( share == null ) {\n return \"\\\\\\\\\" + url.getHost();\n }\n return \"\\\\\\\\\" + url.getHost() + canon.replace( '/', '\\\\' );\n }" ]
Notifies all registered BufferChangeLogger instances of a change. @param newData the buffer that contains the new data being added @param numChars the number of valid characters in the buffer
[ "protected void notifyBufferChange(char[] newData, int numChars) {\n synchronized(bufferChangeLoggers) {\n Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator();\n while (iterator.hasNext()) {\n iterator.next().bufferChanged(newData, numChars);\n }\n }\n }" ]
[ "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 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 }", "PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\n }", "public static base_response unset(nitro_service client, vridparam resource, String[] args) throws Exception{\n\t\tvridparam unsetresource = new vridparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public double[] getRegressionCoefficients(RandomVariable value) {\n\t\tif(basisFunctions.length == 0) {\n\t\t\treturn new double[] { };\n\t\t}\n\t\telse if(basisFunctions.length == 1) {\n\t\t\t/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */\n\t\t\treturn new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };\n\t\t}\n\t\telse if(basisFunctions.length == 2) {\n\t\t\t/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */\n\t\t\tdouble a = basisFunctions[0].squared().getAverage();\n\t\t\tdouble b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();\n\t\t\tdouble c = b;\n\t\t\tdouble d = basisFunctions[1].squared().getAverage();\n\n\t\t\tdouble determinant = (a * d - b * c);\n\t\t\tif(determinant != 0) {\n\t\t\t\tdouble x = value.mult(basisFunctions[0]).getAverage();\n\t\t\t\tdouble y = value.mult(basisFunctions[1]).getAverage();\n\n\t\t\t\tdouble alpha0 = (d * x - b * y) / determinant;\n\t\t\t\tdouble alpha1 = (a * y - c * x) / determinant;\n\n\t\t\t\treturn new double[] { alpha0, alpha1 };\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * General case\n\t\t */\n\n\t\t// Build regression matrix\n\t\tdouble[][] BTB = new double[basisFunctions.length][basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tfor(int j=0; j<=i; j++) {\n\t\t\t\tdouble covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();\n\t\t\t\tBTB[i][j] = covariance;\n\t\t\t\tBTB[j][i] = covariance;\n\t\t\t}\n\t\t}\n\n\t\tdouble[] BTX = new double[basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tdouble covariance = basisFunctions[i].mult(value).getAverage();\n\t\t\tBTX[i] = covariance;\n\t\t}\n\n\t\treturn LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);\n\t}", "public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }", "public MaterialAccount getAccountAtCurrentPosition(int position) {\n\n if (position < 0 || position >= accountManager.size())\n throw new RuntimeException(\"Account Index Overflow\");\n\n return findAccountNumber(position);\n }", "@Override\n public PaxDate date(int prolepticYear, int month, int dayOfMonth) {\n return PaxDate.of(prolepticYear, month, dayOfMonth);\n }", "protected float computeUniformPadding(final CacheDataSet cache) {\n float axisSize = getViewPortSize(getOrientationAxis());\n float totalPadding = axisSize - cache.getTotalSize();\n float uniformPadding = totalPadding > 0 && cache.count() > 1 ?\n totalPadding / (cache.count() - 1) : 0;\n return uniformPadding;\n }" ]
Lists the formation info for an app @param appName See {@link #listApps} for a list of apps that can be used.
[ "public List<Formation> listFormation(String appName) {\n return connection.execute(new FormationList(appName), apiKey);\n }" ]
[ "public void addCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(!dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().add(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.addModulesOrganization(corporateGroupId, dbOrganization);\n }", "private static List< Block > createBlocks(int[] data, boolean debug) {\r\n\r\n List< Block > blocks = new ArrayList<>();\r\n Block current = null;\r\n\r\n for (int i = 0; i < data.length; i++) {\r\n EncodingMode mode = chooseMode(data[i]);\r\n if ((current != null && current.mode == mode) &&\r\n (mode != EncodingMode.NUM || current.length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n current.length++;\r\n } else {\r\n current = new Block(mode);\r\n blocks.add(current);\r\n }\r\n }\r\n\r\n if (debug) {\r\n System.out.println(\"Initial block pattern: \" + blocks);\r\n }\r\n\r\n smoothBlocks(blocks);\r\n\r\n if (debug) {\r\n System.out.println(\"Final block pattern: \" + blocks);\r\n }\r\n\r\n return blocks;\r\n }", "public static final String getString(byte[] data, int offset)\n {\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int loop = 0; offset + loop < data.length; loop++)\n {\n c = (char) data[offset + loop];\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }", "private void initFieldFactories() {\n\n if (m_model.hasMasterMode()) {\n TranslateTableFieldFactory masterFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER));\n masterFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.MASTER, masterFieldFactory);\n }\n TranslateTableFieldFactory defaultFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT));\n defaultFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, defaultFieldFactory);\n\n }", "protected RdfSerializer createRdfSerializer() throws IOException {\n\n\t\tString outputDestinationFinal;\n\t\tif (this.outputDestination != null) {\n\t\t\toutputDestinationFinal = this.outputDestination;\n\t\t} else {\n\t\t\toutputDestinationFinal = \"{PROJECT}\" + this.taskName + \"{DATE}\"\n\t\t\t\t\t+ \".nt\";\n\t\t}\n\n\t\tOutputStream exportOutputStream = getOutputStream(this.useStdOut,\n\t\t\t\tinsertDumpInformation(outputDestinationFinal),\n\t\t\t\tthis.compressionType);\n\n\t\tRdfSerializer serializer = new RdfSerializer(RDFFormat.NTRIPLES,\n\t\t\t\texportOutputStream, this.sites,\n\t\t\t\tPropertyRegister.getWikidataPropertyRegister());\n\t\tserializer.setTasks(this.tasks);\n\n\t\treturn serializer;\n\t}", "public static final BigInteger printPriority(Priority priority)\n {\n int result = Priority.MEDIUM;\n\n if (priority != null)\n {\n result = priority.getValue();\n }\n\n return (BigInteger.valueOf(result));\n }", "void execute(ExecutableBuilder builder,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n Future<Void> task = executorService.submit(() -> {\n builder.build().execute();\n return null;\n });\n try {\n if (timeout <= 0) { //Synchronous\n task.get();\n } else { // Guarded execution\n try {\n task.get(timeout, unit);\n } catch (TimeoutException ex) {\n // First make the context unusable\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).timeout();\n }\n // Then cancel the task.\n task.cancel(true);\n throw ex;\n }\n }\n } catch (InterruptedException ex) {\n // Could have been interrupted by user (Ctrl-C)\n Thread.currentThread().interrupt();\n cancelTask(task, builder.getCommandContext(), null);\n // Interrupt running operation.\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).interrupted();\n }\n throw ex;\n }\n }", "public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,\n ArtifactoryServer pipelineServer) {\n\n if (artifactoryServerID == null && pipelineServer == null) {\n return null;\n }\n if (artifactoryServerID != null && pipelineServer != null) {\n return null;\n }\n if (pipelineServer != null) {\n CredentialsConfig credentials = pipelineServer.createCredentialsConfig();\n\n return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,\n credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads());\n }\n org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());\n if (server == null) {\n return null;\n }\n return server;\n }", "public void deleteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"to delete module\", name, version);\n\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }" ]
Counts one entity. Every once in a while, the current time is checked so as to print an intermediate report roughly every ten seconds.
[ "private void countEntity() {\n\t\tif (!this.timer.isRunning()) {\n\t\t\tstartTimer();\n\t\t}\n\n\t\tthis.entityCount++;\n\t\tif (this.entityCount % 100 == 0) {\n\t\t\ttimer.stop();\n\t\t\tint seconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\t\tif (seconds >= this.lastSeconds + this.reportInterval) {\n\t\t\t\tthis.lastSeconds = seconds;\n\t\t\t\tprintStatus();\n\t\t\t\tif (this.timeout > 0 && seconds > this.timeout) {\n\t\t\t\t\tlogger.info(\"Timeout. Aborting processing.\");\n\t\t\t\t\tthrow new TimeoutException();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer.start();\n\t\t}\n\t}" ]
[ "private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }", "public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }", "public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }", "private <T> T request(ClientRequest<T> delegate, String operationName) {\n long startTimeMs = -1;\n long startTimeNs = -1;\n\n if(logger.isDebugEnabled()) {\n startTimeMs = System.currentTimeMillis();\n }\n ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);\n String debugMsgStr = \"\";\n\n startTimeNs = System.nanoTime();\n\n BlockingClientRequest<T> blockingClientRequest = null;\n try {\n blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);\n clientRequestExecutor.addClientRequest(blockingClientRequest,\n timeoutMs,\n System.nanoTime() - startTimeNs);\n\n boolean awaitResult = blockingClientRequest.await();\n\n if(awaitResult == false) {\n blockingClientRequest.timeOut();\n }\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"success\";\n\n return blockingClientRequest.getResult();\n } catch(InterruptedException e) {\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"unreachable: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e);\n } catch(UnreachableStoreException e) {\n clientRequestExecutor.close();\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"failure: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e.getCause());\n } finally {\n if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {\n // close the executor if we timed out\n clientRequestExecutor.close();\n }\n // Record operation time\n long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime());\n if(stats != null) {\n stats.recordSyncOpTimeNs(destination, opTimeNs);\n }\n if(logger.isDebugEnabled()) {\n logger.debug(\"Sync request end, type: \"\n + operationName\n + \" requestRef: \"\n + System.identityHashCode(delegate)\n + \" totalTimeNs: \"\n + opTimeNs\n + \" start time: \"\n + startTimeMs\n + \" end time: \"\n + System.currentTimeMillis()\n + \" client:\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalAddress()\n + \":\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalPort()\n + \" server: \"\n + clientRequestExecutor.getSocketChannel()\n .socket()\n .getRemoteSocketAddress() + \" outcome: \"\n + debugMsgStr);\n }\n\n pool.checkin(destination, clientRequestExecutor);\n }\n }", "protected void onLegendDataChanged() {\n\n int legendCount = mLegendList.size();\n float margin = (mGraphWidth / legendCount);\n float currentOffset = 0;\n\n for (LegendModel model : mLegendList) {\n model.setLegendBounds(new RectF(currentOffset, 0, currentOffset + margin, mLegendHeight));\n currentOffset += margin;\n }\n\n Utils.calculateLegendInformation(mLegendList, 0, mGraphWidth, mLegendPaint);\n\n invalidateGlobal();\n }", "public static @Nullable CleverTapAPI getInstance(Context context) throws CleverTapMetaDataNotFoundException, CleverTapPermissionsNotSatisfied {\n // For Google Play Store/Android Studio tracking\n sdkVersion = BuildConfig.SDK_VERSION_STRING;\n return getDefaultInstance(context);\n }", "public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}", "public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }", "public static RowColumn toRowColumn(Key key) {\n if (key == null) {\n return RowColumn.EMPTY;\n }\n if ((key.getRow() == null) || key.getRow().getLength() == 0) {\n return RowColumn.EMPTY;\n }\n Bytes row = ByteUtil.toBytes(key.getRow());\n if ((key.getColumnFamily() == null) || key.getColumnFamily().getLength() == 0) {\n return new RowColumn(row);\n }\n Bytes cf = ByteUtil.toBytes(key.getColumnFamily());\n if ((key.getColumnQualifier() == null) || key.getColumnQualifier().getLength() == 0) {\n return new RowColumn(row, new Column(cf));\n }\n Bytes cq = ByteUtil.toBytes(key.getColumnQualifier());\n if ((key.getColumnVisibility() == null) || key.getColumnVisibility().getLength() == 0) {\n return new RowColumn(row, new Column(cf, cq));\n }\n Bytes cv = ByteUtil.toBytes(key.getColumnVisibility());\n return new RowColumn(row, new Column(cf, cq, cv));\n }" ]
Returns the simple name of the builder class that should be generated for the given type. <p>This is simply the {@link #BUILDER_SIMPLE_NAME_TEMPLATE} with the original type name substituted in. (If the original type is nested, its enclosing classes will be included, separated with underscores, to ensure uniqueness.)
[ "private String generatedBuilderSimpleName(TypeElement type) {\n String packageName = elements.getPackageOf(type).getQualifiedName().toString();\n String originalName = type.getQualifiedName().toString();\n checkState(originalName.startsWith(packageName + \".\"));\n String nameWithoutPackage = originalName.substring(packageName.length() + 1);\n return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll(\"\\\\.\", \"_\"));\n }" ]
[ "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 }", "private void addSequence(String sequenceName, HighLowSequence seq)\r\n {\r\n // lookup the sequence map for calling DB\r\n String jcdAlias = getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias();\r\n Map mapForDB = (Map) sequencesDBMap.get(jcdAlias);\r\n if(mapForDB == null)\r\n {\r\n mapForDB = new HashMap();\r\n }\r\n mapForDB.put(sequenceName, seq);\r\n sequencesDBMap.put(jcdAlias, mapForDB);\r\n }", "public void setAttributes(Object feature, Map<String, Attribute> attributes) throws LayerException {\n\t\tfor (Map.Entry<String, Attribute> entry : attributes.entrySet()) {\n\t\t\tString name = entry.getKey();\n\t\t\tif (!name.equals(getGeometryAttributeName())) {\n\t\t\t\tasFeature(feature).setAttribute(name, entry.getValue());\n\t\t\t}\n\t\t}\n\t}", "public static void startAndWait(PersistentNode node, int maxWaitSec) {\n node.start();\n int waitTime = 0;\n try {\n while (node.waitForInitialCreate(1, TimeUnit.SECONDS) == false) {\n waitTime += 1;\n log.info(\"Waited \" + waitTime + \" sec for ephemeral node to be created\");\n if (waitTime > maxWaitSec) {\n throw new IllegalStateException(\"Failed to create ephemeral node\");\n }\n }\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n }", "protected void progressInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n long totalTimeS = (System.currentTimeMillis() - startTimeMs) / Time.MS_PER_SECOND;\n\n logger.info(tag + \" : scanned \" + scanned + \" and fetched \" + fetched + \" for store '\"\n + storageEngine.getName() + \"' partitionIds:\" + partitionIds + \" in \"\n + totalTimeS + \" s\");\n }\n }", "Response put(URI uri, InputStream instream, String contentType) {\n HttpConnection connection = Http.PUT(uri, contentType);\n\n connection.setRequestBody(instream);\n\n return executeToResponse(connection);\n }", "public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }", "public void setTimewarpInt(String timewarp) {\n\n try {\n m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue());\n } catch (Exception e) {\n m_userSettings.setTimeWarp(-1);\n }\n }", "public ItemRequest<Task> removeProject(String task) {\n \n String path = String.format(\"/tasks/%s/removeProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }" ]
Retrieves the class object for the class with the given name. @param name The class name @return The class object @throws ClassNotFoundException If the class is not on the classpath (the exception message contains the class name)
[ "public static Class getClass(String name) throws ClassNotFoundException\r\n {\r\n try\r\n {\r\n return Class.forName(name);\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ClassNotFoundException(name);\r\n }\r\n }" ]
[ "private void setCrosstabOptions() {\n\t\tif (djcross.isUseFullWidth()){\n\t\t\tjrcross.setWidth(layoutManager.getReport().getOptions().getPrintableWidth());\n\t\t} else {\n\t\t\tjrcross.setWidth(djcross.getWidth());\n\t\t}\n\t\tjrcross.setHeight(djcross.getHeight());\n\n\t\tjrcross.setColumnBreakOffset(djcross.getColumnBreakOffset());\n\n jrcross.setIgnoreWidth(djcross.isIgnoreWidth());\n\t}", "private <T> void add(EjbDescriptor<T> ejbDescriptor) {\n InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor);\n ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor);\n ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName());\n }", "public GroovyMethodDoc[] methods() {\n Collections.sort(methods);\n return methods.toArray(new GroovyMethodDoc[methods.size()]);\n }", "public int getJdbcType(String ojbType) throws SQLException\r\n {\r\n int result;\r\n if(ojbType == null) ojbType = \"\";\r\n\t\tojbType = ojbType.toLowerCase();\r\n if (ojbType.equals(\"bit\"))\r\n result = Types.BIT;\r\n else if (ojbType.equals(\"tinyint\"))\r\n result = Types.TINYINT;\r\n else if (ojbType.equals(\"smallint\"))\r\n result = Types.SMALLINT;\r\n else if (ojbType.equals(\"integer\"))\r\n result = Types.INTEGER;\r\n else if (ojbType.equals(\"bigint\"))\r\n result = Types.BIGINT;\r\n\r\n else if (ojbType.equals(\"float\"))\r\n result = Types.FLOAT;\r\n else if (ojbType.equals(\"real\"))\r\n result = Types.REAL;\r\n else if (ojbType.equals(\"double\"))\r\n result = Types.DOUBLE;\r\n\r\n else if (ojbType.equals(\"numeric\"))\r\n result = Types.NUMERIC;\r\n else if (ojbType.equals(\"decimal\"))\r\n result = Types.DECIMAL;\r\n\r\n else if (ojbType.equals(\"char\"))\r\n result = Types.CHAR;\r\n else if (ojbType.equals(\"varchar\"))\r\n result = Types.VARCHAR;\r\n else if (ojbType.equals(\"longvarchar\"))\r\n result = Types.LONGVARCHAR;\r\n\r\n else if (ojbType.equals(\"date\"))\r\n result = Types.DATE;\r\n else if (ojbType.equals(\"time\"))\r\n result = Types.TIME;\r\n else if (ojbType.equals(\"timestamp\"))\r\n result = Types.TIMESTAMP;\r\n\r\n else if (ojbType.equals(\"binary\"))\r\n result = Types.BINARY;\r\n else if (ojbType.equals(\"varbinary\"))\r\n result = Types.VARBINARY;\r\n else if (ojbType.equals(\"longvarbinary\"))\r\n result = Types.LONGVARBINARY;\r\n\r\n\t\telse if (ojbType.equals(\"clob\"))\r\n \t\tresult = Types.CLOB;\r\n\t\telse if (ojbType.equals(\"blob\"))\r\n\t\t\tresult = Types.BLOB;\r\n else\r\n throw new SQLException(\r\n \"The type '\"+ ojbType + \"' is not a valid jdbc type.\");\r\n return result;\r\n }", "public NodeT getNext() {\n String nextItemKey = queue.poll();\n if (nextItemKey == null) {\n return null;\n }\n return nodeTable.get(nextItemKey);\n }", "private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public static SlotReference getSlotReference(DataReference dataReference) {\n return getSlotReference(dataReference.player, dataReference.slot);\n }", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }", "private CmsMessageBundleEditorTypes.BundleType initBundleType() {\n\n String resourceTypeName = OpenCms.getResourceManager().getResourceType(m_resource).getTypeName();\n return CmsMessageBundleEditorTypes.BundleType.toBundleType(resourceTypeName);\n }" ]
This internal method is used to convert from a Date instance to an integer representing the number of minutes past midnight. @param date date instance @return minutes past midnight as an integer
[ "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 readResources()\n {\n for (MapRow row : getTable(\"RTAB\"))\n {\n Resource resource = m_projectFile.addResource();\n setFields(RESOURCE_FIELDS, row, resource);\n m_eventManager.fireResourceReadEvent(resource);\n // TODO: Correctly handle calendar\n }\n }", "public RedwoodConfiguration collapseExact(){\r\n tasks.add(new Runnable() { public void run() { Redwood.spliceHandler(VisibilityHandler.class, new RepeatedRecordHandler(RepeatedRecordHandler.EXACT), OutputHandler.class); } });\r\n return this;\r\n }", "public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroupbindings obj = new servicegroupbindings();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroupbindings response = (servicegroupbindings) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static onlinkipv6prefix[] get(nitro_service service) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tonlinkipv6prefix[] response = (onlinkipv6prefix[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response delete(nitro_service client, String Dnssuffix) throws Exception {\n\t\tdnssuffix deleteresource = new dnssuffix();\n\t\tdeleteresource.Dnssuffix = Dnssuffix;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "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 void setHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n ODO_HOST = hostName;\n BASE_URL = \"http://\" + ODO_HOST + \":\" + API_PORT + \"/\" + API_BASE + \"/\";\n }", "public static base_response add(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup addresource = new clusternodegroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.strict = resource.strict;\n\t\treturn addresource.add_resource(client);\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 }" ]
Sets the polling status. @param status the polling status. @param statusCode the HTTP status code @throws IllegalArgumentException thrown if status is null.
[ "PollingState<T> withStatus(String status, int statusCode) throws IllegalArgumentException {\n if (status == null) {\n throw new IllegalArgumentException(\"Status is null.\");\n }\n this.status = status;\n this.statusCode = statusCode;\n return this;\n }" ]
[ "public void start() {\n instanceLock.writeLock().lock();\n try {\n for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry :\n nsStreamers.entrySet()) {\n streamerEntry.getValue().start();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "public static base_response export(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata exportresource = new appfwlearningdata();\n\t\texportresource.profilename = resource.profilename;\n\t\texportresource.securitycheck = resource.securitycheck;\n\t\texportresource.target = resource.target;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}", "public static dbdbprofile get(nitro_service service, String name) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tobj.set_name(name);\n\t\tdbdbprofile response = (dbdbprofile) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setSessionTimeout(int timeout) {\n ((ZKBackend) getBackend()).setSessionTimeout(timeout);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Locator session timeout set to: \" + timeout);\n }\n }", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnssimpleacl clearresource = new nssimpleacl();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public ArrayList<Duration> segmentBaselineWork(ProjectFile file, List<TimephasedWork> work, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentWork(file.getBaselineCalendar(), work, rangeUnits, dateList);\n }", "public static base_responses enable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm enableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tenableresources[i] = new snmpalarm();\n\t\t\t\tenableresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}", "public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {\n MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();\n\n Object[] values = new Object[parameterInfoArray.length];\n String[] types = new String[parameterInfoArray.length];\n\n MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);\n\n for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {\n MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];\n String type = parameterInfo.getType();\n types[parameterNum] = type;\n values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);\n }\n\n return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);\n }", "public static sslparameter get(nitro_service service) throws Exception{\n\t\tsslparameter obj = new sslparameter();\n\t\tsslparameter[] response = (sslparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Stops the background stream thread.
[ "public void stop() {\n if (runnerThread == null) {\n return;\n }\n\n runnerThread.interrupt();\n\n nsLock.writeLock().lock();\n try {\n if (runnerThread == null) {\n return;\n }\n\n this.cancel();\n this.close();\n\n while (runnerThread.isAlive()) {\n runnerThread.interrupt();\n try {\n runnerThread.join(1000);\n } catch (final Exception e) {\n e.printStackTrace();\n return;\n }\n }\n runnerThread = null;\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n nsLock.writeLock().unlock();\n }\n }" ]
[ "private void createFrameset(File outputDirectory) throws Exception\n {\n VelocityContext context = createContext();\n generateFile(new File(outputDirectory, INDEX_FILE),\n INDEX_FILE + TEMPLATE_EXTENSION,\n context);\n }", "public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }", "public final int getJdbcType()\r\n {\r\n switch (this.fieldSource)\r\n {\r\n case SOURCE_FIELD :\r\n return this.getFieldRef().getJdbcType().getType();\r\n case SOURCE_NULL :\r\n return java.sql.Types.NULL;\r\n case SOURCE_VALUE :\r\n return java.sql.Types.VARCHAR;\r\n default :\r\n return java.sql.Types.NULL;\r\n }\r\n }", "public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public static String addFolderSlashIfNeeded(String folderName) {\n if (!\"\".equals(folderName) && !folderName.endsWith(\"/\")) {\n return folderName + \"/\";\n } else {\n return folderName;\n }\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 }", "public static base_responses add(nitro_service client, authenticationradiusaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tauthenticationradiusaction addresources[] = new authenticationradiusaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new authenticationradiusaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].serverport = resources[i].serverport;\n\t\t\t\taddresources[i].authtimeout = resources[i].authtimeout;\n\t\t\t\taddresources[i].radkey = resources[i].radkey;\n\t\t\t\taddresources[i].radnasip = resources[i].radnasip;\n\t\t\t\taddresources[i].radnasid = resources[i].radnasid;\n\t\t\t\taddresources[i].radvendorid = resources[i].radvendorid;\n\t\t\t\taddresources[i].radattributetype = resources[i].radattributetype;\n\t\t\t\taddresources[i].radgroupsprefix = resources[i].radgroupsprefix;\n\t\t\t\taddresources[i].radgroupseparator = resources[i].radgroupseparator;\n\t\t\t\taddresources[i].passencoding = resources[i].passencoding;\n\t\t\t\taddresources[i].ipvendorid = resources[i].ipvendorid;\n\t\t\t\taddresources[i].ipattributetype = resources[i].ipattributetype;\n\t\t\t\taddresources[i].accounting = resources[i].accounting;\n\t\t\t\taddresources[i].pwdvendorid = resources[i].pwdvendorid;\n\t\t\t\taddresources[i].pwdattributetype = resources[i].pwdattributetype;\n\t\t\t\taddresources[i].defaultauthenticationgroup = resources[i].defaultauthenticationgroup;\n\t\t\t\taddresources[i].callingstationid = resources[i].callingstationid;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}", "public void removeScript(int id) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
Helper method that encapsulates the minimum logic for publishing a job to a channel. @param jedis the connection to Redis @param namespace the Resque namespace @param channel the channel name @param jobJson the job serialized as JSON
[ "public static void doPublish(final Jedis jedis, final String namespace, final String channel, final String jobJson) {\n jedis.publish(JesqueUtils.createKey(namespace, CHANNEL, channel), jobJson);\n }" ]
[ "@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }", "public Jar setListAttribute(String name, Collection<?> values) {\n return setAttribute(name, join(values));\n }", "public static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }", "public RedwoodConfiguration hideChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.hideChannels(channels); } });\r\n return this;\r\n }", "public void copyNodeMetaData(ASTNode other) {\n if (other.metaDataMap == null) {\n return;\n }\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n metaDataMap.putAll(other.metaDataMap);\n }", "public static base_responses delete(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static base_responses unset(nitro_service client, String acl6name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 unsetresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tunsetresources[i] = new nsacl6();\n\t\t\t\tunsetresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "public 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 static float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }" ]
Try to link the declaration with the importerService referenced by the ServiceReference,. return true if they have been link together, false otherwise. @param declaration The Declaration @param declarationBinderRef The ServiceReference<S> of S @return true if they have been link together, false otherwise.
[ "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 }" ]
[ "public static boolean isTodoItem(final Document todoItemDoc) {\n return todoItemDoc.containsKey(ID_KEY)\n && todoItemDoc.containsKey(TASK_KEY)\n && todoItemDoc.containsKey(CHECKED_KEY);\n }", "private boolean fireEventWait(WebElement webElement, Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, InterruptedException {\n\t\tswitch (eventable.getEventType()) {\n\t\t\tcase click:\n\t\t\t\ttry {\n\t\t\t\t\twebElement.click();\n\t\t\t\t} catch (ElementNotVisibleException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (WebDriverException e) {\n\t\t\t\t\tthrowIfConnectionException(e);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase hover:\n\t\t\t\tLOGGER.info(\"EventType hover called but this isn't implemented yet\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tLOGGER.info(\"EventType {} not supported in WebDriver.\", eventable.getEventType());\n\t\t\t\treturn false;\n\t\t}\n\n\t\tThread.sleep(this.crawlWaitEvent);\n\t\treturn true;\n\t}", "public static nslimitidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tobj.set_name(name);\n\t\tnslimitidentifier_stats response = (nslimitidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "@Nonnull\n\tpublic static InterfaceAnalysis analyze(@Nonnull final String code) {\n\t\tCheck.notNull(code, \"code\");\n\n\t\tfinal CompilationUnit unit = Check.notNull(SourceCodeReader.parse(code), \"compilationUnit\");\n\t\tfinal List<TypeDeclaration> types = Check.notEmpty(unit.getTypes(), \"typeDeclarations\");\n\t\tCheck.stateIsTrue(types.size() == 1, \"only one interface declaration per analysis is supported\");\n\n\t\tfinal ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) types.get(0);\n\n\t\tfinal Imports imports = SourceCodeReader.findImports(unit.getImports());\n\t\tfinal Package pkg = unit.getPackage() != null ? new Package(unit.getPackage().getName().toString()) : Package.UNDEFINED;\n\t\tfinal List<Annotation> annotations = SourceCodeReader.findAnnotations(type.getAnnotations(), imports);\n\t\tfinal List<Method> methods = SourceCodeReader.findMethods(type.getMembers(), imports);\n\t\tCheck.stateIsTrue(!hasPossibleMutatingMethods(methods), \"The passed interface '%s' seems to have mutating methods\", type.getName());\n\t\tfinal List<Interface> extendsInterfaces = SourceCodeReader.findExtends(type);\n\t\tfinal String interfaceName = type.getName();\n\t\treturn new ImmutableInterfaceAnalysis(annotations, extendsInterfaces, imports.asList(), interfaceName, methods, pkg);\n\t}", "public ProjectCalendar getBaselineCalendar()\n {\n //\n // Attempt to locate the calendar normally used by baselines\n // If this isn't present, fall back to using the default\n // project calendar.\n //\n ProjectCalendar result = getCalendarByName(\"Used for Microsoft Project 98 Baseline Calendar\");\n if (result == null)\n {\n result = getDefaultCalendar();\n }\n return result;\n }", "public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}", "public StackTraceElement[] asStackTrace() {\n\t\tint i = 1;\n\t\tStackTraceElement[] list = new StackTraceElement[this.size()];\n\t\tfor (Eventable e : this) {\n\t\t\tlist[this.size() - i] =\n\t\t\t\t\tnew StackTraceElement(e.getEventType().toString(), e.getIdentification()\n\t\t\t\t\t\t\t.toString(), e.getElement().toString(), i);\n\t\t\ti++;\n\t\t}\n\t\treturn list;\n\t}", "protected void finishBox()\n {\n \tif (textLine.length() > 0)\n \t{\n String s;\n if (isReversed(Character.getDirectionality(textLine.charAt(0))))\n s = textLine.reverse().toString();\n else\n s = textLine.toString();\n\n curstyle.setLeft(textMetrics.getX());\n curstyle.setTop(textMetrics.getTop());\n curstyle.setLineHeight(textMetrics.getHeight());\n\n\t renderText(s, textMetrics);\n\t textLine = new StringBuilder();\n\t textMetrics = null;\n \t}\n }", "public static void putUnsignedInt(ByteBuffer buffer, int index, long value) {\n buffer.putInt(index, (int) (value & 0xffffffffL));\n }" ]
If an error is thrown while loading zone data, the exception is logged to system error and null is returned for this and all future requests. @param id the id to load @return the loaded zone
[ "public DateTimeZone getZone(String id) {\n if (id == null) {\n return null;\n }\n\n Object obj = iZoneInfoMap.get(id);\n if (obj == null) {\n return null;\n }\n\n if (id.equals(obj)) {\n // Load zone data for the first time.\n return loadZoneData(id);\n }\n\n if (obj instanceof SoftReference<?>) {\n @SuppressWarnings(\"unchecked\")\n SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;\n DateTimeZone tz = ref.get();\n if (tz != null) {\n return tz;\n }\n // Reference cleared; load data again.\n return loadZoneData(id);\n }\n\n // If this point is reached, mapping must link to another.\n return getZone((String) obj);\n }" ]
[ "public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {\n int points = DEFAULT_ARC_POINTS;\n\n MVCArray res = new MVCArray();\n\n if (startBearing > endBearing) {\n endBearing += 360.0;\n }\n double deltaBearing = endBearing - startBearing;\n deltaBearing = deltaBearing / points;\n for (int i = 0; (i < points + 1); i++) {\n res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));\n }\n\n return res;\n\n }", "@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }", "public synchronized void unregisterJmxIfRequired() {\n referenceCount--;\n if (isRegistered == true && referenceCount <= 0) {\n JmxUtils.unregisterMbean(this.jmxObjectName);\n isRegistered = false;\n }\n }", "@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}", "public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}", "private static boolean containsObject(Object searchFor, Object[] searchIn)\r\n {\r\n for (int i = 0; i < searchIn.length; i++)\r\n {\r\n if (searchFor == searchIn[i])\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }", "public static String formatDateRange(Context context, ReadablePartial start, ReadablePartial end, int flags) {\n return formatDateRange(context, toMillis(start), toMillis(end), flags);\n }", "private void processProperties(XMLStreamWriter writer, Set<Method> methodSet, Class<?> aClass) throws IntrospectionException, XMLStreamException\n {\n BeanInfo beanInfo = Introspector.getBeanInfo(aClass, aClass.getSuperclass());\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\n for (int i = 0; i < propertyDescriptors.length; i++)\n {\n PropertyDescriptor propertyDescriptor = propertyDescriptors[i];\n if (propertyDescriptor.getPropertyType() != null)\n {\n String name = propertyDescriptor.getName();\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n\n String readMethodName = readMethod == null ? null : readMethod.getName();\n String writeMethodName = writeMethod == null ? null : writeMethod.getName();\n addProperty(writer, name, propertyDescriptor.getPropertyType(), readMethodName, writeMethodName);\n\n if (readMethod != null)\n {\n methodSet.add(readMethod);\n }\n\n if (writeMethod != null)\n {\n methodSet.add(writeMethod);\n }\n }\n else\n {\n processAmbiguousProperty(writer, methodSet, aClass, propertyDescriptor);\n }\n }\n }" ]
Send an empty request using a standard HTTP connection.
[ "private void sendEmptyRequest(String path, String method) throws DatastoreEmulatorException {\n HttpURLConnection connection = null;\n try {\n URL url = new URL(this.host + path);\n connection = (HttpURLConnection) url.openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(method);\n connection.getOutputStream().close();\n if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {\n throw new DatastoreEmulatorException(\n String.format(\n \"%s request to %s returned HTTP status %s\",\n method, path, connection.getResponseCode()));\n }\n } catch (IOException e) {\n throw new DatastoreEmulatorException(\n String.format(\"Exception connecting to emulator on %s request to %s\", method, path), e);\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }" ]
[ "public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }", "public Bundler put(String key, String value) {\n delegate.putString(key, value);\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 ItemRequest<Project> addFollowers(String project) {\n \n String path = String.format(\"/projects/%s/addFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "private ResourceField selectField(ResourceField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }", "public void setEnable(boolean flag) {\n if (flag == mIsEnabled)\n return;\n\n mIsEnabled = flag;\n\n if (getNative() != 0)\n {\n NativeComponent.setEnable(getNative(), flag);\n }\n if (flag)\n {\n onEnable();\n }\n else\n {\n onDisable();\n }\n }", "private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }", "public static base_responses add(nitro_service client, cacheselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheselector addresources[] = new cacheselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cacheselector();\n\t\t\t\taddresources[i].selectorname = resources[i].selectorname;\n\t\t\t\taddresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static TestCaseStartedEvent withExecutorInfo(TestCaseStartedEvent event) {\n event.getLabels().add(createHostLabel(getHostname()));\n event.getLabels().add(createThreadLabel(format(\"%s.%s(%s)\",\n ManagementFactory.getRuntimeMXBean().getName(),\n Thread.currentThread().getName(),\n Thread.currentThread().getId())\n ));\n return event;\n }" ]
converts a java.net.URI into a string representation with empty authority, if absent and has file scheme.
[ "public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\n }" ]
[ "public void addAll(OptionsContainerBuilder container) {\n\t\tfor ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {\n\t\t\taddAll( entry.getKey(), entry.getValue().build() );\n\t\t}\n\t}", "protected BufferedImage createErrorImage(final Rectangle area) {\n final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);\n final Graphics2D graphics = bufferedImage.createGraphics();\n try {\n graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));\n graphics.clearRect(0, 0, area.width, area.height);\n return bufferedImage;\n } finally {\n graphics.dispose();\n }\n }", "public static base_response delete(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private FormInput formInputMatchingNode(Node element) {\n\t\tNamedNodeMap attributes = element.getAttributes();\n\t\tIdentification id;\n\n\t\tif (attributes.getNamedItem(\"id\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.id,\n\t\t\t\t\tattributes.getNamedItem(\"id\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tif (attributes.getNamedItem(\"name\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.name,\n\t\t\t\t\tattributes.getNamedItem(\"name\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tString xpathExpr = XPathHelper.getXPathExpression(element);\n\t\tif (xpathExpr != null && !xpathExpr.equals(\"\")) {\n\t\t\tid = new Identification(Identification.How.xpath, xpathExpr);\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public static base_response unset(nitro_service client, nsacl6 resource, String[] args) throws Exception{\n\t\tnsacl6 unsetresource = new nsacl6();\n\t\tunsetresource.acl6name = resource.acl6name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "Map<UUID, UUID> getActivityCodes(Activity activity)\n {\n Map<UUID, UUID> map = m_activityCodeCache.get(activity);\n if (map == null)\n {\n map = new HashMap<UUID, UUID>();\n m_activityCodeCache.put(activity, map);\n for (CodeAssignment ca : activity.getCodeAssignment())\n {\n UUID code = getUUID(ca.getCodeUuid(), ca.getCode());\n UUID value = getUUID(ca.getValueUuid(), ca.getValue());\n map.put(code, value);\n }\n }\n return map;\n }", "public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) {\n return self.toString().replaceFirst(regex.toString(), replacement.toString());\n }", "public static void validateCurrentFinalCluster(final Cluster currentCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(currentCluster, finalCluster);\n validateClusterNodeState(currentCluster, finalCluster);\n\n return;\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 }" ]
Send message to all connections of a certain user @param message the message to be sent @param username the username @return this context
[ "public WebSocketContext sendToUser(String message, String username) {\n return sendToConnections(message, username, manager.usernameRegistry(), true);\n }" ]
[ "private void plan() {\n // Mapping of stealer node to list of primary partitions being moved\n final TreeMultimap<Integer, Integer> stealerToStolenPrimaryPartitions = TreeMultimap.create();\n\n // Output initial and final cluster\n if(outputDir != null)\n RebalanceUtils.dumpClusters(currentCluster, finalCluster, outputDir);\n\n // Determine which partitions must be stolen\n for(Node stealerNode: finalCluster.getNodes()) {\n List<Integer> stolenPrimaryPartitions = RebalanceUtils.getStolenPrimaryPartitions(currentCluster,\n finalCluster,\n stealerNode.getId());\n if(stolenPrimaryPartitions.size() > 0) {\n numPrimaryPartitionMoves += stolenPrimaryPartitions.size();\n stealerToStolenPrimaryPartitions.putAll(stealerNode.getId(),\n stolenPrimaryPartitions);\n }\n }\n\n // Determine plan batch-by-batch\n int batches = 0;\n Cluster batchCurrentCluster = Cluster.cloneCluster(currentCluster);\n List<StoreDefinition> batchCurrentStoreDefs = this.currentStoreDefs;\n List<StoreDefinition> batchFinalStoreDefs = this.finalStoreDefs;\n Cluster batchFinalCluster = RebalanceUtils.getInterimCluster(this.currentCluster,\n this.finalCluster);\n\n while(!stealerToStolenPrimaryPartitions.isEmpty()) {\n\n int partitions = 0;\n List<Entry<Integer, Integer>> partitionsMoved = Lists.newArrayList();\n for(Entry<Integer, Integer> stealerToPartition: stealerToStolenPrimaryPartitions.entries()) {\n partitionsMoved.add(stealerToPartition);\n batchFinalCluster = UpdateClusterUtils.createUpdatedCluster(batchFinalCluster,\n stealerToPartition.getKey(),\n Lists.newArrayList(stealerToPartition.getValue()));\n partitions++;\n if(partitions == batchSize)\n break;\n }\n\n // Remove the partitions moved\n for(Iterator<Entry<Integer, Integer>> partitionMoved = partitionsMoved.iterator(); partitionMoved.hasNext();) {\n Entry<Integer, Integer> entry = partitionMoved.next();\n stealerToStolenPrimaryPartitions.remove(entry.getKey(), entry.getValue());\n }\n\n if(outputDir != null)\n RebalanceUtils.dumpClusters(batchCurrentCluster,\n batchFinalCluster,\n outputDir,\n \"batch-\" + Integer.toString(batches) + \".\");\n\n // Generate a plan to compute the tasks\n final RebalanceBatchPlan RebalanceBatchPlan = new RebalanceBatchPlan(batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs);\n batchPlans.add(RebalanceBatchPlan);\n\n numXZonePartitionStoreMoves += RebalanceBatchPlan.getCrossZonePartitionStoreMoves();\n numPartitionStoreMoves += RebalanceBatchPlan.getPartitionStoreMoves();\n nodeMoveMap.add(RebalanceBatchPlan.getNodeMoveMap());\n zoneMoveMap.add(RebalanceBatchPlan.getZoneMoveMap());\n\n batches++;\n batchCurrentCluster = Cluster.cloneCluster(batchFinalCluster);\n // batchCurrentStoreDefs can only be different from\n // batchFinalStoreDefs for the initial batch.\n batchCurrentStoreDefs = batchFinalStoreDefs;\n }\n\n logger.info(this);\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 }", "private String getDynamicAttributeValue(\n CmsFile file,\n I_CmsXmlContentValue value,\n String attributeName,\n CmsEntity editedLocalEntity) {\n\n if ((null != editedLocalEntity) && (editedLocalEntity.getAttribute(attributeName) != null)) {\n getSessionCache().setDynamicValue(\n attributeName,\n editedLocalEntity.getAttribute(attributeName).getSimpleValue());\n }\n String currentValue = getSessionCache().getDynamicValue(attributeName);\n if (null != currentValue) {\n return currentValue;\n }\n if (null != file) {\n if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) {\n List<CmsCategory> categories = new ArrayList<CmsCategory>(0);\n try {\n categories = CmsCategoryService.getInstance().readResourceCategories(getCmsObject(), file);\n } catch (CmsException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e);\n }\n I_CmsWidget widget = null;\n widget = CmsWidgetUtil.collectWidgetInfo(value).getWidget();\n if ((null != widget) && (widget instanceof CmsCategoryWidget)) {\n String mainCategoryPath = ((CmsCategoryWidget)widget).getStartingCategory(\n getCmsObject(),\n getCmsObject().getSitePath(file));\n StringBuffer pathes = new StringBuffer();\n for (CmsCategory category : categories) {\n if (category.getPath().startsWith(mainCategoryPath)) {\n String path = category.getBasePath() + category.getPath();\n path = getCmsObject().getRequestContext().removeSiteRoot(path);\n pathes.append(path).append(',');\n }\n }\n String dynamicConfigString = pathes.length() > 0 ? pathes.substring(0, pathes.length() - 1) : \"\";\n getSessionCache().setDynamicValue(attributeName, dynamicConfigString);\n return dynamicConfigString;\n }\n }\n }\n return \"\";\n\n }", "private void updateLetsEncrypt() {\n\n getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0));\n\n CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig();\n if ((config == null) || !config.isValidAndEnabled()) {\n return;\n }\n CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config);\n boolean ok = converter.run(getReport(), OpenCms.getSiteManager());\n if (ok) {\n getReport().println(\n org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0),\n I_CmsReport.FORMAT_OK);\n }\n\n }", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "private void addToGraph(ClassDoc cd) {\n\t// avoid adding twice the same class, but don't rely on cg.getClassInfo\n\t// since there are other ways to add a classInfor than printing the class\n\tif (visited.contains(cd.toString()))\n\t return;\n\n\tvisited.add(cd.toString());\n\tcg.printClass(cd, false);\n\tcg.printRelations(cd);\n\tif (opt.inferRelationships)\n\t cg.printInferredRelations(cd);\n\tif (opt.inferDependencies)\n\t cg.printInferredDependencies(cd);\n }", "private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) {\n\t\treturn IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString())\n\t\t\t\t.shouldDeleteMessages(this.properties.isDelete())\n\t\t\t\t.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead()));\n\t}", "public synchronized boolean put(byte value) {\n if (available == capacity) {\n return false;\n }\n buffer[idxPut] = value;\n idxPut = (idxPut + 1) % capacity;\n available++;\n return true;\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 }" ]
is there a faster algorithm out there? This one is a bit sluggish
[ "public static DMatrixRMaj[] span(int dimen, int numVectors , Random rand ) {\n if( dimen < numVectors )\n throw new IllegalArgumentException(\"The number of vectors must be less than or equal to the dimension\");\n\n DMatrixRMaj u[] = new DMatrixRMaj[numVectors];\n\n u[0] = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);\n NormOps_DDRM.normalizeF(u[0]);\n\n for( int i = 1; i < numVectors; i++ ) {\n// System.out.println(\" i = \"+i);\n DMatrixRMaj a = new DMatrixRMaj(dimen,1);\n DMatrixRMaj r=null;\n\n for( int j = 0; j < i; j++ ) {\n// System.out.println(\"j = \"+j);\n if( j == 0 )\n r = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);\n\n // find a vector that is normal to vector j\n // u[i] = (1/2)*(r + Q[j]*r)\n a.set(r);\n VectorVectorMult_DDRM.householder(-2.0,u[j],r,a);\n CommonOps_DDRM.add(r,a,a);\n CommonOps_DDRM.scale(0.5,a);\n\n// UtilEjml.print(a);\n\n DMatrixRMaj t = a;\n a = r;\n r = t;\n\n // normalize it so it doesn't get too small\n double val = NormOps_DDRM.normF(r);\n if( val == 0 || Double.isNaN(val) || Double.isInfinite(val))\n throw new RuntimeException(\"Failed sanity check\");\n CommonOps_DDRM.divide(r,val);\n }\n\n u[i] = r;\n }\n\n return u;\n }" ]
[ "@Override\n\tpublic Integer getPrefixLengthForSingleBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tInteger divPrefix = div.getPrefixLengthForSingleBlock();\n\t\t\tif(divPrefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\ttotalPrefix += divPrefix;\n\t\t\tif(divPrefix < div.getBitCount()) {\n\t\t\t\t//remaining segments must be full range or we return null\n\t\t\t\tfor(i++; i < count; i++) {\n\t\t\t\t\tAddressDivisionBase laterDiv = getDivision(i);\n\t\t\t\t\tif(!laterDiv.isFullRange()) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cacheBits(totalPrefix);\n\t}", "public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }", "private long getTime(Date start1, Date end1, Date start2, Date end2)\n {\n long total = 0;\n\n if (start1 != null && end1 != null && start2 != null && end2 != null)\n {\n long start;\n long end;\n\n if (start1.getTime() < start2.getTime())\n {\n start = start2.getTime();\n }\n else\n {\n start = start1.getTime();\n }\n\n if (end1.getTime() < end2.getTime())\n {\n end = end1.getTime();\n }\n else\n {\n end = end2.getTime();\n }\n\n if (start < end)\n {\n total = end - start;\n }\n }\n\n return (total);\n }", "public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) {\n\t\tfinal DbModule module = getModule(dbArtifact);\n\t\tif(module == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tfinal String jenkinsJobUrl = module.getBuildInfo().get(\"jenkins-job-url\");\n\t\t\n\t\tif(jenkinsJobUrl == null){\n\t\t\treturn \"\";\t\t\t\n\t\t}\n\n\t\treturn jenkinsJobUrl;\n\t}", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getTimeElapsed() {\n int currentSession = getCurrentSession();\n if (currentSession == 0) return -1;\n\n int now = (int) (System.currentTimeMillis() / 1000);\n return now - currentSession;\n }", "public void add(Map<String, Object> map) throws SQLException {\n if (withinDataSetBatch) {\n if (batchData.size() == 0) {\n batchKeys = map.keySet();\n } else {\n if (!map.keySet().equals(batchKeys)) {\n throw new IllegalArgumentException(\"Inconsistent keys found for batch add!\");\n }\n }\n batchData.add(map);\n return;\n }\n int answer = executeUpdate(buildListQuery(map), new ArrayList<Object>(map.values()));\n if (answer != 1) {\n LOG.warning(\"Should have updated 1 row not \" + answer + \" when trying to add: \" + map);\n }\n }", "public double getRate(AnalyticModel model) {\n\t\tif(model==null) {\n\t\t\tthrow new IllegalArgumentException(\"model==null\");\n\t\t}\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve==null) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve of name '\" + forwardCurveName + \"' found in given model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble fixingDate = schedule.getFixing(0);\n\t\treturn forwardCurve.getForward(model,fixingDate);\n\t}", "static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }", "@UiHandler(\"m_atNumber\")\r\n void onWeekOfMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekOfMonth(event.getValue());\r\n }\r\n }" ]
Reads basic summary details from the project properties. @param file MPX file
[ "private static void listProjectProperties(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n ProjectProperties properties = file.getProjectProperties();\n Date startDate = properties.getStartDate();\n Date finishDate = properties.getFinishDate();\n String formattedStartDate = startDate == null ? \"(none)\" : df.format(startDate);\n String formattedFinishDate = finishDate == null ? \"(none)\" : df.format(finishDate);\n\n System.out.println(\"MPP file type: \" + properties.getMppFileType());\n System.out.println(\"Project Properties: StartDate=\" + formattedStartDate + \" FinishDate=\" + formattedFinishDate);\n System.out.println();\n }" ]
[ "@Override\n public boolean decompose(DMatrixRMaj orig) {\n if( orig.numCols != orig.numRows )\n throw new IllegalArgumentException(\"Matrix must be square.\");\n if( orig.numCols <= 0 )\n return false;\n\n int N = orig.numRows;\n\n // compute a similar tridiagonal matrix\n if( !decomp.decompose(orig) )\n return false;\n\n if( diag == null || diag.length < N) {\n diag = new double[N];\n off = new double[N-1];\n }\n decomp.getDiagonal(diag,off);\n\n // Tell the helper to work with this matrix\n helper.init(diag,off,N);\n\n if( computeVectors ) {\n if( computeVectorsWithValues ) {\n return extractTogether();\n } else {\n return extractSeparate(N);\n }\n } else {\n return computeEigenValues();\n }\n }", "public void removeFilter(String filterName)\n {\n Filter filter = getFilterByName(filterName);\n if (filter != null)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.remove(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.remove(filter);\n }\n m_filtersByName.remove(filterName);\n m_filtersByID.remove(filter.getID());\n }\n }", "public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,\n zoneId);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n boolean first = true;\n Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());\n for(int initPartitionId: sortedInitPartitionIds) {\n if(!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n\n int runLength = idToRunLength.get(initPartitionId);\n if(runLength == 1) {\n sb.append(initPartitionId);\n } else {\n int endPartitionId = (initPartitionId + runLength - 1)\n % cluster.getNumberOfPartitions();\n sb.append(initPartitionId).append(\"-\").append(endPartitionId);\n }\n }\n sb.append(\"]\");\n\n return sb.toString();\n }", "public CollectionRequest<Tag> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/tags\", workspace);\n return new CollectionRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "@Override\n public boolean supportsNativeRotation() {\n return this.params.useNativeAngle &&\n (this.params.serverType == WmsLayerParam.ServerType.MAPSERVER ||\n this.params.serverType == WmsLayerParam.ServerType.GEOSERVER);\n }", "private void registerSynchronization(TransactionImpl odmgTrans, Transaction transaction)\r\n {\r\n // todo only need for development\r\n if (odmgTrans == null || transaction == null)\r\n {\r\n log.error(\"One of the given parameters was null --> cannot do synchronization!\" +\r\n \" omdg transaction was null: \" + (odmgTrans == null) +\r\n \", external transaction was null: \" + (transaction == null));\r\n return;\r\n }\r\n\r\n int status = -1; // default status.\r\n try\r\n {\r\n status = transaction.getStatus();\r\n if (status != Status.STATUS_ACTIVE)\r\n {\r\n throw new OJBRuntimeException(\r\n \"Transaction synchronization failed - wrong status of external container tx: \" +\r\n getStatusString(status));\r\n }\r\n }\r\n catch (SystemException e)\r\n {\r\n throw new OJBRuntimeException(\"Can't read status of external tx\", e);\r\n }\r\n\r\n try\r\n {\r\n //Sequence of the following method calls is significant\r\n // 1. register the synchronization with the ODMG notion of a transaction.\r\n transaction.registerSynchronization((J2EETransactionImpl) odmgTrans);\r\n // 2. mark the ODMG transaction as being in a JTA Transaction\r\n // Associate external transaction with the odmg transaction.\r\n txRepository.set(new TxBuffer(odmgTrans, transaction));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Cannot associate PersistenceBroker with running Transaction\", e);\r\n throw new OJBRuntimeException(\r\n \"Transaction synchronization failed - wrong status of external container tx\", e);\r\n }\r\n }", "private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }", "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 }", "public void handle(HttpRequest request, HttpResponder responder) {\n if (urlRewriter != null) {\n try {\n request.setUri(URI.create(request.uri()).normalize().toString());\n if (!urlRewriter.rewrite(request, responder)) {\n return;\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\",\n t.getMessage()));\n LOG.error(\"Exception thrown during rewriting of uri {}\", request.uri(), t);\n return;\n }\n }\n\n try {\n String path = URI.create(request.uri()).normalize().getPath();\n\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations\n = patternRouter.getDestinations(path);\n\n PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination =\n getMatchedDestination(routableDestinations, request.method(), path);\n\n if (matchedDestination != null) {\n //Found a httpresource route to it.\n HttpResourceModel httpResourceModel = matchedDestination.getDestination();\n\n // Call preCall method of handler hooks.\n boolean terminated = false;\n HandlerInfo info = new HandlerInfo(httpResourceModel.getMethod().getDeclaringClass().getName(),\n httpResourceModel.getMethod().getName());\n for (HandlerHook hook : handlerHooks) {\n if (!hook.preCall(request, responder, info)) {\n // Terminate further request processing if preCall returns false.\n terminated = true;\n break;\n }\n }\n\n // Call httpresource method\n if (!terminated) {\n // Wrap responder to make post hook calls.\n responder = new WrappedHttpResponder(responder, handlerHooks, request, info);\n if (httpResourceModel.handle(request, responder, matchedDestination.getGroupNameValues()).isStreaming()) {\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Body Consumer not supported for internalHttpResponder: %s\",\n request.uri()));\n }\n }\n } else if (routableDestinations.size() > 0) {\n //Found a matching resource but could not find the right HttpMethod so return 405\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n } else {\n responder.sendString(HttpResponseStatus.NOT_FOUND, String.format(\"Problem accessing: %s. Reason: Not Found\",\n request.uri()));\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\", t.getMessage()));\n LOG.error(\"Exception thrown during request processing for uri {}\", request.uri(), t);\n }\n }" ]
New REST client uses new REST service
[ "public void useNewRESTService(String address) throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n org.customer.service.CustomerService customerService = JAXRSClientFactory\n .createFromModel(address, \n org.customer.service.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using new RESTful CustomerService with new client\");\n\n customer.v2.Customer customer = createNewCustomer(\"Smith New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith New REST\");\n printNewCustomerDetails(customer);\n }" ]
[ "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 }", "@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}", "@Override\n public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type)\n {\n pipelineCriteria.add(new QueryGremlinCriterion()\n {\n @Override\n public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline)\n {\n pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get()));\n }\n });\n return this;\n }", "@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }", "public static Object findResult(Object self, Object defaultResult, Closure closure) {\n Object result = findResult(self, closure);\n if (result == null) return defaultResult;\n return result;\n }", "public static base_responses unset(nitro_service client, Long clid[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance unsetresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tunsetresources[i] = new clusterinstance();\n\t\t\t\tunsetresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "public static rnatparam get(nitro_service service) throws Exception{\n\t\trnatparam obj = new rnatparam();\n\t\trnatparam[] response = (rnatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public FormInput inputField(InputType type, Identification identification) {\r\n\t\tFormInput input = new FormInput(type, identification);\r\n\t\tthis.formInputs.add(input);\r\n\t\treturn input;\r\n\t}" ]
Print a timestamp value. @param value time value @return time value
[ "public static final String printTimestamp(Date value)\n {\n return (value == null ? null : TIMESTAMP_FORMAT.get().format(value));\n }" ]
[ "public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }", "public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }", "public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }", "static void processServerConfig(final Resource root, final RequiredConfigurationHolder requiredConfigurationHolder, final IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo serverConfig, final ExtensionRegistry extensionRegistry) {\n\n final Set<String> serverGroups = requiredConfigurationHolder.serverGroups;\n final Set<String> socketBindings = requiredConfigurationHolder.socketBindings;\n\n String sbg = serverConfig.getSocketBindingGroup();\n if (sbg != null && !socketBindings.contains(sbg)) {\n processSocketBindingGroup(root, sbg, requiredConfigurationHolder);\n }\n\n final String groupName = serverConfig.getServerGroup();\n final PathElement groupElement = PathElement.pathElement(SERVER_GROUP, groupName);\n // Also check the root, since this also gets executed on the slave which may not have the server-group configured yet\n if (!serverGroups.contains(groupName) && root.hasChild(groupElement)) {\n\n final Resource serverGroup = root.getChild(groupElement);\n final ModelNode groupModel = serverGroup.getModel();\n serverGroups.add(groupName);\n\n // Include the socket binding groups\n if (groupModel.hasDefined(SOCKET_BINDING_GROUP)) {\n final String socketBindingGroup = groupModel.get(SOCKET_BINDING_GROUP).asString();\n processSocketBindingGroup(root, socketBindingGroup, requiredConfigurationHolder);\n }\n\n final String profileName = groupModel.get(PROFILE).asString();\n processProfile(root, profileName, requiredConfigurationHolder, extensionRegistry);\n }\n }", "private void requestBlock() {\n next = ByteBuffer.allocate(blockSizeBytes);\n long requestTimeout = retryParams.getRequestTimeoutMillisForCurrentAttempt();\n pendingFetch = raw.readObjectAsync(next, filename, fetchPosition, requestTimeout);\n }", "public void read(byte[] holder) throws ProtocolException {\r\n int readTotal = 0;\r\n try {\r\n while (readTotal < holder.length) {\r\n int count = input.read(holder, readTotal, holder.length - readTotal);\r\n if (count == -1) {\r\n throw new ProtocolException(\"Unexpected end of stream.\");\r\n }\r\n readTotal += count;\r\n }\r\n // Unset the next char.\r\n nextSeen = false;\r\n nextChar = 0;\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Error reading from stream.\", e);\r\n }\r\n }", "public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null)\n {\n throw new IllegalArgumentException(\"Variable \\\"\" + name\n + \"\\\" has already been assigned and cannot be reassigned\");\n }\n\n frame.put(name, frames);\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 static Key toKey(RowColumn rc) {\n if ((rc == null) || (rc.getRow().equals(Bytes.EMPTY))) {\n return null;\n }\n Text row = ByteUtil.toText(rc.getRow());\n if ((rc.getColumn().equals(Column.EMPTY)) || !rc.getColumn().isFamilySet()) {\n return new Key(row);\n }\n Text cf = ByteUtil.toText(rc.getColumn().getFamily());\n if (!rc.getColumn().isQualifierSet()) {\n return new Key(row, cf);\n }\n Text cq = ByteUtil.toText(rc.getColumn().getQualifier());\n if (!rc.getColumn().isVisibilitySet()) {\n return new Key(row, cf, cq);\n }\n Text cv = ByteUtil.toText(rc.getColumn().getVisibility());\n return new Key(row, cf, cq, cv);\n }" ]
Returns code number of Task field supplied. @param field - name @return - code no
[ "private int getTaskCode(String field) throws MPXJException\n {\n Integer result = m_taskNumbers.get(field.trim());\n\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TASK_FIELD_NAME + \" \" + field);\n }\n\n return (result.intValue());\n }" ]
[ "public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException {\n\t\t// Calculate new derivatives. Note that this method is called only with\n\t\t// parameters = parameterCurrent, so we may use valueCurrent.\n\n\t\tVector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length);\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\tfinal double[] parametersNew\t= parameters.clone();\n\t\t\tfinal double[] derivative\t\t= derivatives[parameterIndex];\n\n\t\t\tfinal int workerParameterIndex = parameterIndex;\n\t\t\tCallable<double[]> worker = new Callable<double[]>() {\n\t\t\t\tpublic double[] call() {\n\t\t\t\t\tdouble parameterFiniteDifference;\n\t\t\t\t\tif(parameterSteps != null) {\n\t\t\t\t\t\tparameterFiniteDifference = parameterSteps[workerParameterIndex];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try to adaptively set a parameter shift. Note that in some\n\t\t\t\t\t\t * applications it may be important to set parameterSteps.\n\t\t\t\t\t\t * appropriately.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tparameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Shift parameter value\n\t\t\t\t\tparametersNew[workerParameterIndex] += parameterFiniteDifference;\n\n\t\t\t\t\t// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsetValues(parametersNew, derivative);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// We signal an exception to calculate the derivative as NaN\n\t\t\t\t\t\tArrays.fill(derivative, Double.NaN);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) {\n\t\t\t\t\t\tderivative[valueIndex] -= valueCurrent[valueIndex];\n\t\t\t\t\t\tderivative[valueIndex] /= parameterFiniteDifference;\n\t\t\t\t\t\tif(Double.isNaN(derivative[valueIndex])) {\n\t\t\t\t\t\t\tderivative[valueIndex] = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn derivative;\n\t\t\t\t}\n\t\t\t};\n\t\t\tif(executor != null) {\n\t\t\t\tFuture<double[]> valueFuture = executor.submit(worker);\n\t\t\t\tvalueFutures.add(parameterIndex, valueFuture);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tFutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker);\n\t\t\t\tvalueFutureTask.run();\n\t\t\t\tvalueFutures.add(parameterIndex, valueFutureTask);\n\t\t\t}\n\t\t}\n\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\ttry {\n\t\t\t\tderivatives[parameterIndex] = valueFutures.get(parameterIndex).get();\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t}\n\t\t}\n\t}", "private ColorItem buildColorItem(int colorId, String label) {\n Color color;\n String colorName;\n switch (colorId) {\n case 0:\n color = new Color(0, 0, 0, 0);\n colorName = \"No Color\";\n break;\n case 1:\n color = Color.PINK;\n colorName = \"Pink\";\n break;\n case 2:\n color = Color.RED;\n colorName = \"Red\";\n break;\n case 3:\n color = Color.ORANGE;\n colorName = \"Orange\";\n break;\n case 4:\n color = Color.YELLOW;\n colorName = \"Yellow\";\n break;\n case 5:\n color = Color.GREEN;\n colorName = \"Green\";\n break;\n case 6:\n color = Color.CYAN;\n colorName = \"Aqua\";\n break;\n case 7:\n color = Color.BLUE;\n colorName = \"Blue\";\n break;\n case 8:\n color = new Color(128, 0, 128);\n colorName = \"Purple\";\n break;\n default:\n color = new Color(0, 0, 0, 0);\n colorName = \"Unknown Color\";\n }\n return new ColorItem(colorId, label, color, colorName);\n }", "public static <T> T createObject(final Class<T> clazz, final Object... args) throws NoSuchConstructorException,\n AmbiguousConstructorException, ReflectiveOperationException {\n return findConstructor(clazz, args).newInstance(args);\n }", "boolean undoChanges() {\n final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY);\n if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) {\n // Was actually completed already\n return false;\n }\n PatchingTaskContext.Mode currentMode = this.mode;\n mode = PatchingTaskContext.Mode.UNDO;\n final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null);\n // Undo changes for the identity\n undoChanges(identityEntry, loader);\n // TODO maybe check if we need to do something for the layers too !?\n if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) {\n // For apply the state needs to be invalidate\n // For rollback the files are invalidated as part of the tasks\n final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY;\n for (final File file : moduleInvalidations) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, mode);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n if(!modulesToReenable.isEmpty()) {\n for (final File file : modulesToReenable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n if(!modulesToDisable.isEmpty()) {\n for (final File file : modulesToDisable) {\n try {\n PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to restore state for %s\", file);\n }\n }\n }\n }\n return true;\n }", "protected Object[] idsOf(final List<?> idsOrValues) {\n // convert list to array that we can mutate\n final Object[] ids = idsOrValues.toArray();\n\n // mutate array to contain only non-empty ids\n int length = 0;\n for (int i = 0; i < ids.length;) {\n final Object p = ids[i++];\n if (p instanceof HasId) {\n // only use values with ids that are non-empty\n final String id = ((HasId) p).getId();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p instanceof String) {\n // only use ids that are non-empty\n final String id = p.toString();\n if (!StringUtils.isEmpty(id)) {\n ids[length++] = id;\n }\n } else if (p != null) {\n throw new StoreException(\"Invalid id or value of type \" + p);\n }\n }\n\n // no ids in array\n if (length == 0) {\n return null;\n }\n\n // some ids in array\n if (length != ids.length) {\n final Object[] tmp = new Object[length];\n System.arraycopy(ids, 0, tmp, 0, length);\n return tmp;\n }\n\n // array was full\n return ids;\n }", "private void processUDF(UDFTypeType udf)\n {\n FieldTypeClass fieldType = FIELD_TYPE_MAP.get(udf.getSubjectArea());\n if (fieldType != null)\n {\n UserFieldDataType dataType = UserFieldDataType.getInstanceFromXmlName(udf.getDataType());\n String name = udf.getTitle();\n FieldType field = addUserDefinedField(fieldType, dataType, name);\n if (field != null)\n {\n m_fieldTypeMap.put(udf.getObjectId(), field);\n }\n }\n }", "protected long getRevisionIdFromResponse(JsonNode response) throws JsonMappingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"API response is null\");\n\t\t}\n\t\tJsonNode entity = null;\n\t\tif(response.has(\"entity\")) {\n\t\t\tentity = response.path(\"entity\");\n\t\t} else if(response.has(\"pageinfo\")) {\n\t\t\tentity = response.path(\"pageinfo\");\n\t\t} \n\t\tif(entity != null && entity.has(\"lastrevid\")) {\n\t\t\treturn entity.path(\"lastrevid\").asLong();\n\t\t}\n\t\tthrow new JsonMappingException(\"The last revision id could not be found in API response\");\n\t}", "public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }", "public static AppDescriptor deserializeFrom(byte[] bytes) {\n try {\n ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n return (AppDescriptor) ois.readObject();\n } catch (IOException e) {\n throw E.ioException(e);\n } catch (ClassNotFoundException e) {\n throw E.unexpected(e);\n }\n }" ]
Method to build Integration flow for IMAP Idle configuration. @param urlName Mail source URL. @return Integration Flow object IMAP IDLE.
[ "private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) {\n\t\treturn IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString())\n\t\t\t\t.shouldDeleteMessages(this.properties.isDelete())\n\t\t\t\t.javaMailProperties(getJavaMailProperties(urlName))\n\t\t\t\t.selectorExpression(this.properties.getExpression())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead()));\n\t}" ]
[ "@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }", "public void setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(htmlElementTranslator!=null){\r\n\t\t\tthis.htmlElementTranslator = htmlElementTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\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 }", "static BsonDocument getFreshVersionDocument() {\n final BsonDocument versionDoc = new BsonDocument();\n\n versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1));\n versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString()));\n versionDoc.append(Fields.VERSION_COUNTER_FIELD, new BsonInt64(0L));\n\n return versionDoc;\n }", "public static boolean isPortletEnvSupported() {\n if (enabled == null) {\n synchronized (PortletSupport.class) {\n if (enabled == null) {\n try {\n PortletSupport.class.getClassLoader().loadClass(\"javax.portlet.PortletContext\");\n enabled = true;\n } catch (Throwable ignored) {\n enabled = false;\n }\n }\n }\n }\n return enabled;\n }", "public static base_response unset(nitro_service client, bridgetable resource, String[] args) throws Exception{\n\t\tbridgetable unsetresource = new bridgetable();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public final void setWeeksOfMonth(SortedSet<WeekOfMonth> weeksOfMonth) {\n\n m_weeksOfMonth.clear();\n if (null != weeksOfMonth) {\n m_weeksOfMonth.addAll(weeksOfMonth);\n }\n\n }", "public static String stringifyJavascriptObject(Object object) {\n StringBuilder bld = new StringBuilder();\n stringify(object, bld);\n return bld.toString();\n }", "@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }" ]
Stores the gathered usage statistics about property uses to a CSV file. @param usageStatistics the statistics to store @param fileName the name of the file to use
[ "private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
[ "public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken, Integer paginationPageSize) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>)readerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class,\n OauthToken.class, RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, paginationPageSize, false);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }", "public GridCoverage2D call() {\n try {\n BufferedImage coverageImage = this.tiledLayer.createBufferedImage(\n this.tilePreparationInfo.getImageWidth(),\n this.tilePreparationInfo.getImageHeight());\n Graphics2D graphics = coverageImage.createGraphics();\n try {\n for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {\n final TileTask task;\n if (tileInfo.getTileRequest() != null) {\n task = new SingleTileLoaderTask(\n tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),\n tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);\n } else {\n task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),\n tileInfo.getTileIndexX(), tileInfo.getTileIndexY());\n }\n Tile tile = task.call();\n if (tile.getImage() != null) {\n graphics.drawImage(tile.getImage(),\n tile.getxIndex() * this.tiledLayer.getTileSize().width,\n tile.getyIndex() * this.tiledLayer.getTileSize().height, null);\n }\n }\n } finally {\n graphics.dispose();\n }\n\n GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);\n GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());\n gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,\n this.tilePreparationInfo.getGridCoverageOrigin().y,\n this.tilePreparationInfo.getGridCoverageMaxX(),\n this.tilePreparationInfo.getGridCoverageMaxY());\n return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,\n null, null, null);\n } catch (Exception e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}", "protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }", "public void addNamespace(final MongoNamespace namespace) {\n this.instanceLock.writeLock().lock();\n try {\n if (this.nsStreamers.containsKey(namespace)) {\n return;\n }\n final NamespaceChangeStreamListener streamer =\n new NamespaceChangeStreamListener(\n namespace,\n instanceConfig.getNamespaceConfig(namespace),\n service,\n networkMonitor,\n authMonitor,\n getLockForNamespace(namespace));\n this.nsStreamers.put(namespace, streamer);\n } finally {\n this.instanceLock.writeLock().unlock();\n }\n }", "public ApiResponse<TagsEnvelope> getTagCategoriesWithHttpInfo() throws ApiException {\n com.squareup.okhttp.Call call = getTagCategoriesValidateBeforeCall(null, null);\n Type localVarReturnType = new TypeToken<TagsEnvelope>(){}.getType();\n return apiClient.execute(call, localVarReturnType);\n }", "private boolean isForGerritHost(HttpRequest request) {\n if (!(request instanceof HttpRequestWrapper)) return false;\n HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();\n if (!(originalRequest instanceof HttpRequestBase)) return false;\n URI uri = ((HttpRequestBase) originalRequest).getURI();\n URI authDataUri = URI.create(authData.getHost());\n if (uri == null || uri.getHost() == null) return false;\n boolean hostEquals = uri.getHost().equals(authDataUri.getHost());\n boolean portEquals = uri.getPort() == authDataUri.getPort();\n return hostEquals && portEquals;\n }", "private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, boolean logDetails) {\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\tdatabaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter);\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"dropping table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"DROP TABLE \");\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(' ');\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t}", "public static int hash(int input)\n {\n int k1 = mixK1(input);\n int h1 = mixH1(DEFAULT_SEED, k1);\n\n return fmix(h1, SizeOf.SIZE_OF_INT);\n }" ]
Parses a String comprised of 0 or more comma-delimited key=value pairs. @param s the string to parse @return the Map of parsed key value pairs
[ "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 static void checkArrayLength(String parameterName, int actualLength,\n int expectedLength) {\n if (actualLength != expectedLength) {\n throw Exceptions.IllegalArgument(\n \"Array %s should have %d elements, not %d\", parameterName,\n expectedLength, actualLength);\n }\n }", "public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,\r\n edu.stanford.nlp.sequences.FeatureFactory<IN> featureFactory) {\r\n pad.set(AnswerAnnotation.class, flags.backgroundSymbol);\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n ArrayList<List<String>> features = new ArrayList<List<String>>();\r\n\r\n // for (int i = 0; i < windowSize; i++) {\r\n // List featuresC = new ArrayList();\r\n // for (int j = 0; j < FeatureFactory.win[i].length; j++) {\r\n // featuresC.addAll(featureFactory.features(info, loc,\r\n // FeatureFactory.win[i][j]));\r\n // }\r\n // features.add(featuresC);\r\n // }\r\n\r\n Collection<Clique> done = new HashSet<Clique>();\r\n for (int i = 0; i < windowSize; i++) {\r\n List<String> featuresC = new ArrayList<String>();\r\n List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);\r\n windowCliques.removeAll(done);\r\n done.addAll(windowCliques);\r\n for (Clique c : windowCliques) {\r\n featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons\r\n }\r\n features.add(featuresC);\r\n }\r\n\r\n int[] labels = new int[windowSize];\r\n\r\n for (int i = 0; i < windowSize; i++) {\r\n String answer = pInfo.get(loc + i - windowSize + 1).get(AnswerAnnotation.class);\r\n labels[i] = classIndex.indexOf(answer);\r\n }\r\n\r\n printFeatureLists(pInfo.get(loc), features);\r\n\r\n CRFDatum<List<String>, CRFLabel> d = new CRFDatum<List<String>, CRFLabel>(features, new CRFLabel(labels));\r\n // System.err.println(d);\r\n return d;\r\n }", "public static base_response disable(nitro_service client, String name) throws Exception {\n\t\tvserver disableresource = new vserver();\n\t\tdisableresource.name = name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (null == authenticationServices) {\n\t\t\tauthenticationServices = new ArrayList<AuthenticationService>();\n\t\t}\n\t\tif (!excludeDefault) {\n\t\t\tauthenticationServices.add(staticAuthenticationService);\n\t\t}\n\t}", "public static ManagerFunctions.InputN createMultTransA() {\n return (inputs, manager) -> {\n if( inputs.size() != 2 )\n throw new RuntimeException(\"Two inputs required\");\n\n final Variable varA = inputs.get(0);\n final Variable varB = inputs.get(1);\n\n Operation.Info ret = new Operation.Info();\n\n if( varA instanceof VariableMatrix && varB instanceof VariableMatrix ) {\n\n // The output matrix or scalar variable must be created with the provided manager\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"multTransA-mm\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)varA).matrix;\n DMatrixRMaj mB = ((VariableMatrix)varB).matrix;\n\n CommonOps_DDRM.multTransA(mA,mB,output.matrix);\n }\n };\n } else {\n throw new IllegalArgumentException(\"Expected both inputs to be a matrix\");\n }\n\n return ret;\n };\n }", "@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 String[] removeDuplicateStrings(String[] array) {\n if (isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n Collections.addAll(set, array);\n return toStringArray(set);\n }", "public static String resolveSvnMigratedRevision(final Revision revision, final String branch) {\n if (revision == null) {\n return null;\n }\n final Pattern pattern = Pattern.compile(\"^git-svn-id: .*\" + branch + \"@([0-9]+) \", Pattern.MULTILINE);\n final Matcher matcher = pattern.matcher(revision.getMessage());\n if (matcher.find()) {\n return matcher.group(1);\n } else {\n return revision.getRevision();\n }\n }", "public ConnectionInfo getConnection(String name) {\n final URI uri = uriWithPath(\"./connections/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ConnectionInfo.class);\n }" ]
This method calculates the absolute number of days between two dates. Note that where two date objects are provided that fall on the same day, this method will return one not zero. Note also that this method assumes that the dates are passed in the correct order, i.e. startDate < endDate. @param startDate Start date @param endDate End date @return number of days in the date range
[ "private int getDaysInRange(Date startDate, Date endDate)\n {\n int result;\n Calendar cal = DateHelper.popCalendar(endDate);\n int endDateYear = cal.get(Calendar.YEAR);\n int endDateDayOfYear = cal.get(Calendar.DAY_OF_YEAR);\n\n cal.setTime(startDate);\n\n if (endDateYear == cal.get(Calendar.YEAR))\n {\n result = (endDateDayOfYear - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n }\n else\n {\n result = 0;\n do\n {\n result += (cal.getActualMaximum(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n cal.roll(Calendar.YEAR, 1);\n cal.set(Calendar.DAY_OF_YEAR, 1);\n }\n while (cal.get(Calendar.YEAR) < endDateYear);\n result += endDateDayOfYear;\n }\n DateHelper.pushCalendar(cal);\n \n return result;\n }" ]
[ "@Override public void onBindViewHolder(RendererViewHolder viewHolder, int position) {\n T content = getItem(position);\n Renderer<T> renderer = viewHolder.getRenderer();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null renderer\");\n }\n renderer.setContent(content);\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n }", "public static Command newInsert(Object object,\n String outIdentifier,\n boolean returnObject,\n String entryPoint ) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier,\n returnObject,\n entryPoint );\n }", "protected final boolean isPatternValid() {\n\n switch (getPatternType()) {\n case DAILY:\n return isEveryWorkingDay() || isIntervalValid();\n case WEEKLY:\n return isIntervalValid() && isWeekDaySet();\n case MONTHLY:\n return isIntervalValid() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case YEARLY:\n return isMonthSet() && isWeekDaySet() ? isWeekOfMonthSet() : isDayOfMonthValid();\n case INDIVIDUAL:\n case NONE:\n return true;\n default:\n return false;\n }\n }", "public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}", "public static base_response unset(nitro_service client, sslservice resource, String[] args) throws Exception{\n\t\tsslservice unsetresource = new sslservice();\n\t\tunsetresource.servicename = resource.servicename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private boolean contains(ArrayList defs, DefBase obj)\r\n {\r\n for (Iterator it = defs.iterator(); it.hasNext();)\r\n {\r\n if (obj.getName().equals(((DefBase)it.next()).getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }", "public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}", "public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
Sets the alias using a userAlias object. @param userAlias The alias to set
[ "public void setAlias(UserAlias userAlias)\r\n\t{\r\n\t\tm_alias = userAlias.getName();\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(userAlias);\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
[ "public static int getDayAsReadableInt(long time) {\n Calendar cal = calendarThreadLocal.get();\n cal.setTimeInMillis(time);\n return getDayAsReadableInt(cal);\n }", "public static String getDumpFileWebDirectory(\n\t\t\tDumpContentType dumpContentType, String projectName) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\tif (\"wikidatawiki\".equals(projectName)) {\n\t\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t\t+ \"wikidata\" + \"/\";\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Wikimedia Foundation uses non-systematic directory names for this type of dump file.\"\n\t\t\t\t\t\t\t\t+ \" I don't know where to find dumps of project \"\n\t\t\t\t\t\t\t\t+ projectName);\n\t\t\t}\n\t\t} else if (WmfDumpFile.WEB_DIRECTORY.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t+ projectName + \"/\";\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}", "public static void main(String[] args) throws Exception {\r\n System.err.println(\"CRFBiasedClassifier invoked at \" + new Date()\r\n + \" with arguments:\");\r\n for (String arg : args) {\r\n System.err.print(\" \" + arg);\r\n }\r\n System.err.println();\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFBiasedClassifier crf = new CRFBiasedClassifier(props);\r\n String testFile = crf.flags.testFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n if(crf.flags.classBias != null) {\r\n StringTokenizer biases = new java.util.StringTokenizer(crf.flags.classBias,\",\");\r\n while (biases.hasMoreTokens()) {\r\n StringTokenizer bias = new java.util.StringTokenizer(biases.nextToken(),\":\");\r\n String cname = bias.nextToken();\r\n double w = Double.parseDouble(bias.nextToken());\r\n crf.setBiasWeight(cname,w);\r\n System.err.println(\"Setting bias for class \"+cname+\" to \"+w);\r\n }\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n }", "public static Thread addShutdownHook(final Process process) {\n final Thread thread = new Thread(new Runnable() {\n @Override\n public void run() {\n if (process != null) {\n process.destroy();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n });\n thread.setDaemon(true);\n Runtime.getRuntime().addShutdownHook(thread);\n return thread;\n }", "public static nslimitselector get(nitro_service service, String selectorname) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tnslimitselector response = (nslimitselector) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}", "@Deprecated\n private static ListAttributeDefinition wrapAsList(final AttributeDefinition def) {\n final ListAttributeDefinition list = new ListAttributeDefinition(new SimpleListAttributeDefinition.Builder(def.getName(), def)\n .setElementValidator(def.getValidator())) {\n\n\n @Override\n public ModelNode getNoTextDescription(boolean forOperation) {\n final ModelNode model = super.getNoTextDescription(forOperation);\n setValueType(model);\n return model;\n }\n\n @Override\n protected void addValueTypeDescription(final ModelNode node, final ResourceBundle bundle) {\n setValueType(node);\n }\n\n @Override\n public void marshallAsElement(final ModelNode resourceModel, final boolean marshalDefault, final XMLStreamWriter writer) throws XMLStreamException {\n throw new RuntimeException();\n }\n\n @Override\n protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {\n setValueType(node);\n }\n\n @Override\n protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {\n setValueType(node);\n }\n\n private void setValueType(ModelNode node) {\n node.get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.STRING);\n }\n };\n return list;\n }", "public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\n }", "private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }" ]