auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private UrlEncodedFormEntity createUrlEncodedFormEntity(final String contentEncoding) throws UnsupportedEncodingException { PropertyIterator args = getArguments().iterator(); List<NameValuePair> nvps = new ArrayList<>(); String urlContentEncoding = contentEncoding; if (urlContentEncoding == null || urlContentEncoding.length() == 0) { urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING; } while (args.hasNext()) { HTTPArgument arg = (HTTPArgument) args.next().getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } String parameterValue = arg.getValue(); if (!arg.isAlwaysEncoded()) { try { URLCodec urlCodec = new URLCodec(contentEncoding); parameterName = urlCodec.decode(parameterName, urlContentEncoding); parameterValue = urlCodec.decode(parameterValue, urlContentEncoding); } catch (DecoderException e) { <START> log.error(contentEncoding + " exception in encoding!"); <END> throw new Error(e.toString(), e); } } nvps.add(new BasicNameValuePair(parameterName, parameterValue)); } return new UrlEncodedFormEntity(nvps, urlContentEncoding); }</code><technical_language>add new log messages, try string formats. In this case log.error("{} exception in encoding!", contentEncoding); I wonder, message include parameter and/or name give more context</technical_language>

Target:
private UrlEncodedFormEntity createUrlEncodedFormEntity(final String contentEncoding) throws UnsupportedEncodingException { PropertyIterator args = getArguments().iterator(); List<NameValuePair> nvps = new ArrayList<>(); String urlContentEncoding = contentEncoding; if (urlContentEncoding == null || urlContentEncoding.length() == 0) { urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING; } while (args.hasNext()) { HTTPArgument arg = (HTTPArgument) args.next().getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } String parameterValue = arg.getValue(); if (!arg.isAlwaysEncoded()) { try { URLCodec urlCodec = new URLCodec(contentEncoding); parameterName = urlCodec.decode(parameterName, urlContentEncoding); parameterValue = urlCodec.decode(parameterValue, urlContentEncoding); } catch (DecoderException e) { log.error("exception in encoding for parameter name and parameter value {}!", contentEncoding,parameterName,parameterValue); throw new Error(e.toString(), e); } } nvps.add(new BasicNameValuePair(parameterName, parameterValue)); } return new UrlEncodedFormEntity(nvps, urlContentEncoding); }
Source:
<code>public <T> HTMLDisplayer<T> getHTMLDisplayer(Type targetType, String roleHint) throws HTMLDisplayerException { try { HTMLDisplayer<T> component; ComponentManager componentManager = this.componentManagerProvider.get(); Type type = targetType; <START> Type converterType = new DefaultParameterizedType(null, HTMLDisplayer.class, type); <END> while (!componentManager.hasComponent(converterType, roleHint) && type instanceof ParameterizedType) { type = ((ParameterizedType) type).getRawType(); converterType = new DefaultParameterizedType(null, HTMLDisplayer.class, type); } if (!componentManager.hasComponent(converterType, roleHint)) { converterType = HTMLDisplayer.class; } if (componentManager.hasComponent(converterType, roleHint)) { component = componentManager.getInstance(converterType, roleHint); } else { component = componentManager.getInstance(converterType); } return component; } catch (ComponentLookupException e) { throw new HTMLDisplayerException( "Failed to initialized the HTML displayer for target type [" + targetType + "] and role [" + String .valueOf(roleHint) + "]", e); } }</code><technical_language>converter? displayerType</technical_language>

Target:
public <T> HTMLDisplayer<T> getHTMLDisplayer(Type targetType, String roleHint) throws HTMLDisplayerException { try { HTMLDisplayer<T> component; ComponentManager componentManager = this.componentManagerProvider.get(); Type type = targetType; Type displayerType = new DefaultParameterizedType(null, HTMLDisplayer.class, type); while (!componentManager.hasComponent(displayerType, roleHint) && type instanceof ParameterizedType) { type = ((ParameterizedType) type).getRawType(); displayerType = new DefaultParameterizedType(null, HTMLDisplayer.class, type); } if (!componentManager.hasComponent(displayerType, roleHint)) { displayerType = HTMLDisplayer.class; } if (componentManager.hasComponent(displayerType, roleHint)) { component = componentManager.getInstance(displayerType, roleHint); } else { component = componentManager.getInstance(displayerType); } return component; } catch (ComponentLookupException e) { throw new HTMLDisplayerException( "Failed to initialized the HTML displayer for target type [" + targetType + "] and role [" + String .valueOf(roleHint) + "]", e); } }
Source:
<code>public boolean isModified() { if (this.refreshDelay < 0) { return false; } long time = System.currentTimeMillis(); <START> if (this.refreshDelay == 0 || (time - this.lastModifiedChecked.get()) > this.refreshDelay) { <END> this.lastModifiedChecked.set(time); boolean modified = this.source.isModified(); if (modified) { this.script = null; } return modified; } return false; }</code><technical_language>this (time - this.lastModifiedChecked.get()) > this.refreshDelay) > 0</technical_language>

Target:
public boolean isModified() { return this.refreshDelay >= 0 && (System.currentTimeMillis() - this.lastModifiedChecked.get()) > this.refreshDelay && this.source.isModified(); }
Source:
<code>public FileStatus getFileStatus(Path path) throws IOException { List<ClientFileInfo> tachyInfo = fileSystem.listStatus(pathToString(path.getParent())); FileStatus stratInfo = null; for (int x = 0; x < tachyInfo.size(); x++) { if (tachyInfo.get(x).path.equals(pathToString(path))) { <START> stratInfo = new TachyonFileStatus(tachyInfo.get(x), name); <END> } } return stratInfo; }</code><technical_language>I save some iterations immediately returning. hits once</technical_language>

