auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<String, String> getFields() { <START> return Collections.unmodifiableMap(fields); <END> }</code><technical_language>is change field instance creation. create unmodifiable map time this method is called? I prefer once</technical_language>

Target:
public Map<String, String> getFields() { return fields; }
Source:
<code>public void startPeers() { log.info("starting peers"); Map<String, ServiceReservation> peers = null; try { Method method = this.getClass().getMethod("getMetaData"); ServiceType st = (ServiceType) method.invoke(null); peers = st.getPeers(); } catch (Exception e) { } if (peers == null) { return; } <START> <END> Set<Class<?>> ancestry = new HashSet<Class<?>>(); Class<?> targetClass = this.getClass(); while (targetClass.getCanonicalName().startsWith("org.myrobotlab") && !targetClass.getCanonicalName().startsWith("org.myrobotlab.framework")) { ancestry.add(targetClass); targetClass = targetClass.getSuperclass(); } for (Class<?> sourceClass : ancestry) { Field fields[] = sourceClass.getDeclaredFields(); for (int j = 0, m = fields.length; j < m; j++) { try { Field f = fields[j]; f.setAccessible(true); Field targetField = sourceClass.getDeclaredField(f.getName()); targetField.setAccessible(true); if (peers.containsKey(f.getName())) { if (f.get(this) != null) { log.info("peer already assigned", f.getName()); continue; } log.info("assinging {}.{} = startPeer({})", sourceClass.getSimpleName(), f.getName(), f.getName()); Object o = startPeer(f.getName()); targetField.set(this, o); } } catch (Exception e) { log.error("copy failed", e); } } } }</code><technical_language>calling Runtime.start here? fully grokin' need for logic below</technical_language>

Target:
public void startPeers() { log.info("starting peers"); Map<String, ServiceReservation> peers = null; try { Method method = this.getClass().getMethod("getMetaData"); ServiceType st = (ServiceType) method.invoke(null); peers = st.getPeers(); } catch (Exception e) { } if (peers == null) { return; } Set<Class<?>> ancestry = new HashSet<Class<?>>(); Class<?> targetClass = this.getClass(); while (targetClass.getCanonicalName().startsWith("org.myrobotlab") && !targetClass.getCanonicalName().startsWith("org.myrobotlab.framework")) { ancestry.add(targetClass); targetClass = targetClass.getSuperclass(); } for (Class<?> sourceClass : ancestry) { Field fields[] = sourceClass.getDeclaredFields(); for (int j = 0, m = fields.length; j < m; j++) { try { Field f = fields[j]; f.setAccessible(true); Field targetField = sourceClass.getDeclaredField(f.getName()); targetField.setAccessible(true); if (peers.containsKey(f.getName())) { ServiceReservation sr = peers.get(f.getName()); if (sr.autoStart == null || sr.autoStart == false) { log.info("peer defined - but configured to not autoStart"); continue; } if (f.get(this) != null) { log.info("peer already assigned", f.getName()); continue; } log.info("assinging {}.{} = startPeer({})", sourceClass.getSimpleName(), f.getName(), f.getName()); Object o = startPeer(f.getName()); targetField.set(this, o); } } catch (Exception e) { log.error("copy failed", e); } } } }
Source:
<code>private static String timestamp() { <START> SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); <END> return sdfr.format(new Date()); }</code><technical_language>date string format a protected static constant. do need temporary variable? (This method is called times a tick.)</technical_language>

Target:
private static String timestamp() { return LogKitten.TIMESTAMP_FORMAT.format(new Date()); }
Source:
<code>private <T> T execute(String type, ResponseHandler<T> responseHandler, String sparql) { <START> log.trace("Running SPARQL: {}", sparql); <END> long startQuery = System.currentTimeMillis(); final ContentResponse response; try { response = retryer.call(() -> makeRequest(type, sparql, responseHandler.acceptHeader()).send()); if (response.getStatus() != HttpStatus.OK_200) { throw new ContainedException("Non-200 response from triple store: " + response + " body=\n" + responseBodyAsString(response)); } log.debug("Completed in ms", System.currentTimeMillis() - startQuery); return responseHandler.parse(response); } catch (ExecutionException | RetryException | IOException e) { throw new FatalException("Error updating triple store", e); } }</code><technical_language>I discovered I do want enable displaying SPARQL. for this patch, is this log level easily accessible need do else</technical_language>

Target:
private <T> T execute(String type, ResponseHandler<T> responseHandler, String sparql) { log.trace("Running SPARQL: {}", sparql); long startQuery = System.currentTimeMillis(); final ContentResponse response; try { response = retryer.call(() -> makeRequest(type, sparql, responseHandler.acceptHeader()).send()); if (response.getStatus() != HttpStatus.OK_200) { throw new ContainedException("Non-200 response from triple store: " + response + " body=\n" + response.getContentAsString()); } log.debug("Completed in ms", System.currentTimeMillis() - startQuery); return responseHandler.parse(response); } catch (ExecutionException | RetryException | IOException e) { throw new FatalException("Error updating triple store", e); } }
Source:
<code>private void hotSetMemlog(HotSetAmountOfMemoryParameters params, VdcReturnValueBase setAmountOfMemoryResult) { if (!setAmountOfMemoryResult.isValid()) { AuditLogableBase logable = new HotSetAmountOfMemoryCommand<>(params, null); List<String> validationMessages = getBackend().getErrorsTranslator(). translateErrorText(setAmountOfMemoryResult.getValidationMessages()); logable.addCustomValue(HotSetAmountOfMemoryCommand.LOGABLE_FIELD_ERROR_MESSAGE, StringUtils.join(validationMessages, ",")); <START> auditLogDirector.log(logable, AuditLogType.FAILED_HOT_SET_MEMORY); <END> } }</code><technical_language>please split a patch</technical_language>

