auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); <START> final Flux<AmqpReceiveLink> receiveLinkMono = <END> connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: mode: [{}]" + " sessionEnabled? transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkMono.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete); }); }</code><technical_language>reason this is called Mono is a Flux</technical_language>

Target:
private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: mode: [{}]" + " sessionEnabled? transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); }
Source:
<code>private static Row getRowFromVersionedValue(MVTable table, long recKey, VersionedValue versionedValue) { Object value = versionedValue == null ? null : versionedValue.value; Row result = null; if (value != null) { Row result11; if(value instanceof Row) { result11 = (Row) value; assert result11.getKey() == recKey <START> : result11.getKey() + " != " + recKey; <END> } else { ValueArray array = (ValueArray) value; result11 = table.createRow(array.getList(), 0); result11.setKey(recKey); } result = result11; } return result; }</code><technical_language>Indendation is a multiplier of 4</technical_language>

Target:
private static Row getRowFromVersionedValue(MVTable table, long recKey, VersionedValue versionedValue) { Object value = versionedValue == null ? null : versionedValue.value; if (value == null) { return null; } Row result; if(value instanceof Row) { result = (Row) value; assert result.getKey() == recKey : result.getKey() + " != " + recKey; } else { ValueArray array = (ValueArray) value; result = table.createRow(array.getList(), 0); result.setKey(recKey); } return result; }
Source:
<code>public SaslServerBuilder setProviderSupplier(Supplier<Provider[]> providerSupplier) { this.providerSupplier = providerSupplier; <START> return this; <END> }</code><technical_language>good Assert.assertNotNull check providerSupplier passed in null</technical_language>

Target:
public SaslServerBuilder setProviderSupplier(Supplier<Provider[]> providerSupplier) { Assert.assertNotNull("providerSupplier", providerSupplier); this.providerSupplier = providerSupplier; return this; }
Source:
<code>protected CommandStatus run() { boolean sameFileExtension = checkFileExtension(); String[] destinationDirs = destination.toString().split("/"); if (sameFileExtension) { try { status = CommandStatus.RUNNING; Files.move(source, source.resolveSibling(destinationDirs[destinationDirs.length - 1]), REPLACE_EXISTING); } catch (IOException e) { <START> e.printStackTrace(); <END> status = CommandStatus.FAILED; return status; } } else { try { status = CommandStatus.RUNNING; Files.move(source, destination); } catch (IOException e) { try { Files.move(source, destination.resolve(source.getFileName())); } catch (IOException e1) { e.printStackTrace(); e1.printStackTrace(); return CommandStatus.FAILED; } } } return CommandStatus.SUCCESS; }</code><technical_language>Remove log</technical_language>

Target:
protected CommandStatus run() { boolean sameFileExtension = checkFileExtension(); String[] destinationDirs = destination.toString().split("/"); logger.info("Moving " + source + " to " + destination); if (sameFileExtension) { try { status = CommandStatus.RUNNING; Files.move(source, source.resolveSibling(destinationDirs[destinationDirs.length - 1]), REPLACE_EXISTING); } catch (IOException e) { logger.error( "The move type was identified as a name change in the same directory, but the move failed!"); logger.error("Returning failed.", e); status = CommandStatus.FAILED; return status; } } else { try { status = CommandStatus.RUNNING; Files.move(source, destination); } catch (IOException e) { try { Files.move(source, destination.resolve(source.getFileName())); } catch (IOException e1) { logger.error("File was supposed to move directories, but move failed!", e1); logger.error("Returning failed."); status = CommandStatus.FAILED; return status; } } } return CommandStatus.SUCCESS; }
Source:
<code>public void onCreate() { ICredentialsRepository iCredentialsRepository = new CredentialsLocalDataSource(); mGetUrlForWebViewsUseCase = new GetUrlForWebViewsUseCase(mDashboardActivity, iCredentialsRepository); IAsyncExecutor asyncExecutor = new AsyncExecutor(); IConnectivityManager mConnectivity = new ConnectivityManager(); IFileDownloader fileDownloader = new FileDownloader( mDashboardActivity.getApplicationContext().getFilesDir(), mDashboardActivity.getApplicationContext().getResources().openRawResource( R.raw.driveserviceprivatekey)); final MediaRepository mediaRepository = new MediaRepository(); mDownloadMediaUseCase = new DownloadMediaUseCase(asyncExecutor, fileDownloader, mConnectivity, mediaRepository, new Callback() { @Override public void onCancel(Exception ex) { if (ex instanceof UserRecoverableAuthIOException) { DashboardActivity.dashboardActivity.startActivityForResult( ((UserRecoverableAuthIOException) ex).getIntent(), REQUEST_AUTHORIZATION); return; } if (ex instanceof GooglePlayServicesAvailabilityIOException) { showDialog( ((GooglePlayServicesAvailabilityIOException) ex) .getConnectionStatusCode()); return; } } @Override public void showToast(String message) { Toast.makeText(mDashboardActivity.getApplicationContext(), message, Toast.LENGTH_LONG).show(); } @Override public void acquireGooglePlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable( PreferencesState.getInstance().getContext()); if (apiAvailability.isUserResolvableError(connectionStatusCode)) { showDialog(connectionStatusCode); } } @Override public void onSuccess(HashMap<String, String> syncedFiles) { int correctSyncedFiles = mediaRepository.updateSyncedFiles(syncedFiles); if (correctSyncedFiles > 0) { showToast(String.format("%d files synced", correctSyncedFiles)); } } @Override public void onRemove(String uid) { System.out.println( "downloadFile error (file extension not supported)" + uid); <START> mediaRepository.deleteModel(mediaRepository.findByUid(uid)); <END> } }); }</code><technical_language>a class of presentation layer invoke mediaRepository, this is a case responsibility</technical_language>

