auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public String invoke(String id) { <END> String interceptorInvocationCounterKey = id + "-COUNT"; log.info("Test Invoked"); String clientInterceptor = wasClientInterceptorInvoked(); log.info(String.format("clientInterceptorInvoked: %b %s", (clientInterceptor!=null), clientInterceptor)); context.getContextData().put("ClientInterceptorInvoked", clientInterceptor); return "" + context.getContextData().get(interceptorInvocationCounterKey); }</code><technical_language>is purpose of this? pulled out of map key</technical_language>

Target:
public int invoke(String id) { String interceptorInvocationCounterKey = id + "-COUNT"; String clientInterceptor = wasClientInterceptorInvoked(); context.getContextData().put("ClientInterceptorInvoked", clientInterceptor); return (Integer) context.getContextData().get(interceptorInvocationCounterKey); }
Source:
<code>public AnnotationProcessorValidationTarget resolveValidationTarget(ExecutableElement element, AnnotationMirror annotation) { Set<AnnotationProcessorValidationTarget> allowedTargets = getSupportedValidationTargets( annotation.getAnnotationType() ); <START> assert allowedTargets.size()>0; <END> if(allowedTargets.size()==1) { return allowedTargets.toArray( new AnnotationProcessorValidationTarget[1] )[0]; } AnnotationProcessorConstraintTarget constrTarget = getConstraintTarget( annotation ); if(constrTarget==null) { return null; } switch(constrTarget) { case PARAMETERS: return AnnotationProcessorValidationTarget.PARAMETERS; case RETURN_VALUE: return AnnotationProcessorValidationTarget.ANNOTATED_ELEMENT; case IMPLICIT: default: return resolveImplicitValidationTarget( element ); } }</code><technical_language>assert statements in code base, rely (it's a user's choice enable not). I remove it, obtain another method of class empty</technical_language>

Target:
public AnnotationProcessorValidationTarget resolveValidationTarget(ExecutableElement element, AnnotationMirror annotation) { Set<AnnotationProcessorValidationTarget> allowedTargets = getSupportedValidationTargets( annotation.getAnnotationType() ); if(allowedTargets.size()==1) { return allowedTargets.toArray( new AnnotationProcessorValidationTarget[1] )[0]; } AnnotationProcessorConstraintTarget constrTarget = getConstraintTarget( annotation ); if(constrTarget==null) { return null; } switch(constrTarget) { case PARAMETERS: return AnnotationProcessorValidationTarget.PARAMETERS; case RETURN_VALUE: return AnnotationProcessorValidationTarget.ANNOTATED_ELEMENT; case IMPLICIT: default: return resolveImplicitValidationTarget( element ); } }
Source:
<code>protected void executeQueryCommand() { Disk diskFromDao = getDbFacade().getDiskDao().get(getParameters().getEntityId()); <START> if (diskFromDao != null) { <END> getQueryReturnValue().setReturnValue(null); return; } Volume Volume = getVolumeProviderProxy().getVolumeById(getParameters().getEntityId().toString()); Guid storageDomainId = getParameters().getId(); CinderDisk unregisteredDisk = CinderBroker.volumeToCinderDisk(Volume, storageDomainId); getQueryReturnValue().setReturnValue(unregisteredDisk); }</code><technical_language>Please add a log disk exists in DB fetched VolumeProvider</technical_language>

Target:
protected void executeQueryCommand() { Disk diskFromDao = getDbFacade().getDiskDao().get(getParameters().getEntityId()); if (diskFromDao != null) { log.info("The disk already exist in the DB, hence, should not be fetched from Cinder."); getQueryReturnValue().setReturnValue(null); return; } Volume Volume = getVolumeProviderProxy().getVolumeById(getParameters().getEntityId().toString()); Guid storageDomainId = getParameters().getId(); CinderDisk unregisteredDisk = CinderBroker.volumeToCinderDisk(Volume, storageDomainId); getQueryReturnValue().setReturnValue(unregisteredDisk); }
Source:
<code>private ActionBarDrawerToggle setupDrawerToggle() { return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close) { @Override <START> public void onDrawerOpened(View drawerView) { <END> super.onDrawerOpened(drawerView); } }; }</code><technical_language>remove this method</technical_language>

Target:
private ActionBarDrawerToggle setupDrawerToggle() { return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close); }
Source:
<code>public void setSessionProperty(String sessionId, String key, String value) throws SqlExecutionException { ExecutionContext<?> context = getExecutionContext(sessionId); Environment env = context.getEnvironment(); Environment newEnv = Environment.enrich(env, ImmutableMap.of(key, value), ImmutableMap.of()); ExecutionContext.SessionState sessionState = context.getSessionState(); newEnv.getConfiguration().asMap().forEach((k, v) -> <START> sessionState.config.getConfiguration().setString(k, v)); <END> ExecutionContext<?> newContext = createExecutionContextBuilder( context.getOriginalSessionContext()) .env(newEnv) .sessionState(sessionState) .build(); this.contextMap.put(sessionId, newContext); }</code><technical_language>this influence RESET command clear session properties</technical_language>

