auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void checkAttributeValue(PerunSessionImpl sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { List<String> emails; Object value = attribute.getValue(); if (value == null) { <START> throw new WrongAttributeValueException(attribute, resource, group, "can't be null."); <END> } else if (!(value instanceof List)) { throw new WrongAttributeValueException(attribute, resource, group, "is of type " + value.getClass() + ", but should be ArrayList"); } else { emails = (List<String>) value; } for (String email : emails) { Matcher emailMatcher = emailPattern.matcher(email); if (!emailMatcher.matches()) throw new WrongAttributeValueException(attribute, resource, group, "Email " + email + " is not in correct form."); } AttributesManagerBl am = sess.getPerunBl().getAttributesManagerBl(); try { Object adName = am.getAttribute(sess, resource, group, ADNAME_ATTRIBUTE).getValue(); if (adName != null && emails.isEmpty()) { throw new WrongAttributeValueException(attribute, resource, group, "at least one email must be defined"); } } catch (AttributeNotExistsException | GroupResourceMismatchException e) { throw new InternalErrorException(e.getMessage(), e); } if (hasDuplicate(emails)) { throw new WrongAttributeValueException(attribute, resource, group, "duplicate values"); } }</code><technical_language>this checked check adName existence ? do @licehammer ? sure, is desired workflow adName - manual changes fixes, etc. translate empty list null storing (not retrieving), get "empty list" line 73</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { List<String> emails; Object value = attribute.getValue(); if (value == null) { emails = Collections.emptyList(); } else if (value instanceof List) { emails = (List<String>) value; } else { throw new WrongAttributeValueException(attribute, resource, group, "is of type " + value.getClass() + ", but should be ArrayList"); } for (String email : emails) { Matcher emailMatcher = emailPattern.matcher(email); if (!emailMatcher.matches()) throw new WrongAttributeValueException(attribute, resource, group, "Email " + email + " is not in correct form."); } AttributesManagerBl am = sess.getPerunBl().getAttributesManagerBl(); try { Object adName = am.getAttribute(sess, resource, group, ADNAME_ATTRIBUTE).getValue(); if (adName != null && emails.isEmpty()) { throw new WrongAttributeValueException(attribute, resource, group, "at least one email must be defined"); } } catch (AttributeNotExistsException | GroupResourceMismatchException e) { throw new InternalErrorException(e.getMessage(), e); } if (hasDuplicate(emails)) { throw new WrongAttributeValueException(attribute, resource, group, "duplicate values"); } }
Source:
<code>private String getSourceHostForContainer(ContainerPlacementRequestMessage requestMessage) { String sourceHost = null; String processorId = requestMessage.getProcessorId(); if (samzaApplicationState.runningProcessors.containsKey(processorId)) { SamzaResource currentResource = samzaApplicationState.runningProcessors.get(processorId); LOG.info("Processor ID: matched a running container with containerId ID: is running on host: for ContainerPlacement action: {}", processorId, currentResource.getContainerId(), currentResource.getHost(), requestMessage); sourceHost = currentResource.getHost(); } else { <START> sourceHost = Optional.ofNullable(localityManager.readLocality().getHostLocality(processorId)) <END> .map(HostLocality::host) .orElse(null); LOG.info("Processor ID: is not running and was last seen on host: for ContainerPlacement action: {}", processorId, sourceHost, requestMessage); } return sourceHost; }</code><technical_language>localityManager readLocality results null</technical_language>

Target:
private String getSourceHostForContainer(ContainerPlacementRequestMessage requestMessage) { String sourceHost = null; String processorId = requestMessage.getProcessorId(); if (samzaApplicationState.runningProcessors.containsKey(processorId)) { SamzaResource currentResource = samzaApplicationState.runningProcessors.get(processorId); LOG.info("Processor ID: matched a running container with containerId ID: is running on host: for ContainerPlacement action: {}", processorId, currentResource.getContainerId(), currentResource.getHost(), requestMessage); sourceHost = currentResource.getHost(); } else { sourceHost = Optional.ofNullable(localityManager.readLocality().getProcessorLocality(processorId)) .map(ProcessorLocality::host) .orElse(null); LOG.info("Processor ID: is not running and was last seen on host: for ContainerPlacement action: {}", processorId, sourceHost, requestMessage); } return sourceHost; }
Source:
<code>private void onCloneTemplate() { final UnitVmModel model = (UnitVmModel) getWindow(); NewTemplateVmModelBehavior behavior = (NewTemplateVmModelBehavior) model.getBehavior(); Snapshot snapshot = getSelectedItem(); if (snapshot == null) { cancel(); return; } final VM vm = behavior.getVm(); if (!model.validate(false)) { model.setIsValid(false); } else if (model.getIsSubTemplate().getEntity()) { postNameUniqueCheck(vm); } else { String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery<>( isNameUnique -> { if (!isNameUnique) { model.getInvalidityReasons().clear(); model.getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); model.getName().setIsValid(false); model.setIsValid(false); model.fireValidationCompleteEvent(); } else { postNameUniqueCheck(vm); } }), name, <START> null); <END> } }</code><technical_language>cleaner create a new overload of this method, 'datacenterId' parameter</technical_language>

Target:
private void onCloneTemplate() { final UnitVmModel model = (UnitVmModel) getWindow(); NewTemplateVmModelBehavior behavior = (NewTemplateVmModelBehavior) model.getBehavior(); Snapshot snapshot = getSelectedItem(); if (snapshot == null) { cancel(); return; } final VM vm = behavior.getVm(); if (!model.validate(false)) { model.setIsValid(false); } else if (model.getIsSubTemplate().getEntity()) { postNameUniqueCheck(vm); } else { String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery<>( isNameUnique -> { if (!isNameUnique) { model.getInvalidityReasons().clear(); model.getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); model.getName().setIsValid(false); model.setIsValid(false); model.fireValidationCompleteEvent(); } else { postNameUniqueCheck(vm); } }), name, model.getSelectedDataCenter().getId()); } }
Source:
<code>private void getDeprecatedContainers() { deprecatedContainers.clear(); <START> if (accountService != null) { <END> Set<Container> containers = accountService.getDeprecatedContainers(config.storeContainerDeletionRetentionDays); deprecatedContainers.addAll(containers.stream() .map(container -> new Pair<>(container.getParentAccountId(), container.getId())) .collect(Collectors.toSet())); } }</code><technical_language>This change add IMO. I move retention part original loop</technical_language>

