auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); if (null == mDisplayState) { cleanUp(); } else { mInAppView = inflater.inflate(R.layout.com_mixpanel_android_activity_notification_mini, container, false); final TextView bodyTextView = (TextView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_title); final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image); MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification(); bodyTextView.setText(inApp.getBody()); bodyTextView.setTextColor(inApp.getBorderColor()); notifImage.setImageBitmap(inApp.getImage()); mHandler.postDelayed(mRemover, MINI_REMOVE_TIME); GradientDrawable viewBackground = new GradientDrawable(); viewBackground.setColor(inApp.getBackgroundColor()); viewBackground.setCornerRadius(6); viewBackground.setStroke(2, inApp.getBorderColor()); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mInAppView.setBackgroundDrawable(viewBackground); } else { mInAppView.setBackground(viewBackground); } Drawable myIcon = new BitmapDrawable(getResources(), mDisplayState.getInAppNotification().getImage()); <START> final int newColor = inApp.getImageTintColor(); <END> myIcon.setColorFilter(newColor, PorterDuff.Mode.SRC_ATOP); notifImage.setImageDrawable(myIcon); } return mInAppView; }</code><technical_language>out of curiosity, is final</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); if (null == mDisplayState) { cleanUp(); } else { mInAppView = inflater.inflate(R.layout.com_mixpanel_android_activity_notification_mini, container, false); final TextView bodyTextView = (TextView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_title); final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image); MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification(); bodyTextView.setText(inApp.getBody()); bodyTextView.setTextColor(inApp.getBodyColor()); notifImage.setImageBitmap(inApp.getImage()); mHandler.postDelayed(mRemover, MINI_REMOVE_TIME); GradientDrawable viewBackground = new GradientDrawable(); viewBackground.setColor(inApp.getBackgroundColor()); viewBackground.setCornerRadius(6); viewBackground.setStroke(2, inApp.getBorderColor()); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mInAppView.setBackgroundDrawable(viewBackground); } else { mInAppView.setBackground(viewBackground); } Drawable myIcon = new BitmapDrawable(getResources(), mDisplayState.getInAppNotification().getImage()); myIcon.setColorFilter(inApp.getImageTintColor(), PorterDuff.Mode.SRC_ATOP); notifImage.setImageDrawable(myIcon); } return mInAppView; }
Source:
<code>private ResourceSet createResourceSet() { final ResourceSet resourceSet = new ResourceSetImpl(); getSets().add(resourceSet); <START> if (!EMFPlugin.IS_ECLIPSE_RUNNING) { <END> UMLResourcesUtil.init(resourceSet); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("uml", new UMLResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("notation", new GMFResourceFactory()); EPackage.Registry.INSTANCE.put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE); EPackage.Registry.INSTANCE.put(NotationPackage.eNS_URI, NotationPackage.eINSTANCE); final URL UMLJarredFileLocation = ResourcesPlugin.class.getResource("ResourcesPlugin.class"); String UMLJarPath = UMLJarredFileLocation.toString(); UMLJarPath = UMLJarPath.substring(0, UMLJarPath.indexOf('!')); final Map<URI, URI> uriMap = URIConverter.URI_MAP; uriMap.put(URI.createURI(UMLResource.LIBRARIES_PATHMAP), URI.createURI(UMLJarPath + "!/libraries/")); uriMap.put(URI.createURI(UMLResource.METAMODELS_PATHMAP), URI.createURI(UMLJarPath + "!/metamodels/")); uriMap.put(URI.createURI(UMLResource.PROFILES_PATHMAP), URI.createURI(UMLJarPath + "!/profiles/")); } return resourceSet; }</code><technical_language>usage of utility methods in common umlrt.uml plugin: org.eclipse.papyrusrt.umlrt.uml.util.UMLRTResourcesUtil? contains static methods for this kind of purpose</technical_language>

Target:
private ResourceSet createResourceSet() { final ResourceSet resourceSet = new ResourceSetImpl(); getSets().add(resourceSet); if (!EMFPlugin.IS_ECLIPSE_RUNNING) { UMLRTResourcesUtil.init(resourceSet); } return resourceSet; }
Source:
<code>private boolean pmwBankAccountTypeIsDefinedInKfs(String pmwBankAccountTypeToVerify) { List<PaymentWorksBankAccountType> matchingValues = getPaymentWorksBatchUtilityService().findAllPmwBankAccountTypesMaching(pmwBankAccountTypeToVerify); <START> return matchingValues.size() == 1 ? true : false; <END> }</code><technical_language>"? true : false" suffix is redundant boolean expression's result result want. Also, do expect more account type match account type code? If not, referenced method simplified accordingly</technical_language>

Target:
private boolean pmwBankAccountTypeIsDefinedInKfs(String pmwBankAccountTypeToVerify) { List<PaymentWorksBankAccountType> matchingValues = getPaymentWorksBatchUtilityService().findAllPmwBankAccountTypesMatching(pmwBankAccountTypeToVerify); return (matchingValues.size() == 1); }
Source:
<code>public void firstNumberCanBeGiven() throws Exception { final BigInteger initialCounterValue = new BigInteger("5001"); <START> final CustomObjectBigIntegerNumberGeneratorConfigBuilder configBuilder = CustomObjectBigIntegerNumberGeneratorConfigBuilder.of(client(), randomKey()); <END> configBuilder.container(randomKey()); configBuilder.initialValue(initialCounterValue); final CustomObjectBigIntegerNumberGeneratorConfig config = configBuilder.build(); final BigIntegerNumberGenerator generator = CustomObjectBigIntegerNumberGenerator.of(config); final BigInteger firstNumber = generator.getNextNumber().toCompletableFuture().join(); assertThat(firstNumber).isEqualTo(initialCounterValue); }</code><technical_language>a fluent style here: final CustomObjectBigIntegerNumberGeneratorConfig config = CustomObjectBigIntegerNumberGeneratorConfigBuilder.of(client(), key) .container(randomKey()) .initialValue(initialCounterValue) .build();</technical_language>

