auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ArrayList<ExecutorDetails> getSortedExecs(Map<String, Integer> spreadCompCnts, Map<String, Set<String>> constraintMatrix, Map<String, Set<ExecutorDetails>> compToExecs) { ArrayList<ExecutorDetails> retList = new ArrayList<>(); Map<String, Double> compConstraintCountMap = new HashMap<>(); constraintMatrix.forEach((comp, subMatrix) -> { double count = subMatrix.size(); if (spreadCompCnts.containsKey(comp)) { <START> count += (1_000.0 / spreadCompCnts.get(comp)); <END> } compConstraintCountMap.put(comp, count); }); NavigableMap<String, Double> sortedCompConstraintCountMap = sortByValues(compConstraintCountMap); for (String comp : sortedCompConstraintCountMap.keySet()) { retList.addAll(compToExecs.get(comp)); } return retList; }</code><technical_language>Instead of large number this function total executors requested topology</technical_language>

Target:
private ArrayList<ExecutorDetails> getSortedExecs(Map<String, Integer> spreadCompCnts, Map<String, Set<String>> constraintMatrix, Map<String, Set<ExecutorDetails>> compToExecs) { ArrayList<ExecutorDetails> retList = new ArrayList<>(); Map<String, Double> compConstraintCountMap = new HashMap<>(); constraintMatrix.forEach((comp, subMatrix) -> { double count = subMatrix.size(); if (spreadCompCnts.containsKey(comp)) { count += (compToExecs.size() / spreadCompCnts.get(comp)); } compConstraintCountMap.put(comp, count); }); NavigableMap<String, Double> sortedCompConstraintCountMap = sortByValues(compConstraintCountMap); for (String comp : sortedCompConstraintCountMap.keySet()) { retList.addAll(compToExecs.get(comp)); } return retList; }
Source:
<code><START> public void updateEnhanced(final EnhancedDependency enhancedDependency) { <END> if (this.enhancedDependencies.contains(enhancedDependency)) { this.enhancedDependencies.update(enhancedDependency); } else { this.enhancedDependencies.add(enhancedDependency); } }</code><technical_language>this change is needed</technical_language>

Target:
private void updateEnhanced(final EnhancedDependency enhancedDependency) { if (this.enhancedDependencies.contains(enhancedDependency)) { this.enhancedDependencies.update(enhancedDependency); } else { this.enhancedDependencies.add(enhancedDependency); } }
Source:
<code><START> public void testPushPrivateRepo() throws Exception { <END> final File pom = getTestFile("src/test/resources/pom-push-private-repo.xml"); assertNotNull("Null pom.xml", pom); assertTrue("pom.xml does not exist", pom.exists()); final PushMojo mojo = (PushMojo) lookupMojo("push", pom); assertNotNull(mojo); mojo.execute(); }</code><technical_language>I is a do so. do is stubbing maven settings here: <LINK_0></technical_language>

Target:
public void testPushPrivateRepo() throws Exception { final File pom = getTestFile("src/test/resources/pom-push-private-repo.xml"); assertNotNull("Null pom.xml", pom); assertTrue("pom.xml does not exist", pom.exists()); final PushMojo mojo = (PushMojo) lookupMojo("push", pom); assertNotNull(mojo); final DockerClient docker = mock(DockerClient.class); }
Source:
<code>protected String getIndent(IDocument document, int line) throws BadLocationException { String definitionLine = document.get(document.getLineOffset(line - 1), document.getLineLength(line - 1)); Matcher m = WHITESPACE_PATTERN.matcher(definitionLine); final String definitionIndent = m.matches() ? m.group(1) : ""; <START> return definitionIndent + " "; <END> }</code><technical_language>this in line YEdit's spaces-per-tab preference</technical_language>

Target:
protected String getIndent(IDocument document, int line) throws BadLocationException { String definitionLine = document.get(document.getLineOffset(line - 1), document.getLineLength(line - 1)); Matcher m = WHITESPACE_PATTERN.matcher(definitionLine); final String definitionIndent = m.matches() ? m.group(1) : ""; return definitionIndent + Strings.repeat(" ", getTabWidth()); }
Source:
<code>final public void addBinary(Binary value) { if (primitiveType != null) { int precision = primitiveType.asPrimitiveType().getDecimalMetadata().getPrecision(); int scale = primitiveType.asPrimitiveType().getDecimalMetadata().getScale(); BigDecimal finaldecimal = DecimalUtils.binaryToDecimal(value, precision, scale); parent.add(finaldecimal); } else { <START> parent.add("Broken DecimalType"); <END> } }</code><technical_language>Throw exception in constructor if primitiveType is null</technical_language>

Target:
final public void addBinary(Binary value) { int precision = primitiveType.asPrimitiveType().getDecimalMetadata().getPrecision(); int scale = primitiveType.asPrimitiveType().getDecimalMetadata().getScale(); BigDecimal finaldecimal = DecimalUtils.binaryToDecimal(value, precision, scale); parent.add(finaldecimal); }
Source:
<code>public boolean isRepresentationsResource() { boolean isRepresentationsResource = false; try { isRepresentationsResource = resource.getURI() != null; } catch (IllegalStateException e) { } isRepresentationsResource = isRepresentationsResource && new FileQuery(resource.getURI().fileExtension()).isSessionResourceFile(); isRepresentationsResource = isRepresentationsResource || resource instanceof AirdResource; if (!isRepresentationsResource && !resource.getContents().isEmpty()) { for (EObject contentEObject : resource.getContents()) { <START> if (contentEObject != null && contentEObject.eClass().equals(ViewpointPackage.eINSTANCE.getDAnalysis())) { <END> isRepresentationsResource = true; break; } } } return isRepresentationsResource; }</code><technical_language>handle cases a simple contentEObject instanceof DAnalysis. If want this kind of checks, please use: ViewpointPackage.Literals.DANALYSIS.isInstanceof(contentEObject)</technical_language>

