auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); Path folder = Paths.get(System.getProperty("user.dir") + "/testResources/"); ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); <START> assertEquals(exercises.size(), 153); <END> assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }</code><technical_language>this</technical_language>

Target:
public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); Path folder = Paths.get(System.getProperty("user.dir") + "/testResources/"); ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); assertEquals(153, exercises.size()); assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }
Source:
<code>public void clickAdvancedButton() { <START> advancedButton.click(); <END> }</code><technical_language>public method, add "log()" statement</technical_language>

Target:
public void clickAdvancedButton() { advancedButton.click(); PageObjectLogging.log("clickAdvancedButton", "Advance button was clicked", true, driver); }
Source:
<code>private String[] rootArgumentsOnly() throws BadArgumentException { List<String> rootArguments = new ArrayList<String>(); for (int i = 0; i < this.args.length; i++) { final String token = this.args[i]; if (matchesOption(COMMAND, token) || matchesOption(VIEW_TYPE, token) || matchesOption(ACCESS_KEY, token) || matchesOption(SECRET_KEY, token) || matchesOption(ENDPOINT, token) || matchesOption(PROXY, token)) { rootArguments.add(token); if (i < this.args.length) { rootArguments.add(this.args[++i]); } else { throw new BadArgumentException("No argument supplied for option: " + token); } } if (matchesOption(COMMAND_HELP, token)) { rootArguments.add(token); if ((i < this.args.length) && (!this.args[i + 1].startsWith("-"))) { rootArguments.add(this.args[++i]); } } if ((matchesOption(VERBOSE, token)) || (matchesOption(PRINT_HELP, token)) || (matchesOption(TRACE, token)) || (matchesOption(DEBUG, token)) || (matchesOption(VERBOSE, token)) || (matchesOption(LOG_TRACE, token)) || (matchesOption(LOG_DEBUG, token)) || (matchesOption(LOG_VERBOSE, token))) { rootArguments.add(token); } } <START> String[] ret = new String[rootArguments.size()]; <END> ret = rootArguments.toArray(ret); return ret; }</code><technical_language>Missing final</technical_language>

Target:
private String[] rootArgumentsOnly() throws BadArgumentException { final List<String> rootArguments = new ArrayList<String>(); for (int i = 0; i < this.args.length; i++) { final String token = this.args[i]; if (matchesOption(COMMAND, token) || matchesOption(VIEW_TYPE, token) || matchesOption(ACCESS_KEY, token) || matchesOption(SECRET_KEY, token) || matchesOption(ENDPOINT, token) || matchesOption(PROXY, token) || matchesOption(RETRIES, token)) { rootArguments.add(token); if (i < this.args.length) { rootArguments.add(this.args[++i]); } else { throw new BadArgumentException("No argument supplied for option: " + token); } } if (matchesOption(COMMAND_HELP, token)) { rootArguments.add(token); if ((i < this.args.length) && (!this.args[i + 1].startsWith("-"))) { rootArguments.add(this.args[++i]); } } if ((matchesOption(VERBOSE, token)) || (matchesOption(PRINT_HELP, token)) || (matchesOption(TRACE, token)) || (matchesOption(DEBUG, token)) || (matchesOption(VERBOSE, token)) || (matchesOption(LOG_TRACE, token)) || (matchesOption(LOG_DEBUG, token)) || (matchesOption(LOG_VERBOSE, token))) { rootArguments.add(token); } } return rootArguments.toArray(new String[rootArguments.size()]); }
Source:
<code>private <T> T query(IQuery<DB, T> query, boolean asTransaction) { DB connection = dbManager.getConnection(); try { connection.setAutoCommit(!asTransaction); long startTime = System.currentTimeMillis(); T value = query.query(connection); if (asTransaction) { connection.commit(); } long executionTime = System.currentTimeMillis() - startTime; if (metricsTrackingEnabled) { queryMetrics.update(executionTime, Thread.currentThread().getStackTrace()[3]); } dbManager.returnConnection(connection); return value; } catch (Exception e) { LOG.error("SQL execution failure", e); if (asTransaction) { try { <START> connection.rollback(); <END> } catch (Exception e2) { } } dbManager.returnConnection(connection); throw new SqlExecutionFailureException(e); } catch (Throwable t) { if (asTransaction) { connection.rollback(); } throw t; } }</code><technical_language>sense put this in a try-finally block? remove this block connection returned? java if (asTransaction) { connection.rollback(); }</technical_language>

