auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private SweepResults runInternal( TableReference tableRef, SweepBatchConfig batchConfig, byte[] startRow, RunType runType) { Preconditions.checkNotNull(tableRef, "tableRef cannot be null"); Preconditions.checkState(!AtlasDbConstants.hiddenTables.contains(tableRef)); if (tableRef.getQualifiedName().startsWith(AtlasDbConstants.NAMESPACE_PREFIX)) { log.warn("The sweeper should not be run on tables passed through namespace mapping."); return SweepResults.createEmptySweepResult(); } if (keyValueService.getMetadataForTable(tableRef).length == 0) { log.warn("The sweeper tried to sweep table '{}', but the table does not exist. Skipping table.", UnsafeArg.of("table name", tableRef)); return SweepResults.createEmptySweepResult(); } <START> SweepStrategy sweepStrategy = SweepStrategy.THOROUGH; <END> Optional<Sweeper> sweeper = Sweeper.of(sweepStrategy); if (!sweeper.isPresent()) { return SweepResults.createEmptySweepResult(); } return doRun(tableRef, batchConfig, startRow, runType, sweeper.get()); }</code><technical_language>I this is do-not-merge :)</technical_language>

Target:
private SweepResults runInternal( TableReference tableRef, SweepBatchConfig batchConfig, byte[] startRow, RunType runType) { Preconditions.checkNotNull(tableRef, "tableRef cannot be null"); Preconditions.checkState(!AtlasDbConstants.hiddenTables.contains(tableRef)); if (tableRef.getQualifiedName().startsWith(AtlasDbConstants.NAMESPACE_PREFIX)) { log.warn("The sweeper should not be run on tables passed through namespace mapping."); return SweepResults.createEmptySweepResult(); } if (keyValueService.getMetadataForTable(tableRef).length == 0) { log.warn("The sweeper tried to sweep table '{}', but the table does not exist. Skipping table.", UnsafeArg.of("table name", tableRef)); return SweepResults.createEmptySweepResult(); } SweepStrategy sweepStrategy = sweepStrategyManager.get().getOrDefault(tableRef, SweepStrategy.CONSERVATIVE); Optional<Sweeper> sweeper = Sweeper.of(sweepStrategy); if (!sweeper.isPresent()) { return SweepResults.createEmptySweepResult(); } return doRun(tableRef, batchConfig, startRow, runType, sweeper.get()); }
Source:
<code>VersionKey guess() { IService service = OpenShiftServerUtils.getService(server); if (service != null) { IProject project = service.getProject(); if (project != null) { List<IBuildConfig> buildConfigs = project.getResources(ResourceKind.BUILD_CONFIG); if (buildConfigs != null) { IBuildConfig buildConfig = ResourceUtils.getBuildConfigForService(service, buildConfigs); DockerImageURI imageUri = OpenShiftServerUtils.getImageUri(buildConfig); <START> return knowImages.get(imageUri.getName()); <END> } } } return null; }</code><technical_language>if imageUri == null</technical_language>

Target:
VersionKey guess() { IService service = OpenShiftServerUtils.getService(server); if (service != null) { IProject project = service.getProject(); if (project != null) { List<IBuildConfig> buildConfigs = project.getResources(ResourceKind.BUILD_CONFIG); if (buildConfigs != null) { IBuildConfig buildConfig = ResourceUtils.getBuildConfigForService(service, buildConfigs); if (buildConfig != null) { DockerImageURI imageUri = ResourceUtils.getImageUri(buildConfig); if (imageUri != null) { return knowImages.get(imageUri.getName()); } } } } } return null; }
Source:
<code>private void addTags(Class<?> clazz, CucumberOptions options, RuntimeOptionsBuilder args) { String tagExpression = options.tags(); if (!tagExpression.isEmpty()) { try { args.addTagFilter(TagExpressionParser.parse(tagExpression)); } catch (TagExpressionException tee) { <START> throw new IllegalArgumentException(String.format("%s at '%s'", tee.getMessage(), clazz.getName()), tee); <END> } } }</code><technical_language>generally speaking capture exceptions close source. I moved try-catch parse method here</technical_language>

Target:
private void addTags(Class<?> clazz, CucumberOptions options, RuntimeOptionsBuilder args) { String tagExpression = options.tags(); if (!tagExpression.isEmpty()) { try { args.addTagFilter(TagExpressionParser.parse(tagExpression)); } catch (TagExpressionException tee) { throw new IllegalArgumentException(String.format("Invalid tag expression at '%s'", clazz.getName()), tee); } } }
Source:
<code>public void testSTRs() { <START> assertEquals(VariantType.TANDEM_REPEAT, VariantClassifier.getVariantClassification("(A)5", "(A)7", 4)); <END> }</code><technical_language>A short tandem repeat reference is "A" alternate is "AAAAA", displayed explicitly instead of syntax "(A)5"</technical_language>

Target:
public void testSTRs() { assertEquals(VariantType.TANDEM_REPEAT, VariantClassifier.getVariantClassification("(A)5", "(A)7", 4)); assertEquals(VariantType.TANDEM_REPEAT, VariantClassifier.getVariantClassification("AAAAA", "AAAAAAA", 4)); }
Source:
<code>void ensureOpen(final AsyncCompletionHandler<Void> handler) { try { if (channel != null) { handler.completed(null); } else { channel = AsynchronousSocketChannel.open(); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); channel.connect(serverAddress.getSocketAddress(), null, new CompletionHandler<Void, Object>() { @Override public void completed(final Void result, final Object attachment) { handler.completed(null); } @Override public void failed(final Throwable exc, final Object attachment) { <START> if (exc instanceof ConnectException) { <END> handler.failed(new MongoSocketOpenException("Exception opening socket", serverAddress, exc)); } else { handler.failed(exc); } } }); } } catch (IOException e) { throw new MongoSocketOpenException("Exception opening socket", serverAddress, e); } }</code><technical_language>Is this exception wrap</technical_language>