Target:
public void setSessionProperty(String sessionId, String key, String value) throws SqlExecutionException { ExecutionContext<?> context = getExecutionContext(sessionId); Environment env = context.getEnvironment(); Environment newEnv = Environment.enrich(env, ImmutableMap.of(key, value), ImmutableMap.of()); ExecutionContext<?> newContext = createExecutionContextBuilder( context.getOriginalSessionContext()) .env(newEnv) .sessionState(context.getSessionState()) .build(); this.contextMap.put(sessionId, newContext); }
Source:
<code>public Attribute fillAttribute(PerunSessionImpl sess, Group group, Resource resource, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException { Attribute attribute = new Attribute(attributeDefinition); Attribute unixGIDNamespaceAttribute; try { unixGIDNamespaceAttribute = sess.getPerunBl().getModulesUtilsBl().getUnixGIDNamespaceAttributeWithNotNullValue(sess, resource); } catch(WrongReferenceAttributeValueException ex) { return attribute; } Attribute gidAttribute; try { gidAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, AttributesManager.NS_GROUP_ATTR_DEF + ":unixGID-namespace:" + unixGIDNamespaceAttribute.getValue()); } catch(AttributeNotExistsException ex) { throw new ConsistencyErrorException(ex); } try { <START> sess.getPerunBl().getAttributesManagerBl().checkAttributeSyntax(sess, group, gidAttribute); <END> sess.getPerunBl().getAttributesManagerBl().forceCheckAttributeSemantics(sess, group, gidAttribute); attribute.setValue(gidAttribute.getValue()); return attribute; } catch(WrongAttributeValueException ex) { gidAttribute.setValue(null); gidAttribute = sess.getPerunBl().getAttributesManagerBl().fillAttribute(sess, group, gidAttribute); attribute.setValue(gidAttribute.getValue()); return attribute; } catch(WrongReferenceAttributeValueException ex) { return attribute; } }</code><technical_language>here. added checkAttributeSyntax in fillAttribute method in virt_googleGroupNames is checkAttributeSemantics</technical_language>

Target:
public Attribute fillAttribute(PerunSessionImpl sess, Group group, Resource resource, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException { Attribute attribute = new Attribute(attributeDefinition); Attribute unixGIDNamespaceAttribute; try { unixGIDNamespaceAttribute = sess.getPerunBl().getModulesUtilsBl().getUnixGIDNamespaceAttributeWithNotNullValue(sess, resource); } catch(WrongReferenceAttributeValueException ex) { return attribute; } Attribute gidAttribute; try { gidAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, AttributesManager.NS_GROUP_ATTR_DEF + ":unixGID-namespace:" + unixGIDNamespaceAttribute.getValue()); } catch(AttributeNotExistsException ex) { throw new ConsistencyErrorException(ex); } try { sess.getPerunBl().getAttributesManagerBl().forceCheckAttributeSyntax(sess, group, gidAttribute); sess.getPerunBl().getAttributesManagerBl().forceCheckAttributeSemantics(sess, group, gidAttribute); attribute.setValue(gidAttribute.getValue()); return attribute; } catch(WrongAttributeValueException ex) { gidAttribute.setValue(null); gidAttribute = sess.getPerunBl().getAttributesManagerBl().fillAttribute(sess, group, gidAttribute); attribute.setValue(gidAttribute.getValue()); return attribute; } catch(WrongReferenceAttributeValueException ex) { return attribute; } }
Source:
<code>private void addActiveTask(HashSet<ITask> relevantTasks) { ITask activeTask = taskActivityManager.getActiveTask(); <START> if (activeTask != null) { <END> relevantTasks.add(activeTask); } }</code><technical_language>add task if a local task</technical_language>

Target:
private void addActiveTask(HashSet<ITask> relevantTasks) { ITask activeTask = taskActivityManager.getActiveTask(); if (activeTask != null && !(activeTask instanceof LocalTask)) { relevantTasks.add(activeTask); } }
Source:
<code><START> private NewSessionPayload(Reader source, boolean forceMobileJSONWP) throws IOException { <END> this.forceMobileJSONWP = forceMobileJSONWP; int threshold = (int) Math.min( Integer.MAX_VALUE, Math.min( Runtime.getRuntime().freeMemory() / 5, Runtime.getRuntime().maxMemory() / 10)); backingStore = new FileBackedOutputStream(threshold); try (Writer writer = new OutputStreamWriter(backingStore, UTF_8)) { CharStreams.copy(source, writer); } ImmutableSet.Builder<CapabilitiesFilter> adapters = ImmutableSet.builder(); ServiceLoader.load(CapabilitiesFilter.class).forEach(adapters::add); adapters .add(new ChromeFilter()) .add(new EdgeFilter()) .add(new FirefoxFilter()) .add(new InternetExplorerFilter()) .add(new OperaFilter()) .add(new SafariFilter()); this.adapters = adapters.build(); ImmutableSet.Builder<CapabilityTransform> transforms = ImmutableSet.builder(); ServiceLoader.load(CapabilityTransform.class).forEach(transforms::add); transforms .add(new ProxyTransform()) .add(new StripAnyPlatform()) .add(new W3CPlatformNameNormaliser()); this.transforms = transforms.build(); ImmutableSet.Builder<Dialect> dialects = ImmutableSet.builder(); if (getOss() != null) { dialects.add(Dialect.OSS); } if (getAlwaysMatch() != null || getFirstMatches() != null) { dialects.add(Dialect.W3C); } this.dialects = dialects.build(); validate(); }</code><technical_language>This copies a lot of stuff original selenium code. Is avoid duplication</technical_language>

Target:
private NewSessionPayload(Reader source, boolean forceMobileJSONWP) throws IOException { this.forceMobileJSONWP = forceMobileJSONWP; int threshold = (int) Math.min( Integer.MAX_VALUE, Math.min( Runtime.getRuntime().freeMemory() / 5, Runtime.getRuntime().maxMemory() / 10)); backingStore = new FileBackedOutputStream(threshold); try (Writer writer = new OutputStreamWriter(backingStore, UTF_8)) { CharStreams.copy(source, writer); } ImmutableSet.Builder<CapabilitiesFilter> adapters = ImmutableSet.builder(); ServiceLoader.load(CapabilitiesFilter.class).forEach(adapters::add); adapters .add(new ChromeFilter()) .add(new EdgeFilter()) .add(new FirefoxFilter()) .add(new InternetExplorerFilter()) .add(new OperaFilter()) .add(new SafariFilter()); this.adapters = adapters.build(); ImmutableSet.Builder<CapabilityTransform> transforms = ImmutableSet.builder(); ServiceLoader.load(CapabilityTransform.class).forEach(transforms::add); transforms .add(new ProxyTransform()) .add(new StripAnyPlatform()) .add(new W3CPlatformNameNormaliser()); this.transforms = transforms.build(); ImmutableSet.Builder<Dialect> dialects = ImmutableSet.builder(); if (getOss() != null) { dialects.add(Dialect.OSS); } if (getAlwaysMatch() != null || getFirstMatch() != null) { dialects.add(Dialect.W3C); } validate(); }
Source:
<code>private MessageTemplate(MessageTemplate copyFrom) { if (copyFrom != null) { this.ttl = copyFrom.getTtl(); tags.addAll(copyFrom.getTags()); <START> } <END> }</code><technical_language>This copy constructor call default</technical_language>