Target:
private <T> T query(IQuery<DB, T> query, boolean asTransaction) { DB connection = dbManager.getConnection(); boolean connectionSafeToReturn = true; try { connection.setAutoCommit(!asTransaction); long startTime = System.currentTimeMillis(); T value = query.query(connection); if (asTransaction) { connection.commit(); } long executionTime = System.currentTimeMillis() - startTime; if (metricsTrackingEnabled) { queryMetrics.update(executionTime, Thread.currentThread().getStackTrace()[3]); } return value; } catch (Exception e) { LOG.error("SQL execution failure", e); if (asTransaction) { connectionSafeToReturn = tryToSafelyRollback(connection); } throw new SqlExecutionFailureException(e); } catch (Throwable t) { if (asTransaction) { connectionSafeToReturn = tryToSafelyRollback(connection); } throw t; } finally { if (connectionSafeToReturn) { dbManager.returnConnection(connection); } else { dbManager.invalidateConnection(connection); } } }
Source:
<code>public void testPerformance() throws Exception { init(false, temporaryFolder.getRoot()); File smallFile = temporaryFolder.newFile("smallFile.xml"); <START> File bigFile = temporaryFolder.newFile("bigFile.xml"); <END> String simpleTag = "<tag1 attr=\"val1\">text</tag1>\n"; String xml = "<?xml version=\"1.0\"?><root>\n"; StringBuilder str = new StringBuilder(xml); for (int i = 0; i < 20000; i++) { str.append(simpleTag); } str.append("</root>"); FileUtils.write(smallFile, str.toString()); fs.add(createInputFile(smallFile.getAbsolutePath())); long t1 = System.currentTimeMillis(); sensor.analyse(context); long diffSmall = System.currentTimeMillis() - t1; str = new StringBuilder(xml); for (int i = 0; i < 40000; i++) { str.append(simpleTag); } str.append("</root>"); FileUtils.write(bigFile, str.toString()); init(false, temporaryFolder.getRoot()); fs.add(createInputFile(bigFile.getAbsolutePath())); t1 = System.currentTimeMillis(); sensor.analyse(context); long diffBig = System.currentTimeMillis() - t1; assert (diffBig < (2.5 * diffSmall)); }</code><technical_language>Extract logic build a xml file a dedicated method. configure call number of tags want. simplify test allow repeat operation</technical_language>

Target:
public void testPerformance() throws Exception { initFileSystemWithFile(createXmlFile(20000, "smallFile.xml")); long timeSmallFile = measureTimeToAnalyzeFile(); initFileSystemWithFile(createXmlFile(40000, "bigFile.xml")); long timeBigFile = measureTimeToAnalyzeFile(); assertThat(timeBigFile < (2.5 * timeSmallFile)).isTrue(); }
Source:
<code>public CompletableFuture<LanguageServer> getInitializedServer() { <START> if (initializeFuture != null && !this.initializeFuture.isDone()) { <END> return initializeFuture.thenApply(r -> this.languageServer); } return CompletableFuture.completedFuture(this.languageServer); }</code><technical_language>This maybe? call start() 1st line server is started</technical_language>

Target:
public CompletableFuture<LanguageServer> getInitializedServer() { try { start(); } catch (IOException ex) { LanguageServerPlugin.logError(ex); } if (initializeFuture != null && !this.initializeFuture.isDone()) { if (Display.getCurrent() != null) { Job waitForInitialization = new Job(Messages.initializeLanguageServer_job) { @Override protected IStatus run(IProgressMonitor monitor) { initializeFuture.join(); return Status.OK_STATUS; } }; waitForInitialization.setUser(true); waitForInitialization.setSystem(false); PlatformUI.getWorkbench().getProgressService().showInDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), waitForInitialization); } return initializeFuture.thenApply(r -> this.languageServer); } return CompletableFuture.completedFuture(this.languageServer); }
Source:
<code>public boolean isExistingRole(String roleName) throws UserStoreException { Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; boolean isExisting = false; try { dbConnection = getDBConnection(); prepStmt = dbConnection.prepareStatement(HybridJDBCConstants.GET_ROLE_ID); prepStmt.setString(1, roleName); prepStmt.setInt(2, tenantId); rs = prepStmt.executeQuery(); if (rs.next()) { int value = rs.getInt(1); if (value > -1) { isExisting = true; } } if(log.isDebugEnabled()) { log.debug("Is roleName: " + roleName + " Exist: " + isExisting + " TenantId: " + tenantId); } return isExisting; } catch (SQLException e) { <START> throw new UserStoreException("Error occurred while getting role id from role name :"+roleName, e); <END> } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } }</code><technical_language>add debug log</technical_language>

Target:
public boolean isExistingRole(String roleName) throws UserStoreException { Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; boolean isExisting = false; try { dbConnection = getDBConnection(); prepStmt = dbConnection.prepareStatement(HybridJDBCConstants.GET_ROLE_ID); prepStmt.setString(1, roleName); prepStmt.setInt(2, tenantId); rs = prepStmt.executeQuery(); if (rs.next()) { int value = rs.getInt(1); if (value > -1) { isExisting = true; } } if(log.isDebugEnabled()) { log.debug("Is roleName: " + roleName + " Exist: " + isExisting + " TenantId: " + tenantId); } return isExisting; } catch (SQLException e) { String errorMessage = "Error occurred while getting role id from role name : " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } }
Source:
<code>private static Properties loadProperties(Class<?> clazz, String resource) { <START> return loadProperties(clazz.getResourceAsStream(resource)); <END> }</code><technical_language>try resources for InputStream</technical_language>

