auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public NetSocket resume() { pause = false; if (pendingData != null) { <START> if (dataHandler != null) { <END> if (!pendingData.isEmpty()) { for (;;) { final Buffer buf = pendingData.poll(); if (buf == null) { break; } vertx.runOnContext(new VoidHandler() { @Override protected void handle() { handleDataReceived(buf); } }); } } } else { pendingData.clear(); } } doResume(); return this; }</code><technical_language>I check if dataHandler is null here. Consider case. pending buffers in queue user sets datahandler null user calls resume - this drops data! user sets datahandlee handler data handler called data dropped. I check if dataHandler is null in handleDataReceived method</technical_language>

Target:
public NetSocket resume() { if (!paused) { return this; } paused = false; if (pendingData != null) { for (;;) { final Buffer buf = pendingData.poll(); if (buf == null) { break; } vertx.runOnContext(new VoidHandler() { @Override protected void handle() { handleDataReceived(buf); } }); } } doResume(); return this; }
Source:
<code><START> protected void deactivate() { <END> if (pollThreadTask != null && !pollThreadTask.isDone()) { logger.debug("Cancelling WatchdogServiceImpl task ..."); pollThreadTask.cancel(true); logger.info("WatchdogServiceImpl task cancelled? = {}", pollThreadTask.isDone()); pollThreadTask = null; } if (this.pollThreadExecutor != null) { logger.debug("Terminating WatchdogServiceImpl Thread ..."); this.pollThreadExecutor.shutdownNow(); try { this.pollThreadExecutor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.warn("Interrupted", e); } logger.info("WatchdogServiceImpl Thread terminated? - {}", this.pollThreadExecutor.isTerminated()); this.pollThreadExecutor = null; } criticalServiceList = null; if (watchdogAction.equals(WATCHDOG_ACTION_KURA_RESTART)) { new Thread() { @Override public void run() { stopKura(); } }.start(); } }</code><technical_language>I split this separate methods in order segregate actions taken</technical_language>

Target:
protected void deactivate() { cancelPollTask(); shutdownPollExecutor(); refreshWatchdog(); }
Source:
<code>public boolean supportsPath(final Path path) { <START> boolean anyResourceTypeMatch = this.getResourceTypeDefinitionList() <END> .stream() .anyMatch(resourceTypeDefinition -> resourceTypeDefinition.accept(convertPath(path))); return !(isFolder(path) || isHidden(path)) && anyResourceTypeMatch; }</code><technical_language>If refactored this one-liner a method call, call return statement advantage of short-circuiting. Currently querying type definitions, if path is a folder is hidden</technical_language>

Target:
public boolean supportsPath(final Path path) { return !(this.isFolder(path) || this.isHidden(path)) && this.isSupportedByAnyResourceType(path); }
Source:
<code>public Action<?, ?> extendMetadataAction() { return new AbstractUpscaleAction<>(StackEvent.class) { private final Set<InstanceStatus> unusedInstanceStatuses = Set.of(InstanceStatus.CREATE_REQUESTED, InstanceStatus.CREATED); @Override protected void doExecute(StackContext context, StackEvent payload, Map<Object, Object> variables) { Stack stack = context.getStack(); stackUpdater.updateStackStatus(stack.getId(), DetailedStackStatus.UPSCALE_IN_PROGRESS, "Extending metadata"); <START> List<CloudInstance> allKnownInstances = cloudStackConverter.buildInstances(context.getStack()); List<Resource> resources = resourceService.findAllByStackId(context.getStack().getId()); <END> List<CloudResource> cloudResources = resourceConverter.convert(resources); List<CloudInstance> newCloudInstances = allKnownInstances.stream() .filter(this::isNewInstances) .collect(Collectors.toList()); CollectMetadataRequest request = new CollectMetadataRequest(context.getCloudContext(), context.getCloudCredential(), cloudResources, newCloudInstances, allKnownInstances); sendEvent(context, request.selector(), request); } private boolean isNewInstances(CloudInstance cloudInstance) { return unusedInstanceStatuses.contains(cloudInstance.getTemplate().getStatus()); } }; }</code><technical_language>nit: stack instead of context.getStack()</technical_language>

Target:
public Action<?, ?> extendMetadataAction() { return new AbstractUpscaleAction<>(StackEvent.class) { private final Set<InstanceStatus> unusedInstanceStatuses = Set.of(InstanceStatus.CREATE_REQUESTED, InstanceStatus.CREATED); @Override protected void doExecute(StackContext context, StackEvent payload, Map<Object, Object> variables) { Stack stack = context.getStack(); stackUpdater.updateStackStatus(stack.getId(), getInProgressStatus(variables), "Extending metadata"); List<CloudInstance> allKnownInstances = cloudStackConverter.buildInstances(stack); List<Resource> resources = resourceService.findAllByStackId(stack.getId()); List<CloudResource> cloudResources = resourceConverter.convert(resources); List<CloudInstance> newCloudInstances = allKnownInstances.stream() .filter(this::isNewInstances) .collect(Collectors.toList()); CollectMetadataRequest request = new CollectMetadataRequest(context.getCloudContext(), context.getCloudCredential(), cloudResources, newCloudInstances, allKnownInstances); sendEvent(context, request.selector(), request); } private boolean isNewInstances(CloudInstance cloudInstance) { return unusedInstanceStatuses.contains(cloudInstance.getTemplate().getStatus()); } }; }
Source:
<code>static String getHighestMessageLevel(Collection<MessagesContainer.AcceptedMessage> messages) { return messages. stream(). map(MessagesContainer.AcceptedMessage::getMessageLevel). <START> max(VALUE_COMPARATOR). <END> map(Message.MessageLevel::toString). orElse(null); }</code><technical_language>qualify class name name a out of context</technical_language>

Target:
static String getHighestMessageLevel(Collection<MessagesContainer.AcceptedMessage> messages) { return messages. stream(). map(MessagesContainer.AcceptedMessage::getMessageLevel). max(Message.MessageLevel.VALUE_COMPARATOR). map(Message.MessageLevel::toString). orElse(null); }
Source:
<code>public void addMessageHandler(final Class<? extends Message> messageType, final MessageHandler handler) { if (messageType == null) { <START> throw new IllegalArgumentException("Cannot add handler for null message type"); <END> } if (handler == null) { throw new IllegalArgumentException("Cannot add null handler"); } synchronized (messageHandlers) { messageHandlers.computeIfAbsent(messageType, key -> new LinkedList<>()).add(handler); } }</code><technical_language>I noticed this places, this NPE instead of IAE</technical_language>

