auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void refresh() { control("details/validate-button").click(); waitFor(driver, hasContent("Items refreshed successfully"), 10); <START> elasticSleep(1000); <END> }</code><technical_language>Is a do waiting for event happen instead of fixed time interval</technical_language>

Target:
public void refresh() { control("details/validate-button").click(); waitFor(hasContent("Items refreshed successfully")); control("details/deployReleaseRepository/validate-button").click(); control("details/deployReleaseRepository/keyFromText").sendKeys(DEFAULT_REPO); control("details/deploySnapshotRepository/validate-button").click(); control("details/deploySnapshotRepository/keyFromText").sendKeys(DEFAULT_REPO); }
Source:
<code>protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { <START> if ((assertion.getAttributeStatements() == null || assertion.getAttributeStatements().isEmpty()) <END> && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().isEmpty())) { assertAuthzDecisionStatements(assertion); } }</code><technical_language>Consider empty check in Collection</technical_language>

Target:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getAttributeStatements()) && CollectionUtils.isEmpty(assertion.getAuthnStatements())) { assertAuthzDecisionStatements(assertion); } }
Source:
<code>protected ProgressStep makeProgressStep(String input, Set<InputType> inputTypes) throws IOException { for (FactoryType factoryType : getFactoryTypes(inputTypes)) { ProgressStep step = progressStepFactoryMap.get(factoryType).create(input, inputTypes); if (step != null) { return step; } } <START> throw new ValidationException(Collections.singletonList(new ValidationError("Could not construct ProgressStep"))); <END> }</code><technical_language>ValidationError messages useful user, a ProgressStep is</technical_language>

Target:
protected ProgressStep makeProgressStep(String input, Set<InputType> inputTypes) throws IOException { for (FactoryType factoryType : getFactoryTypes(inputTypes)) { ProgressStep step = progressStepFactoryMap.get(factoryType).create(input, inputTypes); if (step != null) { return step; } } throw new ValidationException(Collections.singletonList( new ValidationError(String.format("No %s found matching '%s'", LimsUtils.joinWithConjunction(getNames(inputTypes), "or"), input)))); }
Source:
<code>public CustomModel(CustomModel toCopy) { this.maxSpeedFallback = toCopy.maxSpeedFallback; <START> this.vehicleWeight = toCopy.vehicleWeight; this.vehicleWidth = toCopy.vehicleWidth; this.vehicleLength = toCopy.vehicleLength; this.vehicleHeight = toCopy.vehicleHeight; <END> this.headingPenalty = toCopy.headingPenalty; this.distanceInfluence = toCopy.distanceInfluence; speedFactor = deepCopy(toCopy.getSpeedFactor()); maxSpeed = deepCopy(toCopy.getMaxSpeed()); priorityMap = deepCopy(toCopy.getPriority()); areas.putAll(toCopy.getAreas()); }</code><technical_language>I if group a subnode (like vehicleDimensions), a bit distracting root level. speed_factor, max_speed priority more important</technical_language>

Target:
public CustomModel(CustomModel toCopy) { this.maxSpeedFallback = toCopy.maxSpeedFallback; this.headingPenalty = toCopy.headingPenalty; this.distanceInfluence = toCopy.distanceInfluence; speedFactorMap = deepCopy(toCopy.getSpeedFactor()); maxSpeedMap = deepCopy(toCopy.getMaxSpeed()); priorityMap = deepCopy(toCopy.getPriority()); areas.putAll(toCopy.getAreas()); }
Source:
<code><START> public void clearAllStats() { <END> commandsProcessed.set(0); opsPerSecond.set(0); totalNetworkBytesRead.set(0); connectionsReceived.set(0); expirations.set(0); keyspaceHits.set(0); keyspaceMisses.set(0); stats.setLong(clientId, 0); }</code><technical_language>For consistency, I good reset other (Geode-specific) stats (not clientId)</technical_language>

Target:
public void clearAllStats() { commandsProcessed.set(0); opsPerSecond.set(0); totalNetworkBytesRead.set(0); connectionsReceived.set(0); expirations.set(0); keyspaceHits.set(0); keyspaceMisses.set(0); stats.setLong(clientId, 0); stats.setLong(passiveExpirationChecksId, 0); stats.setLong(passiveExpirationCheckTimeId, 0); stats.setLong(passiveExpirationsId, 0); stats.setLong(expirationsId, 0); stats.setLong(expirationTimeId, 0); }
Source:
<code>public static RequestStatus deleteComponent(PortletRequest request, Logger log) { String id = request.getParameter(PortalConstants.COMPONENT_ID); if (id != null) { try { <START> String deleteComment_encoded = request.getParameter(PortalConstants.MODERATION_REQUEST_COMMENT); <END> User user = UserCacheHolder.getUserFromRequest(request); if(deleteComment_encoded != null) { String deleteComment = new String(Base64.getDecoder().decode(deleteComment_encoded)); user.setCommentMadeDuringModerationRequest(deleteComment); } ComponentService.Iface client = new ThriftClients().makeComponentClient(); return client.deleteComponent(id, user); } catch (TException e) { log.error("Could not delete component from DB", e); } } return RequestStatus.FAILURE; }</code><technical_language>unconventional name for a Java variable</technical_language>