Target:
void ensureOpen(final AsyncCompletionHandler<Void> handler) { try { if (channel != null) { handler.completed(null); } else { channel = AsynchronousSocketChannel.open(); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, settings.isKeepAlive()); if (settings.getSendBufferSize() > 0) { channel.setOption(StandardSocketOptions.SO_RCVBUF, settings.getReceiveBufferSize()); } if (settings.getSendBufferSize() > 0) { channel.setOption(StandardSocketOptions.SO_SNDBUF, settings.getReceiveBufferSize()); } channel.connect(serverAddress.getSocketAddress(), null, new CompletionHandler<Void, Object>() { @Override public void completed(final Void result, final Object attachment) { handler.completed(null); } @Override public void failed(final Throwable exc, final Object attachment) { if (exc instanceof ConnectException) { handler.failed(new MongoSocketOpenException("Exception opening socket", getAddress(), exc)); } else { handler.failed(exc); } } }); } } catch (IOException e) { throw new MongoSocketOpenException("Exception opening socket", serverAddress, e); } }
Source:
<code>public static Map<Character, Integer> getPileupBaseCounts(final SamLocusIterator.LocusInfo locus) { int aCount = 0, cCount = 0, gCount = 0, tCount = 0; for (final SamLocusIterator.RecordAndOffset rec : locus.getRecordAndPositions()) { switch (Character.toUpperCase(rec.getReadBase())) { case 'A': ++aCount; break; case 'C': ++cCount; break; case 'G': ++gCount; break; case 'T': ++tCount; break; default: break; } } <START> final Map<Character, Integer> baseCounts = new HashMap<>(); <END> baseCounts.put('A', aCount); baseCounts.put('C', cCount); baseCounts.put('G', gCount); baseCounts.put('T', tCount); return baseCounts; }</code><technical_language>EnumMap<Nucleotide, Integer> a bit cleaner faster if works</technical_language>

Target:
static Nucleotide.Counter getPileupBaseCounts(final SamLocusIterator.LocusInfo locus) { final Nucleotide.Counter result = new Nucleotide.Counter(); for (final SamLocusIterator.RecordAndOffset rec : locus.getRecordAndPositions()) { result.add(rec.getReadBase()); } return result; }
Source:
<code>@Override public void remove() { try { <START> QueueFile.this.remove(); <END> } catch (IOException e) { throw new RuntimeException(e); } size = elementCount; cursor--; }</code><technical_language>This honor contract of iterator's remove. In fact, support this atomically a single file</technical_language>

Target:
@Override public void remove() { lastElementIndex--; if (lastElementIndex != 0) { throw new UnsupportedOperationException("This iterator can only remove " + "elements at the head of the QueueFile."); } try { QueueFile.this.remove(); } catch (IOException e) { throw new RuntimeException(e); } size = elementCount; cursor--; }
Source:
<code>private void checkAlgorithm(String algorithm) { if (isAsymmetricEncryption(algorithm) && !IS_ALGORITHM_AVAILABLE) { <START> log.warn("Non-symmetric encryption '{}' has been configured," + <END> "but the version of aws-java-sdk you are using is outdated and does not support it. " + "Please upgrade to a more recent version.", algorithm); } }</code><technical_language>Asymmetric maybe</technical_language>

Target:
private void checkAlgorithm(String algorithm) { if (isAsymmetricEncryption(algorithm) && !IS_ALGORITHM_AVAILABLE) { log.warn("Asymmetric encryption '{}' has been configured," + "but the version of aws-java-sdk you are using is outdated and does not support it. " + "Please upgrade to a more recent version.", algorithm); } }
Source:
<code>protected void updateUI(int orientation) { if (orientation == Configuration.ORIENTATION_LANDSCAPE) { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.GONE); } else { if (transcriptAdapter == null) { messageContainer.setVisibility(View.VISIBLE); transcriptListView.setVisibility(View.GONE); initTranscriptListView(); } else { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.VISIBLE); transcriptListLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { transcriptListView.getViewTreeObserver().removeOnGlobalLayoutListener(this); final float transcriptRowHeight = getResources().getDimension(R.dimen.transcript_row_height); final float listviewHeight = transcriptListView.getHeight(); topOffset = (listviewHeight / 2) - (transcriptRowHeight / 2); } }; transcriptListView.getViewTreeObserver().addOnGlobalLayoutListener(transcriptListLayoutListener); } } <START> if(getActivity() instanceof VideoPlayerFullScreenListener) ((VideoPlayerFullScreenListener) getActivity()).isVideoPlayerFullScreen(orientation == Configuration.ORIENTATION_LANDSCAPE); <END> }</code><technical_language>statements if conditions {}</technical_language>