Target:
public void addMessageHandler(final Class<? extends Message> messageType, final MessageHandler handler) { if (messageType == null) { throw new IllegalArgumentException("Cannot add handler for null message type"); } if (handler == null) { throw new IllegalArgumentException("Cannot add null handler"); } LOGGER.log(Level.FINEST, "Adding message handler {0} for message type: {1}", new Object[] {handler, messageType}); synchronized (messageHandlers) { messageHandlers.computeIfAbsent(messageType, key -> new LinkedList<>()).add(handler); } }
Source:
<code>public void setGeoJsonLayer(AirMapGeoJsonLayer layer) { <START> if (!isInitialized()) { <END> return; } mapInterface.setGeoJsonLayer(layer); }</code><technical_language>instead of dropping this exception</technical_language>

Target:
public void setGeoJsonLayer(AirMapGeoJsonLayer layer) throws JSONException { if (!isInitialized()) { return; } mapInterface.setGeoJsonLayer(layer); }
Source:
<code>public Builder sourceType(Class<? extends CommandSource> senderType, boolean deep) { this.sourceType = senderType; <START> sourceTypeDeep = deep; <END> return this; }</code><technical_language>Qualify this</technical_language>

Target:
public Builder sourceType(Class<? extends CommandSource> senderType, boolean deep) { checkNotNull(senderType, "sender type"); this.sourceType = senderType; this.sourceTypeDeep = deep; return this; }
Source:
<code>private Map.Entry<String, String> toEntry(Method m) { String name = m.getName() .substring(1); String help; try { Class<?> c = m.getDeclaringClass(); Field field = c.getField(m.getName() + "Help"); help = (String) field.get(null); } catch (Exception e) { help = ""; } String h = help; <START> return new Map.Entry<String, String>() { <END> @Override public String getKey() { return name; } @Override public String getValue() { return h; } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } }; }</code><technical_language><LINK_0> ? need write Map.Entry implementations</technical_language>

Target:
private Map.Entry<String, String> toEntry(Method m) { String name = m.getName() .substring(1); String help; try { Class<?> c = m.getDeclaringClass(); Field field = c.getField(m.getName() + "Help"); help = (String) field.get(null); } catch (Exception e) { help = ""; } String h = help; return new AbstractMap.SimpleImmutableEntry<String, String>(name, h); }
Source:
<code>public DynamicPeriodicTrigger(long period, TimeUnit timeUnit) { Assert.isTrue(period >= 0, "period must not be negative"); this.timeUnit = (timeUnit != null) ? timeUnit : TimeUnit.MILLISECONDS; <START> this.period = this.timeUnit.toMillis(period); <END> }</code><technical_language>correct - this a confusing - passed-in time unit, converting millis. timeunit is of for initial delay. Suggest moving TU setInitialDelay, remove altogether work Millis</technical_language>

Target:
public DynamicPeriodicTrigger(long period, TimeUnit timeUnit) { Assert.isTrue(period >= 0, "period must not be negative"); Assert.notNull(timeUnit, "timeUnit must not be null"); this.timeUnit = timeUnit; this.period = this.timeUnit.toMillis(period); }
Source:
<code>private static int getCurrentMilestoneIndex(List<TurboMilestone> allMilestones) { int currentIndex = -1; for (TurboMilestone checker : allMilestones) { if (checker.isOpen()) { if (checker.getDueDate().isPresent() && checker.getDueDate().get().isBefore(LocalDate.now()) && checker.getOpenIssues() == 0) { continue; } currentIndex = allMilestones.indexOf(checker); <START> break; <END> } } if (currentIndex == -1 && allMilestones.size() > 0) { currentIndex = allMilestones.size() - 1; } return currentIndex; }</code><technical_language>a bit strange break continue in here. java if (allMilestones.isEmpty()) { return Optional.empty(); } int index = 0; for (TurboMilestone milestone : allMilestones) { boolean eligible = ...; if (eligible) { return index; } index++; } return Optional.of(allMilestones.size() - 1);</technical_language>

Target:
private static Optional<Integer> getCurrentMilestoneIndex(List<TurboMilestone> allMilestones) { if (allMilestones.isEmpty()) { return Optional.empty(); } int currentIndex = 0; for (TurboMilestone checker : allMilestones) { boolean overdue = checker.getDueDate().isPresent() && checker.getDueDate().get().isBefore(LocalDate.now()); boolean relevant = !(overdue && (checker.getOpenIssues() == 0)); if (checker.isOpen() && relevant) { return Optional.of(currentIndex); } currentIndex++; } return Optional.of(allMilestones.size() - 1); }
Source:
<code>public Action[] getActions(boolean context) { List<Action> actionsList = new ArrayList<>(); actionsList.addAll(Arrays.asList(super.getActions(true))); actionsList.add(new FileSystemDetailsAction(content)); <START> if (!this.getDirectoryBrowseMode()) { <END> actionsList.add(new ViewContextAction(Bundle.FileNode_getActions_viewFileInDir_text(), this)); actionsList.add(null); } actionsList.add(new NewWindowViewAction(Bundle.FileNode_getActions_viewInNewWin_text(), this)); actionsList.add(new ExternalViewerAction(Bundle.FileNode_getActions_openInExtViewer_text(), this)); actionsList.add(ViewFileInTimelineAction.createViewFileAction(getContent())); actionsList.add(null); actionsList.add(ExtractAction.getInstance()); actionsList.add(new HashSearchAction(Bundle.FileNode_getActions_searchFilesSameMD5_text(), this)); actionsList.add(null); actionsList.add(AddContentTagAction.getInstance()); final Collection<AbstractFile> selectedFilesList = new HashSet<>(Utilities.actionsGlobalContext().lookupAll(AbstractFile.class)); if (1 == selectedFilesList.size()) { actionsList.add(DeleteFileContentTagAction.getInstance()); } actionsList.addAll(ContextMenuExtensionPoint.getActions()); return actionsList.toArray(new Action[actionsList.size()]); }</code><technical_language>this move some common place AbstractFsContentNode, is supe type of of node classes</technical_language>