Target:
public boolean isRepresentationsResource() { boolean isRepresentationsResource = false; try { isRepresentationsResource = resource.getURI() != null; } catch (IllegalStateException e) { } isRepresentationsResource = isRepresentationsResource && new FileQuery(resource.getURI().fileExtension()).isSessionResourceFile(); isRepresentationsResource = isRepresentationsResource || resource instanceof AirdResource; if (!isRepresentationsResource && !resource.getContents().isEmpty()) { for (EObject contentEObject : resource.getContents()) { if (contentEObject != null && contentEObject.eClass().equals(ViewpointPackage.Literals.DANALYSIS)) { isRepresentationsResource = true; break; } } } return isRepresentationsResource; }
Source:
<code>public <I, E extends Entity<I, ?>> void register(Repository<I, E> repository) { checkNotNull(repository); Security.allowOnlyFrameworkServer(); <START> initialize(repository); <END> guard.register(repository); repository.onRegistered(); registerEventDispatcher(stand()); }</code><technical_language>init()</technical_language>

Target:
public <I, E extends Entity<I, ?>> void register(Repository<I, E> repository) { checkNotNull(repository); Security.allowOnlyFrameworkServer(); registerIfAware(repository); guard.register(repository); repository.onRegistered(); registerEventDispatcher(stand()); }
Source:
<code>public boolean isEqualTo(String channel, Client client) { <START> return channel.equals(this.channel) && client.equals(this.client); <END> }</code><technical_language>is null checking happening. assume input channel client non-null</technical_language>

Target:
public boolean isEqualTo(String channel, Client client) { if (channel == null || client == null) { return false; } return channel.equals(this.channel) && client.equals(this.client); }
Source:
<code>public void start() throws Exception { MqttClientOptions options = new MqttClientOptions() .setPort(1883) <START> .setHost("0.0.0.0") <END> .setKeepAliveTimeSeconds(2); MqttClient client = MqttClient.create(Vertx.vertx(), options); client.publishHandler(publish -> { System.out.println("Just received message on [" + publish.topicName() + "] payload [" + publish.payload().toString(Charset.defaultCharset()) + "] with QoS [" + publish.qosLevel() + "]"); }); client.subscribeCompleteHandler(h -> { System.out.println("Receive SUBACK from server"); System.out.print("Granted QoS levels: "); h.grantedQoSLevels().forEach(System.out::print); System.out.println(); client.publish( MQTT_TOPIC, Buffer.buffer(MQTT_MESSAGE.getBytes()), MqttQoS.AT_MOST_ONCE, false, false, s -> System.out.println("Publish sent to a server")); vertx.setTimer(5000, l -> client.unsubscribe(MQTT_TOPIC)); }); client.unsubscribeCompleteHandler(h -> { System.out.println("Receive UNSUBACK from server"); vertx.setTimer(5000, l -> client.disconnect(d -> System.out.println("Disconnected form server")) ); }); client.connect(ch -> { if (ch.succeeded()) { System.out.println("Connected to a server"); client.subscribe(MQTT_TOPIC, 0); } else { System.out.println("Failed to connect to a server"); System.out.println(ch.cause()); } }); }</code><technical_language>more "configurable" constants please</technical_language>

Target:
public void start() throws Exception { MqttClientOptions options = new MqttClientOptions() .setPort(SERVER_PORT) .setHost(SERVER_HOST) .setKeepAliveTimeSeconds(2); MqttClient client = MqttClient.create(Vertx.vertx(), options); client.publishHandler(publish -> { System.out.println("Just received message on [" + publish.topicName() + "] payload [" + publish.payload().toString(Charset.defaultCharset()) + "] with QoS [" + publish.qosLevel() + "]"); }); client.subscribeCompleteHandler(h -> { System.out.println("Receive SUBACK from server with granted QoS : " + h.grantedQoSLevels()); client.publish( MQTT_TOPIC, Buffer.buffer(MQTT_MESSAGE), MqttQoS.AT_MOST_ONCE, false, false, s -> System.out.println("Publish sent to a server")); vertx.setTimer(5000, l -> client.unsubscribe(MQTT_TOPIC)); }); client.unsubscribeCompleteHandler(h -> { System.out.println("Receive UNSUBACK from server"); vertx.setTimer(5000, l -> client.disconnect(d -> System.out.println("Disconnected form server")) ); }); client.connect(ch -> { if (ch.succeeded()) { System.out.println("Connected to a server"); client.subscribe(MQTT_TOPIC, 0); } else { System.out.println("Failed to connect to a server"); System.out.println(ch.cause()); } }); }
Source:
<code>public void onSelectDataSource() { dataSourceSelector.setGlobal(); dataSourceSelector.show( new ParameterizedCommand<DataSourceDefInfo>() { @Override public void execute( DataSourceDefInfo defInfo ) { ensurePersistenceUnit(); if ( defInfo.isDeployed() ) { getContent().getDescriptorModel().getPersistenceUnit().setJtaDataSource( defInfo.getDeploymentInfo().getJndi() ); view.setJTADataSource( defInfo.getDeploymentInfo().getJndi() ); } } }, new Command() { @Override public void execute() { <START> } <END> } ); }</code><technical_language>Lambda expressions for Commands ParameterizedCommands this shorter: () -> {}</technical_language>

Target:
public void onSelectDataSource() { dataSourceSelector.setGlobalSelection(); dataSourceSelector.show( new ParameterizedCommand<DataSourceInfo>() { @Override public void execute( DataSourceInfo dataSourceInfo ) { ensurePersistenceUnit(); if ( dataSourceInfo.isDeployed() ) { getContent().getDescriptorModel().getPersistenceUnit().setJtaDataSource( dataSourceInfo.getJndi() ); view.setJTADataSource( dataSourceInfo.getJndi() ); } } }, new Command() { @Override public void execute() { } } ); }
Source:
<code>public void setTasks(List<TaskDetails> newTasks) { if ((newTasks != null) && (newTasks.size() > 0)) { <START> throw new NotImplementedException("Expected to be invoked only during deserialization for empty/null TaskDetails. Deserialization of non-empty TaskDetails should not be done in this setter but by implementing a TaskDetails Custom Deserializer in ClientObjectMapper."); <END> } this.tasks.clear(); }</code><technical_language>break this line ~80 characters so</technical_language>

