auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void initializeButtons() { Window window = getWindow(); Resources res = getContext().getResources(); Button positiveButtonView = window.findViewById(R.id.positive_button); positiveButtonView.setText(mPositiveButtonText); positiveButtonView.setOnClickListener(v -> { if (mOnClickListener != null) { mOnClickListener.onClick(this, Arrays.copyOf(mCheckedItems, mCheckedItems.length)); } dismiss(); }); int buttonOffset = res.getDimensionPixelSize(R.dimen.car_padding_4) - res.getDimensionPixelSize(R.dimen.car_padding_2); ViewGroup.MarginLayoutParams positiveButtonLayoutParams = (ViewGroup.MarginLayoutParams) positiveButtonView.getLayoutParams(); Button negativeButtonView = window.findViewById(R.id.negative_button); if (!TextUtils.isEmpty(mNegativeButtonText)) { negativeButtonView.setText(mNegativeButtonText); negativeButtonView.setOnClickListener(v -> dismiss()); ViewGroup.MarginLayoutParams negativeButtonLayoutParams = (ViewGroup.MarginLayoutParams) negativeButtonView.getLayoutParams(); int buttonSpacing = <START> getContext().getResources().getDimensionPixelSize( <END> R.dimen.car_padding_2); positiveButtonLayoutParams.setMarginStart(buttonSpacing); positiveButtonView.requestLayout(); negativeButtonLayoutParams.setMarginStart(buttonOffset); negativeButtonLayoutParams.setMarginEnd(buttonSpacing); negativeButtonView.requestLayout(); } else { negativeButtonView.setVisibility(View.GONE); positiveButtonLayoutParams.setMarginStart(buttonOffset); positiveButtonView.requestLayout(); } }</code><technical_language>"res" here. Alternatively, retrieving car_padding_2 twice, save a local variable</technical_language>

Target:
private void initializeButtons() { Window window = getWindow(); Resources res = getContext().getResources(); Button positiveButtonView = window.findViewById(R.id.positive_button); positiveButtonView.setText(mPositiveButtonText); positiveButtonView.setOnClickListener(v -> { if (mOnClickListener != null) { mOnClickListener.onClick(this, Arrays.copyOf(mCheckedItems, mCheckedItems.length)); } dismiss(); }); int buttonOffset = res.getDimensionPixelSize(R.dimen.car_padding_4) - res.getDimensionPixelSize(R.dimen.car_padding_2); ViewGroup.MarginLayoutParams positiveButtonLayoutParams = (ViewGroup.MarginLayoutParams) positiveButtonView.getLayoutParams(); Button negativeButtonView = window.findViewById(R.id.negative_button); if (!TextUtils.isEmpty(mNegativeButtonText)) { negativeButtonView.setText(mNegativeButtonText); negativeButtonView.setOnClickListener(v -> dismiss()); ViewGroup.MarginLayoutParams negativeButtonLayoutParams = (ViewGroup.MarginLayoutParams) negativeButtonView.getLayoutParams(); int buttonSpacing = res.getDimensionPixelSize(R.dimen.car_padding_2); positiveButtonLayoutParams.setMarginStart(buttonSpacing); positiveButtonView.requestLayout(); negativeButtonLayoutParams.setMarginStart(buttonOffset); negativeButtonLayoutParams.setMarginEnd(buttonSpacing); negativeButtonView.requestLayout(); } else { negativeButtonView.setVisibility(View.GONE); positiveButtonLayoutParams.setMarginStart(buttonOffset); positiveButtonView.requestLayout(); } }
Source:
<code>public void readingStreamIdsByHashInTheSameTransactionIsPermitted() throws IOException { <START> final byte[] bytes = new byte[2 * StreamTestStreamStore.BLOCK_SIZE_IN_BYTES]; <END> long id = timestampService.getFreshTimestamp(); Random rand = new Random(); rand.nextBytes(bytes); Sha256Hash hash = Sha256Hash.computeHash(bytes); ImmutableMap<Long, InputStream> streams = ImmutableMap.of(id, new ByteArrayInputStream(bytes)); storeStreamAndCheckHash(id, hash, streams); byte[] bytesInKvs = readBytesForSingleStream(id); assertArrayEquals(bytesInKvs, bytes); }</code><technical_language>need final</technical_language>

Target:
public void readingStreamIdsByHashInTheSameTransactionIsPermitted() throws IOException { long id = timestampService.getFreshTimestamp(); byte[] bytes = generateRandomTwoBlockStream(); Sha256Hash hash = Sha256Hash.computeHash(bytes); Map<Long, InputStream> streams = ImmutableMap.of(id, new ByteArrayInputStream(bytes)); storeStreamAndCheckHash(id, hash, streams); byte[] bytesInKvs = readBytesForSingleStream(id); assertArrayEquals(bytesInKvs, bytes); }
Source:
<code>public InstructorHomePage(Browser browser){ super(browser); <START> if (!browser.driver.findElements(By.id("fsCopyModal")).isEmpty()) { <END> this.fsCopyModal = new InstructorCopyFsToModal(browser); } }</code><technical_language>This condition fit in InstructorCopyFsToModal.java more, reduce reliance id string</technical_language>

Target:
public InstructorHomePage(Browser browser){ super(browser); if (InstructorCopyFsToModal.isPresentOnPage(browser)) { this.fsCopyModal = new InstructorCopyFsToModal(browser); } }
Source:
<code>public static State getState(ChannelUID channelUID, AstroChannelConfig config, Object instance) throws Exception { Object value = getPropertyValue(channelUID, instance); if (value == null) { return UnDefType.UNDEF; } else if (value instanceof Calendar) { <START> ZoneId zone= ZoneId.of("+03:00"); <END> GregorianCalendar cal = (GregorianCalendar) value; cal.setTimeZone(TimeZone.getTimeZone(zone)); ZonedDateTime zoned= cal.toZonedDateTime().withFixedOffsetZone(); return new DateTimeType(zoned); } else if (value instanceof Number) { BigDecimal decimalValue = new BigDecimal(value.toString()).setScale(2, RoundingMode.HALF_UP); return new DecimalType(decimalValue); } else if (value instanceof String || value instanceof Enum) { return new StringType(value.toString()); } else { throw new RuntimeException("Unsupported value type " + value.getClass().getSimpleName()); } }</code><technical_language>This a arbitrary value. Is timezone supposed "+3" always</technical_language>

