auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void checkForMissedServletContexts() { try { BundleContext context = getContext(); if (context == null) { return; } Collection<ServiceReference<ServletContext>> references = getContext().getServiceReferences(ServletContext.class, null); for (ServiceReference<ServletContext> reference : references) { Bundle refBundle = reference.getBundle(); BundleContext bundlectx = refBundle.getBundleContext(); ServletContext service = bundlectx.getService(reference); if (service.getFilterRegistration(DELEGATING_FILTER) == null) { LOGGER.error( <START> "Platform filter delegate failed to start in time to inject itself into {}. This means the servlet will not properly attach the user subject to requests. Attempting to resolve the issue by restarting the bundle.", <END> refBundle.getSymbolicName(), refBundle.getBundleId(), refBundle.getSymbolicName()); refBundle.stop(); refBundle.start(); } } } catch (InvalidSyntaxException | BundleException e) { LOGGER.error( "Problem checking ServletContexts for DelegateServletFilter injections. One of the servlets running might not have all of the needed filters injected. See debug logs for additional details."); LOGGER.debug("Additional Details:", e); } }</code><technical_language>This line long; this bundle passed format checks</technical_language>

Target:
private void checkForMissedServletContexts() { try { BundleContext context = getContext(); if (context == null) { return; } Collection<ServiceReference<ServletContext>> references = context.getServiceReferences(ServletContext.class, null); for (ServiceReference<ServletContext> reference : references) { Bundle refBundle = reference.getBundle(); BundleContext bundlectx = refBundle.getBundleContext(); ServletContext service = bundlectx.getService(reference); if (service.getFilterRegistration(DELEGATING_FILTER) == null) { LOGGER.error( "Platform filter delegate failed to start in time to inject itself into {}. This means the servlet will not properly attach the user subject to requests. Attempting to resolve the issue by restarting the bundle.", refBundle.getSymbolicName(), refBundle.getBundleId(), refBundle.getSymbolicName()); refBundle.stop(); refBundle.start(); } } } catch (InvalidSyntaxException | BundleException e) { LOGGER.error( "Problem checking ServletContexts for DelegateServletFilter injections. One of the servlets running might not have all of the needed filters injected. A system restart is recommended. See debug logs for additional details."); LOGGER.debug("Additional Details:", e); } }
Source:
<code><START> public void addNonEmptyError(String error, List<String> errors) { <END> if (!error.isEmpty()) { errors.add(error); } }</code><technical_language>java * @param error a potentially empty error message. * @param errors List of error messages, @code{error} is appended to, if @code{error} is nonempty. @damithc errors description stills verbose, ideas for a one</technical_language>

Target:
public void addNonEmptyError(String error, List<String> errors) { if (error.isEmpty()) { return; } errors.add(error); }
Source:
<code>public void create(final String identifier, final ServerSideConfiguration config) throws EntityAlreadyExistsException, EhcacheEntityCreationException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { String message = "Unable to create entity for cluster id " + identifier + ": another client owns the maintenance lease"; LOGGER.error(message); <START> throw new EhcacheEntityCreationException(message); <END> } else { try { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { while (true) { ref.create(UUID.randomUUID()); try { EhcacheClientEntity entity = ref.fetchEntity(); try { configure(entity, config); return; } finally { entity.close(); } } catch (EntityNotFoundException e) { } } } catch (EntityNotProvidedException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } catch (EntityVersionMismatchException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } } finally { if (localMaintenance != null) { localMaintenance.unlock(); } } } }</code><technical_language>weird log throw - is throw enough</technical_language>