Target:
public void setTasks(List<TaskDetails> newTasks) { if ((newTasks != null) && (newTasks.size() > 0)) { throw new NotImplementedException("Expected to be invoked only during deserialization " + "for empty/null TaskDetails. Deserialization of non-empty TaskDetails should not be done " + "in this setter but by implementing a TaskDetails Custom Deserializer in ClientObjectMapper."); } this.tasks.clear(); }
Source:
<code>public Message receive(final String queueName) { return execute(new ChannelCallback<Message>() { @Override public Message doInRabbit(Channel channel) throws IOException { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; } <START> }, obtainTargetConnectionFactoryIfNecessary(null)); <END> }</code><technical_language>Polish here: <LINK_0> Also, I need provide a #queueName variable for receive() operations determine connection factory based queue name received from</technical_language>

Target:
public Message receive(final String queueName) { return execute(new ChannelCallback<Message>() { @Override public Message doInRabbit(Channel channel) throws IOException { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; } }, obtainTargetConnectionFactoryIfNecessary(this.receiveConnectionFactorySelectorExpression, queueName)); }
Source:
<code>public Response revokeSingleToken(@PathParam("accountId") String accountId, JsonNode payload) throws ValidationException, TokenNotFoundException { validatePayloadHasFields(payload, Collections.emptyList(), asList(TOKEN_LINK_FIELD, TOKEN_FIELD)); if (payload.hasNonNull(TOKEN_FIELD)) { return tokenService.extractEncryptedTokenFrom(payload.get(TOKEN_FIELD).asText()) .map(token -> authDao.revokeSingleToken(accountId, TokenHash.of(token.getName())) .map(this::buildRevokedTokenResponse)) .orElseThrow(() -> new TokenNotFoundException("Could not revoke token")) <START> .orElseThrow(() -> new TokenNotFoundException("Could not retrieve token_hash from token")); <END> } else { TokenLink tokenLink = TokenLink.of(payload.get(TOKEN_LINK_FIELD).asText()); return authDao.revokeSingleToken(accountId, tokenLink) .map(this::buildRevokedTokenResponse) .orElseThrow(() -> new TokenNotFoundException("Could not revoke token with " + tokenLink)); } }</code><technical_language>This message fit: a property called token_hash in token</technical_language>

Target:
public Response revokeSingleToken(@PathParam("accountId") String accountId, JsonNode payload) throws ValidationException, TokenNotFoundException { validatePayloadHasFields(payload, Collections.emptyList(), asList(TOKEN_LINK_FIELD, TOKEN_FIELD)); if (payload.hasNonNull(TOKEN_FIELD)) { return tokenService.extractEncryptedTokenFrom(payload.get(TOKEN_FIELD).asText()) .map(token -> authDao.revokeSingleToken(accountId, TokenHash.of(token.getName())) .map(this::buildRevokedTokenResponse)) .orElseThrow(() -> new TokenNotFoundException("Could not revoke token")) .orElseThrow(() -> new TokenNotFoundException("Could not extract encrypted token while revoking token")); } else { TokenLink tokenLink = TokenLink.of(payload.get(TOKEN_LINK_FIELD).asText()); return authDao.revokeSingleToken(accountId, tokenLink) .map(this::buildRevokedTokenResponse) .orElseThrow(() -> new TokenNotFoundException("Could not revoke token with " + tokenLink)); } }
Source:
<code>public void visit(Constructor<?> constructor) { assert constructor.getDeclaringClass().equals(classType.getRuntimeClass()) : "classType " + classType + " and declaring class " + constructor.getDeclaringClass().getName() + " should be same"; if (!reflectionPredicate.test(constructor)) { return; } TypedClassOperation operation = instantiateTypes(TypedOperation.forConstructor(constructor)); checkSubTypes(operation); if (!omitPredicate.shouldOmit(operation)) { if (operationSpecifications != null) { OperationConditions conditions = operationSpecifications.getOperationConditions(constructor); <START> if (!conditions.isEmpty()) { <END> operation.addConditions(conditions); } } operations.add(operation); } }</code><technical_language>I do this unconditionally, avoid expensive re-computation of empty conditions</technical_language>

Target:
public void visit(Constructor<?> constructor) { if (debug) { System.out.println("OperationExtractor.visit: constructor=" + constructor); } assert constructor.getDeclaringClass().equals(classType.getRuntimeClass()) : "classType " + classType + " and declaring class " + constructor.getDeclaringClass().getName() + " should be same"; if (!reflectionPredicate.test(constructor)) { return; } TypedClassOperation operation = instantiateTypes(TypedOperation.forConstructor(constructor)); if (debug) { System.out.println("OperationExtractor.visit: operation=" + operation); } checkSubTypes(operation); if (!omitPredicate.shouldOmit(operation)) { if (operationSpecifications != null) { ExecutableSpecification execSpec = operationSpecifications.getExecutableSpecification(constructor); if (!execSpec.isEmpty()) { operation.addExecutableSpecification(execSpec); } } if (debug) { System.out.println("OperationExtractor.visit: add operation " + operation); } operations.add(operation); } }
Source:
<code>public void getProcessSource(Process process, OutputStream outputStream) { notNull(process, "process"); try { final File tempFile = createTempFile("processSource", ".zip"); tempFile.deleteOnExit(); final InputStream response = restTemplate.execute(process.getSourceLink(), HttpMethod.GET, <START> noopRequestCallback, new FileResponseExtractor(tempFile)); <END> FileCopyUtils.copy(response, outputStream); } catch (IOException | GoodDataException | RestClientException e) { throw new GoodDataException("Unable to get process source " + process.getSourceLink(), e); } }</code><technical_language>please reuse ResponseExtractor ReportService.exportReport(ReportDefinition, ReportExportFormat, OutputStream)</technical_language>

