idx int32 46 1.86M | input stringlengths 321 6.6k | target stringlengths 9 1.24k |
|---|---|---|
123,709 | final DeleteCommentResult executeDeleteComment(DeleteCommentRequest deleteCommentRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(deleteCommentRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<DeleteCommentRequest> request = null;<NEW_LINE>Response<DeleteCommentResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new DeleteCommentRequestProtocolMarshaller(protocolFactory).marshall<MASK><NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "WorkDocs");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteComment");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<DeleteCommentResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteCommentResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | (super.beforeMarshalling(deleteCommentRequest)); |
1,479,031 | protected int diffModuleDef(JCModuleDecl oldT, JCModuleDecl newT, int[] bounds) {<NEW_LINE>int localPointer = bounds[0];<NEW_LINE>int[] qualBounds = getBounds(oldT.qualId);<NEW_LINE>if (oldT.getModuleType() == newT.getModuleType()) {<NEW_LINE>copyTo(localPointer, qualBounds[0]);<NEW_LINE>} else {<NEW_LINE>if (oldT.getModuleType() == ModuleTree.ModuleKind.OPEN) {<NEW_LINE>// removing "open":<NEW_LINE>moveFwdToToken(tokenSequence, localPointer, JavaTokenId.OPEN);<NEW_LINE>copyTo(localPointer, tokenSequence.offset());<NEW_LINE>} else {<NEW_LINE>copyTo(localPointer, qualBounds[0]);<NEW_LINE>printer.print("open ");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>localPointer = diffTree(oldT.qualId, newT.qualId, qualBounds);<NEW_LINE>int insertHint = oldT.directives.isEmpty() ? endPos(oldT) - 1 : oldT.directives.get(<MASK><NEW_LINE>tokenSequence.move(insertHint);<NEW_LINE>tokenSequence.moveNext();<NEW_LINE>insertHint = moveBackToToken(tokenSequence, insertHint, JavaTokenId.LBRACE) + 1;<NEW_LINE>int old = printer.indent();<NEW_LINE>PositionEstimator est = EstimatorFactory.members(oldT.directives, newT.directives, diffContext);<NEW_LINE>localPointer = copyUpTo(localPointer, insertHint);<NEW_LINE>// diff inner comments<NEW_LINE>insertHint = diffInnerComments(oldT, newT, insertHint);<NEW_LINE>localPointer = diffList(oldT.directives, newT.directives, insertHint, est, Measure.REAL_MEMBER, printer);<NEW_LINE>printer.undent(old);<NEW_LINE>if (localPointer != -1 && localPointer < origText.length()) {<NEW_LINE>if (origText.charAt(localPointer) == '}') {<NEW_LINE>// another stupid hack<NEW_LINE>printer.toLeftMargin();<NEW_LINE>}<NEW_LINE>copyTo(localPointer, bounds[1]);<NEW_LINE>}<NEW_LINE>return bounds[1];<NEW_LINE>} | 0).getStartPosition() - 1; |
168,539 | protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {<NEW_LINE>Parser parser = new Parser(PATTERN, (String) msg);<NEW_LINE>if (!parser.matches()) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());<NEW_LINE>if (deviceSession == null) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>Position position = new Position(getProtocolName());<NEW_LINE>position.setDeviceId(deviceSession.getDeviceId());<NEW_LINE>int time = parser.nextInt();<NEW_LINE>DateBuilder dateBuilder = new DateBuilder(new Date());<NEW_LINE>dateBuilder.setHour(time / 100 / 100);<NEW_LINE>dateBuilder.setMinute(time / 100 % 100);<NEW_LINE>dateBuilder.setSecond(time % 100);<NEW_LINE>position.setTime(dateBuilder.getDate());<NEW_LINE>position.setValid(true);<NEW_LINE>position.setLatitude(parser.nextCoordinate());<NEW_LINE>position.setLongitude(parser.nextCoordinate());<NEW_LINE>position.setSpeed(parser.nextDouble(0));<NEW_LINE>position.setCourse(parser.nextDouble(0));<NEW_LINE>position.set("carrid", parser.next());<NEW_LINE>position.set("serdis", parser.next());<NEW_LINE>position.set("rsrp", parser.nextInt());<NEW_LINE>position.set(Position.KEY_RSSI, parser.nextInt());<NEW_LINE>position.set(<MASK><NEW_LINE>position.set("ecio", parser.next());<NEW_LINE>return position;<NEW_LINE>} | "rsrq", parser.nextInt()); |
1,105,331 | public boolean fromXmlNode(final I_AD_MigrationStep step, final Element stepNode) {<NEW_LINE>step.setSeqNo(Integer.parseInt(stepNode.getAttribute(NODE_SeqNo)));<NEW_LINE>step.setStepType(stepNode.getAttribute(NODE_StepType));<NEW_LINE>step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied);<NEW_LINE>final Node commentNode = stepNode.getElementsByTagName(NODE_Comments).item(0);<NEW_LINE>if (commentNode != null) {<NEW_LINE>step.setComments(MigrationHandler.getElementText(commentNode));<NEW_LINE>}<NEW_LINE>if (X_AD_MigrationStep.STEPTYPE_ApplicationDictionary.equals(step.getStepType())) {<NEW_LINE>final NodeList children = stepNode.getElementsByTagName(NODE_PO);<NEW_LINE>for (int i = 0; i < children.getLength(); i++) {<NEW_LINE>final Element poNode = (Element) children.item(i);<NEW_LINE>step.setAction(poNode.getAttribute(NODE_Action));<NEW_LINE>step.setTableName(poNode.getAttribute(NODE_Table));<NEW_LINE>step.setAD_Table_ID(Integer.parseInt(<MASK><NEW_LINE>step.setRecord_ID(Integer.parseInt(poNode.getAttribute(NODE_Record_ID)));<NEW_LINE>InterfaceWrapperHelper.save(step);<NEW_LINE>final NodeList data = poNode.getElementsByTagName(NODE_Data);<NEW_LINE>for (int j = 0; j < data.getLength(); j++) {<NEW_LINE>final Properties ctx = InterfaceWrapperHelper.getCtx(step);<NEW_LINE>final String trxName = InterfaceWrapperHelper.getTrxName(step);<NEW_LINE>final I_AD_MigrationData stepData = InterfaceWrapperHelper.create(ctx, I_AD_MigrationData.class, trxName);<NEW_LINE>stepData.setAD_MigrationStep(step);<NEW_LINE>final Element dataElement = (Element) data.item(j);<NEW_LINE>Services.get(IXMLHandlerFactory.class).getHandler(I_AD_MigrationData.class).fromXmlNode(stepData, dataElement);<NEW_LINE>InterfaceWrapperHelper.save(stepData);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} else if (X_AD_MigrationStep.STEPTYPE_SQLStatement.equals(step.getStepType())) {<NEW_LINE>step.setDBType(stepNode.getAttribute(NODE_DBType));<NEW_LINE>final Node sqlNode = stepNode.getElementsByTagName(NODE_SQLStatement).item(0);<NEW_LINE>if (sqlNode != null) {<NEW_LINE>step.setSQLStatement(MigrationHandler.getElementText(sqlNode));<NEW_LINE>}<NEW_LINE>final Node rollbackNode = stepNode.getElementsByTagName(NODE_RollbackStatement).item(0);<NEW_LINE>if (rollbackNode != null) {<NEW_LINE>step.setRollbackStatement(MigrationHandler.getElementText(rollbackNode));<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>throw new AdempiereException("Unknown StepType: " + step.getStepType());<NEW_LINE>}<NEW_LINE>InterfaceWrapperHelper.save(step);<NEW_LINE>logger.info("Imported step: " + Services.get(IMigrationBL.class).getSummary(step));<NEW_LINE>return true;<NEW_LINE>} | poNode.getAttribute(NODE_AD_Table_ID))); |
1,569,197 | public void deleteAs2KeysId(Integer id) throws ApiException {<NEW_LINE>Object localVarPostBody = null;<NEW_LINE>// verify the required parameter 'id' is set<NEW_LINE>if (id == null) {<NEW_LINE>throw new ApiException(400, "Missing the required parameter 'id' when calling deleteAs2KeysId");<NEW_LINE>}<NEW_LINE>// create path and map variables<NEW_LINE>String localVarPath = "/as2_keys/{id}".replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));<NEW_LINE>// query params<NEW_LINE>List<Pair> localVarQueryParams = new ArrayList<Pair>();<NEW_LINE>Map<String, String> localVarHeaderParams = new HashMap<String, String>();<NEW_LINE>Map<String, Object> localVarFormParams = new HashMap<String, Object>();<NEW_LINE>final String[] localVarAccepts = {};<NEW_LINE>final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);<NEW_LINE>final String[] localVarContentTypes = {};<NEW_LINE>final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);<NEW_LINE>String[] <MASK><NEW_LINE>apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);<NEW_LINE>} | localVarAuthNames = new String[] {}; |
561,756 | private void checkInstalledPluginDependencies(PluginDescriptor pluginDescriptor) {<NEW_LINE>final Set<PluginId> notInstalled = new HashSet<>();<NEW_LINE>final Set<PluginId> disabledIds = new HashSet<>();<NEW_LINE>final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();<NEW_LINE>final PluginId[] optionalDependentPluginIds = pluginDescriptor.getOptionalDependentPluginIds();<NEW_LINE>for (PluginId id : dependentPluginIds) {<NEW_LINE>if (ArrayUtil.find(optionalDependentPluginIds, id) > -1)<NEW_LINE>continue;<NEW_LINE>final boolean disabled = ((InstalledPluginsTableModel) myPluginsModel).isDisabled(id);<NEW_LINE>final boolean enabled = ((InstalledPluginsTableModel) myPluginsModel).isEnabled(id);<NEW_LINE>if (!enabled && !disabled) {<NEW_LINE>notInstalled.add(id);<NEW_LINE>} else if (disabled) {<NEW_LINE>disabledIds.add(id);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (!notInstalled.isEmpty()) {<NEW_LINE>Messages.showWarningDialog("Plugin " + pluginDescriptor.getName() + " depends on unknown plugin" + (notInstalled.size() > 1 ? "s " : " ") + StringUtil.join(notInstalled, PluginId::toString, ", "), CommonBundle.getWarningTitle());<NEW_LINE>}<NEW_LINE>if (!disabledIds.isEmpty()) {<NEW_LINE>final Set<PluginDescriptor> dependencies = new HashSet<>();<NEW_LINE>for (PluginDescriptor ideaPluginDescriptor : myPluginsModel.getAllPlugins()) {<NEW_LINE>if (disabledIds.contains(ideaPluginDescriptor.getPluginId())) {<NEW_LINE>dependencies.add(ideaPluginDescriptor);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>final String disabledPluginsMessage = "disabled plugin" + (dependencies.size(<MASK><NEW_LINE>String message = "Plugin " + pluginDescriptor.getName() + " depends on " + disabledPluginsMessage + StringUtil.join(dependencies, PluginDescriptor::getName, ", ") + ". Enable " + disabledPluginsMessage.trim() + "?";<NEW_LINE>if (Messages.showOkCancelDialog(getMainPanel(), message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()) == Messages.OK) {<NEW_LINE>((InstalledPluginsTableModel) myPluginsModel).enableRows(dependencies.toArray(new PluginDescriptor[dependencies.size()]), Boolean.TRUE);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ) > 1 ? "s " : " "); |
1,364,974 | final CancelExportTaskResult executeCancelExportTask(CancelExportTaskRequest cancelExportTaskRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(cancelExportTaskRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<CancelExportTaskRequest> request = null;<NEW_LINE>Response<CancelExportTaskResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new CancelExportTaskRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(cancelExportTaskRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "CloudWatch Logs");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CancelExportTask");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<CancelExportTaskResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new CancelExportTaskResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | awsRequestMetrics.endEvent(Field.RequestMarshallTime); |
1,673,922 | private void scheduleOnce() {<NEW_LINE>try {<NEW_LINE>taskScheduler.checkIfShutdown();<NEW_LINE>} catch (IllegalStateException e) {<NEW_LINE>logger.warn("Shutting down due to taskScheduler being shutdown");<NEW_LINE>shutdown();<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>// check if next scheduling iteration is actually needed right away<NEW_LINE>final <MASK><NEW_LINE>addPendingRunningTasks();<NEW_LINE>removeTasks();<NEW_LINE>setTaskReadyTimes();<NEW_LINE>final boolean newLeaseExists = leaseBlockingQueue.peek() != null;<NEW_LINE>if (qModified || newLeaseExists || doNextIteration()) {<NEW_LINE>taskScheduler.setTaskToClusterAutoScalerMapGetter(taskToClusterAutoScalerMapGetter);<NEW_LINE>lastSchedIterationAt.set(System.currentTimeMillis());<NEW_LINE>if (preHook != null)<NEW_LINE>preHook.call();<NEW_LINE>List<VirtualMachineLease> currentLeases = new ArrayList<>();<NEW_LINE>leaseBlockingQueue.drainTo(currentLeases);<NEW_LINE>final SchedulingResult schedulingResult = taskScheduler.scheduleOnce(taskQueue, currentLeases);<NEW_LINE>// mark end of scheduling iteration before assigning tasks.<NEW_LINE>taskQueue.getUsageTracker().reset();<NEW_LINE>assignTasks(schedulingResult, taskScheduler);<NEW_LINE>schedulingResultCallback.call(schedulingResult);<NEW_LINE>doPendingActions();<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>SchedulingResult result = new SchedulingResult(null);<NEW_LINE>result.addException(e);<NEW_LINE>schedulingResultCallback.call(result);<NEW_LINE>}<NEW_LINE>} | boolean qModified = taskQueue.reset(); |
1,097,448 | public synchronized void sttEventReceived(STTEvent sttEvent) {<NEW_LINE>if (sttEvent instanceof SpeechRecognitionEvent) {<NEW_LINE>if (!isSTTServerAborting) {<NEW_LINE>SpeechRecognitionEvent sre = (SpeechRecognitionEvent) sttEvent;<NEW_LINE>String question = sre.getTranscript();<NEW_LINE>try {<NEW_LINE>toggleProcessing(false);<NEW_LINE>say(hli.interpret(locale, question));<NEW_LINE>} catch (InterpretationException e) {<NEW_LINE><MASK><NEW_LINE>if (msg != null) {<NEW_LINE>say(msg);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>abortSTT();<NEW_LINE>}<NEW_LINE>} else if (sttEvent instanceof RecognitionStartEvent) {<NEW_LINE>toggleProcessing(true);<NEW_LINE>} else if (sttEvent instanceof RecognitionStopEvent) {<NEW_LINE>toggleProcessing(false);<NEW_LINE>} else if (sttEvent instanceof SpeechRecognitionErrorEvent) {<NEW_LINE>if (!isSTTServerAborting) {<NEW_LINE>abortSTT();<NEW_LINE>toggleProcessing(false);<NEW_LINE>SpeechRecognitionErrorEvent sre = (SpeechRecognitionErrorEvent) sttEvent;<NEW_LINE>String text = i18nProvider.getText(bundle, "error.stt-error", null, locale);<NEW_LINE>say(text == null ? sre.getMessage() : text.replace("{0}", sre.getMessage()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | String msg = e.getMessage(); |
1,319,387 | public ScheduleTime lastScheduleTime(Instant currentScheduleTime) {<NEW_LINE>// estimate interval (doesn't have to be exact value)<NEW_LINE>Instant next = next(currentScheduleTime);<NEW_LINE>Instant nextNext = next(next);<NEW_LINE>long estimatedInterval = nextNext.getEpochSecond<MASK><NEW_LINE>// get an aligned time that is before currentScheduleTime<NEW_LINE>Instant before = currentScheduleTime.minusSeconds(estimatedInterval);<NEW_LINE>do {<NEW_LINE>before = before.minusSeconds(estimatedInterval);<NEW_LINE>} while (!before.isBefore(currentScheduleTime));<NEW_LINE>// before is before currentScheduleTime but not sure how many times before. calculate it.<NEW_LINE>Instant nextOfBefore = next(before);<NEW_LINE>while (nextOfBefore.isBefore(currentScheduleTime)) {<NEW_LINE>before = nextOfBefore;<NEW_LINE>nextOfBefore = next(before);<NEW_LINE>}<NEW_LINE>// nextOfBefore is same with currentScheduleTime or after currentScheduleTime. nextOfBefore is next of before. done.<NEW_LINE>return ScheduleTime.of(before, before.plusSeconds(delaySeconds));<NEW_LINE>} | () - next.getEpochSecond(); |
909,403 | public void update() {<NEW_LINE>super.update();<NEW_LINE>BuildingItem toRemove = null;<NEW_LINE>for (BuildingItem i : buildersInAction) {<NEW_LINE>i.update();<NEW_LINE>if (i.isDone) {<NEW_LINE>toRemove = i;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (toRemove != null) {<NEW_LINE>buildersInAction.remove(toRemove);<NEW_LINE>}<NEW_LINE>if (worldObj.isRemote) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (itemBlueprint != null && ItemBlueprint.getId(itemBlueprint) != null && bluePrintBuilder == null) {<NEW_LINE>BlueprintBase bpt = ItemBlueprint.loadBlueprint(itemBlueprint);<NEW_LINE>if (bpt != null && bpt instanceof Blueprint) {<NEW_LINE>bpt = bpt.adjustToWorld(worldObj, pos, direction);<NEW_LINE>if (bpt != null) {<NEW_LINE>bluePrintBuilder = new BptBuilderBlueprint((Blueprint) bpt, worldObj, pos);<NEW_LINE>bptContext = bluePrintBuilder.getContext();<NEW_LINE>box.initialize(bluePrintBuilder);<NEW_LINE>sendNetworkUpdate();<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (laser == null && direction != null) {<NEW_LINE>Vec3d point5 = new Vec3d(0.5, 0.5, 0.5);<NEW_LINE>laser = new LaserData();<NEW_LINE>laser.head = Utils.convert(pos).add(point5);<NEW_LINE>laser.tail = laser.head.add(Utils<MASK><NEW_LINE>laser.isVisible = true;<NEW_LINE>sendNetworkUpdate();<NEW_LINE>}<NEW_LINE>if (initNBT != null) {<NEW_LINE>if (bluePrintBuilder != null) {<NEW_LINE>bluePrintBuilder.loadBuildStateToNBT(initNBT.getCompoundTag("builderState"), this);<NEW_LINE>}<NEW_LINE>initNBT = null;<NEW_LINE>}<NEW_LINE>} | .convert(direction, 0.5)); |
1,798,172 | public static void main(String[] args) {<NEW_LINE>MeterRegistry registry = SampleConfig.myMonitoringSystem();<NEW_LINE>LongTaskTimer timer = registry.more().longTaskTimer("longTaskTimer");<NEW_LINE>RandomEngine r = new MersenneTwister64(0);<NEW_LINE>Normal incomingRequests = new Normal(0, 1, r);<NEW_LINE>Normal duration = new Normal(30, 50, r);<NEW_LINE>AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());<NEW_LINE>Flux.interval(Duration.ofSeconds(1)).doOnEach(d -> latencyForThisSecond.set(duration.nextInt<MASK><NEW_LINE>final Map<LongTaskTimer.Sample, CountDownLatch> tasks = new ConcurrentHashMap<>();<NEW_LINE>// the potential for an "incoming request" every 10 ms<NEW_LINE>Flux.interval(Duration.ofSeconds(1)).doOnEach(d -> {<NEW_LINE>if (incomingRequests.nextDouble() + 0.4 > 0 && tasks.isEmpty()) {<NEW_LINE>int taskDur;<NEW_LINE>while ((taskDur = duration.nextInt()) < 0) ;<NEW_LINE>synchronized (tasks) {<NEW_LINE>tasks.put(timer.start(), new CountDownLatch(taskDur));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>synchronized (tasks) {<NEW_LINE>for (Map.Entry<LongTaskTimer.Sample, CountDownLatch> e : tasks.entrySet()) {<NEW_LINE>e.getValue().countDown();<NEW_LINE>if (e.getValue().getCount() == 0) {<NEW_LINE>e.getKey().stop();<NEW_LINE>tasks.remove(e.getKey());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}).blockLast();<NEW_LINE>} | ())).subscribe(); |
1,358,840 | private Object convertParameterizedType(Message<?> message, Type conversionHint) {<NEW_LINE>ObjectMapper objectMapper = this.getObjectMapper();<NEW_LINE>Object payload = message.getPayload();<NEW_LINE>try {<NEW_LINE>JavaType type = this.typeCache.get(conversionHint);<NEW_LINE>if (type == null) {<NEW_LINE>conversionHint = FunctionTypeUtils.isMessage(conversionHint) ? FunctionTypeUtils.getImmediateGenericType(conversionHint, 0) : conversionHint;<NEW_LINE>type = objectMapper.getTypeFactory().constructType(conversionHint);<NEW_LINE>this.typeCache.put(conversionHint, type);<NEW_LINE>}<NEW_LINE>if (payload instanceof byte[]) {<NEW_LINE>return objectMapper.readValue((byte[]) payload, type);<NEW_LINE>} else if (payload instanceof String) {<NEW_LINE>return objectMapper.readValue((String) payload, type);<NEW_LINE>} else {<NEW_LINE>final JavaType typeToUse = type;<NEW_LINE>if (payload instanceof Collection) {<NEW_LINE>Collection<?> collection = (Collection<?>) ((Collection<?>) payload).stream().map(value -> {<NEW_LINE>try {<NEW_LINE>if (value instanceof byte[]) {<NEW_LINE>return objectMapper.readValue((byte[]) value, typeToUse.getContentType());<NEW_LINE>} else if (value instanceof String) {<NEW_LINE>return objectMapper.readValue((String) value, typeToUse.getContentType());<NEW_LINE>} else {<NEW_LINE>// fall back to simple type-conversion<NEW_LINE>// see https://github.com/spring-cloud/spring-cloud-stream/issues/1898<NEW_LINE>return objectMapper.convertValue(<MASK><NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>logger.error("Failed to convert payload " + value, e);<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>}).collect(Collectors.toList());<NEW_LINE>return collection;<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>throw new MessageConversionException("Cannot parse payload ", e);<NEW_LINE>}<NEW_LINE>} | value, typeToUse.getContentType()); |
1,641,721 | public CompletableFuture<Void> removeLedgerMetadata(long ledgerId, Version version) {<NEW_LINE>Optional<Long> existingVersion = Optional.empty();<NEW_LINE>if (Version.NEW == version) {<NEW_LINE>log.error("Request to delete ledger {} metadata with version set to the initial one", ledgerId);<NEW_LINE>return FutureUtil.failedFuture<MASK><NEW_LINE>} else if (Version.ANY != version) {<NEW_LINE>if (!(version instanceof LongVersion)) {<NEW_LINE>log.info("Not an instance of ZKVersion: {}", ledgerId);<NEW_LINE>return FutureUtil.failedFuture(new BKException.BKMetadataVersionException());<NEW_LINE>} else {<NEW_LINE>existingVersion = Optional.of(((LongVersion) version).getLongVersion());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return store.delete(getLedgerPath(ledgerId), existingVersion).thenRun(() -> {<NEW_LINE>// removed listener on ledgerId<NEW_LINE>Set<BookkeeperInternalCallbacks.LedgerMetadataListener> listenerSet = listeners.remove(ledgerId);<NEW_LINE>if (null != listenerSet) {<NEW_LINE>if (log.isDebugEnabled()) {<NEW_LINE>log.debug("Remove registered ledger metadata listeners on ledger {} after ledger is deleted.", ledgerId);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>if (log.isDebugEnabled()) {<NEW_LINE>log.debug("No ledger metadata listeners to remove from ledger {} when it's being deleted.", ledgerId);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | (new BKException.BKMetadataVersionException()); |
1,259,561 | protected void onAttachedToWindow() {<NEW_LINE>super.onAttachedToWindow();<NEW_LINE><MASK><NEW_LINE>emailView.setText(editor.email);<NEW_LINE>emailWatcher = new TextWatcher() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void beforeTextChanged(CharSequence s, int start, int count, int after) {<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onTextChanged(CharSequence s, int start, int before, int count) {<NEW_LINE>editor.email = s.toString();<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void afterTextChanged(Editable s) {<NEW_LINE>}<NEW_LINE>};<NEW_LINE>emailView.addTextChangedListener(emailWatcher);<NEW_LINE>saveButton.setOnClickListener(new OnClickListener() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onClick(View v) {<NEW_LINE>editor.email = emailView.getText().toString();<NEW_LINE>ContactsStorage storage = Flow.getService(FlowServices.CONTACTS_STORAGE, v.getContext());<NEW_LINE>// noinspection ConstantConditions<NEW_LINE>storage.save(editor.toContact());<NEW_LINE>Flow.get(v).set(new ListContactsScreen());<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | nameView.setText(editor.name); |
1,785,223 | private void fillAnalysisUser(UserConfig userConfig, AnalysisUser analysisUser, Map<String, WallProvider> blackListMap, ProblemReporter problemReporter) {<NEW_LINE>String tenant = analysisUser.getTenant();<NEW_LINE>String dbGroup = analysisUser.getDbGroup();<NEW_LINE>String blacklistStr = analysisUser.getBlacklist();<NEW_LINE>UserName userName = new UserName(userConfig.getName(), tenant);<NEW_LINE>if (this.userConfigMap.containsKey(userName)) {<NEW_LINE>throw new ConfigException("User [" + userName + "] has already existed");<NEW_LINE>}<NEW_LINE>if (StringUtil.isEmpty(dbGroup)) {<NEW_LINE>throw new ConfigException("User [" + userName + "]'s dbGroup is empty");<NEW_LINE>}<NEW_LINE>WallProvider wallProvider = getWallProvider(blackListMap, problemReporter, blacklistStr, userName);<NEW_LINE>AnalysisUserConfig analysisUserConfig = new AnalysisUserConfig(userConfig, userName.<MASK><NEW_LINE>analysisUserConfig.setId(this.userId.incrementAndGet());<NEW_LINE>this.userConfigMap.put(userName, analysisUserConfig);<NEW_LINE>} | getTenant(), wallProvider, dbGroup); |
604,416 | void connectStopsToStreetNetwork() {<NEW_LINE>EncodingManager em = graph.getEncodingManager();<NEW_LINE>FlagEncoder footEncoder = em.getEncoder("foot");<NEW_LINE>final EdgeFilter filter = new DefaultSnapFilter(new FastestWeighting(footEncoder), em.getBooleanEncodedValue(Subnetwork.key("foot")));<NEW_LINE>for (Stop stop : feed.stops.values()) {<NEW_LINE>if (stop.location_type == 0) {<NEW_LINE>// Only stops. Not interested in parent stations for now.<NEW_LINE>Snap locationSnap = walkNetworkIndex.findClosest(stop.stop_lat, stop.stop_lon, filter);<NEW_LINE>Integer stopNode;<NEW_LINE>if (locationSnap.isValid()) {<NEW_LINE>stopNode = gtfsStorage.getStreetToPt().get(locationSnap.getClosestNode());<NEW_LINE>if (stopNode == null) {<NEW_LINE>stopNode = out.createNode();<NEW_LINE>indexBuilder.addToAllTilesOnLine(stopNode, stop.stop_lat, stop.stop_lon, stop.stop_lat, stop.stop_lon);<NEW_LINE>gtfsStorage.getPtToStreet().put(<MASK><NEW_LINE>gtfsStorage.getStreetToPt().put(locationSnap.getClosestNode(), stopNode);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>stopNode = out.createNode();<NEW_LINE>indexBuilder.addToAllTilesOnLine(stopNode, stop.stop_lat, stop.stop_lon, stop.stop_lat, stop.stop_lon);<NEW_LINE>}<NEW_LINE>gtfsStorage.getStationNodes().put(new GtfsStorage.FeedIdWithStopId(id, stop.stop_id), stopNode);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | stopNode, locationSnap.getClosestNode()); |
1,335,874 | private HttpRequest createRequest(ChannelHandlerContext ctx, io.netty.handler.codec.http.HttpRequest nettyRequest) {<NEW_LINE>// Attempt to map the netty method<NEW_LINE>HttpMethod method;<NEW_LINE>if (nettyRequest.method().equals(HEAD)) {<NEW_LINE>method = HttpMethod.GET;<NEW_LINE>} else {<NEW_LINE>try {<NEW_LINE>method = HttpMethod.valueOf(nettyRequest.method().name());<NEW_LINE>} catch (IllegalArgumentException e) {<NEW_LINE>ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.METHOD_NOT_ALLOWED));<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Attempt to decode parameters<NEW_LINE>try {<NEW_LINE>QueryStringDecoder decoder = new QueryStringDecoder(nettyRequest.uri());<NEW_LINE>HttpRequest req = new HttpRequest(<MASK><NEW_LINE>decoder.parameters().forEach((key, values) -> values.forEach(value -> req.addQueryParameter(key, value)));<NEW_LINE>nettyRequest.headers().entries().stream().filter(entry -> entry.getKey() != null).forEach(entry -> req.addHeader(entry.getKey(), entry.getValue()));<NEW_LINE>return req;<NEW_LINE>} catch (Exception e) {<NEW_LINE>ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));<NEW_LINE>LOG.log(Debug.getDebugLogLevel(), "Not possible to decode parameters.", e);<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>} | method, decoder.path()); |
800,218 | // Print method header and return the ERROR_RETURN string.<NEW_LINE>private String generateCPPMethodheader(BNFProduction p, Token t) {<NEW_LINE>StringBuffer sig = new StringBuffer();<NEW_LINE>String ret, params;<NEW_LINE>String method_name = p.getLhs();<NEW_LINE>boolean void_ret = false;<NEW_LINE>boolean ptr_ret = false;<NEW_LINE>codeGenerator.printTokenSetup(t);<NEW_LINE>ccol = 1;<NEW_LINE>String comment1 = codeGenerator.getLeadingComments(t);<NEW_LINE>cline = t.beginLine;<NEW_LINE>ccol = t.beginColumn;<NEW_LINE>sig.append(t.image);<NEW_LINE>if (t.kind == JavaCCParserConstants.VOID)<NEW_LINE>void_ret = true;<NEW_LINE>if (t.kind == JavaCCParserConstants.STAR)<NEW_LINE>ptr_ret = true;<NEW_LINE>for (int i = 1; i < p.getReturnTypeTokens().size(); i++) {<NEW_LINE>t = (Token) (p.getReturnTypeTokens<MASK><NEW_LINE>sig.append(codeGenerator.getStringToPrint(t));<NEW_LINE>if (t.kind == JavaCCParserConstants.VOID)<NEW_LINE>void_ret = true;<NEW_LINE>if (t.kind == JavaCCParserConstants.STAR)<NEW_LINE>ptr_ret = true;<NEW_LINE>}<NEW_LINE>String comment2 = codeGenerator.getTrailingComments(t);<NEW_LINE>ret = sig.toString();<NEW_LINE>sig.setLength(0);<NEW_LINE>sig.append("(");<NEW_LINE>if (p.getParameterListTokens().size() != 0) {<NEW_LINE>codeGenerator.printTokenSetup((Token) (p.getParameterListTokens().get(0)));<NEW_LINE>for (java.util.Iterator it = p.getParameterListTokens().iterator(); it.hasNext(); ) {<NEW_LINE>t = (Token) it.next();<NEW_LINE>sig.append(codeGenerator.getStringToPrint(t));<NEW_LINE>}<NEW_LINE>sig.append(codeGenerator.getTrailingComments(t));<NEW_LINE>}<NEW_LINE>sig.append(")");<NEW_LINE>params = sig.toString();<NEW_LINE>// For now, just ignore comments<NEW_LINE>codeGenerator.generateMethodDefHeader(ret, cu_name, p.getLhs() + params, sig.toString());<NEW_LINE>// Generate a default value for error return.<NEW_LINE>String default_return;<NEW_LINE>if (ptr_ret)<NEW_LINE>default_return = "NULL";<NEW_LINE>else if (void_ret)<NEW_LINE>default_return = "";<NEW_LINE>else<NEW_LINE>// 0 converts to most (all?) basic types.<NEW_LINE>default_return = "0";<NEW_LINE>StringBuffer ret_val = new StringBuffer("\n#if !defined ERROR_RET_" + method_name + "\n");<NEW_LINE>ret_val.append("#define ERROR_RET_" + method_name + " " + default_return + "\n");<NEW_LINE>ret_val.append("#endif\n");<NEW_LINE>ret_val.append("#define __ERROR_RET__ ERROR_RET_" + method_name + "\n");<NEW_LINE>return ret_val.toString();<NEW_LINE>} | ().get(i)); |
508,669 | public void run(RegressionEnvironment env) {<NEW_LINE>String[] fields = new String[] { "a0", "b0", "a1", "b1" };<NEW_LINE>String epl <MASK><NEW_LINE>env.compileDeploy(epl).addListener("s0");<NEW_LINE>sendSupportBean(env, "E1", 1);<NEW_LINE>env.assertPropsNew("s0", fields, new Object[] { "E1", 1, "E1", 1 });<NEW_LINE>sendSupportBean(env, "E2", 2);<NEW_LINE>env.assertPropsNew("s0", fields, new Object[] { "E2", 2, "E2", 2 });<NEW_LINE>sendMarketBean(env, "E1", 1);<NEW_LINE>env.assertPropsOld("s0", fields, new Object[] { "E1", 1, "E1", 1 });<NEW_LINE>sendMarketBean(env, "E0", 0);<NEW_LINE>env.assertListenerNotInvoked("s0");<NEW_LINE>env.undeployAll();<NEW_LINE>} | = "@name('create') create window MyWindowJSN#keepall as select theString as a, intPrimitive as b from SupportBean;\n" + "on SupportMarketDataBean delete from MyWindowJSN where symbol = a;\n" + "insert into MyWindowJSN select theString as a, intPrimitive as b from SupportBean;\n" + "@name('s0') select irstream s0.a as a0, s0.b as b0, s1.a as a1, s1.b as b1 from MyWindowJSN as s0, MyWindowJSN as s1 where s0.a = s1.a;\n"; |
804,747 | private synchronized void initOptions(boolean firstTime) {<NEW_LINE>long start = 0;<NEW_LINE>if (LOG.isLoggable(Level.FINE)) {<NEW_LINE>start = System.currentTimeMillis();<NEW_LINE>// NOI18N<NEW_LINE>Object[] objects = new Object[] { firstTime ? "" : "re", wmRoot != null ? FileUtil.toFile(wmRoot) : "<null>" };<NEW_LINE>// NOI18N<NEW_LINE>LOG.log(Level.FINE, "JSP parser {0}initializing for WM {1}", objects);<NEW_LINE>}<NEW_LINE>WebModule webModule = wm.get();<NEW_LINE>if (webModule == null) {<NEW_LINE>// already gced<NEW_LINE>// NOI18N<NEW_LINE>LOG.fine("WebModule already GCed");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>editorContext = new ParserServletContext(wmRoot, this, true);<NEW_LINE>diskContext = new <MASK><NEW_LINE>editorOptions = new OptionsImpl(editorContext);<NEW_LINE>diskOptions = new OptionsImpl(diskContext);<NEW_LINE>rctxt = null;<NEW_LINE>// try null, but test with tag files<NEW_LINE>// new JspRuntimeContext(context, options);<NEW_LINE>createClassLoaders();<NEW_LINE>if (LOG.isLoggable(Level.FINE)) {<NEW_LINE>// NOI18N<NEW_LINE>Object[] objects = new Object[] { firstTime ? "" : "re", System.currentTimeMillis() - start };<NEW_LINE>// NOI18N<NEW_LINE>LOG.log(Level.FINE, "JSP parser {0}initialized in {1} ms", objects);<NEW_LINE>}<NEW_LINE>} | ParserServletContext(wmRoot, this, false); |
565,641 | public boolean enterCaseNode(CaseNode caseNode) {<NEW_LINE>List<Statement> nodes = caseNode.getStatements();<NEW_LINE>if (nodes.size() == 1) {<NEW_LINE>Statement node = nodes.get(0);<NEW_LINE>if (node instanceof BlockStatement) {<NEW_LINE>return super.enterCaseNode(caseNode);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (nodes.size() >= 1) {<NEW_LINE>// indentation mark<NEW_LINE>FormatToken formatToken = tokenUtils.getPreviousToken(getStart(nodes.get(0)), JsTokenId.OPERATOR_COLON, true);<NEW_LINE>if (formatToken != null) {<NEW_LINE>TokenUtils.appendTokenAfterLastVirtual(formatToken, FormatToken.forFormat(FormatToken.Kind.INDENTATION_INC));<NEW_LINE>}<NEW_LINE>// put indentation mark<NEW_LINE>formatToken = getCaseEndToken(getStart(nodes.get(0)), getFinish(nodes.get(nodes.size() - 1)));<NEW_LINE>if (formatToken != null) {<NEW_LINE>TokenUtils.appendTokenAfterLastVirtual(formatToken, FormatToken.forFormat<MASK><NEW_LINE>}<NEW_LINE>handleBlockContent(nodes, true);<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | (FormatToken.Kind.INDENTATION_DEC)); |
1,558,447 | public void testMessageOrder_B_SecOff(HttpServletRequest request, HttpServletResponse response) throws Exception {<NEW_LINE>JMSProducer producer1 = jmsContextQueue.createProducer();<NEW_LINE>JMSProducer producer2 = jmsContextQueueNew.createProducer();<NEW_LINE>JMSConsumer jmsConsumer = jmsContextQueue.createConsumer(jmsQueue);<NEW_LINE>int[] msgOrder = new int[10];<NEW_LINE>for (int msgNo = 0; msgNo < 10; msgNo++) {<NEW_LINE>if ((msgNo % 2) == 0) {<NEW_LINE>Message msg = jmsContextQueue.createMessage();<NEW_LINE>msg.setIntProperty("Message_Order", msgNo);<NEW_LINE>producer1.send(jmsQueue, msg);<NEW_LINE>} else {<NEW_LINE>Message msg = jmsContextQueueNew.createMessage();<NEW_LINE>msg.setIntProperty("Message_Order", msgNo);<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>int msgRcvd = jmsConsumer.receive(1000).getIntProperty("Message_Order");<NEW_LINE>System.out.println("Received message [ " + msgRcvd + " ]");<NEW_LINE>msgOrder[msgNo] = msgRcvd;<NEW_LINE>}<NEW_LINE>int outOfOrderCount = 0;<NEW_LINE>for (int msgNo = 0; msgNo < 10; msgNo++) {<NEW_LINE>if (msgOrder[msgNo] != msgNo) {<NEW_LINE>outOfOrderCount++;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>boolean testFailed = false;<NEW_LINE>if (outOfOrderCount != 0) {<NEW_LINE>testFailed = true;<NEW_LINE>}<NEW_LINE>if (testFailed) {<NEW_LINE>throw new Exception("testMessageOrder_B_SecOff failed: Messages were not received in the expected order");<NEW_LINE>}<NEW_LINE>} | producer2.send(jmsQueue, msg); |
5,302 | public void actionPerformed(ActionEvent e) {<NEW_LINE>if (e.getSource() == addButton) {<NEW_LINE>Configuration config;<NEW_LINE>try {<NEW_LINE>config = new Configuration(null);<NEW_LINE>} catch (IOException e1) {<NEW_LINE>throw new RuntimeException(e1);<NEW_LINE>}<NEW_LINE>File initialDir;<NEW_LINE>File ruleFile;<NEW_LINE>if (config.getExternalRuleDirectory() != null) {<NEW_LINE>initialDir = new File(config.getExternalRuleDirectory());<NEW_LINE>if (initialDir.isDirectory()) {<NEW_LINE>ruleFile = Tools.openFileDialog(owner, new XMLFileFilter(), initialDir);<NEW_LINE>} else {<NEW_LINE>ruleFile = Tools.openFileDialog(owner, new XMLFileFilter());<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>ruleFile = Tools.openFileDialog(owner, new XMLFileFilter());<NEW_LINE>}<NEW_LINE>if (ruleFile == null) {<NEW_LINE>// dialog was canceled<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>config.setExternalRuleDirectory(ruleFile.getParent());<NEW_LINE>try {<NEW_LINE>config.saveConfiguration(null);<NEW_LINE>} catch (IOException e1) {<NEW_LINE>throw new RuntimeException(e1);<NEW_LINE>}<NEW_LINE>if (!ruleFiles.contains(ruleFile)) {<NEW_LINE>ruleFiles.add(ruleFile);<NEW_LINE>list.setListData(ruleFiles.toArray(new File[0]));<NEW_LINE>} else {<NEW_LINE>JOptionPane jop = new JOptionPane();<NEW_LINE>JOptionPane.showMessageDialog(jop, messages.getString("guiDuplicate"), messages.getString("guiWarning"), JOptionPane.WARNING_MESSAGE);<NEW_LINE>}<NEW_LINE>} else if (e.getSource() == removeButton) {<NEW_LINE>if (list.getSelectedIndex() != -1) {<NEW_LINE>ruleFiles.remove(list.getSelectedIndex());<NEW_LINE>list.setListData(ruleFiles.toArray(new File[0]));<NEW_LINE>}<NEW_LINE>} else if (e.getSource() == closeButton) {<NEW_LINE>dialog.setVisible(false);<NEW_LINE>} else {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>} | throw new IllegalArgumentException("Don't know how to handle " + e); |
1,844,167 | // shares lots of code with inot; candidate for refactoring<NEW_LINE>@Override<NEW_LINE>public MappeableContainer not(final int firstOfRange, final int lastOfRange) {<NEW_LINE>// TODO: may need to convert to a RunContainer<NEW_LINE>// TODO: this can be optimized for performance<NEW_LINE>if (firstOfRange >= lastOfRange) {<NEW_LINE>// empty range<NEW_LINE>return clone();<NEW_LINE>}<NEW_LINE>// determine the span of array indices to be affected<NEW_LINE>int startIndex = BufferUtil.unsignedBinarySearch(content, 0, cardinality, (char) firstOfRange);<NEW_LINE>if (startIndex < 0) {<NEW_LINE>startIndex = -startIndex - 1;<NEW_LINE>}<NEW_LINE>int lastIndex = BufferUtil.unsignedBinarySearch(content, 0, cardinality, (char) (lastOfRange - 1));<NEW_LINE>if (lastIndex < 0) {<NEW_LINE>lastIndex = -lastIndex - 2;<NEW_LINE>}<NEW_LINE>final int currentValuesInRange = lastIndex - startIndex + 1;<NEW_LINE>final int spanToBeFlipped = lastOfRange - firstOfRange;<NEW_LINE>final int newValuesInRange = spanToBeFlipped - currentValuesInRange;<NEW_LINE>final int cardinalityChange = newValuesInRange - currentValuesInRange;<NEW_LINE>final int newCardinality = cardinality + cardinalityChange;<NEW_LINE>if (newCardinality > DEFAULT_MAX_SIZE) {<NEW_LINE>return toBitmapContainer().not(firstOfRange, lastOfRange);<NEW_LINE>}<NEW_LINE>final <MASK><NEW_LINE>if (!BufferUtil.isBackedBySimpleArray(answer.content)) {<NEW_LINE>throw new RuntimeException("Should not happen. Internal bug.");<NEW_LINE>}<NEW_LINE>char[] sarray = answer.content.array();<NEW_LINE>for (int i = 0; i < startIndex; ++i) {<NEW_LINE>// copy stuff before the active area<NEW_LINE>sarray[i] = content.get(i);<NEW_LINE>}<NEW_LINE>int outPos = startIndex;<NEW_LINE>// item at inPos always >= valInRange<NEW_LINE>int inPos = startIndex;<NEW_LINE>int valInRange = firstOfRange;<NEW_LINE>for (; valInRange < lastOfRange && inPos <= lastIndex; ++valInRange) {<NEW_LINE>if ((char) valInRange != content.get(inPos)) {<NEW_LINE>sarray[outPos++] = (char) valInRange;<NEW_LINE>} else {<NEW_LINE>++inPos;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (; valInRange < lastOfRange; ++valInRange) {<NEW_LINE>answer.content.put(outPos++, (char) valInRange);<NEW_LINE>}<NEW_LINE>// content after the active range<NEW_LINE>for (int i = lastIndex + 1; i < cardinality; ++i) {<NEW_LINE>answer.content.put(outPos++, content.get(i));<NEW_LINE>}<NEW_LINE>answer.cardinality = newCardinality;<NEW_LINE>return answer;<NEW_LINE>} | MappeableArrayContainer answer = new MappeableArrayContainer(newCardinality); |
857,905 | public RunOutcome run(@Nonnull StepExecutionDetails<ReindexJobParameters, ReindexChunkRange> theStepExecutionDetails, @Nonnull IJobDataSink<ReindexChunkIds> theDataSink) throws JobExecutionFailedException {<NEW_LINE>ReindexChunkRange data = theStepExecutionDetails.getData();<NEW_LINE><MASK><NEW_LINE>Date end = data.getEnd();<NEW_LINE>ourLog.info("Beginning scan for reindex IDs in range {} to {}", start, end);<NEW_LINE>Date nextStart = start;<NEW_LINE>RequestPartitionId requestPartitionId = theStepExecutionDetails.getParameters().getRequestPartitionId();<NEW_LINE>Set<ReindexChunkIds.Id> idBuffer = new LinkedHashSet<>();<NEW_LINE>long previousLastTime = 0L;<NEW_LINE>int totalIdsFound = 0;<NEW_LINE>int chunkCount = 0;<NEW_LINE>while (true) {<NEW_LINE>String url = theStepExecutionDetails.getData().getUrl();<NEW_LINE>ourLog.info("Fetching resource ID chunk for URL {} - Range {} - {}", url, nextStart, end);<NEW_LINE>IResourceReindexSvc.IdChunk nextChunk = myResourceReindexSvc.fetchResourceIdsPage(nextStart, end, requestPartitionId, url);<NEW_LINE>if (nextChunk.getIds().isEmpty()) {<NEW_LINE>ourLog.info("No data returned");<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>ourLog.info("Found {} IDs from {} to {}", nextChunk.getIds().size(), nextStart, nextChunk.getLastDate());<NEW_LINE>for (int i = 0; i < nextChunk.getIds().size(); i++) {<NEW_LINE>ReindexChunkIds.Id nextId = new ReindexChunkIds.Id();<NEW_LINE>nextId.setResourceType(nextChunk.getResourceTypes().get(i));<NEW_LINE>nextId.setId(nextChunk.getIds().get(i).getId().toString());<NEW_LINE>idBuffer.add(nextId);<NEW_LINE>}<NEW_LINE>// If we get the same last time twice in a row, we've clearly reached the end<NEW_LINE>if (nextChunk.getLastDate().getTime() == previousLastTime) {<NEW_LINE>ourLog.info("Matching final timestamp of {}, loading is completed", new Date(previousLastTime));<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>previousLastTime = nextChunk.getLastDate().getTime();<NEW_LINE>nextStart = nextChunk.getLastDate();<NEW_LINE>while (idBuffer.size() >= 1000) {<NEW_LINE>List<ReindexChunkIds.Id> submissionIds = new ArrayList<>();<NEW_LINE>for (Iterator<ReindexChunkIds.Id> iter = idBuffer.iterator(); iter.hasNext(); ) {<NEW_LINE>submissionIds.add(iter.next());<NEW_LINE>iter.remove();<NEW_LINE>if (submissionIds.size() >= 1000) {<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>totalIdsFound += submissionIds.size();<NEW_LINE>chunkCount++;<NEW_LINE>submitWorkChunk(submissionIds, theDataSink);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>totalIdsFound += idBuffer.size();<NEW_LINE>chunkCount++;<NEW_LINE>submitWorkChunk(idBuffer, theDataSink);<NEW_LINE>ourLog.info("Submitted {} chunks with {} resource IDs", chunkCount, totalIdsFound);<NEW_LINE>return RunOutcome.SUCCESS;<NEW_LINE>} | Date start = data.getStart(); |
1,312,489 | private AnnotationValuePb.Builder handleEndAnnotationFieldNode(AnnotationPb.Builder currentAnnotation, AnnotationValuePb.Builder currentAnnotationValue, Iterable<AnnotationPb> nestedAnnotations) {<NEW_LINE>checkState("anno_field".equals(xmlStreamReader.getLocalName()), "not an " + "anno_field node");<NEW_LINE>checkState(null != currentAnnotationValue, "Not building annotation value! %s", currentLocation);<NEW_LINE>checkState(null != currentAnnotation, "Not building annotation! %s", currentLocation);<NEW_LINE>if (!isEmpty(nestedAnnotations)) {<NEW_LINE>currentAnnotationValue.addAllFieldAnnotationValue(nestedAnnotations);<NEW_LINE>currentAnnotationValue.setFieldType(TestInfo.Type.ANNOTATION);<NEW_LINE>}<NEW_LINE>int fieldCount = 0;<NEW_LINE>if (currentAnnotationValue.getFieldType().equals(TestInfo.Type.ANNOTATION)) {<NEW_LINE>fieldCount = currentAnnotationValue.getFieldAnnotationValueCount();<NEW_LINE>} else {<NEW_LINE>fieldCount = currentAnnotationValue.getFieldValueCount();<NEW_LINE>}<NEW_LINE>if (!currentAnnotationValue.getIsArray()) {<NEW_LINE>checkState(fieldCount == 1, "Never processed field value!" + " %s", currentLocation);<NEW_LINE>}<NEW_LINE>// else we could have had a 0 length array, so thats ok.<NEW_LINE>if (fieldCount > 0) {<NEW_LINE>checkState(currentAnnotationValue.hasFieldType(), "No field type in anno value! %s", currentLocation);<NEW_LINE>}<NEW_LINE>currentAnnotation.<MASK><NEW_LINE>return null;<NEW_LINE>} | addAnnotationValue(currentAnnotationValue.build()); |
932,327 | static <T> T readProtobuf(final ChannelBuffer buf, final Parser<T> parser) {<NEW_LINE>final int length = HBaseRpc.readProtoBufVarint(buf);<NEW_LINE><MASK><NEW_LINE>final byte[] payload;<NEW_LINE>final int offset;<NEW_LINE>if (buf.hasArray()) {<NEW_LINE>// Zero copy.<NEW_LINE>payload = buf.array();<NEW_LINE>offset = buf.arrayOffset() + buf.readerIndex();<NEW_LINE>buf.readerIndex(buf.readerIndex() + length);<NEW_LINE>} else {<NEW_LINE>// We have to copy the entire payload out of the buffer :(<NEW_LINE>payload = new byte[length];<NEW_LINE>buf.readBytes(payload);<NEW_LINE>offset = 0;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>return parser.parseFrom(payload, offset, length);<NEW_LINE>} catch (InvalidProtocolBufferException e) {<NEW_LINE>final String msg = "Invalid RPC response: length=" + length + ", payload=" + Bytes.pretty(payload);<NEW_LINE>LOG.error("Invalid RPC from buffer: " + buf);<NEW_LINE>throw new InvalidResponseException(msg, e);<NEW_LINE>}<NEW_LINE>} | HBaseRpc.checkArrayLength(buf, length); |
1,317,586 | private Set<String> reLoadAllDbs() {<NEW_LINE>Map<String, String> allDbs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);<NEW_LINE>Connection connection = null;<NEW_LINE>Statement statement = null;<NEW_LINE>String sql = PolarPrivUtil.getLoadAllDbsSql();<NEW_LINE>try {<NEW_LINE>try {<NEW_LINE>connection = metaDbDataSource.getConnection();<NEW_LINE>statement = connection.createStatement();<NEW_LINE>ResultSet resultSet = statement.executeQuery(sql);<NEW_LINE>while (resultSet.next()) {<NEW_LINE>String dbName = resultSet.getString(1);<NEW_LINE>String appName = resultSet.getString(2);<NEW_LINE>allDbs.put(dbName, appName);<NEW_LINE>}<NEW_LINE>this.dbNameAppNameMap = allDbs;<NEW_LINE><MASK><NEW_LINE>} finally {<NEW_LINE>if (statement != null) {<NEW_LINE>statement.close();<NEW_LINE>}<NEW_LINE>if (connection != null) {<NEW_LINE>connection.close();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} catch (Throwable e) {<NEW_LINE>logger.error(String.format("Failed in loadAllDbs, sql: %s", sql), e);<NEW_LINE>throw GeneralUtil.nestedException(e);<NEW_LINE>}<NEW_LINE>} | return this.dbNameAppNameMap.keySet(); |
1,677,679 | public final StartEPLExpressionRuleContext startEPLExpressionRule() throws RecognitionException {<NEW_LINE>StartEPLExpressionRuleContext _localctx = new StartEPLExpressionRuleContext(_ctx, getState());<NEW_LINE>enterRule(_localctx, 0, RULE_startEPLExpressionRule);<NEW_LINE>int _la;<NEW_LINE>try {<NEW_LINE>enterOuterAlt(_localctx, 1);<NEW_LINE>{<NEW_LINE>setState(531);<NEW_LINE>_errHandler.sync(this);<NEW_LINE>_la = _input.LA(1);<NEW_LINE>while (((((_la - 125)) & ~0x3f) == 0 && ((1L << (_la - 125)) & ((1L << (EXPRESSIONDECL - 125)) | (1L << (CLASSDECL - 125)) | (1L << (ATCHAR - 125)))) != 0)) {<NEW_LINE>{<NEW_LINE>setState(529);<NEW_LINE>_errHandler.sync(this);<NEW_LINE>switch(_input.LA(1)) {<NEW_LINE>case ATCHAR:<NEW_LINE>{<NEW_LINE>setState(526);<NEW_LINE>annotationEnum();<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>case EXPRESSIONDECL:<NEW_LINE>{<NEW_LINE>setState(527);<NEW_LINE>expressionDecl();<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>case CLASSDECL:<NEW_LINE>{<NEW_LINE>setState(528);<NEW_LINE>classDecl();<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>throw new NoViableAltException(this);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>setState(533);<NEW_LINE>_errHandler.sync(this);<NEW_LINE>_la = _input.LA(1);<NEW_LINE>}<NEW_LINE>setState(534);<NEW_LINE>eplExpression();<NEW_LINE>setState(535);<NEW_LINE>match(EOF);<NEW_LINE>}<NEW_LINE>} catch (RecognitionException re) {<NEW_LINE>_localctx.exception = re;<NEW_LINE><MASK><NEW_LINE>_errHandler.recover(this, re);<NEW_LINE>} finally {<NEW_LINE>exitRule();<NEW_LINE>}<NEW_LINE>return _localctx;<NEW_LINE>} | _errHandler.reportError(this, re); |
1,609,650 | public VolumeSpecification unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>VolumeSpecification volumeSpecification = new VolumeSpecification();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("VolumeType", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>volumeSpecification.setVolumeType(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("Iops", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>volumeSpecification.setIops(context.getUnmarshaller(Integer.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("SizeInGB", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>volumeSpecification.setSizeInGB(context.getUnmarshaller(Integer.<MASK><NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return volumeSpecification;<NEW_LINE>} | class).unmarshall(context)); |
1,303,152 | final ListOTAUpdatesResult executeListOTAUpdates(ListOTAUpdatesRequest listOTAUpdatesRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(listOTAUpdatesRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<ListOTAUpdatesRequest> request = null;<NEW_LINE>Response<ListOTAUpdatesResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new ListOTAUpdatesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listOTAUpdatesRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "IoT");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListOTAUpdates");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<ListOTAUpdatesResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListOTAUpdatesResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | awsRequestMetrics.endEvent(Field.RequestMarshallTime); |
325,277 | public CookieNames unmarshall(StaxUnmarshallerContext context) throws Exception {<NEW_LINE>CookieNames cookieNames = new CookieNames();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>if (context.isStartOfDocument())<NEW_LINE>targetDepth += 1;<NEW_LINE>while (true) {<NEW_LINE>XMLEvent xmlEvent = context.nextEvent();<NEW_LINE>if (xmlEvent.isEndDocument())<NEW_LINE>return cookieNames;<NEW_LINE>if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {<NEW_LINE>if (context.testExpression("Quantity", targetDepth)) {<NEW_LINE>cookieNames.setQuantity(IntegerStaxUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>if (context.testExpression("Items", targetDepth)) {<NEW_LINE>cookieNames.withItems(new ArrayList<String>());<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>if (context.testExpression("Items/Name", targetDepth)) {<NEW_LINE>cookieNames.withItems(StringStaxUnmarshaller.getInstance<MASK><NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>} else if (xmlEvent.isEndElement()) {<NEW_LINE>if (context.getCurrentDepth() < originalDepth) {<NEW_LINE>return cookieNames;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ().unmarshall(context)); |
87,350 | public void dump(PrintStream out, StringBuilder indent, Set<ModelInterfaceType> dumped) {<NEW_LINE>ModelType type = getType();<NEW_LINE>if (type instanceof ModelInterfaceType) {<NEW_LINE>ModelInterfaceType interfaceType = (ModelInterfaceType) type;<NEW_LINE>out.append(indent).print(this);<NEW_LINE>if (!dumped.add(interfaceType)) {<NEW_LINE>out.println(" ...");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>out.println();<NEW_LINE>indent.append(' ');<NEW_LINE>for (ModelInterfaceType supertype : interfaceType.supertypes) {<NEW_LINE>dumpSupertype(out, indent, supertype, dumped);<NEW_LINE>}<NEW_LINE>for (ModelAttribute attr : interfaceType.attributes) {<NEW_LINE>out.append<MASK><NEW_LINE>}<NEW_LINE>for (ModelElement element : interfaceType.elements) {<NEW_LINE>element.dump(out, indent, dumped);<NEW_LINE>}<NEW_LINE>indent.setLength(indent.length() - 1);<NEW_LINE>} else {<NEW_LINE>out.append(indent).println(this);<NEW_LINE>}<NEW_LINE>} | (indent).println(attr); |
710,445 | public void resolve(ResolveContext resolveContext, List<? extends ResolutionAwareRepository> repositories, GlobalDependencyResolutionRules metadataHandler, Spec<? super DependencyMetadata> edgeFilter, DependencyGraphVisitor graphVisitor, DependencyArtifactsVisitor artifactsVisitor, AttributesSchemaInternal consumerSchema, ArtifactTypeRegistry artifactTypeRegistry, boolean includeSyntheticDependencies) {<NEW_LINE>LOGGER.debug("Resolving {}", resolveContext);<NEW_LINE>validateResolutionStrategy(resolveContext.getResolutionStrategy());<NEW_LINE>ComponentResolversChain resolvers = createResolvers(resolveContext, repositories, metadataHandler, artifactTypeRegistry, consumerSchema);<NEW_LINE>DependencyGraphBuilder builder = createDependencyGraphBuilder(resolvers, resolveContext.getResolutionStrategy(), metadataHandler, <MASK><NEW_LINE>DependencyGraphVisitor artifactsGraphVisitor = new ResolvedArtifactsGraphVisitor(artifactsVisitor, resolvers.getArtifactSelector());<NEW_LINE>// Resolve the dependency graph<NEW_LINE>builder.resolve(resolveContext, new CompositeDependencyGraphVisitor(graphVisitor, artifactsGraphVisitor), includeSyntheticDependencies);<NEW_LINE>} | edgeFilter, consumerSchema, moduleExclusions, buildOperationExecutor); |
1,365,479 | protected View.OnClickListener generateOnClickListener(@NonNull final BaseActivity activity, @Nullable final Integer textColor, @Nullable final Float textSize, final boolean showLinkButtons) {<NEW_LINE>return (button) -> {<NEW_LINE>final ScrollView scrollView = new ScrollView(activity);<NEW_LINE>final View view = mSpoilerText.generateView(activity, textColor, textSize, true);<NEW_LINE>scrollView.addView(view);<NEW_LINE>final ViewGroup.MarginLayoutParams layoutParams = (FrameLayout.LayoutParams) view.getLayoutParams();<NEW_LINE>final int marginPx = General.dpToPixels(activity, 14);<NEW_LINE>layoutParams.setMargins(marginPx, marginPx, marginPx, marginPx);<NEW_LINE>final AlertDialog.Builder builder = new AlertDialog.Builder(activity);<NEW_LINE>builder.setView(scrollView);<NEW_LINE>builder.setNeutralButton(R.string.dialog_close, (dialog, which) -> {<NEW_LINE>});<NEW_LINE>final <MASK><NEW_LINE>alert.show();<NEW_LINE>};<NEW_LINE>} | AlertDialog alert = builder.create(); |
125,609 | private static DenseVectorSummarizer merge(DenseVectorSummarizer left, DenseVectorSummarizer right) {<NEW_LINE>if (right.count == 0) {<NEW_LINE>return left;<NEW_LINE>}<NEW_LINE>if (left.count == 0) {<NEW_LINE>left.count = right.count;<NEW_LINE>left.sum = right.sum.clone();<NEW_LINE>left.squareSum = right.squareSum.clone();<NEW_LINE>left.normL1 = right.normL1.clone();<NEW_LINE>left.min = right.min.clone();<NEW_LINE>left.max = right.max.clone();<NEW_LINE>left.numNonZero = right.numNonZero.clone();<NEW_LINE>if (right.outerProduct != null) {<NEW_LINE>left.outerProduct <MASK><NEW_LINE>}<NEW_LINE>return left;<NEW_LINE>}<NEW_LINE>int n = left.sum.size();<NEW_LINE>int nSrt = right.sum.size();<NEW_LINE>if (n >= nSrt) {<NEW_LINE>left.count += right.count;<NEW_LINE>for (int i = 0; i < nSrt; i++) {<NEW_LINE>left.sum.add(i, right.sum.get(i));<NEW_LINE>left.squareSum.add(i, right.squareSum.get(i));<NEW_LINE>left.normL1.add(i, right.normL1.get(i));<NEW_LINE>left.min.set(i, Math.min(left.min.get(i), right.min.get(i)));<NEW_LINE>left.max.set(i, Math.max(left.max.get(i), right.max.get(i)));<NEW_LINE>left.numNonZero.add(i, right.numNonZero.get(i));<NEW_LINE>}<NEW_LINE>if (left.outerProduct != null && right.outerProduct != null) {<NEW_LINE>for (int i = 0; i < nSrt; i++) {<NEW_LINE>for (int j = 0; j < nSrt; j++) {<NEW_LINE>left.outerProduct.add(i, j, right.outerProduct.get(i, j));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} else if (left.outerProduct == null && right.outerProduct != null) {<NEW_LINE>left.outerProduct = right.outerProduct.clone();<NEW_LINE>}<NEW_LINE>return left;<NEW_LINE>} else {<NEW_LINE>DenseVectorSummarizer clonedSrt = right.copy();<NEW_LINE>return merge(clonedSrt, left);<NEW_LINE>}<NEW_LINE>} | = right.outerProduct.clone(); |
977,569 | ParseResult open(File file, long fileID) {<NEW_LINE>if (file == null) {<NEW_LINE>return ParseResult.ERROR;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>pstFile = new PSTFile(file);<NEW_LINE>} catch (PSTException ex) {<NEW_LINE>// This is the message thrown from the PSTFile constructor if it<NEW_LINE>// detects that the file is encrypted.<NEW_LINE>if (ex.getMessage().equals("Only unencrypted and compressable PST files are supported at this time")) {<NEW_LINE>// NON-NLS<NEW_LINE>// NON-NLS<NEW_LINE>logger.log(Level.INFO, "Found encrypted PST file.");<NEW_LINE>return ParseResult.ENCRYPT;<NEW_LINE>}<NEW_LINE>if (ex.getMessage().toLowerCase().startsWith("unable to")) {<NEW_LINE>logger.log(Level.WARNING, ex.getMessage());<NEW_LINE>logger.log(Level.WARNING, String.format("Error in parsing PST file %s, file may be empty or corrupt", file.getName()));<NEW_LINE>return ParseResult.ERROR;<NEW_LINE>}<NEW_LINE>// NON-NLS<NEW_LINE>String msg = file.getName() <MASK><NEW_LINE>logger.log(Level.WARNING, msg, ex);<NEW_LINE>return ParseResult.ERROR;<NEW_LINE>} catch (IOException ex) {<NEW_LINE>// NON-NLS<NEW_LINE>String msg = file.getName() + ": Failed to create internal java-libpst PST file to parse:\n" + ex.getMessage();<NEW_LINE>logger.log(Level.WARNING, msg, ex);<NEW_LINE>return ParseResult.ERROR;<NEW_LINE>} catch (IllegalArgumentException ex) {<NEW_LINE>// Not sure if this is true, was in previous version of code.<NEW_LINE>// NON-NLS<NEW_LINE>logger.log(Level.INFO, "Found encrypted PST file.");<NEW_LINE>return ParseResult.ENCRYPT;<NEW_LINE>}<NEW_LINE>return ParseResult.OK;<NEW_LINE>} | + ": Failed to create internal java-libpst PST file to parse:\n" + ex.getMessage(); |
737,202 | public FusekiServer start() {<NEW_LINE>try {<NEW_LINE>FusekiModuleStep.serverBeforeStarting(this);<NEW_LINE>server.start();<NEW_LINE>FusekiModuleStep.serverAfterStarting(this);<NEW_LINE>} catch (IOException ex) {<NEW_LINE>if (ex.getCause() instanceof java.security.UnrecoverableKeyException)<NEW_LINE>// Unbundle for clearer message.<NEW_LINE>throw new FusekiException(ex.getMessage());<NEW_LINE>throw new FusekiException(ex);<NEW_LINE>} catch (IllegalStateException ex) {<NEW_LINE>throw new FusekiException(<MASK><NEW_LINE>} catch (Exception ex) {<NEW_LINE>throw new FusekiException(ex);<NEW_LINE>}<NEW_LINE>Connector[] connectors = server.getServer().getConnectors();<NEW_LINE>if (connectors.length == 0)<NEW_LINE>serverLog.warn("Start Fuseki: No connectors");<NEW_LINE>// Extract the ports from the Connectors.<NEW_LINE>Arrays.stream(connectors).forEach(c -> {<NEW_LINE>if (c instanceof ServerConnector) {<NEW_LINE>ServerConnector connector = (ServerConnector) c;<NEW_LINE>String protocol = connector.getDefaultConnectionFactory().getProtocol();<NEW_LINE>String scheme = (protocol.startsWith("SSL-") || protocol.equals("SSL")) ? "https" : "http";<NEW_LINE>int port = connector.getLocalPort();<NEW_LINE>connector(scheme, port);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>if (httpsPort > 0 && httpPort > 0)<NEW_LINE>Fuseki.serverLog.info("Start Fuseki (http=" + httpPort + " https=" + httpsPort + ")");<NEW_LINE>else if (httpsPort > 0)<NEW_LINE>Fuseki.serverLog.info("Start Fuseki (https=" + httpsPort + ")");<NEW_LINE>else if (httpPort > 0)<NEW_LINE>Fuseki.serverLog.info("Start Fuseki (http=" + httpPort + ")");<NEW_LINE>else<NEW_LINE>Fuseki.serverLog.info("Start Fuseki");<NEW_LINE>// Any post-startup configuration here.<NEW_LINE>// --<NEW_LINE>// Done!<NEW_LINE>return this;<NEW_LINE>} | ex.getMessage(), ex); |
976,538 | private Object jpql(Statement statement, Runtime runtime) throws Exception {<NEW_LINE>Object data = null;<NEW_LINE>try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {<NEW_LINE>Business business = new Business(emc);<NEW_LINE>Class<? extends JpaObject> cls = this.clazz(business, statement);<NEW_LINE>EntityManager em;<NEW_LINE>if (StringUtils.equalsIgnoreCase(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC) && StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)) {<NEW_LINE>em = business.entityManagerContainer().get(DynamicBaseEntity.class);<NEW_LINE>} else {<NEW_LINE>em = business.entityManagerContainer().get(cls);<NEW_LINE>}<NEW_LINE>Query query = em.createQuery(statement.getData());<NEW_LINE>for (Parameter<?> p : query.getParameters()) {<NEW_LINE>if (runtime.hasParameter(p.getName())) {<NEW_LINE>query.setParameter(p.getName(), runtime.getParameter(p.getName()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)) {<NEW_LINE>if (isPageSql(statement.getData())) {<NEW_LINE>query.setFirstResult((runtime.page - 1) * runtime.size);<NEW_LINE>query.setMaxResults(runtime.size);<NEW_LINE>}<NEW_LINE>data = query.getResultList();<NEW_LINE>} else {<NEW_LINE>business.<MASK><NEW_LINE>data = query.executeUpdate();<NEW_LINE>business.entityManagerContainer().commit();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return data;<NEW_LINE>} | entityManagerContainer().beginTransaction(cls); |
134,488 | private static ResourceConfig createResourceConfig(final WebConfig config) throws ServletException {<NEW_LINE>final ServletContext servletContext = config.getServletContext();<NEW_LINE>// check if ResourceConfig has already been created, if so use it<NEW_LINE>ResourceConfig resourceConfig = Utils.retrieve(config.getServletContext(), config.getName());<NEW_LINE>if (resourceConfig != null) {<NEW_LINE>return resourceConfig;<NEW_LINE>}<NEW_LINE>final Map<String, Object> initParams = getInitParams(config);<NEW_LINE>final Map<String, Object> contextParams = Utils.getContextParams(servletContext);<NEW_LINE>// check if the JAX-RS application config class property is present<NEW_LINE>final String jaxrsApplicationClassName = config.getInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS);<NEW_LINE>if (jaxrsApplicationClassName == null) {<NEW_LINE>// If no resource config class property is present, create default config<NEW_LINE>resourceConfig = new ResourceConfig().addProperties<MASK><NEW_LINE>final String webApp = config.getInitParameter(ServletProperties.PROVIDER_WEB_APP);<NEW_LINE>if (webApp != null && !"false".equals(webApp)) {<NEW_LINE>resourceConfig.registerFinder(new WebAppResourcesScanner(servletContext));<NEW_LINE>}<NEW_LINE>return resourceConfig;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>final Class<? extends javax.ws.rs.core.Application> jaxrsApplicationClass = AccessController.doPrivileged(ReflectionHelper.<javax.ws.rs.core.Application>classForNameWithExceptionPEA(jaxrsApplicationClassName));<NEW_LINE>if (javax.ws.rs.core.Application.class.isAssignableFrom(jaxrsApplicationClass)) {<NEW_LINE>return ResourceConfig.forApplicationClass(jaxrsApplicationClass).addProperties(initParams).addProperties(contextParams);<NEW_LINE>} else {<NEW_LINE>throw new ServletException(LocalizationMessages.RESOURCE_CONFIG_PARENT_CLASS_INVALID(jaxrsApplicationClassName, javax.ws.rs.core.Application.class));<NEW_LINE>}<NEW_LINE>} catch (final PrivilegedActionException e) {<NEW_LINE>throw new ServletException(LocalizationMessages.RESOURCE_CONFIG_UNABLE_TO_LOAD(jaxrsApplicationClassName), e.getCause());<NEW_LINE>} catch (final ClassNotFoundException e) {<NEW_LINE>throw new ServletException(LocalizationMessages.RESOURCE_CONFIG_UNABLE_TO_LOAD(jaxrsApplicationClassName), e);<NEW_LINE>}<NEW_LINE>} | (initParams).addProperties(contextParams); |
1,562,647 | public void writeTo(DexFile file, AnnotatedOutput out) {<NEW_LINE>boolean annotates = out.annotates();<NEW_LINE>TypeIdsSection typeIds = file.getTypeIds();<NEW_LINE>int <MASK><NEW_LINE>int superIdx = (superclass == null) ? -1 : typeIds.indexOf(superclass);<NEW_LINE>int interOff = OffsettedItem.getAbsoluteOffsetOr0(interfaces);<NEW_LINE>int annoOff = annotationsDirectory.isEmpty() ? 0 : annotationsDirectory.getAbsoluteOffset();<NEW_LINE>int sourceFileIdx = (sourceFile == null) ? -1 : file.getStringIds().indexOf(sourceFile);<NEW_LINE>int dataOff = classData.isEmpty() ? 0 : classData.getAbsoluteOffset();<NEW_LINE>int staticValuesOff = OffsettedItem.getAbsoluteOffsetOr0(staticValuesItem);<NEW_LINE>if (annotates) {<NEW_LINE>out.annotate(0, indexString() + ' ' + thisClass.toHuman());<NEW_LINE>out.annotate(4, " class_idx: " + Hex.u4(classIdx));<NEW_LINE>out.annotate(4, " access_flags: " + AccessFlags.classString(accessFlags));<NEW_LINE>out.annotate(4, " superclass_idx: " + Hex.u4(superIdx) + " // " + ((superclass == null) ? "<none>" : superclass.toHuman()));<NEW_LINE>out.annotate(4, " interfaces_off: " + Hex.u4(interOff));<NEW_LINE>if (interOff != 0) {<NEW_LINE>TypeList list = interfaces.getList();<NEW_LINE>int sz = list.size();<NEW_LINE>for (int i = 0; i < sz; i++) {<NEW_LINE>out.annotate(0, " " + list.getType(i).toHuman());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>out.annotate(4, " source_file_idx: " + Hex.u4(sourceFileIdx) + " // " + ((sourceFile == null) ? "<none>" : sourceFile.toHuman()));<NEW_LINE>out.annotate(4, " annotations_off: " + Hex.u4(annoOff));<NEW_LINE>out.annotate(4, " class_data_off: " + Hex.u4(dataOff));<NEW_LINE>out.annotate(4, " static_values_off: " + Hex.u4(staticValuesOff));<NEW_LINE>}<NEW_LINE>out.writeInt(classIdx);<NEW_LINE>out.writeInt(accessFlags);<NEW_LINE>out.writeInt(superIdx);<NEW_LINE>out.writeInt(interOff);<NEW_LINE>out.writeInt(sourceFileIdx);<NEW_LINE>out.writeInt(annoOff);<NEW_LINE>out.writeInt(dataOff);<NEW_LINE>out.writeInt(staticValuesOff);<NEW_LINE>} | classIdx = typeIds.indexOf(thisClass); |
1,174,312 | private static void addMavenCoordinates(File modifiedJsonFile, JsonArray jsonArray, Map<String, LibertyFeature> features) throws IOException {<NEW_LINE><MASK><NEW_LINE>for (int i = 0; i < jsonArray.size(); i++) {<NEW_LINE>JsonObject jsonObject = jsonArray.getJsonObject(i);<NEW_LINE>JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(jsonObject);<NEW_LINE>JsonObject wlpInfo = jsonObject.getJsonObject(Constants.WLP_INFORMATION_KEY);<NEW_LINE>JsonObjectBuilder wlpInfoBuilder = Json.createObjectBuilder(wlpInfo);<NEW_LINE>JsonArray provideFeatureArray = wlpInfo.getJsonArray(Constants.PROVIDE_FEATURE_KEY);<NEW_LINE>String symbolicName = provideFeatureArray.getString(0);<NEW_LINE>wlpInfoBuilder.add(Constants.MAVEN_COORDINATES_KEY, features.get(symbolicName).getMavenCoordinates().toString());<NEW_LINE>if (features.get(symbolicName).getMinimumLicenseMavenCoordinate() != null) {<NEW_LINE>wlpInfoBuilder.add("licenseMavenCoordinate", features.get(symbolicName).getMinimumLicenseMavenCoordinate());<NEW_LINE>}<NEW_LINE>jsonObjectBuilder.add(Constants.WLP_INFORMATION_KEY, wlpInfoBuilder);<NEW_LINE>jsonArrayBuilder.add(jsonObjectBuilder);<NEW_LINE>}<NEW_LINE>// Write JSON to the modified file<NEW_LINE>FileOutputStream out = null;<NEW_LINE>try {<NEW_LINE>Map<String, Object> config = new HashMap<String, Object>();<NEW_LINE>config.put(JsonGenerator.PRETTY_PRINTING, true);<NEW_LINE>JsonWriterFactory writerFactory = Json.createWriterFactory(config);<NEW_LINE>out = new FileOutputStream(modifiedJsonFile);<NEW_LINE>JsonWriter streamWriter = writerFactory.createWriter(out);<NEW_LINE>streamWriter.write(jsonArrayBuilder.build());<NEW_LINE>} finally {<NEW_LINE>if (out != null) {<NEW_LINE>out.close();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); |
632,848 | public void onError(Exception e) {<NEW_LINE>byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;<NEW_LINE>org.apache.thrift.TBase msg;<NEW_LINE>getBlobReplication_result result = new getBlobReplication_result();<NEW_LINE>if (e instanceof KeyNotFoundException) {<NEW_LINE>result.knf = (KeyNotFoundException) e;<NEW_LINE>result.set_knf_isSet(true);<NEW_LINE>msg = result;<NEW_LINE>} else {<NEW_LINE>msgType = org.apache<MASK><NEW_LINE>msg = (org.apache.thrift.TBase) new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>fcall.sendResponse(fb, msg, msgType, seqid);<NEW_LINE>return;<NEW_LINE>} catch (Exception ex) {<NEW_LINE>LOGGER.error("Exception writing to internal frame buffer", ex);<NEW_LINE>}<NEW_LINE>fb.close();<NEW_LINE>} | .thrift.protocol.TMessageType.EXCEPTION; |
1,714,186 | public void buildModel() {<NEW_LINE>model = new Model("NQueen");<NEW_LINE>vars = new IntVar[n];<NEW_LINE>IntVar[] diag1 = new IntVar[n];<NEW_LINE>IntVar[] diag2 = new IntVar[n];<NEW_LINE>IntVar[] dualvars = new IntVar[n];<NEW_LINE>IntVar[] dualdiag1 = new IntVar[n];<NEW_LINE>IntVar[] dualdiag2 = new IntVar[n];<NEW_LINE>for (int i = 0; i < n; i++) {<NEW_LINE>vars[i] = model.intVar("Q_" + i, 1, n, false);<NEW_LINE>diag1[i] = model.intVar("D1_" + i, 1, 2 * n, false);<NEW_LINE>diag2[i] = model.intVar("D2_" + i, -n, n, false);<NEW_LINE>dualvars[i] = model.intVar("DQ_" + i, 1, n, false);<NEW_LINE>dualdiag1[i] = model.intVar("DD1_" + i, 1, 2 * n, false);<NEW_LINE>dualdiag2[i] = model.intVar("DD2_" + i<MASK><NEW_LINE>}<NEW_LINE>for (int i = 0; i < n; i++) {<NEW_LINE>model.arithm(diag1[i], "=", vars[i], "+", i).post();<NEW_LINE>model.arithm(diag2[i], "=", vars[i], "-", i).post();<NEW_LINE>model.arithm(dualdiag1[i], "=", dualvars[i], "+", i).post();<NEW_LINE>model.arithm(dualdiag2[i], "=", dualvars[i], "-", i).post();<NEW_LINE>}<NEW_LINE>model.allDifferent(diag1, "BC").post();<NEW_LINE>model.allDifferent(diag2, "BC").post();<NEW_LINE>model.allDifferent(dualdiag1, "BC").post();<NEW_LINE>model.allDifferent(dualdiag2, "BC").post();<NEW_LINE>model.inverseChanneling(vars, dualvars, 1, 1).post();<NEW_LINE>} | , -n, n, false); |
758,333 | String model(CalciteConnectionImpl connection) {<NEW_LINE>String model = connection.config().model();<NEW_LINE>if (model != null) {<NEW_LINE>return model;<NEW_LINE>}<NEW_LINE>SchemaFactory schemaFactory = connection.config().schemaFactory(SchemaFactory.class, null);<NEW_LINE>final Properties info = connection.getProperties();<NEW_LINE>final String schemaName = Util.first(connection.config().schema(), "adhoc");<NEW_LINE>if (schemaFactory == null) {<NEW_LINE>final JsonSchema.Type schemaType = connection<MASK><NEW_LINE>if (schemaType != null) {<NEW_LINE>switch(schemaType) {<NEW_LINE>case JDBC:<NEW_LINE>schemaFactory = JdbcSchema.Factory.INSTANCE;<NEW_LINE>break;<NEW_LINE>case MAP:<NEW_LINE>schemaFactory = AbstractSchema.Factory.INSTANCE;<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (schemaFactory != null) {<NEW_LINE>final JsonBuilder json = new JsonBuilder();<NEW_LINE>final Map<String, Object> root = json.map();<NEW_LINE>root.put("version", "1.0");<NEW_LINE>root.put("defaultSchema", schemaName);<NEW_LINE>final List<Object> schemaList = json.list();<NEW_LINE>root.put("schemas", schemaList);<NEW_LINE>final Map<String, Object> schema = json.map();<NEW_LINE>schemaList.add(schema);<NEW_LINE>schema.put("type", "custom");<NEW_LINE>schema.put("name", schemaName);<NEW_LINE>schema.put("factory", schemaFactory.getClass().getName());<NEW_LINE>final Map<String, Object> operandMap = json.map();<NEW_LINE>schema.put("operand", operandMap);<NEW_LINE>for (Map.Entry<String, String> entry : Util.toMap(info).entrySet()) {<NEW_LINE>if (entry.getKey().startsWith("schema.")) {<NEW_LINE>operandMap.put(entry.getKey().substring("schema.".length()), entry.getValue());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return "inline:" + json.toJsonString(root);<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | .config().schemaType(); |
883,270 | public boolean refresh(TypeElement typeElement) {<NEW_LINE>Map<String, ? extends AnnotationMirror> annByType = getHelper().getAnnotationsByType(typeElement.getAnnotationMirrors());<NEW_LINE>// NOI18N<NEW_LINE>AnnotationMirror annotationMirror = annByType.get("javax.annotation.security.DeclareRoles");<NEW_LINE>if (annotationMirror == null) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>// The same problem as for IZ#172425 - Servlet 3.0 model is not updated properly<NEW_LINE>roles.clear();<NEW_LINE>AnnotationParser parser = AnnotationParser.create(getHelper());<NEW_LINE>parser.expectStringArray("value", new // NOI18N<NEW_LINE>ArrayValueHandler() {<NEW_LINE><NEW_LINE>public Object handleArray(List<AnnotationValue> arrayMembers) {<NEW_LINE>for (AnnotationValue arrayMember : arrayMembers) {<NEW_LINE>String value = <MASK><NEW_LINE>roles.add(value);<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>}, null);<NEW_LINE>ParseResult parseResult = parser.parse(annotationMirror);<NEW_LINE>return true;<NEW_LINE>} | (String) arrayMember.getValue(); |
1,038,285 | private QueryResult prepareAndRun(SearchJob searchJob, Query query) {<NEW_LINE>final QueryBackend<? extends <MASK><NEW_LINE>LOG.debug("[{}] Using {} to generate query", query.id(), backend);<NEW_LINE>// with all the results done, we can execute the current query and eventually complete our own result<NEW_LINE>// if any of this throws an exception, the handle in #execute will convert it to an error and return a "failed" result instead<NEW_LINE>// if the backend already returns a "failed result" then nothing special happens here<NEW_LINE>final GeneratedQueryContext generatedQueryContext = backend.generate(searchJob, query, searchConfig.get());<NEW_LINE>LOG.trace("[{}] Generated query {}, running it on backend {}", query.id(), generatedQueryContext, backend);<NEW_LINE>final QueryResult result = backend.run(searchJob, query, generatedQueryContext);<NEW_LINE>LOG.debug("[{}] Query returned {}", query.id(), result);<NEW_LINE>if (!generatedQueryContext.errors().isEmpty()) {<NEW_LINE>generatedQueryContext.errors().forEach(searchJob::addError);<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | GeneratedQueryContext> backend = getQueryBackend(query); |
754,050 | public GradientValue_F32 compute(int x, int y) {<NEW_LINE>float a00, a01, a02, a10, a12, a20, a21, a22;<NEW_LINE>if (x >= 1 && y >= 1 && x < input.width - 1 && y < input.height - 1) {<NEW_LINE>int s = input.stride;<NEW_LINE>int tl = input.startIndex + input.stride * (y - 1) + x - 1;<NEW_LINE>a00 = input.data[tl];<NEW_LINE>a01 = input.data[tl + 1];<NEW_LINE>a02 = input.data[tl + 2];<NEW_LINE>a10 = input.data[tl + s];<NEW_LINE>a12 = input.data[tl + 2 + s];<NEW_LINE>a20 = input.<MASK><NEW_LINE>a21 = input.data[tl + 1 + 2 * s];<NEW_LINE>a22 = input.data[tl + 2 + 2 * s];<NEW_LINE>} else {<NEW_LINE>a00 = border.get(x - 1, y - 1);<NEW_LINE>a01 = border.get(x, y - 1);<NEW_LINE>a02 = border.get(x + 1, y - 1);<NEW_LINE>a10 = border.get(x - 1, y);<NEW_LINE>a12 = border.get(x + 1, y);<NEW_LINE>a20 = border.get(x - 1, y + 1);<NEW_LINE>a21 = border.get(x, y + 1);<NEW_LINE>a22 = border.get(x + 1, y + 1);<NEW_LINE>}<NEW_LINE>gradient.y = -(a00 + a01 + a02);<NEW_LINE>gradient.y += (a20 + a21 + a22);<NEW_LINE>gradient.x = -(a00 + a10 + a20);<NEW_LINE>gradient.x += (a02 + a12 + a22);<NEW_LINE>return gradient;<NEW_LINE>} | data[tl + 2 * s]; |
1,791,237 | private EntityData.Entity serializeEntityFull(EntityRef entityRef, FieldSerializeCheck<Component> fieldCheck) {<NEW_LINE>EntityData.Entity.Builder entity = EntityData.Entity.newBuilder();<NEW_LINE>if (!ignoringEntityId) {<NEW_LINE>entity.setId(entityRef.getId());<NEW_LINE>}<NEW_LINE>entity.setAlwaysRelevant(entityRef.isAlwaysRelevant());<NEW_LINE>EntityRef owner = entityRef.getOwner();<NEW_LINE>if (owner.exists()) {<NEW_LINE>entity.<MASK><NEW_LINE>}<NEW_LINE>EntityScope scope = entityRef.getScope();<NEW_LINE>if (scope != null) {<NEW_LINE>switch(scope) {<NEW_LINE>case GLOBAL:<NEW_LINE>entity.setScope(GLOBAL);<NEW_LINE>break;<NEW_LINE>case SECTOR:<NEW_LINE>entity.setScope(SECTOR);<NEW_LINE>break;<NEW_LINE>case CHUNK:<NEW_LINE>entity.setScope(CHUNK);<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (Component component : entityRef.iterateComponents()) {<NEW_LINE>if (!componentSerializeCheck.serialize(componentLibrary.getMetadata(component.getClass()))) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>EntityData.Component componentData = componentSerializer.serialize(component, fieldCheck);<NEW_LINE>if (componentData != null) {<NEW_LINE>entity.addComponent(componentData);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return entity.build();<NEW_LINE>} | setOwner(owner.getId()); |
43,858 | final UploadLayerPartResult executeUploadLayerPart(UploadLayerPartRequest uploadLayerPartRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(uploadLayerPartRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE><MASK><NEW_LINE>Request<UploadLayerPartRequest> request = null;<NEW_LINE>Response<UploadLayerPartResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new UploadLayerPartRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(uploadLayerPartRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "ECR");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UploadLayerPart");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<UploadLayerPartResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UploadLayerPartResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | awsRequestMetrics.startEvent(Field.ClientExecuteTime); |
1,323,614 | protected int executeInsert(DriverState state, String sql, SupplyValueFunction func, Enumeration<Object[]> generator) throws SQLException {<NEW_LINE>Objects.requireNonNull(generator);<NEW_LINE>final Connection conn = state.getConnection();<NEW_LINE>int rows = 0;<NEW_LINE>if ("table".equals(INSERT_MODE)) {<NEW_LINE>sql = sql.substring(0, sql.indexOf('\n') + 1);<NEW_LINE>} else if ("input".equals(INSERT_MODE)) {<NEW_LINE>sql = sql.substring(0, sql.indexOf('\n')<MASK><NEW_LINE>}<NEW_LINE>if (state.usePreparedStatement()) {<NEW_LINE>try (PreparedStatement s = conn.prepareStatement(sql)) {<NEW_LINE>rows = processBatch(s, sql, func, generator);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>try (Statement s = conn.createStatement()) {<NEW_LINE>rows = processBatch(s, sql, func, generator);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return rows;<NEW_LINE>} | ).replaceFirst("--", ""); |
374,711 | public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {<NEW_LINE>detachAndScrapAttachedViews(recycler);<NEW_LINE>int widthUsed = 0;<NEW_LINE>int heightUsed = 0;<NEW_LINE>int lineHeight = 0;<NEW_LINE>int itemsCountOneLine = 0;<NEW_LINE>for (int i = 0; i < getItemCount(); i++) {<NEW_LINE>View child = recycler.getViewForPosition(i);<NEW_LINE>addView(child);<NEW_LINE>measureChildWithMargins(child, widthUsed, heightUsed);<NEW_LINE>int width = getDecoratedMeasuredWidth(child);<NEW_LINE>int height = getDecoratedMeasuredHeight(child);<NEW_LINE>lineHeight = Math.max(lineHeight, height);<NEW_LINE>if (widthUsed + width >= getWidth()) {<NEW_LINE>widthUsed = 0;<NEW_LINE>if (itemsCountOneLine > 0) {<NEW_LINE>itemsCountOneLine = -1;<NEW_LINE>heightUsed += lineHeight;<NEW_LINE>child.forceLayout();<NEW_LINE>measureChildWithMargins(child, widthUsed, heightUsed);<NEW_LINE>width = getDecoratedMeasuredWidth(child);<NEW_LINE>height = getDecoratedMeasuredHeight(child);<NEW_LINE>}<NEW_LINE>lineHeight = 0;<NEW_LINE>}<NEW_LINE>layoutDecorated(child, widthUsed, heightUsed, <MASK><NEW_LINE>widthUsed += width;<NEW_LINE>itemsCountOneLine++;<NEW_LINE>}<NEW_LINE>} | widthUsed + width, heightUsed + height); |
1,437,772 | public boolean add(Session session) {<NEW_LINE><MASK><NEW_LINE>try (Span span = tracer.getCurrentContext().createSpan("MSET sessionUriKey <sessionUri> capabilitiesKey <capabilities> ")) {<NEW_LINE>Map<String, EventAttributeValue> attributeMap = new HashMap<>();<NEW_LINE>SESSION_ID.accept(span, session.getId());<NEW_LINE>SESSION_ID_EVENT.accept(attributeMap, session.getId());<NEW_LINE>CAPABILITIES.accept(span, session.getCapabilities());<NEW_LINE>CAPABILITIES_EVENT.accept(attributeMap, session.getCapabilities());<NEW_LINE>setCommonSpanAttributes(span);<NEW_LINE>setCommonEventAttributes(attributeMap);<NEW_LINE>String uriKey = uriKey(session.getId());<NEW_LINE>String uriValue = session.getUri().toString();<NEW_LINE>String stereotypeKey = stereotypeKey(session.getId());<NEW_LINE>String stereotypeJson = JSON.toJson(session.getStereotype());<NEW_LINE>String capabilitiesKey = capabilitiesKey(session.getId());<NEW_LINE>String capabilitiesJson = JSON.toJson(session.getCapabilities());<NEW_LINE>String startKey = startKey(session.getId());<NEW_LINE>String startValue = JSON.toJson(session.getStartTime());<NEW_LINE>span.setAttribute(REDIS_URI_KEY, uriKey);<NEW_LINE>span.setAttribute(REDIS_URI_VALUE, uriValue);<NEW_LINE>span.setAttribute(REDIS_CAPABILITIES_KEY, capabilitiesKey);<NEW_LINE>span.setAttribute(REDIS_CAPABILITIES_VALUE, capabilitiesJson);<NEW_LINE>span.setAttribute(DATABASE_OPERATION, "MSET");<NEW_LINE>attributeMap.put(REDIS_URI_KEY, EventAttribute.setValue(uriKey));<NEW_LINE>attributeMap.put(REDIS_URI_VALUE, EventAttribute.setValue(uriValue));<NEW_LINE>attributeMap.put(REDIS_CAPABILITIES_KEY, EventAttribute.setValue(capabilitiesKey));<NEW_LINE>attributeMap.put(REDIS_CAPABILITIES_VALUE, EventAttribute.setValue(capabilitiesJson));<NEW_LINE>attributeMap.put(REDIS_START_KEY, EventAttribute.setValue(startKey));<NEW_LINE>attributeMap.put(REDIS_START_VALUE, EventAttribute.setValue(startValue));<NEW_LINE>attributeMap.put(DATABASE_OPERATION, EventAttribute.setValue("MSET"));<NEW_LINE>span.addEvent("Inserted into the database", attributeMap);<NEW_LINE>connection.mset(ImmutableMap.of(uriKey, uriValue, stereotypeKey, stereotypeJson, capabilitiesKey, capabilitiesJson, startKey, startValue));<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>} | Require.nonNull("Session to add", session); |
622,574 | public static APIRecoverDataVolumeEvent __example__() {<NEW_LINE>APIRecoverDataVolumeEvent event = new APIRecoverDataVolumeEvent();<NEW_LINE>String volumeUuid = uuid();<NEW_LINE>VolumeInventory vol = new VolumeInventory();<NEW_LINE>vol.setName("test-volume");<NEW_LINE>vol.setCreateDate(new Timestamp(org.zstack.header.message.DocUtils.date));<NEW_LINE>vol.setLastOpDate(new Timestamp(org.zstack.header.message.DocUtils.date));<NEW_LINE>vol.setType(VolumeType.Root.toString());<NEW_LINE>vol.setUuid(volumeUuid);<NEW_LINE>vol.setSize(SizeUnit.GIGABYTE.toByte(100));<NEW_LINE>vol.setActualSize(SizeUnit.GIGABYTE.toByte(20));<NEW_LINE>vol.setDeviceId(0);<NEW_LINE>vol.setState(VolumeState.Enabled.toString());<NEW_LINE>vol.setFormat("qcow2");<NEW_LINE>vol.setDiskOfferingUuid(uuid());<NEW_LINE>vol.setInstallPath(String.format<MASK><NEW_LINE>vol.setStatus(VolumeStatus.Ready.toString());<NEW_LINE>vol.setPrimaryStorageUuid(uuid());<NEW_LINE>vol.setVmInstanceUuid(uuid());<NEW_LINE>vol.setRootImageUuid(uuid());<NEW_LINE>event.setInventory(vol);<NEW_LINE>return event;<NEW_LINE>} | ("/zstack_ps/rootVolumes/acct-36c27e8ff05c4780bf6d2fa65700f22e/vol-%s/%s.qcow2", volumeUuid, volumeUuid)); |
1,026,027 | private <T> String batchUpload(String batchName, List<T> models) throws WeixinException {<NEW_LINE>StringWriter writer = new StringWriter();<NEW_LINE>try {<NEW_LINE>JSONObject csvObj = JSON.parseObject(weixinBundle().getString(batchName));<NEW_LINE>JSONArray columns = csvObj.getJSONArray("column");<NEW_LINE>writer.write(csvObj.getString("header"));<NEW_LINE>final Map<String, Object> column = new <MASK><NEW_LINE>for (Object col : columns) {<NEW_LINE>column.put(col.toString(), "");<NEW_LINE>}<NEW_LINE>writer.write("\r\n");<NEW_LINE>for (T model : models) {<NEW_LINE>JSON.toJSONString(model, new PropertyFilter() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public boolean apply(Object object, String name, Object value) {<NEW_LINE>if (column.containsKey(name)) {<NEW_LINE>if (value instanceof Collection) {<NEW_LINE>column.put(name, StringUtil.join(((Collection<?>) value).iterator(), ';'));<NEW_LINE>} else {<NEW_LINE>column.put(name, value);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>});<NEW_LINE>writer.write(StringUtil.join(column.values(), ','));<NEW_LINE>writer.write("\r\n");<NEW_LINE>}<NEW_LINE>return uploadMedia(0, new ByteArrayInputStream(writer.getBuffer().toString().getBytes(Consts.UTF_8)), batchName).getMediaId();<NEW_LINE>} finally {<NEW_LINE>try {<NEW_LINE>writer.close();<NEW_LINE>} catch (IOException e) {<NEW_LINE>;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | LinkedHashMap<String, Object>(); |
727,756 | public void executeNonQueryPlan(ExecutNonQueryReq request, AsyncMethodCallback<TSStatus> resultHandler) {<NEW_LINE>if (member.getCharacter() != NodeCharacter.LEADER) {<NEW_LINE>// forward the plan to the leader<NEW_LINE>AsyncClient client = member.getAsyncClient(member.getLeader());<NEW_LINE>if (client != null) {<NEW_LINE>try {<NEW_LINE>client.executeNonQueryPlan(request, resultHandler);<NEW_LINE>} catch (TException e) {<NEW_LINE>resultHandler.onError(e);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>TSStatus status = member.executeNonQueryPlan(request);<NEW_LINE>resultHandler.onComplete(StatusUtils.getStatus(status, new EndPoint(member.getThisNode().getClientIp(), member.getThisNode().getClientPort())));<NEW_LINE>} catch (Exception e) {<NEW_LINE>resultHandler.onError(e);<NEW_LINE>}<NEW_LINE>} | resultHandler.onComplete(StatusUtils.NO_LEADER); |
581,751 | public void visit(BLangTypeInit typeInitExpr) {<NEW_LINE>typeInitExpr.<MASK><NEW_LINE>BLangNode parent = typeInitExpr.initInvocation.parent;<NEW_LINE>if (parent != null && parent.getKind() == NodeKind.OBJECT_CTOR_EXPRESSION) {<NEW_LINE>BLangObjectConstructorExpression oce = (BLangObjectConstructorExpression) parent;<NEW_LINE>BLangClassDefinition dirtyOceClass = oce.classNode;<NEW_LINE>if (dirtyOceClass.hasClosureVars && classDef.oceEnvData.closureDesugaringInProgress) {<NEW_LINE>// below lines are probably not needed after proper handling<NEW_LINE>dirtyOceClass.hasClosureVars = false;<NEW_LINE>OCEDynamicEnvironmentData dirtyOceEnvData = dirtyOceClass.oceEnvData;<NEW_LINE>dirtyOceEnvData.isDirty = true;<NEW_LINE>OCEDynamicEnvironmentData currentClassOceData = classDef.oceEnvData;<NEW_LINE>currentClassOceData.closureBlockSymbols.removeAll(dirtyOceEnvData.closureBlockSymbols);<NEW_LINE>currentClassOceData.closureFuncSymbols.removeAll(dirtyOceEnvData.closureFuncSymbols);<NEW_LINE>dirtyOceEnvData.parents.remove(classDef);<NEW_LINE>for (BLangSimpleVarRef simpleVarRef : dirtyOceEnvData.desugaredClosureVars) {<NEW_LINE>dlog.error(simpleVarRef.pos, DiagnosticErrorCode.UNSUPPORTED_MULTILEVEL_CLOSURES, simpleVarRef);<NEW_LINE>}<NEW_LINE>visit(dirtyOceClass);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>result = typeInitExpr;<NEW_LINE>} | initInvocation = rewriteExpr(typeInitExpr.initInvocation); |
287,763 | public static SnapshotInfo readFrom(final StreamInput in) throws IOException {<NEW_LINE>final Snapshot snapshot;<NEW_LINE>if (in.getVersion().onOrAfter(GetSnapshotsRequest.PAGINATED_GET_SNAPSHOTS_VERSION)) {<NEW_LINE>snapshot = new Snapshot(in);<NEW_LINE>} else {<NEW_LINE>snapshot = new Snapshot(UNKNOWN_REPO_NAME, new SnapshotId(in));<NEW_LINE>}<NEW_LINE>final List<String> indices = in.readStringList();<NEW_LINE>final SnapshotState state = in.readBoolean() ? SnapshotState.fromValue(in.readByte()) : null;<NEW_LINE>final String reason = in.readOptionalString();<NEW_LINE>final long startTime = in.readVLong();<NEW_LINE>final long endTime = in.readVLong();<NEW_LINE>final int totalShards = in.readVInt();<NEW_LINE>final int successfulShards = in.readVInt();<NEW_LINE>final List<SnapshotShardFailure> shardFailures = in.readList(SnapshotShardFailure::new);<NEW_LINE>final Version version = in.readBoolean() ? Version.readVersion(in) : null;<NEW_LINE>final Boolean includeGlobalState = in.readOptionalBoolean();<NEW_LINE>final Map<String, Object<MASK><NEW_LINE>final List<String> dataStreams = in.readStringList();<NEW_LINE>final List<SnapshotFeatureInfo> featureStates = in.readList(SnapshotFeatureInfo::new);<NEW_LINE>final Map<String, IndexSnapshotDetails> indexSnapshotDetails = in.readMap(StreamInput::readString, IndexSnapshotDetails::new);<NEW_LINE>return new SnapshotInfo(snapshot, indices, dataStreams, featureStates, reason, version, startTime, endTime, totalShards, successfulShards, shardFailures, includeGlobalState, userMetadata, state, indexSnapshotDetails);<NEW_LINE>} | > userMetadata = in.readMap(); |
1,073,194 | @Produces({ "application/json" })<NEW_LINE>public Response filterAuthenticatedUsers(@QueryParam("searchTerm") String searchTerm, @QueryParam("selectedPage") Integer selectedPage, @QueryParam("itemsPerPage") Integer itemsPerPage, @QueryParam("sortKey") String sortKey) {<NEW_LINE>User authUser;<NEW_LINE>try {<NEW_LINE>authUser = this.findUserOrDie();<NEW_LINE>} catch (AbstractApiBean.WrappedResponse ex) {<NEW_LINE>return error(Response.Status.FORBIDDEN, BundleUtil.getStringFromBundle("dashboard.list_users.api.auth.invalid_apikey"));<NEW_LINE>}<NEW_LINE>if (!authUser.isSuperuser()) {<NEW_LINE>return error(Response.Status.FORBIDDEN, BundleUtil.getStringFromBundle("dashboard.list_users.api.auth.not_superuser"));<NEW_LINE>}<NEW_LINE>UserListMaker userListMaker = new UserListMaker(userService);<NEW_LINE>// String sortKey = null;<NEW_LINE>UserListResult userListResult = userListMaker.runUserSearch(<MASK><NEW_LINE>return ok(userListResult.toJSON());<NEW_LINE>} | searchTerm, itemsPerPage, selectedPage, sortKey); |
251,569 | private static AuthnRequest parseRequest(AbstractSaml2AuthenticationRequest request) {<NEW_LINE>if (request == null) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>String samlRequest = request.getSamlRequest();<NEW_LINE>if (!StringUtils.hasText(samlRequest)) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>if (request.getBinding() == Saml2MessageBinding.REDIRECT) {<NEW_LINE>samlRequest = Saml2Utils.samlInflate(Saml2Utils.samlDecode(samlRequest));<NEW_LINE>} else {<NEW_LINE>samlRequest = new String(Saml2Utils.samlDecode(samlRequest), StandardCharsets.UTF_8);<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>Document document = XMLObjectProviderRegistrySupport.getParserPool().parse(new ByteArrayInputStream(samlRequest.<MASK><NEW_LINE>Element element = document.getDocumentElement();<NEW_LINE>return (AuthnRequest) authnRequestUnmarshaller.unmarshall(element);<NEW_LINE>} catch (Exception ex) {<NEW_LINE>String message = "Failed to deserialize associated authentication request [" + ex.getMessage() + "]";<NEW_LINE>throw createAuthenticationException(Saml2ErrorCodes.MALFORMED_REQUEST_DATA, message, ex);<NEW_LINE>}<NEW_LINE>} | getBytes(StandardCharsets.UTF_8))); |
450,418 | public void validatePeriods(final I_C_Flatrate_Term term) {<NEW_LINE>if (term.getStartDate() != null && !term.isProcessed()) {<NEW_LINE>Services.get(IFlatrateBL<MASK><NEW_LINE>setMasterEndDate(term);<NEW_LINE>}<NEW_LINE>final Properties ctx = InterfaceWrapperHelper.getCtx(term);<NEW_LINE>final String trxName = InterfaceWrapperHelper.getTrxName(term);<NEW_LINE>final List<String> errors = new ArrayList<>();<NEW_LINE>final IMsgBL msgBL = Services.get(IMsgBL.class);<NEW_LINE>if (term.getStartDate() != null && term.getEndDate() != null && !X_C_Flatrate_Conditions.TYPE_CONDITIONS_Subscription.equals(term.getType_Conditions())) {<NEW_LINE>final ICalendarDAO calendarDAO = Services.get(ICalendarDAO.class);<NEW_LINE>final I_C_Calendar invoicingCal = term.getC_Flatrate_Conditions().getC_Flatrate_Transition().getC_Calendar_Contract();<NEW_LINE>final List<I_C_Period> periodsOfTerm = calendarDAO.retrievePeriods(ctx, invoicingCal, term.getStartDate(), term.getEndDate(), trxName);<NEW_LINE>if (periodsOfTerm.isEmpty()) {<NEW_LINE>errors.add(msgBL.getMsg(ctx, MSG_TERM_ERROR_YEAR_WITHOUT_PERIODS_2P, new Object[] { term.getStartDate(), term.getEndDate() }));<NEW_LINE>} else {<NEW_LINE>if (periodsOfTerm.get(0).getStartDate().after(term.getStartDate())) {<NEW_LINE>errors.add(msgBL.getMsg(ctx, MSG_TERM_ERROR_PERIOD_START_DATE_AFTER_TERM_START_DATE_2P, new Object[] { term.getStartDate(), invoicingCal.getName() }));<NEW_LINE>}<NEW_LINE>final I_C_Period lastPeriodOfTerm = periodsOfTerm.get(periodsOfTerm.size() - 1);<NEW_LINE>if (lastPeriodOfTerm.getEndDate().before(term.getEndDate())) {<NEW_LINE>errors.add(msgBL.getMsg(ctx, MSG_TERM_ERROR_PERIOD_END_DATE_BEFORE_TERM_END_DATE_2P, new Object[] { lastPeriodOfTerm.getEndDate(), invoicingCal.getName() }));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (!errors.isEmpty()) {<NEW_LINE>throw new AdempiereException(concatStrings(errors)).markAsUserValidationError();<NEW_LINE>}<NEW_LINE>} | .class).updateNoticeDateAndEndDate(term); |
1,586,331 | public void propertyChanged(int property) {<NEW_LINE>String type = "unknown";<NEW_LINE>if (property == SpeedManagerListener.PR_ASN) {<NEW_LINE>type = "ASN change";<NEW_LINE>mon.readFromPersistentMap();<NEW_LINE>mon.updateFromCOConfigManager();<NEW_LINE>SMSearchLogger.log("ASN change.");<NEW_LINE>} else if (property == SpeedManagerListener.PR_DOWN_CAPACITY) {<NEW_LINE>type = "download capacity";<NEW_LINE>SpeedManagerLimitEstimate pmEst = PingSpaceMon.getDownloadLimit();<NEW_LINE>SpeedManagerLimitEstimate smEst = PingSpaceMon.getDownloadEstCapacity();<NEW_LINE>SMSearchLogger.log(<MASK><NEW_LINE>SMSearchLogger.log(" download - estimated capacity: " + smEst.getString());<NEW_LINE>mon.notifyDownload(smEst);<NEW_LINE>} else if (property == SpeedManagerListener.PR_UP_CAPACITY) {<NEW_LINE>type = "upload capacity";<NEW_LINE>SpeedManagerLimitEstimate shortTermLimit = PingSpaceMon.getUploadLimit(false);<NEW_LINE>SpeedManagerLimitEstimate pmEst = PingSpaceMon.getUploadLimit(true);<NEW_LINE>SpeedManagerLimitEstimate smEst = PingSpaceMon.getUploadEstCapacity();<NEW_LINE>SMSearchLogger.log(" upload - short term limit: " + shortTermLimit.getString());<NEW_LINE>SMSearchLogger.log(" upload - persistent limit: " + pmEst.getString());<NEW_LINE>SMSearchLogger.log(" upload - estimated capacity: " + smEst.getString());<NEW_LINE>mon.notifyUpload(smEst);<NEW_LINE>}<NEW_LINE>SpeedManagerLogger.log("Updated from SpeedManagerPingMapper property=" + type);<NEW_LINE>} | " download - persistent limit: " + pmEst.getString()); |
501,982 | protected void writeIndexGen(final RepositoryData repositoryData, final long repositoryStateId) throws IOException {<NEW_LINE>// can not write to a read only repository<NEW_LINE>assert isReadOnly() == false;<NEW_LINE>final long currentGen = latestIndexBlobId();<NEW_LINE>if (repositoryStateId != SnapshotsInProgress.UNDEFINED_REPOSITORY_STATE_ID && currentGen != repositoryStateId) {<NEW_LINE>// the index file was updated by a concurrent operation, so we were operating on stale<NEW_LINE>// repository data<NEW_LINE>throw new RepositoryException(metadata.name(), "concurrent modification of the index-N file, expected current generation [" + repositoryStateId + "], actual current generation [" + currentGen + "] - possibly due to simultaneous snapshot deletion requests");<NEW_LINE>}<NEW_LINE>final long newGen = currentGen + 1;<NEW_LINE>final BytesReference snapshotsBytes;<NEW_LINE>try (BytesStreamOutput bStream = new BytesStreamOutput()) {<NEW_LINE>try (StreamOutput stream = new OutputStreamStreamOutput(bStream)) {<NEW_LINE>XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, stream);<NEW_LINE>repositoryData.snapshotsToXContent(builder, ToXContent.EMPTY_PARAMS);<NEW_LINE>builder.close();<NEW_LINE>}<NEW_LINE>snapshotsBytes = bStream.bytes();<NEW_LINE>}<NEW_LINE>// write the index file<NEW_LINE>final String indexBlob = INDEX_FILE_PREFIX + Long.toString(newGen);<NEW_LINE>logger.debug("Repository [{}] writing new index generational blob [{}]", metadata.name(), indexBlob);<NEW_LINE>writeAtomic(indexBlob, snapshotsBytes, true);<NEW_LINE>// delete the N-2 index file if it exists, keep the previous one around as a backup<NEW_LINE>if (isReadOnly() == false && newGen - 2 >= 0) {<NEW_LINE>final String oldSnapshotIndexFile = INDEX_FILE_PREFIX + Long.toString(newGen - 2);<NEW_LINE>blobContainer().deleteBlobIgnoringIfNotExists(oldSnapshotIndexFile);<NEW_LINE>}<NEW_LINE>// write the current generation to the index-latest file<NEW_LINE>final BytesReference genBytes;<NEW_LINE>try (BytesStreamOutput bStream = new BytesStreamOutput()) {<NEW_LINE>bStream.writeLong(newGen);<NEW_LINE>genBytes = bStream.bytes();<NEW_LINE>}<NEW_LINE>logger.debug("Repository [{}] updating index.latest with generation [{}]", metadata.name(), newGen);<NEW_LINE><MASK><NEW_LINE>} | writeAtomic(INDEX_LATEST_BLOB, genBytes, false); |
1,692,551 | protected IStatus run(IProgressMonitor monitor) {<NEW_LINE>MultiStatus errors = new MultiStatus(GitPlugin.PLUGIN_ID, <MASK><NEW_LINE>try {<NEW_LINE>// $NON-NLS-1$<NEW_LINE>monitor.beginTask("", IProgressMonitor.UNKNOWN);<NEW_LINE>while (true) {<NEW_LINE>if (monitor.isCanceled()) {<NEW_LINE>throw new OperationCanceledException();<NEW_LINE>}<NEW_LINE>// FIXME What if the refresh fails? Should we retry? Can we?<NEW_LINE>IStatus status;<NEW_LINE>if (refreshAll.compareAndSet(true, false)) {<NEW_LINE>// Clear all the requests out, because we'll refresh everything anyways<NEW_LINE>synchronized (fRequests) {<NEW_LINE>fRequests = new HashSet<IPath>(3);<NEW_LINE>}<NEW_LINE>// refresh everything<NEW_LINE>status = index.refresh(monitor);<NEW_LINE>} else {<NEW_LINE>// We were asked to refresh only some files.<NEW_LINE>// Take all the requests off the queue<NEW_LINE>List<IPath> copy;<NEW_LINE>synchronized (fRequests) {<NEW_LINE>if (fRequests.isEmpty()) {<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>copy = new ArrayList<IPath>(fRequests);<NEW_LINE>fRequests = new HashSet<IPath>(3);<NEW_LINE>}<NEW_LINE>// Now refresh all the paths we had<NEW_LINE>status = index.refresh(true, copy, monitor);<NEW_LINE>}<NEW_LINE>if (!status.isOK()) {<NEW_LINE>errors.merge(status);<NEW_LINE>}<NEW_LINE>// be polite to other threads (no effect on some platforms)<NEW_LINE>Thread.yield();<NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE>monitor.done();<NEW_LINE>}<NEW_LINE>if (!errors.isOK()) {<NEW_LINE>// Log this, but don't actually return an error status, or it bubbles up to UI in error dialog<NEW_LINE>IdeLog.log(GitPlugin.getDefault(), errors);<NEW_LINE>}<NEW_LINE>return Status.OK_STATUS;<NEW_LINE>} | 1, Messages.GitIndexRefreshJob_ErrorMsg, null); |
162,399 | public static ExchangeMetaData adaptToExchangeMetaData(ExchangeMetaData originalMetaData, Map<String, KrakenAssetPair> krakenPairs, Map<String, KrakenAsset> krakenAssets) {<NEW_LINE>Map<CurrencyPair, CurrencyPairMetaData> pairs = new HashMap<>();<NEW_LINE>// add assets before pairs to Utils!<NEW_LINE>KrakenUtils.setKrakenAssets(krakenAssets);<NEW_LINE>KrakenUtils.setKrakenAssetPairs(krakenPairs);<NEW_LINE>for (String krakenPairCode : krakenPairs.keySet()) {<NEW_LINE>// skip dark markets!<NEW_LINE>if (!krakenPairCode.endsWith(".d")) {<NEW_LINE>KrakenAssetPair krakenPair = krakenPairs.get(krakenPairCode);<NEW_LINE>pairs.put(adaptCurrencyPair(krakenPairCode), adaptPair(krakenPair, pairs.get(adaptCurrencyPair(krakenPairCode))));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>Map<Currency, CurrencyMetaData> <MASK><NEW_LINE>for (String krakenAssetCode : krakenAssets.keySet()) {<NEW_LINE>KrakenAsset krakenAsset = krakenAssets.get(krakenAssetCode);<NEW_LINE>Currency currencyCode = KrakenAdapters.adaptCurrency(krakenAssetCode);<NEW_LINE>currencies.put(currencyCode, new CurrencyMetaData(krakenAsset.getScale(), null));<NEW_LINE>}<NEW_LINE>return new ExchangeMetaData(pairs, currencies, originalMetaData == null ? null : originalMetaData.getPublicRateLimits(), originalMetaData == null ? null : originalMetaData.getPrivateRateLimits(), originalMetaData == null ? null : originalMetaData.isShareRateLimits());<NEW_LINE>} | currencies = new HashMap<>(); |
117,543 | protected void assertValidFindBy(FindBy findBy) {<NEW_LINE>if (findBy.how() != null) {<NEW_LINE>if (findBy.using() == null) {<NEW_LINE>throw new IllegalArgumentException("If you set the 'how' property, you must also set 'using'");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>Set<String> finders = new HashSet<>();<NEW_LINE>if (!"".equals(findBy.using()))<NEW_LINE>finders.add("how: " + findBy.using());<NEW_LINE>if (!"".equals(findBy.className()))<NEW_LINE>finders.add("class name:" + findBy.className());<NEW_LINE>if (!"".equals(findBy.css()))<NEW_LINE>finders.add("css:" + findBy.css());<NEW_LINE>if (!"".equals(findBy.id()))<NEW_LINE>finders.add("id: " + findBy.id());<NEW_LINE>if (!"".equals(findBy.linkText()))<NEW_LINE>finders.add("link text: " + findBy.linkText());<NEW_LINE>if (!"".equals(findBy.name()))<NEW_LINE>finders.add("name: " + findBy.name());<NEW_LINE>if (!"".equals(findBy.partialLinkText()))<NEW_LINE>finders.add("partial link text: " + findBy.partialLinkText());<NEW_LINE>if (!"".equals(findBy.tagName()))<NEW_LINE>finders.add("tag name: " + findBy.tagName());<NEW_LINE>if (!"".equals(findBy.xpath()))<NEW_LINE>finders.add(<MASK><NEW_LINE>// A zero count is okay: it means to look by name or id.<NEW_LINE>if (finders.size() > 1) {<NEW_LINE>throw new IllegalArgumentException(String.format("You must specify at most one location strategy. Number found: %d (%s)", finders.size(), finders.toString()));<NEW_LINE>}<NEW_LINE>} | "xpath: " + findBy.xpath()); |
488,410 | protected boolean loadFromCatalog(String basePhysicalIRI, ZipFile z) throws IOException {<NEW_LINE>ZipEntry yaml = z.stream().filter(e -> CATALOG_PATTERN.matcher(e.getName()).matches()).findFirst().orElse(null);<NEW_LINE>if (yaml == null) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse<MASK><NEW_LINE>NodeList uris = doc.getElementsByTagName("uri");<NEW_LINE>for (int i = 0; i < uris.getLength(); i++) {<NEW_LINE>// Catalogs do not have a way to indicate root ontologies; all ontologies will be<NEW_LINE>// considered root.<NEW_LINE>// Duplicate entries are unsupported; entries whose name starts with duplicate: will<NEW_LINE>// cause mismatches<NEW_LINE>Element e = (Element) uris.item(i);<NEW_LINE>IRI physicalIRI = IRI.create(basePhysicalIRI + e.getAttribute("uri"));<NEW_LINE>physicalRoots.add(physicalIRI);<NEW_LINE>String name = e.getAttribute("name");<NEW_LINE>if (name.startsWith("duplicate:")) {<NEW_LINE>name = name.replace("duplicate:", "");<NEW_LINE>}<NEW_LINE>logicalToPhysicalIRI.put(IRI.create(name), physicalIRI);<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} catch (SAXException | ParserConfigurationException e1) {<NEW_LINE>throw new IOException(e1);<NEW_LINE>}<NEW_LINE>} | (z.getInputStream(yaml)); |
1,555,702 | public void run() {<NEW_LINE>resultStatus = ExecutionStatus.RUNNING;<NEW_LINE>currentResultStatus = ExecutionStatus.RUNNING;<NEW_LINE>try {<NEW_LINE>// 1. init amClient<NEW_LINE>initAMClient();<NEW_LINE>checkEnd();<NEW_LINE>LOG.info("init amClient.");<NEW_LINE>// 2. get version from master<NEW_LINE>getCurrentJobVersion();<NEW_LINE>checkEnd();<NEW_LINE>LOG.info("get current job version.");<NEW_LINE>getTaskIndex();<NEW_LINE>LOG.info("get task index.");<NEW_LINE>// 3. register to master<NEW_LINE>registerNode();<NEW_LINE>checkEnd();<NEW_LINE>LOG.info("register node to application master.");<NEW_LINE>// 4. start heart beat<NEW_LINE>startHeartBeat();<NEW_LINE>LOG.info("start heart beat thread.");<NEW_LINE>// 5. wait for cluster running<NEW_LINE>waitClusterRunning();<NEW_LINE>LOG.info("wait for cluster to running status.");<NEW_LINE>// 6. get cluster<NEW_LINE>getClusterInfo();<NEW_LINE>Preconditions.checkNotNull(mlClusterDef, "Cannot get cluster def from AM");<NEW_LINE>checkEnd();<NEW_LINE>LOG.info("get cluster info.");<NEW_LINE>// 7. set machine learning context<NEW_LINE>resetMLContext();<NEW_LINE>checkEnd();<NEW_LINE>LOG.info("reset machine learning context.");<NEW_LINE>// 8. run python script<NEW_LINE>runScript();<NEW_LINE>checkEnd();<NEW_LINE>LOG.info("run script.");<NEW_LINE>currentResultStatus = ExecutionStatus.SUCCEED;<NEW_LINE>} catch (Exception e) {<NEW_LINE>if (e instanceof FlinkKillException || e instanceof InterruptedException) {<NEW_LINE>LOG.info("{} killed by flink.", mlContext.getIdentity());<NEW_LINE>currentResultStatus = ExecutionStatus.KILLED_BY_FLINK;<NEW_LINE>} else {<NEW_LINE>// no one ask for this thread to stop, thus there must be some error occurs<NEW_LINE>LOG.error("Got exception during python running", e);<NEW_LINE>mlContext.addFailNum();<NEW_LINE>currentResultStatus = ExecutionStatus.FAILED;<NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE><MASK><NEW_LINE>// set resultStatus value after node notified to am.<NEW_LINE>resultStatus = currentResultStatus;<NEW_LINE>}<NEW_LINE>} | stopExecution(currentResultStatus == ExecutionStatus.SUCCEED); |
1,379,444 | public void delete(Set<String> declarationNames) throws InvokerException {<NEW_LINE>Map<Identifier, GlobalVariable> queuedGlobalVars = new HashMap<>();<NEW_LINE>Map<Identifier, String> queuedModuleDclns = new HashMap<>();<NEW_LINE>for (String declarationName : declarationNames) {<NEW_LINE><MASK><NEW_LINE>if (globalVars.containsKey(identifier)) {<NEW_LINE>queuedGlobalVars.put(identifier, globalVars.get(identifier));<NEW_LINE>} else if (moduleDclns.containsKey(identifier)) {<NEW_LINE>queuedModuleDclns.put(identifier, moduleDclns.get(identifier));<NEW_LINE>} else {<NEW_LINE>addErrorDiagnostic(declarationName + " is not defined.\n" + "Please enter names of declarations that are already defined.");<NEW_LINE>throw new InvokerException();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>queuedGlobalVars.keySet().forEach(globalVars::remove);<NEW_LINE>queuedModuleDclns.keySet().forEach(moduleDclns::remove);<NEW_LINE>processCurrentState();<NEW_LINE>} catch (InvokerException e) {<NEW_LINE>globalVars.putAll(queuedGlobalVars);<NEW_LINE>moduleDclns.putAll(queuedModuleDclns);<NEW_LINE>addErrorDiagnostic("Deleting declaration(s) failed.");<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>} | Identifier identifier = new Identifier(declarationName); |
1,372,410 | public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {<NEW_LINE><MASK><NEW_LINE>reporter.setStatus("starting " + field + " ::host = " + hostName);<NEW_LINE>// sum long values<NEW_LINE>if (field.startsWith("l:")) {<NEW_LINE>long lSum = 0;<NEW_LINE>while (values.hasNext()) {<NEW_LINE>lSum += Long.parseLong(values.next().toString());<NEW_LINE>}<NEW_LINE>output.collect(key, new Text(String.valueOf(lSum)));<NEW_LINE>}<NEW_LINE>if (field.startsWith("min:")) {<NEW_LINE>long minVal = -1;<NEW_LINE>while (values.hasNext()) {<NEW_LINE>long value = Long.parseLong(values.next().toString());<NEW_LINE>if (minVal == -1) {<NEW_LINE>minVal = value;<NEW_LINE>} else {<NEW_LINE>if (value != 0 && value < minVal) {<NEW_LINE>minVal = value;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>output.collect(key, new Text(String.valueOf(minVal)));<NEW_LINE>}<NEW_LINE>if (field.startsWith("max:")) {<NEW_LINE>long maxVal = -1;<NEW_LINE>while (values.hasNext()) {<NEW_LINE>long value = Long.parseLong(values.next().toString());<NEW_LINE>if (maxVal == -1) {<NEW_LINE>maxVal = value;<NEW_LINE>} else {<NEW_LINE>if (value > maxVal) {<NEW_LINE>maxVal = value;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>output.collect(key, new Text(String.valueOf(maxVal)));<NEW_LINE>}<NEW_LINE>reporter.setStatus("finished " + field + " ::host = " + hostName);<NEW_LINE>} | String field = key.toString(); |
214,365 | public void processNewResult(Object newResult) {<NEW_LINE>Database db = ResultUtil.findDatabase(newResult);<NEW_LINE>SetDBIDs positiveIDs = DBIDUtil.ensureSet(DatabaseUtil.getObjectsByLabelMatch(db, positiveClassName));<NEW_LINE>if (positiveIDs.size() == 0) {<NEW_LINE>LOG.warning("Computing a P/R-G curve failed - no objects matched.");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>List<OutlierResult> <MASK><NEW_LINE>List<OrderingResult> ordResults = ResultUtil.getOrderingResults(newResult);<NEW_LINE>for (OutlierResult o : outResults) {<NEW_LINE>PRGCurve curve = PRGCEvaluation.materializePRGC(new OutlierScoreAdapter(positiveIDs, o));<NEW_LINE>Metadata.hierarchyOf(o).addChild(curve);<NEW_LINE>//<NEW_LINE>MeasurementGroup //<NEW_LINE>g = EvaluationResult.findOrCreate(o, EvaluationResult.RANKING).findOrCreateGroup("Evaluation measures");<NEW_LINE>if (!g.hasMeasure(AUPRGC_LABEL)) {<NEW_LINE>g.addMeasure(AUPRGC_LABEL, curve.getAUC(), 0., 1., false);<NEW_LINE>}<NEW_LINE>// Process them only once.<NEW_LINE>ordResults.remove(o.getOrdering());<NEW_LINE>}<NEW_LINE>for (OrderingResult r : ordResults) {<NEW_LINE>DBIDs sorted = r.order(r.getDBIDs());<NEW_LINE>PRGCurve curve = PRGCEvaluation.materializePRGC(new SimpleAdapter(positiveIDs, sorted.iter(), sorted.size()));<NEW_LINE>Metadata.hierarchyOf(r).addChild(curve);<NEW_LINE>//<NEW_LINE>MeasurementGroup //<NEW_LINE>g = EvaluationResult.findOrCreate(r, EvaluationResult.RANKING).findOrCreateGroup("Evaluation measures");<NEW_LINE>if (!g.hasMeasure(AUPRGC_LABEL)) {<NEW_LINE>g.addMeasure(AUPRGC_LABEL, curve.getAUC(), 0., 1., false);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | outResults = OutlierResult.getOutlierResults(newResult); |
951,662 | public EncryptionConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>EncryptionConfiguration encryptionConfiguration = new EncryptionConfiguration();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE><MASK><NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("NoEncryptionConfig", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>encryptionConfiguration.setNoEncryptionConfig(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("KMSEncryptionConfig", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>encryptionConfiguration.setKMSEncryptionConfig(KMSEncryptionConfigJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return encryptionConfiguration;<NEW_LINE>} | JsonToken token = context.getCurrentToken(); |
1,353,784 | public S3TagList requestRoomS3Tags(Long roomId, String xSdsAuthToken) throws ApiException {<NEW_LINE>Object localVarPostBody = null;<NEW_LINE>// verify the required parameter 'roomId' is set<NEW_LINE>if (roomId == null) {<NEW_LINE>throw new ApiException(400, "Missing the required parameter 'roomId' when calling requestRoomS3Tags");<NEW_LINE>}<NEW_LINE>// create path and map variables<NEW_LINE>String localVarPath = "/v4/nodes/rooms/{room_id}/s3_tags".replaceAll("\\{" + "room_id" + "\\}", apiClient.escapeString(roomId.toString()));<NEW_LINE>// query params<NEW_LINE>List<Pair> localVarQueryParams = new ArrayList<Pair>();<NEW_LINE>Map<String, String> localVarHeaderParams = new HashMap<String, String>();<NEW_LINE>Map<String, Object> localVarFormParams = new <MASK><NEW_LINE>if (xSdsAuthToken != null)<NEW_LINE>localVarHeaderParams.put("X-Sds-Auth-Token", apiClient.parameterToString(xSdsAuthToken));<NEW_LINE>final String[] localVarAccepts = { "application/json" };<NEW_LINE>final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);<NEW_LINE>final String[] localVarContentTypes = {};<NEW_LINE>final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);<NEW_LINE>String[] localVarAuthNames = new String[] { "oauth2" };<NEW_LINE>GenericType<S3TagList> localVarReturnType = new GenericType<S3TagList>() {<NEW_LINE>};<NEW_LINE>return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);<NEW_LINE>} | HashMap<String, Object>(); |
161,565 | protected void onDraw(Canvas canvas) {<NEW_LINE>if (mChecked) {<NEW_LINE>mPaint.setStyle(Paint.Style.FILL);<NEW_LINE>mPaint.setColor(mUncheckedBackgroundColor);<NEW_LINE>mPaint.setAlpha(255);<NEW_LINE>canvas.drawRoundRect(mOutline, mOutline.height() / 2, mOutline.height() / 2, mPaint);<NEW_LINE>mPaint.setStyle(Paint.Style.FILL);<NEW_LINE>mPaint.setColor(mCheckedBackgroundColor);<NEW_LINE>mPaint.setAlpha((int) (255 * 0.1));<NEW_LINE>canvas.drawRoundRect(mOutline, mOutline.height() / 2, mOutline.height() / 2, mPaint);<NEW_LINE>mPaint.setStyle(Paint.Style.STROKE);<NEW_LINE>mPaint.setStrokeWidth(mStrokeWidth);<NEW_LINE>mPaint.setColor(mCheckedBackgroundColor);<NEW_LINE>mPaint.setAlpha((int) (255 * 0f));<NEW_LINE>canvas.drawRoundRect(mOutline, mOutline.height() / 2, mOutline.<MASK><NEW_LINE>} else {<NEW_LINE>mPaint.setStyle(Paint.Style.FILL);<NEW_LINE>mPaint.setColor(mUncheckedBackgroundColor);<NEW_LINE>mPaint.setAlpha(255);<NEW_LINE>canvas.drawRoundRect(mOutline, mOutline.height() / 2, mOutline.height() / 2, mPaint);<NEW_LINE>}<NEW_LINE>super.onDraw(canvas);<NEW_LINE>} | height() / 2, mPaint); |
1,167,216 | protected void masterOperation(final UpdateSettingsRequest request, final ClusterState state, final ActionListener<AcknowledgedResponse> listener) {<NEW_LINE>final Index[] concreteIndices = indexNameExpressionResolver.concreteIndices(state, request);<NEW_LINE>UpdateSettingsClusterStateUpdateRequest clusterStateUpdateRequest = new UpdateSettingsClusterStateUpdateRequest().indices(concreteIndices).settings(request.settings()).setPreserveExisting(request.isPreserveExisting()).ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout());<NEW_LINE>updateSettingsService.updateSettings(clusterStateUpdateRequest, new ActionListener<ClusterStateUpdateResponse>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onResponse(ClusterStateUpdateResponse response) {<NEW_LINE>listener.onResponse(new AcknowledgedResponse<MASK><NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onFailure(Exception t) {<NEW_LINE>logger.debug(() -> new ParameterizedMessage("failed to update settings on indices [{}]", (Object) concreteIndices), t);<NEW_LINE>listener.onFailure(t);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | (response.isAcknowledged())); |
1,308,368 | public void onMapReady(@NonNull final MapboxMap mapboxMap) {<NEW_LINE>MultipleHeatmapStylingActivity.this.mapboxMap = mapboxMap;<NEW_LINE>mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onStyleLoaded(@NonNull final Style style) {<NEW_LINE>CameraPosition cameraPositionForFragmentMap = new CameraPosition.Builder().target(new LatLng(34.056684, -118.254002)).zoom(11.047).build();<NEW_LINE>mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPositionForFragmentMap), 2600);<NEW_LINE>try {<NEW_LINE>style.addSource(new GeoJsonSource(HEATMAP_SOURCE_ID, new URI("asset://la_heatmap_styling_points.geojson")));<NEW_LINE>} catch (URISyntaxException exception) {<NEW_LINE>Timber.d(exception);<NEW_LINE>}<NEW_LINE>initHeatmapColors();<NEW_LINE>initHeatmapRadiusStops();<NEW_LINE>initHeatmapIntensityStops();<NEW_LINE>addHeatmapLayer(style);<NEW_LINE>findViewById(R.id.switch_heatmap_style_fab).setOnClickListener(new View.OnClickListener() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onClick(View view) {<NEW_LINE>index++;<NEW_LINE>if (index == listOfHeatmapColors.length - 1) {<NEW_LINE>index = 0;<NEW_LINE>}<NEW_LINE>Layer heatmapLayer = style.getLayer(HEATMAP_LAYER_ID);<NEW_LINE>if (heatmapLayer != null) {<NEW_LINE>heatmapLayer.setProperties(heatmapColor(listOfHeatmapColors[index]), heatmapRadius(listOfHeatmapRadiusStops[index]), <MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>});<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | heatmapIntensity(listOfHeatmapIntensityStops[index])); |
155,746 | private void paintZoomIndicator(Graphics2D graphics) {<NEW_LINE>if (mZoom != 0) {<NEW_LINE>int width = getWidth() / 4;<NEW_LINE>int x = (getWidth() / 2) - (width / 2);<NEW_LINE>// Draw the outer window<NEW_LINE>graphics.drawRect(x, getHeight() - 12, width, 10);<NEW_LINE><MASK><NEW_LINE>int windowOffset = 0;<NEW_LINE>if (mDFTZoomWindowOffset != 0) {<NEW_LINE>windowOffset = (int) (((double) mDFTZoomWindowOffset / (double) mDFTSize) * width);<NEW_LINE>}<NEW_LINE>// Draw the zoom window<NEW_LINE>graphics.fillRect(x + windowOffset, getHeight() - 12, zoomWidth, 10);<NEW_LINE>// Draw the zoom text<NEW_LINE>graphics.drawString("Zoom: " + getZoomMultiplier() + "x", x + width + 3, getHeight() - 2);<NEW_LINE>}<NEW_LINE>} | int zoomWidth = width / getZoomMultiplier(); |
1,165,292 | public void process() {<NEW_LINE>JMeterContext context = getThreadContext();<NEW_LINE><MASK><NEW_LINE>List<String> jsonResponses = extractJsonResponse(context, vars);<NEW_LINE>String[] refNames = getRefNames().split(SEPARATOR);<NEW_LINE>String[] jsonPathExpressions = getJsonPathExpressions().split(SEPARATOR);<NEW_LINE>String[] defaultValues = getDefaultValues().split(SEPARATOR);<NEW_LINE>int[] matchNumbers = getMatchNumbersAsInt(defaultValues.length);<NEW_LINE>validateSameLengthOfArguments(refNames, jsonPathExpressions, defaultValues);<NEW_LINE>for (int i = 0; i < jsonPathExpressions.length; i++) {<NEW_LINE>int matchNumber = matchNumbers[i];<NEW_LINE>String currentRefName = refNames[i].trim();<NEW_LINE>String currentJsonPath = jsonPathExpressions[i].trim();<NEW_LINE>clearOldRefVars(vars, currentRefName);<NEW_LINE>try {<NEW_LINE>if (jsonResponses.isEmpty()) {<NEW_LINE>handleEmptyResponse(vars, defaultValues[i], currentRefName);<NEW_LINE>} else {<NEW_LINE>List<Object> extractedValues = extractValues(jsonResponses, currentJsonPath);<NEW_LINE>handleResult(vars, defaultValues[i], matchNumber, currentRefName, extractedValues);<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>if (log.isDebugEnabled()) {<NEW_LINE>log.error("Error processing JSON content in {}, message: {}", getName(), e.getLocalizedMessage(), e);<NEW_LINE>} else {<NEW_LINE>log.error("Error processing JSON content in {}, message: {}", getName(), e.getLocalizedMessage());<NEW_LINE>}<NEW_LINE>// if something goes wrong, add default value<NEW_LINE>vars.put(currentRefName, defaultValues[i]);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | JMeterVariables vars = context.getVariables(); |
1,418,637 | private void drawStabilityInfo() {<NEW_LINE>String at;<NEW_LINE>// // at M=<NEW_LINE>at = trans.get("RocketInfo.at") + UnitGroup.UNITS_COEFFICIENT.getDefaultUnit().toStringUnit(Application.getPreferences().getDefaultMach());<NEW_LINE>if (!Double.isNaN(aoa)) {<NEW_LINE>at += " " + ALPHA + "=" + UnitGroup.UNITS_ANGLE.getDefaultUnit().toStringUnit(aoa);<NEW_LINE>}<NEW_LINE>if (!Double.isNaN(theta)) {<NEW_LINE>at += " " + THETA + "=" + UnitGroup.UNITS_ANGLE.getDefaultUnit().toStringUnit(theta);<NEW_LINE>}<NEW_LINE>GlyphVector cgValue = createText(getCg());<NEW_LINE>GlyphVector cpValue = createText(getCp());<NEW_LINE>GlyphVector stabValue = createText(getStability());<NEW_LINE>// // CG:<NEW_LINE>GlyphVector cgText = createText(trans.get("RocketInfo.cgText"));<NEW_LINE>// // CP:<NEW_LINE>GlyphVector cpText = createText(trans.get("RocketInfo.cpText"));<NEW_LINE>// // Stability:<NEW_LINE>GlyphVector stabText = createText(trans.get("RocketInfo.stabText"));<NEW_LINE>GlyphVector atText = createSmallText(at);<NEW_LINE>// GlyphVector visual bounds drops the spaces, so we'll add them<NEW_LINE>FontMetrics fontMetrics = g2.getFontMetrics(cgText.getFont());<NEW_LINE>int spaceWidth = fontMetrics.stringWidth(" ");<NEW_LINE>Rectangle2D cgRect = cgValue.getVisualBounds();<NEW_LINE>Rectangle2D cpRect = cpValue.getVisualBounds();<NEW_LINE>Rectangle2D cgTextRect = cgText.getVisualBounds();<NEW_LINE><MASK><NEW_LINE>Rectangle2D stabRect = stabValue.getVisualBounds();<NEW_LINE>Rectangle2D stabTextRect = stabText.getVisualBounds();<NEW_LINE>Rectangle2D atTextRect = atText.getVisualBounds();<NEW_LINE>double unitWidth = MathUtil.max(cpRect.getWidth(), cgRect.getWidth(), stabRect.getWidth());<NEW_LINE>double textWidth = Math.max(cpTextRect.getWidth(), cgTextRect.getWidth());<NEW_LINE>// Add an extra space worth of width so the text doesn't run into the values<NEW_LINE>unitWidth = unitWidth + spaceWidth;<NEW_LINE>g2.setColor(Color.BLACK);<NEW_LINE>g2.drawGlyphVector(stabValue, (float) (x2 - stabRect.getWidth()), y1);<NEW_LINE>g2.drawGlyphVector(cgValue, (float) (x2 - cgRect.getWidth()), y1 + line);<NEW_LINE>g2.drawGlyphVector(cpValue, (float) (x2 - cpRect.getWidth()), y1 + 2 * line);<NEW_LINE>g2.drawGlyphVector(stabText, (float) (x2 - unitWidth - stabTextRect.getWidth()), y1);<NEW_LINE>g2.drawGlyphVector(cgText, (float) (x2 - unitWidth - cgTextRect.getWidth()), y1 + line);<NEW_LINE>g2.drawGlyphVector(cpText, (float) (x2 - unitWidth - cpTextRect.getWidth()), y1 + 2 * line);<NEW_LINE>cgCaret.setPosition(x2 - unitWidth - textWidth - 10, y1 + line - 0.3 * line);<NEW_LINE>cgCaret.paint(g2, 1.7);<NEW_LINE>cpCaret.setPosition(x2 - unitWidth - textWidth - 10, y1 + 2 * line - 0.3 * line);<NEW_LINE>cpCaret.paint(g2, 1.7);<NEW_LINE>float atPos;<NEW_LINE>if (unitWidth + textWidth + 10 > atTextRect.getWidth()) {<NEW_LINE>atPos = (float) (x2 - (unitWidth + textWidth + 10 + atTextRect.getWidth()) / 2);<NEW_LINE>} else {<NEW_LINE>atPos = (float) (x2 - atTextRect.getWidth());<NEW_LINE>}<NEW_LINE>g2.setColor(Color.GRAY);<NEW_LINE>g2.drawGlyphVector(atText, atPos, y1 + 3 * line);<NEW_LINE>} | Rectangle2D cpTextRect = cpText.getVisualBounds(); |
938,415 | public static <T> T injectBean(Class<T> beanClass, String beanName, HttpServletRequest request, boolean skipConvertError) {<NEW_LINE>Object bean = createInstance(beanClass);<NEW_LINE>String modelNameAndDot = StrKit.notBlank(beanName) ? beanName + "." : null;<NEW_LINE>TypeConverter converter = TypeConverter.me();<NEW_LINE>Map<String, String[]> parasMap = request.getParameterMap();<NEW_LINE>Method[] methods = beanClass.getMethods();<NEW_LINE>for (Method method : methods) {<NEW_LINE>String methodName = method.getName();<NEW_LINE>if (methodName.startsWith("set") == false || methodName.length() <= 3) {<NEW_LINE>// only setter method<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>Class<?>[] types = method.getParameterTypes();<NEW_LINE>if (types.length != 1) {<NEW_LINE>// only one parameter<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>String attrName = StrKit.firstCharToLowerCase(methodName.substring(3));<NEW_LINE>String paraName = modelNameAndDot <MASK><NEW_LINE>if (parasMap.containsKey(paraName)) {<NEW_LINE>try {<NEW_LINE>String paraValue = request.getParameter(paraName);<NEW_LINE>Object value = paraValue != null ? converter.convert(types[0], paraValue) : null;<NEW_LINE>method.invoke(bean, value);<NEW_LINE>} catch (Exception e) {<NEW_LINE>if (skipConvertError == false) {<NEW_LINE>// throw new RuntimeException(e);<NEW_LINE>throw new RuntimeException("Can not convert parameter: " + paraName, e);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return (T) bean;<NEW_LINE>} | != null ? modelNameAndDot + attrName : attrName; |
1,625,087 | public User login() throws UnauthenticatedException {<NEW_LINE>String username = "";<NEW_LINE>if (mConf.isSet(PropertyKey.SECURITY_LOGIN_USERNAME)) {<NEW_LINE>username = mConf.getString(PropertyKey.SECURITY_LOGIN_USERNAME);<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>// Use the class loader of User.class to construct the LoginContext. LoginContext uses this<NEW_LINE>// class loader to dynamically instantiate login modules. This enables<NEW_LINE>// Subject#getPrincipals to use reflection to search for User.class instances.<NEW_LINE>LoginContext loginContext = SecurityUtils.createLoginContext(AuthType.SIMPLE, mSubject, User.class.getClassLoader(), new LoginModuleConfiguration(), new AppLoginModule.AppCallbackHandler(username));<NEW_LINE>loginContext.login();<NEW_LINE>} catch (LoginException e) {<NEW_LINE>throw new UnauthenticatedException("Failed to login: " + e.getMessage(), e);<NEW_LINE>}<NEW_LINE>LOG.debug("login subject: {}", mSubject);<NEW_LINE>Set<User> userSet = mSubject.getPrincipals(User.class);<NEW_LINE>if (userSet.isEmpty()) {<NEW_LINE>throw new UnauthenticatedException("Failed to login: No Alluxio User is found.");<NEW_LINE>}<NEW_LINE>if (userSet.size() > 1) {<NEW_LINE>StringBuilder msg = new StringBuilder("Failed to login: More than one Alluxio Users are found:");<NEW_LINE>for (User user : userSet) {<NEW_LINE>msg.append(" ").append(user.toString());<NEW_LINE>}<NEW_LINE>throw new <MASK><NEW_LINE>}<NEW_LINE>return userSet.iterator().next();<NEW_LINE>} | UnauthenticatedException(msg.toString()); |
157,509 | protected Answer execute(GetHostStatsCommand cmd) {<NEW_LINE>VmwareContext context = getServiceContext();<NEW_LINE>VmwareHypervisorHost hyperHost = getHyperHost(context);<NEW_LINE>HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), 0, 0, 0, "host", <MASK><NEW_LINE>Answer answer = new GetHostStatsAnswer(cmd, hostStats);<NEW_LINE>try {<NEW_LINE>HostStatsEntry entry = getHyperHostStats(hyperHost);<NEW_LINE>if (entry != null) {<NEW_LINE>s_logger.debug(String.format("Host stats response from hypervisor is: [%s].", _gson.toJson(entry)));<NEW_LINE>entry.setHostId(cmd.getHostId());<NEW_LINE>answer = new GetHostStatsAnswer(cmd, entry);<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>s_logger.error(createLogMessageException(e, cmd), e);<NEW_LINE>}<NEW_LINE>if (s_logger.isTraceEnabled()) {<NEW_LINE>s_logger.trace("GetHostStats Answer: " + _gson.toJson(answer));<NEW_LINE>}<NEW_LINE>return answer;<NEW_LINE>} | 0, 0, 0, 0); |
983,150 | public void call(final Stream stream, final AlertCondition.CheckResult result) throws AlarmCallbackException {<NEW_LINE>final Map<String, Object> event = Maps.newHashMap();<NEW_LINE>event.put("stream", stream);<NEW_LINE>event.put("check_result", result);<NEW_LINE>final byte[] body;<NEW_LINE>try {<NEW_LINE>body = objectMapper.writeValueAsBytes(event);<NEW_LINE>} catch (JsonProcessingException e) {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>final String url = configuration.getString(CK_URL);<NEW_LINE>final HttpUrl httpUrl = HttpUrl.parse(url);<NEW_LINE>if (httpUrl == null) {<NEW_LINE>throw new AlarmCallbackException("Malformed URL: " + url);<NEW_LINE>}<NEW_LINE>if (!whitelistService.isWhitelisted(url)) {<NEW_LINE>throw new AlarmCallbackException("URL <" + url + "> is not whitelisted.");<NEW_LINE>}<NEW_LINE>final Request request = new Request.Builder().url(httpUrl).post(RequestBody.create(CONTENT_TYPE, body)).build();<NEW_LINE>try (final Response r = httpClient.newCall(request).execute()) {<NEW_LINE>if (!r.isSuccessful()) {<NEW_LINE>throw new AlarmCallbackException("Expected successful HTTP response [2xx] but got [" + r.code() + "].");<NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>throw new AlarmCallbackException(e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} | throw new AlarmCallbackException("Unable to serialize alarm", e); |
1,573,875 | private Object doSendAndReceiveAsync(Destination reqDestination, jakarta.jms.Message jmsRequest, Session session, int priority) throws JMSException {<NEW_LINE>String correlation = null;<NEW_LINE>MessageProducer messageProducer = null;<NEW_LINE>try {<NEW_LINE>messageProducer = session.createProducer(reqDestination);<NEW_LINE>correlation = this.gatewayCorrelation + "_" + this.correlationId.incrementAndGet();<NEW_LINE>if (this.correlationKey.equals("JMSCorrelationID")) {<NEW_LINE>jmsRequest.setJMSCorrelationID(correlation);<NEW_LINE>} else {<NEW_LINE>jmsRequest.setStringProperty(this.correlationKey, correlation);<NEW_LINE>jmsRequest.setJMSCorrelationID(null);<NEW_LINE>}<NEW_LINE>LinkedBlockingQueue<jakarta.jms.Message> replyQueue = null;<NEW_LINE>String correlationToLog = correlation;<NEW_LINE>logger.debug(() -> getComponentName() + " Sending message with correlationId " + correlationToLog);<NEW_LINE>SettableListenableFuture<AbstractIntegrationMessageBuilder<?>> future = null;<NEW_LINE>boolean async = isAsync();<NEW_LINE>if (!async) {<NEW_LINE>replyQueue = new LinkedBlockingQueue<>(1);<NEW_LINE>this.replies.put(correlation, replyQueue);<NEW_LINE>} else {<NEW_LINE>future = createFuture(correlation);<NEW_LINE>}<NEW_LINE>sendRequestMessage(jmsRequest, messageProducer, priority);<NEW_LINE>if (async) {<NEW_LINE>return future;<NEW_LINE>} else {<NEW_LINE>return obtainReplyFromContainer(correlation, replyQueue);<NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE>JmsUtils.closeMessageProducer(messageProducer);<NEW_LINE>if (correlation != null && !isAsync()) {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | this.replies.remove(correlation); |
495,761 | private Interface initRoutingInterface(Interface_idContext id) {<NEW_LINE>Map<String, Interface> interfaces;<NEW_LINE>InterfaceId interfaceId = new InterfaceId(id);<NEW_LINE>if (interfaceId.getNode() != null) {<NEW_LINE>String nodeDeviceName = interfaceId.getNode();<NEW_LINE>NodeDevice nodeDevice = _configuration.getNodeDevices().computeIfAbsent(nodeDeviceName, n -> new NodeDevice());<NEW_LINE>interfaces = nodeDevice.getInterfaces();<NEW_LINE>} else {<NEW_LINE>interfaces = _currentLogicalSystem.getInterfaces();<NEW_LINE>}<NEW_LINE>String name = getParentInterfaceName(id);<NEW_LINE>Interface iface = interfaces.get(name);<NEW_LINE>if (iface == null) {<NEW_LINE>// TODO: this is not ideal, interface should not be created here as we are not sure if the<NEW_LINE>// interface was defined<NEW_LINE>iface = new Interface(name);<NEW_LINE>iface.setRoutingInstance(_currentLogicalSystem.getDefaultRoutingInstance());<NEW_LINE>interfaces.put(name, iface);<NEW_LINE>}<NEW_LINE>String unit = firstNonNull(interfaceId.getUnit(), "0");<NEW_LINE><MASK><NEW_LINE>Map<String, Interface> units = iface.getUnits();<NEW_LINE>Interface unitIface = units.get(unitFullName);<NEW_LINE>if (unitIface == null) {<NEW_LINE>// TODO: this is not ideal, interface should not be created here as we are not sure if the<NEW_LINE>// interface was defined<NEW_LINE>unitIface = new Interface(unitFullName);<NEW_LINE>unitIface.setRoutingInstance(_currentLogicalSystem.getDefaultRoutingInstance());<NEW_LINE>units.put(unitFullName, unitIface);<NEW_LINE>unitIface.setParent(iface);<NEW_LINE>}<NEW_LINE>return unitIface;<NEW_LINE>} | String unitFullName = name + "." + unit; |
879,249 | public Pack read(DataInputX din) throws IOException {<NEW_LINE>this.gxid = din.readLong();<NEW_LINE>this.txid = din.readLong();<NEW_LINE>this.caller = din.readLong();<NEW_LINE>this.timestamp = din.readLong();<NEW_LINE>this.elapsed = (int) din.readDecimal();<NEW_LINE>this.spanType = din.readByte();<NEW_LINE>this.name = (int) din.readDecimal();<NEW_LINE>this.objHash = (int) din.readDecimal();<NEW_LINE>this.error = (int) din.readDecimal();<NEW_LINE>this.localEndpointServiceName = (int) din.readDecimal();<NEW_LINE>this.localEndpointIp = din.readBlob();<NEW_LINE>this.localEndpointPort = din.readShort();<NEW_LINE>this.remoteEndpointServiceName = (int) din.readDecimal();<NEW_LINE>this.remoteEndpointIp = din.readBlob();<NEW_LINE>this.remoteEndpointPort = din.readShort();<NEW_LINE>this.debug = din.readBoolean();<NEW_LINE>this.shared = din.readBoolean();<NEW_LINE>this.annotationTimestamps = <MASK><NEW_LINE>this.annotationValues = (ListValue) din.readValue();<NEW_LINE>this.tags = (MapValue) din.readValue();<NEW_LINE>return this;<NEW_LINE>} | (ListValue) din.readValue(); |
136,198 | public void layout() {<NEW_LINE>BitmapFont font = style.font;<NEW_LINE>Drawable selectedDrawable = style.selection;<NEW_LINE>itemHeight = font.getCapHeight() - font.getDescent() * 2;<NEW_LINE>itemHeight += selectedDrawable.getTopHeight() + selectedDrawable.getBottomHeight();<NEW_LINE>prefWidth = 0;<NEW_LINE>Pool<GlyphLayout> layoutPool = Pools.get(GlyphLayout.class);<NEW_LINE>GlyphLayout layout = layoutPool.obtain();<NEW_LINE>for (int i = 0; i < items.size; i++) {<NEW_LINE>layout.setText(font, toString(<MASK><NEW_LINE>prefWidth = Math.max(layout.width, prefWidth);<NEW_LINE>}<NEW_LINE>layoutPool.free(layout);<NEW_LINE>prefWidth += selectedDrawable.getLeftWidth() + selectedDrawable.getRightWidth();<NEW_LINE>prefHeight = items.size * itemHeight;<NEW_LINE>Drawable background = style.background;<NEW_LINE>if (background != null) {<NEW_LINE>prefWidth = Math.max(prefWidth + background.getLeftWidth() + background.getRightWidth(), background.getMinWidth());<NEW_LINE>prefHeight = Math.max(prefHeight + background.getTopHeight() + background.getBottomHeight(), background.getMinHeight());<NEW_LINE>}<NEW_LINE>} | items.get(i))); |
246,613 | int insertVertex_(int path, int before, Point point) {<NEW_LINE>int prev = before != -1 ? getPrevVertex(before) : getLastVertex(path);<NEW_LINE>int next = prev != -1 ? getNextVertex(prev) : -1;<NEW_LINE>int vertex = newVertex_(point == null ? m_point_count : -1);<NEW_LINE>int vindex = getVertexIndex(vertex);<NEW_LINE>if (point != null)<NEW_LINE><MASK><NEW_LINE>setPathToVertex_(vertex, path);<NEW_LINE>setNextVertex_(vertex, next);<NEW_LINE>setPrevVertex_(vertex, prev);<NEW_LINE>if (next != -1)<NEW_LINE>setPrevVertex_(next, vertex);<NEW_LINE>if (prev != -1)<NEW_LINE>setNextVertex_(prev, vertex);<NEW_LINE>boolean b_closed = isClosedPath(path);<NEW_LINE>int first = getFirstVertex(path);<NEW_LINE>if (before == -1)<NEW_LINE>setLastVertex_(path, vertex);<NEW_LINE>if (before == first)<NEW_LINE>setFirstVertex_(path, vertex);<NEW_LINE>if (b_closed && next == -1) {<NEW_LINE>setNextVertex_(vertex, vertex);<NEW_LINE>setPrevVertex_(vertex, vertex);<NEW_LINE>}<NEW_LINE>setPathSize_(path, getPathSize(path) + 1);<NEW_LINE>int geometry = getGeometryFromPath(path);<NEW_LINE>setGeometryVertexCount_(geometry, getPointCount(geometry) + 1);<NEW_LINE>return vertex;<NEW_LINE>} | m_vertices.setPointByVal(vindex, point); |
467,170 | private List<AllocCandidate> extractAllocCandidates(@NonNull final I_M_HU hu, @NonNull final IAllocationRequest request) {<NEW_LINE>final IHUStorageFactory huStorageFactory = request.getHUContext().getHUStorageFactory();<NEW_LINE>final ArrayList<AllocCandidate> candidates = new ArrayList<>();<NEW_LINE>final List<I_M_HU_Item> huItems = services.retrieveItems(hu);<NEW_LINE>for (final I_M_HU_Item item : huItems) {<NEW_LINE>final HUItemType itemType = services.getItemType(item);<NEW_LINE>if (HUItemType.Material.equals(itemType) && services.isVirtual(item)) {<NEW_LINE>final IHUItemStorage huItemStorage = huStorageFactory.getStorage(item);<NEW_LINE>final Quantity currentQty = huItemStorage.getQuantity(request.getProductId(), request.getC_UOM());<NEW_LINE>candidates.add(AllocCandidate.builder().type(AllocCandidateType.MATERIAL).huItem(item).includedHU(null).currentQty<MASK><NEW_LINE>}<NEW_LINE>if (HUItemType.Material.equals(itemType) || HUItemType.HandlingUnit.equals(itemType) || HUItemType.HUAggregate.equals(itemType)) {<NEW_LINE>final List<I_M_HU> includedHUs = services.retrieveIncludedHUs(item);<NEW_LINE>for (final I_M_HU includedHU : includedHUs) {<NEW_LINE>final IHUStorage huStorage = huStorageFactory.getStorage(includedHU);<NEW_LINE>final Quantity currentQty = huStorage.getQuantity(request.getProductId(), request.getC_UOM());<NEW_LINE>candidates.add(AllocCandidate.builder().type(AllocCandidateType.INCLUDED_HU).huItem(item).includedHU(includedHU).currentQty(currentQty).build());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return candidates;<NEW_LINE>} | (currentQty).build()); |
581,940 | private void loadInstanceIdByZK() {<NEW_LINE>int execCount = 1;<NEW_LINE>while (true) {<NEW_LINE>if (execCount > this.retryCount) {<NEW_LINE>throw new RuntimeException("instanceId allocate error when using zk, reason: no available instanceId found");<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>List<String> nodeList = client.getChildren().forPath(INSTANCE_PATH);<NEW_LINE>String slavePath = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(INSTANCE_PATH.concat("/node"), "ready".getBytes());<NEW_LINE>String tempInstanceId = slavePath.substring(slavePath.length() - 10);<NEW_LINE>this.instanceId = Long.parseLong(tempInstanceId) & ((1 << instanceIdBits) - 1);<NEW_LINE>// check if id collides<NEW_LINE>if (checkInstanceIdCollision(nodeList)) {<NEW_LINE>execCount++;<NEW_LINE>} else {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new RuntimeException(<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | "instanceId allocate error when using zk, reason:" + e.getMessage()); |
1,648,304 | private JPanel makeButtonPanel() {<NEW_LINE>JPanel buttonPanel = new JPanel();<NEW_LINE>buttonPanel.setLayout(new GridLayout(2, 2));<NEW_LINE>// $NON-NLS-1$<NEW_LINE>addParameterButton = new JButton(JMeterUtils.getResString("add_parameter"));<NEW_LINE>// $NON-NLS-1$<NEW_LINE>addUserButton = new JButton(JMeterUtils.getResString("add_user"));<NEW_LINE>// $NON-NLS-1$<NEW_LINE>deleteRowButton = new JButton(JMeterUtils.getResString("delete_parameter"));<NEW_LINE>// $NON-NLS-1$<NEW_LINE>deleteColumnButton = new JButton<MASK><NEW_LINE>// $NON-NLS-1$<NEW_LINE>moveRowUpButton = new JButton(JMeterUtils.getResString("up"));<NEW_LINE>// $NON-NLS-1$<NEW_LINE>moveRowDownButton = new JButton(JMeterUtils.getResString("down"));<NEW_LINE>buttonPanel.add(addParameterButton);<NEW_LINE>buttonPanel.add(deleteRowButton);<NEW_LINE>buttonPanel.add(moveRowUpButton);<NEW_LINE>buttonPanel.add(addUserButton);<NEW_LINE>buttonPanel.add(deleteColumnButton);<NEW_LINE>buttonPanel.add(moveRowDownButton);<NEW_LINE>addParameterButton.addActionListener(new AddParamAction());<NEW_LINE>addUserButton.addActionListener(new AddUserAction());<NEW_LINE>deleteRowButton.addActionListener(new DeleteRowAction());<NEW_LINE>deleteColumnButton.addActionListener(new DeleteColumnAction());<NEW_LINE>moveRowUpButton.addActionListener(new MoveRowUpAction());<NEW_LINE>moveRowDownButton.addActionListener(new MoveRowDownAction());<NEW_LINE>return buttonPanel;<NEW_LINE>} | (JMeterUtils.getResString("delete_user")); |
585,091 | public NType resolve(Scope outer) throws Exception {<NEW_LINE>resolveList(defaults, outer);<NEW_LINE>resolveList(decoratorList, outer);<NEW_LINE>Scope funcTable = getTable();<NEW_LINE>NBinding selfBinding = funcTable.lookup("__self__");<NEW_LINE>if (selfBinding != null && !selfBinding.getType().isClassType()) {<NEW_LINE>selfBinding = null;<NEW_LINE>}<NEW_LINE>if (selfBinding != null) {<NEW_LINE>if (args.size() < 1) {<NEW_LINE>addWarning(name, "method should have at least one argument (self)");<NEW_LINE>} else if (!(args.get(0) instanceof NName)) {<NEW_LINE>addError(name, "self parameter must be an identifier");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>NTupleType fromType = new NTupleType();<NEW_LINE>bindParamsToDefaults(selfBinding, fromType);<NEW_LINE>if (varargs != null) {<NEW_LINE>NBinding b = funcTable.lookupLocal(varargs.id);<NEW_LINE>if (b != null) {<NEW_LINE>fromType.add(b.getType());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (kwargs != null) {<NEW_LINE>NBinding b = funcTable.lookupLocal(kwargs.id);<NEW_LINE>if (b != null) {<NEW_LINE>fromType.add(b.getType());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>NType <MASK><NEW_LINE>getType().asFuncType().setReturnType(toType);<NEW_LINE>return getType();<NEW_LINE>} | toType = resolveExpr(body, funcTable); |
125,375 | private void updateViews(@NonNull PullRequest pullRequest) {<NEW_LINE>setTitle(String.format("#%s"<MASK><NEW_LINE>if (getSupportActionBar() != null) {<NEW_LINE>getSupportActionBar().setSubtitle(pullRequest.getRepoId());<NEW_LINE>}<NEW_LINE>date.setText(SpannableBuilder.builder().append(getPresenter().getMergeBy(pullRequest, getApplicationContext())));<NEW_LINE>size.setVisibility(View.GONE);<NEW_LINE>User userModel = pullRequest.getUser();<NEW_LINE>if (userModel != null) {<NEW_LINE>title.setText(SpannableBuilder.builder().append(userModel.getLogin()).append("/").append(pullRequest.getTitle()));<NEW_LINE>avatarLayout.setUrl(userModel.getAvatarUrl(), userModel.getLogin(), false, LinkParserHelper.isEnterprise(pullRequest.getUrl()));<NEW_LINE>} else {<NEW_LINE>title.setText(SpannableBuilder.builder().append(pullRequest.getTitle()));<NEW_LINE>}<NEW_LINE>detailsIcon.setVisibility(View.VISIBLE);<NEW_LINE>} | , pullRequest.getNumber())); |
1,759,887 | public void partitionBackupGc(List<Integer> readyPartitionBackupIds) throws IOException {<NEW_LINE>if (readyPartitionBackupIds.isEmpty()) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>int[] partitionBackupIds;<NEW_LINE>try (JnaResponse jnaResponse = GraphLibrary.INSTANCE.getBackupList(this.bePointer)) {<NEW_LINE>if (!jnaResponse.success()) {<NEW_LINE><MASK><NEW_LINE>throw new IOException(errMsg);<NEW_LINE>}<NEW_LINE>byte[] data = jnaResponse.getData();<NEW_LINE>if (data == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>IntBuffer intBuf = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder()).asIntBuffer();<NEW_LINE>partitionBackupIds = new int[intBuf.remaining()];<NEW_LINE>intBuf.get(partitionBackupIds);<NEW_LINE>}<NEW_LINE>for (int bId : partitionBackupIds) {<NEW_LINE>if (!readyPartitionBackupIds.contains(bId)) {<NEW_LINE>try (JnaResponse jnaResponse = GraphLibrary.INSTANCE.deleteBackup(this.bePointer, bId)) {<NEW_LINE>if (!jnaResponse.success()) {<NEW_LINE>logger.error("fail to delete backup [" + bId + "] from partition [" + this.partitionId + "], ignore");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | String errMsg = jnaResponse.getErrMsg(); |
273,278 | Converter<JWT, Mono<JWTClaimsSet>> processor() {<NEW_LINE>JWKSecurityContextJWKSet jwkSource = new JWKSecurityContextJWKSet();<NEW_LINE>JWSKeySelector<JWKSecurityContext> jwsKeySelector = new JWSVerificationKeySelector<>(this.jwsAlgorithm, jwkSource);<NEW_LINE>DefaultJWTProcessor<JWKSecurityContext> jwtProcessor = new DefaultJWTProcessor<>();<NEW_LINE>jwtProcessor.setJWSKeySelector(jwsKeySelector);<NEW_LINE>jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {<NEW_LINE>});<NEW_LINE><MASK><NEW_LINE>return (jwt) -> {<NEW_LINE>if (jwt instanceof SignedJWT) {<NEW_LINE>return this.jwkSource.apply((SignedJWT) jwt).onErrorMap((e) -> new IllegalStateException("Could not obtain the keys", e)).collectList().map((jwks) -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwks)));<NEW_LINE>}<NEW_LINE>throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());<NEW_LINE>};<NEW_LINE>} | this.jwtProcessorCustomizer.accept(jwtProcessor); |
1,076,830 | static Stream<Map.Entry<ConfigKeyImpl, ConfigNode>> flattenNodes(ConfigKeyImpl key, ConfigNode node) {<NEW_LINE>switch(node.nodeType()) {<NEW_LINE>case OBJECT:<NEW_LINE>return ((ConfigNode.ObjectNode) node).entrySet().stream().map(e -> flattenNodes(key.child(e.getKey()), e.getValue())).reduce(Stream.of(new AbstractMap.SimpleEntry<>(key, <MASK><NEW_LINE>case LIST:<NEW_LINE>return IntStream.range(0, ((ConfigNode.ListNode) node).size()).boxed().map(i -> flattenNodes(key.child(Integer.toString(i)), ((ConfigNode.ListNode) node).get(i))).reduce(Stream.of(new AbstractMap.SimpleEntry<>(key, node)), Stream::concat);<NEW_LINE>case VALUE:<NEW_LINE>return Stream.of(new AbstractMap.SimpleEntry<>(key, node));<NEW_LINE>default:<NEW_LINE>throw new IllegalArgumentException("Invalid node type.");<NEW_LINE>}<NEW_LINE>} | node)), Stream::concat); |
1,691,220 | public void deleteByIdWithResponse(String id, Context context) {<NEW_LINE>String resourceGroupName = <MASK><NEW_LINE>if (resourceGroupName == null) {<NEW_LINE>throw logger.logExceptionAsError(new IllegalArgumentException(String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));<NEW_LINE>}<NEW_LINE>String clusterName = Utils.getValueFromIdByName(id, "clusters");<NEW_LINE>if (clusterName == null) {<NEW_LINE>throw logger.logExceptionAsError(new IllegalArgumentException(String.format("The resource ID '%s' is not valid. Missing path segment 'clusters'.", id)));<NEW_LINE>}<NEW_LINE>String applicationTypeName = Utils.getValueFromIdByName(id, "applicationTypes");<NEW_LINE>if (applicationTypeName == null) {<NEW_LINE>throw logger.logExceptionAsError(new IllegalArgumentException(String.format("The resource ID '%s' is not valid. Missing path segment 'applicationTypes'.", id)));<NEW_LINE>}<NEW_LINE>this.delete(resourceGroupName, clusterName, applicationTypeName, context);<NEW_LINE>} | Utils.getValueFromIdByName(id, "resourceGroups"); |
568,866 | public static void execute(ManagerService service) {<NEW_LINE><MASK><NEW_LINE>// write header<NEW_LINE>buffer = HEADER.write(buffer, service, true);<NEW_LINE>// write fields<NEW_LINE>for (FieldPacket field : FIELDS) {<NEW_LINE>buffer = field.write(buffer, service, true);<NEW_LINE>}<NEW_LINE>// write eof<NEW_LINE>buffer = EOF.write(buffer, service, true);<NEW_LINE>// write rows<NEW_LINE>byte packetId = EOF.getPacketId();<NEW_LINE>if (FlowController.isEnableFlowControl()) {<NEW_LINE>for (RowDataPacket row : getServerConnections(service)) {<NEW_LINE>row.setPacketId(++packetId);<NEW_LINE>buffer = row.write(buffer, service, true);<NEW_LINE>}<NEW_LINE>for (RowDataPacket row : getBackendConnections(service)) {<NEW_LINE>row.setPacketId(++packetId);<NEW_LINE>buffer = row.write(buffer, service, true);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// write last eof<NEW_LINE>EOFRowPacket lastEof = new EOFRowPacket();<NEW_LINE>lastEof.setPacketId(++packetId);<NEW_LINE>lastEof.write(buffer, service);<NEW_LINE>} | ByteBuffer buffer = service.allocate(); |
840,836 | public void testSearchBase() throws Exception {<NEW_LINE>// check for valid user and group<NEW_LINE>String returnUser = servlet.checkPassword(USER_DN, "password");<NEW_LINE><MASK><NEW_LINE>assertTrue("Expected '" + USER_DN + "' to be valid user.", servlet.isValidUser(USER_DN));<NEW_LINE>List<String> groups = servlet.getGroupsForUser(USER_DN);<NEW_LINE>assertFalse("Should have found groups", groups.isEmpty());<NEW_LINE>assertTrue("Group should include " + GROUP + " returned " + groups, groups.contains(GROUP_DN));<NEW_LINE>returnUser = servlet.getUniqueUserId(USER);<NEW_LINE>assertNotNull("Should find user " + USER, returnUser);<NEW_LINE>assertEquals("Wrong unique ID returned for " + USER, USER_DN, returnUser);<NEW_LINE>// check that the bad user is excluded<NEW_LINE>returnUser = servlet.checkPassword(BAD_USER_DN, "password");<NEW_LINE>assertNull(BAD_USER + " should not be able to login", returnUser);<NEW_LINE>assertFalse(BAD_USER + " should not be a valid user", servlet.isValidUser(BAD_USER_DN));<NEW_LINE>try {<NEW_LINE>returnUser = servlet.getUniqueUserId(BAD_USER);<NEW_LINE>fail("Should not find user " + BAD_USER);<NEW_LINE>} catch (Exception e) {<NEW_LINE>// expected<NEW_LINE>}<NEW_LINE>} | assertNotNull("Should find user on checkPassword using " + USER_DN, returnUser); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.