auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Set<String> getCategories() { DocumentList docs = this.getAllCategoriesFromPublishedPosts(); Set<String> result = new HashSet<String>(); for (Map<String, Object> document : docs) { <START> String[] categories = DBUtil.toStringArray(document.get("categories")); <END> Collections.addAll(result, categories); } return result; }</code><technical_language>reference crawler attribute instead of a hard coded string value: Crawler.Attributes.CATEGORIES</technical_language>

Target:
public Set<String> getCategories() { DocumentList docs = this.getAllCategoriesFromPublishedPosts(); Set<String> result = new HashSet<String>(); for (Map<String, Object> document : docs) { String[] categories = DBUtil.toStringArray(document.get(Crawler.Attributes.CATEGORIES)); Collections.addAll(result, categories); } return result; }
Source:
<code>private ZapMenuItem getMenuImportLocalGraphQl() { if (menuImportLocalGraphQl == null) { menuImportLocalGraphQl = new ZapMenuItem("graphql.topmenu.import.importgraphql"); menuImportLocalGraphQl.setToolTipText( Constant.messages.getString("graphql.topmenu.import.importgraphql.tooltip")); menuImportLocalGraphQl.addActionListener( e -> new ImportFromFileDialog( <START> View.getSingleton().getMainFrame(), ExtensionGraphQl.this)); <END> } return menuImportLocalGraphQl; }</code><technical_language>I this simply this instead of Class.this? (Same below)</technical_language>

Target:
private ZapMenuItem getMenuImportLocalGraphQl() { if (menuImportLocalGraphQl == null) { menuImportLocalGraphQl = new ZapMenuItem("graphql.topmenu.import.importgraphql"); menuImportLocalGraphQl.setToolTipText( Constant.messages.getString("graphql.topmenu.import.importgraphql.tooltip")); menuImportLocalGraphQl.addActionListener( e -> new ImportFromFileDialog(View.getSingleton().getMainFrame(), this)); } return menuImportLocalGraphQl; }
Source:
<code>public void doOperation(int operation) { if (operation == QUICK_OUTLINE && outlinePresenter != null) { outlinePresenter.showInformation(); return; } <START> Runnable toRevert = null; try { switch (operation) { case PASTE: if (preprocessor != null) { Clipboard clipboard = new Clipboard(getControlDisplay()); toRevert = preprocessor.prepareClipboard(clipboard); } break; } super.doOperation(operation); } finally { if (toRevert != null) { toRevert.run(); } } <END> }</code><technical_language>This try/finally pattern is awkward prone error. code is hard read - API clients repeat this. sense do do this instead? if (operation == PASTE) { createPastePreprocessor().preprocess(clipboard -> doOperation(operation)); }</technical_language>

Target:
public void doOperation(int operation) { if (operation == QUICK_OUTLINE && outlinePresenter != null) { outlinePresenter.showInformation(); return; } Runnable toRevert = null; try { switch (operation) { case PASTE: if (preprocessor != null) { Clipboard clipboard = new Clipboard(getControl().getDisplay()); toRevert = preprocessor.prepareClipboard(clipboard); } break; } super.doOperation(operation); } finally { if (toRevert != null) { toRevert.run(); } } }
Source:
<code>public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { ColumnExpression columnExp = (ColumnExpression)exps.get(0); LiteralExpression isAscendingExpression = (LiteralExpression)exps.get(1); boolean isAscending = (Boolean)isAscendingExpression.getValue(); LiteralExpression valueExp = (LiteralExpression)exps.get(2); <START> NavigableMap<ImmutableBytesPtr, Integer> sortedMap = new TreeMap<ImmutableBytesPtr, Integer>(valueVsCount); <END> if (!isAscending) { sortedMap = sortedMap.descendingMap(); } long distinctCountsSum = 0; for (Entry<ImmutableBytesPtr, Integer> entry : sortedMap.entrySet()) { Object value = valueExp.getValue(); Object colValue = columnExp.getDataType().toObject(entry.getKey()); int compareResult = columnExp.getDataType().compareTo(colValue, value, valueExp.getDataType()); boolean done = isAscending ? compareResult > 0 : compareResult <= 0; if (done) break; distinctCountsSum += entry.getValue(); } float result = (float)distinctCountsSum / totalCount; this.cachedResult = new BigDecimal(result); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(this.cachedResult); ptr.set(buffer); return true; }</code><technical_language>create a new map here? pretty heavy-weight. allocating a Map.Entry<ImmutableBytesPtr, Integer> valueVsCount.size()], sorting Arrays.sort, iterating doing</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { ColumnExpression columnExp = (ColumnExpression)exps.get(0); LiteralExpression isAscendingExpression = (LiteralExpression)exps.get(1); boolean isAscending = (Boolean)isAscendingExpression.getValue(); LiteralExpression valueExp = (LiteralExpression)exps.get(2); Entry<ImmutableBytesPtr, Integer>[] entries = getSortedValueVsCount(isAscending); long distinctCountsSum = 0; for (Entry<ImmutableBytesPtr, Integer> entry : entries) { Object value = valueExp.getValue(); Object colValue = columnExp.getDataType().toObject(entry.getKey()); int compareResult = columnExp.getDataType().compareTo(colValue, value, valueExp.getDataType()); boolean done = isAscending ? compareResult > 0 : compareResult <= 0; if (done) break; distinctCountsSum += entry.getValue(); } float result = (float)distinctCountsSum / totalCount; this.cachedResult = new BigDecimal(result); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(this.cachedResult); ptr.set(buffer); return true; }
Source:
<code>public void updateCheckedState(TreeItem item) { Object element = item.getData(); if (element instanceof IBreakpoint) { try { item.setChecked(((IBreakpoint) element).isEnabled()); refreshItem(item); } catch (CoreException e) { DebugUIPlugin.log(e); } } else if (element instanceof IBreakpointContainer) { IBreakpoint[] breakpoints = ((IBreakpointContainer) element).getBreakpoints(); int enabledChildren= 0; for (IBreakpoint breakpoint : breakpoints) { try { if (breakpoint.isEnabled()) { enabledChildren++; } } catch (CoreException e) { DebugUIPlugin.log(e); } } if (enabledChildren == 0) { item.setGrayed(false); item.setChecked(false); } else if (enabledChildren == breakpoints.length) { item.setGrayed(false); item.setChecked(true); } else { item.setGrayed(true); item.setChecked(true); } for (TreeItem <START> item2 : <END> item.getItems()) { updateCheckedState(item2); } } }</code><technical_language>rename child childItem</technical_language>