Target:
public static State getState(ChannelUID channelUID, AstroChannelConfig config, Object instance) throws Exception { Object value = getPropertyValue(channelUID, instance); if (value == null) { return UnDefType.UNDEF; } else if (value instanceof Calendar) { Calendar cal = (Calendar) value; GregorianCalendar gregorianCal = (GregorianCalendar) DateTimeUtils.applyConfig(cal, config); cal.setTimeZone(TimeZone.getTimeZone(timeZoneProvider.getTimeZone())); ZonedDateTime zoned = gregorianCal.toZonedDateTime().withFixedOffsetZone(); return new DateTimeType(zoned); } else if (value instanceof Number) { BigDecimal decimalValue = new BigDecimal(value.toString()).setScale(2, RoundingMode.HALF_UP); return new DecimalType(decimalValue); } else if (value instanceof String || value instanceof Enum) { return new StringType(value.toString()); } else { throw new RuntimeException("Unsupported value type " + value.getClass().getSimpleName()); } }
Source:
<code>public void testGetAdapter() { org.eclipse.core.resources.IFolder folder = EasyMock .createMock(org.eclipse.core.resources.IFolder.class); <START> Capture<Class> mappedAdapterClassCapture = new Capture(); <END> EasyMock.expect( folder.getAdapter(EasyMock.capture(mappedAdapterClassCapture))) .andStubReturn(folder); EasyMock.expect(folder.getType()).andStubReturn( org.eclipse.core.resources.IResource.FOLDER); EasyMock.replay(folder); final IFolder coreFolder = new EclipseFolderImpl(folder); final Object adapted = coreFolder.getAdapter(IFolder.class); EasyMock.verify(folder); Assert.assertEquals(org.eclipse.core.resources.IFolder.class, mappedAdapterClassCapture.getValue()); Assert.assertTrue("returned adapter is not a folder", adapted instanceof IFolder); }</code><technical_language>This produces some yellow lines ... this statement generified ... Capture<Class<? extends IResource>></technical_language>

Target:
public void testGetAdapter() { org.eclipse.core.resources.IFolder folder = EasyMock .createMock(org.eclipse.core.resources.IFolder.class); Capture<Class<Object>> mappedAdapterClassCapture = new Capture<Class<Object>>(); EasyMock .expect( folder.getAdapter(EasyMock.capture(mappedAdapterClassCapture))) .andStubReturn(folder); EasyMock.expect(folder.getType()) .andStubReturn(org.eclipse.core.resources.IResource.FOLDER); EasyMock.replay(folder); final IFolder coreFolder = new EclipseFolderImpl(folder); final Object adapted = coreFolder.getAdapter(IFolder.class); EasyMock.verify(folder); Assert.assertEquals(org.eclipse.core.resources.IFolder.class, mappedAdapterClassCapture.getValue()); Assert.assertTrue("returned adapter is not a folder", adapted instanceof IFolder); }
Source:
<code>private Map<Column,Bytes> getImpl(Bytes row, Set<Column> columns) throws Exception { env.getSharedResources().getVisCache().validate(columns); ScannerConfiguration config = new ScannerConfiguration(); config.setSpan(Span.exact(row)); for (Column column : columns) { if (column.isQualifierSet()) { config.fetchColumn(column.getFamily(), column.getQualifier()); } else { <START> config.fetchColumnFamily(column.getFamily()); <END> } } RowIterator iter = getImpl(config); Map<Column,Bytes> ret = new HashMap<>(); while (iter.hasNext()) { Entry<Bytes,ColumnIterator> entry = iter.next(); ColumnIterator citer = entry.getValue(); while (citer.hasNext()) { Entry<Column,Bytes> centry = citer.next(); if (columns.contains(centry.getKey())) { ret.put(centry.getKey(), centry.getValue()); } } } updateColumnsRead(row, columns); return ret; }</code><technical_language>I want do this. This code is exact columns. filter exact columns anyway</technical_language>

Target:
private Map<Column,Bytes> getImpl(Bytes row, Set<Column> columns) { env.getSharedResources().getVisCache().validate(columns); ScannerConfiguration config = new ScannerConfiguration(); config.setSpan(Span.exact(row)); for (Column column : columns) { config.fetchColumn(column.getFamily(), column.getQualifier()); } RowIterator iter = getImpl(config); Map<Column,Bytes> ret = new HashMap<>(); while (iter.hasNext()) { Entry<Bytes,ColumnIterator> entry = iter.next(); ColumnIterator citer = entry.getValue(); while (citer.hasNext()) { Entry<Column,Bytes> centry = citer.next(); if (columns.contains(centry.getKey())) { ret.put(centry.getKey(), centry.getValue()); } } } updateColumnsRead(row, columns); return ret; }
Source:
<code>public static ProtocolVersion fromString(String value) { requireNonNull(value, "value is null"); <START> switch (value) { <END> case "v1": return V1; case "v2": return V2; default: throw new IllegalArgumentException("Unknown value: " + value); } }</code><technical_language>This java return valueOf(value.toUpperCase(ENGLISH));</technical_language>

Target:
public static ProtocolVersion fromString(String value) { requireNonNull(value, "value is null"); return valueOf(value.toUpperCase(ENGLISH)); }
Source:
<code>public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { ackTarget = (Address) input.readObject(); if (ackTarget != null) { id = input.readLong(); } topologyId = input.readInt(); keys = MarshallUtil.unmarshallCollection(input, ArrayList::new); <START> if (keys == null) { <END> segments = MarshallUtil.unmarshallIntCollection(input, SmallIntSet::new); } }</code><technical_language>luck is keys null able read command</technical_language>