Target:
private static Properties loadProperties(Class<?> clazz, String resource) { try ( InputStream is = clazz.getResourceAsStream(resource); ) { return loadProperties(is); } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
<code>public CommonPrefixes toCommonPrefixes() throws RuntimeException{ <START> if(isContents()) { <END> throw new RuntimeException("Could not create CommonPrefixes"); } final CommonPrefixes commonPrefixes = new CommonPrefixes(); commonPrefixes.setPrefix(prefix); return commonPrefixes; }</code><technical_language>Missing a space if (</technical_language>

Target:
public CommonPrefixes toCommonPrefixes() throws RuntimeException{ if (isContents()) { throw new UnableToConvertToCommonPrefixesException("Could not create a CommonPrefix"); } final CommonPrefixes commonPrefixes = new CommonPrefixes(); commonPrefixes.setPrefix(prefix); return commonPrefixes; }
Source:
<code>void saveToPreferences(Preferences prefs, ISecurePreferences securePrefs) throws StorageException { prefs.put(PROPERTY_ID, id); if(userVisibleName == null) { <START> prefs.put(PROPERTY_NAME, userVisibleName); <END> } prefs.putBoolean(PROPERTY_REMOVABLE, removable); if( defaultUsername != null ) prefs.put(PROPERTY_DEFAULT_USER, defaultUsername); Set<String> users = credentials.keySet(); String[] userList = (String[]) users.toArray(new String[users.size()]); prefs.put(PROPERTY_USER_LIST, String.join("\n", userList)); for( int i = 0; i < userList.length; i++ ) { String user = userList[i]; ISecurePreferences userNode = securePrefs.node(user); userNode.put(PROPERTY_PASS, getCredentials(user), true); } String[] promptedUsers = (String[]) promptedCredentials.toArray(new String[promptedCredentials.size()]); prefs.put(PROPERTY_PROMPTED_USER_LIST, String.join("\n", promptedUsers)); }</code><technical_language>log this error least. hide this problem completely</technical_language>

Target:
void saveToPreferences(Preferences prefs, ISecurePreferences securePrefs) throws StorageException { prefs.put(PROPERTY_ID, id); if(userVisibleName != null) { prefs.put(PROPERTY_NAME, userVisibleName); } prefs.putBoolean(PROPERTY_REMOVABLE, removable); if( defaultUsername != null ) prefs.put(PROPERTY_DEFAULT_USER, defaultUsername); Set<String> users = credentials.keySet(); String[] userList = (String[]) users.toArray(new String[users.size()]); prefs.put(PROPERTY_USER_LIST, String.join("\n", userList)); for( int i = 0; i < userList.length; i++ ) { String user = userList[i]; ISecurePreferences userNode = securePrefs.node(user); userNode.put(PROPERTY_PASS, getCredentials(user), true); } String[] promptedUsers = (String[]) promptedCredentials.toArray(new String[promptedCredentials.size()]); prefs.put(PROPERTY_PROMPTED_USER_LIST, String.join("\n", promptedUsers)); }
Source:
<code>public Response<Void> createWithResponse(Map<String, String> metadata, PublicAccessType accessType, Duration timeout, Context context) { <START> try { return blobContainerClient.createWithResponse(metadata, Transforms.toBlobPublicAccessType(accessType), timeout, context); } catch (BlobStorageException ex) { throw logger.logExceptionAsError(DataLakeImplUtils.transformBlobStorageException(ex)); } <END> }</code><technical_language>DataLakeImplUtils add a method ensure code is called place a try/catch convert is performed? java public static <T> T returnOrConvertException(Supplier<T> supplier, ClientLogger logger) { try { return supplier.get(); } catch (BlobStorageException ex) { throw logger.logExceptionAsError(transformBlobStorageException(ex)); } } A calling pattern clients this. java return DataLakeImplUtils.returnOrConvertException(() -> blobContainerClient.createWithResponse(metadata, Transforms.toBlobPublicAccessType(accessType), timeout, context), logger); a thought, current implementation correct changes cumbersome</technical_language>

Target:
public Response<Void> createWithResponse(Map<String, String> metadata, PublicAccessType accessType, Duration timeout, Context context) { return DataLakeImplUtils.returnOrConvertException(() -> blobContainerClient.createWithResponse(metadata, Transforms.toBlobPublicAccessType(accessType), timeout, context), logger); }
Source:
<code>protected List<Trace> getFragmentsForTraceId(String tenantId, String traceId) { <START> List<Trace> ret = new ArrayList<Trace>(); <END> String index = client.getIndex(tenantId); try { RefreshRequestBuilder refreshRequestBuilder = client.getClient().admin().indices().prepareRefresh(index); client.getClient().admin().indices().refresh(refreshRequestBuilder.request()).actionGet(); BoolQueryBuilder query = QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("traceId", traceId)); SearchRequestBuilder request = client.getClient().prepareSearch(index) .setTypes(TRACE_TYPE) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(query) .addSort(ElasticsearchUtil.TIMESTAMP_FIELD, SortOrder.ASC); SearchResponse response = request.execute().actionGet(); if (response.isTimedOut()) { msgLog.warnQueryTimedOut(); } for (SearchHit searchHitFields : response.getHits()) { try { ret.add(mapper.readValue(searchHitFields.getSourceAsString(), Trace.class)); } catch (IOException e) { msgLog.errorFailedToParse(e); } } if (msgLog.isTraceEnabled()) { msgLog.tracef("Query fragments with traceId[%s] is: %s", traceId, ret); } } catch (org.elasticsearch.indices.IndexMissingException ime) { if (msgLog.isTraceEnabled()) { msgLog.tracef("No index found, so unable to retrieve traces"); } } catch (org.elasticsearch.action.search.SearchPhaseExecutionException spee) { if (msgLog.isTraceEnabled()) { msgLog.tracef("Failed to get fragments", spee); } } return ret; }</code><technical_language>diamond operator</technical_language>

Target:
protected List<Trace> getFragmentsForTraceId(String tenantId, String traceId) { List<Trace> ret = Collections.emptyList(); String index = client.getIndex(tenantId); try { RefreshRequestBuilder refreshRequestBuilder = client.getClient().admin().indices().prepareRefresh(index); client.getClient().admin().indices().refresh(refreshRequestBuilder.request()).actionGet(); BoolQueryBuilder query = QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("traceId", traceId)); SearchRequestBuilder request = client.getClient().prepareSearch(index) .setTypes(TRACE_TYPE) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(query); SearchResponse response = request.execute().actionGet(); if (response.isTimedOut()) { msgLog.warnQueryTimedOut(); } ret = new ArrayList<Trace>((int)response.getHits().getTotalHits()); for (SearchHit searchHitFields : response.getHits()) { try { ret.add(mapper.readValue(searchHitFields.getSourceAsString(), Trace.class)); } catch (IOException e) { msgLog.errorFailedToParse(e); } } msgLog.tracef("Query fragments with traceId[%s] is: %s", traceId, ret); } catch (org.elasticsearch.indices.IndexMissingException ime) { msgLog.tracef("No index found, so unable to retrieve traces"); } catch (org.elasticsearch.action.search.SearchPhaseExecutionException spee) { msgLog.tracef("Failed to get fragments", spee); } return ret; }
Source:
<code>public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); <START> doReturn("").when(command).isConnWithSameDetailsExists(newPosixConnection, <END> null); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }</code><technical_language>empty string</technical_language>