Target:
public void updateCheckedState(TreeItem item) { Object element = item.getData(); if (element instanceof IBreakpoint) { try { item.setChecked(((IBreakpoint) element).isEnabled()); refreshItem(item); } catch (CoreException e) { DebugUIPlugin.log(e); } } else if (element instanceof IBreakpointContainer) { IBreakpoint[] breakpoints = ((IBreakpointContainer) element).getBreakpoints(); int enabledChildren= 0; for (IBreakpoint breakpoint : breakpoints) { try { if (breakpoint.isEnabled()) { enabledChildren++; } } catch (CoreException e) { DebugUIPlugin.log(e); } } if (enabledChildren == 0) { item.setGrayed(false); item.setChecked(false); } else if (enabledChildren == breakpoints.length) { item.setGrayed(false); item.setChecked(true); } else { item.setGrayed(true); item.setChecked(true); } for (TreeItem childItem : item.getItems()) { updateCheckedState(childItem); } } }
Source:
<code>public void negativeTests(final IlluminaFileUtil.SupportedIlluminaFormat[] formats, final IlluminaDataType[] dataTypes, final List<String> filesToDelete, final List<String> filesToEmpty, final int lane, final List<Integer> tiles, final int[] cycles, final String readStructure, final int expectedNumErrors, final List<Integer> filterTiles, final boolean makeFakeFiles) { makeFiles(formats, lane, tiles, cycles); IlluminaFileUtilTest.deleteRelativeFiles(intensityDir, filesToDelete); IlluminaFileUtilTest.emptyRelativeFiles(intensityDir, filesToEmpty); writeTileMetricsOutFile(makeMap(makeList(lane - 1, lane + 1, lane), makeList(makeList(1, 2, 3), tiles, tiles))); final String[] args = makeCheckerArgs(basecallDir, lane, readStructure, dataTypes, filterTiles, makeFakeFiles, false); final int returnCode = runPicardCommandLine(args); Assert.assertEquals(returnCode, 1); try { final int numErrors = Integer.parseInt(new String(Files.readAllBytes(Paths.get("./errors.count")))); Assert.assertEquals(numErrors, expectedNumErrors); <START> Files.deleteIfExists(Paths.get("./errors.count")); <END> } catch (IOException e) { Assert.fail("Could not read the number of errors from file", e); } if (makeFakeFiles) { Assert.assertEquals(runPicardCommandLine(args), 0); } }</code><technical_language>save duplicate Paths.get a local var</technical_language>

Target:
public void negativeTests(final IlluminaFileUtil.SupportedIlluminaFormat[] formats, final IlluminaDataType[] dataTypes, final List<String> filesToDelete, final List<String> filesToEmpty, final int lane, final List<Integer> tiles, final int[] cycles, final String readStructure, final int expectedNumErrors, final List<Integer> filterTiles, final boolean makeFakeFiles) { makeFiles(formats, lane, tiles, cycles); IlluminaFileUtilTest.deleteRelativeFiles(intensityDir, filesToDelete); IlluminaFileUtilTest.emptyRelativeFiles(intensityDir, filesToEmpty); writeTileMetricsOutFile(makeMap(makeList(lane - 1, lane + 1, lane), makeList(makeList(1, 2, 3), tiles, tiles))); final String[] args = makeCheckerArgs(basecallDir, lane, readStructure, dataTypes, filterTiles, makeFakeFiles, false); final int returnCode = runPicardCommandLine(args); Assert.assertEquals(returnCode, 1); try { final Path errorPath = Paths.get("./errors.count"); final int numErrors = Integer.parseInt(new String(Files.readAllBytes(errorPath))); Assert.assertEquals(numErrors, expectedNumErrors); Files.deleteIfExists(errorPath); } catch (IOException e) { Assert.fail("Could not read the number of errors from file", e); } if (makeFakeFiles) { Assert.assertEquals(runPicardCommandLine(args), 0); } }
Source:
<code>public WorkflowItemRest upload(HttpServletRequest request, String apiCategory, String model, Integer id, MultipartFile file) throws Exception { Context context = obtainContext(); WorkflowItemRest wsi = findOne(id); XmlWorkflowItem source = wis.find(context, id); List<ErrorRest> errors = new ArrayList<ErrorRest>(); SubmissionConfig submissionConfig = submissionConfigReader.getSubmissionConfigByName(wsi.getSubmissionDefinition().getName()); for (int i = 0; i < submissionConfig.getNumberOfSteps(); i++) { SubmissionStepConfig stepConfig = submissionConfig.getStep(i); ClassLoader loader = this.getClass().getClassLoader(); Class stepClass; try { stepClass = loader.loadClass(stepConfig.getProcessingClassName()); Object stepInstance = stepClass.newInstance(); if (UploadableStep.class.isAssignableFrom(stepClass)) { UploadableStep uploadableStep = (UploadableStep) stepInstance; uploadableStep.doPreProcessing(context, source); ErrorRest err = uploadableStep.upload(context, submissionService, stepConfig, source, file); uploadableStep.doPostProcessing(context, source); if (err != null) { errors.add(err); } } } catch (Exception e) { <START> log.error(e.getMessage(), e); <END> } } wsi = converter.convert(source); if (errors.isEmpty()) { wsi.setStatus(true); } else { wsi.setStatus(false); wsi.getErrors().addAll(errors); } context.commit(); return wsi; }</code><technical_language>Another area of catching error in a for loop. this method proceed if Exceptions thrown in upload? thrown user</technical_language>