Target:
protected void updateUI(int orientation) { if (orientation == Configuration.ORIENTATION_LANDSCAPE) { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.GONE); } else { if (transcriptAdapter == null) { messageContainer.setVisibility(View.VISIBLE); transcriptListView.setVisibility(View.GONE); initTranscriptListView(); } else { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.VISIBLE); transcriptListLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { transcriptListView.getViewTreeObserver().removeOnGlobalLayoutListener(this); final float transcriptRowHeight = getResources().getDimension(R.dimen.transcript_row_height); final float listviewHeight = transcriptListView.getHeight(); topOffset = (listviewHeight / 2) - (transcriptRowHeight / 2); } }; transcriptListView.getViewTreeObserver().addOnGlobalLayoutListener(transcriptListLayoutListener); } } }
Source:
<code>public void <START> test_sendfile_null() <END> throws Exception { try { Libcore.os.sendfile(FileDescriptor.out, FileDescriptor.in, null, 0); fail(); } catch (NullPointerException expected) { } }</code><technical_language>EINVAL is expected for FileDescriptor.out / FileDescriptor.in. This is expected work for descriptors "regular" files, work if in / out pipes sockets (which are, in some configs. man-page weasel words this "EINVAL... mmap(2)-like operation is for in_fd,"</technical_language>

Target:
public void test_sendfile_null() throws Exception { File in = createTempFile("test_sendfile_null", "Hello, world!"); try { assertEquals("Hello", checkSendfile(true, in, null, "Hello".length())); assertEquals("Hello", checkSendfile(false, in, null, "Hello".length())); } finally { in.delete(); } }
Source:
<code><START> public static long[] encodePoint( int keyId, CoordinateReferenceSystem crs, double[] coordinate ) throws IllegalArgumentException <END> { if ( coordinate.length > 3 ) { throw new UnsupportedOperationException( "Points with more than 3 dimensions are not supported in the PropertyStore" ); } long keyAndType = keyId | (((long) (PropertyType.GEOMETRY.intValue()) << StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS)); long gtype_bits = GeometryType.GEOMETRY_POINT.gtype << (StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS + 4); long dimension_bits = ((long) coordinate.length) << (StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS + 8); long crsTableId_bits = ((long) crs.table.tableId) << (StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS + 12); long crsCode_bits = ((long) crs.code) << (StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS + 16); long[] data = new long[1 + coordinate.length]; data[0] = keyAndType | gtype_bits | dimension_bits | crsTableId_bits | crsCode_bits; for ( int i = 0; i < coordinate.length; i++ ) { data[1 + i] = Double.doubleToLongBits( coordinate[i] ); } return data; }</code><technical_language>magic numbers masks extracted constants proper naming for future readers convenience</technical_language>

Target:
public static long[] encodePoint( int keyId, CoordinateReferenceSystem crs, double[] coordinate ) { if ( coordinate.length > GeometryType.getMaxSupportedDimensions() ) { throw new UnsupportedOperationException( "Points with more than " + GeometryType.getMaxSupportedDimensions() + " dimensions are not supported" ); } int idBits = StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS; long keyAndType = keyId | (((long) (PropertyType.GEOMETRY.intValue()) << idBits)); long gtype_bits = GeometryType.GEOMETRY_POINT.gtype << (idBits + 4); long dimension_bits = ((long) coordinate.length) << (idBits + 8); long crsTableId_bits = ((long) crs.getTable().getTableId()) << (idBits + 12); long crsCode_bits = ((long) crs.getCode()) << (idBits + 16); long[] data = new long[1 + coordinate.length]; data[0] = keyAndType | gtype_bits | dimension_bits | crsTableId_bits | crsCode_bits; for ( int i = 0; i < coordinate.length; i++ ) { data[1 + i] = Double.doubleToLongBits( coordinate[i] ); } return data; }
Source:
<code>private void persistThingEnableStatus(ThingUID thingUID, boolean enabled) { <START> if (storage != null) { <END> logger.debug("Cannot persist thing enable status. Storage unavailable."); } logger.debug("Thing with UID will be persisted as {}.", thingUID, enabled?"enabled.":"disabled."); if (enabled) { storage.remove(thingUID.getAsString()); } else { storage.put(thingUID.getAsString(), enabled); } }</code><technical_language>I guess storage == null. I suggest return in this case get a NPE later</technical_language>

Target:
private void persistThingEnableStatus(ThingUID thingUID, boolean enabled) { if (storage == null) { logger.debug("Cannot persist enable status of thing with UID {}. Persistent storage unavailable.", thingUID); return; } logger.debug("Thing with UID will be persisted as {}.", thingUID, enabled ? "enabled." : "disabled."); if (enabled) { storage.remove(thingUID.getAsString()); } else { storage.put(thingUID.getAsString(), ""); } }
Source:
<code><START> public void uninstallFeatures( <END> long maxWaitTime, EnumSet<FeaturesService.Option> options, String feature, String... additionalFeatures) throws InterruptedException { Set<String> featuresToUninstall = featuresFromNames(feature, additionalFeatures) .filter(featuresService::isInstalled) .map(Feature::getName) .collect(Collectors.toSet()); String featureNames = String.join(", ", featuresToUninstall); LOGGER.info("Uninstalling the following features: [{}]", featureNames); long startTime = System.currentTimeMillis(); try { featuresService.uninstallFeatures(featuresToUninstall, options); } catch (Exception e) { throw new SynchronizedInstallerException( "Failed to uninstall features [" + String.join(",", featuresToUninstall) + "]", e); } waitForBundles(getRemainingTime(startTime, maxWaitTime)); LOGGER.info( "Finished uninstalling features in ms", featureNames, (System.currentTimeMillis() - startTime)); }</code><technical_language>if resulting set is empty</technical_language>

Target:
public void uninstallFeatures( long maxWaitTime, EnumSet<FeaturesService.Option> options, String feature, String... additionalFeatures) throws InterruptedException { Set<String> featuresToUninstall = featuresFromNames(feature, additionalFeatures) .filter(featuresService::isInstalled) .map(Feature::getName) .collect(Collectors.toSet()); if (featuresToUninstall.isEmpty()) { return; } String featureNames = String.join(", ", featuresToUninstall); LOGGER.info("Uninstalling the following features: [{}]", featureNames); long startTime = System.currentTimeMillis(); try { featuresService.uninstallFeatures(featuresToUninstall, options); } catch (Exception e) { throw new SynchronizedInstallerException( "Failed to uninstall features [" + String.join(", ", featuresToUninstall) + "]", e); } waitForBundles(getRemainingTime(startTime, maxWaitTime)); LOGGER.info( "Finished uninstalling features in ms", featureNames, (System.currentTimeMillis() - startTime)); }
Source:
<code>public void testExecuteQueryWithEmptyOption() throws Exception { String query = "status:open"; String option = ""; List<GerritQueryResult> results = null; try { <START> results = executeQuery(query, option); <END> } catch (GerritException e) { exception.expect(GerritHttpException.class); exception.expectMessage(HTTP_ERROR_400); return; } assertNotNull(results); }</code><technical_language>is example: exception.expect(GerritHttpException.class); exception.expectMessage(HTTP_ERROR_400); executeQuery(query, option);</technical_language>

Target:
public void testExecuteQueryWithEmptyOption() throws Exception { String query = "status:open"; String option = ""; List<GerritQueryResult> results = null; results = executeQuery(query, option); assertNotNull(results); }
Source:
<code>private void setFinalResult( SpeculativeExecution execution, Connection connection, Message.Response response) { if (!isDone.compareAndSet(false, true)) { if (logger.isTraceEnabled()) logger.trace("[{}] Got beaten to setting the result", execution.id); return; } if (logger.isTraceEnabled()) logger.trace("[{}] Setting final result", execution.id); cancelPendingExecutions(execution); try { if (timerContext != null) timerContext.stop(); ExecutionInfo info; int speculativeExecutions = executionIndex.get() - 1; if (execution.position == 0 && speculativeExecutions == 0 && triedHosts == null && execution.retryConsistencyLevel == null && response.getCustomPayload() == null) { info = execution.current.defaultExecutionInfo; } else { List<Host> hosts; if (triedHosts == null) { hosts = ImmutableList.of(execution.current); } else { hosts = triedHosts; hosts.add(execution.current); } info = new ExecutionInfo( speculativeExecutions, execution.position, hosts, execution.retryConsistencyLevel, response.getCustomPayload()); } callback.onSet(connection, response, info, statement, System.nanoTime() - startTime); if (logger.isWarnEnabled() && response.warnings != null && !response.warnings.isEmpty() <START> && Boolean.getBoolean(RequestHandler.LOG_REQUEST_WARNINGS_PROPERTY)) { <END> for (String warning : response.warnings) { logger.warn(warning); } } } catch (Exception e) { callback.onException( connection, new DriverInternalError( "Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime, 0); } }</code><technical_language>happen if property RequestHandler.LOG_REQUEST_WARNINGS_PROPERTY)) set</technical_language>

Target:
private void setFinalResult( SpeculativeExecution execution, Connection connection, Message.Response response) { if (!isDone.compareAndSet(false, true)) { if (logger.isTraceEnabled()) logger.trace("[{}] Got beaten to setting the result", execution.id); return; } if (logger.isTraceEnabled()) logger.trace("[{}] Setting final result", execution.id); cancelPendingExecutions(execution); try { if (timerContext != null) timerContext.stop(); ExecutionInfo info; int speculativeExecutions = executionIndex.get() - 1; if (execution.position == 0 && speculativeExecutions == 0 && triedHosts == null && execution.retryConsistencyLevel == null && response.getCustomPayload() == null) { info = execution.current.defaultExecutionInfo; } else { List<Host> hosts; if (triedHosts == null) { hosts = ImmutableList.of(execution.current); } else { hosts = triedHosts; hosts.add(execution.current); } info = new ExecutionInfo( speculativeExecutions, execution.position, hosts, execution.retryConsistencyLevel, response.getCustomPayload()); } callback.onSet(connection, response, info, statement, System.nanoTime() - startTime); if (response.warnings != null && !response.warnings.isEmpty() && !Boolean.getBoolean(RequestHandler.DISABLE_QUERY_WARNING_LOGS) && logger.isWarnEnabled()) { logServerWarnings(response.warnings); } } catch (Exception e) { callback.onException( connection, new DriverInternalError( "Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime, 0); } }
Source:
<code>T select( int slot ) { if ( instances[slot] == null ) { assertOpen(); <START> instances[slot] = factory.apply( slot ); <END> } return instances[slot]; }</code><technical_language>I a race close. T1 check assertOpen T2 close() T1 factory.apply( slot )</technical_language>

Target:
T select( int slot ) { if ( instances[slot] == null ) { throw new IllegalStateException( "Instance is not instantiated" ); } return instances[slot]; }
Source:
<code>public static DateJsonUnmarshaller getInstance(TimestampFormat format) { if (instance == null || !instance.format.equals(format)) <START> instance = new DateJsonUnmarshaller(format); <END> return instance; }</code><technical_language>Put brackets if statement body</technical_language>

Target:
public static DateJsonUnmarshaller getInstance(TimestampFormat format) { if (instance == null || !instance.format.equals(format)) { instance = new DateJsonUnmarshaller(format); } return instance; }
Source:
<code>public void testBroadcastwithInitialEvals() throws InterruptedException { final ExecutorService executor = Executors.newFixedThreadPool(NUM_THREAD); final AtomicInteger operationIdCounter = new AtomicInteger(0); final int numMoves = 5; final int numActiveEvals = NUM_INIT_EVALS; final int numOtherEvals = numActiveEvals - 2; final CountDownLatch movedLatch = new CountDownLatch(numMoves); final FinishedCallback finishedCallback = new FinishedCallback(movedLatch); runRandomMove(executor, operationIdCounter, numMoves, numActiveEvals, finishedCallback); movedLatch.await(20000, TimeUnit.MILLISECONDS); final int numBroadcasts = numOtherEvals * (numMoves - finishedCallback.getNumFailedMoves()); while (messageSender.getBroadcastCount() < numBroadcasts) { Thread.sleep(1000); } <START> Thread.sleep(2000); <END> assertEquals(numBroadcasts, messageSender.getBroadcastCount()); }</code><technical_language>kindly explain is this additional sleep for</technical_language>

Target:
public void testBroadcastwithInitialEvals() throws InterruptedException { final ExecutorService executor = Executors.newFixedThreadPool(NUM_THREAD); final AtomicInteger operationIdCounter = new AtomicInteger(0); final int numMoves = 5; final int numActiveEvals = NUM_INIT_EVALS; final int numOtherEvals = numActiveEvals - 2; final CountDownLatch movedLatch = new CountDownLatch(numMoves); final FinishedCallback finishedCallback = new FinishedCallback(movedLatch); runRandomMove(executor, operationIdCounter, numMoves, numActiveEvals, finishedCallback); assertTrue("Move does not finish within time", movedLatch.await(20000, TimeUnit.MILLISECONDS)); int loop = 0; final int numBroadcasts = numOtherEvals * (numMoves - finishedCallback.getNumFailedMoves()); while (messageSender.getBroadcastCount() < numBroadcasts) { loop++; Thread.sleep(WAIT_INTERVAL_MS); } Thread.sleep(WAIT_INTERVAL_MS * (loop + 1)); assertEquals("There are more broadcasts above expectation", numBroadcasts, messageSender.getBroadcastCount()); }
Source:
<code>void writeRename(ReftableWriter w) throws IOException { long idx = reftableDatabase.nextUpdateIndex(); w.setMinUpdateIndex(idx).setMaxUpdateIndex(idx).begin(); List<Ref> refs = new ArrayList<>(3); Ref dest = destination.getRef(); Ref head = <START> exactRef("HEAD"); <END> if (head != null && head.isSymbolic() && head.getLeaf().getName().equals(source.getName())) { head = new SymbolicRef("HEAD", dest, idx); refs.add(head); } ObjectId objId = source.getRef().getObjectId(); refs.add(new ObjectIdRef.PeeledNonTag(Ref.Storage.NEW, destination.getName(), objId)); refs.add(new ObjectIdRef.Unpeeled(Ref.Storage.NEW, source.getName(), null)); w.sortAndWriteRefs(refs); PersonIdent who = destination.getRefLogIdent(); if (who == null) { who = new PersonIdent(fileRepository); } if (!destination.getRefLogMessage().isEmpty()) { List<String> refnames = refs.stream().map(r -> r.getName()) .collect(Collectors.toList()); Collections.sort(refnames); for (String s : refnames) { ObjectId old = ("HEAD".equals(s) || s.equals(source.getName())) ? objId : ObjectId.zeroId(); ObjectId newId = ("HEAD".equals(s) || s.equals(destination.getName())) ? objId : ObjectId.zeroId(); w.writeLog(s, idx, who, old, newId, destination.getRefLogMessage()); } } }</code><technical_language>Constants.HEAD multiple occurrences</technical_language>

Target:
void writeRename(ReftableWriter w) throws IOException { long idx = reftableDatabase.nextUpdateIndex(); w.setMinUpdateIndex(idx).setMaxUpdateIndex(idx).begin(); List<Ref> refs = new ArrayList<>(3); Ref dest = destination.getRef(); Ref head = exactRef(Constants.HEAD); if (head != null && head.isSymbolic() && head.getLeaf().getName().equals(source.getName())) { head = new SymbolicRef(Constants.HEAD, dest, idx); refs.add(head); } ObjectId objId = source.getRef().getObjectId(); refs.add(new ObjectIdRef.PeeledNonTag(Ref.Storage.NEW, destination.getName(), objId)); refs.add(new ObjectIdRef.Unpeeled(Ref.Storage.NEW, source.getName(), null)); w.sortAndWriteRefs(refs); PersonIdent who = destination.getRefLogIdent(); if (who == null) { who = new PersonIdent(fileRepository); } if (!destination.getRefLogMessage().isEmpty()) { List<String> refnames = refs.stream().map(r -> r.getName()) .collect(Collectors.toList()); Collections.sort(refnames); for (String s : refnames) { ObjectId old = (Constants.HEAD.equals(s) || s.equals(source.getName())) ? objId : ObjectId.zeroId(); ObjectId newId = (Constants.HEAD.equals(s) || s.equals(destination.getName())) ? objId : ObjectId.zeroId(); w.writeLog(s, idx, who, old, newId, destination.getRefLogMessage()); } } }
Source:
<code>public StringBuilder GetTagIdAndChildrenIds() { StringBuilder builder = new StringBuilder(); builder.append(StringFormat.format("'%1$s'", gettag_id())); for (tags tag : _children) { <START> builder.append("," + tag.GetTagIdAndChildrenIds()); <END> } return builder; }</code><technical_language>builder.append(",").append(tag.GetTagIdAndChildrenIds());</technical_language>

Target:
public StringBuilder GetTagIdAndChildrenIds() { StringBuilder builder = new StringBuilder(); builder.append("'").append(gettag_id()).append("'"); for (tags tag : _children) { builder.append(",").append(tag.GetTagIdAndChildrenIds()); } return builder; }
Source:
<code>public Page<DiscussionComment> call() throws Exception { <START> List<String> requestedFields = Collections.singletonList("profile_image"); <END> return environment.getDiscussionAPI().getCommentsList(responseId, PAGE_SIZE, page, requestedFields); }</code><technical_language>This field defined a constant somewhere, part of enum set for compile-time safety checking</technical_language>

Target:
public Page<DiscussionComment> call() throws Exception { List<String> requestedFields = Collections.singletonList( DiscussionRequestFields.PROFILE_IMAGE.getQueryParamValue()); return environment.getDiscussionAPI().getCommentsList(responseId, PAGE_SIZE, page, requestedFields); }
Source:
<code>public void testUninstanciableLocalClass001() throws Exception { File outDir = AbstractTestTools.createTempDir(); List<Class<? extends IToolchain>> excludeList = new ArrayList<Class<? extends IToolchain>>(1); excludeList.add(JillBasedToolchain.class); excludeList.add(IncrementalToolchain.class); JackBasedToolchain toolchain = AbstractTestTools.getCandidateToolchain(JackBasedToolchain.class, excludeList); <START> File testOut = AbstractTestTools.createTempFile("FrontendTests-", "-testUninstanciableLocalClass001"); toolchain.setReporter(ReporterKind.DEFAULT, testOut); <END> toolchain.addToClasspath(toolchain.getDefaultBootClasspath()) .srcToLib( outDir, false, AbstractTestTools.getTestRootDir("com.android.jack.frontend.test004.jack")); String errString = AbstractTestTools.getFileContent(testOut); int warnIndex = errString.indexOf("WARNING:"); Assert.assertTrue(warnIndex != -1); warnIndex = errString.indexOf("WARNING:", warnIndex + 1); Assert.assertTrue(warnIndex != -1); Assert.assertTrue(errString.indexOf("WARNING:", warnIndex + 1) == -1); }</code><technical_language>a file instead of BAOS others before</technical_language>

Target:
public void testUninstanciableLocalClass001() throws Exception { File outDir = AbstractTestTools.createTempDir(); List<Class<? extends IToolchain>> excludeList = new ArrayList<Class<? extends IToolchain>>(1); excludeList.add(JillBasedToolchain.class); excludeList.add(IncrementalToolchain.class); JackBasedToolchain toolchain = AbstractTestTools.getCandidateToolchain(JackBasedToolchain.class, excludeList); ByteArrayOutputStream errOut = new ByteArrayOutputStream(); toolchain.setReporter(ReporterKind.DEFAULT, errOut); toolchain.addToClasspath(toolchain.getDefaultBootClasspath()) .srcToLib( outDir, false, AbstractTestTools.getTestRootDir("com.android.jack.frontend.test004.jack")); String errString = errOut.toString(); int warnIndex = errString.indexOf("WARNING:"); Assert.assertTrue(warnIndex != -1); warnIndex = errString.indexOf("WARNING:", warnIndex + 1); Assert.assertTrue(warnIndex != -1); Assert.assertTrue(errString.indexOf("WARNING:", warnIndex + 1) == -1); }
Source:
<code>protected synchronized void close(Exception cause) { if (isCleanClose(cause) && !isOpen()) { return; } super.close(cause); readExecutor.shutdownNow(); framedTransport.close(); if (isCleanClose(cause)) { LOGGER.info("transport closed"); } else { LOGGER.info("transport closed with cause: " + cause.getMessage()); } <START> signalClose(cause); <END> }</code><technical_language>signalClose is handled FTransport's close method</technical_language>

Target:
protected synchronized void close(Exception cause) { if (isCleanClose(cause) && !isOpen()) { return; } super.close(cause); readExecutor.shutdownNow(); framedTransport.close(); if (isCleanClose(cause)) { LOGGER.info("transport closed"); } else { LOGGER.info("transport closed with cause: " + cause.getMessage()); } }
Source:
<code>public void testEmptyState() throws IOException { try (TmpPath tmp_dir = new TmpPath()) { GlobalStreamId globalStreamId_a = new GlobalStreamId("a", "a"); String dir = tmp_dir.getPath(); LocalState ls = new LocalState(dir, true); <START> FileOutputStream data = FileUtils.openOutputStream(new File(dir, "12345")); <END> FileOutputStream version = FileUtils.openOutputStream(new File(dir, "12345.version")); Assert.assertNull(ls.get("c")); ls.put("a", globalStreamId_a); Assert.assertEquals(globalStreamId_a, ls.get("a")); } }</code><technical_language>streams closed. I try resources for</technical_language>

Target:
public void testEmptyState() throws IOException { try (TmpPath tmp_dir = new TmpPath()) { GlobalStreamId globalStreamId_a = new GlobalStreamId("a", "a"); String dir = tmp_dir.getPath(); LocalState ls = new LocalState(dir, true); FileUtils.touch(new File(dir, "12345")); FileUtils.touch(new File(dir, "12345.version")); Assert.assertNull(ls.get("c")); ls.put("a", globalStreamId_a); Assert.assertEquals(globalStreamId_a, ls.get("a")); } }
Source:
<code>public static String toLowerHyphen(String name) { StringBuilder result = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); <START> if (i > 0 && isUpercase(c)) { <END> result.append('-').append(toLowerCase(c)); } else if (isUpercase(c)) { result.append(toLowerCase(c)); } else { result.append(c); } } return result.toString(); }</code><technical_language>misspelled. leaving character capitalized</technical_language>

Target:
public static String toLowerHyphen(String name) { StringBuilder result = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isUpperCase(c)) { if (i != 0) result.append('-'); result.append(Character.toLowerCase(c)); } else { result.append(c); } } return result.toString(); }
Source:
<code>public String toString() { return "IncomingMessageEnvelope [systemStreamPartition=" + systemStreamPartition + ", offset=" + offset + <START> ", key=" + key + ", message=" + message + ", eventTime=" + eventTimeInstant.toEpochMilli() + <END> ", arrivalSystemNanoTime=" + arrivalSystemNanoTime + "]"; }</code><technical_language>This throw NPE if eventTimeInstant is null</technical_language>

Target:
public String toString() { return "IncomingMessageEnvelope [systemStreamPartition=" + systemStreamPartition + ", offset=" + offset + ", key=" + key + ", message=" + message + ", eventTime=" + eventTime + ", arrivalTime=" + arrivalTime + "]"; }
Source:
<code>private static Map<String, String> serializeContainerModelMap(Map<String, ContainerModel> containerModelMap) { Map<String, String> serializedContainerModelMap = new HashMap<>(); ObjectMapper samzaObjectMapper = SamzaObjectMapper.getObjectMapper(); String serializedContainerModel; for (Map.Entry<String, ContainerModel> containerModelEntry : containerModelMap.entrySet()) { <START> serializedContainerModel = ""; <END> try { serializedContainerModel = samzaObjectMapper.writeValueAsString(containerModelEntry.getValue()); } catch (IOException e) { LOG.error("Exception in serializing container model ", e); } finally { serializedContainerModelMap.put(containerModelEntry.getKey(), serializedContainerModel); } } return serializedContainerModelMap; }</code><technical_language>This empty string get put map. Jackson read correctly</technical_language>

Target:
private static String serializeContainerModelMap(Map<String, ContainerModel> containerModelMap) { ObjectMapper samzaObjectMapper = SamzaObjectMapper.getObjectMapper(); try { return samzaObjectMapper.writeValueAsString(containerModelMap); } catch (IOException e) { LOG.error("Exception in serializing container model ", e); } return null; }
Source:
<code>public static EntityData.Prefab readPrefab(BufferedReader reader) throws IOException { try { return newGson().fromJson(reader, EntityData.Prefab.class); } catch (JsonSyntaxException e) { <START> return null; <END> } }</code><technical_language>JsonSyntaxExcpetion is caught, signature IOException is thrown in case of error</technical_language>

Target:
public static EntityData.Prefab readPrefab(BufferedReader reader) throws IOException { try { return newGson().fromJson(reader, EntityData.Prefab.class); } catch (JsonSyntaxException e) { throw new IOException("Failed to load prefab", e); } }
Source:
<code>public void editBufferSize() throws Exception { final int value = 1024; <START> ModelNodeResult modelNodeResult = operations.readAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE); <END> modelNodeResult.assertSuccess(); try { new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, BUFFER_SIZE, String.valueOf(value)) .verifyFormSaved() .verifyAttribute(BUFFER_SIZE, value); } finally { operations.writeAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE, modelNodeResult.value()); } }</code><technical_language>Please rename originalBufferSizeResult originalResult</technical_language>

Target:
public void editBufferSize() throws Exception { final int value = 1024; final ModelNodeResult originalNodeResult = operations.readAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE); originalNodeResult.assertSuccess(); try { new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, BUFFER_SIZE, String.valueOf(value)) .verifyFormSaved() .verifyAttribute(BUFFER_SIZE, value); } finally { operations.writeAttribute(BUFFER_POOL_ADDRESS, BUFFER_SIZE, originalNodeResult.value()); } }
Source:
<code>public TupleConverter(GroupType parquetSchema, Schema pigSchema, boolean elephantBirdCompatible, boolean columnIndexAccess) { this.parquetSchema = parquetSchema; this.elephantBirdCompatible = elephantBirdCompatible; try { this.schemaSize = max(parquetSchema.getFieldCount(), pigSchema.getFields().size()); this.converters = new Converter[this.schemaSize]; for (int i = 0, c = 0; i < schemaSize; i++) { FieldSchema field = pigSchema.getField(i); Type type = null; if(parquetSchema.containsField(field.alias) || columnIndexAccess) { if(columnIndexAccess) { if(i >= parquetSchema.getFieldCount()) continue; <START> type = parquetSchema.getType(i); <END> }else { type = parquetSchema.getType(parquetSchema.getFieldIndex(field.alias)); } final int index = i; converters[c++] = newConverter(field, type, new ParentValueContainer() { @Override void add(Object value) { TupleConverter.this.set(index, value); } }, elephantBirdCompatible, columnIndexAccess); } } } catch (FrontendException e) { throw new ParquetDecodingException("can not initialize pig converter from:\n" + parquetSchema + "\n" + pigSchema, e); } }</code><technical_language>following? getType(columnIndexAccess, alias, i) { if (columnIndexAccess) { if (i < parquetSchema.getFieldCount()) { return parquetSchema.getType(i); } } else { if (parquetSchema.containsField(alias)) { return parquetSchema.getType(parquetSchema.getFieldIndex(alias)); } } return null } ... type = getType(columnIndexAccess, field.alias, i) if (type!= nul) { .... } logic types of access is intertwined hard follow. (also possibly reuse approach mentioned for schema converter.)</technical_language>