Target:
public void create(final String identifier, final ServerSideConfiguration config) throws EntityAlreadyExistsException, EhcacheEntityCreationException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { throw new EhcacheEntityCreationException("Unable to create entity for cluster id " + identifier + ": another client owns the maintenance lease"); } else { try { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { while (true) { ref.create(UUID.randomUUID()); try { EhcacheClientEntity entity = ref.fetchEntity(); try { configure(entity, config); return; } finally { entity.close(); } } catch (EntityNotFoundException e) { } } } catch (EntityNotProvidedException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } catch (EntityVersionMismatchException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } } finally { if (localMaintenance != null) { localMaintenance.unlock(); } } } }
Source:
<code>public PrologEnvironment newPrologEnvironment() throws CompileException { <START> PrologEnvironment env; <END> if (cLoader != null) { return envFactory.create(cLoader); } env = envFactory.create(getClass().getClassLoader()); String rules = getConfig().getPrologRules(); if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.intern("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }</code><technical_language>Move this declaration down, if. needed if a ClassLoader</technical_language>

Target:
public PrologEnvironment newPrologEnvironment() throws CompileException { if (ruleLoader != null) { return envFactory.create(ruleLoader); } PrologEnvironment env = envFactory.create(getClass().getClassLoader()); String rules = getConfig().getPrologRules(); if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.intern("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }
Source:
<code>public void retrieveConfigurationObjects( @Identification final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final com.alliander.osgp.domain.core.valueobjects.smartmetering.RetrieveConfigurationObjectsRequest request, final String messageType) throws FunctionalException { <START> LOGGER.debug("synchronizeTime for organisationIdentification: for deviceIdentification: {}", <END> organisationIdentification, deviceIdentification); final SmartMeter smartMeteringDevice = this.domainHelperService.findSmartMeter(deviceIdentification); final RetrieveConfigurationObjectsRequest requestDto = new RetrieveConfigurationObjectsRequest( request.getDeviceIdentification()); this.osgpCoreRequestMessageSender.send(new RequestMessage(correlationUid, organisationIdentification, deviceIdentification, smartMeteringDevice.getIpAddress(), requestDto), messageType); }</code><technical_language>"synchronizeTime" in debug message</technical_language>

Target:
public void retrieveConfigurationObjects( @Identification final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final com.alliander.osgp.domain.core.valueobjects.smartmetering.RetrieveConfigurationObjectsRequest request, final String messageType) throws FunctionalException { LOGGER.debug("retrieveConfigurationObjects for organisationIdentification: for deviceIdentification: {}", organisationIdentification, deviceIdentification); final SmartMeter smartMeteringDevice = this.domainHelperService.findSmartMeter(deviceIdentification); final RetrieveConfigurationObjectsRequest requestDto = new RetrieveConfigurationObjectsRequest( request.getDeviceIdentification()); this.osgpCoreRequestMessageSender.send(new RequestMessage(correlationUid, organisationIdentification, deviceIdentification, smartMeteringDevice.getIpAddress(), requestDto), messageType); }
Source:
<code>@Override public FileIO create(File file, OpenOption... modes) throws IOException { <START> if (file.getAbsolutePath().contains("node01-") && file.getAbsolutePath().contains("binary_meta")) <END> throw new IOException("No space left on device"); return delegateFactory.create(file, modes); }</code><technical_language>replace hardcoded "node01-"</technical_language>

Target:
@Override public FileIO create(File file, OpenOption... modes) throws IOException { if (unluckyConsistentId.get() != null && file.getAbsolutePath().contains(unluckyConsistentId.get()) && file.getAbsolutePath().contains(StandaloneGridKernalContext.BINARY_META_FOLDER)) throw new IOException("No space left on device"); return delegateFactory.create(file, modes); }
Source:
<code>public int serve(List<Path> resultsPaths, Path reportPath) throws IOException { if (notExists()) { throw new FileNotFoundException("Can't find allure installation"); } if (Files.exists(reportPath)) { FileUtils.deleteDirectory(reportPath.toFile()); } CommandLine commandLine = new CommandLine(getAllureExecutablePath().toAbsolutePath().toFile()); commandLine.addArgument("serve"); for (Path resultsPath : resultsPaths) { commandLine.addArgument(resultsPath.toAbsolutePath().toString(), true); } <START> DefaultExecutor executor = new DefaultExecutor(); <END> ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); executor.setExitValue(0); return executor.execute(commandLine); }</code><technical_language>remove duplicate code</technical_language>

Target:
public int serve(List<Path> resultsPaths, Path reportPath) throws IOException { this.checkAllureExists(); FileUtils.deleteQuietly(reportPath.toFile()); CommandLine commandLine = new CommandLine(getAllureExecutablePath().toAbsolutePath().toFile()); commandLine.addArgument("serve"); for (Path resultsPath : resultsPaths) { commandLine.addArgument(resultsPath.toAbsolutePath().toString(), true); } return execute(commandLine); }
Source:
<code>public void testPassParamsToEndpoint() throws IOException { String requestString = "/context?queryParam=some%20value"; boolean isSpaceCharacterEscaped = false; logViewerClient.clearLogs(); try { HttpRequestUtil.sendGetRequest(getApiInvocationURL("test") + requestString, null); } catch (Exception timeout) { } <START> LogEvent[] logs = logViewerClient.getAllSystemLogs(); <END> for (LogEvent logEvent : logs) { String message = logEvent.getMessage(); if (message.contains("queryParam = some%20value")) { isSpaceCharacterEscaped = true; break; } } Assert.assertTrue(isSpaceCharacterEscaped, "Fail to send a message via REST when query parameter consist of space character"); }</code><technical_language>getAllSystemLogs() method is deprecated. correct method</technical_language>

Target:
public void testPassParamsToEndpoint() throws Exception { String requestString = "/context?queryParam=some%20value"; boolean isSpaceCharacterEscaped = false; logViewerClient.clearLogs(); try { HttpRequestUtil.sendGetRequest(getApiInvocationURL("test") + requestString, null); } catch (Exception timeout) { } LogEvent[] logs = logViewerClient.getAllRemoteSystemLogs(); for (LogEvent logEvent : logs) { String message = logEvent.getMessage(); if (message.contains("queryParam = some%20value")) { isSpaceCharacterEscaped = true; break; } } Assert.assertTrue(isSpaceCharacterEscaped, "Fail to send a message via REST when query parameter consist of space character"); }
Source:
<code>public void testMultipleDeploy() throws Exception { <START> System.out.println("~~! " + testsCfg.description()); <END> runInAllDataModes(new ServiceTestRunnable(true, new DeployClosure() { @Override public void run(IgniteServices services, String svcName, TestService svc) throws Exception { services.deployMultiple(svcName, (Service)svc, 0, 1); waitForServiceDeploymentIfNeeded(services, svcName); } })); }</code><technical_language>I suggest GridAbstractTest.info (if this output is needed)</technical_language>

Target:
public void testMultipleDeploy() throws Exception { runInAllDataModes(new ServiceTestRunnable(true, new DeployClosure() { @Override public void run(IgniteServices services, String svcName, TestService svc) throws Exception { services.deployMultiple(svcName, (Service)svc, 0, 1); waitForServiceDeploymentIfNeeded(services, svcName); } })); }
Source:
<code>private Quota generateQuotaForNewStoragePool() { <START> boolean isDefaultQuota = (getStoragePool().getQuotaEnforcementType() == QuotaEnforcementTypeEnum.DISABLED); <END> Quota defaultStoragePoolQuota = getQuotaHelper().getUnlimitedQuota(getStoragePool(), isDefaultQuota); return defaultStoragePoolQuota; }</code><technical_language>I this boolean removed now, add a default quota time create a DC, flag time edit it. creation of quota time defaultQuota = true</technical_language>

Target:
private Quota generateQuotaForNewStoragePool() { return getQuotaHelper().getUnlimitedQuota(getStoragePool(), true); }
Source:
<code>public void testTableReadonlyHidesAddRemoveButtons() throws NoRendererFoundException, NoPropertyDescriptorFoundExeption, EMFFormsNoRendererException { final TableControlHandle handle = createTableWithTwoTableColumns(); handle.getTableControl().setReadonly(true); shell.open(); final RendererResult result = SWTViewTestHelper.renderControl(handle.getTableControl(), domainElement, shell); assertTrue(result.getControl().isPresent() && result.getControl().get() instanceof Composite); final TableControlSWTRenderer swtRenderer = TableControlSWTRenderer.class.cast(result.getRenderer()); final Optional<Control> addRowButton = swtRenderer.getControlForAction(AddRowAction.ACTION_ID); final Optional<Control> removeRowButton = swtRenderer.getControlForAction(RemoveRowAction.ACTION_ID); final Optional<Control> duplicateRowButton = swtRenderer.getControlForAction(DuplicateRowAction.ACTION_ID); <START> assertTrue(!addRowButton.isPresent()); <END> assertTrue(!removeRowButton.isPresent()); assertTrue(!duplicateRowButton.isPresent()); }</code><technical_language>assertFalse</technical_language>

Target:
public void testTableReadonlyHidesAddRemoveButtons() throws NoRendererFoundException, NoPropertyDescriptorFoundExeption, EMFFormsNoRendererException { final TableControlHandle handle = createTableWithTwoTableColumns(); handle.getTableControl().setReadonly(true); shell.open(); final RendererResult result = SWTViewTestHelper.renderControl(handle.getTableControl(), domainElement, shell); assertTrue(result.getControl().isPresent() && result.getControl().get() instanceof Composite); final TableControlSWTRenderer swtRenderer = TableControlSWTRenderer.class.cast(result.getRenderer()); final Optional<Control> addRowButton = swtRenderer.getControlForAction(AddRowAction.ACTION_ID); final Optional<Control> removeRowButton = swtRenderer.getControlForAction(RemoveRowAction.ACTION_ID); final Optional<Control> duplicateRowButton = swtRenderer.getControlForAction(DuplicateRowAction.ACTION_ID); assertFalse(addRowButton.isPresent()); assertFalse(removeRowButton.isPresent()); assertFalse(duplicateRowButton.isPresent()); }
Source:
<code>public void run() { if(isValid()) { if(getRunLocal() == false) { try{ ScpClient scpclient = new ScpClient(); serverfileName = fileName.substring(fileName.lastIndexOf('/')+1); tmpfileName="/tmp/"+ serverfileName; scpclient.transfer(fileName,tmpfileName); <START> }catch(Exception e){e.printStackTrace();} <END> } String[] script = buildScript(); String[] envVars = getEnvironmentVariables(); if(continueRun) { ScriptConsole console; if(getRunLocal() == false) { console = ScriptConsole.getInstance(serverfileName); } else { console = ScriptConsole.getInstance(fileName); } console.run(script, envVars, new PasswordPrompt(IDESessionSettings.password), new StapErrorParser()); } } LogManager.logDebug("End run:", this); }</code><technical_language>Please catch Exception this catch RuntimeException too</technical_language>

Target:
public void run() { if(isValid()) { if(getRunLocal() == false) { try{ ScpClient scpclient = new ScpClient(); serverfileName = fileName.substring(fileName.lastIndexOf('/')+1); tmpfileName="/tmp/"+ serverfileName; scpclient.transfer(fileName,tmpfileName); }catch(Exception e){e.printStackTrace();} } String[] script = buildScript(); String[] envVars = getEnvironmentVariables(); if(continueRun) { ScriptConsole console; if(getRunLocal() == false) { console = ScriptConsole.getInstance(serverfileName); } else { console = ScriptConsole.getInstance(fileName); } console.run(script, envVars, new PasswordPrompt(IDESessionSettings.password), new StapErrorParser()); } } }
Source:
<code>public void testCurrentAndNextReturnsCorrect() { ArrayList<CandidateClusterContext> arrayList = new ArrayList<>(); CandidateClusterContext first = createContext(1); arrayList.add(first); CandidateClusterContext second = createContext(2); arrayList.add(second); ClusterDiscoveryService discoveryService = new ClusterDiscoveryService(arrayList, 10, lifecycleService); assertEquals(first, discoveryService.current()); <START> assertEquals(second, searchAndGetNextCluster(1, discoveryService)); <END> assertEquals(second, discoveryService.current()); assertEquals(first, searchAndGetNextCluster(2, discoveryService)); assertEquals(first, discoveryService.current()); }</code><technical_language>I understand searchAndGetNextCluster . giving index ? simpler replace this method like: private CandidateClusterContext getNextCluster(ClusterDiscoveryService discoveryService) { AtomicReference<CandidateClusterContext> currentCandidate = new AtomicReference<>(); discoveryService.tryNextCluster((current, next) -> { currentCandidate.set(next); return true; }); return currentCandidate.get(); }</technical_language>

Target:
public void testCurrentAndNextReturnsCorrect() { ArrayList<CandidateClusterContext> arrayList = new ArrayList<>(); CandidateClusterContext first = createContext(1); arrayList.add(first); CandidateClusterContext second = createContext(2); arrayList.add(second); ClusterDiscoveryService discoveryService = new ClusterDiscoveryService(arrayList, 10, lifecycleService); assertEquals(first, discoveryService.current()); assertEquals(second, getNextCluster(discoveryService)); assertEquals(second, discoveryService.current()); assertEquals(first, getNextCluster(discoveryService)); assertEquals(first, discoveryService.current()); }
Source:
<code>public static void browsePostOrPage(Context context, Blog blog, Post post) { if (blog == null || post == null || TextUtils.isEmpty(post.getPermaLink())) return; String url = post.getPermaLink(); <START> if (!post.isPublished()) { <END> if (-1 == url.indexOf('?')) { url = url.concat("?preview=true"); } else { url = url.concat("&preview=true"); } } WPWebViewActivity.openUrlByUsingBlogCredentials(context, blog, post, url); }</code><technical_language>able rely post.isLocalChange() for that</technical_language>

Target:
public static void browsePostOrPage(Context context, Blog blog, Post post) { if (blog == null || post == null || TextUtils.isEmpty(post.getPermaLink())) return; String url = post.getPermaLink(); url = UrlUtils.appendUrlParameter(url, "preview", "true"); WPWebViewActivity.openUrlByUsingBlogCredentials(context, blog, post, url); }
Source:
<code><START> public PluginInterface waitForPluginToBeAvailable( Class<? extends PluginTypeInterface> pluginType, String pluginId, int waitLimit ) { <END> int timeToSleep = 1; try { Thread.sleep( timeToSleep ); waitLimit -= timeToSleep; } catch ( InterruptedException e ) { throw new RuntimeException( "Waiting for Plugin to be Available interrupted!", e ); } PluginInterface pluginInterface = findPluginWithId( pluginType, pluginId ); return waitLimit == 0 && pluginInterface == null ? null : pluginInterface != null ? pluginInterface : waitForPluginToBeAvailable( pluginType, pluginId, waitLimit ); }</code><technical_language>this method private</technical_language>

Target:
private PluginInterface waitForPluginToBeAvailable( Class<? extends PluginTypeInterface> pluginType, String pluginId, int waitLimit ) { int timeToSleep = 50; try { Thread.sleep( timeToSleep ); waitLimit -= timeToSleep; } catch ( InterruptedException e ) { log.logError( e.getLocalizedMessage(), e ); Thread.currentThread().interrupt(); return null; } PluginInterface pluginInterface = findPluginWithId( pluginType, pluginId ); return waitLimit <= 0 && pluginInterface == null ? null : pluginInterface != null ? pluginInterface : waitForPluginToBeAvailable( pluginType, pluginId, waitLimit ); }
Source:
<code>public static Path fromPortableString(String portablePathString) { Objects.requireNonNull(portablePathString, "The given string must not be null"); if (File.separator.equals(PORTABLE_SEPARATOR)) { return Paths.get(portablePathString); } if (portablePathString.contains(WINDOWS_SEPARATOR)) { log.warn( <START> "The given portable path contains occurrences of the Windows separator character '" <END> + WINDOWS_SEPARATOR + "'. This will most likely lead to issues as this character is used as the " + "separator by the local filesystem, meaning the interpretation of the portable " + "path will not match the path on the sender side."); } String localPathString = portablePathString.replace(PORTABLE_SEPARATOR, File.separator); return Paths.get(localPathString); }</code><technical_language>warning message other is detailed more related transmission of activities. I do if is helpful mention a sender in message utility methods. if message in log file is helpful include path do in context happen (I guess is XStream Marshaller converting activities)</technical_language>

Target:
public static Path fromPortableString(String portablePathString) { Objects.requireNonNull(portablePathString, "The given string must not be null"); String localPathString; if (File.separator.equals(PORTABLE_SEPARATOR)) { localPathString = portablePathString; } else { if (portablePathString.contains(File.separator)) { log.warn( "The given portable path contains occurrences of the local separator character '" + File.separator + "'. This character was not seen as a separator on the system where the portable " + "path string was created, meaning resolving it locally will lead to a different " + "path. portable path string: " + portablePathString); } localPathString = portablePathString.replace(PORTABLE_SEPARATOR, File.separator); } Path localPath = Paths.get(localPathString); return normalize(localPath); }
Source:
<code>public ASTNode visit(Term trm, Void _) throws ParseFailedException { boolean error = false; <START> if (strict && !trm.getSort().equals(maxSort)) <END> error = true; if ((!trm.getSort().equals(KSorts.K) && !trm.getSort().equals(KSorts.KITEM) && !trm.getSort().equals(KSorts.KRESULT))) if (!context.isSubsortedEq(maxSort, trm.getSort())) error = true; if (error) { KException kex = new KException( ExceptionType.ERROR, KExceptionGroup.CRITICAL, "type error: unexpected term '" + trm + "' of sort '" + trm.getSort() + "', expected sort '" + maxSort + "'.", getName(), trm.getFilename(), trm.getLocation()); throw new ParseFailedException(kex); } return trm; }</code><technical_language>something's confusing here. If strict is true, this filter rejects well-typed terms? Why</technical_language>

Target:
public ASTNode visit(Term trm, Void _) throws ParseFailedException { boolean error = false; if (strict && !trm.getSort().equals(maxSort)) error = true; if ((!trm.getSort().equals(Sort.K) && !trm.getSort().equals(Sort.KITEM) && !trm.getSort().equals(Sort.KRESULT))) if (!context.isSubsortedEq(maxSort, trm.getSort())) error = true; if (error) { KException kex = new KException( ExceptionType.ERROR, KExceptionGroup.CRITICAL, "type error: unexpected term '" + trm + "' of sort '" + trm.getSort() + "', expected sort '" + maxSort + "'.", getName(), trm.getFilename(), trm.getLocation()); throw new ParseFailedException(kex); } return trm; }
Source:
<code>public ServletContextInitializer servletContextInitializer() { return servletContext -> { WebApplicationContext ctx = getRequiredWebApplicationContext(servletContext); SessionCookieConfig config = servletContext.getSessionCookieConfig(); config.setHttpOnly(true); <START> config.setSecure(true); <END> XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING); XRLog.setLoggingEnabled(false); }; }</code><technical_language>this work in dev mode, config.setSecure(environment.acceptsProfiles(Initializer.PROFILE_LIVE ))</technical_language>

Target:
public ServletContextInitializer servletContextInitializer() { return servletContext -> { WebApplicationContext ctx = getRequiredWebApplicationContext(servletContext); ConfigurableEnvironment environment = ctx.getBean(ConfigurableEnvironment.class); SessionCookieConfig config = servletContext.getSessionCookieConfig(); config.setHttpOnly(true); config.setSecure(environment.acceptsProfiles(Initializer.PROFILE_LIVE)); XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING); XRLog.setLoggingEnabled(false); }; }
Source:
<code>public String buildUpdateSelective(ProviderContext context) { final String tableName = context.getMapperType().getAnnotation(BaseMapper.Meta.class).tableName(); Map<String, String> columnMap = getColumnMap(context); <START> StringBuffer sqlBuffer = new StringBuffer(); <END> sqlBuffer.append("<script>"); sqlBuffer.append("update "); sqlBuffer.append(tableName); sqlBuffer.append("<set>"); for (Map.Entry<String, String> entry : columnMap.entrySet()) { sqlBuffer.append("<if test=\"").append(entry.getValue()).append(" != null\">"); sqlBuffer.append(entry.getKey()).append(" = #{").append(entry.getValue()).append("} ,"); sqlBuffer.append("</if>"); } sqlBuffer.append("</set>"); sqlBuffer.append("where id = #{id}"); sqlBuffer.append("</script>"); return sqlBuffer.toString(); }</code><technical_language>Please StringBuilder</technical_language>

Target:
public String buildUpdateSelective(ProviderContext context) { final String tableName = context.getMapperType().getAnnotation(BaseMapper.Meta.class).tableName(); Map<String, String> columnMap = getColumnMap(context); StringBuilder sqlBuffer = new StringBuilder(); sqlBuffer.append("<script>"); sqlBuffer.append("update "); sqlBuffer.append(tableName); sqlBuffer.append("<set>"); for (Map.Entry<String, String> entry : columnMap.entrySet()) { sqlBuffer.append("<if test=\"").append(entry.getValue()).append(" != null\">"); sqlBuffer.append(entry.getKey()).append(" = #{").append(entry.getValue()).append("} ,"); sqlBuffer.append("</if>"); } sqlBuffer.append("</set>"); sqlBuffer.append("where id = #{id}"); sqlBuffer.append("</script>"); return sqlBuffer.toString(); }
Source:
<code>private AsyncTimelockService createRawAsyncTimelockService( String client, Supplier<ManagedTimestampService> timestampServiceSupplier) { <START> log.info("Creating async timelock service."); <END> ScheduledExecutorService reaperExecutor = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("async-lock-reaper-" + client + "-%d") .setDaemon(true) .build()); ScheduledExecutorService timeoutExecutor = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("async-lock-timeouts-" + client + "-%d") .setDaemon(true) .build()); return new AsyncTimelockServiceImpl( AsyncLockService.createDefault(reaperExecutor, timeoutExecutor), timestampServiceSupplier.get()); }</code><technical_language>small caveat here, this method is called AwaitingLeadershipProxyso this get logged leader - want move this createTimeLockServicesWithAsync</technical_language>