Target:
private void hotSetMemlog(HotSetAmountOfMemoryParameters params, VdcReturnValueBase setAmountOfMemoryResult) { if (!setAmountOfMemoryResult.isValid()) { AuditLogableBase logable = new HotSetAmountOfMemoryCommand<>(params, null); List<String> validationMessages = getBackend().getErrorsTranslator(). translateErrorText(setAmountOfMemoryResult.getValidationMessages()); logable.addCustomValue(HotSetAmountOfMemoryCommand.LOGABLE_FIELD_ERROR_MESSAGE, StringUtils.join(validationMessages, ",")); auditLogDirector.log(logable, AuditLogType.FAILED_HOT_SET_NUMBER_OF_CPUS); } }
Source:
<code>protected boolean checkIfImageDiskCanBeAdded(VM vm, DiskValidator diskValidator) { <START> if (Guid.Empty.equals(getParameters().getStorageDomainId()) && Guid.Empty.equals(getStorageDomainId())) { <END> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_SPECIFIED); } boolean returnValue; StorageDomainValidator storageDomainValidator = createStorageDomainValidator(); returnValue = validate(storageDomainValidator.isDomainExistAndActive()) && !isShareableDiskOnGlusterDomain() && checkImageConfiguration() && validate(storageDomainValidator.hasSpaceForNewDisk(getDiskImageInfo())) && validate(storageDomainValidator.isDomainWithinThresholds()) && checkExceedingMaxBlockDiskSize() && canAddShareableDisk() && validate(diskValidator.isVirtIoScsiValid(vm)) && validate(diskValidator.isDiskInterfaceSupported(getVm())); if (returnValue && vm != null) { StoragePool sp = getStoragePool(); returnValue = validate(new StoragePoolValidator(sp).isUp()) && isStoragePoolMatching(vm) && isVmNotLocked() && isVmNotInPreviewSnapshot(); } return returnValue; }</code><technical_language>look, narrow check getStorageDomainId()</technical_language>

Target:
protected boolean checkIfImageDiskCanBeAdded(VM vm, DiskValidator diskValidator) { if (Guid.Empty.equals(getStorageDomainId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_SPECIFIED); } boolean returnValue; StorageDomainValidator storageDomainValidator = createStorageDomainValidator(); returnValue = validate(storageDomainValidator.isDomainExistAndActive()) && !isShareableDiskOnGlusterDomain() && checkImageConfiguration() && validate(storageDomainValidator.hasSpaceForNewDisk(getDiskImageInfo())) && validate(storageDomainValidator.isDomainWithinThresholds()) && checkExceedingMaxBlockDiskSize() && canAddShareableDisk() && validate(diskValidator.isVirtIoScsiValid(vm)) && validate(diskValidator.isDiskInterfaceSupported(getVm())); if (returnValue && vm != null) { StoragePool sp = getStoragePool(); returnValue = validate(new StoragePoolValidator(sp).isUp()) && isStoragePoolMatching(vm) && isVmNotLocked() && isVmNotInPreviewSnapshot(); } return returnValue; }
Source:
<code>protected void executeQueryCommand() { <START> VmDeviceDAO dao = DbFacade.getInstance().getVmDeviceDAO(); <END> List<VmDevice> disks = new ArrayList(dao.getVmDeviceByVmIdAndType(getParameters().getId(), VmDeviceType.DISK.getName())); for (VmDevice disk: disks) { if (VmPayload.IsPayload(disk.getSpecParams())) { VmPayload payload = new VmPayload(VmDeviceType.valueOf(disk.getType().toUpperCase()), disk.getSpecParams()); payload.setType(VmDeviceType.valueOf(disk.getDevice().toUpperCase())); payload.setContent(new String(Base64.decodeBase64(payload.getContent()))); getQueryReturnValue().setReturnValue(payload); } } }</code><technical_language>Please replace with: VmDeviceDAO dao = getDbFacade().getVmDeviceDAO(); ease mocking writing tests</technical_language>

Target:
protected void executeQueryCommand() { VmDeviceDAO dao = DbFacade.getInstance().getVmDeviceDAO(); List<VmDevice> disks = dao.getVmDeviceByVmIdAndType(getParameters().getId(), VmDeviceType.DISK.getName()); for (VmDevice disk: disks) { if (VmPayload.isPayload(disk.getSpecParams())) { VmPayload payload = new VmPayload(VmDeviceType.valueOf(disk.getType().toUpperCase()), disk.getSpecParams()); payload.setType(VmDeviceType.valueOf(disk.getDevice().toUpperCase())); payload.setContent(new String(Base64.decodeBase64(payload.getContent()))); getQueryReturnValue().setReturnValue(payload); } } }
Source:
<code>public static Properties readProperties(final String propertyFile) throws IOException { final Properties props = new Properties(); final InputStream input = Arguments.class.getClassLoader().getResourceAsStream(propertyFile); if (input != null) { props.load(input); return props; } <START> return null; <END> }</code><technical_language>returning null, return props object properties populated. I realize write this, a good change regardless</technical_language>

Target:
public static Properties readProperties(final String propertyFile) throws IOException { final Properties props = new Properties(); final InputStream input = Arguments.class.getClassLoader().getResourceAsStream(propertyFile); if (input != null) { props.load(input); return props; } props.put("version", "N/a"); props.put("build.date", "N/a"); return props; }
Source:
<code>public ComponentDefinition set(@Nullable String ns, @NotNull String key, @NotNull String value) { <START> attributes.put((ns != null ? (ns + ":") : "") + key, value); <END> return this; }</code><technical_language>Nit: (ns != null ? (ns + ":") : "") a local variable, say, "prefix" for readability</technical_language>

Target:
public ComponentDefinition set(@Nullable String ns, @NotNull String key, @NotNull String value) { String prefix = (ns != null ? (ns + ":") : ""); attributes.put(prefix + key, value); return this; }
Source:
<code>public Response getUserStatsAppStatus(@Context final Request request, @PathParam("streams_app") final String appName) { switch (appName) { case "site_statistics": return Response.ok(ImmutableMap.of("running", SiteStatisticsStreamsApplication.getAppStatus().get("running"))).build(); case "user_statistics": return Response.ok(ImmutableMap.of("running", UserStatisticsStreamsApplication.getAppStatus().get("running"))).build(); default: <START> return Response.ok(ImmutableMap.of("running", false)).build(); <END> } }</code><technical_language>more useful return exception if streams app is a valid appName? "site_statistics" app is a typo/capital letter in path param</technical_language>