Target:
public Action[] getActions(boolean context) { List<Action> actionsList = new ArrayList<>(); actionsList.addAll(Arrays.asList(super.getActions(true))); if (!this.getDirectoryBrowseMode()) { actionsList.add(new ViewContextAction(Bundle.FileNode_getActions_viewFileInDir_text(), this)); actionsList.add(null); } actionsList.add(new NewWindowViewAction(Bundle.FileNode_getActions_viewInNewWin_text(), this)); actionsList.add(new ExternalViewerAction(Bundle.FileNode_getActions_openInExtViewer_text(), this)); actionsList.add(ViewFileInTimelineAction.createViewFileAction(getContent())); actionsList.add(null); actionsList.add(ExtractAction.getInstance()); actionsList.add(new HashSearchAction(Bundle.FileNode_getActions_searchFilesSameMD5_text(), this)); actionsList.add(null); actionsList.add(AddContentTagAction.getInstance()); final Collection<AbstractFile> selectedFilesList = new HashSet<>(Utilities.actionsGlobalContext().lookupAll(AbstractFile.class)); if (1 == selectedFilesList.size()) { actionsList.add(DeleteFileContentTagAction.getInstance()); } actionsList.addAll(ContextMenuExtensionPoint.getActions()); return actionsList.toArray(new Action[actionsList.size()]); }
Source:
<code>public static String getRedirectUriServerName(String name) { try { if <START> (InetAddress.getByName(name) instanceof <END> Inet6Address) { name = String.format("[%s]", name); } } catch (UnknownHostException ex) { log.error("Error getting redirect uri server name, unknown hostname : %s" , name); log.debug("Exception", ex); } return name; }</code><technical_language>InetAddress.getByName(name) resolves name address represents. in case of name is a host name resolves IPv6 address host name wrapped brackets part of URI. of do job here: * sun.net.util.IPAddressUtil.isIPv6LiteralAddress(name) * org.apache.http.conn.util.isIPv6Address(name)</technical_language>

Target:
public static String getRedirectUriServerName(String name) { return InetAddressUtils.isIPv6Address(name) ? String.format("[%s]", name) : name; }
Source:
<code>public void tryOpenUri(URI uri) { if (hostServices != null) { hostServices.showDocument(uri.toString()); } else if (desktop != null) { try { desktop.browse(uri); } catch (IOException e) { <START> logger.warn("Could not open URI with 'Browse' action", e); <END> } } }</code><technical_language>optionally: suggestion logger.warn("Unable open URI 'Browse' action", e);</technical_language>

Target:
public void tryOpenUri(URI uri) { if (hostServices != null) { hostServices.showDocument(uri.toString()); } else if (desktop != null) { try { desktop.browse(uri); } catch (IOException e) { logger.warn("Unable to open URI with 'Browse' action", e); } } }
Source:
<code>public void onOutgoingEmergencySms(EmergencyNumber emergencyNumber) { <START> Log.i(TAG, <END> "onOutgoingEmergencySms: emergencyNumber=" + emergencyNumber); mOnOutgoingSmsEmergencyNumberChanged = emergencyNumber; }</code><technical_language>is this specific different? 1) log 2) lock</technical_language>

Target:
public void onOutgoingEmergencySms(EmergencyNumber emergencyNumber) { synchronized (mLock) { mOnOutgoingSmsEmergencyNumberChanged = emergencyNumber; mLock.notify(); } }
Source:
<code>public void validate() { if (hasLegacyConfiguration()) { if (isSizeBounded() || isCountBounded()) { <START> CONFIG.ignoredMemoryDeprecatedSettings("size", memoryStorageConfigurationBuilder.size()); <END> } else { translate(); } } if (isSizeBounded() && isCountBounded()) { throw CONFIG.cannotProvideBothSizeAndCount(); } checkBinaryRequirement(); EvictionStrategy strategy = evictionStrategy(); if (!strategy.isEnabled()) { if (isSizeBounded() || isCountBounded()) { EvictionStrategy newStrategy = EvictionStrategy.REMOVE; evictionStrategy(newStrategy); if (isCountBounded()) { CONFIG.debugf("Max entries configured (%d) without eviction strategy. Eviction strategy overridden to %s", maxCount(), newStrategy); } else { CONFIG.debugf("Max size configured (%d) without eviction strategy. Eviction strategy overridden to %s", maxSize(), newStrategy); } } else if (getBuilder().persistence().passivation() && strategy != EvictionStrategy.MANUAL && !getBuilder().template()) { CONFIG.passivationWithoutEviction(); } } else { if (!isCountBounded() && !isSizeBounded()) { throw CONFIG.invalidEvictionSize(); } if (strategy.isExceptionBased()) { TransactionConfigurationBuilder transactionConfiguration = getBuilder().transaction(); org.infinispan.transaction.TransactionMode transactionMode = transactionConfiguration.transactionMode(); if (transactionMode == null || !transactionMode.isTransactional() || transactionConfiguration.useSynchronization() || transactionConfiguration.use1PcForAutoCommitTransactions()) { throw CONFIG.exceptionBasedEvictionOnlySupportedInTransactionalCaches(); } } } }</code><technical_language>I throw exception if both, remove ambiguity</technical_language>

Target:
public void validate() { }
Source:
<code><START> IonSqlQueryBuilder(TypeManager typeManager) <END> { this.typeManager = requireNonNull(typeManager, "typeManager is null"); }</code><technical_language>methods public part of public API of class. If want restrict access class, class package private</technical_language>

Target:
public IonSqlQueryBuilder(TypeManager typeManager) { this.typeManager = requireNonNull(typeManager, "typeManager is null"); }
Source:
<code><START> private boolean verifyInstructorCanViewPhoto(InstructorAttributes instructor, String section) { <END> if (!instructor.isAllowedForPrivilege(section, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS)) { return false; } return true; }</code><technical_language>This is supposed a void throwing, calling effect</technical_language>