Target:
public void onCreate() { ICredentialsRepository iCredentialsRepository = new CredentialsLocalDataSource(); mGetUrlForWebViewsUseCase = new GetUrlForWebViewsUseCase(mDashboardActivity, iCredentialsRepository); IAsyncExecutor asyncExecutor = new AsyncExecutor(); IConnectivityManager mConnectivity = new ConnectivityManager(); IFileDownloader fileDownloader = new FileDownloader( mDashboardActivity.getApplicationContext().getFilesDir(), mDashboardActivity.getApplicationContext().getResources().openRawResource( R.raw.driveserviceprivatekey)); final MediaRepository mediaRepository = new MediaRepository(); mDownloadMediaUseCase = new DownloadMediaUseCase(asyncExecutor, fileDownloader, mConnectivity, mediaRepository); }
Source:
<code>public void open() throws IOException; public void append(E entity) throws IOException; public void sync() throws IOException; public void cleanup() throws IOException; } protected final FileSystem fs; private final Path directory; private final DatasetDescriptor descriptor; @VisibleForTesting <START> public FileAppender<E> appender; <END> private Path tempPath; private Path finalPath; private ReaderWriterState state; private int count = 0; @VisibleForTesting final Configuration conf; public FileSystemWriter(FileSystem fs, Path path, DatasetDescriptor descriptor) { Preconditions.checkNotNull(fs, "File system is not defined"); Preconditions.checkNotNull(path, "Destination directory is not defined"); Preconditions.checkNotNull(descriptor, "Descriptor is not defined"); this.fs = fs; this.directory = path; this.descriptor = descriptor; this.conf = new Configuration(fs.getConf()); this.state = ReaderWriterState.NEW; for (String prop : descriptor.listProperties()) { conf.set(prop, descriptor.getProperty(prop)); } }</code><technical_language>this package-private protected test public</technical_language>

Target:
public void open() throws IOException; public void append(E entity) throws IOException; public void sync() throws IOException; public void cleanup() throws IOException; } protected final FileSystem fs; private final Path directory; private final DatasetDescriptor descriptor; private FileAppender<E> appender; private Path tempPath; private Path finalPath; private ReaderWriterState state; private int count = 0; @VisibleForTesting final Configuration conf; public FileSystemWriter(FileSystem fs, Path path, DatasetDescriptor descriptor) { Preconditions.checkNotNull(fs, "File system is not defined"); Preconditions.checkNotNull(path, "Destination directory is not defined"); Preconditions.checkNotNull(descriptor, "Descriptor is not defined"); this.fs = fs; this.directory = path; this.descriptor = descriptor; this.conf = new Configuration(fs.getConf()); this.state = ReaderWriterState.NEW; for (String prop : descriptor.listProperties()) { conf.set(prop, descriptor.getProperty(prop)); } }
Source:
<code>protected void onFinishInflate() { super.onFinishInflate(); View.inflate(getContext(), R.layout.merge_login_view, this); loginButton = Views.findById(this, R.id.sign_in_button); <START> Views.findById(this, R.id.login_icon_frame_layout).setBackground(new BubblyDrawable(getContext())); <END> }</code><technical_language>a time? java View frame = Views.findById(this, R.id.login_icon_frame_layout); frame.setBackground(new BubblyDrawable(getContext()));</technical_language>