Target:
public Response getUserStatsAppStatus(@Context final Request request, @PathParam("streams_app") final String appName) { switch (appName) { case "site_statistics": return Response.ok(ImmutableMap.of("running", SiteStatisticsStreamsApplication.getAppStatus().get("running"))).build(); case "user_statistics": return Response.ok(ImmutableMap.of("running", UserStatisticsStreamsApplication.getAppStatus().get("running"))).build(); case "anonymous_events": return Response.ok(ImmutableMap.of("running", AnonymousEventsStreamsApplication.getAppStatus().get("running"))).build(); default: return new SegueErrorResponse(Status.NOT_FOUND, "Invalid streams app name provided.").toResponse(); } }
Source:
<code>public boolean isWeightParam(Layer layer, String key) { <START> return weightKeys(layer).contains(key); <END> }</code><technical_language>do this object creation</technical_language>

Target:
public boolean isWeightParam(Layer layer, String key) { return WEIGHT_KEY.equals(key) || (hasLayerNorm(layer) && GAIN_KEY.equals(key)); }
Source:
<code>protected void eventHandle(ITmfEvent event) { String functionEntryName = functionEntry(event); if (functionEntryName != null) { long timestamp = event.getTimestamp().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); String thread = threadName(event); int quark = ss.getQuarkAbsoluteAndAdd(THREADS, thread, CALL_STACK); ITmfStateValue value = TmfStateValue.newValueString(functionEntryName); <START> try { <END> ss.pushAttribute(timestamp, value, quark); } catch (TimeRangeException e) { e.printStackTrace(); } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } } else { String functionExitName = functionExit(event); if (functionExitName != null) { long timestamp = event.getTimestamp().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); String thread = threadName(event); int quark = ss.getQuarkAbsoluteAndAdd(THREADS, thread, CALL_STACK); try { ss.popAttribute(timestamp, quark); } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (TimeRangeException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } } } }</code><technical_language>1 try here, if inside</technical_language>

Target:
protected void eventHandle(ITmfEvent event) { String functionEntryName = functionEntry(event); try { if (functionEntryName != null) { long timestamp = event.getTimestamp().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); String thread = threadName(event); int quark = ss.getQuarkAbsoluteAndAdd(THREADS, thread, CALL_STACK); ITmfStateValue value = TmfStateValue.newValueString(functionEntryName); ss.pushAttribute(timestamp, value, quark); } else if (functionExit(event) != null) { long timestamp = event.getTimestamp().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); String thread = threadName(event); int quark = ss.getQuarkAbsoluteAndAdd(THREADS, thread, CALL_STACK); ss.popAttribute(timestamp, quark); } } catch (TimeRangeException e) { e.printStackTrace(); } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } }
Source:
<code>public AggregateReduceFunctionsRule(Class<? extends Aggregate> aggregateClass, RelBuilderFactory relBuilderFactory, EnumSet<SqlKind> functionsToReduce) { super(operand(aggregateClass, any()), relBuilderFactory, null); <START> Preconditions.checkArgument(functionsToReduce != null, <END> "Error: expecting a valid handle for AggregateFunctionsToReduce"); this.functionsToReduce = EnumSet.noneOf(SqlKind.class); for (SqlKind function : functionsToReduce) { if (SqlKind.AVG_AGG_FUNCTIONS.contains(function) || SqlKind.COVAR_AVG_AGG_FUNCTIONS.contains(function) || function == SqlKind.SUM) { this.functionsToReduce.add(function); } else { throw new IllegalArgumentException( "AggregateReduceFunctionsRule doesn't support function: " + function.sql); } } }</code><technical_language>Please Preconditions.checkNotNull Objects.requireNonNull. remove 'Error: ' message: is redundant wrongly confused java.lang.Error</technical_language>

Target:
public AggregateReduceFunctionsRule(Class<? extends Aggregate> aggregateClass, RelBuilderFactory relBuilderFactory, EnumSet<SqlKind> functionsToReduce) { super(operand(aggregateClass, any()), relBuilderFactory, null); Objects.requireNonNull(functionsToReduce, "Expecting a valid handle for AggregateFunctionsToReduce"); this.functionsToReduce = EnumSet.noneOf(SqlKind.class); for (SqlKind function : functionsToReduce) { if (SqlKind.AVG_AGG_FUNCTIONS.contains(function) || SqlKind.COVAR_AVG_AGG_FUNCTIONS.contains(function) || function == SqlKind.SUM) { this.functionsToReduce.add(function); } else { throw new IllegalArgumentException( "AggregateReduceFunctionsRule doesn't support function: " + function.sql); } } }
Source:
<code>public boolean isValid(CruiseConfig preprocessedConfig) { <START> preprocessedConfig.getPackageRepositories().validate(new ConfigSaveValidationContext(preprocessedConfig)); <END> PackageRepository packageRepository = preprocessedConfig.getPackageRepositories().find(this.repository.getRepoId()); packageRepository.validate(new ConfigSaveValidationContext(preprocessedConfig.getPackageRepositories())); BasicCruiseConfig.copyErrors(packageRepository, this.repository); return getAllErrors(this.repository).isEmpty(); }</code><technical_language>While validating plugin exists in getPluginConfiguration, some plugin side validations done. Check PackageAsRepositoryExtension#isRepositoryConfigurationValid PackageAsRepositoryExtension#isPackageConfigurationValid</technical_language>

Target:
public boolean isValid(CruiseConfig preprocessedConfig) { PackageRepositories repositories = preprocessedConfig.getPackageRepositories(); this.preprocessedRepository = repositories.find(this.repository.getRepoId()); preprocessedRepository.validate(null); repositories.validate(null); boolean isValidConfiguration = packageRepositoryService.validatePluginId(preprocessedRepository) && packageRepositoryService.validateRepositoryConfiguration(preprocessedRepository); BasicCruiseConfig.copyErrors(preprocessedRepository, this.repository); return getAllErrors(this.repository).isEmpty() && isValidConfiguration && result.isSuccessful(); }
Source:
<code>private Crypter getCrypter() throws EncryptionException { synchronized (crypterSync) { if (crypter != null) { return crypter; } try { <START> String pathToKeys = rootPath.get() + "/WEB-INF/keystore"; <END> crypter = new Crypter(pathToKeys); return crypter; } catch (KeyczarException e) { throw new EncryptionException(e); } } }</code><technical_language>leading "/", builds fail remove it</technical_language>