Target:
private void verifyInstructorCanViewPhoto(InstructorAttributes instructor, String section) { if (!instructor.isAllowedForPrivilege(section, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS)) { throw new UnauthorizedAccessException("Instructor does not have enough privileges to view the photo"); } }
Source:
<code>protected void write(final IFile file, final InputStream contents, final boolean force, IProgressMonitor monitor) throws CoreException { assertNotNull("file cannot be null", file); class WriteFileContents implements IWorkspaceRunnable { @Override public void run(IProgressMonitor jobMonitor) throws CoreException { int flags = force ? IResource.FORCE : IResource.NONE; IFileStore store = ((Resource) file).getStore(); assertNotNull("file store cannot be null", store); IFileInfo info = store.fetchInfo(); assertNotNull("file info cannot be null for file " + file, info); FileSystemResourceManager localManager = getLocalManager(); assertNotNull("file system resource manager cannot be null", localManager); localManager.write(file, contents, info, flags, false, jobMonitor); } } <START> getWorkspace().run(new <END> WriteFileContents(), null); }</code><technical_language>getWorkspace() is null? java.lang.NullPointerException org.eclipse.core.tests.internal.localstore.FileSystemResourceManagerTest.write(FileSystemResourceManagerTest.java:481) org.eclipse.core.tests.internal.localstore.FileSystemResourceManagerTest.testWriteFile(FileSystemResourceManagerTest.java:380)</technical_language>

Target:
protected void write(final IFile file, final InputStream contents, final boolean force, IProgressMonitor monitor) throws CoreException { assertNotNull("file cannot be null", file); class WriteFileContents implements IWorkspaceRunnable { @Override public void run(IProgressMonitor jobMonitor) throws CoreException { int flags = force ? IResource.FORCE : IResource.NONE; IFileStore store = ((Resource) file).getStore(); assertNotNull("file store cannot be null", store); IFileInfo info = store.fetchInfo(); assertNotNull("file info cannot be null for file " + file, info); FileSystemResourceManager localManager = getLocalManager(); assertNotNull("file system resource manager cannot be null", localManager); localManager.write(file, contents, info, flags, false, jobMonitor); } } IWorkspace workspace = getWorkspace(); assertNotNull("workspace cannot be null", workspace); workspace.run(new WriteFileContents(), null); }
Source:
<code>public void render(Response response) { CharSequence js = getJavaScript(); if (Strings.isEmpty(js) == false) { JavaScriptUtils.writeJavaScript(response, <START> "var f = function() {" + js + ";};\nif ('loaded' === document.readyState) f(); else window.addEventListener('load', f);"); <END> } }</code><technical_language>Is loaded correct state for sure? <LINK_0> "complete" is mentioned. I remember some other pitfalls readyState for some browsers. This german site mentions "loaded" is in IE. <LINK_1></technical_language>

Target:
public void render(Response response) { CharSequence js = getJavaScript(); if (Strings.isEmpty(js) == false) { JavaScriptUtils.writeJavaScript(response, "(function() {var f = function() {" + js + ";};\nif ('complete' === document.readyState) f(); else window.addEventListener('load', f);})();"); } }
Source:
<code>private static ImmutableList<StructMember> convertDs3Elements(final ImmutableList<Ds3Element> elementsList, final ImmutableSet<String> enumNames) throws ParseException { final ImmutableList.Builder<StructMember> builder = ImmutableList.builder(); for (final Ds3Element currentElement : elementsList) { <START> if (currentElement.getName().equals("StorageClass")) continue; END> builder.add(new StructMember(C_TypeHelper.convertDs3ElementType(currentElement, enumNames), StructHelper.getNameUnderscores(currentElement.getName()))); } return builder.build(); }</code><technical_language>including this property in java autogen? include if value</technical_language>

Target:
private static ImmutableList<StructMember> convertDs3Elements(final ImmutableList<Ds3Element> elementsList, final ImmutableSet<String> enumNames) throws ParseException { final ImmutableList.Builder<StructMember> builder = ImmutableList.builder(); for (final Ds3Element currentElement : elementsList) { builder.add(new StructMember( C_TypeHelper.convertDs3ElementType(currentElement, enumNames), StructHelper.getNameUnderscores(currentElement.getName()))); } return builder.build(); }
Source:
<code>public CacheConfigurationBuilder<K, V> withService(ServiceConfiguration<?, ?> config) { @SuppressWarnings("unchecked") Collection<? extends ServiceConfiguration<?, ?>> others = getServices((Class<? extends ServiceConfiguration<?, ?>>) config.getClass()); CacheConfigurationBuilder<K, V> otherBuilder = new CacheConfigurationBuilder<>(this); <START> for (ServiceConfiguration<?, ?> other : others) { <END> if (!other.compatibleWith(config)) { otherBuilder.serviceConfigurations.remove(other); } } otherBuilder.serviceConfigurations.add(config); return otherBuilder; }</code><technical_language>direct unit testing of withService updateServices . appears a fair amount of indirect testing of withService updateServices coverage</technical_language>

Target:
public CacheConfigurationBuilder<K, V> withService(ServiceConfiguration<?, ?> config) { CacheConfigurationBuilder<K, V> otherBuilder = new CacheConfigurationBuilder<>(this); otherBuilder.serviceConfigurations.removeIf(other -> !other.compatibleWith(config) || !config.compatibleWith(other)); otherBuilder.serviceConfigurations.add(config); return otherBuilder; }
Source:
<code>public Response getAllServices(@HeaderParam(HttpHeaders.IF_NONE_MATCH) String ifNoneMatch, @HeaderParam(HttpHeaders.ACCEPT_ENCODING) String acceptEncoding) { CachedBaragonState state = stateCache.getState(); String verisonString = Integer.toString(state.getVersion()); <START> System.out.println(ifNoneMatch); <END> if (ifNoneMatch != null && ifNoneMatch.equals(verisonString.trim())) { return Response.notModified() .header(HttpHeaders.ETAG, state.getVersion()) .build(); } ResponseBuilder builder = Response.ok(); final byte[] entity; if (acceptEncoding != null && acceptEncoding.contains("gzip")) { builder.header(HttpHeaders.CONTENT_ENCODING, "gzip"); entity = state.getGzip(); } else { entity = state.getUncompressed(); } return builder .entity(entity) .header(HttpHeaders.ETAG, state.getVersion()) .build(); }</code><technical_language>meant remove</technical_language>