Target:
public TupleConverter(GroupType parquetSchema, Schema pigSchema, boolean elephantBirdCompatible, boolean columnIndexAccess) { this.parquetSchema = parquetSchema; this.elephantBirdCompatible = elephantBirdCompatible; try { this.schemaSize = max(parquetSchema.getFieldCount(), pigSchema.getFields().size()); this.converters = new Converter[this.schemaSize]; for (int i = 0, c = 0; i < schemaSize; i++) { FieldSchema field = pigSchema.getField(i); if(parquetSchema.containsField(field.alias) || columnIndexAccess) { Type type = getType(columnIndexAccess, field.alias, i); if(type != null) { final int index = i; converters[c++] = newConverter(field, type, new ParentValueContainer() { @Override void add(Object value) { TupleConverter.this.set(index, value); } }, elephantBirdCompatible, columnIndexAccess); } } } } catch (FrontendException e) { throw new ParquetDecodingException("can not initialize pig converter from:\n" + parquetSchema + "\n" + pigSchema, e); } }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Credentials credentials = getUserCredentials(request); if (credentials == null) { response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); <START> response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); <END> } }</code><technical_language>of redirects relative</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean acceptBasicAuthHeaders = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ACCEPT_BASIC_AUTH_HEADERS); boolean enableBasicAuth = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ENABLE_BASIC_AUTH); Credentials credentials = null; if (acceptBasicAuthHeaders) { credentials = getUserCredentials(request); } if (credentials != null) { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } else if (enableBasicAuth) { response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }
Source:
<code>public PostgreSQLConnector(Supplier<MetadataStorageConnectorConfig> config, Supplier<MetadataStorageTablesConfig> dbTables) { super(config, dbTables); final BasicDataSource datasource = getDatasource(); datasource.setDriverClassLoader(getClass().getClassLoader()); datasource.setDriverClassName("org.postgresql.Driver"); this.dbi = new DBI(datasource); <START> log.info("Configured PostgreSQL as the metadata storage"); <END> }</code><technical_language>this debug level</technical_language>