Target:
private AsyncTimelockService createRawAsyncTimelockService( String client, Supplier<ManagedTimestampService> timestampServiceSupplier) { ScheduledExecutorService reaperExecutor = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("async-lock-reaper-" + client + "-%d") .setDaemon(true) .build()); ScheduledExecutorService timeoutExecutor = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("async-lock-timeouts-" + client + "-%d") .setDaemon(true) .build()); return new AsyncTimelockServiceImpl( AsyncLockService.createDefault(reaperExecutor, timeoutExecutor), timestampServiceSupplier.get()); }
Source:
<code>public void testDisconnectedEventFactHandle() { String drl = "declare String \n" + " @role(event)\n" + "end\n"; KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL) .build() .newKieSession(); DefaultFactHandle helloHandle = (DefaultFactHandle) ksession.insert("hello"); DefaultFactHandle goodbyeHandle = (DefaultFactHandle) ksession.insert("goodbye"); FactHandle key = DefaultFactHandle.createFromExternalFormat(helloHandle.toExternalForm()); assertThat(key).isInstanceOf(EventFactHandle.class); <START> assertThat(ksession.getObject(key)).isEqualTo("hello"); <END> key = DefaultFactHandle.createFromExternalFormat(goodbyeHandle.toExternalForm()); assertThat(key).isInstanceOf(EventFactHandle.class); assertThat(ksession.getObject(key)).isEqualTo("goodbye"); }</code><technical_language>of assertions essentially checking thing, SoftAssertions check report of once</technical_language>