Target:
public WorkflowItemRest upload(HttpServletRequest request, String apiCategory, String model, Integer id, MultipartFile file) throws Exception { Context context = obtainContext(); WorkflowItemRest wsi = findOne(id); XmlWorkflowItem source = wis.find(context, id); List<ErrorRest> errors = new ArrayList<ErrorRest>(); SubmissionConfig submissionConfig = submissionConfigReader.getSubmissionConfigByName(wsi.getSubmissionDefinition().getName()); for (int i = 0; i < submissionConfig.getNumberOfSteps(); i++) { SubmissionStepConfig stepConfig = submissionConfig.getStep(i); ClassLoader loader = this.getClass().getClassLoader(); Class stepClass; try { stepClass = loader.loadClass(stepConfig.getProcessingClassName()); Object stepInstance = stepClass.newInstance(); if (UploadableStep.class.isAssignableFrom(stepClass)) { UploadableStep uploadableStep = (UploadableStep) stepInstance; uploadableStep.doPreProcessing(context, source); ErrorRest err = uploadableStep.upload(context, submissionService, stepConfig, source, file); uploadableStep.doPostProcessing(context, source); if (err != null) { errors.add(err); } } } catch (Exception e) { log.error(e.getMessage(), e); } } wsi = converter.convert(source); if (!errors.isEmpty()) { wsi.getErrors().addAll(errors); } context.commit(); return wsi; }
Source:
<code>public static SSAInformation convert( AstMethod M, final AstIRFactory.AstIR ir, SSAOptions options, final IntSet values) { try { if (DEBUG) { System.err.println(("starting conversion for " + values)); System.err.println(ir); } if (DEBUG_UNDO) System.err.println((">>> starting " + ir.getMethod())); SSAConversion ssa = new SSAConversion(M, ir, options) { final int limit = ir.getSymbolTable().getMaxValueNumber(); @Override protected boolean skip(int i) { return (i >= 0) && (i <= limit) && (!values.contains(i)); } }; ssa.perform(); if (DEBUG_UNDO) System.err.println(("<<< done " + ir.getMethod())); return ssa.getComputedLocalMap(); <START> } catch (RuntimeException | Error e) { <END> throw e; } }</code><technical_language>delete this try-catch? re-throwing</technical_language>

Target:
public static SSAInformation convert( AstMethod M, final AstIRFactory.AstIR ir, SSAOptions options, final IntSet values) { if (DEBUG) { System.err.println(("starting conversion for " + values)); System.err.println(ir); } if (DEBUG_UNDO) System.err.println((">>> starting " + ir.getMethod())); SSAConversion ssa = new SSAConversion(M, ir, options) { final int limit = ir.getSymbolTable().getMaxValueNumber(); @Override protected boolean skip(int i) { return (i >= 0) && (i <= limit) && (!values.contains(i)); } }; ssa.perform(); if (DEBUG_UNDO) System.err.println(("<<< done " + ir.getMethod())); return ssa.getComputedLocalMap(); }
Source:
<code>public void execute() throws MetaClassNotFoundException, FeatureNotFoundException { Session session = null; if (objectToDelete instanceof DSemanticDecorator) { session = SessionManager.INSTANCE.getSession(((DSemanticDecorator) objectToDelete).getTarget()); } else { session = SessionManager.INSTANCE.getSession(objectToDelete); } ECrossReferenceAdapter semanticCrossReferencer = null; if (session != null) { semanticCrossReferencer = session.getSemanticCrossReferencer(); } <START> accessor.eDelete(objectToDelete, semanticCrossReferencer); <END> }</code><technical_language>org.eclipse.sirius.ecore.extender.business.api.accessor.ModelAccessor.eDelete(EObject, ECrossReferenceAdapter, Predicate<EReference>, boolean) org.eclipse.sirius.ecore.extender.business.internal.accessor.ecore.EcoreIntrinsicExtender.eDelete(EObject, ECrossReferenceAdapter, Predicate<EReference>) predicate, previously reference removed</technical_language>

Target:
public void execute() throws MetaClassNotFoundException, FeatureNotFoundException { Session session = null; if (objectToDelete instanceof DSemanticDecorator) { session = SessionManager.INSTANCE.getSession(((DSemanticDecorator) objectToDelete).getTarget()); } else { session = SessionManager.INSTANCE.getSession(objectToDelete); } ECrossReferenceAdapter semanticCrossReferencer = null; if (session != null) { semanticCrossReferencer = session.getSemanticCrossReferencer(); } accessor.eDelete(objectToDelete, semanticCrossReferencer, danglingEReferencesToIgnores); }
Source:
<code>static public void init(int maxPhraseLength, String path, boolean flatgazetteers) throws IOException { <START> if(gazetteers_map.containsKey(path)) { <END> gazetteers = gazetteers_map.get(path); } else { synchronized (GAZ_INIT_LOCK) { if (flatgazetteers) { gazetteers = new FlatGazetteers(path); } else { gazetteers = new TreeGazetteers(maxPhraseLength, path); } } gazetteers_map.put(path, gazetteers); } }</code><technical_language>change this? @cowchipkid problems this</technical_language>