Target:
private MessageTemplate(MessageTemplate copyFrom) { this(); if (copyFrom != null) { this.ttl = copyFrom.getTtl(); tags.addAll(copyFrom.getTags()); } }
Source:
<code>public void setKeyStroke(String k) { ScoutKeystroke scoutKeystroke = new ScoutKeystroke(k); scoutKeystroke.parse(); if (scoutKeystroke.isValid()) { propertySupport.setPropertyString(PROP_KEYSTROKE, scoutKeystroke.getNormalizedKeystroke()); } else { <START> LOG.warn("Could not create keystroke '" + k + "' because he is invalid!"); <END> } }</code><technical_language>he</technical_language>

Target:
public void setKeyStroke(String k) { KeyStrokeNormalizer scoutKeystroke = new KeyStrokeNormalizer(k); scoutKeystroke.normalize(); if (scoutKeystroke.isValid()) { propertySupport.setPropertyString(PROP_KEYSTROKE, scoutKeystroke.getNormalizedKeystroke()); } else { LOG.warn("Could not create keystroke '" + k + "' because it is invalid!"); } }
Source:
<code>protected boolean requestCookie(HttpConnectionInterceptorContext context) { return requestCookie(context, sessionURL, sessionRequestBody, <START> "application/x-www-form-urlencoded", <END> "application/json", new OnExecuteCallable() { @Override public boolean call(HttpConnection connection) throws IOException { if (sessionHasStarted(connection.responseAsInputStream())) { return storeCookiesFromResponse(connection.getConnection()); } else { return false; } } } ); }</code><technical_language>I default JSON if encoding is more reliable. I expecting _iam_session accept JSON **if** oidc/token leaves normal _session odd out do override</technical_language>

Target:
boolean requestCookie(HttpConnectionInterceptorContext context) { return requestCookie(context, sessionURL, sessionRequestBody, sessionRequestMimeType, "application/json", new OnExecuteCallable() { @Override public boolean call(HttpConnection connection) throws IOException { if (sessionHasStarted(connection.responseAsInputStream())) { return storeCookiesFromResponse(connection.getConnection()); } else { return false; } } } ); }
Source:
<code>public CrateConnection(ClientHandleRegistry.ClientHandle handle, Properties properties) { this.clientHandle = handle; this.readOnly = false; <START> this.strict = Boolean.valueOf(properties.getProperty("strict", "false")); <END> this.properties = properties; }</code><technical_language>strict is a property handled others handled</technical_language>

Target:
public CrateConnection(ClientHandleRegistry.ClientHandle handle, Properties properties) { this.clientHandle = handle; this.readOnly = false; this.properties = properties; setDefaultProperty("strict", "false"); }
Source:
<code>public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeUTF(managerPrefix); out.writeUTF(uriString); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeUTF(inMemoryFormat.name()); out.writeObject(evictionConfig); out.writeObject(wanReplicationRef); writeKeyValueTypes(out); writeTenant(out); writeFactories(out); out.writeBoolean(isReadThrough); out.writeBoolean(isWriteThrough); out.writeBoolean(isStoreByValue); out.writeBoolean(isManagementEnabled); out.writeBoolean(isStatisticsEnabled); <START> out.writeBoolean(hotRestartConfig.isEnabled()); <END> out.writeBoolean(hotRestartConfig.isFsync()); out.writeObject(eventJournalConfig); out.writeUTF(quorumName); out.writeBoolean(hasListenerConfiguration()); if (hasListenerConfiguration()) { writeListenerConfigurations(out); } out.writeUTF(mergePolicy); out.writeBoolean(disablePerEntryInvalidationEvents); }</code><technical_language>unrelated this PR this: hotRestartConfig serialized object (it is IdentifiedDataSerializable) instead of field-by-field, allow for independent evolution of HotRestartConfig. Please feel free leave a todo, apparently this PR meant fix in CacheConfig :)</technical_language>

Target:
public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeUTF(managerPrefix); out.writeUTF(uriString); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeUTF(inMemoryFormat.name()); out.writeObject(evictionConfig); out.writeObject(wanReplicationRef); writeKeyValueTypes(out); writeTenant(out); writeFactories(out); out.writeBoolean(isReadThrough); out.writeBoolean(isWriteThrough); out.writeBoolean(isStoreByValue); out.writeBoolean(isManagementEnabled); out.writeBoolean(isStatisticsEnabled); out.writeObject(hotRestartConfig); out.writeObject(eventJournalConfig); out.writeUTF(quorumName); out.writeBoolean(hasListenerConfiguration()); if (hasListenerConfiguration()) { writeListenerConfigurations(out); } out.writeUTF(mergePolicy); out.writeBoolean(disablePerEntryInvalidationEvents); }
Source:
<code>public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) <START> .clientIntelligence(ClientIntelligence.BASIC) END> .marshaller(ProtoStreamMarshaller.class); RemoteCacheManager client = new RemoteCacheManager(builder.build()); RemoteCache<String, InstaPost> instaPostsCache = client.administration().getOrCreateCache(CACHE_NAME, "default"); addInstapostsSchema(client); QueryFactory queryFactory = Search.getQueryFactory(instaPostsCache); Query query = queryFactory.create("FROM tutorial.InstaPost p where p.user = :userName"); query.setParameter("userName", "belen_esteban"); ContinuousQuery<String, InstaPost> continuousQuery = Search.getContinuousQuery(instaPostsCache); ContinuousQueryListener<String, InstaPost> listener = new ContinuousQueryListener<String, InstaPost>() { @Override public void resultJoining(String id, InstaPost post) { System.out.println(String.format("@%s has posted again! Hashtag: #%s", post.user, post.hashtag)); } }; continuousQuery.removeAllListeners(); continuousQuery.addContinuousQueryListener(query, listener); for (int i = 0; i < 1000; i++) { addRandomPost(instaPostsCache); Thread.sleep(10); } client.administration().removeCache(CACHE_NAME); client.stop(); }</code><technical_language>Hmmm, if host is 127.0.0.1 do need client intelligence basic? remove basic intelligence this tutorial</technical_language>