Target:
public void testDisconnectedEventFactHandle() { final String drl = "declare String \n" + " @role(event)\n" + "end\n"; final KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL) .build() .newKieSession(); final DefaultFactHandle helloHandle = (DefaultFactHandle) ksession.insert("hello"); final DefaultFactHandle goodbyeHandle = (DefaultFactHandle) ksession.insert("goodbye"); final SoftAssertions softly = new SoftAssertions(); FactHandle key = DefaultFactHandle.createFromExternalFormat(helloHandle.toExternalForm()); softly.assertThat(key).isInstanceOf(EventFactHandle.class); softly.assertThat(ksession.getObject(key)).isEqualTo("hello"); key = DefaultFactHandle.createFromExternalFormat(goodbyeHandle.toExternalForm()); softly.assertThat(key).isInstanceOf(EventFactHandle.class); softly.assertThat(ksession.getObject(key)).isEqualTo("goodbye"); softly.assertAll(); }
Source:
<code>public ReviewerInfo format(ReviewerResource rsrc) throws OrmException, NoSuchChangeException { ReviewerInfo out = new ReviewerInfo(); Account account = rsrc.getAccount(); out.id = account.getId().toString(); out.email = account.getPreferredEmail(); out.name = account.getFullName(); Change change = rsrc.getChange(); PatchSet.Id psId = change.currentPatchSetId(); List<PatchSetApproval> approvals = db.get().patchSetApprovals() .byPatchSetUser(psId, account.getId()).toList(); ChangeControl control = controlFactory.controlFor(change, userFactory.create(account.getId())); FunctionState fs = functionState.create(control, psId, approvals); for (ApprovalType at : approvalTypes.getApprovalTypes()) { CategoryFunction.forCategory(at.getCategory()).run(at, fs); } <START> out.approvals = Maps.newHashMapWithExpectedSize(approvals.size()); <END> for (PatchSetApproval ca : approvals) { for (PermissionRange pr : control.getLabelRanges()) { if (pr.getMin() != 0 || pr.getMax() != 0) { ApprovalType at = approvalTypes.byId(ca.getCategoryId()); out.approvals.put(at.getCategory().getLabelName(), ApprovalCategoryValue.formatValue(ca.getValue())); } } } return out; }</code><technical_language>If this map is empty end null out</technical_language>