Target:
static public void init(int maxPhraseLength, String path, boolean flatgazetteers) throws IOException { synchronized (GAZ_INIT_LOCK) { if (flatgazetteers) { if (!gazetteers_map.containsKey(path) || gazetteers_map.get(path) instanceof TreeGazetteers) { gazetteers_map.put(path, new FlatGazetteers(path)); } } else { if (!gazetteers_map.containsKey(path) || gazetteers_map.get(path) instanceof FlatGazetteers) { gazetteers_map.put(path, new TreeGazetteers(maxPhraseLength, path)); } } gazetteers = gazetteers_map.get(path); } }
Source:
<code>private void initColumns(int widthHint, int treeWidgetWidth, String[] visibleColumnIds) { for (TreeColumn <START> treeColumn : <END> getTree().getColumns()) { Object colData = treeColumn.getData(); String columnId = colData instanceof String ? (String) colData : null; Integer width = fColumnSizes.get(colData); if (width == null) { int ans = getInitialColumnWidth(columnId, treeWidgetWidth, visibleColumnIds); if (ans == -1) { treeColumn.setWidth(widthHint); } else { treeColumn.setWidth(ans); } } else { treeColumn.setWidth(width.intValue()); } treeColumn.addControlListener(fListener); } }</code><technical_language>rename column</technical_language>

Target:
private void initColumns(int widthHint, int treeWidgetWidth, String[] visibleColumnIds) { for (TreeColumn column : getTree().getColumns()) { Object colData = column.getData(); String columnId = colData instanceof String ? (String) colData : null; Integer width = fColumnSizes.get(colData); if (width == null) { int ans = getInitialColumnWidth(columnId, treeWidgetWidth, visibleColumnIds); if (ans == -1) { column.setWidth(widthHint); } else { column.setWidth(ans); } } else { column.setWidth(width.intValue()); } column.addControlListener(fListener); } }
Source:
<code>public void accept() { <START> if (m_eos.get()) <END> return; AtomicBoolean workerInService = new AtomicBoolean(false); while (shouldRun()) { if (!workerInService.get() && !m_eos.get()) { try { KinesisClientLibConfiguration kclConfig = new KinesisClientLibConfiguration(m_config.getAppName(), m_config.getStreamName(), credentials(), UUID.randomUUID().toString()); kclConfig.withRegionName(m_config.getRegion()).withMaxRecords(m_config.getMaxReadBatchSize()) .withInitialPositionInStream(InitialPositionInStream.TRIM_HORIZON) .withIdleTimeBetweenReadsInMillis(m_config.getIdleTimeBetweenReads()) .withTaskBackoffTimeMillis(m_config.getTaskBackoffTimeMillis()).withKinesisClientConfig( KinesisStreamImporterConfig.getClientConfigWithUserAgent(m_config.getAppName())); m_worker = new Worker.Builder().recordProcessorFactory(new RecordProcessorFactory()) .config(kclConfig).build(); info(null, "Starting worker for Kinesis stream %s", m_config.getStreamName()); workerInService.compareAndSet(false, true); m_worker.run(); } catch (Exception e) { rateLimitedLog(Level.ERROR, e, "Error in Kinesis stream importer %s", m_config.getResourceID()); if (null != m_worker) m_worker.shutdown(); if (shouldRun()) { backoffSleep(3); workerInService.compareAndSet(true, false); } } } } m_eos.compareAndSet(false, true); info(null, "The importer stops: %s", m_config.getResourceID().toString()); }</code><technical_language>Do need this? Is accept called for URI while shutdown</technical_language>

Target:
public void accept() { info(null, "Starting data stream fetcher for " + m_config.getResourceID().toString()); try { KinesisClientLibConfiguration kclConfig = new KinesisClientLibConfiguration(m_config.getAppName(), m_config.getStreamName(), credentials(), UUID.randomUUID().toString()); kclConfig.withRegionName(m_config.getRegion()).withMaxRecords((int) m_config.getMaxReadBatchSize()) .withInitialPositionInStream(InitialPositionInStream.TRIM_HORIZON) .withIdleTimeBetweenReadsInMillis(m_config.getIdleTimeBetweenReads()) .withTaskBackoffTimeMillis(m_config.getTaskBackoffTimeMillis()).withKinesisClientConfig( KinesisStreamImporterConfig.getClientConfigWithUserAgent(m_config.getAppName())); m_worker = new Worker.Builder().recordProcessorFactory(new RecordProcessorFactory()).config(kclConfig) .build(); m_worker.run(); } catch (RuntimeException e) { rateLimitedLog(Level.ERROR, e, "Error in Kinesis stream importer %s", m_config.getResourceID()); if (null != m_worker) m_worker.shutdown(); } info(null, "Data stream fetcher stopped for %s. Callback Rcvd: %d. Submitted: %d", m_config.getResourceID().toString(), m_cbcnt.get(), m_submitCount.get()); }
Source:
<code>public void onCreate() { super.onCreate(); TwitterAuthConfig authConfig = new TwitterAuthConfig(BuildConfig.TWITTER_API_KEY, BuildConfig.TWITTER_API_SECRET); <START> Fabric.with(this, new Crashlytics(), new Twitter(authConfig)); <END> LoggerStarter.start(this); graph = ObjectGraph.create(Modules.list(this)); }</code><technical_language>I some concerns this. 1. this crashlytics run in debug mode well? Crashlytics "ignore" in debug, want reported. in if...else in LoggerStarter. 2. reason for crash logging initialized in LoggerStarter is b/c if content provider is accessed a Context is (like if export data), Application get launched crashes get reported us. LoggerStarter is initialized in content provider, circumvents this limitation. 3. this create a Twitter singleton for lifetime of app? If so, a waste of memory for login stuff for vendors twitter</technical_language>

Target:
public void onCreate() { super.onCreate(); LoggerStarter.start(this); graph = ObjectGraph.create(Modules.list(this)); }
Source:
<code>public void shouldMapMeasurementToDefinedMeasurementNameAndRegex() { Map<String, String> measurementMappings = new HashMap<String, String>(); measurementMappings.put("resources", ".*resources.*"); InfluxDbReporter filteredReporter = InfluxDbReporter .forRegistry(registry) .measurementMappings(measurementMappings) .build(influxDb); filteredReporter.report( this.<Gauge>map(), this.<Counter>map(), this.<Histogram>map(), this.map("com.example.resources.RandomResource", mock(Meter.class)), this.<Timer>map() ); final ArgumentCaptor<InfluxDbPoint> influxDbPointCaptor = ArgumentCaptor.forClass(InfluxDbPoint.class); Mockito.verify(influxDb, atLeastOnce()).appendPoints(influxDbPointCaptor.capture()); InfluxDbPoint point = influxDbPointCaptor.getValue(); <START> assertThat(point.getMeasurement()).isEqualTo("resources"); <END> }</code><technical_language>cool, check tagged too! e.g. metricName=com.example.resources.RandomResource</technical_language>

