auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Mono<Response<RecognizePiiEntitiesResultCollection>> getRecognizePiiEntitiesResponse( Iterable<TextDocumentInput> documents, RecognizePiiEntityOptions options, Context context) { return service.entitiesRecognitionPiiWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), <START> options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics(), options == null ? null : options.getDomainFilter() == null ? null : options.getDomainFilter().toString(), <END> null, context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .doOnSubscribe(ignoredValue -> logger.info( "Start recognizing Personally Identifiable Information entities for a batch of documents.")) .doOnSuccess(response -> logger.info( "Successfully recognized Personally Identifiable Information entities for a batch of documents.")) .doOnError(error -> logger.warning("Failed to recognize Personally Identifiable Information entities - {}", error)) .map(this::toRecognizePiiEntitiesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); }</code><technical_language>club check for options in a single call above</technical_language>

Target:
private Mono<Response<RecognizePiiEntitiesResultCollection>> getRecognizePiiEntitiesResponse( Iterable<TextDocumentInput> documents, RecognizePiiEntityOptions options, Context context) { String modelVersion = null; Boolean includeStatistics = null; String domainFilter = null; if (options != null) { modelVersion = options.getModelVersion(); includeStatistics = options.isIncludeStatistics(); final PiiEntityDomainType domainType = options.getDomainFilter(); if (domainType != null) { domainFilter = domainType.toString(); } } return service.entitiesRecognitionPiiWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), modelVersion, includeStatistics, domainFilter, StringIndexType.UTF16CODE_UNIT, context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .doOnSubscribe(ignoredValue -> logger.info( "Start recognizing Personally Identifiable Information entities for a batch of documents.")) .doOnSuccess(response -> logger.info( "Successfully recognized Personally Identifiable Information entities for a batch of documents.")) .doOnError(error -> logger.warning("Failed to recognize Personally Identifiable Information entities - {}", error)) .map(this::toRecognizePiiEntitiesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); }
Source:
<code>public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator) { if (!SystemSessionProperties.isNewOptimizerEnabled(session) && !legacyRules.isEmpty()) { for (PlanOptimizer optimizer : legacyRules) { plan = optimizer.optimize(plan, session, symbolAllocator.getTypes(), symbolAllocator, idAllocator); } return plan; } Memo memo = new Memo(idAllocator, plan); Lookup lookup = Lookup.from(planNode -> Stream.of(memo.resolve(planNode))); <START> Matcher matcher = new DefaultMatcher(); <END> Duration timeout = SystemSessionProperties.getOptimizerTimeout(session); Context context = new Context(memo, lookup, idAllocator, symbolAllocator, System.nanoTime(), timeout.toMillis(), session); exploreGroup(memo.getRootGroup(), context, matcher); return memo.extract(); }</code><technical_language>explain this works put in commit message</technical_language>

Target:
public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator) { if (!SystemSessionProperties.isNewOptimizerEnabled(session) && !legacyRules.isEmpty()) { for (PlanOptimizer optimizer : legacyRules) { plan = optimizer.optimize(plan, session, symbolAllocator.getTypes(), symbolAllocator, idAllocator); } return plan; } Memo memo = new Memo(idAllocator, plan); Lookup lookup = Lookup.from(planNode -> Stream.of(memo.resolve(planNode))); Duration timeout = SystemSessionProperties.getOptimizerTimeout(session); Context context = new Context(memo, lookup, idAllocator, symbolAllocator, System.nanoTime(), timeout.toMillis(), session); exploreGroup(memo.getRootGroup(), context); return memo.extract(); }
Source:
<code>protected List<FactMappingValidationError> validateDMN(Simulation simulation, KieContainer kieContainer) { List<FactMappingValidationError> errors = new ArrayList<>(); String dmnFilePath = simulation.getSimulationDescriptor().getDmnFilePath(); DMNModel dmnModel = getDMNModel(kieContainer, dmnFilePath); for (FactMapping factMapping : simulation.getSimulationDescriptor().getFactMappings()) { if (isToSkip(factMapping)) { continue; } String nodeName = factMapping.getFactIdentifier().getName(); DMNType rootDMNType; try { <START> rootDMNType = dmnModel.getDecisionByName(nodeName) != null ? <END> dmnModel.getDecisionByName(nodeName).getResultType() : dmnModel.getInputByName(nodeName).getType(); } catch (NullPointerException e) { errors.add(createNodeChangedError(factMapping, "node not found")); continue; } List<String> steps = expressionElementToString(factMapping); Type rootType = getRootType((BaseDMNTypeImpl) rootDMNType); if (!CONTEXT.equals(rootType) && steps.size() == 0 && rootDMNType.isComposite()) { errors.add(createNodeChangedError(factMapping, rootDMNType.getName())); continue; } try { DMNType fieldType = navigateDMNType(rootDMNType, steps); if (!isDMNFactMappingValid(factMapping.getClassName(), factMapping, fieldType)) { errors.add(createFieldChangedError(factMapping, fieldType.getName())); } } catch (IllegalStateException e) { errors.add(createGenericError(factMapping, e.getMessage())); } } return errors; }</code><technical_language>@danielezonca If I correctly understand, code is iterating factmappings (regardless of "GIVEN/EXPECTED" type) -then search a match dmnmodel, of "DECISION/INPUT" type. validate if factmapping is a "GIVEN" in dmnmodel is a "DECISION", other around: I wrong? If is so, fixed</technical_language>

