auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void restClientShouldPropagateSecurityContext() throws Exception { IgniteEx node1 = grid(0); <START> TestSecurityProcessor secPrc = U.field(node1.context().security(), "secPrc"); List<TestSecurityProcessor.AuthorizeRecord> records = secPrc.getAuthorizeRecords(); records.clear(); <END> Map<String, String> pie = new JettyRestProcessorAbstractSelfTest.VisorGatewayArgument(VisorQueryTask.class) .forNode(node1.localNode()) .argument(VisorQueryTaskArg.class, "pie", URLEncoder.encode("select * from pie", StandardCharsets.UTF_8.name()), false, false, false, false, 1); pie.put("user", "client"); pie.put("password", "client"); content(pie); for (TestSecurityProcessor.AuthorizeRecord record : records) assertEquals("client", record.getLogin()); }</code><technical_language>code style violation</technical_language>

Target:
public void restClientShouldPropagateSecurityContext() throws Exception { IgniteEx node1 = grid(0); TestSecurityProcessor secPrc = U.field(node1.context().security(), "secPrc"); List<TestSecurityProcessor.AuthorizeRecord> records = secPrc.getAuthorizeRecords(); records.clear(); String qry = URLEncoder.encode("select * from pie", StandardCharsets.UTF_8.name()); Map<String, String> pie = new JettyRestProcessorAbstractSelfTest.VisorGatewayArgument(VisorQueryTask.class) .forNode(node1.localNode()) .argument(VisorQueryTaskArg.class, "pie", qry, false, false, false, false, 1); pie.put("user", "client"); pie.put("password", "client"); content(pie); for (TestSecurityProcessor.AuthorizeRecord record : records) assertEquals("client", record.getLogin()); }
Source:
<code>public String apply(String value) { <START> return Strings.emptyToNull(String.format(format, value)); <END> }</code><technical_language>if format string is non-empty String.format(..) empty, Strings.emptyToNull(..) is anything. want do instead? String.format(format, Strings.emptyToNull(value));</technical_language>

Target:
public String apply(String value) { return String.format(format, value); }
Source:
<code>public static TaskFactory finalizeTaskFactory(TaskFactory factory, ExecutorService taskThreadPool) { validateFactory(factory); boolean isAsyncTaskClass = factory instanceof AsyncStreamTaskFactory; if (isAsyncTaskClass) { log.info("Got an AsyncStreamTask implementation."); return factory; } boolean isStreamOperatorTaskClass = factory instanceof StreamOperatorTaskFactory; if (isStreamOperatorTaskClass) { <START> log.info("Adapting StreamOperatorTask to AsyncStreamTaskAdapter"); <END> return (AsyncStreamTaskFactory) () -> { StreamOperatorTask operatorTask = (StreamOperatorTask) factory.createInstance(); operatorTask.setTaskThreadPool(taskThreadPool); return operatorTask; }; } log.info("Converting StreamTask to AsyncStreamTaskAdapter"); return (AsyncStreamTaskFactory) () -> new AsyncStreamTaskAdapter(((StreamTaskFactory) factory).createInstance(), taskThreadPool); }</code><technical_language>Update log message (not adapting AsyncStreamTaskAdapter)</technical_language>

Target:
public static TaskFactory finalizeTaskFactory(TaskFactory factory, ExecutorService taskThreadPool) { validateFactory(factory); boolean isAsyncTaskClass = factory instanceof AsyncStreamTaskFactory; if (isAsyncTaskClass) { log.info("Got an AsyncStreamTask implementation."); return factory; } boolean isStreamOperatorTaskClass = factory instanceof StreamOperatorTaskFactory; if (isStreamOperatorTaskClass) { log.info("Adapting StreamOperatorTaskFactory to inject container thread pool"); return (AsyncStreamTaskFactory) () -> { StreamOperatorTask operatorTask = (StreamOperatorTask) factory.createInstance(); operatorTask.setTaskThreadPool(taskThreadPool); return operatorTask; }; } log.info("Converting StreamTask to AsyncStreamTaskAdapter"); return (AsyncStreamTaskFactory) () -> new AsyncStreamTaskAdapter(((StreamTaskFactory) factory).createInstance(), taskThreadPool); }
Source:
<code>public void addRelationMembers(PerunSession sess, Group resultGroup, List<Member> changedMembers, int sourceGroupId) throws InternalErrorException, AlreadyMemberException, WrongReferenceAttributeValueException, WrongAttributeValueException, GroupNotExistsException { List<Member> newMembers; try{ newMembers = addIndirectMembers(sess, resultGroup, changedMembers, sourceGroupId); if(newMembers.isEmpty()) { return; } List<Integer> relations = groupsManagerImpl.getResultGroupsIds(sess, resultGroup.getId()); for (Integer groupId : relations) { addRelationMembers(sess, groupsManagerImpl.getGroupById(sess, groupId), newMembers, resultGroup.getId()); } } catch (InternalErrorException | AlreadyMemberException | WrongReferenceAttributeValueException | WrongAttributeValueException | GroupNotExistsException ex) { <START> log.info("Can't add new member. Cause: {}", ex); <END> } }</code><technical_language>remove this catch exception thrown this method. this moment skipping exceptions all</technical_language>

Target:
public void addRelationMembers(PerunSession sess, Group resultGroup, List<Member> changedMembers, int sourceGroupId) throws InternalErrorException, AlreadyMemberException, WrongReferenceAttributeValueException, WrongAttributeValueException, GroupNotExistsException { List<Member> newMembers; newMembers = addIndirectMembers(sess, resultGroup, changedMembers, sourceGroupId); if(newMembers.isEmpty()) { return; } List<Integer> relations = groupsManagerImpl.getResultGroupsIds(sess, resultGroup.getId()); for (Integer groupId : relations) { addRelationMembers(sess, groupsManagerImpl.getGroupById(sess, groupId), newMembers, resultGroup.getId()); } }
Source:
<code>public boolean matchDestination(final String r) { <START> if (allowMismatchedWildcards && getDestination() == null) { return match(r, getSource()); } <END> return match(r, getDestination()); }</code><technical_language>This equally convenient !allowMismatchedWildcards, alas API change. I more consistent for caller responsible for handling this. (Or in a followup change a method sets destination src if unset, this more convenient.)</technical_language>

