auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void onPostExecute( Integer result ) { mainActivity.transferComplete(); MainActivity.info("DB backup postExe"); final View view = fragment.getView(); if (view != null) { final TextView tv = view.findViewById( R.id.backup_db_text ); if (tv != null) { tv.setText( mainActivity.getString(R.string.backup_db_text) ); } } if (null != result) { if (pd.isShowing()) { pd.dismiss(); } if (null != dbResult && dbResult.getFirst()) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_SUBJECT, "WiGLE Database Backup"); intent.setType("application/xsqlite-3"); final Context c = getContext(); if (null == c) { MainActivity.error("null context in DB backup postExec"); } else { final File backupFile = new File(dbResult.getSecond()); MainActivity.info("backupfile: " + backupFile.getAbsolutePath()); <START> MainActivity.info("exists: " + backupFile.exists() + " read: " + backupFile.canRead()); <END> final Uri fileUri = FileProvider.getUriForFile(c, MainActivity.getMainActivity().getApplicationContext().getPackageName() + ".sqliteprovider", new File(dbResult.getSecond())); intent.putExtra(Intent.EXTRA_STREAM, fileUri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, getResources().getText(R.string.send_to))); } } else { MainActivity.error("null or empty DB result in DB backup postExec"); } } }</code><technical_language>condense a single log line for readability</technical_language>

Target:
protected void onPostExecute( Integer result ) { mainActivity.transferComplete(); MainActivity.info("DB backup postExe"); final View view = fragment.getView(); if (view != null) { final TextView tv = view.findViewById( R.id.backup_db_text ); if (tv != null) { tv.setText( mainActivity.getString(R.string.backup_db_text) ); } } if (null != result) { if (pd.isShowing()) { pd.dismiss(); } if (null != dbResult && dbResult.getFirst()) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_SUBJECT, "WiGLE Database Backup"); intent.setType("application/xsqlite-3"); final Context c = getContext(); if (null == c) { MainActivity.error("null context in DB backup postExec"); } else { final File backupFile = new File(dbResult.getSecond()); MainActivity.info("backupfile: " + backupFile.getAbsolutePath() + " exists: " + backupFile.exists() + " read: " + backupFile.canRead()); final Uri fileUri = FileProvider.getUriForFile(c, MainActivity.getMainActivity().getApplicationContext().getPackageName() + ".sqliteprovider", new File(dbResult.getSecond())); intent.putExtra(Intent.EXTRA_STREAM, fileUri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, getResources().getText(R.string.send_to))); } } else { MainActivity.error("null or empty DB result in DB backup postExec"); } } }
Source:
<code>public void doNotRemoveSlaveShortlyAfterConnection() throws Exception { <START> LauncherFactory launcherFactory = new TestCommandLauncherFactory("bash -c \"sleep 70 && java -jar '%s'\""); <END> JCloudsCloud cloud = j.configureSlaveProvisioningWithFloatingIP(j.dummyCloud(j.dummySlaveTemplate( j.defaultSlaveOptions().getBuilder().retentionTime(1).launcherFactory(launcherFactory).build(), "label" ))); JCloudsSlave slave = j.provision(cloud, "label"); JCloudsComputer computer = (JCloudsComputer) slave.toComputer(); while(computer.getChannel() == null){ Thread.sleep(1000); } computer.getRetentionStrategy().check(computer); assertFalse(computer.isPendingDelete()); }</code><technical_language>test is linux specific</technical_language>

Target:
public void doNotRemoveSlaveShortlyAfterConnection() throws Exception { Assume.assumeFalse(Functions.isWindows()); LauncherFactory launcherFactory = new TestCommandLauncherFactory("bash -c \"sleep 70 && java -jar '%s'\""); JCloudsCloud cloud = j.configureSlaveProvisioningWithFloatingIP(j.dummyCloud(j.dummySlaveTemplate( j.defaultSlaveOptions().getBuilder().retentionTime(1).launcherFactory(launcherFactory).build(), "label" ))); JCloudsSlave slave = j.provision(cloud, "label"); JCloudsComputer computer = (JCloudsComputer) slave.toComputer(); while(computer.getChannel() == null){ Thread.sleep(1000); } computer.getRetentionStrategy().check(computer); assertFalse(computer.isPendingDelete()); }
Source:
<code>protected Map<String, Pair<String, String>> getExclusiveLocks() { <START> if ((getParameters().getVm() != null) && (!StringUtils.isBlank(getParameters().getVm().getName()))) { <END> return Collections.singletonMap(getParameters().getVm().getName(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_NAME, VdcBllMessages.ACTION_TYPE_FAILED_NAME_ALREADY_USED)); } return null; }</code><technical_language>nit: i extra parenthesis in clauses redundant (just a matter of taste...)</technical_language>

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (getParameters().getVm() != null && !StringUtils.isBlank(getParameters().getVm().getName())) { return Collections.singletonMap(getParameters().getVm().getName(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_NAME, VdcBllMessages.ACTION_TYPE_FAILED_NAME_ALREADY_USED)); } return null; }
Source:
<code><START> public Double sample(final RandomGenerator rng, final AlleleFractionState state, final AlleleFractionData data) { <END> return sampler.sample(logConditionalOnMinorFraction(state, data, segmentIndex)); }</code><technical_language>note rebasing i added handle missing data: if (data.numHetsInSegment(segmentIndex) == 0) { return Double.NaN; }</technical_language>