Target:
public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .marshaller(ProtoStreamMarshaller.class); RemoteCacheManager client = new RemoteCacheManager(builder.build()); RemoteCache<String, InstaPost> instaPostsCache = client.administration().getOrCreateCache(CACHE_NAME, "default"); addInstapostsSchema(client); QueryFactory queryFactory = Search.getQueryFactory(instaPostsCache); Query query = queryFactory.create("FROM tutorial.InstaPost p where p.user = :userName"); query.setParameter("userName", "belen_esteban"); ContinuousQuery<String, InstaPost> continuousQuery = Search.getContinuousQuery(instaPostsCache); List<InstaPost> queryPosts = new ArrayList<>(); ContinuousQueryListener<String, InstaPost> listener = new ContinuousQueryListener<String, InstaPost>() { @Override public void resultJoining(String key, InstaPost post) { System.out.println(String.format("@%s has posted again! Hashtag: #%s", post.user, post.hashtag)); queryPosts.add(post); } }; continuousQuery.addContinuousQueryListener(query, listener); for (int i = 0; i < 1000; i++) { addRandomPost(instaPostsCache); Thread.sleep(10); } System.out.println("Total posts " + instaPostsCache.size()); System.out.println("Total posts by @belen_esteban " + queryPosts.size()); continuousQuery.removeContinuousQueryListener(listener); client.administration().removeCache(CACHE_NAME); client.stop(); }
Source:
<code>public void testDetermineMessageReturnsClassNameForNoParameterExpansion() throws Exception { Log log = mock(Log.class); <START> when(log.isDebugEnabled()).thenReturn(false); <END> assertEquals("LoggedUtils.determineMessage shouldn't return parameter expansion for a disabled log level.", Object.class.getName(), LoggedUtils.determineMessage(log, LoggedOverridingSubclassNoParameters.class.getAnnotation(Logged.class), new Object())); assertEquals("LoggedUtils.determineMessage shouldn't return parameter expansion when diabled completely.", Object.class.getName(), LoggedUtils.determineMessage(log, LoggedClass.class.getAnnotation(Logged.class), new Object())); }</code><technical_language>need return false explicitly is default mocking behavior</technical_language>

Target:
public void testDetermineMessageReturnsClassNameForNoParameterExpansion() throws Exception { Log log = mock(Log.class); assertEquals("LoggedUtils.determineMessage shouldn't return parameter expansion for a disabled log level.", Object.class.getName(), LoggedUtils.determineMessage(log, LoggedOverridingSubclassNoParameters.class.getAnnotation(Logged.class), new Object())); assertEquals("LoggedUtils.determineMessage shouldn't return parameter expansion when diabled completely.", Object.class.getName(), LoggedUtils.determineMessage(log, LoggedClass.class.getAnnotation(Logged.class), new Object())); }
Source:
<code>private static boolean isGetter(ASTMethodDeclaration node, Map<String, String> fieldNames) { if (node.getFirstDescendantOfType(ASTFormalParameters.class).getParameterCount() != 0 || node.getFirstDescendantOfType(ASTResultType.class).isVoid()) { return false; } <START> return fieldNames.containsKey(node.getName()); <END> }</code><technical_language>sure, if this works, node.getName() is e.g. getAge, fieldname is age..</technical_language>

Target:
private static boolean isGetter(ASTMethodDeclaration node, Map<String, String> fieldNames) { if (node.getFirstDescendantOfType(ASTFormalParameters.class).getParameterCount() != 0 || node.getFirstDescendantOfType(ASTResultType.class).isVoid()) { return false; } if (node.getName().startsWith("get")) { return containsIgnoreCase(fieldNames.keySet(), node.getName().substring(3)); } else if (node.getName().startsWith("is")) { return containsIgnoreCase(fieldNames.keySet(), node.getName().substring(2)); } return fieldNames.containsKey(node.getName()); }
Source:
<code>private Map<?,?> loadValues() { String pathWithLocaleAndFilename = "/" + locale.getLanguage() + "/" + this.filename; String pathWithFilename = "/" + filename + ".yml"; String pathWithLocale = "/" + locale.getLanguage() + ".yml"; List<String> paths = Arrays.asList(pathWithLocaleAndFilename, pathWithFilename, pathWithLocale); InputStream stream = null; for (String path : paths) { stream = findStream(path); if (stream != null) { break; } } if (stream == null) { return null; } <START> final Map<?,?> valuesMap = new Yaml().loadAs(stream, Map.class); <END> Map<?,?> localeBased = (Map<?,?>) valuesMap.get(locale.getLanguage()); if (localeBased == null) { localeBased = (Map<?,?>) valuesMap.get(filename); } return (Map<?,?>) localeBased.get("faker"); }</code><technical_language>stick logical change PR please? happy add babylon5 if wanted refactor Map, please a PR</technical_language>