Target:
public static RequestStatus deleteComponent(PortletRequest request, Logger log) { String id = request.getParameter(PortalConstants.COMPONENT_ID); if (id != null) { try { String deleteCommentEncoded = request.getParameter(PortalConstants.MODERATION_REQUEST_COMMENT); User user = UserCacheHolder.getUserFromRequest(request); if(deleteCommentEncoded != null) { String deleteComment = new String(Base64.getDecoder().decode(deleteCommentEncoded)); user.setCommentMadeDuringModerationRequest(deleteComment); } ComponentService.Iface client = new ThriftClients().makeComponentClient(); return client.deleteComponent(id, user); } catch (TException e) { log.error("Could not delete component from DB", e); } } return RequestStatus.FAILURE; }
Source:
<code>public RemoteTableDescriptor<K, V> withRateLimiter(RateLimiter rateLimiter, TableRateLimiter.CreditFunction<K, V> readCreditFn, TableRateLimiter.CreditFunction<K, V> writeCreditFn) { Preconditions.checkNotNull(rateLimiter, "null read rate limiter"); this.rateLimiter = rateLimiter; this.readCreditFn = readCreditFn; this.writeCreditFn = writeCreditFn; if (this.readCreditFn != null) { <START> this.readCreditFn.setTableId(String.format("%s.%s", tableId, READ_CREDIT_FN)); <END> } if (this.writeCreditFn != null) { this.writeCreditFn.setTableId(String.format("%s.%s", tableId, WRITE_CREDIT_FN)); } return this; }</code><technical_language>remove this. formatted strings same, write a method do formatting</technical_language>

Target:
public RemoteTableDescriptor<K, V> withRateLimiter(RateLimiter rateLimiter, TableRateLimiter.CreditFunction<K, V> readCreditFn, TableRateLimiter.CreditFunction<K, V> writeCreditFn) { Preconditions.checkNotNull(rateLimiter, "null read rate limiter"); this.rateLimiter = rateLimiter; this.readCreditFn = readCreditFn; this.writeCreditFn = writeCreditFn; return this; }
Source:
<code>public Term resolveFunctionAndAnywhere(KItem kItem, boolean copyOnShareSubstAndEval, TermContext context) { try { Term result = kItem.isEvaluable(context) ? evaluateFunction(kItem, copyOnShareSubstAndEval, context) : kItem.applyAnywhereRules(copyOnShareSubstAndEval, context); if (result instanceof KItem && ((KItem) result).isEvaluable(context) && result.isGround()) { <START> if (options.warnings.includesExceptionType(ExceptionType.HIDDENWARNING) && tool != Tool.KOMPILE) { <END> StringBuilder sb = new StringBuilder(); sb.append("Unable to resolve function symbol:\n\t\t"); sb.append(result); sb.append('\n'); if (!context.definition().functionRules().isEmpty()) { sb.append("\tDefined function rules:\n"); for (Rule rule : context.definition().functionRules().get((KLabelConstant) ((KItem) result).kLabel())) { sb.append("\t\t"); sb.append(rule); sb.append('\n'); } } kem.registerCriticalWarning(sb.toString(), kItem); } if (RuleAuditing.isAuditBegun()) { System.err.println("Function failed to evaluate: returned " + result); } } return result; } catch (StackOverflowError e) { throw KExceptionManager.criticalError(TRACE_MSG, e); } catch (KEMException e) { e.exception.addTraceFrame("while evaluating function " + kItem.kLabel().toString()); throw e; } }</code><technical_language>if want this a hidden warning, modify call registerWarning, for consistency</technical_language>

Target:
public Term resolveFunctionAndAnywhere(KItem kItem, boolean copyOnShareSubstAndEval, TermContext context) { try { Term result = kItem.isEvaluable(context) ? evaluateFunction(kItem, copyOnShareSubstAndEval, context) : kItem.applyAnywhereRules(copyOnShareSubstAndEval, context); if (result instanceof KItem && ((KItem) result).isEvaluable(context) && result.isGround()) { if (options.warnings.includesExceptionType(ExceptionType.HIDDENWARNING) && tool != Tool.KOMPILE) { StringBuilder sb = new StringBuilder(); sb.append("Unable to resolve function symbol:\n\t\t"); sb.append(result); sb.append('\n'); if (!context.definition().functionRules().isEmpty()) { sb.append("\tDefined function rules:\n"); for (Rule rule : context.definition().functionRules().get((KLabelConstant) ((KItem) result).kLabel())) { sb.append("\t\t"); sb.append(rule); sb.append('\n'); } } kem.registerInternalHiddenWarning(sb.toString(), kItem); } if (RuleAuditing.isAuditBegun()) { System.err.println("Function failed to evaluate: returned " + result); } } return result; } catch (StackOverflowError e) { throw KExceptionManager.criticalError(TRACE_MSG, e); } catch (KEMException e) { e.exception.addTraceFrame("while evaluating function " + kItem.kLabel().toString()); throw e; } }
Source:
<code><START> public List<VdsNetworkInterface> getAllInterfacesByLabelForDataCenter(Guid dataCenterId, String label) { <END> List<VdsNetworkInterface> result = new ArrayList<>(); for (VdsNetworkInterface vdsNetworkInterface : getAllInterfacesByDataCenterId(dataCenterId)) { final Set<String> labels = vdsNetworkInterface.getLabels(); if (labels != null && labels.contains(label)) { result.add(vdsNetworkInterface); } } return result; }</code><technical_language>Duplicates code in 'getAllInterfacesByLabelForCluster(..)'. Please refactor avoid duplication</technical_language>