Target:
protected void onFinishInflate() { super.onFinishInflate(); View.inflate(getContext(), R.layout.merge_login_view, this); loginButton = Views.findById(this, R.id.sign_in_button); View iconFrame = Views.findById(this, R.id.login_icon_frame_layout); iconFrame.setBackground(new BubblyDrawable(getResources())); }
Source:
<code>private GlusterBrickEntity getBrick(List<GlusterBrickEntity> bricksList, String qualifiedBrickName) { String[] pathElements = qualifiedBrickName.split(StorageConstants.GLUSTER_VOL_SEPARATOR); String hostName = pathElements[0]; for (GlusterBrickEntity brick : bricksList) { VDS vds = getVdsDao().get(brick.getServerId()); String hostAddress; try { <START> hostAddress = InetAddress.getByName(hostName).getHostAddress(); <END> } catch (UnknownHostException e) { return null; } for (VdsNetworkInterface vdsNi : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { if (vdsNi.getIpv4Address().equals(hostAddress) || vdsNi.getIpv6Address().equals(hostAddress)) { return brick; } } } return null; }</code><technical_language>this need loop? this changed get translated qualifiedBrickName IP address, GlusterCoreUtil.getQualifiedName</technical_language>

Target:
private GlusterBrickEntity getBrick(List<GlusterBrickEntity> bricksList, String qualifiedBrickName) { String[] pathElements = qualifiedBrickName.split(StorageConstants.GLUSTER_VOL_SEPARATOR); String hostName = pathElements[0]; String hostAddress; try { hostAddress = InetAddress.getByName(hostName).getHostAddress(); } catch (UnknownHostException e) { return null; } for (GlusterBrickEntity brick : bricksList) { VDS vds = getVdsDao().get(brick.getServerId()); for (VdsNetworkInterface vdsNi : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { if (vdsNi.getIpv4Address().equals(hostAddress) || vdsNi.getIpv6Address().equals(hostAddress)) { return brick; } } } return null; }
Source:
<code>private String getBinJarName(File binDir, String pattern) { File[] binJarFiles = ConfigurationGenerator.getJarFilesFromPattern(binDir, pattern); if (binJarFiles.length != 1) { <START> throw new RuntimeException("No files found in " + binDir.getAbsolutePath() + " looking for " + pattern); <END> } return binDir.getName() + File.separator + binJarFiles[0].getName(); }</code><technical_language>files too, useful mention this if > 1</technical_language>

Target:
protected String getBinJarName(File binDir, String pattern) { File[] binJarFiles = ConfigurationGenerator.getJarFilesFromPattern(binDir, pattern); if (binJarFiles.length != 1) { throw new RuntimeException("There should be only 1 file but " + binJarFiles.length + " were found in " + binDir.getAbsolutePath() + " looking for " + pattern); } return binDir.getName() + File.separator + binJarFiles[0].getName(); }
Source:
<code>private String removePort(String url) { try { URI parsedUrl = new URI(url); return (parsedUrl.getPort()) == -1 ? url : url.replaceFirst(":\\d+", ""); } catch (Exception e) { <START> return ""; <END> } }</code><technical_language>return url</technical_language>

Target:
private String removePort(String url) { try { URI parsedUrl = new URI(url); return (parsedUrl.getPort() == -1) ? url : updatePort(parsedUrl, -1); } catch (Exception e) { return url; } }
Source:
<code><START> Study getMockStudy() throws Exception { <END> Study mockStudy = new Study(); mockStudy.setStudyId(1); mockStudy.setStudyInstanceUid("1.2.826.0.1.3680043.8.2186.1.1"); return mockStudy; }</code><technical_language>this need throws Exception</technical_language>

Target:
Study getMockStudy() { Study mockStudy = new Study(); mockStudy.setStudyId(1); mockStudy.setStudyInstanceUid("1.2.826.0.1.3680043.8.2186.1.1"); return mockStudy; }
Source:
<code>protected void committed(int operatorId, long windowId) throws IOException, InterruptedException { LOG.debug("data manager committed {}", windowId); for (Long currentWindow : savedWindows.keySet()) { if (currentWindow <= smallestPendingWindow) { continue; } if (currentWindow <= windowId) { LOG.debug("to transfer {}", currentWindow); <START> smallestPendingWindow = currentWindow; <END> windowsToTransfer.add(currentWindow); } else { break; } } }</code><technical_language>name changed of smallestPendingWindow. slightly misleading</technical_language>

Target:
protected void committed(int operatorId, long windowId) throws IOException, InterruptedException { LOG.debug("data manager committed {}", windowId); for (Long currentWindow : savedWindows.keySet()) { if (currentWindow <= largestWindowAddedToTransferQueue) { continue; } if (currentWindow <= windowId) { LOG.debug("to transfer {}", currentWindow); largestWindowAddedToTransferQueue = currentWindow; windowsToTransfer.add(currentWindow); } else { break; } } }
Source:
<code>public void init(final ProcessorContext context, final StateStore root) { this.context = context; initStoreSerde(context); metrics = (StreamsMetricsImpl) context.metrics(); taskName = context.taskId().toString(); <START> final String metricsGroup = "stream-" + metricsScope + "-state-metrics"; <END> final Map<String, String> taskTags = metrics.storeLevelTagMap(taskName, metricsScope, ROLLUP_VALUE); final Map<String, String> storeTags = metrics.storeLevelTagMap(taskName, metricsScope, name()); putTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "put", metrics, metricsGroup, taskName, name(), taskTags, storeTags); fetchTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "fetch", metrics, metricsGroup, taskName, name(), taskTags, storeTags); flushTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "flush", metrics, metricsGroup, taskName, name(), taskTags, storeTags); final Sensor restoreTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "restore", metrics, metricsGroup, taskName, name(), taskTags, storeTags); final long startNs = time.nanoseconds(); try { super.init(context, root); } finally { metrics.recordLatency( restoreTime, startNs, time.nanoseconds() ); } }</code><technical_language>moved String literals constants. reason this is here</technical_language>

Target:
public void init(final ProcessorContext context, final StateStore root) { this.context = context; initStoreSerde(context); metrics = (StreamsMetricsImpl) context.metrics(); taskName = context.taskId().toString(); final String metricsGroup = GROUP_PREFIX + metricsScope + STATE_LEVEL_GROUP_SUFFIX; final Map<String, String> taskTags = metrics.storeLevelTagMap(taskName, metricsScope, ROLLUP_VALUE); final Map<String, String> storeTags = metrics.storeLevelTagMap(taskName, metricsScope, name()); putTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "put", metrics, metricsGroup, taskName, name(), taskTags, storeTags); fetchTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "fetch", metrics, metricsGroup, taskName, name(), taskTags, storeTags); flushTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "flush", metrics, metricsGroup, taskName, name(), taskTags, storeTags); final Sensor restoreTime = createTaskAndStoreLatencyAndThroughputSensors(DEBUG, "restore", metrics, metricsGroup, taskName, name(), taskTags, storeTags); final long startNs = time.nanoseconds(); try { super.init(context, root); } finally { metrics.recordLatency( restoreTime, startNs, time.nanoseconds() ); } }
Source:
<code>public boolean doMonitor(ServiceEmitter emitter) { for (Map.Entry<String, EventReceiverFirehoseMetric> entry : register.getMetrics()) { final String serviceName = entry.getKey(); final EventReceiverFirehoseMetric metric = entry.getValue(); final ServiceMetricEvent.Builder builder = ServiceMetricEvent.builder() .setDimension("serviceName", serviceName) .setDimension( "bufferCapacity", String.valueOf(metric.getCapacity()) ); <START> emitter.emit(builder.build("ingest/firehose/bufferSize", metric.getCurrentBufferSize())); <END> } return true; }</code><technical_language>please call this ingest/events/buffered please add this docs</technical_language>