Target:
private Crypter getCrypter() throws EncryptionException { synchronized (crypterSync) { if (crypter != null) { return crypter; } try { String pathToKeys = rootPath.get() + "WEB-INF/keystore"; crypter = new Crypter(pathToKeys); return crypter; } catch (KeyczarException e) { throw new EncryptionException(e); } } }
Source:
<code>private int <START> handleEnd(@NonNull <END> ITmfEvent event, ITmfStateSystemBuilder ss, long timestamp, String processName) { ITmfStateValue functionExitState = functionExit(event); if (functionExitState != null) { return endHandle(event, ss, timestamp, processName); } return -1; }</code><technical_language>handleEnd calls endHandle... I confuse :p</technical_language>

Target:
private int handleEnd(@NonNull ITmfEvent event, ITmfStateSystemBuilder ss, long timestamp, String processName) { ITmfStateValue functionExitState = functionExit(event); if (functionExitState != null) { String pName = processName; if (pName == null) { int processId = getProcessId(event); pName = (processId == UNKNOWN_PID) ? UNKNOWN : Integer.toString(processId); } String threadName = getThreadName(event); if (threadName == null) { threadName = Long.toString(getThreadId(event)); } int quark = ss.getQuarkAbsoluteAndAdd(PROCESSES, pName, threadName, CALL_STACK); ss.popAttribute(timestamp, quark); return ss.queryOngoingState(quark).unboxInt() + quark; } return -1; }
Source:
<code><START> public MessagingMessageConverterAdapter(Object bean, Method method) { <END> this.bean = bean; this.method = method; this.inferredArgumentType = determineInferredType(); }</code><technical_language>RedundantModifierChecker bad here: class is private</technical_language>

Target:
private MessagingMessageConverterAdapter(Object bean, Method method) { this.bean = bean; this.method = method; this.inferredArgumentType = determineInferredType(); if (logger.isDebugEnabled() && this.inferredArgumentType != null) { logger.debug("Inferred argument type for " + method.toString() + " is " + this.inferredArgumentType); } }
Source:
<code><START> private void transitToNextState() { <END> final State currentState = (State) stateMachine.getCurrentState(); switch (currentState) { case INIT: stateMachine.setState(State.RUN); LOG.log(Level.INFO, String.format("State transition: %s -> %s", State.INIT, State.RUN)); break; case RUN: stateMachine.setState(State.RUN_FINISHING); LOG.log(Level.INFO, String.format("State transition: %s -> %s", State.RUN, State.RUN_FINISHING)); break; case RUN_FINISHING: stateMachine.setState(State.CLEANUP); LOG.log(Level.INFO, String.format("State transition: %s -> %s", State.RUN_FINISHING, State.CLEANUP)); break; case CLEANUP: throw new RuntimeException(String.format("No more transition is allowed after %s state", State.CLEANUP)); default: throw new RuntimeException(String.format("Invalid state: %s", currentState)); } }</code><technical_language>this method synchronized</technical_language>

Target:
private synchronized void transitToNextState() { final State currentState = (State) stateMachine.getCurrentState(); switch (currentState) { case INIT: stateMachine.setState(State.RUN); LOG.log(Level.INFO, String.format("State transition: %s -> %s", State.INIT, State.RUN)); break; case RUN: stateMachine.setState(State.RUN_FINISHING); LOG.log(Level.INFO, String.format("State transition: %s -> %s", State.RUN, State.RUN_FINISHING)); break; case RUN_FINISHING: stateMachine.setState(State.CLEANUP); LOG.log(Level.INFO, String.format("State transition: %s -> %s", State.RUN_FINISHING, State.CLEANUP)); break; case CLEANUP: throw new RuntimeException(String.format("No more transition is allowed after %s state", State.CLEANUP)); default: throw new RuntimeException(String.format("Invalid state: %s", currentState)); } }
Source:
<code>public void addNote(String user, String text) { if (user == null || text == null) { <START> throw new IllegalArgumentException("Note mut have non-null user and text"); <END> } getNotes().add(new Note(user, text)); }</code><technical_language>"mut" -> "must"</technical_language>

Target:
public void addNote(String user, String text) { if (user == null || text == null) { throw new IllegalArgumentException("Note must have non-null user and text"); } getNotes().add(new Note(user, text)); }
Source:
<code>public static void main(String[] args) throws Exception { Builder processingGraphBuilder = Builder.createBuilder(); processingGraphBuilder.newSource(SmartWatchReading::new) .setName("incoming-watch-readings") .reduceByKeyAndWindow( reading -> reading.getJoggerId(), reading -> reading.getFeetRun(), WindowConfig.TumblingTimeWindow(Duration.ofSeconds(10)), (cumulative, incoming) -> cumulative + incoming ) .setName("reduce-to-total-distance-per-jogger") .map(keyWindow -> { long totalFeetRun = keyWindow.getValue(); long startTime = keyWindow.getKey().getWindow().getStartTime(); long endTime = keyWindow.getKey().getWindow().getEndTime(); long timeLengthMillis = endTime - startTime; <START> LOG.info( <END> String.format("Calculating the average speed for jogger %s from time %d to %d", keyWindow.getKey().getKey(), startTime, endTime ) ); float feetPerMinute = totalFeetRun / (float) (timeLengthMillis / 1000); String paceString = new DecimalFormat("#.##").format(feetPerMinute); return new KeyValue<>(keyWindow.getKey().getKey(), paceString); }) .setName("calculate-average-speed") .consume(kv -> { String logMessage = String.format("(runner: %s, avgFeetPerMinute: %s)", kv.getKey(), kv.getValue()); LOG.info(logMessage); }); Config config = new Config(); String topologyName = StreamletUtils.getTopologyName(args); new Runner().run(topologyName, config, processingGraphBuilder); }</code><technical_language>pipe this log operator</technical_language>