Target:
public FileStatus getFileStatus(Path path) throws IOException { try { List<ClientFileInfo> tachyInfo = fileSystem.listStatus(pathToString(path.getParent())); int targetID = fileSystem.getFileId(pathToString(path)); for (int x = 0; x < tachyInfo.size(); x++) { if (tachyInfo.get(x).id == targetID) { return new TachyonFileStatus(tachyInfo.get(x), name); } } return null; } catch (IOException ioe) { if (ioe.getCause() instanceof FileDoesNotExistException) { throw new FileNotFoundException(ioe.getCause().getMessage()); } else { throw ioe; } } }
Source:
<code>private void showVideoSpeedFragmentPopup() { hideSettingsPopUp(); List<Float> speeds = new ArrayList<>(); speeds.add(0.5f); speeds.add(1.f); speeds.add(1.5f); <START> speeds.add(2.0f); <END> speedDialogFragment = SpeedDialogFragment.getInstance(speeds, new SpeedDialogFragment.IListDialogCallback() { @Override public void onItemClicked(Float speed) { setPlaybackSpeed(speed); if (player != null) { player.setPlaybackSpeed(speed); } } @Override public void onCancelClicked() { speedDialogFragment.dismiss(); } }, loginPrefs.getPlaybackSpeed()); speedDialogFragment.show(getFragmentManager(), "video_speed_dialog"); speedDialogFragment.setCancelable(false); }</code><technical_language>here. values belong SpeedDialogFragment constants. Bonus point: great if write a separate FloatDescriptor interface for constants for build time checking</technical_language>

Target:
private void showVideoSpeedFragmentPopup() { hideSettingsPopUp(); speedDialogFragment = SpeedDialogFragment.getInstance(new SpeedDialogFragment.IListDialogCallback() { @Override public void onItemClicked(Float speed) { loginPrefs.saveDefaultPlaybackSpeed(speed); if (player != null) { player.setPlaybackSpeed(speed); } } @Override public void onCancelClicked() { speedDialogFragment.dismiss(); } }, loginPrefs.getDefaultPlaybackSpeed()); speedDialogFragment.show(getFragmentManager(), "video_speed_dialog"); speedDialogFragment.setCancelable(true); }
Source:
<code>private void markExperimentFailure(Exception exception) { nextPermittedExperiment.accumulateAndGet(Instant.now(clock).plus(REFRESH_INTERVAL), (existing, current) -> existing.compareTo(current) > 0 ? existing : current); log.info("Experiment failed; we will revert to the fallback service. We will allow attempting to use" <START> + " the experimental service again in {}.", SafeArg.of("retryDuration", REFRESH_INTERVAL), exception); <END> }</code><technical_language>remove interpolated</technical_language>

Target:
private void markExperimentFailure(Exception exception) { nextPermittedExperiment.accumulateAndGet(Instant.now(clock).plus(REFRESH_INTERVAL), (existing, current) -> existing.compareTo(current) > 0 ? existing : current); log.info("Experiment failed; we will revert to the fallback service. We will allow attempting to use the" + " experimental service again after a timeout.", SafeArg.of("timeout", REFRESH_INTERVAL), exception); }
Source:
<code>private void validateActivityDates(Long startDate, Long endDate) throws ValidationException{ Calendar calendarCounter = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Integer maxActivityRangeInDays = Integer.getInteger(env.getProperty("maxActivityRangeInDays"), 60); calendarCounter.setTime(new Date(endDate)); calendarCounter.add(Calendar.DATE, -maxActivityRangeInDays); if(new Date(startDate).compareTo(calendarCounter.getTime()) < 0){ throw new ValidationException("Cannot search an activity with a date range more than " + maxActivityRangeInDays + " days."); <START> } <END> }</code><technical_language>if startDate is _after_ endDate</technical_language>

Target:
private void validateActivityDates(Long startDate, Long endDate) throws ValidationException{ Calendar calendarCounter = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Integer maxActivityRangeInDays = Integer.getInteger(env.getProperty("maxActivityRangeInDays"), 60); calendarCounter.setTime(new Date(endDate)); if(new Date(startDate).compareTo(calendarCounter.getTime()) > 0){ throw new ValidationException("Cannot search for activity with the start date after the end date"); } calendarCounter.add(Calendar.DATE, -maxActivityRangeInDays); if(new Date(startDate).compareTo(calendarCounter.getTime()) < 0){ throw new ValidationException("Cannot search for activity with a date range more than " + maxActivityRangeInDays + " days."); } }
Source:
<code>private Route<? extends EventMessage, EventContext, I> eventImportRouting() { return (message, context) -> { Set<I> ids = eventImportRouting.apply(message, context); int numberOfTargets = ids.size(); String messageType = message.getClass() .getName(); checkState( numberOfTargets > 0, "Could not get aggregate ID from the event context: `%s`. Event class: `%s`.", context, messageType ); checkState( numberOfTargets == 1, "Expected one aggregate ID, but got %s (%s). Event class: `%s`, context: `%s`.", String.valueOf(numberOfTargets), ids, messageType, context ); I id = ids.stream() .findFirst() .orElseThrow(() -> newIllegalStateException( "Unable to route import event `%s`. Event: %s", <START> messageType, shortDebugString(message)) <END> ); return id; }; }</code><technical_language>Logging event body is a security concern. Please log meta-data, event ID timestamp</technical_language>

Target:
private Route<? extends EventMessage, EventContext, I> eventImportRouting() { return (message, context) -> { Set<I> ids = eventImportRouting.apply(message, context); int numberOfTargets = ids.size(); String messageType = message.getClass() .getName(); checkState( numberOfTargets > 0, "Could not get aggregate ID from the event context: `%s`. Event class: `%s`.", context, messageType ); checkState( numberOfTargets == 1, "Expected one aggregate ID, but got %s (%s). Event class: `%s`, context: `%s`.", String.valueOf(numberOfTargets), ids, messageType, context ); I id = ids.stream() .findFirst() .orElseThrow(() -> newIllegalStateException( "Unable to route import event `%s`.", messageType) ); return id; }; }
Source:
<code>public void testVisibilityImplicitClassMembers() throws Exception { IBinding[] memberBindings = findQualifiedPossiblyImplicit(pdom, "AClass::AClass"); int visibility = getMemberVisibility(memberBindings[0]); VisibilityAsserts.assertVisibility(ICPPClassType.v_public, visibility); <START> int visibility2 = getMemberVisibility(memberBindings[0]); <END> VisibilityAsserts.assertVisibility(ICPPClassType.v_public, visibility2); }</code><technical_language>0 -> 1</technical_language>