Target:
public boolean doMonitor(ServiceEmitter emitter) { for (Map.Entry<String, EventReceiverFirehoseMetric> entry : register.getMetrics()) { final String serviceName = entry.getKey(); final EventReceiverFirehoseMetric metric = entry.getValue(); final ServiceMetricEvent.Builder builder = ServiceMetricEvent.builder() .setDimension("serviceName", serviceName) .setDimension( "bufferCapacity", String.valueOf(metric.getCapacity()) ); emitter.emit(builder.build("ingest/events/buffered", metric.getCurrentBufferSize())); } return true; }
Source:
<code>protected void handleException(Throwable t) { LOG.warn("Fatal error occurred while closing {}, aborting...", this.encodedRegionName, t); <START> getServer().abort("Failed to close " + this.encodedRegionName, t); <END> }</code><technical_language>Please add 'can recover' back? tells abort region server</technical_language>

Target:
protected void handleException(Throwable t) { LOG.warn("Fatal error occurred while closing region {}, aborting...", encodedName, t); getServer().abort("Failed to close region " + encodedName + " and can not recover", t); }
Source:
<code>protected void addChildVisual(final EditPart childEditPart, final int index) { <START> boolean visible = true; if (childEditPart instanceof InterfaceEditPart) { IInterfaceElement iElement = ((InterfaceEditPart) childEditPart).getModel(); if (iElement instanceof AdapterDeclaration){ visible = isVarVisible(); } } <END> EditPart refEditPart = null; if(index < getChildren().size()){ refEditPart = (EditPart)getChildren().get(index); } if (childEditPart instanceof InterfaceEditPart) { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); if (((InterfaceEditPart) childEditPart).getModel().isIsInput()) { if (((InterfaceEditPart) childEditPart).isEvent()) { insertChild(getLeftEventInterfaceContainer(), refEditPart, child); } else { if (visible) { insertChild(getLeftVarInterfaceContainer(), refEditPart, child); } else { insertChild(getLeftInterfaceContainer(), refEditPart, child); } } } else { if (((InterfaceEditPart) childEditPart).isEvent()) { insertChild(getRightEventInterfaceContainer(), refEditPart, child); } else { if (visible) { insertChild(getRightVarInterfaceContainer(), refEditPart, child); } else { insertChild(getRightInterfaceContainer(), refEditPart, child); } } } child.setVisible(visible); } else { super.addChildVisual(childEditPart, -1); } }</code><technical_language>remove</technical_language>

Target:
protected void addChildVisual(final EditPart childEditPart, final int index) { EditPart refEditPart = null; if (index < getChildren().size()) { refEditPart = (EditPart) getChildren().get(index); } if (childEditPart instanceof InterfaceEditPart) { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); insertChild(getChildVisualContainer(childEditPart), refEditPart, child); child.setVisible(isVarVisible(childEditPart)); } else { super.addChildVisual(childEditPart, -1); } }
Source:
<code>public void onSendMessage(View v) { String inputMessage = mInputField.getText().toString().trim(); mInputField.setText(""); <START> if (inputMessage.length() > 0 || mSendImage){ <END> Content content; if (mSendImage && mImage != null) { content = new ImageContent(mImage, inputMessage); mSendImage = false; mImage = null; mImageThumbnail.setImageBitmap(null); mImageThumbnail.setPadding(0, 0, 0, 0); } else { content = new TextContent(inputMessage); } Message message = new Message("message", new Id(0), mUser.getId(), content, new Date()); if (mType == ContentType.GROUP_MESSAGES) { Log.d("MessageActivity", "Send group message"); mGroupMessageAdapter.add(message); mGroupMessageAdapter.notifyDataSetChanged(); ((GroupMessageFragment) mCurrentFragment).getMessageListView() .smoothScrollToPosition(mGroupMessageAdapter.getCount() - 1); NodeMessageRequest request = new NodeMessageRequest(message, mGroup.getId(), mGroup.getVisibility()); YieldsApplication.getBinder().sendRequest(request); } else { mCommentAdapter.add(message); mCommentAdapter.notifyDataSetChanged(); ((CommentFragment) mCurrentFragment).getCommentListView() .smoothScrollToPosition(mCommentAdapter.getCount() - 1); NodeMessageRequest request = new NodeMessageRequest(message, mCommentMessage.getId(), Group.GroupVisibility.PRIVATE); YieldsApplication.getBinder().sendRequest(request); } YieldsApplication.getGroup().addMessage(message); } }</code><technical_language>isEmpty :D</technical_language>