Target:
public List<VdsNetworkInterface> getAllInterfacesByLabelForDataCenter(Guid dataCenterId, String label) { return nicsContainingLabel(getAllInterfacesByDataCenterId(dataCenterId), label); }
Source:
<code>private Response getS3Preview(URI fileURI, int numLines) { val filename = getFilename(fileURI); val outputKey = getOutputKey(filename); val request = new GetObjectRequest( outputBucket, outputKey ).withRange(0, 100 * 1024); val object = s3Client.getObject(request); ObjectMetadata objectMetadata = object.getObjectMetadata(); boolean gzip = "gzip".equalsIgnoreCase(objectMetadata.getContentEncoding()); <START> try (val s3Reader = new CSVReader(new BufferedReader(new InputStreamReader(gzip ? new GZIPInputStream(object.getObjectContent()) : object.getObjectContent())))) { <END> return getPreviewFromCSV(s3Reader, numLines); } catch (IOException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }</code><technical_language>Please break this line a bit, a bit complicated stands. Simply moving result of ternary result of a multiline if..else sufficient</technical_language>

Target:
private Response getS3Preview(URI fileURI, int numLines) { val filename = getFilename(fileURI); val outputKey = getOutputKey(filename); val request = new GetObjectRequest( outputBucket, outputKey ).withRange(0, 100 * 1024); val object = s3Client.getObject(request); ObjectMetadata objectMetadata = object.getObjectMetadata(); boolean gzip = "gzip".equalsIgnoreCase(objectMetadata.getContentEncoding()); try (InputStream input = object.getObjectContent()) { InputStreamReader reader; if (gzip) { reader = new InputStreamReader(new GZIPInputStream(input)); } else { reader = new InputStreamReader(input); } return getPreviewFromCSV(new CSVReader(reader), numLines); } catch (IOException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }
Source:
<code>protected Object[] createParameters(Class<?>[] paramTypes, GitTestSupport gitTestsSupport) throws Throwable { Builder<Object> builder = ImmutableSet.builder(); for (Class<?> paramType : paramTypes) { if (paramType.equals(GitTestSupport.class)) { builder.add(gitTestsSupport); } else if (paramType.equals(MergeResult.class)) { builder.add(gitTestsSupport.getMergeResult()); <START> } else if (paramType.equals(List.class)) { <END> builder.add(gitTestsSupport.getProjects()); } else if (paramType.equals(Repository.class)) { builder.add(gitTestsSupport.getRepository()); } else if (paramType.equals(Status.class)) { builder.add(gitTestsSupport.getStatus()); } else { throw new IllegalArgumentException("Unknown parameter " + paramType.getCanonicalName()); } } return builder.build().toArray(); }</code><technical_language>support Collection Iterable</technical_language>

Target:
protected Object[] createParameters(Class<?>[] paramTypes, GitTestSupport gitTestsSupport) throws Throwable { final Builder<Object> builder = ImmutableList.builder(); for (Class<?> paramType : paramTypes) { if (paramType.equals(GitTestSupport.class)) { builder.add(gitTestsSupport); } else if (paramType.equals(MergeResult.class)) { builder.add(gitTestsSupport.getMergeResult()); } else if (isCollectionCompatible(paramType)) { builder.add(gitTestsSupport.getProjects()); } else if (paramType.equals(Repository.class)) { builder.add(gitTestsSupport.getRepository()); } else if (paramType.equals(Status.class)) { builder.add(gitTestsSupport.getStatus()); } else { throw new IllegalArgumentException( "Unsupported parameter type " + paramType.getCanonicalName()); } } return builder.build().toArray(); }
Source:
<code>public void requestStop() { taskState.requestStop(); try { <START> pubsub.shutdown(); <END> } catch (Exception e) { LOGGER.error("Failed to shutdown Pubsub publisher: " + e.getLocalizedMessage()); LOGGER.error(" projectId: " + projectId); LOGGER.error(" topic: " + topic.getTopic()); } if ( ddlPubsub != null ) { try { ddlPubsub.shutdown(); } catch (Exception e) { LOGGER.error("Failed to shutdown Pubsub publisher: " + e.getLocalizedMessage()); LOGGER.error(" projectId: " + projectId); LOGGER.error(" topic: " + ddlTopic.getTopic()); } } }</code><technical_language>requestStop allowed throw exception #742 is merged - happy if out catches propagate error</technical_language>

Target:
public void requestStop() throws Exception { taskState.requestStop(); pubsub.shutdown(); if ( ddlPubsub != null ) { ddlPubsub.shutdown(); } }
Source:
<code>private Record dequeueRecord() { <START> if ( records.size() < LOW_RECORD_WATERMARK ) <END> { if ( state() != State.STREAMING_STATE ) { request( fetchSize ); } isAutoPullEnabled = true; } return records.poll(); }</code><technical_language>"<=" for case fetchSize = 1. (or case HIGH_RECORD_WATERMARK == LOW_RECORD_WATERMARK)</technical_language>

Target:
private Record dequeueRecord() { Record record = records.poll(); if ( records.size() <= lowRecordWatermark ) { if ( state() != State.STREAMING_STATE ) { request( fetchSize ); } isAutoPullEnabled = true; } return record; }
Source:
<code>public HttpResponse doDoLogin( @QueryParameter String userid, @QueryParameter String password, @QueryParameter String from ) { if (Strings.isNullOrEmpty(userid)) { throw new UserError("Missing username"); } if (Strings.isNullOrEmpty(password)) { throw new UserError("Missing password"); } String dn = "cn=" + userid + "," + params.newUserBaseDN(); try { LdapContext context = connect(dn, password); try { Stapler.getCurrentRequest().getSession().setAttribute(Myself.class.getName(), new Myself(this, dn, context.getAttributes(dn), getGroups(dn,context))); } finally { context.close(); } <START> } catch (Exception e) { <END> throw new UserError(String.format("User \"%s\" not found or password incorrect %n", userid) ); } if (from==null || !from.startsWith("/")) from="/"; return HttpResponses.redirectTo(from); }</code><technical_language>Bit worried this exception logged, previously I assume thrown uncaught exception handler logged there? Exception is caught a number of infrastructure related reasons preventing log in, log message hide problem</technical_language>

Target:
public HttpResponse doDoLogin( @QueryParameter String userid, @QueryParameter String password, @QueryParameter String from ) { if (Strings.isNullOrEmpty(userid)) { throw new UserError("Missing username"); } if (Strings.isNullOrEmpty(password)) { throw new UserError("Missing password"); } String dn = "cn=" + userid + "," + params.newUserBaseDN(); try { LdapContext context = connect(dn, password); try { Stapler.getCurrentRequest().getSession().setAttribute(Myself.class.getName(), new Myself(this, dn, context.getAttributes(dn), getGroups(dn,context))); } finally { context.close(); } } catch (AuthenticationException e) { throw new UserError(String.format("User \"%s\" not found or password incorrect %n", userid) ); } catch (Exception e) { String errorId = String.valueOf(Math.round(Math.random() * 1e8)); LOGGER.log(Level.SEVERE, "Login error " + errorId, e); throw new UserError("Something went wrong. Please try again later.", errorId); } if (from==null || !from.startsWith("/")) from="/"; return HttpResponses.redirectTo(from); }
Source:
<code>public String[] marshal(final List<String> value) throws Exception { <START> System.err.println("unmarshal: " + value); <END> if (value == null) return null; return value.stream().map(String::trim).collect(Collectors.toList()).toArray(TYPE); }</code><technical_language>System.err -> LOG.trace</technical_language>

Target:
public String[] marshal(final List<String> value) throws Exception { if (value == null) return null; return value.stream().map(String::trim).collect(Collectors.toList()).toArray(TYPE); }
Source:
<code><START> public long getStartOfLastLinearBin() { <END> return -1; }</code><technical_language>This problems for BamReader.queryUnmapped()</technical_language>

Target:
public long getStartOfLastLinearBin() { if (metaDataPos > 0 && position() != metaDataPos) { seek(metaDataPos); } final int sequenceIndex = getNumberOfReferences(); long loffset = -1L; for (int i = 0; i < sequenceIndex; i++) { final int nBins = readInteger(); for (int j = 0; j < nBins; j++) { readInteger(); loffset = readLong(); final int nChunks = readInteger(); skipBytes(BAMFileConstants.CSI_CHUNK_SIZE * nChunks); } } return loffset; }
Source:
<code>public String toString() { <START> if(customName == "") { <END> if (lowNumber == 0) { return String.format("%s.%s", bigNumber, intermediateNumber); } return String.format("%s.%s.%s", bigNumber, intermediateNumber, lowNumber); } else { if (lowNumber == 0) { return String.format("%s.%s-%s", bigNumber, intermediateNumber, customName); } return String.format("%s.%s.%s-%s", bigNumber, intermediateNumber, lowNumber, customName); } }</code><technical_language>Double equal compare strings StringUtils.isBlank here</technical_language>

Target:
public String toString() { if(StringUtils.isBlank(customName)) { if (lowNumber == 0) { return String.format("%s.%s", bigNumber, intermediateNumber); } return String.format("%s.%s.%s", bigNumber, intermediateNumber, lowNumber); } else { if (lowNumber == 0) { return String.format("%s.%s-%s", bigNumber, intermediateNumber, customName); } return String.format("%s.%s.%s-%s", bigNumber, intermediateNumber, lowNumber, customName); } }
Source:
<code><START> public RankingFilter withObjUriQualifiers(final ObjQualifierConverter objQualifierConverter) { <END> Validate.notNull(objQualifierConverter, "objQualifierConverter"); return new RankingFilter( translateIdentifierQualifiers(this.measures, objQualifierConverter), attributes == null ? null : translateIdentifierQualifiers(this.attributes, objQualifierConverter), operator, value ); }</code><technical_language>use-case for this method, is similar [MeasureDefinition#withObjUriQualifiers](<LINK_0> consider extract some interface for this in future</technical_language>

Target:
public RankingFilter withObjUriQualifiers(final ObjQualifierConverter objQualifierConverter) { notNull(objQualifierConverter, "objQualifierConverter"); return new RankingFilter( translateIdentifierQualifiers(this.measures, objQualifierConverter), attributes == null ? null : translateIdentifierQualifiers(this.attributes, objQualifierConverter), operator, value ); }
Source:
<code>protected Position handlePosition(Position position) { String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", "", true); Position last = getLastPosition(position.getDeviceId()); if (attributesString.isEmpty()) { attributesString = Position.KEY_DRIVER_UNIQUE_ID; } else { <START> if (attributesString.equals("all")) { <END> position.setAttributes(last.getAttributes()); return position; } else { attributesString += "," + Position.KEY_DRIVER_UNIQUE_ID; } } if (last != null) { for (String attribute : attributesString.split("[ ,]")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }</code><technical_language>This is related computed attributes in way. Also, setting attributes clear existing attributes, I correct. Also, I special keyword is a good idea. need some of copying attributes. For example, if copyAttributes is copy app</technical_language>

Target:
protected Position handlePosition(Position position) { Position last = getLastPosition(position.getDeviceId()); String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", null, true); return copyAttributes(attributesString, position, last); }
Source:
<code>public void banCommit() throws Exception { add(git, "a.txt", "some content"); Commit c = createCommit(git, admin.getIdent(), "subject"); RestResponse r = adminSession.put("/projects/" + project.get() + "/ban/", BanCommit.Input.fromCommits(c.getCommit().getName())); assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK); BanResultInfo info = newGson().fromJson(r.getReader(), BanResultInfo.class); assertThat(Iterables.getOnlyElement(info.newlyBanned)) .isEqualTo(c.getCommit().getName()); assertThat(info.alreadyBanned).isNull(); assertThat(info.ignored).isNull(); PushResult pushResult = pushHead(git, "refs/heads/master", false); <START> assertThat(pushResult.getRemoteUpdate("refs/heads/master").getMessage() .startsWith("contains banned commit")); <END> }</code><technical_language>be: assertThat(pushResult.getRemoteUpdate("refs/heads/master").getMessage()) .startsWith("contains banned commit");</technical_language>

Target:
public void banCommit() throws Exception { add(git, "a.txt", "some content"); Commit c = createCommit(git, admin.getIdent(), "subject"); RestResponse r = adminSession.put("/projects/" + project.get() + "/ban/", BanCommit.Input.fromCommits(c.getCommit().getName())); assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK); BanResultInfo info = newGson().fromJson(r.getReader(), BanResultInfo.class); assertThat(Iterables.getOnlyElement(info.newlyBanned)) .isEqualTo(c.getCommit().getName()); assertThat(info.alreadyBanned).isNull(); assertThat(info.ignored).isNull(); PushResult pushResult = pushHead(git, "refs/heads/master", false); assertThat(pushResult.getRemoteUpdate("refs/heads/master").getMessage()) .startsWith("contains banned commit"); }
Source:
<code>private void lockVmSnapshotsWithWait(VM vm) { Map<String, String> snapshotsExlusiveLockMap = new HashMap<String, String>(); <START> snapshotsExlusiveLockMap.put(vm.getId().toString(), LockingGroup.VM_SNAPSHOTS.name()); <END> snapshotsEngineLock.setExclusiveLocks(snapshotsExlusiveLockMap); getLockManager().acquireLockWait(snapshotsEngineLock); }</code><technical_language>instead of new put, Collections.singletonMap - cleaner eyes</technical_language>

Target:
private void lockVmSnapshotsWithWait(VM vm) { Map<String, String> snapshotsExlusiveLockMap = Collections.singletonMap(vm.getId().toString(), LockingGroup.VM_SNAPSHOTS.name()); snapshotsEngineLock.setExclusiveLocks(snapshotsExlusiveLockMap); getLockManager().acquireLockWait(snapshotsEngineLock); }
Source:
<code>public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { <START> throw new IllegalArgumentException("The given Public Key is null."); <END> } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalArgumentException e) { throw new SignatureVerificationException(this, e); } }</code><technical_language>IllegalStateException</technical_language>

Target:
public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { throw new IllegalStateException("The given Public Key is null."); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { throw new SignatureVerificationException(this, e); } }
Source:
<code>ConstrainedElement build(ConstraintHelper constraintHelper, TypeResolutionHelper typeResolutionHelper, ValueExtractorManager valueExtractorManager) { if ( property.getKind() == Property.Kind.FIELD ) { return ConstrainedProperty.forField( ConfigurationSource.API, property, getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } else { return new ConstrainedExecutable( ConfigurationSource.API, property.as( Callable.class ), <START> getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), <END> getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } }</code><technical_language>a ConstrainedProperty.forGetter()</technical_language>

Target:
ConstrainedElement build(ConstraintHelper constraintHelper, TypeResolutionHelper typeResolutionHelper, ValueExtractorManager valueExtractorManager) { if ( property instanceof JavaBeanField ) { return ConstrainedProperty.forField( ConfigurationSource.API, property, getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } else { return new ConstrainedExecutable( ConfigurationSource.API, property.as( Callable.class ), getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } }
Source:
<code>private RequestFuture<Map<TopicPartition, OffsetAndMetadata>> sendOffsetFetchRequest(Set<TopicPartition> partitions) { Node coordinator = checkAndGetCoordinator(); if (coordinator == null) return RequestFuture.coordinatorNotAvailable(); log.debug("Fetching committed offsets for partitions: {}", partitions); OffsetFetchRequest.Builder requestBuilder = <START> new OffsetFetchRequest.Builder(this.rebalanceConfig.groupId, false, new ArrayList<>(partitions)); <END> return client.send(coordinator, requestBuilder) .compose(new OffsetFetchResponseHandler()); }</code><technical_language>planning setting this flag? application need fetched offsets account ongoing transactions</technical_language>

Target:
private RequestFuture<Map<TopicPartition, OffsetAndMetadata>> sendOffsetFetchRequest(Set<TopicPartition> partitions) { Node coordinator = checkAndGetCoordinator(); if (coordinator == null) return RequestFuture.coordinatorNotAvailable(); log.debug("Fetching committed offsets for partitions: {}", partitions); OffsetFetchRequest.Builder requestBuilder = new OffsetFetchRequest.Builder(this.rebalanceConfig.groupId, true, new ArrayList<>(partitions)); return client.send(coordinator, requestBuilder) .compose(new OffsetFetchResponseHandler()); }
Source:
<code><START> public void each(MatrixProcedure procedure) { <END> int l = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (j == rowIndices[l]) { procedure.apply(i,j,values[l++]); } else { procedure.apply(i,j,0); } } } }</code><technical_language>need this. is method in AbstractMatrix class logic. do there</technical_language>

Target:
public void each(MatrixProcedure procedure) { int k = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (j == rowIndices[k]) { procedure.apply(i, j, values[k]); k++; } else { procedure.apply(i, j, 0); } } } }
Source:
<code>public Api getAPIForSite(Site site) { <START> if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(WikipediaApp.PREFERENCE_EVENTLOGGING_ENABLED, true)) { <END> if (!MccMncStateHandler.hasMccMncBeenSent()) { Api api = MccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, getUserAgent()); if (api != null) { return api; } } } if (!apis.containsKey(site.getDomain())) { apis.put(site.getDomain(), new Api(site.getApiDomain(), getUserAgent())); } return apis.get(site.getDomain()); }</code><technical_language>move this check MccMncStateHandler, get called less? :)</technical_language>