Target:
public Response getAllServices(@HeaderParam(HttpHeaders.IF_NONE_MATCH) String ifNoneMatch, @HeaderParam(HttpHeaders.ACCEPT_ENCODING) String acceptEncoding) { CachedBaragonState state = stateCache.getState(); String verisonString = Integer.toString(state.getVersion()); if (ifNoneMatch != null && ifNoneMatch.equals(verisonString.trim())) { return Response.notModified() .header(HttpHeaders.ETAG, state.getVersion()) .build(); } ResponseBuilder builder = Response.ok(); final byte[] entity; if (acceptEncoding != null && acceptEncoding.contains("gzip")) { builder.header(HttpHeaders.CONTENT_ENCODING, "gzip"); entity = state.getGzip(); } else { entity = state.getUncompressed(); } return builder .entity(entity) .header(HttpHeaders.ETAG, state.getVersion()) .build(); }
Source:
<code>public static void startJetty(String rmUrl, String scheduleUrl) { List<String> applicationUrls = (new JettyStarter().deployWebApplications(rmUrl, scheduleUrl)); if (applicationUrls != null) { for (String applicationUrl : applicationUrls) { if (applicationUrl.endsWith("/rest")) { <START> if (!PASchedulerProperties.SCHEDULER_REST_URL.isSet()) { <END> PASchedulerProperties.SCHEDULER_REST_URL.updateProperty(applicationUrl); } } if (applicationUrl.endsWith("/catalog")) { if (!PASchedulerProperties.CATALOG_REST_URL.isSet()) { PASchedulerProperties.CATALOG_REST_URL.updateProperty(applicationUrl); } } } } }</code><technical_language>combine 'if' one</technical_language>

Target:
public static void startJetty(String rmUrl, String scheduleUrl) { List<String> applicationUrls = (new JettyStarter().deployWebApplications(rmUrl, scheduleUrl)); if (applicationUrls != null) { for (String applicationUrl : applicationUrls) { if (applicationUrl.endsWith("/rest") && !PASchedulerProperties.SCHEDULER_REST_URL.isSet()) { PASchedulerProperties.SCHEDULER_REST_URL.updateProperty(applicationUrl); } if (applicationUrl.endsWith("/catalog") && !PASchedulerProperties.CATALOG_REST_URL.isSet()) { PASchedulerProperties.CATALOG_REST_URL.updateProperty(applicationUrl); } } } }
Source:
<code>public static boolean isMixedCase(final CharSequence cs) { if (cs == null || isEmpty(cs)) { return false; } boolean containsUppercase = false; boolean containsLowercase = false; final int sz = cs.length(); <START> for (int i = 0; i < sz; i++) { <END> if (Character.isUpperCase(cs.charAt(i)) == true) { containsUppercase = true; } else if (Character.isLowerCase(cs.charAt(i)) == true) { containsLowercase = true; } else { return false; } } return containsUppercase && containsLowercase; }</code><technical_language>more efficient track case of character break return false occurrence of other case? Saves iterating rest of character sequence if mixed case</technical_language>