Target:
private void getDeprecatedContainers() { deprecatedContainers.clear(); if (accountService != null) { Set<Container> containers = AccountUtils.getDeprecatedContainers(accountService, config.storeContainerDeletionRetentionDays); deprecatedContainers.addAll(containers.stream() .map(container -> new Pair<>(container.getParentAccountId(), container.getId())) .collect(Collectors.toSet())); } }
Source:
<code>public CombinedTypeSolver(TypeSolver... elements) { <START> this(ExceptionFilters.IGNORE_ALL, elements); <END> }</code><technical_language>IGNORE_ALL default</technical_language>

Target:
public CombinedTypeSolver(TypeSolver... elements) { this(ExceptionHandlers.IGNORE_NONE, elements); }
Source:
<code><START> public ElideResponse(int responseCode, String body, Throwable failureReason) { <END> this.responseCode = responseCode; this.body = body; this.failureReason = failureReason; }</code><technical_language>I original public constructor deprecate it</technical_language>

Target:
public ElideResponse(int responseCode, String body, Throwable failureReason) { this.responseCode = responseCode; this.body = body; this.failureReason = Optional.ofNullable(failureReason); }
Source:
<code>private Guid getStoragePoolId(GetVmTemplateParameters params) { <START> return params.getStoragePoolId() != null ? params.getStoragePoolId() : params.getVdsGroupId() != null ? DbFacade.getInstance().getVdsGroupDao().get(params.getVdsGroupId()).getStoragePoolId() : null; <END> }</code><technical_language>also, DbFacade.getInstance().getVdsGroupDao().get(params.getVdsGroupId()) return null</technical_language>

Target:
private Guid getStoragePoolId(GetVmTemplateParameters params) { Guid result = null; if (params.getDataCenterId() != null) { result = params.getDataCenterId(); } else if (params.getClusterId() != null) { VDSGroup vdsGroup = DbFacade.getInstance().getVdsGroupDao().get(params.getClusterId()); if (vdsGroup != null) { result = vdsGroup.getStoragePoolId(); } } return result; }
Source:
<code><START> public JSONArray coordinatesToJSONArray() throws JSONException{ <END> JSONArray points = new JSONArray(); for (ParseGeoPoint coordinate : coordinates) { JSONArray point = new JSONArray(); point.put(coordinate.getLatitude()); point.put(coordinate.getLongitude()); points.put(point); } return points; }</code><technical_language>this package protected? exposing JSONs in SDK</technical_language>

Target:
protected JSONArray coordinatesToJSONArray() throws JSONException{ JSONArray points = new JSONArray(); for (ParseGeoPoint coordinate : coordinates) { JSONArray point = new JSONArray(); point.put(coordinate.getLatitude()); point.put(coordinate.getLongitude()); points.put(point); } return points; }
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.acquireControllerLock(); <START> final ModelNode model = Resource.Tools.readModel(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, true)); <END> final int suspendTimeout = HOST_SUSPEND_TIMEOUT.resolveModelAttribute(context, operation).asInt(); final BlockingTimeout blockingTimeout = BlockingTimeout.Factory.getProxyBlockingTimeout(context); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.getServiceRegistry(true); Set<String> servers = getServersForHost(model); final List<ModelNode> errorResponses = serverInventory.suspendServers(servers, suspendTimeout, blockingTimeout); if (!errorResponses.isEmpty()) { context.getFailureDescription().set(errorResponses); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }, OperationContext.Stage.RUNTIME); }</code><technical_language>This done in this file more efficient read entire model, huge in a domain. this done 2 reads, a non-recursive read of root get host name (which recursing), a read of server config resources host</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.acquireControllerLock(); final Resource hostResource = context.readResource(PathAddress.EMPTY_ADDRESS); final int suspendTimeout = HOST_SUSPEND_TIMEOUT.resolveModelAttribute(context, operation).asInt(); final BlockingTimeout blockingTimeout = BlockingTimeout.Factory.getProxyBlockingTimeout(context); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.getServiceRegistry(true); Set<String> servers = getServersForHost(hostResource); final List<ModelNode> errorResponses = serverInventory.suspendServers(servers, suspendTimeout, blockingTimeout); if (!errorResponses.isEmpty()) { context.getFailureDescription().set(errorResponses); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }, OperationContext.Stage.RUNTIME); }
Source:
<code>public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Span.Builder spanBuilder = tracer.spanBuilder(METHOD_NAME); END final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) <START> .addData(HOST_NAME_KEY, HOSTNAME_VALUE).addData(SPAN_BUILDER_KEY, spanBuilder); <END> final Context updatedContext = openTelemetryTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); END assertSpanWithExplicitParent(updatedContext, parentSpanId); final ReadableSpan recordEventsSpan = (ReadableSpan) updatedContext.getData(PARENT_SPAN_KEY).get(); assertEquals(Span.Kind.PRODUCER, recordEventsSpan.toSpanData().getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes(); assertEquals(attributeMap.get(COMPONENT), AttributeValue.stringAttributeValue(COMPONENT_VALUE)); assertEquals(attributeMap.get(MESSAGE_BUS_DESTINATION), AttributeValue.stringAttributeValue(ENTITY_PATH_VALUE)); assertEquals(attributeMap.get(PEER_ENDPOINT), AttributeValue.stringAttributeValue(HOSTNAME_VALUE)); }</code><technical_language>this is odd indent level</technical_language>