Target:
public Api getAPIForSite(Site site) { Api api = mccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, getUserAgent()); if (api != null) { return api; } if (!apis.containsKey(site.getDomain())) { apis.put(site.getDomain(), new Api(site.getApiDomain(), getUserAgent())); } return apis.get(site.getDomain()); }
Source:
<code>protected AbstractCachingAuthenticator(long allowedTimestampSlop, long cacheTimeout, TimeUnit timeUnit, long maxCacheElements) { super(allowedTimestampSlop, timeUnit); cache = CacheBuilder.newBuilder() .maximumSize(maxCacheElements) .expireAfterWrite(cacheTimeout, timeUnit) <START> .build(new CacheLoader<Credentials, Optional<Principal>>() { <END> @Override public Optional<Principal> load(Credentials credentials) throws Exception { return Optional.fromNullable(loadPrincipal(credentials)); } }); }</code><technical_language>I keying cache a Credentials object, end a cache miss new request, object specific a request (since a timestamp, signature, etc.). I if instead key apiKey is in credentials</technical_language>

Target:
protected AbstractCachingAuthenticator(long allowedTimestampSlop, long cacheTimeout, TimeUnit timeUnit, long maxCacheElements) { super(allowedTimestampSlop, timeUnit); cache = CacheBuilder.newBuilder() .maximumSize(maxCacheElements) .expireAfterWrite(cacheTimeout, timeUnit) .build(); }
Source:
<code>public Collection<SearchPlanForBody> plan(PQuery querySpec, Set<Integer> boundVarIndices) throws QueryProcessingException { Set<PBody> normalizedBodies = prepareNormalizedBodies(querySpec); plansForBodies <START> = Lists.newArrayList(); <END> for (PBody normalizedBody : normalizedBodies) { Set<PVariable> boundVariables = calculatePatternAdornmentForPlanner(boundVarIndices, normalizedBody); SubPlan plan = plannerStrategy.plan(normalizedBody, logger, boundVariables, metaContext, runtimeContext, hints); List<ISearchOperation> compiledOperations = operationCompiler.compile(plan, boundVarIndices); SearchPlanForBody compiledPlan = new SearchPlanForBody(normalizedBody, operationCompiler.getVariableMappings(), plan, compiledOperations); plansForBodies.add(compiledPlan); } return plansForBodies; }</code><technical_language>This list initialized size of normalizedBodies</technical_language>