Target:
public List<ReviewerInfo> format(ReviewerResource rsrc) throws OrmException, NoSuchChangeException { return format(ImmutableList.<ReviewerResource> of(rsrc)); }
Source:
<code>private void prepareDescription(final Description description) { if (description == null || TextUtils.isEmpty(description.getContent()) || description == Description.emptyDescription) { return; } if (description.getType() == Description.HTML) { disposables.add(Single.just(description.getContent()) <START> .map((@NonNull String descriptionText) -> HtmlCompat.fromHtml(descriptionText, HtmlCompat.FROM_HTML_MODE_LEGACY)) .subscribeOn(Schedulers.computation()) <END> .observeOn(AndroidSchedulers.mainThread()) .subscribe((@NonNull Spanned spanned) -> { videoDescriptionView.setText(spanned); videoDescriptionView.setVisibility(View.VISIBLE); })); } else if (description.getType() == Description.MARKDOWN) { final Markwon markwon = Markwon.builder(getContext()) .usePlugin(LinkifyPlugin.create()) .build(); markwon.setMarkdown(videoDescriptionView, description.getContent()); videoDescriptionView.setVisibility(View.VISIBLE); } else { videoDescriptionView.setAutoLinkMask(Linkify.WEB_URLS); videoDescriptionView.setText(description.getContent(), TextView.BufferType.SPANNABLE); videoDescriptionView.setVisibility(View.VISIBLE); } }</code><technical_language>@friendlyanon</technical_language>