Target:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { ackTarget = (Address) input.readObject(); if (ackTarget != null) { id = input.readLong(); } topologyId = input.readInt(); keys = MarshallUtil.unmarshallCollection(input, ArrayList::new); }
Source:
<code>public void installed(Viewer viewer) { threadNameChangeListener.attach(); if (fIsScrapbook) { <START> return; <END> } final Viewer finalViewer = viewer; Job job = new Job("Initialize Java Debug Session") { @Override protected IStatus run(IProgressMonitor monitor) { if (!isDisposed()) { doInstalled(finalViewer); } return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { return JavaDebugTargetProxy.this == family; } }; job.setSystem(true); job.schedule(500); fThreadEventHandler.init(viewer); }</code><technical_language>sense attach this return, in doInstalled() later</technical_language>

Target:
public void installed(Viewer viewer) { if (fIsScrapbook) { return; } final Viewer finalViewer = viewer; Job job = new Job("Initialize Java Debug Session") { @Override protected IStatus run(IProgressMonitor monitor) { if (!isDisposed()) { doInstalled(finalViewer); } return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { return JavaDebugTargetProxy.this == family; } }; job.setSystem(true); job.schedule(500); fThreadEventHandler.init(viewer); }
Source:
<code>public void testNoGapsInLocusAccumulator() { final SamReader reader = SamReaderFactory.make().open(new File("src/test/resources/htsjdk/samtools/util/sliver.sam")); final EdgeReadIterator iterator = new EdgeReadIterator(reader, null); AbstractLocusInfo<EdgingRecordAndOffset> previous=null; <START> while (iterator.hasNext() && (previous == null || previous.getPosition() < 1_000_000)) { <END> final AbstractLocusInfo<EdgingRecordAndOffset> next = iterator.next(); if (previous != null) { Assert.assertEquals(next.getPosition(), previous.getPosition() + 1); } previous = next; } }</code><technical_language>I realize this (1_000_000) added Java. Nice</technical_language>

Target:
public void testNoGapsInLocusAccumulator() { final SamReader reader = SamReaderFactory.make().open(new File("src/test/resources/htsjdk/samtools/util/sliver.sam")); final EdgeReadIterator iterator = new EdgeReadIterator(reader, null); AbstractLocusInfo<EdgingRecordAndOffset> previous = null; int counter = 0; while (iterator.hasNext() && (previous == null || previous.getPosition() < 1_000_000)) { counter++; final AbstractLocusInfo<EdgingRecordAndOffset> next = iterator.next(); if (previous != null) { Assert.assertEquals(next.getPosition(), previous.getPosition() + 1); } previous = next; } Assert.assertEquals(counter, 1_000_000); }
Source:
<code>public B enrich(Consumer<EnricherSpec> enricherConfigurer) { EnricherSpec enricherSpec = new EnricherSpec(); enricherConfigurer.accept(enricherSpec); Collection<Object> componentsToRegister = enricherSpec.getComponentsToRegister(); if (!CollectionUtils.isEmpty(componentsToRegister)) { for (Object component : componentsToRegister) { if (component instanceof IntegrationFlowDefinition) { IntegrationFlowDefinition<?> flowBuilder = (IntegrationFlowDefinition<?>) component; if (flowBuilder.isOutputChannelRequired()) { addComponent(flowBuilder.get()); } else { <START> throw new BeanCreationException("Enricher subFlow must require an output channel"); <END> } } } } if (componentsToRegister != null) { componentsToRegister.clear(); } return register(enricherSpec, null); }</code><technical_language>honest I reason in this restriction. is guarantee flow ends a reply producer. sends channel a flow return result replyChannel. Yes, is point wait for reply downstream flow for enricher, similar concern unpredictable sub-flow behavior existing XML definition. So, point relax this assertion configure requestChannel input sub-flow this.componentsToRegister.add(flowBuilder.get()); in EnricherSpec. this IntegrationFlowDefinition affected all. problem "no reply sub-flow" remains end-user. choice</technical_language>

Target:
public B enrich(Consumer<EnricherSpec> enricherConfigurer) { return register(new EnricherSpec(), enricherConfigurer); }
Source:
<code>public WindowPrefs() { this.width = new SimpleIntegerProperty(800); this.height = new SimpleIntegerProperty(600); x = new SimpleDoubleProperty(-1d); y = new SimpleDoubleProperty(-1d); maximized = new SimpleBooleanProperty(); lastView = new SimpleStringProperty(); lastChildViews = new SimpleMapProperty<>(FXCollections.observableHashMap()); <START> backgroundImagePath = new SimpleStringProperty(); <END> }</code><technical_language>suggestion backgroundImagePath = new SimpleObjectProperty<>();</technical_language>

Target:
public WindowPrefs() { this.width = new SimpleIntegerProperty(800); this.height = new SimpleIntegerProperty(600); x = new SimpleDoubleProperty(-1d); y = new SimpleDoubleProperty(-1d); maximized = new SimpleBooleanProperty(); lastView = new SimpleStringProperty(); lastChildViews = new SimpleMapProperty<>(FXCollections.observableHashMap()); backgroundImagePath = new SimpleObjectProperty<>(); }
Source:
<code>public CairoEngine(CairoConfiguration configuration, @Nullable MessageBus messageBus) { this.configuration = configuration; this.writerPool = new WriterPool(configuration, messageBus); this.readerPool = new ReaderPool(configuration); this.writerMaintenanceJob = new WriterMaintenanceJob(configuration); this.telemetryQueue = new RingQueue<>(TelemetryRow::new, configuration.getTelemetryQueueCapacity()); this.telemetryPubSeq = new SPSequence(configuration.getTelemetryQueueCapacity()); <START> this.telemetrySubSeq = new MCSequence(configuration.getTelemetryQueueCapacity()); <END> this.telemetryPubSeq.then(this.telemetrySubSeq).then(this.telemetryPubSeq); this.messageBus = messageBus; }</code><technical_language>this is incorrect. This queue Multiple publisher single consumer</technical_language>

Target:
public CairoEngine(CairoConfiguration configuration, @Nullable MessageBus messageBus) { this.configuration = configuration; this.writerPool = new WriterPool(configuration, messageBus); this.readerPool = new ReaderPool(configuration); this.writerMaintenanceJob = new WriterMaintenanceJob(configuration); this.telemetryQueue = new RingQueue<>(TelemetryRow::new, configuration.getTelemetryQueueCapacity()); this.telemetryPubSeq = new MPSequence(configuration.getTelemetryQueueCapacity()); this.telemetrySubSeq = new SCSequence(); this.telemetryPubSeq.then(this.telemetrySubSeq).then(this.telemetryPubSeq); this.messageBus = messageBus; this.compiler = new SqlCompiler(this); this.sqlExecutionContext = new SqlExecutionContextImpl(messageBus, 1, this); }
Source:
<code>public Map<String, PortType> getOutputPorts() { <START> return new HashMap<String, PortType>(); <END> }</code><technical_language>Collections.emptyMap()</technical_language>

Target:
public Map<String, PortType> getOutputPorts() { return Collections.emptyMap(); }
Source:
<code>private void showWorkflows(String projName) throws Exception { DigdagClient client = buildClient(); CollectionPrinter<RestWorkflowDefinition> formatter = new CollectionPrinter<>(); formatter.column("PROJECT", wf -> wf.getProject().getName()); <START> formatter.column("PROJECT ID", wf -> Integer.toString(wf.getProject().getId())); <END> formatter.column("WORKFLOW", wf -> wf.getName()); formatter.column("REVISION", wf -> wf.getRevision()); List<RestWorkflowDefinition> defs; if (projName != null) { RestProject proj = client.getProject(projName); defs = client.getWorkflowDefinitions(proj.getId()); } else { defs = new ArrayList<>(); for (RestProject proj : client.getProjects()) { try { defs.addAll(client.getWorkflowDefinitions(proj.getId())); } catch (NotFoundException ex) { continue; } } } formatter.print(format, defs, out); out.println(); out.flush(); err.println("Use `digdag workflows <project-name> <name>` to show details."); }</code><technical_language>minor: I PROJECT_ID (underscore) is space a column. for other ID columns</technical_language>

Target:
private void showWorkflows(String projName) throws Exception { DigdagClient client = buildClient(); EntityCollectionPrinter<RestWorkflowDefinition> formatter = new EntityCollectionPrinter<>(); formatter.field("PROJECT", wf -> wf.getProject().getName()); formatter.field("PROJECT ID", wf -> Integer.toString(wf.getProject().getId())); formatter.field("WORKFLOW", RestWorkflowDefinition::getName); formatter.field("REVISION", RestWorkflowDefinition::getRevision); List<RestWorkflowDefinition> defs; if (projName != null) { RestProject proj = client.getProject(projName); defs = client.getWorkflowDefinitions(proj.getId()); } else { defs = new ArrayList<>(); for (RestProject proj : client.getProjects()) { try { defs.addAll(client.getWorkflowDefinitions(proj.getId())); } catch (NotFoundException ex) { continue; } } } formatter.print(format, defs, out); out.println(); out.flush(); err.println("Use `digdag workflows <project-name> <name>` to show details."); }
Source:
<code>public IteratorOptions describeOptions() { IteratorOptions io = new IteratorOptions("comb", "Combiners apply reduce functions to multiple versions of values with otherwise equal keys", null, null); <START> io.addNamedOption(ALL_OPTION, <END> "set to true to apply Combiner to every column, otherwise leave blank. if true, " + COLUMNS_OPTION + " option will be ignored."); io.addNamedOption(COLUMNS_OPTION, "<col fam>[:<col qual>]{,<col fam>[:<col qual>]} escape non-alphanum chars using %<hex>."); return io; }</code><technical_language>Nit: unrelated formatting</technical_language>

Target:
public IteratorOptions describeOptions() { IteratorOptions io = new IteratorOptions("comb", "Combiners apply reduce functions to multiple versions of values with otherwise equal keys", null, null); io.addNamedOption(ALL_OPTION, "set to true to apply Combiner to every column, otherwise leave blank. if true, " + COLUMNS_OPTION + " option will be ignored."); io.addNamedOption(COLUMNS_OPTION, "<col fam>[:<col qual>]{,<col fam>[:<col qual>]} escape non-alphanum chars using %<hex>."); io.addNamedOption(REDUCE_ON_FULL_COMPACTION_ONLY_OPTION, "If true, only reduce on full major compactions. Defaults to false. "); return io; }
Source:
<code>public int getChannel() { <START> return hasPartState() ? part.getChannel(getPartState()) : 0; <END> }</code><technical_language>For consistency, IChanneledNetwork.DEFAULT_CHANNEL well</technical_language>

Target:
public int getChannel() { return hasPartState() ? part.getChannel(getPartState()) : IChanneledNetwork.DEFAULT_CHANNEL; }
Source:
<code>private void checkEndOfRowGroup() throws IOException { <START> if (rowsReturned != totalCountLoadedSoFar) return; <END> PageReadStore pages = reader.readNextRowGroup(); if (pages == null) { throw new IOException("expecting more rows but reached last block. Read " + rowsReturned + " out of " + totalRowCount); } List<ColumnDescriptor> columns = requestedSchema.getColumns(); List<Type> types = requestedSchema.getFields(); columnReaders = new VectorizedColumnReader[columns.size()]; for (int i = 0; i < columns.size(); ++i) { columnReaders[i] = new VectorizedColumnReader(columns.get(i), pages.getPageReader(columns.get(i)), skipTimestampConversion, types.get(i)); } totalCountLoadedSoFar += pages.getRowCount(); }</code><technical_language>nit: add braces</technical_language>

Target:
private void checkEndOfRowGroup() throws IOException { if (rowsReturned != totalCountLoadedSoFar) { return; } PageReadStore pages = reader.readNextRowGroup(); if (pages == null) { throw new IOException("expecting more rows but reached last block. Read " + rowsReturned + " out of " + totalRowCount); } List<ColumnDescriptor> columns = requestedSchema.getColumns(); List<Type> types = requestedSchema.getFields(); columnReaders = new VectorizedColumnReader[columns.size()]; for (int i = 0; i < columns.size(); ++i) { columnReaders[i] = new VectorizedColumnReader(columns.get(i), pages.getPageReader(columns.get(i)), skipTimestampConversion, types.get(i)); } totalCountLoadedSoFar += pages.getRowCount(); }
Source:
<code>private void addDataNodeToStateMetrics(final DataNode dataNode) { <START> final String metricName = dataNode.toString()+ "-State"; <END> Gauge<Long> dataNodeState = new Gauge<Long>() { @Override public Long getValue() { return dataNode.getState() == HardwareState.AVAILABLE ? 1L : 0L; } }; registry.register(MetricRegistry.name(ClusterMap.class, metricName), dataNodeState); dataNodeStateList.add(dataNodeState); }</code><technical_language>dataNode + "-State" enough. toString is required. Spacing. wan't apply coding standard template this change</technical_language>

Target:
private void addDataNodeToStateMetrics(final DataNode dataNode) { final String metricName = dataNode + "-ResourceState"; Gauge<Long> dataNodeState = new Gauge<Long>() { @Override public Long getValue() { return dataNode.getState() == HardwareState.AVAILABLE ? 1L : 0L; } }; registry.register(MetricRegistry.name(ClusterMap.class, metricName), dataNodeState); dataNodeStateList.add(dataNodeState); }
Source:
<code>public void write(DataOutput out) throws IOException { ArrayList<String> fields = new ArrayList<>(); if (maxMemory != null) <START> addField(fields, MAX_MEM.getKey(), maxMemory); <END> if (maxLatency != null) addField(fields, MAX_LATENCY.getKey(), maxLatency); if (maxWriteThreads != null) addField(fields, MAX_WRITE_THREADS.getKey(), maxWriteThreads); if (timeout != null) addField(fields, MAX_TIMEOUT.getKey(), timeout); if (durability != Durability.DEFAULT) addField(fields, DURABILITY.getKey(), durability); String output = StringUtils.join(",", fields); byte[] bytes = output.getBytes(UTF_8); byte[] len = String.format("%6s#", Integer.toString(bytes.length, 36)).getBytes(UTF_8); if (len.length != 7) throw new IllegalStateException("encoded length does not match expected value"); out.write(len); out.write(bytes); }</code><technical_language>leave this method unchanged. if is a benefit changing keys</technical_language>

Target:
public void write(DataOutput out) throws IOException { ArrayList<String> fields = new ArrayList<>(); if (maxMemory != null) addField(fields, "maxMemory", maxMemory); if (maxLatency != null) addField(fields, "maxLatency", maxLatency); if (maxWriteThreads != null) addField(fields, "maxWriteThreads", maxWriteThreads); if (timeout != null) addField(fields, "timeout", timeout); if (durability != Durability.DEFAULT) addField(fields, "durability", durability); String output = StringUtils.join(",", fields); byte[] bytes = output.getBytes(UTF_8); byte[] len = String.format("%6s#", Integer.toString(bytes.length, 36)).getBytes(UTF_8); if (len.length != 7) throw new IllegalStateException("encoded length does not match expected value"); out.write(len); out.write(bytes); }
Source:
<code>public static void checkForRisingAllert(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Boolean rising_alert = prefs.getBoolean("rising_alert", false); if(!rising_alert) { return; } if(prefs.getLong("alerts_disabled_until", 0) > new Date().getTime()){ Log.i("NOTIFICATIONS", "checkForRisingAllert: Notifications are currently disabled!!"); return; } <START> if(prefs.getLong("high_alerts_disabled_until", 0) > new Date().getTime()){ <END> Log.i("NOTIFICATIONS", "checkForRisingAllert: High alerts are currently disabled!!"); return; } if(IsUnclearTime(context)) { Log.d(TAG_ALERT, "checkForRisingAllert we are in an clear time, returning without doing anything"); return ; } String riseRate = prefs.getString("rising_bg_val", "2"); float friseRate = 2; try { friseRate = Float.parseFloat(riseRate); } catch (NumberFormatException nfe) { Log.e(TAG_ALERT, "checkForRisingAllert reading falling_bg_val failed, continuing with 2", nfe); } Log.d(TAG_ALERT, "checkForRisingAllert will check for rate of " + friseRate); boolean riseAlert = checkForDropRiseAllert(friseRate, false); Notifications.RisingAlert(context, riseAlert); }</code><technical_language>I this is related high alert. this alerts is fired bother in case</technical_language>

Target:
public static void checkForRisingAllert(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Boolean rising_alert = prefs.getBoolean("rising_alert", false); if(!rising_alert) { return; } if(prefs.getLong("alerts_disabled_until", 0) > new Date().getTime()){ Log.i("NOTIFICATIONS", "checkForRisingAllert: Notifications are currently disabled!!"); return; } if(IsUnclearTime(context)) { Log.d(TAG_ALERT, "checkForRisingAllert we are in an clear time, returning without doing anything"); return ; } String riseRate = prefs.getString("rising_bg_val", "2"); float friseRate = 2; try { friseRate = Float.parseFloat(riseRate); } catch (NumberFormatException nfe) { Log.e(TAG_ALERT, "checkForRisingAllert reading falling_bg_val failed, continuing with 2", nfe); } Log.d(TAG_ALERT, "checkForRisingAllert will check for rate of " + friseRate); boolean riseAlert = checkForDropRiseAllert(friseRate, false); Notifications.RisingAlert(context, riseAlert); }
Source:
<code>public long getTimeBucket(long time) { if (time < start) { return -1; } long diffFromStart = time - fixedStart; long key = diffFromStart / bucketSpanMillis; if (time >= end) { long diffInBuckets = (time - end) / bucketSpanMillis; long move = (diffInBuckets + 1) * bucketSpanMillis; start += move; end += move; <START> if (((time - oldend) / bucketSpanMillis) >= 0) { <END> triggerPurge = true; oldend = end; lowestPurgeableTimeBucket = ((start - fixedStart) / bucketSpanMillis) - 2; } } return key; }</code><technical_language>this condition strictly > 0 more conservative? Also, replacing if block following: triggerPurge = (diffInBuckets > 0); if (triggerPurge) { lowestPurgeableTimeBucket = ((start - fixedStart) / bucketSpanMillis) - 2; } remove oldend</technical_language>

Target:
public long getTimeBucket(long time) { if (time < start) { return -1; } long diffFromStart = time - fixedStart; long key = diffFromStart / bucketSpanMillis; if (time >= end) { long diffInBuckets = (time - end) / bucketSpanMillis; long move = (diffInBuckets + 1) * bucketSpanMillis; start += move; end += move; triggerPurge = (move > 0); if (triggerPurge) { lowestPurgeableTimeBucket = ((start - fixedStart) / bucketSpanMillis) - 2; } } return key; }
Source:
<code>private static void assertGeometry(String wkt) throws ParseException { Slice geometry = stGeometryFromText(utf8Slice(wkt)); Geometry expected = WKT_READER.read(wkt); Geometry actual = JtsGeometryUtils.deserialize(geometry); if (expected.isEmpty()) { assertTrue(actual.isEmpty()); } else { assertEquals(actual, expected); } if (expected.isEmpty()) { assertTrue(JtsGeometryUtils.deserialize(JtsGeometryUtils.serialize(expected)).isEmpty()); } else { <START> assertEquals(JtsGeometryUtils.deserialize(JtsGeometryUtils.serialize(expected)), expected); <END> } }</code><technical_language>this tests JTS-serialized geometry JTS-deserialized; test JTS-serialized geometry ESRI-deserialized</technical_language>

Target:
private static void assertGeometry(String wkt) throws ParseException { Slice geometry = stGeometryFromText(utf8Slice(wkt)); Geometry expected = WKT_READER.read(wkt); Geometry actual = JtsGeometryUtils.deserialize(geometry); if (expected.isEmpty()) { assertTrue(actual.isEmpty()); } else { assertEquals(actual, expected); } Slice jtsSerializedGeometry = JtsGeometryUtils.serialize(expected); if (expected.isEmpty()) { assertTrue(JtsGeometryUtils.deserialize(jtsSerializedGeometry).isEmpty()); } else { assertEquals(JtsGeometryUtils.deserialize(jtsSerializedGeometry), expected); } assertEquals(GeometryUtils.deserialize(jtsSerializedGeometry).asText(), (GeometryUtils.deserialize(geometry)).asText()); }
Source:
<code>private void writeViolation(final String account, final String region, final Object metaInfo, final String canonicalHostedZoneName, final List<String> instanceIds) { final Optional<Map> taupageYaml = instanceIds. stream(). map(id -> fetchTaupageYaml.getTaupageYaml(id, account, region)). filter(Optional::isPresent). map(Optional::get). findFirst(); final ViolationBuilder violationBuilder = new ViolationBuilder(); final Violation violation = violationBuilder.withAccountId(account) .withRegion(region) .withPluginFullyQualifiedClassName(FetchElasticLoadBalancersJob.class) .withType(UNSECURED_PUBLIC_ENDPOINT) .withMetaInfo(metaInfo) .withEventId(EVENT_ID) .withInstanceId(canonicalHostedZoneName) <START> .withAccountId(taupageYaml.map(data -> (String) data.get(APPLICATION_ID)).map(StringUtils::trimToNull).orElse(null)) <END> .withApplicationVersion(taupageYaml.map(data -> (String) data.get(APPLICATION_VERSION)).map(StringUtils::trimToNull).orElse(null)) .build(); violationSink.put(violation); }</code><technical_language>bug: withAccountId instead of withApplicationId</technical_language>

Target:
private void writeViolation(final String account, final String region, final Object metaInfo, final String canonicalHostedZoneName, final List<String> instanceIds) { final Optional<Map> taupageYaml = instanceIds. stream(). map(id -> fetchTaupageYaml.getTaupageYaml(id, account, region)). filter(Optional::isPresent). map(Optional::get). findFirst(); final ViolationBuilder violationBuilder = new ViolationBuilder(); final Violation violation = violationBuilder.withAccountId(account) .withRegion(region) .withPluginFullyQualifiedClassName(FetchElasticLoadBalancersJob.class) .withType(UNSECURED_PUBLIC_ENDPOINT) .withMetaInfo(metaInfo) .withEventId(EVENT_ID) .withInstanceId(canonicalHostedZoneName) .withApplicationId(taupageYaml.map(data -> (String) data.get(APPLICATION_ID)).map(StringUtils::trimToNull).orElse(null)) .withApplicationVersion(taupageYaml.map(data -> (String) data.get(APPLICATION_VERSION)).map(StringUtils::trimToNull).orElse(null)) .build(); violationSink.put(violation); }
Source:
<code>public void decompress(ByteBuffer input, ByteBuffer output) throws MalformedInputException { if (input.isDirect() || output.isDirect()) { <START> throw new UnsupportedOperationException("Decompression of direct byte buffer not supported"); <END> } byte[] inputArray; int inputOffset; if (input.hasArray()) { inputArray = input.array(); inputOffset = input.arrayOffset() + input.position(); } else { throw new IllegalArgumentException("Unsupported input ByteBuffer implementation " + input.getClass().getName()); } byte[] outputArray; int outputOffset; if (output.hasArray()) { outputArray = output.array(); outputOffset = output.arrayOffset() + output.position(); } else { throw new IllegalArgumentException("Unsupported output ByteBuffer implementation " + output.getClass().getName()); } int written = decompress(inputArray, inputOffset, input.remaining(), outputArray, outputOffset, output.remaining()); output.position(output.position() + written); }</code><technical_language>IllegalArgumentException</technical_language>

Target:
public void decompress(ByteBuffer input, ByteBuffer output) throws MalformedInputException { if (input.isDirect() || output.isDirect() || !input.hasArray() || !output.hasArray()) { throw new IllegalArgumentException("Non-direct byte buffer backed by byte array required"); } int inputOffset = input.arrayOffset() + input.position(); int outputOffset = output.arrayOffset() + output.position(); int written = decompress(input.array(), inputOffset, input.remaining(), output.array(), outputOffset, output.remaining()); output.position(output.position() + written); }
Source:
<code><START> private void initialize() throws IOException { <END> dirChooser = new DirectoryChooser(); dbload = new DBLoadService(); dbload.setOnFailed(e -> { new ExceptionDialog(list.getParent(), dbload.getException(), "Database is already in use, please choose another."); }); dbload.setOnRunning(e -> progressDialog.show()); dbload.setOnSucceeded(e -> { dbProperty.setValue(dbload.getValue()); startButton.setDisable(false); progressDialog.close(); }); dbProperty = new SimpleObjectProperty<>(this, "graph"); items = FXCollections.observableArrayList(SELECT_OPTION); scanDirectory(); list.setItems(items); list.getSelectionModel().select(getDBPath()); list.getSelectionModel().selectedItemProperty().addListener((obj, oldV, newV) -> { deleteButton.setDisable(true); if (newV != SELECT_OPTION) { deleteButton.setDisable(false); } dbload.setDatabase(newV); System.out.println(this.getDBPath()); }); }</code><technical_language>is this exception caught</technical_language>

Target:
private void initialize() { dirChooser = new DirectoryChooser(); dbload = new DBLoadService(); dbload.setOnFailed(e -> { new ExceptionDialog(list.getParent(), dbload.getException(), "Database is already in use, please choose another."); progressDialog.close(); }); dbload.setOnRunning(e -> progressDialog.show()); dbload.setOnSucceeded(e -> { dbProperty.setValue(dbload.getValue()); progressDialog.close(); }); items = list.getItems(); dbProperty = new SimpleObjectProperty<>(this, "graph"); scanDirectory(DEFAULT_DB_PATH); list.setItems(items); list.getSelectionModel().select(getDBPath()); list.getSelectionModel().selectedItemProperty().addListener((obj, oldV, newV) -> { deleteButton.setDisable(true); if (newV != selectDB) { deleteButton.setDisable(false); } dbload.setDatabase(newV); }); }
Source:
<code>public void work() { LOG.debug("[Agent Loop] Trying to retrieve work."); <START> if (pluginJarLocationMonitor.getLastRun() > 0) { <END> retrieveCookieIfNecessary(); retrieveWork(); LOG.debug("[Agent Loop] Successfully retrieved work."); } else { LOG.debug("[Agent Loop] PluginLocationMonitor has not yet run. Not retrieving work since plugins may not be initialized."); } }</code><technical_language>wrap a [CountDownLatch](<LINK_0> instead</technical_language>

Target:
public void work() { LOG.debug("[Agent Loop] Trying to retrieve work."); if (pluginJarLocationMonitor.hasRunAtLeastOnce()) { retrieveCookieIfNecessary(); retrieveWork(); LOG.debug("[Agent Loop] Successfully retrieved work."); } else { LOG.debug("[Agent Loop] PluginLocationMonitor has not yet run. Not retrieving work since plugins may not be initialized."); } }
Source:
<code>public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null && source.getSourceId() != null) { Permanent sourceObject = (Permanent) source.getSourceObjectIfItStillExists(game); TargetCardInGraveyard target = new TargetCardInGraveyard(filter); target.setNotTarget(true); if (target.canChoose(source.getSourceId(), controller.getId(), game) && controller.chooseUse(outcome, "Exile a creature card from a graveyard?", source, game)) { if (controller.choose(Outcome.Exile, target, source.getId(), game)) { Card cardChosen = game.getCard(target.getFirstTarget()); if (cardChosen != null) { <START> controller.moveCardToExileWithInfo(cardChosen, null, "", source.getSourceId(), game, Zone.GRAVEYARD, true); <END> if (sourceObject != null) { sourceObject.getCounters(game).addCounter(CounterType.P1P1.createInstance()); game.informPlayers(controller.getLogName() + " puts a +1/+1 counter on " + sourceObject.getName()); } } } else if (sourceObject != null) { sourceObject.tap(game); } } else if (sourceObject != null) { sourceObject.tap(game); } return true; } return false; }</code><technical_language>controller.moveCards( ...) here</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null && source.getSourceId() != null) { Permanent sourceObject = (Permanent) source.getSourceObjectIfItStillExists(game); TargetCardInGraveyard target = new TargetCardInGraveyard(filter); target.setNotTarget(true); if (target.canChoose(source.getSourceId(), controller.getId(), game) && controller.chooseUse(outcome, "Exile a creature card from a graveyard?", source, game)) { if (controller.choose(Outcome.Exile, target, source.getId(), game)) { Card cardChosen = game.getCard(target.getFirstTarget()); if (cardChosen != null) { controller.moveCardsToExile(cardChosen, source, game, true, null, ""); if (sourceObject != null) { sourceObject.getCounters(game).addCounter(CounterType.P1P1.createInstance()); game.informPlayers(controller.getLogName() + " puts a +1/+1 counter on " + sourceObject.getLogName()); } } } else if (sourceObject != null) { sourceObject.tap(game); } } else if (sourceObject != null) { sourceObject.tap(game); } return true; } return false; }
Source:
<code>public T deleteHostedVersion(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Entry to modify.", required = true) @PathParam("entryId") Long entryId, @ApiParam(value = "version", required = true) @QueryParam("version") String version) { T entry = getEntryDAO().findById(entryId); checkEntry(entry); checkUserCanUpdate(user, entry); checkHosted(entry); if (entry.getActualDefaultVersion().getName().equals(version)) { <START> entry.setActualDefaultVersion(null); <END> } entry.getWorkflowVersions().removeIf(v -> Objects.equals(v.getName(), version)); PublicStateManager.getInstance().handleIndexUpdate(entry, StateManagerMode.UPDATE); return entry; }</code><technical_language>Thinking choose newest version setting default version (in case is left)</technical_language>

Target:
public T deleteHostedVersion(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Entry to modify.", required = true) @PathParam("entryId") Long entryId, @ApiParam(value = "version", required = true) @QueryParam("version") String version) { T entry = getEntryDAO().findById(entryId); checkEntry(entry); checkUserCanUpdate(user, entry); checkHosted(entry); if (entry.getActualDefaultVersion().getName().equals(version)) { Optional<U> max = entry.getWorkflowVersions().stream().filter(v -> !Objects.equals(v.getName(), version)) .max(Comparator.comparingLong(ver -> ver.getDate().getTime())); entry.setActualDefaultVersion(max.orElse(null)); } entry.getWorkflowVersions().removeIf(v -> Objects.equals(v.getName(), version)); PublicStateManager.getInstance().handleIndexUpdate(entry, StateManagerMode.UPDATE); return entry; }
Source:
<code>public Map<String, SuggestedQuantity> getSuggestedQuantities(List<Pool> pools, Consumer c, Date date) { JsonJsContext args = new JsonJsContext(mapper); Stream<PoolDTO> poolStream = pools == null ? Stream.empty() : pools.stream().map(this.translator.getStreamMapper(Pool.class, PoolDTO.class)); Stream<EntitlementDTO> entStream = c.getEntitlements() == null ? Stream.empty() : c.getEntitlements().stream() .filter(ent -> ent.isValidOnDate(date)) .map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class)); Stream<GuestIdDTO> guestIdStream = c.getGuestIds() == null ? Stream.empty() : c.getGuestIds().stream() .map(this.translator.getStreamMapper(GuestId.class, GuestIdDTO.class)); args.put("pools", poolStream.collect(Collectors.toSet())); args.put("consumer", this.translator.translate(c, ConsumerDTO.class)); args.put("validEntitlements", entStream.collect(Collectors.toSet())); args.put("log", log, false); <START> args.put("guestIds", guestIdStream.collect(Collectors.toList())); <END> String json = jsRules.runJsFunction(String.class, "get_suggested_quantities", args); Map<String, SuggestedQuantity> resultMap; TypeReference<Map<String, SuggestedQuantity>> typeref = new TypeReference<Map<String, SuggestedQuantity>>() {}; try { resultMap = mapper.toObject(json, typeref); } catch (Exception e) { throw new RuleExecutionException(e); } return resultMap; }</code><technical_language>Stream</technical_language>