Target:
public void getProcessSource(Process process, OutputStream outputStream) { notNull(process, "process"); notNull(outputStream, "outputStream"); try { restTemplate.execute(process.getSourceLink(), HttpMethod.GET, noopRequestCallback, new OutputStreamResponseExtractor(outputStream)); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to get process source " + process.getSourceLink(), e); } }
Source:
<code>public void markAsRead() { try { synchronized (mSyncLock) { mNoteJSON.put("read", 1); } } catch (JSONException e) { Log.e(TAG, "Unable to update note read property", e); return; } <START> if (getBucket() != null) <END> save(); }</code><technical_language>Question: add braces this statement</technical_language>

Target:
public void markAsRead() { try { synchronized (mSyncLock) { mNoteJSON.put("read", 1); } } catch (JSONException e) { Log.e(TAG, "Unable to update note read property", e); return; } if (getBucket() != null) { save(); } }
Source:
<code>protected boolean refreshRoot(IWorkspaceRoot target, int depth, boolean updateAliases, IProgressMonitor monitor) throws CoreException { monitor = <START> Policy.monitorFor(monitor); <END> IProject[] projects = target.getProjects(IContainer.INCLUDE_HIDDEN); int totalWork = projects.length; String title = Messages.localstore_refreshingRoot; try { SubMonitor subMonitor = SubMonitor.convert(monitor, title, totalWork); if (depth == IResource.DEPTH_ZERO) return false; boolean changed = false; depth = depth == IResource.DEPTH_ONE ? IResource.DEPTH_ZERO : depth; for (int i = 0; i < projects.length; i++) { changed |= refresh(projects[i], depth, updateAliases, subMonitor.newChild(1)); } return changed; } finally { monitor.done(); } }</code><technical_language>need for Policy.monitorFor(...)</technical_language>

Target:
protected boolean refreshRoot(IWorkspaceRoot target, int depth, boolean updateAliases, IProgressMonitor monitor) throws CoreException { IProject[] projects = target.getProjects(IContainer.INCLUDE_HIDDEN); String title = Messages.localstore_refreshingRoot; SubMonitor subMonitor = SubMonitor.convert(monitor, title, projects.length); if (depth == IResource.DEPTH_ZERO) return false; boolean changed = false; depth = depth == IResource.DEPTH_ONE ? IResource.DEPTH_ZERO : depth; for (int i = 0; i < projects.length; i++) { changed |= refresh(projects[i], depth, updateAliases, subMonitor.newChild(1)); } return changed; }
Source:
<code>public final void insertSample(double sample) { int i = index.getAndIncrement(); if (i < numSpot) reservoir[i] = sample; else { <START> int rand_generated = rand.nextInt(i + 2); END> if (rand_generated < numSpot) { reservoir[rand_generated] = sample; } } }</code><technical_language>Add a link algorithm implemented: <LINK_0> rand_generated follow variable's naming convention</technical_language>

Target:
public synchronized final void insertSample(double sample) { int i = index.getAndIncrement(); if (i < reservoir.length) reservoir[i] = sample; else { int randGenerated = random.nextInt(i + 2); if (randGenerated < reservoir.length) { reservoir[randGenerated] = sample; } } }
Source:
<code>@Override public int compareTo (DataNodeId o){ if (o == null) { throw new NullPointerException("input argument null"); <START> } <END> DataNode other = (DataNode) o; int compare = (port < other.port) ? -1 : ((port == other.port) ? 0 : 1); if (compare == 0) { compare = hostname.compareTo(other.hostname); } return compare; }</code><technical_language>compare hascode for datanode if ssl ports</technical_language>

Target:
public int compareTo(DataNodeId o) { if (o == null) { throw new NullPointerException("input argument null"); } DataNode other = (DataNode) o; int compare = (port < other.port) ? -1 : ((port == other.port) ? 0 : 1); if (compare == 0) { compare = hostname.compareTo(other.hostname); } return compare; }
Source:
<code>private int findMaxTabletId(KeyExtent extent, List<Path> recoveryLogs) throws IOException { <START> int tid = -1; <END> try (RecoveryLogsIterator rli = new RecoveryLogsIterator(fs, recoveryLogs, DEFINE_TABLET)) { KeyExtent alternative = extent; if (extent.isRootTablet()) { alternative = RootTable.OLD_EXTENT; } while (rli.hasNext()) { LogFileKey key = rli.next().getKey(); checkState(key.event == DEFINE_TABLET); if (key.tablet.equals(extent) || key.tablet.equals(alternative)) { checkState(key.tid >= 0, "Tid %s for %s is negative", key.tid, extent); checkState(tid == -1 || key.tid >= tid); if (tid != key.tid) { tid = key.tid; } } } } return tid; }</code><technical_language>abstract name "tid". this name for code</technical_language>

Target:
private int findMaxTabletId(KeyExtent extent, List<Path> recoveryLogs) throws IOException { int tabletId = -1; try (RecoveryLogsIterator rli = new RecoveryLogsIterator(fs, recoveryLogs, minKey(DEFINE_TABLET), maxKey(DEFINE_TABLET))) { KeyExtent alternative = extent; if (extent.isRootTablet()) { alternative = RootTable.OLD_EXTENT; } while (rli.hasNext()) { LogFileKey key = rli.next().getKey(); checkState(key.event == DEFINE_TABLET); if (key.tablet.equals(extent) || key.tablet.equals(alternative)) { checkState(key.tabletId >= 0, "tabletId %s for %s is negative", key.tabletId, extent); checkState(tabletId == -1 || key.tabletId >= tabletId); if (tabletId != key.tabletId) { tabletId = key.tabletId; } } } } return tabletId; }
Source:
<code>public FSRegisteredPackage(FSPackageRegistry registry, FSInstallState installState) throws IOException, RepositoryException { <START> this.installState = installState; <END> this.registry = registry; }</code><technical_language>other methods isInstalled() getInstallationTime(). rely immutable installstate? otherwise, I store installState in this object, remember packageId filePath. i..e: this.packageId = installState.getPackageId(); this.filePath = installState.getFilePath();</technical_language>

Target:
public FSRegisteredPackage(FSPackageRegistry registry, FSInstallState installState) throws IOException, RepositoryException { this.id = installState.getPackageId(); this.filepath = installState.getFilePath(); this.registry = registry; }
Source:
<code>public boolean writeJobCoordinatorMetadata(JobCoordinatorMetadata metadata) { Preconditions.checkNotNull(metadata, "Job coordinator metadata cannot be null"); boolean writeSucceeded = false; try { String metadataValueString = metadataMapper.writeValueAsString(metadata); metadataStore.put(clusterType, valueSerde.toBytes(metadataValueString)); writeSucceeded = true; } catch (Exception e) { <START> LOG.error("Failed to write the job coordinator metadata to metadata store due to ", e); <END> } LOG.info("Successfully written job coordinator metadata: for cluster {}.", metadata, clusterType); return writeSucceeded; }</code><technical_language>swallowing exception lead issues incorrect metrics previousMetadata is non-existent due exception metric records new deployment? unnecessary restart of containers. isnt this important enough fail JC for? this invoked HA is enabled right, wont fail a non-AM HA JC</technical_language>

Target:
public void writeJobCoordinatorMetadata(JobCoordinatorMetadata metadata) { Preconditions.checkNotNull(metadata, "Job coordinator metadata cannot be null"); try { String metadataValueString = metadataMapper.writeValueAsString(metadata); metadataStore.put(clusterType.name(), valueSerde.toBytes(metadataValueString)); LOG.info("Successfully written job coordinator metadata: for cluster {}.", metadata, clusterType); } catch (Exception e) { LOG.error("Failed to write the job coordinator metadata to metadata store due to ", e); throw new SamzaException("Failed to write the job coordinator metadata.", e); } }
Source:
<code><START> private static boolean isInvalidDate(final MeasurementVariable var, final String value) { final Date parsedDate = Util.tryParseDate(value, Util.FRONTEND_DATE_FORMAT); final boolean isDateParseable = parsedDate != null; return var.getDataTypeId() != null && var.getDataTypeId() == TermId.DATE_VARIABLE.getId() && !Util.isValidDate(value) && !isDateParseable; } <END></code><technical_language>I if change logic of Util.isValidDate instead. if parseable is invalid too</technical_language>

Target:
private static boolean isInvalidDate(final MeasurementVariable var, final String value) { return var.getDataTypeId() != null && var.getDataTypeId() == TermId.DATE_VARIABLE.getId() && !Util.isValidDate(value); }
Source:
<code>protected Response createFromAppSpec(ApplicationSpec applicationSpec) { checkApplicationTypesAreValid(applicationSpec); checkLocationsAreValid(applicationSpec); List<Location> locations = brooklyn().getLocations(applicationSpec); Application app = brooklyn().create(applicationSpec); Task<?> t = brooklyn().start(app, locations); TaskSummary ts = TaskTransformer.FROM_TASK.apply(t); <START> UriBuilder locationBuilder = uriInfo.getBaseUriBuilder(); <END> locationBuilder = locationBuilder.path(ApplicationApi.class); locationBuilder = locationBuilder.path(ApplicationApi.class, "get"); URI ref = locationBuilder.build(app.getApplicationId()); return created(ref).entity(ts).build(); }</code><technical_language>do this a fluent api instead? URI ref = uriInfo.getBaseUriBuilder() .path(ApplicationApi.class) .path(ApplicationApi.class, "get") .build(app.getApplicationId());</technical_language>

Target:
protected Response createFromAppSpec(ApplicationSpec applicationSpec) { checkApplicationTypesAreValid(applicationSpec); checkLocationsAreValid(applicationSpec); List<Location> locations = brooklyn().getLocations(applicationSpec); Application app = brooklyn().create(applicationSpec); Task<?> t = brooklyn().start(app, locations); TaskSummary ts = TaskTransformer.FROM_TASK.apply(t); URI ref = uriInfo.getBaseUriBuilder() .path(ApplicationApi.class) .path(ApplicationApi.class, "get") .build(app.getApplicationId()); return created(ref).entity(ts).build(); }
Source:
<code>private void updateActionAvailability() { boolean isItemSelected = getSelectedItems() != null <START> && getSelectedItems() != null <END> && getSelectedItems().size() > 0; boolean isDomainActive = getEntity() != null && getEntity().getStorageDomainSharedStatus() == StorageDomainSharedStatus.Active; getImportCommand().setIsExecutionAllowed(isItemSelected && isDomainActive); getRemoveCommand().setIsExecutionAllowed(isItemSelected && isDomainActive); }</code><technical_language>touch this line, duplication removed</technical_language>

Target:
private void updateActionAvailability() { boolean isItemSelected = getSelectedItems() != null && getSelectedItems() != null && getSelectedItems().size() > 0; boolean isDomainActive = getEntity() != null && getEntity().getStorageDomainSharedStatus() == StorageDomainSharedStatus.Active; boolean isExecutionAllowed = isItemSelected && isDomainActive; getImportCommand().setIsExecutionAllowed(isExecutionAllowed); getRemoveCommand().setIsExecutionAllowed(isExecutionAllowed); }
Source:
<code>public void testCatalogServiceDirectory() throws ServiceException, CatalogApiException { final DefaultCatalogService service = new DefaultCatalogService(new CatalogConfig() { @Override public String getCatalogURI() { return "file:catalog/src/test/resources/versionedCatalog"; <START> } <END> }, tenantInternalApi, catalogCache, cacheInvalidationCallback); service.loadCatalog(); Assert.assertNotNull(service.getFullCatalog(internalCallContext)); Assert.assertEquals(service.getFullCatalog(internalCallContext).getCatalogName(), "WeaponsHireSmall"); }</code><technical_language>I confused change: do a new catalog prefix</technical_language>

Target:
public void testCatalogServiceDirectory() throws ServiceException, CatalogApiException { final DefaultCatalogService service = new DefaultCatalogService(new CatalogConfig() { @Override public String getCatalogURI() { return "file:src/test/resources/versionedCatalog"; } }, tenantInternalApi, catalogCache, cacheInvalidationCallback); service.loadCatalog(); Assert.assertNotNull(service.getFullCatalog(internalCallContext)); Assert.assertEquals(service.getFullCatalog(internalCallContext).getCatalogName(), "WeaponsHireSmall"); }
Source:
<code>protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException { if (argValue instanceof SqlParameterValue) { SqlParameterValue paramValue = (SqlParameterValue) argValue; if (paramValue.getSqlType() == Types.BLOB) { if (paramValue.getValue() != null) { Assert.isInstanceOf(byte[].class, paramValue.getValue(), "Value of blob parameter must be byte[]"); } byte[] valueBytes = (byte[]) paramValue.getValue(); <START> this.lobCreator.setBlobAsBytes(ps, parameterPosition, valueBytes); <END> } } super.doSetValue(ps, parameterPosition, argValue); }</code><technical_language>return lobCreator.setBlobAsBytes</technical_language>

Target:
protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException { if (argValue instanceof SqlParameterValue) { SqlParameterValue paramValue = (SqlParameterValue) argValue; if (paramValue.getSqlType() == Types.BLOB) { if (paramValue.getValue() != null) { Assert.isInstanceOf(byte[].class, paramValue.getValue(), "Value of blob parameter must be byte[]"); } byte[] valueBytes = (byte[]) paramValue.getValue(); this.lobCreator.setBlobAsBytes(ps, parameterPosition, valueBytes); return; } } super.doSetValue(ps, parameterPosition, argValue); }
Source:
<code>private void checkAssignments(Object data, Set<String> loopVariables, ASTStatement loopBody, boolean checkIncrement, IgnoreFlags... ignoreFlags) { for (ASTAssignmentOperator operator : loopBody.findDescendantsOfType(ASTAssignmentOperator.class)) { final String operatorImage = operator.getImage(); final boolean isIncrement = "+=".equals(operatorImage) || "-=".equals(operatorImage); if (isIncrement != checkIncrement) { continue; } if (ignoreNode(operator, loopBody, ignoreFlags)) { continue; } <START> final ASTPrimaryExpression primaryExpression = operator.jjtGetParent().getFirstChildOfType(ASTPrimaryExpression.class); <END> final ASTName name = primaryExpression.getFirstDescendantOfType(ASTName.class); checkVariable(data, loopVariables, name); } }</code><technical_language>sure, a bug not. evolved in is - this/super integrated grammar. added a note #1019 changing this break a lot of things... for need live it, change for 7.0.0</technical_language>

Target:
private void checkAssignments(Object data, Set<String> loopVariables, ASTStatement loopBody, boolean checkIncrement, IgnoreFlags... ignoreFlags) { for (ASTAssignmentOperator operator : loopBody.findDescendantsOfType(ASTAssignmentOperator.class)) { final String operatorImage = operator.getImage(); final boolean isIncrement = "+=".equals(operatorImage) || "-=".equals(operatorImage); if (isIncrement != checkIncrement) { continue; } if (ignoreNode(operator, loopBody, ignoreFlags)) { continue; } final ASTPrimaryExpression primaryExpression = operator.jjtGetParent().getFirstChildOfType(ASTPrimaryExpression.class); checkVariable(data, loopVariables, singleVariableName(primaryExpression)); } }
Source:
<code>private int getItemIndex(T item, Stream<T> stream) { Objects.requireNonNull(item, NULL_ITEM_ERROR_MESSAGE); AtomicInteger index = new AtomicInteger(-1); <START> if (!stream.peek(t -> index.incrementAndGet()) <END> .filter(t -> equals(item, t)) .findFirst().isPresent()) { return -1; } return index.get(); }</code><technical_language>Please avoid letter variable</technical_language>

Target:
private int getItemIndex(T item, Stream<T> stream) { Objects.requireNonNull(item, NULL_ITEM_ERROR_MESSAGE); AtomicInteger index = new AtomicInteger(-1); if (!stream.peek(nextItem -> index.incrementAndGet()) .filter(nextItem -> equals(item, nextItem)) .findFirst().isPresent()) { return -1; } return index.get(); }
Source:
<code><START> protected void executeCommand() { <END> QuotaDAO dao = DbFacade.getInstance().getQuotaDAO(); dao.remove(getParameters().getQuotaId()); }</code><technical_language>call inline DbFacade.getInstance().getQuotaDAO().remove()...</technical_language>

Target:
protected void executeCommand() { getQuotaDAO().remove(getParameters().getQuotaId()); }
Source:
<code>public boolean isEnabled() { if (!unstagedViewer.getTree().isFocusControl()) return false; IStructuredSelection selection = getSelection(); if (selection.isEmpty()) return false; for (Object element : selection.toList()) { <START> if (!(element instanceof StagingEntry)) { <END> return false; } StagingEntry entry = (StagingEntry) element; if (!entry.getAvailableActions().contains(StagingEntry.Action.DELETE)) return false; } return true; }</code><technical_language>style nit: braces single line block</technical_language>

Target:
public boolean isEnabled() { if (!unstagedViewer.getTree().isFocusControl()) return false; IStructuredSelection selection = getSelection(); if (selection.isEmpty()) return false; for (Object element : selection.toList()) { if (!(element instanceof StagingEntry)) return false; StagingEntry entry = (StagingEntry) element; if (!entry.getAvailableActions().contains(StagingEntry.Action.DELETE)) return false; } return true; }
Source:
<code>public void migrate(Handle handle, MigrationContext context) { handle.update( context.newCreateTableBuilder("delayed_sssion_attempts") .addLongIdNoAutoIncrement("id", "references session_attempts (id)") .addLong("dependent_session_id", "") .addLong("next_run_time", "not null") .addTimestamp("updated_at", "not null") .build()); <START> handle.update("create index delayed_sssion_attempts_on_next_run_time on delayed_sssion_attempts (next_run_time)"); <END> }</code><technical_language>s/sssion/session</technical_language>

Target:
public void migrate(Handle handle, MigrationContext context) { handle.update( context.newCreateTableBuilder("delayed_session_attempts") .addLongIdNoAutoIncrement("id", "references session_attempts (id)") .addLong("dependent_session_id", "") .addLong("next_run_time", "not null") .addTimestamp("updated_at", "not null") .build()); handle.update("create index delayed_session_attempts_on_next_run_time on delayed_session_attempts (next_run_time)"); }
Source:
<code><START> public List<Drug> getDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames, <END> boolean includeRetired, Integer start, Integer length) throws DAOException { Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(Drug.class, "drug"); searchCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); if (StringUtils.isBlank(drugName) && concept == null) return Collections.emptyList(); if (includeRetired == false) searchCriteria.add(Restrictions.eq("drug.retired", false)); if (concept != null) searchCriteria.add(Restrictions.eq("drug.concept", concept)); MatchMode matchMode = MatchMode.START; if (searchOnPhrase) matchMode = MatchMode.ANYWHERE; if (!StringUtils.isBlank(drugName)) { Disjunction searchPhraseDisjunction = Restrictions.disjunction(); searchPhraseDisjunction.add(Restrictions.ilike("drug.name", drugName, matchMode)); if (searchDrugConceptNames) { searchCriteria.createCriteria("concept", "concept").createAlias("concept.names", "names"); searchPhraseDisjunction.add(Restrictions.ilike("names.name", drugName, matchMode)); } searchCriteria.add(searchPhraseDisjunction); } if (start != null) searchCriteria.setFirstResult(start); if (length != null && length > 0) searchCriteria.setMaxResults(length); return searchCriteria.list(); }</code><technical_language>If changed behavior of getDrugs(...) need change behavior of matching getCountOfDrugs(...) method (which args, startIndex size Integers</technical_language>

Target:
public List<Drug> getDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames, boolean includeRetired, Integer start, Integer length) throws DAOException { if (StringUtils.isBlank(drugName) && concept == null) return Collections.emptyList(); Criteria searchCriteria = getSearchCriteria(drugName, concept, searchOnPhrase, searchDrugConceptNames, includeRetired); searchCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); if (start != null) searchCriteria.setFirstResult(start); if (length != null && length > 0) searchCriteria.setMaxResults(length); return searchCriteria.list(); }
Source:
<code>private Set<QualifiedTablePrefix> calculatePrefixesWithSchemaName( ConnectorSession connectorSession, TupleDomain<ColumnHandle> constraint, Optional<Predicate<Map<ColumnHandle, NullableValue>>> predicate) { Optional<Set<String>> schemas = filterString(constraint, SCHEMA_COLUMN_HANDLE); if (schemas.isPresent()) { return schemas.get().stream() <START> .map(schema -> schema.toLowerCase(ENGLISH)) <END> .map(schema -> new QualifiedTablePrefix(catalogName, schema)) .collect(toImmutableSet()); } Session session = ((FullConnectorSession) connectorSession).getSession(); return metadata.listSchemaNames(session, catalogName).stream() .filter(schema -> !predicate.isPresent() || predicate.get().test(schemaAsFixedValues(schema))) .map(schema -> new QualifiedTablePrefix(catalogName, schema)) .collect(toImmutableSet()); }</code><technical_language>filter name contains upercase</technical_language>