Target:
public static boolean isMixedCase(final CharSequence cs) { if (cs == null || isEmpty(cs) || cs.length() <= 1) { return false; } boolean containsUppercase = false; boolean containsLowercase = false; final int sz = cs.length(); for (int i = 0; i < sz; i++) { if (containsUppercase && containsLowercase) { return true; } else if (Character.isUpperCase(cs.charAt(i))) { containsUppercase = true; } else if (Character.isLowerCase(cs.charAt(i))) { containsLowercase = true; } } return containsUppercase && containsLowercase; }
Source:
<code><START> private Iterable<String> experimentsWithMetadataProvider() { <END> return jdbcUtils.getPublicSingleCellExperimentAccessions() .stream() .filter(accession -> !accession.equalsIgnoreCase("E-GEOD-99058")) .collect(Collectors.toSet()); }</code><technical_language>In parameterized tests [method sources return Stream<T>](<LINK_0>, saving collect(...) step. If want return unique values [distinct()](<LINK_1></technical_language>

Target:
private Stream<String> experimentsWithMetadataProvider() { return jdbcUtils.getPublicSingleCellExperimentAccessions() .stream() .filter(accession -> !accession.equalsIgnoreCase("E-GEOD-99058")); }
Source:
<code>public Image getImage(Object element) { if (element instanceof CanvasViewInfo) { element = ((CanvasViewInfo) element).getUiViewNode(); } if (element instanceof UiElementNode) { UiElementNode node = (UiElementNode) element; ElementDescriptor desc = node.getDescriptor(); if (desc != null) { Image img = null; if (desc.getUiName().equals(LINEAR_LAYOUT)) { Element e = (Element) node.getXmlNode(); if (VALUE_VERTICAL.equals(e.getAttributeNS(ANDROID_URI, ATTR_ORIENTATION))) { IconFactory factory = IconFactory.getInstance(); img = factory.getIcon("VerticalLinearLayout"); } } if (img == null) { <START> img = desc.getFormIcon(); <END> } if (img != null) { if (node.hasError()) { return new ErrorImageComposite(img).createImage(); } else { return img; } } } } return AdtPlugin.getAndroidLogo(); }</code><technical_language>outline getIcon done in Eclipse (for XML Java files) -- this a big deal builtins icon. I if create a "custom view" icon here..</technical_language>

Target:
public Image getImage(Object element) { if (element instanceof CanvasViewInfo) { element = ((CanvasViewInfo) element).getUiViewNode(); } if (element instanceof UiElementNode) { UiElementNode node = (UiElementNode) element; ElementDescriptor desc = node.getDescriptor(); if (desc != null) { Image img = null; if (desc.getUiName().equals(LINEAR_LAYOUT)) { Element e = (Element) node.getXmlNode(); if (VALUE_VERTICAL.equals(e.getAttributeNS(ANDROID_URI, ATTR_ORIENTATION))) { IconFactory factory = IconFactory.getInstance(); img = factory.getIcon("VerticalLinearLayout"); } } if (img == null) { img = desc.getCustomizedIcon(); } if (img != null) { if (node.hasError()) { return new ErrorImageComposite(img).createImage(); } else { return img; } } } } return AdtPlugin.getAndroidLogo(); }
Source:
<code><START> public String[] getLines() { <END> return (String[]) lines.toArray(new String[lines.size()]); }</code><technical_language>array? List<String> is fine</technical_language>

Target:
public synchronized List<String> getLines() { return new ArrayList<>(lines); }
Source:
<code>public Runtime(ResourceLoader resourceLoader, ClassLoader classLoader, Collection<? extends Backend> backends, RuntimeOptions runtimeOptions) { <START> this(resourceLoader, classLoader, backends, runtimeOptions, new UndefinedStepsTracker()); <END> }</code><technical_language>This class in a public API, is need constructors for compatibility. cut this (or preferrably - one) constructors please</technical_language>

Target:
public Runtime(ResourceLoader resourceLoader, ClassLoader classLoader, Collection<? extends Backend> backends, RuntimeOptions runtimeOptions) { this(resourceLoader, classLoader, backends, runtimeOptions, null); }
Source:
<code>public String getNamespaceURI() { if (namespaceURI == null) { namespaceURI = ClassUtils.getPackageName(getNativeWidget() .getClass()); } <START> System.err.println(namespaceURI); <END> return namespaceURI; }</code><technical_language>remove syserrs</technical_language>

Target:
public String getNamespaceURI() { if (namespaceURI == null) { namespaceURI = ClassUtils.getPackageName(getNativeWidget() .getClass()); } return namespaceURI; }
Source:
<code>protected static void setOverrideFileName(String... path) { String filePaths = Joiner.on(LIST_SEPARATOR).skipNulls().join(path); <START> fOverridePath = filePaths == null ? null : filePaths.isEmpty() ? null : filePaths; <END> fOverride = true; }</code><technical_language>store String[] for open() getFileName() return item in array</technical_language>

Target:
public static void setOverrideFileName(String... path) { fOverridePath = (path == null) ? null : path; fOverride = true; }
Source:
<code>public void into(RemoteViews remoteViews, int viewId, int notificationId, Notification notification) { if (remoteViews == null) { throw new IllegalArgumentException("RemoteViews must not be null."); } if (notification == null) { throw new IllegalArgumentException("Notification must not be null."); } if (deferred) { throw new IllegalStateException("Fit cannot be used with RemoteViews."); <START> } <END> Request finalData = picasso.transformRequest(data.build()); String key = createKey(finalData); RemoteViewsAction action = new NotificationAction(picasso, finalData, remoteViews, viewId, notificationId, notification, skipMemoryCache, errorResId, key); performRemoteViewInto(action); }</code><technical_language>Checks tests for placeholder & error drawables remote views</technical_language>

Target:
public void into(RemoteViews remoteViews, int viewId, int notificationId, Notification notification) { if (remoteViews == null) { throw new IllegalArgumentException("RemoteViews must not be null."); } if (notification == null) { throw new IllegalArgumentException("Notification must not be null."); } if (deferred) { throw new IllegalStateException("Fit cannot be used with RemoteViews."); } if (placeholderDrawable != null || errorDrawable != null) { throw new IllegalArgumentException( "Cannot use placeholder or error drawables with remote views."); } Request finalData = picasso.transformRequest(data.build()); String key = createKey(finalData); RemoteViewsAction action = new NotificationAction(picasso, finalData, remoteViews, viewId, notificationId, notification, skipMemoryCache, errorResId, key); performRemoteViewInto(action); }
Source:
<code>public String createSortTitle(String title) { if (title == null) { return null; } for (String prefix : prefixes) { <START> String prefixWithLeadingSpace = prefix + " "; <END> if (title.startsWith(prefixWithLeadingSpace)) { return title.substring(prefixWithLeadingSpace.length()) + ", " + prefix; } } return title; }</code><technical_language>generate in constructor? Otherwise, creating _sizeof(prefixes)_ new Strings time createSortTitle is called</technical_language>

Target:
public String createSortTitle(String title) { if (title == null) { return null; } for (Map.Entry<String, String> prefix : prefixToPrefixWithLeadingSpace.entrySet()) { String prefixWithLeadingSpace = prefix.getValue(); if (title.startsWith(prefixWithLeadingSpace)) { return title.substring(prefixWithLeadingSpace.length()) + ", " + prefix.getKey(); } } return title; }
Source:
<code>public static void main(String[] args) throws Exception { File f = new File("/home/kohsuke/ws/hudson/investigations/javafx-windows-hang/out.log"); <START> DataInputStream fin = new DataInputStream(new FileInputStream(f)); <END> fin.readFully(new byte[4]); try (ObjectInputStream ois = new ObjectInputStream(fin)) { for (int n=0; ; n++) { Command o = (Command)ois.readObject(); System.out.println("#"+n+" : "+o); if (o instanceof RPCRequest) { RPCRequest request = (RPCRequest) o; System.out.print(" ("); boolean first=true; for (Object argument : request.getArguments()) { if(first) first=false; else System.out.print(","); System.out.print(argument); } System.out.println(")"); } if (o.createdAt!=null) o.createdAt.printStackTrace(System.out); } } }</code><technical_language>read included in a try resources? suggestion try (DataInputStream fin = new DataInputStream(new FileInputStream(f))) {</technical_language>

Target:
public static void main(String[] args) throws Exception { File f = new File("/home/kohsuke/ws/hudson/investigations/javafx-windows-hang/out.log"); try (DataInputStream fin = new DataInputStream(new FileInputStream(f))) { fin.readFully(new byte[4]); try (ObjectInputStream ois = new ObjectInputStream(fin)) { for (int n=0; ; n++) { Command o = (Command)ois.readObject(); System.out.println("#"+n+" : "+o); if (o instanceof RPCRequest) { RPCRequest request = (RPCRequest) o; System.out.print(" ("); boolean first=true; for (Object argument : request.getArguments()) { if(first) first=false; else System.out.print(","); System.out.print(argument); } System.out.println(")"); } if (o.createdAt!=null) o.createdAt.printStackTrace(System.out); } } } }
Source:
<code>private static JSONObject echo(RestRequestMetadata restRequestMetadata, AdminMetrics adminMetrics) throws RestServiceException { Map<String, List<String>> parameters = restRequestMetadata.getArgs(); if (parameters != null && parameters.containsKey(TEXT_KEY)) { try { String text = parameters.get(TEXT_KEY).get(0); return packageResult(text); } catch (JSONException e) { logger.error("While trying to construct response for echo GET: Exception - ", e); adminMetrics.echoGetResponseBuildingError.inc(); throw new RestServiceException("Unable to construct result object - ", e, RestServiceErrorCode.ResponseBuildingFailure); } } else { <START> logger.debug("While trying to handle echo GET: Request missing parameter - {}", TEXT_KEY); <END> adminMetrics.echoGetMissingParameter.inc(); throw new RestServiceException("Request missing parameter - " + TEXT_KEY, RestServiceErrorCode.MissingArgs); } }</code><technical_language>do error trace debug</technical_language>

Target:
private static JSONObject echo(RestRequestMetadata restRequestMetadata, AdminMetrics adminMetrics) throws RestServiceException { Map<String, List<String>> parameters = restRequestMetadata.getArgs(); if (parameters != null && parameters.containsKey(TEXT_KEY)) { String text = parameters.get(TEXT_KEY).get(0); logger.trace("Text to echo for request is {}", restRequestMetadata.getUri(), text); try { return packageResult(text); } catch (JSONException e) { adminMetrics.echoGetResponseBuildingError.inc(); throw new RestServiceException("Unable to construct result JSON object during echo GET - ", e, RestServiceErrorCode.ResponseBuildingFailure); } } else { adminMetrics.echoGetMissingParameterError.inc(); throw new RestServiceException("Request for echo GET missing parameter - " + TEXT_KEY, RestServiceErrorCode.MissingArgs); } }
Source:
<code>public Subfield(String path) { requireNonNull(path, "path is null"); SubfieldTokenizer tokenizer = new SubfieldTokenizer(path); checkArgument(tokenizer.hasNext(), "Column name is missing: " + path); PathElement firstElement = tokenizer.next(); <START> checkArgument(firstElement instanceof NestedField, "Subfield path must start with a column name: " + path); <END> this.name = ((NestedField) firstElement).getName(); List<PathElement> pathElements = new ArrayList<>(); tokenizer.forEachRemaining(pathElements::add); this.path = Collections.unmodifiableList(pathElements); }</code><technical_language>nit: more a column (e.g., variable in a lambda) SubField a generic data structure</technical_language>

Target:
public Subfield(String path) { requireNonNull(path, "path is null"); SubfieldTokenizer tokenizer = new SubfieldTokenizer(path); checkArgument(tokenizer.hasNext(), "Column name is missing: " + path); PathElement firstElement = tokenizer.next(); checkArgument(firstElement instanceof NestedField, "Subfield path must start with a name: " + path); this.name = ((NestedField) firstElement).getName(); List<PathElement> pathElements = new ArrayList<>(); tokenizer.forEachRemaining(pathElements::add); this.path = Collections.unmodifiableList(pathElements); }
Source:
<code>public void prepareRun(BatchAggregatorContext context) throws Exception { super.prepareRun(context); Schema schema = context.getInputSchema(); if (schema == null || schema.getFields() == null) { return; } <START> FieldOperation operation = <END> new FieldTransformOperation("Parse", "Parsed field", schema.getFields().stream().map(Schema.Field::getName) .collect(Collectors.toList()), uniqueFields); context.record(Collections.singletonList(operation)); }</code><technical_language>This is wrong. this plugin is filter duplicate records based unique keys filter function. input output schema basically change. field lineage operations a list of one-to-one field mapping input field output field</technical_language>

Target:
public void prepareRun(BatchAggregatorContext context) throws Exception { super.prepareRun(context); TransformLineageRecorderUtils.generateOneToOnes(dedupConfig.getUniqueFields(), "dedup", "Removed duplicate records.."); }
Source:
<code>private ArrayList<BlobId> generateBlobId(ArrayList<String> blobIdListStr, ClusterMap map) throws IOException { ArrayList<BlobId> blobIdList = new ArrayList<BlobId>(); <START> for(String blobIdStr: blobIdListStr) { <END> BlobId blobId = new BlobId(blobIdStr, map); blobIdList.add(blobId); } return blobIdList; }</code><technical_language>this throw if of ids is bad? Do want change continue processing valid blob ids</technical_language>

Target:
private ArrayList<BlobId> generateBlobId(ArrayList<String> blobIdListStr, ClusterMap map) throws IOException { ArrayList<BlobId> blobIdList = new ArrayList<BlobId>(); for (String blobIdStr : blobIdListStr) { try { BlobId blobId = new BlobId(blobIdStr, map); blobIdList.add(blobId); } catch (IOException e) { System.out.println("IOException thrown for blobId " + blobIdStr); invalidBlobs.put(blobIdStr, e); } catch (IllegalArgumentException e) { System.out.println("IllegalArgumentException thrown for blobId " + blobIdStr); invalidBlobs.put(blobIdStr, e); } } return blobIdList; }
Source:
<code>public static Function<HttpPollValue, Double> latency() { return new Function<HttpPollValue, Double>() { @Override @Nullable public Double apply(HttpPollValue input) { if (input.getLatencyFullContent()==null) return null; <START> return input.getLatencyFullContent().doubleValue(); <END> } }; }</code><technical_language>convert this a double, leave exact long value</technical_language>

Target:
public static Function<HttpPollValue, Long> latency() { return new Function<HttpPollValue, Long>() { public Long apply(HttpPollValue input) { return input.getLatencyFullContent(); } }; }
Source:
<code>public void testConstructor() throws Exception { HttpTransport transport = new MockHttpTransport(); HttpRequest request = transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL); HttpResponse response = request.execute(); HttpHeaders headers = response.getHeaders(); <START> HttpResponseException e = new HttpResponseException(response); <END> assertThat(e).hasMessageThat().isEqualTo("200\nRequest URL: " + SIMPLE_GENERIC_URL); assertNull(e.getContent()); assertEquals(200, e.getStatusCode()); assertNull(e.getStatusMessage()); assertTrue(headers == e.getHeaders()); }</code><technical_language>e --> exception (per Google style abbreviate variable names)</technical_language>

Target:
public void testConstructor() throws Exception { HttpTransport transport = new MockHttpTransport(); HttpRequest request = transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL); HttpResponse response = request.execute(); HttpHeaders headers = response.getHeaders(); HttpResponseException responseException = new HttpResponseException(response); assertThat(responseException).hasMessageThat().isEqualTo("200\nGET " + SIMPLE_GENERIC_URL); assertNull(responseException.getContent()); assertEquals(200, responseException.getStatusCode()); assertNull(responseException.getStatusMessage()); assertTrue(headers == responseException.getHeaders()); }
Source:
<code>public void createDatastore(Datastore datastore) { final String name = datastore.getName(); synchronized (_datastoreCatalog) { if (_datastoreCatalog.containsDatastore(name)) { logger.warn("Datastore '{}' already exists. No new datastore will be created!", name); } else { if (_datastoreCatalog instanceof MutableDatastoreCatalog) { ((MutableDatastoreCatalog) _datastoreCatalog).addDatastore(datastore); } else { <START> logger.error("Tried to create datastore '{}', but the datastore catalog is not mutable", name); <END> } } } }</code><technical_language>user, happens, I see. this throw exception user get a warning</technical_language>

Target:
public void createDatastore(Datastore datastore) { final String name = datastore.getName(); synchronized (_datastoreCatalog) { if (_datastoreCatalog.containsDatastore(name)) { logger.warn("Datastore '{}' already exists. No new datastore will be created!", name); } else { if (_datastoreCatalog instanceof MutableDatastoreCatalog) { ((MutableDatastoreCatalog) _datastoreCatalog).addDatastore(datastore); } else { throw new IllegalStateException("Tried to create datastore '" + name + "', but the datastore catalog is not mutable"); } } } }
Source:
<code>private void removeImages() { List<CinderDisk> cinderDisks = new ArrayList<>(); for (final DiskImage source : getSourceImages()) { if (source.getDiskStorageType() == DiskStorageType.CINDER) { cinderDisks.add((CinderDisk) source); continue; } List<DiskImage> images = diskImageDao.getAllSnapshotsForParent(source.getImageId()); DiskImage dest = null; if (!images.isEmpty()) { dest = images.get(0); } if (getSnapshotActionType() == VdcActionType.RemoveSnapshotSingleDiskLive) { CommandCoordinatorUtil.executeAsyncCommand( getSnapshotActionType(), buildRemoveSnapshotSingleDiskParameters(source, dest, getSnapshotActionType()), cloneContextAndDetachFromParent()); } else { RemoveSnapshotSingleDiskParameters parameters = buildRemoveSnapshotSingleDiskParameters( source, dest, getSnapshotActionType()); VdcReturnValueBase vdcReturnValue = runInternalActionWithTasksContext( getSnapshotActionType(), parameters); <START> if (getSnapshotActionType() == VdcActionType.RemoveSnapshotSingleDisk) { <END> getTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); } } List<Guid> quotasToRemoveFromCache = new ArrayList<>(); quotasToRemoveFromCache.add(source.getQuotaId()); if (dest != null) { quotasToRemoveFromCache.add(dest.getQuotaId()); } getQuotaManager().removeQuotaFromCache(getStoragePoolId(), quotasToRemoveFromCache); } if (!cinderDisks.isEmpty()) { handleCinderSnapshotDisks(cinderDisks); } }</code><technical_language>please remove if condition</technical_language>