Target:
public void firstNumberCanBeGiven() throws Exception { final BigInteger initialCounterValue = new BigInteger("5001"); final CustomObjectBigIntegerNumberGeneratorConfig config = CustomObjectBigIntegerNumberGeneratorConfigBuilder.of(client(), randomKey()) .container(randomKey()) .initialValue(initialCounterValue) .build(); final BigIntegerNumberGenerator generator = CustomObjectBigIntegerNumberGenerator.of(config); final BigInteger firstNumber = generator.getNextNumber().toCompletableFuture().join(); assertThat(firstNumber).isEqualTo(initialCounterValue); }
Source:
<code>public void serialize(PathDetail value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartArray(); gen.writeNumber(value.getFirst()); gen.writeNumber(value.getLast()); if (value.getValue() instanceof Double) gen.writeNumber((Double) value.getValue()); else if (value.getValue() instanceof Long) gen.writeNumber((Long) value.getValue()); else if (value.getValue() instanceof Integer) gen.writeNumber((Integer) value.getValue()); else if (value.getValue() instanceof Integer) <START> gen.writeNumber((Integer) value.getValue()); <END> else if (value.getValue() instanceof Boolean) gen.writeBoolean((Boolean) value.getValue()); else if (value.getValue() instanceof String) gen.writeString((String) value.getValue()); else throw new JsonGenerationException("Unsupported type for PathDetail.value" + value.getValue().getClass(), gen); gen.writeEndArray(); }</code><technical_language>I this is duplicated</technical_language>

Target:
public void serialize(PathDetail value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartArray(); gen.writeNumber(value.getFirst()); gen.writeNumber(value.getLast()); if (value.getValue() instanceof Double) gen.writeNumber((Double) value.getValue()); else if (value.getValue() instanceof Long) gen.writeNumber((Long) value.getValue()); else if (value.getValue() instanceof Integer) gen.writeNumber((Integer) value.getValue()); else if (value.getValue() instanceof Boolean) gen.writeBoolean((Boolean) value.getValue()); else if (value.getValue() instanceof String) gen.writeString((String) value.getValue()); else throw new JsonGenerationException("Unsupported type for PathDetail.value" + value.getValue().getClass(), gen); gen.writeEndArray(); }
Source:
<code>public void setUp() { <START> System.setProperty("user.timezone", "UTC"); <END> TimeZone.setDefault(null); configuration = Configuration.DEFAULT; }</code><technical_language>failures do this test</technical_language>

Target:
public void setUp() { configuration = Configuration.DEFAULT; }
Source:
<code>private static OutputFormat<BaseRow> createBulkWriterOutputFormat( BulkWriter.Factory<BaseRow> factory, Path path) { return new OutputFormat<BaseRow>() { private BulkWriter<BaseRow> writer; @Override public void configure(Configuration parameters) { } @Override public void open(int taskNumber, int numTasks) throws IOException { this.writer = factory.create(path.getFileSystem() .create(path, FileSystem.WriteMode.OVERWRITE)); } @Override <START> public void writeRecord(BaseRow record) throws IOException { <END> writer.addElement(record); } @Override public void close() throws IOException { writer.flush(); writer.finish(); } }; }</code><technical_language>Add a serialVersionUID</technical_language>

Target:
private static OutputFormat<BaseRow> createBulkWriterOutputFormat( BulkWriter.Factory<BaseRow> factory, Path path) { return new OutputFormat<BaseRow>() { private static final long serialVersionUID = 1L; private transient BulkWriter<BaseRow> writer; @Override public void configure(Configuration parameters) { } @Override public void open(int taskNumber, int numTasks) throws IOException { this.writer = factory.create(path.getFileSystem() .create(path, FileSystem.WriteMode.OVERWRITE)); } @Override public void writeRecord(BaseRow record) throws IOException { writer.addElement(record); } @Override public void close() throws IOException { writer.flush(); writer.finish(); } }; }
Source:
<code>private boolean validateProxy() { if (!hasProxy()) { return true; } final String host = mProxyHost.getText().toString().trim(); final String port = mProxyPort.getText().toString().trim(); return <START> ProxySelector.validate(host, port, "") == 0; <END> }</code><technical_language>import android.net.Proxy; Proxy.validate(host, port, "") == Proxy.PROXY_VALID; ...simply ProxySelector.validate returns a resource ID is a UI concept. different, really</technical_language>

Target:
private boolean validateProxy() { if (!hasProxy()) { return true; } final String host = mProxyHost.getText().toString().trim(); final String port = mProxyPort.getText().toString().trim(); return Proxy.validate(host, port, "") == Proxy.PROXY_VALID; }
Source:
<code>protected boolean validate() { if (!super.validate() || !checkStorageDomain()) { return false; } oldDomain = storageDomainStaticDao.get(getStorageDomain().getId()); getStorageDomain().setLastTimeUsedAsMaster(oldDomain.getLastTimeUsedAsMaster()); <START> return validateMasterDomainCannotBeBackup() && validateStoragePropertiesUpdate(); <END> }</code><technical_language>I a proper place put this line 63 part of validateStoragePropertiesUpdate. validate method clean</technical_language>

Target:
protected boolean validate() { if (!super.validate() || !checkStorageDomain()) { return false; } oldDomain = storageDomainStaticDao.get(getStorageDomain().getId()); getStorageDomain().setLastTimeUsedAsMaster(oldDomain.getLastTimeUsedAsMaster()); return validateStoragePropertiesUpdate(); }
Source:
<code>public void disconnect() { <START> Object lock = partitions != null ? partitions : new Object(); synchronized (lock) { <END> document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } }</code><technical_language>code is wrong. shoulkd lock objects null, check is reliable (it wrong null check), locking a new Object() sense - lock *anything*, current thread local object instance</technical_language>