Target:
public boolean matchDestination(final String r) { return match(r, getDestination()); }
Source:
<code>public void testStatusBasedFilter() throws ParseException { DataStoreTransaction dtx = elide.getDataStore().beginTransaction(); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf828d"), dtx); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf827d"), dtx); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf826d"), dtx); AsyncQuery asyncQuery1 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf828d", 1577883600000L, QueryStatus.CANCEL_COMPLETE); AsyncQuery asyncQuery2 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf827d", 1577883600000L, QueryStatus.CANCELLED); AsyncQuery asyncQuery3 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf826d", 1577883600000L, QueryStatus.PROCESSING); Collection<AsyncQuery> asyncCollection = new ArrayList<AsyncQuery>(); asyncCollection.add(asyncQuery1); asyncCollection.add(asyncQuery2); asyncCollection.add(asyncQuery3); <START> when(cancelThread.getAsyncQueryDao().loadAsyncQueryCollection(any())).thenReturn(asyncCollection); <END> cancelThread.cancelAsyncQuery(); ArgumentCaptor<FilterExpression> fltStatusCaptor = ArgumentCaptor.forClass(FilterExpression.class); verify(asyncQueryDao, times(1)).loadAsyncQueryCollection(fltStatusCaptor.capture()); assertEquals("asyncQuery.status IN [[CANCELLED, PROCESSING, QUEUED]]", fltStatusCaptor.getValue().toString()); }</code><technical_language>verify updateStatus statement well</technical_language>

Target:
public void testStatusBasedFilter() throws ParseException { DataStoreTransaction dtx = elide.getDataStore().beginTransaction(); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf828d"), dtx); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf827d"), dtx); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf826d"), dtx); AsyncQuery asyncQuery1 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf828d", 1577883600000L, QueryStatus.CANCEL_COMPLETE); AsyncQuery asyncQuery2 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf827d", 1577883600000L, QueryStatus.CANCELLED); AsyncQuery asyncQuery3 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf826d", 1577883600000L, QueryStatus.PROCESSING); Collection<AsyncQuery> asyncCollection = new ArrayList<AsyncQuery>(); asyncCollection.add(asyncQuery1); asyncCollection.add(asyncQuery2); asyncCollection.add(asyncQuery3); when(cancelThread.getAsyncQueryDao().loadAsyncQueryCollection(any())).thenReturn(asyncCollection); cancelThread.cancelAsyncQuery(); ArgumentCaptor<FilterExpression> fltStatusCaptor = ArgumentCaptor.forClass(FilterExpression.class); verify(asyncQueryDao, times(1)).loadAsyncQueryCollection(fltStatusCaptor.capture()); assertEquals("asyncQuery.status IN [[CANCELLED, PROCESSING, QUEUED]]", fltStatusCaptor.getValue().toString()); verify(asyncQueryDao, times(1)).updateStatusAsyncQueryCollection(any(), any()); }
Source:
<code>public void destroyObject(PooledObject<CassandraClient> client) { try (CassandraClient cassandraClient = client.getObject()) { <START> cassandraClient.close(); <END> log.debug("Closed transport for client of host {}", UnsafeArg.of("client", client), SafeArg.of("cassandraClient", CassandraLogHelper.host(addr))); } }</code><technical_language>close() called here, explicitly due try block? remove try block simply call client.getObject().close() directly</technical_language>

Target:
public void destroyObject(PooledObject<CassandraClient> client) { client.getObject().close(); log.debug("Closed transport for client of host {}", UnsafeArg.of("client", client), SafeArg.of("cassandraClient", CassandraLogHelper.host(addr))); }
Source:
<code>public IndexManager(Datastore datastore) { this.datastore = datastore; validFieldName = Pattern.compile(INDEX_FIELD_NAME_PATTERN); queue = Executors.newSingleThreadExecutor(); final String filename = datastore.extensionDataFolder(EXTENSION_NAME) + File.separator + "indexes.sqlite"; SQLDatabase sqlDatabase = null; try { <START> sqlDatabase = queue.submit(new Callable<SQLDatabase>() { <END> @Override public SQLDatabase call() throws Exception { SQLDatabase db = SQLDatabaseFactory.openSqlDatabase(filename); String[] schemaIndex; if (db.getVersion() == 1) { schemaIndex = new String[] { "ALTER TABLE " + INDEX_METADATA_TABLE_NAME + " " + "ADD COLUMN index_settings TEXT NULL;" }; } else { schemaIndex = new String[] { "CREATE TABLE " + INDEX_METADATA_TABLE_NAME + " ( " + "index_name TEXT NOT NULL, " + "index_type TEXT NOT NULL, " + "index_settings TEXT NULL, " + "field_name TEXT NOT NULL, " + "last_sequence INTEGER NOT NULL);" }; } SQLDatabaseFactory.updateSchema(db, schemaIndex, VERSION); return db; } }).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Problem opening or creating database.", e); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Problem opening or creating database.", e); } database = sqlDatabase; }</code><technical_language>for this PR, done while refactoring this class. hold sqlDatabase, instead SQLDatabaseQueue interact database, @alfinkel do plans refactor parts of this class do need another ticket handle this</technical_language>