Target:
protected List<FactMappingValidationError> validateDMN(Simulation simulation, KieContainer kieContainer) { return DMNScenarioValidation.INSTANCE.validate(simulation, kieContainer); }
Source:
<code>private void put(byte[] cf, int cfLength, byte[] cq, int cqLength, byte[] cv, boolean hasts, long ts, boolean deleted, byte[] val, int valLength) { if (buffer == null) { throw new IllegalStateException("Can not add to mutation after serializing it"); } <START> long length = cfLength + cqLength + valLength; <END> long newSize = size.sizeInBytes + length; Preconditions.checkArgument(newSize < MAX_MUTATION_SIZE && newSize >= 0, "Maximum mutation size must be less than 2GB "); put(cf, cfLength); put(cq, cqLength); put(cv); put(hasts); if (hasts) { put(ts); } put(deleted); if (valLength < VALUE_SIZE_COPY_CUTOFF) { put(val, valLength); } else { if (values == null) { values = new ArrayList<>(); } byte copy[] = new byte[valLength]; System.arraycopy(val, 0, copy, 0, valLength); values.add(copy); put(-1 * values.size()); } size.addEntryWithSize(length); }</code><technical_language>This capture complete picture. data is serialized, length is written in addition data. For example if a 20 byte family is written write 21 bytes including length. length is written a variable length long, hard bytes beforehand. this hard beforehand, I suggest worst case assuming 5 bytes. strategy of tracking length of long values asking buffer for size of else. This accurate size for is serialized is obtained need estimated is serialized. java long estimatedNewSize = (cfLength + cqLength + valLength + cv.lenght() + 4* 5 + 1 + (hasTs ? 8 : 0)) + buffer.currentSize() + valueLenghts; //sanity check estimated new size // if large value, increment valueLenghts</technical_language>