Target:
private void prepareDescription(final Description description) { if (description == null || TextUtils.isEmpty(description.getContent()) || description == Description.emptyDescription) { return; } if (description.getType() == Description.HTML) { disposables.add(Single.just(description.getContent()) .map((@NonNull final String descriptionText) -> HtmlCompat.fromHtml(descriptionText, HtmlCompat.FROM_HTML_MODE_LEGACY)) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((@NonNull final Spanned spanned) -> { videoDescriptionView.setText(spanned); videoDescriptionView.setVisibility(View.VISIBLE); })); } else if (description.getType() == Description.MARKDOWN) { final Markwon markwon = Markwon.builder(requireContext()) .usePlugin(LinkifyPlugin.create()) .build(); markwon.setMarkdown(videoDescriptionView, description.getContent()); videoDescriptionView.setVisibility(View.VISIBLE); } else { videoDescriptionView.setAutoLinkMask(Linkify.WEB_URLS); videoDescriptionView.setText(description.getContent(), TextView.BufferType.SPANNABLE); videoDescriptionView.setVisibility(View.VISIBLE); } }
Source:
<code>public boolean connectHostToDomainsInActiveOrUnknownStatus(VDS vds) { <START> StoragePool sp = DbFacade.getInstance().getStoragePoolDao().getForVds(vds.getId()); <END> ConnectHostToStoragePoolServersParameters params = new ConnectHostToStoragePoolServersParameters(sp, vds, false); return backend .runInternalAction(VdcActionType.ConnectHostToStoragePoolServers, params) .getSucceeded(); }</code><technical_language>please @Inject for StoragePoolDao.</technical_language>