Target:
public void onSendMessage(View v) { String inputMessage = mInputField.getText().toString().trim(); mInputField.setText(""); if (!inputMessage.isEmpty() || mSendImage){ Content content; if (mSendImage && mImage != null) { content = new ImageContent(mImage, inputMessage); mSendImage = false; mImage = null; mImageThumbnail.setImageBitmap(null); mImageThumbnail.setPadding(0, 0, 0, 0); } else { content = new TextContent(inputMessage); } Message message = new Message("message", new Id(0), mUser.getId(), content, new Date()); if (mType == ContentType.GROUP_MESSAGES) { Log.d("MessageActivity", "Send group message"); mGroupMessageAdapter.add(message); mGroupMessageAdapter.notifyDataSetChanged(); ((GroupMessageFragment) mCurrentFragment).getMessageListView() .smoothScrollToPosition(mGroupMessageAdapter.getCount() - 1); NodeMessageRequest request = new NodeMessageRequest(message, mGroup.getId(), mGroup.getVisibility()); YieldsApplication.getBinder().sendRequest(request); } else { mCommentAdapter.add(message); mCommentAdapter.notifyDataSetChanged(); ((CommentFragment) mCurrentFragment).getCommentListView() .smoothScrollToPosition(mCommentAdapter.getCount() - 1); NodeMessageRequest request = new NodeMessageRequest(message, mCommentMessage.getId(), Group.GroupVisibility.PRIVATE); YieldsApplication.getBinder().sendRequest(request); } YieldsApplication.getGroup().addMessage(message); } }
Source:
<code>@After public void tearDown() throws InterruptedException { clientListener.assertExhausted(); <START> client.connectionPool().evictAll(); <END> if (client.connectionPool().connectionCount() > 0) { System.out.println("Delaying to avoid flakes"); Thread.sleep(500L); System.out.println("After delay: " + client.connectionPool().connectionCount()); } }</code><technical_language>Same, this in OkHttpClientTestRule</technical_language>

Target:
@After public void tearDown() throws InterruptedException { clientListener.assertExhausted(); }
Source:
<code><START> public <T> void updateMetricExpiration(Metric<T> metric) { <END> if (!MetricType.STRING.equals(metric.getType())) { long expiration = 0; if (metric.getDataRetention() != null) { expiration = System.currentTimeMillis() + metric.getDataRetention() * DAY_TO_MILLIS; } else { expiration = System.currentTimeMillis() + this.getTTL(metric.getMetricId()) * DAY_TO_MILLIS; } ListenableFutureObservable .from(dataAccess.updateMetricExpirationIndex(metric.getMetricId(), expiration), metricsTasks) .doOnError(t -> log.error("Failure to update expiration index", t)); } }</code><technical_language>reactive functional return Observable<Void> (preferably) Completable instead of void</technical_language>