Target:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); doReturn(newPosixConnection.getId()).when(command).isConnWithSameDetailsExists(newPosixConnection, null); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }
Source:
<code>public ListenableFuture<Boolean> createContainerInLocation(Location location, String container, CreateContainerOptions options) { if (Futures.getUnchecked(containerExists(container))) { return Futures.immediateFuture(Boolean.FALSE); } return super.createContainerInLocation(location, container, options); <START> } <END></code><technical_language>OK, thanks for explaining. If some S3 providers "respect" desired behaviour, I agree provider-specific code is right place for this</technical_language>

Target:
public ListenableFuture<Boolean> createContainerInLocation(Location location, String container, CreateContainerOptions options) { if ((location == null || location.getId().equals(Region.US_STANDARD)) && Futures.getUnchecked(containerExists(container))) { return Futures.immediateFuture(Boolean.FALSE); } return super.createContainerInLocation(location, container, options); }
Source:
<code>public void testGetErrorDetails() { VerificationError error = ResultErrorBuilder.withCodeAndDescription(VerificationError.asCode("test_code"), "test error desc") .detail(VerificationError.asAttribute("test_attr_1"), "test_detail_1") .detail(VerificationError.HttpAttribute.HTTP_CODE,"test_detail_2") .detail("HTTP_TEXT", "test_detail_3") .build(); Assert.assertEquals("test_detail_1", error.getDetail(VerificationError.asAttribute("test_attr_1"))); Assert.assertEquals("test_detail_1", error.getDetail("test_attr_1")); Assert.assertEquals("test_detail_2", error.getDetail(VerificationError.HttpAttribute.HTTP_CODE)); Assert.assertNull(error.getDetail(VerificationError.asAttribute("HTTP_CODE"))); <START> Assert.assertNull(error.getDetail("HTTP_CODE")); <END> Assert.assertNull(error.getDetail(VerificationError.HttpAttribute.HTTP_TEXT)); Assert.assertEquals("test_detail_3", error.getDetail("HTTP_TEXT")); Assert.assertNull(error.getDetail(VerificationError.asAttribute("test_attr_non_existant"))); }</code><technical_language>Yeah I in favor of a common pattern do lead a confusion for end users (you know, copy paste)</technical_language>

Target:
public void testGetErrorDetails() { VerificationError error = ResultErrorBuilder.withCodeAndDescription(VerificationError.asCode("test_code"), "test error desc") .detail(VerificationError.asAttribute("test_attr_1"), "test_detail_1") .detail(VerificationError.HttpAttribute.HTTP_CODE,"test_detail_2") .build(); Assert.assertEquals("test_detail_1", error.getDetail(VerificationError.asAttribute("test_attr_1"))); Assert.assertEquals("test_detail_1", error.getDetail("test_attr_1")); Assert.assertEquals("test_detail_2", error.getDetail(VerificationError.HttpAttribute.HTTP_CODE)); Assert.assertNull(error.getDetail(VerificationError.HttpAttribute.HTTP_TEXT)); Assert.assertNull(error.getDetail(VerificationError.asAttribute("test_attr_non_existant"))); }
Source:
<code><START> public void start() { <END> }</code><technical_language>useful if log a message indicating connector started</technical_language>

Target:
public void start() { LOG.info("Start called."); }
Source:
<code>public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException { Intent intent = request.getIntent(); if (HELP.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText("The OneBusAway skill will tell you upcoming transit arrivals " + "at a stop of your choice. You've already configured your region and stop, " + "so just open the skill or ask me for arrivals. " + "You can also ask me to change your city or stop."); return SpeechletResponse.newTellResponse(out); } else if (SET_CITY.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_CITY.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText( String.format("You live in %s, near the %s region.", userData.getCity(), userData.getRegionName())); return SpeechletResponse.newTellResponse(out); } else if (SET_STOP_NUMBER.equals(intent.getName())) { <START> populateAttributes(session); <END> return anonSpeechlet.onIntent(request, session); } else if (GET_STOP_NUMBER.equals(intent.getName())) { return getStopDetails(); } else if (GET_ARRIVALS.equals(intent.getName())) { return tellArrivals(); } else { throw new SpeechletException("Did not recognize intent name"); } }</code><technical_language>I AuthedSpeechlet populateAttributes always, in this branch. easier for reason session attributes</technical_language>