Target:
private void put(byte[] cf, int cfLength, byte[] cq, int cqLength, byte[] cv, boolean hasts, long ts, boolean deleted, byte[] val, int valLength) { if (buffer == null) { throw new IllegalStateException("Can not add to mutation after serializing it"); } long estimatedSizeAfterPut = estRowAndLargeValSize + buffer.size() + cfLength + cqLength + cv.length + (hasts ? 8 : 0) + valLength + 2 + 4 * SERIALIZATION_OVERHEAD; Preconditions.checkArgument(estimatedSizeAfterPut < MAX_MUTATION_SIZE && estimatedSizeAfterPut >= 0, "Maximum mutation size must be less than 2GB "); put(cf, cfLength); put(cq, cqLength); put(cv); put(hasts); if (hasts) { put(ts); } put(deleted); if (valLength < VALUE_SIZE_COPY_CUTOFF) { put(val, valLength); } else { if (values == null) { values = new ArrayList<>(); } byte copy[] = new byte[valLength]; System.arraycopy(val, 0, copy, 0, valLength); values.add(copy); put(-1 * values.size()); estRowAndLargeValSize += valLength + SERIALIZATION_OVERHEAD; } entries++; }
Source:
<code>public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException { FilePath expected = preferredLocation(tool, node); Installable inst = getInstallable(); if(inst==null) { log.getLogger().println("Invalid tool ID "+id); return expected; } if (inst instanceof NodeSpecific) <START> inst = (Installable) ((NodeSpecific) inst).forNode(node, log); <END> if(isUpToDate(expected,inst)) return expected; if(expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { expected.child(".timestamp").delete(); FilePath base = findPullUpDirectory(expected); if(base!=null && base!=expected) base.moveAllChildrenTo(expected); expected.child(".installedFrom").write(inst.url,"UTF-8"); expected.act(new ZipExtractionInstaller.ChmodRecAPlusX()); } return expected; }</code><technical_language>Please brackets tabs least. code is confusing</technical_language>

Target:
public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException { FilePath expected = preferredLocation(tool, node); Installable inst = getInstallable(); if(inst==null) { log.getLogger().println("Invalid tool ID "+id); return expected; } if (inst instanceof NodeSpecific) { inst = (Installable) ((NodeSpecific) inst).forNode(node, log); } if(isUpToDate(expected,inst)) return expected; if(expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { expected.child(".timestamp").delete(); FilePath base = findPullUpDirectory(expected); if(base!=null && base!=expected) base.moveAllChildrenTo(expected); expected.child(".installedFrom").write(inst.url,"UTF-8"); expected.act(new ZipExtractionInstaller.ChmodRecAPlusX()); } return expected; }
Source:
<code>public void initReader() throws Exception { if (sourceReader != null) { return; } final MetricGroup metricGroup = getMetricGroup(); assert metricGroup != null; final int subtaskIndex = getRuntimeContext().getIndexOfThisSubtask(); final SourceReaderContext context = new SourceReaderContext() { @Override public MetricGroup metricGroup() { return metricGroup; } @Override public Configuration getConfiguration() { return configuration; } @Override public String getLocalHostName() { return localHostname; } @Override public int getIndexOfSubtask() { return subtaskIndex; } @Override public void sendSplitRequest() { operatorEventGateway.sendEventToCoordinator(new RequestSplitEvent(getLocalHostName())); } @Override public void sendSourceEventToCoordinator(SourceEvent event) { operatorEventGateway.sendEventToCoordinator(new SourceEventWrapper(event)); } @Override public UserCodeClassLoader getUserCodeClassLoader() { <START> return (UserCodeClassLoader) getRuntimeContext().getUserCodeClassLoader(); <END> } }; sourceReader = readerFactory.apply(context); }</code><technical_language>This a cast incompatible types</technical_language>

Target:
public void initReader() throws Exception { if (sourceReader != null) { return; } final MetricGroup metricGroup = getMetricGroup(); assert metricGroup != null; final int subtaskIndex = getRuntimeContext().getIndexOfThisSubtask(); final SourceReaderContext context = new SourceReaderContext() { @Override public MetricGroup metricGroup() { return metricGroup; } @Override public Configuration getConfiguration() { return configuration; } @Override public String getLocalHostName() { return localHostname; } @Override public int getIndexOfSubtask() { return subtaskIndex; } @Override public void sendSplitRequest() { operatorEventGateway.sendEventToCoordinator(new RequestSplitEvent(getLocalHostName())); } @Override public void sendSourceEventToCoordinator(SourceEvent event) { operatorEventGateway.sendEventToCoordinator(new SourceEventWrapper(event)); } @Override public UserCodeClassLoader getUserCodeClassLoader() { return new UserCodeClassLoader() { @Override public ClassLoader asClassLoader() { return getRuntimeContext().getUserCodeClassLoader(); } @Override public void registerReleaseHookIfAbsent( String releaseHookName, Runnable releaseHook) { getRuntimeContext().registerUserCodeClassLoaderReleaseHookIfAbsent( releaseHookName, releaseHook); } }; } }; sourceReader = readerFactory.apply(context); }
Source:
<code>private InlineParser getInlineParser() { if (this.inlineParserFactory == null) { return new InlineParserImpl(specialCharacters, delimiterCharacters, delimiterProcessors); } else { <START> return this.inlineParserFactory.create(); <END> } }</code><technical_language>custom inline parser need delimiterProcessors etc? I create method get a InlineParserContext (similar HtmlNodeRendererContext), this: java interface InlineParserContext { Map<Character, DelimiterProcessor> getDelimiterProcessors(); } (The other two, specialCharacters delimiterCharacters derived delimiter processors optimization, need interface.)</technical_language>

Target:
private InlineParser getInlineParser() { if (this.inlineParserFactory == null) { return new InlineParserImpl(delimiterProcessors); } else { CustomInlineParserContext inlineParserContext = new CustomInlineParserContext(delimiterProcessors); return this.inlineParserFactory.create(inlineParserContext); } }
Source:
<code>public int start(int startingPosition, int probePosition, Page allProbeChannelsPage) { for (JoinFilterFunction searchFunction : searchFunctions) { startingPosition = findStartPositionForFunction(searchFunction, startingPosition, probePosition, allProbeChannelsPage); if (startingPosition == -1) { return -1; } } <START> return startingPosition; <END> }</code><technical_language>I this is a (correctness) regression. * need operate single sortedPositionLinks[startingPosition] call findStartPositionForFunction else original startingPosition * need position _maximal_ offset, next return end of range range started</technical_language>

Target:
public int start(int startingPosition, int probePosition, Page allProbeChannelsPage) { if (applyAllSearchFunctions(startingPosition, probePosition, allProbeChannelsPage)) { return startingPosition; } int[] links = sortedPositionLinks[startingPosition]; if (links == null) { return -1; } int currentStartOffset = 0; for (JoinFilterFunction searchFunction : searchFunctions) { currentStartOffset = findStartPositionForFunction(searchFunction, links, currentStartOffset, probePosition, allProbeChannelsPage); if (currentStartOffset == -1) { return -1; } } return links[currentStartOffset]; }
Source:
<code><START> protected Object execute(final RebaseOperation rebase) <END> throws ExecutionException { final Repository repository = rebase.getRepository(); final RebaseCommand.Operation operation = rebase.getOperation(); JobUtil.scheduleUserJob(rebase, jobname, JobFamilies.REBASE, new JobChangeAdapter() { @Override public void aboutToRun(IJobChangeEvent event) { if (operation == Operation.BEGIN && !repository.getRepositoryState().equals( RepositoryState.SAFE)) { throw new IllegalStateException( "Can't start rebase if repository state isn't SAFE"); } super.aboutToRun(event); } @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (operation == Operation.BEGIN && result.getSeverity() == IStatus.ERROR) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) { Throwable t = result.getException(); try { new RebaseOperation(repository, Operation.ABORT).execute(null); Activator.showError(t.getMessage(), t); } catch (CoreException e1) { IStatus mStatus = createMultiStatus(t, e1); CoreException mStatusException = new CoreException( mStatus); Activator.showError( mStatusException.getMessage(), mStatusException); } } } if (result.getSeverity() == IStatus.CANCEL) Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(); MessageDialog .openInformation( shell, UIText.AbstractRebaseCommand_DialogTitle, dialogMessage); } }); else if (result.isOK()) RebaseResultDialog.show(rebase.getResult(), repository); } }); return null; }</code><technical_language>this is method returning null is need return this method I return type void</technical_language>

Target:
protected void execute(final RebaseOperation rebase) throws ExecutionException { final Repository repository = rebase.getRepository(); if (repository == null) return; final RebaseCommand.Operation operation = rebase.getOperation(); JobUtil.scheduleUserJob(rebase, jobname, JobFamilies.REBASE, new JobChangeAdapter() { @Override public void aboutToRun(IJobChangeEvent event) { if (operation == Operation.BEGIN && !repository.getRepositoryState().equals( RepositoryState.SAFE)) { throw new IllegalStateException( "Can't start rebase if repository state isn't SAFE"); } super.aboutToRun(event); } @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (operation == Operation.BEGIN && result.getSeverity() == IStatus.ERROR) { handleBeginError(repository, result); } else if (result.getSeverity() == IStatus.CANCEL) Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(); MessageDialog .openInformation( shell, UIText.AbstractRebaseCommand_DialogTitle, dialogMessage); } }); else if (result.isOK()) RebaseResultDialog.show(rebase.getResult(), repository); } }); return; }
Source:
<code>public void testFiresListener() { Store store = mock(Store.class); <START> Ehcache ehcache = new Ehcache(CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Object.class, Object.class), store); <END> final StateChangeListener listener = mock(StateChangeListener.class); ehcache.registerListener(listener); ehcache.init(); verify(listener).stateTransition(Status.UNINITIALIZED, Status.AVAILABLE); reset(listener); ehcache.deregisterListener(listener); ehcache.close(); verify(listener, never()).stateTransition(Status.AVAILABLE, Status.UNINITIALIZED); }</code><technical_language>Picky this is a good candidate for static import</technical_language>