Target:
public Collection<SearchPlanForBody> plan(PQuery querySpec, Set<Integer> boundVarIndices) throws QueryProcessingException { Set<PBody> normalizedBodies = prepareNormalizedBodies(querySpec); plansForBodies = Lists.newArrayListWithExpectedSize(normalizedBodies.size()); for (PBody normalizedBody : normalizedBodies) { Set<PVariable> boundVariables = calculatePatternAdornmentForPlanner(boundVarIndices, normalizedBody); SubPlan plan = plannerStrategy.plan(normalizedBody, logger, boundVariables, metaContext, runtimeContext, hints); List<ISearchOperation> compiledOperations = operationCompiler.compile(plan, boundVarIndices); SearchPlanForBody compiledPlan = new SearchPlanForBody(normalizedBody, operationCompiler.getVariableMappings(), plan, compiledOperations); plansForBodies.add(compiledPlan); } return plansForBodies; }
Source:
<code>public static void untar(InputStream in, File targetDir) throws IOException { <START> try (TarArchiveInputStream tarIn = new TarArchiveInputStream(in)) { <END> byte[] b = new byte[BUF_SIZE]; TarArchiveEntry tarEntry; while ((tarEntry = tarIn.getNextTarEntry()) != null) { final File file = new File(targetDir, tarEntry.getName()); if (tarEntry.isDirectory()) { if (!file.mkdirs()) { throw new IOException("Unable to create folder " + file.getAbsolutePath()); } } else { final File parent = file.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IOException("Unable to create folder " + parent.getAbsolutePath()); } } try (FileOutputStream fos = new FileOutputStream(file)) { int r; while ((r = tarIn.read(b)) != -1) { fos.write(b, 0, r); } } } } } }</code><technical_language>I idea in a fact caller of untar method suppose close InputStream for example <LINK_0></technical_language>