Target:
public Double sample(final RandomGenerator rng, final AlleleFractionState state, final AlleleFractionData data) { if (data.numHetsInSegment(segmentIndex) == 0) { return Double.NaN; } return sampler.sample(logConditionalOnMinorFraction(state, data, segmentIndex)); }
Source:
<code>public XantchaSleeperAgent(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}{R}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.MINION); this.power = new MageInt(5); this.toughness = new MageInt(5); Ability ability = new EntersBattlefieldTriggeredAbility(new XantchaSleeperAgentChangeControlEffect()) ; ability.addTarget(new TargetOpponent()); this.addAbility(ability); <START> this.addAbility(new AttacksEachCombatStaticAbility()); <END> Effect effect = new LoseLifePermanentControllerEffect(2); effect.setText("Xantcha’s controller loses 2 life"); SimpleActivatedAbility simpleAbility = new SimpleActivatedAbility(Zone.BATTLEFIELD, effect, new ManaCostsImpl("{3}")); simpleAbility.addEffect(new DrawCardSourceControllerEffect(1).setText("and you draw a card")); simpleAbility.addEffect(new InfoEffect("Any player may activate this ability")); simpleAbility.setMayActivate(TargetController.ANY); this.addAbility(simpleAbility); }</code><technical_language>need prevent attacks owner? Effect effect = new CantAttackYouOrPlaneswalkerAllEffect(Duration.WhileOnBattlefield, filter);</technical_language>

Target:
public XantchaSleeperAgent(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}{R}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.MINION); this.power = new MageInt(5); this.toughness = new MageInt(5); Ability ability = new EntersBattlefieldTriggeredAbility(new XantchaSleeperAgentChangeControlEffect()) ; ability.addTarget(new TargetOpponent()); this.addAbility(ability); ability = new AttacksEachCombatStaticAbility(); Effect effect = new XantchaSleeperAgentAttackRestrictionEffect(); ability.addEffect(effect); this.addAbility(ability); effect = new LoseLifePermanentControllerEffect(2); effect.setText("Xantcha’s controller loses 2 life"); SimpleActivatedAbility simpleAbility = new SimpleActivatedAbility(Zone.BATTLEFIELD, effect, new ManaCostsImpl("{3}")); simpleAbility.addEffect(new DrawCardSourceControllerEffect(1).setText("and you draw a card")); simpleAbility.addEffect(new InfoEffect("Any player may activate this ability")); simpleAbility.setMayActivate(TargetController.ANY); this.addAbility(simpleAbility); }
Source:
<code>public static void verify() throws IOException { BenchmarkData data = new BenchmarkData(); data.setup(); BenchmarkSTArea benchmark = new BenchmarkSTArea(); assertEquals(Math.round(1000 * (Double) benchmark.stSphericalArea(data) / 3.659E8), 1000); assertEquals(Math.round(1000 * (Double) benchmark.stSphericalArea500k(data) / 2151E11), 1000); assertEquals(benchmark.stArea(data), 0.05033099592771004); <START> assertEquals(benchmark.stArea500k(data), 0.0); <END> }</code><technical_language>I surprised zero here. Then, I a closer 500K polygon realized boundary is a great-circle crossing poles points a constant longitude (is right?). projects a single line (walked twice) zero area. I this is a good polygon test edge-cases in area computation, I for benchmarking. A polygon lots of vertexes, "gotchas" a fit. Also, createPolygon method name sounds generic, implementation creates a polygon. move this method out of utility class this benchmark</technical_language>

Target:
public static void verify() throws IOException { BenchmarkData data = new BenchmarkData(); data.setup(); BenchmarkSTArea benchmark = new BenchmarkSTArea(); assertEquals(Math.round(1000 * (Double) benchmark.stSphericalArea(data) / 3.659E8), 1000); assertEquals(Math.round(1000 * (Double) benchmark.stSphericalArea500k(data) / 38842273735.0), 1000); assertEquals(benchmark.stArea(data), 0.05033099592771004); assertEquals(Math.round(1000 * (Double) benchmark.stArea500k(data) / Math.PI), 1000); }
Source:
<code>private void populateList() { fCombo.removeAll(); fCombo.add(fMessage); <START> for (String fCommentTemplate : fCommentTemplates) { <END> fCombo.add(CVSUIMessages.CommitCommentArea_6 + ": " + Util.flattenText(fCommentTemplate)); } for (String fComment : fComments) { fCombo.add(Util.flattenText(fComment)); } fCombo.setText(fMessage); }</code><technical_language>a field</technical_language>

Target:
private void populateList() { fCombo.removeAll(); fCombo.add(fMessage); for (String commentTemplate : fCommentTemplates) { fCombo.add(CVSUIMessages.CommitCommentArea_6 + ": " + Util.flattenText(commentTemplate)); } for (String comment : fComments) { fCombo.add(Util.flattenText(comment)); } fCombo.setText(fMessage); }
Source:
<code>public boolean isOnlyCurrentBranchSelected(Set<RefFilter> filters) { for (RefFilter filter : filters) { if (filter.isSelected()) { <START> if (!filtersForCurrentBranch.contains(filter)) <END> return false; } else { if (filtersForCurrentBranch.contains(filter)) return false; } } return true; }</code><technical_language>missing braces</technical_language>

Target:
public boolean isOnlyCurrentBranchSelected(Set<RefFilter> filters) { for (RefFilter filter : filters) { if (filter.isSelected()) { if (!filtersForCurrentBranch.contains(filter)) { return false; } } else { if (filtersForCurrentBranch.contains(filter)) { return false; } } } return true; }
Source:
<code>protected void onPreExecute() { mBitmap = getBitmap(); mReferenceBitmap = BitmapAssets.getBitmap(getApplicationContext(), mBitmapName); <START> final float tolerance = 0.01f; END> mSame = compareTo(mBitmap, mReferenceBitmap, tolerance); }</code><technical_language>Yes, this test is strict. this point in time, willing change is allows for some rounding errors</technical_language>

Target:
protected void onPreExecute() { mBitmap = getBitmap(); mReferenceBitmap = BitmapAssets.getBitmap(getApplicationContext(), mBitmapName); final int threshold = 1; mSame = compareTo(mBitmap, mReferenceBitmap, threshold); }
Source:
<code><START> default boolean endsWith(Seq<? extends T> that) { <END> Objects.requireNonNull(that, "that is null"); Iterator<T> i = this.iterator().drop(length() - that.length()); Iterator<? extends T> j = that.iterator(); while(i.hasNext() && j.hasNext()) { if(!Objects.equals(i.next(), j.next())) return false; } return !j.hasNext(); }</code><technical_language>null-check</technical_language>