Target:
public void testFiresListener() { Store store = mock(Store.class); Ehcache ehcache = new Ehcache(newCacheConfigurationBuilder().buildConfig(Object.class, Object.class), store); final StateChangeListener listener = mock(StateChangeListener.class); ehcache.registerListener(listener); ehcache.init(); verify(listener).stateTransition(Status.UNINITIALIZED, Status.AVAILABLE); reset(listener); ehcache.deregisterListener(listener); ehcache.close(); verify(listener, never()).stateTransition(Status.AVAILABLE, Status.UNINITIALIZED); }
Source:
<code>public void actionPerformed(ActionEvent e) { final StatusNotification notification = new StatusNotification("Running Tests...", PROGRESS, FLOAT_MODE); notificationManager.notify(notification); final Project project = appContext.getRootProject(); Map<String, String> parameters = new HashMap<>(); parameters.put("updateClasspath", "true"); <START> parameters.put("testngXML", project.getPath() + "/src/test/resources/testng.xml"); <END> Promise<TestResult> testResultPromise = service.getTestResult(project.getPath(), "testng", parameters); testResultPromise.then(new Operation<TestResult>() { @Override public void apply(TestResult result) throws OperationException { notification.setStatus(SUCCESS); if (result.isSuccess()) { notification.setTitle("Test runner executed successfully"); notification.setContent("All tests are passed"); } else { notification.setTitle("Test runner executed successfully with test failures."); notification.setContent(result.getFailureCount() + " test(s) failed.\n"); } presenter.handleResponse(result); } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError exception) throws OperationException { final String errorMessage = (exception.getMessage() != null) ? exception.getMessage() : "Failed to run test cases"; notification.setContent(errorMessage); notification.setStatus(FAIL); } }); }</code><technical_language>work testng.xml in project sources</technical_language>

Target:
public void actionPerformed(ActionEvent e) { final StatusNotification notification = new StatusNotification("Running Tests...", PROGRESS, FLOAT_MODE); notificationManager.notify(notification); final Project project = appContext.getRootProject(); Map<String, String> parameters = new HashMap<>(); parameters.put("updateClasspath", "true"); parameters.put("testngXML", project.getPath() + "/" + MavenAttributes.DEFAULT_TEST_RESOURCES_FOLDER + "/testng.xml"); Promise<TestResult> testResultPromise = service.getTestResult(project.getPath(), "testng", parameters); testResultPromise.then(new Operation<TestResult>() { @Override public void apply(TestResult result) throws OperationException { notification.setStatus(SUCCESS); if (result.isSuccess()) { notification.setTitle("Test runner executed successfully"); notification.setContent("All tests are passed"); } else { notification.setTitle("Test runner executed successfully with test failures."); notification.setContent(result.getFailureCount() + " test(s) failed.\n"); } presenter.handleResponse(result); } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError exception) throws OperationException { final String errorMessage = (exception.getMessage() != null) ? exception.getMessage() : "Failed to run test cases"; notification.setContent(errorMessage); notification.setStatus(FAIL); } }); }
Source:
<code>private ChangeInfo getChange(PushOneCommit.Result pr) throws IOException { return getChange(pr.getChangeId(), <START> ListChangesOption.DETAILED_LABELS); <END> }</code><technical_language>Nit: in another file imported ListChangesOption statically (for MESSAGES). Umport statically too</technical_language>

Target:
private ChangeInfo getChange(PushOneCommit.Result pr) throws IOException { return getChange(pr.getChangeId(), DETAILED_LABELS); }
Source:
<code>public void update(Container entity) { CuratorFramework client = zkConnection.getClient(); String path = Paths.build(Paths.CONTAINERS, entity.getName()); try { <START> client.checkExists().forPath(path); <END> client.setData().forPath(path, ZooKeeperUtils.mapToBytes(entity.getAttributes())); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } }</code><technical_language>checkExists method returns a Stat object if path exists, null otherwise. return is evaluated. If path exist, do want throw NoNodeException , is a exception throw? NoSuchContainerException some other generic Spring Data exception absence of entity in a repository</technical_language>

Target:
public void update(Container entity) { CuratorFramework client = zkConnection.getClient(); String path = Paths.build(Paths.CONTAINERS, entity.getName()); try { Stat stat = client.checkExists().forPath(path); if (stat == null) { throw new NoSuchContainerException("Could not find container with id " + entity.getName()); } client.setData().forPath(path, ZooKeeperUtils.mapToBytes(entity.getAttributes())); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e, e.getMessage()); } }
Source:
<code>@Test public void testFilterClausesFactoredForPruning1() { String sql = "select " + "sum(\"store_sales\") filter (where \"store_state\" = 'CA'), " + "sum(\"store_sales\") filter (where \"store_state\" = 'WA') " + "from \"foodmart\""; <START> String expectedQuery = "{'queryType':'timeseries','dataSource':'foodmart','descending':false," <END> + "'granularity':'all','filter':{'type':'or','fields':[{'type':'selector','dimension':" + "'store_state','value':'CA'},{'type':'selector','dimension':'store_state'," + "'value':'WA'}]},'aggregations':[{'type':'filtered','filter':{'type':'selector'," + "'dimension':'store_state','value':'CA'},'aggregator':{'type':'doubleSum','name':" + "'EXPR$0','fieldName':'store_sales'}},{'type':'filtered','filter':{'type':'selector'," + "'dimension':'store_state','value':'WA'},'aggregator':{'type':'doubleSum','name':" + "'EXPR$1','fieldName':'store_sales'}}],'intervals':" + "['1900-01-09T00:00:00.000/2992-01-10T00:00:00.000']," + "'context':{'skipEmptyBuckets':true}}"; sql(sql).queryContains(druidChecker(expectedQuery)); }</code><technical_language>execute some of this queries, e.g., returnsUnordered, verify executed correctly</technical_language>