Target:
public void disconnect() { synchronized (partitions) { document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } }
Source:
<code>private void prepareOpenShiftPVCs(OpenShiftEnvironment osEnv, String namespace) throws InfrastructureException { try (OpenShiftClient client = clientFactory.create()) { final Map<String, PersistentVolumeClaim> existing = new HashMap<>(); client.persistentVolumeClaims() .inNamespace(namespace) .list() .getItems() <START> .forEach(p -> existing.put(p.getMetadata().getName(), p)); <END> final Map<String, PersistentVolumeClaim> toCreate = Maps.difference(osEnv.getPersistentVolumeClaims(), existing).entriesOnlyOnLeft(); for (PersistentVolumeClaim pvc : toCreate.values()) { client.persistentVolumeClaims().inNamespace(namespace).create(pvc); } } catch (KubernetesClientException ex) { throw new InfrastructureException(ex.getMessage(), ex); } }</code><technical_language>Collectors.toMap helped</technical_language>

Target:
private void prepareOpenShiftPVCs(OpenShiftEnvironment osEnv, String namespace) throws InfrastructureException { try (OpenShiftClient client = clientFactory.create()) { final Set<String> existing = client.persistentVolumeClaims() .inNamespace(namespace) .list() .getItems() .stream() .map(p -> p.getMetadata().getName()) .collect(toSet()); osEnv.getPersistentVolumeClaims() .entrySet() .stream() .filter(e -> !existing.contains(e.getKey())) .map(Map.Entry::getValue) .forEach(e -> client.persistentVolumeClaims().inNamespace(namespace).create(e)); } catch (KubernetesClientException ex) { throw new InfrastructureException(ex.getMessage(), ex); } }
Source:
<code>public ActionButton(EEFWidgetAction action, Composite parent, EEFWidgetFactory widgetFactory, IInterpreter interpreter, IVariableManager variableManager) { this.action = action; this.button = widgetFactory.createButton(parent, "", SWT.NONE); String expression = action.getLabelExpression(); EAttribute eAttribute = EefPackage.Literals.EEF_WIDGET_ACTION__LABEL_EXPRESSION; String buttonLabel = new Eval(interpreter, variableManager).get(eAttribute, expression, String.class); <START> button.setText(buttonLabel); <END> }</code><technical_language>button need a minimum width</technical_language>

Target:
public ActionButton(EEFWidgetAction action, Composite parent, EEFWidgetFactory widgetFactory, IInterpreter interpreter, IVariableManager variableManager) { this.action = action; this.button = widgetFactory.createButton(parent, "", SWT.NONE); String expression = action.getLabelExpression(); EAttribute eAttribute = EefPackage.Literals.EEF_WIDGET_ACTION__LABEL_EXPRESSION; String buttonLabel = Objects.firstNonNull(new Eval(interpreter, variableManager).get(eAttribute, expression, String.class), "..."); button.setText(buttonLabel); }
Source:
<code>protected void onPostResume() { super.onPostResume(); if (map != null) map.clear(); getMapPreferences(); <START> getCurrentAssignment(); <END> }</code><technical_language>Is call this in main thread</technical_language>

Target:
protected void onPostResume() { super.onPostResume(); Log.i(TAG, "Resuming"); if (map != null) map.clear(); getMapPreferences(); getCurrentAssignment(); setUpMap(); }
Source:
<code>public static void tearDown() throws IOException, OperationException, TimeoutException, InterruptedException { operations.removeIfExists(FILE_HANDLER_ADDRESS); <START> administration.reloadIfRequired(); <END> operations.removeIfExists(FILE_HANDLER_TB_REMOVED_ADDRESS); administration.reloadIfRequired(); }</code><technical_language>consecutive reloads necessary reload end sufficient</technical_language>

Target:
public static void tearDown() throws IOException, OperationException, TimeoutException, InterruptedException { operations.removeIfExists(FILE_HANDLER_ADDRESS); operations.removeIfExists(FILE_HANDLER_TB_REMOVED_ADDRESS); administration.reloadIfRequired(); }
Source:
<code>public int compareTo(DocumentWriteOperation o) { if(o == null) throw new NullPointerException("DocumentWriteOperation cannot be null"); <START> if(this.getUri() instanceof String && o.getUri() instanceof String) <END> return getUri().compareTo(o.getUri()); if(this.getUri() == null && o.getUri() instanceof String) return -1; if(this.getUri() instanceof String && o.getUri()==null) return 1; if(this.getUri() == null && o.getUri() == null) super.hashCode(); return 0; }</code><technical_language>instanceof implies a specific subtype instead of null is checked. != null easier understand relative == null tests</technical_language>

Target:
public int compareTo(DocumentWriteOperation o) { if(o == null) throw new NullPointerException("DocumentWriteOperation cannot be null"); if(this.getUri() != null && o.getUri() != null) return getUri().compareTo(o.getUri()); if(this.getUri() == null && o.getUri() != null) return -1; if(this.getUri() != null && o.getUri()==null) return 1; if(this.getUri() == null && o.getUri() == null) { if(this.hashCode() > o.hashCode()) return 1; else if (this.hashCode() < o.hashCode()) return -1; return 0; } return 0; }
Source:
<code>public void removeCache(final String alias) { statusTransitioner.checkAvailable(); <START> MDC.put("alias", alias); <END> final CacheHolder cacheHolder = caches.remove(alias); if(cacheHolder != null) { final Ehcache<?, ?> ehcache = cacheHolder.retrieve(cacheHolder.keyType, cacheHolder.valueType); if(!statusTransitioner.isTransitioning()) { for (CacheManagerListener listener : listeners) { listener.cacheRemoved(alias, ehcache); } } closeEhcache(alias, ehcache); LOGGER.info("Cache '{}' is removed from EhcacheManager.", alias); } MDC.remove("alias"); }</code><technical_language>ehcache user of MDC, "alias" is a generic term. I this prefixed avoid potential name clashes</technical_language>