Target:
private Set<QualifiedTablePrefix> calculatePrefixesWithSchemaName( ConnectorSession connectorSession, TupleDomain<ColumnHandle> constraint, Optional<Predicate<Map<ColumnHandle, NullableValue>>> predicate) { Optional<Set<String>> schemas = filterString(constraint, SCHEMA_COLUMN_HANDLE); if (schemas.isPresent()) { return schemas.get().stream() .filter(this::isLowerCase) .map(schema -> new QualifiedTablePrefix(catalogName, schema)) .collect(toImmutableSet()); } Session session = ((FullConnectorSession) connectorSession).getSession(); return metadata.listSchemaNames(session, catalogName).stream() .filter(schema -> !predicate.isPresent() || predicate.get().test(schemaAsFixedValues(schema))) .map(schema -> new QualifiedTablePrefix(catalogName, schema)) .collect(toImmutableSet()); }
Source:
<code>public Response toResponse(MalformedIdException exception) { log.error( "Malformed id detected while processing \"{}\" request for path \"{}\"", request.getMethod(), uriInfo.getPath() ); log.error("Exception", exception); final Fault fault = new Fault(); fault.setReason("Operation <START> Failed"); <END> fault.setDetail(exception.getCause().getMessage()); return Response.status(Status.BAD_REQUEST).entity(fault).build(); }</code><technical_language>I thought word of a sentence capitalized, sentence end punctuation: Operation failed. Call picky, I admit</technical_language>

