auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static LabelType fromApprovalCategory(ApprovalCategory ac, List<ApprovalCategoryValue> acvs) { List<LabelValue> values = new ArrayList<LabelValue>(acvs.size()); for (ApprovalCategoryValue acv : acvs) { values.add( new LabelValue(acv.getValue(), acv.getName())); } LabelType lt = new LabelType(ac.getId().get(), ac.getLabelName(), values); lt.setAbbreviatedName(ac.getAbbreviatedName()); lt.setFunctionName(ac.getFunctionName()); lt.setCopyMinScore(ac.isCopyMinScore()); <START> lt.setCanOverride(false); <END> return lt; }</code><technical_language>ApprovalCategory overrideable</technical_language>

Target:
public static LabelType fromApprovalCategory(ApprovalCategory ac, List<ApprovalCategoryValue> acvs) { List<LabelValue> values = new ArrayList<LabelValue>(acvs.size()); for (ApprovalCategoryValue acv : acvs) { values.add( new LabelValue(acv.getValue(), acv.getName())); } LabelType lt = new LabelType(ac.getId().get(), ac.getLabelName(), values); lt.setAbbreviatedName(ac.getAbbreviatedName()); lt.setFunctionName(ac.getFunctionName()); lt.setCopyMinScore(ac.isCopyMinScore()); lt.setCanOverride(true); return lt; }
Source:
<code>public boolean test(@Nonnull ItemStack item) { if (items.isEmpty()) { return defaultValue; } int potentialMatches = 0; <START> for (ItemStackWrapper stack : items) { if (stack.getType() == item.getType()) { potentialMatches++; } } <END> if (potentialMatches == 0) { return defaultValue; } else { ItemStack subject = potentialMatches == 1 ? item : new ItemStackWrapper(item); for (ItemStackWrapper stack : items) { if (SlimefunUtils.isItemSimilar(subject, stack, checkLore, false)) { return !defaultValue; } } return defaultValue; } }</code><technical_language>(In I approved I assume waiting Walshy decide believes you, this a bump for blob)</technical_language>

Target:
public boolean test(@Nonnull ItemStack item) { if (items.isEmpty()) { return rejectOnMatch; } int potentialMatches = 0; for (ItemStackWrapper stack : items) { if (stack.getType() == item.getType()) { potentialMatches++; } } if (potentialMatches == 0) { return rejectOnMatch; } else { ItemStack subject = potentialMatches == 1 ? item : new ItemStackWrapper(item); for (ItemStackWrapper stack : items) { if (SlimefunUtils.isItemSimilar(subject, stack, checkLore, false)) { return !rejectOnMatch; } } return rejectOnMatch; } }
Source:
<code>public void coerce(RecordCursor delegate, int field) { if (delegate.isNull(field)) { setIsNull(true); return; } Block block = (Block) delegate.getObject(field); if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); BlockBuilder mapBuilder = blockBuilder.beginBlockEntry(); for (int i = 0; i < block.getPositionCount(); i += 2) { if (block.isNull(i)) { mapBuilder.appendNull(); } else if (keyCoercer == null) { block.writePositionTo(i, mapBuilder); mapBuilder.closeEntry(); } else { <START> rewriteBlock(fromKeyType, toKeyType, block.getSingleValueBlock(i), 0, mapBuilder, keyCoercer, field, bridgingRecordCursor); <END> } if (block.isNull(i + 1)) { mapBuilder.appendNull(); } if (valueCoercer == null) { block.writePositionTo(i + 1, mapBuilder); mapBuilder.closeEntry(); } else { rewriteBlock(fromValueType, toValueType, block.getSingleValueBlock(i + 1), 0, mapBuilder, valueCoercer, field, bridgingRecordCursor); } } blockBuilder.closeEntry(); pageBuilder.declarePosition(); setObject(blockBuilder.getRegion(blockBuilder.getPositionCount() - 1, 1).getObject(0, Block.class)); }</code><technical_language>Instead of block.getSingleValueBlock(i), 0), write block, i</technical_language>

Target:
public void coerce(RecordCursor delegate, int field) { if (delegate.isNull(field)) { setIsNull(true); return; } Block block = (Block) delegate.getObject(field); if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); BlockBuilder mapBuilder = blockBuilder.beginBlockEntry(); for (int i = 0; i < block.getPositionCount(); i++) { int k = i % 2; if (coercers[k] == null) { toKeyValueTypes.get(k).appendTo(block, i, mapBuilder); } else { if (block.isNull(i)) { mapBuilder.appendNull(); } else { rewriteBlock(fromKeyValueTypes.get(k), toKeyValueTypes.get(k), block, i, mapBuilder, coercers[k], bridgingRecordCursor); } } } blockBuilder.closeEntry(); pageBuilder.declarePosition(); setObject(toType.getObject(blockBuilder, blockBuilder.getPositionCount() - 1)); }
Source:
<code>public final Iterable<E> search( final B request, final GenomicsRequestInitializer<? super C> initializer) { final A api = getApi(genomics); return FluentIterable .from( new Iterable<Pair>() { @Override public Iterator<Pair> iterator() { try { return new AbstractSequentialIterator<Pair>( new Pair(createSearch(api, request, Optional.<String>absent()), null)) { @Override protected Pair computeNext(Pair pair) { return Optional.fromNullable(pair.request) .transform( new Function<C, Pair>() { @Override public Pair apply(C search) { try { D response = search.execute(); <START> successfulRequests += 1; <END> Optional<String> pageToken = Optional.fromNullable(getNextPageToken(response)); return new Pair( pageToken.isPresent() ? createSearch(api, request, pageToken) : null, response); } catch (IOException e) { throw new SearchException(e); } } }) .orNull(); } }; } catch (IOException e) { throw new SearchException(e); } } }) .skip(1) .transform( new Function<Pair, D>() { @Override public D apply(Pair pair) { return pair.response; } }) .transformAndConcat( new Function<D, Iterable<E>>() { @Override public Iterable<E> apply(D response) { return Optional.fromNullable(getResponses(response)).or(Collections.<E>emptyList()); } }); }</code><technical_language>successfulRequests++</technical_language>