Target:
private Map loadValues() { String pathWithLocaleAndFilename = "/" + locale.getLanguage() + "/" + this.filename; String pathWithFilename = "/" + filename + ".yml"; String pathWithLocale = "/" + locale.getLanguage() + ".yml"; List<String> paths = Arrays.asList(pathWithLocaleAndFilename, pathWithFilename, pathWithLocale); InputStream stream = null; for (String path : paths) { stream = findStream(path); if (stream != null) { break; } } if (stream == null) { return null; } final Map valuesMap = new Yaml().loadAs(stream, Map.class); Map localeBased = (Map) valuesMap.get(locale.getLanguage()); if (localeBased == null) { localeBased = (Map) valuesMap.get(filename); } return (Map) localeBased.get("faker"); }
Source:
<code>private void removeRemoteSourceHelper(RequestErrorTracker errorTracker, Request request, SettableFuture<?> future) { errorTracker.startRequest(); FutureCallback<StatusResponse> callback = new FutureCallback<StatusResponse>() { @Override public void onSuccess(@Nullable StatusResponse response) { if (response == null) { <START> throw new RuntimeException("Request failed with null response"); <END> } if (response.getStatusCode() != HttpStatus.OK.code()) { throw new RuntimeException("Request failed with HTTP status " + response.getStatusCode()); } future.set(null); } @Override public void onFailure(Throwable failedReason) { if (failedReason instanceof RejectedExecutionException && httpClient.isClosed()) { log.error("Unable to destroy exchange source at %s. HTTP client is closed", request.getUri()); return; } try { errorTracker.requestFailed(failedReason); } catch (PrestoException e) { future.setException(e); return; } ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit(); if (errorRateLimit.isDone()) { removeRemoteSourceHelper(errorTracker, request, future); } else { errorRateLimit.addListener(() -> removeRemoteSourceHelper(errorTracker, request, future), errorScheduledExecutor); } } }; addCallback(httpClient.executeAsync(request, createStatusResponseHandler()), callback, directExecutor()); }</code><technical_language>nit: throw new PrestoException(GENERIC_INTERNAL_ERROR, "") is categorized</technical_language>

Target:
private void removeRemoteSourceHelper(RequestErrorTracker errorTracker, Request request, SettableFuture<?> future) { errorTracker.startRequest(); FutureCallback<StatusResponse> callback = new FutureCallback<StatusResponse>() { @Override public void onSuccess(@Nullable StatusResponse response) { if (response == null) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Request failed with null response"); } if (response.getStatusCode() != OK.code()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Request failed with HTTP status " + response.getStatusCode()); } future.set(null); } @Override public void onFailure(Throwable failedReason) { if (failedReason instanceof RejectedExecutionException && httpClient.isClosed()) { LOG.error("Unable to destroy exchange source at %s. HTTP client is closed", request.getUri()); future.setException(failedReason); return; } try { errorTracker.requestFailed(failedReason); } catch (PrestoException e) { future.setException(e); return; } ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit(); if (errorRateLimit.isDone()) { removeRemoteSourceHelper(errorTracker, request, future); } else { errorRateLimit.addListener(() -> removeRemoteSourceHelper(errorTracker, request, future), errorScheduledExecutor); } } }; addCallback(httpClient.executeAsync(request, createStatusResponseHandler()), callback, directExecutor()); }
Source:
<code>protected void succeeded(long nanos, Description description) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "{} execution time: {}", description.getMethodName(), DurationFormatUtils.formatDuration(TimeUnit.NANOSECONDS.toMillis(nanos), "HH:mm:ss.S")); } <START> } <END></code><technical_language>useful print out description.getClassName() lots of tests extend this class</technical_language>

Target:
protected void succeeded(long nanos, Description description) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "{}.{} execution time: {}", description.getClassName(), description.getMethodName(), DurationFormatUtils.formatDuration(TimeUnit.NANOSECONDS.toMillis(nanos), "HH:mm:ss.S")); } }
Source:
<code>private List<TabletMetadata> findOverlappingTablets(KeyExtent loadRange, Iterator<TabletMetadata> tabletIter) { try { List<TabletMetadata> tablets = new ArrayList<>(); TabletMetadata currTablet = tabletIter.next(); int cmp; while ((cmp = PREV_COMP.compare(currTablet.getPrevEndRow(), loadRange.getPrevEndRow())) < 0) { currTablet = tabletIter.next(); } if (cmp != 0) { throw new IllegalStateException("Unexpected prev end row " + currTablet + " " + loadRange); } tablets.add(currTablet); while ((cmp = END_COMP.compare(currTablet.getEndRow(), loadRange.getEndRow())) < 0) { currTablet = tabletIter.next(); tablets.add(currTablet); } if (cmp != 0) { throw new IllegalStateException("Unexpected end row " + currTablet + " " + loadRange); } return tablets; } catch (NoSuchElementException e) { NoSuchElementException ne2 = <START> new NoSuchElementException("Failed to find overlapping tablets for " + loadRange); <END> ne2.initCause(e); throw ne2; } }</code><technical_language>include currTablet here, in IllegalStateException (would declare variable try, of course). Also, instead of throwing NoSuchElementException here, .initCause, throw new IllegalStateException(msg, e);</technical_language>

Target:
private List<TabletMetadata> findOverlappingTablets(KeyExtent loadRange, Iterator<TabletMetadata> tabletIter) { TabletMetadata currTablet = null; try { List<TabletMetadata> tablets = new ArrayList<>(); currTablet = tabletIter.next(); int cmp; while ((cmp = PREV_COMP.compare(currTablet.getPrevEndRow(), loadRange.getPrevEndRow())) < 0) { currTablet = tabletIter.next(); } if (cmp != 0) { throw new IllegalStateException("Unexpected prev end row " + currTablet + " " + loadRange); } tablets.add(currTablet); while ((cmp = END_COMP.compare(currTablet.getEndRow(), loadRange.getEndRow())) < 0) { currTablet = tabletIter.next(); tablets.add(currTablet); } if (cmp != 0) { throw new IllegalStateException("Unexpected end row " + currTablet + " " + loadRange); } return tablets; } catch (NoSuchElementException e) { NoSuchElementException ne2 = new NoSuchElementException( "Failed to find overlapping tablets " + currTablet + " " + loadRange); ne2.initCause(e); throw ne2; } }
Source:
<code>public PluginInterface findPlugin( Instance instance ) { PluginInterface result = null; if( this.simulatePlugins ) { result = new PluginMock(); } else { String installerName = null; if( instance.getComponent() != null ) installerName = ComponentHelpers.findComponentInstaller( instance.getComponent()); for( PluginInterface pi : this.plugins ) { if( pi.getPluginName().equalsIgnoreCase( installerName )) { result = pi; break; } } if( result == null ) this.logger.severe( "No plugin was found for instance '" + instance.getName() + "' with installer '" + installerName + "'." ); } if( result != null ) result.setNames( this.applicationName, this.scopedInstancePath ); <START> return (result == null ? null : new PluginProxy(result)); <END> }</code><technical_language>Surrounding brackets useless</technical_language>