Target:
public static void main(String[] args) throws Exception { Builder processingGraphBuilder = Builder.createBuilder(); processingGraphBuilder.newSource(SmartWatchReading::new) .setName("incoming-watch-readings") .reduceByKeyAndWindow( reading -> reading.getJoggerId(), reading -> reading.getFeetRun(), WindowConfig.TumblingTimeWindow(Duration.ofSeconds(10)), (cumulative, incoming) -> cumulative + incoming ) .setName("reduce-to-total-distance-per-jogger") .map(keyWindow -> { long totalFeetRun = keyWindow.getValue(); long startTime = keyWindow.getKey().getWindow().getStartTime(); long endTime = keyWindow.getKey().getWindow().getEndTime(); long timeLengthMillis = endTime - startTime; float feetPerMinute = totalFeetRun / (float) (timeLengthMillis / 1000); String paceString = new DecimalFormat("#.##").format(feetPerMinute); return new KeyValue<>(keyWindow.getKey().getKey(), paceString); }) .setName("calculate-average-speed") .consume(kv -> { String logMessage = String.format("(runner: %s, avgFeetPerMinute: %s)", kv.getKey(), kv.getValue()); LOG.info(logMessage); }); Config config = new Config(); String topologyName = StreamletUtils.getTopologyName(args); new Runner().run(topologyName, config, processingGraphBuilder); }
Source:
<code>public int read(byte[] buf, int offset, int byteCount) throws IOException { Platform.blockGuardOnNetwork(); checkOpen(); ArrayUtils.checkOffsetAndCount(buf.length, offset, byteCount); if (byteCount == 0) { return 0; } synchronized (readLock) { synchronized (stateLock) { if (state == STATE_CLOSED) { throw new SocketException("socket is closed"); } if (DBG_STATE) assertReadableOrWriteableState(); } int ret = NativeCrypto.SSL_read(sslNativePointer, Platform.getFileDescriptor(socket), OpenSSLSocketImpl.this, buf, offset, byteCount, getSoTimeout()); if (ret == -1 && socket != <START> this) { <END> synchronized (stateLock) { if (state == STATE_CLOSED) { throw new SocketException("socket is closed"); } } } return ret; } }</code><technical_language>this compile some toolchains, needs OpenSSLSocketImpl.this</technical_language>

Target:
public int read(byte[] buf, int offset, int byteCount) throws IOException { Platform.blockGuardOnNetwork(); checkOpen(); ArrayUtils.checkOffsetAndCount(buf.length, offset, byteCount); if (byteCount == 0) { return 0; } synchronized (readLock) { synchronized (stateLock) { if (state == STATE_CLOSED) { throw new SocketException("socket is closed"); } if (DBG_STATE) assertReadableOrWriteableState(); } int ret = NativeCrypto.SSL_read(sslNativePointer, Platform.getFileDescriptor(socket), OpenSSLSocketImpl.this, buf, offset, byteCount, getSoTimeout()); if (ret == -1) { synchronized (stateLock) { if (state == STATE_CLOSED) { throw new SocketException("socket is closed"); } } } return ret; } }
Source:
<code><START> public static String getActionUrl(String itUrl,Action action) { <END> String urlName = action.getUrlName(); if(urlName==null) return null; try { if (new URI(urlName).isAbsolute()) { return urlName; } } catch (URISyntaxException x) { Logger.getLogger(Functions.class.getName()).log(Level.WARNING, "Failed to parse URL for {0}: {1}", new Object[] {action, x}); return null; } if(urlName.startsWith("/")) return joinPath(Stapler.getCurrentRequest().getContextPath(),urlName); else return joinPath(Stapler.getCurrentRequest().getContextPath()+'/'+itUrl,urlName); }</code><technical_language>NIT: checkfornull</technical_language>

Target:
public static @CheckForNull String getActionUrl(String itUrl,Action action) { String urlName = action.getUrlName(); if(urlName==null) return null; try { if (new URI(urlName).isAbsolute()) { return urlName; } } catch (URISyntaxException x) { Logger.getLogger(Functions.class.getName()).log(Level.WARNING, "Failed to parse URL for {0}: {1}", new Object[] {action, x}); return null; } if(urlName.startsWith("/")) return joinPath(Stapler.getCurrentRequest().getContextPath(),urlName); else return joinPath(Stapler.getCurrentRequest().getContextPath()+'/'+itUrl,urlName); }
Source:
<code>public void before() throws IOException, InterruptedException { lightblue.getControllerInstance().cleanupMongoCollections("country"); if (lightblue.getControllerInstance().getIdentityManager() != null) { lightblue.changeIdentityManager(null); <START> Thread.sleep(5000); <END> } }</code><technical_language>This sleep is needed if changing identity manager, right? put in changeIdentityManager</technical_language>

Target:
public void before() throws IOException { lightblue.getControllerInstance().cleanupMongoCollections("country"); if (lightblue.getControllerInstance().getIdentityManager() != null) { lightblue.changeIdentityManager(null); } }
Source:
<code>public default GraphTraversal<S, E> property(final VertexProperty.Cardinality cardinality, final Object key, final Object value, final Object... keyValues) { if (null == cardinality) this.asAdmin().getBytecode().addStep(Symbols.property, key, value, keyValues); else this.asAdmin().getBytecode().addStep(Symbols.property, cardinality, key, value, keyValues); Step endStep = this.asAdmin().getEndStep(); while (endStep instanceof AddPropertyStep) { endStep = endStep.getPreviousStep(); } if ((endStep instanceof AddVertexStep || endStep instanceof AddEdgeStep || endStep instanceof AddVertexStartStep || endStep instanceof AddEdgeStartStep) && <START> keyValues.length == 0 && null == cardinality) { <END> ((Mutating) endStep).addPropertyMutations(key, value); } else { this.asAdmin().addStep(new AddPropertyStep(this.asAdmin(), cardinality, key, value)); ((AddPropertyStep) this.asAdmin().getEndStep()).addPropertyMutations(keyValues); } return this; }</code><technical_language>I this part graph's default cardinality (graph().features().vertex().getCardinality(key)) account</technical_language>