Target:
public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Span.Builder spanBuilder = tracer.spanBuilder(METHOD_NAME); END final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) .addData(HOST_NAME_KEY, HOSTNAME_VALUE).addData(SPAN_BUILDER_KEY, spanBuilder); final Context updatedContext = openTelemetryTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); END assertSpanWithExplicitParent(updatedContext, parentSpanId); final ReadableSpan recordEventsSpan = (ReadableSpan) updatedContext.getData(PARENT_SPAN_KEY).get(); assertEquals(Span.Kind.PRODUCER, recordEventsSpan.toSpanData().getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes(); verifySpanAttributes(attributeMap); }
Source:
<code>public DonorDeferral getLastDonorDeferral(Long donorId) { List<DonorDeferral> deferrals = getDonorDeferrals(donorId); if (deferrals == null || deferrals.isEmpty()) { return null; } DonorDeferral lastDeferral = deferrals.get(0); <START> Date lastDeferredUntil = lastDeferral.getDeferredUntil(); <END> for (DonorDeferral deferral : deferrals) { if (deferral.getDeferredUntil() != null && deferral.getDeferredUntil().after(lastDeferredUntil)) { lastDeferral = deferral; } } return lastDeferral; }</code><technical_language>Line 402 (initialisation of lastDeferredUntil) needs loop changed time lastDeferral is updated</technical_language>

Target:
public DonorDeferral getLastDonorDeferral(Long donorId) { List<DonorDeferral> deferrals = getDonorDeferrals(donorId); if (deferrals == null || deferrals.isEmpty()) { return null; } DonorDeferral lastDeferral = deferrals.get(0); Date lastDeferredUntil = lastDeferral.getDeferredUntil(); for (DonorDeferral deferral : deferrals) { if (deferral.getDeferredUntil() != null && deferral.getDeferredUntil().after(lastDeferredUntil)) { lastDeferral = deferral; lastDeferredUntil = lastDeferral.getDeferredUntil(); } } return lastDeferral; }
Source:
<code>@Override public boolean isSampled(long ignoredTraceId) { long now = System.nanoTime(); long updateAt = nextUpdate.get(); if (now > updateAt || (updateAt > 0 && now < 0)) { <START> if (nextUpdate.compareAndSet(updateAt, getNextUpdateValue(updateAt))) { <END> usage.set(1); return true; } } return usage.getAndIncrement() < tracesPerSecond; }</code><technical_language>pass this function eliminate a call some cost it</technical_language>

Target:
@Override public boolean isSampled(long ignoredTraceId) { long now = System.nanoTime(); long updateAt = nextReset.get(); long nanosUntilReset = -(now - updateAt); boolean shouldReset = nanosUntilReset <= 0; if (shouldReset) { if (nextReset.compareAndSet(updateAt, updateAt + NANOS_PER_SECOND)) { usage.set(0); } } int max = maxFunction.max(shouldReset ? 0 : nanosUntilReset); int prev, next; do { prev = usage.get(); next = prev + 1; if (next > max) return false; } while (!usage.compareAndSet(prev, next)); return true; }
Source:
<code>private void preMerge() throws MergeException, OrmException, InvalidNameException { openBranch(); validateChangeList(); mergeTip = branchTip; <START> <END> final List<MergeStrategySection> refStrategies = new ArrayList<MergeStrategySection>(projectCache.get( destProject.getNameKey()).getLocalMergeStrategySections()); refStrategies.addAll(projectCache.get(destProject.getNameKey()) .getInheritedMergeStrategySections()); final List<MergeStrategySection> refStrategiesMatchers = extractNonMatchersRefStrategies(refStrategies, destBranch.get()); if (refStrategiesMatchers.size() == 0) { throw new MergeException("No Reference Pattern matches : " + destBranch.get()); } else { Collections.sort(refStrategies, new Comparator<MergeStrategySection>() { @Override public int compare(MergeStrategySection a, MergeStrategySection b) { MostSpecificComparator regexComparator = new MostSpecificComparator(destBranch.get()); return regexComparator.compare(a.getName(), b.getName()); } }); final MergeStrategySection mostSpecific = refStrategies.get(0); MergeStrategySection.SubmitType submitType = mostSpecific.getSubmitType(); switch (submitType) { case CHERRY_PICK: cherryPickChanges(); break; case FAST_FORWARD_ONLY: case MERGE_ALWAYS: case MERGE_IF_NECESSARY: default: reduceToMinimalMerge(); mergeTopics(submitType); markCleanMerges(); break; } } }</code><technical_language>feels wrong this sort of checking in this class, is huge already. I suspect passing in merge strategy factory cleaner</technical_language>

Target:
private void preMerge() throws MergeException, OrmException, InvalidNameException { openBranch(); validateChangeList(); mergeTip = branchTip; try { final MergeStrategySection mostSpecific = projectCache.get(destProject.getNameKey()) .getMostSpecificMergeStrategy(destBranch.get()); switch (mostSpecific.getSubmitType()) { case CHERRY_PICK: cherryPickChanges(mostSpecific.isUseContentMerge()); break; case FAST_FORWARD_ONLY: case MERGE_ALWAYS: case MERGE_IF_NECESSARY: default: reduceToMinimalMerge(); mergeTopics(mostSpecific.getSubmitType(), mostSpecific.isUseContentMerge()); markCleanMerges(); break; } } catch (NoSuchRefPatternMatches e) { throw new MergeException(e.getMessage()); } }
Source:
<code>public void deleteInvalidPath() throws Exception { <START> if (IS_WIN) { return; } <END> final int NB_QUEUES = 5; Name fooLog = Name.ofUrn("test/foo"); ChronicleLogManager manager = (ChronicleLogManager) createManager(); assertTrue(manager.createIfNotExists(fooLog, NB_QUEUES)); String basePath = manager.getBasePath(); assertTrue(manager.delete(fooLog)); assertTrue(manager.createIfNotExists(fooLog, NB_QUEUES)); Files.createFile(Paths.get(basePath, fooLog.getId(), "foo.txt")); try { manager.delete(fooLog); fail("Cannot delete a Log with external data"); } catch (IllegalArgumentException e) { } }</code><technical_language>Please assumeFalse(SystemUtils.IS_OS_WINDOWS) instead</technical_language>