Target:
public static void untar(InputStream in, File targetDir) throws IOException { final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); byte[] b = new byte[BUF_SIZE]; TarArchiveEntry tarEntry; while ((tarEntry = tarIn.getNextTarEntry()) != null) { final File file = new File(targetDir, tarEntry.getName()); if (tarEntry.isDirectory()) { if (!file.mkdirs()) { throw new IOException("Unable to create folder " + file.getAbsolutePath()); } } else { final File parent = file.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IOException("Unable to create folder " + parent.getAbsolutePath()); } } try (FileOutputStream fos = new FileOutputStream(file)) { int r; while ((r = tarIn.read(b)) != -1) { fos.write(b, 0, r); } } } } }
Source:
<code>public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } IterableMappingMethod other = (IterableMappingMethod) obj; if ( !getResultType().equals( other.getResultType() ) ) { return false; } if ( getSourceParameters().size() != other.getSourceParameters().size() ) { return false; } for ( int i = 0; i < getSourceParameters().size(); i++ ) { List<Type> thisTypeParameters = getSourceParameters().get( i ).getType().getTypeParameters(); List<Type> otherTypeParameters = other.getSourceParameters().get( i ).getType().getTypeParameters(); if ( thisTypeParameters.isEmpty() && otherTypeParameters.isEmpty() ) { continue; } <START> if ( !thisTypeParameters.get( 0 ).equals( otherTypeParameters.get( 0 ) ) ) { <END> return false; } } return true; }</code><technical_language>I case thisTypeParameters is empty otherTypeParameters is empty (and vice versa) is missing. check ...size() != ...size() (as sourceParameters) iterate check parameter pair</technical_language>