Target:
public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException { populateAttributes(session); Intent intent = request.getIntent(); if (HELP.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText("The OneBusAway skill will tell you upcoming transit arrivals " + "at a stop of your choice. You've already configured your region and stop, " + "so just open the skill or ask me for arrivals. " + "You can also ask me to change your city or stop."); return SpeechletResponse.newTellResponse(out); } else if (SET_CITY.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_CITY.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText( String.format("You live in %s, near the %s region.", userData.getCity(), userData.getRegionName())); return SpeechletResponse.newTellResponse(out); } else if (SET_STOP_NUMBER.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_STOP_NUMBER.equals(intent.getName())) { return getStopDetails(); } else if (GET_ARRIVALS.equals(intent.getName())) { return tellArrivals(); } else { throw new SpeechletException("Did not recognize intent name"); } }
Source:
<code><START> private void addStandardMappings(final String indexName) throws ElasticsearchException, IOException { <END> final ContentTypeAPI contentTypeAPI = APILocator.getContentTypeAPI(APILocator.systemUser()); final List<String> allTypes = Try.of(() -> new DotConnect().setSQL("select inode from structure").loadObjectResults()) .getOrElseThrow(e -> new DotRuntimeException(e)) .stream() .map(r -> (String) r.get("inode")) .collect(Collectors.toList()); final Map<String, Map<String, String>> mappingMap = new HashMap<>(); for (final String typeVar : allTypes) { mappingMap.clear(); final ContentType type = Try.of(() -> contentTypeAPI.find(typeVar)).getOrNull(); if (type == null) { continue; } final List<Field> indexedFields = type.fields().stream().filter(f -> f.indexed()) .filter(f -> !f.fieldVariablesMap().containsKey(FieldVariable.ES_CUSTOM_MAPPING_KEY)) .collect(Collectors.toList()); for (Field field : indexedFields) { Optional<Map<String, String>> fieldType = resolveFieldType(field); if (fieldType.isPresent()) { mappingMap.put(type.variable().toLowerCase() + "." + field.variable().toLowerCase(), fieldType.get()); } } if (!mappingMap.isEmpty()) { final JSONObject jsonObject = new JSONObject().put("properties", mappingMap); mappingAPI.putMapping(indexName, jsonObject.toString()); } } }</code><technical_language>if upper layer CloseDBIfOpened is ok, consider putting</technical_language>

Target:
private void addStandardMappings(final String indexName) throws ElasticsearchException, IOException { final ContentTypeAPI contentTypeAPI = APILocator.getContentTypeAPI(APILocator.systemUser()); final List<String> allTypes = Try.of(() -> new DotConnect().setSQL("select inode from structure").loadObjectResults()) .getOrElseThrow(e -> new DotRuntimeException(e)) .stream() .map(r -> (String) r.get("inode")) .collect(Collectors.toList()); final Map<String, Map<String, String>> mappingMap = new HashMap<>(); for (final String typeVar : allTypes) { mappingMap.clear(); final ContentType type = Try.of(() -> contentTypeAPI.find(typeVar)).getOrNull(); if (type == null) { continue; } final List<Field> indexedFields = type.fields().stream().filter(f -> f.indexed()) .filter(f -> !f.fieldVariablesMap().containsKey(FieldVariable.ES_CUSTOM_MAPPING_KEY)) .collect(Collectors.toList()); for (Field field : indexedFields) { Optional<Map<String, String>> fieldType = resolveFieldType(field); if (fieldType.isPresent()) { mappingMap.put(field.variable().toLowerCase(), fieldType.get()); } } if (!mappingMap.isEmpty()) { final JSONObject jsonObject = new JSONObject(); final JSONObject properties = new JSONObject(); jsonObject.put(type.variable().toLowerCase(), new JSONObject() .put("properties", mappingMap)); properties.put("properties", jsonObject); mappingAPI.putMapping(indexName, properties.toString()); } } }
Source:
<code>public VersionedCatalog loadDefaultCatalog(final String uriString) throws CatalogApiException { try { final List<URI> xmlURIs; if (uriString.endsWith(XML_EXTENSION)) { xmlURIs = new ArrayList<URI>(); xmlURIs.add(new URI(uriString)); } else { final URL url = getURLFromString(uriString); final String directoryContents = UriAccessor.accessUriAsString(uriString); xmlURIs = findXmlReferences(directoryContents, url); } <START> final DefaultVersionedCatalog result = new DefaultVersionedCatalog(new ArrayList<>()); <END> for (final URI u : xmlURIs) { final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(u, StandaloneCatalog.class); result.add(new StandaloneCatalogWithPriceOverride(catalog, priceOverride, InternalCallContextFactory.INTERNAL_TENANT_RECORD_ID, internalCallContextFactory)); } XMLLoader.initializeAndValidate(result); return result; } catch (final ValidationException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (final JAXBException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (IllegalArgumentException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (Exception e) { logger.warn("Failed to load default catalog", e); throw new IllegalStateException(e); } }</code><technical_language>no-arg constructor</technical_language>

Target:
public VersionedCatalog loadDefaultCatalog(final String uriString) throws CatalogApiException { try { final List<URI> xmlURIs; if (uriString.endsWith(XML_EXTENSION)) { xmlURIs = new ArrayList<URI>(); xmlURIs.add(new URI(uriString)); } else { final URL url = getURLFromString(uriString); final String directoryContents = UriAccessor.accessUriAsString(uriString); xmlURIs = findXmlReferences(directoryContents, url); } final DefaultVersionedCatalog result = new DefaultVersionedCatalog(); for (final URI u : xmlURIs) { final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(u, StandaloneCatalog.class); result.add(new StandaloneCatalogWithPriceOverride(catalog, priceOverride, InternalCallContextFactory.INTERNAL_TENANT_RECORD_ID, internalCallContextFactory)); } XMLLoader.initializeAndValidate(result); return result; } catch (final ValidationException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (final JAXBException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (IllegalArgumentException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (Exception e) { logger.warn("Failed to load default catalog", e); throw new IllegalStateException(e); } }
Source:
<code>public <T extends StorageLocationSetting> T createStorageLocationSetting(UserInfo userInfo, T storageLocationSetting) throws DatastoreException, NotFoundException { ValidateArgument.required(userInfo, "The user"); ValidateArgument.required(storageLocationSetting, "The storage location"); <START> if (storageLocationSetting instanceof BaseKeyStorageLocationSetting) { <END> sanitizeBaseKey((BaseKeyStorageLocationSetting) storageLocationSetting); } this.processStorageLocation(userInfo, storageLocationSetting); if (storageLocationSetting instanceof BucketOwnerStorageLocationSetting) { bucketOwnerVerifier.verifyBucketOwnership(userInfo, (BucketOwnerStorageLocationSetting) storageLocationSetting); } if (storageLocationSetting.getUploadType() == null) { storageLocationSetting.setUploadType(UploadType.NONE); } storageLocationSetting.setCreatedBy(userInfo.getId()); storageLocationSetting.setCreatedOn(new Date()); Long storageLocationId = storageLocationDAO.create(storageLocationSetting); return (T) storageLocationDAO.get(storageLocationId); }</code><technical_language>processors order annotation control dependencies</technical_language>

Target:
public <T extends StorageLocationSetting> T createStorageLocationSetting(UserInfo userInfo, T storageLocationSetting) throws DatastoreException, NotFoundException { ValidateArgument.required(userInfo, "The user"); ValidateArgument.required(storageLocationSetting, "The storage location"); this.processStorageLocation(userInfo, storageLocationSetting); if (storageLocationSetting.getUploadType() == null) { storageLocationSetting.setUploadType(UploadType.NONE); } storageLocationSetting.setCreatedBy(userInfo.getId()); storageLocationSetting.setCreatedOn(new Date()); Long storageLocationId = storageLocationDAO.create(storageLocationSetting); return (T) storageLocationDAO.get(storageLocationId); }
Source:
<code>public void testProducers() throws IOException { JsonObject allBeans = getPageAsJSONObject(BEANS_PATH_ALL, url); JsonArray beansData = allBeans.getJsonArray(DATA); List<JsonObject> producers = getAllJsonObjectsByClass(TestProducer.class, beansData); Optional<JsonObject> fieldProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_FIELD.name())) .findAny(); <START> assertNotNull("Cannot find producer field from " + TestProducer.class.getName(), fieldProducer.get()); <END> assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(String.class.getName(), null, fieldProducer.get().getJsonArray(TYPES), false)); Optional<JsonObject> methodProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_METHOD.name())) .findAny(); assertNotNull("Cannot find producer field from " + TestProducer.class.getName(), methodProducer.get()); assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(ModelBean.class.getName(), null, methodProducer.get().getJsonArray(TYPES), false)); }</code><technical_language>This fail "Cannot find producer ..." message. pass throw NoSuchElementException if optional is empty</technical_language>