Target:
@Test public void testFilterClausesFactoredForPruning1() { String sql = "select " + "sum(\"store_sales\") filter (where \"store_state\" = 'CA'), " + "sum(\"store_sales\") filter (where \"store_state\" = 'WA') " + "from \"foodmart\""; String expectedQuery = "{'queryType':'timeseries','dataSource':'foodmart','descending':false," + "'granularity':'all','filter':{'type':'or','fields':[{'type':'selector','dimension':" + "'store_state','value':'CA'},{'type':'selector','dimension':'store_state'," + "'value':'WA'}]},'aggregations':[{'type':'filtered','filter':{'type':'selector'," + "'dimension':'store_state','value':'CA'},'aggregator':{'type':'doubleSum','name':" + "'EXPR$0','fieldName':'store_sales'}},{'type':'filtered','filter':{'type':'selector'," + "'dimension':'store_state','value':'WA'},'aggregator':{'type':'doubleSum','name':" + "'EXPR$1','fieldName':'store_sales'}}],'intervals':" + "['1900-01-09T00:00:00.000/2992-01-10T00:00:00.000']," + "'context':{'skipEmptyBuckets':true}}"; sql(sql) .queryContains(druidChecker(expectedQuery)) .returnsUnordered("EXPR$0=159167.840144217; EXPR$1=263793.2202244997"); }
Source:
<code>public Answer dettachVolume(final DettachCommand cmd) { final DiskTO disk = cmd.getDisk(); final VolumeObjectTO vol = (VolumeObjectTO)disk.getData(); final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)vol.getDataStore(); final String vmName = cmd.getVmName(); final String serial = resource.diskUuidToSerial(vol.getUuid()); try { final Connect conn = LibvirtConnection.getConnectionByVmName(vmName); final KVMPhysicalDisk phyDisk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), vol.getPath()); attachOrDetachDisk(conn, false, vmName, phyDisk, disk.getDiskSeq().intValue(), serial, vol.getBytesReadRate(), vol.getBytesWriteRate(), vol.getIopsReadRate(), vol.getIopsWriteRate()); storagePoolMgr.disconnectPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), vol.getPath()); return new DettachAnswer(disk); } catch (final LibvirtException e) { <START> s_logger.debug("Failed to dettach volume: " + vol.getPath() + ", due to ", e); <END> return new DettachAnswer(e.toString()); } catch (final InternalErrorException e) { s_logger.debug("Failed to dettach volume: " + vol.getPath() + ", due to ", e); return new DettachAnswer(e.toString()); } }</code><technical_language>correct spelling is detach</technical_language>

Target:
public Answer dettachVolume(final DettachCommand cmd) { final DiskTO disk = cmd.getDisk(); final VolumeObjectTO vol = (VolumeObjectTO)disk.getData(); final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)vol.getDataStore(); final String vmName = cmd.getVmName(); final String serial = resource.diskUuidToSerial(vol.getUuid()); try { final Connect conn = LibvirtConnection.getConnectionByVmName(vmName); final KVMPhysicalDisk phyDisk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), vol.getPath()); attachOrDetachDisk(conn, false, vmName, phyDisk, disk.getDiskSeq().intValue(), serial, vol.getBytesReadRate(), vol.getBytesWriteRate(), vol.getIopsReadRate(), vol.getIopsWriteRate()); storagePoolMgr.disconnectPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), vol.getPath()); return new DettachAnswer(disk); } catch (final LibvirtException e) { s_logger.debug("Failed to detach volume: " + vol.getPath() + ", due to ", e); return new DettachAnswer(e.toString()); } catch (final InternalErrorException e) { s_logger.debug("Failed to detach volume: " + vol.getPath() + ", due to ", e); return new DettachAnswer(e.toString()); } }
Source:
<code>private boolean isResigned(File file) { if (file.getAbsolutePath().contains("resigned")) { <START> String ext = file.getName(); <END> return ext.endsWith(".apk"); } return false; }</code><technical_language>this return isApp(file)</technical_language>

Target:
private boolean isResigned(File file) { return (isApp(file) && file.getAbsolutePath().contains("resigned")); }
Source:
<code>static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); <START> assertEquals(expectedStatusCode, response.statusCode()); <END> assertConfigurationEquals(expected, response.getValue()); }</code><technical_language>getStatusCode()</technical_language>

Target:
static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); }
Source:
<code><START> public int getCellType() { <END> throw new UnsupportedOperationException("Not implememted yet."); }</code><technical_language>Deleted @NotImplemented return getCellTypeEnum().getCode();</technical_language>

Target:
public CellType getCellType() { return cellType; }
Source:
<code>public Path generate(String id, String version, String packaging, String... dependencyList) throws IOException, NoSuchAlgorithmException, JAXBException, NugetFormatException { NugetArtifactCoordinates coordinates = new NugetArtifactCoordinates(id, version, packaging); <START> Path fullPath = basePath.resolve(coordinates.toPath()); <END> Files.createDirectories(fullPath.getParent()); SemanticVersion semanticVersion = SemanticVersion.parse(version); logger.debug("Version of the package: {}", packaging, semanticVersion.toString()); generate(fullPath, id, semanticVersion, dependencyList); return fullPath; }</code><technical_language>@ptirador dropped .normalize().toAbsolutePath() part</technical_language>