Target:
public PostgreSQLConnector(Supplier<MetadataStorageConnectorConfig> config, Supplier<MetadataStorageTablesConfig> dbTables) { super(config, dbTables); final BasicDataSource datasource = getDatasource(); datasource.setDriverClassLoader(getClass().getClassLoader()); datasource.setDriverClassName("org.postgresql.Driver"); this.dbi = new DBI(datasource); log.info("Configured PostgreSQL as metadata storage"); }
Source:
<code>public void restoreEquivalences(Publisher publisher) { Iterator<Content> content = contentLister.listContent(new ContentListingCriteria.Builder().forPublisher(publisher).build()); while (content.hasNext()) { Content c = (Content) content.next(); for (Alias alias : Iterables.filter(c.getAliases(), IS_EQUIVALENCE_ALIAS)) { Maybe<Identified> only = contentResolver.findByCanonicalUris(ImmutableSet.of(alias.getValue())).getFirstValue(); if (only.hasValue()) { c.addEquivalentTo((Described) only.requireValue()); <START> c.setAliases(Iterables.filter(c.getAliases(), Predicates.not(IS_EQUIVALENCE_ALIAS))); <END> write(c); } else { log.warn("Could not find equivalent content of for so not writing equivalence", alias.getValue(), c.getCanonicalUri()); } } } }</code><technical_language>a risk of losing alias this? removing alias safer</technical_language>