Target:
public final Iterable<E> search( final B request, final GenomicsRequestInitializer<? super C> initializer) { final A api = getApi(genomics); return FluentIterable .from( new Iterable<Pair>() { @Override public Iterator<Pair> iterator() { try { return new AbstractSequentialIterator<Pair>( new Pair(createSearch(api, request, Optional.<String>absent()), null)) { @Override protected Pair computeNext(Pair pair) { return Optional.fromNullable(pair.request) .transform( new Function<C, Pair>() { @Override public Pair apply(C search) { try { D response = search.execute(); successfulRequests++; Optional<String> pageToken = Optional.fromNullable(getNextPageToken(response)); return new Pair( pageToken.isPresent() ? createSearch(api, request, pageToken) : null, response); } catch (IOException e) { throw new SearchException(e); } } }) .orNull(); } }; } catch (IOException e) { throw new SearchException(e); } } }) .skip(1) .transform( new Function<Pair, D>() { @Override public D apply(Pair pair) { return pair.response; } }) .transformAndConcat( new Function<D, Iterable<E>>() { @Override public Iterable<E> apply(D response) { return Optional.fromNullable(getResponses(response)).or(Collections.<E>emptyList()); } }); }
Source:
<code>private static User getUserByUUID(UUID uuid) { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } if (uuid == null) { <START> throw new RuntimeException("Economy uuid cannot be null"); <END> } return ess.getUser(uuid); }</code><technical_language>RuntimeException for this. IllegalArgumentException is a choice</technical_language>

Target:
private static User getUserByUUID(UUID uuid) { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } if (uuid == null) { throw new IllegalArgumentException("Economy uuid cannot be null"); } return ess.getUser(uuid); }
Source:
<code>public static ResponseStatus getResponseStatus(RestServiceErrorCode restServiceErrorCode) { switch (restServiceErrorCode) { case Deleted: return ResponseStatus.Gone; case NotFound: return ResponseStatus.NotFound; case BadRequest: case InvalidArgs: case InvalidRequestState: case MalformedRequest: case MissingArgs: case UnknownHttpObject: case UnsupportedHttpMethod: case UnsupportedOperation: return ResponseStatus.BadRequest; <START> case BlobMediaScanDirty: <END> return ResponseStatus.FORBIDDEN; case Unauthorized: return ResponseStatus.Unauthorized; case BlobMediaScanInProgress: return ResponseStatus.PROXY_AUTHENTICATION_REQUIRED; case InternalServerError: case InternalObjectCreationError: case RequestChannelClosed: case RequestResponseQueuingFailure: case ResponseBuildingFailure: case ServiceUnavailable: case UnsupportedRestMethod: default: return ResponseStatus.InternalServerError; } }</code><technical_language>references blobs in RestServiceErrorCode. Call ResourceDirty</technical_language>

Target:
public static ResponseStatus getResponseStatus(RestServiceErrorCode restServiceErrorCode) { switch (restServiceErrorCode) { case Deleted: return ResponseStatus.Gone; case NotFound: return ResponseStatus.NotFound; case BadRequest: case InvalidArgs: case InvalidRequestState: case MalformedRequest: case MissingArgs: case UnknownHttpObject: case UnsupportedHttpMethod: case UnsupportedOperation: return ResponseStatus.BadRequest; case ResourceDirty: return ResponseStatus.Forbidden; case Unauthorized: return ResponseStatus.Unauthorized; case ResourceScanInProgress: return ResponseStatus.ProxyAuthenticationRequired; case InternalServerError: case InternalObjectCreationError: case RequestChannelClosed: case RequestResponseQueuingFailure: case ResponseBuildingFailure: case ServiceUnavailable: case UnsupportedRestMethod: default: return ResponseStatus.InternalServerError; } }
Source:
<code>public static CommandBase<?> createCommand(String className, Guid commandId) { Constructor<?> constructor = null; Boolean isAcessible = null; try { constructor = Class.forName(className).getDeclaredConstructor(Guid.class); if (!constructor.isAccessible()) { isAcessible = constructor.isAccessible(); constructor.setAccessible(true); } <START> CommandBase<?> cmd = (CommandBase<?>) constructor.newInstance(commandId); <END> Injector.injectMembers(cmd); return cmd; } catch (Exception e) { log.error( "CommandsFactory : Failed to get type information using " + "reflection for Class : " + className + ", Command Id:" + commandId, e); return null; } finally { if (isAcessible != null) { constructor.setAccessible(isAcessible); } } }</code><technical_language>nice. redundant arrays</technical_language>

Target:
public static CommandBase<?> createCommand(String className, Guid commandId) { Constructor<?> constructor = null; Boolean isAcessible = null; try { constructor = Class.forName(className).getDeclaredConstructor(Guid.class); if (!constructor.isAccessible()) { isAcessible = constructor.isAccessible(); constructor.setAccessible(true); } CommandBase<?> cmd = (CommandBase<?>) constructor.newInstance(commandId); return Injector.injectMembers(cmd); } catch (Exception e) { log.error("CommandsFactory : Failed to get type information using reflection for Class '{}', Command Id '{}': {}", className, commandId, e.getMessage()); log.error("Exception", e); return null; } finally { if (isAcessible != null) { constructor.setAccessible(isAcessible); } } }
Source:
<code>public void resourceChanged(IResourceChangeEvent event) { final IResourceDelta delta = event.getDelta(); if (delta == null) { return; } <START> lock.lock(); <END> try { delta.accept(new ModelResourceDeltaVisitor()); } catch (CoreException e) { EMFCompareIDEUIPlugin.getDefault().log(e); } finally { lock.unlock(); } }</code><technical_language>? this happen concurrently ? workspace modification locks prevents this</technical_language>