Target:
public Map<String, SuggestedQuantity> getSuggestedQuantities(List<Pool> pools, Consumer c, Date date) { JsonJsContext args = new JsonJsContext(mapper); Stream<PoolDTO> poolStream = pools == null ? Stream.empty() : pools.stream().map(this.translator.getStreamMapper(Pool.class, PoolDTO.class)); Stream<EntitlementDTO> entStream = c.getEntitlements() == null ? Stream.empty() : c.getEntitlements().stream() .filter(ent -> ent.isValidOnDate(date)) .map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class)); Stream<GuestIdDTO> guestIdStream = c.getGuestIds() == null ? Stream.empty() : c.getGuestIds().stream() .map(this.translator.getStreamMapper(GuestId.class, GuestIdDTO.class)); args.put("pools", poolStream); args.put("consumer", this.translator.translate(c, ConsumerDTO.class)); args.put("validEntitlements", entStream); args.put("log", log, false); args.put("guestIds", guestIdStream); String json = jsRules.runJsFunction(String.class, "get_suggested_quantities", args); Map<String, SuggestedQuantity> resultMap; TypeReference<Map<String, SuggestedQuantity>> typeref = new TypeReference<Map<String, SuggestedQuantity>>() {}; try { resultMap = mapper.toObject(json, typeref); } catch (Exception e) { throw new RuleExecutionException(e); } return resultMap; }
Source:
<code>protected String getRoutingLookupKey() { return super.getConnectionFactory() instanceof RoutingConnectionFactory ? (this.lookupKeyQualifier + this.queues.stream() .map(q -> q.getName()) .collect(Collectors.toList()) .toString() <START> .replaceAll(" ", "")) <END> : null; }</code><technical_language>Collectors.joining(",") instead</technical_language>