Target:
public boolean connectHostToDomainsInActiveOrUnknownStatus(VDS vds) { StoragePool sp = storagePoolDao.getForVds(vds.getId()); ConnectHostToStoragePoolServersParameters params = new ConnectHostToStoragePoolServersParameters(sp, vds, false); return backend .runInternalAction(VdcActionType.ConnectHostToStoragePoolServers, params) .getSucceeded(); }
Source:
<code>void handleDirectoryWebhook(Map<String, List<String>> headers, String body, String method, String path) throws AuthException { try { WebhookPackage webhookPackage = directoryClient.handleWebhook(headers, body, method, path); if (webhookPackage instanceof DirectoryUserDeviceLinkCompletionWebhookPackage) { DeviceLinkCompletionResponse response = ((DirectoryUserDeviceLinkCompletionWebhookPackage) webhookPackage).getDeviceLinkCompletionResponse(); LOG.info("Directory User Device link completion:"); <START> LOG.info(" Device ID: " + naForNull(response.getDeviceId().toString())); <END> LOG.info(" Public Key ID: " + naForNull(response.getDevicePublicKeyId())); LOG.info(" Public Key: " + naForNull(response.getDevicePublicKey())); deviceLinkCompletionMap.put(response.getDeviceId().toString(), response); } } catch (BaseException apiException) { throw new AuthException("Error handling Directory webhook", apiException); } }</code><technical_language>If calling naForNull(), real concerns of response.getDeviceId() returning null? If so, calling .toString() a potentially-null object throw a NPE. naForNull is useless of null checks .toString()</technical_language>

Target:
void handleDirectoryWebhook(Map<String, List<String>> headers, String body, String method, String path) throws AuthException { try { WebhookPackage webhookPackage = directoryClient.handleWebhook(headers, body, method, path); if (webhookPackage instanceof DirectoryUserDeviceLinkCompletionWebhookPackage) { DeviceLinkCompletionResponse response = ((DirectoryUserDeviceLinkCompletionWebhookPackage) webhookPackage).getDeviceLinkCompletionResponse(); LOG.info("Directory User Device link completion:"); LOG.info(" Device ID: " + safeNull(response.getDeviceId().toString())); LOG.info(" Public Key ID: " + safeNull(response.getDevicePublicKeyId())); LOG.info(" Public Key: " + safeNull(response.getDevicePublicKey())); deviceLinkCompletionMap.put(response.getDeviceId().toString(), response); } } catch (BaseException apiException) { throw new AuthException("Error handling Directory webhook", apiException); } }
Source:
<code>public synchronized void onBecomeOnlineFromOffline(Message message, NotificationContext context) { if (_numOfSuccessBeforeFail-- > 0) { <START> System.out.println("State transition from Offline to Online"); <END> return; } throw new HelixException("Number of Success reached"); }</code><technical_language>lets loggers</technical_language>

Target:
public synchronized void onBecomeOnlineFromOffline(Message message, NotificationContext context) { if (_numOfSuccessBeforeFail-- > 0) { LOG.info("State transition from Offline to Online"); return; } throw new HelixException("Number of Success reached"); }
Source:
<code>private boolean isStorageNotLow(Context context) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK); <START> intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW); <END> Intent intent = context.registerReceiver(null, intentFilter); if (intent == null || intent.getAction() == null) { return true; } else { switch (intent.getAction()) { case Intent.ACTION_DEVICE_STORAGE_OK: return true; case Intent.ACTION_DEVICE_STORAGE_LOW: return false; default: return true; } } }</code><technical_language>@jdegroot-dss works for internal storage. downloading external storage, this method of determining is useless false. If is space in internal storage, download external storage this requirement is enabled</technical_language>

Target:
private boolean isStorageNotLow(Context context) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW); @Nullable Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW)); return intent == null; }
Source:
<code>public boolean setTransactionTimeout(int seconds) throws XAException { <START> log.infof("setTransactionTimeout: setting timeout: %s", seconds); <END> this.transactionTimeout = seconds; return true; }</code><technical_language>tracef</technical_language>

Target:
public boolean setTransactionTimeout(int seconds) throws XAException { log.tracef("setTransactionTimeout: setting timeout: %s", seconds); this.transactionTimeout = seconds; return true; }
Source:
<code>public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, PendingIntent operation) { checkNotNull(operation, "PendingIntent cannot be null."); networkCapabilities = new NetworkCapabilities(networkCapabilities); enforceNetworkRequestPermissions(networkCapabilities); enforceMeteredApnPolicy(networkCapabilities); ensureRequestableCapabilities(networkCapabilities); MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier( networkCapabilities.getNetworkSpecifier()); <START> if (networkCapabilities.getNetworkSpecifier() instanceof NetworkSpecifier.UidContainer) { if (((NetworkSpecifier.UidContainer) networkCapabilities.getNetworkSpecifier()).getUid() != Binder.getCallingUid()) { throw new SecurityException("Invalid UID provided by caller"); } } <END> NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.REQUEST); NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation); if (DBG) log("pendingRequest for " + nri); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, nri)); return networkRequest; }</code><technical_language>if implementing virtual dispatch solution a method base class, please regroup duplicated checks common utility method</technical_language>