Target:
public void shouldMapMeasurementToDefinedMeasurementNameAndRegex() { Map<String, String> measurementMappings = new HashMap<String, String>(); measurementMappings.put("resources", ".*resources.*"); final InfluxDbReporter reporter = InfluxDbReporter .forRegistry(registry) .measurementMappings(measurementMappings) .build(influxDb); reporter.report( this.<Gauge>map(), this.<Counter>map(), this.<Histogram>map(), this.map("com.example.resources.RandomResource", mock(Meter.class)), this.<Timer>map() ); final ArgumentCaptor<InfluxDbPoint> influxDbPointCaptor = ArgumentCaptor.forClass(InfluxDbPoint.class); Mockito.verify(influxDb, atLeastOnce()).appendPoints(influxDbPointCaptor.capture()); InfluxDbPoint point = influxDbPointCaptor.getValue(); assertThat(point.getMeasurement()).isEqualTo("resources"); assertThat(point.getTags()).containsEntry("metricName", "com.example.resources.RandomResource"); }
Source:
<code>public static void bind(final String propName, StringProperty stringProp) { if(props == null) { return; } String storedValue = props.getProperty(propName); if(storedValue != null) { stringProp.set(storedValue); } stringProp.addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> o, String oldValue, String newValue) { props.setProperty(propName, newValue); store(); <START> <END> }}); }</code><technical_language>This delayed write mechanism exists properties change bound preferences. For example bind width of table columns split panes. user drags a table column width property updates rapidly update a file write happen UX thread bad</technical_language>

Target:
public static void bind(final String propName, StringProperty stringProp) { if(props == null) { return; } String storedValue = props.getProperty(propName); if(storedValue != null) { stringProp.set(storedValue); } stringProp.addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> o, String oldValue, String newValue) { props.setProperty(propName, newValue); timer.schedule(new TimerTask() { @Override public void run() { if(!awaitingStore) { Platform.runLater(PrefBind::store); awaitingStore = true; } }}, 1000); }}); }
Source:
<code>private static Iterable<String> head(final Response origin, final int status, final CharSequence reason) throws IOException { if (status < 100 || status > 999) { throw new IllegalArgumentException( String.format( "according to RFC 7230 HTTP status code must have three digits: %d", status ) ); } return new Concat<String>( Collections.singletonList( String.format("HTTP/1.1 %d %s", status, reason) ), new Filtered<String>( <START> item -> { <END> return !item.startsWith("HTTP/"); }, origin.head() ) ); }</code><technical_language>@paulodamaso braces return needed</technical_language>

Target:
private static Iterable<String> head(final Response origin, final int status, final CharSequence reason) throws IOException { if (status < 100 || status > 999) { throw new IllegalArgumentException( String.format( "according to RFC 7230 HTTP status code must have three digits: %d", status ) ); } return new Concat<String>( Collections.singletonList( String.format("HTTP/1.1 %d %s", status, reason) ), new Filtered<String>( item -> !item.startsWith("HTTP/"), origin.head() ) ); }
Source:
<code><START> public IndexGeneratorJob( <END> HadoopDruidIndexerConfig config ) { this.config = config; }</code><technical_language>Do need remove this? I idea this exposed users, useful. If this removed, code computing INVALID_ROW_COUNTER in HadoopDruidIndexerMapper removed well</technical_language>

Target:
public IndexGeneratorJob( HadoopDruidIndexerConfig config ) { this.config = config; this.jobStats = new IndexGeneratorStats(); }
Source:
<code>private void writeAndFlushNextMessageIfPossible(final Channel channel) throws IOException { if (fatalError || !channel.isWritable()) { return; } BufferAndAvailability next = null; try { while (true) { NetworkSequenceViewReader reader = pollAvailableReader(); if (reader == null) { return; } next = reader.getNextBuffer(); if (next == null) { if (!reader.isReleased()) { continue; } Throwable cause = reader.getFailureCause(); if (cause != null) { ErrorResponse msg = new ErrorResponse( new ProducerFailedException(cause), reader.getReceiverId()); ctx.writeAndFlush(msg); } } else { if (next.moreAvailable()) { registerAvailableReader(reader); } Object msg; <START> if (next.buffer() != null) { <END> msg = new BufferResponse( next.buffer(), reader.getSequenceNumber(), reader.getReceiverId(), next.backlog()); } else { msg = new NettyMessage.AddBacklog(next.backlog(), reader.getReceiverId()); } channel.writeAndFlush(msg).addListener(writeListener); return; } } } catch (Throwable t) { if (next != null) { next.buffer().recycleBuffer(); } throw new IOException(t.getMessage(), t); } }</code><technical_language>message path is distinguished in PartitionRequestQueue CreditBasedSequenceNumberingViewReader now. improve judge in place instead. 1. Introduce ServerOutboundMessage class extend NettyMessage AddBacklog BufferResponse extend ServerOutboundMessage. 2. Introduce NetworkSequenceViewReader#getNextMessage instead of existing NetworkSequenceViewReader#getNextBuffer. CreditBasedSequenceNumberingViewReader implementation, judge condition for distinguish. public NettyMessage.ServerOutboundMessage getNextMessage() throws IOException { if (numCreditsAvailable == 0 && initialCredit == 0 && !subpartitionView.isAvailable(numCreditsAvailable)) { return getBacklogMessage(); } else { return getNextBufferResponse(); } } do reduce necessary transformation BufferAndAvailability BufferResponse</technical_language>