Target:
public void deleteInvalidPath() throws Exception { org.junit.Assume.assumeFalse(IS_WIN); final int NB_QUEUES = 5; Name fooLog = Name.ofUrn("test/foo"); ChronicleLogManager manager = (ChronicleLogManager) createManager(); assertTrue(manager.createIfNotExists(fooLog, NB_QUEUES)); String basePath = manager.getBasePath(); assertTrue(manager.delete(fooLog)); assertTrue(manager.createIfNotExists(fooLog, NB_QUEUES)); Files.createFile(Paths.get(basePath, fooLog.getId(), "foo.txt")); try { manager.delete(fooLog); fail("Cannot delete a Log with external data"); } catch (IllegalArgumentException e) { } }
Source:
<code>private boolean isAnyProjectConnected() { Project[] openProjects = projectManager.getOpenProjects(); for (Project p : openProjects) { SonarLintProjectSettings projectSettings = SonarLintUtils.get(p, SonarLintProjectSettings.class); if (projectSettings.isBindingEnabled()) { return true; } } <START> return false; <END> }</code><technical_language>easier read if rewritten a stream</technical_language>

Target:
private boolean isAnyProjectConnected() { Project[] openProjects = projectManager.getOpenProjects(); return Arrays.stream(openProjects).anyMatch(p -> SonarLintUtils.get(p, SonarLintProjectSettings.class).isBindingEnabled()); }
Source:
<code>private ExpressionNode literalObject(final MethodBuilder builder) throws ProgramDefinitionError { <START> String implicitClassSignature = "objL@" + lexer.getCurrentLineNumber() + "@" <END> + lexer.getCurrentColumn(); SourceSection source = getSource(getCoordinate()); MixinBuilder implicitClassBuilder = new MixinBuilder(builder, AccessModifier.PUBLIC, symbolFor(implicitClassSignature), source, structuralProbe); MethodBuilder primaryFactory = implicitClassBuilder.getPrimaryFactoryMethodBuilder(); primaryFactory.addArgument("self", getEmptySource()); primaryFactory.setSignature(Symbols.NEW); implicitClassBuilder.setupInitializerBasedOnPrimaryFactory(source); inheritanceListAndOrBody(implicitClassBuilder); MixinDefinition mixinDef = implicitClassBuilder.assemble(source); ObjectLiteralNode objectLiteral = new ObjectLiteralNode(mixinDef, builder.getSelfRead(source), source); return SNodeFactory.createMessageSend(symbolFor("new"), new ExpressionNode[] {objectLiteral}, false, source, source); }</code><technical_language>Please do :)</technical_language>

Target:
private ExpressionNode literalObject(final MethodBuilder builder) throws ProgramDefinitionError { SourceSection source = getSource(getCoordinate()); SSymbol signature = symbolFor("objL@" + lexer.getCurrentLineNumber() + "@" + lexer.getCurrentColumn()); MixinBuilder classBuilder = new MixinBuilder(builder, AccessModifier.PUBLIC, signature, source, structuralProbe, language); MethodBuilder primaryFactory = classBuilder.getPrimaryFactoryMethodBuilder(); primaryFactory.addArgument("self", getEmptySource()); primaryFactory.setSignature(Symbols.NEW); classBuilder.setupInitializerBasedOnPrimaryFactory(source); inheritanceListAndOrBody(classBuilder); MixinDefinition mixinDef = classBuilder.assemble(source); ExpressionNode outerRead = builder.getSelfRead(source); ExpressionNode newMessage = createMessageSend(symbolFor("new"), new ExpressionNode[] {builder.getSelfRead(source)}, false, source, source, language); return new ObjectLiteralNode(mixinDef, outerRead, newMessage, source); }
Source:
<code><START> public String[] listPartitionNames(final String topicId) throws NakadiException { <END> return listPartitions(topicId).stream().map(p -> p.getPartitionId()).toArray(String[]::new); }</code><technical_language>array</technical_language>

Target:
public List<String> listPartitionNames(final String topicId) throws NakadiException { return unmodifiableList(listPartitions(topicId).stream().map(p -> p.getPartitionId()).collect(toList())); }
Source:
<code>private void handleScanTimeout(ScanTimeoutException rte) throws IOException { logger.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); if (currentTimeoutBackoff == null) { currentTimeoutBackoff = <START> new TimeoutRetryBackOff(retryOptions.getMaxScanTimeoutRetries(), BackOff.ZERO_BACKOFF); <END> } currentErrorBackoff = null; backOffAndRetry(currentTimeoutBackoff, rte); }</code><technical_language>do need a BackOff.ZERO_BACKOFF / delegate</technical_language>

Target:
private void handleScanTimeout(ScanTimeoutException rte) throws IOException { logger.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); if (timeoutRetryCount == null) { timeoutRetryCount = new AtomicInteger(); } currentErrorBackoff = null; if (timeoutRetryCount.incrementAndGet() <= retryOptions.getMaxScanTimeoutRetries()) { reissueRequest(); } else { throw new BigtableRetriesExhaustedException( "Exhausted streaming retries after too many timeouts", rte); } }
Source:
<code>public CandidateDTO firstTypeToSecondType(CandidateEntity source) { Assert.notNull(source); CandidateDTO candidateDTO = CandidateDTO.builder() .id(source.getId()) .name(source.getName()) .email(source.getEmail()) .phone(source.getPhone()) .referer(source.getReferer()) .languageSkill(source.getLanguageSkill()) .description(source.getDescription()) .build(); Set<String> positions = new HashSet<>(); List<ApplicationDTO> applicationDTOs = applicationsService.getApplicationsByCandidateDTO(candidateDTO); for (ApplicationDTO applicationDTO : applicationDTOs) { <START> PositionDTO positionDTO = positionService.getPositionById(applicationDTO.getPositionId()); <END> positions.add(positionDTO.getName()); } candidateDTO.setPositions(positions); return candidateDTO; }</code><technical_language>collect PositionDTOs one, result in a lot of database operation. is eliminate unnecessary database selects if collect PositionDTOs in call. In JpaRepository is a method: List<T> findAll(Iterable< ID > var1);. In this situation perfect, refactor getPositionById method findAll</technical_language>