Target:
public void resourceChanged(IResourceChangeEvent event) { final IResourceDelta delta = event.getDelta(); if (delta == null) { return; } internalLock.lock(); try { delta.accept(new ModelResourceDeltaVisitor()); } catch (CoreException e) { EMFCompareIDEUIPlugin.getDefault().log(e); } finally { internalLock.unlock(); } }
Source:
<code>public void withR2D3(String userAction, final Command command) { withDependencies( "R2D3", userAction, new Dependency[] { Dependency.cranPackage("htmltools", "0.3.6"), Dependency.cranPackage("htmlwidgets", "1.2", true), Dependency.cranPackage("jsonlite", "0.9.19"), <START> Dependency.cranPackage("r2d3", "0.2.0", true) <END> }, true, succeeded -> { if (succeeded) command.execute(); }); }</code><technical_language>Worth recommending latest r2d3 CRAN? (0.2.2)</technical_language>

Target:
public void withR2D3(String userAction, final Command command) { withDependencies( "R2D3", userAction, new Dependency[] { Dependency.cranPackage("htmltools", "0.3.6"), Dependency.cranPackage("htmlwidgets", "1.2", true), Dependency.cranPackage("jsonlite", "0.9.19"), Dependency.cranPackage("r2d3", "0.2.2", true) }, true, succeeded -> { if (succeeded) command.execute(); }); }
Source:
<code>void addFieldListParams(String name, Iterable<?> values) { if (name == null) { throw new IllegalArgumentException("Field name must not be null."); } if (values == null) { throw new IllegalArgumentException("Field param values must not be null."); } for (Object value : values) { <START> formBody.addField(name, value.toString()); <END> } }</code><technical_language>This NPE if passes a list null. Do ignore throw exception</technical_language>

Target:
void addFieldListParams(String name, Iterable<?> values) { if (name == null) { throw new IllegalArgumentException("Field name must not be null."); } if (values == null) { throw new IllegalArgumentException("Field param values must not be null."); } for (Object value : values) { if (value != null) { formBody.addField(name, value.toString()); } } }
Source:
<code>private void visitProperties(ObjectType objType, boolean isStatic) { <START> visitProperties(objType, isStatic, null); <END> }</code><technical_language>pass Collections.emptySet() here, handle null below? avoid null favour empty collections instead (fewer code paths, pondering nullness, etc)</technical_language>

Target:
private void visitProperties(ObjectType objType, boolean isStatic) { visitProperties(objType, isStatic, Collections.<String>emptySet()); }
Source:
<code>public static void testGetLevelSizeOK() { <START> final AbstractBAMFileIndex afi = new DiskBasedBAMFileIndex(new File(BAM_FILE.getPath() + ".bai"), <END> null); Assert.assertEquals(afi.getLevelSize(0), 1); Assert.assertEquals(afi.getLevelSize(1), 8); Assert.assertEquals(afi.getLevelSize(2), 64); Assert.assertEquals(afi.getLevelSize(3), 512); Assert.assertEquals(afi.getLevelSize(4), 4096); Assert.assertEquals(afi.getLevelSize(5), 32768); }</code><technical_language>Unnecessary getPath() below, write new File(BAM_FILE + ".bai"). BAM_FILE is unused define BAI_FILE instead</technical_language>

Target:
public static void testGetLevelSizeOK() { Assert.assertEquals(afi.getLevelSize(0), 1); Assert.assertEquals(afi.getLevelSize(1), 8); Assert.assertEquals(afi.getLevelSize(2), 64); Assert.assertEquals(afi.getLevelSize(3), 512); Assert.assertEquals(afi.getLevelSize(4), 4096); Assert.assertEquals(afi.getLevelSize(5), 32768); }
Source:
<code>public void merge() throws MergeException { setDestProject(); try { openSchema(); openRepository(); submitted = db.changes().submitted(destBranch).toList(); preMerge(); updateBranch(); updateChangeStatus(); updateSubscriptions(); } catch (OrmException e) { throw new MergeException("Cannot query the database", e); } finally { if (inserter != null) { inserter.release(); } if (rw != null) { rw.release(); } <START> if (repo != null) { <END> repo.close(); } db.close(); db = null; } }</code><technical_language>repo set null well</technical_language>

Target:
public void merge() throws MergeException { setDestProject(); try { openSchema(); openRepository(); submitted = db.changes().submitted(destBranch).toList(); preMerge(); updateBranch(); updateChangeStatus(); updateSubscriptions(); } catch (OrmException e) { throw new MergeException("Cannot query the database", e); } finally { if (inserter != null) { inserter.release(); } if (rw != null) { rw.release(); } if (repo != null) { repo.close(); } if (db != null) { db.close(); } } }
Source:
<code>public void setProvidedProducts(Collection<Product> providedProducts) { this.providedProductDtos = null; if (providedProducts != null) { <START> this.providedProducts = new HashSet<>(providedProducts); <END> } }</code><technical_language>need clear collection if inbound collection is null. drop entire single line: this.providedProducts = providedProducts != null ? new HashSet<>(providedProducts) : null;</technical_language>

Target:
public void setProvidedProducts(Collection<Product> providedProducts) { this.providedProductDtos = null; if (providedProducts != null) { this.providedProducts = new HashSet<>(providedProducts); } else { this.providedProducts = new HashSet<>(); } }
Source:
<code>public void testOpenFile(final Path sequenceFile) throws IOException { TwoBitSequenceFile tbf = new TwoBitSequenceFile(sequenceFile); final SAMSequenceDictionary dict = tbf.getSequenceDictionary(); Assert.assertNotNull(dict); Assert.assertEquals(dict.size(), 2); Assert.assertEquals(dict.getSequence(0).getSequenceName(), "chrM"); Assert.assertEquals(dict.getSequence(0).getSequenceLength(), 16_571); Assert.assertEquals(dict.getSequence(1).getSequenceName(), "chr20"); Assert.assertEquals(dict.getSequence(0).getSequenceLength(), 1_000_000); Assert.assertNull(tbf.getSequence("do_not_exists")); ReferenceSequence seq =tbf.getSequence("chrM"); Assert.assertNotNull(seq); Assert.assertEquals(seq.getName(), "chrM"); Assert.assertEquals(seq.length(), 16_571); tbf.getSequence("chr20"); Assert.assertNotNull(seq); Assert.assertEquals(seq.getName(), "chr20"); Assert.assertEquals(seq.length(), 1_000_000); <START> final String chrM_100_120="GGAGCCGGAGCACCCTATGTC"; <END> for(int i=0;i<=20;i++) { seq =tbf.getSubsequenceAt("chrM", 100, 100+i); Assert.assertEquals(seq.getName(), "chrM"); Assert.assertEquals(seq.length(), i+1); Assert.assertEquals(seq.getContigIndex() , 99); Assert.assertEquals(seq.getBaseString() , chrM_100_120.substring(0, i)); } tbf.close(); }</code><technical_language>good a test checks Ns masked regions</technical_language>