Target:
public void testVisibilityImplicitClassMembers() throws Exception { IBinding[] memberBindings = findQualifiedPossiblyImplicit(pdom, "AClass::AClass"); assertVisibility(ICPPClassType.v_public, getMemberVisibility(memberBindings[0])); assertVisibility(ICPPClassType.v_public, getMemberVisibility(memberBindings[1])); }
Source:
<code>public void onClick(View arg0) { if (app.deleteWaypoint(id)) { <START> if (Settings.isStoreOfflineWpMaps()) { <END> for (int level = 1; level <= 5; level++) { try { if (id > 0) { StaticMapsProvider.getMapFile(geocode, "wp" + id + "_", level, false).delete(); } } catch (Exception e) { Log.e(Settings.tag, "cgeowaypoint.deleteWaypointListener.onClick: " + e.toString()); } } } cgeoapplication.removeCacheFromCache(geocode); finish(); return; } else { showToast(res.getString(R.string.err_waypoint_delete_failed)); } }</code><technical_language>settings check is wrong here. files deleted if setting is currently active. files remain, if I new settings, disable delete a waypoint</technical_language>

Target:
public void onClick(View arg0) { if (app.deleteWaypoint(id)) { StaticMapsProvider.removeWpStaticMaps(id, geocode); cgeoapplication.removeCacheFromCache(geocode); finish(); return; } else { showToast(res.getString(R.string.err_waypoint_delete_failed)); } }
Source:
<code><START> public void canDoActionFailsOnNullHook() { <END> cmd = spy(new DisableGlusterHookCommand(new GlusterHookParameters(CLUSTER_ID, HOOK_ID))); setupMocks(cmd,false); assertFalse(cmd.canDoAction()); }</code><technical_language>In canDoActionFails* tests, verify exact error message, similar is done in EnableGlusterHookCommandTest assertTrue(cmd.getReturnValue().getCanDoActionMessages().contains(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_DOES_NOT_EXIST.toString()));</technical_language>

Target:
public void canDoActionFailsOnNullHook() { cmd = spy(new DisableGlusterHookCommand(new GlusterHookParameters(CLUSTER_ID, HOOK_ID))); setupMocks(cmd,false); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue().getCanDoActionMessages().contains(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_DOES_NOT_EXIST.toString())); }
Source:
<code>private void askAddToIndex(final String path, final String fileName) { final ProjectDescriptor project = appContext.getCurrentProject().getRootProject(); Map<String, List<String>> attributes = project.getAttributes(); <START> if (!(attributes.containsKey("vcs.provider.name") && attributes.get("vcs.provider.name").contains("git"))) { <END> return; } ConfirmCallback confirmCallback = new ConfirmCallback() { @Override public void accepted() { String filePath = path.substring(project.getName().length() + 2); try { gitServiceClient .add(project, false, Collections.singletonList(filePath), new RequestCallback<Void>() { @Override protected void onSuccess(Void result) { notificationManager.showInfo(localizationConstant.actionNewFileAddToIndexNotification(fileName)); } @Override protected void onFailure(Throwable exception) { notificationManager.showError(exception.getMessage()); } }); } catch (WebSocketException e) { e.printStackTrace(); } } }; CancelCallback cancelCallback = new CancelCallback() { @Override public void cancelled() { } }; dialogFactory.createConfirmDialog(localizationConstant.actionNewFileAddToIndexTitle(), localizationConstant.actionNewFileAddToIndexText(fileName), confirmCallback, cancelCallback).show(); }</code><technical_language>git mixin here</technical_language>

Target:
private void askAddToIndex(final String path, final String fileName) { final ProjectConfigDto project = appContext.getCurrentProject().getRootProject(); Map<String, List<String>> attributes = project.getAttributes(); if (!(attributes.containsKey("vcs.provider.name") && attributes.get("vcs.provider.name").contains("git"))) { return; } ConfirmCallback confirmCallback = new ConfirmCallback() { @Override public void accepted() { String filePath = path.substring(project.getName().length() + 2); try { gitServiceClient .add(project, false, Collections.singletonList(filePath), new RequestCallback<Void>() { @Override protected void onSuccess(Void result) { notificationManager.showInfo(localizationConstant.actionNewFileAddToIndexNotification(fileName)); } @Override protected void onFailure(Throwable exception) { notificationManager.showError(exception.getMessage()); } }); } catch (WebSocketException e) { e.printStackTrace(); } } }; CancelCallback cancelCallback = new CancelCallback() { @Override public void cancelled() { } }; dialogFactory.createConfirmDialog(localizationConstant.actionNewFileAddToIndexTitle(), localizationConstant.actionNewFileAddToIndexText(fileName), confirmCallback, cancelCallback).show(); }
Source:
<code>public CPPASTLiteralExpression(int kind, char[] value) { fKind = kind; <START> this.setValue(value); <END> }</code><technical_language>Redundant qualifier</technical_language>