Target:
public CandidateDTO firstTypeToSecondType(CandidateEntity source) { Assert.notNull(source); CandidateDTO candidateDTO = CandidateDTO.builder() .id(source.getId()) .name(source.getName()) .email(source.getEmail()) .phone(source.getPhone()) .referer(source.getReferer()) .languageSkill(source.getLanguageSkill()) .description(source.getDescription()) .build(); Set<String> positions = new HashSet<>(); List<Long> positionIds = applicationsService.getApplicationsByCandidateDTO(candidateDTO).stream() .map(application -> application.getPositionId()) .distinct() .collect(Collectors.toList()); if (!positionIds.isEmpty()) { List<String> positionNames = positionService.getPositionsById(positionIds).stream() .map(position -> position.getName()) .collect(Collectors.toList()); positions.addAll(positionNames); } candidateDTO.setPositions(positions); return candidateDTO; }
Source:
<code>public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { EnvVars env = build.getEnvironment(listener); HgExe hg = new HgExe(findInstallation(getInstallation()), getCredentials(build.getParent(), env), launcher, workspaceToNode(workspace), listener, env); try { String tip = hg.tip(workspace2Repo(workspace, env), null); String rev = hg.tipNumber(workspace2Repo(workspace, env), null); <START> String branch = revisionType == RevisionType.TAG ? hg.branch(workspace2Repo(workspace, env), null) : null; <END> return tip != null && rev != null ? new MercurialTagAction(tip, rev, getSubdir(env), branch) : null; } finally { hg.close(); } }</code><technical_language>For future expansion of RevisionType this revisionType != RevisionType.BRANCH, for matter</technical_language>

Target:
public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { EnvVars env = build.getEnvironment(listener); HgExe hg = new HgExe(findInstallation(getInstallation()), getCredentials(build.getParent(), env), launcher, workspaceToNode(workspace), listener, env); try { String tip = hg.tip(workspace2Repo(workspace, env), null); String rev = hg.tipNumber(workspace2Repo(workspace, env), null); String branch = revisionType != RevisionType.BRANCH ? hg.branch(workspace2Repo(workspace, env), null) : null; return tip != null && rev != null ? new MercurialTagAction(tip, rev, getSubdir(env), branch) : null; } finally { hg.close(); } }
Source:
<code>public int hashCode() { <START> return Objects.hash(version, id, samFileHeader); <END> }</code><technical_language>aware if update version.hashCode build account this longer correct this compare version.equals</technical_language>

Target:
public int hashCode() { int result = Objects.hash(version, samFileHeader); result = 31 * result + Arrays.hashCode(id); return result; }
Source:
<code>public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation, TouchCalibration calibration) { if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION, "setTouchCalibrationForInputDevice()")) { throw new SecurityException("Requires SET_INPUT_CALIBRATION permission"); } if (inputDeviceDescriptor == null) { throw new IllegalArgumentException("inputDeviceDescriptor must not be null"); } if (calibration == null) { throw new IllegalArgumentException("calibration must not be null"); <START> } <END> synchronized (mDataStore) { try { if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation, calibration)) nativeReloadCalibration(mPtr); } finally { mDataStore.saveIfNeeded(); } } }</code><technical_language>check surface rotation is valid here</technical_language>

Target:
public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation, TouchCalibration calibration) { if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION, "setTouchCalibrationForInputDevice()")) { throw new SecurityException("Requires SET_INPUT_CALIBRATION permission"); } if (inputDeviceDescriptor == null) { throw new IllegalArgumentException("inputDeviceDescriptor must not be null"); } if (calibration == null) { throw new IllegalArgumentException("calibration must not be null"); } if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) { throw new IllegalArgumentException("surfaceRotation value out of bounds"); } synchronized (mDataStore) { try { if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation, calibration)) { nativeReloadCalibration(mPtr); } } finally { mDataStore.saveIfNeeded(); } } }
Source:
<code><START> public static void setURLHelperFactory(URLHelperFactory factory) { <END> urlHelperFactory = factory; }</code><technical_language>This throw if is null</technical_language>

Target:
public static void setURLHelperFactory(URLHelperFactory factory) { if(factory == null) { throw new NullPointerException("Null URLHelperFactory"); } urlHelperFactory = factory; }
Source:
<code>public org.apache.bookkeeper.client.api.LedgerEntry readLastEntry() throws InterruptedException, ExecutionException { long lastEntryId = getLastAddConfirmed(); if (lastEntryId < 0) { <START> return null; <END> } else { return readEntriesInternalAsync(lastEntryId, lastEntryId).get().getEntry(lastEntryId); } }</code><technical_language>throw NoSuchEntryException consistent asyncReadLastEntry</technical_language>