Target:
public void testOpenFile(final Path sequenceFile) throws IOException { TwoBitSequenceFile tbf = new TwoBitSequenceFile(sequenceFile); final SAMSequenceDictionary dict = tbf.getSequenceDictionary(); Assert.assertNotNull(dict); Assert.assertEquals(dict.size(), 2); Assert.assertEquals(dict.getSequence(0).getSequenceName(), "chrM"); Assert.assertEquals(dict.getSequence(0).getSequenceLength(), 16_571); Assert.assertEquals(dict.getSequence(1).getSequenceName(), "chr20"); Assert.assertEquals(dict.getSequence(1).getSequenceLength(), 1_000_000); Assert.assertNull(tbf.getSequence("do_not_exists")); ReferenceSequence seq =tbf.getSequence("chrM"); Assert.assertNotNull(seq); Assert.assertEquals(seq.getName(), "chrM"); Assert.assertEquals(seq.length(), 16_571); seq = tbf.getSequence("chr20"); Assert.assertNotNull(seq); Assert.assertEquals(seq.getName(), "chr20"); Assert.assertEquals(seq.length(), 1_000_000); final String chrM_100_120="GGAGCCGGAGCACCCTATGTC"; for(int i=0;i<=20;i++) { seq =tbf.getSubsequenceAt("chrM", 100, 100+i); Assert.assertEquals(seq.getName(), "chrM"); Assert.assertEquals(seq.length(), i+1); Assert.assertEquals(seq.getContigIndex() , 99); Assert.assertEquals(seq.getBaseString().toUpperCase() , chrM_100_120.substring(0, i+1)); } tbf.close(); }
Source:
<code>public void onSaveButton(String scenarioType) { if (saveCommand != null) { simulationDescriptor.setSkipFromBuild(view.getSkipFromBuild().isChecked()); switch (ScenarioSimulationModel.Type.valueOf(scenarioType)) { case RULE: saveRuleSettings(); break; case DMN: saveDMNSettings(); <START> break; <END> } saveCommand.execute(); } }</code><technical_language>a small suggestion add a default new IlligalStateException in case if add some new scenario type</technical_language>

Target:
public void onSaveButton(String scenarioType) { if (saveCommand != null) { simulationDescriptor.setSkipFromBuild(view.getSkipFromBuild().isChecked()); switch (ScenarioSimulationModel.Type.valueOf(scenarioType)) { case RULE: saveRuleSettings(); break; case DMN: saveDMNSettings(); break; default: } saveCommand.execute(); } }
Source:
<code>private static boolean isBlockCommentOnOneLine(DetailAST commentBeginAst) { final DetailAST commentEnd = commentBeginAst.getFirstChild().getNextSibling(); <START> return commentEnd.getLineNo() == commentBeginAst.getLineNo(); <END> }</code><technical_language>TokenUtil.areOnSameLine</technical_language>

Target:
private static boolean isBlockCommentOnOneLine(DetailAST commentBeginAst) { final DetailAST commentEnd = commentBeginAst.getFirstChild().getNextSibling(); return TokenUtil.areOnSameLine(commentBeginAst, commentEnd); }
Source:
<code>protected void init() throws EmailException { <START> if (args.projectCache != null) { <END> projectState = args.projectCache.get(project.getNameKey()); } else { projectState = null; } super.init(); owners = getOwners(); watchers = getWatchers(); add(RecipientType.TO, owners); if (!watchers.isEmpty()) { add(RecipientType.BCC, watchers); } setBranchSubjectHeader(); setListIdHeader(); }</code><technical_language>happen args.projectCache is null? If yes, check in line 119 230</technical_language>

Target:
protected void init() throws EmailException { projectState = args.projectCache.get(project.getNameKey()); super.init(); Set<Account.Id> subscribers = getSubscribers(); if (!subscribers.isEmpty()) { add(RecipientType.BCC, subscribers); } setBranchSubjectHeader(); setListIdHeader(); }
Source:
<code>public boolean canRefresh(DRepresentation representation) { return isSupported(representation) && <START> isRequiredViewpointsSelected(representation); <END> }</code><technical_language>areRequiredViewpointsSelected</technical_language>

Target:
public boolean canRefresh(DRepresentation representation) { return isSupported(representation) && areRequiredViewpointsSelected(representation); }
Source:
<code>public static Path removeFirstSegments(Path path, int count) { Objects.requireNonNull(path, "The given path must not be null"); <START> if (path.getNameCount() <= count) { <END> return Paths.get(""); } return path.subpath(count, path.getNameCount()); }</code><technical_language>change some methods signatures/arguments _*NameCount*_ methods _Segments_ wording</technical_language>

Target:
public static Path removeFirstSegments(Path path, int count) { Objects.requireNonNull(path, "The given path must not be null"); if (count < 0) { throw new IllegalArgumentException("The given count must not be negative - count: " + count); } if (path.getNameCount() <= count) { return Paths.get(""); } return path.subpath(count, path.getNameCount()); }
Source:
<code>public void invoke() { for (int x = 0; x < retry; x++) { try { Optional<ManagementClient> orchestrator = getOrchestrator(); if(orchestrator.isPresent()){ UUID workflowId = sendRequest(orchestrator.get()); waitForWorkflow(workflowId, orchestrator.get(), timeout, pollPeriod); } else{ throw new IllegalStateException("Orchestrator can not be selected"); } <START> } catch (Exception e) { <END> log.warn("WorkflowRequest: Error while running on attempt {}, cause {}", this, x, e); } for (int y = 0; y < runtime.getParameters().getInvalidateRetry(); y++) { runtime.invalidateLayout(); Layout layoutToVerify = new Layout(runtime.getLayoutView().getLayout()); if (verifyRequest(layoutToVerify)) { log.info("WorkflowRequest: Successfully completed {}", this); return; } } log.warn("WorkflowRequest: Retrying on attempt {}", this, x); } throw new WorkflowResultUnknownException(); }</code><technical_language>I swallowing exceptions is a good idea. retry needs happen timeout network exceptions</technical_language>