Target:
public IndexManager(Datastore datastore) { this.datastore = datastore; validFieldName = Pattern.compile(INDEX_FIELD_NAME_PATTERN); queue = Executors.newSingleThreadExecutor(); final String filename = datastore.extensionDataFolder(EXTENSION_NAME) + File.separator + "indexes.sqlite"; SQLDatabase sqlDatabase = null; try { sqlDatabase = queue.submit(new Callable<SQLDatabase>() { @Override public SQLDatabase call() throws Exception { SQLDatabase db = SQLDatabaseFactory.openSqlDatabase(filename); SQLDatabaseFactory.updateSchema(db, QueryConstants.getSchemaVersion1(), 1); SQLDatabaseFactory.updateSchema(db, QueryConstants.getSchemaVersion2(), 2); return db; } }).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Problem opening or creating database.", e); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Problem opening or creating database.", e); } database = sqlDatabase; }
Source:
<code><START> public T get() { <END> return getOr(defaultValue); }</code><technical_language>final</technical_language>

Target:
public final T get() { return getOr(defaultValue); }
Source:
<code>public void singleLockHashMap() throws InterruptedException { <START> (new SingleLock()).doWork(new HashMap<String,String>(), THREADS, SLOTS); <END> }</code><technical_language>I understand re-instantiated object time. play results? want do is reuse instantiated field level. way, benchmark is work done map cost of instantiating worker object</technical_language>

Target:
public Map<String,String> singleLockHashMap() throws InterruptedException { return singleLock.doWork(new HashMap<String,String>(), THREADS, SLOTS); }
Source:
<code>public String getBuildName() { <START> return properties.get("build.name"); <END> }</code><technical_language>I suggest *BuildInfoFields.BUILD_NAME* instead of "build.name"</technical_language>

Target:
public String getBuildName() { return properties.get(BuildInfoFields.BUILD_NAME); }
Source:
<code><START> public List<ObjectId> readMergeHeads() throws IOException { <END> List<ObjectId> heads = null; File mergeHeadFile = new File(gitDir, Constants.MERGE_HEAD); if (mergeHeadFile.exists()) { try { FileReader r = new FileReader(mergeHeadFile); BufferedReader mh = new BufferedReader(r); String headStr; try { heads = new LinkedList<ObjectId>(); while ((headStr = mh.readLine()) != null) { heads.add(ObjectId.fromString(headStr)); } } finally { r.close(); } } catch (FileNotFoundException e) { heads = null; } } return heads; }</code><technical_language>note ps2 empty MERGE_HEAD file a form of corruption. able shorten code a bit here: File mergeHeadFile = new File(gitDir, Constants.MERGE_HEAD); byte[] raw; try { raw = IO.readFully(mergeHeadFile); } catch (FileNotFoundException notFound) { return new LinkedList<ObjectId>(); } if (raw.length == 0) throw new IOException("MERGE_HEAD file empty: " + mergeHeadFile); LinkedList<ObjectId> heads = new LinkedList<ObjectId>(); for (int p = 0; p < raw.length; ) { heads.add(ObjectId.fromString(raw, p)); p = RawParseUtils.nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH); } return heads; Hmm, shorter (~5 lines?). behavior matches C git better. IIRC C git reads 40 characters line ignores rest of it. is nextLF</technical_language>

Target:
public List<ObjectId> readMergeHeads() throws IOException { File mergeHeadFile = new File(gitDir, Constants.MERGE_HEAD); byte[] raw; try { raw = IO.readFully(mergeHeadFile); } catch (FileNotFoundException notFound) { return new LinkedList<ObjectId>(); } if (raw.length == 0) throw new IOException("MERGE_HEAD file empty: " + mergeHeadFile); LinkedList<ObjectId> heads = new LinkedList<ObjectId>(); for (int p = 0; p < raw.length;) { heads.add(ObjectId.fromString(raw, p)); p = RawParseUtils .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH); } return heads; }
Source:
<code>public Statement apply(final Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { IntegrationTestUtils.reserveMasterPorts(); mTestName = IntegrationTestUtils .getTestName(description.getTestClass().getSimpleName(), description.getMethodName()); try { try { Annotation configAnnotation; configAnnotation = description.getAnnotation(ServerConfig.class); if (configAnnotation != null) { ServerConfig config = (ServerConfig) configAnnotation; for (int i = 0; i < config.confParams().length; i += 2) { mConfiguration.put(PropertyKey.fromString(config.confParams()[i]), config.confParams()[i + 1]); } <START> } <END> boolean startCluster = mStartCluster; configAnnotation = description.getAnnotation(Config.class); if (configAnnotation != null) { Config config = (Config) configAnnotation; for (int i = 0; i < config.confParams().length; i += 2) { mConfiguration.put(PropertyKey.fromString(config.confParams()[i]), config.confParams()[i + 1]); } startCluster = config.startCluster(); } if (startCluster) { start(); } } catch (Exception e) { throw new RuntimeException(e); } try { statement.evaluate(); } finally { mLocalAlluxioCluster.stop(); } } finally { IntegrationTestUtils.releaseMasterPorts(); } } }; }</code><technical_language>this share code block well..</technical_language>