Target:
public default GraphTraversal<S, E> property(final VertexProperty.Cardinality cardinality, final Object key, final Object value, final Object... keyValues) { if (null == cardinality) this.asAdmin().getBytecode().addStep(Symbols.property, key, value, keyValues); else this.asAdmin().getBytecode().addStep(Symbols.property, cardinality, key, value, keyValues); Step endStep = this.asAdmin().getEndStep(); while (endStep instanceof AddPropertyStep) { endStep = endStep.getPreviousStep(); } if ((endStep instanceof AddEdgeStep || endStep instanceof AddEdgeStartStep) || ((endStep instanceof AddVertexStep || endStep instanceof AddVertexStartStep) && keyValues.length == 0 && (key instanceof T || (key instanceof String && null == cardinality) || key instanceof Traversal))) { ((Mutating) endStep).addPropertyMutations(key, value); } else { final AddPropertyStep<Element> addPropertyStep = new AddPropertyStep<>(this.asAdmin(), cardinality, key, value); this.asAdmin().addStep(addPropertyStep); addPropertyStep.addPropertyMutations(keyValues); } return this; }
Source:
<code><START> public void deleteService(final Integer nodeId, final InetAddress addr, final String svcName) { <END> final OnmsMonitoredService service = m_monitoredServiceDao.get(nodeId, addr, svcName); if (service != null) { final OnmsIpInterface iface = service.getIpInterface(); final OnmsNode node = iface.getNode(); final boolean lastService = (iface.getMonitoredServices().size() == 1); final boolean lastInterface = (node.getIpInterfaces().size() == 1); final DeleteEventVisitor visitor = new DeleteEventVisitor(m_eventForwarder); iface.removeMonitoredService(service); m_nodeDao.saveOrUpdate(node); m_nodeDao.flush(); service.visit(visitor); if (lastService) { node.removeIpInterface(iface); m_nodeDao.saveOrUpdate(node); m_nodeDao.flush(); iface.visit(visitor); if (lastInterface) { m_nodeDao.delete(node); m_nodeDao.flush(); node.visit(visitor); } } } }</code><technical_language>useful log messages anymore</technical_language>

Target:
public void deleteService(final Integer nodeId, final InetAddress addr, final String svcName) { LOG.debug("deleteService: nodeId={}, addr={}, service={}", nodeId, addr, svcName); final OnmsMonitoredService service = m_monitoredServiceDao.get(nodeId, addr, svcName); if (service != null) { final OnmsIpInterface iface = service.getIpInterface(); final OnmsNode node = iface.getNode(); final boolean lastService = (iface.getMonitoredServices().size() == 1); final boolean lastInterface = (node.getIpInterfaces().size() == 1); final DeleteEventVisitor visitor = new DeleteEventVisitor(m_eventForwarder); iface.removeMonitoredService(service); m_nodeDao.saveOrUpdate(node); m_nodeDao.flush(); service.visit(visitor); if (lastService) { LOG.debug("Deleting interface from node {}", InetAddressUtils.str(iface.getIpAddress()), nodeId); node.removeIpInterface(iface); m_nodeDao.saveOrUpdate(node); m_nodeDao.flush(); iface.visit(visitor); if (lastInterface) { LOG.debug("Deleting node {}", nodeId); m_nodeDao.delete(node); m_nodeDao.flush(); node.visit(visitor); } } } }
Source:
<code>public static boolean containsSearchAnnotations(XClass mappedClass) { <START> List<XClass> hierarchy = ReflectionHelper.createXClassHierarchy( mappedClass ); <END> for ( XClass clazz : hierarchy ) { if ( containsLocalSearchAnnotation( clazz ) ) { return true; } } return false; }</code><technical_language>reason added ReflectionHelper.? remove a method of this class</technical_language>

Target:
public static boolean containsSearchAnnotations(XClass mappedClass) { List<XClass> hierarchy = createXClassHierarchy( mappedClass ); for ( XClass clazz : hierarchy ) { if ( containsLocalSearchAnnotation( clazz ) ) { return true; } } return false; }
Source:
<code>private PerfData test(int characters) { PerfData ret = new PerfData(); String a = DiffTestDataGenerator.generateSequence(characters, 971, 3); String b = DiffTestDataGenerator.generateSequence(characters, 1621, 5); CharArray ac = new CharArray(a); CharArray bc = new CharArray(b); CharCmp cmp = new CharCmp(); MyersDiff<CharArray> myersDiff = null; int cpuTimeChanges = 0; long lastReadout = 0; long interimTime = 0; int repetitions = 0; stopwatch.start(); while (cpuTimeChanges < minCPUTimerTicks && interimTime < longTaskBoundary) { myersDiff = new MyersDiff<CharArray>(cmp, ac, bc); repetitions++; interimTime = stopwatch.readout(); if (interimTime != lastReadout) { cpuTimeChanges++; lastReadout = interimTime; } } ret.runningTime = stopwatch.stop() / repetitions; <START> ret.N = cmp.size(ac) + cmp.size(bc); <END> ret.D = myersDiff.getEdits().size(); return ret; }</code><technical_language>odd ask comparator object size</technical_language>

Target:
private PerfData test(int characters) { PerfData ret = new PerfData(); String a = DiffTestDataGenerator.generateSequence(characters, 971, 3); String b = DiffTestDataGenerator.generateSequence(characters, 1621, 5); CharArray ac = new CharArray(a); CharArray bc = new CharArray(b); CharCmp cmp = new CharCmp(); MyersDiff<CharArray> myersDiff = null; int cpuTimeChanges = 0; long lastReadout = 0; long interimTime = 0; int repetitions = 0; stopwatch.start(); while (cpuTimeChanges < minCPUTimerTicks && interimTime < longTaskBoundary) { myersDiff = new MyersDiff<CharArray>(cmp, ac, bc); repetitions++; interimTime = stopwatch.readout(); if (interimTime != lastReadout) { cpuTimeChanges++; lastReadout = interimTime; } } ret.runningTime = stopwatch.stop() / repetitions; ret.N = ac.size() + bc.size(); ret.D = myersDiff.getEdits().size(); return ret; }
Source:
<code>public IResourceVariant[] getMembers(IProgressMonitor progress) throws IOException { if (members != null) try { return members; } finally { progress.done(); } Repository repo = getRepository(); TreeWalk tw = new TreeWalk(repo); tw.reset(); int nth = tw.addTree(getObjectId()); int iteratorNth = tw.addTree(new FileTreeIterator(repo)); tw.setFilter(new NotIgnoredFilter(iteratorNth)); IProgressMonitor monitor = SubMonitor.convert(progress); monitor.beginTask( NLS.bind(CoreText.GitFolderResourceVariant_fetchingMembers, this), tw.getTreeCount()); List<IResourceVariant> result = new ArrayList<IResourceVariant>(); try { while (tw.next()) { if (monitor.isCanceled()) { throw new OperationCanceledException(); <START> } <END> ObjectId newObjectId = tw.getObjectId(nth); String path = getPath() + "/" + new String(tw.getRawPath()); if (!newObjectId.equals(zeroId())) if (tw.isSubtree()) result.add(new GitFolderResourceVariant(repo, newObjectId, path)); else result.add(new GitBlobResourceVariant(repo, newObjectId, path)); monitor.worked(1); } members = result.toArray(new IResourceVariant[result.size()]); return members; } finally { monitor.done(); } }</code><technical_language>prefer single statement if's brackets</technical_language>