Target:
public PluginInterface findPlugin( Instance instance ) { PluginInterface result = null; if( this.simulatePlugins ) { result = new PluginMock(); } else { String installerName = null; if( instance.getComponent() != null ) installerName = ComponentHelpers.findComponentInstaller( instance.getComponent()); for( PluginInterface pi : this.plugins ) { if( pi.getPluginName().equalsIgnoreCase( installerName )) { result = pi; break; } } if( result == null ) this.logger.severe( "No plugin was found for instance '" + instance.getName() + "' with installer '" + installerName + "'." ); } if( result != null ) result.setNames( this.applicationName, this.scopedInstancePath ); return result == null ? null : new PluginProxy(result); }
Source:
<code>public void checkSpecificAccessControl() { <START> AccountAttributes account = logic.getAccount(userInfo.getId()); <END> if (account == null) { throw new UnauthorizedAccessException("This account is not registered"); } gateKeeper.verifyInstructorPrivileges(account); }</code><technical_language>is a potential NPE if userInfo is null (unregistered student)</technical_language>

Target:
public void checkSpecificAccessControl() { String entityType = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE); if (!((entityType.equals(Const.EntityType.STUDENT) && userInfo.isStudent) || (entityType.equals(Const.EntityType.INSTRUCTOR) && userInfo.isInstructor))) { throw new UnauthorizedAccessException("Current account cannot access to courses of request entity type"); } }
Source:
<code>public void testStaticGroupsAlphabeticalOrder() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); checkConfig.addAttribute("option", "top"); checkConfig.addAttribute("groups", "org, java"); checkConfig.addAttribute("sortStaticImportsAlphabetically", "true"); <START> checkConfig.addAttribute("separated", "true"); <END> final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputImportOrderStaticGroupOrder.java"), expected); }</code><technical_language>good catch. @djydewang , remove changes. If need more tests - create new</technical_language>

Target:
public void testStaticGroupsAlphabeticalOrder() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); checkConfig.addAttribute("option", "top"); checkConfig.addAttribute("groups", "org, java"); checkConfig.addAttribute("sortStaticImportsAlphabetically", "true"); final String[] expected = { "6: " + getCheckMessage(MSG_SEPARATED_IN_GROUP, "org.*"), "8: " + getCheckMessage(MSG_SEPARATED_IN_GROUP, "java.util.Set"), }; verify(checkConfig, getPath("InputImportOrderStaticGroupOrder.java"), expected); }
Source:
<code>public Query getRevisionAndjobsInfoQuery(final String user, final boolean pending, final boolean running, final boolean finished, String startCursor, String endCursor, int pageSize, boolean first, FilterModel filterModel) { try { Jobs.Builder jobsBuilder = new Jobs.Builder().excludeDataManagement().excludeRemovedTime(); if (startCursor != null) jobsBuilder.after(startCursor); if (endCursor != null) jobsBuilder.before(endCursor); if (first) jobsBuilder.first(pageSize); else jobsBuilder.last(pageSize); List<JobInput> input = new ArrayList<>(); jobsBuilder.input(input); for (JobStatus status : JobStatus.values()) { boolean fetch; switch (status) { case PENDING: fetch = pending; break; case RUNNING: fetch = running; break; case FINISHED: fetch = finished; break; default: fetch = true; } if (fetch) { if (filterModel.isMatchAny() && !filterModel.getConstraints().isEmpty()) { for (Constraint constraint : filterModel.getConstraints()) { <START> input.add(getJobInputWithStatus(status, <END> user, constraint.getFilteringString(Field.ID), constraint.getFilteringString(Field.PRIORITY), constraint.getFilteringString(Field.NAME))); } } else { String id = null; String priority = null; String name = null; for (Constraint contraint : filterModel.getConstraints()) { id = getValue(id, contraint.getFilteringString(Field.ID)); priority = getValue(priority, contraint.getFilteringString(Field.PRIORITY)); name = getValue(name, contraint.getFilteringString(Field.NAME)); } input.add(getJobInputWithStatus(status, user, id, priority, name)); } } } Query.Builder queryBuilder = new Query.Builder().query(jobsBuilder.build().getQueryString()); return queryBuilder.build(); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage()); return null; } }</code><technical_language>create a private method in order improve readability</technical_language>

Target:
public Query getRevisionAndjobsInfoQuery(final String user, final boolean pending, final boolean running, final boolean finished, String startCursor, String endCursor, int pageSize, boolean first, FilterModel filterModel) { try { Jobs.Builder jobsBuilder = new Jobs.Builder().excludeDataManagement().excludeRemovedTime(); if (startCursor != null) jobsBuilder.after(startCursor); if (endCursor != null) jobsBuilder.before(endCursor); if (first) jobsBuilder.first(pageSize); else jobsBuilder.last(pageSize); List<JobInput> input = getJobInputs(user, pending, running, finished, filterModel); jobsBuilder.input(input); Query.Builder queryBuilder = new Query.Builder().query(jobsBuilder.build().getQueryString()); return queryBuilder.build(); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage()); return null; } }
Source:
<code>public SerializationConfigurationBuilder addContextInitializer(SerializationContextInitializer sci) { <START> if (sci != null) <END> attributes.attribute(SERIALIZATION_CONTEXT_INITIALIZERS).computeIfAbsent(ArrayList::new).add(sci); return this; }</code><technical_language>do need hide this ? NPE throw IllegalArgumentException</technical_language>