Target:
public void testProducers() throws IOException { JsonObject allBeans = getPageAsJSONObject(BEANS_PATH_ALL, url); JsonArray beansData = allBeans.getJsonArray(DATA); List<JsonObject> producers = getAllJsonObjectsByClass(TestProducer.class, beansData); Optional<JsonObject> fieldProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_FIELD.name())) .findAny(); assertTrue("Cannot find producer field from " + TestProducer.class.getName(), fieldProducer.isPresent()); assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(String.class.getName(), null, fieldProducer.get().getJsonArray(TYPES), false)); Optional<JsonObject> methodProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_METHOD.name())) .findAny(); assertTrue("Cannot find producer method from " + TestProducer.class.getName(), methodProducer.isPresent()); assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(ModelBean.class.getName(), null, methodProducer.get().getJsonArray(TYPES), false)); }
Source:
<code>public void run() throws Exception { boolean hasInterceptor = mapServiceContext.hasInterceptor(name); List<Data> keyValueSequence = this.keyValueSequence; for (int i = 0; i < keyValueSequence.size(); i += 2) { Data key = keyValueSequence.get(i); Data dataValue = keyValueSequence.get(i + 1); checkNotNull(key, "Key loaded by a MapLoader cannot be null."); Object value = hasInterceptor ? mapServiceContext.toObject(dataValue) : dataValue; recordStore.putFromLoad(key, value, getCallerAddress()); if (value != null && !recordStore.existInMemory(key)) { continue; } if (value != null) { callAfterPutInterceptors(value); } Record record = recordStore.getRecord(key); if (isPostProcessing(recordStore)) { checkNotNull(record, "Value loaded by a MapLoader cannot be null."); value = record.getValue(); <START> } <END> publishWanUpdate(key, value); addInvalidation(key); } }</code><technical_language>Retrieving record in this method guarded if (isPostProcessing(recordStore)). Also, a general question, provide record publishWanUpdate if it? overloaded methods for record for value</technical_language>