Target:
public IResourceVariant[] getMembers(IProgressMonitor progress) throws IOException { if (members != null) try { return members; } finally { progress.done(); } Repository repo = getRepository(); TreeWalk tw = new TreeWalk(repo); tw.reset(); int nth = tw.addTree(getObjectId()); int iteratorNth = tw.addTree(new FileTreeIterator(repo)); tw.setFilter(new NotIgnoredFilter(iteratorNth)); IProgressMonitor monitor = SubMonitor.convert(progress); monitor.beginTask( NLS.bind(CoreText.GitFolderResourceVariant_fetchingMembers, this), tw.getTreeCount()); List<IResourceVariant> result = new ArrayList<IResourceVariant>(); try { while (tw.next()) { if (monitor.isCanceled()) throw new OperationCanceledException(); ObjectId newObjectId = tw.getObjectId(nth); String path = getPath() + "/" + new String(tw.getRawPath()); if (!newObjectId.equals(zeroId())) if (tw.isSubtree()) result.add(new GitFolderResourceVariant(repo, newObjectId, path)); else result.add(new GitBlobResourceVariant(repo, newObjectId, path)); monitor.worked(1); } members = result.toArray(new IResourceVariant[result.size()]); return members; } finally { monitor.done(); } }
Source:
<code>public void setUp() { MockitoAnnotations.initMocks(this); <START> caseActionService = new CaseActionServiceImpl(commcareCaseService); <END> eventHandler = new CaseEventHandler(caseActionService); Map<String, String> caseProperties = new HashMap<>(); caseProperties.put("field1", "value1"); caseProperties.put("field2", "value2"); Map<String, Object> createCaseParams = new HashMap<>(); createCaseParams.put(EventDataKeys.CASE_TYPE, CASE_TYPE); createCaseParams.put(EventDataKeys.OWNER_ID, OWNER_ID); createCaseParams.put(EventDataKeys.CASE_NAME, CASE_NAME); createCaseParams.put(EventDataKeys.FIELD_VALUES, caseProperties); createCaseEvent = new MotechEvent(EventSubjects.CREATE_CASE + ".config1", createCaseParams); Map<String, Object> updateCaseParams = new HashMap<>(); updateCaseParams.put(EventDataKeys.CASE_ID, CASE_ID); updateCaseParams.put(EventDataKeys.OWNER_ID, OWNER_ID); updateCaseParams.put(EventDataKeys.FIELD_VALUES, caseProperties); updateCaseEvent = new MotechEvent(EventSubjects.UPDATE_CASE + ".config1", updateCaseParams); }</code><technical_language>this a mock (?)</technical_language>

Target:
public void setUp() { MockitoAnnotations.initMocks(this); eventHandler = new CaseEventHandler(caseActionService); Map<String, String> caseProperties = new HashMap<>(); caseProperties.put("field1", "value1"); caseProperties.put("field2", "value2"); Map<String, Object> createCaseParams = new HashMap<>(); createCaseParams.put(EventDataKeys.CASE_TYPE, CASE_TYPE); createCaseParams.put(EventDataKeys.OWNER_ID, OWNER_ID); createCaseParams.put(EventDataKeys.CASE_NAME, CASE_NAME); createCaseParams.put(EventDataKeys.FIELD_VALUES, caseProperties); createCaseEvent = new MotechEvent(EventSubjects.CREATE_CASE + '.' + CONFIG_NAME, createCaseParams); Map<String, Object> updateCaseParams = new HashMap<>(); updateCaseParams.put(EventDataKeys.CASE_ID, CASE_ID); updateCaseParams.put(EventDataKeys.OWNER_ID, OWNER_ID); updateCaseParams.put(EventDataKeys.FIELD_VALUES, caseProperties); updateCaseEvent = new MotechEvent(EventSubjects.UPDATE_CASE + '.' + CONFIG_NAME, updateCaseParams); }
Source:
<code>public RankedBitVectorImpl(long initialSize, int countBlockSize, int findPositionBlockSize) { if (countBlockSize < 1) { throw new IllegalArgumentException( "Block size must be a positive number. The received value was: " + countBlockSize + "."); <START> } <END> if (findPositionBlockSize < 0x40) { throw new IllegalArgumentException("Block size is too small: " + findPositionBlockSize + ". The minimum is " + 0x40 + "."); } this.bitVector = new BitVectorImpl(initialSize); this.countBitsArray = new CountBitsArray(this.bitVector, countBlockSize); this.findPositionOfFalse = new FindPositionArray(this.bitVector, false, findPositionBlockSize); this.findPositionOfTrue = new FindPositionArray(this.bitVector, true, findPositionBlockSize); }</code><technical_language>This check done constructor of CountBitsArray. Moreover, need a blocksize of 64 for reason in case of FindPositionArray</technical_language>