Target:
public <T> Observable<Void> updateMetricExpiration(Metric<T> metric) { if (!MetricType.STRING.equals(metric.getType())) { long expiration = 0; if (metric.getDataRetention() != null) { expiration = DateTimeService.now.get().getMillis() + metric.getDataRetention() * DAY_TO_MILLIS; } else { expiration = DateTimeService.now.get().getMillis() + this.getTTL(metric.getMetricId()) * DAY_TO_MILLIS; } return dataAccess.updateMetricExpirationIndex(metric.getMetricId(), expiration) .doOnError(t -> log.error("Failure to update expiration index", t)) .flatMap(r -> null); } return Observable.empty(); }
Source:
<code>public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); try { boolean renewCookie = false; int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject .class); String error = errorResponse.getAsJsonPrimitive ("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive ("reason").getAsString(); if (!"credentials_expired".equals(error)) { throw new HttpConnectionInterceptorException(error, reason); } else { renewCookie = true; } } catch (JsonParseException e) { throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: renewCookie = true; break; default: <START> String cookieHeader = connection.getHeaderField("Set-Cookie"); <END> if(cookieHeader != null){ cookie = this.extractCookieFromHeaderValue(cookieHeader); } break; } if (renewCookie) { cookie = getCookie(connection.getURL(), context); if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }</code><technical_language>some responses a 403 is expiry case. If included a Set-Cookie this miss it. I if check for header earlier worry response codes</technical_language>

Target:
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); String cookieHeader = connection.getHeaderField("Set-Cookie"); if(cookieHeader != null){ cookie = this.extractCookieFromHeaderValue(cookieHeader); return context; } try { boolean renewCookie = false; int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject .class); String error = errorResponse.getAsJsonPrimitive ("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive ("reason").getAsString(); if (!"credentials_expired".equals(error)) { throw new HttpConnectionInterceptorException(error, reason); } else { renewCookie = true; } } catch (JsonParseException e) { throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: renewCookie = true; break; default: break; } if (renewCookie) { cookie = getCookie(connection.getURL(), context); if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }
Source:
<code>void refreshTokenWithoutCache(final String refreshToken, final AuthenticationRequest authenticationRequest, final AuthenticationCallback<AuthenticationResult> externalCallback) { Logger.setCorrelationId(authenticationRequest.getCorrelationId()); Logger.v(TAG, "Refresh token without cache"); final CallbackHandler callbackHandle = new CallbackHandler(getHandler(), externalCallback); THREAD_EXECUTOR.execute(new Runnable() { @Override public void run() { try { validateAcquireTokenRequest(authenticationRequest); final AcquireTokenSilentHandler acquireTokenSilentHandler = new AcquireTokenSilentHandler(mContext, authenticationRequest, mTokenCacheAccessor); final AuthenticationResult authResult = acquireTokenSilentHandler.acquireTokenWithRefreshToken(refreshToken); mAPIEvent.setWasApiCallSuccessful(true); callbackHandle.onSuccess(authResult); } catch (final AuthenticationException authenticationException) { mAPIEvent.setWasApiCallSuccessful(false); callbackHandle.onError(authenticationException); } finally { Telemetry.getInstance().stopEvent(authenticationRequest.getTelemetryRequestId(), mAPIEvent, mAPIEvent.getEventName()); <START> Telemetry.getInstance().flush(authenticationRequest.getTelemetryRequestId()); <END> } } }); }</code><technical_language>elemetry.getInstance().flush(authenticationRequest.getTelemetryRequestId()); [](start = 21, length = 76) if possible, put flush stopEvent itself, check if API event, I code is more reliable, error prone. #Closed</technical_language>

Target:
void refreshTokenWithoutCache(final String refreshToken, final AuthenticationRequest authenticationRequest, final AuthenticationCallback<AuthenticationResult> externalCallback) { Logger.setCorrelationId(authenticationRequest.getCorrelationId()); Logger.v(TAG, "Refresh token without cache"); final CallbackHandler callbackHandle = new CallbackHandler(getHandler(), externalCallback); THREAD_EXECUTOR.execute(new Runnable() { @Override public void run() { try { validateAcquireTokenRequest(authenticationRequest); final AcquireTokenSilentHandler acquireTokenSilentHandler = new AcquireTokenSilentHandler(mContext, authenticationRequest, mTokenCacheAccessor); final AuthenticationResult authResult = acquireTokenSilentHandler.acquireTokenWithRefreshToken(refreshToken); mAPIEvent.setWasApiCallSuccessful(true, null); mAPIEvent.setIdToken(authResult.getIdToken()); callbackHandle.onSuccess(authResult); } catch (final AuthenticationException authenticationException) { mAPIEvent.setWasApiCallSuccessful(false, authenticationException); callbackHandle.onError(authenticationException); } finally { mAPIEvent.setCorrelationId(authenticationRequest.getCorrelationId().toString()); mAPIEvent.stopTelemetryAndFlush(); } } }); }
Source:
<code>public BaseAsset() { <START> this.channelListeners = Collections.synchronizedSet(new HashSet<>()); <END> this.monitor = new ReentrantLock(); }</code><technical_language>CopyOnWriteArrayList a alternative provides optimized functionality for thread-safety good for maintaining list of listeners updated occasionally</technical_language>

Target:
public BaseAsset() { this.channelListeners = new CopyOnWriteArraySet<>(); this.monitor = new ReentrantLock(); }
Source:
<code><START> private boolean isValueDefined(int valueStart, int valueEnd) { <END> return valueStart != -1 && valueStart != valueEnd; }</code><technical_language>Please revert static. a general practice in Netty for methods depend instance state</technical_language>

Target:
private static boolean isValueDefined(int valueStart, int valueEnd) { return valueStart != -1 && valueStart != valueEnd; }
Source:
<code><START> public void gotoAnnotation(Direction direction) { <END> if (leftSourceViewer == null || rightSourceViewer == null) { return; } List<CompareAnnotation> annotations = getAnnotations(); if (annotations.isEmpty()) { return; } if (currentAnnotation == null) { if (direction == Direction.FORWARDS) { currentAnnotation = annotations.get(0); } else { currentAnnotation = annotations.get(annotations.size() - 1); } } else { int annotationIndex = annotations.indexOf(currentAnnotation); if (direction == Direction.FORWARDS && annotationIndex + 1 < annotations.size()) { annotationIndex++; } else if (direction == Direction.BACKWARDS && annotationIndex - 1 >= 0) { annotationIndex--; } currentAnnotation = annotations.get(annotationIndex); } if (currentAnnotation != null) { if (currentAnnotation.getSide() == LEFT_SIDE) { moveToAnnotation(rightSourceViewer, leftSourceViewer, currentAnnotation.getAnnotation().getPosition()); } else { moveToAnnotation(leftSourceViewer, rightSourceViewer, currentAnnotation.getAnnotation().getPosition()); } } }</code><technical_language>Needless this is a bit quick dirty. of this stuff improved a bit</technical_language>

Target:
public void gotoAnnotation(Direction direction) { if (leftSourceViewer == null || rightSourceViewer == null) { return; } List<CompareAnnotation> annotations = getAnnotations(); if (annotations.isEmpty()) { return; } int annotationIndex = annotations.indexOf(currentAnnotation); annotationIndex += direction == Direction.FORWARDS ? 1 : -1; if (annotationIndex < 0) { annotationIndex = annotations.size() - 1; } if (annotationIndex >= annotations.size()) { annotationIndex = 0; } currentAnnotation = annotations.get(annotationIndex); if (currentAnnotation.getSide() == LEFT_SIDE) { moveToAnnotation(rightSourceViewer, leftSourceViewer, currentAnnotation.getAnnotation().getPosition()); } else { moveToAnnotation(leftSourceViewer, rightSourceViewer, currentAnnotation.getAnnotation().getPosition()); } }
Source:
<code>protected @Nullable Object resolveValue(ITmfEvent event, int baseQuark, DataDrivenScenarioInfo scenarioInfo, IAnalysisDataContainer container) { <START> final ITmfEventField field = event.getContent().getField(fFieldName.split(".")); END> Object fieldValue = null; if (field == null) { if (fFieldName.equalsIgnoreCase(TmfXmlStrings.CPU)) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu != null) { return cpu; } } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.TIMESTAMP)) { return event.getTimestamp().getValue(); } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.HOSTID)) { return event.getTrace().getHostId(); } fieldValue = TmfTraceUtils.resolveAspectOfNameForEvent(event.getTrace(), fFieldName, event); } else { fieldValue = field.getValue(); } return fieldValue; }</code><technical_language>Wow! time I this, yeah, great catch</technical_language>

Target:
protected @Nullable Object resolveValue(ITmfEvent event, int baseQuark, DataDrivenScenarioInfo scenarioInfo, IAnalysisDataContainer container) { final ITmfEventField field = event.getContent().getField(fFieldName); Object fieldValue = null; if (field == null) { final ITmfEventField splitFieldName = event.getContent().getField(fFieldName.split("\\.")); if (splitFieldName != null) { fieldValue = splitFieldName.getValue(); if (fieldValue != null) { return fieldValue; } } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.CPU)) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu != null) { return cpu; } } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.TIMESTAMP)) { return event.getTimestamp().getValue(); } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.HOSTID)) { return event.getTrace().getHostId(); } fieldValue = TmfTraceUtils.resolveAspectOfNameForEvent(event.getTrace(), fFieldName, event); } else { fieldValue = field.getValue(); } return fieldValue; }
Source:
<code>synchronized public int read(byte[] buf, int off, int len) throws IOException { LOG.trace("read(buf, off={}, len={}" off, len); <START> <END> int read = 0; while (len > 0) { if (buffersize == 0) { fill(); if (buffersize == 0) { break; } } int tocopy = Math.min(len, buffersize); LOG.trace("tocopy={}" + tocopy); System.arraycopy(buffer, bufferoffset, buf, off, tocopy); buffersize -= tocopy; bufferoffset += tocopy; len -= tocopy; read += tocopy; off += tocopy; } LOG.trace("read={}", read); return read; }</code><technical_language>compile error</technical_language>

Target:
synchronized public int read(byte[] buf, int off, int len) throws IOException { LOG.trace("read(buf, off={}, len={}", off, len); int read = 0; while (len > 0) { if (buffersize == 0) { fill(); if (buffersize == 0) { break; } } int tocopy = Math.min(len, buffersize); LOG.trace("tocopy={}" + tocopy); System.arraycopy(buffer, bufferoffset, buf, off, tocopy); buffersize -= tocopy; bufferoffset += tocopy; len -= tocopy; read += tocopy; off += tocopy; } LOG.trace("read={}", read); return read; }
Source:
<code><START> public Message<?> preSend(Message<?> message, MessageChannel channel) { <END> if (message instanceof ErrorMessage) { return message; } if (message.getPayload() instanceof byte[]) { return MessageConverterConfigurer.this.messageBuilderFactory .withPayload(message.getPayload()) .copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } Message<?> sentMessage = null; Object converted; if (this.input) { return MessageConverterConfigurer.this.messageBuilderFactory .withPayload(message.getPayload()) .copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } else { MutableMessageHeaders headers = new MutableMessageHeaders( message.getHeaders()); if (!headers.containsKey(MessageHeaders.CONTENT_TYPE)) { headers.put(MessageHeaders.CONTENT_TYPE, this.mimeType); } converted = this.messageConverter.toMessage(message.getPayload(), headers); } if (converted != null) { if (converted instanceof Message) { sentMessage = (Message<?>) converted; } else { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory .withPayload(converted).copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } } if (sentMessage == null) { throw new MessageConversionException(message, this.messageConverter.getClass().toString() + " could not convert '" + message + "' to the configured output type: '" + this.mimeType + "'"); } return sentMessage; }</code><technical_language>provideHint conversion. Is a specific reason for that</technical_language>

Target:
public Message<?> preSend(Message<?> message, MessageChannel channel) { if (message instanceof ErrorMessage) { return message; } Message<?> sentMessage = null; Object converted; if (this.input || message.getPayload() instanceof byte[]) { return MessageConverterConfigurer.this.messageBuilderFactory .withPayload(message.getPayload()) .copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } else { MutableMessageHeaders headers = new MutableMessageHeaders( message.getHeaders()); if (!headers.containsKey(MessageHeaders.CONTENT_TYPE)) { headers.put(MessageHeaders.CONTENT_TYPE, this.mimeType); } converted = this.messageConverter.toMessage(message.getPayload(), headers); } if (converted != null) { if (converted instanceof Message) { sentMessage = (Message<?>) converted; } else { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory .withPayload(converted).copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } } if (sentMessage == null) { throw new MessageConversionException(message, this.messageConverter.getClass().toString() + " could not convert '" + message + "' to the configured output type: '" + this.mimeType + "'"); } return sentMessage; }
Source:
<code>public void testParameterSourceFactoryAndJpaParameters() { JpaExecutor executor = new JpaExecutor(this.entityManager); ParameterSourceFactory parameterSourceFactory = new ExpressionEvaluatingParameterSourceFactory(); executor.setParameterSourceFactory(parameterSourceFactory); executor.setJpaParameters(Collections.singletonList(new JpaParameter("firstName", null, "#this"))); try { executor.afterPropertiesSet(); } catch (Exception e) { assertThat(e, instanceOf(IllegalStateException.class)); assertThat(e.getMessage(), startsWith("The 'jpaParameters' and 'parameterSourceFactory' are mutually exclusive.")); } <START> } <END></code><technical_language>Consider assertJ's assertThatThrownBy(() -> executor.afterPropertiesSet()).... for this kind of test. needs a fail("Expected exception)</technical_language>