Target:
public void run() throws Exception { boolean hasInterceptor = mapServiceContext.hasInterceptor(name); List<Data> keyValueSequence = this.keyValueSequence; for (int i = 0; i < keyValueSequence.size(); i += 2) { Data key = keyValueSequence.get(i); Data dataValue = keyValueSequence.get(i + 1); checkNotNull(key, "Key loaded by a MapLoader cannot be null."); Object value = hasInterceptor ? mapServiceContext.toObject(dataValue) : dataValue; recordStore.putFromLoad(key, value, getCallerAddress()); if (value != null && !recordStore.existInMemory(key)) { continue; } if (value != null) { callAfterPutInterceptors(value); } if (isPostProcessing(recordStore)) { Record record = recordStore.getRecord(key); checkNotNull(record, "Value loaded by a MapLoader cannot be null."); value = record.getValue(); } publishWanUpdate(key, value); addInvalidation(key); } }
Source:
<code>void initialize(ServerConfiguration conf, LedgerManager ledgerManager, LedgerDirsManager ledgerDirsManager, LedgerDirsManager indexDirsManager, StateManager stateManager, CheckpointSource checkpointSource, Checkpointer checkpointer, StatsLogger statsLogger) throws IOException; void start(); void shutdown() throws InterruptedException; boolean ledgerExists(long ledgerId) throws IOException; boolean setFenced(long ledgerId) throws IOException; boolean isFenced(long ledgerId) throws IOException; void setMasterKey(long ledgerId, byte[] masterKey) throws IOException; byte[] readMasterKey(long ledgerId) throws IOException, BookieException; long addEntry(ByteBuf entry) throws IOException, BookieException; <START> ByteBuf getEntry(long ledgerId, long entryId) throws IOException, Bookie.NoEntryException; <END> long getLastAddConfirmed(long ledgerId) throws IOException; boolean waitForLastAddConfirmedUpdate(long ledgerId, long previousLAC, Watcher<LastAddConfirmedUpdateNotification> watcher) throws IOException; void flush() throws IOException; void checkpoint(Checkpoint checkpoint) throws IOException; void deleteLedger(long ledgerId) throws IOException; interface LedgerDeletionListener { void ledgerDeleted(long ledgerId); }</code><technical_language>is purpose of changes in this file</technical_language>

Target:
void initialize(ServerConfiguration conf, LedgerManager ledgerManager, LedgerDirsManager ledgerDirsManager, LedgerDirsManager indexDirsManager, StateManager stateManager, CheckpointSource checkpointSource, Checkpointer checkpointer, StatsLogger statsLogger) throws IOException; void start(); void shutdown() throws InterruptedException; boolean ledgerExists(long ledgerId) throws IOException; boolean setFenced(long ledgerId) throws IOException; boolean isFenced(long ledgerId) throws IOException; void setMasterKey(long ledgerId, byte[] masterKey) throws IOException; byte[] readMasterKey(long ledgerId) throws IOException, BookieException; long addEntry(ByteBuf entry) throws IOException, BookieException; ByteBuf getEntry(long ledgerId, long entryId) throws IOException; long getLastAddConfirmed(long ledgerId) throws IOException; boolean waitForLastAddConfirmedUpdate(long ledgerId, long previousLAC, Watcher<LastAddConfirmedUpdateNotification> watcher) throws IOException; void flush() throws IOException; void checkpoint(Checkpoint checkpoint) throws IOException; void deleteLedger(long ledgerId) throws IOException; interface LedgerDeletionListener { void ledgerDeleted(long ledgerId); }
Source:
<code>public void deleteRole(String username, String role) { throw new RuntimeException("Deleting a role is not supporting in LDAP"); <START> <END> }</code><technical_language>extra space required</technical_language>

Target:
public void deleteRole(String username, String role) { throw new UnsupportedOperationException("Deleting a role is not supporting in LDAP"); }
Source:
<code>private void checkSpaceForStatement(Tree tree) { boolean shouldReportIssue = false; Iterator<Tree> it = ((PHPTree) tree).childrenIterator(); Tree next; Tree previous = null; while (it.hasNext()) { next = it.next(); if (isSemicolon(previous)) { SyntaxToken semicolonToken = (SyntaxToken) previous; <START> SyntaxToken nextToken = ((PHPTree) next).getFirstToken(); <END> int nbSpace = TokenUtils.getNbSpaceBetween(semicolonToken, nextToken); if (nbSpace != 1 && TokenUtils.isOnSameLine(semicolonToken, nextToken)) { shouldReportIssue = true; } } previous = next; } if (shouldReportIssue) { check.reportIssue(FOR_SEMICOLON_MESSAGE, tree); } }</code><technical_language>@lindamartin i right checking next for null happen if previous is semicolon</technical_language>

Target:
private void checkSpaceForStatement(Tree tree) { Iterator<Tree> iterator = ((PHPTree) tree).childrenIterator(); Tree next; Tree previous = null; while (iterator.hasNext()) { next = iterator.next(); if (isSemicolon(previous)) { SyntaxToken semicolonToken = (SyntaxToken) previous; SyntaxToken nextToken = ((PHPTree) next).getFirstToken(); int nbSpace = TokenUtils.getNbSpaceBetween(semicolonToken, nextToken); if (nbSpace != 1 && TokenUtils.isOnSameLine(semicolonToken, nextToken)) { check.reportIssue(FOR_SEMICOLON_MESSAGE, tree); break; } } previous = next; } }
Source:
<code>public void publishComments(final PatchSet.Id psid, final String message, final Set<ApprovalCategoryValue.Id> approvals, final AsyncCallback<VoidResult> callback) { run(callback, new Action<VoidResult>() { public VoidResult run(ReviewDb db) throws OrmException, Failure { final PublishResult r; r = db.run(new OrmRunnable<PublishResult, ReviewDb>() { public PublishResult run(ReviewDb db, Transaction txn, boolean retry) throws OrmException { return doPublishComments(psid, message, approvals, db, txn); } }); try { final CommentSender cm = new CommentSender(server, r.change); cm.setFrom(Common.getAccountId()); <START> cm.setPatchSet(r.patchSet, PatchSetInfoFactory.patchSetInfoFromPatchSetId(psid)); <END> cm.setChangeMessage(r.message); cm.setPatchLineComments(r.comments); cm.setReviewDb(db); cm.setHttpServletRequest(GerritJsonServlet.getCurrentCall() .getHttpServletRequest()); cm.send(); } catch (EmailException e) { log.error("Cannot send comments by email for patch set " + psid, e); throw new Failure(e); } catch (PatchSetInfoNotAvailableException e) { log.error("Failed to obtain PatchSetInfo for patch set " + psid, e); throw new Failure(e); } return VoidResult.INSTANCE; } }); }</code><technical_language>statically accessible</technical_language>