Target:
public LedgerEntry readLastEntry() throws InterruptedException, BKException { long lastEntryId = getLastAddConfirmed(); if (lastEntryId < 0) { throw new BKException.BKNoSuchEntryException(); } else { CompletableFuture<Enumeration<LedgerEntry>> result = new CompletableFuture<>(); asyncReadEntries(lastEntryId, lastEntryId, new SyncReadCallback(result), null); return SyncCallbackUtils.waitForResult(result).nextElement(); } }
Source:
<code>public Summary create() { if (quantiles != null && quantiles.length > 0) { for (double q : quantiles) { if (q < 0 || q > 1) { <START> throw new IllegalArgumentException("quantile value must be in interval [0, 1]"); <END> } } } for (String label: labelNames) { if (label.equals(QUANTILE_LABEL)) { throw new IllegalStateException("Summary cannot have a label named '" + QUANTILE_LABEL + "'."); } } return new Summary(this); }</code><technical_language>[ means in countries. 0<=x<=1</technical_language>

Target:
public Summary create() { if (quantiles != null && quantiles.length > 0) { for (double q : quantiles) { if (!isValidQuantile(q)) { throw new IllegalArgumentException("quantile value must be 0 <= q <= 1"); } } } for (String label: labelNames) { if (label.equals(QUANTILE_LABEL)) { throw new IllegalStateException("Summary cannot have a label named '" + QUANTILE_LABEL + "'."); } } dontInitializeNoLabelsChild = true; return new Summary(this); }
Source:
<code>private boolean hasSameThingType(Thing thing) { <START> return Objects.equal(this.getUID().getThingTypeUID(), thing.getThingTypeUID()); <END> }</code><technical_language>Note for Java 7 later: This method treated deprecated; Objects.equals(java.lang.Object, java.lang.Object) instead. plain Java. Side note: of arguments null? I doubt, using: this.getUID().getThingTypeUID().equals(thing.getThingTypeUID())</technical_language>

Target:
private boolean hasSameThingType(Thing thing) { return Objects.equals(this.getUID().getThingTypeUID(), thing.getThingTypeUID()); }
Source:
<code>public UndertowCorruptionHandlerService(UndertowService service, CorruptionHealthCheck healthCheck) { this.delegate = service; this.healthCheck = healthCheck; this.wrapper = handler -> exchange -> { if (healthCheck.isHealthy()) { handler.handleRequest(exchange); } else { exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE); <START> exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); <END> exchange.getResponseSender().send(Constants.CORRUPTION_MESSAGE); exchange.endExchange(); } }; }</code><technical_language>I this is needed if standardise internal frameworks</technical_language>

Target:
public UndertowCorruptionHandlerService(UndertowService service, CorruptionHealthCheck healthCheck) { this.delegate = service; this.healthCheck = healthCheck; this.wrapper = handler -> exchange -> { if (healthCheck.isHealthy()) { handler.handleRequest(exchange); } else { exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE); exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "0"); exchange.endExchange(); } }; }
Source:
<code>private LargeServerMessage messageToLargeMessage(Message message) throws Exception { <START> LargeServerMessage lsm = getStorageManager().createLargeMessage(storageManager.generateID(), message); <END> byte[] body = message.getBodyBuffer().toByteBuffer().array(); lsm.addBytes(body); lsm.releaseResources(); lsm.putLongProperty(Message.HDR_LARGE_BODY_SIZE, body.length); return lsm; }</code><technical_language>need change this to: java // Currently large message exists core protocol, convert message a core message // notice in case message is a core-message, this work a type-cast. ICoreMessage coreMessage = message.toCore(); LargeServerMessage lsm = getStorageManager().createLargeMessage(storageManager.generateID(), coreMessage); coreMessage.getReadOnlyBodyBuffer()</technical_language>

Target:
private LargeServerMessage messageToLargeMessage(Message message) throws Exception { ICoreMessage coreMessage = message.toCore(); LargeServerMessage lsm = getStorageManager().createLargeMessage(storageManager.generateID(), coreMessage); byte[] body = coreMessage.getReadOnlyBodyBuffer().toByteBuffer().array(); lsm.addBytes(body); lsm.releaseResources(); lsm.putLongProperty(Message.HDR_LARGE_BODY_SIZE, body.length); return lsm; }
Source:
<code>public static void initGraphicsForVisibleAndInvisibleElements(IFigure figure, Graphics graphics, View correspondingView) { try { graphics.pushState(); ViewQuery viewQuery = new ViewQuery(correspondingView); if (figure instanceof SiriusWrapLabel) { EObject element = correspondingView.getElement(); if (element instanceof DDiagramElement) { EList<GraphicalFilter> graphicalFilters = ((DDiagramElement) element).getGraphicalFilters(); boolean isLabelFiltered = graphicalFilters.stream().anyMatch(HideLabelFilter.class::isInstance) || graphicalFilters.stream().anyMatch(HideFilter.class::isInstance) || (correspondingView instanceof Edge && !((DDiagramElement) correspondingView.getElement()).isVisible()); if (isLabelFiltered && viewQuery.isInShowingMode()) { graphics.setAlpha(50); } } } else if (figure.isVisible() != correspondingView.isVisible() && viewQuery.isInShowingMode()) { graphics.setAlpha(50); } } catch (IllegalStateException e) { <START> System.out.println("initGraphicsForVisibleAndInvisibleElements"); END> } }</code><technical_language>println in production code</technical_language>