Target:
private void removeImages() { List<CinderDisk> cinderDisks = new ArrayList<>(); for (final DiskImage source : getSourceImages()) { if (source.getDiskStorageType() == DiskStorageType.CINDER) { cinderDisks.add((CinderDisk) source); continue; } List<DiskImage> images = diskImageDao.getAllSnapshotsForParent(source.getImageId()); DiskImage dest = null; if (!images.isEmpty()) { dest = images.get(0); } if (getSnapshotActionType() == VdcActionType.RemoveSnapshotSingleDiskLive) { CommandCoordinatorUtil.executeAsyncCommand( getSnapshotActionType(), buildRemoveSnapshotSingleDiskParameters(source, dest, getSnapshotActionType()), cloneContextAndDetachFromParent()); } else { RemoveSnapshotSingleDiskParameters parameters = buildRemoveSnapshotSingleDiskParameters( source, dest, getSnapshotActionType()); VdcReturnValueBase vdcReturnValue = runInternalActionWithTasksContext( getSnapshotActionType(), parameters); getTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); } List<Guid> quotasToRemoveFromCache = new ArrayList<>(); quotasToRemoveFromCache.add(source.getQuotaId()); if (dest != null) { quotasToRemoveFromCache.add(dest.getQuotaId()); } getQuotaManager().removeQuotaFromCache(getStoragePoolId(), quotasToRemoveFromCache); } if (!cinderDisks.isEmpty()) { handleCinderSnapshotDisks(cinderDisks); } }
Source:
<code>public ListAllMyBucketsResult call() throws IOException, SignatureException, SSLSetupException { final GetServiceResponse response = getClient().getService(new GetServiceRequest()); final ListAllMyBucketsResult result = response.getResult(); if (result.getBuckets() == null) { <START> return null; <END> } return result; }</code><technical_language>moved view logic out of here, return result view worry if getBuckets() call returns null</technical_language>

Target:
public ListAllMyBucketsResult call() throws IOException, SignatureException, SSLSetupException { final GetServiceResponse response = getClient().getService(new GetServiceRequest()); final ListAllMyBucketsResult result = response.getResult(); return result; }
Source:
<code>public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) { <START> if(tab == EsteemedInnovation.tab) { <END> for (Type type : Type.LOOKUP) { items.add(new ItemStack(this, 1, type.ordinal())); } } }</code><technical_language>Missing space (</technical_language>

Target:
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) { if (isInCreativeTab(tab)) { for (Type type : Type.LOOKUP) { items.add(new ItemStack(this, 1, type.ordinal())); } } }