Target:
public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } IterableMappingMethod other = (IterableMappingMethod) obj; if ( !getResultType().equals( other.getResultType() ) ) { return false; } if ( getSourceParameters().size() != other.getSourceParameters().size() ) { return false; } for ( int i = 0; i < getSourceParameters().size(); i++ ) { List<Type> thisTypeParameters = getSourceParameters().get( i ).getType().getTypeParameters(); List<Type> otherTypeParameters = other.getSourceParameters().get( i ).getType().getTypeParameters(); if ( !thisTypeParameters.equals( otherTypeParameters ) ) { return false; } } return true; }
Source:
<code>public static void assertLogMessageEquals(String expected, String actual) { <START> String expectedGoogleId = expected.split("\\|\\|\\|")[6]; <END> assertLogMessageEquals(expected, actual, expectedGoogleId); }</code><technical_language>constant instead of a magic number</technical_language>

Target:
public static void assertLogMessageEquals(String expected, String actual) { String expectedGoogleId = expected.split("\\|\\|\\|")[ActivityLogEntry.POSITION_OF_GOOGLEID]; assertLogMessageEquals(expected, actual, expectedGoogleId); }
Source:
<code>private byte[] getBaseQualitiesImpl() { try { Fragment fragment; if (isAligned) { fragment = getCurrentAlignment(); } else { fragment = getCurrentUnalignedRead(); } <START> boolean reverse = false; END> byte[] quals = fragment.getFragmentQualities().getBytes(); for (int i = 0; i < quals.length / 2; i++) { quals[i] -= 33; quals[quals.length - i - 1] -= 33; if (reverse) { byte temp = quals[i]; quals[i] = quals[quals.length - i - 1]; quals[quals.length - i - 1] = temp; } } if (quals.length % 2 != 0) { quals[quals.length / 2] -= 33; } return quals; } catch (ErrorMsg e) { throw new RuntimeException(e); } }</code><technical_language>Address this TODO (or delete if addressed)</technical_language>

Target:
private byte[] getBaseQualitiesImpl() { try { Fragment fragment; if (isAligned) { fragment = getCurrentAlignment(); } else { fragment = getCurrentUnalignedRead(); } return SAMUtils.fastqToPhred(fragment.getFragmentQualities()); } catch (ErrorMsg e) { throw new RuntimeException(e); } }
Source:
<code>public void testChangeEventsOnlyOnSave() throws Exception { final ConfigChangedEvent[] events = new ConfigChangedEvent[1]; db.getListenerList().addConfigChangedListener( new ConfigChangedListener() { public void onConfigChanged(ConfigChangedEvent event) { events[0] = event; } }); FileBasedConfig config = db.getConfig(); assertNull(events[0]); config.setString("test", "section", "event", "value"); assertNull(events[0]); config.save(); assertNotNull(events[0]); assertEquals(events[0].getRepository(), db); events[0] = null; <START> assertNull(events[0]); <END> config.unset("test", "section", "event"); assertNull(events[0]); config.save(); assertNotNull(events[0]); assertEquals(events[0].getRepository(), db); }</code><technical_language>this assertion unnecessary (you set null line above)</technical_language>

Target:
public void testChangeEventsOnlyOnSave() throws Exception { final ConfigChangedEvent[] events = new ConfigChangedEvent[1]; db.getListenerList().addConfigChangedListener( new ConfigChangedListener() { public void onConfigChanged(ConfigChangedEvent event) { events[0] = event; } }); FileBasedConfig config = db.getConfig(); assertNull(events[0]); config.setString("test", "section", "event", "value"); assertNull(events[0]); config.save(); assertNotNull(events[0]); assertEquals(events[0].getRepository(), db); events[0] = null; config.unset("test", "section", "event"); assertNull(events[0]); config.save(); assertNotNull(events[0]); assertEquals(events[0].getRepository(), db); }
Source:
<code>public Object visit(ASTMethodDeclaration node, Object data) { if (currentLookup.peek() == null) { return super.visit(node, data); } for (ASTAnnotation annot : node.getDeclaredAnnotations()) { if (Override.class.equals(annot.getType())) { return super.visit(node, data); } } try { boolean overridden = currentLookup.peek().isOverridden(node.getName(), node.getFormalParameters()); if (overridden) { addViolation(data, node, new Object[]{node.getQualifiedName().getOperation()}); } <START> } catch (NoSuchMethodException e) { <END> } return super.visit(node, data); }</code><technical_language>I started dogfood task, I know, this EmptyCatchBlock flagged. If sure, exception ignored, expected exception variable name</technical_language>

Target:
public Object visit(ASTMethodDeclaration node, Object data) { if (currentLookup.peek() == null) { return super.visit(node, data); } for (ASTAnnotation annot : node.getDeclaredAnnotations()) { if (Override.class.equals(annot.getType())) { return super.visit(node, data); } } try { boolean overridden = currentLookup.peek().isOverridden(node.getName(), node.getFormalParameters()); if (overridden) { addViolation(data, node, new Object[]{node.getQualifiedName().getOperation()}); } } catch (NoSuchMethodException e) { LOG.warning("MissingOverride encountered unexpected method " + node.getMethodName()); } return super.visit(node, data); }
Source:
<code>public void check(OperationResult result) { HealthStateType healthStateType = HealthStateType.general(HealthStateScope.forPipeline(pipelineName)); Pipeline pipeline = pipelineService.fullPipelineByCounter(pipelineName, pipelineCounter); if (pipeline == null) { result.success(healthStateType); <START> return; <END> } if (!pipeline.hasStageBeenRun(stageName)) { if (goConfigService.hasPreviousStage(pipelineName, stageName)) { CaseInsensitiveString previousStageName = goConfigService.previousStage(pipelineName, stageName).name(); StageConfig currentStageConfig = goConfigService.nextStage(pipelineName, previousStageName.toString()); Approval approval = currentStageConfig.getApproval(); if (approval.isAllowOnlyOnSuccess()) { Stage previousStage = pipeline.getStages().byName(previousStageName.toString()); StageResult previousStageResult = previousStage.getResult(); if (previousStageResult != StageResult.Passed) { String errorMessage = String.format("Cannot schedule %s as the previous stage %s has %s!", stageName, previousStageName.toString(), previousStageResult.name()); healthStateType = HealthStateType.forbidden(); result.notAcceptable(errorMessage, healthStateType); return; } } } } result.success(healthStateType); }</code><technical_language>Some of this duplicate code ScheduleService#checkIfPreviousStagePassed, of de-duplicating some of this</technical_language>