Target:
public void invoke() { for (int x = 0; x < retry; x++) { try { Optional<ManagementClient> orchestrator = getOrchestrator(); if(orchestrator.isPresent()){ UUID workflowId = sendRequest(orchestrator.get()); waitForWorkflow(workflowId, orchestrator.get(), timeout, pollPeriod); } else{ throw new IllegalStateException("Orchestrator can not be selected"); } } catch (NetworkException | TimeoutException | IllegalStateException e) { log.warn("WorkflowRequest: Error while running on attempt {}, cause {}", this, x, e); } for (int y = 0; y < runtime.getParameters().getInvalidateRetry(); y++) { runtime.invalidateLayout(); Layout layoutToVerify = new Layout(runtime.getLayoutView().getLayout()); if (verifyRequest(layoutToVerify)) { log.info("WorkflowRequest: Successfully completed {}", this); return; } } log.warn("WorkflowRequest: Retrying on attempt {}", this, x); } throw new WorkflowResultUnknownException(); }
Source:
<code>public void refresh() { super.refresh(); Object value = this.target.eGet(this.eReference); if (value instanceof EObject) { Adapter adapter = this.composedAdapterFactory.adapt((EObject) value, IItemLabelProvider.class); if (adapter instanceof IItemLabelProvider) { IItemLabelProvider labelProvider = (IItemLabelProvider) adapter; this.text.setText(labelProvider.getText(value)); <START> this.text.setUnderlined(false); <END> this.image.setImage(ExtendedImageRegistry.INSTANCE.getImage(labelProvider.getImage(value))); String onClickExpression = Optional.ofNullable(this.description.getOnClickExpression()).orElse(""); if (!onClickExpression.isEmpty()) { this.text.setUnderlined(true); } } } else if (value == null) { this.image.setImage(null); this.text.setText(Messages.SingleReference_noValue); } }</code><technical_language>remove this, is enough retrieve previous behavior</technical_language>

