query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Fling the content @param velocityX The initial velocity in the X direction. Positive numbers mean that the finger/cursor is moving to the left on the screen, which means we want to scroll towards the beginning. @param velocityY The initial velocity in the Y direction. Positive numbers mean that the finger/cursor is moving down the screen, which means we want to scroll towards the top. @param velocityZ TODO: Z-scrolling is currently not supported @return
[ "public boolean fling(float velocityX, float velocityY, float velocityZ) {\n boolean scrolled = true;\n float viewportX = mScrollable.getViewPortWidth();\n if (Float.isNaN(viewportX)) {\n viewportX = 0;\n }\n float maxX = Math.min(MAX_SCROLLING_DISTANCE,\n viewportX * MAX_VIEWPORT_LENGTHS);\n\n float viewportY = mScrollable.getViewPortHeight();\n if (Float.isNaN(viewportY)) {\n viewportY = 0;\n }\n float maxY = Math.min(MAX_SCROLLING_DISTANCE,\n viewportY * MAX_VIEWPORT_LENGTHS);\n\n float xOffset = (maxX * velocityX)/VELOCITY_MAX;\n float yOffset = (maxY * velocityY)/VELOCITY_MAX;\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"fling() velocity = [%f, %f, %f] offset = [%f, %f]\",\n velocityX, velocityY, velocityZ,\n xOffset, yOffset);\n\n if (equal(xOffset, 0)) {\n xOffset = Float.NaN;\n }\n\n if (equal(yOffset, 0)) {\n yOffset = Float.NaN;\n }\n\n// TODO: Think about Z-scrolling\n mScrollable.scrollByOffset(xOffset, yOffset, Float.NaN, mInternalScrollListener);\n\n return scrolled;\n }" ]
[ "public static int timezoneOffset(H.Session session) {\n String s = null != session ? session.get(SESSION_KEY) : null;\n return S.notBlank(s) ? Integer.parseInt(s) : serverTimezoneOffset();\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 static base_response add(nitro_service client, dnssuffix resource) throws Exception {\n\t\tdnssuffix addresource = new dnssuffix();\n\t\taddresource.Dnssuffix = resource.Dnssuffix;\n\t\treturn addresource.add_resource(client);\n\t}", "private static boolean isVariableInteger(TokenList.Token t) {\n if( t == null )\n return false;\n\n return t.getScalarType() == VariableScalar.Type.INTEGER;\n }", "static WeldContainer startInitialization(String id, Deployment deployment, Bootstrap bootstrap) {\n if (SINGLETON.isSet(id)) {\n throw WeldSELogger.LOG.weldContainerAlreadyRunning(id);\n }\n WeldContainer weldContainer = new WeldContainer(id, deployment, bootstrap);\n SINGLETON.set(id, weldContainer);\n RUNNING_CONTAINER_IDS.add(id);\n return weldContainer;\n }", "public static <InnerT> PagedList<InnerT> convertToPagedList(List<InnerT> list) {\n PageImpl<InnerT> page = new PageImpl<>();\n page.setItems(list);\n page.setNextPageLink(null);\n return new PagedList<InnerT>(page) {\n @Override\n public Page<InnerT> nextPage(String nextPageLink) {\n return null;\n }\n };\n }", "public void setGroupName(String name, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" SET \" + Constants.GENERIC_NAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }", "@RequestMapping(value = \"api/edit/disableAll\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableAll(Model model, int profileID,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) {\n editService.disableAll(profileID, clientUUID);\n return null;\n }" ]
Adds two complex numbers. @param z1 Complex Number. @param z2 Complex Number. @return Returns new ComplexNumber instance containing the sum of specified complex numbers.
[ "public static ComplexNumber Add(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);\r\n }" ]
[ "public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "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 }", "@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 }", "public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\n }", "public static base_response delete(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey deleteresource = new sslcertkey();\n\t\tdeleteresource.certkey = resource.certkey;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public ActionContext applyContentType(Result result) {\n if (!result.status().isError()) {\n return applyContentType();\n }\n return applyContentType(contentTypeForErrorResult(req()));\n }", "public void invalidate(final int dataIndex) {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate [%d]\", dataIndex);\n mMeasuredChildren.remove(dataIndex);\n }\n }", "public ResponseOnSingeRequest genErrorResponse(Exception t) {\n ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();\n String displayError = PcErrorMsgUtils.replaceErrorMsg(t.toString());\n\n sshResponse.setStackTrace(PcStringUtils.printStackTrace(t));\n sshResponse.setErrorMessage(displayError);\n sshResponse.setFailObtainResponse(true);\n\n logger.error(\"error in exec SSH. \\nIf exection is JSchException: \"\n + \"Auth cancel and using public key. \"\n + \"\\nMake sure 1. private key full path is right (try sshMeta.getPrivKeyAbsPath()). \"\n + \"\\n2. the user name and key matches \" + t);\n\n return sshResponse;\n }", "protected void createNewFile(final File file) {\n try {\n file.createNewFile();\n setFileNotWorldReadablePermissions(file);\n } catch (IOException e){\n throw new RuntimeException(e);\n }\n }" ]
convert Event bean to EventType manually. @param event the event @return the event type
[ "public static EventType map(Event event) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(event.getTimestamp()));\n eventType.setEventType(convertEventType(event.getEventType()));\n OriginatorType origType = mapOriginator(event.getOriginator());\n eventType.setOriginator(origType);\n MessageInfoType miType = mapMessageInfo(event.getMessageInfo());\n eventType.setMessageInfo(miType);\n eventType.setCustomInfo(convertCustomInfo(event.getCustomInfo()));\n eventType.setContentCut(event.isContentCut());\n if (event.getContent() != null) {\n DataHandler datHandler = getDataHandlerForString(event);\n eventType.setContent(datHandler);\n }\n return eventType;\n }" ]
[ "private static synchronized boolean isLog4JConfigured()\r\n {\r\n if(!log4jConfigured)\r\n {\r\n Enumeration en = org.apache.log4j.Logger.getRootLogger().getAllAppenders();\r\n\r\n if (!(en instanceof org.apache.log4j.helpers.NullEnumeration))\r\n {\r\n log4jConfigured = true;\r\n }\r\n else\r\n {\r\n Enumeration cats = LogManager.getCurrentLoggers();\r\n while (cats.hasMoreElements())\r\n {\r\n org.apache.log4j.Logger c = (org.apache.log4j.Logger) cats.nextElement();\r\n if (!(c.getAllAppenders() instanceof org.apache.log4j.helpers.NullEnumeration))\r\n {\r\n log4jConfigured = true;\r\n }\r\n }\r\n }\r\n if(log4jConfigured)\r\n {\r\n String msg = \"Log4J is already configured, will not search for log4j properties file\";\r\n LoggerFactory.getBootLogger().info(msg);\r\n }\r\n else\r\n {\r\n LoggerFactory.getBootLogger().info(\"Log4J is not configured\");\r\n }\r\n }\r\n return log4jConfigured;\r\n }", "public void add(StatementRank rank, Resource subject) {\n\t\tif (this.bestRank == rank) {\n\t\t\tsubjects.add(subject);\n\t\t} else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) {\n\t\t\t//We found a preferred statement\n\t\t\tsubjects.clear();\n\t\t\tbestRank = StatementRank.PREFERRED;\n\t\t\tsubjects.add(subject);\n\t\t}\n\t}", "private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n DayTypes dayTypes = gpCalendar.getDayTypes();\n DefaultWeek defaultWeek = dayTypes.getDefaultWeek();\n if (defaultWeek == null)\n {\n mpxjCalendar.setWorkingDay(Day.SUNDAY, false);\n mpxjCalendar.setWorkingDay(Day.MONDAY, true);\n mpxjCalendar.setWorkingDay(Day.TUESDAY, true);\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true);\n mpxjCalendar.setWorkingDay(Day.THURSDAY, true);\n mpxjCalendar.setWorkingDay(Day.FRIDAY, true);\n mpxjCalendar.setWorkingDay(Day.SATURDAY, false);\n }\n else\n {\n mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon()));\n mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue()));\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed()));\n mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu()));\n mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri()));\n mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat()));\n mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun()));\n }\n\n for (Day day : Day.values())\n {\n if (mpxjCalendar.isWorkingDay(day))\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) {\n Set<Pattern> set = new HashSet<>();\n for (String wildcardExpr : runtimeNames) {\n Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr);\n set.add(pattern);\n }\n return listDeploymentNames(deploymentRootResource, set);\n }", "public double getDurationMs() {\n double durationMs = 0;\n for (Duration duration : durations) {\n if (duration.taskFinished()) {\n durationMs += duration.getDurationMS();\n }\n }\n return durationMs;\n }", "public static Resource getSetupPage(I_SetupUiContext context, String name) {\n\n String path = CmsStringUtil.joinPaths(context.getSetupBean().getContextPath(), CmsSetupBean.FOLDER_SETUP, name);\n Resource resource = new ExternalResource(path);\n return resource;\n }", "public ItemRequest<Workspace> update(String workspace) {\n \n String path = String.format(\"/workspaces/%s\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"PUT\");\n }", "public static String make512Safe(StringBuffer input, String newline) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString content = input.toString();\n\t\tString rest = content;\n\t\twhile (!rest.isEmpty()) {\n\t\t\tif (rest.contains(\"\\n\")) {\n\t\t\t\tString line = rest.substring(0, rest.indexOf(\"\\n\"));\n\t\t\t\trest = rest.substring(rest.indexOf(\"\\n\") + 1);\n\t\t\t\tif (line.length() > 1 && line.charAt(line.length() - 1) == '\\r')\n\t\t\t\t\tline = line.substring(0, line.length() - 1);\n\t\t\t\tappend512Safe(line, result, newline);\n\t\t\t} else {\n\t\t\t\tappend512Safe(rest, result, newline);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result.toString();\n\t}", "public List<Object> getAll(int dataSet) throws SerializationException {\r\n\t\tList<Object> result = new ArrayList<Object>();\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult.add(getData(ds));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}" ]
Decorates a node with the affected operator, if any. @param context @param tree @param operations @return
[ "public JsonObject getJSONwithOperations(TreeContext context, ITree tree, List<Operation> operations) {\n\n\t\tOperationNodePainter opNodePainter = new OperationNodePainter(operations);\n\t\tCollection<NodePainter> painters = new ArrayList<NodePainter>();\n\t\tpainters.add(opNodePainter);\n\t\treturn getJSONwithCustorLabels(context, tree, painters);\n\t}" ]
[ "public static void writeObject(File file, Object object) throws IOException {\n FileOutputStream fileOut = new FileOutputStream(file);\n ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));\n try {\n out.writeObject(object);\n out.flush();\n // Force sync\n fileOut.getFD().sync();\n } finally {\n IoUtils.safeClose(out);\n }\n }", "ResultAction executeOperation() {\n\n assert isControllingThread();\n try {\n /** Execution has begun */\n executing = true;\n\n processStages();\n\n if (resultAction == ResultAction.KEEP) {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());\n } else {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());\n }\n } catch (RuntimeException e) {\n handleUncaughtException(e);\n ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);\n } finally {\n // On failure close any attached response streams\n if (resultAction != ResultAction.KEEP && !isBooting()) {\n synchronized (this) {\n if (responseStreams != null) {\n int i = 0;\n for (OperationResponse.StreamEntry is : responseStreams.values()) {\n try {\n is.getStream().close();\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.debugf(e, \"Failed closing stream at index %d\", i);\n }\n i++;\n }\n responseStreams.clear();\n }\n }\n }\n }\n\n\n return resultAction;\n }", "public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, objectOrProxy, true);\r\n }", "public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }", "public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }", "private static void processTaskFilter(ProjectFile project, Filter filter)\n {\n for (Task task : project.getTasks())\n {\n if (filter.evaluate(task, null))\n {\n System.out.println(task.getID() + \",\" + task.getUniqueID() + \",\" + task.getName());\n }\n }\n }", "@Override\n public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) {\n return minimize(function, point, null);\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n List<String> storeNames = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET_RO);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(KEY_MAX_VERSION);\n metaKeys.add(KEY_CURRENT_VERSION);\n metaKeys.add(KEY_STORAGE_FORMAT);\n }\n\n doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);\n }" ]
Stops the current connection. No reconnecting will occur. Kills thread + cleanup. Waits for the loop to end
[ "public void stop(int waitMillis) throws InterruptedException {\n try {\n if (!isDone()) {\n setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format(\"Stopped by user: waiting for %d ms\", waitMillis)));\n }\n if (!waitForFinish(waitMillis)) {\n logger.warn(\"{} Client thread failed to finish in {} millis\", name, waitMillis);\n }\n } finally {\n rateTracker.shutdown();\n }\n }" ]
[ "protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public static String[] copyArrayAddFirst(String[] arr, String add) {\n String[] arrCopy = new String[arr.length + 1];\n arrCopy[0] = add;\n System.arraycopy(arr, 0, arrCopy, 1, arr.length);\n return arrCopy;\n }", "public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n assert resource != null : \"The resource cannot be null\";\n return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);\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 }", "public static void writeCorrelationId(Message message, String correlationId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage) message;\n Header hdCorrelationId = soapMessage.getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n if ((soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) != null)\n && (soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) instanceof SAAJStreamWriter)\n && (((SAAJStreamWriter) soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class))\n .getDocument()\n .getElementsByTagNameNS(\"http://www.talend.com/esb/sam/correlationId/v1\",\n \"correlationId\").getLength() > 0)) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(CORRELATION_ID_QNAME, correlationId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored correlationId '\" + correlationId + \"' in soap header: \"\n + CORRELATION_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create correlationId header.\", e);\n }\n\n }", "public void setEndType(final String value) {\r\n\r\n final EndType endType = EndType.valueOf(value);\r\n if (!endType.equals(m_model.getEndType())) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n switch (endType) {\r\n case SINGLE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case TIMES:\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case DATE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(m_model.getStart() == null ? new Date() : m_model.getStart());\r\n break;\r\n default:\r\n break;\r\n }\r\n m_model.setEndType(endType);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "private Level getLogLevel() {\n return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;\n }", "private Widget setStyle(Widget widget) {\n\n widget.setWidth(m_width);\n widget.getElement().getStyle().setDisplay(Display.INLINE_BLOCK);\n return widget;\n }", "public void printMinors(int matrix[], int N, PrintStream stream) {\n this.N = N;\n this.stream = stream;\n\n // compute all the minors\n int index = 0;\n for( int i = 1; i <= N; i++ ) {\n for( int j = 1; j <= N; j++ , index++) {\n stream.print(\" double m\"+i+\"\"+j+\" = \");\n if( (i+j) % 2 == 1 )\n stream.print(\"-( \");\n printTopMinor(matrix,i-1,j-1,N);\n if( (i+j) % 2 == 1 )\n stream.print(\")\");\n stream.print(\";\\n\");\n }\n }\n\n stream.println();\n // compute the determinant\n stream.print(\" double det = (a11*m11\");\n for( int i = 2; i <= N; i++ ) {\n stream.print(\" + \"+a(i-1)+\"*m\"+1+\"\"+i);\n }\n stream.println(\")/scale;\");\n\n }" ]
Get a list of all active server mappings defined for current profile @return Collection of ServerRedirects
[ "public List<ServerRedirect> getServerMappings() {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONObject response = new JSONObject(doGet(BASE_SERVER, null));\n JSONArray serverArray = response.getJSONArray(\"servers\");\n\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServer = serverArray.getJSONObject(i);\n ServerRedirect server = getServerRedirectFromJSON(jsonServer);\n if (server != null) {\n servers.add(server);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return servers;\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 static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }", "@RequestMapping(value = \"api/servergroup\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerGroup createServerGroup(Model model,\n @RequestParam(value = \"name\") String name,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId);\n return ServerRedirectService.getInstance().getServerGroup(groupId, profileId);\n }", "public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }", "public void addDefaultCalendarHours(Day day)\n {\n ProjectCalendarHours hours = addCalendarHours(day);\n\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n hours.addRange(DEFAULT_WORKING_MORNING);\n hours.addRange(DEFAULT_WORKING_AFTERNOON);\n }\n }", "public void setEndType(final String value) {\r\n\r\n final EndType endType = EndType.valueOf(value);\r\n if (!endType.equals(m_model.getEndType())) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n switch (endType) {\r\n case SINGLE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case TIMES:\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case DATE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(m_model.getStart() == null ? new Date() : m_model.getStart());\r\n break;\r\n default:\r\n break;\r\n }\r\n m_model.setEndType(endType);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "public synchronized void start() throws SocketException {\n\n if (!isRunning()) {\n socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));\n startTime.set(System.currentTimeMillis());\n deliverLifecycleAnnouncement(logger, true);\n\n final byte[] buffer = new byte[512];\n final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);\n Thread receiver = new Thread(null, new Runnable() {\n @Override\n public void run() {\n boolean received;\n while (isRunning()) {\n try {\n if (getCurrentDevices().isEmpty()) {\n socket.get().setSoTimeout(60000); // We have no devices to check for timeout; block for a whole minute to check for shutdown\n } else {\n socket.get().setSoTimeout(1000); // Check every second to see if a device has vanished\n }\n socket.get().receive(packet);\n received = !ignoredAddresses.contains(packet.getAddress());\n } catch (SocketTimeoutException ste) {\n received = false;\n } catch (IOException e) {\n // Don't log a warning if the exception was due to the socket closing at shutdown.\n if (isRunning()) {\n // We did not expect to have a problem; log a warning and shut down.\n logger.warn(\"Problem reading from DeviceAnnouncement socket, stopping\", e);\n stop();\n }\n received = false;\n }\n try {\n if (received && (packet.getLength() == 54)) {\n final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);\n if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {\n // Looks like the kind of packet we need\n if (packet.getLength() < 54) {\n logger.warn(\"Ignoring too-short \" + kind.name + \" packet; expected 54 bytes, but only got \" +\n packet.getLength() + \".\");\n } else {\n if (packet.getLength() > 54) {\n logger.warn(\"Processing too-long \" + kind.name + \" packet; expected 54 bytes, but got \" +\n packet.getLength() + \".\");\n }\n DeviceAnnouncement announcement = new DeviceAnnouncement(packet);\n final boolean foundNewDevice = isDeviceNew(announcement);\n updateDevices(announcement);\n if (foundNewDevice) {\n deliverFoundAnnouncement(announcement);\n }\n }\n }\n }\n expireDevices();\n } catch (Throwable t) {\n logger.warn(\"Problem processing DeviceAnnouncement packet\", t);\n }\n }\n }\n }, \"beat-link DeviceFinder receiver\");\n receiver.setDaemon(true);\n receiver.start();\n }\n }", "public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\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}" ]
Checks that all the qualifiers in the set requiredQualifiers are in the set of qualifiers. Qualifier equality rules for annotation members are followed. @param requiredQualifiers The required qualifiers @param qualifiers The set of qualifiers to check @return True if all matches, false otherwise
[ "public static boolean containsAllQualifiers(Set<QualifierInstance> requiredQualifiers, Set<QualifierInstance> qualifiers) {\n return qualifiers.containsAll(requiredQualifiers);\n }" ]
[ "private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }", "@Nullable\n public StitchUserT getUser() {\n authLock.readLock().lock();\n try {\n return activeUser;\n } finally {\n authLock.readLock().unlock();\n }\n }", "private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }", "public static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }", "private void handleUpdate(final int player) {\n final TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n final WaveformDetail waveformDetail = WaveformFinder.getInstance().getLatestDetailFor(player);\n final BeatGrid beatGrid = BeatGridFinder.getInstance().getLatestBeatGridFor(player);\n if (metadata != null && waveformDetail != null && beatGrid != null) {\n final String signature = computeTrackSignature(metadata.getTitle(), metadata.getArtist(),\n metadata.getDuration(), waveformDetail, beatGrid);\n if (signature != null) {\n signatures.put(player, signature);\n deliverSignatureUpdate(player, signature);\n }\n }\n }", "void backupConfiguration() throws IOException {\n\n final String configuration = Constants.CONFIGURATION;\n\n final File a = new File(installedImage.getAppClientDir(), configuration);\n final File d = new File(installedImage.getDomainDir(), configuration);\n final File s = new File(installedImage.getStandaloneDir(), configuration);\n\n if (a.exists()) {\n final File ab = new File(configBackup, Constants.APP_CLIENT);\n backupDirectory(a, ab);\n }\n if (d.exists()) {\n final File db = new File(configBackup, Constants.DOMAIN);\n backupDirectory(d, db);\n }\n if (s.exists()) {\n final File sb = new File(configBackup, Constants.STANDALONE);\n backupDirectory(s, sb);\n }\n\n }", "public void populateFromAttributes(\n @Nonnull final Template template,\n @Nonnull final Map<String, Attribute> attributes,\n @Nonnull final PObject requestJsonAttributes) {\n if (requestJsonAttributes.has(JSON_REQUEST_HEADERS) &&\n requestJsonAttributes.getObject(JSON_REQUEST_HEADERS).has(JSON_REQUEST_HEADERS) &&\n !attributes.containsKey(JSON_REQUEST_HEADERS)) {\n attributes.put(JSON_REQUEST_HEADERS, new HttpRequestHeadersAttribute());\n }\n for (Map.Entry<String, Attribute> attribute: attributes.entrySet()) {\n try {\n put(attribute.getKey(),\n attribute.getValue().getValue(template, attribute.getKey(), requestJsonAttributes));\n } catch (ObjectMissingException | IllegalArgumentException e) {\n throw e;\n } catch (Throwable e) {\n String templateName = \"unknown\";\n for (Map.Entry<String, Template> entry: template.getConfiguration().getTemplates()\n .entrySet()) {\n if (entry.getValue() == template) {\n templateName = entry.getKey();\n break;\n }\n }\n\n String defaults = \"\";\n\n if (attribute instanceof ReflectiveAttribute<?>) {\n ReflectiveAttribute<?> reflectiveAttribute = (ReflectiveAttribute<?>) attribute;\n defaults = \"\\n\\n The attribute defaults are: \" + reflectiveAttribute.getDefaultValue();\n }\n\n String errorMsg = \"An error occurred when creating a value from the '\" + attribute.getKey() +\n \"' attribute for the '\" +\n templateName + \"' template.\\n\\nThe JSON is: \\n\" + requestJsonAttributes + defaults +\n \"\\n\" +\n e.toString();\n\n throw new AttributeParsingException(errorMsg, e);\n }\n }\n\n if (template.getConfiguration().isThrowErrorOnExtraParameters()) {\n final List<String> extraProperties = new ArrayList<>();\n for (Iterator<String> it = requestJsonAttributes.keys(); it.hasNext(); ) {\n final String attributeName = it.next();\n if (!attributes.containsKey(attributeName)) {\n extraProperties.add(attributeName);\n }\n }\n\n if (!extraProperties.isEmpty()) {\n throw new ExtraPropertyException(\"Extra properties found in the request attributes\",\n extraProperties, attributes.keySet());\n }\n }\n }", "public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }", "protected List<String> splitLinesAndNewLines(String text) {\n\t\tif (text == null)\n\t\t\treturn Collections.emptyList();\n\t\tint idx = initialSegmentSize(text);\n\t\tif (idx == text.length()) {\n\t\t\treturn Collections.singletonList(text);\n\t\t}\n\n\t\treturn continueSplitting(text, idx);\n\t}" ]
Use this API to fetch all the cacheobject resources that are configured on netscaler. This uses cacheobject_args which is a way to provide additional arguments while fetching the resources.
[ "public static cacheobject[] get(nitro_service service, cacheobject_args args) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service, option);\n\t\treturn response;\n\t}" ]
[ "public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}", "public static int e(ISubsystem subsystem, String tag, String msg) {\n return isEnabled(subsystem) ?\n currentLog.e(tag, getMsg(subsystem,msg)) : 0;\n }", "public HashMap<String, String> getProperties() {\n if (this.properties == null) {\n this.properties = new HashMap<String, String>();\n }\n return properties;\n }", "public String getLinkUrl(JSONObject jsonObject){\n if(jsonObject == null) return null;\n try {\n JSONObject urlObject = jsonObject.has(\"url\") ? jsonObject.getJSONObject(\"url\") : null;\n if(urlObject == null) return null;\n JSONObject androidObject = urlObject.has(\"android\") ? urlObject.getJSONObject(\"android\") : null;\n if(androidObject != null){\n return androidObject.has(\"text\") ? androidObject.getString(\"text\") : \"\";\n }else{\n return \"\";\n }\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link URL with JSON - \"+e.getLocalizedMessage());\n return null;\n }\n }", "public DbModule getModule(final String moduleId) {\n final DbModule dbModule = repositoryHandler.getModule(moduleId);\n\n if (dbModule == null) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Module \" + moduleId + \" does not exist.\").build());\n }\n\n return dbModule;\n }", "protected Object getObjectFromResultSet() throws PersistenceBrokerException\r\n {\r\n\r\n try\r\n {\r\n // if all primitive attributes of the object are contained in the ResultSet\r\n // the fast direct mapping can be used\r\n return super.getObjectFromResultSet();\r\n }\r\n // if the full loading failed we assume that at least PK attributes are contained\r\n // in the ResultSet and perform a slower Identity based loading...\r\n // This may of course also fail and can throw another PersistenceBrokerException\r\n catch (PersistenceBrokerException e)\r\n {\r\n Identity oid = getIdentityFromResultSet();\r\n return getBroker().getObjectByIdentity(oid);\r\n }\r\n\r\n }", "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }", "public void visitOpen(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitOpen(packaze, access, modules);\n }\n }", "public boolean setMethodArguments(String pathName, String methodName, Integer ordinal, Object... arguments) {\n try {\n BasicNameValuePair[] params = new BasicNameValuePair[arguments.length + 2];\n int x = 0;\n for (Object argument : arguments) {\n params[x] = new BasicNameValuePair(\"arguments[]\", argument.toString());\n x++;\n }\n params[x] = new BasicNameValuePair(\"profileIdentifier\", this._profileName);\n params[x + 1] = new BasicNameValuePair(\"ordinal\", ordinal.toString());\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodName, params));\n\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }" ]
Responsible for executing file rolls as and when required, in addition to delegating to the super class to perform the actual append operation. Synchronized for safety during enforced file roll. @see org.apache.log4j.WriterAppender#subAppend(org.apache.log4j.spi.LoggingEvent)
[ "@Override\n\tprotected final void subAppend(final LoggingEvent event) {\n\t\tif (event instanceof ScheduledFileRollEvent) {\n\t\t\t// the scheduled append() call has been made by a different thread\n\t\t\tsynchronized (this) {\n\t\t\t\tif (this.closed) {\n\t\t\t\t\t// just consume the event\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.rollFile(event);\n\t\t\t}\n\t\t} else if (event instanceof FileRollEvent) {\n\t\t\t// definitely want to avoid rolling here whilst a file roll event is still being handled\n\t\t\tsuper.subAppend(event);\n\t\t} else {\n\n\t\t\tif(event instanceof FoundationLof4jLoggingEvent){\n\t\t\t\tFoundationLof4jLoggingEvent foundationLof4jLoggingEvent = (FoundationLof4jLoggingEvent)event;\n\t\t\t\tfoundationLof4jLoggingEvent.setAppenderName(this.getName());\n\t\t\t}\n\t\t\t\n\t\t\tthis.rollFile(event);\n\t\t\tsuper.subAppend(event);\n\t\t}\n\t}" ]
[ "private void processCalendars() throws SQLException\n {\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_CALENDARS WHERE PROJ_ID=?\", m_projectID))\n {\n processCalendar(row);\n }\n\n updateBaseCalendarNames();\n\n processCalendarData(m_project.getCalendars());\n }", "private Component createMainComponent() throws IOException, CmsException {\n\n VerticalLayout mainComponent = new VerticalLayout();\n mainComponent.setSizeFull();\n mainComponent.addStyleName(\"o-message-bundle-editor\");\n m_table = createTable();\n Panel navigator = new Panel();\n navigator.setSizeFull();\n navigator.setContent(m_table);\n navigator.addActionHandler(new CmsMessageBundleEditorTypes.TableKeyboardHandler(m_table));\n navigator.addStyleName(\"v-panel-borderless\");\n\n mainComponent.addComponent(m_options.getOptionsComponent());\n mainComponent.addComponent(navigator);\n mainComponent.setExpandRatio(navigator, 1f);\n m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());\n return mainComponent;\n }", "public static String capitalize( String text ) {\n if( text == null || text.isEmpty() ) {\n return text;\n }\n return text.substring( 0, 1 ).toUpperCase().concat( text.substring( 1, text.length() ) );\n }", "public static boolean checkAddProperty(\r\n CmsCmisTypeManager typeManager,\r\n Properties properties,\r\n String typeId,\r\n Set<String> filter,\r\n String id) {\r\n\r\n if ((properties == null) || (properties.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Properties must not be null!\");\r\n }\r\n\r\n if (id == null) {\r\n throw new IllegalArgumentException(\"Id must not be null!\");\r\n }\r\n\r\n TypeDefinition type = typeManager.getType(typeId);\r\n if (type == null) {\r\n throw new IllegalArgumentException(\"Unknown type: \" + typeId);\r\n }\r\n if (!type.getPropertyDefinitions().containsKey(id)) {\r\n throw new IllegalArgumentException(\"Unknown property: \" + id);\r\n }\r\n\r\n String queryName = type.getPropertyDefinitions().get(id).getQueryName();\r\n\r\n if ((queryName != null) && (filter != null)) {\r\n if (!filter.contains(queryName)) {\r\n return false;\r\n } else {\r\n filter.remove(queryName);\r\n }\r\n }\r\n\r\n return true;\r\n }", "public void addIterator(OJBIterator iterator)\r\n {\r\n /**\r\n * only add iterators that are not null and non-empty.\r\n */\r\n if (iterator != null)\r\n {\r\n if (iterator.hasNext())\r\n {\r\n setNextIterator();\r\n m_rsIterators.add(iterator);\r\n }\r\n }\r\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 }", "public static String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\n }", "@Nonnull\n public static Proctor construct(@Nonnull final TestMatrixArtifact matrix, ProctorLoadResult loadResult, FunctionMapper functionMapper) {\n final ExpressionFactory expressionFactory = RuleEvaluator.EXPRESSION_FACTORY;\n\n final Map<String, TestChooser<?>> testChoosers = Maps.newLinkedHashMap();\n final Map<String, String> versions = Maps.newLinkedHashMap();\n\n for (final Entry<String, ConsumableTestDefinition> entry : matrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n final TestType testType = testDefinition.getTestType();\n final TestChooser<?> testChooser;\n if (TestType.RANDOM.equals(testType)) {\n testChooser = new RandomTestChooser(expressionFactory, functionMapper, testName, testDefinition);\n } else {\n testChooser = new StandardTestChooser(expressionFactory, functionMapper, testName, testDefinition);\n }\n testChoosers.put(testName, testChooser);\n versions.put(testName, testDefinition.getVersion());\n }\n\n return new Proctor(matrix, loadResult, testChoosers);\n }", "public List<GanttDesignerRemark.Task> getTask()\n {\n if (task == null)\n {\n task = new ArrayList<GanttDesignerRemark.Task>();\n }\n return this.task;\n }" ]
Get the contents from the request URL. @param url URL to get the response from @param layer the raster layer @return {@link InputStream} with the content @throws IOException cannot get content
[ "public InputStream getStream(String url, RasterLayer layer) throws IOException {\n\t\tif (layer instanceof ProxyLayerSupport) {\n\t\t\tProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;\n\t\t\tif (proxyLayer.isUseCache() && null != cacheManagerService) {\n\t\t\t\tObject cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);\n\t\t\t\tif (null != cachedObject) {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) cachedObject);\n\t\t\t\t} else {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);\n\t\t\t\t\tInputStream stream = super.getStream(url, proxyLayer);\n\t\t\t\t\tByteArrayOutputStream os = new ByteArrayOutputStream();\n\t\t\t\t\tint b;\n\t\t\t\t\twhile ((b = stream.read()) >= 0) {\n\t\t\t\t\t\tos.write(b);\n\t\t\t\t\t}\n\t\t\t\t\tcacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),\n\t\t\t\t\t\t\tgetLayerEnvelope(proxyLayer));\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) os.toByteArray());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn super.getStream(url, layer);\n\t}" ]
[ "public void setInvalidValues(final Set<String> invalidValues,\n final boolean isCaseSensitive,\n final String invalidValueErrorMessage) {\n if (isCaseSensitive) {\n this.invalidValues = invalidValues;\n } else {\n this.invalidValues = new HashSet<String>();\n for (String value : invalidValues) {\n this.invalidValues.add(value.toLowerCase());\n }\n }\n this.isCaseSensitive = isCaseSensitive;\n this.invalidValueErrorMessage = invalidValueErrorMessage;\n }", "protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) {\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createRollbackElement(entry);\n elements.add(element);\n }\n\n final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState();\n final String name = installedIdentity.getIdentity().getName();\n final IdentityImpl identity = new IdentityImpl(name, modification.getVersion());\n if (patchType == Patch.PatchType.CUMULATIVE) {\n identity.setPatchType(Patch.PatchType.CUMULATIVE);\n identity.setResultingVersion(installedIdentity.getIdentity().getVersion());\n } else if (patchType == Patch.PatchType.ONE_OFF) {\n identity.setPatchType(Patch.PatchType.ONE_OFF);\n }\n final List<ContentModification> modifications = identityEntry.rollbackActions;\n final Patch delegate = new PatchImpl(patchId, \"rollback patch\", identity, elements, modifications);\n return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity);\n }", "public static <IN extends CoreMap> CRFClassifier<IN> getClassifier(File file) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n CRFClassifier<IN> crf = new CRFClassifier<IN>();\r\n crf.loadClassifier(file);\r\n return crf;\r\n }", "public static String changeFirstLetterToCapital(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toUpperCase(a);\n return new String(letras);\n }", "public ItemRequest<Webhook> deleteById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"DELETE\");\n }", "private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }", "private void revisitGateways(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setGatewayInfo((Process) root);\n }\n }\n }", "public boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }", "private void ensureFields(ClassDescriptorDef classDef, Collection fields) throws ConstraintException\r\n {\r\n boolean forceVirtual = !classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true);\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n // First we check whether this field is already present in the class\r\n FieldDescriptorDef foundFieldDef = classDef.getField(fieldDef.getName());\r\n\r\n if (foundFieldDef != null)\r\n {\r\n if (isEqual(fieldDef, foundFieldDef))\r\n {\r\n if (forceVirtual)\r\n {\r\n foundFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n continue;\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a different field of the same name\");\r\n }\r\n }\r\n\r\n // perhaps a reference or collection ?\r\n if (classDef.getCollection(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a collection of the same name\");\r\n }\r\n if (classDef.getReference(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a reference of the same name\");\r\n }\r\n classDef.addFieldClone(fieldDef);\r\n classDef.getField(fieldDef.getName()).setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n }" ]
convenience factory method for the most usual case.
[ "public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException {\n MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry();\n MetaClass meta = metaRegistry.getMetaClass(theClass);\n return new ProxyMetaClass(metaRegistry, theClass, meta);\n }" ]
[ "public void useXopAttachmentServiceWithProxy() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments\";\n \n XopAttachmentService proxy = JAXRSClientFactory.create(serviceURI, \n XopAttachmentService.class);\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a proxy\");\n \n XopBean xopResponse = proxy.echoXopAttachment(xop);\n \n verifyXopResponse(xop, xopResponse);\n }", "private void handleSendDataRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Send Data Request\");\n\t\t\n\t\tint callbackId = incomingMessage.getMessagePayloadByte(0);\n\t\tTransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));\n\t\tSerialMessage originalMessage = this.lastSentMessage;\n\t\t\n\t\tif (status == null) {\n\t\t\tlogger.warn(\"Transmission state not found, ignoring.\");\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.debug(\"CallBack ID = {}\", callbackId);\n\t\tlogger.debug(String.format(\"Status = %s (0x%02x)\", status.getLabel(), status.getKey()));\n\t\t\n\t\tif (originalMessage == null || originalMessage.getCallbackId() != callbackId) {\n\t\t\tlogger.warn(\"Already processed another send data request for this callback Id, ignoring.\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tswitch (status) {\n\t\t\tcase COMPLETE_OK:\n\t\t\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\t// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.\n\t\t\t\tif (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {\n\t\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tif (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase COMPLETE_NO_ACK:\n\t\t\tcase COMPLETE_FAIL:\n\t\t\tcase COMPLETE_NOT_IDLE:\n\t\t\tcase COMPLETE_NOROUTE:\n\t\t\t\ttry {\n\t\t\t\t\thandleFailedSendDataRequest(originalMessage);\n\t\t\t\t} finally {\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\tdefault:\n\t\t}\n\t}", "private I_CmsFacetQueryItem parseFacetQueryItem(final String prefix) {\n\n I_CmsXmlContentValue query = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_QUERY, m_locale);\n if (null != query) {\n String queryString = query.getStringValue(null);\n I_CmsXmlContentValue label = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_LABEL, m_locale);\n String labelString = null != label ? label.getStringValue(null) : null;\n return new CmsFacetQueryItem(queryString, labelString);\n } else {\n return null;\n }\n }", "private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }", "public Object lookup(Identity oid)\r\n {\r\n Object ret = null;\r\n if (oid != null)\r\n {\r\n ObjectCache cache = getCache(oid, null, METHOD_LOOKUP);\r\n if (cache != null)\r\n {\r\n ret = cache.lookup(oid);\r\n }\r\n }\r\n return ret;\r\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean timeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }", "public <T extends Widget & Checkable> List<T> getCheckableChildren() {\n List<Widget> children = getChildren();\n ArrayList<T> result = new ArrayList<>();\n for (Widget c : children) {\n if (c instanceof Checkable) {\n result.add((T) c);\n }\n }\n return result;\n }", "public static base_responses update(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface updateresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new Interface();\n\t\t\t\tupdateresources[i].id = resources[i].id;\n\t\t\t\tupdateresources[i].speed = resources[i].speed;\n\t\t\t\tupdateresources[i].duplex = resources[i].duplex;\n\t\t\t\tupdateresources[i].flowctl = resources[i].flowctl;\n\t\t\t\tupdateresources[i].autoneg = resources[i].autoneg;\n\t\t\t\tupdateresources[i].hamonitor = resources[i].hamonitor;\n\t\t\t\tupdateresources[i].tagall = resources[i].tagall;\n\t\t\t\tupdateresources[i].trunk = resources[i].trunk;\n\t\t\t\tupdateresources[i].lacpmode = resources[i].lacpmode;\n\t\t\t\tupdateresources[i].lacpkey = resources[i].lacpkey;\n\t\t\t\tupdateresources[i].lagtype = resources[i].lagtype;\n\t\t\t\tupdateresources[i].lacppriority = resources[i].lacppriority;\n\t\t\t\tupdateresources[i].lacptimeout = resources[i].lacptimeout;\n\t\t\t\tupdateresources[i].ifalias = resources[i].ifalias;\n\t\t\t\tupdateresources[i].throughput = resources[i].throughput;\n\t\t\t\tupdateresources[i].bandwidthhigh = resources[i].bandwidthhigh;\n\t\t\t\tupdateresources[i].bandwidthnormal = resources[i].bandwidthnormal;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static int cudnnGetActivationDescriptor(\n cudnnActivationDescriptor activationDesc, \n int[] mode, \n int[] reluNanOpt, \n double[] coef)/** ceiling for clipped RELU, alpha for ELU */\n {\n return checkResult(cudnnGetActivationDescriptorNative(activationDesc, mode, reluNanOpt, coef));\n }" ]
Parse init parameter for integer value, returning default if not found or invalid
[ "protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {\n final String parameterString = servletContext.getInitParameter(parameterName);\n if(parameterString != null && parameterString.trim().length() > 0) {\n try {\n return Integer.parseInt(parameterString);\n }\n catch (NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return defaultValue;\n }" ]
[ "@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}", "public void getRepresentationContent(String representationHint, String assetPath, OutputStream output) {\n\n List<Representation> reps = this.getInfoWithRepresentations(representationHint).getRepresentations();\n if (reps.size() < 1) {\n throw new BoxAPIException(\"No matching representations found\");\n }\n Representation representation = reps.get(0);\n String repState = representation.getStatus().getState();\n\n if (repState.equals(\"viewable\") || repState.equals(\"success\")) {\n\n this.makeRepresentationContentRequest(representation.getContent().getUrlTemplate(),\n assetPath, output);\n return;\n } else if (repState.equals(\"pending\") || repState.equals(\"none\")) {\n\n String repContentURLString = null;\n while (repContentURLString == null) {\n repContentURLString = this.pollRepInfo(representation.getInfo().getUrl());\n }\n\n this.makeRepresentationContentRequest(repContentURLString, assetPath, output);\n return;\n\n } else if (repState.equals(\"error\")) {\n\n throw new BoxAPIException(\"Representation had error status\");\n } else {\n\n throw new BoxAPIException(\"Representation had unknown status\");\n }\n\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 }", "@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }", "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {\n ResourceRootIndexer.indexResourceRoot(resourceRoot);\n }\n }", "public static base_response update(nitro_service client, aaaparameter resource) throws Exception {\n\t\taaaparameter updateresource = new aaaparameter();\n\t\tupdateresource.enablestaticpagecaching = resource.enablestaticpagecaching;\n\t\tupdateresource.enableenhancedauthfeedback = resource.enableenhancedauthfeedback;\n\t\tupdateresource.defaultauthtype = resource.defaultauthtype;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.maxloginattempts = resource.maxloginattempts;\n\t\tupdateresource.failedlogintimeout = resource.failedlogintimeout;\n\t\tupdateresource.aaadnatip = resource.aaadnatip;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }", "@Override\n public void prettyPrint(StringBuffer sb, int indent)\n {\n sb.append(Log.getSpaces(indent));\n sb.append(GVRBone.class.getSimpleName());\n sb.append(\" [name=\" + getName() + \", boneId=\" + getBoneId()\n + \", offsetMatrix=\" + getOffsetMatrix()\n + \", finalTransformMatrix=\" + getFinalTransformMatrix() // crashes debugger\n + \"]\");\n sb.append(System.lineSeparator());\n }", "@RequestMapping(value = \"api/servergroup\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerGroup createServerGroup(Model model,\n @RequestParam(value = \"name\") String name,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId);\n return ServerRedirectService.getInstance().getServerGroup(groupId, profileId);\n }" ]
Sets a listener to inform when the user closes the SearchView. @param listener the listener to call when the user closes the SearchView.
[ "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 }" ]
[ "static GVROrthogonalCamera makeOrthoShadowCamera(GVRPerspectiveCamera centerCam)\n {\n GVROrthogonalCamera shadowCam = new GVROrthogonalCamera(centerCam.getGVRContext());\n float near = centerCam.getNearClippingDistance();\n float far = centerCam.getFarClippingDistance();\n float fovy = (float) Math.toRadians(centerCam.getFovY());\n float h = (float) (Math.atan(fovy / 2.0f) * far) / 2.0f;\n\n shadowCam.setLeftClippingDistance(-h);\n shadowCam.setRightClippingDistance(h);\n shadowCam.setTopClippingDistance(h);\n shadowCam.setBottomClippingDistance(-h);\n shadowCam.setNearClippingDistance(near);\n shadowCam.setFarClippingDistance(far);\n return shadowCam;\n }", "public synchronized boolean tryDelegateResponseHandling(Response<ByteArray, Object> response) {\n if(responseHandlingCutoff) {\n return false;\n } else {\n responseQueue.offer(response);\n this.notifyAll();\n return true;\n }\n }", "@Override\n\tpublic Object[] getDatabaseSnapshot(Serializable id, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting current persistent state for: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\n\t\t//snapshot is a Map in the end\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\t//if there is no resulting row, return null\n\t\tif ( resultset == null || resultset.getSnapshot().isEmpty() ) {\n\t\t\treturn null;\n\t\t}\n\t\t//otherwise return the \"hydrated\" state (ie. associations are not resolved)\n\t\tGridType[] types = gridPropertyTypes;\n\t\tObject[] values = new Object[types.length];\n\t\tboolean[] includeProperty = getPropertyUpdateability();\n\t\tfor ( int i = 0; i < types.length; i++ ) {\n\t\t\tif ( includeProperty[i] ) {\n\t\t\t\tvalues[i] = types[i].hydrate( resultset, getPropertyAliases( \"\", i ), session, null ); //null owner ok??\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}", "@SuppressWarnings(\"unchecked\")\n public <T> T getOptionValue(String name)\n {\n return (T) configurationOptions.get(name);\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 }", "public boolean ignoreOperation(final Resource domainResource, final Collection<ServerConfigInfo> serverConfigs, final PathAddress pathAddress) {\n if (pathAddress.size() == 0) {\n return false;\n }\n boolean ignore = ignoreResourceInternal(domainResource, serverConfigs, pathAddress);\n return ignore;\n }", "public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }", "private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }", "public int getIndexMax() {\n int indexMax = 0;\n double max = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m > max ) {\n max = m;\n indexMax = i;\n }\n }\n\n return indexMax;\n }" ]
Set the locking values @param cld @param obj @param oldLockingValues
[ "private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)\r\n {\r\n FieldDescriptor fields[] = cld.getLockingFields();\r\n\r\n for (int i=0; i<fields.length; i++)\r\n {\r\n PersistentField field = fields[i].getPersistentField();\r\n Object lockVal = oldLockingValues[i].getValue();\r\n\r\n field.set(obj, lockVal);\r\n }\r\n }" ]
[ "public static aaagroup_aaauser_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_aaauser_binding obj = new aaagroup_aaauser_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_aaauser_binding response[] = (aaagroup_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\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 }", "public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "private Serializable doWorkInIsolationTransaction(final SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\tclass Work extends AbstractReturningWork<IntegralDataTypeHolder> {\n\t\t\tprivate final SharedSessionContractImplementor localSession = session;\n\n\t\t\t@Override\n\t\t\tpublic IntegralDataTypeHolder execute(Connection connection) throws SQLException {\n\t\t\t\ttry {\n\t\t\t\t\treturn doWorkInCurrentTransactionIfAny( localSession );\n\t\t\t\t}\n\t\t\t\tcatch ( RuntimeException sqle ) {\n\t\t\t\t\tthrow new HibernateException( \"Could not get or update next value\", sqle );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//we want to work out of transaction\n\t\tboolean workInTransaction = false;\n\t\tWork work = new Work();\n\t\tSerializable generatedValue = session.getTransactionCoordinator().createIsolationDelegate().delegateWork( work, workInTransaction );\n\t\treturn generatedValue;\n\t}", "public void process(SearchDistributor distributor) {\r\n List<PossibleState> bootStrap;\r\n try {\r\n bootStrap = bfs(bootStrapMin);\r\n } catch (ModelException e) {\r\n bootStrap = new LinkedList<>();\r\n }\n\r\n List<Frontier> frontiers = new LinkedList<>();\r\n for (PossibleState p : bootStrap) {\r\n SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList);\r\n frontiers.add(dge);\r\n }\n\r\n distributor.distribute(frontiers);\r\n }", "public String getBaselineDurationText()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }", "protected void populateTasksByStealer(List<StealerBasedRebalanceTask> sbTaskList) {\n // Setup mapping of stealers to work for this run.\n for(StealerBasedRebalanceTask task: sbTaskList) {\n if(task.getStealInfos().size() != 1) {\n throw new VoldemortException(\"StealerBasedRebalanceTasks should have a list of RebalancePartitionsInfo of length 1.\");\n }\n\n RebalanceTaskInfo stealInfo = task.getStealInfos().get(0);\n int stealerId = stealInfo.getStealerId();\n if(!this.tasksByStealer.containsKey(stealerId)) {\n this.tasksByStealer.put(stealerId, new ArrayList<StealerBasedRebalanceTask>());\n }\n this.tasksByStealer.get(stealerId).add(task);\n }\n\n if(tasksByStealer.isEmpty()) {\n return;\n }\n // Shuffle order of each stealer's work list. This randomization\n // helps to get rid of any \"patterns\" in how rebalancing tasks were\n // added to the task list passed in.\n for(List<StealerBasedRebalanceTask> taskList: tasksByStealer.values()) {\n Collections.shuffle(taskList);\n }\n }", "public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n return client;\n }", "protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}" ]
Writes a list of UDF types. @author lsong @param type parent entity type @param mpxj parent entity @return list of UDFAssignmentType instances
[ "private List<UDFAssignmentType> writeUDFType(FieldTypeClass type, FieldContainer mpxj)\n {\n List<UDFAssignmentType> out = new ArrayList<UDFAssignmentType>();\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n FieldType fieldType = cf.getFieldType();\n if (fieldType != null && type == fieldType.getFieldTypeClass())\n {\n Object value = mpxj.getCachedValue(fieldType);\n if (FieldTypeHelper.valueIsNotDefault(fieldType, value))\n {\n UDFAssignmentType udf = m_factory.createUDFAssignmentType();\n udf.setTypeObjectId(FieldTypeHelper.getFieldID(fieldType));\n setUserFieldValue(udf, fieldType.getDataType(), value);\n out.add(udf);\n }\n }\n }\n return out;\n }" ]
[ "public static <T, R extends Resource<T>> T getEntity(R resource) {\n return resource.getEntity();\n }", "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 PasswordSpec parse(String spec) {\n char[] ca = spec.toCharArray();\n int len = ca.length;\n illegalIf(0 == len, spec);\n Builder builder = new Builder();\n StringBuilder minBuf = new StringBuilder();\n StringBuilder maxBuf = new StringBuilder();\n boolean lenSpecStart = false;\n boolean minPart = false;\n for (int i = 0; i < len; ++i) {\n char c = ca[i];\n switch (c) {\n case SPEC_LOWERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireLowercase();\n break;\n case SPEC_UPPERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireUppercase();\n break;\n case SPEC_SPECIAL_CHAR:\n illegalIf(lenSpecStart, spec);\n builder.requireSpecialChar();\n break;\n case SPEC_LENSPEC_START:\n lenSpecStart = true;\n minPart = true;\n break;\n case SPEC_LENSPEC_CLOSE:\n illegalIf(minPart, spec);\n lenSpecStart = false;\n break;\n case SPEC_LENSPEC_SEP:\n minPart = false;\n break;\n case SPEC_DIGIT:\n if (!lenSpecStart) {\n builder.requireDigit();\n } else {\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n break;\n default:\n illegalIf(!lenSpecStart || !isDigit(c), spec);\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n }\n illegalIf(lenSpecStart, spec);\n if (minBuf.length() != 0) {\n builder.minLength(Integer.parseInt(minBuf.toString()));\n }\n if (maxBuf.length() != 0) {\n builder.maxLength(Integer.parseInt(maxBuf.toString()));\n }\n return builder;\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 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 static base_response rename(nitro_service client, nsacl6 resource, String new_acl6name) throws Exception {\n\t\tnsacl6 renameresource = new nsacl6();\n\t\trenameresource.acl6name = resource.acl6name;\n\t\treturn renameresource.rename_resource(client,new_acl6name);\n\t}", "public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }", "@Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n try {\n if (exceptionRaised.get()) {\n return;\n }\n\n if (!(msg instanceof HttpRequest)) {\n // If there is no methodInfo, it means the request was already rejected.\n // What we received here is just residue of the request, which can be ignored.\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n }\n return;\n }\n HttpRequest request = (HttpRequest) msg;\n BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled);\n\n // Reset the methodInfo for the incoming request error handling\n methodInfo = null;\n methodInfo = prepareHandleMethod(request, responder, ctx);\n\n if (methodInfo != null) {\n ReferenceCountUtil.retain(msg);\n ctx.fireChannelRead(msg);\n } else {\n if (!responder.isResponded()) {\n // If not yet responded, just respond with a not found and close the connection\n HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);\n HttpUtil.setContentLength(response, 0);\n HttpUtil.setKeepAlive(response, false);\n ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);\n } else {\n // If already responded, just close the connection\n ctx.channel().close();\n }\n }\n } finally {\n ReferenceCountUtil.release(msg);\n }\n }", "protected boolean isReserved( String name ) {\n if( functions.isFunctionName(name))\n return true;\n\n for (int i = 0; i < name.length(); i++) {\n if( !isLetter(name.charAt(i)) )\n return true;\n }\n return false;\n }" ]
Applies the matrices computed from the scene object's linked to the skeleton bones to the current pose. @see #applyPose(GVRPose, int) @see #setPose(GVRPose)
[ "public void poseFromBones()\n {\n for (int i = 0; i < getNumBones(); ++i)\n {\n GVRSceneObject bone = mBones[i];\n if (bone == null)\n {\n continue;\n }\n if ((mBoneOptions[i] & BONE_LOCK_ROTATION) != 0)\n {\n continue;\n }\n GVRTransform trans = bone.getTransform();\n mPose.setLocalMatrix(i, trans.getLocalModelMatrix4f());\n }\n mPose.sync();\n updateBonePose();\n }" ]
[ "public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }", "public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }", "private long getTotalTime(ProjectCalendarDateRanges hours, Date startDate, Date endDate)\n {\n long total = 0;\n if (startDate.getTime() != endDate.getTime())\n {\n Date start = DateHelper.getCanonicalTime(startDate);\n Date end = DateHelper.getCanonicalTime(endDate);\n\n for (DateRange range : hours)\n {\n Date rangeStart = range.getStart();\n Date rangeEnd = range.getEnd();\n if (rangeStart != null && rangeEnd != null)\n {\n Date canoncialRangeStart = DateHelper.getCanonicalTime(rangeStart);\n Date canonicalRangeEnd = DateHelper.getCanonicalTime(rangeEnd);\n\n Date startDay = DateHelper.getDayStartDate(rangeStart);\n Date finishDay = DateHelper.getDayStartDate(rangeEnd);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n canonicalRangeEnd = DateHelper.addDays(canonicalRangeEnd, 1);\n }\n\n if (canoncialRangeStart.getTime() == canonicalRangeEnd.getTime() && rangeEnd.getTime() > rangeStart.getTime())\n {\n total += (24 * 60 * 60 * 1000);\n }\n else\n {\n total += getTime(start, end, canoncialRangeStart, canonicalRangeEnd);\n }\n }\n }\n }\n\n return (total);\n }", "protected Iterable<URI> getTargetURIs(final EObject primaryTarget) {\n\t\tfinal TargetURIs result = targetURIsProvider.get();\n\t\turiCollector.add(primaryTarget, result);\n\t\treturn result;\n\t}", "public Object copy(Object obj, PersistenceBroker broker)\r\n\t\t\tthrows ObjectCopyException\r\n\t{\r\n\t\tif (obj instanceof OjbCloneable)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\treturn ((OjbCloneable) obj).ojbClone();\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new ObjectCopyException(\"Object must implement OjbCloneable in order to use the\"\r\n\t\t\t\t\t\t\t\t\t\t + \" CloneableObjectCopyStrategy\");\r\n\t\t}\r\n\t}", "private void addCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = generateCheckBox(date, checkState);\n m_checkBoxes.add(cb);\n reInitLayoutElements();\n\n }", "public static Object buildNewObjectInstance(ClassDescriptor cld)\r\n {\r\n Object result = null;\r\n\r\n // If either the factory class and/or factory method is null,\r\n // just follow the normal code path and create via constructor\r\n if ((cld.getFactoryClass() == null) || (cld.getFactoryMethod() == null))\r\n {\r\n try\r\n {\r\n // 1. create an empty Object (persistent classes need a public default constructor)\r\n Constructor con = cld.getZeroArgumentConstructor();\r\n if(con == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided! Class was '\" + cld.getClassNameOfObject() + \"'\");\r\n }\r\n result = ConstructorHelper.instantiate(con);\r\n }\r\n catch (InstantiationException e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"Can't instantiate class '\" + cld.getClassNameOfObject()+\"'\");\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n // 1. create an empty Object by calling the no-parms factory method\r\n Method method = cld.getFactoryMethod();\r\n\r\n if (Modifier.isStatic(method.getModifiers()))\r\n {\r\n // method is static so call it directly\r\n result = method.invoke(null, null);\r\n }\r\n else\r\n {\r\n // method is not static, so create an object of the factory first\r\n // note that this requires a public no-parameter (default) constructor\r\n Object factoryInstance = cld.getFactoryClass().newInstance();\r\n\r\n result = method.invoke(factoryInstance, null);\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to build object instance of class '\"\r\n + cld.getClassNameOfObject() + \"' from factory:\" + cld.getFactoryClass()\r\n + \".\" + cld.getFactoryMethod(), ex);\r\n }\r\n }\r\n return result;\r\n }", "public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static clusterinstance[] get(nitro_service service, Long clid[]) throws Exception{\n\t\tif (clid !=null && clid.length>0) {\n\t\t\tclusterinstance response[] = new clusterinstance[clid.length];\n\t\t\tclusterinstance obj[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++) {\n\t\t\t\tobj[i] = new clusterinstance();\n\t\t\t\tobj[i].set_clid(clid[i]);\n\t\t\t\tresponse[i] = (clusterinstance) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
Adds a new Token to the end of the linked list
[ "public void push( Token token ) {\n size++;\n if( first == null ) {\n first = token;\n last = token;\n token.previous = null;\n token.next = null;\n } else {\n last.next = token;\n token.previous = last;\n token.next = null;\n last = token;\n }\n }" ]
[ "public static vpnsessionpolicy_aaauser_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionpolicy_aaauser_binding obj = new vpnsessionpolicy_aaauser_binding();\n\t\tobj.set_name(name);\n\t\tvpnsessionpolicy_aaauser_binding response[] = (vpnsessionpolicy_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }", "static EntityIdValue fromId(String id, String siteIri) {\n\t\tswitch (guessEntityTypeFromId(id)) {\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM:\n\t\t\t\treturn new ItemIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY:\n\t\t\t\treturn new PropertyIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_LEXEME:\n\t\t\t\treturn new LexemeIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_FORM:\n\t\t\t\treturn new FormIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_SENSE:\n\t\t\t\treturn new SenseIdValueImpl(id, siteIri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}", "private static JsonParser newJsonParserForNode(JsonNode jsonNode) throws IOException {\n JsonParser parser = new JsonFactory().createParser(jsonNode.toString());\n parser.nextToken();\n return parser;\n }", "public int indexOfKey(Object key) {\n return key == null ? indexOfNull() : indexOf(key, key.hashCode());\n }", "public static KieRuntimeLogger newFileLogger(KieRuntimeEventManager session,\n String fileName) {\n return getKnowledgeRuntimeLoggerProvider().newFileLogger( session,\n fileName );\n }", "public void applyToBackground(View view) {\n if (mColorInt != 0) {\n view.setBackgroundColor(mColorInt);\n } else if (mColorRes != -1) {\n view.setBackgroundResource(mColorRes);\n }\n }", "private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }", "public static base_response unset(nitro_service client, systemcollectionparam resource, String[] args) throws Exception{\n\t\tsystemcollectionparam unsetresource = new systemcollectionparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Performs the actual spell check query using Solr. @param request the spell check request @return Results of the Solr spell check of type SpellCheckResponse or null if something goes wrong.
[ "private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) {\n\n if ((null == request) || !request.isInitialized()) {\n return null;\n }\n\n final String[] wordsToCheck = request.m_wordsToCheck;\n\n final ModifiableSolrParams params = new ModifiableSolrParams();\n params.set(\"spellcheck\", \"true\");\n params.set(\"spellcheck.dictionary\", request.m_dictionaryToUse);\n params.set(\"spellcheck.extendedResults\", \"true\");\n\n // Build one string from array of words and use it as query.\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < wordsToCheck.length; i++) {\n builder.append(wordsToCheck[i] + \" \");\n }\n\n params.set(\"spellcheck.q\", builder.toString());\n\n final SolrQuery query = new SolrQuery();\n query.setRequestHandler(\"/spell\");\n query.add(params);\n\n try {\n QueryResponse qres = m_solrClient.query(query);\n return qres.getSpellCheckResponse();\n } catch (Exception e) {\n LOG.debug(\"Exception while performing spellcheck query...\", e);\n }\n\n return null;\n }" ]
[ "public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {\n\t\tif (clazz1 == null) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tif (clazz2 == null) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz1.isAssignableFrom(clazz2)) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz2.isAssignableFrom(clazz1)) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tClass<?> ancestor = clazz1;\n\t\tdo {\n\t\t\tancestor = ancestor.getSuperclass();\n\t\t\tif (ancestor == null || Object.class.equals(ancestor)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\twhile (!ancestor.isAssignableFrom(clazz2));\n\t\treturn ancestor;\n\t}", "public static String pennPOSToWordnetPOS(String s) {\r\n if (s.matches(\"NN|NNP|NNS|NNPS\")) {\r\n return \"noun\";\r\n }\r\n if (s.matches(\"VB|VBD|VBG|VBN|VBZ|VBP|MD\")) {\r\n return \"verb\";\r\n }\r\n if (s.matches(\"JJ|JJR|JJS|CD\")) {\r\n return \"adjective\";\r\n }\r\n if (s.matches(\"RB|RBR|RBS|RP|WRB\")) {\r\n return \"adverb\";\r\n }\r\n return null;\r\n }", "private Map<String, Table> getIndex(Table table)\n {\n Map<String, Table> result;\n\n if (!table.getResourceFlag())\n {\n result = m_taskTablesByName;\n }\n else\n {\n result = m_resourceTablesByName;\n }\n return result;\n }", "public static Iterable<Metadata> getAllMetadata(BoxItem item, String ... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new BoxResourceIterable<Metadata>(\n item.getAPI(),\n GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery(item.getItemURL().toString(), builder.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected Metadata factory(JsonObject jsonObject) {\n return new Metadata(jsonObject);\n }\n\n };\n }", "public void addCollaborator(String appName, String collaborator) {\n connection.execute(new SharingAdd(appName, collaborator), apiKey);\n }", "public boolean endsWith(Bytes suffix) {\n Objects.requireNonNull(suffix, \"endsWith(Bytes suffix) cannot have null parameter\");\n int startOffset = this.length - suffix.length;\n\n if (startOffset < 0) {\n return false;\n } else {\n int end = startOffset + this.offset + suffix.length;\n for (int i = startOffset + this.offset, j = suffix.offset; i < end; i++, j++) {\n if (this.data[i] != suffix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }", "public static base_responses clear(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable clearresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new bridgetable();\n\t\t\t\tclearresources[i].vlan = resources[i].vlan;\n\t\t\t\tclearresources[i].ifnum = resources[i].ifnum;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}", "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 static int abs(int a) {\n if(a >= 0)\n return a;\n else if(a != Integer.MIN_VALUE)\n return -a;\n return Integer.MAX_VALUE;\n }" ]
FastJSON does not provide the API so we have to create our own
[ "private static final void writeJson(Writer os, //\n Object object, //\n SerializeConfig config, //\n SerializeFilter[] filters, //\n DateFormat dateFormat, //\n int defaultFeatures, //\n SerializerFeature... features) {\n SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);\n\n try {\n JSONSerializer serializer = new JSONSerializer(writer, config);\n\n if (dateFormat != null) {\n serializer.setDateFormat(dateFormat);\n serializer.config(SerializerFeature.WriteDateUseDateFormat, true);\n }\n\n if (filters != null) {\n for (SerializeFilter filter : filters) {\n serializer.addFilter(filter);\n }\n }\n serializer.write(object);\n } finally {\n writer.close();\n }\n }" ]
[ "public void executeDelete(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeDelete: \" + obj);\r\n }\r\n\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getDeleteStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getDeleteStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"JdbcAccessImpl: getDeleteStatement returned a null statement\");\r\n }\r\n\r\n sm.bindDelete(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeDelete: \" + stmt);\r\n\r\n // @todo: clearify semantics\r\n // thma: the following check is not secure. The object could be deleted *or* changed.\r\n // if it was deleted it makes no sense to throw an OL exception.\r\n // does is make sense to throw an OL exception if the object was changed?\r\n if (stmt.executeUpdate() == 0 && cld.isLocking()) //BRJ\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tString objToString = \"\";\r\n \ttry {\r\n \t\tobjToString = obj.toString();\r\n \t} catch (Exception ex) {}\r\n throw new OptimisticLockException(\"Object has been modified or deleted by someone else: \" + objToString, obj);\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getDeleteProcedure(), obj, stmt);\r\n }\r\n catch (OptimisticLockException e)\r\n {\r\n // Don't log as error\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"OptimisticLockException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedDeleteStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }", "private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes,\tComponent component) {\n Long currentTimeOfComponent = 0L;\n String key = component.getComponentType();\n if (mapComponentTimes.containsKey(key)) {\n currentTimeOfComponent = mapComponentTimes.get(key);\n }\n //when transactions are run in parallel, we should log the longest transaction only to avoid that \n //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms \n Long maxTime = Math.max(component.getTime(), currentTimeOfComponent);\n mapComponentTimes.put(key, maxTime);\n }", "public void setSize(ButtonSize size) {\n if (this.size != null) {\n removeStyleName(this.size.getCssName());\n }\n this.size = size;\n\n if (size != null) {\n addStyleName(size.getCssName());\n }\n }", "public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) {\n final DbArtifact artifact = getArtifact(gavc);\n final List<DbLicense> licenses = new ArrayList<>();\n\n for(final String name: artifact.getLicenses()){\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name);\n\n // Here is a license to identify\n if(matchingLicenses.isEmpty()){\n final DbLicense notIdentifiedLicense = new DbLicense();\n notIdentifiedLicense.setName(name);\n licenses.add(notIdentifiedLicense);\n } else {\n matchingLicenses.stream()\n .filter(filters::shouldBeInReport)\n .forEach(licenses::add);\n }\n }\n\n return licenses;\n }", "public final void notifyContentItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (position < 0 || position >= newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for content items [0 - \" + (newContentItemCount - 1) + \"].\");\n }\n notifyItemInserted(position + newHeaderItemCount);\n }", "private Map<String, Table> getIndex(Table table)\n {\n Map<String, Table> result;\n\n if (!table.getResourceFlag())\n {\n result = m_taskTablesByName;\n }\n else\n {\n result = m_resourceTablesByName;\n }\n return result;\n }", "public static sslglobal_sslpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslglobal_sslpolicy_binding[] response = (sslglobal_sslpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public void setSlideDrawable(Drawable drawable) {\n mSlideDrawable = new SlideDrawable(drawable);\n mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL);\n\n if (mActionBarHelper != null) {\n mActionBarHelper.setDisplayShowHomeAsUpEnabled(true);\n\n if (mDrawerIndicatorEnabled) {\n mActionBarHelper.setActionBarUpIndicator(mSlideDrawable,\n isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc);\n }\n }\n }", "@Override\n public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
Modify the tranform's current rotation in quaternion terms, around a pivot other than the origin. @param w 'W' component of the quaternion. @param x 'X' component of the quaternion. @param y 'Y' component of the quaternion. @param z 'Z' component of the quaternion. @param pivotX 'X' component of the pivot's location. @param pivotY 'Y' component of the pivot's location. @param pivotZ 'Z' component of the pivot's location.
[ "public void rotateWithPivot(float w, float x, float y, float z,\n float pivotX, float pivotY, float pivotZ) {\n getTransform().rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ);\n if (mTransformCache.rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ)) {\n onTransformChanged();\n }\n }" ]
[ "public void postPhoto(Photo photo, String blogId, String blogPassword) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_POST_PHOTO);\r\n\r\n parameters.put(\"blog_id\", blogId);\r\n parameters.put(\"photo_id\", photo.getId());\r\n parameters.put(\"title\", photo.getTitle());\r\n parameters.put(\"description\", photo.getDescription());\r\n if (blogPassword != null) {\r\n parameters.put(\"blog_password\", blogPassword);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\n }\n }", "public void remove(RowKey key) {\n\t\tcurrentState.put( key, new AssociationOperation( key, null, REMOVE ) );\n\t}", "public void close()\n {\n if (transac_open)\n {\n try\n {\n this._cnx.rollback();\n }\n catch (Exception e)\n {\n // Ignore.\n }\n }\n\n for (Statement s : toClose)\n {\n closeQuietly(s);\n }\n toClose.clear();\n\n closeQuietly(_cnx);\n _cnx = null;\n }", "public List<Task> getActiveTasks() {\n InputStream response = null;\n URI uri = new URIBase(getBaseUri()).path(\"_active_tasks\").build();\n try {\n response = couchDbClient.get(uri);\n return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS);\n } finally {\n close(response);\n }\n }", "private String getCurrencyFormat(CurrencySymbolPosition position)\n {\n String result;\n\n switch (position)\n {\n case AFTER:\n {\n result = \"1.1#\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"1.1 #\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"# 1.1\";\n break;\n }\n\n default:\n case BEFORE:\n {\n result = \"#1.1\";\n break;\n }\n }\n\n return result;\n }", "public static final Integer getInteger(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return ((Integer) bundle.getObject(key));\n }", "static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final\n ViewQueryParameters<K, V> initialParameters) {\n\n // Decode the base64 token into JSON\n String json = new String(Base64.decodeBase64(paginationToken), Charset.forName(\"UTF-8\"));\n\n // Get a suitable Gson, we need any adapter registered for the K key type\n Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters);\n\n // Deserialize the pagination token JSON, using the appropriate K, V types\n PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class);\n\n // Create new query parameters using the initial ViewQueryParameters as a starting point.\n ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy();\n\n // Merge the values from the token into the new query parameters\n tokenPageParameters.descending = token.descending;\n tokenPageParameters.endkey = token.endkey;\n tokenPageParameters.endkey_docid = token.endkey_docid;\n tokenPageParameters.inclusive_end = token.inclusive_end;\n tokenPageParameters.startkey = token.startkey;\n tokenPageParameters.startkey_docid = token.startkey_docid;\n\n return new PageMetadata<K, V>(token.direction, token\n .pageNumber, tokenPageParameters);\n }", "public boolean getCritical()\n {\n Boolean critical = (Boolean) getCachedValue(TaskField.CRITICAL);\n if (critical == null)\n {\n Duration totalSlack = getTotalSlack();\n ProjectProperties props = getParentFile().getProjectProperties();\n int criticalSlackLimit = NumberHelper.getInt(props.getCriticalSlackLimit());\n if (criticalSlackLimit != 0 && totalSlack.getDuration() != 0 && totalSlack.getUnits() != TimeUnit.DAYS)\n {\n totalSlack = totalSlack.convertUnits(TimeUnit.DAYS, props);\n }\n critical = Boolean.valueOf(totalSlack.getDuration() <= criticalSlackLimit && NumberHelper.getInt(getPercentageComplete()) != 100 && ((getTaskMode() == TaskMode.AUTO_SCHEDULED) || (getDurationText() == null && getStartText() == null && getFinishText() == null)));\n set(TaskField.CRITICAL, critical);\n }\n return (BooleanHelper.getBoolean(critical));\n }" ]
Cleans up the given group and adds it to the list of groups if still valid @param group @param groups
[ "private void addGroup(List<Token> group, List<List<Token>> groups) {\n\n if(group.isEmpty()) return;\n\n // remove trailing tokens that should be ignored\n while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains(\n group.get(group.size() - 1).getType())) {\n group.remove(group.size() - 1);\n }\n\n // if the group still has some tokens left, we'll add it to our list of groups\n if(!group.isEmpty()) {\n groups.add(group);\n }\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 void setRightTableModel(TableModel model)\n {\n TableModel old = m_rightTable.getModel();\n m_rightTable.setModel(model);\n firePropertyChange(\"rightTableModel\", old, model);\n }", "public final void setVolumeByIncrement(float level) throws IOException {\n Volume volume = this.getStatus().volume;\n float total = volume.level;\n\n if (volume.increment <= 0f) {\n throw new ChromeCastException(\"Volume.increment is <= 0\");\n }\n\n // With floating points we always have minor decimal variations, using the Math.min/max\n // works around this issue\n // Increase volume\n if (level > total) {\n while (total < level) {\n total = Math.min(total + volume.increment, level);\n setVolume(total);\n }\n // Decrease Volume\n } else if (level < total) {\n while (total > level) {\n total = Math.max(total - volume.increment, level);\n setVolume(total);\n }\n }\n }", "public Location getInfo(String placeId, String woeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "static void rethrowIrrecoverableConnectionFailures(IOException e) throws SlaveRegistrationException {\n Throwable cause = e;\n while ((cause = cause.getCause()) != null) {\n if (cause instanceof SaslException) {\n throw HostControllerLogger.ROOT_LOGGER.authenticationFailureUnableToConnect(cause);\n } else if (cause instanceof SSLHandshakeException) {\n throw HostControllerLogger.ROOT_LOGGER.sslFailureUnableToConnect(cause);\n } else if (cause instanceof SlaveRegistrationException) {\n throw (SlaveRegistrationException) cause;\n }\n }\n }", "public BoxFileUploadSessionPartList listParts(int offset, int limit) {\n URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint();\n URLTemplate template = new URLTemplate(listPartsURL.toString());\n\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(OFFSET_QUERY_STRING, offset);\n String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString();\n\n //Template is initalized with the full URL. So empty string for the path.\n URL url = template.buildWithQuery(\"\", queryString);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n return new BoxFileUploadSessionPartList(jsonObject);\n }", "private Object getLiteralValue(Expression expression) {\n\t\tif (!(expression instanceof Literal)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a Literal.\");\n\t\t}\n\t\treturn ((Literal) expression).getValue();\n\t}", "public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }", "public void fillFromToWith(int from, int to, Object val) {\r\n\tcheckRangeFromTo(from,to,this.size);\r\n\tfor (int i=from; i<=to;) setQuick(i++,val); \r\n}" ]
Reads the configuration of a field facet. @param pathPrefix The XML Path that leads to the field facet configuration, or <code>null</code> if the XML was not correctly structured. @return The read configuration, or <code>null</code> if the XML was not correctly structured.
[ "protected I_CmsSearchConfigurationFacetField parseFieldFacet(final String pathPrefix) {\n\n try {\n final String field = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_FACET_FIELD);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final Integer limit = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_LIMIT);\n final String prefix = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_PREFIX);\n final String sorder = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (@SuppressWarnings(\"unused\") final Exception e) {\n order = null;\n }\n final String filterQueryModifier = parseOptionalStringValue(\n pathPrefix + XML_ELEMENT_FACET_FILTERQUERYMODIFIER);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_FACET_FIELD),\n e);\n return null;\n }\n }" ]
[ "@SuppressWarnings(\"SameParameterValue\")\n private void assembleAndSendPacket(Util.PacketType kind, byte[] payload, InetAddress destination, int port) throws IOException {\n DatagramPacket packet = Util.buildPacket(kind,\n ByteBuffer.wrap(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH).asReadOnlyBuffer(),\n ByteBuffer.wrap(payload));\n packet.setAddress(destination);\n packet.setPort(port);\n socket.get().send(packet);\n }", "public static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\n }", "public long getTimeFor(int player) {\n TrackPositionUpdate update = positions.get(player);\n if (update != null) {\n return interpolateTimeSinceUpdate(update, System.nanoTime());\n }\n return -1; // We don't know.\n }", "private static void writeUtf16Bom(OutputStream stream, boolean bigEndian) throws IOException {\n if (bigEndian) {\n stream.write(-2);\n stream.write(-1);\n } else {\n stream.write(-1);\n stream.write(-2);\n }\n }", "private void exportModules() {\n\n // avoid to export modules if unnecessary\n if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue())\n || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) {\n m_logStream.println();\n m_logStream.println(\"NOT EXPORTING MODULES - you disabled copy and unzip.\");\n m_logStream.println();\n return;\n }\n CmsModuleManager moduleManager = OpenCms.getModuleManager();\n\n Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty())\n ? m_currentConfiguration.getConfiguredModules()\n : m_modulesToExport;\n\n for (String moduleName : modulesToExport) {\n CmsModule module = moduleManager.getModule(moduleName);\n if (module != null) {\n CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler(\n getCmsObject(),\n module,\n \"Git export handler\");\n try {\n handler.exportData(\n getCmsObject(),\n new CmsPrintStreamReport(\n m_logStream,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()),\n false));\n } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) {\n e.printStackTrace(m_logStream);\n }\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 }", "public static PluginManager getInstance() {\n if (_instance == null) {\n _instance = new PluginManager();\n _instance.classInformation = new HashMap<String, ClassInformation>();\n _instance.methodInformation = new HashMap<String, com.groupon.odo.proxylib.models.Method>();\n _instance.jarInformation = new ArrayList<String>();\n\n if (_instance.proxyLibPath == null) {\n //Get the System Classloader\n ClassLoader sysClassLoader = Thread.currentThread().getContextClassLoader();\n\n //Get the URLs\n URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();\n\n for (int i = 0; i < urls.length; i++) {\n if (urls[i].getFile().contains(\"proxylib\")) {\n // store the path to the proxylib\n _instance.proxyLibPath = urls[i].getFile();\n break;\n }\n }\n }\n _instance.initializePlugins();\n }\n return _instance;\n }", "protected void propagateOnNoPick(GVRPicker picker)\n {\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, IPickEvents.class, \"onNoPick\", picker);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, IPickEvents.class, \"onNoPick\", picker);\n }\n }\n }", "public Operation.Info create( char op , Variable input ) {\n switch( op ) {\n case '\\'':\n return Operation.transpose(input, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }" ]
List of releases for an app. @param appName App name. See {@link #listApps} for a list of apps that can be used. @return a list of releases
[ "public List<Release> listReleases(String appName) {\n return connection.execute(new ReleaseList(appName), apiKey);\n }" ]
[ "private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData)\n {\n for (ResultSetRow row : calendarData)\n {\n processCalendarData(calendar, row);\n }\n }", "private void updateScaling() {\n\n List<I_CmsTransform> transforms = new ArrayList<>();\n CmsCroppingParamBean crop = m_croppingProvider.get();\n CmsImageInfoBean info = m_imageInfoProvider.get();\n\n double wv = m_image.getElement().getParentElement().getOffsetWidth();\n double hv = m_image.getElement().getParentElement().getOffsetHeight();\n if (crop == null) {\n transforms.add(\n new CmsBoxFit(CmsBoxFit.Mode.scaleOnlyIfNecessary, wv, hv, info.getWidth(), info.getHeight()));\n } else {\n int wt, ht;\n wt = crop.getTargetWidth() >= 0 ? crop.getTargetWidth() : info.getWidth();\n ht = crop.getTargetHeight() >= 0 ? crop.getTargetHeight() : info.getHeight();\n transforms.add(new CmsBoxFit(CmsBoxFit.Mode.scaleOnlyIfNecessary, wv, hv, wt, ht));\n if (crop.isCropped()) {\n transforms.add(\n new CmsBoxFit(CmsBoxFit.Mode.scaleAlways, wt, ht, crop.getCropWidth(), crop.getCropHeight()));\n transforms.add(new CmsTranslate(crop.getCropX(), crop.getCropY()));\n } else {\n transforms.add(\n new CmsBoxFit(CmsBoxFit.Mode.scaleAlways, wt, ht, crop.getOrgWidth(), crop.getOrgHeight()));\n }\n }\n CmsCompositeTransform chain = new CmsCompositeTransform(transforms);\n m_coordinateTransform = chain;\n if ((crop == null) || !crop.isCropped()) {\n m_region = transformRegionBack(\n m_coordinateTransform,\n CmsRectangle.fromLeftTopWidthHeight(0, 0, info.getWidth(), info.getHeight()));\n } else {\n m_region = transformRegionBack(\n m_coordinateTransform,\n CmsRectangle.fromLeftTopWidthHeight(\n crop.getCropX(),\n crop.getCropY(),\n crop.getCropWidth(),\n crop.getCropHeight()));\n }\n }", "public void onLayoutApplied(final WidgetContainer container, final Vector3Axis viewPortSize) {\n mContainer = container;\n mViewPort.setSize(viewPortSize);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }", "private String appendXmlStartTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"<\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }", "public Object remove(String name) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\t\treturn context.remove(name);\n\t}", "private void populateTask(Row row, Task task)\n {\n task.setUniqueID(row.getInteger(\"Z_PK\"));\n task.setName(row.getString(\"ZTITLE\"));\n task.setPriority(Priority.getInstance(row.getInt(\"ZPRIORITY\")));\n task.setMilestone(row.getBoolean(\"ZISMILESTONE\"));\n task.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n task.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n task.setNotes(row.getString(\"ZOBJECTDESCRIPTION\"));\n task.setDuration(row.getDuration(\"ZGIVENDURATION_\"));\n task.setOvertimeWork(row.getWork(\"ZGIVENWORKOVERTIME_\"));\n task.setWork(row.getWork(\"ZGIVENWORK_\"));\n task.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n task.setActualOvertimeWork(row.getWork(\"ZGIVENACTUALWORKOVERTIME_\"));\n task.setActualWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setRemainingWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setGUID(row.getUUID(\"ZUNIQUEID\"));\n\n Integer calendarID = row.getInteger(\"ZGIVENCALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n task.setCalendar(calendar);\n }\n }\n\n populateConstraints(row, task);\n\n // Percent complete is calculated bottom up from assignments and actual work vs. planned work\n\n m_eventManager.fireTaskReadEvent(task);\n }", "public double distanceSquared(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return dx * dx + dy * dy + dz * dz;\n }", "public static boolean isDouble(CharSequence self) {\n try {\n Double.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public static final Integer getInteger(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return ((Integer) bundle.getObject(key));\n }" ]
Handles the cases in which we can use longs rather than BigInteger @param section @param increment @param addrCreator @param lowerProducer @param upperProducer @param prefixLength @return
[ "protected static <R extends AddressSection, S extends AddressSegment> R fastIncrement(\n\t\t\tR section,\n\t\t\tlong increment,\n\t\t\tAddressCreator<?, R, ?, S> addrCreator, \n\t\t\tSupplier<R> lowerProducer,\n\t\t\tSupplier<R> upperProducer,\n\t\t\tInteger prefixLength) {\n\t\tif(increment >= 0) {\n\t\t\tBigInteger count = section.getCount();\n\t\t\tif(count.compareTo(LONG_MAX) <= 0) {\n\t\t\t\tlong longCount = count.longValue();\n\t\t\t\tif(longCount > increment) {\n\t\t\t\t\tif(longCount == increment + 1) {\n\t\t\t\t\t\treturn upperProducer.get();\n\t\t\t\t\t}\n\t\t\t\t\treturn incrementRange(section, increment, addrCreator, lowerProducer, prefixLength);\n\t\t\t\t}\n\t\t\t\tBigInteger value = section.getValue();\n\t\t\t\tBigInteger upperValue;\n\t\t\t\tif(value.compareTo(LONG_MAX) <= 0 && (upperValue = section.getUpperValue()).compareTo(LONG_MAX) <= 0) {\n\t\t\t\t\treturn increment(\n\t\t\t\t\t\t\tsection,\n\t\t\t\t\t\t\tincrement,\n\t\t\t\t\t\t\taddrCreator,\n\t\t\t\t\t\t\tcount.longValue(),\n\t\t\t\t\t\t\tvalue.longValue(),\n\t\t\t\t\t\t\tupperValue.longValue(),\n\t\t\t\t\t\t\tlowerProducer,\n\t\t\t\t\t\t\tupperProducer,\n\t\t\t\t\t\t\tprefixLength);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tBigInteger value = section.getValue();\n\t\t\tif(value.compareTo(LONG_MAX) <= 0) {\n\t\t\t\treturn add(lowerProducer.get(), value.longValue(), increment, addrCreator, prefixLength);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}" ]
[ "protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }", "protected Connection openConnection() throws IOException {\n // Perhaps this can just be done once?\n CallbackHandler callbackHandler = null;\n SSLContext sslContext = null;\n if (realm != null) {\n sslContext = realm.getSSLContext();\n CallbackHandlerFactory handlerFactory = realm.getSecretCallbackHandlerFactory();\n if (handlerFactory != null) {\n String username = this.username != null ? this.username : localHostName;\n callbackHandler = handlerFactory.getCallbackHandler(username);\n }\n }\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(callbackHandler);\n config.setSslContext(sslContext);\n config.setUri(uri);\n\n AuthenticationContext authenticationContext = this.authenticationContext != null ? this.authenticationContext : AuthenticationContext.captureCurrent();\n\n // Connect\n try {\n return authenticationContext.run((PrivilegedExceptionAction<Connection>) () -> ProtocolConnectionUtils.connectSync(config));\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof IOException) {\n throw (IOException) e.getCause();\n }\n throw new IOException(e);\n }\n }", "private long getTotalTime(ProjectCalendarDateRanges hours, Date startDate, Date endDate)\n {\n long total = 0;\n if (startDate.getTime() != endDate.getTime())\n {\n Date start = DateHelper.getCanonicalTime(startDate);\n Date end = DateHelper.getCanonicalTime(endDate);\n\n for (DateRange range : hours)\n {\n Date rangeStart = range.getStart();\n Date rangeEnd = range.getEnd();\n if (rangeStart != null && rangeEnd != null)\n {\n Date canoncialRangeStart = DateHelper.getCanonicalTime(rangeStart);\n Date canonicalRangeEnd = DateHelper.getCanonicalTime(rangeEnd);\n\n Date startDay = DateHelper.getDayStartDate(rangeStart);\n Date finishDay = DateHelper.getDayStartDate(rangeEnd);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n canonicalRangeEnd = DateHelper.addDays(canonicalRangeEnd, 1);\n }\n\n if (canoncialRangeStart.getTime() == canonicalRangeEnd.getTime() && rangeEnd.getTime() > rangeStart.getTime())\n {\n total += (24 * 60 * 60 * 1000);\n }\n else\n {\n total += getTime(start, end, canoncialRangeStart, canonicalRangeEnd);\n }\n }\n }\n }\n\n return (total);\n }", "private int determineForkedJvmCount(TestsCollection testCollection) {\n int cores = Runtime.getRuntime().availableProcessors();\n int jvmCount;\n if (this.parallelism.equals(PARALLELISM_AUTO)) {\n if (cores >= 8) {\n // Maximum parallel jvms is 4, conserve some memory and memory bandwidth.\n jvmCount = 4;\n } else if (cores >= 4) {\n // Make some space for the aggregator.\n jvmCount = 3;\n } else if (cores == 3) {\n // Yes, three-core chips are a thing.\n jvmCount = 2;\n } else {\n // even for dual cores it usually makes no sense to fork more than one\n // JVM.\n jvmCount = 1;\n }\n } else if (this.parallelism.equals(PARALLELISM_MAX)) {\n jvmCount = Runtime.getRuntime().availableProcessors();\n } else {\n try {\n jvmCount = Math.max(1, Integer.parseInt(parallelism));\n } catch (NumberFormatException e) {\n throw new BuildException(\"parallelism must be 'auto', 'max' or a valid integer: \"\n + parallelism);\n }\n }\n\n if (!testCollection.hasReplicatedSuites()) {\n jvmCount = Math.min(testCollection.testClasses.size(), jvmCount);\n }\n return jvmCount;\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher deleteFacet(String... attributes) {\n for (String attribute : attributes) {\n facetRequestCount.put(attribute, 0);\n facets.remove(attribute);\n }\n rebuildQueryFacets();\n return this;\n }", "public static int convertBytesToInt(byte[] bytes, int offset)\n {\n return (BITWISE_BYTE_TO_INT & bytes[offset + 3])\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8)\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16)\n | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24);\n }", "public void put(@NotNull final Transaction txn, final long localId,\n final int blobId, @NotNull final ByteIterable value) {\n primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value);\n allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId));\n }", "private static void waitUntilFinished(FluoConfiguration config) {\n try (Environment env = new Environment(config)) {\n List<TableRange> ranges = getRanges(env);\n\n outer: while (true) {\n long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n for (TableRange range : ranges) {\n boolean sawNotifications = waitTillNoNotifications(env, range);\n if (sawNotifications) {\n ranges = getRanges(env);\n // This range had notifications. Processing those notifications may have created\n // notifications in previously scanned ranges, so start over.\n continue outer;\n }\n }\n long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n\n // Check to ensure the Oracle issued no timestamps during the scan for notifications.\n if (ts2 - ts1 == 1) {\n break;\n }\n }\n } catch (Exception e) {\n log.error(\"An exception was thrown -\", e);\n System.exit(-1);\n }\n }", "@Override\n\tpublic boolean containsPrefixBlock(int prefixLength) {\n\t\tcheckSubnet(this, prefixLength);\n\t\tint divisionCount = getDivisionCount();\n\t\tint prevBitCount = 0;\n\t\tfor(int i = 0; i < divisionCount; i++) {\n\t\t\tAddressDivision division = getDivision(i);\n\t\t\tint bitCount = division.getBitCount();\n\t\t\tint totalBitCount = bitCount + prevBitCount;\n\t\t\tif(prefixLength < totalBitCount) {\n\t\t\t\tint divPrefixLen = Math.max(0, prefixLength - prevBitCount);\n\t\t\t\tif(!division.isPrefixBlock(division.getDivisionValue(), division.getUpperDivisionValue(), divPrefixLen)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(++i; i < divisionCount; i++) {\n\t\t\t\t\tdivision = getDivision(i);\n\t\t\t\t\tif(!division.isFullRange()) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tprevBitCount = totalBitCount;\n\t\t}\n\t\treturn true;\n\t}" ]
Delete a server group by id @param id server group ID
[ "public void deleteServerGroup(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = \" + id);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }" ]
[ "public void setRefreshing(boolean refreshing) {\n if (refreshing && mRefreshing != refreshing) {\n // scale and show\n mRefreshing = refreshing;\n int endTarget = 0;\n if (!mUsingCustomStart) {\n switch (mDirection) {\n case BOTTOM:\n endTarget = getMeasuredHeight() - (int) (mSpinnerFinalOffset);\n break;\n case TOP:\n default:\n endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));\n break;\n }\n } else {\n endTarget = (int) mSpinnerFinalOffset;\n }\n setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,\n true /* requires update */);\n mNotify = false;\n startScaleUpAnimation(mRefreshListener);\n } else {\n setRefreshing(refreshing, false /* notify */);\n }\n }", "public static base_responses disable(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 disableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tdisableresources[i] = new Interface();\n\t\t\t\tdisableresources[i].id = id[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}", "public int scrollToItem(int position) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToItem position = %d\", position);\n scrollToPosition(position);\n return mCurrentItemIndex;\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 static void main(String[] args) {\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal-->\r\n //MODEL USAGE EXAMPLE: <assign name=\"var_out_V1_2\" expr=\"%ssn\"/> <dg:transform name=\"EQ\"/>\r\n Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>();\r\n transformers.put(\"EQ\", new EquivalenceClassTransformer());\r\n Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>();\r\n cte.add(new InLineTransformerExtension(transformers));\r\n Engine engine = new SCXMLEngine(cte);\n\r\n //will default to samplemachine, but you could specify a different file if you choose to\r\n InputStream is = CmdLine.class.getResourceAsStream(\"/\" + (args.length == 0 ? \"samplemachine\" : args[0]) + \".xml\");\n\r\n engine.setModelByInputFileStream(is);\n\r\n // Usually, this should be more than the number of threads you intend to run\r\n engine.setBootstrapMin(1);\n\r\n //Prepare the consumer with the proper writer and transformer\r\n DataConsumer consumer = new DataConsumer();\r\n consumer.addDataTransformer(new SampleMachineTransformer());\n\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation.\r\n //MODEL USAGE EXAMPLE: <dg:assign name=\"var_out_V2\" set=\"%regex([0-9]{3}[A-Z0-9]{5})\"/>\r\n consumer.addDataTransformer(new EquivalenceClassTransformer());\n\r\n consumer.addDataWriter(new DefaultWriter(System.out,\r\n new String[]{\"var_1_1\", \"var_1_2\", \"var_1_3\", \"var_1_4\", \"var_1_5\", \"var_1_6\", \"var_1_7\",\r\n \"var_2_1\", \"var_2_2\", \"var_2_3\", \"var_2_4\", \"var_2_5\", \"var_2_6\", \"var_2_7\", \"var_2_8\"}));\n\r\n //Prepare the distributor\r\n DefaultDistributor defaultDistributor = new DefaultDistributor();\r\n defaultDistributor.setThreadCount(1);\r\n defaultDistributor.setDataConsumer(consumer);\r\n Logger.getLogger(\"org.apache\").setLevel(Level.WARN);\n\r\n engine.process(defaultDistributor);\r\n }", "protected void writePropertiesToLog(Logger logger, Level level) {\n writeToLog(logger, level, getMapAsString(this.properties, separator), null);\n\n if (this.exception != null) {\n writeToLog(this.logger, Level.ERROR, \"Error:\", this.exception);\n }\n }", "public boolean unlink(D declaration, ServiceReference<S> declarationBinderRef) {\n S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);\n try {\n declarationBinder.removeDeclaration(declaration);\n } catch (BinderException e) {\n LOG.debug(declarationBinder + \" throw an exception when removing of it the Declaration \"\n + declaration, e);\n declaration.unhandle(declarationBinderRef);\n return false;\n } finally {\n declaration.unbind(declarationBinderRef);\n }\n return true;\n }", "private String formatTimeUnit(TimeUnit timeUnit)\n {\n int units = timeUnit.getValue();\n String result;\n String[][] unitNames = LocaleData.getStringArrays(m_locale, LocaleData.TIME_UNITS_ARRAY);\n\n if (units < 0 || units >= unitNames.length)\n {\n result = \"\";\n }\n else\n {\n result = unitNames[units][0];\n }\n\n return (result);\n }", "public Duration getFinishSlack()\n {\n Duration finishSlack = (Duration) getCachedValue(TaskField.FINISH_SLACK);\n if (finishSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n finishSlack = DateHelper.getVariance(this, getEarlyFinish(), getLateFinish(), duration.getUnits());\n set(TaskField.FINISH_SLACK, finishSlack);\n }\n }\n return (finishSlack);\n }" ]
Generate a unique ID across the cluster @return generated ID
[ "public String genId() {\n S.Buffer sb = S.newBuffer();\n sb.a(longEncoder.longToStr(nodeIdProvider.nodeId()))\n .a(longEncoder.longToStr(startIdProvider.startId()))\n .a(longEncoder.longToStr(sequenceProvider.seqId()));\n return sb.toString();\n }" ]
[ "public Operation.Info create( char op , Variable input ) {\n switch( op ) {\n case '\\'':\n return Operation.transpose(input, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }", "public void addColumn(FastTrackColumn column)\n {\n FastTrackField type = column.getType();\n Object[] data = column.getData();\n for (int index = 0; index < data.length; index++)\n {\n MapRow row = getRow(index);\n row.getMap().put(type, data[index]);\n }\n }", "private static void parseSsextensions(JSONObject modelJSON,\n Diagram current) throws JSONException {\n if (modelJSON.has(\"ssextensions\")) {\n JSONArray array = modelJSON.getJSONArray(\"ssextensions\");\n for (int i = 0; i < array.length(); i++) {\n current.addSsextension(array.getString(i));\n }\n }\n }", "@Deprecated\n public static TraceContextHolder wrap(TraceContext traceContext) {\n return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;\n }", "public static base_response delete(nitro_service client, String viewname) throws Exception {\n\t\tdnsview deleteresource = new dnsview();\n\t\tdeleteresource.viewname = viewname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static String getDays(RecurringTask task)\n {\n StringBuilder sb = new StringBuilder();\n for (Day day : Day.values())\n {\n sb.append(task.getWeeklyDay(day) ? \"1\" : \"0\");\n }\n return sb.toString();\n }", "private static long hexdump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n\n for (loop = 0; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n while (loop < BUFFER_SIZE)\n {\n sb.append(\" \");\n ++loop;\n }\n\n sb.append(\" \");\n\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.println(sb.toString());\n }\n\n return (byteCount);\n }", "public void addBetween(Object attribute, Object value1, Object value2)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }", "synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }" ]
Creates metadata on this folder using a specified scope and template. @param templateName the name of the metadata template. @param scope the scope of the template (usually "global" or "enterprise"). @param metadata the new metadata values. @return the metadata returned from the server.
[ "public Metadata createMetadata(String templateName, String scope, Metadata metadata) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n request.setBody(metadata.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }" ]
[ "public ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }", "public static double getRadiusToBoundedness(double D, int N, double timelag, double B){\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble radius = Math.sqrt(cov_area/(4*B));\n\t\treturn radius;\n\t}", "private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap)\n {\n Project.Resources resources = project.getResources();\n if (resources != null)\n {\n for (Project.Resources.Resource resource : resources.getResource())\n {\n readResource(resource, calendarMap);\n }\n }\n }", "protected void setProperty(String propertyName, JavascriptObject propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getJSObject());\n }", "private void generateWrappingPart(WrappingHint.Builder builder) {\n builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER)\n .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField));\n }", "public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }", "protected void appendTableWithJoins(TableAlias alias, StringBuffer where, StringBuffer buf)\r\n {\r\n int stmtFromPos = 0;\r\n byte joinSyntax = getJoinSyntaxType();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n stmtFromPos = buf.length(); // store position of join (by: Terry Dexter)\r\n }\r\n\r\n if (alias == getRoot())\r\n {\r\n // BRJ: also add indirection table to FROM-clause for MtoNQuery \r\n if (getQuery() instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)m_query; \r\n buf.append(getTableAliasForPath(mnQuery.getIndirectionTable(), null).getTableAndAlias());\r\n buf.append(\", \");\r\n } \r\n buf.append(alias.getTableAndAlias());\r\n }\r\n else if (joinSyntax != SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n buf.append(alias.getTableAndAlias());\r\n }\r\n\r\n if (!alias.hasJoins())\r\n {\r\n return;\r\n }\r\n\r\n for (Iterator it = alias.iterateJoins(); it.hasNext();)\r\n {\r\n Join join = (Join) it.next();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92(join, where, buf);\r\n if (it.hasNext())\r\n {\r\n buf.insert(stmtFromPos, \"(\");\r\n buf.append(\")\");\r\n }\r\n }\r\n else if (joinSyntax == SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92NoParen(join, where, buf);\r\n }\r\n else\r\n {\r\n appendJoin(where, buf, join);\r\n }\r\n\r\n }\r\n }", "public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\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 }" ]
Adds steps types from given injector and recursively its parent @param injector the current Inject @param types the List of steps types
[ "private void addTypes(Injector injector, List<Class<?>> types) {\n for (Binding<?> binding : injector.getBindings().values()) {\n Key<?> key = binding.getKey();\n Type type = key.getTypeLiteral().getType();\n if (hasAnnotatedMethods(type)) {\n types.add(((Class<?>)type));\n }\n }\n if (injector.getParent() != null) {\n addTypes(injector.getParent(), types);\n }\n }" ]
[ "@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }", "public static long readUnsignedInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xffL) << 24) | ((bytes[offset + 1] & 0xffL) << 16)\n | ((bytes[offset + 2] & 0xffL) << 8) | (bytes[offset + 3] & 0xffL));\n }", "public static boolean checkDuplicateElements(DMatrixSparseCSC A ) {\n A = A.copy(); // create a copy so that it doesn't modify A\n A.sortIndices(null);\n return !checkSortedFlag(A);\n }", "private void addCalendarException(MpxjTreeNode parentNode, final ProjectCalendarException exception)\n {\n MpxjTreeNode exceptionNode = new MpxjTreeNode(exception, CALENDAR_EXCEPTION_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return m_dateFormat.format(exception.getFromDate());\n }\n };\n parentNode.add(exceptionNode);\n addHours(exceptionNode, exception);\n }", "public static String roundCorner(int radiusInner, int radiusOuter, int color) {\n if (radiusInner < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radiusOuter < 0) {\n throw new IllegalArgumentException(\"Outer radius must be greater than or equal to zero.\");\n }\n StringBuilder builder = new StringBuilder(FILTER_ROUND_CORNER).append(\"(\").append(radiusInner);\n if (radiusOuter > 0) {\n builder.append(\"|\").append(radiusOuter);\n }\n final int r = (color & 0xFF0000) >>> 16;\n final int g = (color & 0xFF00) >>> 8;\n final int b = color & 0xFF;\n return builder.append(\",\") //\n .append(r).append(\",\") //\n .append(g).append(\",\") //\n .append(b).append(\")\") //\n .toString();\n }", "private static Object checkComponentType(Object array, Class<?> expectedComponentType) {\n\t\tClass<?> actualComponentType = array.getClass().getComponentType();\n\t\tif (!expectedComponentType.isAssignableFrom(actualComponentType)) {\n\t\t\tthrow new ArrayStoreException(\n\t\t\t\t\tString.format(\"The expected component type %s is not assignable from the actual type %s\",\n\t\t\t\t\t\t\texpectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));\n\t\t}\n\t\treturn array;\n\t}", "public void addVars(Map<String, String> env) {\n if (tagUrl != null) {\n env.put(\"RELEASE_SCM_TAG\", tagUrl);\n env.put(RT_RELEASE_STAGING + \"SCM_TAG\", tagUrl);\n }\n if (releaseBranch != null) {\n env.put(\"RELEASE_SCM_BRANCH\", releaseBranch);\n env.put(RT_RELEASE_STAGING + \"SCM_BRANCH\", releaseBranch);\n }\n if (releaseVersion != null) {\n env.put(RT_RELEASE_STAGING + \"VERSION\", releaseVersion);\n }\n if (nextVersion != null) {\n env.put(RT_RELEASE_STAGING + \"NEXT_VERSION\", nextVersion);\n }\n }", "public void setOwner(Graph<DataT, NodeT> ownerGraph) {\n if (this.ownerGraph != null) {\n throw new RuntimeException(\"Changing owner graph is not allowed\");\n }\n this.ownerGraph = ownerGraph;\n }", "public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }" ]
Get the next available ordinal for a method ID @param methodId ID of method @return value of next ordinal @throws Exception exception
[ "private Integer getNextOrdinalForMethodId(int methodId, String pathName) throws Exception {\n String pathInfo = doGet(BASE_PATH + uriEncode(pathName), new BasicNameValuePair[0]);\n JSONObject pathResponse = new JSONObject(pathInfo);\n\n JSONArray enabledEndpoints = pathResponse.getJSONArray(\"enabledEndpoints\");\n int lastOrdinal = 0;\n for (int x = 0; x < enabledEndpoints.length(); x++) {\n if (enabledEndpoints.getJSONObject(x).getInt(\"overrideId\") == methodId) {\n lastOrdinal++;\n }\n }\n return lastOrdinal + 1;\n }" ]
[ "public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){\n\t\tHazardCurve survivalProbabilities = new HazardCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tsurvivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn survivalProbabilities;\n\t}", "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }", "public static String replaceParameters(final InputStream stream) {\n String content = IOUtil.asStringPreservingNewLines(stream);\n return resolvePlaceholders(content);\n }", "public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public static <K, V, T> List<Versioned<V>> get(Store<K, V, T> storageEngine, K key, T transform) {\n Map<K, List<Versioned<V>>> result = storageEngine.getAll(Collections.singleton(key),\n Collections.singletonMap(key,\n transform));\n if(result.size() > 0)\n return result.get(key);\n else\n return Collections.emptyList();\n }", "public void pause()\n {\n if (mAudioListener != null)\n {\n int sourceId = getSourceId();\n if (sourceId != GvrAudioEngine.INVALID_ID)\n {\n mAudioListener.getAudioEngine().pauseSound(sourceId);\n }\n }\n }", "private void clearArt(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverAlbumArtUpdate(player, null); // Inform listeners that the artwork is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DataReference art : new HashSet<DataReference>(artCache.keySet())) {\n if (art.player == player) {\n artCache.remove(art);\n }\n }\n }", "public String[] parseMFString(String mfString) {\n Vector<String> strings = new Vector<String>();\n\n StringReader sr = new StringReader(mfString);\n StreamTokenizer st = new StreamTokenizer(sr);\n st.quoteChar('\"');\n st.quoteChar('\\'');\n String[] mfStrings = null;\n\n int tokenType;\n try {\n while ((tokenType = st.nextToken()) != StreamTokenizer.TT_EOF) {\n\n strings.add(st.sval);\n\n }\n } catch (IOException e) {\n\n Log.d(TAG, \"String parsing Error: \" + e);\n\n e.printStackTrace();\n }\n mfStrings = new String[strings.size()];\n for (int i = 0; i < strings.size(); i++) {\n mfStrings[i] = strings.get(i);\n }\n return mfStrings;\n }", "private EndpointOverride getEndpointOverrideFromResultSet(ResultSet results) throws Exception {\n EndpointOverride endpoint = new EndpointOverride();\n endpoint.setPathId(results.getInt(Constants.GENERIC_ID));\n endpoint.setPath(results.getString(Constants.PATH_PROFILE_ACTUAL_PATH));\n endpoint.setBodyFilter(results.getString(Constants.PATH_PROFILE_BODY_FILTER));\n endpoint.setPathName(results.getString(Constants.PATH_PROFILE_PATHNAME));\n endpoint.setContentType(results.getString(Constants.PATH_PROFILE_CONTENT_TYPE));\n endpoint.setRequestType(results.getInt(Constants.PATH_PROFILE_REQUEST_TYPE));\n endpoint.setRepeatNumber(results.getInt(Constants.REQUEST_RESPONSE_REPEAT_NUMBER));\n endpoint.setGroupIds(results.getString(Constants.PATH_PROFILE_GROUP_IDS));\n endpoint.setRequestEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_REQUEST_ENABLED));\n endpoint.setResponseEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_RESPONSE_ENABLED));\n endpoint.setClientUUID(results.getString(Constants.GENERIC_CLIENT_UUID));\n endpoint.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n endpoint.setGlobal(results.getBoolean(Constants.PATH_PROFILE_GLOBAL));\n return endpoint;\n }" ]
Utility to list indexes of a given type. @param type the type of index to list, null means all types @param modelType the class to deserialize the index into @param <T> the type of the index @return the list of indexes of the specified type
[ "private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\n }" ]
[ "List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) {\n\t\tList<String> dumpFileDates = findDumpDatesOnline(dumpContentType);\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String dateStamp : dumpFileDates) {\n\t\t\tif (dumpContentType == DumpContentType.DAILY) {\n\t\t\t\tresult.add(new WmfOnlineDailyDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager));\n\t\t\t} else if (dumpContentType == DumpContentType.JSON) {\n\t\t\t\tresult.add(new JsonOnlineDumpFile(dateStamp, this.projectName,\n\t\t\t\t\t\tthis.webResourceFetcher, this.dumpfileDirectoryManager));\n\t\t\t} else {\n\t\t\t\tresult.add(new WmfOnlineStandardDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager, dumpContentType));\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(\"Found \" + result.size() + \" online dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}", "private static void deleteUserDirectories(final File root,\n final FileFilter filter) {\n final File[] dirs = root.listFiles(filter);\n LOGGER.info(\"Identified (\" + dirs.length + \") directories to delete\");\n for (final File dir : dirs) {\n LOGGER.info(\"Deleting \" + dir);\n if (!FileUtils.deleteQuietly(dir)) {\n LOGGER.info(\"Failed to delete directory \" + dir);\n }\n }\n }", "public void prepare(Properties p, Connection cnx)\n {\n this.tablePrefix = p.getProperty(\"com.enioka.jqm.jdbc.tablePrefix\", \"\");\n queries.putAll(DbImplBase.queries);\n for (Map.Entry<String, String> entry : DbImplBase.queries.entrySet())\n {\n queries.put(entry.getKey(), this.adaptSql(entry.getValue()));\n }\n }", "private static boolean isEqual(Method m, Method a) {\n if (m.getName().equals(a.getName()) && m.getParameterTypes().length == a.getParameterTypes().length && m.getReturnType().isAssignableFrom(a.getReturnType())) {\n for (int i = 0; i < m.getParameterTypes().length; i++) {\n if (!(m.getParameterTypes()[i].isAssignableFrom(a.getParameterTypes()[i]))) {\n return false;\n }\n }\n return true;\n }\n return false;\n }", "public static final String printDuration(Duration value)\n {\n return value == null ? null : Double.toString(value.getDuration());\n }", "public static String getTemplateAsString(String fileName) throws IOException {\n // in .jar file\n String fNameJar = getFileNameInPath(fileName);\n InputStream inStream = DomUtils.class.getResourceAsStream(\"/\"\n + fNameJar);\n if (inStream == null) {\n // try to find file normally\n File f = new File(fileName);\n if (f.exists()) {\n inStream = new FileInputStream(f);\n } else {\n throw new IOException(\"Cannot find \" + fileName + \" or \"\n + fNameJar);\n }\n }\n\n BufferedReader bufferedReader = new BufferedReader(\n new InputStreamReader(inStream));\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line).append(\"\\n\");\n }\n\n bufferedReader.close();\n return stringBuilder.toString();\n }", "public int[] indices(Collection<E> elems) {\r\n int[] indices = new int[elems.size()];\r\n int i = 0;\r\n for (E elem : elems) {\r\n indices[i++] = indexOf(elem);\r\n }\r\n return indices;\r\n }", "public static <E> List<E> listify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (List<E>) collectify(mapper, source, List.class, targetElementType);\n }", "protected boolean check(String id, List<String> includes, List<String> excludes) {\n\t\treturn check(id, includes) && !check(id, excludes);\n\t}" ]
Check if a given string is a valid java package or class name. This method use the technique documented in [this SO question](https://stackoverflow.com/questions/13557195/how-to-check-if-string-is-a-valid-class-identifier) with the following extensions: * if the string does not contain `.` then assume it is not a valid package or class name @param s the string to be checked @return `true` if `s` is a valid java package or class name
[ "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 gslbservice get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice response = (gslbservice) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static void checkRequired(OptionSet options, String opt1, String opt2)\n throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt1);\n opts.add(opt2);\n checkRequired(options, opts);\n }", "public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));\n\t}", "public void setDirectory(final String directory) {\n this.directory = new File(this.configuration.getDirectory(), directory);\n if (!this.directory.exists()) {\n throw new IllegalArgumentException(String.format(\n \"Directory does not exist: %s.\\n\" +\n \"Configuration contained value %s which is supposed to be relative to \" +\n \"configuration directory.\",\n this.directory, directory));\n }\n\n if (!this.directory.getAbsolutePath()\n .startsWith(this.configuration.getDirectory().getAbsolutePath())) {\n throw new IllegalArgumentException(String.format(\n \"All files and directories must be contained in the configuration directory the \" +\n \"directory provided in the configuration breaks that contract: %s in config \" +\n \"file resolved to %s.\",\n directory, this.directory));\n }\n }", "public void selectTab() {\n for (Widget child : getChildren()) {\n if (child instanceof HasHref) {\n String href = ((HasHref) child).getHref();\n if (parent != null && !href.isEmpty()) {\n parent.selectTab(href.replaceAll(\"[^a-zA-Z\\\\d\\\\s:]\", \"\"));\n parent.reload();\n break;\n }\n }\n }\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 static void registerDataPersisters(DataPersister... dataPersisters) {\n\t\t// we build the map and replace it to lower the chance of concurrency issues\n\t\tList<DataPersister> newList = new ArrayList<DataPersister>();\n\t\tif (registeredPersisters != null) {\n\t\t\tnewList.addAll(registeredPersisters);\n\t\t}\n\t\tfor (DataPersister persister : dataPersisters) {\n\t\t\tnewList.add(persister);\n\t\t}\n\t\tregisteredPersisters = newList;\n\t}", "private void processCurrency(Row row)\n {\n String currencyName = row.getString(\"curr_short_name\");\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n symbols.setGroupingSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n DecimalFormat nf = new DecimalFormat();\n nf.setDecimalFormatSymbols(symbols);\n nf.applyPattern(\"#.#\");\n m_currencyMap.put(currencyName, nf);\n\n if (currencyName.equalsIgnoreCase(m_defaultCurrencyName))\n {\n m_numberFormat = nf;\n m_defaultCurrencyData = row;\n }\n }", "protected String getClasspath() throws IOException {\n List<String> classpath = new ArrayList<>();\n classpath.add(getBundleJarPath());\n classpath.addAll(getPluginsPath());\n return StringUtils.toString(classpath.toArray(new String[classpath.size()]), \" \");\n }" ]
Tries to load a site specific error page. If @param cms {@link CmsObject} used for reading the resource (site root and uri get adjusted!) @param req the current request @param res the current response @param errorCode the error code to display @return a flag, indicating if the custom error page could be loaded.
[ "private boolean tryCustomErrorPage(CmsObject cms, HttpServletRequest req, HttpServletResponse res, int errorCode) {\n\n String siteRoot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();\n CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);\n if (site != null) {\n // store current site root and URI\n String currentSiteRoot = cms.getRequestContext().getSiteRoot();\n String currentUri = cms.getRequestContext().getUri();\n try {\n if (site.getErrorPage() != null) {\n String rootPath = site.getErrorPage();\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n }\n String rootPath = CmsStringUtil.joinPaths(siteRoot, \"/.errorpages/handle\" + errorCode + \".html\");\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n } finally {\n cms.getRequestContext().setSiteRoot(currentSiteRoot);\n cms.getRequestContext().setUri(currentUri);\n }\n }\n return false;\n }" ]
[ "public Widget addControl(String name, int resId, Widget.OnTouchListener listener, int position) {\n Widget control = findChildByName(name);\n if (control == null) {\n control = createControlWidget(resId, name, null);\n }\n setupControl(name, control, listener, position);\n return control;\n }", "private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }", "public static <T extends HasWord> TokenizerFactory<T> factory(LexedTokenFactory<T> factory, String options) {\r\n return new PTBTokenizerFactory<T>(factory, options);\r\n\r\n }", "public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }", "public List<T> parseList(JsonParser jsonParser) throws IOException {\n List<T> list = new ArrayList<>();\n if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n list.add(parse(jsonParser));\n }\n }\n return list;\n }", "public static double blackScholesATMOptionValue(\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble forward,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tif(optionMaturity < 0) {\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t// Calculate analytic value\n\t\tdouble dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);\n\t\tdouble dMinus = -dPlus;\n\n\t\tdouble valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;\n\n\t\treturn valueAnalytic;\n\t}", "public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {\n\t\tThread currentThread = Thread.currentThread();\n\t\tClassLoader threadContextClassLoader = currentThread.getContextClassLoader();\n\t\tif (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {\n\t\t\tcurrentThread.setContextClassLoader(classLoaderToUse);\n\t\t\treturn threadContextClassLoader;\n\t\t}\n\t\telse {\n\t\t\treturn null;\n\t\t}\n\t}", "public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "private void validatePermissions(final File dirPath, final File file) {\n\n // Check execute and read permissions for parent dirPath\n if( !dirPath.canExecute() || !dirPath.canRead() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n return;\n }\n\n // Check read and write permissions for properties file\n if( !file.canRead() || !file.canWrite() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n }\n\n }" ]
Executes all event manipulating handler and writes the event with persist handler. @param events the events
[ "public void putEvents(List<Event> events) {\n List<Event> filteredEvents = filterEvents(events);\n executeHandlers(filteredEvents);\n for (Event event : filteredEvents) {\n persistenceHandler.writeEvent(event);\n }\n }" ]
[ "protected List<String> splitLinesAndNewLines(String text) {\n\t\tif (text == null)\n\t\t\treturn Collections.emptyList();\n\t\tint idx = initialSegmentSize(text);\n\t\tif (idx == text.length()) {\n\t\t\treturn Collections.singletonList(text);\n\t\t}\n\n\t\treturn continueSplitting(text, idx);\n\t}", "public PreparedStatementCreator page(final Dialect dialect, final int limit, final int offset) {\n return new PreparedStatementCreator() {\n public PreparedStatement createPreparedStatement(Connection con) throws SQLException {\n return getPreparedStatementCreator()\n .setSql(dialect.createPageSelect(builder.toString(), limit, offset))\n .createPreparedStatement(con);\n }\n };\n }", "public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {\n int dir = (asc) ? 1 : -1;\n collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject(\"background\", background));\n }", "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 GVRTexture getSplashTexture(GVRContext gvrContext) {\n Bitmap bitmap = BitmapFactory.decodeResource( //\n gvrContext.getContext().getResources(), //\n R.drawable.__default_splash_screen__);\n GVRTexture tex = new GVRTexture(gvrContext);\n tex.setImage(new GVRBitmapImage(gvrContext, bitmap));\n return tex;\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 logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)\n {\n if (!timeTakenByPhase.containsKey(phase))\n {\n RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class).create();\n model.setRulePhase(phase.toString());\n model.setTimeTaken(timeTaken);\n model.setOrderExecuted(timeTakenByPhase.size());\n timeTakenByPhase.put(phase, model.getElement().id());\n }\n else\n {\n GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class);\n RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n }", "private JSONValue dateToJson(Date d) {\n\n return null != d ? new JSONString(Long.toString(d.getTime())) : null;\n }", "public static base_responses add(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 addresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsacl6();\n\t\t\t\taddresources[i].acl6name = resources[i].acl6name;\n\t\t\t\taddresources[i].acl6action = resources[i].acl6action;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].established = resources[i].established;\n\t\t\t\taddresources[i].icmptype = resources[i].icmptype;\n\t\t\t\taddresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
other static handlers
[ "static void handleNotificationClicked(Context context,Bundle notification) {\n if (notification == null) return;\n\n String _accountId = null;\n try {\n _accountId = notification.getString(Constants.WZRK_ACCT_ID_KEY);\n } catch (Throwable t) {\n // no-op\n }\n\n if (instances == null) {\n CleverTapAPI instance = createInstanceIfAvailable(context, _accountId);\n if (instance != null) {\n instance.pushNotificationClickedEvent(notification);\n }\n return;\n }\n\n for (String accountId: instances.keySet()) {\n CleverTapAPI instance = CleverTapAPI.instances.get(accountId);\n boolean shouldProcess = false;\n if (instance != null) {\n shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);\n }\n if (shouldProcess) {\n instance.pushNotificationClickedEvent(notification);\n break;\n }\n }\n }" ]
[ "@GET\n @Produces(MediaType.APPLICATION_JSON)\n @Path(\"/graph/{name}/{version}\")\n public Response getModuleGraph(@PathParam(\"name\") final String moduleName,\n @PathParam(\"version\") final String moduleVersion,\n @Context final UriInfo uriInfo){\n\n LOG.info(\"Dependency Checker got a get module graph export request.\");\n\n if(moduleName == null || moduleVersion == null){\n return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build();\n }\n\n final FiltersHolder filters = new FiltersHolder();\n filters.init(uriInfo.getQueryParameters());\n\n final String moduleId = DbModule.generateID(moduleName, moduleVersion);\n final AbstractGraph moduleGraph = getGraphsHandler(filters).getModuleGraph(moduleId);\n\n return Response.ok(moduleGraph).build();\n }", "public static base_response add(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey addresource = new sslcertkey();\n\t\taddresource.certkey = resource.certkey;\n\t\taddresource.cert = resource.cert;\n\t\taddresource.key = resource.key;\n\t\taddresource.password = resource.password;\n\t\taddresource.fipskey = resource.fipskey;\n\t\taddresource.inform = resource.inform;\n\t\taddresource.passplain = resource.passplain;\n\t\taddresource.expirymonitor = resource.expirymonitor;\n\t\taddresource.notificationperiod = resource.notificationperiod;\n\t\taddresource.bundle = resource.bundle;\n\t\treturn addresource.add_resource(client);\n\t}", "public static boolean isStandaloneRunning(final ModelControllerClient client) {\n try {\n final ModelNode response = client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"server-state\"));\n if (Operations.isSuccessfulOutcome(response)) {\n final String state = Operations.readResult(response).asString();\n return !CONTROLLER_PROCESS_STATE_STARTING.equals(state)\n && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state);\n }\n } catch (RuntimeException | IOException e) {\n LOGGER.trace(\"Interrupted determining if standalone is running\", e);\n }\n return false;\n }", "public String getStatement()\r\n {\r\n if(sql == null)\r\n {\r\n StringBuffer stmt = new StringBuffer(128);\r\n ClassDescriptor cld = getClassDescriptor();\r\n\r\n FieldDescriptor[] fieldDescriptors = cld.getPkFields();\r\n if(fieldDescriptors == null || fieldDescriptors.length == 0)\r\n {\r\n throw new OJBRuntimeException(\"No PK fields defined in metadata for \" + cld.getClassNameOfObject());\r\n }\r\n FieldDescriptor field = fieldDescriptors[0];\r\n\r\n stmt.append(SELECT);\r\n stmt.append(field.getColumnName());\r\n stmt.append(FROM);\r\n stmt.append(cld.getFullTableName());\r\n appendWhereClause(cld, false, stmt);\r\n\r\n sql = stmt.toString();\r\n }\r\n return sql;\r\n }", "private Date getDateTime(String value) throws MPXJException\n {\n try\n {\n Number year = m_fourDigitFormat.parse(value.substring(0, 4));\n Number month = m_twoDigitFormat.parse(value.substring(4, 6));\n Number day = m_twoDigitFormat.parse(value.substring(6, 8));\n\n Number hours = m_twoDigitFormat.parse(value.substring(9, 11));\n Number minutes = m_twoDigitFormat.parse(value.substring(11, 13));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.YEAR, year.intValue());\n cal.set(Calendar.MONTH, month.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, day.intValue());\n\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\n\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n Date result = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n return result;\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse date-time \" + value, ex);\n }\n }", "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 }", "static ItemIdValueImpl fromIri(String iri) {\n\t\tint separator = iri.lastIndexOf('/') + 1;\n\t\ttry {\n\t\t\treturn new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator));\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid Wikibase entity IRI: \" + iri, e);\n\t\t}\n\t}", "@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n // Calculate summaries.\n summaryListener.suiteSummary(e);\n\n Description suiteDescription = e.getDescription();\n String displayName = suiteDescription.getDisplayName();\n if (displayName.trim().isEmpty()) {\n junit4.log(\"Could not emit XML report for suite (null description).\", \n Project.MSG_WARN);\n return;\n }\n\n if (!suiteCounts.containsKey(displayName)) {\n suiteCounts.put(displayName, 1);\n } else {\n int newCount = suiteCounts.get(displayName) + 1;\n suiteCounts.put(displayName, newCount);\n if (!ignoreDuplicateSuites && newCount == 2) {\n junit4.log(\"Duplicate suite name used with XML reports: \"\n + displayName + \". This may confuse tools that process XML reports. \"\n + \"Set 'ignoreDuplicateSuites' to true to skip this message.\", Project.MSG_WARN);\n }\n displayName = displayName + \"-\" + newCount;\n }\n \n try {\n File reportFile = new File(dir, \"TEST-\" + displayName + \".xml\");\n RegistryMatcher rm = new RegistryMatcher();\n rm.bind(String.class, new XmlStringTransformer());\n Persister persister = new Persister(rm);\n persister.write(buildModel(e), reportFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize report for suite \"\n + displayName + \": \" + x.toString(), x, Project.MSG_WARN);\n }\n }", "public ServerSetup createCopy(String bindAddress) {\r\n ServerSetup setup = new ServerSetup(getPort(), bindAddress, getProtocol());\r\n setup.setServerStartupTimeout(getServerStartupTimeout());\r\n setup.setConnectionTimeout(getConnectionTimeout());\r\n setup.setReadTimeout(getReadTimeout());\r\n setup.setWriteTimeout(getWriteTimeout());\r\n setup.setVerbose(isVerbose());\r\n\r\n return setup;\r\n }" ]
Polls from the location header and updates the polling state with the polling response for a PUT operation. @param pollingState the polling state for the current operation. @param <T> the return type of the caller.
[ "private <T> Observable<PollingState<T>> updateStateFromLocationHeaderOnPutAsync(final PollingState<T> pollingState) {\n return pollAsync(pollingState.locationHeaderLink(), pollingState.loggingContext())\n .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(Response<ResponseBody> response) {\n int statusCode = response.code();\n if (statusCode == 202) {\n pollingState.withResponse(response);\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n } else if (statusCode == 200 || statusCode == 201) {\n try {\n pollingState.updateFromResponseOnPutPatch(response);\n } catch (CloudException | IOException e) {\n return Observable.error(e);\n }\n }\n return Observable.just(pollingState);\n }\n });\n }" ]
[ "@Override\n @SuppressLint(\"NewApi\")\n public boolean onTouch(View v, MotionEvent event) {\n if(touchable) {\n\n if (event.getAction() == MotionEvent.ACTION_DOWN) {\n view.setBackgroundColor(colorPressed);\n\n return true;\n }\n\n if (event.getAction() == MotionEvent.ACTION_CANCEL) {\n if (isSelected)\n view.setBackgroundColor(colorSelected);\n else\n view.setBackgroundColor(colorUnpressed);\n\n return true;\n }\n\n\n if (event.getAction() == MotionEvent.ACTION_UP) {\n\n view.setBackgroundColor(colorSelected);\n afterClick();\n\n return true;\n }\n }\n\n return false;\n }", "public Pair<int[][][][], int[][]> documentsToDataAndLabels(Collection<List<IN>> documents) {\r\n\r\n // first index is the number of the document\r\n // second index is position in the document also the index of the\r\n // clique/factor table\r\n // third index is the number of elements in the clique/window these features\r\n // are for (starting with last element)\r\n // fourth index is position of the feature in the array that holds them\r\n // element in data[i][j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique of the ith document\r\n // int[][][][] data = new int[documentsSize][][][];\r\n List<int[][][]> data = new ArrayList<int[][][]>();\r\n\r\n // first index is the number of the document\r\n // second index is the position in the document\r\n // element in labels[i][j] is the index of the correct label (if it exists)\r\n // at position j in document i\r\n // int[][] labels = new int[documentsSize][];\r\n List<int[]> labels = new ArrayList<int[]>();\r\n\r\n int numDatums = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n data.add(docPair.first());\r\n labels.add(docPair.second());\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + data.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n printFeatures();\r\n\r\n int[][][][] dataA = new int[0][][][];\r\n int[][] labelsA = new int[0][];\r\n\r\n return new Pair<int[][][][], int[][]>(data.toArray(dataA), labels.toArray(labelsA));\r\n }", "public void run()\r\n { \t\r\n \tSystem.out.println(AsciiSplash.getSplashArt());\r\n System.out.println(\"Welcome to the OJB PB tutorial application\");\r\n System.out.println();\r\n // never stop (there is a special use case to quit the application)\r\n while (true)\r\n {\r\n try\r\n {\r\n // select a use case and perform it\r\n UseCase uc = selectUseCase();\r\n uc.apply();\r\n }\r\n catch (Throwable t)\r\n {\r\n broker.close();\r\n System.out.println(t.getMessage());\r\n }\r\n }\r\n }", "public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }", "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 }", "@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withTag(String key, String value) {\n if (this.inner().getTags() == null) {\n this.inner().withTags(new HashMap<String, String>());\n }\n this.inner().getTags().put(key, value);\n return (FluentModelImplT) this;\n }", "public void ifDoesntHaveMemberTag(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean result = false;\r\n\r\n if (getCurrentField() != null) {\r\n if (!hasTag(attributes, FOR_FIELD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (!hasTag(attributes, FOR_METHOD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n if (!result) {\r\n String error = attributes.getProperty(\"error\");\r\n\r\n if (error != null) {\r\n getEngine().print(error);\r\n }\r\n }\r\n }", "public static Object executeXPath(Node document, String xpathExpression, Map<String, String> namespaceMapping, QName result)\n throws XPathException, MarshallingException\n {\n NamespaceMapContext mapContext = new NamespaceMapContext(namespaceMapping);\n try\n {\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n xpath.setNamespaceContext(mapContext);\n XPathExpression expr = xpath.compile(xpathExpression);\n\n return executeXPath(document, expr, result);\n }\n catch (XPathExpressionException e)\n {\n throw new XPathException(\"Xpath(\" + xpathExpression + \") cannot be compiled\", e);\n }\n catch (Exception e)\n {\n throw new MarshallingException(\"Exception unmarshalling XML.\", e);\n }\n }", "private static String quoteSort(Sort[] sort) {\n LinkedList<String> sorts = new LinkedList<String>();\n for (Sort pair : sort) {\n sorts.add(String.format(\"{%s: %s}\", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));\n }\n return sorts.toString();\n }" ]
Create an import declaration and delegates its registration for an upper class.
[ "public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {\n Map<String, Object> metadata = new HashMap<String, Object>();\n metadata.put(Constants.DEVICE_ID, deviceId);\n metadata.put(Constants.DEVICE_TYPE, deviceType);\n metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);\n metadata.put(\"scope\", \"generic\");\n ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();\n\n importDeclarations.put(deviceId, declaration);\n\n registerImportDeclaration(declaration);\n }" ]
[ "public final void notifyFooterItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount + contentItemCount, itemCount);\n }", "public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}", "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 }", "private Duration getDuration(Double duration)\n {\n Duration result = null;\n\n if (duration != null)\n {\n result = Duration.getInstance(NumberHelper.getDouble(duration), TimeUnit.HOURS);\n }\n\n return result;\n }", "public List<Action> getRootActions() {\n\t\tfinal List<Action> rootActions = srcUpdTrees.stream().map(t -> originalActionsSrc.get(t))\n\t\t\t\t.collect(Collectors.toList());\n\n\t\trootActions.addAll(srcDelTrees.stream() //\n\t\t\t\t.filter(t -> !srcDelTrees.contains(t.getParent()) && !srcUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsSrc.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstAddTrees.stream() //\n\t\t\t\t.filter(t -> !dstAddTrees.contains(t.getParent()) && !dstUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstMvTrees.stream() //\n\t\t\t\t.filter(t -> !dstMvTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.removeAll(Collections.singleton(null));\n\t\treturn rootActions;\n\t}", "@Override\n public void attachScriptFile(IScriptable target, IScriptFile scriptFile) {\n mScriptMap.put(target, scriptFile);\n scriptFile.invokeFunction(\"onAttach\", new Object[] { target });\n }", "private static void defineField(Map<String, FieldType> container, String name, FieldType type)\n {\n defineField(container, name, type, null);\n }", "public CustomHeadersInterceptor replaceHeader(String name, String value) {\n this.headers.put(name, new ArrayList<String>());\n this.headers.get(name).add(value);\n return this;\n }", "public Object get(int dataSet) throws SerializationException {\r\n\t\tObject result = null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult = getData(ds);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}" ]
Places a connection back in the originating partition. @param connectionHandle to place back @throws SQLException on error
[ "protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException {\r\n\r\n\t\tif (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){\r\n\t\t\tconnectionHandle.logicallyClosed.set(true);\r\n\t\t\t((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false));\r\n\t\t} else {\r\n\t\t\tBlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections();\r\n\t\t\t\tif (!queue.offer(connectionHandle)){ // this shouldn't fail\r\n\t\t\t\t\tconnectionHandle.internalClose();\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}" ]
[ "public static STSClient createSTSX509Client(Bus bus, Map<String, String> stsProps) {\r\n final STSClient stsClient = createClient(bus, stsProps);\r\n\r\n stsClient.setWsdlLocation(stsProps.get(STS_X509_WSDL_LOCATION));\r\n stsClient.setEndpointQName(new QName(stsProps.get(STS_NAMESPACE), stsProps.get(STS_X509_ENDPOINT_NAME)));\r\n\r\n return stsClient;\r\n }", "public Future<PutObjectResult> putAsync(String key, String value) {\n return Future.of(() -> put(key, value), this.uploadService)\n .flatMap(t->t.fold(p->Future.ofResult(p),e->Future.ofError(e)));\n }", "public Set<String> getKeys(Class<?> type) {\n return data.entrySet().stream().filter(val -> type.isAssignableFrom(val.getValue()\n .getClass())).map(Map.Entry::getKey).collect(Collectors\n .toSet());\n }", "public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }", "private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns)\n {\n Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>();\n for (ColumnDefinition def : columns)\n {\n map.put(def.getName(), def);\n }\n return map;\n }", "public void addExtraInfo(String key, Object value) {\n // Turn extraInfo into map\n Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo);\n // Add value\n infoMap.put(key, value);\n\n // Turn back into string\n extraInfo = getJSONFromMap(infoMap);\n }", "public Optional<URL> getRoute(String routeName) {\n Route route = getClient().routes()\n .inNamespace(namespace).withName(routeName).get();\n\n return route != null ? Optional.ofNullable(createUrlFromRoute(route)) : Optional.empty();\n }", "int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }", "HtmlTag attr(String name, String value) {\n if (attrs == null) {\n attrs = new HashMap<>();\n }\n attrs.put(name, value);\n return this;\n }" ]
Returns true if the context has access to any given permissions.
[ "private static boolean hasSelfPermissions(Context context, String... permissions) {\n for (String permission : permissions) {\n if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {\n return true;\n }\n }\n return false;\n }" ]
[ "public int[] sampleBatchWithoutReplacement() {\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n if (cur == indices.length) {\n cur = 0;\n }\n if (cur == 0) {\n IntArrays.shuffle(indices);\n }\n batch[i] = indices[cur++];\n }\n return batch;\n }", "public static Diagram parseJson(JSONObject json,\n Boolean keepGlossaryLink) throws JSONException {\n ArrayList<Shape> shapes = new ArrayList<Shape>();\n HashMap<String, JSONObject> flatJSON = flatRessources(json);\n for (String resourceId : flatJSON.keySet()) {\n parseRessource(shapes,\n flatJSON,\n resourceId,\n keepGlossaryLink);\n }\n String id = \"canvas\";\n\n if (json.has(\"resourceId\")) {\n id = json.getString(\"resourceId\");\n shapes.remove(new Shape(id));\n }\n ;\n Diagram diagram = new Diagram(id);\n\n // remove Diagram\n // (Diagram)getShapeWithId(json.getString(\"resourceId\"), shapes);\n parseStencilSet(json,\n diagram);\n parseSsextensions(json,\n diagram);\n parseStencil(json,\n diagram);\n parseProperties(json,\n diagram,\n keepGlossaryLink);\n parseChildShapes(shapes,\n json,\n diagram);\n parseBounds(json,\n diagram);\n diagram.setShapes(shapes);\n return diagram;\n }", "protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\n }", "public double getDouble(Integer id, Integer type)\n {\n double result = Double.longBitsToDouble(getLong(id, type));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return result;\n }", "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 }", "private void readCostRateTables(Resource resource, Rates rates)\n {\n if (rates == null)\n {\n CostRateTable table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(0, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(1, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(2, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(3, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(4, table);\n }\n else\n {\n Set<CostRateTable> tables = new HashSet<CostRateTable>();\n\n for (net.sf.mpxj.mspdi.schema.Project.Resources.Resource.Rates.Rate rate : rates.getRate())\n {\n Rate standardRate = DatatypeConverter.parseRate(rate.getStandardRate());\n TimeUnit standardRateFormat = DatatypeConverter.parseTimeUnit(rate.getStandardRateFormat());\n Rate overtimeRate = DatatypeConverter.parseRate(rate.getOvertimeRate());\n TimeUnit overtimeRateFormat = DatatypeConverter.parseTimeUnit(rate.getOvertimeRateFormat());\n Double costPerUse = DatatypeConverter.parseCurrency(rate.getCostPerUse());\n Date endDate = rate.getRatesTo();\n\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n\n int tableIndex = rate.getRateTable().intValue();\n CostRateTable table = resource.getCostRateTable(tableIndex);\n if (table == null)\n {\n table = new CostRateTable();\n resource.setCostRateTable(tableIndex, table);\n }\n table.add(entry);\n tables.add(table);\n }\n\n for (CostRateTable table : tables)\n {\n Collections.sort(table);\n }\n }\n }", "private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\n }", "private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) {\n ClassFileServices classFileServices = services.get(ClassFileServices.class);\n if (classFileServices != null) {\n final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class);\n try {\n final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods());\n services.add(FastProcessAnnotatedTypeResolver.class, resolver);\n } catch (UnsupportedObserverMethodException e) {\n BootstrapLogger.LOG.notUsingFastResolver(e.getObserver());\n return;\n }\n }\n }", "protected void addRow(int uniqueID, Map<String, Object> map)\n {\n m_rows.put(Integer.valueOf(uniqueID), new MapRow(map));\n }" ]
Create a temporary directory under a given workspace
[ "public static FilePath createAndGetTempDir(final FilePath ws) throws IOException, InterruptedException {\n // The token that combines the project name and unique number to create unique workspace directory.\n String workspaceList = System.getProperty(\"hudson.slaves.WorkspaceList\");\n return ws.act(new MasterToSlaveCallable<FilePath, IOException>() {\n @Override\n public FilePath call() {\n final FilePath tempDir = ws.sibling(ws.getName() + Objects.toString(workspaceList, \"@\") + \"tmp\").child(\"artifactory\");\n File tempDirFile = new File(tempDir.getRemote());\n tempDirFile.mkdirs();\n tempDirFile.deleteOnExit();\n return tempDir;\n }\n });\n }" ]
[ "protected int _countPeriods(String str)\n {\n int commas = 0;\n for (int i = 0, end = str.length(); i < end; ++i) {\n int ch = str.charAt(i);\n if (ch < '0' || ch > '9') {\n if (ch == '.') {\n ++commas;\n } else {\n return -1;\n }\n }\n }\n return commas;\n }", "private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) {\n ImmutableSet.Builder<Type> types = ImmutableSet.builder();\n // session beans\n Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>();\n HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass());\n for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) {\n // first we need to resolve the local interface\n Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface()));\n SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface);\n if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) {\n // WELD-1675 Only add types also included in Annotated.getTypeClosure()\n for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) {\n if (annotated.getTypeClosure().contains(entry.getValue())) {\n typeMap.put(entry.getKey(), entry.getValue());\n }\n }\n } else {\n // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class\n typeMap.putAll(interfaceDiscovery.getTypeMap());\n }\n }\n if (annotated.isAnnotationPresent(Typed.class)) {\n types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class)));\n } else {\n typeMap.put(Object.class, Object.class);\n types.addAll(typeMap.values());\n }\n return Beans.getLegalBeanTypes(types.build(), annotated);\n }", "@IntRange(from = 0, to = OPAQUE)\n private static int resolveLineAlpha(\n @IntRange(from = 0, to = OPAQUE) final int sceneAlpha,\n final float maxDistance,\n final float distance) {\n final float alphaPercent = 1f - distance / maxDistance;\n final int alpha = (int) ((float) OPAQUE * alphaPercent);\n return alpha * sceneAlpha / OPAQUE;\n }", "public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) {\n // Filter out nodes that don't belong to the zone being dropped\n Set<Node> survivingNodes = new HashSet<Node>();\n for(int nodeId: intermediateCluster.getNodeIds()) {\n if(intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) {\n survivingNodes.add(intermediateCluster.getNodeById(nodeId));\n }\n }\n\n // Filter out dropZoneId from all zones\n Set<Zone> zones = new HashSet<Zone>();\n for(int zoneId: intermediateCluster.getZoneIds()) {\n if(zoneId == dropZoneId) {\n continue;\n }\n List<Integer> proximityList = intermediateCluster.getZoneById(zoneId)\n .getProximityList();\n proximityList.remove(new Integer(dropZoneId));\n zones.add(new Zone(zoneId, proximityList));\n }\n\n return new Cluster(intermediateCluster.getName(),\n Utils.asSortedList(survivingNodes),\n Utils.asSortedList(zones));\n }", "@Override\n public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms)\n throws VoldemortException {\n // acquire write lock\n writeLock.lock();\n try {\n String key = ByteUtils.getString(keyBytes.get(), \"UTF-8\");\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n\n Versioned<Object> valueObject = convertStringToObject(key, value);\n\n this.put(key, valueObject);\n } finally {\n writeLock.unlock();\n }\n }", "public static hanode_routemonitor6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor6_binding obj = new hanode_routemonitor6_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor6_binding response[] = (hanode_routemonitor6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void primeCache() {\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 handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }", "public Path getTransformedXSLTPath(FileModel payload)\n {\n ReportService reportService = new ReportService(getGraphContext());\n Path outputPath = reportService.getReportDirectory();\n outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload));\n if (!Files.isDirectory(outputPath))\n {\n try\n {\n Files.createDirectories(outputPath);\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to create output directory at: \" + outputPath + \" due to: \"\n + e.getMessage(), e);\n }\n }\n return outputPath;\n }", "public synchronized void maybeThrottle(int eventsSeen) {\n if (maxRatePerSecond > 0) {\n long now = time.milliseconds();\n try {\n rateSensor.record(eventsSeen, now);\n } catch (QuotaViolationException e) {\n // If we're over quota, we calculate how long to sleep to compensate.\n double currentRate = e.getValue();\n if (currentRate > this.maxRatePerSecond) {\n double excessRate = currentRate - this.maxRatePerSecond;\n long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);\n if(logger.isDebugEnabled()) {\n logger.debug(\"Throttler quota exceeded:\\n\" +\n \"eventsSeen \\t= \" + eventsSeen + \" in this call of maybeThrotte(),\\n\" +\n \"currentRate \\t= \" + currentRate + \" events/sec,\\n\" +\n \"maxRatePerSecond \\t= \" + this.maxRatePerSecond + \" events/sec,\\n\" +\n \"excessRate \\t= \" + excessRate + \" events/sec,\\n\" +\n \"sleeping for \\t\" + sleepTimeMs + \" ms to compensate.\\n\" +\n \"rateConfig.timeWindowMs() = \" + rateConfig.timeWindowMs());\n }\n if (sleepTimeMs > rateConfig.timeWindowMs()) {\n logger.warn(\"Throttler sleep time (\" + sleepTimeMs + \" ms) exceeds \" +\n \"window size (\" + rateConfig.timeWindowMs() + \" ms). This will likely \" +\n \"result in not being able to honor the rate limit accurately.\");\n // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size\n // too high could cause this problem.\n }\n time.sleep(sleepTimeMs);\n } else if (logger.isDebugEnabled()) {\n logger.debug(\"Weird. Got QuotaValidationException but measured rate not over rateLimit: \" +\n \"currentRate = \" + currentRate + \" , rateLimit = \" + this.maxRatePerSecond);\n }\n }\n }\n }" ]
set custom response for profile's default client @param profileName profileName to modify @param pathName friendly name of path @param customData custom request data @return true if success, false otherwise
[ "public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }" ]
[ "private void emit(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n float[] allParticlePositions = new float[particlePositions.length + particleBoundingVolume.length];\n System.arraycopy(particlePositions, 0, allParticlePositions, 0, particlePositions.length);\n System.arraycopy(particleBoundingVolume, 0, allParticlePositions,\n particlePositions.length, particleBoundingVolume.length);\n\n float[] allSpawnTimes = new float[particleTimeStamps.length + BVSpawnTimes.length];\n System.arraycopy(particleTimeStamps, 0, allSpawnTimes, 0, particleTimeStamps.length);\n System.arraycopy(BVSpawnTimes, 0, allSpawnTimes, particleTimeStamps.length, BVSpawnTimes.length);\n\n float[] allParticleVelocities = new float[particleVelocities.length + BVVelocities.length];\n System.arraycopy(particleVelocities, 0, allParticleVelocities, 0, particleVelocities.length);\n System.arraycopy(BVVelocities, 0, allParticleVelocities, particleVelocities.length, BVVelocities.length);\n\n\n Particles particleMesh = new Particles(mGVRContext, mMaxAge,\n mParticleSize, mEnvironmentAcceleration, mParticleSizeRate, mFadeWithAge,\n mParticleTexture, mColor, mNoiseFactor);\n\n\n GVRSceneObject particleObject = particleMesh.makeParticleMesh(allParticlePositions,\n allParticleVelocities, allSpawnTimes);\n\n this.addChildObject(particleObject);\n meshInfo.add(Pair.create(particleObject, currTime));\n }", "public double dot(Vector3d v1) {\n return x * v1.x + y * v1.y + z * v1.z;\n }", "private static String normalizeDirName(String name)\n {\n if(name == null)\n return null;\n return name.toLowerCase().replaceAll(\"[^a-zA-Z0-9]\", \"-\");\n }", "protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }", "protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }", "public static servicegroup_lbmonitor_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_lbmonitor_binding obj = new servicegroup_lbmonitor_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_lbmonitor_binding response[] = (servicegroup_lbmonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }", "public 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}", "public static nslimitidentifier_stats[] get(nitro_service service) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tnslimitidentifier_stats[] response = (nslimitidentifier_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}" ]
Method to know if already exists one file with the same name in the same folder @param scenario_name @param path @param dest_dir @return true when the file does not exist
[ "protected static boolean fileDoesNotExist(String file, String path,\n String dest_dir) {\n\n File f = new File(dest_dir);\n if (!f.isDirectory())\n return false;\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n\n File javaFile = new File(f, file);\n boolean result = !javaFile.exists();\n\n return result;\n }" ]
[ "public static inat get(nitro_service service, String name) throws Exception{\n\t\tinat obj = new inat();\n\t\tobj.set_name(name);\n\t\tinat response = (inat) obj.get_resource(service);\n\t\treturn response;\n\t}", "private String toSQLClause(FieldCriteria c, ClassDescriptor cld)\r\n {\r\n String colName = toSqlClause(c.getAttribute(), cld);\r\n return colName + c.getClause() + c.getValue();\r\n }", "public static void setDefaultConfiguration(SimpleConfiguration config) {\n config.setProperty(CONNECTION_ZOOKEEPERS_PROP, CONNECTION_ZOOKEEPERS_DEFAULT);\n config.setProperty(CONNECTION_ZOOKEEPER_TIMEOUT_PROP, CONNECTION_ZOOKEEPER_TIMEOUT_DEFAULT);\n config.setProperty(DFS_ROOT_PROP, DFS_ROOT_DEFAULT);\n config.setProperty(ACCUMULO_ZOOKEEPERS_PROP, ACCUMULO_ZOOKEEPERS_DEFAULT);\n config.setProperty(WORKER_NUM_THREADS_PROP, WORKER_NUM_THREADS_DEFAULT);\n config.setProperty(TRANSACTION_ROLLBACK_TIME_PROP, TRANSACTION_ROLLBACK_TIME_DEFAULT);\n config.setProperty(LOADER_NUM_THREADS_PROP, LOADER_NUM_THREADS_DEFAULT);\n config.setProperty(LOADER_QUEUE_SIZE_PROP, LOADER_QUEUE_SIZE_DEFAULT);\n config.setProperty(MINI_START_ACCUMULO_PROP, MINI_START_ACCUMULO_DEFAULT);\n config.setProperty(MINI_DATA_DIR_PROP, MINI_DATA_DIR_DEFAULT);\n }", "public void reinitIfClosed() {\n if (isClosed.get()) {\n logger.info(\"External Resource was released. Now Re-initializing resources ...\");\n\n ActorConfig.createAndGetActorSystem();\n httpClientStore.reinit();\n tcpSshPingResourceStore.reinit();\n try {\n Thread.sleep(1000l);\n } catch (InterruptedException e) {\n logger.error(\"error reinit httpClientStore\", e);\n }\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been reinitialized.\");\n } else {\n logger.debug(\"NO OP. Resource was not released.\");\n }\n }", "private int getBeliefCount() {\n Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT);\n if (count == null) count = 0; // Just in case, not really sure if this is necessary.\n return count;\n }", "public Axis getOrientationAxis() {\n final Axis axis;\n switch(getOrientation()) {\n case HORIZONTAL:\n axis = Axis.X;\n break;\n case VERTICAL:\n axis = Axis.Y;\n break;\n case STACK:\n axis = Axis.Z;\n break;\n default:\n Log.w(TAG, \"Unsupported orientation %s\", mOrientation);\n axis = Axis.X;\n break;\n }\n return axis;\n }", "protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }", "public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}", "@VisibleForTesting\n @Nullable\n protected LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) {\n final Stroke stroke = createStroke(styleJson, true);\n if (stroke == null) {\n return null;\n } else {\n return this.styleBuilder.createLineSymbolizer(stroke);\n }\n }" ]
Return the content from an URL in byte array @param stringUrl URL to get @return byte array @throws IOException I/O error happened
[ "public static byte[] getContentBytes(String stringUrl) throws IOException {\n URL url = new URL(stringUrl);\n byte[] data = MyStreamUtils.readContentBytes(url.openStream());\n return data;\n }" ]
[ "synchronized int storeObject(JSONObject obj, Table table) {\n if (!this.belowMemThreshold()) {\n Logger.v(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = table.getName();\n\n Cursor cursor = null;\n int count = DB_UPDATE_ERROR;\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n cursor = db.rawQuery(\"SELECT COUNT(*) FROM \" + tableName, null);\n cursor.moveToFirst();\n count = cursor.getInt(0);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n\n if (cursor != null) {\n cursor.close();\n cursor = null;\n }\n dbHelper.deleteDatabase();\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n dbHelper.close();\n }\n return count;\n }", "public static base_responses update(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile updateresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleprofile();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].apikey = resources[i].apikey;\n\t\t\t\tupdateresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void readDefinitions()\n {\n for (MapRow row : m_tables.get(\"TTL\"))\n {\n Integer id = row.getInteger(\"DEFINITION_ID\");\n List<MapRow> list = m_definitions.get(id);\n if (list == null)\n {\n list = new ArrayList<MapRow>();\n m_definitions.put(id, list);\n }\n list.add(row);\n }\n\n List<MapRow> rows = m_definitions.get(WBS_FORMAT_ID);\n if (rows != null)\n {\n m_wbsFormat = new SureTrakWbsFormat(rows.get(0));\n }\n }", "public static RgbaColor from(String color) {\n if (color.startsWith(\"#\")) {\n return fromHex(color);\n }\n else if (color.startsWith(\"rgba\")) {\n return fromRgba(color);\n }\n else if (color.startsWith(\"rgb\")) {\n return fromRgb(color);\n }\n else if (color.startsWith(\"hsla\")) {\n return fromHsla(color);\n }\n else if (color.startsWith(\"hsl\")) {\n return fromHsl(color);\n }\n else {\n return getDefaultColor();\n }\n }", "public static boolean isAscii(Slice utf8)\n {\n int length = utf8.length();\n int offset = 0;\n\n // Length rounded to 8 bytes\n int length8 = length & 0x7FFF_FFF8;\n for (; offset < length8; offset += 8) {\n if ((utf8.getLongUnchecked(offset) & TOP_MASK64) != 0) {\n return false;\n }\n }\n // Enough bytes left for 32 bits?\n if (offset + 4 < length) {\n if ((utf8.getIntUnchecked(offset) & TOP_MASK32) != 0) {\n return false;\n }\n\n offset += 4;\n }\n // Do the rest one by one\n for (; offset < length; offset++) {\n if ((utf8.getByteUnchecked(offset) & 0x80) != 0) {\n return false;\n }\n }\n\n return true;\n }", "public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }", "public AT_Context setFrameLeftRightMargin(int frameLeft, int frameRight){\r\n\t\tif(frameRight>-1 && frameLeft>-1){\r\n\t\t\tthis.frameLeftMargin = frameLeft;\r\n\t\t\tthis.frameRightMargin = frameRight;\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static double blackScholesOptionTheta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate theta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble theta = volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue + riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn theta;\n\t\t}\n\t}", "public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\t\t// Check if the LMM uses a discount curve which is created from a forward curve\n\t\tif(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains(\"DiscountCurveFromForwardCurve\".toLowerCase())){\n\t\t\treturn new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime));\n\t\t}\n\t\telse {\n\t\t\t// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.\n\t\t\t// Only at startTime 0!\n\t\t\treturn (DiscountCurveInterface) model.getModel().getDiscountCurve();\n\t\t}\n\n\t}" ]
Returns the JRDesignGroup for the DJGroup passed @param jd @param layoutManager @param group @return
[ "public static JRDesignGroup getJRDesignGroup(DynamicJasperDesign jd, LayoutManager layoutManager, DJGroup group) {\n\t\tMap references = layoutManager.getReferencesMap();\n\t\tfor (Object o : references.keySet()) {\n\t\t\tString groupName = (String) o;\n\t\t\tDJGroup djGroup = (DJGroup) references.get(groupName);\n\t\t\tif (group == djGroup) {\n\t\t\t\treturn (JRDesignGroup) jd.getGroupsMap().get(groupName);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}" ]
[ "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}", "public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) {\n return Filter.newBuilder()\n .setCompositeFilter(CompositeFilter.newBuilder()\n .addAllFilters(subfilters)\n .setOp(CompositeFilter.Operator.AND));\n }", "@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }", "public static File createDir(String dir) {\n // create outdir\n File directory = null;\n if(dir != null) {\n directory = new File(dir);\n if(!(directory.exists() || directory.mkdir())) {\n Utils.croak(\"Can't find or create directory \" + dir);\n }\n }\n return directory;\n }", "public static List<Versioned<byte[]>> resolveVersions(List<Versioned<byte[]>> values) {\n List<Versioned<byte[]>> resolvedVersions = new ArrayList<Versioned<byte[]>>(values.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<byte[]> value: values) {\n Iterator<Versioned<byte[]>> iter = resolvedVersions.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<byte[]> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(!obsolete) {\n // else update the set of accepted versions\n resolvedVersions.add(value);\n }\n }\n\n return resolvedVersions;\n }", "public Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\n }", "@SuppressWarnings(\"unchecked\")\n public HttpMethodInfo handle(HttpRequest request,\n HttpResponder responder, Map<String, String> groupValues) throws Exception {\n //TODO: Refactor group values.\n try {\n if (httpMethods.contains(request.method())) {\n //Setup args for reflection call\n Object [] args = new Object[paramsInfo.size()];\n\n int idx = 0;\n for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {\n if (info.containsKey(PathParam.class)) {\n args[idx] = getPathParamValue(info, groupValues);\n }\n if (info.containsKey(QueryParam.class)) {\n args[idx] = getQueryParamValue(info, request.uri());\n }\n if (info.containsKey(HeaderParam.class)) {\n args[idx] = getHeaderParamValue(info, request);\n }\n idx++;\n }\n\n return new HttpMethodInfo(method, handler, responder, args, exceptionHandler);\n } else {\n //Found a matching resource but could not find the right HttpMethod so return 405\n throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format\n (\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n }\n } catch (Throwable e) {\n throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Error in executing request: %s %s\", request.method(),\n request.uri()), e);\n }\n }", "private void insert(int position, int c) {\r\n for (int i = 143; i > position; i--) {\r\n set[i] = set[i - 1];\r\n character[i] = character[i - 1];\r\n }\r\n character[position] = c;\r\n }", "public static URL classFileUrl(Class<?> clazz) throws IOException {\n ClassLoader cl = clazz.getClassLoader();\n if (cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL res = cl.getResource(clazz.getName().replace('.', '/') + \".class\");\n if (res == null) {\n throw new IllegalArgumentException(\"Unable to locate class file for \" + clazz);\n }\n return res;\n }" ]
The setter for setting configuration file. It will convert the value to a URI. @param configurationFiles the configuration file map.
[ "public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }" ]
[ "public Where<T, ID> not(Where<T, ID> comparison) {\n\t\taddClause(new Not(pop(\"NOT\")));\n\t\treturn this;\n\t}", "private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)\n throws CmsException {\n\n CmsObject cmsClone;\n if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {\n cmsClone = cms;\n } else {\n cmsClone = OpenCms.initCmsObject(cms);\n cmsClone.getRequestContext().setSiteRoot(module.getSite());\n }\n\n return cmsClone;\n }", "protected Object checkUndefined(Object val) {\n if (val instanceof String && ((String) val).equals(\"undefined\")) {\n return null;\n }\n return val;\n }", "public long indexOf(final String element) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return doIndexOf(jedis, element);\n }\n });\n }", "public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);\r\n }", "private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }", "private void setHeaderList(Map<String, List<String>> headers, String name, String value) {\n\n List<String> values = new ArrayList<String>();\n values.add(SET_HEADER + value);\n headers.put(name, values);\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 }", "public void handleStateEvent(String callbackKey) {\n if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {\n ((StateEventHandler) handlers.get(callbackKey)).handle();\n } else {\n System.err.println(\"Error in handle: \" + callbackKey + \" for state handler \");\n }\n }" ]
Deletes a specific client id for a profile @param model @param profileIdentifier @param clientUUID @return returns the table of the remaining clients or an exception if deletion failed for some reason @throws Exception
[ "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n logger.info(\"Attempting to remove the following client: {}\", clientUUID);\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n clientService.remove(profileId, clientUUID);\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }" ]
[ "public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }", "void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}", "protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {\n try {\n if (getBeanType().isInterface()) {\n ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());\n } else {\n boolean constructorFound = false;\n for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {\n if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {\n constructorFound = true;\n String[] exceptions = new String[constructor.getExceptionTypes().length];\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = constructor.getExceptionTypes()[i].getName();\n }\n ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag());\n }\n }\n if (!constructorFound) {\n // the bean only has private constructors, we need to generate\n // two fake constructors that call each other\n addConstructorsForBeanWithPrivateConstructors(proxyClassType);\n }\n }\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }", "public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\n }", "public synchronized void addListener(CollectionProxyListener listener)\r\n {\r\n if (_listeners == null)\r\n {\r\n _listeners = new ArrayList();\r\n }\r\n // to avoid multi-add of same listener, do check\r\n if(!_listeners.contains(listener))\r\n {\r\n _listeners.add(listener);\r\n }\r\n }", "public DynamicReport build() {\n\n if (built) {\n throw new DJBuilderException(\"DynamicReport already built. Cannot use more than once.\");\n } else {\n built = true;\n }\n\n report.setOptions(options);\n if (!globalVariablesGroup.getFooterVariables().isEmpty() || !globalVariablesGroup.getHeaderVariables().isEmpty() || !globalVariablesGroup.getVariables().isEmpty() || hasPercentageColumn()) {\n report.getColumnsGroups().add(0, globalVariablesGroup);\n }\n\n createChartGroups();\n\n addGlobalCrosstabs();\n\n addSubreportsToGroups();\n\n concatenateReports();\n\n report.setAutoTexts(autoTexts);\n return report;\n }", "public static base_response add(nitro_service client, cmppolicylabel resource) throws Exception {\n\t\tcmppolicylabel addresource = new cmppolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}", "private boolean runQueuedTask(boolean hasPermit) {\n if (!hasPermit && beginRequest(paused) == RunResult.REJECTED) {\n return false;\n }\n QueuedTask task = null;\n if (!paused) {\n task = taskQueue.poll();\n } else {\n //the container is suspended, but we still need to run any force queued tasks\n task = findForcedTask();\n }\n if (task != null) {\n if(!task.runRequest()) {\n decrementRequestCount();\n }\n return true;\n } else {\n decrementRequestCount();\n return false;\n }\n }", "public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\n }" ]
Set the url for the shape file. @param url shape file url @throws LayerException file cannot be accessed @since 1.7.1
[ "@Api\n\tpublic void setUrl(String url) throws LayerException {\n\t\ttry {\n\t\t\tthis.url = url;\n\t\t\tMap<String, Object> params = new HashMap<String, Object>();\n\t\t\tparams.put(\"url\", url);\n\t\t\tDataStore store = DataStoreFactory.create(params);\n\t\t\tsetDataStore(store);\n\t\t} catch (IOException ioe) {\n\t\t\tthrow new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url);\n\t\t}\n\t}" ]
[ "protected void addNeighbor(Queue<ColorPoint> queue, int px, int py, int color, Feature component) {\n if (!inBoundary(px, py, component)) {\n return;\n }\n\n if (!mask.isTouched(px, py)) {\n queue.add(new ColorPoint(px, py, color));\n }\n }", "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 List<Collaborator> listCollaborators(String appName) {\n return connection.execute(new CollabList(appName), apiKey);\n }", "protected void add(Widget child, Element container) {\n\n // Detach new child.\n child.removeFromParent();\n\n // Logical attach.\n getChildren().add(child);\n\n // Physical attach.\n DOM.appendChild(container, child.getElement());\n\n // Adopt.\n adopt(child);\n }", "public static List<File> listFiles(File[] directories, IOFileFilter fileFilter, IOFileFilter dirFilter) {\n List<File> files = new ArrayList<>();\n for (File directory : directories) {\n if (!directory.isDirectory()) {\n continue;\n }\n Collection<File> filesInDirectory = FileUtils.listFiles(directory,\n fileFilter,\n dirFilter);\n files.addAll(filesInDirectory);\n }\n return files;\n }", "private Integer getNumId(String idString, boolean isUri) {\n\t\tString numString;\n\t\tif (isUri) {\n\t\t\tif (!idString.startsWith(\"http://www.wikidata.org/entity/\")) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tnumString = idString.substring(\"http://www.wikidata.org/entity/Q\"\n\t\t\t\t\t.length());\n\t\t} else {\n\t\t\tnumString = idString.substring(1);\n\t\t}\n\t\treturn Integer.parseInt(numString);\n\t}", "private String getPropertyLabel(PropertyIdValue propertyIdValue) {\n\t\tPropertyRecord propertyRecord = this.propertyRecords\n\t\t\t\t.get(propertyIdValue);\n\t\tif (propertyRecord == null || propertyRecord.propertyDocument == null) {\n\t\t\treturn propertyIdValue.getId();\n\t\t} else {\n\t\t\treturn getLabel(propertyIdValue, propertyRecord.propertyDocument);\n\t\t}\n\t}", "public static Polygon calculateBounds(final MapfishMapContext context) {\n double rotation = context.getRootContext().getRotation();\n ReferencedEnvelope env = context.getRootContext().toReferencedEnvelope();\n\n Coordinate centre = env.centre();\n AffineTransform rotateInstance = AffineTransform.getRotateInstance(rotation, centre.x, centre.y);\n\n double[] dstPts = new double[8];\n double[] srcPts = {\n env.getMinX(), env.getMinY(), env.getMinX(), env.getMaxY(),\n env.getMaxX(), env.getMaxY(), env.getMaxX(), env.getMinY()\n };\n\n rotateInstance.transform(srcPts, 0, dstPts, 0, 4);\n\n return new GeometryFactory().createPolygon(new Coordinate[]{\n new Coordinate(dstPts[0], dstPts[1]), new Coordinate(dstPts[2], dstPts[3]),\n new Coordinate(dstPts[4], dstPts[5]), new Coordinate(dstPts[6], dstPts[7]),\n new Coordinate(dstPts[0], dstPts[1])\n });\n }", "public static base_response update(nitro_service client, nsspparams resource) throws Exception {\n\t\tnsspparams updateresource = new nsspparams();\n\t\tupdateresource.basethreshold = resource.basethreshold;\n\t\tupdateresource.throttle = resource.throttle;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Inserts a String value into the mapping of the underlying Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a String, or null @return this bundler instance to chain method calls
[ "public Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\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}", "static File getTargetFile(final File root, final MiscContentItem item) {\n return PatchContentLoader.getMiscPath(root, item);\n }", "protected NodeData createBodyStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"background-color\", tf.createColor(255, 255, 255)));\n return ret;\n }", "private 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 }", "private void forward() {\n\n Set<String> selected = new HashSet<>();\n\n for (CheckBox checkbox : m_componentCheckboxes) {\n CmsSetupComponent component = (CmsSetupComponent)(checkbox.getData());\n if (checkbox.getValue().booleanValue()) {\n selected.add(component.getId());\n }\n }\n String error = null;\n for (String compId : selected) {\n CmsSetupComponent component = m_componentMap.get(compId);\n for (String dep : component.getDependencies()) {\n if (!selected.contains(dep)) {\n error = \"Unfulfilled dependency: The component \"\n + component.getName()\n + \" can not be installed because its dependency \"\n + m_componentMap.get(dep).getName()\n + \" is not selected\";\n break;\n }\n }\n }\n if (error == null) {\n Set<String> modules = new HashSet<>();\n\n for (CmsSetupComponent component : m_componentMap.values()) {\n\n if (selected.contains(component.getId())) {\n\n for (CmsModule module : m_context.getSetupBean().getAvailableModules().values()) {\n if (component.match(module.getName())) {\n modules.add(module.getName());\n }\n }\n }\n }\n List<String> moduleList = new ArrayList<>(modules);\n m_context.getSetupBean().setInstallModules(CmsStringUtil.listAsString(moduleList, \"|\"));\n m_context.stepForward();\n } else {\n CmsSetupErrorDialog.showErrorDialog(error, error);\n }\n }", "public Record findRecordById(String id) {\n if (directory == null)\n init();\n\n Property idprop = config.getIdentityProperties().iterator().next();\n for (Record r : lookup(idprop, id))\n if (r.getValue(idprop.getName()).equals(id))\n return r;\n\n return null; // not found\n }", "private Set<String> populateTableNames(String url) throws SQLException\n {\n Set<String> tableNames = new HashSet<String>();\n Connection connection = null;\n ResultSet rs = null;\n\n try\n {\n connection = DriverManager.getConnection(url);\n DatabaseMetaData dmd = connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tableNames.add(rs.getString(\"TABLE_NAME\").toUpperCase());\n }\n }\n\n finally\n {\n if (rs != null)\n {\n rs.close();\n }\n\n if (connection != null)\n {\n connection.close();\n }\n }\n\n return tableNames;\n }", "public static Info rand( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"rand-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n RandomMatrices_DDRM.fillUniform(output.matrix, 0,1,manager.getRandom());\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }", "public static final Rect getViewportBounds() {\n return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight());\n }" ]
Checks the second, hour, month, day, month and year are equal.
[ "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear()\n && d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }" ]
[ "public void setSize(ButtonSize size) {\n if (this.size != null) {\n removeStyleName(this.size.getCssName());\n }\n this.size = size;\n\n if (size != null) {\n addStyleName(size.getCssName());\n }\n }", "@Override\n\tpublic Object[] getDatabaseSnapshot(Serializable id, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting current persistent state for: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\n\t\t//snapshot is a Map in the end\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\t//if there is no resulting row, return null\n\t\tif ( resultset == null || resultset.getSnapshot().isEmpty() ) {\n\t\t\treturn null;\n\t\t}\n\t\t//otherwise return the \"hydrated\" state (ie. associations are not resolved)\n\t\tGridType[] types = gridPropertyTypes;\n\t\tObject[] values = new Object[types.length];\n\t\tboolean[] includeProperty = getPropertyUpdateability();\n\t\tfor ( int i = 0; i < types.length; i++ ) {\n\t\t\tif ( includeProperty[i] ) {\n\t\t\t\tvalues[i] = types[i].hydrate( resultset, getPropertyAliases( \"\", i ), session, null ); //null owner ok??\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}", "ValidationResult cleanMultiValuePropertyKey(String name) {\n ValidationResult vr = cleanObjectKey(name);\n\n name = (String) vr.getObject();\n\n // make sure its not a known property key (reserved in the case of multi-value)\n\n try {\n RestrictedMultiValueFields rf = RestrictedMultiValueFields.valueOf(name);\n //noinspection ConstantConditions\n if (rf != null) {\n vr.setErrorDesc(name + \"... is a restricted key for multi-value properties. Operation aborted.\");\n vr.setErrorCode(523);\n vr.setObject(null);\n }\n } catch (Throwable t) {\n //no-op\n }\n\n return vr;\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal);\n }", "@NonNull\n @SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher reset() {\n lastResponsePage = 0;\n lastRequestPage = 0;\n lastResponseId = 0;\n endReached = false;\n clearFacetRefinements();\n cancelPendingRequests();\n numericRefinements.clear();\n return this;\n }", "public Bytes subSequence(int start, int end) {\n if (start > end || start < 0 || end > length) {\n throw new IndexOutOfBoundsException(\"Bad start and/end start = \" + start + \" end=\" + end\n + \" offset=\" + offset + \" length=\" + length);\n }\n return new Bytes(data, offset + start, end - start);\n }", "public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }", "private int getSegmentForX(int x) {\n if (autoScroll.get()) {\n int playHead = (x - (getWidth() / 2));\n int offset = Util.timeToHalfFrame(getFurthestPlaybackPosition()) / scale.get();\n return (playHead + offset) * scale.get();\n }\n return x * scale.get();\n }", "public <T extends Widget & Checkable> void clearChecks() {\n List<T> children = getCheckableChildren();\n for (T c : children) {\n c.setChecked(false);\n }\n }" ]
Creates a new ServerDetails object for resolver, this will take URL and name from the deployer ServerDetails as a default behaviour
[ "private ServerDetails createInitialResolveDetailsFromDeployDetails(ServerDetails deployerDetails) {\n RepositoryConf oldResolveRepositoryConfig = deployerDetails.getResolveReleaseRepository();\n RepositoryConf oldSnapshotResolveRepositoryConfig = deployerDetails.getResolveSnapshotRepository();\n RepositoryConf resolverReleaseRepos = oldResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldResolveRepositoryConfig;\n RepositoryConf resolveSnapshotRepos = oldSnapshotResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotResolveRepositoryConfig;\n return new ServerDetails(deployerDetails.getArtifactoryName(), deployerDetails.getArtifactoryUrl(),\n null, null, resolverReleaseRepos, resolveSnapshotRepos, null, null);\n }" ]
[ "public static void main(String[] args) throws ParseException, IOException {\n\t\tClient client = new Client(\n\t\t\t\tnew DumpProcessingController(\"wikidatawiki\"), args);\n\t\tclient.performActions();\n\t}", "public AsciiTable setTextAlignment(TextAlignment textAlignment){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }", "public static Iterable<BoxCollection.Info> getAllCollections(final BoxAPIConnection api) {\n return new Iterable<BoxCollection.Info>() {\n public Iterator<BoxCollection.Info> iterator() {\n URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL());\n return new BoxCollectionIterator(api, url);\n }\n };\n }", "private SortedProperties getLocalization(Locale locale) throws IOException, CmsException {\n\n if (null == m_localizations.get(locale)) {\n switch (m_bundleType) {\n case PROPERTY:\n loadLocalizationFromPropertyBundle(locale);\n break;\n case XML:\n loadLocalizationFromXmlBundle(locale);\n break;\n case DESCRIPTOR:\n return null;\n default:\n break;\n }\n }\n return m_localizations.get(locale);\n }", "private Object tryConvert(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final Object rowValue) throws URISyntaxException, IOException {\n if (this.converters.isEmpty()) {\n return rowValue;\n }\n\n String value = String.valueOf(rowValue);\n for (TableColumnConverter<?> converter: this.converters) {\n if (converter.canConvert(value)) {\n return converter.resolve(clientHttpRequestFactory, value);\n }\n }\n\n return rowValue;\n }", "protected void append(Env env) {\n addAllWithFilter(this.envVars, env.envVars, filter.getPatternFilter());\n addAllWithFilter(this.sysVars, env.sysVars, filter.getPatternFilter());\n }", "public T removeFile(final String name, final List<String> path, final byte[] existingHash, final boolean isDirectory) {\n return removeFile(name, path, existingHash, isDirectory, null);\n }", "public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {\n\t\tMap<Double, RandomVariable> sum = new HashMap<>();\n\n\t\tfor(double time: timeDiscretization) {\n\t\t\tsum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));\n\t\t}\n\n\t\treturn new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);\n\t}" ]
Waits the given amount of time in seconds for a standalone server to start. @param client the client used to communicate with the server @param startupTimeout the time, in seconds, to wait for the server start @throws InterruptedException if interrupted while waiting for the server to start @throws RuntimeException if the process has died @throws TimeoutException if the timeout has been reached and the server is still not started
[ "public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }" ]
[ "private void notifyIfStopped() {\n if (isAcceptingNewJobs() || !this.runningTasksFutures.isEmpty()) {\n return;\n }\n final File stoppedFile = new File(this.workingDirectories.getWorking(), \"stopped\");\n try {\n LOGGER.info(\"The print has finished processing jobs and can now stop\");\n stoppedFile.createNewFile();\n } catch (IOException e) {\n LOGGER.warn(\"Cannot create the {} file\", stoppedFile, e);\n }\n }", "public static base_responses update(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder updateresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslocspresponder();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].cache = resources[i].cache;\n\t\t\t\tupdateresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\tupdateresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\tupdateresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\tupdateresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\tupdateresources[i].respondercert = resources[i].respondercert;\n\t\t\t\tupdateresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\tupdateresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\tupdateresources[i].signingcert = resources[i].signingcert;\n\t\t\t\tupdateresources[i].usenonce = resources[i].usenonce;\n\t\t\t\tupdateresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private synchronized void initSystemCache() {\n List<StoreDefinition> value = storeMapper.readStoreList(new StringReader(SystemStoreConstants.SYSTEM_STORE_SCHEMA));\n metadataCache.put(SYSTEM_STORES_KEY, new Versioned<Object>(value));\n }", "private Number calculateUnitsPercentComplete(Row row)\n {\n double result = 0;\n\n double actualWorkQuantity = NumberHelper.getDouble(row.getDouble(\"act_work_qty\"));\n double actualEquipmentQuantity = NumberHelper.getDouble(row.getDouble(\"act_equip_qty\"));\n double numerator = actualWorkQuantity + actualEquipmentQuantity;\n\n if (numerator != 0)\n {\n double remainingWorkQuantity = NumberHelper.getDouble(row.getDouble(\"remain_work_qty\"));\n double remainingEquipmentQuantity = NumberHelper.getDouble(row.getDouble(\"remain_equip_qty\"));\n double denominator = remainingWorkQuantity + actualWorkQuantity + remainingEquipmentQuantity + actualEquipmentQuantity;\n result = denominator == 0 ? 0 : ((numerator * 100) / denominator);\n }\n\n return NumberHelper.getDouble(result);\n }", "private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }", "public static inat get(nitro_service service, String name) throws Exception{\n\t\tinat obj = new inat();\n\t\tobj.set_name(name);\n\t\tinat response = (inat) obj.get_resource(service);\n\t\treturn response;\n\t}", "public AT_Context setFrameLeftRightMargin(int frameLeft, int frameRight){\r\n\t\tif(frameRight>-1 && frameLeft>-1){\r\n\t\t\tthis.frameLeftMargin = frameLeft;\r\n\t\t\tthis.frameRightMargin = frameRight;\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public Query getCountQuery(Query aQuery)\r\n {\r\n if(aQuery instanceof QueryBySQL)\r\n {\r\n return getQueryBySqlCount((QueryBySQL) aQuery);\r\n }\r\n else if(aQuery instanceof ReportQueryByCriteria)\r\n {\r\n return getReportQueryByCriteriaCount((ReportQueryByCriteria) aQuery);\r\n }\r\n else\r\n {\r\n return getQueryByCriteriaCount((QueryByCriteria) aQuery);\r\n }\r\n }", "public String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }" ]
Use this API to update route6.
[ "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}" ]
[ "public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }", "public Set<D> getMatchedDeclaration() {\n Set<D> bindedSet = new HashSet<D>();\n for (Map.Entry<ServiceReference<D>, Boolean> e : declarations.entrySet()) {\n if (e.getValue()) {\n bindedSet.add(getDeclaration(e.getKey()));\n }\n }\n return bindedSet;\n }", "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_response add(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder addresource = new sslocspresponder();\n\t\taddresource.name = resource.name;\n\t\taddresource.url = resource.url;\n\t\taddresource.cache = resource.cache;\n\t\taddresource.cachetimeout = resource.cachetimeout;\n\t\taddresource.batchingdepth = resource.batchingdepth;\n\t\taddresource.batchingdelay = resource.batchingdelay;\n\t\taddresource.resptimeout = resource.resptimeout;\n\t\taddresource.respondercert = resource.respondercert;\n\t\taddresource.trustresponder = resource.trustresponder;\n\t\taddresource.producedattimeskew = resource.producedattimeskew;\n\t\taddresource.signingcert = resource.signingcert;\n\t\taddresource.usenonce = resource.usenonce;\n\t\taddresource.insertclientcert = resource.insertclientcert;\n\t\treturn addresource.add_resource(client);\n\t}", "public AT_Row setPaddingTopBottom(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTopBottom(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public final void setIndividualDates(SortedSet<Date> dates) {\n\n m_individualDates.clear();\n if (null != dates) {\n m_individualDates.addAll(dates);\n }\n for (Date d : getExceptions()) {\n if (!m_individualDates.contains(d)) {\n m_exceptions.remove(d);\n }\n }\n\n }", "public static base_responses disable(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 disableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tdisableresources[i] = new Interface();\n\t\t\t\tdisableresources[i].id = id[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}", "public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }", "public static Cluster swapPartitions(final Cluster nextCandidateCluster,\n final int nodeIdA,\n final int partitionIdA,\n final int nodeIdB,\n final int partitionIdB) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n // Swap partitions between nodes!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdA,\n Lists.newArrayList(partitionIdB));\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdB,\n Lists.newArrayList(partitionIdA));\n\n return returnCluster;\n }" ]
Creates a copy with verbose mode enabled. @param serverSetups the server setups. @return copies of server setups with verbose mode enabled.
[ "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 }" ]
[ "@Override\n\tpublic Object[] getDatabaseSnapshot(Serializable id, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting current persistent state for: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\n\t\t//snapshot is a Map in the end\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\t//if there is no resulting row, return null\n\t\tif ( resultset == null || resultset.getSnapshot().isEmpty() ) {\n\t\t\treturn null;\n\t\t}\n\t\t//otherwise return the \"hydrated\" state (ie. associations are not resolved)\n\t\tGridType[] types = gridPropertyTypes;\n\t\tObject[] values = new Object[types.length];\n\t\tboolean[] includeProperty = getPropertyUpdateability();\n\t\tfor ( int i = 0; i < types.length; i++ ) {\n\t\t\tif ( includeProperty[i] ) {\n\t\t\t\tvalues[i] = types[i].hydrate( resultset, getPropertyAliases( \"\", i ), session, null ); //null owner ok??\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}", "public static String formatBigDecimal(BigDecimal number) {\n\t\tif (number.signum() != -1) {\n\t\t\treturn \"+\" + number.toString();\n\t\t} else {\n\t\t\treturn number.toString();\n\t\t}\n\t}", "public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}", "public void doLocalClear()\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clear materialization cache\");\r\n invokeCounter = 0;\r\n enabledReadCache = false;\r\n objectBuffer.clear();\r\n }", "public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {\n\t\tDayCountConventionInterface daycountConvention = getDayCountConvention(convention);\n\t\treturn daycountConvention.getDaycount(startDate, endDate);\n\t}", "public static base_response update(nitro_service client, appfwlearningsettings resource) throws Exception {\n\t\tappfwlearningsettings updateresource = new appfwlearningsettings();\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.starturlminthreshold = resource.starturlminthreshold;\n\t\tupdateresource.starturlpercentthreshold = resource.starturlpercentthreshold;\n\t\tupdateresource.cookieconsistencyminthreshold = resource.cookieconsistencyminthreshold;\n\t\tupdateresource.cookieconsistencypercentthreshold = resource.cookieconsistencypercentthreshold;\n\t\tupdateresource.csrftagminthreshold = resource.csrftagminthreshold;\n\t\tupdateresource.csrftagpercentthreshold = resource.csrftagpercentthreshold;\n\t\tupdateresource.fieldconsistencyminthreshold = resource.fieldconsistencyminthreshold;\n\t\tupdateresource.fieldconsistencypercentthreshold = resource.fieldconsistencypercentthreshold;\n\t\tupdateresource.crosssitescriptingminthreshold = resource.crosssitescriptingminthreshold;\n\t\tupdateresource.crosssitescriptingpercentthreshold = resource.crosssitescriptingpercentthreshold;\n\t\tupdateresource.sqlinjectionminthreshold = resource.sqlinjectionminthreshold;\n\t\tupdateresource.sqlinjectionpercentthreshold = resource.sqlinjectionpercentthreshold;\n\t\tupdateresource.fieldformatminthreshold = resource.fieldformatminthreshold;\n\t\tupdateresource.fieldformatpercentthreshold = resource.fieldformatpercentthreshold;\n\t\tupdateresource.xmlwsiminthreshold = resource.xmlwsiminthreshold;\n\t\tupdateresource.xmlwsipercentthreshold = resource.xmlwsipercentthreshold;\n\t\tupdateresource.xmlattachmentminthreshold = resource.xmlattachmentminthreshold;\n\t\tupdateresource.xmlattachmentpercentthreshold = resource.xmlattachmentpercentthreshold;\n\t\treturn updateresource.update_resource(client);\n\t}", "@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)\n public static synchronized void register(android.app.Application application) {\n if (application == null) {\n Logger.i(\"Application instance is null/system API is too old\");\n return;\n }\n\n if (registered) {\n Logger.v(\"Lifecycle callbacks have already been registered\");\n return;\n }\n\n registered = true;\n application.registerActivityLifecycleCallbacks(\n new android.app.Application.ActivityLifecycleCallbacks() {\n\n @Override\n public void onActivityCreated(Activity activity, Bundle bundle) {\n CleverTapAPI.onActivityCreated(activity);\n }\n\n @Override\n public void onActivityStarted(Activity activity) {}\n\n @Override\n public void onActivityResumed(Activity activity) {\n CleverTapAPI.onActivityResumed(activity);\n }\n\n @Override\n public void onActivityPaused(Activity activity) {\n CleverTapAPI.onActivityPaused();\n }\n\n @Override\n public void onActivityStopped(Activity activity) {}\n\n @Override\n public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}\n\n @Override\n public void onActivityDestroyed(Activity activity) {}\n }\n\n );\n Logger.i(\"Activity Lifecycle Callback successfully registered\");\n }", "public static Logger getLogger(String className) {\n\t\tif (logType == null) {\n\t\t\tlogType = findLogType();\n\t\t}\n\t\treturn new Logger(logType.createLog(className));\n\t}", "public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}" ]
Log a message at the provided level.
[ "public void log(Level level, String msg) {\n\t\tlogIfEnabled(level, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}" ]
[ "public synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }", "public ManagementModelNode findNode(String address) {\n ManagementModelNode root = (ManagementModelNode)tree.getModel().getRoot();\n Enumeration<javax.swing.tree.TreeNode> allNodes = root.depthFirstEnumeration();\n while (allNodes.hasMoreElements()) {\n ManagementModelNode node = (ManagementModelNode)allNodes.nextElement();\n if (node.addressPath().equals(address)) return node;\n }\n\n return null;\n }", "protected void layoutChild(final int dataIndex) {\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n float offset = mOffset.get(Axis.X);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.X, offset);\n }\n\n offset = mOffset.get(Axis.Y);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Y, offset);\n }\n\n offset = mOffset.get(Axis.Z);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Z, offset);\n }\n }\n }", "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 }", "@Override\n public void solve(DMatrixRBlock B, DMatrixRBlock X) {\n if( B.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in B.\");\n\n DSubmatrixD1 L = new DSubmatrixD1(decomposer.getT(null));\n\n if( X != null ) {\n if( X.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in X.\");\n if( X.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in X\");\n }\n \n if( B.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in B\");\n\n // L * L^T*X = B\n\n // Solve for Y: L*Y = B\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),false);\n\n // L^T * X = Y\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),true);\n\n if( X != null ) {\n // copy the solution from B into X\n MatrixOps_DDRB.extractAligned(B,X);\n }\n\n }", "public static 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 ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }", "public static dospolicy[] get(nitro_service service) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tdospolicy[] response = (dospolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void registerDataPersisters(DataPersister... dataPersisters) {\n\t\t// we build the map and replace it to lower the chance of concurrency issues\n\t\tList<DataPersister> newList = new ArrayList<DataPersister>();\n\t\tif (registeredPersisters != null) {\n\t\t\tnewList.addAll(registeredPersisters);\n\t\t}\n\t\tfor (DataPersister persister : dataPersisters) {\n\t\t\tnewList.add(persister);\n\t\t}\n\t\tregisteredPersisters = newList;\n\t}" ]
Enables lifecycle callbacks for Android devices @param application App's Application object
[ "@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)\n public static synchronized void register(android.app.Application application) {\n if (application == null) {\n Logger.i(\"Application instance is null/system API is too old\");\n return;\n }\n\n if (registered) {\n Logger.v(\"Lifecycle callbacks have already been registered\");\n return;\n }\n\n registered = true;\n application.registerActivityLifecycleCallbacks(\n new android.app.Application.ActivityLifecycleCallbacks() {\n\n @Override\n public void onActivityCreated(Activity activity, Bundle bundle) {\n CleverTapAPI.onActivityCreated(activity);\n }\n\n @Override\n public void onActivityStarted(Activity activity) {}\n\n @Override\n public void onActivityResumed(Activity activity) {\n CleverTapAPI.onActivityResumed(activity);\n }\n\n @Override\n public void onActivityPaused(Activity activity) {\n CleverTapAPI.onActivityPaused();\n }\n\n @Override\n public void onActivityStopped(Activity activity) {}\n\n @Override\n public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}\n\n @Override\n public void onActivityDestroyed(Activity activity) {}\n }\n\n );\n Logger.i(\"Activity Lifecycle Callback successfully registered\");\n }" ]
[ "private void writeInterfaceCriteria(final XMLExtendedStreamWriter writer, final ModelNode subModel, final boolean nested) throws XMLStreamException {\n for (final Property property : subModel.asPropertyList()) {\n if (property.getValue().isDefined()) {\n writeInterfaceCriteria(writer, property, nested);\n }\n }\n }", "public ClassNode annotatedWith(String name) {\n ClassNode anno = infoBase.node(name);\n this.annotations.add(anno);\n anno.annotated.add(this);\n return this;\n }", "private void logColumn(FastTrackColumn column)\n {\n if (m_log != null)\n {\n m_log.println(\"TABLE: \" + m_currentTable.getType());\n m_log.println(column.toString());\n m_log.flush();\n }\n }", "public static PackageType resolve(final MavenProject project) {\n final String packaging = project.getPackaging().toLowerCase(Locale.ROOT);\n if (DEFAULT_TYPES.containsKey(packaging)) {\n return DEFAULT_TYPES.get(packaging);\n }\n return new PackageType(packaging);\n }", "public static MatchInfo fromUri(final URI uri, final HttpMethod method) {\n int newPort = uri.getPort();\n if (newPort < 0) {\n try {\n newPort = uri.toURL().getDefaultPort();\n } catch (MalformedURLException | IllegalArgumentException e) {\n newPort = ANY_PORT;\n }\n }\n\n return new MatchInfo(uri.getScheme(), uri.getHost(), newPort, uri.getPath(), uri.getQuery(),\n uri.getFragment(), ANY_REALM, method);\n }", "public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) {\r\n\r\n\t\tif(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tthrow new IllegalArgumentException(\"SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL.\");\r\n\t\t}\r\n\r\n\t\t//Reverse sign of moneyness, if switching between payer and receiver convention.\r\n\t\tint reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1;\r\n\r\n\t\tList<Integer> maturities\t= new ArrayList<>();\r\n\t\tList<Integer> tenors\t\t= new ArrayList<>();\r\n\t\tList<Integer> moneynesss\t= new ArrayList<>();\r\n\t\tList<Double> values\t\t= new ArrayList<>();\r\n\r\n\t\tfor(DataKey key : entryMap.keySet()) {\r\n\t\t\tmaturities.add(key.maturity);\r\n\t\t\ttenors.add(key.tenor);\r\n\t\t\tmoneynesss.add(key.moneyness * reverse);\r\n\t\t\tvalues.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model));\r\n\t\t}\r\n\r\n\t\treturn new SwaptionDataLattice(referenceDate, targetConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule,\r\n\t\t\t\tmaturities.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\ttenors.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\tmoneynesss.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\tvalues.stream().mapToDouble(Double::doubleValue).toArray());\r\n\t}", "public static <T> T splitEachLine(File self, String regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure<T> closure) throws IOException {\n return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);\n }", "private boolean isRelated(Task task, List<Relation> list)\n {\n boolean result = false;\n for (Relation relation : list)\n {\n if (relation.getTargetTask().getUniqueID().intValue() == task.getUniqueID().intValue())\n {\n result = true;\n break;\n }\n }\n return result;\n }", "public static base_response add(nitro_service client, nslimitselector resource) throws Exception {\n\t\tnslimitselector addresource = new nslimitselector();\n\t\taddresource.selectorname = resource.selectorname;\n\t\taddresource.rule = resource.rule;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Set up the ThreadContext and delegate.
[ "@Override\n public void run() {\n try {\n threadContext.activate();\n // run the original thread\n runnable.run();\n } finally {\n threadContext.invalidate();\n threadContext.deactivate();\n }\n\n }" ]
[ "public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public void sendFaderStartCommand(Set<Integer> deviceNumbersToStart, Set<Integer> deviceNumbersToStop) throws IOException {\n ensureRunning();\n byte[] payload = new byte[FADER_START_PAYLOAD.length];\n System.arraycopy(FADER_START_PAYLOAD, 0, payload, 0, FADER_START_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n\n for (int i = 1; i <= 4; i++) {\n if (deviceNumbersToStart.contains(i)) {\n payload[i + 4] = 0;\n }\n if (deviceNumbersToStop.contains(i)) {\n payload[i + 4] = 1;\n }\n }\n\n assembleAndSendPacket(Util.PacketType.FADER_START_COMMAND, payload, getBroadcastAddress(), BeatFinder.BEAT_PORT);\n }", "protected List<String> extractWords() throws IOException\n {\n while( true ) {\n lineNumber++;\n String line = in.readLine();\n if( line == null ) {\n return null;\n }\n\n // skip comment lines\n if( hasComment ) {\n if( line.charAt(0) == comment )\n continue;\n }\n\n // extract the words, which are the variables encoded\n return parseWords(line);\n }\n }", "public static ComplexNumber Subtract(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real - scalar, z1.imaginary);\r\n }", "public static String objectToColumnString(Object object, String delimiter, String[] fieldNames)\r\n throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0; i < fieldNames.length; i++) {\r\n if (sb.length() > 0) {\r\n sb.append(delimiter);\r\n }\r\n try {\r\n Field field = object.getClass().getDeclaredField(fieldNames[i]);\r\n sb.append(field.get(object)) ;\r\n } catch (IllegalAccessException ex) {\r\n Method method = object.getClass().getDeclaredMethod(\"get\" + StringUtils.capitalize(fieldNames[i]));\r\n sb.append(method.invoke(object));\r\n }\r\n }\r\n return sb.toString();\r\n }", "private long getTotalTime(ProjectCalendarDateRanges exception, Date date, boolean after)\n {\n long currentTime = DateHelper.getCanonicalTime(date).getTime();\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd(), currentTime, after);\n }\n return (total);\n }", "public static cacheselector[] get(nitro_service service, String selectorname[]) throws Exception{\n\t\tif (selectorname !=null && selectorname.length>0) {\n\t\t\tcacheselector response[] = new cacheselector[selectorname.length];\n\t\t\tcacheselector obj[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++) {\n\t\t\t\tobj[i] = new cacheselector();\n\t\t\t\tobj[i].set_selectorname(selectorname[i]);\n\t\t\t\tresponse[i] = (cacheselector) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public static int timezoneOffset(H.Session session) {\n String s = null != session ? session.get(SESSION_KEY) : null;\n return S.notBlank(s) ? Integer.parseInt(s) : serverTimezoneOffset();\n }", "private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {\n\t\tFilter filter = null;\n\t\tif (null != layerFilter) {\n\t\t\tfilter = filterService.parseFilter(layerFilter);\n\t\t}\n\t\tif (null != featureIds) {\n\t\t\tFilter fidFilter = filterService.createFidFilter(featureIds);\n\t\t\tif (null == filter) {\n\t\t\t\tfilter = fidFilter;\n\t\t\t} else {\n\t\t\t\tfilter = filterService.createAndFilter(filter, fidFilter);\n\t\t\t}\n\t\t}\n\t\treturn filter;\n\t}" ]
Validates specialization if this bean specializes another bean.
[ "public void checkSpecialization() {\n if (isSpecializing()) {\n boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);\n String previousSpecializedBeanName = null;\n for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {\n String name = specializedBean.getName();\n if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {\n // there may be multiple beans specialized by this bean - make sure they all share the same name\n throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);\n }\n previousSpecializedBeanName = name;\n if (isNameDefined && name != null) {\n throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());\n }\n\n // When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are\n // added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among\n // these types are NOT types of the specializing bean (that's the way java works)\n boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>\n && specializedBean.getBeanClass().getTypeParameters().length > 0\n && !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));\n for (Type specializedType : specializedBean.getTypes()) {\n if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n boolean contains = getTypes().contains(specializedType);\n if (!contains) {\n for (Type specializingType : getTypes()) {\n // In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be\n // equal in the java sense. Therefore we have to use our own equality util.\n if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {\n contains = true;\n break;\n }\n }\n }\n if (!contains) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n }\n }\n }\n }" ]
[ "private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }", "protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) {\n String sourceLine = sourceCode.line(node.getLineNumber()-1);\n return createViolation(node.getLineNumber(), sourceLine, message);\n }", "public void clearTmpData() {\n\t\tfor (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {\n\t\t\t((LblTree) e.nextElement()).setTmpData(null);\n\t\t}\n\t}", "public Value get(Object key) {\n /* If the length is under and we are asking for the key, then just look for the key. Don't build the map. */\n if (map == null && items.length < 20) {\n for (Object item : items) {\n MapItemValue miv = (MapItemValue) item;\n if (key.equals(miv.name.toValue())) {\n return miv.value;\n }\n }\n return null;\n } else {\n if (map == null) buildIfNeededMap();\n return map.get(key);\n }\n }", "public static systemsession[] get(nitro_service service, Long sid[]) throws Exception{\n\t\tif (sid !=null && sid.length>0) {\n\t\t\tsystemsession response[] = new systemsession[sid.length];\n\t\t\tsystemsession obj[] = new systemsession[sid.length];\n\t\t\tfor (int i=0;i<sid.length;i++) {\n\t\t\t\tobj[i] = new systemsession();\n\t\t\t\tobj[i].set_sid(sid[i]);\n\t\t\t\tresponse[i] = (systemsession) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private void onConnectionClose(final Connection closed) {\n synchronized (this) {\n if(connection == closed) {\n connection = null;\n if(shutdown) {\n connectTask = DISCONNECTED;\n return;\n }\n final ConnectTask previous = connectTask;\n connectTask = previous.connectionClosed();\n }\n }\n }", "private void requestPlayerDBServerPort(DeviceAnnouncement announcement) {\n Socket socket = null;\n try {\n InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT);\n socket = new Socket();\n socket.connect(address, socketTimeout.get());\n InputStream is = socket.getInputStream();\n OutputStream os = socket.getOutputStream();\n socket.setSoTimeout(socketTimeout.get());\n os.write(DB_SERVER_QUERY_PACKET);\n byte[] response = readResponseWithExpectedSize(is, 2, \"database server port query packet\");\n if (response.length == 2) {\n setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2));\n }\n } catch (java.net.ConnectException ce) {\n logger.info(\"Player \" + announcement.getNumber() +\n \" doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata.\");\n } catch (Exception e) {\n logger.warn(\"Problem requesting database server port number\", e);\n } finally {\n if (socket != null) {\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing database server port request socket\", e);\n }\n }\n }\n }", "public static List<? extends Expression> getMethodArguments(ASTNode methodCall) {\r\n if (methodCall instanceof ConstructorCallExpression) {\r\n return extractExpressions(((ConstructorCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof MethodCallExpression) {\r\n return extractExpressions(((MethodCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof StaticMethodCallExpression) {\r\n return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments());\r\n } else if (respondsTo(methodCall, \"getArguments\")) {\r\n throw new RuntimeException(); // TODO: remove, should never happen\r\n }\r\n return new ArrayList<Expression>();\r\n }", "public static java.sql.Timestamp getTimestamp(Object value) {\n try {\n return toTimestamp(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }" ]
Use this API to add autoscaleprofile resources.
[ "public static base_responses add(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile addresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].apikey = resources[i].apikey;\n\t\t\t\taddresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "@Override\n protected void reset() {\n super.reset();\n mapClassesToNamedBoundProviders.clear();\n mapClassesToUnNamedBoundProviders.clear();\n hasTestModules = false;\n installBindingForScope();\n }", "protected boolean check(String value, String regex) {\n\t\tPattern pattern = Pattern.compile(regex);\n\t\treturn pattern.matcher(value).matches();\n\t}", "public StateVertex crawlIndex() {\n\t\tLOG.debug(\"Setting up vertex of the index page\");\n\n\t\tif (basicAuthUrl != null) {\n\t\t\tbrowser.goToUrl(basicAuthUrl);\n\t\t}\n\n\t\tbrowser.goToUrl(url);\n\n\t\t// Run url first load plugin to clear the application state\n\t\tplugins.runOnUrlFirstLoadPlugins(context);\n\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tStateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),\n\t\t\t\tstateComparator.getStrippedDom(browser), browser);\n\t\tPreconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,\n\t\t\t\t\"It seems some the index state is crawled more than once.\");\n\n\t\tLOG.debug(\"Parsing the index for candidate elements\");\n\t\tImmutableList<CandidateElement> extract = candidateExtractor.extract(index);\n\n\t\tplugins.runPreStateCrawlingPlugins(context, extract, index);\n\n\t\tcandidateActionCache.addActions(extract, index);\n\n\t\treturn index;\n\n\t}", "public IPv6AddressSection[] mergeToSequentialBlocks(IPv6AddressSection ...sections) throws SizeMismatchException {\n\t\tList<IPAddressSegmentSeries> blocks = getMergedSequentialBlocks(this, sections, true, createSeriesCreator(getAddressCreator(), getMaxSegmentValue()));\n\t\treturn blocks.toArray(new IPv6AddressSection[blocks.size()]);\n\t}", "private static JSONArray parseStencilSetExtensions(ArrayList<String> extensions) {\n if (extensions != null) {\n JSONArray extensionsArray = new JSONArray();\n\n for (String extension : extensions) {\n extensionsArray.put(extension.toString());\n }\n\n return extensionsArray;\n }\n\n return new JSONArray();\n }", "public HomekitRoot createBridge(\n HomekitAuthInfo authInfo,\n String label,\n String manufacturer,\n String model,\n String serialNumber)\n throws IOException {\n HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);\n root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));\n return root;\n }", "private AirMapViewBuilder getWebMapViewBuilder() {\n if (context != null) {\n try {\n ApplicationInfo ai = context.getPackageManager()\n .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);\n Bundle bundle = ai.metaData;\n String accessToken = bundle.getString(\"com.mapbox.ACCESS_TOKEN\");\n String mapId = bundle.getString(\"com.mapbox.MAP_ID\");\n\n if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(mapId)) {\n return new MapboxWebMapViewBuilder(accessToken, mapId);\n }\n } catch (PackageManager.NameNotFoundException e) {\n Log.e(TAG, \"Failed to load Mapbox access token and map id\", e);\n }\n }\n return new WebAirMapViewBuilder();\n }", "public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}", "public static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {\n StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);\n for (String kp : keyPrefix) {\n prefix.append('.').append(kp);\n }\n return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, LoggingExtension.class.getClassLoader(), true, false) {\n @Override\n public String getOperationParameterDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDescription(operationName, paramName, locale, bundle);\n }\n\n @Override\n public String getOperationParameterValueTypeDescription(final String operationName, final String paramName, final Locale locale,\n final ResourceBundle bundle, final String... suffixes) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterValueTypeDescription(operationName, paramName, locale, bundle, suffixes);\n }\n\n @Override\n public String getOperationParameterDeprecatedDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDeprecatedDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDeprecatedDescription(operationName, paramName, locale, bundle);\n }\n };\n }" ]
Notifies that a content item is inserted. @param position the position of the content item.
[ "public final void notifyContentItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (position < 0 || position >= newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for content items [0 - \" + (newContentItemCount - 1) + \"].\");\n }\n notifyItemInserted(position + newHeaderItemCount);\n }" ]
[ "public void collectVariables(EnvVars env, Run build, TaskListener listener) {\n EnvVars buildParameters = Utils.extractBuildParameters(build, listener);\n if (buildParameters != null) {\n env.putAll(buildParameters);\n }\n addAllWithFilter(envVars, env, filter.getPatternFilter());\n Map<String, String> sysEnv = new HashMap<>();\n Properties systemProperties = System.getProperties();\n Enumeration<?> enumeration = systemProperties.propertyNames();\n while (enumeration.hasMoreElements()) {\n String propertyKey = (String) enumeration.nextElement();\n sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));\n }\n addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());\n }", "public void setPadding(float padding, Layout.Axis axis) {\n OrientedLayout layout = null;\n switch(axis) {\n case X:\n layout = mShiftLayout;\n break;\n case Y:\n layout = mShiftLayout;\n break;\n case Z:\n layout = mStackLayout;\n break;\n }\n if (layout != null) {\n if (!equal(layout.getDividerPadding(axis), padding)) {\n layout.setDividerPadding(padding, axis);\n\n if (layout.getOrientationAxis() == axis) {\n requestLayout();\n }\n }\n }\n\n }", "public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {\n\t\tLOGGER.debug(\"Running OnBrowserCreatedPlugins...\");\n\t\tcounters.get(OnBrowserCreatedPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {\n\t\t\tif (plugin instanceof OnBrowserCreatedPlugin) {\n\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\ttry {\n\t\t\t\t\t((OnBrowserCreatedPlugin) plugin)\n\t\t\t\t\t\t\t.onBrowserCreated(newBrowser);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public static boolean xpathExists(Node document, String xpathExpression, Map<String, String> namespaceMapping) throws XPathException,\n MarshallingException\n {\n Boolean result = (Boolean) executeXPath(document, xpathExpression, namespaceMapping, XPathConstants.BOOLEAN);\n return result != null && result;\n }", "public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags)\n {\n boolean includeTagsEnabled = !includeTags.isEmpty();\n\n for (String tag : tags)\n {\n boolean isIncluded = includeTags.contains(tag);\n boolean isExcluded = excludeTags.contains(tag);\n\n if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded))\n {\n return true;\n }\n }\n\n return false;\n }", "private void addReverse(final File[] files) {\n for (int i = files.length - 1; i >= 0; --i) {\n stack.add(files[i]);\n }\n }", "public static double ratioSmallestOverLargest( double []sv ) {\n if( sv.length == 0 )\n return Double.NaN;\n\n double min = sv[0];\n double max = min;\n\n for (int i = 1; i < sv.length; i++) {\n double v = sv[i];\n if( v > max )\n max = v;\n else if( v < min )\n min = v;\n }\n\n return min/max;\n }", "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}", "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 }" ]
Set child components. @param children children
[ "public void setChildren(List<PrintComponent<?>> children) {\n\t\tthis.children = children;\n\t\t// needed for Json unmarshall !!!!\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.setParent(this);\n\t\t}\n\t}" ]
[ "public File getStylesheetPath()\n {\n String path = System.getProperty(STYLESHEET_KEY);\n return path == null ? null : new File(path);\n }", "protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\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 ConfigBuilder withHost(final String host) {\n if (host == null || \"\".equals(host)) {\n throw new IllegalArgumentException(\"host must not be null or empty: \" + host);\n }\n this.host = host;\n return this;\n }", "public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }", "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }", "private List<TimephasedCost> getTimephasedActualCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n double actualCost = getActualCost().doubleValue();\n\n if (actualCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(getCalendar(), actualCost, getActualStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(getCalendar(), actualCost, getActualFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently; have to 'fill up' each\n //day with the standard amount before going to the next one\n double numWorkingDays = getCalendar().getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n result.addAll(splitCostProrated(getCalendar(), actualCost, standardAmountPerDay, getActualStart()));\n }\n }\n\n return result;\n }", "public void 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 }" ]
Return the list of licenses attached to an artifact @param gavc String @param filters FiltersHolder @return List<DbLicense>
[ "public List<DbLicense> getArtifactLicenses(final String gavc, final FiltersHolder filters) {\n final DbArtifact artifact = getArtifact(gavc);\n final List<DbLicense> licenses = new ArrayList<>();\n\n for(final String name: artifact.getLicenses()){\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(name);\n\n // Here is a license to identify\n if(matchingLicenses.isEmpty()){\n final DbLicense notIdentifiedLicense = new DbLicense();\n notIdentifiedLicense.setName(name);\n licenses.add(notIdentifiedLicense);\n } else {\n matchingLicenses.stream()\n .filter(filters::shouldBeInReport)\n .forEach(licenses::add);\n }\n }\n\n return licenses;\n }" ]
[ "public static ModelNode getOperationAddress(final ModelNode op) {\n return op.hasDefined(OP_ADDR) ? op.get(OP_ADDR) : new ModelNode();\n }", "public ProjectCalendar getDefaultCalendar()\n {\n String calendarName = m_properties.getDefaultCalendarName();\n ProjectCalendar calendar = getCalendarByName(calendarName);\n if (calendar == null)\n {\n if (m_calendars.isEmpty())\n {\n calendar = addDefaultBaseCalendar();\n }\n else\n {\n calendar = m_calendars.get(0);\n }\n }\n return calendar;\n }", "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 <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(Object parent, FID id) throws SQLException {\n\t\t// this can happen if we have a foreign-auto-refresh scenario\n\t\tif (foreignFieldType == null) {\n\t\t\treturn null;\n\t\t}\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tif (!fieldConfig.isForeignCollectionEager()) {\n\t\t\t// we know this won't go recursive so no need for the counters\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\n\t\t// try not to create level counter objects unless we have to\n\t\tLevelCounters levelCounters = threadLevelCounters.get();\n\t\tif (levelCounters == null) {\n\t\t\tif (fieldConfig.getForeignCollectionMaxEagerLevel() == 0) {\n\t\t\t\t// then return a lazy collection instead\n\t\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(),\n\t\t\t\t\t\tfieldConfig.isForeignCollectionOrderAscending());\n\t\t\t}\n\t\t\tlevelCounters = new LevelCounters();\n\t\t\tthreadLevelCounters.set(levelCounters);\n\t\t}\n\n\t\tif (levelCounters.foreignCollectionLevel == 0) {\n\t\t\tlevelCounters.foreignCollectionLevelMax = fieldConfig.getForeignCollectionMaxEagerLevel();\n\t\t}\n\t\t// are we over our level limit?\n\t\tif (levelCounters.foreignCollectionLevel >= levelCounters.foreignCollectionLevelMax) {\n\t\t\t// then return a lazy collection instead\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\t\tlevelCounters.foreignCollectionLevel++;\n\t\ttry {\n\t\t\treturn new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t} finally {\n\t\t\tlevelCounters.foreignCollectionLevel--;\n\t\t}\n\t}", "public float getTexCoordU(int vertex, int coords) {\n if (!hasTexCoords(coords)) {\n throw new IllegalStateException(\n \"mesh has no texture coordinate set \" + coords);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for coords are done by java for us */\n \n return m_texcoords[coords].getFloat(\n vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);\n }", "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}", "private static EventEnumType convertEventType(org.talend.esb.sam.common.event.EventTypeEnum eventType) {\n if (eventType == null) {\n return null;\n }\n return EventEnumType.valueOf(eventType.name());\n }", "public static void main(final String[] args) {\n if (System.getProperty(\"db.name\") == null) {\n System.out.println(\"Not running in multi-instance mode: no DB to connect to\");\n System.exit(1);\n }\n while (true) {\n try {\n Class.forName(\"org.postgresql.Driver\");\n DriverManager.getConnection(\"jdbc:postgresql://\" + System.getProperty(\"db.host\") + \":5432/\" +\n System.getProperty(\"db.name\"),\n System.getProperty(\"db.username\"),\n System.getProperty(\"db.password\"));\n System.out.println(\"Opened database successfully. Running in multi-instance mode\");\n System.exit(0);\n return;\n } catch (Exception e) {\n System.out.println(\"Failed to connect to the DB: \" + e.toString());\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e1) {\n //ignored\n }\n }\n }\n }", "public static Calendar parseDividendDate(String date) {\n if (!Utils.isParseable(date)) {\n return null;\n }\n date = date.trim();\n SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US);\n format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n try {\n Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n parsedDate.setTime(format.parse(date));\n\n if (parsedDate.get(Calendar.YEAR) == 1970) {\n // Not really clear which year the dividend date is... making a reasonable guess.\n int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH);\n int year = today.get(Calendar.YEAR);\n if (monthDiff > 6) {\n year -= 1;\n } else if (monthDiff < -6) {\n year += 1;\n }\n parsedDate.set(Calendar.YEAR, year);\n }\n\n return parsedDate;\n } catch (ParseException ex) {\n log.warn(\"Failed to parse dividend date: \" + date);\n log.debug(\"Failed to parse dividend date: \" + date, ex);\n return null;\n }\n }" ]
Update the content of the tables.
[ "protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }" ]
[ "public String createSessionForResource(String configPath, String fileName) throws CmsUgcException {\n\n CmsUgcSession formSession = CmsUgcSessionFactory.getInstance().createSessionForFile(\n getCmsObject(),\n getRequest(),\n configPath,\n fileName);\n return \"\" + formSession.getId();\n }", "@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 }", "public static base_responses unlink(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey unlinkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunlinkresources[i] = new sslcertkey();\n\t\t\t\tunlinkresources[i].certkey = resources[i].certkey;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, unlinkresources,\"unlink\");\n\t\t}\n\t\treturn result;\n\t}", "public static String getImageIdFromTag(String imageTag, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(imageTag).exec().getId();\n } finally {\n closeQuietly(dockerClient);\n }\n }", "protected void splitCriteria()\r\n {\r\n Criteria whereCrit = getQuery().getCriteria();\r\n Criteria havingCrit = getQuery().getHavingCriteria();\r\n\r\n if (whereCrit == null || whereCrit.isEmpty())\r\n {\r\n getJoinTreeToCriteria().put(getRoot(), null);\r\n }\r\n else\r\n {\r\n // TODO: parameters list shold be modified when the form is reduced to DNF.\r\n getJoinTreeToCriteria().put(getRoot(), whereCrit);\r\n buildJoinTree(whereCrit);\r\n }\r\n\r\n if (havingCrit != null && !havingCrit.isEmpty())\r\n {\r\n buildJoinTree(havingCrit);\r\n }\r\n\r\n }", "@Nonnull\n\tprivate static Properties findDefaultProperties() {\n\t\tfinal InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);\n\t\tfinal Properties p = new Properties();\n\t\ttry {\n\t\t\tp.load(in);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(String.format(\"Can not load resource %s\", DEFAULT_PROPERTIES_PATH));\n\t\t}\n\t\treturn p;\n\t}", "public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }", "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}", "private void deliverDeviceUpdate(final DeviceUpdate update) {\n for (DeviceUpdateListener listener : getUpdateListeners()) {\n try {\n listener.received(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device update to listener\", t);\n }\n }\n }" ]
This method returns the string representation of an object. In most cases this will simply involve calling the normal toString method on the object, but a couple of exceptions are handled here. @param o the object to formatted @return formatted string representing input Object
[ "private String format(Object o)\n {\n String result;\n\n if (o == null)\n {\n result = \"\";\n }\n else\n {\n if (o instanceof Boolean == true)\n {\n result = LocaleData.getString(m_locale, (((Boolean) o).booleanValue() == true ? LocaleData.YES : LocaleData.NO));\n }\n else\n {\n if (o instanceof Float == true || o instanceof Double == true)\n {\n result = (m_formats.getDecimalFormat().format(((Number) o).doubleValue()));\n }\n else\n {\n if (o instanceof Day)\n {\n result = Integer.toString(((Day) o).getValue());\n }\n else\n {\n result = o.toString();\n }\n }\n }\n\n //\n // At this point there should be no line break characters in\n // the file. If we find any, replace them with spaces\n //\n result = stripLineBreaks(result, MPXConstants.EOL_PLACEHOLDER_STRING);\n\n //\n // Finally we check to ensure that there are no embedded\n // quotes or separator characters in the value. If there are, then\n // we quote the value and escape any existing quote characters.\n //\n if (result.indexOf('\"') != -1)\n {\n result = escapeQuotes(result);\n }\n else\n {\n if (result.indexOf(m_delimiter) != -1)\n {\n result = '\"' + result + '\"';\n }\n }\n }\n\n return (result);\n }" ]
[ "public static systemuser get(nitro_service service, String username) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tobj.set_username(username);\n\t\tsystemuser response = (systemuser) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {\n try {\n return c.getMethod(name, argTypes);\n } catch(NoSuchMethodException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }", "public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }", "public JsonObject getJsonObject() {\n\n JsonObject obj = new JsonObject();\n obj.add(\"field\", this.field);\n\n obj.add(\"value\", this.value);\n\n return obj;\n }", "public static boolean hasPermission(Permission permission) {\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n try {\n security.checkPermission(permission);\n } catch (java.security.AccessControlException e) {\n return false;\n }\n }\n return true;\n }", "private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }", "public PartialCollection<BoxItem.Info> getItemsRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"offset\", offset)\n .appendParam(\"limit\", limit);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), 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 String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> items = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n BoxItem.Info entryInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject());\n if (entryInfo != null) {\n items.add(entryInfo);\n }\n }\n return items;\n }", "public RedwoodConfiguration captureStdout(){\r\n tasks.add(new Runnable() { public void run() { Redwood.captureSystemStreams(true, false); } });\r\n return this;\r\n }" ]
Called by subclasses that initialize collections @param session the session @param id the collection identifier @param type collection type @throws HibernateException if an error occurs
[ "public final void loadCollection(\n\t\tfinal SharedSessionContractImplementor session,\n\t\tfinal Serializable id,\n\t\tfinal Type type) throws HibernateException {\n\n\t\tif ( log.isDebugEnabled() ) {\n\t\t\tlog.debug(\n\t\t\t\t\t\"loading collection: \" +\n\t\t\t\t\tMessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() )\n\t\t\t\t);\n\t\t}\n\n\t\tSerializable[] ids = new Serializable[]{id};\n\t\tQueryParameters qp = new QueryParameters( new Type[]{type}, ids, ids );\n\t\tdoQueryAndInitializeNonLazyCollections(\n\t\t\t\tsession,\n\t\t\t\tqp,\n\t\t\t\tOgmLoadingContext.EMPTY_CONTEXT,\n\t\t\t\ttrue\n\t\t\t);\n\n\t\tlog.debug( \"done loading collection\" );\n\n\t}" ]
[ "public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}", "private float[] calculatePointerPosition(float angle) {\n\t\tfloat x = (float) (mColorWheelRadius * Math.cos(angle));\n\t\tfloat y = (float) (mColorWheelRadius * Math.sin(angle));\n\n\t\treturn new float[] { x, y };\n\t}", "private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }", "@Override\n public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {\n return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);\n }", "@ArgumentsChecked\n\t@Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class })\n\tpublic static void isNumber(final boolean condition, @Nonnull final String value) {\n\t\tif (condition) {\n\t\t\tCheck.isNumber(value);\n\t\t}\n\t}", "private void initialize(Handler callbackHandler) {\n\t\tint processors = Runtime.getRuntime().availableProcessors();\n\t\tmDownloadDispatchers = new DownloadDispatcher[processors];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}", "public static base_responses update(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance updateresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusterinstance();\n\t\t\t\tupdateresources[i].clid = resources[i].clid;\n\t\t\t\tupdateresources[i].deadinterval = resources[i].deadinterval;\n\t\t\t\tupdateresources[i].hellointerval = resources[i].hellointerval;\n\t\t\t\tupdateresources[i].preemption = resources[i].preemption;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void fetchUninitializedAttributes() {\n for (String prefixedId : getPrefixedAttributeNames()) {\n BeanIdentifier id = getNamingScheme().deprefix(prefixedId);\n if (!beanStore.contains(id)) {\n ContextualInstance<?> instance = (ContextualInstance<?>) getAttribute(prefixedId);\n beanStore.put(id, instance);\n ContextLogger.LOG.addingDetachedContextualUnderId(instance, id);\n }\n }\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 }" ]
Unmarshal the XML content with auto-correction. @param file the file that contains the XML @return the XML read from the file @throws CmsXmlException thrown if the XML can't be read.
[ "private CmsXmlContent unmarshalXmlContent(CmsFile file) throws CmsXmlException {\n\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n content.setAutoCorrectionEnabled(true);\n content.correctXmlStructure(m_cms);\n\n return content;\n }" ]
[ "public Set<String> rangeByScoreReverse(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (scoreRange.hasLimit()) {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse(), scoreRange.offset(), scoreRange.count());\n } else {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse());\n }\n }\n });\n }", "public static int getMemberDimension() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getDimension();\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().getDimension();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getDimension();\r\n }\r\n }\r\n return 0;\r\n }", "public ImmutableList<AbstractElement> getFirstSetGrammarElements() {\n\t\tif (firstSetGrammarElements == null) {\n\t\t\tfirstSetGrammarElements = ImmutableList.copyOf(mutableFirstSetGrammarElements);\n\t\t}\n\t\treturn firstSetGrammarElements;\n\t}", "void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}", "@Modified(id = \"importerServices\")\n void modifiedImporterService(ServiceReference<ImporterService> serviceReference) {\n try {\n importersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ImporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n importersManager.removeLinks(serviceReference);\n return;\n }\n if (importersManager.matched(serviceReference)) {\n importersManager.updateLinks(serviceReference);\n } else {\n importersManager.removeLinks(serviceReference);\n }\n }", "private void processGeneratedProperties(\n\t\t\tSerializable id,\n\t\t\tObject entity,\n\t\t\tObject[] state,\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tGenerationTiming matchTiming) {\n\n\t\tTuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\t\tsaveSharedTuple( entity, tuple, session );\n\n\t\tif ( tuple == null || tuple.getSnapshot().isEmpty() ) {\n\t\t\tthrow log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );\n\t\t}\n\n\t\tint propertyIndex = -1;\n\t\tfor ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {\n\t\t\tpropertyIndex++;\n\t\t\tfinal ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();\n\t\t\tif ( isReadRequired( valueGeneration, matchTiming ) ) {\n\t\t\t\tObject hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( \"\", propertyIndex ), session, entity );\n\t\t\t\tstate[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );\n\t\t\t\tsetPropertyValue( entity, propertyIndex, state[propertyIndex] );\n\t\t\t}\n\t\t}\n\t}", "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 <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }", "public static PropertyOrder.Builder makeOrder(String property,\n PropertyOrder.Direction direction) {\n return PropertyOrder.newBuilder()\n .setProperty(makePropertyReference(property))\n .setDirection(direction);\n }" ]
Begin building a url for this host with the specified image.
[ "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 }" ]
[ "private JSONArray toJsonStringArray(Collection<? extends Object> collection) {\n\n if (null != collection) {\n JSONArray array = new JSONArray();\n for (Object o : collection) {\n array.put(\"\" + o);\n }\n return array;\n } else {\n return null;\n }\n }", "public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }", "public double[] getBasisVector( int which ) {\n if( which < 0 || which >= numComponents )\n throw new IllegalArgumentException(\"Invalid component\");\n\n DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);\n CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);\n\n return v.data;\n }", "public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {\n if (artifactsProps == null) {\n artifactsProps = ArrayListMultimap.create();\n }\n artifactsProps.put(\"build.name\", buildName);\n artifactsProps.put(\"build.number\", buildNumber);\n artifactsProps.put(\"build.timestamp\", timestamp);\n String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);\n\n Properties buildInfoItemsProps = new Properties();\n buildInfoItemsProps.setProperty(\"build.name\", buildName);\n buildInfoItemsProps.setProperty(\"build.number\", buildNumber);\n buildInfoItemsProps.setProperty(\"build.timestamp\", timestamp);\n\n ArtifactoryServer server = config.getArtifactoryServer();\n CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();\n ArtifactoryDependenciesClient dependenciesClient = null;\n ArtifactoryBuildInfoClient propertyChangeClient = null;\n\n try {\n dependenciesClient = server.createArtifactoryDependenciesClient(\n preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);\n\n CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);\n propertyChangeClient = server.createArtifactoryClient(\n preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy));\n\n Module buildInfoModule = new Module();\n buildInfoModule.setId(imageTag.substring(imageTag.indexOf(\"/\") + 1));\n\n // If manifest and imagePath not found, return.\n if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {\n return buildInfoModule;\n }\n\n listener.getLogger().println(\"Fetching details of published docker layers from Artifactory...\");\n boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);\n DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);\n\n listener.getLogger().println(\"Tagging published docker layers with build properties in Artifactory...\");\n setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,\n dependenciesClient, propertyChangeClient, server);\n setBuildInfoModuleProps(buildInfoModule);\n return buildInfoModule;\n } finally {\n if (dependenciesClient != null) {\n dependenciesClient.close();\n }\n if (propertyChangeClient != null) {\n propertyChangeClient.close();\n }\n }\n }", "public static void outputString(final HttpServletResponse response, final Object obj) {\n try {\n response.setContentType(\"text/javascript\");\n response.setCharacterEncoding(\"utf-8\");\n disableCache(response);\n response.getWriter().write(obj.toString());\n response.getWriter().flush();\n response.getWriter().close();\n } catch (IOException e) {\n }\n }", "public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\n }", "public void delete(boolean notifyUser, boolean force) {\n String queryString = new QueryStringBuilder()\n .appendParam(\"notify\", String.valueOf(notifyUser))\n .appendParam(\"force\", String.valueOf(force))\n .toString();\n\n URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }", "public static vpnglobal_authenticationsamlpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_authenticationsamlpolicy_binding obj = new vpnglobal_authenticationsamlpolicy_binding();\n\t\tvpnglobal_authenticationsamlpolicy_binding response[] = (vpnglobal_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Returns the Java executable command. @param javaHome the java home directory or {@code null} to use the default @return the java command to use
[ "private static String resolveJavaCommand(final Path javaHome) {\n final String exe;\n if (javaHome == null) {\n exe = \"java\";\n } else {\n exe = javaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n return exe;\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 }", "private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}", "public static void writeUnsignedShort(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 8));\n bytes[offset + 1] = (byte) (0xFF & value);\n }", "private static Data loadLeapSeconds() {\n Data bestData = null;\n URL url = null;\n try {\n // this is the new location of the file, working on Java 8, Java 9 class path and Java 9 module path\n Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(\"META-INF/\" + LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location does not work on Java 9 module path because the resource is encapsulated\n en = Thread.currentThread().getContextClassLoader().getResources(LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location is the canonical one, and class-based loading works on Java 9 module path\n url = SystemUtcRules.class.getResource(\"/\" + LEAP_SECONDS_TXT);\n if (url != null) {\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n } catch (Exception ex) {\n throw new RuntimeException(\"Unable to load time-zone rule data: \" + url, ex);\n }\n if (bestData == null) {\n // no data on classpath, but we allow manual registration of leap seconds\n // setup basic known data - MJD 1972-01-01 is 41317L, where offset was 10\n bestData = new Data(new long[] {41317L}, new int[] {10}, new long[] {tai(41317L, 10)});\n }\n return bestData;\n }", "private static void mergeBlocks(List< Block > blocks) {\r\n for (int i = 1; i < blocks.size(); i++) {\r\n Block b1 = blocks.get(i - 1);\r\n Block b2 = blocks.get(i);\r\n if ((b1.mode == b2.mode) &&\r\n (b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n b1.length += b2.length;\r\n blocks.remove(i);\r\n i--;\r\n }\r\n }\r\n }", "public static long decodeLong(byte[] ba, int offset) {\n return ((((long) ba[offset + 0] << 56) + ((long) (ba[offset + 1] & 255) << 48)\n + ((long) (ba[offset + 2] & 255) << 40) + ((long) (ba[offset + 3] & 255) << 32)\n + ((long) (ba[offset + 4] & 255) << 24) + ((ba[offset + 5] & 255) << 16)\n + ((ba[offset + 6] & 255) << 8) + ((ba[offset + 7] & 255) << 0)));\n }", "private boolean loadCustomErrorPage(\n CmsObject cms,\n HttpServletRequest req,\n HttpServletResponse res,\n String rootPath) {\n\n try {\n\n // get the site of the error page resource\n CmsSite errorSite = OpenCms.getSiteManager().getSiteForRootPath(rootPath);\n cms.getRequestContext().setSiteRoot(errorSite.getSiteRoot());\n String relPath = cms.getRequestContext().removeSiteRoot(rootPath);\n if (cms.existsResource(relPath)) {\n cms.getRequestContext().setUri(relPath);\n OpenCms.getResourceManager().loadResource(cms, cms.readResource(relPath), req, res);\n return true;\n } else {\n return false;\n }\n } catch (Throwable e) {\n // something went wrong log the exception and return false\n LOG.error(e.getMessage(), e);\n return false;\n }\n }", "public Jar addClass(Class<?> clazz) throws IOException {\n final String resource = clazz.getName().replace('.', '/') + \".class\";\n return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource));\n }", "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 }" ]
Adds the scroll position CSS extension to the given component @param componentContainer the component to extend @param scrollBarrier the scroll barrier @param barrierMargin the margin @param styleName the style name to set beyond the scroll barrier
[ "@SuppressWarnings(\"unused\")\n public static void addTo(\n AbstractSingleComponentContainer componentContainer,\n int scrollBarrier,\n int barrierMargin,\n String styleName) {\n\n new CmsScrollPositionCss(componentContainer, scrollBarrier, barrierMargin, styleName);\n }" ]
[ "public static Constructor<?> getConstructor(final Class<?> clazz,\n final Class<?>... argumentTypes) throws NoSuchMethodException {\n try {\n return AccessController\n .doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {\n public Constructor<?> run()\n throws NoSuchMethodException {\n return clazz.getConstructor(argumentTypes);\n }\n });\n }\n // Unwrap\n catch (final PrivilegedActionException pae) {\n final Throwable t = pae.getCause();\n // Rethrow\n if (t instanceof NoSuchMethodException) {\n throw (NoSuchMethodException) t;\n } else {\n // No other checked Exception thrown by Class.getConstructor\n try {\n throw (RuntimeException) t;\n }\n // Just in case we've really messed up\n catch (final ClassCastException cce) {\n throw new RuntimeException(\n \"Obtained unchecked Exception; this code should never be reached\",\n t);\n }\n }\n }\n }", "public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n checkSchemeAndPort(scheme, port);\r\n StringBuilder buffer = new StringBuilder();\r\n if (!host.startsWith(scheme + \"://\")) {\r\n buffer.append(scheme).append(\"://\");\r\n }\r\n buffer.append(host);\r\n if (port > 0) {\r\n buffer.append(':');\r\n buffer.append(port);\r\n }\r\n if (path == null) {\r\n path = \"/\";\r\n }\r\n buffer.append(path);\r\n\r\n if (!parameters.isEmpty()) {\r\n buffer.append('?');\r\n }\r\n int size = parameters.size();\r\n for (Map.Entry<String, String> entry : parameters.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append('=');\r\n Object value = entry.getValue();\r\n if (value != null) {\r\n String string = value.toString();\r\n try {\r\n string = URLEncoder.encode(string, UTF8);\r\n } catch (UnsupportedEncodingException e) {\r\n // Should never happen, but just in case\r\n }\r\n buffer.append(string);\r\n }\r\n if (--size != 0) {\r\n buffer.append('&');\r\n }\r\n }\r\n\r\n /*\r\n * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&\r\n * !ignoreMethod(getMethod(parameters))) { buffer.append(\"&api_sig=\"); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }\r\n */\r\n\r\n return new URL(buffer.toString());\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 @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final MongoNamespace namespace,\n final BsonValue documentId\n ) {\n this.instanceLock.readLock().lock();\n final NamespaceChangeStreamListener streamer;\n try {\n streamer = nsStreamers.get(namespace);\n } finally {\n this.instanceLock.readLock().unlock();\n }\n\n if (streamer == null) {\n return null;\n }\n\n return streamer.getUnprocessedEventForDocumentId(documentId);\n }", "public static base_response update(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite updateresource = new gslbsite();\n\t\tupdateresource.sitename = resource.sitename;\n\t\tupdateresource.metricexchange = resource.metricexchange;\n\t\tupdateresource.nwmetricexchange = resource.nwmetricexchange;\n\t\tupdateresource.sessionexchange = resource.sessionexchange;\n\t\tupdateresource.triggermonitor = resource.triggermonitor;\n\t\treturn updateresource.update_resource(client);\n\t}", "@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }", "protected boolean isSavedConnection(DatabaseConnection connection) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tif (currentSaved == null) {\n\t\t\treturn false;\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\t// ignore the release when we have a saved connection\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "private static void checkPreconditions(final String dateFormat, final Locale locale) {\n\t\tif( dateFormat == null ) {\n\t\t\tthrow new NullPointerException(\"dateFormat should not be null\");\n\t\t} else if( locale == null ) {\n\t\t\tthrow new NullPointerException(\"locale should not be null\");\n\t\t}\n\t}", "private List<MapRow> sort(List<MapRow> rows, final String attribute)\n {\n Collections.sort(rows, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n String value1 = o1.getString(attribute);\n String value2 = o2.getString(attribute);\n return value1.compareTo(value2);\n }\n });\n return rows;\n }" ]
Returns an entry with the given proposal and the prefix from the context, or null if the proposal is not valid.
[ "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }" ]
[ "protected final Event processEvent() throws IOException {\n while (true) {\n String line;\n try {\n line = readLine();\n } catch (final EOFException ex) {\n if (doneOnce) {\n throw ex;\n }\n doneOnce = true;\n line = \"\";\n }\n\n // If the line is empty (a blank line), Dispatch the event, as defined below.\n if (line.isEmpty()) {\n // If the data buffer is an empty string, set the data buffer and the event name buffer to\n // the empty string and abort these steps.\n if (dataBuffer.length() == 0) {\n eventName = \"\";\n continue;\n }\n\n // If the event name buffer is not the empty string but is also not a valid NCName,\n // set the data buffer and the event name buffer to the empty string and abort these steps.\n // NOT IMPLEMENTED\n\n final Event.Builder eventBuilder = new Event.Builder();\n eventBuilder.withEventName(eventName.isEmpty() ? Event.MESSAGE_EVENT : eventName);\n eventBuilder.withData(dataBuffer.toString());\n\n // Set the data buffer and the event name buffer to the empty string.\n dataBuffer = new StringBuilder();\n eventName = \"\";\n\n return eventBuilder.build();\n // If the line starts with a U+003A COLON character (':')\n } else if (line.startsWith(\":\")) {\n // ignore the line\n // If the line contains a U+003A COLON character (':') character\n } else if (line.contains(\":\")) {\n // Collect the characters on the line before the first U+003A COLON character (':'),\n // and let field be that string.\n final int colonIdx = line.indexOf(\":\");\n final String field = line.substring(0, colonIdx);\n\n // Collect the characters on the line after the first U+003A COLON character (':'),\n // and let value be that string.\n // If value starts with a single U+0020 SPACE character, remove it from value.\n String value = line.substring(colonIdx + 1);\n value = value.startsWith(\" \") ? value.substring(1) : value;\n\n processField(field, value);\n // Otherwise, the string is not empty but does not contain a U+003A COLON character (':')\n // character\n } else {\n processField(line, \"\");\n }\n }\n }", "public CSTNode get( int index ) \n {\n CSTNode element = null;\n\n if( index < size() ) \n {\n element = (CSTNode)elements.get( index );\n }\n\n return element;\n }", "public float getMetallic()\n {\n Property p = getProperty(PropertyKey.METALLIC.m_key);\n\n if (null == p || null == p.getData())\n {\n throw new IllegalArgumentException(\"Metallic property not found\");\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.FloatBuffer fbuf = ((java.nio.ByteBuffer) rawValue).asFloatBuffer();\n return fbuf.get();\n }\n else\n {\n return (Float) rawValue;\n }\n }", "private ArrayList handleDependentReferences(Identity oid, Object userObject,\r\n Object[] origFields, Object[] newFields, Object[] newRefs)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(userObject.getClass());\r\n FieldDescriptor[] fieldDescs = mif.getFieldDescriptions();\r\n Collection refDescs = mif.getObjectReferenceDescriptors();\r\n int count = 1 + fieldDescs.length;\r\n ArrayList newObjects = new ArrayList();\r\n int countRefs = 0;\r\n\r\n for (Iterator it = refDescs.iterator(); it.hasNext(); count++, countRefs++)\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) it.next();\r\n Identity origOid = (origFields == null ? null : (Identity) origFields[count]);\r\n Identity newOid = (Identity) newFields[count];\r\n\r\n if (rds.getOtmDependent())\r\n {\r\n if ((origOid == null) && (newOid != null))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n Object relObj = newRefs[countRefs];\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, oid, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n else if ((origOid != null) &&\r\n ((newOid == null) || !newOid.equals(origOid)))\r\n {\r\n markDelete(origOid, oid, false);\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }", "public static boolean classNodeImplementsType(ClassNode node, Class target) {\r\n ClassNode targetNode = ClassHelper.make(target);\r\n if (node.implementsInterface(targetNode)) {\r\n return true;\r\n }\r\n if (node.isDerivedFrom(targetNode)) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getInterfaces() != null) {\r\n for (ClassNode declaredInterface : node.getInterfaces()) {\r\n if (classNodeImplementsType(declaredInterface, target)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "private void emit(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n float[] allParticlePositions = new float[particlePositions.length + particleBoundingVolume.length];\n System.arraycopy(particlePositions, 0, allParticlePositions, 0, particlePositions.length);\n System.arraycopy(particleBoundingVolume, 0, allParticlePositions,\n particlePositions.length, particleBoundingVolume.length);\n\n float[] allSpawnTimes = new float[particleTimeStamps.length + BVSpawnTimes.length];\n System.arraycopy(particleTimeStamps, 0, allSpawnTimes, 0, particleTimeStamps.length);\n System.arraycopy(BVSpawnTimes, 0, allSpawnTimes, particleTimeStamps.length, BVSpawnTimes.length);\n\n float[] allParticleVelocities = new float[particleVelocities.length + BVVelocities.length];\n System.arraycopy(particleVelocities, 0, allParticleVelocities, 0, particleVelocities.length);\n System.arraycopy(BVVelocities, 0, allParticleVelocities, particleVelocities.length, BVVelocities.length);\n\n\n Particles particleMesh = new Particles(mGVRContext, mMaxAge,\n mParticleSize, mEnvironmentAcceleration, mParticleSizeRate, mFadeWithAge,\n mParticleTexture, mColor, mNoiseFactor);\n\n\n GVRSceneObject particleObject = particleMesh.makeParticleMesh(allParticlePositions,\n allParticleVelocities, allSpawnTimes);\n\n this.addChildObject(particleObject);\n meshInfo.add(Pair.create(particleObject, currTime));\n }", "@Inject(\"struts.json.action.fileProtocols\")\n\tpublic void setFileProtocols(String fileProtocols) {\n\t\tif (StringUtils.isNotBlank(fileProtocols)) {\n\t\t\tthis.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols);\n\t\t}\n\t}", "@PreDestroy\n public final void shutdown() {\n this.timer.shutdownNow();\n this.executor.shutdownNow();\n if (this.cleanUpTimer != null) {\n this.cleanUpTimer.shutdownNow();\n }\n }", "public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}" ]
Add a user by ID to the list of people to notify when the retention period is ending. @param userID The ID of the user to add to the list.
[ "public void addCustomNotificationRecipient(String userID) {\n BoxUser user = new BoxUser(null, userID);\n this.customNotificationRecipients.add(user.new Info());\n\n }" ]
[ "public IPv6Address toLinkLocalIPv6() {\r\n\t\tIPv6AddressNetwork network = getIPv6Network();\r\n\t\tIPv6AddressSection linkLocalPrefix = network.getLinkLocalPrefix();\r\n\t\tIPv6AddressCreator creator = network.getAddressCreator();\r\n\t\treturn creator.createAddress(linkLocalPrefix.append(toEUI64IPv6()));\r\n\t}", "public void setEnterpriseDate(int index, Date value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_DATE, index), value);\n }", "public base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\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 }", "@SuppressWarnings(\"WeakerAccess\")\n public ByteBuffer getRawData() {\n if (rawData != null) {\n rawData.rewind();\n return rawData.slice();\n }\n return null;\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 }", "@SuppressWarnings(\"unchecked\")\n private static Object resolveConflictWithResolver(\n final ConflictHandler conflictResolver,\n final BsonValue documentId,\n final ChangeEvent localEvent,\n final ChangeEvent remoteEvent\n ) {\n return conflictResolver.resolveConflict(\n documentId,\n localEvent,\n remoteEvent);\n }", "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 }", "private void setBandFinalHeight(JRDesignBand band, int currHeigth, boolean fitToContent) {\n if (band != null) {\n int finalHeight = LayoutUtils.findVerticalOffset(band);\n //noinspection StatementWithEmptyBody\n if (finalHeight < currHeigth && !fitToContent) {\n //nothing\n } else {\n band.setHeight(finalHeight);\n }\n }\n\n }" ]
Apply a filter to the list of all resources, and show the results. @param project project file @param filter filter
[ "private static void processResourceFilter(ProjectFile project, Filter filter)\n {\n for (Resource resource : project.getResources())\n {\n if (filter.evaluate(resource, null))\n {\n System.out.println(resource.getID() + \",\" + resource.getUniqueID() + \",\" + resource.getName());\n }\n }\n }" ]
[ "public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "protected void update(float scale) {\n // Updates only when the plane is in the scene\n GVRSceneObject owner = getOwnerObject();\n\n if ((owner != null) && isEnabled() && owner.isEnabled())\n {\n convertFromARtoVRSpace(scale);\n }\n }", "public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {\n\t\ttry {\n\t\t\ttemplate.saveState();\n\t\t\t// opacity\n\t\t\tPdfGState state = new PdfGState();\n\t\t\tstate.setFillOpacity(opacity);\n\t\t\tstate.setBlendMode(PdfGState.BM_NORMAL);\n\t\t\ttemplate.setGState(state);\n\t\t\t// clipping code\n\t\t\tif (clipRect != null) {\n\t\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),\n\t\t\t\t\t\tclipRect.getHeight());\n\t\t\t\ttemplate.clip();\n\t\t\t\ttemplate.newPath();\n\t\t\t}\n\t\t\ttemplate.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(), origY\n\t\t\t\t\t+ rect.getBottom());\n\t\t} catch (DocumentException e) {\n\t\t\tlog.warn(\"could not draw image\", e);\n\t\t} finally {\n\t\t\ttemplate.restoreState();\n\t\t}\n\t}", "public static InetAddress getLocalHost() throws UnknownHostException {\n InetAddress addr;\n try {\n addr = InetAddress.getLocalHost();\n } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404\n addr = InetAddress.getByName(null);\n }\n return addr;\n }", "public List<I_CmsEditableGroupRow> getRows() {\n\n List<I_CmsEditableGroupRow> result = Lists.newArrayList();\n for (Component component : m_container) {\n if (component instanceof I_CmsEditableGroupRow) {\n result.add((I_CmsEditableGroupRow)component);\n }\n }\n return result;\n }", "private void deleteUnusedCaseSteps( ReportModel model ) {\n\n for( ScenarioModel scenarioModel : model.getScenarios() ) {\n if( scenarioModel.isCasesAsTable() && !hasAttachment( scenarioModel ) ) {\n List<ScenarioCaseModel> cases = scenarioModel.getScenarioCases();\n for( int i = 1; i < cases.size(); i++ ) {\n ScenarioCaseModel caseModel = cases.get( i );\n caseModel.setSteps( Collections.<StepModel>emptyList() );\n }\n }\n }\n }", "public static int[] randomPermutation(int size) {\n Random r = new Random();\n int[] result = new int[size];\n\n for (int j = 0; j < size; j++) {\n result[j] = j;\n }\n \n for (int j = size - 1; j > 0; j--) {\n int k = r.nextInt(j);\n int temp = result[j];\n result[j] = result[k];\n result[k] = temp;\n }\n\n return result;\n }", "private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}", "public NamespacesList<Pair> getPairs(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Pair> nsList = new NamespacesList<Pair>();\r\n parameters.put(\"method\", METHOD_GET_PAIRS);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"pair\");\r\n nsList.setPage(nsElement.getAttribute(\"page\"));\r\n nsList.setPages(nsElement.getAttribute(\"pages\"));\r\n nsList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parsePair(element));\r\n }\r\n return nsList;\r\n }" ]
Record a prepare operation. @param preparedOperation the prepared operation
[ "void recordPreparedOperation(final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> preparedOperation) {\n recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(preparedOperation));\n }" ]
[ "protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }", "@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n blockB.reshape(B.numRows,B.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n // since overwrite B is true X does not need to be passed in\n alg.solve(blockB,null);\n\n MatrixOps_DDRB.convert(blockB,X);\n }", "public void removeLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference serviceReference : declaration.getStatus().getServiceReferencesBounded()) {\n // FIXME : In case of multiples Linker, we will remove the link of all the ServiceReference\n // FIXME : event the ones which dun know nothing about\n linkerManagement.unlink(declaration, serviceReference);\n }\n }", "private void readTableData(List<SynchroTable> tables, InputStream is) throws IOException\n {\n for (SynchroTable table : tables)\n {\n if (REQUIRED_TABLES.contains(table.getName()))\n {\n readTable(is, table);\n }\n }\n }", "private boolean isDepOfIdlArtifact(Artifact artifact, Map<String, Artifact> depsMap) {\n List<String> depTrail = artifact.getDependencyTrail();\n // depTrail can be null sometimes, which seems like a maven bug\n if (depTrail != null) {\n for (String name : depTrail) {\n Artifact dep = depsMap.get(name);\n if (dep != null && isIdlCalssifier(dep, classifier)) {\n return true;\n }\n }\n }\n return false;\n }", "public static String expandLine(CharSequence self, int tabStop) {\n String s = self.toString();\n int index;\n while ((index = s.indexOf('\\t')) != -1) {\n StringBuilder builder = new StringBuilder(s);\n int count = tabStop - index % tabStop;\n builder.deleteCharAt(index);\n for (int i = 0; i < count; i++) builder.insert(index, \" \");\n s = builder.toString();\n }\n return s;\n }", "@PrefMetadata(type = CmsElementViewPreference.class)\n public String getElementView() {\n\n return m_settings.getAdditionalPreference(CmsElementViewPreference.PREFERENCE_NAME, false);\n }", "public ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }", "public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }" ]
Look up the playback state that has reached furthest in the track, but give playing players priority over stopped players. This is used to choose the scroll center when auto-scrolling is active. @return the playback state, if any, with the highest playing {@link PlaybackState#position} value
[ "public PlaybackState getFurthestPlaybackState() {\n PlaybackState result = null;\n for (PlaybackState state : playbackStateMap.values()) {\n if (result == null || (!result.playing && state.playing) ||\n (result.position < state.position) && (state.playing || !result.playing)) {\n result = state;\n }\n }\n return result;\n }" ]
[ "public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int codePointCount = 0;\n for (int i = 0; i < srcLen; ) {\n final int cp = codePointAt(src, srcOff + i, srcOff + srcLen);\n final int charCount = Character.charCount(cp);\n dest[destOff + codePointCount++] = cp;\n i += charCount;\n }\n return codePointCount;\n }", "private void readNormalDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay weekDay)\n {\n int dayNumber = weekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n calendar.setWorkingDay(day, BooleanHelper.getBoolean(weekDay.isDayWorking()));\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = weekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }", "public Bundler put(String key, Serializable value) {\n delegate.putSerializable(key, value);\n return this;\n }", "protected float transformLength(float w)\n {\n Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();\n Matrix m = new Matrix();\n m.setValue(2, 0, w);\n return m.multiply(ctm).getTranslateX();\n }", "public ItemRequest<Project> removeFollowers(String project) {\n \n String path = String.format(\"/projects/%s/removeFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\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 SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {\r\n\r\n\t\tSwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);\r\n\t\tcombined.entryMap.putAll(entryMap);\r\n\r\n\t\tif(quotingConvention == other.quotingConvention && displacement == other.displacement) {\r\n\t\t\tcombined.entryMap.putAll(other.entryMap);\r\n\t\t} else {\r\n\t\t\tSwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);\r\n\t\t\tcombined.entryMap.putAll(converted.entryMap);\r\n\t\t}\r\n\r\n\t\treturn combined;\r\n\t}", "@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 String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }" ]
Triggers a replication request.
[ "public ReplicationResult trigger() {\n assertNotEmpty(source, \"Source\");\n assertNotEmpty(target, \"Target\");\n InputStream response = null;\n try {\n JsonObject json = createJson();\n if (log.isLoggable(Level.FINE)) {\n log.fine(json.toString());\n }\n\n final URI uri = new DatabaseURIHelper(client.getBaseUri()).path(\"_replicate\").build();\n response = client.post(uri, json.toString());\n final InputStreamReader reader = new InputStreamReader(response, \"UTF-8\");\n return client.getGson().fromJson(reader, ReplicationResult.class);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n } finally {\n close(response);\n }\n }" ]
[ "public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}", "@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }", "public static Type getArrayComponentType(Type type) {\n if (type instanceof GenericArrayType) {\n return GenericArrayType.class.cast(type).getGenericComponentType();\n }\n if (type instanceof Class<?>) {\n Class<?> clazz = (Class<?>) type;\n if (clazz.isArray()) {\n return clazz.getComponentType();\n }\n }\n throw new IllegalArgumentException(\"Not an array type \" + type);\n }", "private void buildMultiJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)\r\n {\r\n DescriptorRepository repository = cld.getRepository();\r\n Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, false);\r\n\r\n for (int i = 0; i < multiJoinedClasses.length; i++)\r\n {\r\n ClassDescriptor subCld = repository.getDescriptorFor(multiJoinedClasses[i]);\r\n SuperReferenceDescriptor srd = subCld.getSuperReference();\r\n if (srd != null)\r\n {\r\n FieldDescriptor[] leftFields = subCld.getPkFields();\r\n FieldDescriptor[] rightFields = srd.getForeignKeyFieldDescriptors(subCld);\r\n TableAlias base_alias = getTableAliasForPath(name, null, null);\r\n\r\n String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;\r\n TableAlias right = new TableAlias(subCld, aliasName, false, null);\r\n\r\n Join join1to1 = new Join(left, leftFields, right, rightFields, useOuterJoin, \"subClass\");\r\n base_alias.addJoin(join1to1);\r\n\r\n buildMultiJoinTree(right, subCld, name, useOuterJoin);\r\n }\r\n }\r\n }", "private static void listResources(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Resource: \" + resource.getName() + \" (Unique ID=\" + resource.getUniqueID() + \") Start=\" + resource.getStart() + \" Finish=\" + resource.getFinish());\n }\n System.out.println();\n }", "public int[] getTenors(int moneynessBP, int maturityInMonths) {\r\n\r\n\t\ttry {\r\n\t\t\tList<Integer> ret = new ArrayList<>();\r\n\t\t\tfor(int tenor : getGridNodesPerMoneyness().get(moneynessBP)[1]) {\r\n\t\t\t\tif(containsEntryFor(maturityInMonths, tenor, moneynessBP)) {\r\n\t\t\t\t\tret.add(tenor);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret.stream().mapToInt(Integer::intValue).toArray();\r\n\t\t} catch (NullPointerException e) {\r\n\t\t\treturn new int[0];\r\n\t\t}\r\n\t}", "public static vlan get(nitro_service service, Long id) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tobj.set_id(id);\n\t\tvlan response = (vlan) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void setResourceInformation() {\n\n String sitePath = m_cms.getSitePath(m_resource);\n int pathEnd = sitePath.lastIndexOf('/') + 1;\n String baseName = sitePath.substring(pathEnd);\n m_sitepath = sitePath.substring(0, pathEnd);\n switch (CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())) {\n case PROPERTY:\n String localeSuffix = CmsStringUtil.getLocaleSuffixForName(baseName);\n if ((null != localeSuffix) && !localeSuffix.isEmpty()) {\n baseName = baseName.substring(\n 0,\n baseName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));\n m_locale = CmsLocaleManager.getLocale(localeSuffix);\n }\n if ((null == m_locale) || !m_locales.contains(m_locale)) {\n m_switchedLocaleOnOpening = true;\n m_locale = m_locales.iterator().next();\n }\n break;\n case XML:\n m_locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(\n m_cms,\n m_resource,\n m_xmlBundle);\n break;\n case DESCRIPTOR:\n m_basename = baseName.substring(\n 0,\n baseName.length() - CmsMessageBundleEditorTypes.Descriptor.POSTFIX.length());\n m_locale = new Locale(\"en\");\n break;\n default:\n throw new IllegalArgumentException(\n Messages.get().container(\n Messages.ERR_UNSUPPORTED_BUNDLE_TYPE_1,\n CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())).toString());\n }\n m_basename = baseName;\n\n }", "public List<String> asList() {\n final List<String> result = new ArrayList<>();\n for (Collection<Argument> args : map.values()) {\n for (Argument arg : args) {\n result.add(arg.asCommandLineArgument());\n }\n }\n return result;\n }" ]
Sets the left padding character for all cells in the table. @param paddingLeftChar new padding character, ignored if null @return this to allow chaining
[ "public AsciiTable setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public static int getBytesToken(ParsingContext ctx) {\n String input = ctx.getInput().substring(ctx.getLocation());\n int tokenOffset = 0;\n int i = 0;\n char[] inputChars = input.toCharArray();\n for (; i < input.length(); i += 1) {\n char c = inputChars[i];\n if (c == ' ') {\n continue;\n }\n if (c != BYTES_TOKEN_CHARS[tokenOffset]) {\n return -1;\n } else {\n tokenOffset += 1;\n if (tokenOffset == BYTES_TOKEN_CHARS.length) {\n // Found the token.\n return i;\n }\n }\n }\n return -1;\n }", "public final void notifyFooterItemChanged(int position) {\n if (position < 0 || position >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount + contentItemCount);\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 }", "public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\tif (key == null)\n\t\t\tthrow new NullPointerException(\"key\");\n\t\tCollections.sort(list, new KeyComparator<T, C>(key));\n\t\treturn list;\n\t}", "protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }", "protected static final float[] getSpreadInRange(float member, int count, int max, int offset) {\n // to find the spread, we first find the min that is a\n // multiple of max/count away from the member\n\n int interval = max / count;\n float min = (member + offset) % interval;\n\n if (min == 0 && member == max) {\n min += interval;\n }\n\n float[] range = new float[count];\n for (int i = 0; i < count; i++) {\n range[i] = min + interval * i + offset;\n }\n\n return range;\n }", "public <CT> CT callBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException {\n\t\tif (connectionSource.isSingleConnection(tableInfo.getTableName())) {\n\t\t\tsynchronized (this) {\n\t\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t\t}\n\t\t} else {\n\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t}\n\t}", "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 }", "public static double blackModelDgitialCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;\n\t}" ]
Get the value of the specified column. @param columnName the name of the column @return the corresponding value of the column, {@code null} if the column does not exist in the row key
[ "public Object getColumnValue(String columnName) {\n\t\tfor ( int j = 0; j < columnNames.length; j++ ) {\n\t\t\tif ( columnNames[j].equals( columnName ) ) {\n\t\t\t\treturn columnValues[j];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public static base_response enable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm enableresource = new snmpalarm();\n\t\tenableresource.trapname = trapname;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public void putAll(Map<KEY, VALUE> mapDataToPut) {\n int targetSize = maxSize - mapDataToPut.size();\n if (maxSize > 0 && values.size() > targetSize) {\n evictToTargetSize(targetSize);\n }\n Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();\n for (Entry<KEY, VALUE> entry : entries) {\n put(entry.getKey(), entry.getValue());\n }\n }", "private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {\n final String DUMMY_PROP=\"dummywrite\";\n instance.put(DUMMY_PROP,\"test\");\n instance.flush();\n instance.remove(DUMMY_PROP);\n instance.flush();\n }", "public CollectionDescriptorDef getCollection(String name)\r\n {\r\n CollectionDescriptorDef collDef = null;\r\n\r\n for (Iterator it = _collections.iterator(); it.hasNext(); )\r\n {\r\n collDef = (CollectionDescriptorDef)it.next();\r\n if (collDef.getName().equals(name))\r\n {\r\n return collDef;\r\n }\r\n }\r\n return null;\r\n }", "public static snmpalarm[] get(nitro_service service) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tsnmpalarm[] response = (snmpalarm[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public Class getRealClass(Object objectOrProxy)\r\n {\r\n IndirectionHandler handler;\r\n\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n handler = getIndirectionHandler(objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n handler = VirtualProxy.getIndirectionHandler((VirtualProxy) objectOrProxy);\r\n /*\r\n arminw:\r\n think we should return the real class\r\n */\r\n // return handler.getIdentity().getObjectsTopLevelClass();\r\n return handler.getIdentity().getObjectsRealClass();\r\n }\r\n else\r\n {\r\n return objectOrProxy.getClass();\r\n }\r\n }", "public int bindShader(GVRContext context, IRenderable rdata, GVRScene scene, boolean isMultiview)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n GVRMaterial mtl = rdata.getMaterial();\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, mtl);\n }\n if (nativeShader > 0)\n {\n rdata.setShader(nativeShader, isMultiview);\n }\n return nativeShader;\n }\n }", "public static void count() {\n long duration = SystemClock.uptimeMillis() - startTime;\n float avgFPS = sumFrames / (duration / 1000f);\n\n Log.v(\"FPSCounter\",\n \"total frames = %d, total elapsed time = %d ms, average fps = %f\",\n sumFrames, duration, avgFPS);\n }", "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 }" ]
Add statistics about a created map. @param mapContext the @param mapValues the
[ "public synchronized void addMapStats(\n final MapfishMapContext mapContext, final MapAttribute.MapAttributeValues mapValues) {\n this.mapStats.add(new MapStats(mapContext, mapValues));\n }" ]
[ "StringBuilder assembleConfig(boolean meta) {\n StringBuilder builder = new StringBuilder();\n\n if (meta) {\n builder.append(PREFIX_META);\n }\n\n if (isTrim) {\n builder.append(PART_TRIM);\n if (trimPixelColor != null) {\n builder.append(\":\").append(trimPixelColor.value);\n if (trimColorTolerance > 0) {\n builder.append(\":\").append(trimColorTolerance);\n }\n }\n builder.append(\"/\");\n }\n\n if (hasCrop) {\n builder.append(cropLeft).append(\"x\").append(cropTop) //\n .append(\":\").append(cropRight).append(\"x\").append(cropBottom);\n\n builder.append(\"/\");\n }\n\n if (hasResize) {\n if (fitInStyle != null) {\n builder.append(fitInStyle.value).append(\"/\");\n }\n if (flipHorizontally) {\n builder.append(\"-\");\n }\n if (resizeWidth == ORIGINAL_SIZE) {\n builder.append(\"orig\");\n } else {\n builder.append(resizeWidth);\n }\n builder.append(\"x\");\n if (flipVertically) {\n builder.append(\"-\");\n }\n if (resizeHeight == ORIGINAL_SIZE) {\n builder.append(\"orig\");\n } else {\n builder.append(resizeHeight);\n }\n if (isSmart) {\n builder.append(\"/\").append(PART_SMART);\n } else {\n if (cropHorizontalAlign != null) {\n builder.append(\"/\").append(cropHorizontalAlign.value);\n }\n if (cropVerticalAlign != null) {\n builder.append(\"/\").append(cropVerticalAlign.value);\n }\n }\n builder.append(\"/\");\n }\n\n if (filters != null) {\n builder.append(PART_FILTERS);\n for (String filter : filters) {\n builder.append(\":\").append(filter);\n }\n builder.append(\"/\");\n }\n\n builder.append(isLegacy ? md5(image) : image);\n\n return builder;\n }", "@Override\n @SuppressLint(\"NewApi\")\n public boolean onTouch(View v, MotionEvent event) {\n if(touchable) {\n\n if (event.getAction() == MotionEvent.ACTION_DOWN) {\n view.setBackgroundColor(colorPressed);\n\n return true;\n }\n\n if (event.getAction() == MotionEvent.ACTION_CANCEL) {\n if (isSelected)\n view.setBackgroundColor(colorSelected);\n else\n view.setBackgroundColor(colorUnpressed);\n\n return true;\n }\n\n\n if (event.getAction() == MotionEvent.ACTION_UP) {\n\n view.setBackgroundColor(colorSelected);\n afterClick();\n\n return true;\n }\n }\n\n return false;\n }", "public List<Tag> getPrimeTags()\n {\n return this.definedTags.values().stream()\n .filter(Tag::isPrime)\n .collect(Collectors.toList());\n }", "protected String calculateNextVersion(String fromVersion) {\n // first turn it to release version\n fromVersion = calculateReleaseVersion(fromVersion);\n String nextVersion;\n int lastDotIndex = fromVersion.lastIndexOf('.');\n try {\n if (lastDotIndex != -1) {\n // probably a major minor version e.g., 2.1.1\n String minorVersionToken = fromVersion.substring(lastDotIndex + 1);\n String nextMinorVersion;\n int lastDashIndex = minorVersionToken.lastIndexOf('-');\n if (lastDashIndex != -1) {\n // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5)\n String buildNumber = minorVersionToken.substring(lastDashIndex + 1);\n int nextBuildNumber = Integer.parseInt(buildNumber) + 1;\n nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber;\n } else {\n nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + \"\";\n }\n nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion;\n } else {\n // maybe it's just a major version; try to parse as an int\n int nextMajorVersion = Integer.parseInt(fromVersion) + 1;\n nextVersion = nextMajorVersion + \"\";\n }\n } catch (NumberFormatException e) {\n return fromVersion;\n }\n return nextVersion + \"-SNAPSHOT\";\n }", "int acquireTransaction(@NotNull final Thread thread) {\n try (CriticalSection ignored = criticalSection.enter()) {\n final int currentThreadPermits = getThreadPermitsToAcquire(thread);\n waitForPermits(thread, currentThreadPermits > 0 ? nestedQueue : regularQueue, 1, currentThreadPermits);\n }\n return 1;\n }", "private String joinElements(int length)\n {\n StringBuilder sb = new StringBuilder();\n for (int index = 0; index < length; index++)\n {\n sb.append(m_elements.get(index));\n }\n return sb.toString();\n }", "public void setReadTimeout(int millis) {\n\t\t// Hack to get round Spring's dynamic loading of http client stuff\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t}", "public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }", "public synchronized void resumeDeployment(final String deployment) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n ep.resume();\n }\n }\n }" ]
Returns an empty Promotion details in Json @return String @throws IOException
[ "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 static String getModuleVersion(final String moduleId) {\n final int splitter = moduleId.lastIndexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(splitter+1);\n }", "public boolean shouldNotCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, noCacheIdentifiers) || checkSuffixes(uri, noCacheSuffixes);\n\t}", "private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }", "private List<SynchroTable> readTableHeaders(InputStream is) throws IOException\n {\n // Read the headers\n List<SynchroTable> tables = new ArrayList<SynchroTable>();\n byte[] header = new byte[48];\n while (true)\n {\n is.read(header);\n m_offset += 48;\n SynchroTable table = readTableHeader(header);\n if (table == null)\n {\n break;\n }\n tables.add(table);\n }\n\n // Ensure sorted by offset\n Collections.sort(tables, new Comparator<SynchroTable>()\n {\n @Override public int compare(SynchroTable o1, SynchroTable o2)\n {\n return o1.getOffset() - o2.getOffset();\n }\n });\n\n // Calculate lengths\n SynchroTable previousTable = null;\n for (SynchroTable table : tables)\n {\n if (previousTable != null)\n {\n previousTable.setLength(table.getOffset() - previousTable.getOffset());\n }\n\n previousTable = table;\n }\n\n for (SynchroTable table : tables)\n {\n SynchroLogger.log(\"TABLE\", table);\n }\n\n return tables;\n }", "public static dnsaaaarec[] get(nitro_service service) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private Number calculatePercentComplete(Row row)\n {\n Number result;\n switch (PercentCompleteType.getInstance(row.getString(\"complete_pct_type\")))\n {\n case UNITS:\n {\n result = calculateUnitsPercentComplete(row);\n break;\n }\n\n case DURATION:\n {\n result = calculateDurationPercentComplete(row);\n break;\n }\n\n default:\n {\n result = calculatePhysicalPercentComplete(row);\n break;\n }\n }\n\n return result;\n }", "private void addToGraph(ClassDoc cd) {\n\t// avoid adding twice the same class, but don't rely on cg.getClassInfo\n\t// since there are other ways to add a classInfor than printing the class\n\tif (visited.contains(cd.toString()))\n\t return;\n\n\tvisited.add(cd.toString());\n\tcg.printClass(cd, false);\n\tcg.printRelations(cd);\n\tif (opt.inferRelationships)\n\t cg.printInferredRelations(cd);\n\tif (opt.inferDependencies)\n\t cg.printInferredDependencies(cd);\n }", "public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }", "public Object getObjectByQuery(Query query) throws PersistenceBrokerException\n {\n Object result = null;\n if (query instanceof QueryByIdentity)\n {\n // example obj may be an entity or an Identity\n Object obj = query.getExampleObject();\n if (obj instanceof Identity)\n {\n Identity oid = (Identity) obj;\n result = getObjectByIdentity(oid);\n }\n else\n {\n // TODO: This workaround doesn't allow 'null' for PK fields\n if (!serviceBrokerHelper().hasNullPKField(getClassDescriptor(obj.getClass()), obj))\n {\n Identity oid = serviceIdentity().buildIdentity(obj);\n result = getObjectByIdentity(oid);\n }\n }\n }\n else\n {\n Class itemClass = query.getSearchClass();\n ClassDescriptor cld = getClassDescriptor(itemClass);\n /*\n use OJB intern Iterator, thus we are able to close used\n resources instantly\n */\n OJBIterator it = getIteratorFromQuery(query, cld);\n /*\n arminw:\n patch by Andre Clute, instead of taking the first found result\n try to get the first found none null result.\n He wrote:\n I have a situation where an item with a certain criteria is in my\n database twice -- once deleted, and then a non-deleted version of it.\n When I do a PB.getObjectByQuery(), the RsIterator get's both results\n from the database, but the first row is the deleted row, so my RowReader\n filters it out, and do not get the right result.\n */\n try\n {\n while (result==null && it.hasNext())\n {\n result = it.next();\n }\n } // make sure that we close the used resources\n finally\n {\n if(it != null) it.releaseDbResources();\n }\n }\n return result;\n }" ]
Create dummy groups for each concatenated report, and in the footer of each group adds the subreport.
[ "protected void concatenateReports() {\n\n if (!concatenatedReports.isEmpty()) { // dummy group for page break if needed\n DJGroup globalGroup = createDummyGroup();\n report.getColumnsGroups().add(0, globalGroup);\n }\n\n for (Subreport subreport : concatenatedReports) {\n DJGroup globalGroup = createDummyGroup();\n globalGroup.getFooterSubreports().add(subreport);\n report.getColumnsGroups().add(0, globalGroup);\n }\n }" ]
[ "public static String determineFieldName(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);\n\t}", "private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = m_calendarMap.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n }", "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our previews, on the proper thread, and outside our lock.\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(hotCache.keySet());\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(deck.player, null);\n }\n }\n }\n });\n hotCache.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }", "protected void markStatementsForDeletion(StatementDocument currentDocument,\n\t\t\tList<Statement> deleteStatements) {\n\t\tfor (Statement statement : deleteStatements) {\n\t\t\tboolean found = false;\n\t\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\t\tif (!sg.getProperty().equals(statement.getMainSnak().getPropertyId())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tStatement changedStatement = null;\n\t\t\t\tfor (Statement existingStatement : sg) {\n\t\t\t\t\tif (existingStatement.equals(statement)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\ttoDelete.add(statement.getStatementId());\n\t\t\t\t\t} else if (existingStatement.getStatementId().equals(\n\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\t// (we assume all existing statement ids to be nonempty\n\t\t\t\t\t\t// here)\n\t\t\t\t\t\tchangedStatement = existingStatement;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!found) {\n\t\t\t\t\tStringBuilder warning = new StringBuilder();\n\t\t\t\t\twarning.append(\"Cannot delete statement (id \")\n\t\t\t\t\t\t\t.append(statement.getStatementId())\n\t\t\t\t\t\t\t.append(\") since it is not present in data. Statement was:\\n\")\n\t\t\t\t\t\t\t.append(statement);\n\n\t\t\t\t\tif (changedStatement != null) {\n\t\t\t\t\t\twarning.append(\n\t\t\t\t\t\t\t\t\"\\nThe data contains another statement with the same id: maybe it has been edited? Other statement was:\\n\")\n\t\t\t\t\t\t\t\t.append(changedStatement);\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(warning.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "private String toLengthText(long bytes) {\n if (bytes < 1024) {\n return bytes + \" B\";\n } else if (bytes < 1024 * 1024) {\n return (bytes / 1024) + \" KB\";\n } else if (bytes < 1024 * 1024 * 1024) {\n return String.format(\"%.2f MB\", bytes / (1024.0 * 1024.0));\n } else {\n return String.format(\"%.2f GB\", bytes / (1024.0 * 1024.0 * 1024.0));\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<BritishCutoverDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<BritishCutoverDate>) super.localDateTime(temporal);\n }", "public UriComponentsBuilder uri(URI uri) {\n\t\tAssert.notNull(uri, \"'uri' must not be null\");\n\t\tthis.scheme = uri.getScheme();\n\t\tif (uri.isOpaque()) {\n\t\t\tthis.ssp = uri.getRawSchemeSpecificPart();\n\t\t\tresetHierarchicalComponents();\n\t\t}\n\t\telse {\n\t\t\tif (uri.getRawUserInfo() != null) {\n\t\t\t\tthis.userInfo = uri.getRawUserInfo();\n\t\t\t}\n\t\t\tif (uri.getHost() != null) {\n\t\t\t\tthis.host = uri.getHost();\n\t\t\t}\n\t\t\tif (uri.getPort() != -1) {\n\t\t\t\tthis.port = String.valueOf(uri.getPort());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawPath())) {\n\t\t\t\tthis.pathBuilder = new CompositePathComponentBuilder(uri.getRawPath());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawQuery())) {\n\t\t\t\tthis.queryParams.clear();\n\t\t\t\tquery(uri.getRawQuery());\n\t\t\t}\n\t\t\tresetSchemeSpecificPart();\n\t\t}\n\t\tif (uri.getRawFragment() != null) {\n\t\t\tthis.fragment = uri.getRawFragment();\n\t\t}\n\t\treturn this;\n\t}", "public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }" ]
In the 3.0 xsd the vault configuration and its options are part of the vault xsd. @param reader the reader at the vault element @param expectedNs the namespace @return the vault configuration
[ "static VaultConfig readVaultElement_3_0(XMLExtendedStreamReader reader, Namespace expectedNs) throws XMLStreamException {\n final VaultConfig config = new VaultConfig();\n\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n String name = reader.getAttributeLocalName(i);\n if (name.equals(CODE)){\n config.code = value;\n } else if (name.equals(MODULE)){\n config.module = value;\n } else {\n unexpectedVaultAttribute(reader.getAttributeLocalName(i), reader);\n }\n }\n if (config.code == null && config.module != null){\n throw new XMLStreamException(\"Attribute 'module' was specified without an attribute\"\n + \" 'code' for element '\" + VAULT + \"' at \" + reader.getLocation());\n }\n readVaultOptions(reader, config);\n return config;\n }" ]
[ "@Override\n public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor)\n throws Exception {\n clientRequestExecutor.close();\n int numDestroyed = destroyed.incrementAndGet();\n if(stats != null) {\n stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT);\n }\n\n if(logger.isDebugEnabled())\n logger.debug(\"Destroyed socket \" + numDestroyed + \" connection to \" + dest.getHost()\n + \":\" + dest.getPort());\n }", "public static double HighAccuracyFunction(double x) {\n if (x < -8 || x > 8)\n return 0;\n\n double sum = x;\n double term = 0;\n\n double nextTerm = x;\n double pwr = x * x;\n double i = 1;\n\n // Iterate until adding next terms doesn't produce\n // any change within the current numerical accuracy.\n\n while (sum != term) {\n term = sum;\n\n // Next term\n nextTerm *= pwr / (i += 2);\n\n sum += nextTerm;\n }\n\n return 0.5 + sum * Math.exp(-0.5 * pwr - 0.5 * Constants.Log2PI);\n }", "public SignedJWT verifyToken(String jwtString) throws ParseException {\n try {\n SignedJWT jwt = SignedJWT.parse(jwtString);\n if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) {\n return jwt;\n }\n return null;\n } catch (JOSEException e) {\n throw new RuntimeException(\"Error verifying JSON Web Token\", e);\n }\n }", "public double getDouble(Integer id, Integer type)\n {\n double result = Double.longBitsToDouble(getLong(id, type));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return result;\n }", "private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,\r\n\t\t\tDayCountConvention daycountConvention) {\r\n\r\n\t\tboolean isFixed = leg.getElementsByTagName(\"interestType\").item(0).getTextContent().equalsIgnoreCase(\"FIX\");\r\n\r\n\t\tArrayList<Period> periods \t\t= new ArrayList<>();\r\n\t\tArrayList<Double> notionalsList\t= new ArrayList<>();\r\n\t\tArrayList<Double> rates\t\t\t= new ArrayList<>();\r\n\r\n\t\t//extracting data for each period\r\n\t\tNodeList periodsXML = leg.getElementsByTagName(\"incomePayment\");\r\n\t\tfor(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {\r\n\r\n\t\t\tElement periodXML = (Element) periodsXML.item(periodIndex);\r\n\r\n\t\t\tLocalDate startDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"startDate\").item(0).getTextContent());\r\n\t\t\tLocalDate endDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"endDate\").item(0).getTextContent());\r\n\r\n\t\t\tLocalDate fixingDate\t= startDate;\r\n\t\t\tLocalDate paymentDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"payDate\").item(0).getTextContent());\r\n\r\n\t\t\tif(! isFixed) {\r\n\t\t\t\tfixingDate = LocalDate.parse(periodXML.getElementsByTagName(\"fixingDate\").item(0).getTextContent());\r\n\t\t\t}\r\n\r\n\t\t\tperiods.add(new Period(fixingDate, paymentDate, startDate, endDate));\r\n\r\n\t\t\tdouble notional\t\t= Double.parseDouble(periodXML.getElementsByTagName(\"nominal\").item(0).getTextContent());\r\n\t\t\tnotionalsList.add(new Double(notional));\r\n\r\n\t\t\tif(isFixed) {\r\n\t\t\t\tdouble fixedRate\t= Double.parseDouble(periodXML.getElementsByTagName(\"fixedRate\").item(0).getTextContent());\r\n\t\t\t\trates.add(new Double(fixedRate));\r\n\t\t\t} else {\r\n\t\t\t\trates.add(new Double(0));\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);\r\n\t\tdouble[] notionals\t= notionalsList.stream().mapToDouble(Double::doubleValue).toArray();\r\n\t\tdouble[] spreads\t= rates.stream().mapToDouble(Double::doubleValue).toArray();\r\n\r\n\t\treturn new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);\r\n\t}", "private String randomString(String[] s) {\n if (s == null || s.length <= 0) return \"\";\n return s[this.random.nextInt(s.length)];\n }", "public static DMatrixRMaj elements(DMatrixRMaj A , BMatrixRMaj marked , DMatrixRMaj output ) {\n if( A.numRows != marked.numRows || A.numCols != marked.numCols )\n throw new MatrixDimensionException(\"Input matrices must have the same shape\");\n if( output == null )\n output = new DMatrixRMaj(1,1);\n\n output.reshape(countTrue(marked),1);\n\n int N = A.getNumElements();\n\n int index = 0;\n for (int i = 0; i < N; i++) {\n if( marked.data[i] ) {\n output.data[index++] = A.data[i];\n }\n }\n\n return output;\n }", "protected I_CmsSearchConfigurationFacetRange parseRangeFacet(JSONObject rangeFacetObject) {\n\n try {\n String range = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_RANGE);\n String name = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(rangeFacetObject, JSON_KEY_FACET_MINCOUNT);\n String start = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_START);\n String end = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_END);\n String gap = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_GAP);\n List<String> sother = parseOptionalStringValues(rangeFacetObject, JSON_KEY_RANGE_FACET_OTHER);\n Boolean hardEnd = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_RANGE_FACET_HARDEND);\n List<I_CmsSearchConfigurationFacetRange.Other> other = null;\n if (sother != null) {\n other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sother.size());\n for (String so : sother) {\n try {\n I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf(\n so);\n other.add(o);\n } catch (Exception e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e);\n }\n }\n }\n Boolean isAndFacet = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(rangeFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n rangeFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetRange(\n range,\n start,\n end,\n gap,\n other,\n hardEnd,\n name,\n minCount,\n label,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1,\n JSON_KEY_RANGE_FACET_RANGE\n + \", \"\n + JSON_KEY_RANGE_FACET_START\n + \", \"\n + JSON_KEY_RANGE_FACET_END\n + \", \"\n + JSON_KEY_RANGE_FACET_GAP),\n e);\n return null;\n }\n\n }", "public static void addToString(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n boolean forPartial) {\n String typename = (forPartial ? \"partial \" : \"\") + datatype.getType().getSimpleName();\n Predicate<PropertyCodeGenerator> isOptional = generator -> {\n Initially initially = generator.initialState();\n return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial));\n };\n boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional);\n boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional)\n && !generatorsByProperty.isEmpty();\n\n code.addLine(\"\")\n .addLine(\"@%s\", Override.class)\n .addLine(\"public %s toString() {\", String.class);\n if (allOptional) {\n bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename);\n } else if (anyOptional) {\n bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional);\n } else {\n bodyWithConcatenation(code, generatorsByProperty, typename);\n }\n code.addLine(\"}\");\n }" ]
a small static helper to set a multi state drawable on a view @param icon @param iconColor @param selectedIcon @param selectedIconColor @param tinted @param imageView
[ "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 String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}", "public static base_response add(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager addresource = new snmpmanager();\n\t\taddresource.ipaddress = resource.ipaddress;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn addresource.add_resource(client);\n\t}", "public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\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 }", "@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }", "public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }", "public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }", "public Collection<Contact> getPublicList(String userId) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_LIST);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "public static Boolean parseBoolean(String value) throws ParseException\n {\n Boolean result = null;\n Integer number = parseInteger(value);\n if (number != null)\n {\n result = number.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n return result;\n }" ]
Get the axis along the orientation @return
[ "public Axis getOrientationAxis() {\n final Axis axis;\n switch(getOrientation()) {\n case HORIZONTAL:\n axis = Axis.X;\n break;\n case VERTICAL:\n axis = Axis.Y;\n break;\n case STACK:\n axis = Axis.Z;\n break;\n default:\n Log.w(TAG, \"Unsupported orientation %s\", mOrientation);\n axis = Axis.X;\n break;\n }\n return axis;\n }" ]
[ "public synchronized void stop() {\n if (isRunning()) {\n socket.get().close();\n socket.set(null);\n deliverLifecycleAnnouncement(logger, false);\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 }", "public void processSplitData(Task task, List<TimephasedWork> timephasedComplete, List<TimephasedWork> timephasedPlanned)\n {\n Date splitsComplete = null;\n TimephasedWork lastComplete = null;\n TimephasedWork firstPlanned = null;\n if (!timephasedComplete.isEmpty())\n {\n lastComplete = timephasedComplete.get(timephasedComplete.size() - 1);\n splitsComplete = lastComplete.getFinish();\n }\n\n if (!timephasedPlanned.isEmpty())\n {\n firstPlanned = timephasedPlanned.get(0);\n }\n\n LinkedList<DateRange> splits = new LinkedList<DateRange>();\n TimephasedWork lastAssignment = null;\n DateRange lastRange = null;\n for (TimephasedWork assignment : timephasedComplete)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n splits.add(lastRange);\n lastAssignment = assignment;\n }\n\n //\n // We may not have a split, we may just have a partially\n // complete split.\n //\n Date splitStart = null;\n if (lastComplete != null && firstPlanned != null && lastComplete.getTotalAmount().getDuration() != 0 && firstPlanned.getTotalAmount().getDuration() != 0)\n {\n lastRange = splits.removeLast();\n splitStart = lastRange.getStart();\n }\n\n lastAssignment = null;\n lastRange = null;\n for (TimephasedWork assignment : timephasedPlanned)\n {\n if (splitStart == null)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n }\n else\n {\n lastRange = new DateRange(splitStart, assignment.getFinish());\n }\n splits.add(lastRange);\n splitStart = null;\n lastAssignment = assignment;\n }\n\n //\n // We must have a minimum of 3 entries for this to be a valid split task\n //\n if (splits.size() > 2)\n {\n task.getSplits().addAll(splits);\n task.setSplitCompleteDuration(splitsComplete);\n }\n else\n {\n task.setSplits(null);\n task.setSplitCompleteDuration(null);\n }\n }", "public static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) {\n for(StoreDefinition def: list)\n if(def.getName().equals(name))\n return def;\n return null;\n }", "public void showCurrentDates(Collection<CmsPair<Date, Boolean>> dates) {\n\n m_overviewList.setDatesWithCheckState(dates);\n m_overviewPopup.center();\n\n }", "protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) {\n if (text.indexOf(':') == -1) {\n text = text.replace(\" \", \"\");\n int numdigits = 0;\n int lastdigit = 0;\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (Character.isDigit(c)) {\n numdigits++;\n lastdigit = i;\n }\n }\n if (numdigits == 1 || numdigits == 2) {\n // insert :00\n int colon = lastdigit + 1;\n text = text.substring(0, colon) + \":00\" + text.substring(colon);\n }\n else if (numdigits > 2) {\n // insert :\n int colon = lastdigit - 1;\n text = text.substring(0, colon) + \":\" + text.substring(colon);\n }\n return parseUsingFallbacks(text, timeFormat);\n }\n else {\n return null;\n }\n }", "public void addSerie(AbstractColumn column, StringExpression labelExpression) {\r\n\t\tseries.add(column);\r\n\t\tseriesLabels.put(column, labelExpression);\r\n\t}", "public int getIndexByDate(Date date)\n {\n int result = -1;\n int index = 0;\n\n for (CostRateTableEntry entry : this)\n {\n if (DateHelper.compare(date, entry.getEndDate()) < 0)\n {\n result = index;\n break;\n }\n ++index;\n }\n\n return result;\n }", "public Set<ConstraintViolation> validate() {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int record = 1; record <= 3; ++record) {\r\n\t\t\terrors.addAll(validate(record));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}" ]
Add the final assignment of the property to the partial value object's source code.
[ "public void addPartialFieldAssignment(\n SourceBuilder code, Excerpt finalField, String builder) {\n addFinalFieldAssignment(code, finalField, builder);\n }" ]
[ "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 }", "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) {\n // for expressions like foo = { ... }\n // we know that the RHS type is a closure\n // but we must check if the binary expression is an assignment\n // because we need to check if a setter uses @DelegatesTo\n VariableExpression ve = new VariableExpression(\"%\", setterInfo.receiverType);\n MethodCallExpression call = new MethodCallExpression(\n ve,\n setterInfo.name,\n rightExpression\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate==null) {\n // this may happen if there's a setter of type boolean/String/Class, and that we are using the property\n // notation AND that the RHS is not a boolean/String/Class\n for (MethodNode setter : setterInfo.setters) {\n ClassNode type = getWrapper(setter.getParameters()[0].getOriginType());\n if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) {\n call = new MethodCallExpression(\n ve,\n setterInfo.name,\n new CastExpression(type,rightExpression)\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate!=null) {\n break;\n }\n }\n }\n }\n if (directSetterCandidate != null) {\n for (MethodNode setter : setterInfo.setters) {\n if (setter == directSetterCandidate) {\n leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate);\n storeType(leftExpression, getType(rightExpression));\n break;\n }\n }\n } else {\n ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType();\n addAssignmentError(firstSetterType, getType(rightExpression), expression);\n return true;\n }\n return false;\n }", "public PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }", "private void deliverCacheUpdate(SlotReference slot, MetadataCache cache) {\n for (final MetadataCacheListener listener : getCacheListeners()) {\n try {\n if (cache == null) {\n listener.cacheDetached(slot);\n } else {\n listener.cacheAttached(slot, cache);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering metadata cache update to listener\", t);\n }\n }\n }", "public ItemRequest<Project> findById(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"GET\");\n }", "public synchronized void setMonitoredPlayer(final int player) {\n if (player < 0) {\n throw new IllegalArgumentException(\"player cannot be negative\");\n }\n clearPlaybackState();\n monitoredPlayer.set(player);\n if (player > 0) { // Start monitoring the specified player\n setPlaybackState(player, 0, false); // Start with default values for required simple state.\n VirtualCdj.getInstance().addUpdateListener(updateListener);\n MetadataFinder.getInstance().addTrackMetadataListener(metadataListener);\n cueList.set(null); // Assume the worst, but see if we have one available next.\n if (MetadataFinder.getInstance().isRunning()) {\n TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n if (metadata != null) {\n cueList.set(metadata.getCueList());\n }\n }\n WaveformFinder.getInstance().addWaveformListener(waveformListener);\n if (WaveformFinder.getInstance().isRunning() && WaveformFinder.getInstance().isFindingDetails()) {\n waveform.set(WaveformFinder.getInstance().getLatestDetailFor(player));\n } else {\n waveform.set(null);\n }\n BeatGridFinder.getInstance().addBeatGridListener(beatGridListener);\n if (BeatGridFinder.getInstance().isRunning()) {\n beatGrid.set(BeatGridFinder.getInstance().getLatestBeatGridFor(player));\n } else {\n beatGrid.set(null);\n }\n try {\n TimeFinder.getInstance().start();\n if (!animating.getAndSet(true)) {\n // Create the thread to update our position smoothly as the track plays\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (animating.get()) {\n try {\n Thread.sleep(33); // Animate at 30 fps\n } catch (InterruptedException e) {\n logger.warn(\"Waveform animation thread interrupted; ending\");\n animating.set(false);\n }\n setPlaybackPosition(TimeFinder.getInstance().getTimeFor(getMonitoredPlayer()));\n }\n }\n }).start();\n }\n } catch (Exception e) {\n logger.error(\"Unable to start the TimeFinder to animate the waveform detail view\");\n animating.set(false);\n }\n } else { // Stop monitoring any player\n animating.set(false);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n cueList.set(null);\n waveform.set(null);\n beatGrid.set(null);\n }\n if (!autoScroll.get()) {\n invalidate();\n }\n repaint();\n }", "private void printKeySet() {\r\n Set<?> keys = keySet();\r\n System.out.println(\"printing keyset:\");\r\n for (Object o: keys) {\r\n //System.out.println(Arrays.asList((Object[]) i.next()));\r\n System.out.println(o);\r\n }\r\n }", "private BigInteger printExtendedAttributeDurationFormat(Object value)\n {\n BigInteger result = null;\n if (value instanceof Duration)\n {\n result = DatatypeConverter.printDurationTimeUnits(((Duration) value).getUnits(), false);\n }\n return (result);\n }" ]
Create a smaller array from an existing one. @param strings an array containing element of type {@link String} @param begin the starting position of the sub-array @param length the number of element to consider @return a new array continaining only the selected elements
[ "public static String[] slice(String[] strings, int begin, int length) {\n\t\tString[] result = new String[length];\n\t\tSystem.arraycopy( strings, begin, result, 0, length );\n\t\treturn result;\n\t}" ]
[ "public void onDrawFrame(float frameTime) {\n final GVRSceneObject owner = getOwnerObject();\n if (owner == null) {\n return;\n }\n\n final int size = mRanges.size();\n final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();\n\n for (final Object[] range : mRanges) {\n ((GVRSceneObject)range[1]).setEnable(false);\n }\n\n for (int i = size - 1; i >= 0; --i) {\n final Object[] range = mRanges.get(i);\n final GVRSceneObject child = (GVRSceneObject) range[1];\n if (child.getParent() != owner) {\n Log.w(TAG, \"the scene object for distance greater than \" + range[0] + \" is not a child of the owner; skipping it\");\n continue;\n }\n\n final float[] values = child.getBoundingVolumeRawValues();\n mCenter.set(values[0], values[1], values[2], 1.0f);\n mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);\n\n mVector.sub(mCenter);\n mVector.negate();\n\n float distance = mVector.dot(mVector);\n\n if (distance >= (Float) range[0]) {\n child.setEnable(true);\n break;\n }\n }\n }", "public static ModelNode getFailureDescription(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n throw ControllerClientLogger.ROOT_LOGGER.noFailureDescription();\n }\n if (result.hasDefined(FAILURE_DESCRIPTION)) {\n return result.get(FAILURE_DESCRIPTION);\n }\n return new ModelNode();\n }", "private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }", "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 }", "private String getFullUrl(String url) {\n return url.startsWith(\"https://\") || url.startsWith(\"http://\") ? url : transloadit.getHostUrl() + url;\n }", "protected void beforeLoading()\r\n {\r\n if (_listeners != null)\r\n {\r\n CollectionProxyListener listener;\r\n\r\n if (_perThreadDescriptorsEnabled) {\r\n loadProfileIfNeeded();\r\n }\r\n for (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n {\r\n listener = (CollectionProxyListener)_listeners.get(idx);\r\n listener.beforeLoading(this);\r\n }\r\n }\r\n }", "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 Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "@Deprecated\n public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {\n this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);\n return this;\n }" ]
Use this API to delete systementitydata.
[ "public static base_response delete(nitro_service client, systementitydata resource) throws Exception {\n\t\tsystementitydata deleteresource = new systementitydata();\n\t\tdeleteresource.type = resource.type;\n\t\tdeleteresource.name = resource.name;\n\t\tdeleteresource.alldeleted = resource.alldeleted;\n\t\tdeleteresource.allinactive = resource.allinactive;\n\t\tdeleteresource.datasource = resource.datasource;\n\t\tdeleteresource.core = resource.core;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
[ "public ItemRequest<Webhook> getById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"GET\");\n }", "public static DoubleMatrix absi(DoubleMatrix x) { \n\t\t/*# mapfct('Math.abs') #*/\n//RJPP-BEGIN------------------------------------------------------------\n\t for (int i = 0; i < x.length; i++)\n\t x.put(i, (double) Math.abs(x.get(i)));\n\t return x;\n//RJPP-END--------------------------------------------------------------\n\t}", "protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public CrosstabBuilder setColumnStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setColumnHeaderStyle(headerStyle);\r\n\t\tcrosstab.setColumnTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setColumnTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}", "public void identifyNode(int nodeId) throws SerialInterfaceException {\n\t\tSerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessagePriority.High);\n \tbyte[] newPayload = { (byte) nodeId };\n \tnewMessage.setMessagePayload(newPayload);\n \tthis.enqueue(newMessage);\n\t}", "static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {\n final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());\n final FlushableDataOutput output = context.writeMessage(header);\n try {\n // This is an error\n output.writeByte(DomainControllerProtocol.PARAM_ERROR);\n // send error code\n output.writeByte(errorCode);\n // error message\n if (message == null) {\n output.writeUTF(\"unknown error\");\n } else {\n output.writeUTF(message);\n }\n // response end\n output.writeByte(ManagementProtocol.RESPONSE_END);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }", "public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }", "private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }", "public void forAllClassDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _model.getClasses(); it.hasNext(); )\r\n {\r\n _curClassDef = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curClassDef = null;\r\n\r\n LogHelper.debug(true, OjbTagsHandler.class, \"forAllClassDefinitions\", \"Processed \"+_model.getNumClasses()+\" types\");\r\n }" ]
Indicates that contextual session bean instance has been constructed.
[ "public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) {\n Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get();\n classes.remove(descriptor.getBeanClass());\n if (classes.isEmpty()) {\n CONTEXTUAL_SESSION_BEANS.remove();\n }\n }" ]
[ "public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors)\n\t\t\tthrows SQLException {\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn dropTable(dao, ignoreErrors);\n\t}", "@Override\n\tpublic boolean retainAll(Collection<?> collection) {\n\t\tif (dao == null) {\n\t\t\treturn false;\n\t\t}\n\t\tboolean changed = false;\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tT data = iterator.next();\n\t\t\t\tif (!collection.contains(data)) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn changed;\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "public static cmpglobal_cmppolicy_binding[] get(nitro_service service) throws Exception{\n\t\tcmpglobal_cmppolicy_binding obj = new cmpglobal_cmppolicy_binding();\n\t\tcmpglobal_cmppolicy_binding response[] = (cmpglobal_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }", "public static base_response add(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy addresource = new transformpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\treturn addresource.add_resource(client);\n\t}", "public Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\n }", "private void loadAllRemainingLocalizations() throws CmsException, UnsupportedEncodingException, IOException {\n\n if (!m_alreadyLoadedAllLocalizations) {\n // is only necessary for property bundles\n if (m_bundleType.equals(BundleType.PROPERTY)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n CmsResource resource = m_bundleFiles.get(l);\n if (resource != null) {\n CmsFile file = m_cms.readFile(resource);\n m_bundleFiles.put(l, file);\n SortedProperties props = new SortedProperties();\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_localizations.put(l, props);\n }\n }\n }\n }\n if (m_bundleType.equals(BundleType.XML)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n loadLocalizationFromXmlBundle(l);\n }\n }\n }\n m_alreadyLoadedAllLocalizations = true;\n }\n\n }", "public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) {\n return new EnumStringConverter<E>(enumType);\n }", "public static aaauser_intranetip_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_intranetip_binding obj = new aaauser_intranetip_binding();\n\t\tobj.set_username(username);\n\t\taaauser_intranetip_binding response[] = (aaauser_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
get bearer token returned by IAM in JSON format
[ "private String getBearerToken(HttpConnectionInterceptorContext context) {\n final AtomicReference<String> iamTokenResponse = new AtomicReference<String>();\n boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody,\n \"application/x-www-form-urlencoded\", \"application/json\",\n new StoreBearerCallable(iamTokenResponse));\n if (result) {\n return iamTokenResponse.get();\n } else {\n return null;\n }\n }" ]
[ "public Date getTimestamp(FastTrackField dateName, FastTrackField timeName)\n {\n Date result = null;\n Date date = getDate(dateName);\n if (date != null)\n {\n Calendar dateCal = DateHelper.popCalendar(date);\n Date time = getDate(timeName);\n if (time != null)\n {\n Calendar timeCal = DateHelper.popCalendar(time);\n dateCal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY));\n dateCal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE));\n dateCal.set(Calendar.SECOND, timeCal.get(Calendar.SECOND));\n dateCal.set(Calendar.MILLISECOND, timeCal.get(Calendar.MILLISECOND));\n DateHelper.pushCalendar(timeCal);\n }\n\n result = dateCal.getTime();\n DateHelper.pushCalendar(dateCal);\n }\n\n return result;\n }", "@PostConstruct\n public final void addMetricsAppenderToLogback() {\n final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();\n final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);\n\n final InstrumentedAppender metrics = new InstrumentedAppender(this.metricRegistry);\n metrics.setContext(root.getLoggerContext());\n metrics.start();\n root.addAppender(metrics);\n }", "public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unchecked\") private Object formatType(DataType type, Object value)\n {\n switch (type)\n {\n case DATE:\n {\n value = formatDateTime(value);\n break;\n }\n\n case CURRENCY:\n {\n value = formatCurrency((Number) value);\n break;\n }\n\n case UNITS:\n {\n value = formatUnits((Number) value);\n break;\n }\n\n case PERCENTAGE:\n {\n value = formatPercentage((Number) value);\n break;\n }\n\n case ACCRUE:\n {\n value = formatAccrueType((AccrueType) value);\n break;\n }\n\n case CONSTRAINT:\n {\n value = formatConstraintType((ConstraintType) value);\n break;\n }\n\n case WORK:\n case DURATION:\n {\n value = formatDuration(value);\n break;\n }\n\n case RATE:\n {\n value = formatRate((Rate) value);\n break;\n }\n\n case PRIORITY:\n {\n value = formatPriority((Priority) value);\n break;\n }\n\n case RELATION_LIST:\n {\n value = formatRelationList((List<Relation>) value);\n break;\n }\n\n case TASK_TYPE:\n {\n value = formatTaskType((TaskType) value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return (value);\n }", "public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }", "public static String getTypeValue(Class<? extends WindupFrame> clazz)\n {\n TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);\n if (typeValueAnnotation == null)\n throw new IllegalArgumentException(\"Class \" + clazz.getCanonicalName() + \" lacks a @TypeValue annotation\");\n\n return typeValueAnnotation.value();\n }", "public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }", "public TaskMode getTaskMode()\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;\n }", "public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }" ]
Deselects all child items of the provided item. @param item the item for which all childs should be deselected.d
[ "private void deselectChildren(CmsTreeItem item) {\r\n\r\n for (String childId : m_childrens.get(item.getId())) {\r\n CmsTreeItem child = m_categories.get(childId);\r\n deselectChildren(child);\r\n child.getCheckBox().setChecked(false);\r\n if (m_selectedCategories.contains(childId)) {\r\n m_selectedCategories.remove(childId);\r\n }\r\n }\r\n }" ]
[ "public Response executeToResponse(HttpConnection connection) {\n InputStream is = null;\n try {\n is = this.executeToInputStream(connection);\n Response response = getResponse(is, Response.class, getGson());\n response.setStatusCode(connection.getConnection().getResponseCode());\n response.setReason(connection.getConnection().getResponseMessage());\n return response;\n } catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response code or message.\", e);\n } finally {\n close(is);\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}", "public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}\", this.getNode().getNodeId(), endpoint.getEndpointId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) MULTI_CHANNEL_CAPABILITY_GET,\r\n\t\t\t\t\t\t\t\t(byte) endpoint.getEndpointId() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\r\n\t}", "public Headers getAllHeaders() {\n Headers requestHeaders = getHeaders();\n requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders;\n //We don't want to add headers more than once.\n return requestHeaders;\n }", "private static Collection<String> addOtherClasses(Collection<String> feats, List<? extends CoreLabel> info,\r\n int loc, Clique c) {\r\n String addend = null;\r\n String pAnswer = info.get(loc - 1).get(AnswerAnnotation.class);\r\n String p2Answer = info.get(loc - 2).get(AnswerAnnotation.class);\r\n String p3Answer = info.get(loc - 3).get(AnswerAnnotation.class);\r\n String p4Answer = info.get(loc - 4).get(AnswerAnnotation.class);\r\n String p5Answer = info.get(loc - 5).get(AnswerAnnotation.class);\r\n String nAnswer = info.get(loc + 1).get(AnswerAnnotation.class);\r\n // cdm 2009: Is this really right? Do we not need to differentiate names that would collide???\r\n if (c == FeatureFactory.cliqueCpC) {\r\n addend = '|' + pAnswer;\r\n } else if (c == FeatureFactory.cliqueCp2C) {\r\n addend = '|' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCp3C) {\r\n addend = '|' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCp4C) {\r\n addend = '|' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCp5C) {\r\n addend = '|' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2C) {\r\n addend = '|' + pAnswer + '-' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4Cp5C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer + '-' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCnC) {\r\n addend = '|' + nAnswer;\r\n } else if (c == FeatureFactory.cliqueCpCnC) {\r\n addend = '|' + pAnswer + '-' + nAnswer;\r\n }\r\n if (addend == null) {\r\n return feats;\r\n }\r\n Collection<String> newFeats = new HashSet<String>();\r\n for (String feat : feats) {\r\n String newFeat = feat + addend;\r\n newFeats.add(newFeat);\r\n }\r\n return newFeats;\r\n }", "private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }", "protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }", "protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }", "protected boolean check(String value, String regex) {\n\t\tPattern pattern = Pattern.compile(regex);\n\t\treturn pattern.matcher(value).matches();\n\t}" ]
Destroys an instance of the bean @param instance The instance
[ "@Override\n public void destroy(T instance, CreationalContext<T> creationalContext) {\n super.destroy(instance, creationalContext);\n try {\n getProducer().preDestroy(instance);\n // WELD-1010 hack?\n if (creationalContext instanceof CreationalContextImpl) {\n ((CreationalContextImpl<T>) creationalContext).release(this, instance);\n } else {\n creationalContext.release();\n }\n } catch (Exception e) {\n BeanLogger.LOG.errorDestroying(instance, this);\n BeanLogger.LOG.catchingDebug(e);\n }\n }" ]
[ "private void setMasterTempo(double newTempo) {\n double oldTempo = Double.longBitsToDouble(masterTempo.getAndSet(Double.doubleToLongBits(newTempo)));\n if ((getTempoMaster() != null) && (Math.abs(newTempo - oldTempo) > getTempoEpsilon())) {\n // This is a change in tempo, so report it to any registered listeners, and update our metronome if we are synced.\n if (isSynced()) {\n metronome.setTempo(newTempo);\n notifyBeatSenderOfChange();\n }\n deliverTempoChangedAnnouncement(newTempo);\n }\n }", "@NonNull public Context getContext() {\n if (searchView != null) {\n return searchView.getContext();\n } else if (supportView != null) {\n return supportView.getContext();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }", "protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\n }", "public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\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 }", "private ProjectFile handleSQLiteFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".sqlite\");\n\n try\n {\n Class.forName(\"org.sqlite.JDBC\");\n String url = \"jdbc:sqlite:\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseFileReader(), file);\n }\n\n if (tableNames.contains(\"PROJWBS\"))\n {\n Connection connection = null;\n try\n {\n Properties props = new Properties();\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n connection = DriverManager.getConnection(url, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(connection);\n addListeners(reader);\n return reader.read();\n }\n finally\n {\n if (connection != null)\n {\n connection.close();\n }\n }\n }\n\n if (tableNames.contains(\"ZSCHEDULEITEM\"))\n {\n return readProjectFile(new MerlinReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }", "public static final int getShort(byte[] data, int offset)\n {\n int result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "private boolean isEqual(FieldDescriptorDef first, FieldDescriptorDef second)\r\n {\r\n return first.getName().equals(second.getName()) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN)) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n }" ]
Returns an integer between interval @param min Minimum value @param max Maximum value @return int number
[ "public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\n }" ]
[ "@SuppressWarnings(\"unused\")\n public void setError(CharSequence error, Drawable icon) {\n mPhoneEdit.setError(error, icon);\n }", "List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps,\n\t\t\tList<MwDumpFile> onlineDumps) {\n\t\tList<MwDumpFile> result = new ArrayList<>(localDumps);\n\n\t\tHashSet<String> localDateStamps = new HashSet<>();\n\t\tfor (MwDumpFile dumpFile : localDumps) {\n\t\t\tlocalDateStamps.add(dumpFile.getDateStamp());\n\t\t}\n\t\tfor (MwDumpFile dumpFile : onlineDumps) {\n\t\t\tif (!localDateStamps.contains(dumpFile.getDateStamp())) {\n\t\t\t\tresult.add(dumpFile);\n\t\t\t}\n\t\t}\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\t\treturn result;\n\t}", "private String formatRelationList(List<Relation> value)\n {\n String result = null;\n\n if (value != null && value.size() != 0)\n {\n StringBuilder sb = new StringBuilder();\n for (Relation relation : value)\n {\n if (sb.length() != 0)\n {\n sb.append(m_delimiter);\n }\n\n sb.append(formatRelation(relation));\n }\n\n result = sb.toString();\n }\n\n return (result);\n }", "public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doDelete();\r\n mod.setModificationState(StateTransient.getInstance());\r\n }", "public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}", "protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }", "@Override\r\n public String upload(byte[] data, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(data);\r\n return sendUploadRequest(metaData, payload);\r\n }", "private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {\n if (tries >= 5) {\n throw new BindException(\"Unable to bind to several ports, most recently \" + relay.getPort() + \". Giving up\");\n }\n try {\n if (server.isStarted()) {\n relay.start();\n } else {\n throw new RuntimeException(\"Can't start SslRelay: server is not started (perhaps it was just shut down?)\");\n }\n } catch (BindException e) {\n // doh - the port is being used up, let's pick a new port\n LOG.info(\"Unable to bind to port %d, going to try port %d now\", relay.getPort(), relay.getPort() + 1);\n relay.setPort(relay.getPort() + 1);\n startRelayWithPortTollerance(server, relay, tries + 1);\n }\n }", "public int bindShader(GVRContext context, GVRShaderData material, String vertexDesc)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, material);\n }\n return nativeShader;\n }\n }" ]
A map of the header key value pairs. Keys are strings and values are either list of strings or a string. @param headers the header map
[ "@SuppressWarnings(\"unchecked\")\n public void setHeaders(final Map<String, Object> headers) {\n this.headers.clear();\n for (Map.Entry<String, Object> entry: headers.entrySet()) {\n if (entry.getValue() instanceof List) {\n List value = (List) entry.getValue();\n // verify they are all strings\n for (Object o: value) {\n Assert.isTrue(o instanceof String, o + \" is not a string it is a: '\" +\n o.getClass() + \"'\");\n }\n this.headers.put(entry.getKey(), (List<String>) entry.getValue());\n } else if (entry.getValue() instanceof String) {\n final List<String> value = Collections.singletonList((String) entry.getValue());\n this.headers.put(entry.getKey(), value);\n } else {\n throw new IllegalArgumentException(\"Only strings and list of strings may be headers\");\n }\n }\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 }", "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}", "public static String getParentDirectory(String filePath) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, filePath))\n return getURLParentDirectory(filePath);\n\n return new File(filePath).getParent();\n }", "private void stop() {\n\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\tif (mDownloadDispatchers[i] != null) {\n\t\t\t\tmDownloadDispatchers[i].quit();\n\t\t\t}\n\t\t}\n\t}", "public static String simpleTypeName(Object obj) {\n if (obj == null) {\n return \"null\";\n }\n\n return simpleTypeName(obj.getClass(), false);\n }", "public RedwoodConfiguration loggingClass(final String classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces); } });\r\n return this;\r\n }", "private String visibility(Options opt, ProgramElementDoc e) {\n\treturn opt.showVisibility ? Visibility.get(e).symbol : \" \";\n }", "public static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }", "public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }" ]
The transaction will be executed with caching enabled. However, all newly cached values will be discarded as soon as the transaction is over. @since 2.1
[ "public <Result, Param extends Resource> Result execWithTemporaryCaching(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\tIgnoreValuesMemento memento = cacheAdapter.ignoreNewValues();\n\t\ttry {\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tmemento.done();\n\t\t}\n\t}" ]
[ "public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\n }", "public static void addToMediaStore(Context context, File file) {\n String[] path = new String[]{file.getPath()};\n MediaScannerConnection.scanFile(context, path, null, null);\n }", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n m_project.getProjectProperties().setFileApplication(\"Synchro\");\n m_project.getProjectProperties().setFileType(\"SP\");\n\n CustomFieldContainer fields = m_project.getCustomFields();\n fields.getCustomField(TaskField.TEXT1).setAlias(\"Code\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n processCalendars();\n processResources();\n processTasks();\n processPredecessors();\n\n return m_project;\n }", "public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }", "public int updateRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {\n\t\tlogger.debug(\"running raw update statement: {}\", statement);\n\t\tif (arguments.length > 0) {\n\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\tlogger.trace(\"update arguments: {}\", (Object) arguments);\n\t\t}\n\t\tCompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.UPDATE, noFieldTypes,\n\t\t\t\tDatabaseConnection.DEFAULT_RESULT_FLAGS, false);\n\t\ttry {\n\t\t\tassignStatementArguments(compiledStatement, arguments);\n\t\t\treturn compiledStatement.runUpdate();\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}", "public static double SquaredEuclidean(double[] x, double[] y) {\n double d = 0.0, u;\n\n for (int i = 0; i < x.length; i++) {\n u = x[i] - y[i];\n d += u * u;\n }\n\n return d;\n }", "private ClassDescriptor discoverDescriptor(Class clazz)\r\n {\r\n ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName());\r\n\r\n if (result == null)\r\n {\r\n Class superClass = clazz.getSuperclass();\r\n // only recurse if the superClass is not java.lang.Object\r\n if (superClass != null)\r\n {\r\n result = discoverDescriptor(superClass);\r\n }\r\n if (result == null)\r\n {\r\n // we're also checking the interfaces as there could be normal\r\n // mappings for them in the repository (using factory-class,\r\n // factory-method, and the property field accessor)\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n if ((interfaces != null) && (interfaces.length > 0))\r\n {\r\n for (int idx = 0; (idx < interfaces.length) && (result == null); idx++)\r\n {\r\n result = discoverDescriptor(interfaces[idx]);\r\n }\r\n }\r\n }\r\n\r\n if (result != null)\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tsynchronized (descriptorTable) {\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n \t\tdescriptorTable.put(clazz.getName(), result);\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \t}\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n }\r\n return result;\r\n }", "public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {\n URI uri = request.getURI();\n\n try {\n LOG.fine(\"CONNECT: \" + uri);\n InetAddrPort addrPort;\n // When logging, we'll attempt to send messages to hosts that don't exist\n if (uri.toString().endsWith(\".selenium.doesnotexist:443\")) {\n // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)\n addrPort = new InetAddrPort(443);\n } else {\n addrPort = new InetAddrPort(uri.toString());\n }\n\n if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {\n sendForbid(request, response, uri);\n } else {\n HttpConnection http_connection = request.getHttpConnection();\n http_connection.forceClose();\n\n HttpServer server = http_connection.getHttpServer();\n\n SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server);\n\n int port = listener.getPort();\n\n // Get the timeout\n int timeoutMs = 30000;\n Object maybesocket = http_connection.getConnection();\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n timeoutMs = s.getSoTimeout();\n }\n\n // Create the tunnel\n HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs);\n\n if (tunnel != null) {\n // TODO - need to setup semi-busy loop for IE.\n if (_tunnelTimeoutMs > 0) {\n tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n s.setSoTimeout(_tunnelTimeoutMs);\n }\n }\n tunnel.setTimeoutMs(timeoutMs);\n\n customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());\n request.getHttpConnection().setHttpTunnel(tunnel);\n response.setStatus(HttpResponse.__200_OK);\n response.setContentLength(0);\n }\n request.setHandled(true);\n }\n } catch (Exception e) {\n LOG.fine(\"error during handleConnect\", e);\n response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());\n }\n }", "public static String getLocalizedKey(Map<String, ?> propertiesMap, String key, Locale locale) {\n\n List<String> localizedKeys = CmsLocaleManager.getLocaleVariants(key, locale, true, false);\n for (String localizedKey : localizedKeys) {\n if (propertiesMap.containsKey(localizedKey)) {\n return localizedKey;\n }\n }\n return key;\n }" ]
Given an array of variable names, returns a JsonObject of values. @param dataMap an map containing variable names and their corresponding values names. @return a json object of values
[ "public JSONObject getJsonFormatted(Map<String, String> dataMap) {\r\n JSONObject oneRowJson = new JSONObject();\n\r\n for (int i = 0; i < outTemplate.length; i++) {\r\n oneRowJson.put(outTemplate[i], dataMap.get(outTemplate[i]));\r\n }\n\n\r\n return oneRowJson;\r\n }" ]
[ "public static vrid6[] get(nitro_service service) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tvrid6[] response = (vrid6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Span prefix(CharSequence rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n return prefix(Bytes.of(rowPrefix));\n }", "public static Map<String, IDiagramPlugin>\n getLocalPluginsRegistry(ServletContext context) {\n if (LOCAL == null) {\n LOCAL = initializeLocalPlugins(context);\n }\n return LOCAL;\n }", "public static Map<FieldType, String> getDefaultTaskFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(TaskField.UNIQUE_ID, \"task_id\");\n map.put(TaskField.GUID, \"guid\");\n map.put(TaskField.NAME, \"task_name\");\n map.put(TaskField.ACTUAL_DURATION, \"act_drtn_hr_cnt\");\n map.put(TaskField.REMAINING_DURATION, \"remain_drtn_hr_cnt\");\n map.put(TaskField.ACTUAL_WORK, \"act_work_qty\");\n map.put(TaskField.REMAINING_WORK, \"remain_work_qty\");\n map.put(TaskField.BASELINE_WORK, \"target_work_qty\");\n map.put(TaskField.BASELINE_DURATION, \"target_drtn_hr_cnt\");\n map.put(TaskField.DURATION, \"target_drtn_hr_cnt\");\n map.put(TaskField.CONSTRAINT_DATE, \"cstr_date\");\n map.put(TaskField.ACTUAL_START, \"act_start_date\");\n map.put(TaskField.ACTUAL_FINISH, \"act_end_date\");\n map.put(TaskField.LATE_START, \"late_start_date\");\n map.put(TaskField.LATE_FINISH, \"late_end_date\");\n map.put(TaskField.EARLY_START, \"early_start_date\");\n map.put(TaskField.EARLY_FINISH, \"early_end_date\");\n map.put(TaskField.REMAINING_EARLY_START, \"restart_date\");\n map.put(TaskField.REMAINING_EARLY_FINISH, \"reend_date\");\n map.put(TaskField.BASELINE_START, \"target_start_date\");\n map.put(TaskField.BASELINE_FINISH, \"target_end_date\");\n map.put(TaskField.CONSTRAINT_TYPE, \"cstr_type\");\n map.put(TaskField.PRIORITY, \"priority_type\");\n map.put(TaskField.CREATED, \"create_date\");\n map.put(TaskField.TYPE, \"duration_type\");\n map.put(TaskField.FREE_SLACK, \"free_float_hr_cnt\");\n map.put(TaskField.TOTAL_SLACK, \"total_float_hr_cnt\");\n map.put(TaskField.TEXT1, \"task_code\");\n map.put(TaskField.TEXT2, \"task_type\");\n map.put(TaskField.TEXT3, \"status_code\");\n map.put(TaskField.NUMBER1, \"rsrc_id\");\n\n return map;\n }", "public void saveFile(File file, String type)\n {\n try\n {\n Class<? extends ProjectWriter> fileClass = WRITER_MAP.get(type);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot write files of type: \" + type);\n }\n\n ProjectWriter writer = fileClass.newInstance();\n writer.write(m_projectFile, file);\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n }", "private void createTimephasedData(ProjectFile file, ResourceAssignment assignment, List<TimephasedWork> timephasedPlanned, List<TimephasedWork> timephasedComplete)\n {\n if (timephasedPlanned.isEmpty() && timephasedComplete.isEmpty())\n {\n Duration totalMinutes = assignment.getWork().convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n\n Duration workPerDay;\n\n if (assignment.getResource() == null || assignment.getResource().getType() == ResourceType.WORK)\n {\n workPerDay = totalMinutes.getDuration() == 0 ? totalMinutes : ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n int units = NumberHelper.getInt(assignment.getUnits());\n if (units != 100)\n {\n workPerDay = Duration.getInstance((workPerDay.getDuration() * units) / 100.0, workPerDay.getUnits());\n }\n }\n else\n {\n if (assignment.getVariableRateUnits() == null)\n {\n Duration workingDays = assignment.getCalendar().getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.DAYS);\n double units = NumberHelper.getDouble(assignment.getUnits());\n double unitsPerDayAsMinutes = (units * 60) / (workingDays.getDuration() * 100);\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n else\n {\n double unitsPerHour = NumberHelper.getDouble(assignment.getUnits());\n workPerDay = ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n Duration hoursPerDay = workPerDay.convertUnits(TimeUnit.HOURS, file.getProjectProperties());\n double unitsPerDayAsHours = (unitsPerHour * hoursPerDay.getDuration()) / 100;\n double unitsPerDayAsMinutes = unitsPerDayAsHours * 60;\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n }\n\n Duration overtimeWork = assignment.getOvertimeWork();\n if (overtimeWork != null && overtimeWork.getDuration() != 0)\n {\n Duration totalOvertimeMinutes = overtimeWork.convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n totalMinutes = Duration.getInstance(totalMinutes.getDuration() - totalOvertimeMinutes.getDuration(), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(assignment.getStart());\n tra.setAmountPerDay(workPerDay);\n tra.setModified(false);\n tra.setFinish(assignment.getFinish());\n tra.setTotalAmount(totalMinutes);\n timephasedPlanned.add(tra);\n }\n }", "public Set<Tag> getAncestorTags(Tag tag)\n {\n Set<Tag> ancestors = new HashSet<>();\n getAncestorTags(tag, ancestors);\n return ancestors;\n }", "public void remove(Identity oid)\r\n {\r\n //processQueue();\r\n if(oid != null)\r\n {\r\n removeTracedIdentity(oid);\r\n objectTable.remove(buildKey(oid));\r\n if(log.isDebugEnabled()) log.debug(\"Remove object \" + oid);\r\n }\r\n }", "public Duration getFinishSlack()\n {\n Duration finishSlack = (Duration) getCachedValue(TaskField.FINISH_SLACK);\n if (finishSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n finishSlack = DateHelper.getVariance(this, getEarlyFinish(), getLateFinish(), duration.getUnits());\n set(TaskField.FINISH_SLACK, finishSlack);\n }\n }\n return (finishSlack);\n }" ]
Returns list of files matches filters in specified directories @param directories which will using to find files @param fileFilter file filter @param dirFilter directory filter @return list of files matches filters in specified directories
[ "public static List<File> listFiles(File[] directories, IOFileFilter fileFilter, IOFileFilter dirFilter) {\n List<File> files = new ArrayList<>();\n for (File directory : directories) {\n if (!directory.isDirectory()) {\n continue;\n }\n Collection<File> filesInDirectory = FileUtils.listFiles(directory,\n fileFilter,\n dirFilter);\n files.addAll(filesInDirectory);\n }\n return files;\n }" ]
[ "private List getColumns(List fields)\r\n {\r\n ArrayList columns = new ArrayList();\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n columns.add(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n return columns;\r\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear()\n && d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }", "private void saveToBundleDescriptor() throws CmsException {\n\n if (null != m_descFile) {\n m_removeDescriptorOnCancel = false;\n updateBundleDescriptorContent();\n m_descFile.getFile().setContents(m_descContent.marshal());\n m_cms.writeFile(m_descFile.getFile());\n }\n }", "public static <T> Set<T> getSet(Collection<T> collection) {\n Set<T> set = new LinkedHashSet<T>();\n set.addAll(collection);\n\n return set;\n }", "public void fillTile(InternalTile tile, Envelope maxTileExtent)\n\t\t\tthrows GeomajasException {\n\t\tList<InternalFeature> origFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tfor (InternalFeature feature : origFeatures) {\n\t\t\tif (!addTileCode(tile, maxTileExtent, feature.getGeometry())) {\n\t\t\t\tlog.debug(\"add feature\");\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t}", "protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }", "public ParallelTaskBuilder prepareHttpHead(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.HEAD);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }", "protected String ensureTextColorFormat(String textColor) {\n String formatted = \"\";\n boolean mainColor = true;\n for (String style : textColor.split(\" \")) {\n if (mainColor) {\n // the main color\n if (!style.endsWith(\"-text\")) {\n style += \"-text\";\n }\n mainColor = false;\n } else {\n // the shading type\n if (!style.startsWith(\"text-\")) {\n style = \" text-\" + style;\n }\n }\n formatted += style;\n }\n return formatted;\n }" ]
Checks, if all values necessary for a specific pattern are valid. @return a flag, indicating if all values required for the pattern are valid.
[ "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 static void outputString(final HttpServletResponse response, final Object obj) {\n try {\n response.setContentType(\"text/javascript\");\n response.setCharacterEncoding(\"utf-8\");\n disableCache(response);\n response.getWriter().write(obj.toString());\n response.getWriter().flush();\n response.getWriter().close();\n } catch (IOException e) {\n }\n }", "@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 lbmonbindings_servicegroup_binding[] get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonbindings_servicegroup_binding obj = new lbmonbindings_servicegroup_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonbindings_servicegroup_binding response[] = (lbmonbindings_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void delete(final String referenceId) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.equal(root.get(\"referenceId\"), referenceId));\n getSession().createQuery(delete).executeUpdate();\n }", "public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }", "public static void main(String args[]) throws Exception {\n final StringBuffer buffer = new StringBuffer(\"The lazy fox\");\n Thread t1 = new Thread() {\n public void run() {\n synchronized(buffer) {\n buffer.delete(0,4);\n buffer.append(\" in the middle\");\n System.err.println(\"Middle\");\n try { Thread.sleep(4000); } catch(Exception e) {}\n buffer.append(\" of fall\");\n System.err.println(\"Fall\");\n }\n }\n };\n Thread t2 = new Thread() {\n public void run() {\n try { Thread.sleep(1000); } catch(Exception e) {}\n buffer.append(\" jump over the fence\");\n System.err.println(\"Fence\");\n }\n };\n t1.start();\n t2.start();\n\n t1.join();\n t2.join();\n System.err.println(buffer);\n }", "public static base_response flush(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup flushresource = new cachecontentgroup();\n\t\tflushresource.name = resource.name;\n\t\tflushresource.query = resource.query;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.selectorvalue = resource.selectorvalue;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) {\n return buildFilesStream\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath()))\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath()))\n .map(org.jfrog.hudson.pipeline.types.File::new)\n .distinct()\n .collect(Collectors.toList());\n }", "public boolean decompose(DMatrixRMaj mat , int indexStart , int n ) {\n double m[] = mat.data;\n\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = m[indexStart+i*mat.numCols+j];\n\n int iEl = i*n;\n int jEl = j*n;\n int end = iEl+i;\n // k = 0:i-1\n for( ; iEl<end; iEl++,jEl++ ) {\n// sum -= el[i*n+k]*el[j*n+k];\n sum -= el[iEl]*el[jEl];\n }\n\n if( i == j ) {\n // is it positive-definate?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n el[i*n+i] = el_ii;\n m[indexStart+i*mat.numCols+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n double v = sum*div_el_ii;\n el[j*n+i] = v;\n m[indexStart+j*mat.numCols+i] = v;\n }\n }\n }\n\n return true;\n }" ]
Harvest any values that may have been returned during the execution of a procedure. @param proc the procedure descriptor that provides info about the procedure that was invoked. @param obj the object that was persisted @param stmt the statement that was used to persist the object. @throws PersistenceBrokerSQLException if a problem occurs.
[ "private void harvestReturnValues(\r\n ProcedureDescriptor proc,\r\n Object obj,\r\n PreparedStatement stmt)\r\n throws PersistenceBrokerSQLException\r\n {\r\n // If the procedure descriptor is null or has no return values or\r\n // if the statement is not a callable statment, then we're done.\r\n if ((proc == null) || (!proc.hasReturnValues()))\r\n {\r\n return;\r\n }\r\n\r\n // Set up the callable statement\r\n CallableStatement callable = (CallableStatement) stmt;\r\n\r\n // This is the index that we'll use to harvest the return value(s).\r\n int index = 0;\r\n\r\n // If the proc has a return value, then try to harvest it.\r\n if (proc.hasReturnValue())\r\n {\r\n\r\n // Increment the index\r\n index++;\r\n\r\n // Harvest the value.\r\n this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);\r\n }\r\n\r\n // Check each argument. If it's returned by the procedure,\r\n // then harvest the value.\r\n Iterator iter = proc.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n index++;\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);\r\n }\r\n }\r\n }" ]
[ "public FileModel getChildFile(ArchiveModel archiveModel, String filePath)\n {\n filePath = FilenameUtils.separatorsToUnix(filePath);\n StringTokenizer stk = new StringTokenizer(filePath, \"/\");\n\n FileModel currentFileModel = archiveModel;\n while (stk.hasMoreTokens() && currentFileModel != null)\n {\n String pathElement = stk.nextToken();\n\n currentFileModel = findFileModel(currentFileModel, pathElement);\n }\n return currentFileModel;\n }", "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }", "protected final void setDerivedEndType() {\n\n m_endType = getPatternType().equals(PatternType.NONE) || getPatternType().equals(PatternType.INDIVIDUAL)\n ? EndType.SINGLE\n : null != getSeriesEndDate() ? EndType.DATE : EndType.TIMES;\n }", "public static aaauser_aaagroup_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_aaagroup_binding obj = new aaauser_aaagroup_binding();\n\t\tobj.set_username(username);\n\t\taaauser_aaagroup_binding response[] = (aaauser_aaagroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response enable(nitro_service client, String id) throws Exception {\n\t\tInterface enableresource = new Interface();\n\t\tenableresource.id = id;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public double getAccruedInterest(LocalDate date, AnalyticModel model) {\n\t\tint periodIndex=schedule.getPeriodIndex(date);\n\t\tPeriod period=schedule.getPeriod(periodIndex);\n\t\tDayCountConvention dcc= schedule.getDaycountconvention();\n\t\tdouble accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);\n\t\treturn accruedInterest;\n\t}", "private synchronized HostServerGroupEffect getMappableDomainEffect(PathAddress address, String key,\n Map<String, Set<String>> map, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = map.get(key);\n return mapped != null ? HostServerGroupEffect.forDomain(address, mapped)\n : HostServerGroupEffect.forUnassignedDomain(address);\n }", "public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void setSizes(Collection<Size> sizes) {\r\n for (Size size : sizes) {\r\n if (size.getLabel() == Size.SMALL) {\r\n smallSize = size;\r\n } else if (size.getLabel() == Size.SQUARE) {\r\n squareSize = size;\r\n } else if (size.getLabel() == Size.THUMB) {\r\n thumbnailSize = size;\r\n } else if (size.getLabel() == Size.MEDIUM) {\r\n mediumSize = size;\r\n } else if (size.getLabel() == Size.LARGE) {\r\n largeSize = size;\r\n } else if (size.getLabel() == Size.LARGE_1600) {\r\n large1600Size = size;\r\n } else if (size.getLabel() == Size.LARGE_2048) {\r\n large2048Size = size;\r\n } else if (size.getLabel() == Size.ORIGINAL) {\r\n originalSize = size;\r\n } else if (size.getLabel() == Size.SQUARE_LARGE) {\r\n squareLargeSize = size;\r\n } else if (size.getLabel() == Size.SMALL_320) {\r\n small320Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_640) {\r\n medium640Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_800) {\r\n medium800Size = size;\r\n } else if (size.getLabel() == Size.VIDEO_PLAYER) {\r\n videoPlayer = size;\r\n } else if (size.getLabel() == Size.SITE_MP4) {\r\n siteMP4 = size;\r\n } else if (size.getLabel() == Size.VIDEO_ORIGINAL) {\r\n videoOriginal = size;\r\n }\r\n else if (size.getLabel() == Size.MOBILE_MP4) {\r\n \tmobileMP4 = size;\r\n }\r\n else if (size.getLabel() == Size.HD_MP4) {\r\n \thdMP4 = size;\r\n }\r\n }\r\n }" ]
Waits until all pending operations are complete and closes this repository. @param failureCauseSupplier the {@link Supplier} that creates a new {@link CentralDogmaException} which will be used to fail the operations issued after this method is called
[ "void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\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 static void resetNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).reset();\n\t}", "private Map<Integer, Integer> getNodeIdToPrimaryCount(Cluster cluster) {\n Map<Integer, Integer> nodeIdToPrimaryCount = Maps.newHashMap();\n for(Node node: cluster.getNodes()) {\n nodeIdToPrimaryCount.put(node.getId(), node.getPartitionIds().size());\n }\n\n return nodeIdToPrimaryCount;\n }", "public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}", "public InputStream getAvatar() {\n URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n return response.getBody();\n }", "public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }", "public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }", "public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }", "private void updateDateTimeFormats(ProjectProperties properties)\n {\n String[] timePatterns = getTimePatterns(properties);\n String[] datePatterns = getDatePatterns(properties);\n String[] dateTimePatterns = getDateTimePatterns(properties, timePatterns);\n\n m_dateTimeFormat.applyPatterns(dateTimePatterns);\n m_dateFormat.applyPatterns(datePatterns);\n m_timeFormat.applyPatterns(timePatterns);\n\n m_dateTimeFormat.setLocale(m_locale);\n m_dateFormat.setLocale(m_locale);\n\n m_dateTimeFormat.setNullText(m_nullText);\n m_dateFormat.setNullText(m_nullText);\n m_timeFormat.setNullText(m_nullText);\n\n m_dateTimeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n m_timeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n }" ]
Boyer Moore scan that proceeds forwards from the end of the file looking for the first LOCSIG
[ "private static long scanForLocSig(FileChannel channel) throws IOException {\n\n channel.position(0);\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long end = channel.size();\n while (channel.position() <= end) {\n\n read(bb, channel);\n\n int bufferPos = 0;\n while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the size of the pattern is static\n // b) the pattern is static and has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Outer switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid local file record\n long startLocRecord = channel.position() - bb.limit() + bufferPos;\n long currentPos = channel.position();\n if (validateLocalFileRecord(channel, startLocRecord, -1)) {\n return startLocRecord;\n }\n // Restore position in case it shifted\n channel.position(currentPos);\n\n // wasn't a valid local file record; continue scan\n bufferPos += 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos + patternPos) - Byte.MIN_VALUE;\n bufferPos += LOC_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos += 4;\n }\n }\n }\n\n return -1;\n }" ]
[ "private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException {\n if (shouldWriteDecoratorAndElements(model)) {\n writer.writeStartElement(decoratorElement);\n persistChildren(writer, model);\n writer.writeEndElement();\n }\n }", "public static base_response update(nitro_service client, csparameter resource) throws Exception {\n\t\tcsparameter updateresource = new csparameter();\n\t\tupdateresource.stateupdate = resource.stateupdate;\n\t\treturn updateresource.update_resource(client);\n\t}", "private String fixSpecials(final String inString) {\n\t\tStringBuilder tmp = new StringBuilder();\n\n\t\tfor (int i = 0; i < inString.length(); i++) {\n\t\t\tchar chr = inString.charAt(i);\n\n\t\t\tif (isSpecial(chr)) {\n\t\t\t\ttmp.append(this.escape);\n\t\t\t\ttmp.append(chr);\n\t\t\t} else {\n\t\t\t\ttmp.append(chr);\n\t\t\t}\n\t\t}\n\n\t\treturn tmp.toString();\n\t}", "private void addCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = generateCheckBox(date, checkState);\n m_checkBoxes.add(cb);\n reInitLayoutElements();\n\n }", "public static base_response create(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey createresource = new sslfipskey();\n\t\tcreateresource.fipskeyname = resource.fipskeyname;\n\t\tcreateresource.modulus = resource.modulus;\n\t\tcreateresource.exponent = resource.exponent;\n\t\treturn createresource.perform_operation(client,\"create\");\n\t}", "public static String getDumpFileDirectoryName(\n\t\t\tDumpContentType dumpContentType, String dateStamp) {\n\t\treturn dumpContentType.toString().toLowerCase() + \"-\" + dateStamp;\n\t}", "@Override\n public void perform(Rewrite event, EvaluationContext context)\n {\n perform((GraphRewrite) event, context);\n }", "public CollectionRequest<Task> findByProject(String projectId) {\n \n String path = String.format(\"/projects/%s/tasks\", projectId);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\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 }" ]
Writes this JAR to an output stream, and closes the stream.
[ "public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }" ]
[ "public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }", "public static base_response add(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction addresource = new autoscaleaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.parameters = resource.parameters;\n\t\taddresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\taddresource.quiettime = resource.quiettime;\n\t\taddresource.vserver = resource.vserver;\n\t\treturn addresource.add_resource(client);\n\t}", "@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 InputStream sendRequest(String requestMethod,\n\t\t\tMap<String, String> parameters) throws IOException {\n\t\tString queryString = getQueryString(parameters);\n\t\tURL url = new URL(this.apiBaseUrl);\n\t\tHttpURLConnection connection = (HttpURLConnection) WebResourceFetcherImpl\n\t\t\t\t.getUrlConnection(url);\n\n\t\tsetupConnection(requestMethod, queryString, connection);\n\t\tOutputStreamWriter writer = new OutputStreamWriter(\n\t\t\t\tconnection.getOutputStream());\n\t\twriter.write(queryString);\n\t\twriter.flush();\n\t\twriter.close();\n\n\t\tint rc = connection.getResponseCode();\n\t\tif (rc != 200) {\n\t\t\tlogger.warn(\"Error: API request returned response code \" + rc);\n\t\t}\n\n\t\tInputStream iStream = connection.getInputStream();\n\t\tfillCookies(connection.getHeaderFields());\n\t\treturn iStream;\n\t}", "public void recordConnectionEstablishmentTimeUs(SocketDestination dest, long connEstTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordConnectionEstablishmentTimeUs(null, connEstTimeUs);\n recordConnectionEstablishmentTimeUs(null, connEstTimeUs);\n } else {\n this.connectionEstablishmentRequestCounter.addRequest(connEstTimeUs * Time.NS_PER_US);\n }\n }", "public static boolean sameNetwork(int prefixLength, InetAddress address1, InetAddress address2) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Comparing address \" + address1.getHostAddress() + \" with \" + address2.getHostAddress() + \", prefixLength=\" + prefixLength);\n }\n long prefixMask = 0xffffffffL & (-1 << (32 - prefixLength));\n return (addressToLong(address1) & prefixMask) == (addressToLong(address2) & prefixMask);\n }", "private void createResults(List<ISuite> suites,\n File outputDirectory,\n boolean onlyShowFailures) throws Exception\n {\n int index = 1;\n for (ISuite suite : suites)\n {\n int index2 = 1;\n for (ISuiteResult result : suite.getResults().values())\n {\n boolean failuresExist = result.getTestContext().getFailedTests().size() > 0\n || result.getTestContext().getFailedConfigurations().size() > 0;\n if (!onlyShowFailures || failuresExist)\n {\n VelocityContext context = createContext();\n context.put(RESULT_KEY, result);\n context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));\n context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));\n context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));\n context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));\n context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));\n String fileName = String.format(\"suite%d_test%d_%s\", index, index2, RESULTS_FILE);\n generateFile(new File(outputDirectory, fileName),\n RESULTS_FILE + TEMPLATE_EXTENSION,\n context);\n }\n ++index2;\n }\n ++index;\n }\n }", "public Metadata createMetadata(String templateName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.createMetadata(templateName, scope, metadata);\n }", "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }" ]
Check if the path to the property correspond to an association. @param targetTypeName the name of the entity containing the property @param pathWithoutAlias the path to the property WITHOUT aliases @return {@code true} if the property is an association or {@code false} otherwise
[ "public boolean isAssociation(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( pathWithoutAlias.get( 0 ) );\n\t\treturn propertyType.isAssociationType();\n\t}" ]
[ "final void begin() {\n if (this.properties.isDateRollEnforced()) {\n final Thread thread = new Thread(this,\n \"Log4J Time-based File-roll Enforcer\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }", "protected synchronized PersistenceBroker getBroker() throws PBFactoryException\r\n {\r\n /*\r\n mkalen:\r\n NB! The loadProfileIfNeeded must be called _before_ acquiring a broker below,\r\n since some methods in PersistenceBrokerImpl will keep a local reference to\r\n the descriptor repository that was active during broker construction/refresh\r\n (not checking the repository beeing used on method invocation).\r\n\r\n PersistenceBrokerImpl#getClassDescriptor(Class clazz) is such a method,\r\n that will throw ClassNotPersistenceCapableException on the following scenario:\r\n\r\n (All happens in one thread only):\r\n t0: activate per-thread metadata changes\r\n t1: load, register and activate profile A\r\n t2: load object O1 witch collection proxy C to objects {O2} (C stores profile key K(A))\r\n t3: close broker from t2\r\n t4: load, register and activate profile B\r\n t5: reference O1.getO2Collection, causing C loadData() to be invoked\r\n t6: C calls getBroker\r\n broker B is created and descriptorRepository is set to descriptors from profile B\r\n t7: C calls loadProfileIfNeeded, re-activating profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback (via QueryReferenceBroker) to getClassDescriptor\r\n the local descriptorRepository from t6 is used!\r\n => We will now try to query for {O2} with profile B\r\n (even though we re-activated profile A in t7)\r\n => ClassNotPersistenceCapableException\r\n\r\n Keeping loadProfileIfNeeded() at the start of this method changes everything from t6:\r\n t6: C calls loadProfileIfNeeded, re-activating profile A\r\n t7: C calls getBroker,\r\n broker B is created and descriptorRepository is set to descriptors from profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback to getClassDescriptor,\r\n the local descriptorRepository from t6 is used\r\n => We query for {O2} with profile A\r\n => All good :-)\r\n */\r\n if (_perThreadDescriptorsEnabled)\r\n {\r\n loadProfileIfNeeded();\r\n }\r\n\r\n PersistenceBroker broker;\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found or was closed, create a intern new one\r\n if (broker == null || broker.isClosed())\r\n {\r\n broker = PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n // signal that we use a new internal obtained PB instance to read the\r\n // data and that this instance have to be closed after use\r\n _needsClose = true;\r\n }\r\n return broker;\r\n }", "@Override\n public void registerChildren(ManagementResourceRegistration resourceRegistration) {\n // Register wildcard children last to prevent duplicate registration errors when override definitions exist\n for (ResourceDefinition rd : singletonChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n for (ResourceDefinition rd : wildcardChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n }", "private void centerOnCurrentItem() {\n if(!mPieData.isEmpty()) {\n PieModel current = mPieData.get(getCurrentItem());\n int targetAngle;\n\n if(mOpenClockwise) {\n targetAngle = (mIndicatorAngle - current.getStartAngle()) - ((current.getEndAngle() - current.getStartAngle()) / 2);\n if (targetAngle < 0 && mPieRotation > 0) targetAngle += 360;\n }\n else {\n targetAngle = current.getStartAngle() + (current.getEndAngle() - current.getStartAngle()) / 2;\n targetAngle += mIndicatorAngle;\n if (targetAngle > 270 && mPieRotation < 90) targetAngle -= 360;\n }\n\n mAutoCenterAnimator.setIntValues(targetAngle);\n mAutoCenterAnimator.setDuration(AUTOCENTER_ANIM_DURATION).start();\n\n }\n }", "private void parseJSON(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n JsonValue value = member.getValue();\n if (value.isNull()) {\n continue;\n }\n\n try {\n String memberName = member.getName();\n if (memberName.equals(\"id\")) {\n this.versionID = value.asString();\n } else if (memberName.equals(\"sha1\")) {\n this.sha1 = value.asString();\n } else if (memberName.equals(\"name\")) {\n this.name = value.asString();\n } else if (memberName.equals(\"size\")) {\n this.size = Double.valueOf(value.toString()).longValue();\n } else if (memberName.equals(\"created_at\")) {\n this.createdAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_at\")) {\n this.modifiedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"trashed_at\")) {\n this.trashedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_by\")) {\n JsonObject userJSON = value.asObject();\n String userID = userJSON.get(\"id\").asString();\n BoxUser user = new BoxUser(getAPI(), userID);\n this.modifiedBy = user.new Info(userJSON);\n }\n } catch (ParseException e) {\n assert false : \"A ParseException indicates a bug in the SDK.\";\n }\n }\n }", "public void saveFavorites(List<CmsFavoriteEntry> favorites) throws CmsException {\n\n try {\n JSONObject json = new JSONObject();\n JSONArray array = new JSONArray();\n for (CmsFavoriteEntry entry : favorites) {\n array.put(entry.toJson());\n }\n json.put(BASE_KEY, array);\n String data = json.toString();\n CmsUser user = readUser();\n user.setAdditionalInfo(ADDINFO_KEY, data);\n m_cms.writeUser(user);\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n\n }", "public static base_response unset(nitro_service client, ntpserver resource, String[] args) throws Exception{\n\t\tntpserver unsetresource = new ntpserver();\n\t\tunsetresource.serverip = resource.serverip;\n\t\tunsetresource.servername = resource.servername;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public List<TableProperty> getEditableColumns(CmsMessageBundleEditorTypes.EditMode mode) {\n\n return m_editorState.get(mode).getEditableColumns();\n }", "public int[] getVertexPointIndices() {\n int[] indices = new int[numVertices];\n for (int i = 0; i < numVertices; i++) {\n indices[i] = vertexPointIndices[i];\n }\n return indices;\n }" ]
Move the animation frame counter forward. @return boolean specifying if animation should continue or if loopCount has been fulfilled.
[ "boolean advance() {\n if (header.frameCount <= 0) {\n return false;\n }\n\n if(framePointer == getFrameCount() - 1) {\n loopIndex++;\n }\n\n if(header.loopCount != LOOP_FOREVER && loopIndex > header.loopCount) {\n return false;\n }\n\n framePointer = (framePointer + 1) % header.frameCount;\n return true;\n }" ]
[ "@Pure\n\tpublic static <T> Iterable<T> filterNull(Iterable<T> unfiltered) {\n\t\treturn Iterables.filter(unfiltered, Predicates.notNull());\n\t}", "private int[] readColorTable(int ncolors) {\n int nbytes = 3 * ncolors;\n int[] tab = null;\n byte[] c = new byte[nbytes];\n\n try {\n rawData.get(c);\n\n // Max size to avoid bounds checks.\n tab = new int[MAX_BLOCK_SIZE];\n int i = 0;\n int j = 0;\n while (i < ncolors) {\n int r = ((int) c[j++]) & 0xff;\n int g = ((int) c[j++]) & 0xff;\n int b = ((int) c[j++]) & 0xff;\n tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;\n }\n } catch (BufferUnderflowException e) {\n //if (Log.isLoggable(TAG, Log.DEBUG)) {\n Logger.d(TAG, \"Format Error Reading Color Table\", e);\n //}\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n\n return tab;\n }", "private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }", "private void readTableData(List<SynchroTable> tables, InputStream is) throws IOException\n {\n for (SynchroTable table : tables)\n {\n if (REQUIRED_TABLES.contains(table.getName()))\n {\n readTable(is, table);\n }\n }\n }", "private ProjectFile handleByteOrderMark(InputStream stream, int length, Charset charset) throws Exception\n {\n UniversalProjectReader reader = new UniversalProjectReader();\n reader.setSkipBytes(length);\n reader.setCharset(charset);\n return reader.read(stream);\n }", "private void ensurePKsFromHierarchy(ClassDescriptorDef classDef) throws ConstraintException\r\n {\r\n SequencedHashMap pks = new SequencedHashMap();\r\n\r\n for (Iterator it = classDef.getAllExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n ArrayList subPKs = subTypeDef.getPrimaryKeys();\r\n\r\n // check against already present PKs\r\n for (Iterator pkIt = subPKs.iterator(); pkIt.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)pkIt.next();\r\n FieldDescriptorDef foundPKDef = (FieldDescriptorDef)pks.get(fieldDef.getName());\r\n\r\n if (foundPKDef != null)\r\n {\r\n if (!isEqual(fieldDef, foundPKDef))\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required primary key \"+fieldDef.getName()+\r\n \" because its definitions in \"+fieldDef.getOwner().getName()+\" and \"+\r\n foundPKDef.getOwner().getName()+\" differ\");\r\n }\r\n }\r\n else\r\n {\r\n pks.put(fieldDef.getName(), fieldDef);\r\n }\r\n }\r\n }\r\n\r\n ensureFields(classDef, pks.values());\r\n }", "public static responderpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy_binding obj = new responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tresponderpolicy_binding response = (responderpolicy_binding) obj.get_resource(service);\n\t\treturn response;\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 }", "public synchronized void maybeThrottle(int eventsSeen) {\n if (maxRatePerSecond > 0) {\n long now = time.milliseconds();\n try {\n rateSensor.record(eventsSeen, now);\n } catch (QuotaViolationException e) {\n // If we're over quota, we calculate how long to sleep to compensate.\n double currentRate = e.getValue();\n if (currentRate > this.maxRatePerSecond) {\n double excessRate = currentRate - this.maxRatePerSecond;\n long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);\n if(logger.isDebugEnabled()) {\n logger.debug(\"Throttler quota exceeded:\\n\" +\n \"eventsSeen \\t= \" + eventsSeen + \" in this call of maybeThrotte(),\\n\" +\n \"currentRate \\t= \" + currentRate + \" events/sec,\\n\" +\n \"maxRatePerSecond \\t= \" + this.maxRatePerSecond + \" events/sec,\\n\" +\n \"excessRate \\t= \" + excessRate + \" events/sec,\\n\" +\n \"sleeping for \\t\" + sleepTimeMs + \" ms to compensate.\\n\" +\n \"rateConfig.timeWindowMs() = \" + rateConfig.timeWindowMs());\n }\n if (sleepTimeMs > rateConfig.timeWindowMs()) {\n logger.warn(\"Throttler sleep time (\" + sleepTimeMs + \" ms) exceeds \" +\n \"window size (\" + rateConfig.timeWindowMs() + \" ms). This will likely \" +\n \"result in not being able to honor the rate limit accurately.\");\n // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size\n // too high could cause this problem.\n }\n time.sleep(sleepTimeMs);\n } else if (logger.isDebugEnabled()) {\n logger.debug(\"Weird. Got QuotaValidationException but measured rate not over rateLimit: \" +\n \"currentRate = \" + currentRate + \" , rateLimit = \" + this.maxRatePerSecond);\n }\n }\n }\n }" ]