Target:
public SerializationConfigurationBuilder addContextInitializer(SerializationContextInitializer sci) { if (sci == null) throw new CacheConfigurationException("SerializationContextInitializer cannot be null"); attributes.attribute(SERIALIZATION_CONTEXT_INITIALIZERS).computeIfAbsent(ArrayList::new).add(sci); return this; }
Source:
<code>public void testAttemptLoadAsResourceFileDNE() throws Exception { Properties testProperties = PropertiesLoader.attemptLoadAsResource(NON_EXISTENT_FILENAME, null); <START> assertThat(testProperties.entrySet(), equalTo(Collections.emptySet())); <END> }</code><technical_language>assertThat(entries, is(empty())) - need create empty set</technical_language>

Target:
public void testAttemptLoadAsResourceFileDNE() throws Exception { Properties testProperties = PropertiesLoader.attemptLoadAsResource(NON_EXISTENT_FILENAME, null); assertThat(testProperties.entrySet(), is(empty())); }
Source:
<code>public void putWithAuthentication(String url, String username, String password, int id, Model model, AsyncHttpResponseHandler response) throws UnsupportedEncodingException { Header[] headers = { createBasicAuthenticationHeader(username, password) }; <START> String body = model.getData().toString().substring(0); <END> put(url, id, new ArrayList<Header>(Arrays.asList(headers)), body, response); }</code><technical_language>substring(0)</technical_language>

Target:
public void putWithAuthentication(String url, String username, String password, int id, Model model, AsyncHttpResponseHandler response) throws UnsupportedEncodingException { Header[] headers = { createBasicAuthenticationHeader(username, password) }; String body = model.getData().toString(); put(url, id, new ArrayList<Header>(Arrays.asList(headers)), body, response); }
Source:
<code>public ManagedArtifact getArtifact(String pathInfo) { try { repositorySynchronizationLock.lock(); <START> LOGGER.entering(); <END> ManagedArtifact managedArtifact = getMatchedArtifact(pathInfo); if (managedArtifact.isExpired()) { throw new ArtifactDownloadException("The requested artifact: " + managedArtifact.getArtifactName() + " has expired"); } LOGGER.exiting(managedArtifact); return managedArtifact; } finally { repositorySynchronizationLock.unlock(); } }</code><technical_language>LOGGER.entering(pathInfo) useful</technical_language>

Target:
public ManagedArtifact getArtifact(String pathInfo) { LOGGER.entering(pathInfo); try { repositorySynchronizationLock.lock(); ManagedArtifact managedArtifact = getMatchedArtifact(pathInfo); if (managedArtifact.isExpired()) { throw new ArtifactDownloadException("The requested artifact: " + managedArtifact.getArtifactName() + " has expired"); } LOGGER.exiting(managedArtifact); return managedArtifact; } finally { repositorySynchronizationLock.unlock(); } }
Source:
<code>public void reportMetrics(final Map<MetricName, Gauge> gauges, final Map<MetricName, Counter> counters, final Map<MetricName, Histogram> histograms, final Map<MetricName, Meter> meters, final Map<MetricName, Timer> timers) { <START> if (!elasticsearchClient.isElasticsearchAvailable() && !corePlugin.isOnlyLogElasticsearchMetricReports()) { <END> return; } long timestamp = clock.getTime(); final Timer.Context time = registry.timer(reportingTimeMetricName).time(); final MetricsOutputStreamHandler metricsOutputStreamHandler = new MetricsOutputStreamHandler(gauges, counters, histograms, meters, timers, timestamp); if (!corePlugin.isOnlyLogElasticsearchMetricReports()) { httpClient.send("POST", corePlugin.getElasticsearchUrl() + "/_bulk", null, metricsOutputStreamHandler, new ElasticsearchClient.BulkErrorReportingResponseHandler()); } else { try { final ByteArrayOutputStream os = new ByteArrayOutputStream(); metricsOutputStreamHandler.withHttpURLConnection(os); elasticsearchMetricsLogger.info(os.toString("UTF-8")); } catch (IOException e) { logger.warn(e.getMessage(), e); } } time.stop(); }</code><technical_language>remove && move httpClient.send</technical_language>

Target:
public void reportMetrics(final Map<MetricName, Gauge> gauges, final Map<MetricName, Counter> counters, final Map<MetricName, Histogram> histograms, final Map<MetricName, Meter> meters, final Map<MetricName, Timer> timers) { long timestamp = clock.getTime(); final Timer.Context time = registry.timer(reportingTimeMetricName).time(); final MetricsOutputStreamHandler metricsOutputStreamHandler = new MetricsOutputStreamHandler(gauges, counters, histograms, meters, timers, timestamp); if (!corePlugin.isOnlyLogElasticsearchMetricReports()) { if (!elasticsearchClient.isElasticsearchAvailable()) { return; } httpClient.send("POST", corePlugin.getElasticsearchUrl() + "/_bulk", null, metricsOutputStreamHandler, new ElasticsearchClient.BulkErrorReportingResponseHandler()); } else { try { final ByteArrayOutputStream os = new ByteArrayOutputStream(); metricsOutputStreamHandler.withHttpURLConnection(os); elasticsearchMetricsLogger.info(os.toString("UTF-8")); } catch (IOException e) { logger.warn(e.getMessage(), e); } } time.stop(); }
Source:
<code>public void transientFilesWorkAreCleaned() throws Exception { final File file = feature.resolveAndCreate(new File("pfouh")); <START> Thread.sleep(100); <END> service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }</code><technical_language>Is this needed</technical_language>

