auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<String, String> toConfig() { final Map<String, String> config = new HashMap<>(super.toConfig()); <START> final String systemName = getSystemName(); <END> final String streamId = getStreamId(); final String clientConfigPrefix = String.format(KinesisConfig.CONFIG_STREAM_KINESIS_CLIENT_LIB_CONFIG, systemName, streamId); this.region.ifPresent( val -> config.put(String.format(KinesisConfig.CONFIG_STREAM_REGION, systemName, streamId), val)); this.accessKey.ifPresent( val -> config.put(String.format(KinesisConfig.CONFIG_STREAM_ACCESS_KEY, systemName, streamId), val)); this.secretKey.ifPresent( val -> config.put(String.format(KinesisConfig.CONFIG_STREAM_SECRET_KEY, systemName, streamId), val)); this.kclConfig.forEach((k, v) -> config.put(clientConfigPrefix + k, v)); return config; }</code><technical_language>nit: rest of code-base final for local variables a bit boiler-platey</technical_language>

Target:
public Map<String, String> toConfig() { Map<String, String> config = new HashMap<>(super.toConfig()); String systemName = getSystemName(); String streamId = getStreamId(); String clientConfigPrefix = String.format(KinesisConfig.CONFIG_STREAM_KINESIS_CLIENT_LIB_CONFIG, systemName, streamId); this.region.ifPresent( val -> config.put(String.format(KinesisConfig.CONFIG_STREAM_REGION, systemName, streamId), val)); this.accessKey.ifPresent( val -> config.put(String.format(KinesisConfig.CONFIG_STREAM_ACCESS_KEY, systemName, streamId), val)); this.secretKey.ifPresent( val -> config.put(String.format(KinesisConfig.CONFIG_STREAM_SECRET_KEY, systemName, streamId), val)); this.kclConfig.forEach((k, v) -> config.put(clientConfigPrefix + k, v)); return config; }
Source:
<code>Map<Integer, ExposedByteArrayOutputStream> createOutputMap(final CompressionHeader header) throws IOException { final Map<Integer, ExposedByteArrayOutputStream> outputMap = new HashMap<>(); <START> for (final EncodingParams params : header.encodingMap.values()) { <END> if (params.id == EncodingID.EXTERNAL) { try (final ExposedByteArrayOutputStream ebaos = new ExposedByteArrayOutputStream()) { final int externalBlockId = ITF8.readUnsignedITF8(params.params); outputMap.put(externalBlockId, ebaos); } } } return outputMap; }</code><technical_language>This loop in createInputMap implemented streaming is done in Slice.getExternalInputMap()</technical_language>

Target:
Map<Integer, ExposedByteArrayOutputStream> createOutputMap(final CompressionHeader header) { return header.encodingMap.values() .stream() .filter(params -> params.id == EncodingID.EXTERNAL) .collect(Collectors.toMap( params -> ITF8.readUnsignedITF8(params.params), params -> new ExposedByteArrayOutputStream())); }
Source:
<code>public void testSerializeAndDeserializeSession() throws Exception { KieSession ksession = session.getStateful(); File tempFile = createTempFile(name.getMethodName(), ""); ksession.fireAllRules(); OutputStream fos = null; try { fos = new FileOutputStream(tempFile); Marshaller marshaller = KieServices.Factory.get().getMarshallers().newMarshaller(getKbase()); marshaller.marshall(fos, ksession); <START> } finally { <END> if (fos != null) { fos.close(); } } InputStream fis = null; try { fis = new FileInputStream(tempFile); Marshaller marshaller = KieServices.Factory.get().getMarshallers().newMarshaller(getKbase()); marshaller.unmarshall(fis, ksession); } finally { if (fis != null) { fis.close(); } } ksession.insert(new Promotion("Claire", "Scientist")); int firedRules = ksession.fireAllRules(); Assertions.assertThat(firedRules).isEqualTo(1); }</code><technical_language>Java 8. try-with-resources is friend</technical_language>

Target:
public void testSerializeAndDeserializeSession() throws Exception { KieSession ksession = session.getStateful(); File tempFile = File.createTempFile(name.getMethodName(), null); ksession.fireAllRules(); try (OutputStream fos = new FileOutputStream(tempFile)) { Marshaller marshaller = getServices().getMarshallers().newMarshaller(getKbase()); marshaller.marshall(fos, ksession); } try (InputStream fis = new FileInputStream(tempFile)) { Marshaller marshaller = getServices().getMarshallers().newMarshaller(getKbase()); marshaller.unmarshall(fis, ksession); } ksession.insert(new Promotion("Claire", "Scientist")); int firedRules = ksession.fireAllRules(); Assertions.assertThat(firedRules).isEqualTo(1); }
Source:
<code>public static synchronized void unregisterAppInfo(String prefix, String id, Metrics metrics) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { <START> id = id == null ? "" : id; <END> ObjectName name = new ObjectName(prefix + ":type=app-info,id=" + Sanitizer.jmxSanitize(id)); if (server.isRegistered(name)) server.unregisterMBean(name); unregisterMetrics(metrics); } catch (JMException e) { log.warn("Error unregistering AppInfo mbean", e); } }</code><technical_language>Hmm, move this check KafkaConsumer's catch block close also</technical_language>

Target:
public static synchronized void unregisterAppInfo(String prefix, String id, Metrics metrics) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { ObjectName name = new ObjectName(prefix + ":type=app-info,id=" + Sanitizer.jmxSanitize(id)); if (server.isRegistered(name)) server.unregisterMBean(name); unregisterMetrics(metrics); } catch (JMException e) { log.warn("Error unregistering AppInfo mbean", e); } }
Source:
<code><START> public boolean equals(Object obj) { <END> if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RepositoryKey other = (RepositoryKey) obj; if (repository == null) { if (other.repository != null) { return false; } } else if (!repository.equals(other.repository)) { return false; } return true; }</code><technical_language>If goal is object idenity cache key, do this: @Override public int hashCode() { result = repository.hashCode(); } @Override public boolean equals(Object obj) { return this.repository == obj.repository; } check repository is null in constructor</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return this.repository == ((RepositoryKey) obj).getRepository(); }
Source:
<code>public Map<String, String> getSystemSessionProperties(SessionConfigurationContext context) { <START> HashMap<String, String> combinedProperties = new HashMap<>(); <END> for (SessionMatchSpec sessionMatchSpec : sessionMatchSpecs) { combinedProperties.putAll(sessionMatchSpec.match(context)); } return ImmutableMap.copyOf(combinedProperties); }</code><technical_language>Nit: declare Map</technical_language>

Target:
public Map<String, String> getSystemSessionProperties(SessionConfigurationContext context) { Map<String, String> combinedProperties = new HashMap<>(); for (SessionMatchSpec sessionMatchSpec : sessionMatchSpecs) { combinedProperties.putAll(sessionMatchSpec.match(context)); } return ImmutableMap.copyOf(combinedProperties); }
Source:
<code>public void shouldCheckIndexIsOkOnColumn() { init(); <START> sharedRealm.beginTransaction(); <END> table.addSearchIndex(1); sharedRealm.commitTransaction(); }</code><technical_language>call beginTransaction() in setUp() cancelTransaction() in tearDown()</technical_language>

Target:
public void shouldCheckIndexIsOkOnColumn() { init(); table.addSearchIndex(1); }
Source:
<code>private List<SearchResult> searchUsingRestApi(String tenant, List<String> queries) { List<SearchResult> results = new ArrayList<>(); Timer.Context multiSearchCtx = searchTimer.time(); int hitsCount = 0; try { queryBatchHistogram.update(queries.size()); String response = elasticsearchRestHelper.fetch( ELASTICSEARCH_INDEX_NAME_READ, ELASTICSEARCH_DOCUMENT_TYPE, tenant, queries.get(0)); List<SearchResult> searchResults = getSearchResults(response); hitsCount = searchResults.size(); results.addAll(searchResults); } catch (JsonProcessingException e) { <START> e.printStackTrace(); <END> } catch (IOException e) { e.printStackTrace(); } finally { multiSearchCtx.stop(); } searchResultsSizeHistogram.update(hitsCount); return dedupResults(results); }</code><technical_language>good log these</technical_language>

Target:
private List<SearchResult> searchUsingRestApi(String tenant, List<String> queries) { List<SearchResult> results = new ArrayList<>(); Timer.Context multiSearchCtx = searchTimer.time(); int hitsCount; try { queryBatchHistogram.update(queries.size()); String response = elasticsearchRestHelper.fetch( ELASTICSEARCH_INDEX_NAME_READ, ELASTICSEARCH_DOCUMENT_TYPE, tenant, queries); List<SearchResult> searchResults = getSearchResults(response); hitsCount = searchResults.size(); results.addAll(searchResults); } catch (JsonProcessingException e) { log.error("Elasticsearch metrics query failed for tenantId {}. {}", tenant, e.getMessage()); throw new RuntimeException(String.format("searchUsingRestApi failed with message: %s", e.getMessage()), e); } catch (IOException e) { log.error("Elasticsearch metrics query failed for tenantId {}. {}", tenant, e.getMessage()); throw new RuntimeException(String.format("searchUsingRestApi failed with message: %s", e.getMessage()), e); } finally { multiSearchCtx.stop(); } searchResultsSizeHistogram.update(hitsCount); return dedupResults(results); }
Source:
<code>public SearchResults filterResults(SearchResults searchResults) { List<PageTitle> filteredResults = new ArrayList<>(); List<PageTitle> results = searchResults.getPageTitles(); for (int i = 0, count = 0; i < results.size() && count < maxItems; i++) { final PageTitle res = results.get(i); if (!title.equalsIgnoreCase(res.getPrefixedText()) && (!requireThumbnail || res.getThumbUrl() != null) <START> && (!(res.getDescription() != null && (res.getDescription().contains("disambiguation") || res.getDescription().contains("Main page"))))) { <END> filteredResults.add(res); count++; } } return new SearchResults(filteredResults, null, null); }</code><technical_language>get this MainPageNameData</technical_language>

Target:
public SearchResults filterResults(SearchResults searchResults) { List<PageTitle> filteredResults = new ArrayList<>(); List<PageTitle> results = searchResults.getPageTitles(); for (int i = 0, count = 0; i < results.size() && count < maxItems; i++) { final PageTitle res = results.get(i); if (!title.equalsIgnoreCase(res.getPrefixedText()) && (!requireThumbnail || res.getThumbUrl() != null) && !res.getProperties().has("disambiguation")) { filteredResults.add(res); count++; } } return new SearchResults(filteredResults, null, null); }
Source:
<code>public void destroy() { Process p = null; try { LinuxProcessBuilder lpb = new LinuxProcessBuilder(user, null, scriptBaseFolder); String killProcessTreeScript = new File(scriptBaseFolder, PROCESS_TREE_KILLER_LOCATION).getAbsolutePath(); lpb.directory(new File(System.getProperty("java.io.tmpdir"))); lpb.command(killProcessTreeScript, this.cleanupTimeoutGetter.getCleanupTimeSecondsString()); lpb.environment().put("PROCESS_KILL_TOKEN", this.token); p = lpb.start(); p.waitFor(); if (logger.isDebugEnabled()) { printStdout(p, Level.DEBUG); printStderr(p, Level.DEBUG); logger.debug("token: " + this.token + " exitval:" + p.exitValue()); } } catch (Exception e) { printStderr(p, Level.WARN); <START> logger.warn("Failed to destroy OS process with token: " + this.token, e); <END> } }</code><technical_language>I do logger.warn("Failed destroy OS process token: " + this.token, e); printStdout(p, Level.WARN); printStderr(p, Level.WARN);</technical_language>

Target:
public void destroy() { Process p = null; try { LinuxProcessBuilder lpb = new LinuxProcessBuilder(user, null, scriptBaseFolder); String killProcessTreeScript = new File(scriptBaseFolder, PROCESS_TREE_KILLER_LOCATION).getAbsolutePath(); lpb.directory(new File(System.getProperty("java.io.tmpdir"))); lpb.command(killProcessTreeScript, this.cleanupTimeoutGetter.getCleanupTimeSecondsString()); lpb.environment().put("PROCESS_KILL_TOKEN", this.token); p = lpb.start(); p.waitFor(); if (logger.isDebugEnabled()) { printStdout(p, Level.DEBUG); printStderr(p, Level.DEBUG); logger.debug("token: " + this.token + " exitval:" + p.exitValue()); } } catch (Exception e) { logger.warn("Failed to destroy OS process with token: " + this.token, e); printStdout(p, Level.WARN); printStderr(p, Level.WARN); } }
Source:
<code>public void testWorkPath() throws Exception { List<PID> pids = makePidList(4); when(pathFactory.getAncestorPids(pid)).thenReturn(pids); filter.filter(dip); <START> verify(idb).setRollup(eq(contentObject.getPid().getId())); <END> }</code><technical_language>Verify ancestor path is set parentCollection parentUnit set</technical_language>

Target:
public void testWorkPath() throws Exception { List<PID> pids = makePidList(4); when(pathFactory.getAncestorPids(pid)).thenReturn(pids); filter.filter(dip); verify(idb).setAncestorPath(listCaptor.capture()); List<String> ancestorPath = listCaptor.getValue(); ancestorPathCheck(ancestorPath, pids); assertEquals(4, ancestorPath.size()); verify(idb).setRollup(eq(contentObject.getPid().getId())); }
Source:
<code><START> List<JsonObject> findBySort(boolean closed, boolean active, String sort, Integer offset,Integer size) <END> throws DataException { BoolQueryBuilder query = new BoolQueryBuilder(); query.must(getQuerySortHelperStatus(closed)); query.must(getQueryProjectActive(active)); return searcher.findDocuments(query.toString(), sort, offset, size); }</code><technical_language>Missing space offset,Integer size</technical_language>

Target:
private List<JsonObject> findBySort(boolean closed, boolean active, String sort, Integer offset, Integer size) throws DataException { BoolQueryBuilder query = new BoolQueryBuilder(); query.must(getQuerySortHelperStatus(closed)); query.must(getQueryProjectActive(active)); return searcher.findDocuments(query.toString(), sort, offset, size); }
Source:
<code>private AbstractHistoryCategory[] sortRevisions(IFileRevision[] revisions, IProgressMonitor monitor) { try { monitor.beginTask(null, 100); DateHistoryCategory[] tempCategories = new DateHistoryCategory[4]; Calendar currentCal = Calendar.getInstance(); tempCategories[0] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Today, currentCal, null); Calendar yesterdayCal = Calendar.getInstance(); yesterdayCal.roll(Calendar.DAY_OF_YEAR, -1); tempCategories[1] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Yesterday, yesterdayCal, null); Calendar monthCal = Calendar.getInstance(); monthCal.set(Calendar.DAY_OF_MONTH, 1); tempCategories[2] = new DateHistoryCategory(TeamUIMessages.HistoryPage_ThisMonth, monthCal, yesterdayCal); tempCategories[3] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Previous, null, monthCal); ArrayList<AbstractHistoryCategory> finalCategories = new ArrayList<AbstractHistoryCategory>(); for (DateHistoryCategory <START> tempCategorie : <END> tempCategories) { tempCategorie.collectFileRevisions(revisions, false); if (tempCategorie.hasRevisions()) { finalCategories.add(tempCategorie); } } if (finalCategories.isEmpty()){ finalCategories.add(getErrorMessage()); } return finalCategories.toArray(new AbstractHistoryCategory[finalCategories.size()]); } finally { monitor.done(); } }</code><technical_language>Category</technical_language>

Target:
private AbstractHistoryCategory[] sortRevisions(IFileRevision[] revisions, IProgressMonitor monitor) { try { monitor.beginTask(null, 100); DateHistoryCategory[] tempCategories = new DateHistoryCategory[4]; Calendar currentCal = Calendar.getInstance(); tempCategories[0] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Today, currentCal, null); Calendar yesterdayCal = Calendar.getInstance(); yesterdayCal.roll(Calendar.DAY_OF_YEAR, -1); tempCategories[1] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Yesterday, yesterdayCal, null); Calendar monthCal = Calendar.getInstance(); monthCal.set(Calendar.DAY_OF_MONTH, 1); tempCategories[2] = new DateHistoryCategory(TeamUIMessages.HistoryPage_ThisMonth, monthCal, yesterdayCal); tempCategories[3] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Previous, null, monthCal); ArrayList<AbstractHistoryCategory> finalCategories = new ArrayList<AbstractHistoryCategory>(); for (DateHistoryCategory tempCategory : tempCategories){ tempCategory.collectFileRevisions(revisions, false); if (tempCategory.hasRevisions()){ finalCategories.add(tempCategory); } } if (finalCategories.isEmpty()){ finalCategories.add(getErrorMessage()); } return finalCategories.toArray(new AbstractHistoryCategory[finalCategories.size()]); } finally { monitor.done(); } }
Source:
<code>public static IModelCustom loadModel(String resourceName) throws IllegalArgumentException, ModelFormatException { int i = resourceName.lastIndexOf('.'); int j = resourceName.lastIndexOf(':'); if (i == -1 || j == -1) { FMLLog.severe("The resource name %s is not valid", resourceName); throw new IllegalArgumentException("The resource name is not valid"); } String suffix = resourceName.substring(i + 1); String modID = resourceName.substring(0, j); IModelCustomLoader loader = instances.get(suffix); if (loader == null) { FMLLog.severe("The resource name %s is not supported", resourceName); throw new IllegalArgumentException("The resource name is not supported"); } ResourceLocation resource = new ResourceLocation(modID, resourceName.substring(j + 1)); <START> return loader.loadInstance(resourceName, resource); <END> }</code><technical_language>need for extra, constructor of ResourceLocation splits domains for you</technical_language>

Target:
public static IModelCustom loadModel(String resourceName) throws IllegalArgumentException, ModelFormatException { int i = resourceName.lastIndexOf('.'); int j = resourceName.lastIndexOf(':'); if (i == -1 || j == -1) { FMLLog.severe("The resource name %s is not valid", resourceName); throw new IllegalArgumentException("The resource name is not valid"); } String suffix = resourceName.substring(i + 1); String modID = resourceName.substring(0, j); IModelCustomLoader loader = instances.get(suffix); if (loader == null) { FMLLog.severe("The resource name %s is not supported", resourceName); throw new IllegalArgumentException("The resource name is not supported"); } <<<<<<< HEAD ResourceLocation resLoc = new ResourceLocation(resourceName); return loader.loadInstance(resourceName, resLoc); ======= ResourceLocation resource = new ResourceLocation(modID, resourceName.substring(j + 1)); return loader.loadInstance(resourceName, resource); >>>>>>> master }
Source:
<code>public void invokeCallbackMethods() { initCommandExecutor(); CommandEntity cmdEntity; for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext();) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); switch (status) { case FAILED: try { callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { log.errorFormat("Error invoking onFailed for FAILED command {0}", cmdId.toString()); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: try { callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); } catch (Exception ex) { <START> log.errorFormat("Error invoking onSucceeded for SUCCEEDED command {0}", cmdId.toString()); <END> coco.updateCommandStatus(cmdId, CommandStatus.FAILED); } break; case ACTIVE: cmdEntity = coco.getCommandEntity(cmdId); if (cmdEntity.isExecuted() && cmdEntity.isAsync()) { try { callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { coco.updateCommandStatus(cmdId, CommandStatus.FAILED); log.errorFormat("Error invoking doPolling for active command {0}", cmdId.toString()); } } break; default: break; } } }</code><technical_language>i is refactor error handling, if external method. you</technical_language>

Target:
public void invokeCallbackMethods() { initCommandExecutor(); CommandEntity cmdEntity; for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext();) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); switch (status) { case FAILED: try { callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { handleError(ex, status, cmdId); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: try { callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); } catch (Exception ex) { handleError(ex, status, cmdId); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case ACTIVE: cmdEntity = coco.getCommandEntity(cmdId); if (cmdEntity.isExecuted()) { try { callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { handleError(ex, status, cmdId); } } break; default: break; } } }
Source:
<code><START> private String getCookieParam(String param, String cookieString) { <END> if (param.equals(NAME)) { return cookieString.substring(0, cookieString.indexOf('=')); } if (param.equals(VALUE)) { if (cookieString.contains(";")) { return cookieString.substring(cookieString.indexOf('=') + 1, cookieString.indexOf(';')); } else { return cookieString.substring(cookieString.indexOf('=') + 1); } } if(SECURE.equals(param) && cookieString.contains(SECURE)) { return "true"; } if (cookieString.contains(param + '=')) { final int endParam = cookieString.indexOf(';', cookieString.indexOf(param + '=')); final int beginIndex = cookieString.indexOf(param + '=') + param.length() + 1; if (endParam > 0) { return cookieString.substring(beginIndex, endParam); } else { return cookieString.substring(beginIndex); } } throw new CitrusRuntimeException(String.format( "Unable to get cookie argument '%s' from cookie String: %s", param, cookieString)); }</code><technical_language>consider e.g. [java.net.HttpCookie#parse](<LINK_0> reduce parsing code</technical_language>

Target:
private String getCookieParam(String param, String cookieString) { if (param.equals(NAME)) { return cookieString.substring(0, cookieString.indexOf('=')); } if (param.equals(VALUE)) { if (cookieString.contains(";")) { return cookieString.substring(cookieString.indexOf('=') + 1, cookieString.indexOf(';')); } else { return cookieString.substring(cookieString.indexOf('=') + 1); } } if(SECURE.equals(param) && cookieString.contains(SECURE)) { return String.valueOf(true); } if (cookieString.contains(param + '=')) { final int endParam = cookieString.indexOf(';', cookieString.indexOf(param + '=')); final int beginIndex = cookieString.indexOf(param + '=') + param.length() + 1; if (endParam > 0) { return cookieString.substring(beginIndex, endParam); } else { return cookieString.substring(beginIndex); } } throw new CitrusRuntimeException(String.format( "Unable to get cookie argument '%s' from cookie String: %s", param, cookieString)); }
Source:
<code>public List<Result> execute(IotasEvent input) { <START> final List<Result> results = splitter.splitEvent(input, splitAction.getOutputStreams()); <END> for (Result result : results) { for (IotasEvent event : result.events) { checkGroupIdPartitionId(event); } } return results; }</code><technical_language>Minor: getOutputStreams() for this instead of splitAction</technical_language>

Target:
public List<Result> execute(IotasEvent input) { final List<Result> results = splitter.splitEvent(input, getOutputStreams()); for (Result result : results) { for (IotasEvent event : result.events) { checkGroupIdPartitionId(event); } } return results; }
Source:
<code>public void helpBuildingEvent(EventBuilder eventBuilder) { HttpServletRequest servletRequest = SentryServletRequestListener.getServletRequest(); if (servletRequest == null) { return; } <START> HttpServletRequestWrapper servletRequestWrapper = new HttpServletRequestWrapper(servletRequest); <END> addHttpInterface(eventBuilder, servletRequestWrapper); addUserInterface(eventBuilder, servletRequestWrapper); }</code><technical_language>suggestion HttpRequestInterface servletRequestWrapper = new HttpServletRequestWrapper(servletRequest);</technical_language>

Target:
public void helpBuildingEvent(EventBuilder eventBuilder) { HttpServletRequest servletRequest = SentryServletRequestListener.getServletRequest(); if (servletRequest == null) { return; } HttpRequestInterface servletRequestWrapper = new HttpServletRequestWrapper(servletRequest); addHttpInterface(eventBuilder, servletRequestWrapper); addUserInterface(eventBuilder, servletRequestWrapper); }
Source:
<code>private ConfigurableAuthService setUpAuthClient( final Map<String, String> config) { final URL authURL = getURL(config, KBASE_AUTH_URL); final String authAllowInsecure = config.get(INSECURE_AUTH_URL); final URL globusURL = getURL(config, GLOBUS_AUTH_URL); if (authURL == null || globusURL == null) { return null; } <START> System.out.println(UserAndJobStateServer.class.getName() + ": " + INSECURE_AUTH_URL +" = " + <END> (authAllowInsecure == null ? "<not-set> ('false' will be used)" : authAllowInsecure)); final AuthConfig c; try { c = new AuthConfig().withGlobusAuthURL(globusURL) .withKBaseAuthServerURL(authURL) .withAllowInsecureURLs("true".equals(authAllowInsecure)); } catch (URISyntaxException e) { throw new RuntimeException("Neat. I'm suprised this happened", e); } final boolean token = config.get(KBASE_ADMIN_TOKEN) != null; final ConfigurableAuthService auth; try { auth = new ConfigurableAuthService(c); if (token) { c.withToken(auth.validateToken(config.get(KBASE_ADMIN_TOKEN))); } else { c.withRefreshingToken(auth.getRefreshingToken( config.get(KBASE_ADMIN_USER), config.get(KBASE_ADMIN_PWD), TOKEN_REFRESH_INTERVAL_SEC)); } return auth; } catch (AuthException e) { fail("Couldn't log in the KBase administrative user " + (token ? "with a token" : config.get(KBASE_ADMIN_USER)) + ": " + e.getMessage()); } catch (IOException e) { fail("Couldn't connect to authorization service at " + c.getAuthServerURL() + " : " + e.getLocalizedMessage()); } return null; }</code><technical_language>This logged other params in constructor</technical_language>

Target:
private ConfigurableAuthService setUpAuthClient( final Map<String, String> config) { final URL authURL = getURL(config, KBASE_AUTH_URL); final String authAllowInsecure = config.get(INSECURE_AUTH_URL); final URL globusURL = getURL(config, GLOBUS_AUTH_URL); if (authURL == null || globusURL == null) { return null; } final AuthConfig c; try { c = new AuthConfig().withGlobusAuthURL(globusURL) .withKBaseAuthServerURL(authURL) .withAllowInsecureURLs("true".equals(authAllowInsecure)); } catch (URISyntaxException e) { throw new RuntimeException("Neat. I'm suprised this happened", e); } final boolean token = config.get(KBASE_ADMIN_TOKEN) != null; final ConfigurableAuthService auth; try { auth = new ConfigurableAuthService(c); if (token) { c.withToken(auth.validateToken(config.get(KBASE_ADMIN_TOKEN))); } else { c.withRefreshingToken(auth.getRefreshingToken( config.get(KBASE_ADMIN_USER), config.get(KBASE_ADMIN_PWD), TOKEN_REFRESH_INTERVAL_SEC)); } return auth; } catch (AuthException e) { fail("Couldn't log in the KBase administrative user " + (token ? "with a token" : config.get(KBASE_ADMIN_USER)) + ": " + e.getMessage()); } catch (IOException e) { fail("Couldn't connect to authorization service at " + c.getAuthServerURL() + " : " + e.getLocalizedMessage()); } return null; }
Source:
<code>protected void startMachines() throws InfrastructureException { OpenShiftEnvironment osEnv = getContext().getEnvironment(); List<Service> createdServices = new ArrayList<>(); for (Service service : osEnv.getServices().values()) { createdServices.add(project.services().create(service)); } List<Route> createdRoutes = new ArrayList<>(); for (Route route : osEnv.getRoutes().values()) { createdRoutes.add(project.routes().create(route)); } <START> project.pods().watchContainers(new MachineLogsPublisher()); <END> if (StringUtils.isNotBlank(unrecoverableEvents)) { project.pods().watchContainers(new UnrecoverableEventHanler()); } doStartMachine(new OpenShiftServerResolver(createdServices, createdRoutes)); }</code><technical_language>TLDR please, add finally set watchers ensure watchers properly deleted. guarantee is bug prevents execution of finally block k8s infra</technical_language>

Target:
protected void startMachines() throws InfrastructureException { OpenShiftEnvironment osEnv = getContext().getEnvironment(); List<Service> createdServices = new ArrayList<>(); for (Service service : osEnv.getServices().values()) { createdServices.add(project.services().create(service)); } List<Route> createdRoutes = new ArrayList<>(); for (Route route : osEnv.getRoutes().values()) { createdRoutes.add(project.routes().create(route)); } project.pods().watchContainers(new MachineLogsPublisher()); if (!Strings.isNullOrEmpty(unrecoverableEvents)) { project.pods().watchContainers(new UnrecoverableEventHanler()); } doStartMachine(new OpenShiftServerResolver(createdServices, createdRoutes)); }
Source:
<code>private void addAssetsToView(List<AssetInfo> assetInfos) { if (!reloader.isAssetsLoadingFinished()) { this.showIndexingNotFinished(); reloader.check(assetInfos); } if (assetInfos.isEmpty()) { this.showSearchHitNothing(); } else { this.hideEmptyState(); assetInfos.forEach(asset -> { if (!asset.getFolderItem().getType().equals(FolderItemType.FOLDER)) { AssetItemWidget item = assetItemWidget.get(); final ClientResourceType assetResourceType = getResourceType(asset); final String assetName = getAssetName(asset, assetResourceType); item.init(assetName, getAssetPath(asset), assetResourceType.getDescription(), assetResourceType.getIcon(), getLastModifiedTime(asset), getCreatedTime(asset), detailsCommand((Path) asset.getFolderItem().getItem()), selectCommand((Path) asset.getFolderItem().getItem())); <START> this.view.addAssetItem(elemental2DomUtil.asHTMLElement(item.getElement())); <END> } }); } this.updatedAssetsEventEvent.fire(new UpdatedAssetsEvent(assetInfos)); busyIndicatorView.hideBusyIndicator(); }</code><technical_language>keen converting Element (presumably) a Elemental2 HTMLElement in presenter. pass item view perform conversion there</technical_language>

Target:
private void addAssetsToView(List<AssetInfo> assetInfos) { if (!reloader.isAssetsLoadingFinished()) { this.showIndexingNotFinished(); reloader.check(assetInfos); } if (assetInfos.isEmpty()) { this.showSearchHitNothing(); } else { this.hideEmptyState(); assetInfos.forEach(asset -> { if (!asset.getFolderItem().getType().equals(FolderItemType.FOLDER)) { AssetItemWidget item = assetItemWidget.get(); final ClientResourceType assetResourceType = getResourceType(asset); final String assetName = getAssetName(asset, assetResourceType); item.init(assetName, getAssetPath(asset), assetResourceType.getDescription(), assetResourceType.getIcon(), getLastModifiedTime(asset), getCreatedTime(asset), detailsCommand((Path) asset.getFolderItem().getItem()), selectCommand((Path) asset.getFolderItem().getItem())); this.view.addAssetItem(item); } }); } this.updatedAssetsEventEvent.fire(new UpdatedAssetsEvent(assetInfos)); busyIndicatorView.hideBusyIndicator(); }
Source:
<code>public static native int getDexOptNeeded(String fileName, String instructionSet, String compilerFilter, String classLoaderContext, boolean newProfile, boolean downgrade) throws FileNotFoundException, IOException; public static native String getDexFileStatus(String fileName, String instructionSet) throws FileNotFoundException; public static native String[] getDexFileOutputPaths(String fileName, String instructionSet) throws FileNotFoundException; public native static boolean isValidCompilerFilter(String filter); public native static boolean isProfileGuidedCompilerFilter(String filter); public native static String getNonProfileGuidedCompilerFilter(String filter); public native static String getSafeModeCompilerFilter(String filter); public long getStaticSizeOfDexFile() { return <START> mCookie == null ? 0 : <END> getStaticSizeOfDexFile(mCookie); }</code><technical_language>racy</technical_language>

Target:
public static native int getDexOptNeeded(String fileName, String instructionSet, String compilerFilter, String classLoaderContext, boolean newProfile, boolean downgrade) throws FileNotFoundException, IOException; public static native String getDexFileStatus(String fileName, String instructionSet) throws FileNotFoundException; public static native String[] getDexFileOutputPaths(String fileName, String instructionSet) throws FileNotFoundException; public native static boolean isValidCompilerFilter(String filter); public native static boolean isProfileGuidedCompilerFilter(String filter); public native static String getNonProfileGuidedCompilerFilter(String filter); public native static String getSafeModeCompilerFilter(String filter); public long getStaticSizeOfDexFile() { Object cookie = mCookie; return cookie == null ? 0 : getStaticSizeOfDexFile(cookie); }
Source:
<code>public static HistoricItem historicState(Item item, AbstractInstant timestamp, String serviceId) { PersistenceService service = getService(serviceId); if (service instanceof QueryablePersistenceService) { QueryablePersistenceService qService = (QueryablePersistenceService) service; FilterCriteria filter = new FilterCriteria(); <START> filter.setEndDate(ZonedDateTime.ofInstant(timestamp.toDate().toInstant(), TimeZone.getDefault().toZoneId())); <END> filter.setItemName(item.getName()); filter.setPageSize(1); filter.setOrdering(Ordering.DESCENDING); Iterable<HistoricItem> result = qService.query(filter); if (result.iterator().hasNext()) { return result.iterator().next(); } else { return null; } } else { LoggerFactory.getLogger(PersistenceExtensions.class) .warn("There is no queryable persistence service registered with the id '{}'", serviceId); return null; } }</code><technical_language>this timeZoneProvider.getTimeZone()</technical_language>

Target:
public static HistoricItem historicState(Item item, AbstractInstant timestamp, String serviceId) { PersistenceService service = getService(serviceId); if (service instanceof QueryablePersistenceService) { QueryablePersistenceService qService = (QueryablePersistenceService) service; FilterCriteria filter = new FilterCriteria(); filter.setEndDate(ZonedDateTime.ofInstant(timestamp.toDate().toInstant(), timeZoneProvider.getTimeZone())); filter.setItemName(item.getName()); filter.setPageSize(1); filter.setOrdering(Ordering.DESCENDING); Iterable<HistoricItem> result = qService.query(filter); if (result.iterator().hasNext()) { return result.iterator().next(); } else { return null; } } else { LoggerFactory.getLogger(PersistenceExtensions.class) .warn("There is no queryable persistence service registered with the id '{}'", serviceId); return null; } }
Source:
<code>private void verifyNumOfProductThumbVisible(By numOfProductBy) { List<WebElement> thumbElemsList = driver.findElement(numOfProductBy).findElements(productThumbBy); if (numOfProductBy.equals(eCommerceMultipleProductBy)) { Assertion.assertTrue(thumbElemsList.size() > 1, "Expecting more than 1 product thumb image. Found: " + thumbElemsList.size()); } else { Assertion.assertTrue(thumbElemsList.size() == 1, <START> "Expecting more than 1 product thumb image. Found: " <END> + thumbElemsList.size()); } }</code><technical_language>Consider updating message "Expecting 1 product thumb image"</technical_language>

Target:
private void verifyNumOfProductThumbVisible(By numOfProductBy) { List<WebElement> thumbElemsList = driver.findElement(numOfProductBy).findElements(productThumbBy); if (numOfProductBy.equals(eCommerceMultipleProductBy)) { Assertion.assertTrue(thumbElemsList.size() > 1, "Expecting more than 1 product thumb image. Found: " + thumbElemsList.size()); } else { Assertion.assertTrue(thumbElemsList.size() == 1, "Expecting only 1 product thumb image. Found: " + thumbElemsList.size()); } }
Source:
<code>public Object getField(ServerConsumer consumer, String fieldName) { ServerSession session = server.getSessionByID(consumer.getSessionID()); if (session == null) { return null; } switch (fieldName) { case "id": return consumer.getSequentialID(); case "session": return consumer.getSessionName(); case "user": return session.getUsername(); case "clientID": return consumer.getConnectionClientID(); case "protocol": return consumer.getConnectionProtocolName(); case "queue": return consumer.getQueueName(); case "queueType": return consumer.getQueueType(); case "filter": <START> return consumer.getFilter() == null ? "" : consumer.getFilter().getFilterString(); <END> case "localAddress": return consumer.getConnectionLocalAddress(); case "remoteAddress": return consumer.getConnectionRemoteAddress(); case "creationTime": return new Date(consumer.getCreationTime()); default: throw new IllegalArgumentException("Unsupported field, " + fieldName); } }</code><technical_language>dupe logic line 61, create a method getFilterString, note youll need this for ConsumerFilterPredicate, worth a static helper method central filter itself. if null, return null, empty string. return filter != null ? filter.getFilterString().toString() : null; e.g. logic in QueueControlImpl n.b. if a generic method, code in QueueControlImpl updated code tidy avoid dupe</technical_language>

Target:
public Object getField(ServerConsumer consumer, String fieldName) { ServerSession session = server.getSessionByID(consumer.getSessionID()); if (session == null) { return null; } switch (fieldName) { case "id": return consumer.getSequentialID(); case "session": return consumer.getSessionName(); case "user": return session.getUsername(); case "clientID": return consumer.getConnectionClientID(); case "protocol": return consumer.getConnectionProtocolName(); case "queue": return consumer.getQueueName(); case "queueType": return consumer.getQueueType(); case "filter": return consumer.getFilterString(); case "localAddress": return consumer.getConnectionLocalAddress(); case "remoteAddress": return consumer.getConnectionRemoteAddress(); case "creationTime": return new Date(consumer.getCreationTime()); default: throw new IllegalArgumentException("Unsupported field, " + fieldName); } }
Source:
<code><START> public void emitEvent(Event event) throws QueueException { <END> eventQueue.emitEvent(event); }</code><technical_language>do need this new method</technical_language>

Target:
public void emitEvent(Event event) { try { eventQueue.emitEvent(event); } catch (QueueException e) { logger.error("Failed to emit event due to [externalId={}]", event.getEventType(), e.getMessage(), event.getResourceExternalId()); } }
Source:
<code>void onEditProfileClicked() { <START> Flow.get(getView().getContext()).set(new ProfileSettingsScreen()); <END> }</code><technical_language>for convenience flow a View call getContext() for</technical_language>

Target:
void onEditProfileClicked() { Flow.get(getView()).set(new ProfileSettingsScreen()); }
Source:
<code>public void testDecimal() { ToolTipString fromFloat = ToolTipString.fromDecimal(1.0f); ToolTipString fromDouble = ToolTipString.fromDecimal(1.0); ToolTipString fromInt = ToolTipString.fromDecimal(1); ToolTipString fromLong = ToolTipString.fromDecimal(1L); assertNotNull(fromFloat); assertNotNull(fromDouble); assertNotNull(fromInt); <START> assertNotNull(fromLong); <END> assertEquals("1", fromFloat.toString()); assertEquals("1", fromDouble.toString()); assertEquals("1", fromInt.toString()); assertEquals("1", fromLong.toString()); assertEquals("1", fromFloat.toHtmlString()); assertEquals("1", fromDouble.toHtmlString()); assertEquals("1", fromInt.toHtmlString()); assertEquals("1", fromLong.toHtmlString()); }</code><technical_language>necessary, test fail</technical_language>

Target:
public void testDecimal() { ToolTipString fromFloat = ToolTipString.fromDecimal(1.0f); ToolTipString fromDouble = ToolTipString.fromDecimal(1.0); ToolTipString fromInt = ToolTipString.fromDecimal(1); ToolTipString fromLong = ToolTipString.fromDecimal(1L); assertEquals("1", fromFloat.toString()); assertEquals("1", fromDouble.toString()); assertEquals("1", fromInt.toString()); assertEquals("1", fromLong.toString()); assertEquals("1", fromFloat.toHtmlString()); assertEquals("1", fromDouble.toHtmlString()); assertEquals("1", fromInt.toHtmlString()); assertEquals("1", fromLong.toHtmlString()); }
Source:
<code>public void search_getSearch() throws Exception { <START> peliasWithMock.search("test", "1", "2", "1", "1", "1", "1", callback); <END> verify(mock).getSearch(eq("test"), eq("1"), eq("2"), eq("1"), eq("1"), eq("1"), eq("1"), eq(apiKey), cb.capture()); }</code><technical_language>helpful min/max values for bounding box test order is correct. peliasWithMock.search("test", "1", "2", "3", "4", "5", "6", callback);</technical_language>

Target:
public void search_getSearch() throws Exception { peliasWithMock.search("test", "1", "2", "3", "4", "5", "6", callback); verify(mock).getSearch(eq("test"), eq("1"), eq("2"), eq("3"), eq("4"), eq("5"), eq("6"), eq(apiKey), cb.capture()); }
Source:
<code>public void testDeserializeMessage() throws Exception { Messenger messenger = new Messenger(new File("")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String className = StringMessage.class.getCanonicalName(); String testMessage = "This is a test of the messaging system"; appendMessage(className, testMessage, baos); <START> InputStream is = simulateSendAndReceive(baos); <END> assertTrue(messenger.deserializeMessage(is)); IMessage message = messenger.getReceivedMessages().get(0); assertNotNull(message); assertTrue(message instanceof StringMessage); assertEquals(testMessage, ((StringMessage)message).getString()); assertEquals(0, is.available()); }</code><technical_language>change this variable is stand for input stream _is_ (this _is_ a sentence)</technical_language>

Target:
public void testDeserializeMessage() throws Exception { Messenger messenger = new Messenger(new File("")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String className = StringMessage.class.getCanonicalName(); String testMessage = "This is a test of the messaging system"; appendMessage(className, testMessage, baos); InputStream received = simulateSendAndReceive(baos); assertTrue(messenger.deserializeMessage(received)); IMessage message = messenger.getReceivedMessages().get(0); assertNotNull(message); assertTrue(message instanceof StringMessage); assertEquals(testMessage, ((StringMessage)message).getString()); assertEquals(0, received.available()); }
Source:
<code>public static HashMap<String, String> updateInputParamsForRelationshipTemplate(final HashMap<String, String> inputParams, final CSARID csarID, final RelationshipTemplateInstance relationshipTemplateInstance, final String neededInterface, final String neededOperation) { if (relationshipTemplateInstance != null) { ParameterHandler.LOG.debug("Operation: on RelationshipTemplate: {}", relationshipTemplateInstance, neededOperation); ParameterHandler.LOG.debug("{} inital input parameters found: {}", inputParams.size(), inputParams.toString()); final List<String> expectedParams = ParameterHandler.getExpectedInputParams(csarID, relationshipTemplateInstance.getTemplateType(), neededInterface, neededOperation); ParameterHandler.LOG.debug("Operation: expects parameters: {}", neededOperation, expectedParams.size(), expectedParams.toString()); <START> if (!expectedParams.isEmpty()) { <END> for (final String expectedParam : expectedParams) { ParameterHandler.LOG.debug("Expected parameter: {}", expectedParam); if (expectedParam.startsWith("SRC_")) { ParameterHandler.LOG.debug("Parameter is defined at the topology stack of the source NodeTemplate."); } else if (expectedParam.startsWith("TRG_")) { ParameterHandler.LOG.debug("Parameter is defined at the topology stack of the target NodeTemplate."); } else { ParameterHandler.LOG.debug("Parameter is defined at the RelationshipTemplate."); } } } } else { ParameterHandler.LOG.warn("Unable to update input parameters with RelationshipTemplateInstance equal to null!"); } return inputParams; }</code><technical_language>inverted</technical_language>

Target:
private static HashMap<String, String> updateInputParamsForRelationshipTemplate(final HashMap<String, String> inputParams, final CSARID csarID, final RelationshipTemplateInstance relationshipTemplateInstance, final String neededInterface, final String neededOperation) { Objects.requireNonNull(relationshipTemplateInstance); LOG.debug("Updating input params for RelationshipTemplate ID: {}", relationshipTemplateInstance.getId()); LOG.debug("{} inital input parameters for operation: found: {}", inputParams.size(), neededOperation, inputParams.toString()); final Set<String> expectedParams = getExpectedInputParams(csarID, relationshipTemplateInstance.getTemplateType(), neededInterface, neededOperation); if (expectedParams.isEmpty()) { LOG.debug("No input params defined for this operation."); return inputParams; } LOG.debug("Operation: expects parameters: {}", neededOperation, expectedParams.size(), expectedParams.toString()); for (final String expectedParam : expectedParams) { LOG.debug("Expected parameter: {}", expectedParam); if (expectedParam.startsWith("SRC_")) { LOG.debug("Parameter is defined at the topology stack of the source NodeTemplate."); } else if (expectedParam.startsWith("TRG_")) { LOG.debug("Parameter is defined at the topology stack of the target NodeTemplate."); } else { LOG.debug("Parameter is defined at the RelationshipTemplate."); } } return inputParams; }
Source:
<code>public static void populate(Cache cache, ObjectMapper mapper, Cache.NamedKey key, Iterable<Object> results) { <START> List<Object> resultList = Lists.newArrayList(results); <END> try { cache.put(key, mapper.writeValueAsBytes(resultList)); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } }</code><technical_language>JsonGenerator approach anyway, compatible cached data (important for remote caches memcached, persist Druid server restarts). Druid servers blow expect a JSON array instead start of object</technical_language>

Target:
public static void populate(Cache cache, ObjectMapper mapper, Cache.NamedKey key, Iterable<Object> results) { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (JsonGenerator gen = mapper.getFactory().createGenerator(bytes)) { for (Object result : results) { gen.writeObject(result); } } cache.put(key, bytes.toByteArray()); } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
<code>private void doBucketProbing() throws IOException { int bucketProbe = getConf() .getInt(S3A_BUCKET_PROBE, S3A_BUCKET_PROBE_DEFAULT); Preconditions.checkArgument(bucketProbe >= 0, "Value of " + S3A_BUCKET_PROBE + " should be >= 0"); <START> String endPoint = getConf().getTrimmed(ENDPOINT, ""); <END> if (!endPoint.isEmpty() && LOG.isDebugEnabled()) { LOG.debug("Bucket endpoint : {}", InetAddress.getByName(endPoint).toString()); } switch (bucketProbe) { case 0: LOG.debug("skipping check for bucket existence"); break; case 1: verifyBucketExists(); break; case 2: verifyBucketExistsV2(); break; default: LOG.warn("Unknown bucket probe option {}: {}; falling back to check #2", S3A_BUCKET_PROBE, bucketProbe); verifyBucketExistsV2(); break; } }</code><technical_language>lets skip this if mode == 0 DNS lookups init delays</technical_language>

Target:
private void doBucketProbing() throws IOException { int bucketProbe = getConf() .getInt(S3A_BUCKET_PROBE, S3A_BUCKET_PROBE_DEFAULT); Preconditions.checkArgument(bucketProbe >= 0, "Value of " + S3A_BUCKET_PROBE + " should be >= 0"); switch (bucketProbe) { case 0: LOG.debug("skipping check for bucket existence"); break; case 1: logDnsLookup(getConf()); verifyBucketExists(); break; case 2: logDnsLookup(getConf()); verifyBucketExistsV2(); break; default: LOG.warn("Unknown bucket probe option {}: {}; falling back to check #2", S3A_BUCKET_PROBE, bucketProbe); verifyBucketExistsV2(); break; } }