Target:
public void removeCache(final String alias) { statusTransitioner.checkAvailable(); final CacheHolder cacheHolder = caches.remove(alias); if(cacheHolder != null) { final Ehcache<?, ?> ehcache = cacheHolder.retrieve(cacheHolder.keyType, cacheHolder.valueType); if(!statusTransitioner.isTransitioning()) { for (CacheManagerListener listener : listeners) { listener.cacheRemoved(alias, ehcache); } } closeEhcache(alias, ehcache, cacheHolder.toBeReleased); LOGGER.info("Cache '{}' is removed from EhcacheManager.", alias); } }
Source:
<code>private void fileChangedWatchService(File file) { while (file.isFile()) { file = file.getParentFile(); } try { if (watcher != null) { watcher.close(); } watcher = FileSystems.getDefault().newWatchService(); final Path path = FileSystems.getDefault().getPath(file.getAbsolutePath()); path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); new Thread(() -> { try { WatchKey key = watcher.take(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { final Path changedPath = (Path) event.context(); Display.getDefault().asyncExec(() -> { if (browser.getUrl().endsWith(changedPath.toString())) { browser.refresh(); } }); } key.reset(); key = watcher.take(); } } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } catch (ClosedWatchServiceException e) { } }).start(); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>print stack trace useless if printed ignore too</technical_language>

Target:
private void fileChangedWatchService(File file) { while (file.isFile()) { file = file.getParentFile(); } try { if (watcher != null) { watcher.close(); } watcher = FileSystems.getDefault().newWatchService(); final Path path = FileSystems.getDefault().getPath(file.getAbsolutePath()); path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); new Thread(() -> { try { WatchKey key = watcher.take(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { final Path changedPath = (Path) event.context(); Display.getDefault().asyncExec(() -> { if (browser.getUrl().endsWith(changedPath.toString())) { browser.refresh(); } }); } key.reset(); key = watcher.take(); } } catch (InterruptedException | ClosedWatchServiceException e) { } }).start(); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>public void testMatch() { H2ResourceGroupsDao dao = setup("db-exact-match-selector"); <START> dao.createExactMatchSelectorsTable(); <END> ResourceGroupId resourceGroupId = new ResourceGroupId(ImmutableList.of("global", "test", "user")); JsonCodec<ResourceGroupId> codec = JsonCodec.jsonCodec(ResourceGroupId.class); dao.insertExactMatchSelector("test", "@test@test_pipeline", codec.toJson(resourceGroupId)); DbSourceExactMatchSelector selector = new DbSourceExactMatchSelector("test", dao); assertEquals( selector.match(new SelectionContext(true, "testuser", Optional.of("@test@test_pipeline"), ImmutableSet.of("tag"), 1, Optional.empty())), Optional.of(resourceGroupId)); assertEquals( selector.match(new SelectionContext(true, "testuser", Optional.of("@test@test_new"), ImmutableSet.of(), 1, Optional.empty())), Optional.empty()); }</code><technical_language>lines moved new setup method above</technical_language>

Target:
public void testMatch() { ResourceGroupId resourceGroupId = new ResourceGroupId(ImmutableList.of("global", "test", "user")); dao.insertExactMatchSelector("test", "@test@test_pipeline", CODEC.toJson(resourceGroupId)); DbSourceExactMatchSelector selector = new DbSourceExactMatchSelector("test", dao); assertEquals( selector.match(new SelectionContext(true, "testuser", Optional.of("@test@test_pipeline"), ImmutableSet.of("tag"), 1, Optional.empty())), Optional.of(resourceGroupId)); assertEquals( selector.match(new SelectionContext(true, "testuser", Optional.of("@test@test_new"), ImmutableSet.of(), 1, Optional.empty())), Optional.empty()); }
Source:
<code><START> private static List<CassandraRawCellValue> keySlicesToCells(List<KeySlice> slices) { <END> List<CassandraRawCellValue> ret = new ArrayList<>(); for (KeySlice slice : slices) { for (ColumnOrSuperColumn col : slice.getColumns()) { ret.add(new CassandraRawCellValue(slice.getKey(), col.getColumn())); } } return ret; }</code><technical_language>rewrite this a pair of streams, I prefer way. (if is curious how, I internal gist)</technical_language>

Target:
private static List<CassandraRawCellValue> keySlicesToCells(List<KeySlice> slices) { List<CassandraRawCellValue> ret = new ArrayList<>(); for (KeySlice slice : slices) { for (ColumnOrSuperColumn col : slice.getColumns()) { ret.add(ImmutableCassandraRawCellValue.builder() .rowKey(slice.getKey()) .column(col.getColumn()) .build()); } } return ret; }
Source:
<code>private void iterate(Object key, ReadWriteMap<Object, Integer> rw, int expectedValue) throws InterruptedException { rw.eval(key, (Function<ReadWriteEntryView<Object, Integer>, Void> & Serializable) entry -> { try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return entry.set(entry.find().orElse(0) + 1); }).join(); <START> Thread.sleep(100); END> Assert.assertEquals( (Object) cacheManagers.stream() .map(cm -> cm.<Object, Integer> getCache(DIST).getAdvancedCache()) .filter(cache -> cache.getDistributionManager().getLocality(key).isLocal()) .map(cache -> cache.getDataContainer().get(key).getValue()) .collect(Collectors.toList()), Collections.nCopies(numDistOwners, expectedValue)); }</code><technical_language>Minor thing, TestingUtil.sleepThread() sleeps throw InterruptedException</technical_language>

Target:
private void iterate(Object key, ReadWriteMap<Object, Integer> rw, int expectedValue) throws InterruptedException { rw.eval(key, (Function<ReadWriteEntryView<Object, Integer>, Void> & Serializable) entry -> { TestingUtil.sleepThread(10); return entry.set(entry.find().orElse(0) + 1); }).join(); Thread.sleep(100); Assert.assertEquals( (Object) cacheManagers.stream() .map(cm -> cm.<Object, Integer> getCache(DIST).getAdvancedCache()) .filter(cache -> cache.getDistributionManager().getLocality(key).isLocal()) .map(cache -> cache.getDataContainer().get(key).getValue()) .collect(Collectors.toList()), Collections.nCopies(numDistOwners, expectedValue)); }
Source:
<code>public void testDRepresentationElementUpdate() { <START> final IEditorPart editor = DialectUIManager.INSTANCE.openEditor(session, diagram, new NullProgressMonitor()); TestsUtil.synchronizationWithUIThread(); final EPackage ePackage = (EPackage) semanticModel; final EClass eClass = createEClass(ePackage); final Layer layer = diagram.getDescription().getDefaultLayer(); ContainerMapping classMapping = getContainerMapping(layer, "EC EClass"); <END> String changeIdBeforeModification = SiriusHelper.getChangeId(diagram); RecordingCommand cmd = new CreateDDiagramElementCommand(session.getTransactionalEditingDomain(), eClass, classMapping, diagram); session.getTransactionalEditingDomain().getCommandStack().execute(cmd); String changeIdAfterModification = SiriusHelper.getChangeId(diagram); assertNotEquals("Change id has not been updated.", changeIdBeforeModification, changeIdAfterModification); DialectUIManager.INSTANCE.closeEditor(editor, false); TestsUtil.synchronizationWithUIThread(); }</code><technical_language>mutualize this code for tests</technical_language>

Target:
public void testDRepresentationElementUpdate() { final IEditorPart editor = DialectUIManager.INSTANCE.openEditor(session, diagram, new NullProgressMonitor()); TestsUtil.synchronizationWithUIThread(); final EPackage ePackage = (EPackage) semanticModel; final EClass eClass = createEClass(ePackage); final Layer layer = diagram.getDescription().getDefaultLayer(); ContainerMapping classMapping = getContainerMapping(layer, "EC EClass"); String changeIdBeforeModification = new DRepresentationQuery(diagram).getRepresentationDescriptor().getChangeId(); RecordingCommand cmd = new CreateDDiagramElementCommand(session.getTransactionalEditingDomain(), eClass, classMapping, diagram); session.getTransactionalEditingDomain().getCommandStack().execute(cmd); String changeIdAfterModification = new DRepresentationQuery(diagram).getRepresentationDescriptor().getChangeId(); assertNotEquals("Change id has not been updated.", changeIdBeforeModification, changeIdAfterModification); DialectUIManager.INSTANCE.closeEditor(editor, false); TestsUtil.synchronizationWithUIThread(); }
Source:
<code>private static int computeChecksumIndex(String contents, int maxWeight) { int weight = 1; int total = 0; for (int i = contents.length()-1; i >= 0; i--) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); total += indexInString * weight; if (++weight > maxWeight) { weight = 1; } } <START> int checksum = total % 47; <END> return checksum; }</code><technical_language>trivial thing, return this directly</technical_language>