Target:
public void transientFilesWorkAreCleaned() throws Exception { final File file = feature.resolveAndCreate(new File("pfouh")); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }
Source:
<code>public static void validateFactoryOptions(Factory factory, ReadableConfig options) { factory.requiredOptions() <START> .forEach(option -> { <END> final Object value = readOption(options, option); if (value == null) { throw new ValidationException( String.format( "A value for required option '%s' is missing.\n\n" + "Required options are:\n\n" + "%s", option.key(), factory.requiredOptions().stream() .map(ConfigOption::key) .sorted() .collect(Collectors.joining("\n")))); } }); factory.optionalOptions() .forEach(option -> readOption(options, option)); }</code><technical_language>nit: change checks missing required options? I a nice user experience if list missing options front. simple as: List<String> missingRequiredOptions = factory.requiredOptions() .filter(option -> readOption(options, option) == null) .map(ConfigOption::key) .collect(Collectors.toList()); if (!missingRequiredOptions.isEmpty()) { throw new ValidationException(...); }</technical_language>

Target:
public static void validateFactoryOptions(Factory factory, ReadableConfig options) { final List<String> missingRequiredOptions = factory.requiredOptions().stream() .filter(option -> readOption(options, option) == null) .map(ConfigOption::key) .sorted() .collect(Collectors.toList()); if (!missingRequiredOptions.isEmpty()) { throw new ValidationException( String.format( "One or more required options are missing.\n\n" + "Missing required options are:\n\n" + "%s", String.join("\n", missingRequiredOptions))); } factory.optionalOptions() .forEach(option -> readOption(options, option)); }
Source:
<code><START> FirebaseRecyclerAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, FirebaseArray snapshots) { <END> mModelClass = modelClass; mModelLayout = modelLayout; mViewHolderClass = viewHolderClass; mSnapshots = snapshots; mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() { @Override public void onChanged(EventType type, int index, int oldIndex) { switch (type) { case Added: notifyItemInserted(index); break; case Changed: notifyItemChanged(index); break; case Removed: notifyItemRemoved(index); break; case Moved: notifyItemMoved(oldIndex, index); break; default: throw new IllegalStateException("Incomplete case statement"); } } @Override public void onCancelled(DatabaseError databaseError) { FirebaseRecyclerAdapter.this.onCancelled(databaseError); } }); }</code><technical_language>Please public classes: FirebaseArray IndexFirebaseArray. inherit extends of package. Example: I extends FirebaseArray provide filter local</technical_language>

Target:
FirebaseRecyclerAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, FirebaseArray snapshots) { mModelClass = modelClass; mModelLayout = modelLayout; mViewHolderClass = viewHolderClass; mSnapshots = snapshots; mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() { @Override public void onChanged(EventType type, int index, int oldIndex) { switch (type) { case ADDED: notifyItemInserted(index); break; case CHANGED: notifyItemChanged(index); break; case REMOVED: notifyItemRemoved(index); break; case MOVED: notifyItemMoved(oldIndex, index); break; default: throw new IllegalStateException("Incomplete case statement"); } } @Override public void onCancelled(DatabaseError databaseError) { FirebaseRecyclerAdapter.this.onCancelled(databaseError); } }); }
Source:
<code>public void click(){ <START> B86_ZK_4016FileDealer.writeMsg("click"); <END> }</code><technical_language>Clients.log</technical_language>

Target:
public void click(){ Clients.log("click"); }
Source:
<code>private String internalGetUserEnv(final Map<String, String> overrideEnv ) throws IOException, InterruptedException { WindowsProcess envProcess = new WindowsProcess(this.domain, this.user, this.password); try { envProcess.startWithLogon(new String[]{"cmd.exe", "/c", "set"}, null, null); int exitCode = envProcess.waitFor(); if (exitCode != 0) { throw win32ErrorIOException("Unable to read user environment from cmd.exe, exitCode=" + exitCode); } final InputStreamReader isr = new InputStreamReader(envProcess.inputStream); final BufferedReader br = new BufferedReader(isr); try { String[] vals; String line, varname, value; while ((line = br.readLine()) != null) { vals = line.split("="); varname = vals[0]; value = overrideEnv.get(varname); if (value == null) { overrideEnv.put(varname, vals[1]); } } } catch (IOException e) { throw e; } finally { try { br.close(); } catch (Exception e) { } try { isr.close(); } catch (Exception e) { } } String block = null; try { Class<?> cl = Class.forName("java.lang.ProcessEnvironment"); for (final Method method : cl.getDeclaredMethods()) { <START> if ("toEnvironmentBlock".equals(method.getName()) && <END> (method.getParameterTypes().length == 1)) { method.setAccessible(true); block = (String) method.invoke(null, overrideEnv); break; } } } catch (Exception e) { e.printStackTrace(); } return block; } finally { envProcess.destroy(); envProcess.close(); } }</code><technical_language>wrap this logic a private method a clear name</technical_language>

Target:
private String internalGetUserEnv(final Map<String, String> overrideEnv ) throws IOException, InterruptedException { WindowsProcess envProcess = new WindowsProcess(this.domain, this.user, this.password); try { envProcess.startWithLogon(new String[]{"cmd.exe", "/c", "set"}, null, null); int exitCode = envProcess.waitFor(); if (exitCode != 0) { throw win32ErrorIOException("Unable to read user environment from cmd.exe, exitCode=" + exitCode); } final InputStreamReader isr = new InputStreamReader(envProcess.inputStream); final BufferedReader br = new BufferedReader(isr); try { String[] vals; String line, varname, value; while ((line = br.readLine()) != null) { vals = line.split("="); varname = vals[0]; value = overrideEnv.get(varname); if (value == null) { overrideEnv.put(varname, vals[1]); } } } catch (IOException e) { throw e; } finally { try { br.close(); } catch (Exception e) { } try { isr.close(); } catch (Exception e) { } } String block = null; try { Class<?> cl = Class.forName("java.lang.ProcessEnvironment"); for (final Method method : cl.getDeclaredMethods()) { if (isToEnvironmentBlockMethodWithMapParameter(method)) { method.setAccessible(true); block = (String) method.invoke(null, overrideEnv); break; } } } catch (Exception e) { e.printStackTrace(); } return block; } finally { envProcess.destroy(); envProcess.close(); } }