Target:
public void testParameterSourceFactoryAndJpaParameters() { JpaExecutor executor = new JpaExecutor(this.entityManager); ParameterSourceFactory parameterSourceFactory = new ExpressionEvaluatingParameterSourceFactory(); executor.setParameterSourceFactory(parameterSourceFactory); executor.setJpaParameters(Collections.singletonList(new JpaParameter("firstName", null, "#this"))); assertThatThrownBy(executor::afterPropertiesSet) .isExactlyInstanceOf(IllegalStateException.class) .hasMessageStartingWith("The 'jpaParameters' and 'parameterSourceFactory' are mutually exclusive."); }
Source:
<code>public DataGeneratorContainer visit(TimeType timeType) { <START> return DataGeneratorContainer.of(TimeGenerator.of(() -> LocalTime.now().get(MILLI_OF_SECOND))); <END> }</code><technical_language>this MILLI_OF_DAY</technical_language>

Target:
public DataGeneratorContainer visit(TimeType timeType) { return DataGeneratorContainer.of(TimeGenerator.of(() -> LocalTime.now().get(MILLI_OF_DAY))); }
Source:
<code>@Test public void deleteRecursiveOnUnix() throws Exception { <START> assumeFalse(Functions.isWindows()); <END> Path targetDir = temp.newFolder("target").toPath(); Path targetContents = Files.createFile(targetDir.resolve("contents.txt")); Path toDelete = temp.newFolder("toDelete").toPath(); Util.createSymlink(toDelete.toFile(), "../targetDir", "link", TaskListener.NULL); Files.createFile(toDelete.resolve("foo")); Files.createFile(toDelete.resolve("bar")); FilePath f = new FilePath(toDelete.toFile()); f.deleteRecursive(); assertTrue("symlink target should not be deleted", Files.exists(targetDir)); assertTrue("symlink target contents should not be deleted", Files.exists(targetContents)); assertFalse("could not delete target", Files.exists(toDelete)); }</code><technical_language>please add a string assume reason is reporting in results</technical_language>

Target:
@Test public void deleteRecursiveOnUnix() throws Exception { assumeFalse("Uses Unix-specific features", Functions.isWindows()); Path targetDir = temp.newFolder("target").toPath(); Path targetContents = Files.createFile(targetDir.resolve("contents.txt")); Path toDelete = temp.newFolder("toDelete").toPath(); Util.createSymlink(toDelete.toFile(), "../targetDir", "link", TaskListener.NULL); Files.createFile(toDelete.resolve("foo")); Files.createFile(toDelete.resolve("bar")); FilePath f = new FilePath(toDelete.toFile()); f.deleteRecursive(); assertTrue("symlink target should not be deleted", Files.exists(targetDir)); assertTrue("symlink target contents should not be deleted", Files.exists(targetContents)); assertFalse("could not delete target", Files.exists(toDelete)); }
Source:
<code>protected String getTags() throws MojoExecutionException { try { Repository repo = getGitRepository(); ObjectId headId = headCommit.toObjectId(); <START> Collection<String> tags = new JGitCommon().getTags(repo,headId); <END> return Joiner.on(",").join(tags); } catch (GitAPIException e) { loggerBridge.error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")"); return ""; } }</code><technical_language>reuse instance? Is stateful static methods</technical_language>

Target:
protected String getTags() throws MojoExecutionException { try { Repository repo = getGitRepository(); ObjectId headId = headCommit.toObjectId(); Collection<String> tags = jGitCommon.getTags(repo,headId); return Joiner.on(",").join(tags); } catch (GitAPIException e) { loggerBridge.error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")"); return ""; } }
Source:
<code>public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ActionParameter)) return false; ActionParameter actionParameter = (ActionParameter) o; <START> return this.getName().equals(actionParameter.getName()); <END> }</code><technical_language>suggestion return Objects.equals(this.getName(), actionParameter.getName()); reason for this suggestion in general is handles nulls properly, e.g. if this.getName() returns null previous implementation crash</technical_language>

Target:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ActionParameter)) return false; ActionParameter actionParameter = (ActionParameter) o; return Objects.equals(this.getName(), actionParameter.getName()); }
Source:
<code>public abstract String[] extractPartitions(Message payload) throws Exception; public Object getJsonFieldValue(JSONObject jsonObject) { Object fieldValue = null; String messageTimestampName = mConfig.getMessageTimestampName(); String messageTimestampSeparator = mConfig.getMessageTimestampNameSeparator(); if (messageTimestampSeparator != null) { <START> String[] fields = messageTimestampName.split(Pattern.quote(messageTimestampSeparator)); <END> Object finalValue = null; for (int i=0; i < fields.length; i++) { if (!jsonObject.containsKey(fields[i])) { LOG.warn("Could not find key in message", messageTimestampName); break; } if (i < (fields.length -1)) { jsonObject = (JSONObject) jsonObject.get(fields[i]); } else { finalValue = jsonObject.get(fields[i]); } } fieldValue = finalValue; } else { fieldValue = jsonObject.get(messageTimestampName); } return fieldValue; }</code><technical_language>need create a pattern object, this is done in constructor/initializer of MessageParser, of loop of message parsing</technical_language>

Target:
public abstract String[] extractPartitions(Message payload) throws Exception; public Object getJsonFieldValue(JSONObject jsonObject) { Object fieldValue = null; if (mNestedFields != null) { Object finalValue = null; for (int i=0; i < mNestedFields.length; i++) { if (!jsonObject.containsKey(mNestedFields[i])) { LOG.warn("Could not find key in message", mConfig.getMessageTimestampName()); break; } if (i < (mNestedFields.length -1)) { jsonObject = (JSONObject) jsonObject.get(mNestedFields[i]); } else { finalValue = jsonObject.get(mNestedFields[i]); } } fieldValue = finalValue; } else { fieldValue = jsonObject.get(mConfig.getMessageTimestampName()); } return fieldValue; }