Target:
public static void initGraphicsForVisibleAndInvisibleElements(IFigure figure, Graphics graphics, View correspondingView) { try { graphics.pushState(); ViewQuery viewQuery = new ViewQuery(correspondingView); if (figure instanceof SiriusWrapLabel) { EObject element = correspondingView.getElement(); if (element instanceof DDiagramElement) { EList<GraphicalFilter> graphicalFilters = ((DDiagramElement) element).getGraphicalFilters(); boolean isLabelFiltered = graphicalFilters.stream().anyMatch(HideLabelFilter.class::isInstance) || graphicalFilters.stream().anyMatch(HideFilter.class::isInstance) || (correspondingView instanceof Edge && !((DDiagramElement) correspondingView.getElement()).isVisible()); if (isLabelFiltered && viewQuery.isInShowingMode()) { graphics.setAlpha(50); } } } else if (figure.isVisible() != correspondingView.isVisible() && viewQuery.isInShowingMode()) { graphics.setAlpha(50); } } catch (IllegalStateException e) { } }
Source:
<code>protected void executeSave() { final AddNetworkWithSubnetParameters parameters = new AddNetworkWithSubnetParameters(getSelectedDc().getId(), getNetwork()); parameters.setVnicProfileRequired(false); parameters.setNetworkClusterList(createNetworkAttachments()); if (getExternal().getEntity()) { Provider<?> externalProvider = getExternalProviders().getSelectedItem(); ProviderNetwork providerNetwork = new ProviderNetwork(); providerNetwork.setProviderId(externalProvider.getId()); getNetwork().setProvidedBy(providerNetwork); if (hasDefinedSubnet()) { getSubnetModel().flush(); parameters.setExternalSubnet(getSubnetModel().getSubnet()); } if (getConnectedToPhysicalNetwork().getEntity() && getUsePhysicalNetworkFromDatacenter().getEntity()) { Network network = getDatacenterPhysicalNetwork().getSelectedItem(); providerNetwork.setPhysicalNetworkId(network.getId()); <START> } else { <END> providerNetwork.setCustomPhysicalNetworkName(getCustomPhysicalNetwork().getEntity()); providerNetwork.setExternalVlanId(getVLanTag().getEntity()); } Frontend.getInstance().runAction( hasDefinedSubnet() ? ActionType.AddNetworkWithSubnetOnProvider : ActionType.AddNetworkOnProvider, parameters, addNetworkCallback(), null); } else { Frontend.getInstance().runAction(ActionType.AddNetwork, parameters, addNetworkCallback(), null); } }</code><technical_language>this 'else' is reached connectToPhysNet == false, lines redundant custom phys net name vlan tag set user, this is confusing. create if, else-if, else for situations (!connectToPhysNet, connectToPhysNet + useFromDC, connectToPhysNet + custom)</technical_language>

Target:
protected void executeSave() { final AddNetworkWithSubnetParameters parameters = new AddNetworkWithSubnetParameters(getSelectedDc().getId(), getNetwork()); parameters.setVnicProfileRequired(false); parameters.setNetworkClusterList(createNetworkAttachments()); if (getExternal().getEntity()) { Provider<?> externalProvider = getExternalProviders().getSelectedItem(); ProviderNetwork providerNetwork = new ProviderNetwork(); providerNetwork.setProviderId(externalProvider.getId()); getNetwork().setProvidedBy(providerNetwork); if (hasDefinedSubnet()) { getSubnetModel().flush(); parameters.setExternalSubnet(getSubnetModel().getSubnet()); } if (getConnectedToPhysicalNetwork().getEntity() && getUsePhysicalNetworkFromDatacenter().getEntity()) { Network network = getDatacenterPhysicalNetwork().getSelectedItem(); providerNetwork.setPhysicalNetworkId(network.getId()); } else if (getConnectedToPhysicalNetwork().getEntity() && getUsePhysicalNetworkFromCustom().getEntity()) { providerNetwork.setCustomPhysicalNetworkName(getCustomPhysicalNetwork().getEntity()); providerNetwork.setExternalVlanId(getVLanTag().getEntity()); } Frontend.getInstance().runAction( hasDefinedSubnet() ? ActionType.AddNetworkWithSubnetOnProvider : ActionType.AddNetworkOnProvider, parameters, addNetworkCallback(), null); } else { Frontend.getInstance().runAction(ActionType.AddNetwork, parameters, addNetworkCallback(), null); } }
Source:
<code>public void testSetIPv4() throws CapabilityException, ProtocolException { <START> ipCapability.setIPv4(getLogicalPort()); <END> queueCapability.execute(); }</code><technical_language>logicalPort parameter IP address. Action fail checking parameters provided one. provide a LogicalPort IPProtocolEndpoint, change interface definition setIPv4 accept LogicalPort, ipAddress mask</technical_language>

Target:
public void testSetIPv4() throws CapabilityException, ProtocolException { ipCapability.setIPv4(getLogicalPort(), getIPProtocolEndPoint()); queueCapability.execute(); }
Source:
<code>private BigtableDataClient initializeDataClient() throws IOException { Channel channel = createChannel(options.getDataHost(), options.getChannelCount()); RetryOptions retryOptions = options.getRetryOptions(); <START> return new BigtableDataGrpcClient(channel, batchPool, retryOptions, ClientCallService.DEFAULT); <END> }</code><technical_language>remove ClientCallService.DEFAULT</technical_language>

Target:
private BigtableDataClient initializeDataClient() throws IOException { Channel channel = createChannel(options.getDataHost(), options.getChannelCount()); RetryOptions retryOptions = options.getRetryOptions(); return new BigtableDataGrpcClient(channel, batchPool, retryOptions); }
Source:
<code>public void validate(final Environment env) throws ValidationException { try { for (final File file : env.files("*.xml")) { final String name = file.getAbsolutePath().substring( env.basedir().toString().length() ); if (env.exclude("xml", name)) { Logger.info(this, "%s: skipped", name); continue; } Logger.info(this, "%s: to be validated", name); final XML document = new XMLDocument(file); final List<String> schemas = document .xpath("/*/@xsi:schemaLocation"); if (schemas.isEmpty()) { throw new ValidationException( String.format( "XML validation exception: missing schema in %s", name ) ); } else { try { new StrictXML( document, new XSDDocument( URI.create( StringUtils.substringAfter( schemas.get(0), " " ) ).toURL() ) ); } catch (final IllegalStateException ex) { if (ex.getCause() != null && ex.getCause() instanceof SAXException) { <START> this.warn(name, schemas.get(0), ex); <END> } } } } } catch (final IOException ex) { throw new IllegalStateException(ex); } }</code><technical_language>do need a method for it? Logger right here</technical_language>