Target:
private void writeAndFlushNextMessageIfPossible(final Channel channel) throws IOException { if (fatalError || !channel.isWritable()) { return; } ServerOutboundMessage next = null; try { while (true) { NetworkSequenceViewReader reader = pollAvailableReader(); if (reader == null) { return; } next = reader.getNextMessage(); if (next == null) { if (!reader.isReleased()) { continue; } Throwable cause = reader.getFailureCause(); if (cause != null) { ErrorResponse msg = new ErrorResponse( new ProducerFailedException(cause), reader.getReceiverId()); ctx.writeAndFlush(msg); } } else { if (next.isMoreAvailable()) { registerAvailableReader(reader); } channel.writeAndFlush(next.build()).addListener(writeListener); return; } } } catch (Throwable t) { if (next != null) { next.recycle(); } throw new IOException(t.getMessage(), t); } }
Source:
<code>private static Object lockFor(Node node) { <START> return ExtensionList.lookupSingleton(WorkspaceLocatorImpl.class).nodeLocks.computeIfAbsent(node.getNodeName(), name -> new StringBuilder("WorkspaceLocatorImpl lock for ").append(name).toString()); <END> }</code><technical_language>this is safe leak for cloud agents unique node names</technical_language>

Target:
private static Object lockFor(Node node) { try { return ExtensionList.lookupSingleton(WorkspaceLocatorImpl.class).nodeLocks.get(node); } catch (ExecutionException x) { throw new AssertionError(x); } }
Source:
<code>public void beginTraining() { String trainingSetSource = "{training-set-SAS-URL}"; boolean useLabelFile = true; <START> formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile).subscribe( <END> recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); END: com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining#string-boolean }</code><technical_language>change code snippets to, making trainingFilesUrl, useTrainingLabels</technical_language>

Target:
public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; formTrainingAsyncClient.beginTraining(trainingFilesUrl, useTrainingLabels).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); END: com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining#string-boolean }
Source:
<code>public static String generateMatcher(final ImmutableList<Ds3EnumConstant> enumConstants) { final StringBuilder outputBuilder = new StringBuilder(); final int numConstants = enumConstants.size(); <START> if (numConstants > 0) { <END> for (int currentIndex = 0; currentIndex < numConstants; currentIndex++) { outputBuilder.append(CHelper.indent(1)); if (currentIndex > 0) { outputBuilder.append("} else "); } final String currentEnumName = enumConstants.get(currentIndex).getName(); outputBuilder.append("if (xmlStrcmp(text, (const xmlChar*) \""). append(currentEnumName). append("\") == 0) {").append(System.lineSeparator()); outputBuilder.append(indent(2)).append("return "). append(currentEnumName). append(";").append(System.lineSeparator()); } final String enumName = enumConstants.get(0).getName(); outputBuilder.append(indent(1)).append("} else {").append(System.lineSeparator()); outputBuilder.append(indent(2)).append("ds3_log_message(log, DS3_ERROR, \"ERROR: Unknown value of '%s'. Returning "). append(enumName). append(" for safety.").append(System.lineSeparator()); outputBuilder.append(indent(2)).append("return "). append(enumName). append(";").append(System.lineSeparator()); outputBuilder.append(indent(1)).append("}").append(System.lineSeparator()); return outputBuilder.toString(); } return ""; }</code><technical_language>Instead of putting this large block if statement, cleaner reverse it, have: if (numConstants <= 0) { return "": }</technical_language>

Target:
public static String generateMatcher(final ImmutableList<Ds3EnumConstant> enumConstants) { final StringBuilder outputBuilder = new StringBuilder(); final int numConstants = enumConstants.size(); if (numConstants <= 0) { return ""; } for (int currentIndex = 0; currentIndex < numConstants; currentIndex++) { outputBuilder.append(indent(1)); if (currentIndex > 0) { outputBuilder.append("} else "); } final String currentEnumName = enumConstants.get(currentIndex).getName(); outputBuilder.append("if (xmlStrcmp(text, (const xmlChar*) \""). append(currentEnumName). append("\") == 0) {").append(System.lineSeparator()); outputBuilder.append(indent(2)).append("return "). append(currentEnumName). append(";").append(System.lineSeparator()); } final String enumName = enumConstants.get(0).getName(); outputBuilder.append(indent(1)).append("} else {").append(System.lineSeparator()); outputBuilder.append(indent(2)).append("ds3_log_message(log, DS3_ERROR, \"ERROR: Unknown value of '%s'. Returning "). append(enumName). append(" for safety.").append(System.lineSeparator()); outputBuilder.append(indent(2)).append("return "). append(enumName). append(";").append(System.lineSeparator()); outputBuilder.append(indent(1)).append("}").append(System.lineSeparator()); return outputBuilder.toString(); }
Source:
<code>public WorkStateImpl(String name, List<? extends IAtsUser> assignees, double hoursSpent, int percentComplete) { this.name = name; <START> Conditions.checkNotNullOrContainNull(assignees, "assignees"); <END> this.assignees.addAll(assignees); this.hoursSpent = hoursSpent; this.percentComplete = percentComplete; }</code><technical_language>Throwing exception in a constructor is a bad idea. Instead, move condition check code constructing this object</technical_language>

Target:
public WorkStateImpl(String name, List<? extends IAtsUser> assignees, double hoursSpent, int percentComplete) { this.name = name; this.assignees.addAll(assignees); this.hoursSpent = hoursSpent; this.percentComplete = percentComplete; }
Source:
<code>private static String cleanName(Class<?> type) { String simpleName = type.getSimpleName(); <START> int $$idx = simpleName.indexOf("$$"); <END> if ($$idx > 0) { simpleName = simpleName.substring(0, $$idx); } return simpleName; }</code><technical_language>avoid dollar signs in variables names? This is a common practice</technical_language>