Target:
public RankedBitVectorImpl(long initialSize, int countBlockSize, int findPositionBlockSize) { this.bitVector = new BitVectorImpl(initialSize); this.countBitsArray = new CountBitsArray(this.bitVector, countBlockSize); this.findPositionOfFalse = new FindPositionArray(this.bitVector, false, findPositionBlockSize); this.findPositionOfTrue = new FindPositionArray(this.bitVector, true, findPositionBlockSize); }
Source:
<code>private void parse(boolean isSecure) throws URIException, HttpMalformedHeaderException { mIsSecure = isSecure; Matcher matcher = patternRequestLine.matcher(mStartLine); if (!matcher.find()) { mMalformedHeader = true; throw new HttpMalformedHeaderException("Failed to find pattern " + patternRequestLine + " in: " + mStartLine); } mMethod = matcher.group(1); String sUri = matcher.group(2); mVersion = matcher.group(3); if (!mVersion.equalsIgnoreCase(HTTP09) && !mVersion.equalsIgnoreCase(HTTP10) && !mVersion.equalsIgnoreCase(HTTP11)) { mMalformedHeader = true; throw new HttpMalformedHeaderException("Unexpected version: " + mVersion); } if (mMethod.equalsIgnoreCase(CONNECT)) { String hostHeader; <START> hostHeader = sUri; <END> parseHostName(hostHeader); mUri = parseURI(mHostName); } else { mUri = parseURI(sUri); if (mUri.getScheme() == null || mUri.getScheme().equals("")) { mUri = new URI(HTTP + "://" + getHeader(HOST) + mUri.toString(), true); } if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) { mUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true); } if (mUri.getScheme().equalsIgnoreCase(HTTPS)) { setSecure(true); } mHostName = mUri.getHost(); setHostPort(mUri.getPort()); } }</code><technical_language>do this line? String hostHeader = sUri;</technical_language>

Target:
private void parse(boolean isSecure) throws URIException, HttpMalformedHeaderException { mIsSecure = isSecure; Matcher matcher = patternRequestLine.matcher(mStartLine); if (!matcher.find()) { mMalformedHeader = true; throw new HttpMalformedHeaderException("Failed to find pattern " + patternRequestLine + " in: " + mStartLine); } mMethod = matcher.group(1); String sUri = matcher.group(2); mVersion = matcher.group(3); if (!mVersion.equalsIgnoreCase(HTTP09) && !mVersion.equalsIgnoreCase(HTTP10) && !mVersion.equalsIgnoreCase(HTTP11)) { mMalformedHeader = true; throw new HttpMalformedHeaderException("Unexpected version: " + mVersion); } if (mMethod.equalsIgnoreCase(CONNECT)) { parseHostName(sUri); mUri = parseURI(mHostName); } else { mUri = parseURI(sUri); if (mUri.getScheme() == null || mUri.getScheme().equals("")) { mUri = new URI(HTTP + "://" + getHeader(HOST) + mUri.toString(), true); } if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) { mUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true); } if (mUri.getScheme().equalsIgnoreCase(HTTPS)) { setSecure(true); } mHostName = mUri.getHost(); setHostPort(mUri.getPort()); } }
Source:
<code>public VoltCompiler(boolean standaloneCompiler, boolean isXDCR) { this.standaloneCompiler = standaloneCompiler; this.m_isXDCR = isXDCR; <START> cachedAddedClasses.clear(); <END> }</code><technical_language>cache is reset for main compile functions. change behave differently</technical_language>

Target:
public VoltCompiler(boolean standaloneCompiler, boolean isXDCR) { this.standaloneCompiler = standaloneCompiler; this.m_isXDCR = isXDCR; m_cachedAddedClasses.clear(); }
Source:
<code>private Integer deserializeValue(Map<String, Object> entry, String curveKey, int conversionRate) { Map<String, Double> parameters = (Map<String, Double>) entry.get(curveKey); if (parameters == null) { return null; } Double average = parameters.get(VdsProperties.HOST_QOS_AVERAGE); <START> return (average == null) ? null : (int) (average / conversionRate); <END> }</code><technical_language>is get a non-integer value? Is a set host? If is, more accurate save qos parameters HostNetworkQos doubles. saving integer in bits displaying user in Mb. I understand benefit of sending/receiving bits doubles api vdsm</technical_language>

Target:
private Integer deserializeValue(Map<String, Object> entry, String curveKey, int conversionRate) { Map<String, Integer> parameters = (Map<String, Integer>) entry.get(curveKey); if (parameters == null) { return null; } Integer average = parameters.get(VdsProperties.HOST_QOS_AVERAGE); return (average == null) ? null : (average / conversionRate); }
Source:
<code>private void finish() { rBuff = null ; <START> nextIdx = -99 ; <END> slot = null ; }</code><technical_language>nice call this out a constant, NO_NEXT_INDEX like</technical_language>

Target:
private void finish() { rBuff = null ; nextIdx = END ; slot = null ; }
Source:
<code>public Page<UserImpl> getAll(int maxItems, long skipCount) throws ServerException { checkArgument(maxItems >= 0, "The number of items to return can't be negative."); checkArgument(skipCount >= 0, "The number of items to skip can't be negative."); if (skipCount > Integer.MAX_VALUE) { <START> throw new IllegalArgumentException("Skip count parameter must not be more than " + Integer.MAX_VALUE); <END> } try { final List<UserImpl> list = managerProvider.get() .createNamedQuery("User.getAll", UserImpl.class) .setMaxResults(maxItems) .setFirstResult((int)skipCount) .getResultList() .stream() .map(JpaUserDao::erasePassword) .collect(toList()); return new Page<>(list, skipCount, maxItems, getTotalCount()); } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }</code><technical_language>WDYT Preconditions#checkArgument here</technical_language>

Target:
public Page<UserImpl> getAll(int maxItems, long skipCount) throws ServerException { checkArgument(maxItems >= 0, "The number of items to return can't be negative."); checkArgument(skipCount >= 0 && skipCount <= Integer.MAX_VALUE, "The number of items to skip can't be negative or greater than " + Integer.MAX_VALUE); try { final List<UserImpl> list = managerProvider.get() .createNamedQuery("User.getAll", UserImpl.class) .setMaxResults(maxItems) .setFirstResult((int)skipCount) .getResultList() .stream() .map(JpaUserDao::erasePassword) .collect(toList()); return new Page<>(list, skipCount, maxItems, getTotalCount()); } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }