auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testFinishLocalSetupFullyInitialized() throws Exception { final Checker checker = new Checker(); <START> ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); <END> checker.setModuleClassLoader(contextClassLoader); final PackageObjectFactory factory = new PackageObjectFactory( new HashSet<>(), contextClassLoader); checker.setModuleFactory(factory); checker.setBasedir("testBaseDir"); checker.setLocaleLanguage("it"); checker.setLocaleCountry("IT"); checker.finishLocalSetup(); Field sLocale = LocalizedMessage.class.getDeclaredField("sLocale"); sLocale.setAccessible(true); Locale locale = (Locale) sLocale.get(null); Context context = (Context) Whitebox.getInternalState(checker, "childContext"); assertEquals("UTF-8", context.get("charset")); assertEquals(contextClassLoader, context.get("classLoader")); assertEquals("error", context.get("severity")); assertEquals("testBaseDir", context.get("basedir")); assertEquals(Locale.ITALY, locale); }</code><technical_language>do continue avoiding final modifiers?) Please, run mvn clean verify sending PR</technical_language>

Target:
public void testFinishLocalSetupFullyInitialized() throws Exception { final Checker checker = new Checker(); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); checker.setModuleClassLoader(contextClassLoader); final PackageObjectFactory factory = new PackageObjectFactory( new HashSet<>(), contextClassLoader); checker.setModuleFactory(factory); checker.setBasedir("testBaseDir"); checker.setLocaleLanguage("it"); checker.setLocaleCountry("IT"); checker.finishLocalSetup(); final Context context = (Context) Whitebox.getInternalState(checker, "childContext"); assertEquals(System.getProperty("file.encoding", "UTF-8"), context.get("charset")); assertEquals(contextClassLoader, context.get("classLoader")); assertEquals("error", context.get("severity")); assertEquals("testBaseDir", context.get("basedir")); final Field sLocale = LocalizedMessage.class.getDeclaredField("sLocale"); sLocale.setAccessible(true); final Locale locale = (Locale) sLocale.get(null); assertEquals(Locale.ITALY, locale); }
Source:
<code>private static String getFuntionSymbol(FlamegraphEvent event, ISymbolProvider symbolProvider) { String funcSymbol = ""; if (event.getSymbol() instanceof Long || event.getSymbol() instanceof Integer) { Long longAddress = <START> (long) event.getSymbol(); <END> funcSymbol = symbolProvider.getSymbolText(longAddress); if (funcSymbol == null) { return "0x" + Long.toHexString(longAddress); } } else { return event.getSymbol().toString(); } return funcSymbol; }</code><technical_language>if this is supposed a Long instead of long</technical_language>

Target:
private static String getFuntionSymbol(FlamegraphEvent event, ISymbolProvider symbolProvider) { String funcSymbol = ""; if (event.getSymbol() instanceof Long || event.getSymbol() instanceof Integer) { long longAddress = ((Long) event.getSymbol()).longValue(); funcSymbol = symbolProvider.getSymbolText(longAddress); if (funcSymbol == null) { return "0x" + Long.toHexString(longAddress); } } else { return event.getSymbol().toString(); } return funcSymbol; }
Source:
<code><START> public int indexOf(Object element) { <END> if (filteredPlan.isEmpty()) return -1; if (filteredPlan.get(lastFoundElementPosition).equals(element)) return lastFoundElementPosition; int upIndex = getSeqIndex(lastFoundElementPosition + 1); if (filteredPlan.get(upIndex).equals(element)) { lastFoundElementPosition = upIndex; return lastFoundElementPosition; } int downIndex = getSeqIndex(lastFoundElementPosition - 1); if (filteredPlan.get(downIndex).equals(element)) { lastFoundElementPosition = downIndex; return lastFoundElementPosition; } int index = getSeqIndex(upIndex + 1); while (index != downIndex) { if (filteredPlan.get(index).equals(element)) { lastFoundElementPosition = index; return lastFoundElementPosition; } index = getSeqIndex(index + 1); } lastFoundElementPosition = 0; return -1; }</code><technical_language>this works a simpler compute step index</technical_language>

Target:
public int indexOf(Object element) { if (filteredPlan.isEmpty()) return -1; if (filteredPlan.get(lastFoundElementPosition).equals(element)) return lastFoundElementPosition; int upIndex = mapToCircularIndex(lastFoundElementPosition + 1); if (filteredPlan.get(upIndex).equals(element)) { lastFoundElementPosition = upIndex; return lastFoundElementPosition; } int downIndex = mapToCircularIndex(lastFoundElementPosition - 1); if (filteredPlan.get(downIndex).equals(element)) { lastFoundElementPosition = downIndex; return lastFoundElementPosition; } int index = mapToCircularIndex(upIndex + 1); while (index != downIndex) { if (filteredPlan.get(index).equals(element)) { lastFoundElementPosition = index; return lastFoundElementPosition; } index = mapToCircularIndex(index + 1); } lastFoundElementPosition = 0; return -1; }
Source:
<code>public void changeText_sameActivity() { <START> onView(isRoot()).perform(waitId(R.id.terminal_view, TimeUnit.SECONDS.toMillis(15))); <END> onView(withId(R.id.terminal_view)).perform(typeText(mStringToBetyped), closeSoftKeyboard()); Log.d(TermuxTest.class.getSimpleName(), "Hello"); Log.d(TermuxTest.class.getSimpleName(), getText(withId(R.id.terminal_view))); }</code><technical_language>try a longer wait time, view a long time populate CI suggestion onView(isRoot()).perform(waitId(R.id.terminal_view, TimeUnit.SECONDS.toMillis(300)));</technical_language>

Target:
public void changeText_sameActivity() { onView(isRoot()).perform(waitId(R.id.terminal_view, TimeUnit.SECONDS.toMillis(300))); onView(withId(R.id.terminal_view)).perform(typeText(mStringToBetyped), closeSoftKeyboard()); Log.d(TermuxTest.class.getSimpleName(), "Hello"); Log.d(TermuxTest.class.getSimpleName(), getText(withId(R.id.terminal_view))); }
Source:
<code>public static List<String> addProperty(String key, String value) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); List<String> old = _props.get(key); if (old == null) old = new LinkedList<String>(); <START> old.add(value); <END> return _props.put(key, old); }</code><technical_language>old(LinkedList) is thread-safe, multi-thread add wrong. protect it</technical_language>

Target:
public static List<String> addProperty(String key, String value) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); synchronized (_props) { List<String> old = _props.get(key); if (old == null) old = new LinkedList<String>(); old.add(value); return _props.put(key, old); } }
Source:
<code>public static boolean isRemoteCacheOptions(RemoteOptions options) { return options.remoteCache != null <START> && !options.remoteCache.isEmpty() <END> && !options.remoteCache.startsWith("http"); }</code><technical_language>remove this line</technical_language>

Target:
public static boolean isRemoteCacheOptions(RemoteOptions options) { if (options.remoteCache == null || options.remoteCache.isEmpty()) { return false; } String scheme; try { scheme = new URI(options.remoteCache).getScheme(); } catch (URISyntaxException e) { return false; } return scheme == null || scheme.toLowerCase().startsWith("grpc"); }
Source:
<code>private PrincipalCollection renewSecurityAssertions( SecurityTokenHolder tokenHolder, HttpServletRequest request) throws SecurityServiceException { AuthenticationToken token; Collection<SecurityAssertion> assertions = tokenHolder.getPrincipals().byType(SecurityAssertion.class); if (assertions.isEmpty()) { return null; } else if (assertions.size() == 1) { SecurityAssertion assertion = assertions.iterator().next(); <START> if (assertion instanceof SecurityAssertionDefault) { <END> token = new GuestAuthenticationToken(assertion.getPrincipal().getName()); } else if (assertion instanceof SecurityAssertionSaml) { token = new SAMLAuthenticationToken(null, tokenHolder.getPrincipals(), request.getRemoteAddr()); } else { return null; } } else { if (!tokenHolder.getPrincipals().byType(SecurityAssertionSaml.class).isEmpty()) { token = new SAMLAuthenticationToken(null, tokenHolder.getPrincipals(), request.getRemoteAddr()); } else { return null; } } return securityManager.getSubject(token).getPrincipals(); }</code><technical_language>Is this logic correct? SecurityAssertionDefault necessarily a guest assertion</technical_language>

Target:
private PrincipalCollection renewSecurityAssertions( SecurityTokenHolder tokenHolder, HttpServletRequest request) throws SecurityServiceException { AuthenticationToken token; Collection<SecurityAssertion> assertions = tokenHolder.getPrincipals().byType(SecurityAssertion.class); if (assertions.isEmpty()) { return null; } else if (assertions.size() == 1) { SecurityAssertion assertion = assertions.iterator().next(); if (assertion.getWeight() == SecurityAssertion.NO_AUTH_WEIGHT) { token = new GuestAuthenticationToken(assertion.getPrincipal().getName()); } else if (assertion instanceof SecurityAssertionSaml) { token = new SAMLAuthenticationToken(null, tokenHolder.getPrincipals(), request.getRemoteAddr()); } else { return null; } } else { if (!tokenHolder.getPrincipals().byType(SecurityAssertionSaml.class).isEmpty()) { token = new SAMLAuthenticationToken(null, tokenHolder.getPrincipals(), request.getRemoteAddr()); } else { return null; } } return securityManager.getSubject(token).getPrincipals(); }
Source:
<code>private View validateLoginData(String email, String password) { emailView.setError(null); passwordView.setError(null); View focusView = null; if (TextUtils.isEmpty(password)) { showErrorSnackbar(getString(R.string.error_invalid_password)); focusView = passwordView; } if (TextUtils.isEmpty(email)) { showErrorSnackbar(getString(R.string.error_email_required)); focusView = emailView; <START> } else if (!LoginPackage.isEmailValid(email)) { <END> showErrorSnackbar(getString(R.string.error_invalid_email)); focusView = emailView; } return focusView; }</code><technical_language>I this called isValidEmail(). want/need a Kotlin TLF</technical_language>

Target:
private View validateLoginData(String email, String password) { emailView.setError(null); passwordView.setError(null); View focusView = null; if (TextUtils.isEmpty(password)) { showErrorSnackbar(getString(R.string.error_invalid_password)); focusView = passwordView; } if (TextUtils.isEmpty(email)) { showErrorSnackbar(getString(R.string.error_email_required)); focusView = emailView; } else if (!LoginPackage.isValidEmail(email)) { showErrorSnackbar(getString(R.string.error_invalid_email)); focusView = emailView; } return focusView; }
Source:
<code>public Association createAssociation(AssociationKey key) { DBCollection associations = getCollection( key ); DBObject assoc = MongoHelpers.associationKeyToObject( key ); <START> assoc.put( ROWS_FIELDNAME, new ArrayList<Map<String, Object>>() ); <END> associations.insert( assoc ); return new Association( new MongoDBAssociationSnapshot( assoc ) ); }</code><technical_language>I guess predict optimal size initialize ArrayList this point</technical_language>

Target:
public Association createAssociation(AssociationKey key) { DBCollection associations = getAssociationCollection( key ); DBObject assoc = MongoHelpers.associationKeyToObject( key ); assoc.put( ROWS_FIELDNAME, Collections.EMPTY_LIST ); associations.insert( assoc ); return new Association( new MongoDBAssociationSnapshot( assoc ) ); }
Source:
<code>public void shouldConvertWsDeviceToSsld() { final Device device = this.createDevice(); final Ssld ssld = this.mapper.map(device, Ssld.class); <START> assertThat(ssld.getDeviceIdentification()).isEqualTo(DEVICE_IDENTIFICATION); <END> assertThat(ssld.getAlias()).isEqualTo(ALIAS); assertThat(ssld.getContainer()).isNotNull(); assertThat(ssld.getContainer().getCity()).isEqualTo(CITY); assertThat(ssld.getContainer().getPostalCode()).isEqualTo(POSTAL_CODE); assertThat(ssld.getGpsCoordinates().getLatitude()).isEqualTo(GPS_LATITUDE); assertThat(ssld.getGpsCoordinates().getLongitude()).isEqualTo(GPS_LONGITUDE); assertThat(ssld.isPublicKeyPresent()).isEqualTo(PUBLIC_KEY_PRESENT); }</code><technical_language>is this org.junit.Assert.assertEquals? If assertEquals, need add assertj project</technical_language>

Target:
public void shouldConvertWsDeviceToSsld() { final Device device = this.createDevice(); final Ssld ssld = this.mapper.map(device, Ssld.class); assertThat(ssld.getDeviceIdentification()).isEqualTo(DEVICE_IDENTIFICATION); assertThat(ssld.getAlias()).isEqualTo(ALIAS); assertThat(ssld.getContainerAddress()).isNotNull(); assertThat(ssld.getContainerAddress().getCity()).isEqualTo(CITY); assertThat(ssld.getContainerAddress().getPostalCode()).isEqualTo(POSTAL_CODE); assertThat(ssld.getGpsCoordinates().getLatitude()).isEqualTo(GPS_LATITUDE); assertThat(ssld.getGpsCoordinates().getLongitude()).isEqualTo(GPS_LONGITUDE); assertThat(ssld.isPublicKeyPresent()).isEqualTo(PUBLIC_KEY_PRESENT); }
Source:
<code>public void partClosed(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); IAdaptable adapter = part; <START> Control control = adapter.getAdapter(Control.class); <END> if (control != null && dndService != null) { dndService.removeMergedDropTarget(control); } }</code><technical_language>BndEditor need add getAdapter support for Control.class for this properly unmerge dropTarget</technical_language>

Target:
public void partClosed(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); Control control = part.getAdapter(Control.class); if (control != null && dndService != null) { dndService.removeMergedDropTarget(control); } }
Source:
<code>private boolean isRequiresFundingManagerApproval() { final ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService = SpringContext.getBean(ContractsGrantsInvoiceDocumentService.class); boolean result; <START> result = !getInvoiceSuspensionCategories().isEmpty() || !getInvoiceGeneralDetail().getAward().getAutoApproveIndicator() || (contractsGrantsInvoiceDocumentService.isDocumentBatchCreated(this) && !contractsGrantsInvoiceDocumentService.doesInvoicePassValidation(this)); <END> return result; }</code><technical_language>I suppose CollectionUtils.isNotEmpty() buys much</technical_language>

Target:
private boolean isRequiresFundingManagerApproval() { final ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService = SpringContext.getBean(ContractsGrantsInvoiceDocumentService.class); boolean result; result = !CollectionUtils.isEmpty(getInvoiceSuspensionCategories()) || !getInvoiceGeneralDetail().getAward().getAutoApproveIndicator() || (contractsGrantsInvoiceDocumentService.isDocumentBatchCreated(this) && !contractsGrantsInvoiceDocumentService.doesInvoicePassValidation(this)); return result; }
Source:
<code><START> synchronized public void validateTransition(List<WidgetResult> results, IValueProvider valueProvider, IAtsWidgetDefinition widgetDef, IAtsStateDefinition fromStateDef, IAtsStateDefinition toStateDef) { <END> for (AtsXWidgetValidatorProvider provider : providers) { for (IAtsXWidgetValidator validator : provider.getValidators()) { try { WidgetResult status = validator.validateTransition(valueProvider, widgetDef, fromStateDef, toStateDef); if (!status.isValid()) { results.add(status); } } catch (Exception ex) { results.add(new WidgetResult(WidgetStatus.Exception, widgetDef, ex, String.format( "Exception retriving validation for widget [%s] Exception [%s]", validator.getClass().getSimpleName(), ex.getLocalizedMessage()), ex)); return; } } } }</code><technical_language>synchronized? this achieved a thread safe list for providers? is a reason this needed</technical_language>

Target:
public void validateTransition(List<WidgetResult> results, IValueProvider valueProvider, IAtsWidgetDefinition widgetDef, IAtsStateDefinition fromStateDef, IAtsStateDefinition toStateDef) { for (AtsXWidgetValidatorProvider provider : providers) { for (IAtsXWidgetValidator validator : provider.getValidators()) { try { WidgetResult status = validator.validateTransition(valueProvider, widgetDef, fromStateDef, toStateDef); if (!status.isValid()) { results.add(status); } } catch (Exception ex) { results.add(new WidgetResult(WidgetStatus.Exception, widgetDef, ex, String.format( "Exception retriving validation for widget [%s] Exception [%s]", validator.getClass().getSimpleName(), ex.getLocalizedMessage()), ex)); return; } } } }
Source:
<code>public Map<String, Metric> getMetrics() { Map<String, Metric> metrics = new HashMap<>(); String prefix = this.getClass().getName() + "."; <START> metrics.put(prefix + "eventsWrittenPerSec", _eventWriteRate); <END> metrics.put(prefix + "eventBytesWrittenPerSec", _eventByteWriteRate); metrics.put(prefix + "eventTransportErrorCount", _eventTransportErrorCount); return Collections.unmodifiableMap(metrics); }</code><technical_language>add a utility method calls MetricRegistry.name() fully qualified metric name includes datastream.module</technical_language>

Target:
public Map<String, Metric> getMetrics() { Map<String, Metric> metrics = new HashMap<>(); metrics.put(buildMetricName("eventsWrittenPerSec"), _eventWriteRate); metrics.put(buildMetricName("eventBytesWrittenPerSec"), _eventByteWriteRate); metrics.put(buildMetricName("eventTransportErrorCount"), _eventTransportErrorRate); return Collections.unmodifiableMap(metrics); }
Source:
<code>public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); <START> org.wikipedia.LongPressHandler.ListViewContextMenuListener contextMenuListener <END> = new LongPressHandler(this); new org.wikipedia.LongPressHandler(getActivity(), searchResultsList, HistoryEntry.SOURCE_SEARCH, contextMenuListener); }</code><technical_language>put this top of file instead? import org.wikipedia.LongPressHandler.ListViewContextMenuListener;</technical_language>

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); LongPressHandler.ListViewContextMenuListener contextMenuListener = new SearchResultsFragmentLongPressHandler(this); new LongPressHandler(getActivity(), searchResultsList, HistoryEntry.SOURCE_SEARCH, contextMenuListener); }
Source:
<code>public List<Span> getChildren(String tenantId, String id) { List<Span> spans = new ArrayList<>(); try { final String index = client.getIndex(tenantId); RefreshRequestBuilder refreshRequestBuilder = client.getClient() .admin() .indices() .prepareRefresh(index); client.getClient() .admin() .indices() .refresh(refreshRequestBuilder.request()) .actionGet(); QueryBuilder query = QueryBuilders.termQuery("parentId", id); SearchRequestBuilder request = client.getClient() .prepareSearch(index) .setTypes(SPAN_TYPE) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(query); SearchResponse response = request.execute() .actionGet(); for (SearchHit searchHitFields : response.getHits()) { try { spans.add(deserialize(searchHitFields.getSourceAsString(), Span.class)); } catch (IOException ex) { <START> msgLog.errorFailedToParse(ex); <END> } } } catch (IndexMissingException ex) { msgLog.tracef("No index found, so unable to retrieve spans"); } msgLog.tracef("Get children with parentId[%s] is: %s", id, spans); return spans; }</code><technical_language>concern above: is OK return inconsistent result set, if more records fail parse</technical_language>

Target:
public List<Span> getChildren(String tenantId, String id) { List<Span> spans = new ArrayList<>(); final String index = client.getIndex(tenantId); try { RefreshRequestBuilder refreshRequestBuilder = client.getClient() .admin() .indices() .prepareRefresh(index); client.getClient() .admin() .indices() .refresh(refreshRequestBuilder.request()) .actionGet(); QueryBuilder query = QueryBuilders.termQuery("parentId", id); SearchRequestBuilder request = client.getClient() .prepareSearch(index) .setTypes(SPAN_TYPE) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(query); SearchResponse response = request.execute() .actionGet(); for (SearchHit searchHitFields : response.getHits()) { try { spans.add(deserialize(searchHitFields.getSourceAsString(), Span.class)); } catch (IOException ex) { log.errorFailedToParse(ex); throw new IllegalStateException("Failed to deserialize span", ex); } } } catch (IndexMissingException ex) { log.errorf("No index[%s] found, so unable to retrieve spans", index); } log.tracef("Get children with parentId[%s] is: %s", id, spans); return spans; }
Source:
<code>private String cliGetResult(String line) { log.info(line); cli.sendLine(line); String output = null; try { output = (String) cli.readAllAsOpResult().getResult(); } catch (IOException e) { <START> Assert.fail("Fail to get result of CLI command: " + line); <END> } return output; }</code><technical_language>add stack trace failure message. important of failure</technical_language>

Target:
private String cliGetResult(String line) { log.info(line); cli.sendLine(line); String output = null; try { output = (String) cli.readAllAsOpResult().getResult(); } catch (IOException e) { Assert.fail("Fail to get result of CLI command: " + line + "\n" + e.getMessage() + "\n" + e.getStackTrace()); } return output; }
Source:
<code>public void tryBuildDbAuthenticator(final Map<String, Authenticator> authenticators, final Map<String, PasswordEncoder> encoders) { for (int i = 0; i <= MAX_NUM_AUTHENTICATORS; i++) { <START> if (containsProperty(COUCH_URL, i) || containsProperty(COUCH_DATABASENAME, i)) { <END> final Builder httpClientBuilder = new StdHttpClient.Builder(); if (containsProperty(COUCH_USERNAME, i)) { httpClientBuilder.username(getProperty(COUCH_USERNAME, i)); } if (containsProperty(COUCH_PASSWORD, i)) { httpClientBuilder.password(getProperty(COUCH_PASSWORD, i)); } if (containsProperty(COUCH_URL, i)) { httpClientBuilder.password(getProperty(COUCH_URL, i)); } else { throw new TechnicalException("missing "+COUCH_URL+" property in CouchDB configuration"); } final HttpClient httpClient = httpClientBuilder.build(); final CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient); if (!containsProperty(COUCH_DATABASENAME, i)) { throw new TechnicalException("missing "+COUCH_DATABASENAME+" property in CouchDB configuration"); } final String databaseName = getProperty(COUCH_DATABASENAME, i); if (!dbInstance.checkIfDbExists(databaseName)) { throw new TechnicalException("Database "+databaseName+" does not exist, please create it with the appropriate design doc, see <LINK_0>"); } final CouchDbConnector db = dbInstance.createConnector(COUCH_DATABASENAME, false); final CouchProfileService authenticator = new CouchProfileService(db); if (containsProperty(COUCH_PASSWORD_ENCODER, i)) { authenticator.setPasswordEncoder(encoders.get(getProperty(COUCH_PASSWORD_ENCODER, i))); } authenticators.put(concat("couch", i), authenticator); } } }</code><technical_language>Reading source code above, I feeling properties required</technical_language>

Target:
public void tryBuildDbAuthenticator(final Map<String, Authenticator> authenticators, final Map<String, PasswordEncoder> encoders) { for (int i = 0; i <= MAX_NUM_AUTHENTICATORS; i++) { if (containsProperty(COUCH_URL, i) && containsProperty(COUCH_DATABASENAME, i)) { final Builder httpClientBuilder = new StdHttpClient.Builder(); if (containsProperty(COUCH_USERNAME, i)) { httpClientBuilder.username(getProperty(COUCH_USERNAME, i)); } if (containsProperty(COUCH_PASSWORD, i)) { httpClientBuilder.password(getProperty(COUCH_PASSWORD, i)); } try { httpClientBuilder.url(getProperty(COUCH_URL, i)); } catch (MalformedURLException e) { throw new TechnicalException(e); } final String databaseName = getProperty(COUCH_DATABASENAME, i); final HttpClient httpClient = httpClientBuilder.build(); final CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient); if (!dbInstance.checkIfDbExists(databaseName)) { throw new TechnicalException("Database "+databaseName+" does not exist, please create it with the appropriate design doc, see <LINK_0>"); } final CouchDbConnector db = dbInstance.createConnector(COUCH_DATABASENAME, false); final CouchProfileService authenticator = new CouchProfileService(db); if (containsProperty(COUCH_PASSWORD_ENCODER, i)) { authenticator.setPasswordEncoder(encoders.get(getProperty(COUCH_PASSWORD_ENCODER, i))); } authenticators.put(concat("couch", i), authenticator); } } }
Source:
<code>public static DistributedQueryRunner createQueryRunner(String dbConfigUrl, H2ResourceGroupsDao dao) throws Exception { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); builder.put("experimental.resource-groups-enabled", "true"); Map<String, String> properties = builder.build(); <START> DistributedQueryRunner queryRunner = new DistributedQueryRunner(testSessionBuilder().setCatalog("tpch").setSchema("tiny").build(), 2, ImmutableMap.of(), properties, new SqlParserOptions()); <END> try { Plugin h2ResourceGroupManagerPlugin = new H2ResourceGroupManagerPlugin(); queryRunner.installPlugin(h2ResourceGroupManagerPlugin); queryRunner.getCoordinator().getResourceGroupManager().get() .setConfigurationManager(CONFIGURATION_MANAGER_TYPE, ImmutableMap.of("resource-groups.config-db-url", dbConfigUrl)); queryRunner.installPlugin(new TpchPlugin()); queryRunner.createCatalog("tpch", "tpch"); setup(queryRunner, dao); return queryRunner; } catch (Exception e) { queryRunner.close(); throw e; } }</code><technical_language>Split stacked function calls separate lines</technical_language>

Target:
public static DistributedQueryRunner createQueryRunner(String dbConfigUrl, H2ResourceGroupsDao dao) throws Exception { DistributedQueryRunner queryRunner = new DistributedQueryRunner( testSessionBuilder().setCatalog("tpch").setSchema("tiny").build(), 2, ImmutableMap.of("experimental.resource-groups-enabled", "true"), ImmutableMap.of(), new SqlParserOptions()); try { Plugin h2ResourceGroupManagerPlugin = new H2ResourceGroupManagerPlugin(); queryRunner.installPlugin(h2ResourceGroupManagerPlugin); queryRunner.getCoordinator().getResourceGroupManager().get() .setConfigurationManager(CONFIGURATION_MANAGER_TYPE, ImmutableMap.of("resource-groups.config-db-url", dbConfigUrl)); queryRunner.installPlugin(new TpchPlugin()); queryRunner.createCatalog("tpch", "tpch"); setup(queryRunner, dao); return queryRunner; } catch (Exception e) { queryRunner.close(); throw e; } }
Source:
<code>private static void startNCs(ClusterType type, int sleepms) throws IOException, InterruptedException { LOG.info("Starting NC's"); String startNCCmd = System.getProperty("app.home", ".") + File.separator + "bin" + File.separator + "startAllNCs.sh " + type; <START> Files.setPosixFilePermissions(FileSystems.getDefault().getPath(startNCCmd), <END> PosixFilePermissions.fromString("rwxr-x---")); Process p = Runtime.getRuntime().exec(startNCCmd); p.waitFor(); Thread.sleep(sleepms); System.out.println("\nstdout: " + IOUtils.toString(p.getInputStream()) + "\nstderr: " + IOUtils.toString(p.getErrorStream())); if (p.exitValue() != 0) throw new RuntimeException("Failed to start the" + type + " NC's! Script returned exit code: " + p.exitValue() + "\nstdout: " + IOUtils.toString(p.getInputStream()) + "\nstderr: " + IOUtils.toString(p.getErrorStream())); }</code><technical_language>I this idea run issues user file (imagine a system-wide install of genomix). encase this in a try/catch block (or a function one)</technical_language>

Target:
private static void startNCs(ClusterType type, int sleepms) throws IOException, InterruptedException { LOG.info("Starting NC's"); String startNCCmd = System.getProperty("app.home", ".") + File.separator + "bin" + File.separator + "startAllNCs.sh " + type; Process p = Runtime.getRuntime().exec(startNCCmd); p.waitFor(); Thread.sleep(sleepms); System.out.println("\nstdout: " + IOUtils.toString(p.getInputStream()) + "\nstderr: " + IOUtils.toString(p.getErrorStream())); if (p.exitValue() != 0) throw new RuntimeException("Failed to start the" + type + " NC's! Script returned exit code: " + p.exitValue() + "\nstdout: " + IOUtils.toString(p.getInputStream()) + "\nstderr: " + IOUtils.toString(p.getErrorStream())); }
Source:
<code>public Observable<TranslationRowData> getOnClickDownloadSubject() { <START> return onClickDownloadSubject; <END> }</code><technical_language>return onClickDownloadSubject.hide()</technical_language>

Target:
public Observable<TranslationRowData> getOnClickDownloadSubject() { return onClickDownloadSubject.hide(); }
Source:
<code>public void handleRebalance(final String cacheName, final CacheTopology cacheTopology, final int viewId, final Address sender) throws InterruptedException { if (!running) { log.debugf("Ignoring rebalance request %s for cache %s, the local cache manager is not running", cacheTopology.getTopologyId(), cacheName); return; } final LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { log.tracef("Ignoring rebalance %s for cache %s that doesn't exist locally", cacheTopology.getTopologyId(), cacheName); return; } cacheStatus.getTopologyUpdatesCompletionService().submit(new Runnable() { @Override public void run() { try { doHandleRebalance(viewId, cacheStatus, cacheTopology, cacheName, sender); } catch (Throwable t) { <START> log.errorf(t, "Error handling rebalance request %s", cacheTopology); <END> } } }, null); }</code><technical_language>Is this want here? If a Log method then</technical_language>

Target:
public void handleRebalance(final String cacheName, final CacheTopology cacheTopology, final int viewId, final Address sender) throws InterruptedException { if (!running) { log.debugf("Ignoring rebalance request %s for cache %s, the local cache manager is not running", cacheTopology.getTopologyId(), cacheName); return; } final LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { log.tracef("Ignoring rebalance %s for cache %s that doesn't exist locally", cacheTopology.getTopologyId(), cacheName); return; } cacheStatus.getTopologyUpdatesCompletionService().submit(new Runnable() { @Override public void run() { try { doHandleRebalance(viewId, cacheStatus, cacheTopology, cacheName, sender); } catch (Throwable t) { log.rebalanceStartError(cacheName, t); } } }, null); }
Source:
<code><START> public Composite getControl() { <END> return fTimeAlignedComposite; }</code><technical_language>This is API breakage. A composite is a control, a control is necessary composite. (I API tool show that, though). Also, is this change needed</technical_language>

Target:
public Control getControl() { return fTimeAlignedComposite; }
Source:
<code>private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long count, INewSegment segmentCreator) { for (int i = 0; i < count; i++) { <START> long start = i + fuzz[i % size]; <END> store.add(segmentCreator.createSegment(start, start + 10, i)); } }</code><technical_language>I this line create overflows Segments negative start times (before tree start)</technical_language>

Target:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long count, INewSegment segmentCreator) { for (int i = 0; i < count; i++) { long start = (long) i + fuzz[i % size]; store.add(segmentCreator.createSegment(start, start + 10, i)); } }
Source:
<code>public String getBootstrapConnector(String baseConnectorType) { if (!_isInitialized) { String errorMessage = "DatastreamServer is not initialized."; LOG.error(errorMessage); throw new DatastreamRuntimeException(errorMessage); } String ret = _bootstrapConnectors.get(baseConnectorType); if (ret == null) { String errorMessage = "No bootstrap connector specified for connector: " + baseConnectorType; LOG.error(errorMessage); <START> throw new DatastreamRuntimeException(errorMessage); <END> } return ret; }</code><technical_language>new logAndThrow() mentioned above</technical_language>

Target:
public String getBootstrapConnector(String baseConnectorType) { if (!_isInitialized) { String errorMessage = "DatastreamServer is not initialized."; ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, null); } String ret = _bootstrapConnectors.get(baseConnectorType); if (ret == null) { String errorMessage = "No bootstrap connector specified for connector: " + baseConnectorType; ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, null); } return ret; }
Source:
<code>public void factoryCreatesExecutorsWithoutListeners() { <START> WorkflowStateProcessor executor = factory.createProcessor(12, () -> FALSE); <END> assertNotNull(executor); }</code><technical_language>FALSE::booleanValue () -> FALSE consistently</technical_language>

Target:
public void factoryCreatesExecutorsWithoutListeners() { WorkflowStateProcessor executor = factory.createProcessor(12, FALSE::booleanValue); assertNotNull(executor); }
Source:
<code>public String putProject(final ProjectStorageMetadata metadata, final File localFile) { this.hdfsAuth.authorize(); final Path projectsPath = new Path(this.projectRootUri.getPath(), String.valueOf(metadata.getProjectId())); try { if (this.hdfs.mkdirs(projectsPath)) { log.info("Created project dir: " + projectsPath); } final Path targetPath = new Path(projectsPath, StorageUtils.getTargetProjectFilename(metadata.getProjectId(), metadata.getHash())); final Path tmpPath = new Path(projectsPath, TMP_PROJECT_UPLOAD_FILENAME); log.info(String.format("Creating project artifact: meta: %s path: %s", metadata, targetPath)); <START> this.hdfs.copyFromLocalFile(true, true, new Path(localFile.getAbsolutePath()), tmpPath); <END> this.hdfs.rename(tmpPath, targetPath, Options.Rename.OVERWRITE); return getRelativeProjectPath(targetPath); } catch (final IOException e) { log.error("error in putProject(): Metadata: " + metadata); throw new StorageException(e); } }</code><technical_language>1st bool is delete source -- is want? I original behaviour source. matter</technical_language>

Target:
public String putProject(final ProjectStorageMetadata metadata, final File localFile) { this.hdfsAuth.authorize(); final Path projectsPath = new Path(this.projectRootUri.getPath(), String.valueOf(metadata.getProjectId())); try { if (this.hdfs.mkdirs(projectsPath)) { log.info("Created project dir: " + projectsPath); } final Path targetPath = new Path(projectsPath, StorageUtils.getTargetProjectFilename(metadata.getProjectId(), metadata.getHash())); final Path tmpPath = new Path(projectsPath, TMP_PROJECT_UPLOAD_FILENAME); log.info(String.format("Creating project artifact: meta: %s path: %s", metadata, targetPath)); this.hdfs.copyFromLocalFile(false, true, new Path(localFile.getAbsolutePath()), tmpPath); this.hdfs.rename(tmpPath, targetPath, Options.Rename.OVERWRITE); return getRelativeProjectPath(targetPath); } catch (final IOException e) { log.error("error in putProject(): Metadata: " + metadata); throw new StorageException(e); } }
Source:
<code>public List<Port> ports() { List<Port> list = Lists.newArrayList(); <START> list.addAll(ports.stream().filter(port -> port.isVisible()).collect(Collectors.toList())); <END> return list; }</code><technical_language>list collector directly</technical_language>

Target:
public List<Port> ports() { return ports.stream().filter(Port::isVisible).collect(Collectors.toCollection(ArrayList::new)); }
Source:
<code>public void actionPerformed(AnActionEvent e) { PantsMakeBeforeRun.terminatePantsProcess(e.getProject()); <START> PantsConsoleManager.getOrMakeNewConsole(e.getProject()).print("\nPants process terminated.", ConsoleViewContentType.ERROR_OUTPUT); <END> }</code><technical_language>same. feels PantsProcessCancellationAction StopAction this extracted a common location. a reason slightly different</technical_language>

Target:
public void actionPerformed(AnActionEvent e) { PantsMakeBeforeRun.terminatePantsProcess(e.getProject()); PantsConsoleManager.getOrMakeNewConsole(e.getProject()).print(PantsBundle.message("pants.command.terminated"), ConsoleViewContentType.ERROR_OUTPUT); }
Source:
<code>private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean enableBasicAuth = false; String strVal = request.getSession().getServletContext().getInitParameter("enable-basic-auth"); if (StringUtils.isNotEmpty(strVal)) { enableBasicAuth = Boolean.parseBoolean(strVal); } boolean needsBasicAuthHandling = enableBasicAuth && !containsUserCredentialsInParams(request.getParameterMap()); try { <START> Credentials userCredentials = getUserCredentials(enableBasicAuth, request); <END> if (userCredentials == null) { throw new AuthenticationException("Credentials Required"); } try { AuthenticationUtils.handleCredentials( session, userCredentials.getUsername(), userCredentials.getPassword(), userCredentials.getProfile()); request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } } catch (AuthenticationException ex) { if (needsBasicAuthHandling) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_EXTERNAL_URI + request.getQueryString()); } else { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } } }</code><technical_language>a function a selector (enableBasicAuth) is nightly coupled. notice do care basic this point, fallback session. do: Credentials creds = credsFromRequest(request); if (creds == null) { creds = credsFromSession(session); } if (creds != null) { attempt login if fail creds = null } if (creds != null) { redirect } else { show login } and: finally { // clear session do hold passwords credsClearSession(session); }</technical_language>

Target:
private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Credentials userCredentials = getUserCredentialsFromRequest(request); if (userCredentials == null) { userCredentials = getUserCredentialsFromSession(request); } if (userCredentials == null) { throw new AuthenticationException("Credentials Required"); } try { AuthenticationUtils.handleCredentials( session, userCredentials.getUsername(), userCredentials.getPassword(), userCredentials.getProfile()); request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } } catch (AuthenticationException ex) { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } finally { request.getSession().removeAttribute(SSOUtils.USER_CREDENTIALS); } }
Source:
<code>private Citation extractCitationFromRunData(RunData data) { try { SessionState session = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if(session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { List refs = (List) session .getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); String citationCollectionId = (String) sessionManager.getCurrentToolSession().getAttribute(STATE_CITATION_COLLECTION_ID); CitationCollection collection = getCitationService().getCollection(citationCollectionId); Citation citation = null; if (!refs.isEmpty()) { <START> for (Iterator it = refs.iterator(); it.hasNext(); ) { <END> Reference selection = (Reference) it.next(); String resourceId = selection.getId(); ContentResource resource = contentService.getResource(resourceId); ResourceProperties props = resource.getProperties(); String displayName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME); citation = citationService.addCitation("unknown"); citation.setDisplayName(displayName); citation.setCitationProperty("resourceId", resourceId); String urlId = citation.addCustomUrl(resource.getUrl(), resource.getUrl()); citation.setPreferredUrl(urlId); } session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); return citation; } } } catch (PermissionException e) { logger.warn("Unable to extract citation" + e.getMessage()); } catch (IdUnusedException e) { logger.warn("Unable to extract citation" + e.getMessage()); } catch (TypeException e) { logger.warn("Unable to extract citation" + e.getMessage()); } return null; }</code><technical_language>iterate references, throw changes one, is a reason for this</technical_language>

Target:
private Citation extractCitationFromRunData(RunData data) { try { SessionState session = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if(session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { List refs = (List) session .getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); Citation citation = null; if (!refs.isEmpty()) { Reference selection = (Reference) refs.get(0); String resourceId = selection.getId(); ContentResource resource = contentService.getResource(resourceId); ResourceProperties props = resource.getProperties(); String displayName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME); citation = citationService.addCitation("unknown"); citation.setDisplayName(displayName); citation.setCitationProperty("resourceId", resourceId); String urlId = citation.addCustomUrl(resource.getUrl(), resource.getUrl()); citation.setPreferredUrl(urlId); session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); return citation; } } } catch (PermissionException e) { logger.warn("Unable to extract citation" + e.getMessage()); } catch (IdUnusedException e) { logger.warn("Unable to extract citation" + e.getMessage()); } catch (TypeException e) { logger.warn("Unable to extract citation" + e.getMessage()); } return null; }
Source:
<code>private IndexValue(long size, Offset offset, byte flags, long expiresAtMs, long originalMessageOffset, long operationTimeInMs, short serviceId, short containerId) { this.size = size; this.offset = offset; this.flags = flags; if (TimeUnit.MILLISECONDS.toSeconds(expiresAtMs) > Integer.MAX_VALUE) { this.expiresAtMs = Utils.Infinite_Time; <START> } else if (expiresAtMs != Utils.Infinite_Time && expiresAtMs < 0) { <END> this.expiresAtMs = 0; } else { this.expiresAtMs = Utils.getTimeInMsToTheNearestSec(expiresAtMs); } this.originalMessageOffset = originalMessageOffset; this.operationTimeInMs = Utils.getTimeInMsToTheNearestSec(operationTimeInMs); this.serviceId = serviceId; this.containerId = containerId; version = PersistentIndex.CURRENT_VERSION; }</code><technical_language>is this removed</technical_language>

Target:
private IndexValue(long size, Offset offset, byte flags, long expiresAtMs, long originalMessageOffset, long operationTimeInMs, short serviceId, short containerId) { this.size = size; this.offset = offset; this.flags = flags; if (TimeUnit.MILLISECONDS.toSeconds(expiresAtMs) > Integer.MAX_VALUE) { this.expiresAtMs = Utils.Infinite_Time; } else { this.expiresAtMs = Utils.getTimeInMsToTheNearestSec(expiresAtMs); } this.originalMessageOffset = originalMessageOffset; this.operationTimeInMs = Utils.getTimeInMsToTheNearestSec(operationTimeInMs); this.serviceId = serviceId; this.containerId = containerId; version = PersistentIndex.CURRENT_VERSION; }
Source:
<code>public Transaction startLong() { txMetricsCollector.gauge("start.long", 1); Stopwatch timer = new Stopwatch().start(); long currentTime = System.currentTimeMillis(); <START> Transaction tx = startTx(-currentTime); <END> txMetricsCollector.gauge("start.long.latency", (int) timer.elapsedMillis()); return tx; }</code><technical_language>do need currentTime? "-1" simpler, no</technical_language>

Target:
public Transaction startLong() { txMetricsCollector.gauge("start.long", 1); Stopwatch timer = new Stopwatch().start(); Transaction tx = startTx(-1); txMetricsCollector.gauge("start.long.latency", (int) timer.elapsedMillis()); return tx; }
Source:
<code>public void undeploy(String namespace, Deployment deployment) { if (namespace == null || namespace.isEmpty() || deployment == null) { throw new IllegalArgumentException(); } Map<String, Deployment> deploymentsMap = namespaceDeploymentsMap.get(namespace); if (deploymentsMap == null) { throw new RuntimeException("Deployment [" + deployment + "] not found in namespace " + namespace); } <START> if (deploymentsMap.get(deployment.getId()) != null) { <END> deploymentsMap.remove(deployment.getId()); } }</code><technical_language>do need check this? I remove</technical_language>

Target:
public void undeploy(String namespace, Deployment deployment) { if (namespace == null || namespace.isEmpty() || deployment == null) { throw new IllegalArgumentException(); } Map<String, Deployment> deploymentsMap = namespaceDeploymentsMap.get(namespace); if (deploymentsMap == null) { throw new RuntimeException("Deployment [" + deployment + "] not found in namespace " + namespace); } deploymentsMap.remove(deployment.getId()); }
Source:
<code>protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { ClassLoader oldClassloader = Plugins.compareAndSwapLoaders(this); Class<?> klass = findLoadedClass(name); if (klass == null) { try { if (PluginUtils.shouldLoadInIsolation(name)) { klass = findClass(name); } } catch (ClassNotFoundException e) { log.trace("Class '{}' not found. Delegating to parent", name); } } if (klass == null) { klass = super.loadClass(name, false); } if (resolve) { resolveClass(klass); } <START> Plugins.compareAndSwapLoaders(oldClassloader); <END> return klass; } }</code><technical_language>This in a finally block in case exception is thrown, right</technical_language>

Target:
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> klass = findLoadedClass(name); if (klass == null) { try { if (PluginUtils.shouldLoadInIsolation(name)) { klass = findClass(name); } } catch (ClassNotFoundException e) { log.trace("Class '{}' not found. Delegating to parent", name); } } if (klass == null) { klass = super.loadClass(name, false); } if (resolve) { resolveClass(klass); } return klass; } }