Target:
private static int computeChecksumIndex(String contents, int maxWeight) { int weight = 1; int total = 0; for (int i = contents.length() - 1; i >= 0; i--) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); total += indexInString * weight; if (++weight > maxWeight) { weight = 1; } } return total % 47; }
Source:
<code>public Long sumMetric(final Task task, final DimFilter filter, final String metric) throws Exception { TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("test_ds") .filters(filter) .aggregators( ImmutableList.<AggregatorFactory>of( new LongSumAggregatorFactory(metric, metric) ) ).granularity(Granularities.ALL) .intervals("2000/3000") .build(); ArrayList<Result<TimeseriesResultValue>> results = Sequences.toList( task.getQueryRunner(query).run(QueryPlus.wrap(query), ImmutableMap.<String, Object>of()), Lists.<Result<TimeseriesResultValue>>newArrayList() ); if (results.isEmpty()) { <START> return NullHandlingHelper.nullToZeroIfNeeded((Long) null); <END> } return results.get(0).getValue().getLongMetric(metric); }</code><technical_language>NullHandlingHelper NullHandlingUtil joined NullHandling</technical_language>

Target:
public Long sumMetric(final Task task, final DimFilter filter, final String metric) throws Exception { TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("test_ds") .filters(filter) .aggregators( ImmutableList.<AggregatorFactory>of( new LongSumAggregatorFactory(metric, metric) ) ).granularity(Granularities.ALL) .intervals("2000/3000") .build(); List<Result<TimeseriesResultValue>> results = task.getQueryRunner(query).run(QueryPlus.wrap(query), ImmutableMap.of()).toList(); return results.isEmpty() ? NullHandling.defaultLongValue() : results.get(0).getValue().getLongMetric(metric); }
Source:
<code>public void testUnicastSerialDataReceiveSubscribedRx16() throws Exception { dataReader.addSerialDatatReceiveListener(receiveSerialDataListener); Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, rx16Packet); PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_SERIAL_DATA_RECEIVED_METHOD, XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES, IS_NOT_BROADCAST_DATA); Mockito.verify(receiveSerialDataListener, Mockito.times(1)).serialDataReceived(XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES); <START> <END> assertEquals(XBEE_16BIT_ADDRESS.toString(), receiveSerialDataListener.getAddress()); assertArrayEquals(RECEIVED_DATA_BYTES, receiveSerialDataListener.getSerialData()); }</code><technical_language>Add a check verify broadcastSerialDataReceived method called</technical_language>

Target:
public void testUnicastSerialDataReceiveSubscribedRx16() throws Exception { dataReader.addSerialDatatReceiveListener(receiveSerialDataListener); Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, rx16Packet); PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_SERIAL_DATA_RECEIVED_METHOD, XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES, IS_NOT_BROADCAST_DATA); Mockito.verify(receiveSerialDataListener, Mockito.times(1)).serialDataReceived(XBEE_16BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES); Mockito.verify(receiveSerialDataListener, Mockito.never()).broadcastSerialDataReceived(Mockito.anyString(), (byte[])Mockito.any()); assertEquals(XBEE_16BIT_ADDRESS.toString(), receiveSerialDataListener.getAddress()); assertArrayEquals(RECEIVED_DATA_BYTES, receiveSerialDataListener.getSerialData()); }
Source:
<code>public void confirmMessage() { if (!isAcknowledgementSent) { try { channel.basicAck(deliveryTag, false); isAcknowledgementSent = true; } catch (Exception e) { LOG.error(String.format("[consumer tag: %s] Got exception when trying to confirm a message:", consumerTag), e); } } else { <START> LOG.warn(ACK_WAS_ALREADY_SENT); <END> } }</code><technical_language>I agree logging warning for duplicate confirm is ok. if developer invoked confirm reject? I some problem in microservice's logic some more evidence in logs a WARN message</technical_language>