Target:
public void refresh() { super.refresh(); Object value = this.target.eGet(this.eReference); if (value instanceof EObject) { Adapter adapter = this.composedAdapterFactory.adapt((EObject) value, IItemLabelProvider.class); if (adapter instanceof IItemLabelProvider) { IItemLabelProvider labelProvider = (IItemLabelProvider) adapter; this.image.setImage(ExtendedImageRegistry.INSTANCE.getImage(labelProvider.getImage(value))); String onClickExpression = Optional.ofNullable(this.description.getOnClickExpression()).orElse(""); if (onClickExpression.isEmpty()) { this.text.setText(labelProvider.getText(value)); } else { this.hyperlink.setText(labelProvider.getText(value)); } } } else if (value == null) { this.image.setImage(null); String onClickExpression = Optional.ofNullable(this.description.getOnClickExpression()).orElse(""); if (onClickExpression.isEmpty()) { this.text.setText(Messages.SingleReference_noValue); } else { this.hyperlink.setText(Messages.SingleReference_noValue); } } }
Source:
<code>public static String getTaskSummarySeperator(String connectorKind) { <START> AbstractRepositoryConnector connector = TasksUiPlugin.getConnector(connectorKind); <END> if (connector != null) { return connector.getTaskIDSummarySeprator(); } else { return ""; } }</code><technical_language>TasksUi instead of TasksUiPlugin (it's implementation, is API)</technical_language>

Target:
public static String getTaskSummarySeperator(String connectorKind) { AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(connectorKind); if (connector != null) { return connector.getTaskIDSummarySeprator(); } else { return ": "; } }
Source:
<code>private Set<TestClassRequest> filterAndConvertToTestClassRequests(EngineDiscoveryRequest discoveryRequest, TestClassCollector collector) { List<ClassNameFilter> allClassNameFilters = discoveryRequest.getDiscoveryFiltersByType(ClassNameFilter.class); Filter<Class<?>> adaptedFilter = adaptFilter(composeFilters(allClassNameFilters), Class::getName); Filter<Class<?>> classFilter = new ExclusionReasonConsumingFilter<>(adaptedFilter, (testClass, reason) -> logger.fine(() -> String.format("Class %s was excluded by a class filter: %s", testClass.getName(), reason.orElse("<unknown reason>")))); <START> Predicate<Class<?>> loggingTestClass = isPotentialJunit4Predicate(); <END> return collector.toRequests(classFilter.toPredicate().and(loggingTestClass)); }</code><technical_language>a test class logs; rather, a predicate logs test class. please rename loggingPotentialJUnit4TestClassPredicate similar</technical_language>

Target:
private Set<TestClassRequest> filterAndConvertToTestClassRequests(EngineDiscoveryRequest discoveryRequest, TestClassCollector collector) { List<ClassNameFilter> allClassNameFilters = discoveryRequest.getDiscoveryFiltersByType(ClassNameFilter.class); Filter<Class<?>> adaptedFilter = adaptFilter(composeFilters(allClassNameFilters), Class::getName); Filter<Class<?>> classFilter = new ExclusionReasonConsumingFilter<>(adaptedFilter, (testClass, reason) -> logger.fine(() -> String.format("Class %s was excluded by a class filter: %s", testClass.getName(), reason.orElse("<unknown reason>")))); return collector.toRequests(classFilter.toPredicate().and(loggingPotentialJUnit4TestClassPredicate())); }
Source:
<code>public Stream<A> toStream(final Bounded<A> bounded) { final F<A, A> id = identity(); <START> return Stream.fromFunction(this, id, bounded.min()).takeWhile(item -> !item.equals(bounded.max())); <END> }</code><technical_language>takeWhile suggestion return Stream.fromFunction(this, id, bounded.min()).takeWhile(item ->order.isLessThanOrEqualTo(item, bounded.max())); miss Bounded.max() in Stream. (also avoid Object#equals)</technical_language>

Target:
public Stream<A> toStream(final Bounded<A> bounded) { final F<A, A> id = identity(); return Stream.fromFunction(this, id, bounded.min()).takeWhile(item -> order.isLessThanOrEqualTo(item, bounded.max())); }
Source:
<code>public void validateArgs(CommandLine cl) throws InvalidArgumentException { <START> CommandUtils.checkNumOfArgsEquals(this, cl, 2); <END> }</code><technical_language>h is optional I num of args stay 1. please build Alluxio give a manual test</technical_language>

Target:
public void validateArgs(CommandLine cl) throws InvalidArgumentException { CommandUtils.checkNumOfArgsEquals(this, cl, 1); }
Source:
<code>public boolean equals(Object other) { if (!(other instanceof CommittedOffset)) { return false; } CommittedOffset otherOffset = (CommittedOffset) other; return this.offset == otherOffset.offset && this.leaderEpoch.equals(otherOffset.leaderEpoch) <START> && this.metadata.equals(otherOffset.metadata); <END> }</code><technical_language>I tell, metadata is nullable</technical_language>

Target:
public boolean equals(Object other) { if (!(other instanceof CommittedOffset)) { return false; } CommittedOffset otherOffset = (CommittedOffset) other; return this.offset == otherOffset.offset && this.leaderEpoch.equals(otherOffset.leaderEpoch) && Objects.equals(this.metadata, otherOffset.metadata); }
Source:
<code><START> protected Single<Boolean> put(@NonNull final Uri uri, @NonNull final U item) { <END> checkNotNull(item); checkNotNull(uri); int index = ++nextOperationIndex; completionNotifiers.put(index, PublishSubject.create()); operationSubject.onNext(CoreUpdateValue.create(index, uri, item)); return completionNotifiers.get(index) .first() .toSingle(); }</code><technical_language>Put delete method similar, extract duplications method</technical_language>

Target:
protected Single<Boolean> put(@NonNull final Uri uri, @NonNull final U item) { checkNotNull(item); checkNotNull(uri); return createModifyingOperation(index -> CoreValuePut.create(index, uri, item)); }
Source:
<code>AdminEmailAttributes() { <START> this.createDate = Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP; <END> this.emailId = Const.ParamsNames.ADMIN_EMAIL_ID; this.isInTrashBin = false; }</code><technical_language>'this' keyword is redundant</technical_language>

Target:
AdminEmailAttributes() { createDate = Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP; emailId = Const.ParamsNames.ADMIN_EMAIL_ID; }
Source:
<code>protected void executeCommand() { StorageDomainDR storageDomainDR = storageDomainDRDao.get(getParameters().getStorageDomainId(), getParameters().getGeoRepSessionId()); if (storageDomainDR == null) { storageDomainDR = new StorageDomainDR(); storageDomainDR.setStorageDomainId(getParameters().getStorageDomainId()); storageDomainDR.setGeoRepSessionId(getParameters().getGeoRepSessionId()); <START> } else { <END> if (storageDomainDR.getJobId() != null) { schedulerUtil.deleteJob(storageDomainDR.getJobId()); } } if (getParameters().getSchedule().getFrequency() != StorageSyncSchedule.Frequency.NONE) { String jobId = schedulerUtil.scheduleACronJob(new GlusterStorageDomainDRSyncJob(), "syncData", new Class[] { String.class, String.class }, new Object[] { getParameters().getStorageDomainId().toString(), getParameters().getGeoRepSessionId().toString() }, getParameters().getSchedule().toCronExpression()); storageDomainDR.setScheduleCronExpression(getParameters().getSchedule().toCronExpression()); storageDomainDR.setJobId(jobId); storageDomainDRDao.saveOrUpdate(storageDomainDR); } else { storageDomainDRDao.remove(storageDomainDR.getStorageDomainId(), storageDomainDR.getGeoRepSessionId()); } setSucceeded(true); }</code><technical_language>else if (storageDomainDR.getJobId() != null) {</technical_language>

Target:
protected void executeCommand() { StorageDomainDR storageDomainDR = storageDomainDRDao.get(getParameters().getStorageDomainId(), getParameters().getGeoRepSessionId()); if (storageDomainDR == null) { storageDomainDR = new StorageDomainDR(); storageDomainDR.setStorageDomainId(getParameters().getStorageDomainId()); storageDomainDR.setGeoRepSessionId(getParameters().getGeoRepSessionId()); } else if (storageDomainDR.getJobId() != null) { schedulerUtil.deleteJob(storageDomainDR.getJobId()); } if (getParameters().getSchedule().getFrequency() != StorageSyncSchedule.Frequency.NONE) { String jobId = schedulerUtil.scheduleACronJob(new GlusterStorageDomainDRSyncJob(), "syncData", new Class[] { String.class, String.class }, new Object[] { getParameters().getStorageDomainId().toString(), getParameters().getGeoRepSessionId().toString() }, getParameters().getSchedule().toCronExpression()); storageDomainDR.setScheduleCronExpression(getParameters().getSchedule().toCronExpression()); storageDomainDR.setJobId(jobId); storageDomainDRDao.saveOrUpdate(storageDomainDR); } else { storageDomainDRDao.remove(storageDomainDR.getStorageDomainId(), storageDomainDR.getGeoRepSessionId()); } setSucceeded(true); }
Source:
<code>public ImmutableAttributeSet generate(@NonNull final GeneratedComponentRequest request) { <START> final PP_ComponentGenerator generator = componentRepository.getByProductId(request.getProductId()); <END> if (generator == null) { throw new AdempiereException("No Component Generator for product " + request.getProductId()); } final IComponentGenerator generatorClass = javaClassBL.newInstance(generator.getJavaClassId()); return generatorClass.generate(request.getQty(), generator.getParams(), request.getAttributes()); }</code><technical_language>avoid throwing exception caller product a generator not. return ImmutableAttributeSet.EMPTY</technical_language>

Target:
public ImmutableAttributeSet generate(@NonNull final GeneratedComponentRequest request) { final ComponentGenerator generator = componentRepository.getByProductId(request.getProductId()).orElseThrow(() -> new AdempiereException("No Component Generator for product " + request.getProductId())); final IComponentGenerator generatorClass = javaClassBL.newInstance(generator.getJavaClassId()); return generatorClass.generate(request.getQty(), request.getAttributes(), generator.getParams()); }
Source:
<code>public void connect(String exchangeName, String routeKey) throws IOException { connection = factory.newConnection(); channel = connection.createChannel(); this.exchangeName = exchangeName; this.routeKey = routeKey; try { channel.exchangeDeclarePassive(exchangeName); } catch (IOException e) { if (!channel.isOpen()) { channel = connection.createChannel(); } <START> channel.exchangeDeclare(exchangeName, "direct"); <END> } try { channel.queueDeclarePassive(routeKey); } catch (IOException e) { channel.queueDeclare(routeKey, false, false, false, null); } channel.queueBind(routeKey, exchangeName, routeKey); }</code><technical_language>catch exception well</technical_language>

Target:
public void connect(String exchangeName, String routeKey) throws IOException { connection = factory.newConnection(); channel = connection.createChannel(); this.routeKey = routeKey; try { channel.exchangeDeclarePassive(exchangeName); } catch (IOException e) { if (!channel.isOpen()) { channel = connection.createChannel(); } channel.exchangeDeclare(exchangeName, "direct"); } try { channel.queueDeclarePassive(routeKey); } catch (IOException e) { if (!channel.isOpen()) { channel = connection.createChannel(); } channel.queueDeclare(routeKey, false, false, false, null); } channel.queueBind(routeKey, exchangeName, routeKey); }
Source:
<code>public void setUp() throws URISyntaxException { tracer = DistributedTracer.builder().build(); bus = new GuavaEventBus(); clientFactory = HttpClient.Factory.createDefault(); class Handler extends Session implements HttpHandler { private Handler(Capabilities capabilities) { super(new SessionId(UUID.randomUUID()), uri, capabilities); } @Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { return new HttpResponse(); } } <START> ImmutableCapabilities caps = new ImmutableCapabilities("browserName", "cheese"); <END> uri = new URI("http://localhost:1234"); local = LocalNode.builder(tracer, bus, clientFactory, uri) .add(caps, new TestSessionFactory((id, c) -> new Handler(c))) .maximumConcurrentSessions(2) .build(); }</code><technical_language>Prefer "the general interface class captures intent properly" left hand side (which is a long of Capabilities ;) )</technical_language>

Target:
public void setUp() throws URISyntaxException { tracer = DistributedTracer.builder().build(); bus = new GuavaEventBus(); clientFactory = HttpClient.Factory.createDefault(); class Handler extends Session implements HttpHandler { private Handler(Capabilities capabilities) { super(new SessionId(UUID.randomUUID()), uri, capabilities); } @Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { return new HttpResponse(); } } Capabilities caps = new ImmutableCapabilities("browserName", "cheese"); uri = new URI("http://localhost:1234"); local = LocalNode.builder(tracer, bus, clientFactory, uri) .add(caps, new TestSessionFactory((id, c) -> new Handler(c))) .maximumConcurrentSessions(2) .build(); }
Source:
<code>protected StringReader sanitizeXmlDocument(DefaultHandler handler, InputStream inputStream) throws IOException { if (log.isDebugEnabled()) { log.debug("Sanitizing XML document destined for handler " + handler.getClass()); } try { StringBuilder listingDocBuffer = new StringBuilder(); BufferedReader br = new BufferedReader( new InputStreamReader(inputStream, Constants.DEFAULT_ENCODING)); char[] buf = new char[8192]; int read = -1; while ((read = br.read(buf)) != -1) { listingDocBuffer.append(buf, 0, read); } <START> br.close(); <END> String listingDoc = pattern.matcher(listingDocBuffer).replaceAll("&#013;"); return new StringReader(listingDoc); } catch (IOException e) { throw e; } catch (Throwable t) { try { inputStream.close(); } catch (IOException e) { if (log.isErrorEnabled()) { log.error("Unable to close response InputStream after failure sanitizing XML document", e); } } throw new AmazonClientException("Failed to sanitize XML document destined for handler " + handler.getClass(), t); } }</code><technical_language>br.close() in a finally clause, I</technical_language>

Target:
protected StringReader sanitizeXmlDocument(DefaultHandler handler, InputStream inputStream) throws IOException { if (log.isDebugEnabled()) { log.debug("Sanitizing XML document destined for handler " + handler.getClass()); } BufferedReader br = null; try { StringBuilder listingDocBuffer = new StringBuilder(); char[] buf = new char[8192]; int read = -1; br = new BufferedReader( new InputStreamReader(inputStream, Constants.DEFAULT_ENCODING)); while ((read = br.read(buf)) != -1) { listingDocBuffer.append(buf, 0, read); } br.close(); String listingDoc = pattern.matcher(listingDocBuffer).replaceAll("&#013;"); return new StringReader(listingDoc); } catch (IOException e) { throw e; } catch (Throwable t) { try { inputStream.close(); } catch (IOException e) { if (log.isErrorEnabled()) { log.error("Unable to close response InputStream after failure sanitizing XML document", e); } } throw new AmazonClientException("Failed to sanitize XML document destined for handler " + handler.getClass(), t); } finally { IOUtils.closeQuietly(br, log); } }
Source:
<code>public static void addFileHandler(String fileName) { try { FileHandler fh = new FileHandler(fileName); <START> fh.setFormatter(new SimpleFormatter()); <END> getOvirtLogger().addHandler(fh); } catch (SecurityException | IOException ex) { throw new IllegalArgumentException( String.format("Error accessing log file '%s': '%s'", fileName, ex.getMessage()), ex); } }</code><technical_language>I formatter out of logging properties do need declare here</technical_language>

Target:
public static void addFileHandler(String fileName) { try { FileHandler fh = new FileHandler(fileName); fh.setFormatter(new SimpleFormatter()); OVIRT_LOGGER.addHandler(fh); } catch (SecurityException | IOException ex) { throw new IllegalArgumentException( String.format("Error accessing log file '%s': '%s'", fileName, ex.getMessage()), ex); } }
Source:
<code>private static void cleanOldWorkDir() { Path oldWorkDir = Paths.get(PathManager.getConfigPath()).resolve("sonarlint").resolve("work"); <START> if (!oldWorkDir.toFile().isDirectory()) { <END> return; } try (Stream<Path> stream = Files.list(oldWorkDir)) { stream.filter(f -> f.getFileName().toString().startsWith(".sonartmp_")) .forEach(FileUtils::deleteRecursively); } catch (IOException e) { } }</code><technical_language>of SQ issue right? performance issue affect JDK 8 (and latest versions). performance is issue calling this a lot of times. I previous syntax, is more future proof me</technical_language>

Target:
private static void cleanOldWorkDir() { Path oldWorkDir = Paths.get(PathManager.getConfigPath()).resolve("sonarlint").resolve("work"); if (!Files.isDirectory(oldWorkDir)) { return; } try (Stream<Path> stream = Files.list(oldWorkDir)) { stream.filter(f -> f.getFileName().toString().startsWith(".sonartmp_")) .forEach(FileUtils::deleteRecursively); } catch (IOException e) { } }
Source:
<code>private void initSiteSettings() { mSiteSettings = SiteSettingsInterface.getInterface(getActivity(), getSelectedSite(), this); <START> mSiteSettings.init(true); <END> }</code><technical_language>mSiteSettings.init produce a NullPointerException. want add a null check statement safe</technical_language>

Target:
private void initSiteSettings() { mSiteSettings = SiteSettingsInterface.getInterface(getActivity(), getSelectedSite(), this); if (mSiteSettings != null) { mSiteSettings.init(true); } }
Source:
<code>@Override public BufferedImage toImage() { <START> BufferedImage image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); <END> int[] data = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { data[j + (i*128)] = 0; } } return image; }</code><technical_language>this cached</technical_language>