Target:
public Path generate(String id, String version, String packaging, String... dependencyList) throws IOException, NoSuchAlgorithmException, JAXBException, NugetFormatException { NugetArtifactCoordinates coordinates = new NugetArtifactCoordinates(id, version, packaging); Path fullPath = basePath.resolve(coordinates.toPath()).normalize().toAbsolutePath(); Files.createDirectories(fullPath.getParent()); SemanticVersion semanticVersion = SemanticVersion.parse(version); logger.debug("Version of the package: {}", packaging, semanticVersion.toString()); generate(fullPath, id, semanticVersion, dependencyList); return fullPath; }
Source:
<code>protected IScalarEvaluator createEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) throws AlgebricksException { final ArrayBackedValueStorage abvs = new ArrayBackedValueStorage(); final UTF8StringPointable stringp = (UTF8StringPointable) UTF8StringPointable.FACTORY.createPointable(); final TaggedValuePointable nodep = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); final ByteBufferInputStream bbis = new ByteBufferInputStream(); final DataInputStream di = new DataInputStream(bbis); final SequenceBuilder sb = new SequenceBuilder(); final ArrayBackedValueStorage abvsFileNode = new ArrayBackedValueStorage(); final int partition = ctx.getTaskAttemptId().getTaskId().getPartition(); final String nodeId = ctx.getJobletContext().getApplicationContext().getNodeId(); final ITreeNodeIdProvider nodeIdProvider = new TreeNodeIdProvider((short) partition); return new AbstractTaggedValueArgumentScalarEvaluator(args) { @Override protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { IndexUpdater updater = new IndexUpdater(args, result, stringp, bbis, di, sb, abvs, nodeIdProvider, abvsFileNode, nodep, nodeId); try { updater.setup(); updater.updateIndex(); updater.updateMetadataFile(); updater.exit(); } catch (IOException | NoSuchAlgorithmException | JAXBException e) { throw new SystemException(ErrorCode.SYSE0001, e); <START> } <END> } }; }</code><technical_language>Add boolean result: XDMConstants.setTrue(result);</technical_language>

Target:
protected IScalarEvaluator createEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) throws AlgebricksException { final ArrayBackedValueStorage abvs = new ArrayBackedValueStorage(); final UTF8StringPointable stringp = (UTF8StringPointable) UTF8StringPointable.FACTORY.createPointable(); final TaggedValuePointable nodep = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); final ByteBufferInputStream bbis = new ByteBufferInputStream(); final DataInputStream di = new DataInputStream(bbis); final SequenceBuilder sb = new SequenceBuilder(); final ArrayBackedValueStorage abvsFileNode = new ArrayBackedValueStorage(); final int partition = ctx.getTaskAttemptId().getTaskId().getPartition(); final String nodeId = ctx.getJobletContext().getApplicationContext().getNodeId(); final ITreeNodeIdProvider nodeIdProvider = new TreeNodeIdProvider((short) partition); return new AbstractTaggedValueArgumentScalarEvaluator(args) { @Override protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { IndexUpdater updater = new IndexUpdater(args, result, stringp, bbis, di, sb, abvs, nodeIdProvider, abvsFileNode, nodep, nodeId); try { updater.setup(); updater.updateIndex(); updater.updateMetadataFile(); updater.exit(); XDMConstants.setTrue(result); } catch (IOException | NoSuchAlgorithmException | JAXBException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } }; }
Source:
<code>public String getEnvironmentIdByName(String ownerId, String envName) { String jpql = "SELECT e.id FROM Environment e WHERE e.owner.id = :owner_id and e.name = :env_name"; String envId = null; if (ownerId != null && envName != null) { try { envId = this.getEntityManager().createQuery(jpql, String.class) .setParameter("owner_id", ownerId).setParameter("env_name", envName) <START> .getSingleResult(); <END> } catch (NoResultException exp) { log.debug("Unable to find environment Id by envName {}", envName); } } return envId; }</code><technical_language>indentation is 4 characters/1 tab length this is spanned is odd. Also, chaining multiple calls hit line limit, split method calls: envId = this.getEntityManager() .createQuery(jpql, String.class) .setParameter(...) .setParameter(...) .getSingleResult();</technical_language>

Target:
public String getEnvironmentIdByName(String ownerId, String envName) { String jpql = "SELECT e.id FROM Environment e WHERE e.owner.id = :owner_id and e.name = :env_name"; String envId = null; if (ownerId != null && envName != null) { try { envId = this.getEntityManager() .createQuery(jpql, String.class) .setParameter("owner_id", ownerId) .setParameter("env_name", envName) .getSingleResult(); } catch (NoResultException exp) { log.trace("Unable to find environment Id by envName {}", envName); } } return envId; }
Source:
<code>public static void reorderBookmark(Context context, long id, int orderId) { ContentValues cv = new ContentValues(); cv.put(Columns.ORDER_ID, orderId); <START> context.getContentResolver().update(Columns.CONTENT_URI, cv, <END> Columns._ID + " = ?", new String[] { String.valueOf(id) }); }</code><technical_language>ContentUris.withAppendedId(Columns.CONTENT_URI, id) instead of selection below</technical_language>