Target:
public void restoreEquivalences(Publisher publisher) { Iterator<Content> contentIterator = contentLister.listContent( new ContentListingCriteria.Builder() .forPublisher(publisher) .build() ); while (contentIterator.hasNext()) { Content content = contentIterator.next(); for (Alias alias : Iterables.filter(content.getAliases(), IS_EQUIVALENCE_ALIAS)) { Maybe<Identified> contentFromPurgedPublisher = contentResolver.findByCanonicalUris(ImmutableSet.of(alias.getValue())).getFirstValue(); if (contentFromPurgedPublisher.hasValue()) { content.addEquivalentTo((Described) contentFromPurgedPublisher.requireValue()); HashSet<Alias> aliases = Sets.newHashSet(content.getAliases()); aliases.remove(alias); content.setAliases(aliases); write(content); } else { log.warn("Could not find equivalent content of for so not writing equivalence", alias.getValue(), content.getCanonicalUri()); } } } }
Source:
<code>private Schema addForkliftPropertiesToSchema(Schema schema) throws IOException { String originalJson = schema.toString(false); <START> JsonNode propertiesField = mapper.readTree("{\"name\":\"forkliftProperties\",\"type\":\"string\",\"default\":\"\"," + <END> "\"doc\":\"Properties added to support forklift interfaces. Format is key,value entries delimited with new lines\"}"); ObjectNode schemaNode = (ObjectNode)mapper.readTree(originalJson); ArrayNode fieldsNode = (ArrayNode)schemaNode.get("fields"); fieldsNode.add(propertiesField); schemaNode.set("fields", fieldsNode); Schema.Parser parser = new Schema.Parser(); return parser.parse(mapper.writeValueAsString(schemaNode)); }</code><technical_language>This inline JSON hard read; this factored a constant</technical_language>