Target:
public CPPASTLiteralExpression(int kind, char[] value) { this(kind, value, CharArrayUtils.EMPTY); }
Source:
<code>public IStatus discardComment(IReviewItem item, IComment comment, IProgressMonitor monitor) { <START> short side = 1; <END> String id = item.getId(); if (id.startsWith("base-")) { id = id.substring(5); side = 0; } Patch.Key key = Patch.Key.parse(id); for (ILocation location : comment.getLocations()) { if (location instanceof ILineLocation) { ILineLocation lineLocation = (ILineLocation) location; DiscardDraftRequest request = new DiscardDraftRequest(key, lineLocation.getRangeMin(), side); request.setMessage(comment.getDescription()); request.setUuid(comment.getId()); GerritOperation<VoidResult> operation = getOperationFactory().createDiscardDraftOperation(getTask(), request); return operation.run(monitor); } } throw new RuntimeException("Internal Exception. No line location for comment. Comment: " + comment.getId()); }</code><technical_language>consider creating a constant a meaningful name, magic numbers</technical_language>

Target:
public IStatus discardComment(IReviewItem item, IComment comment, IProgressMonitor monitor) { short side = 1; String id = item.getId(); if (id.startsWith("base-")) { id = id.substring(5); side = 0; } Patch.Key key = Patch.Key.parse(id); for (ILocation location : comment.getLocations()) { if (location instanceof ILineLocation) { ILineLocation lineLocation = (ILineLocation) location; DiscardDraftRequest request = new DiscardDraftRequest(key, lineLocation.getRangeMin(), side); request.setMessage(comment.getDescription()); request.setUuid(comment.getId()); GerritOperation<VoidResult> operation = getOperationFactory().createDiscardDraftOperation(getTask(), request); return operation.run(monitor); } } throw new RuntimeException(Messages.GerritReviewBehavior_Internal_Exception + comment.getId()); }
Source:
<code>private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class<?> clazz) { <START> System.out.println(clazz); System.out.println(weapon); <END> assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); assertEquals(expectedWeaponType, weapon.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); }</code><technical_language>remove console printouts proper logger</technical_language>

Target:
private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class<?> clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); assertEquals(expectedWeaponType, weapon.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); }
Source:
<code>public Object getPropertyValue(String name, int index) { Property reservedProperty = getReservedProperty(name); if (reservedProperty != null) { return reservedProperty.getValue(); } <START> getFetchHints().assertPropertyIncluded(name); <END> Property property = this.properties.getProperty(name, index); if (property == null) { return null; } return property.getValue(); }</code><technical_language>Move this check getPropertyValue(String key, String name, int index), gut this method call other one</technical_language>

Target:
public Object getPropertyValue(String name, int index) { return getPropertyValue(null, name, index); }
Source:
<code>public void tearDown() { log.info("tearDown"); try { if (server != null) { log.debug("destroying server process"); try { int pid = getUnixPID(server.getProcess()); <START> Runtime.getRuntime().exec("kill -INT " + pid).waitFor(); <END> } catch (IllegalArgumentException e) { server.getProcess().destroy(); } server.getProcess().waitFor(); log.debug("destroyed server process"); } log.debug("waited for server process"); } catch (Throwable e) { throw new RuntimeException("Server shutdown error: ", e); } }</code><technical_language>add a note this is required? I suprised server.interrupt() propagate process</technical_language>