Target:
public void publishComments(final PatchSet.Id psid, final String message, final Set<ApprovalCategoryValue.Id> approvals, final AsyncCallback<VoidResult> callback) { run(callback, new Action<VoidResult>() { public VoidResult run(ReviewDb db) throws OrmException, Failure { final PublishResult r; r = db.run(new OrmRunnable<PublishResult, ReviewDb>() { public PublishResult run(ReviewDb db, Transaction txn, boolean retry) throws OrmException { return doPublishComments(psid, message, approvals, db, txn); } }); try { final CommentSender cm = new CommentSender(server, r.change); cm.setFrom(Common.getAccountId()); cm.setPatchSet(r.patchSet, patchSetInfoFactory.patchSetInfoFromPatchSetId(psid)); cm.setChangeMessage(r.message); cm.setPatchLineComments(r.comments); cm.setReviewDb(db); cm.setHttpServletRequest(GerritJsonServlet.getCurrentCall() .getHttpServletRequest()); cm.send(); } catch (EmailException e) { log.error("Cannot send comments by email for patch set " + psid, e); throw new Failure(e); } catch (PatchSetInfoNotAvailableException e) { log.error("Failed to obtain PatchSetInfo for patch set " + psid, e); throw new Failure(e); } return VoidResult.INSTANCE; } }); }
Source:
<code>public void end() throws Exception { <START> super.init(); <END> super.cleanup(); logViewer = null; }</code><technical_language>is a super.init() needed here</technical_language>

Target:
public void end() throws Exception { super.cleanup(); logViewer = null; }
Source:
<code>private static X509Certificate setupProviderCert() throws IOException, CertificateException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); <START> return (X509Certificate) cf.generateCertificate(ProductBodyguard.class.getResourceAsStream("/com/eviware/soapui/plugins/pubkey_smartbear_codesigning-fromjks.key")); <END> }</code><technical_language>I nicer call this file simply "PublicKey.key"</technical_language>

Target:
private static X509Certificate setupProviderCert() throws IOException, CertificateException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf.generateCertificate(ProductBodyguard.class.getResourceAsStream("/com/eviware/soapui/plugins/PublicKey.key")); }
Source:
<code>public AbstractRemoteFileOutboundGateway(RemoteFileTemplate<F> remoteFileTemplate, Command command, @Nullable String expressionArg) { Assert.notNull(remoteFileTemplate, "'remoteFileTemplate' cannot be null"); this.remoteFileTemplate = remoteFileTemplate; this.command = command; String expression = expressionArg; boolean noExpressionNeeded = Command.LS.equals(this.command) || Command.NLST.equals(this.command) || Command.PUT.equals(this.command) || Command.MPUT.equals(this.command); if ("++xsd.expression.default++".equals(expression)) { <START> expression = noExpressionNeeded ? null : "payload"; <END> } if (expression == null) { Assert.state(noExpressionNeeded, "Only LS, and NLST commands can rely on the working directory.\n" + "PUT and MPUT commands always use the payload.\n" + "All other commands must be supplied with a filename expression"); this.fileNameProcessor = null; } else { Expression parsedExpression = new SpelExpressionParser().parseExpression(expression); this.fileNameProcessor = new ExpressionEvaluatingMessageProcessor<>(parsedExpression); setPrimaryExpression(parsedExpression); } this.messageSessionCallback = null; remoteFileTemplateExplicitlySet(true); }</code><technical_language>set null parser override "payload" if needed command logic</technical_language>

Target:
public AbstractRemoteFileOutboundGateway(RemoteFileTemplate<F> remoteFileTemplate, Command command, @Nullable String expressionArg) { Assert.notNull(remoteFileTemplate, "'remoteFileTemplate' cannot be null"); this.remoteFileTemplate = remoteFileTemplate; this.command = command; String expression = expressionArg; boolean expressionNeeded = !(Command.LS.equals(this.command) || Command.NLST.equals(this.command) || Command.PUT.equals(this.command) || Command.MPUT.equals(this.command)); if (!StringUtils.hasText(expression) && expressionNeeded) { expression = "payload"; } if (!StringUtils.hasText(expression)) { this.fileNameProcessor = null; } else { Expression parsedExpression = new SpelExpressionParser().parseExpression(expression); this.fileNameProcessor = new ExpressionEvaluatingMessageProcessor<>(parsedExpression); setPrimaryExpression(parsedExpression); } this.messageSessionCallback = null; remoteFileTemplateExplicitlySet(true); }
Source:
<code>private String getGitPath(IFileRevision revision) { if (revision instanceof CommitFileRevision) { return ((CommitFileRevision) revision).getGitPath(); } IResourceVariant variant = <START> Adapters.adapt((revision), <END> IResourceVariant.class); if (variant instanceof GitRemoteResource) { return ((GitRemoteResource) variant).getPath(); } return null; }</code><technical_language>Extra parentheses away, too</technical_language>

Target:
private String getGitPath(IFileRevision revision) { if (revision instanceof CommitFileRevision) { return ((CommitFileRevision) revision).getGitPath(); } IResourceVariant variant = Adapters.adapt(revision, IResourceVariant.class); if (variant instanceof GitRemoteResource) { return ((GitRemoteResource) variant).getPath(); } return null; }