Target:
public static void reorderBookmark(Context context, long id, int orderId) { ContentValues cv = new ContentValues(); cv.put(Columns.ORDER_ID, orderId); Uri uri = ContentUris.withAppendedId(Columns.CONTENT_URI, id); context.getContentResolver().update(uri, cv, null, null); }
Source:
<code>public void create(CDPStructuredEvent structuredEvent) { StructuredEventType eventType = structuredEvent.getOperation().getEventType(); CDPEventDataExtractor<? extends CDPStructuredEvent> eventDataExtractor = eventDataExtractorMap.get(eventType.name().toLowerCase() + "CDPEventDataExtractor"); if (eventDataExtractor == null) { LOGGER.debug("Event data converter does not exist for event type of {}", eventType); return; } boolean shouldAudit = eventDataExtractor.shouldAudit(structuredEvent); if (shouldAudit) { <START> sendAsyncEvent(AUDIT_EVENT_LOG_MESSAGE, eventFactory.createEvent(structuredEvent)); <END> } else { LOGGER.debug("Audit Event is disabled for this structure event: {}", structuredEvent); } }</code><technical_language>I a happy log message welcomed :)</technical_language>

Target:
public void create(CDPStructuredEvent structuredEvent) { StructuredEventType eventType = structuredEvent.getOperation().getEventType(); CDPEventDataExtractor<? extends CDPStructuredEvent> eventDataExtractor = eventDataExtractorMap.get(eventType.name().toLowerCase() + "CDPEventDataExtractor"); if (eventDataExtractor == null) { LOGGER.debug("Event data converter does not exist for event type of {}", eventType); return; } boolean shouldAudit = eventDataExtractor.shouldAudit(structuredEvent); if (shouldAudit) { sendAsyncEvent(AUDIT_EVENT_LOG_MESSAGE, eventFactory.createEvent(structuredEvent)); LOGGER.debug("Audit Event is fired for this structured event: {}", structuredEvent); } else { LOGGER.debug("Audit Event is disabled for this structured event: {}", structuredEvent); } }
Source:
<code>protected Map<String, Pair<Class, Object>> getOverriddenReturnTypes() { Pair<Class, Object> statusPair = new Pair<>(); statusPair.setA(Sort.class); statusPair.setB(Sort.parse("attr")); Pair<Class, Object> enumOptions = new Pair<>(); enumOptions.setA(List.class); enumOptions.setB(Collections.singletonList("test")); Map<String, Pair<Class, Object>> map = new HashMap<>(); <START> map.put(AttributeMetadata.ORDER_BY, statusPair); <END> return map; }</code><technical_language>I mean, defined a lines this used: java Pair<Class, Object> enumOptions = new Pair<>(); enumOptions.setA(List.class); enumOptions.setB(Collections.singletonList("test"));</technical_language>

Target:
protected Map<String, Pair<Class, Object>> getOverriddenReturnTypes() { Pair<Class, Object> orderPair = new Pair<>(); orderPair.setA(Sort.class); orderPair.setB(Sort.parse("attr")); Map<String, Pair<Class, Object>> map = new HashMap<>(); map.put(AttributeMetadata.ORDER_BY, orderPair); return map; }
Source:
<code>public boolean shouldAskForRating() { return allEnvironmentRequirementsMet() <START> && totalEventCountPredicates.allowFeedbackPrompt() <END> && firstEventTimePredicates.allowFeedbackPrompt() && lastEventTimePredicates.allowFeedbackPrompt() && lastEventVersionPredicates.allowFeedbackPrompt(); }</code><technical_language>Good refactor want rename this</technical_language>

Target:
public boolean shouldAskForRating() { return allEnvironmentRequirementsMet() && totalCountPredicate.allowFeedbackPrompt() && firstTimePredicate.allowFeedbackPrompt() && lastTimePredicate.allowFeedbackPrompt() && lastVersionPredicate.allowFeedbackPrompt(); }
Source:
<code>private void queryVfMap() { final AsyncQuery asyncQuery = new AsyncQuery(); <START> asyncQuery.setModel(this); <END> asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValueObj) { VdcQueryReturnValue returnValue = (VdcQueryReturnValue) returnValueObj; vfMap = returnValue.getReturnValue(); queryNetworkAttachments(); } }; VDS vds = getEntity(); IdQueryParameters params = new IdQueryParameters(vds.getId()); params.setRefresh(false); Frontend.getInstance().runQuery(VdcQueryType.GetVfMap, params, asyncQuery); }</code><technical_language>is need for this</technical_language>

Target:
private void queryVfMap() { final AsyncQuery asyncQuery = new AsyncQuery(); asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValueObj) { VdcQueryReturnValue returnValue = (VdcQueryReturnValue) returnValueObj; vfMap = returnValue.getReturnValue(); if (vfMap == null) { vfMap = Collections.emptyMap(); } queryFreeBonds(); } }; VDS vds = getEntity(); IdQueryParameters params = new IdQueryParameters(vds.getId()); params.setRefresh(false); Frontend.getInstance().runQuery(VdcQueryType.GetVfToPfMapByHostId, params, asyncQuery); }
Source:
<code>private void handleBulkWriteError(List<BulkWriteError> errors, List<DocInfo> docs) { for (BulkWriteError e : errors) { DocInfo doc = docs.get(e.getIndex()); doc.docCtx.addError(Error.get("remove", MongoCrudConstants.ERR_SAVE_ERROR, e.getMessage())); <START> } <END> }</code><technical_language>ERR_DELETE_ERROR, add if</technical_language>

Target:
private void handleBulkWriteError(List<BulkWriteError> errors, List<DocInfo> docs) { for (BulkWriteError e : errors) { DocInfo doc = docs.get(e.getIndex()); doc.docCtx.addError(Error.get("remove", MongoCrudConstants.ERR_DELETE_ERROR, e.getMessage())); } }
Source:
<code>protected PairSupplier<Q, E> getPairSupplier(){ if (endpointProvider == null){ throw new NullPointerException("Init endpoint provider!"); } if (queryProvider == null) { <START> logger.info("Query provider is null."); <END> } if (pairSupplier == null){ pairSupplier = pairSupplierFactory.create(queryProvider, endpointProvider); } return pairSupplier; }</code><technical_language>please, don't. log for starting load thread. :)</technical_language>