Target:
private static String cleanName(Class<?> type) { String simpleName = type.getSimpleName(); int doubleDollarIdx = simpleName.indexOf("$$"); if (doubleDollarIdx > 0) { simpleName = simpleName.substring(0, doubleDollarIdx); } return simpleName; }
Source:
<code>private void loadContent(Tip tip) { if (tip instanceof ISwtTip) { loadContentSWT(tip); } else if (tip instanceof IHtmlTip) { loadContentHtml((IHtmlTip) tip); } else if (tip instanceof IUrlTip) { loadContentUrl((IUrlTip) tip); } else { fTipManager.log(LogUtil.error(getClass(), Messages.TipComposite_12 + tip)); } <START> if (tip instanceof IBrowserFunctionProvider) { <END> Map<String, Function<Object[], Object>> browserFunctions = ((IBrowserFunctionProvider) tip) .getBrowserFunctions(); for (Entry<String, Function<Object[], Object>> bFunctionEntry : browserFunctions.entrySet()) { new BrowserFunction(getBrowser(), bFunctionEntry.getKey()) { @Override public Object function(Object[] arguments) { return bFunctionEntry.getValue().apply(arguments); } }; } } fContentComposite.requestLayout(); }</code><technical_language>Please move a separate method invoke for ISwtTip. Consider lambda instead of for loop</technical_language>

Target:
private void loadContent(Tip tip) { if (tip instanceof ISwtTip) { loadContentSWT(tip); } else if (tip instanceof IHtmlTip) { loadContentHtml((IHtmlTip) tip); applyBrowserFunctions(tip); } else if (tip instanceof IUrlTip) { loadContentUrl((IUrlTip) tip); applyBrowserFunctions(tip); } else { fTipManager.log(LogUtil.error(getClass(), Messages.TipComposite_12 + tip)); } fContentComposite.requestLayout(); }
Source:
<code>public void replaceAtHead(long key, Chain expect, Chain update) { <START> LongConsumer lambda = (k) -> segmentFor(k).replaceAtHead(k, expect, update); <END> try { lambda.accept(key); } catch (OversizeMappingException e) { consumeOversizeMappingException(key, lambda); } }</code><technical_language>This method left unchanged right</technical_language>

Target:
public void replaceAtHead(long key, Chain expect, Chain update) { try { segmentFor(key).replaceAtHead(key, expect, update); } catch (OversizeMappingException e) { consumeOversizeMappingException(key, (long k) -> segmentFor(k).replaceAtHead(k, expect, update)); } }
Source:
<code>private DataPublisher getDataPublisher() throws ConfigurationException { AgentHolder.setConfigPath(getDataAgentConfigPath()); String url = getUrl(); DataPublisher dataPublisher; try { dataPublisher = new DataPublisher(url, getUsername(), getPassword()); } catch (DataEndpointAgentConfigurationException | DataEndpointException | DataEndpointConfigurationException | DataEndpointAuthenticationException | TransportException e) { <START> throw new ConfigurationException("Configuring Data Endpoint Agent failed", e); <END> } return dataPublisher; }</code><technical_language>handle exceptions properly useful messages of exception. (This covered code review)</technical_language>

Target:
private DataPublisher getDataPublisher() throws ConfigurationException { AgentHolder.setConfigPath(getDataAgentConfigPath()); String url = getUrl(); DataPublisher dataPublisher; try { dataPublisher = new DataPublisher(url, getUsername(), getPassword()); } catch (DataEndpointAgentConfigurationException e) { LOG.error("Data Endpoint Agent configuration failed: " + e); throw new ConfigurationException("Data Endpoint Agent configuration failed: ", e); } catch (DataEndpointException e) { LOG.error("Communication with Data Endpoint failed: " + e); throw new ConfigurationException("Communication with Data Endpoint failed: ", e); } catch (DataEndpointConfigurationException e) { LOG.error("Parsing Data Endpoint configurations failed: " + e); throw new ConfigurationException("Parsing Data Endpoint configurations failed: ", e); } catch (DataEndpointAuthenticationException e) { LOG.error("Connection to Data Endpoint failed during authentication: " + e); throw new ConfigurationException("Connection to Data Endpoint failed during authentication: ", e); } catch (TransportException e) { LOG.error("Connection failed: " + e); throw new ConfigurationException("Connection failed: ", e); } return dataPublisher; }
Source:
<code>private Long poisonStoreAndGetLastAllocatedTimestamp(Connection connection, Limits limits, TableStatus tableStatus) throws SQLException { <START> long lastAllocated; if (tableStatus == TableStatus.NO_DATA) { lastAllocated = AtlasDbFactory.NO_OP_FAST_FORWARD_TIMESTAMP; } else { lastAllocated = limits.upperLimit().get().value(); } <END> poisonTable(connection); return lastAllocated; }</code><technical_language>nit: suggestion long lastAllocated = tableStatus == TableStatus.NO_DATA ? AtlasDbFactory.NO_OP_FAST_FORWARD_TIMESTAMP : limits.upperLimit().get().value();</technical_language>

Target:
private Long poisonStoreAndGetLastAllocatedTimestamp(Connection connection, Limits limits, TableStatus tableStatus) throws SQLException { long lastAllocated = tableStatus == TableStatus.NO_DATA ? AtlasDbFactory.NO_OP_FAST_FORWARD_TIMESTAMP : limits.upperLimit().get().value(); poisonTable(connection); return lastAllocated; }
Source:
<code><START> protected synchronized void executeFunctionsUponCompletion() { <END> if (uponCompletionFunctions != null) { executeFunctions(uponCompletionFunctions); uponCompletionFunctions = null; } }</code><technical_language>this need synchronized? Is for threads (in txn) hit this time? completion state entered once, of number of threads participating in txn</technical_language>

Target:
protected void executeFunctionsUponCompletion() { if (uponCompletionFunctions != null) { executeFunctions(uponCompletionFunctions); uponCompletionFunctions = null; } }
Source:
<code>private void createVMFromTemplate() { VmTemplate template = getSelectedItem(); final List<UICommand> commands = new ArrayList<>(); commands.add(UICommand.createDefaultOkUiCommand("OnSaveVm", this)); commands.add(UICommand.createCancelUiCommand("Cancel", this)); <START> AsyncQuery getVmInitQuery = new AsyncQuery(); <END> getVmInitQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object result) { VmTemplate withVmInit = (VmTemplate) result; setupNewVmModel(new UnitVmModel(new NewVmFromTemplateModelBehavior(withVmInit), TemplateListModel.this), withVmInit.getVmType(), getSystemTreeSelectedItem(), commands); } }; AsyncDataProvider.getInstance().getTemplateById(getVmInitQuery, template.getId()); }</code><technical_language>inline this temporary variable constructor of AsyncQuery(IAsyncCallback) this ADP.getInstance().getTemplateById(new AsyncQuery(new IAsyncCallback() { ... }), template.getId());</technical_language>

Target:
private void createVMFromTemplate() { VmTemplate template = getSelectedItem(); final List<UICommand> commands = new ArrayList<>(); commands.add(UICommand.createDefaultOkUiCommand("OnSaveVm", this)); commands.add(UICommand.createCancelUiCommand("Cancel", this)); AsyncDataProvider.getInstance().getTemplateById(new AsyncQuery(new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VmTemplate withVmInit = (VmTemplate) returnValue; setupNewVmModel(new UnitVmModel(new NewVmFromTemplateModelBehavior(withVmInit), TemplateListModel.this), withVmInit.getVmType(), getSystemTreeSelectedItem(), commands); } }), template.getId()); }
Source:
<code>public final String attemptToPipelineAuthorization(String method, String uri, Supplier<byte[]> entityBodySupplier) { String pipeliningType = authorizationPipeliningType.get(); if (DIGEST.equals(pipeliningType)) { Map<String, String> challenge = lastChallenge.get(); <START> String algorithm = challenge.get(ALGORITHM); <END> return createDigestAuthorizationHeader(method, uri, challenge, algorithm, entityBodySupplier, getDigestFunction(algorithm)); } else if (BASIC.equals(pipeliningType)) { return handleBasic(); } return null; }</code><technical_language>I guess a race condition - challenge.set() is happening in handleDigest() challenge.get() is called here. Multiple threads calling methods in random order lead unexpected results is some thread-safety built of this class I missing</technical_language>

Target:
public final String attemptToPipelineAuthorization(String method, String uri, Supplier<byte[]> entityBodySupplier) { String pipeliningType = authorizationPipeliningType.get(); if (DIGEST.equals(pipeliningType)) { Map<String, String> challenge = new HashMap<>(lastChallenge.get()); String algorithm = challenge.get(ALGORITHM); return createDigestAuthorizationHeader(method, uri, challenge, algorithm, entityBodySupplier, getDigestFunction(algorithm)); } else if (BASIC.equals(pipeliningType)) { return handleBasic(); } return null; }
Source:
<code>public void writeJSONAddsContainerWithAllValues() throws ComponentLookupException { Map<String, String> map = new LinkedHashMap<String, String>(); <START> map.put(PROPERTY_1, "datum1"); <END> map.put(PROPERTY_2, "datum2"); PatientData<String> patientData = new DictionaryPatientData<String>(this.DATA_NAME, map); doReturn(patientData).when(this.patient).getData(DATA_NAME); JSONObject json = new JSONObject(); this.mocker.getComponentUnderTest().writeJSON(this.patient, json); Assert.assertNotNull(json.get(DATA_NAME)); Assert.assertTrue(json.get(DATA_NAME) instanceof JSONObject); JSONObject container = json.getJSONObject(DATA_NAME); Assert.assertEquals("datum1", container.get(PROPERTY_1)); Assert.assertEquals("datum2", container.get(PROPERTY_2)); }</code><technical_language>datum1 datum2 in local variables</technical_language>

Target:
public void writeJSONAddsContainerWithAllValues() throws ComponentLookupException { String datum1 = "datum1"; String datum2 = "datum2"; Map<String, String> map = new LinkedHashMap<>(); map.put(PROPERTY_1, datum1); map.put(PROPERTY_2, datum2); PatientData<String> patientData = new DictionaryPatientData<>(this.DATA_NAME, map); doReturn(patientData).when(this.patient).getData(DATA_NAME); JSONObject json = new JSONObject(); this.mocker.getComponentUnderTest().writeJSON(this.patient, json); Assert.assertNotNull(json.get(DATA_NAME)); Assert.assertTrue(json.get(DATA_NAME) instanceof JSONObject); JSONObject container = json.getJSONObject(DATA_NAME); Assert.assertEquals(datum1, container.get(PROPERTY_1)); Assert.assertEquals(datum2, container.get(PROPERTY_2)); }
Source:
<code>public ItemStack decrStackSize(int i, int j) { if (!_drawer.isDrawerEnabled(i)) return null; IDrawer drawer = _drawer.getDrawer(i); if (drawer == null) return null; <START> return getMultipleItems(ItemIdentifier.get(drawer.getStoredItemPrototype()), j); <END> }</code><technical_language>This relaied getMultipleItems(); needs access slot i complete inventory</technical_language>

Target:
public ItemStack decrStackSize(int i, int j) { if (!_drawer.isDrawerEnabled(i)) return null; IDrawer drawer = _drawer.getDrawer(i); if (drawer == null || drawer.isEmpty()) return null; int avail = Math.min(j, drawer.getStoredItemCount()); drawer.setStoredItemCount(drawer.getStoredItemCount() - avail); ItemStack stack = drawer.getStoredItemCopy(); stack.stackSize = avail; return stack; }