Target:
public void tearDown() { log.info("tearDown"); try { if (server != null) { log.debug("destroying server process"); server.interrupt(); log.debug("send shutdown command to the BTDomainAdmin"); X_OCTET sendbuf = (X_OCTET) connection.tpalloc("X_OCTET", null); sendbuf.setByteArray("shutdown,testsui,0,".getBytes()); connection.tpcall("BTDomainAdmin", sendbuf, 0); log.debug("destroyed server process"); server.getProcess().waitFor(); } log.debug("waited for server process"); } catch (Throwable e) { throw new RuntimeException("Server shutdown error: ", e); } }
Source:
<code>private <T> T loadOsgiPlugin(Class<T> type, String className) { if (bundleContext == null) { throw new PluginLoadingException("Bundle context is null"); } <START> Class<?> clazz = null; <END> for (Bundle bundle : bundleContext.getBundles()) { try { clazz = bundle.loadClass(className); } catch (ClassNotFoundException e) { } } if (clazz == null) { throw new PluginLoadingException("Class " + className + " do not exist in any bundle"); } try { return type.cast(clazz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { throw new PluginLoadingException("Cannot instantiate plugin for type " + className, e); } }</code><technical_language>searching bundles</technical_language>

Target:
private <T> T loadOsgiPlugin(Class<T> type, String className) { if (bundleContext == null) { return null; } ServiceTracker<T, T> serviceTracker = getServiceTracker(type); @SuppressWarnings("unchecked") T[] services = serviceTracker.getServices((T[]) new Object[serviceTracker.size()]); for (T service : services) { if ((service != null) && (service.getClass().getName().equals(className))) { return service; } } return null; }
Source:
<code>protected static void test_StartWebViewActivity_LoadsUrlAndShowsTitle(@NonNull String url, @Nullable String title) { final WebViewActivity activity = Robolectric.buildActivity(WebViewActivity.class) .withIntent(WebViewActivity.newIntent( RuntimeEnvironment.application, url,title)).setup().get(); final View contentView = Shadows.shadowOf(activity).getContentView(); assertNotNull(contentView); final WebView webView = (WebView) contentView.findViewById(R.id.webView); assertNotNull(webView); final ShadowWebView shadowWebView = Shadows.shadowOf(webView); assertEquals(shadowWebView.getLastLoadedUrl(), url); final ActionBar actionBar = activity.getSupportActionBar(); assertNotNull(actionBar); assertTrue(actionBar.isShowing()); if (!TextUtils.isEmpty(title)) { assertTrue(title.equals(actionBar.getTitle())); <START> } <END> activity.onBackPressed(); assertTrue(activity.isFinishing()); }</code><technical_language>If title parameter _is_ empty, action bar title verified [default](<LINK_0> well</technical_language>

Target:
private void test_StartWebViewActivity_LoadsUrlAndShowsTitle(@NonNull String url, @Nullable String title) throws PackageManager.NameNotFoundException { final WebViewActivity activity = Robolectric.buildActivity(WebViewActivity.class) .withIntent(WebViewActivity.newIntent( RuntimeEnvironment.application, url, title)).setup().get(); final View contentView = Shadows.shadowOf(activity).getContentView(); assertNotNull(contentView); final WebView webView = (WebView) contentView.findViewById(R.id.webView); assertNotNull(webView); final ShadowWebView shadowWebView = Shadows.shadowOf(webView); assertEquals(shadowWebView.getLastLoadedUrl(), url); final ActionBar actionBar = activity.getSupportActionBar(); assertNotNull(actionBar); assertThat(actionBar).isShowing(); if (!TextUtils.isEmpty(title)) { assertThat(actionBar).hasTitle(title); } }
Source:
<code>private void downloadMedia(Media m) { String imageUrl = m.getImageUrl(), fileName = m.getFilename(); if (imageUrl == null || fileName == null || getContext() == null || getActivity() == null) { Timber.d("Skipping download media as either imageUrl %s or filename %s activity is null", imageUrl, fileName); return; } fileName = fileName.replaceFirst("^File:", ""); Uri imageUri = Uri.parse(imageUrl); DownloadManager.Request req = new DownloadManager.Request(imageUri); req.setDescription(getString(R.string.app_name)); req.setTitle(m.getDisplayTitle()); req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); req.allowScanningByMediaScanner(); req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); <START> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M <END> && ContextCompat.checkSelfPermission(getContext(), WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED && getView() != null) { PermissionUtils.checkPermissionsAndPerformAction(getActivity(), WRITE_EXTERNAL_STORAGE, () -> enqueueRequest(req), () -> Toast.makeText(getContext(),R.string.donwload_failed_we_cannot_download_the_file_without_storage_permission,Toast.LENGTH_SHORT).show(), R.string.storage_permission, R.string.write_storage_permission_rationale); } else { enqueueRequest(req); } }</code><technical_language>IMO if condition removed</technical_language>

Target:
private void downloadMedia(Media m) { String imageUrl = m.getImageUrl(), fileName = m.getFilename(); if (imageUrl == null || fileName == null || getContext() == null || getActivity() == null) { Timber.d("Skipping download media as either imageUrl %s or filename %s activity is null", imageUrl, fileName); return; } fileName = fileName.replaceFirst("^File:", ""); Uri imageUri = Uri.parse(imageUrl); DownloadManager.Request req = new DownloadManager.Request(imageUri); req.setDescription(getString(R.string.app_name)); req.setTitle(m.getDisplayTitle()); req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); req.allowScanningByMediaScanner(); req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); PermissionUtils.checkPermissionsAndPerformAction(getActivity(), WRITE_EXTERNAL_STORAGE, () -> enqueueRequest(req), () -> Toast.makeText(getContext(), R.string.download_failed_we_cannot_download_the_file_without_storage_permission, Toast.LENGTH_SHORT).show(), R.string.storage_permission, R.string.write_storage_permission_rationale); }
Source:
<code>public ResourceKind getKind(){ <START> if(node.has(ResourcePropertyKeys.KIND)){ <END> return ResourceKind.valueOf(node.get(ResourcePropertyKeys.KIND).asString()); } return null; }</code><technical_language>@adietish this works for "labels" "kind" technically is in correct. ResourcePropertyKeys is a key change a path defined in ResourcePropertiesRegistry. This path is versioned defined path. This class a number of helper methods retrieve values based keys direct of node is legacy implemented. consider helper methods</technical_language>

Target:
public ResourceKind getKind(){ ModelNode kindNode = get(ResourcePropertyKeys.KIND); if(kindNode.isDefined()){ return ResourceKind.valueOf(kindNode.asString()); } return null; }
Source:
<code>public void setLunId(String value) { <START> if (!privateLunId.equals(value)) <END> { privateLunId = value; onPropertyChanged(new PropertyChangedEventArgs("LUN ID")); } }</code><technical_language>nullity check :)</technical_language>

Target:
public void setLunId(String value) { if (privateLunId != null && !privateLunId.equals(value)) { privateLunId = value; onPropertyChanged(new PropertyChangedEventArgs("LUN ID")); } }
Source:
<code>public void createIndexes(Connection connection, String namespace) throws SQLException { if ("agency".equals(name)) { <START> LOG.info("Skipping indexes for table", name); <END> return; } LOG.info("Indexing..."); String tableName; if (namespace == null) { throw new IllegalStateException("Schema namespace must be provided!"); } else { tableName = namespace.endsWith(".") ? namespace + name : String.join(".", namespace, name); } String indexColumns = getIndexFields(); String indexName = String.join("_", tableName.replace(".", "_"), "idx"); String indexSql = String.format("create index %s on %s (%s)", indexName, tableName, indexColumns); LOG.info(indexSql); connection.createStatement().execute(indexSql); for (Field field : fields) { if (field.shouldBeIndexed()) { Statement statement = connection.createStatement(); String fieldIndex = String.join("_", tableName.replace(".", "_"), field.name, "idx"); String sql = String.format("create index %s on %s (%s)", fieldIndex, tableName, field.name); LOG.info(sql); statement.execute(sql); } } }</code><technical_language>This need a template string</technical_language>