Target:
public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, PendingIntent operation) { checkNotNull(operation, "PendingIntent cannot be null."); networkCapabilities = new NetworkCapabilities(networkCapabilities); enforceNetworkRequestPermissions(networkCapabilities); enforceMeteredApnPolicy(networkCapabilities); ensureRequestableCapabilities(networkCapabilities); MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier( networkCapabilities.getNetworkSpecifier()); if (networkCapabilities.getNetworkSpecifier() != null) { networkCapabilities.getNetworkSpecifier().checkUidIfNecessary(Binder.getCallingUid()); } NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.REQUEST); NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation); if (DBG) log("pendingRequest for " + nri); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, nri)); return networkRequest; }
Source:
<code>public void handleChildChange(String barrierParticipantPath, List<String> participantIds) { if (notAValidEvent()) { return; } if (participantIds == null) { LOG.info("Received notification with null participants for barrier: {}. Ignoring it.", barrierParticipantPath); return; } LOG.info(String.format("Current participants in barrier version: %s = %s.", barrierVersion, participantIds)); LOG.info(String.format("Expected participants in barrier version: %s = %s.", barrierVersion, expectedParticipantIds)); if (participantIds.size() == expectedParticipantIds.size() && CollectionUtils.containsAll(participantIds, expectedParticipantIds)) { String barrierStatePath = keyBuilder.getBarrierStatePath(barrierVersion); State barrierState = zkUtils.getZkClient().readData(barrierStatePath); if (Objects.equals(barrierState, State.NEW)) { LOG.info(String.format("Expected participants has joined the barrier version: %s. Marking the barrier state: %s as %s.", barrierVersion, barrierStatePath, State.DONE)); zkUtils.writeData(barrierStatePath, State.DONE); } <START> LOG.info("Unsubscribing child changes for the path: {}.", barrierParticipantPath); <END> zkUtils.unsubscribeChildChanges(barrierParticipantPath, this); } }</code><technical_language>LOG barrier version applicable. great for debuggability if do a grep "barrier version: xxx" view state transitions in barrier</technical_language>

Target:
public void handleChildChange(String barrierParticipantPath, List<String> participantIds) { if (notAValidEvent()) { return; } if (participantIds == null) { LOG.info("Received notification with null participants for barrier: {}. Ignoring it.", barrierParticipantPath); return; } LOG.info(String.format("Current participants in barrier version: %s = %s.", barrierVersion, participantIds)); LOG.info(String.format("Expected participants in barrier version: %s = %s.", barrierVersion, expectedParticipantIds)); if (participantIds.size() == expectedParticipantIds.size() && CollectionUtils.containsAll(participantIds, expectedParticipantIds)) { String barrierStatePath = keyBuilder.getBarrierStatePath(barrierVersion); State barrierState = zkUtils.getZkClient().readData(barrierStatePath); if (Objects.equals(barrierState, State.NEW)) { LOG.info(String.format("Expected participants has joined the barrier version: %s. Marking the barrier state: %s as %s.", barrierVersion, barrierStatePath, State.DONE)); zkUtils.writeData(barrierStatePath, State.DONE); } else { LOG.debug(String.format("Barrier version: %s is at: %s state. Not marking barrier as %s.", barrierVersion, barrierState, State.DONE)); } LOG.info("Unsubscribing child changes on the path: for barrier version: {}.", barrierParticipantPath, barrierVersion); zkUtils.unsubscribeChildChanges(barrierParticipantPath, this); } }
Source:
<code>public JsonPatchDocument appendCopy(String from, String path) { <START> operations.add(new JsonPatchOperation(JsonPatchOperationKind.COPY, Objects.requireNonNull(path, "'path' cannot be null."), Objects.requireNonNull(from, "'from' cannot be null."), null)); <END> return this; }</code><technical_language>nit: happening in this 1 statement - add, new & null checks. Breaking easier read</technical_language>

Target:
public JsonPatchDocument appendCopy(String from, String path) { Objects.requireNonNull(from, "'from' cannot be null."); Objects.requireNonNull(path, "'path' cannot be null."); operations.add(new JsonPatchOperation(JsonPatchOperationKind.COPY, path, from, null)); return this; }
Source:
<code><START> boolean deregisterHardDeleteMetric(String storeId) { <END> String prefix = storeId + SEPERATOR; return registry.remove(MetricRegistry.name(PersistentIndex.class, prefix + "CurrentHardDeleteProgress")) && registry .remove(MetricRegistry.name(Log.class, prefix + "PercentageHardDeleteCompleted")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteThreadRunning")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteCaughtUp")); }</code><technical_language>this function private</technical_language>

Target:
private boolean deregisterHardDeleteMetric(String storeId) { String prefix = storeId + SEPERATOR; return registry.remove(MetricRegistry.name(PersistentIndex.class, prefix + "CurrentHardDeleteProgress")) && registry .remove(MetricRegistry.name(Log.class, prefix + "PercentageHardDeleteCompleted")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteThreadRunning")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteCaughtUp")); }
Source:
<code>public static Gson getGson(){ if(null==gson){ <START> gson=new Gson(); <END> } return gson; }</code><technical_language>retrieve actual gson instance? I care if exposed component level</technical_language>

Target:
public static Gson getGson() { return ApplicationlessInjection.getInstance(CommonsApplication.getInstance()).getCommonsApplicationComponent().gson(); }
Source:
<code><START> public MPartStack createStack(String id, boolean visible) { <END> MPartStack newStack = modelService.createModelElement(MPartStack.class); newStack.getTags().add("newtablook"); newStack.setElementId(id); newStack.setToBeRendered(visible); return newStack; }</code><technical_language>check, this method declared private</technical_language>

Target:
private MPartStack createStack(String id, boolean visible) { MPartStack newStack = modelService.createModelElement(MPartStack.class); newStack.getTags().add("newtablook"); newStack.setElementId(id); newStack.setToBeRendered(visible); return newStack; }