Target:
private Schema addForkliftPropertiesToSchema(Schema schema) throws IOException { String originalJson = schema.toString(false); JsonNode propertiesField = mapper.readTree(SCHEMA_FIELD_VALUE_PROPERTIES); ObjectNode schemaNode = (ObjectNode)mapper.readTree(originalJson); ArrayNode fieldsNode = (ArrayNode)schemaNode.get("fields"); fieldsNode.add(propertiesField); schemaNode.set("fields", fieldsNode); Schema.Parser parser = new Schema.Parser(); return parser.parse(mapper.writeValueAsString(schemaNode)); }
Source:
<code>public PaymentSearchResponse<TransactionResponse> searchPayments(Account account, Map<String, String> paramsAsMap) { paramsAsMap.put(PARAM_ACCOUNT_ID, account.getAccountId()); paramsAsMap.put(PARAM_TRANSACTION_TYPE, PAYMENT_TRANSACTION_TYPE); Response response = client .target(ledgerUriGenerator.transactionsURIWithParams(paramsAsMap)) .request() .accept(MediaType.APPLICATION_JSON_TYPE) .get(); if (response.getStatus() == SC_OK) { try { return response.readEntity(new GenericType<PaymentSearchResponse<TransactionResponse>>() { }); } catch (ProcessingException ex) { throw new SearchPaymentsException(ex); } } <START> throw new SearchRefundsException(response); <END> }</code><technical_language>SearchPaymentsException</technical_language>

Target:
public PaymentSearchResponse<TransactionResponse> searchPayments(Account account, Map<String, String> paramsAsMap) { paramsAsMap.put(PARAM_ACCOUNT_ID, account.getAccountId()); paramsAsMap.put(PARAM_TRANSACTION_TYPE, PAYMENT_TRANSACTION_TYPE); Response response = client .target(ledgerUriGenerator.transactionsURIWithParams(paramsAsMap)) .request() .accept(MediaType.APPLICATION_JSON_TYPE) .get(); if (response.getStatus() == SC_OK) { try { return response.readEntity(new GenericType<PaymentSearchResponse<TransactionResponse>>() { }); } catch (ProcessingException ex) { throw new SearchPaymentsException(ex); } } throw new SearchPaymentsException(response); }