Target:
public Response toResponse(MalformedIdException exception) { log.error( "Malformed id detected while processing \"{}\" request for path \"{}\"", request.getMethod(), uriInfo.getPath() ); log.error("Exception", exception); final Fault fault = new Fault(); fault.setReason("Operation failed"); fault.setDetail(exception.getCause().getMessage()); return Response.status(Status.BAD_REQUEST).entity(fault).build(); }
Source:
<code>private Map<IFile, IEditorReference> findAllEditorReferences() { IEditorReference[] editorReferences = activePage.getEditorReferences(); Map<IFile, IEditorReference> fileEditors = new HashMap<>(); for (IEditorReference editorReference : editorReferences) { try { IEditorInput editorInput = editorReference.getEditorInput(); if (editorInput instanceof IFileEditorInput) { IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput; IFile file = fileEditorInput.getFile(); fileEditors.put(file, editorReference); } } catch (PartInitException e) { <START> e.printStackTrace(); <END> } } return fileEditors; }</code><technical_language>Please log for errors</technical_language>

Target:
private Map<IFile, IEditorReference> findAllEditorReferences() { IEditorReference[] editorReferences = activePage.getEditorReferences(); Map<IFile, IEditorReference> fileEditors = new HashMap<>(); for (IEditorReference editorReference : editorReferences) { try { IEditorInput editorInput = editorReference.getEditorInput(); if (editorInput instanceof IFileEditorInput) { IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput; IFile file = fileEditorInput.getFile(); fileEditors.put(file, editorReference); } } catch (PartInitException e) { Activator.logError("PartInitException - should not happen", e); } } return fileEditors; }
Source:
<code>public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected, String message) { assertNotNull(actual, "actual is null"); assertNotNull(expected, "expected is null"); ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual); ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected); if (!actualSet.equals(expectedSet)) { <START> Multiset<?> actualDiff = Multisets.difference(actualSet, expectedSet); <END> Multiset<?> expectedDiff = Multisets.difference(expectedSet, actualSet); int limit = 100; fail(format( "%snot equal\n" + "Actual %s rows (only up to %s differing rows shown):\n %s\n" + "Expected %s rows (only up to %s differing rows shown):\n %s\n", message == null ? "" : (message + "\n"), actualSet.size(), limit, Joiner.on("\n ").join(Iterables.limit(actualDiff, limit)), expectedSet.size(), limit, Joiner.on("\n ").join(Iterables.limit(expectedDiff, limit)))); } }</code><technical_language>I rename actualDiff extra unexpected rows, expectedDiff missing rows. I naming in message. I find more clear</technical_language>