Target:
public void confirmMessage() { executeAck("confirm", () -> { channel.basicAck(deliveryTag, false); LOG.debug(String.format("[consumer tag: %s] A message was confirmed", consumerTag)); }); }
Source:
<code><START> public String toString() { <END> return this.getClass().getSimpleName() + " { " + getPayloadId() + " }"; }</code><technical_language>Recommend ToStringBuilder</technical_language>

Target:
public String toString() { return new ToStringBuilder(this) .append("mySubscription", mySubscription) .append("myPayloadString", myPayloadString) .append("myPayload", myPayload) .append("myPayloadId", myPayloadId) .append("myOperationType", myOperationType) .toString(); }
Source:
<code>public Pair<ListenableFuture, Boolean> streamMore(SystemProcedureExecutionContext context, List<DBBPool.BBContainer> outputBuffers, int[] rowCountAccumulator) { ListenableFuture writeFuture = null; prepareBuffers(outputBuffers); Pair<Long, int[]> serializeResult = context.tableStreamSerializeMore(m_tableId, m_type, outputBuffers); if (serializeResult.getFirst() == SERIALIZATION_ERROR) { for (DBBPool.BBContainer container : outputBuffers) { container.discard(); } <START> StreamSnapshotFailedException ex = new StreamSnapshotFailedException("Snapshot of table " + m_tableId + " failed to complete."); <END> m_tableTasks.get(m_tableId).m_target.reportSerializationFailure(ex); return Pair.of(null, false); } if (serializeResult.getSecond()[0] > 0) { if (rowCountAccumulator != null && rowCountAccumulator.length == 1) { rowCountAccumulator[0] += getTupleDataRowCount(outputBuffers); } writeFuture = writeBlocksToTargets(outputBuffers, serializeResult.getSecond()); } else { for (DBBPool.BBContainer container : outputBuffers) { container.discard(); } } return Pair.of(writeFuture, serializeResult.getFirst() > 0); }</code><technical_language>Stream snapshot is for rejoin elastic join. kind of weird throw a StreamSnapshotFailedException here</technical_language>

Target:
public Pair<ListenableFuture, Boolean> streamMore(SystemProcedureExecutionContext context, List<DBBPool.BBContainer> outputBuffers, int[] rowCountAccumulator) { ListenableFuture writeFuture = null; prepareBuffers(outputBuffers); Pair<Long, int[]> serializeResult = context.tableStreamSerializeMore(m_tableId, m_type, outputBuffers); if (serializeResult.getFirst() == SERIALIZATION_ERROR) { for (DBBPool.BBContainer container : outputBuffers) { container.discard(); } SnapshotSerializationException ex = new SnapshotSerializationException("Snapshot of table " + m_tableId + " failed to complete."); for (SnapshotTableTask task : m_tableTasks) { task.m_target.reportSerializationFailure(ex); } return Pair.of(null, false); } if (serializeResult.getSecond()[0] > 0) { if (rowCountAccumulator != null && rowCountAccumulator.length == 1) { rowCountAccumulator[0] += getTupleDataRowCount(outputBuffers); } writeFuture = writeBlocksToTargets(outputBuffers, serializeResult.getSecond()); } else { for (DBBPool.BBContainer container : outputBuffers) { container.discard(); } } return Pair.of(writeFuture, serializeResult.getFirst() > 0); }
Source:
<code>public void testDAGImportSyntax() throws IOException, TimeoutException, ApiException { <START> final ApiClient webClient = WorkflowET.getWebClient(); <END> WorkflowsApi workflowApi = new WorkflowsApi(webClient); UsersApi usersApi = new UsersApi(webClient); final Long userId = usersApi.getUser().getId(); final PublishRequest publishRequest = new PublishRequest(); publishRequest.setPublish(true); usersApi.refreshWorkflows(userId); Workflow githubWorkflow = workflowApi.manualRegister("github", "DockstoreTestUser2/dockstore-whalesay-imports", "/Dockstore.cwl", "test-workflow", "cwl"); Workflow refresh = workflowApi.refresh(githubWorkflow.getId()); Optional<WorkflowVersion> master = refresh.getWorkflowVersions().stream().filter(workflow -> workflow.getName().equals("master")).findFirst(); final String basePath = webClient.getBasePath(); URL url = new URL(basePath + "/workflows/" +githubWorkflow.getId()+"/dag/" + master.get().getId() ); final List<String> strings = Resources.readLines(url, Charset.forName("UTF-8")); int countNode = 0; int last = 0; String node = "tool"; while(last !=-1){ last = strings.get(0).indexOf(node,last); if(last !=-1){ countNode++; last += node.length(); } } Assert.assertTrue("JSON should not be blank", strings.size() > 0); Assert.assertEquals("JSON should have two nodes", countNode, 2); Assert.assertTrue("node data should have rev as tool", strings.get(0).contains("rev")); Assert.assertTrue("node data should have sorted as tool", strings.get(0).contains("sorted")); Assert.assertTrue("edge should connect rev and sorted", strings.get(0).contains("\"source\":\"0\",\"target\":\"1\"")); }</code><technical_language>Oh, re-factor this a bit, putting re-used code a method? I want a bit more clear is test cases is next work this. Thanks</technical_language>