Target:
public void createIndexes(Connection connection, String namespace) throws SQLException { if ("agency".equals(name) || "feed_info".equals(name)) { LOG.info("Skipping indexes for table", name); return; } LOG.info("Indexing {}...", name); String tableName; if (namespace == null) { throw new IllegalStateException("Schema namespace must be provided!"); } else { tableName = namespace.endsWith(".") ? namespace + name : String.join(".", namespace, name); } String indexColumns = getIndexFields(); String indexName = String.join("_", tableName.replace(".", "_"), "idx"); String indexSql = String.format("create index %s on %s (%s)", indexName, tableName, indexColumns); LOG.info(indexSql); connection.createStatement().execute(indexSql); for (Field field : fields) { if (field.shouldBeIndexed()) { Statement statement = connection.createStatement(); String fieldIndex = String.join("_", tableName.replace(".", "_"), field.name, "idx"); String sql = String.format("create index %s on %s (%s)", fieldIndex, tableName, field.name); LOG.info(sql); statement.execute(sql); } } }
Source:
<code>public Object getProperty(final Object object) { try { AccessPermissionChecker.checkAccessPermission(field); } catch (AccessControlException ex) { <START> throw new IllegalArgumentException("Illegal access to field" + " " + field.getName()); <END> } try { return field.get(object); } catch (IllegalAccessException e) { throw new GroovyRuntimeException("Cannot get the property '" + name + "'.", e); } }</code><technical_language>reason for IllegalArgumentException? I more appropriate: java throw new GroovyRuntimeException("Illegal access field " + field.getName() + ".", ex);</technical_language>

Target:
public Object getProperty(final Object object) { AccessPermissionChecker.checkAccessPermission(field); try { return field.get(object); } catch (IllegalAccessException e) { throw new GroovyRuntimeException("Cannot get the property '" + name + "'.", e); } }
Source:
<code>public void testConcurrentStart(int eagerManager, int lazyManager) throws Exception { TestResourceTracker.testThreadStarted(this); String name1 = TestResourceTracker.getNextNodeName(); String name2 = TestResourceTracker.getNextNodeName(); JChannel ch1 = createChannel(name1, 0); JChannel ch2 = createChannel(name2, 1); EmbeddedCacheManager cm1 = createCacheManager(name1, ch1); EmbeddedCacheManager cm2 = createCacheManager(name2, ch2); try { assertEquals(ComponentStatus.INSTANTIATED, extractGlobalComponentRegistry(cm1).getStatus()); assertEquals(ComponentStatus.INSTANTIATED, extractGlobalComponentRegistry(cm2).getStatus()); log.debugf("Channels created. Starting the caches"); Future<Object> repl1Future = fork(() -> manager(eagerManager).getCache("repl")); <START> Thread.sleep(1000); <END> Future<Object> repl2Future = fork(() -> manager(lazyManager).getCache("repl")); repl1Future.get(10, SECONDS); repl2Future.get(10, SECONDS); Cache<String, String> c1r = cm1.getCache("repl"); Cache<String, String> c2r = cm2.getCache("repl"); blockUntilViewsReceived(10000, cm1, cm2); waitForRehashToComplete(c1r, c2r); c1r.put("key", "value"); assertEquals("value", c2r.get("key")); } finally { cm1.stop(); cm2.stop(); ch1.close(); ch2.close(); } }</code><technical_language>get rid of this sleep</technical_language>

Target:
public void testConcurrentStart(int eagerManager, int lazyManager) throws Exception { TestResourceTracker.testThreadStarted(this); String name1 = TestResourceTracker.getNextNodeName(); String name2 = TestResourceTracker.getNextNodeName(); JChannel ch1 = createChannel(name1, 0); JChannel ch2 = createChannel(name2, 1); EmbeddedCacheManager cm1 = createCacheManager(name1, ch1); EmbeddedCacheManager cm2 = createCacheManager(name2, ch2); try { assertEquals(ComponentStatus.INSTANTIATED, extractGlobalComponentRegistry(cm1).getStatus()); assertEquals(ComponentStatus.INSTANTIATED, extractGlobalComponentRegistry(cm2).getStatus()); log.debugf("Channels created. Starting the caches"); Future<Object> repl1Future = fork(() -> manager(eagerManager).getCache("repl")); Thread.sleep(500); Future<Object> repl2Future = fork(() -> manager(lazyManager).getCache("repl")); repl1Future.get(10, SECONDS); repl2Future.get(10, SECONDS); Cache<String, String> c1r = cm1.getCache("repl"); Cache<String, String> c2r = cm2.getCache("repl"); blockUntilViewsReceived(10000, cm1, cm2); waitForRehashToComplete(c1r, c2r); c1r.put("key", "value"); assertEquals("value", c2r.get("key")); } finally { cm1.stop(); cm2.stop(); ch1.close(); ch2.close(); } }
Source:
<code>private JLabel getAddedCountValueLabel() { if (addedCountValueLabel == null) { <START> addedCountValueLabel = new javax.swing.JLabel(); <END> addedCountValueLabel.setText(ZERO_REQUESTS_LABEL_TEXT); } return addedCountValueLabel; }</code><technical_language>this new JLabel()</technical_language>

Target:
private JLabel getAddedCountValueLabel() { if (addedCountValueLabel == null) { addedCountValueLabel = new JLabel(); addedCountValueLabel.setText(ZERO_REQUESTS_LABEL_TEXT); } return addedCountValueLabel; }
Source:
<code>protected void onSuccess(String response) { if(response == null) { RuntimeException responseEmpty = new IllegalArgumentException("End user params are missing"); wootricApiCallback.onApiError(responseEmpty); <START> return; <END> } try { JSONArray jsonArray = new JSONArray(response); if(jsonArray.length() > 0) { JSONObject jsonObject = jsonArray.getJSONObject(0); long endUserId = jsonObject.getLong("id"); wootricApiCallback.onGetEndUserIdSuccess(endUserId); } else { wootricApiCallback.onEndUserNotFound(); } } catch (JSONException e) { wootricApiCallback.onApiError(e); } }</code><technical_language>I for early return avoid response null. refactor a bit this error case is handled in else block. java protected void onSuccess(String response) { if (response != null) { try { JSONArray jsonArray = new JSONArray(response); if (jsonArray.length() > 0) { JSONObject jsonObject = jsonArray.getJSONObject(0); long endUserId = jsonObject.getLong("id"); wootricApiCallback.onGetEndUserIdSuccess(endUserId); } else { wootricApiCallback.onEndUserNotFound(); } } catch (JSONException e) { wootricApiCallback.onApiError(e); } } else { wootricApiCallback.onApiError( new IllegalArgumentException("End user params missing")); } }</technical_language>