Target:
default boolean endsWith(Seq<? extends T> that) { Objects.requireNonNull(that, "that is null"); Iterator<T> i = this.iterator().drop(length() - that.length()); Iterator<? extends T> j = that.iterator(); while(i.hasNext() && j.hasNext()) { if(!Objects.equals(i.next(), j.next())) { return false; } } return !j.hasNext(); }
Source:
<code>HostPortPoolManager(int poolLimit) { this.poolCount = 0; this.maxConnectionsToHostPort = poolLimit; <START> availableConnections = new LinkedList<String>(); <END> }</code><technical_language>do need limit max size of availableConnections poolLimit (linkedin list size)</technical_language>

Target:
HostPortPoolManager(int poolLimit) { poolCount = 0; maxConnectionsToHostPort = poolLimit; availableConnections = new LinkedList<String>(); }
Source:
<code>protected final void startZoomThread(long startTime, long endTime) { try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:ZoomThreadCreated").setCategory(getViewId()).build()) { long clampedStartTime = (fStartTime == Long.MAX_VALUE ? startTime : Math.min(Math.max(startTime, fStartTime), fEndTime)); long clampedEndTime = (fEndTime == Long.MIN_VALUE ? endTime : Math.max(Math.min(endTime, fEndTime), fStartTime)); fDirty.updateAndGet(i -> i <= 0 ? 1 : i + 1); boolean restart = false; ZoomThread zoomThread = fZoomThread; if (zoomThread != null) { zoomThread.cancel(); if (zoomThread.fZoomStartTime == clampedStartTime && zoomThread.fZoomEndTime == clampedEndTime) { restart = true; } } long resolution = Math.max(1, (clampedEndTime - clampedStartTime) / fDisplayWidth); zoomThread = createZoomThread(clampedStartTime, clampedEndTime, resolution, restart); fZoomThread = zoomThread; if (zoomThread != null) { zoomThread.setScopeId(log.getId()); synchronized (fZoomThreadResultLock) { zoomThread.start(); } } else { <START> fDirty.updateAndGet(i -> i > 0 ? i - 1 : i); <END> } } }</code><technical_language>I propose decrement in a 'finally' block, if zoomThread is started, increment more time (to decremented zoom thread). reason increment early is want count 0 due completetion of cancelled zoom thread in short time start new zoom thread</technical_language>

Target:
protected final void startZoomThread(long startTime, long endTime) { try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:ZoomThreadCreated").setCategory(getViewId()).build()) { long clampedStartTime = (fStartTime == Long.MAX_VALUE ? startTime : Math.min(Math.max(startTime, fStartTime), fEndTime)); long clampedEndTime = (fEndTime == Long.MIN_VALUE ? endTime : Math.max(Math.min(endTime, fEndTime), fStartTime)); fDirty.incrementAndGet(); boolean restart = false; ZoomThread zoomThread = fZoomThread; if (zoomThread != null) { zoomThread.cancel(); if (zoomThread.fZoomStartTime == clampedStartTime && zoomThread.fZoomEndTime == clampedEndTime) { restart = true; } } long resolution = Math.max(1, (clampedEndTime - clampedStartTime) / fDisplayWidth); zoomThread = createZoomThread(clampedStartTime, clampedEndTime, resolution, restart); fZoomThread = zoomThread; if (zoomThread != null) { zoomThread.setScopeId(log.getId()); synchronized (fZoomThreadResultLock) { zoomThread.start(); } } else { int val = fDirty.decrementAndGet(); if (val < 0) { Activator.getDefault().logError(DIRTY_UNDERFLOW_ERROR); } } } }
Source:
<code>public void testExtractTimestampWithTimezone() throws Exception { final DateTimeZone saved = DateTimeZone.getDefault(); final DateTimeZone dataTimezone = DateTimeZone.forID("Asia/Shanghai"); try { <START> DateTimeZone.setDefault(DateTimeZone.UTC); <END> DateTime now = new DateTime(); String nowShanghai = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").print(now.withZone(dataTimezone)); TimestampSpec spec = new TimestampSpec("dt", "yyyy-MM-dd HH:mm:ss.SSS", null, dataTimezone.toString()); Assert.assertEquals( now.getMillis(), spec.extractTimestamp(ImmutableMap.<String, Object>of("dt", nowShanghai)).getMillis() ); } finally { DateTimeZone.setDefault(saved); } }</code><technical_language>is necessary set timezone for this test? enough test resulting extracted timestamp requested timezone set, no</technical_language>

Target:
public void testExtractTimestampWithTimezone() throws Exception { DateTimeZone eventTimeZone = DateTimeZone.forID("Asia/Shanghai"); TimestampSpec spec = new TimestampSpec("TIMEstamp", "yyyy-MM-dd HH:mm:ss.SSS", null, eventTimeZone.toString()); Assert.assertEquals( new DateTime("2016-04-05T10:56:36.574+08:00").getMillis(), spec.extractTimestamp(ImmutableMap.<String, Object>of("TIMEstamp", "2016-04-05 10:56:36.574")).getMillis() ); }
Source:
<code>public void writeTo(StreamOutput out) throws IOException { writeNullable(bucket, out); writeNullable(records, out); writeNullable(influencers, out); writeNullable(quantiles, out); writeNullable(modelSnapshot, out); writeNullable(modelSizeStats, out); writeNullable(modelPlot, out); writeNullable(annotation, out); writeNullable(categoryDefinition, out); if (out.getVersion().onOrAfter(Version.V_8_0_0)) { <START> writeNullable(categorizerStats, out); <END> } writeNullable(flushAcknowledgement, out); writeNullable(forecast, out); writeNullable(forecastRequestStats, out); }</code><technical_language>suggestion out.writeOptionalWriteable(categorizerStats); I if this writeNullable method removed? side is is StreamOutput#writeOptionalList. be</technical_language>

Target:
public void writeTo(StreamOutput out) throws IOException { writeNullable(bucket, out); writeNullable(records, out); writeNullable(influencers, out); writeNullable(quantiles, out); writeNullable(modelSnapshot, out); writeNullable(modelSizeStats, out); writeNullable(modelPlot, out); writeNullable(annotation, out); writeNullable(categoryDefinition, out); if (out.getVersion().onOrAfter(Version.V_8_0_0)) { out.writeOptionalWriteable(categorizerStats); } writeNullable(flushAcknowledgement, out); writeNullable(forecast, out); writeNullable(forecastRequestStats, out); }
Source:
<code>public void usesParentFromInvocationTime() throws Exception { server.enqueueDelay(TimeUnit.SECONDS.toMillis(1)); GreeterGrpc.GreeterFutureStub futureStub = GreeterGrpc.newFutureStub(client); brave.Span parent = tracing.tracer().newTrace().name("test").start(); try (Tracer.SpanInScope ws = tracing.tracer().withSpanInScope(parent)) { futureStub.sayHello(HELLO_REQUEST); futureStub.sayHello(HELLO_REQUEST); } finally { parent.finish(); } brave.Span otherSpan = tracing.tracer().newTrace().name("test2").start(); <START> try (Tracer.SpanInScope ws = tracing.tracer().withSpanInScope(otherSpan)) { <END> for (int i = 0; i < 2; i++) { TraceContext context = server.takeRequest().context(); assertThat(context.traceId()) .isEqualTo(parent.context().traceId()); assertThat(context.parentId()) .isEqualTo(parent.context().spanId()); } } finally { otherSpan.finish(); } }</code><technical_language>revert style changes please (including imports etc)</technical_language>

Target:
@Test public void usesParentFromInvocationTime() throws Exception { server.enqueueDelay(TimeUnit.SECONDS.toMillis(1)); GreeterGrpc.GreeterFutureStub futureStub = GreeterGrpc.newFutureStub(client); brave.Span parent = tracer.newTrace().name("test").start(); try (Tracer.SpanInScope ws = tracer.withSpanInScope(parent)) { futureStub.sayHello(HELLO_REQUEST); futureStub.sayHello(HELLO_REQUEST); } finally { parent.finish(); } brave.Span otherSpan = tracer.newTrace().name("test2").start(); try (Tracer.SpanInScope ws = tracer.withSpanInScope(otherSpan)) { for (int i = 0; i < 2; i++) { TraceContext context = server.takeRequest().context(); assertThat(context.traceId()) .isEqualTo(parent.context().traceId()); assertThat(context.parentId()) .isEqualTo(parent.context().spanId()); } } finally { otherSpan.finish(); } }
Source:
<code>private static Optional<Protos.Credential> readCredentials() { if (System.getenv("MESOS_AUTHENTICATE") != null) { LOGGER.debug("Enabling authentication for the framework"); final String principal = System.getenv("DEFAULT_PRINCIPAL"); final String secret = System.getenv("DEFAULT_SECRET"); if (principal == null) { LOGGER.error("Expecting authentication principal in the environment"); System.exit(1); } Protos.Credential.Builder credential = Protos.Credential.newBuilder() <START> .setPrincipal(System.getenv("DEFAULT_PRINCIPAL")); <END> if (secret == null) { LOGGER.error("Expecting authentication secret in the environment"); } else { credential.setSecret(ByteString.copyFrom(secret.getBytes())); } return Optional.of(credential.build()); } else { return Optional.absent(); } }</code><technical_language>call System.getenv instead uf local variable</technical_language>

Target:
private static Optional<Protos.Credential> readCredentials() { if (System.getenv("MESOS_AUTHENTICATE") != null) { LOGGER.debug("Enabling authentication for the framework"); final String principal = System.getenv("DEFAULT_PRINCIPAL"); final String secret = System.getenv("DEFAULT_SECRET"); if (principal == null) { LOGGER.error("Expecting authentication principal in the environment"); System.exit(1); } Protos.Credential.Builder credential = Protos.Credential.newBuilder().setPrincipal(principal); if (secret == null) { LOGGER.error("Expecting authentication secret in the environment"); } else { credential.setSecret(ByteString.copyFrom(secret.getBytes())); } return Optional.of(credential.build()); } else { return Optional.absent(); } }
Source:
<code>public String getMessage(){ <START> return this.message; <END> }</code><technical_language>Nit: unnecessary this</technical_language>

Target:
public String getMessage(){ return message; }
Source:
<code>private void retriableMergeRegions(String regionName1, String regionName2, int maxRetries, int retry) throws IOException { try { admin.mergeRegions(Bytes.toBytes(regionName1), Bytes.toBytes(regionName2), false); } catch (MergeRegionException e) { SpliceLogUtils.warn(LOG, "Merge failed:", e); <START> if (e.getMessage().contains("Unable to merge regions not online") && retry < maxRetries) { <END> try { Thread.sleep(500); } catch (InterruptedException ie) { throw new IOException(e); } SpliceLogUtils.info(LOG, "retry merging region %s and %s", regionName1, regionName2); retriableMergeRegions(regionName1, regionName2, maxRetries, retry+1); } } }</code><technical_language>if merge fails maxRetries, throw exception caller, is this intended behavior? Thanks</technical_language>

Target:
private void retriableMergeRegions(String regionName1, String regionName2, int maxRetries, int retry) throws IOException { try { admin.mergeRegions(Bytes.toBytes(regionName1), Bytes.toBytes(regionName2), false); } catch (MergeRegionException e) { SpliceLogUtils.warn(LOG, "Merge failed:", e); if (e.getMessage().contains("Unable to merge regions not online") && retry < maxRetries) { try { Thread.sleep(500); } catch (InterruptedException ie) { throw new IOException(e); } SpliceLogUtils.info(LOG, "retry merging region %s and %s", regionName1, regionName2); retriableMergeRegions(regionName1, regionName2, maxRetries, retry+1); } else throw e; } }
Source:
<code>public Allergy newObject() { <START> Allergy allergy = Context.getPatientService().getAllergyByUuid(RestTestConstants2_0.ALLERGY_UUID); <END> return allergy; }</code><technical_language>this supposed create return a new (not in database) allergy</technical_language>

Target:
public Allergy newObject() { return Context.getPatientService().getAllergyByUuid(RestTestConstants2_0.ALLERGY_UUID); }
Source:
<code>private boolean modify(String processId, Predicate<Process> checker, Consumer<Process> modifier) { Process process = process1stLevelCache.get(processId); if (process == null) { process = elastic.find(Process.class, processId).orElse(null); } if (process == null) { return false; } int retries = 5; while (retries-- > 0) { if (!checker.test(process)) { return false; } modifier.accept(process); try { elastic.tryUpdate(process); process1stLevelCache.put(processId, process); process2ndLevelCache.put(processId, process); return true; } catch (OptimisticLockException e) { Wait.randomMillis(250, 500); <START> process = elastic.find(Process.class, processId).orElse(null); <END> } } Log.BACKGROUND.WARN("Failed to update process %s after 5 attempts. Skipping update...", processId); return false; }</code><technical_language>move L387 nullcheck retry loop, process null while looping</technical_language>

Target:
private boolean modify(String processId, Predicate<Process> checker, Consumer<Process> modifier) { Process process = process1stLevelCache.get(processId); if (process == null) { process = elastic.find(Process.class, processId).orElse(null); } int retries = 5; while (retries-- > 0) { if (process == null) { return false; } if (!checker.test(process)) { return false; } modifier.accept(process); try { elastic.tryUpdate(process); process1stLevelCache.put(processId, process); process2ndLevelCache.put(processId, process); return true; } catch (OptimisticLockException e) { Wait.randomMillis(250, 500); process = elastic.find(Process.class, processId).orElse(null); } } Log.BACKGROUND.WARN("Failed to update process %s after 5 attempts. Skipping update...", processId); return false; }
Source:
<code>private void createIntervalsList() { UIUtils.createLabel("Show statistics of the past ", intervalSelection); UIUtils.createComboList(intervalSelection, new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { Combo widget = (Combo) e.getSource(); selectedInterval = StatisticsInterval.values()[widget .getSelectionIndex()]; } @Override public void widgetDefaultSelected(SelectionEvent e) { } <START> }, new String[] { "10 minutes.", "30 minutes.", "1 hour.", "2 hours.", <END> "5 hours.", "8 hours.", "10 hours." }, selectedInterval.id); }</code><technical_language>enrich IntervalStatistics strings call IntervalStatistics.values() similar</technical_language>

Target:
private void createIntervalsList() { UIUtils.createLabel("Show statistics of the past ", intervalSelection); UIUtils.createComboList(intervalSelection, new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { Combo widget = (Combo) e.getSource(); selectedInterval = StatisticsInterval.values()[widget .getSelectionIndex()]; } @Override public void widgetDefaultSelected(SelectionEvent e) { } }, StatisticsInterval.names(), selectedInterval.id); }
Source:
<code>public IUser getUser(String sUserId) throws QuadrigaStorageException { IUser user = userDeepMapper.getUser(sUserId); <START> return user; <END> }</code><technical_language>merge line 76 77</technical_language>

Target:
public IUser getUser(String sUserId) throws QuadrigaStorageException { return userDeepMapper.getUser(sUserId); }
Source:
<code>public FormRecognizerException(final String message, final List<ErrorInformation> errorInformationList) { super(message); StringBuilder errorInformationStringBuilder = new StringBuilder().append(message); <START> if (!errorInformationList.isEmpty()) { <END> for (ErrorInformation errorInformation : errorInformationList) { errorInformationStringBuilder.append(", " + "errorCode" + ": [") .append(errorInformation.getCode()).append("], ").append("message") .append(": ").append(errorInformation.getMessage()); } } this.errorInformationMessage = errorInformationStringBuilder.toString(); this.errorInformationList = Collections.unmodifiableList(new ArrayList<>(errorInformationList)); }</code><technical_language>sense !CoreUtils.isNullOrEmpty(errorInformationList) , check for null</technical_language>

Target:
public FormRecognizerException(final String message, final List<ErrorInformation> errorInformationList) { super(message); StringBuilder errorInformationStringBuilder = new StringBuilder().append(message); if (!CoreUtils.isNullOrEmpty(errorInformationList)) { for (ErrorInformation errorInformation : errorInformationList) { errorInformationStringBuilder.append(", " + "errorCode" + ": [") .append(errorInformation.getCode()).append("], ").append("message") .append(": ").append(errorInformation.getMessage()); } this.errorInformationList = Collections.unmodifiableList(errorInformationList); } else { this.errorInformationList = null; } this.errorInformationMessage = errorInformationStringBuilder.toString(); }
Source:
<code><START> InetSocketAddress getQuorumAddress(){ <END> AddressTuple addrs = myAddrs.get(); if (addrs != null) { return addrs.quorumAddr; } try { synchronized (QV_LOCK) { addrs = myAddrs.get(); while (addrs == null) { QV_LOCK.wait(); addrs = myAddrs.get(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } return addrs.quorumAddr; }</code><technical_language>want put double-check-locking mechanism a private getter of myAddrs consolidate logic in 2 getters</technical_language>

Target:
public InetSocketAddress getQuorumAddress(){ return getAddrs().quorumAddr; }
Source:
<code>private void assertResourceGroupWithClientTags(Set<String> clientTags, String expectedResourceGroup) throws InterruptedException { Session session = testSessionBuilder() .setCatalog("tpch") .setSchema("sf100000") .setSource("client_tags") .setClientTags(clientTags) .build(); QueryId queryId = createQuery(queryRunner, session, LONG_LASTING_QUERY); waitForQueryState(queryRunner, queryId, ImmutableSet.of(RUNNING, FINISHED)); Optional<String> resourceGroupName = queryRunner.getCoordinator().getQueryManager().getQueryInfo(queryId).getResourceGroupName(); assertTrue(resourceGroupName.isPresent(), "Query should have a resource group"); <START> assertEquals(resourceGroupName.get().toString(), expectedResourceGroup, format("Expected: '%s' resource group, found: %s", expectedResourceGroup, resourceGroupName.get())); <END> }</code><technical_language>need .toString()</technical_language>

Target:
private void assertResourceGroupWithClientTags(Set<String> clientTags, String expectedResourceGroup) throws InterruptedException { Session session = testSessionBuilder() .setCatalog("tpch") .setSchema("sf100000") .setSource("client_tags") .setClientTags(clientTags) .build(); QueryId queryId = createQuery(queryRunner, session, LONG_LASTING_QUERY); waitForQueryState(queryRunner, queryId, ImmutableSet.of(RUNNING, FINISHED)); Optional<String> resourceGroupName = queryRunner.getCoordinator().getQueryManager().getQueryInfo(queryId).getResourceGroupName(); assertTrue(resourceGroupName.isPresent(), "Query should have a resource group"); assertEquals(resourceGroupName.get(), expectedResourceGroup, format("Expected: '%s' resource group, found: %s", expectedResourceGroup, resourceGroupName.get())); }
Source:
<code>public TokenRequestContext() { this.scopes = new ArrayList<>(); <START> this.httpClient = null; this.logOptions = null; <END> }</code><technical_language>This is necessary</technical_language>

Target:
public TokenRequestContext() { this.scopes = new ArrayList<>(); }
Source:
<code>public void prepare() { final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); final ExecutableValidator execValidator = validator.forExecutables(); Set<ConstraintViolation<ConstraintViolationBenchmark>> paramViolations = execValidator.validateParameters( this, getAccessibleMethod(getClass(), "paramFunc", String.class), new Object[]{""} ); <START> paramViolation = Iterators.getOnlyElement(paramViolations.iterator()); <END> Set<ConstraintViolation<ConstraintViolationBenchmark>> objViolations = execValidator.validateParameters( this, getAccessibleMethod(getClass(), "objectFunc", Foo.class), new Object[]{new Foo()} ); objViolation = Iterators.getOnlyElement(objViolations.iterator()); }</code><technical_language>I safe call iterator.next, violation is exist</technical_language>

Target:
public void prepare() { final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); final ExecutableValidator execValidator = validator.forExecutables(); Set<ConstraintViolation<ConstraintViolationBenchmark.Resource>> paramViolations = execValidator.validateParameters( new Resource(), getAccessibleMethod(ConstraintViolationBenchmark.Resource.class, "paramFunc", String.class), new Object[]{""} ); paramViolation = paramViolations.iterator().next(); Set<ConstraintViolation<ConstraintViolationBenchmark.Resource>> objViolations = execValidator.validateParameters( new Resource(), getAccessibleMethod(ConstraintViolationBenchmark.Resource.class, "objectFunc", Foo.class), new Object[]{new Foo()} ); objViolation = objViolations.iterator().next(); }
Source:
<code>public void testBug464072() throws CoreException { InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES).putBoolean(ResourcesPlugin.PREF_LIGHTWEIGHT_AUTO_REFRESH, true); try { IWorkspace workspace = getWorkspace(); <START> IProject project = workspace.getRoot().getProject("MyProject"); <END> IFile file = project.getFile("file.txt"); ensureExistsInWorkspace(file, true); file.getLocation().toFile().delete(); try { file.getContentDescription(); fail("1.2 - should have failed"); } catch (CoreException e) { assertEquals("1.3", IResourceStatus.RESOURCE_NOT_FOUND, e.getStatus().getCode()); } } finally { InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES).putBoolean(ResourcesPlugin.PREF_LIGHTWEIGHT_AUTO_REFRESH, false); } }</code><technical_language>Please getUniqueString() avoid accidental project name collision</technical_language>

Target:
public void testBug464072() throws CoreException { getResourcesPreferences().putBoolean(ResourcesPlugin.PREF_LIGHTWEIGHT_AUTO_REFRESH, true); try { IWorkspace workspace = getWorkspace(); IProject project = workspace.getRoot().getProject(getUniqueString()); IFile file = project.getFile("file.txt"); ensureExistsInWorkspace(file, true); file.getLocation().toFile().delete(); try { file.getContentDescription(); fail("1.2 - should have failed"); } catch (CoreException e) { assertEquals("1.3", IResourceStatus.RESOURCE_NOT_FOUND, e.getStatus().getCode()); } } finally { getResourcesPreferences().remove(ResourcesPlugin.PREF_LIGHTWEIGHT_AUTO_REFRESH); } }
Source:
<code>public void close(ErrorCondition errorCondition) { Future scheduledFuture = scheduledFutureRef.getAndSet(null); if (scheduledPool != null && scheduledPool instanceof ThreadPoolExecutor && scheduledFuture != null && scheduledFuture != voidFuture && scheduledFuture instanceof Runnable) { if (!((ThreadPoolExecutor) scheduledPool).remove((Runnable) scheduledFuture) && !scheduledFuture.isCancelled() && !scheduledFuture.isDone()) { <START> log.warn("Scheduled task can't be removed from scheduledPool."); <END> } } handler.close(errorCondition, this); }</code><technical_language>parameterised logger needed</technical_language>

Target:
public void close(ErrorCondition errorCondition) { Future<?> scheduledFuture = scheduledFutureRef.getAndSet(null); if (scheduledPool instanceof ThreadPoolExecutor && scheduledFuture != null && scheduledFuture != VOID_FUTURE && scheduledFuture instanceof Runnable) { if (!((ThreadPoolExecutor) scheduledPool).remove((Runnable) scheduledFuture) && !scheduledFuture.isCancelled() && !scheduledFuture.isDone()) { ActiveMQAMQPProtocolLogger.LOGGER.cantRemovingScheduledTask(); } } handler.close(errorCondition, this); }
Source:
<code>private void createProgressFile(File workingDir, String progressFileName) throws IOException { progressFileDir = workingDir.toPath().resolve(PROGRESS_FILE_DIR); try { Files.createDirectories(progressFileDir); <START> progressFileDir.toFile().setExecutable(true, false); <END> progressFileDir.toFile().setWritable(true, false); progressFile = progressFileDir.resolve(progressFileName); progressFile.toFile().setWritable(true, false); Files.createFile(progressFile); } catch (FileAlreadyExistsException e) { } logger.debug("Progress file '" + progressFile + "' created"); }</code><technical_language>safer (for preventing some race conditions) give permissions files created. Static methods Files.createDirectories Files.createFile support a argument for defining permissions. is example: Files.createDirectories(progressFileDir, PosixFilePermissions.asFileAttribute(EnumSet.of( PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, ...)</technical_language>

Target:
private void createProgressFile(File workingDir, String progressFileName) throws IOException { progressFileDir = workingDir.toPath().resolve(PROGRESS_FILE_DIR); try { Files.createDirectories(progressFileDir); ForkerUtils.setSharedPermissions(progressFileDir.toFile(), true); progressFile = progressFileDir.resolve(progressFileName); Files.createFile(progressFile); ForkerUtils.setSharedPermissions(progressFile.toFile(), false); } catch (FileAlreadyExistsException e) { } logger.debug("Progress file '" + progressFile + "' created"); }
Source:
<code>private boolean scanTree(String prefix, File dir) { final Map<String, File> directories = new IdentityHashMap<String, File>(); final String[] entries = dir.list(LockFile.FILTER); if (entries == null) return false; if (0 < entries.length) { for (String f : entries) { File e = new File(dir, f); if (e.isDirectory()) directories.put(f, e); } Arrays.sort(entries, new Comparator<String>() { public int compare(String o1, String o2) { <START> File f1 = directories.get(o1); <END> File f2 = directories.get(o2); if (f1 == null && f2 == null) return o1.compareTo(o2); if (f1 != null && f2 != null) return o1.compareTo(o2); String s1 = f1 == null ? o1 : o1 + "/"; String s2 = f2 == null ? o2 : o2 + "/"; return s1.compareTo(s2); } }); for (String name : entries) { File e = directories.get(name); if (e != null) scanTree(prefix + name + "/", e); else scanOne(prefix + name); } } return true; }</code><technical_language>Instead of of HashMap operations, not: for (int i = 0; i < entries.length) { if (new File(dir, entries[i])).isDirectory()) entries[i] += "/"; } Arrays.sort(entries); object allocations. hash operations. natural comparator for Arrays.sort(). in scanTree routine, need name + "/" for a directory anyway. decide enter scanTree scanOne suffix: for (String name : entries) { if (name.charAt(name.length() - 1) == '/') scanTree(prefix + name, new File(dir, name); else scanOne(prefix + name); }</technical_language>

Target:
private boolean scanTree(String prefix, File dir) { final String[] entries = dir.list(LockFile.FILTER); if (entries == null) return false; if (0 < entries.length) { for (int i = 0; i < entries.length; ++i) { String e = entries[i]; File f = new File(dir, e); if (f.isDirectory()) entries[i] += '/'; } Arrays.sort(entries); for (String name : entries) { if (name.charAt(name.length() - 1) == '/') scanTree(prefix + name, new File(dir, name)); else scanOne(prefix + name); } } return true; }
Source:
<code>@Override public Call<T> map(ResultSet rs) { if (!rs.isFullyFetched()) rs.fetchMoreResults(); for (Row row : rs) { accumulator().accept(row, pendingResults()); if (2000 == rs.getAvailableWithoutFetching() && !rs.isFullyFetched()) { rs.fetchMoreResults(); } if (0 == rs.getAvailableWithoutFetching()) break; } <START> if (rs.getExecutionInfo().getPagingState() == null) return Call.create(pendingResults()); <END> return new AutoValue_AccumulateAllResults_FetchMoreResults(rs).flatMap(this); }</code><technical_language>I presume this means out of pages.</technical_language>

Target:
@Override public Call<T> map(ResultSet rs) { while (rs.getAvailableWithoutFetching() > 0) { accumulator().accept(rs.one(), pendingResults()); } return rs.getExecutionInfo().getPagingState() == null && rs.isExhausted() ? Call.create(pendingResults()) : FetchMoreResults.create(rs).flatMap(this); }
Source:
<code>protected void storage(Instance instance, Map<String, Object> data) { List<Volume> volumes = getObjectManager().children(instance, Volume.class); for (Volume volume : volumes) { if (volume.getDeviceNumber() == 0) { remove(volume, data); } else { execute("volume.detach", volume, null); } } List<Mount> mounts = getObjectManager().find(Mount.class, MOUNT.REMOVED, null, MOUNT.INSTANCE_ID, instance.getId()); <START> for (Mount mount : mounts) { <END> objectProcessManager.scheduleStandardProcess(StandardProcess.DEACTIVATE, mount, data); } }</code><technical_language>if mount is in inactive/removing state? Do want exclude well</technical_language>

Target:
protected void storage(Instance instance, Map<String, Object> data) { List<Volume> volumes = getObjectManager().children(instance, Volume.class); for (Volume volume : volumes) { if (volume.getDeviceNumber() == 0) { remove(volume, data); } else { execute("volume.detach", volume, null); } } Map<Object, Object> criteria = new HashMap<Object, Object>(); criteria.put(MOUNT.REMOVED, new Condition(ConditionType.NULL)); criteria.put(MOUNT.STATE, new Condition(ConditionType.NOTIN, MountDeactivate.MOUNT_STATES)); criteria.put(MOUNT.INSTANCE_ID, instance.getId()); List<Mount> mounts = getObjectManager().find(Mount.class, criteria); for (Mount mount : mounts) { objectProcessManager.scheduleStandardProcess(StandardProcess.DEACTIVATE, mount, data); } }
Source:
<code>public boolean loadSegment(final DataSegment segment) { final SettableSupplier<Boolean> resultSupplier = new SettableSupplier<>(); dataSources.compute( segment.getDataSource(), (k, v) -> { final DataSourceState dataSourceState = v == null ? new DataSourceState() : v; final VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSourceState.getTimeline(); final PartitionHolder<ReferenceCountingSegment> entry = loadedIntervals.findEntry( segment.getInterval(), segment.getVersion() ); if ((entry != null) && (entry.getChunk(segment.getShardSpec().getPartitionNum()) != null)) { log.warn("Told to load an adapter for segment[%s] that already exists", segment.getId()); resultSupplier.set(false); } else { final Segment adapter; try { adapter = getAdapter(segment); } <START> catch (SegmentLoadingException e) { <END> throw new RuntimeException(e); } loadedIntervals.add( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(new ReferenceCountingSegment(adapter)) ); dataSourceState.addSegment(segment); resultSupplier.set(true); } return dataSourceState; } ); return resultSupplier.get(); }</code><technical_language>SegmentLoadingException is specifically checked for in a places treat differently a generic runtime exception. Please it</technical_language>

Target:
public boolean loadSegment(final DataSegment segment) throws SegmentLoadingException { final Segment adapter = getAdapter(segment); final SettableSupplier<Boolean> resultSupplier = new SettableSupplier<>(); dataSources.compute( segment.getDataSource(), (k, v) -> { final DataSourceState dataSourceState = v == null ? new DataSourceState() : v; final VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSourceState.getTimeline(); final PartitionHolder<ReferenceCountingSegment> entry = loadedIntervals.findEntry( segment.getInterval(), segment.getVersion() ); if ((entry != null) && (entry.getChunk(segment.getShardSpec().getPartitionNum()) != null)) { log.warn("Told to load an adapter for segment[%s] that already exists", segment.getId()); resultSupplier.set(false); } else { loadedIntervals.add( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(new ReferenceCountingSegment(adapter)) ); dataSourceState.addSegment(segment); resultSupplier.set(true); } return dataSourceState; } ); return resultSupplier.get(); }
Source:
<code><START> protected Double getDoubleValue(Object o) { <END> if (o == null) { return null; } if (o instanceof Integer) { return (double) ((Integer)o).intValue(); } if (o instanceof Double) { return ((Double)o).doubleValue(); } try { return new Double(o.toString()).doubleValue(); } catch (NumberFormatException e) { return null; } }</code><technical_language>changed return type Double act returning double. For example, is Double, doubleValue() instead of returning object cast Double</technical_language>

Target:
protected Double getDoubleValue(Object o) { if (o == null) { return null; } if (o instanceof Integer) { return ((Integer)o).doubleValue(); } if (o instanceof Double) { return (Double) o; } try { return new Double(o.toString()); } catch (NumberFormatException e) { return null; } }
Source:
<code>static <T> T walkParentLoggerNames(String startName, Function<String, T> nameFunction) { if (startName == null) return null; String nameSegment = startName; while (nameSegment.length() > 0) { T ret = nameFunction.apply(nameSegment); if (ret != null) return ret; int idx = nameSegment.lastIndexOf('.'); if (idx >= 0) nameSegment = nameSegment.substring(0, idx); else <START> break; <END> } return null; }</code><technical_language>Segment ROOT_LOGGER_NAME, empty string</technical_language>

Target:
static <T> T walkParentLoggerNames(String startName, Function<String, T> nameFunction) { if (startName == null) return null; String nameSegment = startName; while (nameSegment.length() > 0) { T ret = nameFunction.apply(nameSegment); if (ret != null) return ret; int idx = nameSegment.lastIndexOf('.'); if (idx >= 0) nameSegment = nameSegment.substring(0, idx); else break; } return nameFunction.apply(Logger.ROOT_LOGGER_NAME); }
Source:
<code>public void configure(WebSecurity web) throws Exception { web.ignoring().requestMatchers((RequestMatcher) request -> CACHED_RESOURCE_HANDLERS.stream() <START> .map(handlerName -> requestMappingContextDictionary.getPattern(handlerName, siteResolver.resolveSite(request))) <END> .filter(Objects::nonNull) .map(RequestMappingContext::getPattern) .anyMatch(handlerPattern -> new AntPathMatcher().match(handlerPattern, request.getServletPath())) ); }</code><technical_language>run auto-formatter here? Operations stream indented a more</technical_language>

Target:
public void configure(WebSecurity web) throws Exception { web.ignoring().requestMatchers((RequestMatcher) request -> CACHED_RESOURCE_HANDLERS.stream() .map(handlerName -> requestMappingContextDictionary.getPattern(handlerName, siteResolver.resolveSite(request))) .filter(Objects::nonNull) .map(RequestMappingContext::getPattern) .anyMatch(handlerPattern -> ANT_PATH_MATCHER.match(handlerPattern, request.getServletPath())) ); }
Source:
<code>public void setConfiguration(String key, Text value) { if (mPointConfiguration.keySet().contains(key)) { <START> mPointConfiguration.remove(key); <END> mPointConfiguration.put(key, value); } else { mConfiguration.put(key, value); } }</code><technical_language>Minor, I this is redundant; put overwrite current value</technical_language>

Target:
public void setConfiguration(String key, Text value) { if (mPointConfiguration.keySet().contains(key)) { mPointConfiguration.put(key, value); } else { mConfiguration.put(key, value); } }
Source:
<code>private AlternateHandle openAlternate(File objdir) throws IOException { final File parent = objdir.getParentFile(); if (FileKey.isGitRepository(parent, fs)) { FileKey key = FileKey.exact(parent, fs); FileRepository db = (FileRepository) RepositoryCache.open(key); return new AlternateRepository(db); } <START> ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, shallowFile); <END> return new AlternateHandle(db); }</code><technical_language>alternate this repository's shallow file. Define alternate a shallow file of null handle this case in getShallowCommits() shallowFile == null means empty set</technical_language>

Target:
private AlternateHandle openAlternate(File objdir) throws IOException { final File parent = objdir.getParentFile(); if (FileKey.isGitRepository(parent, fs)) { FileKey key = FileKey.exact(parent, fs); FileRepository db = (FileRepository) RepositoryCache.open(key); return new AlternateRepository(db); } ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null); return new AlternateHandle(db); }