Target:
public void testDAGImportSyntax() throws IOException, TimeoutException, ApiException { final List<String> strings = getJSON("DockstoreTestUser2/dockstore-whalesay-imports", "/Dockstore.cwl", "cwl", "master"); int countNode = countNodeInJSON(strings); Assert.assertTrue("JSON should not be blank", strings.size() > 0); Assert.assertEquals("JSON should have two nodes", countNode, 2); Assert.assertTrue("node data should have rev as tool", strings.get(0).contains("rev")); Assert.assertTrue("node data should have sorted as tool", strings.get(0).contains("sorted")); Assert.assertTrue("edge should connect rev and sorted", strings.get(0).contains("\"source\":\"0\",\"target\":\"1\"")); }
Source:
<code>public Expr apply(final List<Expr> args) { if (args.size() < 3 || args.size() > 4) { <START> throw new IAE("'%s' must have 3 to 4 arguments", name()); <END> } final Expr arg = args.get(0); if (args.get(1).isLiteral()) { final PeriodGranularity granularity = getGranularity(args, ExprUtils.nilBindings()); final Period period = granularity.getPeriod(); final Chronology chronology = ISOChronology.getInstance(granularity.getTimeZone()); final int step = getStep(args, ExprUtils.nilBindings()); class TimestampShiftExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { return ExprEval.of(chronology.add(period, arg.eval(bindings).asLong(), step)); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampShiftExpr(); } else { class TimestampShiftDynamicExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { final PeriodGranularity granularity = getGranularity(args, bindings); final Period period = granularity.getPeriod(); final Chronology chronology = ISOChronology.getInstance(granularity.getTimeZone()); final int step = getStep(args, bindings); return ExprEval.of(chronology.add(period, arg.eval(bindings).asLong(), step)); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampShiftDynamicExpr(); } }</code><technical_language>ticks</technical_language>

Target:
public Expr apply(final List<Expr> args) { if (args.size() < 3 || args.size() > 4) { throw new IAE("Function[%s] must have 3 to 4 arguments", name()); } if (args.stream().skip(1).allMatch(Expr::isLiteral)) { return new TimestampShiftExpr(args); } else { return new TimestampShiftDynamicExpr(args); } }
Source:
<code>void adaptTypedFilterTo(SingleColumnValueFilter filter, OutputStream outputStream) throws IOException { if (filter.getFilterIfMissing()) { writerIfIncludeMissingRowFilterExpression(filter, outputStream); } else { <START> try (ReaderExpressionScope rowHasOuter = <END> new ReaderExpressionScope(outputStream, "(", ")")) { try (ReaderExpressionScope rowHas = new ReaderExpressionScope(outputStream, "row_has(", ")")) { try (ReaderExpressionScope condWrapper = new ReaderExpressionScope(outputStream, '(', ')')) { writeFilterColumnSpec(filter, outputStream); } } outputStream.write(Bytes.toBytes(" ? ")); try (ReaderExpressionScope trueWrapper = new ReaderExpressionScope(outputStream, '(', ')')) { writerIfIncludeMissingRowFilterExpression(filter, outputStream); } outputStream.write(Bytes.toBytes(" : ")); try (ReaderExpressionScope falseWrapper = new ReaderExpressionScope(outputStream, '(', ')')) { writeAllColumnsSpec(filter, outputStream); } } } }</code><technical_language>advice improving readability</technical_language>

Target:
void adaptTypedFilterTo(SingleColumnValueFilter filter, OutputStream outputStream) throws IOException { if (filter.getFilterIfMissing()) { writeRowHasWithValueMatch(filter, outputStream); } else { try (ReaderExpressionScope rowHasOuter = new ReaderExpressionScope(outputStream, '(', ')')) { try (ReaderExpressionScope rowHas = new ReaderExpressionScope(outputStream, "row_has((", "))")) { writeFilterColumnSpec(filter, outputStream); } outputStream.write(Bytes.toBytes(" ? ")); try (ReaderExpressionScope trueWrapper = new ReaderExpressionScope(outputStream, '(', ')')) { writeRowHasWithValueMatch(filter, outputStream); } outputStream.write(Bytes.toBytes(" : ")); try (ReaderExpressionScope falseWrapper = new ReaderExpressionScope(outputStream, '(', ')')) { writeAllColumnsSpec(outputStream); } } } }
Source:
<code>public void shouldValidateProject() throws Exception { final String validateUri = "/gdc/md/PROJECT_ID/validate"; final String task1Uri = validateUri + "/task/TASK_ID"; final String task2Uri = validateUri + "/task/TASK_ID2"; final String resultUri = validateUri + "/result/RESULT_ID"; onRequest() .havingPathEqualTo(validateUri) .respond() .withBody(readResource("/project/project-validationAvail.json")); onRequest() .havingPathEqualTo(validateUri) .havingMethodEqualTo("POST") .respond() .withBody(MAPPER.writeValueAsString(new AsyncTask(task1Uri))) .withStatus(201); onRequest() .havingPathEqualTo(task1Uri) .respond() .withBody(MAPPER.writeValueAsString(new UriResponse(task2Uri))) .withHeader("Location", task2Uri) .withStatus(303); onRequest() .havingPathEqualTo(task2Uri) .respond() .withBody(MAPPER.writeValueAsString(new AsyncTask(task2Uri))) .withStatus(202) .thenRespond() .withBody(MAPPER.writeValueAsString(new UriResponse(resultUri))) .withHeader("Location", resultUri) .withStatus(303); onRequest() .havingPathEqualTo(resultUri) .respond() .withBody(readResource("/project/project-validationResults.json")) .withStatus(200); final ProjectValidationResults validateResult = gd.getProjectService().validateProject(enabled).get(); assertThat(validateResult, notNullValue()); assertThat(validateResult.getResults(), notNullValue()); <START> verifyThatRequest() <END> .havingPathEqualTo(validateUri) .havingMethodEqualTo("POST") .havingBody(isJsonString("/project/project-validate.json")) .receivedOnce(); }</code><technical_language>this superfluous</technical_language>

Target:
public void shouldValidateProject() throws Exception { final String validateUri = "/gdc/md/PROJECT_ID/validate"; final String task1Uri = validateUri + "/task/TASK_ID"; final String task2Uri = validateUri + "/task/TASK_ID2"; final String resultUri = validateUri + "/result/RESULT_ID"; onRequest() .havingPathEqualTo(validateUri) .respond() .withBody(readResource("/project/project-validationAvail.json")); onRequest() .havingPathEqualTo(validateUri) .havingMethodEqualTo("POST") .havingBody(isJsonString("/project/project-validate.json")) .respond() .withBody(MAPPER.writeValueAsString(new AsyncTask(task1Uri))) .withStatus(201); onRequest() .havingPathEqualTo(task1Uri) .respond() .withBody(MAPPER.writeValueAsString(new UriResponse(task2Uri))) .withHeader("Location", task2Uri) .withStatus(303); onRequest() .havingPathEqualTo(task2Uri) .respond() .withBody(MAPPER.writeValueAsString(new AsyncTask(task2Uri))) .withStatus(202) .thenRespond() .withBody(MAPPER.writeValueAsString(new UriResponse(resultUri))) .withHeader("Location", resultUri) .withStatus(303); onRequest() .havingPathEqualTo(resultUri) .respond() .withBody(readResource("/project/project-validationResults.json")) .withStatus(200); final ProjectValidationResults validateResult = gd.getProjectService().validateProject(enabled).get(); assertThat(validateResult, notNullValue()); }
Source:
<code>public static List<String> getAvailableProfilesSupportingPasswdChange(SSOExtensionsManager extensionsManager) { List<String> profiles = new ArrayList<>(); <START> for (ExtensionProxy authnExtension : extensionsManager.getExtensionsByService(Authn.class.getName())) { <END> if ((authnExtension.getContext().<Long>get(Authn.ContextKeys.CAPABILITIES, 0L) & Authn.Capabilities.CREDENTIALS_CHANGE) != 0) { Properties config = authnExtension.getContext().get(Base.ContextKeys.CONFIGURATION); profiles.add(config.getProperty(Authn.ConfigKeys.PROFILE_NAME)); } } return profiles; }</code><technical_language>a must, this replaced java8 lambda combining Stream.filter.map.collect assuming java8 here</technical_language>

Target:
public static List<String> getAvailableProfilesSupportingPasswdChange(SSOExtensionsManager extensionsManager) { return getAvailableProfilesImpl(extensionsManager, Authn.Capabilities.CREDENTIALS_CHANGE); }
Source:
<code>public boolean isLoadedOnMercury() { boolean result = isTagLoadedOnMercury(); <START> Assertion.assertTrue(result, MercuryMessages.INVISIBLE_MSG); <END> PageObjectLogging.log(getTagName(), MercuryMessages.VISIBLE_MSG, result); return result; }</code><technical_language>assertion in test. Page objects keeping page state asserting if is correct</technical_language>

Target:
public boolean isLoadedOnMercury() { boolean result = isTagLoadedOnMercury(); PageObjectLogging.log(getTagName(), MercuryMessages.VISIBLE_MSG, result); return result; }
Source:
<code><START> private boolean doesNotMatch(String responseBody, List<String> notContentStrings) { <END> boolean matches = true; if (!notContentStrings.isEmpty()) { for (String notContentStr : notContentStrings) { matches = !responseBody.contains(notContentStr); if (!matches) { return matches; } } } return matches; }</code><technical_language>static (same for doesMatch doesBinRegexMatch). - This is doesMatch negated (though do need check if empty beforehand), call instead of duplicating</technical_language>

Target:
private static boolean doesNotMatch(String responseBody, List<String> notContentStrings) { if (notContentStrings.isEmpty()) { return true; } return !doesMatch(responseBody, notContentStrings); }
Source:
<code><START> public int hashCode() { <END> return new HashCodeBuilder() .append(group) .append(name) .append(value) .toHashCode(); }</code><technical_language>fine, generally personally I autogenerate equals hashcode conflicting</technical_language>

Target:
public int hashCode() { int result = group != null ? group.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (value != null ? value.hashCode() : 0); return result; }
Source:
<code>public List<StreamsDatum> process(StreamsDatum streamsDatum) { StreamsDatum result = null; try { Object item = streamsDatum.getDocument(); LOGGER.debug("{} processing {}", STREAMS_ID, item.getClass()); Activity activity = null; if(item instanceof String) { item = deserializeItem(item); } if(item instanceof Video) { activity = new Activity(); youtubeActivityUtil.updateActivity((Video)item, activity, streamsDatum.getId()); } if(activity != null) { result = new StreamsDatum(activity); count++; } } catch (Exception e) { <START> e.printStackTrace(); <END> LOGGER.error("Exception while converting Video to Activity: {}", e.getMessage()); } if( result != null ) return Lists.newArrayList(result); else return Lists.newArrayList(); }</code><technical_language>Instead of logging error message printing stacktrace error stream, log entire stacktrace? ("message', e)</technical_language>

Target:
public List<StreamsDatum> process(StreamsDatum streamsDatum) { StreamsDatum result = null; try { Object item = streamsDatum.getDocument(); LOGGER.debug("{} processing {}", STREAMS_ID, item.getClass()); Activity activity = null; if(item instanceof String) { item = deserializeItem(item); } if(item instanceof Video) { activity = new Activity(); youtubeActivityUtil.updateActivity((Video)item, activity, streamsDatum.getId()); } if(activity != null) { result = new StreamsDatum(activity); count++; } } catch (Exception e) { LOGGER.error("Exception while converting Video to Activity: {}", e); } if( result != null ) return Lists.newArrayList(result); else return Lists.newArrayList(); }
Source:
<code>List<GlyphPair> scriptOneToScriptTwoList() { return homoglyphPairs.stream() .sorted(sortByLength.reversed().thenComparing(sortByNaturalOrder)) <START> .collect(Collectors.toList()); <END> }</code><technical_language>Ideally, is ImmutableList collector, ensure this list is modified creation</technical_language>

Target:
final List<GlyphPair> scriptOneToScriptTwoList() { return homoglyphPairs.stream() .sorted(sortByLength.reversed().thenComparing(sortByNaturalOrder)) .collect(Collectors.toList()); }
Source:
<code><START> public long extractTimestampMillis(final Message message) { <END> return 0; }</code><technical_language>this abstract protected</technical_language>

Target:
abstract protected long extractTimestampMillis(final Message message) throws Exception; protected static long toMillis(final long timestamp) { final long nanosecondDivider = (long) Math.pow(10, 9 + 9); final long millisecondDivider = (long) Math.pow(10, 9 + 3); long timestampMillis; if (timestamp / nanosecondDivider > 0L) { timestampMillis = timestamp / (long) Math.pow(10, 6); } else if (timestamp / millisecondDivider > 0L) { timestampMillis = timestamp; } else { timestampMillis = timestamp * 1000L; } return timestampMillis; }