Target:
protected void onSuccess(String response) { if(response != null) { try { JSONArray jsonArray = new JSONArray(response); if(jsonArray.length() > 0) { JSONObject jsonObject = jsonArray.getJSONObject(0); long endUserId = jsonObject.getLong("id"); wootricApiCallback.onGetEndUserIdSuccess(endUserId); } else { wootricApiCallback.onEndUserNotFound(); } } catch (JSONException e) { wootricApiCallback.onApiError(e); } } else { wootricApiCallback.onApiError(new IllegalArgumentException("End user params are missing")); } }
Source:
<code>public void onLoad() { <START> offset = world.rand.nextInt(10); <END> }</code><technical_language>Add java super.onLoad(); worry future additions parent's onLoad function called this</technical_language>

Target:
public void onLoad() { super.onLoad(); offset = world.rand.nextInt(10); }
Source:
<code>public CSVParser(final Optional<String> listDelimiter) { this.listDelimiter = listDelimiter.isPresent() ? listDelimiter.get() : Parsers.DEFAULT_LIST_DELIMITER; Preconditions.checkState( <START> !this.listDelimiter.equals(String.valueOf(au.com.bytecode.opencsv.CSVParser.DEFAULT_SEPARATOR)), <END> "Cannot have list delimiter of [%s]", au.com.bytecode.opencsv.CSVParser.DEFAULT_SEPARATOR ); this.listSplitter = Splitter.on(this.listDelimiter); this.valueFunction = new Function<String, Object>() { @Override public Object apply(String input) { if (input.contains(CSVParser.this.listDelimiter)) { return Lists.newArrayList( Iterables.transform( listSplitter.split(input), ParserUtils.nullEmptyStringFunction ) ); } else { return ParserUtils.nullEmptyStringFunction.apply(input); } } }; }</code><technical_language>CSV parser handles escaping fine commas a list delimiter. sense some people</technical_language>

Target:
public CSVParser(final Optional<String> listDelimiter) { this.listDelimiter = listDelimiter.isPresent() ? listDelimiter.get() : Parsers.DEFAULT_LIST_DELIMITER; this.listSplitter = Splitter.on(this.listDelimiter); this.valueFunction = new Function<String, Object>() { @Override public Object apply(String input) { if (input.contains(CSVParser.this.listDelimiter)) { return Lists.newArrayList( Iterables.transform( listSplitter.split(input), ParserUtils.nullEmptyStringFunction ) ); } else { return ParserUtils.nullEmptyStringFunction.apply(input); } } }; }
Source:
<code><START> public List<RuntimeException> getTerminatedBy() { <END> return new ArrayList<RuntimeException>(terminatedBy); }</code><technical_language>(or @Restricted(NoExternalUse.class) if this is intended a public API)</technical_language>

Target:
public List<TerminationRequest> getTerminatedBy() { return new ArrayList<TerminationRequest>(terminatedBy); }
Source:
<code>public CellDebugPrint() { strings = new Vector<Vector<Vector<String>>>();; <START> } <END></code><technical_language>Vector ArrayList</technical_language>

Target:
public CellDebugPrint() { strings = new ArrayList<ArrayList<ArrayList<String>>>();; }
Source:
<code>protected void doExecute() { DiagramDescription diagramdesc = DescriptionFactory.eINSTANCE.createDiagramDescription(); <START> diagramdesc.setName(BASE_ID + ".default.layer"); <END> viewpoint.getOwnedRepresentations().add(diagramdesc); Layer layer = DescriptionFactory.eINSTANCE.createLayer(); diagramdesc.setDefaultLayer(layer); ToolSection toolSection = createToolSection(layer); ContainerMapping packageMapping = createPackageMapping(layer, toolSection); ContainerMapping classMapping = createClassMapping(layer, toolSection); NodeMapping attribute = createAttribute(classMapping, toolSection); EdgeMapping edgeMappingInheritance = createEdgeMappingInheritance(layer, toolSection, classMapping); EdgeMapping edgeMappingReference = createEdgeMappingReference(layer, toolSection, classMapping); createDeleteTool(toolSection, classMapping, packageMapping, attribute, edgeMappingInheritance, edgeMappingReference); createEditTool(toolSection, classMapping, packageMapping, attribute, edgeMappingInheritance, edgeMappingReference); }</code><technical_language>baseId +diagram</technical_language>

Target:
protected void doExecute() { DiagramDescription diagramdesc = DescriptionFactory.eINSTANCE.createDiagramDescription(); diagramdesc.setName(baseId + "diagram"); viewpoint.getOwnedRepresentations().add(diagramdesc); Layer layer = DescriptionFactory.eINSTANCE.createLayer(); layer.setName(baseId + ".default.layer"); diagramdesc.setDefaultLayer(layer); ToolSection toolSection = createToolSection(layer); ContainerMapping packageMapping = createPackageMapping(layer, toolSection); ContainerMapping classMapping = createClassMapping(layer, toolSection); NodeMapping attribute = createAttribute(classMapping, toolSection); EdgeMapping edgeMappingInheritance = createEdgeMappingInheritance(layer, toolSection, classMapping); EdgeMapping edgeMappingReference = createEdgeMappingReference(layer, toolSection, classMapping); createDeleteTool(toolSection, classMapping, packageMapping, attribute, edgeMappingInheritance, edgeMappingReference); createEditTool(toolSection, classMapping, packageMapping, attribute, edgeMappingInheritance, edgeMappingReference); }
Source:
<code>public boolean mustRecycleReceivers() { <START> return false; <END> }</code><technical_language>this changing default behavior</technical_language>