Target:
protected PairSupplier<Q, E> getPairSupplier(){ return pairSupplier; }
Source:
<code>public DataStream(String name, String timeStampField, List<Index> indices, long generation) { this.name = name; this.timeStampField = timeStampField; this.indices = indices; this.generation = generation; assert indices.size() > 0; <START> assert indices.get(indices.size() - 1).getName().endsWith(getBackingIndexName(name, generation)); <END> }</code><technical_language>relax logic naming of backing indices, I write index needs stay same. In other words, ILM trigger a rollover creates a new write index, current write index conform naming scheme ILM shrink modify one</technical_language>

Target:
public DataStream(String name, String timeStampField, List<Index> indices, long generation) { this.name = name; this.timeStampField = timeStampField; this.indices = indices; this.generation = generation; assert indices.size() > 0; assert indices.get(indices.size() - 1).getName().equals(getDefaultBackingIndexName(name, generation)); }
Source:
<code>private void redirectToYoutubeDialog() { <START> if (getActivity() != null && !getActivity().isDestroyed()) { <END> ((BaseFragmentActivity) getActivity()) .showAlertDialog( getString(R.string.assessment_unable_to_play_video), getString(R.string.assessment_unable_to_play_video_message), getString(R.string.assessment_open_on_youtube), (dialog, which) -> BrowserUtil .open(getActivity(), unit.getData().encodedVideos.getYoutubeVideoInfo().url), getString(R.string.label_cancel), null ); } }</code><technical_language>release player showing error dialog</technical_language>

Target:
private void redirectToYoutubeDialog() { releaseYoutubePlayer(); if (getActivity() != null && !getActivity().isDestroyed()) { ((BaseFragmentActivity) getActivity()) .showAlertDialog( getString(R.string.assessment_unable_to_play_video), getString(R.string.assessment_unable_to_play_video_message), getString(R.string.assessment_open_on_youtube), (dialog, which) -> BrowserUtil .open(getActivity(), unit.getData().encodedVideos.getYoutubeVideoInfo().url), getString(R.string.label_ok), null ); } }
Source:
<code>private GenericToken findTokenSiblingInThisNode(GenericToken token, int shift) { if (shift == 0) { return token; } else if (shift < 0) { return TokenOps.nthPrevious(jjtGetFirstToken(), token, -shift); } else { <START> return TokenOps.nthFollower(token, +shift); <END> } }</code><technical_language>this explicit + unary is pointless</technical_language>

Target:
private GenericToken findTokenSiblingInThisNode(GenericToken token, int shift) { if (shift == 0) { return token; } else if (shift < 0) { return TokenUtils.nthPrevious(jjtGetFirstToken(), token, -shift); } else { return TokenUtils.nthFollower(token, shift); } }
Source:
<code>private void updateOnNetworkChanges(final DownloadManager downloadManager) { <START> if (deviceDoesNotSupportConnectivityChangesBroadcast()) { <END> ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest networkRequest = new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(); connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { Log.v("network is active now from inside the download manager"); downloadManager.forceStart(); } }); } }</code><technical_language>a guard clause for easier reading + 1 level of indentation & preferring positive if (deviceSupportsConnectivityChangesBroadcast()) { return; } ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest networkRequest = new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(); connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { Log.v("network is active download manager"); downloadManager.forceStart(); } });</technical_language>

Target:
private void updateOnNetworkChanges(final DownloadManager downloadManager) { if (deviceSupportsConnectivityChangesBroadcast()) { return; } ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest networkRequest = new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(); connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { LLog.v("network is active now from inside the download manager"); downloadManager.forceStart(); } }); }
Source:
<code>public Image decorateImage(Image image, Object element) { boolean useSessionLoadedImage = false; if (element instanceof IFile) { IFile iFileToDecorate = (IFile) element; if (SiriusUtil.SESSION_RESOURCE_EXTENSION.equals(iFileToDecorate.getProjectRelativePath().getFileExtension())) { <START> Collection<Session> sessions = SessionManager.INSTANCE.getSessions(); Iterator<Session> sessionIte = sessions.iterator(); while (sessionIte.hasNext() && !useSessionLoadedImage) { Session session = sessionIte.next(); Set<Resource> allSessionResources = session.getAllSessionResources(); for (Resource resource : allSessionResources) { URI sessionUri = resource.getURI(); if (sessionUri != null && sessionUri.isPlatformResource()) { IFile sessionIFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(sessionUri.toPlatformString(true))); if (iFileToDecorate.getProjectRelativePath().equals(sessionIFile.getProjectRelativePath()) && session.isOpen()) { useSessionLoadedImage = true; break; } } } <END> } } } if (useSessionLoadedImage) { return SiriusEditPlugin.getPlugin().getImage(SESSION_LOADED_IMAGE_DESCRIPTOR); } return image; }</code><technical_language>I fear this iteration costly, depending frequently platform calls decorateImage</technical_language>

Target:
public Image decorateImage(Image image, Object element) { boolean useSessionLoadedImage = false; if (!ModelExplorerView.class.getTypeName().equals(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().getClass().getTypeName()) && element instanceof IFile) { List<Session> relatedSessions = FileSessionFinder.getRelatedSessions(Lists.newArrayList((IFile) element), false, false); for (Session session : relatedSessions) { if (session.isOpen()) { useSessionLoadedImage = true; break; } } } if (useSessionLoadedImage) { return SiriusEditPlugin.getPlugin().getImage(SESSION_LOADED_IMAGE_DESCRIPTOR); } return image; }