Target:
public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected, String message) { assertNotNull(actual, "actual is null"); assertNotNull(expected, "expected is null"); ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual); ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected); if (!actualSet.equals(expectedSet)) { Multiset<?> unexpectedRows = Multisets.difference(actualSet, expectedSet); Multiset<?> missingRows = Multisets.difference(expectedSet, actualSet); int limit = 100; fail(format( "%snot equal\n" + "Actual rows (up to %s of %s extra rows shown, %s matching and extra rows in total):\n %s\n" + "Expected rows (up to %s of %s missing rows shown, %s matching and missing rows in total):\n %s\n", message == null ? "" : (message + "\n"), limit, unexpectedRows.size(), actualSet.size(), Joiner.on("\n ").join(Iterables.limit(unexpectedRows, limit)), limit, missingRows.size(), expectedSet.size(), Joiner.on("\n ").join(Iterables.limit(missingRows, limit)))); } }
Source:
<code><START> public void setTaskScheduler(TaskScheduler taskScheduler) { <END> Assert.notNull(taskScheduler, "taskScheduler must not be null"); this.taskScheduler = taskScheduler; }</code><technical_language>override this method public is in AbstractCorrelatingMessageHandler, for example? smells a bit publish kind of options in IntegrationObjectSupport..</technical_language>