Target:
public Statement apply(final Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { IntegrationTestUtils.reserveMasterPorts(); mTestName = IntegrationTestUtils .getTestName(description.getTestClass().getSimpleName(), description.getMethodName()); try { try { Annotation configAnnotation; configAnnotation = description.getAnnotation(ServerConfig.class); if (configAnnotation != null) { overrideConfiguration(((ServerConfig) configAnnotation).confParams()); } boolean startCluster = mStartCluster; configAnnotation = description.getAnnotation(Config.class); if (configAnnotation != null) { Config config = (Config) configAnnotation; overrideConfiguration(config.confParams()); startCluster = config.startCluster(); } if (startCluster) { start(); } } catch (Exception e) { throw new RuntimeException(e); } try { statement.evaluate(); } finally { mLocalAlluxioCluster.stop(); } } finally { IntegrationTestUtils.releaseMasterPorts(); } } }; }
Source:
<code><START> private static DataSize.Unit valueOfUnit(String unitString) <END> { for (DataSize.Unit unit : DataSize.Unit.values()) { if (unit.getUnitString().equals(unitString)) { return unit; } } throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unit string must be one of [B, kB, MB, GB, TB, PB]"); }</code><technical_language>static import DataSize.Unit</technical_language>

Target:
private static Unit valueOfUnit(String unitString) { for (Unit unit : Unit.values()) { if (unit.getUnitString().equals(unitString)) { return unit; } } throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unit string must be one of [B, kB, MB, GB, TB, PB]"); }
Source:
<code>public void onCreateTable(CreateTableEvent tableEvent) throws MetaException { Table t = tableEvent.getTable(); FileIterator fileIter = t.getTableType().equals(TableType.EXTERNAL_TABLE.toString()) <START> ? null : new FileIterator(t.getSd().getLocation()); <END> NotificationEvent event = new NotificationEvent(0, now(), EventType.CREATE_TABLE.toString(), msgFactory.buildCreateTableMessage(t, fileIter).toString()); event.setCatName(t.isSetCatName() ? t.getCatName() : DEFAULT_CATALOG_NAME); event.setDbName(t.getDbName()); event.setTableName(t.getTableName()); process(event, tableEvent); }</code><technical_language>if external table dump is enabled allow file listing do get file list dump</technical_language>

Target:
public void onCreateTable(CreateTableEvent tableEvent) throws MetaException { Table t = tableEvent.getTable(); FileIterator fileIter = MetaStoreUtils.isExternalTable(t) ? null : new FileIterator(t.getSd().getLocation()); NotificationEvent event = new NotificationEvent(0, now(), EventType.CREATE_TABLE.toString(), msgFactory.buildCreateTableMessage(t, fileIter).toString()); event.setCatName(t.isSetCatName() ? t.getCatName() : DEFAULT_CATALOG_NAME); event.setDbName(t.getDbName()); event.setTableName(t.getTableName()); process(event, tableEvent); }
Source:
<code>private void initializeGenerationFromDisk(HostMessenger messenger, final ExportDataProcessor processor, File[] files, List<Pair<Integer, Integer>> localPartitionsToSites) { List<Integer> onDiskPartitions = new ArrayList<Integer>(); Map<String, File> dataFiles = new HashMap<>(); for (File data: files) { if (data.getName().endsWith(".pbd")) { String nonce = data.getName().substring(0, data.getName().lastIndexOf('.')); nonce = nonce.substring(0, nonce.lastIndexOf('_')); nonce = nonce.substring(0, nonce.lastIndexOf('_')); <START> dataFiles.put(nonce, data); <END> } } for (File ad: files) { if (ad.getName().endsWith(".ad")) { String nonce = ad.getName().substring(0, ad.getName().lastIndexOf('.')); File dataFile = dataFiles.get(nonce); if (dataFile != null) { try { addDataSource(ad, localPartitionsToSites, onDiskPartitions, processor); } catch (IOException e) { VoltDB.crashLocalVoltDB("Error intializing export datasource " + ad, true, e); } } else { ad.delete(); } } } Set<Integer> allLocalPartitions = localPartitionsToSites.stream() .map(p -> p.getFirst()) .collect(Collectors.toSet()); Set<Integer> onDIskPartitionsSet = new HashSet<Integer>(onDiskPartitions); onDIskPartitionsSet.removeAll(allLocalPartitions); if (!onDIskPartitionsSet.isEmpty()) { createAckMailboxesIfNeeded(messenger, onDIskPartitionsSet); } }</code><technical_language>duplicated line. this format, nonce = data.getName().substring(0, data.getName().lastIndexOf('_')) return is needed</technical_language>

Target:
private void initializeGenerationFromDisk(HostMessenger messenger, final ExportDataProcessor processor, File[] files, List<Pair<Integer, Integer>> localPartitionsToSites) { List<Integer> onDiskPartitions = new ArrayList<Integer>(); Map<String, File> dataFiles = new HashMap<>(); for (File data: files) { if (data.getName().endsWith(".pbd")) { String nonce = data.getName().substring(0, data.getName().lastIndexOf('_')); nonce = nonce.substring(0, nonce.lastIndexOf('_')); dataFiles.put(nonce, data); } } for (File ad: files) { if (ad.getName().endsWith(".ad")) { String nonce = ad.getName().substring(0, ad.getName().lastIndexOf('.')); File dataFile = dataFiles.get(nonce); if (dataFile != null) { try { addDataSource(ad, localPartitionsToSites, onDiskPartitions, processor); } catch (IOException e) { VoltDB.crashLocalVoltDB("Error intializing export datasource " + ad, true, e); } } else { ad.delete(); } } } Set<Integer> allLocalPartitions = localPartitionsToSites.stream() .map(p -> p.getFirst()) .collect(Collectors.toSet()); Set<Integer> onDIskPartitionsSet = new HashSet<Integer>(onDiskPartitions); onDIskPartitionsSet.removeAll(allLocalPartitions); if (!onDIskPartitionsSet.isEmpty()) { createAckMailboxesIfNeeded(messenger, onDIskPartitionsSet); } }
Source:
<code>private String[] parseSegments(String key) { <START> return key.split("\\.", key.startsWith("attributes.") ? 2 : 0); <END> }</code><technical_language>key.replace("attributes.", "") WDYT? Is more readable</technical_language>

Target:
private String[] parseSegments(String key) { return key.startsWith("attributes.") ? key.split("\\.", 2) : key.split("\\."); }
Source:
<code>public int onStartCommand(Intent intent, int flags, int startId) { ArrayList<AbstractSuite> testSuites = (ArrayList<AbstractSuite>) intent.getSerializableExtra("testSuites"); if (testSuites == null || testSuites.size() == 0) return 0; Application app = ((Application)getApplication()); NotificationService.setChannel(getApplicationContext(), CHANNEL_ID, app.getString(R.string.Settings_AutomatedTesting_Label), false, false, false); Intent notificationIntent = new Intent(this, RunningActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notificationManager = NotificationManagerCompat.from(this); builder = new NotificationCompat.Builder(this, CHANNEL_ID); builder.setContentTitle(getApplication().getString(R.string.Dashboard_Running_Running)) .setContentText(getApplication().getString(R.string.Dashboard_Running_PreparingTest)) .setAutoCancel(false) .setSmallIcon(R.drawable.notification_icon) .setContentIntent(pendingIntent) .setProgress(100, 0, false) .build(); task = (TestAsyncTask) new TestAsyncTask(app, testSuites, this).execute(); Intent broadcastIntent = new Intent(); broadcastIntent.setAction(RunTestService.ACTION_INTERRUPT); PendingIntent pIntent = PendingIntent.getBroadcast(this,1, broadcastIntent,PendingIntent.FLAG_UPDATE_CURRENT); <START> builder.addAction(0, "STOP TEST", pIntent); <END> startForeground(NOTIFICATION_ID, builder.build()); return START_NOT_STICKY; }</code><technical_language>@lorenzoPrimi remember localise this string</technical_language>

Target:
public int onStartCommand(Intent intent, int flags, int startId) { ArrayList<AbstractSuite> testSuites = (ArrayList<AbstractSuite>) intent.getSerializableExtra("testSuites"); if (testSuites == null || testSuites.size() == 0) return 0; Application app = ((Application)getApplication()); NotificationService.setChannel(getApplicationContext(), CHANNEL_ID, app.getString(R.string.Settings_AutomatedTesting_Label), false, false, false); Intent notificationIntent = new Intent(this, RunningActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notificationManager = NotificationManagerCompat.from(this); builder = new NotificationCompat.Builder(this, CHANNEL_ID); builder.setContentTitle(getApplication().getString(R.string.Dashboard_Running_Running)) .setContentText(getApplication().getString(R.string.Dashboard_Running_PreparingTest)) .setAutoCancel(false) .setSmallIcon(R.drawable.notification_icon) .setContentIntent(pendingIntent) .setProgress(100, 0, false) .build(); task = (TestAsyncTask) new TestAsyncTask(app, testSuites, this).execute(); Intent broadcastIntent = new Intent(); broadcastIntent.setAction(RunTestService.ACTION_INTERRUPT); PendingIntent pIntent = PendingIntent.getBroadcast(this,1, broadcastIntent,PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(0, getApplicationContext().getString(R.string.Notification_StopTest), pIntent); startForeground(NOTIFICATION_ID, builder.build()); return START_NOT_STICKY; }
Source:
<code>public static PutAdapter createPutAdapter(BigtableHBaseSettings settings) { Configuration config = settings.getConfiguration(); <START> boolean setClientTimestamp = !config.getBoolean(ALLOW_NO_TIMESTAMP_RETRIES_KEY, false); <END> return new PutAdapter(config.getInt("hbase.client.keyvalue.maxsize", -1), setClientTimestamp); }</code><technical_language>a getter BigtableHBaseSettings for this</technical_language>

Target:
public static PutAdapter createPutAdapter(BigtableHBaseSettings settings) { Configuration config = settings.getConfiguration(); boolean setClientTimestamp = !settings.isRetriesWithoutTimestampAllowed(); return new PutAdapter(config.getInt("hbase.client.keyvalue.maxsize", -1), setClientTimestamp); }
Source:
<code>public String toString() { <START> return "PacBioNotificationDto [movieDurationInSec=" + movieDurationInSec + ", getRunName()=" + getRunAlias() + ", getSequencerName()=" <END> + getSequencerName() + ", getCompletionDate()=" + getCompletionDate() + ", getStartDate()=" + getStartDate() + ", getContainerId()=" + getContainerSerialNumber() + ", getLaneCount()=" + getLaneCount() + ", getHealthType()=" + getHealthType() + ", getSequencerFolderPath()=" + getSequencerFolderPath() + ", isPairedEndRun()=" + isPairedEndRun() + ", getSoftware()=" + getSoftware() + "]"; }</code><technical_language>labels</technical_language>

Target:
public String toString() { return "PacBioNotificationDto [movieDurationInSec=" + movieDurationInSec + ", getRunAlias()=" + getRunAlias() + ", getSequencerName()=" + getSequencerName() + ", getContainerSerialNumber()=" + getContainerSerialNumber() + ", getLaneCount()=" + getLaneCount() + ", getHealthType()=" + getHealthType() + ", getSequencerFolderPath()=" + getSequencerFolderPath() + ", isPairedEndRun()=" + isPairedEndRun() + ", getSoftware()=" + getSoftware() + ", getStartDate()=" + getStartDate() + ", getCompletionDate()=" + getCompletionDate() + "]"; }
Source:
<code>public void testValidDockerignore() throws Exception { <START> try (final GenericContainer container = new GenericContainer(new ImageFromDockerfile() <END> .withFileFromPath(".", DockerfileBuildTest.RESOURCE_PATH) .withDockerfile(new File("src/test/resources/dockerfile-build-test/Dockerfile-currentdir")) .get()) .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) .withCommand("ls", "/")) { container.start(); final String logs = container.getLogs(); assertTrue("Files in the container indicated the .dockerignore was not applied. Output was: " + logs, logs.contains("should_not_be_ignored.txt")); assertTrue("Files in the container indicated the .dockerignore was not applied. Output was: " + logs, !logs.contains("should_be_ignored.txt")); } }</code><technical_language>nit1: please extract image definition nit2: please add a line break try ( ) {? I a bit inconsistent, helps, especially long fluent-style chains</technical_language>

Target:
public void testValidDockerignore() throws Exception { ImageFromDockerfile img = new ImageFromDockerfile() .withFileFromPath(".", DockerfileBuildTest.RESOURCE_PATH) .withDockerfile(DockerfileBuildTest.RESOURCE_PATH.resolve("Dockerfile-currentdir")); try( final GenericContainer<?> container = new GenericContainer<>(img.get()) .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) .withCommand("ls", "/") ) { container.start(); final String logs = container.getLogs(); assertTrue("Files in the container indicated the .dockerignore was not applied. Output was: " + logs, logs.contains("should_not_be_ignored.txt")); assertTrue("Files in the container indicated the .dockerignore was not applied. Output was: " + logs, !logs.contains("should_be_ignored.txt")); } }
Source:
<code>private void findNegotiatingProfiles(ServletRequest req) { List<String> schemes = new ArrayList<String>(); if (profiles == null) { synchronized (this) { if (profiles == null) { schemes = new ArrayList<>(); <START> profiles = new ArrayList<AuthenticationProfile>(1); <END> for (AuthenticationProfile profile : AuthenticationProfileRepository.getInstance().getProfiles()) { if (profile != null) { ExtMap authnContext = profile.getAuthn().getContext(); if ((authnContext.<Long> get(Authn.ContextKeys.CAPABILITIES).longValue() & caps) != caps) { profiles.add(0, profile); } schemes.addAll(authnContext.<List<String>>get(Authn.ContextKeys.HTTP_AUTHENTICATION_SCHEME, Collections.<String>emptyList())); } } } } } ((HttpServletRequest) req).setAttribute(FiltersHelper.Constants.SCHEMES_KEY, schemes); }</code><technical_language>1</technical_language>

Target:
private void findNegotiatingProfiles(ServletRequest req) { List<String> schemes = new ArrayList<String>(); if (profiles == null) { synchronized (this) { if (profiles == null) { schemes = new ArrayList<>(); profiles = new ArrayList<AuthenticationProfile>(); for (AuthenticationProfile profile : AuthenticationProfileRepository.getInstance().getProfiles()) { if (profile != null) { ExtMap authnContext = profile.getAuthn().getContext(); if ((authnContext.<Long> get(Authn.ContextKeys.CAPABILITIES).longValue() & caps) != caps) { profiles.add(0, profile); } schemes.addAll(authnContext.<List<String>>get(Authn.ContextKeys.HTTP_AUTHENTICATION_SCHEME, Collections.<String>emptyList())); } } } } } ((HttpServletRequest) req).setAttribute(FiltersHelper.Constants.SCHEMES_KEY, schemes); }
Source:
<code><START> protected AsyncFileEntry getRootFile() { <END> return rootFile; }</code><technical_language>If this is visible for testing, package-private (no modifier) instead of protected? is meant overridden sub-classes</technical_language>

Target:
AsyncFileEntry getRootFile() { return rootFile; }
Source:
<code>public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type type) { Bind b = (Bind) annotation; String nameFromAnnotation = b == null ? Bind.NO_VALUE : b.value(); Optional<String> name = ParameterUtil.findParameterName(nameFromAnnotation, param); if (GenericTypes.getErasedType(type) == Consumer.class) { return (stmt, arg) -> { }; <START> } <END> return (stmt, arg) -> { stmt.bindByType(index, arg, type); name.ifPresent(n -> stmt.bindByType(n, arg, type)); }; }</code><technical_language>feel right put this feature in this class--the consumer a bound variable. Moreover, putting consumer behavior in this class relies BindFactory default binder if is annotation method parameter--but this overridden SqlObjects.setDefaultParameterCustomizerFactory(), Kotlin SQL Object plugin uses. this feature broken time Kotlin plugin installed. if hardcoded in CustomizingStatementHandler.eachParameterCustomizers(), scanning for explicit customizing annotations, falling default customizer: java if (parameter.getType() == Consumer.class) { if (method.getReturnType() != Void.TYPE) { throw new IllegalStateException( "SQL Object methods a Consumer parameter void return type."); } return Stream.empty(); }</technical_language>

Target:
public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type type) { Bind b = (Bind) annotation; String nameFromAnnotation = b == null ? Bind.NO_VALUE : b.value(); Optional<String> name = ParameterUtil.findParameterName(nameFromAnnotation, param); return (stmt, arg) -> { stmt.bindByType(index, arg, type); name.ifPresent(n -> stmt.bindByType(n, arg, type)); }; }
Source:
<code>public Integer getExpectedClusters(String experimentAccession) { Integer expectedClusters = null; IdfParserOutput idfParserOutput = idfParser.parse(experimentAccession); if (idfParserOutput.getExpectedClusters() != 0 && getAvailableClusters(experimentAccession).contains(idfParserOutput.getExpectedClusters())) { expectedClusters = idfParserOutput.getExpectedClusters(); } else { Optional<Integer> optimalClusterFromFile = dataFileHub.getSingleCellExperimentFiles(experimentAccession).clustersTsv.get().get() .skip(1) .filter(line -> line[0].equalsIgnoreCase("false")) .map(line -> Integer.parseInt(line[1])) .findFirst(); <START> <END> if(optimalClusterFromFile.isPresent()) { expectedClusters = optimalClusterFromFile.get(); } } return expectedClusters; }</code><technical_language>I return if, remember chain this: ... .findFirst() .orElse(expectedClusters)</technical_language>

Target:
public Optional<Integer> getExpectedClusters(String experimentAccession) { IdfParserOutput idfParserOutput = idfParser.parse(experimentAccession); if (idfParserOutput.getExpectedClusters() != 0 && getAvailableClusters(experimentAccession).contains(idfParserOutput.getExpectedClusters())) { return Optional.of(idfParserOutput.getExpectedClusters()); } else { return dataFileHub.getSingleCellExperimentFiles(experimentAccession).clustersTsv.get().get() .skip(1) .filter(line -> line[0].equalsIgnoreCase("true")) .map(line -> Integer.parseInt(line[1])) .findFirst(); } }
Source:
<code>public void findElementsByNamedPagedQueryFailedWithoutCountQuery() { createAndSaveSampleEntity(); createAndSaveSampleEntity(); <START> exceptionRule.expect(IllegalArgumentException.class); <END> exceptionRule.expectMessage("Must specify a count query to get pagination info."); Page<SampleEntityForNamedQuery> page = repository.findByPagedQueryWithoutCountQuery(SAMPLE_ENTITY_NAME, PageRequest.of(0,1)); }</code><technical_language>AssertJ's Assertions.assertThatIllegalArgumentException a callable (() -> repository.findByPagedQueryWithoutCountQuery(SAMPLE_ENTITY_NAME, PageRequest.of(0,1))) remove rule</technical_language>

Target:
public void findElementsByNamedPagedQueryFailedWithoutCountQuery() { createAndSaveSampleEntity(); createAndSaveSampleEntity(); assertThatIllegalArgumentException() .isThrownBy(() -> repository.findByPagedQueryWithoutCountQuery(SAMPLE_ENTITY_NAME, PageRequest.of(0,1))) .withMessage("Must specify a count query to get pagination info."); }
Source:
<code><START> public synchronized void removeDomain( final String domainId ) { <END> delegate.removeDomain( domainId ); purgeDomain( domainId ); removeDomainFromIDCache( domainId ); }</code><technical_language>definition, this class is session based ( SessionCachingMetadataDomainRepository ). However, this change is synchronizing entire MetadataRepository instance. removing a domain for user in session ends blocking another user in another session storing domain removing model. I understand this done this level. If is synchronization required somewhere, I suspect here. specifically in multi-threaded testing methods synchronized this solves</technical_language>

Target:
public void removeDomain( final String domainId ) { delegate.removeDomain( domainId ); purgeDomain( domainId ); removeDomainFromIDCache( domainId ); }
Source:
<code>protected void executeQueryCommand() { for (Map.Entry<Guid, DiskImage> entry : getParameters().getDiskImagesMap().entrySet()) { DiskImage ancestor = getDbFacade().getDiskImageDao().getAncestor(entry.getKey()); if (ancestor != null) { <START> entry.setValue(ancestor); <END> } } getQueryReturnValue().setReturnValue(getParameters().getDiskImagesMap()); }</code><technical_language>query modifies map passed a parameter? Depending query is called (from backend? frontend seiralization?) unintuitive behavior best, inconsistent behavior worst. get a Set<Guid> of IDs (like name suggests!) return a Map<Guid, Disk></technical_language>

Target:
protected void executeQueryCommand() { Map<Guid, DiskImage> imagesAncestors = new HashMap<>(); for (Guid id : getParameters().getIds()) { DiskImage ancestor = getDbFacade().getDiskImageDao().getAncestor( id, getUserID(), getParameters().isFiltered()); imagesAncestors.put(id, ancestor); } getQueryReturnValue().setReturnValue(imagesAncestors); }
Source:
<code>public <START> CPPASTLiteralExpression(int <END> kind, char[] value, char[] numericCompilerSuffixes) { fKind = kind; setValue(kind, value); setNumericCompilerSuffixes(numericCompilerSuffixes); }</code><technical_language>sense introduce ICPPNodeFactory.newLiteralExpression(int, String, , char[] numericCompilerSuffixes) method, in GNUCPPSourceParser, get rid of setNumericCompilerSuffixes method</technical_language>

Target:
public CPPASTLiteralExpression(int kind, char[] value, char[] numericCompilerSuffixes) { fKind = kind; setValue(kind, value); fNumericCompilerSuffixes = (numericCompilerSuffixes == null) ? CharArrayUtils.EMPTY : numericCompilerSuffixes; }
Source:
<code>private void runManagement() { while (true) { if (Thread.interrupted()) { return; } BlockManagementTask currentTask = null; try { if (mLoadTracker.loadDetected(BlockStoreLocation.anyTier())) { LOG.info("Load detected."); Thread.sleep(mLoadDetectionCoolDownMs); continue; } final BlockManagementTask nextTask = getNextTask(); if (nextTask == null) { LOG.info("No management task pending."); Thread.sleep(mIdleSleepMs); continue; } currentTask = nextTask; <START> mTaskExecutor.submit(() -> nextTask.run()).get(); <END> LOG.info("Management task finished: {}", currentTask.getClass().getSimpleName()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } catch (ExecutionException e) { LOG.error("Management task failed: {}. Error: {}", currentTask.getClass().getSimpleName(), e); } catch (Throwable t) { LOG.error("Unexpected error during block management: {}", t); } } LOG.info("Block management coordinator exited."); }</code><technical_language>Add TODO run multiple tasks in parallel</technical_language>

Target:
private void runManagement() { while (true) { if (Thread.interrupted()) { LOG.debug("Coordinator interrupted."); break; } BlockManagementTask currentTask; try { if (mBackoffStrategy == BackoffStrategy.ANY && mLoadTracker.loadDetected(BlockStoreLocation.anyTier())) { LOG.debug("Load detected. Sleeping {}ms.", mLoadDetectionCoolDownMs); Thread.sleep(mLoadDetectionCoolDownMs); continue; } final BlockManagementTask nextTask = getNextTask(); if (nextTask == null) { LOG.debug("No management task pending. Sleeping {}ms.", mLoadDetectionCoolDownMs); Thread.sleep(mLoadDetectionCoolDownMs); continue; } currentTask = nextTask; LOG.debug("Running task of type:{}", currentTask.getClass().getSimpleName()); try { currentTask.run(); } catch (Exception e) { LOG.error("Management task failed: {}. Error: {}", currentTask.getClass().getSimpleName(), e); } LOG.debug("Management task finished: {}", currentTask.getClass().getSimpleName()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } catch (Throwable t) { LOG.error("Unexpected error during block management: {}", t); } } LOG.debug("Block management coordinator exited."); }
Source:
<code>public EList<EObject> getCreatedObjects() { if (createdObjects == null) { InternalTransaction transaction = domain.getActiveTransaction().getRoot(); TransactionChangeDescription changeDescription = transaction.getChangeDescription(); if (changeDescription != null) { createdObjects = changeDescription.getObjectsToDetach(); } } <START> return createdObjects; <END> }</code><technical_language>prevent NPEs return createdObjects == null ? Collections.<EObject> emptySet() : createdObjects; }</technical_language>

Target:
public Collection<EObject> getCreatedObjects() { if (createdObjects == null) { InternalTransaction transaction = domain.getActiveTransaction().getRoot(); TransactionChangeDescription changeDescription = transaction.getChangeDescription(); if (changeDescription != null) { createdObjects = changeDescription.getObjectsToDetach(); } } return Objects.firstNonNull(createdObjects, Collections.<EObject> emptySet()); }
Source:
<code><START> public Docker(DockerServerEndpoint dockerHost, String dockerInstallation, String credentialsId, AbstractBuild build, Launcher launcher, TaskListener listener, boolean verbose, boolean privileged, boolean sudo, String protectedEnvironmentVariables) throws IOException, InterruptedException { <END> this.dockerHost = dockerHost; this.dockerExecutable = DockerTool.getExecutable(dockerInstallation, Computer.currentComputer().getNode(), listener, build.getEnvironment(listener)); this.registryEndpoint = new DockerRegistryEndpoint(null, credentialsId); this.launcher = launcher; this.listener = listener; this.build = build; this.verbose = verbose | debug; this.privileged = privileged; this.sudo = sudo; this.protectedEnvironmentVariables = new HashSet<String>(); if(protectedEnvironmentVariables != null) { for (final String variable : Arrays.asList(protectedEnvironmentVariables.split(","))) { this.protectedEnvironmentVariables.add(variable.trim()); } } }</code><technical_language>This change breaks binary compatibility of non-restricted constructor</technical_language>

Target:
public Docker(DockerServerEndpoint dockerHost, String dockerInstallation, String credentialsId, AbstractBuild build, Launcher launcher, TaskListener listener, boolean verbose, boolean privileged, boolean sudo, String protectedEnvironmentVariables) throws IOException, InterruptedException { this.dockerHost = dockerHost; this.dockerExecutable = DockerTool.getExecutable(dockerInstallation, Computer.currentComputer().getNode(), listener, build.getEnvironment(listener)); this.registryEndpoint = new DockerRegistryEndpoint(null, credentialsId); this.launcher = launcher; this.listener = listener; this.build = build; this.verbose = verbose | debug; this.privileged = privileged; this.sudo = sudo; this.protectedEnvironmentVariables = new HashSet<String>(); if(protectedEnvironmentVariables != null) { for (final String variable : Arrays.asList(protectedEnvironmentVariables.split(","))) { final String trimmedVariable = variable.trim(); if (trimmedVariable.isEmpty()) { continue; } this.protectedEnvironmentVariables.add(trimmedVariable); } } }
Source:
<code>protected abstract boolean isRuntimeSystemPropertyUpdateAllowed(String propertyName, String propertyValue, boolean bootTime) throws OperationFailedException; protected abstract void systemPropertyUpdated(String propertyName, String propertyValue); public abstract UUID getInstanceUuid(); protected UUID createProcessUUID(final Path filePath) throws IOException { UUID uuid = null; if (Files.exists(filePath)) { <START> String line = Files.lines(filePath).findFirst().get(); <END> uuid = UUID.fromString(line); } if (uuid == null) { uuid = UUID.randomUUID(); Files.createDirectories(filePath.getParent()); Files.write(filePath, Collections.singletonList(uuid.toString()), StandardOpenOption.CREATE); } return uuid; }</code><technical_language>This done in a try-with-resources block ensure stream is closed</technical_language>

Target:
protected abstract boolean isRuntimeSystemPropertyUpdateAllowed(String propertyName, String propertyValue, boolean bootTime) throws OperationFailedException; protected abstract void systemPropertyUpdated(String propertyName, String propertyValue); public abstract UUID getInstanceUuid(); protected UUID obtainProcessUUID(final Path filePath) throws IOException { UUID uuid = null; if (Files.exists(filePath)) { try (Stream<String> lines = Files.lines(filePath)) { uuid = UUID.fromString(lines.findFirst().get()); } } if (uuid == null) { uuid = UUID.randomUUID(); Files.createDirectories(filePath.getParent()); Files.write(filePath, Collections.singletonList(uuid.toString()), StandardOpenOption.CREATE); } return uuid; }
Source:
<code>beginRecognizeCustomFormsFromUrl(String fileSourceUrl, String modelId, boolean includeTextDetails, Duration pollInterval) { Objects.requireNonNull(fileSourceUrl, "'fileSourceUrl' is required and cannot be null."); Objects.requireNonNull(modelId, "'modelId' is required and cannot be null."); <START> final Duration interval = pollInterval != null ? pollInterval : Duration.ofSeconds(5); <END> return new PollerFlux<OperationResult, IterableStream<RecognizedForm>>( interval, analyzeFormActivationOperation(fileSourceUrl, modelId, includeTextDetails), createAnalyzeFormPollOperation(modelId), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchAnalyzeFormResultOperation(modelId, includeTextDetails)); }</code><technical_language>duration a constant. So, if change later, change in place instead of updating APIs</technical_language>

Target:
beginRecognizeCustomFormsFromUrl(String fileSourceUrl, String modelId, boolean includeTextDetails, Duration pollInterval) { final Duration interval = pollInterval != null ? pollInterval : DEFAULT_DURATION; return new PollerFlux<OperationResult, IterableStream<RecognizedForm>>( interval, analyzeFormActivationOperation(fileSourceUrl, modelId, includeTextDetails), createAnalyzeFormPollOperation(modelId), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchAnalyzeFormResultOperation(modelId, includeTextDetails)); }
Source:
<code>private void writeConfigFileHeader(HttpServletResponse response) throws IOException { <START> BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream())); <END> writer.write(CONFIG_FILE_HEADER); writer.newLine(); writer.flush(); }</code><technical_language>Try "response.getWriter()"</technical_language>

Target:
private void writeConfigFileHeader(HttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); writer.println(CONFIG_FILE_HEADER); if (writer.checkError()) { throw new IOException("Error when writing to response stream"); } writer.flush(); }