Target:
public void check(OperationResult result) { HealthStateType healthStateType = HealthStateType.general(HealthStateScope.forPipeline(pipelineName)); Pipeline pipeline = pipelineService.fullPipelineByCounter(pipelineName, pipelineCounter); ScheduleStageResult scheduleStageResult = schedulingCheckerService.shouldAllowSchedulingStage(pipeline, stageName); if (scheduleStageResult == ScheduleStageResult.PreviousStageNotPassed) { String errorMessage = String.format("Cannot schedule %s as the previous stage %s has %s!", stageName, scheduleStageResult.getPreviousStageName(), scheduleStageResult.getPreviousStageResult()); healthStateType = HealthStateType.forbidden(); result.notAcceptable(errorMessage, healthStateType); return; } result.success(healthStateType); }
Source:
<code>public void add(String... values) { <START> for (String value : values) { <END> arguments.add(value); } }</code><technical_language>Do is replace Collection.addAll? suggestion arguments.addAll(Arrays.asList(values));</technical_language>

Target:
public void add(String... values) { arguments.addAll(Arrays.asList(values)); }
Source:
<code>void deleteSecurityGroup(String region, String group) { checkNotNull(emptyToNull(region), "region must be defined"); checkNotNull(emptyToNull(group), "group must be defined"); String groupName = namingConvention.create().sharedNameForGroup(group); Multimap<String, String> securityGroupFilterByName = ImmutableMultimap.of("group-name", groupName); Set<SecurityGroup> securityGroupsToDelete = client.getSecurityGroupApi().get() .describeSecurityGroupsInRegionWithFilter(region, securityGroupFilterByName); if (securityGroupsToDelete.size() > 1) { logger.warn("When trying to delete security group found more than one matching the name. Will delete all - {}.", <START> group, securityGroupsToDelete); <END> } for (SecurityGroup securityGroup : securityGroupsToDelete) { logger.debug(">> deleting securityGroup(%s)", groupName); client.getSecurityGroupApi().get().deleteSecurityGroupInRegionById(region, securityGroup.getId()); securityGroupMap.invalidate(new RegionNameAndIngressRules(region, groupName, null, false, null)); logger.debug("<< deleted securityGroup(%s)", groupName); } }</code><technical_language>assume logback. jclouds logger %s for variable substitution</technical_language>

Target:
void deleteSecurityGroup(String region, String group) { checkNotNull(emptyToNull(region), "region must be defined"); checkNotNull(emptyToNull(group), "group must be defined"); String groupName = namingConvention.create().sharedNameForGroup(group); Multimap<String, String> securityGroupFilterByName = ImmutableMultimap.of("group-name", groupName); Set<SecurityGroup> securityGroupsToDelete = client.getSecurityGroupApi().get() .describeSecurityGroupsInRegionWithFilter(region, securityGroupFilterByName); if (securityGroupsToDelete.size() > 1) { logger.warn("When trying to delete security group %s found more than one matching the name. Will delete all - %s.", group, securityGroupsToDelete); } for (SecurityGroup securityGroup : securityGroupsToDelete) { logger.debug(">> deleting securityGroup(%s)", groupName); client.getSecurityGroupApi().get().deleteSecurityGroupInRegionById(region, securityGroup.getId()); securityGroupMap.invalidate(new RegionNameAndIngressRules(region, groupName, null, false, null)); logger.debug("<< deleted securityGroup(%s)", groupName); } }
Source:
<code>protected <T extends Rollup> Table<Locator, Long, T> getRollupsForLocators(final List<Locator> locators, String columnFamily, Range range) { Table<Locator, Long, T> locatorTimestampRollup = HashBasedTable.create(); Map<Locator, List<ResultSetFuture>> resultSetFuturesMap = selectForLocatorListAndRange(columnFamily, locators, range); for (Map.Entry<Locator, List<ResultSetFuture>> entry : resultSetFuturesMap.entrySet() ) { Locator locator = entry.getKey(); try { List<ResultSetFuture> futures = entry.getValue(); Table<Locator, Long, T> result = toLocatorTimestampRollup(futures, locator, CassandraModel.getGranularity(columnFamily)); <START> locatorTimestampRollup.putAll(result); <END> } catch (Exception ex) { Instrumentation.markReadError(); LOG.error(String.format("error querying rollup from column family %s for locator %s, range %s", columnFamily, locator, range), ex); } } return locatorTimestampRollup; }</code><technical_language>throw exception in this block</technical_language>

Target:
protected <T extends Rollup> Table<Locator, Long, T> getRollupsForLocators(final List<Locator> locators, String columnFamily, Range range) { Table<Locator, Long, T> locatorTimestampRollup = HashBasedTable.create(); Map<Locator, List<ResultSetFuture>> resultSetFuturesMap = selectForLocatorListAndRange(columnFamily, locators, range); for (Map.Entry<Locator, List<ResultSetFuture>> entry : resultSetFuturesMap.entrySet() ) { Locator locator = entry.getKey(); List<ResultSetFuture> futures = entry.getValue(); Table<Locator, Long, T> result = toLocatorTimestampRollup(futures, locator, CassandraModel.getGranularity(columnFamily)); locatorTimestampRollup.putAll(result); } return locatorTimestampRollup; }