Target:
public BufferedImage toImage() { BufferedImage image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); int[] data = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { data[j + (i*128)] = getPixel(j, i).getColor().getRgb(); } } return image; }
Source:
<code>public InventoryConfig() { <START> configPath = Paths.get(System.getProperty("jboss.server.config.dir"), "hawkular"); <END> ispnReindex = Boolean.parseBoolean(System.getProperty(ISPN_REINDEX, ISPN_REINDEX_DEFAULT)); dataPath = Paths.get(System.getProperty("jboss.server.data.dir")); scrapeLocation = new File(dataPath.toFile(), "prometheus"); scrapeLocation.mkdirs(); }</code><technical_language>while mkdirs in this method, mkdirs() this hawkular directory safe</technical_language>

Target:
public InventoryConfig() { ispnReindex = Boolean.parseBoolean(System.getProperty(ISPN_REINDEX, ISPN_REINDEX_DEFAULT)); configPath = Paths.get(System.getProperty("jboss.server.config.dir"), "hawkular"); configPath.toFile().mkdirs(); dataPath = Paths.get(System.getProperty("jboss.server.data.dir")); scrapeLocation = new File(dataPath.toFile(), "prometheus"); scrapeLocation.mkdirs(); }
Source:
<code>public void factoryTestBadJson() throws Exception { Properties properties = new Properties(); JSONObject jsonObject = new JSONObject().put("POST", UPLOAD_ENDPOINT); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); try { new AmbryUrlSigningServiceFactory(new VerifiableProperties(properties), new MetricRegistry()).getUrlSigningService(); fail("Expected exception"); } catch (Exception ex) { <START> assertTrue(ex instanceof IllegalStateException); <END> } jsonObject = new JSONObject().put("GET", DOWNLOAD_ENDPOINT); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); try { new AmbryUrlSigningServiceFactory(new VerifiableProperties(properties), new MetricRegistry()).getUrlSigningService(); fail("Expected exception"); } catch (Exception ex) { assertTrue(ex instanceof IllegalStateException); } properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, "[Garbage string &%#123"); try { new AmbryUrlSigningServiceFactory(new VerifiableProperties(properties), new MetricRegistry()).getUrlSigningService(); fail("Expected exception"); } catch (Exception ex) { assertTrue(ex instanceof IllegalStateException); } }</code><technical_language>instead catch IllegalStatException try { ... } catch (IllegalStateException e) { // expected. do } way, if is other IllegalStateException, get a stack trace failure</technical_language>

Target:
public void factoryTestBadJson() { Properties properties = new Properties(); JSONObject jsonObject = new JSONObject().put("POST", UPLOAD_ENDPOINT); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); try { new AmbryUrlSigningServiceFactory(new VerifiableProperties(properties), new MetricRegistry()).getUrlSigningService(); fail("Expected exception"); } catch (IllegalStateException ex) { } jsonObject = new JSONObject().put("GET", DOWNLOAD_ENDPOINT); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); try { new AmbryUrlSigningServiceFactory(new VerifiableProperties(properties), new MetricRegistry()).getUrlSigningService(); fail("Expected exception"); } catch (IllegalStateException ex) { } properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, "[Garbage string &%#123"); try { new AmbryUrlSigningServiceFactory(new VerifiableProperties(properties), new MetricRegistry()).getUrlSigningService(); fail("Expected exception"); } catch (IllegalStateException ex) { } }
Source:
<code>public int store(final String credsStore, final DockerCredentialHelperAuth auth) throws IOException, InterruptedException { final Process process = exec("store", credsStore); try (final Writer outStreamWriter = new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8)) { try (final BufferedWriter writer = new BufferedWriter(outStreamWriter)) { <START> writer.write(mapper.writeValueAsString(auth) + "\n"); <END> writer.flush(); } } return process.waitFor(); }</code><technical_language>I notice this in prior version of code, I if of "\n" strings instead System.lineSeparator() avoid assuming code runs *nux systems</technical_language>

Target:
public int store(final String credsStore, final DockerCredentialHelperAuth auth) throws IOException, InterruptedException { final Process process = exec("store", credsStore); try (final Writer outStreamWriter = new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8)) { try (final BufferedWriter writer = new BufferedWriter(outStreamWriter)) { writer.write(mapper.writeValueAsString(auth)); writer.newLine(); writer.flush(); } } return process.waitFor(); }