Target:
public boolean mustRecycleReceivers() { return true; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { PlotCommit commit = (PlotCommit) getSelection(event).getFirstElement(); final Repository repo = getRepository(event); try { PushBranchWizard wizard = null; <START> Ref goodRef = null; <END> for (int i = 0; i < commit.getRefCount(); i++) { Ref currentRef = commit.getRef(i); if (goodRef == null && currentRef.getName().startsWith(Constants.R_HEADS)) { goodRef = currentRef; } } if (goodRef == null) { wizard = new PushBranchWizard(repo, commit.getId()); } else { wizard = new PushBranchWizard(repo, goodRef); } WizardDialog dlg = new WizardDialog( HandlerUtil.getActiveShellChecked(event), wizard); dlg.setHelpAvailable(true); dlg.open(); } catch (Exception e) { Activator.handleError(e.getMessage(), e, true); } return null; }</code><technical_language>better: localBranch</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { PlotCommit commit = (PlotCommit) getSelection(event).getFirstElement(); final Repository repo = getRepository(event); try { PushBranchWizard wizard = null; Ref localBranch = null; for (int i = 0; i < commit.getRefCount(); i++) { Ref currentRef = commit.getRef(i); if (localBranch == null && currentRef.getName().startsWith(Constants.R_HEADS)) { localBranch = currentRef; } } if (localBranch == null) { wizard = new PushBranchWizard(repo, commit.getId()); } else { wizard = new PushBranchWizard(repo, localBranch); } WizardDialog dlg = new WizardDialog( HandlerUtil.getActiveShellChecked(event), wizard); dlg.setHelpAvailable(true); dlg.open(); } catch (Exception e) { Activator.handleError(e.getMessage(), e, true); } return null; }
Source:
<code>private static boolean isEmptyArray(ExpressionTree expression) { if (!expression.is(Tree.Kind.NEW_ARRAY)) { return false; } NewArrayTree nat = (NewArrayTree) expression; <START> return nat.dimensions().stream().allMatch(PublicStaticMutableMembersCheck::isZeroDimension) && nat.initializers().isEmpty(); <END> }</code><technical_language>I expect check here: hasEmptyInitializer(nat) || allDimensionsAreZero(nat)</technical_language>

Target:
private static boolean isEmptyArray(ExpressionTree expression) { if (!expression.is(Tree.Kind.NEW_ARRAY)) { return false; } NewArrayTree nat = (NewArrayTree) expression; return hasEmptyInitializer(nat) || hasOnlyZeroDimensions(nat.dimensions()); }
Source:
<code>public static <T extends TypedSPI> T getCachedInstance(final Class<T> typedService, final String type) { T instance = TYPED_SERVICES.containsKey(typedService) ? (T) TYPED_SERVICES.get(typedService).get(type) : null; <START> if (instance == null) { <END> throw new JobConfigurationException("Cannot find a cached typed service instance by the interface: @" + typedService.getName() + "and type: " + type); } return instance; }</code><technical_language>constants left variable right in = equals conditional expressions; variable left constants right in greater conditional expressions. Ref <LINK_0></technical_language>

Target:
public static <T extends TypedSPI> T getCachedInstance(final Class<T> typedService, final String type) { T instance = TYPED_SERVICES.containsKey(typedService) ? (T) TYPED_SERVICES.get(typedService).get(type) : null; if (null == instance) { throw new JobConfigurationException("Cannot find a cached typed service instance by the interface: @" + typedService.getName() + "and type: " + type); } return instance; }
Source:
<code><START> public int getVariableOptionIndex(){ <END> return variableOptionIndex; }</code><technical_language>remove public</technical_language>

Target:
int getVariableOptionIndex(){ return variableOptionIndex; }
Source:
<code>private void trackOverridingChains(@Nonnull JDefinedClass currentClass, @Nonnull State state) { for (JMethod method : currentClass.getMethods()) { if <START> (!method.isStatic() && !method.isPrivate() && !(method instanceof JConstructor)) { <END> String signature = getSignatureId(method); if (!state.currentMethods.containsKey(signature)) { state.newMethods.add(method); } state.currentMethods.put(signature, method); } } for (JDefinedClass derived : DirectlyDerivedClassesMarker.getDirectlyDerivedClasses(currentClass)) { trackOverridingChains(derived, state); } for (JMethod method : currentClass.getMethods()) { if (!method.isStatic() && !method.isPrivate() && !(method instanceof JConstructor)) { String signature = getSignatureId(method); assert state.currentMethods.containsKey(signature); JMethod candidate = state.currentMethods.get(signature); if (candidate != null) { assert candidate == method; state.effectivelyFinalMethods.add(method); } if (state.newMethods.contains(method)) { state.currentMethods.remove(signature); } else { state.currentMethods.put(signature, null); } } } }</code><technical_language>Similar code in line 126, move a method increase readability</technical_language>

Target:
private void trackOverridingChains(@Nonnull JDefinedClass currentClass, @Nonnull State state) { for (JMethod method : currentClass.getMethods()) { if (method.getMethodIdWide().getKind() == MethodKind.INSTANCE_VIRTUAL) { String signature = getSignatureId(method); if (!state.currentMethods.containsKey(signature)) { state.newMethods.add(method); } state.currentMethods.put(signature, method); } } for (JDefinedClass derived : DirectlyDerivedClassesMarker.getDirectlyDerivedClasses(currentClass)) { trackOverridingChains(derived, state); } for (JMethod method : currentClass.getMethods()) { if (method.getMethodIdWide().getKind() == MethodKind.INSTANCE_VIRTUAL) { String signature = getSignatureId(method); assert state.currentMethods.containsKey(signature); JMethod candidate = state.currentMethods.get(signature); if (candidate != null) { assert candidate == method; state.effectivelyFinalMethods.add(method); } if (state.newMethods.contains(method)) { state.currentMethods.remove(signature); } else { state.currentMethods.put(signature, null); } } } }
Source:
<code><START> int getLifetime() { <END> return lifetime; }</code><technical_language>other Builder getters public, this ok public is a public user option</technical_language>

Target:
public int getLifetime() { return lifetime; }