Target:
public void validate(final Environment env) throws ValidationException { try { for (final File file : env.files("*.xml")) { final String name = file.getAbsolutePath().substring( env.basedir().toString().length() ); if (env.exclude("xml", name)) { Logger.info(this, "%s: skipped", name); continue; } Logger.info(this, "%s: to be validated", name); final XML document = new XMLDocument(file); final List<String> schemas = document .xpath("/*/@xsi:schemaLocation"); if (schemas.isEmpty()) { throw new ValidationException( String.format( "XML validation exception: missing schema in %s", name ) ); } else { final String schema = schemas.get(0); try { new StrictXML( document, new XSDDocument( URI.create( StringUtils.substringAfter(schema, " ") ).toURL() ) ); } catch (final IllegalStateException ex) { if (ex.getCause() != null && ex.getCause() instanceof SAXException) { Logger.warn( this, "Failed to validate file %s against schema %s. Cause: %s", name, schema, ex.toString() ); } } } } } catch (final IOException ex) { throw new IllegalStateException(ex); } }
Source:
<code>public Map<String, String> parseMessage(String message) { Map<String,String> dlr = new HashMap<String, String>(); <START> final String idTag = "id:"; <END> final String submitTag = "submit date:"; final String doneTag = "done date:"; final String statTag = "stat:"; final int idStartPos = message.indexOf(idTag)+idTag.length(); final int submitStartPos = message.indexOf(submitTag)+submitTag.length(); final int doneStartPos = message.indexOf(doneTag)+doneTag.length(); final int statStartPos = message.indexOf(statTag)+statTag.length(); final int idEndPos = message.indexOf(" ",idStartPos); final int submitEndPos = message.indexOf(" ",submitStartPos); final int doneEndPos = message.indexOf(" ",doneStartPos); final int statEndPos = message.indexOf(" ",statStartPos); final String messageId = message.substring(idStartPos, idEndPos); final String submit_date = message.substring(submitStartPos, submitEndPos); final String done_date = message.substring(doneStartPos, doneEndPos); final String stat = message.substring(statStartPos, statEndPos); dlr.put("id", messageId); dlr.put("submit_date", submit_date); dlr.put("sent_date", done_date); dlr.put("status", stat); return dlr; }</code><technical_language>define CONSTANTS? do contants defined in stack in another placem reuse</technical_language>

Target:
public DLRPayload parseMessage(String message) { DLRPayload dlr = new DLRPayload(); final String messageId = parseTagValue(message, ID_TAG); dlr.setId(messageId); final String submit_date = parseTagValue(message, SUBMIT_TAG); DateTime parsedDate = parseDate(submit_date); dlr.setSubmitDate(parsedDate); final String done_date = parseTagValue(message, DONE_TAG); DateTime doneDate = parseDate(done_date); dlr.setDoneDate(doneDate); final String stat = parseTagValue(message, STAT_TAG); Status parsedStatus = parseRestcommStatus(stat); dlr.setStat(parsedStatus); final String err = parseTagValue(message, ERR_TAG); dlr.setErr(err); final String sub = parseTagValue(message, SUB_TAG); dlr.setSub(sub); final String dlv = parseTagValue(message, DLVRD_TAG); dlr.setDlvrd(dlv); if (logger.isDebugEnabled()) { logger.debug("Parsed DLR is:" + dlr); } return dlr; }
Source:
<code>public void testUnmarshalSeralizedObjectEmpty() throws Exception { AttributeAdapter attributeAdapter = getObjectAttributeAdapter(); Attribute attribute = new AttributeImpl("sampleAttr", Collections.emptyList()); AbstractAttributeType abstractAttributeType = attributeAdapter.marshal(attribute); Attribute result = attributeAdapter.unmarshal(abstractAttributeType); <START> assertThat("Null attribute not returned.", result == null); <END> }</code><technical_language>prefer assert takes actual a Matcher instead of takes in a boolean. produces error messages a test fails. suggestion assertThat("Null attribute returned.", result, is(notNullValue()));</technical_language>

Target:
public void testUnmarshalSeralizedObjectEmpty() throws Exception { AttributeAdapter attributeAdapter = getObjectAttributeAdapter(); Attribute attribute = new AttributeImpl("sampleAttr", Collections.emptyList()); AbstractAttributeType abstractAttributeType = attributeAdapter.marshal(attribute); Attribute result = attributeAdapter.unmarshal(abstractAttributeType); assertThat("Null attribute not returned.", result, is(Matchers.nullValue())); }
Source:
<code>public final void check(Cache<Object, Object> cache, Object key, String cacheAddress) { DataContainer dataContainer = cache.getAdvancedCache().getDataContainer(); if (this == REMOVE || this == CONDITIONAL_REMOVE) { assertFalse("Key was not removed in '" + cacheAddress + "'!", dataContainer.containsKey(key)); } else { <START> assertTrue("Cache '" + cacheAddress + "' does not contains key!", dataContainer.containsKey(key)); <END> InternalCacheEntry entry = dataContainer.get(key); assertNotNull("Cache '" + cacheAddress + "' does not contains entry!", entry); assertEquals("Cache '" + cacheAddress + "' has wrong value!", FINAL_VALUE, entry.getValue()); } }</code><technical_language>I this is necessary, if checking DataContainer directly</technical_language>

Target:
public final void check(Cache<Object, Object> cache, Object key, String cacheAddress) { DataContainer dataContainer = cache.getAdvancedCache().getDataContainer(); if (this == REMOVE || this == CONDITIONAL_REMOVE) { assertFalse("Key was not removed in '" + cacheAddress + "'!", dataContainer.containsKey(key)); } else { InternalCacheEntry entry = dataContainer.get(key); assertNotNull("Cache '" + cacheAddress + "' does not contains entry!", entry); assertEquals("Cache '" + cacheAddress + "' has wrong value!", FINAL_VALUE, entry.getValue()); } }