Target:
protected void setTaskScheduler(TaskScheduler taskScheduler) { Assert.notNull(taskScheduler, "taskScheduler must not be null"); this.taskScheduler = taskScheduler; }
Source:
<code>public JavaRDD<StructuredRecord> transform( SparkExecutionPluginContext sparkExecutionPluginContext, JavaRDD<StructuredRecord> javaRDD) throws Exception { StorageLevel storageLevel = config.getStorageLevel(); if (storageLevel == StorageLevel.NONE()) { throw new RuntimeException(String.format("Invalid storage level '%s'. Please select a valid value")); } javaRDD.persist(storageLevel); return javaRDD; <START> } <END></code><technical_language>A line breaking: public JavaRDD<StructuredRecord> transform(SparkExecutionPluginContext pluginContext, JavaRDD<StructuredRecord> javaRDD) throws Exception {</technical_language>

Target:
public JavaRDD<StructuredRecord> transform(SparkExecutionPluginContext sparkExecutionPluginContext, JavaRDD<StructuredRecord> javaRDD) throws Exception { StorageLevel storageLevel = StorageLevel.MEMORY_AND_DISK(); if (config.storageLevel.isEmpty()) { StorageLevel.fromString(config.storageLevel); } if (storageLevel == StorageLevel.NONE()) { throw new RuntimeException( String.format("Invalid storage level '%s'. Please select a valid value", config.storageLevel)); } javaRDD.persist(storageLevel); return javaRDD; }
Source:
<code>private Set<EObject> getSemanticElementsToDestroy(final DDiagramElement currentDiagramElement) { Set<EObject> elementsToDestroy = Sets.newLinkedHashSet(); <START> return appendSemanticElementsToDestroy(currentDiagramElement, elementsToDestroy) ? elementsToDestroy : null; <END> }</code><technical_language>in lines clearer :)</technical_language>

Target:
private Set<EObject> getSemanticElementsToDestroy(final DDiagramElement currentDiagramElement) { Set<EObject> elementsToDestroy = Sets.newLinkedHashSet(); boolean canDelete = appendSemanticElementsToDestroy(currentDiagramElement, elementsToDestroy); return canDelete ? elementsToDestroy : null; }
Source:
<code>private static java.net.HttpURLConnection createDefaultConnection(String url, RequestOptions options) throws IOException { URL lobURL = new URL(url); <START> HttpURLConnection conn = (HttpURLConnection) (options.getProxy() == null ? lobURL.openConnection() : lobURL.openConnection(options.getProxy())); <END> conn.setUseCaches(false); for (Map.Entry<String, String> header : getHeaders(options).entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } return conn; }</code><technical_language>Nit: flip conditional check for existence instead of non-existence? suggestion HttpURLConnection conn = (HttpURLConnection) (options.getProxy() ? lobURL.openConnection(options.getProxy()) : lobURL.openConnection());</technical_language>

Target:
private static java.net.HttpURLConnection createDefaultConnection(String url, RequestOptions options) throws IOException { URL lobURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) (options.getProxy() ? lobURL.openConnection(options.getProxy()) : lobURL.openConnection()); conn.setUseCaches(false); for (Map.Entry<String, String> header : getHeaders(options).entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } return conn; }