Target:
protected String getRoutingLookupKey() { return super.getConnectionFactory() instanceof RoutingConnectionFactory ? this.lookupKeyQualifier + "[" + this.queues.stream() .map(q -> q.getName()) .collect(Collectors.joining(",")) + "]" : null; }
Source:
<code>Mono<Response<Document>> getDocumentWithResponse(String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { try { return restClient.documents() .getWithRestResponseAsync(key, selectedFields, requestOptions, context) .map(res -> { <START> Document doc = new Document(res.getValue()); <END> DocumentResponseConversions.cleanupDocument(doc); return new SimpleResponse<>(res, doc); }) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } }</code><technical_language>this copy entire map</technical_language>

Target:
Mono<Response<SearchDocument>> getDocumentWithResponse(String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { try { return restClient.documents() .getWithRestResponseAsync(key, selectedFields, requestOptions, context) .map(res -> { SearchDocument doc = new SearchDocument(res.getValue()); DocumentResponseConversions.cleanupDocument(doc); return new SimpleResponse<>(res, doc); }) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
<code>public void setProvider_shouldNotSetProviderIfGivenProviderIsNull() throws Exception { RadiologyReport report = new RadiologyReport(radiologyOrder); <START> try { <END> report.setProvider(null); } catch (IllegalArgumentException e) { assertThat(report.getProvider(), is(provider1)); } }</code><technical_language>please change style <LINK_0></technical_language>

Target:
public void setProvider_shouldNotSetProviderIfGivenProviderIsNull() throws Exception { RadiologyReport report = new RadiologyReport(radiologyOrder); try { report.setPrincipalResultsInterpreter(null); } catch (IllegalArgumentException e) { assertThat(report.getPrincipalResultsInterpreter(), is(provider1)); } }
Source:
<code>private CompletableFuture<HermesResponse> sendOnce(HermesMessage message) { long startTime = System.nanoTime(); return sender.send(URI.create(uri + message.getTopic()), message) .exceptionally(e -> HermesResponseBuilder.hermesFailureResponse(e, message)) <START> .whenComplete((resp, cause) -> messageDeliveryListeners.forEach(l -> l.onSend(resp, System.nanoTime() - startTime))); <END> }</code><technical_language>I if a problem listener get a bit time</technical_language>

Target:
private CompletableFuture<HermesResponse> sendOnce(HermesMessage message) { long startTime = System.nanoTime(); return sender.send(URI.create(uri + message.getTopic()), message) .exceptionally(e -> HermesResponseBuilder.hermesFailureResponse(e, message)) .whenComplete((resp, cause) -> { long latency = System.nanoTime() - startTime; messageDeliveryListeners.forEach(l -> l.onSend(resp, latency)); }); }