auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getHomeCommunityIdFromAssertion(AssertionType assertion) { String homeCommunity = null; try { if (NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { homeCommunity = assertion.getHomeCommunity().getHomeCommunityId(); } <START> } catch (NullPointerException ex) { <END> LOG.warn("Could not obtain HCID from HomeCommunity in assertion.", ex); } return homeCommunity; }</code><technical_language>Remove NullPointerException catch statement rewrite a Null check</technical_language>

Target:
public static String getHomeCommunityIdFromAssertion(AssertionType assertion) { String homeCommunity = null; if (assertion != null && assertion.getHomeCommunity() != null && NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { homeCommunity = assertion.getHomeCommunity().getHomeCommunityId(); } return homeCommunity; }
Source:
<code><START> public void execute(String[] args, ConsoleReader reader) throws Exception <END> { ApplicationReport[] apps; if (args.length == 1) { if (currentApp == null) { throw new CliException("No application selected"); } else { apps = new ApplicationReport[]{currentApp}; } } else { apps = new ApplicationReport[args.length - 1]; for (int i = 1; i < args.length; i++) { ApplicationReport ap = findApplicationReportFromAppNameOrId(args[i]); if (ap == null) { throw new CliException("Streaming application with id or name " + args[i] + " is not found."); } else { apps[i - 1] = ap; } } } for (ApplicationReport app : apps) { try { JSONObject response = getResource(new StramAgent.StramUriSpec().path(StramWebServices.PATH_SHUTDOWN), app, new WebServicesClient.WebServicesHandler<JSONObject>() { @Override public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz) { return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject()); } }); if (consolePresent) { System.out.println("Shutdown requested: " + response); } currentApp = null; } catch (Exception e) { throw new CliException("Failed to request shutdown for appid " + app.getApplicationId().toString(), e); } } }</code><technical_language>callers throw identical exception returned app is null. throw exception caller assume app is non-null? Thinking further, current behavior - proposed suggestion - fails command if a single app-id/app-name is found. Do want behavior modify ignore invalid app-id/app-name</technical_language>

Target:
public void execute(String[] args, ConsoleReader reader) throws Exception { Map<String, ApplicationReport> appIdReports = new LinkedHashMap<>(); if (args.length == 1) { if (currentApp == null) { throw new CliException("No application selected"); } else { appIdReports.put(currentApp.getApplicationId().toString(), currentApp); } } else { String[] appNamesOrIds = Arrays.copyOfRange(args, 1, args.length); for (String appNameOrId : appNamesOrIds) { ApplicationReport ap = findApplicationReportFromAppNameOrId(appNameOrId); appIdReports.put(appNameOrId, ap); } } for (Map.Entry<String, ApplicationReport> entry : appIdReports.entrySet()) { String appNameOrId = entry.getKey(); ApplicationReport app = entry.getValue(); shutdownApp(appNameOrId, app); } }
Source:
<code>public void getVariables() { TestSuiteModel testSuite = new TestSuiteModel(); <START> String variable_indentifier = "variable_indentifier"; <END> String variable_content = "variable_content"; String variable_description = "variable_description"; assertEquals(0, testSuite.getVariables().size()); testSuite.addVariable(variable_indentifier, variable_content, variable_description); assertEquals(1, testSuite.getVariables().size()); }</code><technical_language>please stick java conventions variable names</technical_language>

Target:
public void getVariables() { TestSuiteModel testSuite = new TestSuiteModel(); for (int index = 0; index < elements; index++) { testSuite.setVariable(variableIndentifier[index], variableContent[index], variableDescription[index]); assertEquals(index + 1, testSuite.getVariables().size()); } }
Source:
<code>private static boolean isExternalStorageWritable() { <START> return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); <END> }</code><technical_language>reverse order of equals()</technical_language>

Target:
private static boolean isExternalStorageWritable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); }
Source:
<code>private void requestPurchasesForDeletionCheck() { final Blog currentBlog = WordPress.getCurrentBlog(); WordPress.getRestClientUtils().getSitePurchases(currentBlog.getDotComBlogId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { showPurchasesOrDeleteSiteDialog(response, currentBlog); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { ToastUtils.showToast(getActivity(), getString(R.string.purchases_request_error)); <START> AppLog.e(AppLog.T.API, error.toString()); <END> } }); }</code><technical_language>add a description for error here, "Error occurred while requesting purchases for deletion check: " + error.toString(). I easier for find issue logs, especially for HEs</technical_language>

Target:
private void requestPurchasesForDeletionCheck() { final Blog currentBlog = WordPress.getCurrentBlog(); final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.checking_purchases), true, false); WordPress.getRestClientUtils().getSitePurchases(currentBlog.getDotComBlogId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { progressDialog.dismiss(); if (isAdded()) { showPurchasesOrDeleteSiteDialog(response, currentBlog); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); if (isAdded()) { ToastUtils.showToast(getActivity(), getString(R.string.purchases_request_error)); AppLog.e(AppLog.T.API, "Error occurred while requesting purchases for deletion check: " + error.toString()); } } }); }
Source:
<code>private boolean areBundlesReady(Set<String> toCheck) { BundleStates states = getUnavailableBundles(toCheck); if (!states.getFailedBundles().isEmpty()) { throw new SynchronizedInstallerException( "Bundles failed to start [" + bundleSymbolicNamesToString(states.getFailedBundles()) + "]"); } if (!states.getUnavailableBundles().isEmpty()) { <START> String unavailableBundles = bundleSymbolicNamesToString(states.getUnavailableBundles()); <END> LOGGER.debug( "Waiting on the following bundles to reach a ready state [{}]", unavailableBundles); return false; } return true; }</code><technical_language>if (LOGGER.isDebugEnabled() { ... avoid this logging is turned</technical_language>

Target:
private boolean areBundlesReady(Set<String> toCheck) { BundleStates states = getUnavailableBundles(toCheck); if (!states.getFailedBundles().isEmpty()) { throw new SynchronizedInstallerException( "Bundles failed to start [" + bundleSymbolicNamesToString(states.getFailedBundles()) + "]"); } if (!states.getUnavailableBundles().isEmpty()) { if (LOGGER.isDebugEnabled()) { String unavailableBundles = bundleSymbolicNamesToString(states.getUnavailableBundles()); LOGGER.debug( "Waiting on the following bundles to reach a ready state [{}]", unavailableBundles); } return false; } return true; }
Source:
<code>public static boolean showYesNoDialog(Project project, final String message, final String title) throws IllegalAWTContextException { if (application.isWriteAccessAllowed()) { throw new IllegalAWTContextException("AWT events are not allowed inside write actions."); } LOG.info("Showing yes/no dialog: " + title + " - " + message); final AtomicReference<Integer> response = new AtomicReference<>(); application.invokeAndWait( () -> { Integer option = Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon()); response.set(option); }, ModalityState.defaultModalityState()); Integer result = response.get(); <START> if (result == null) { <END> throw new IllegalStateException("Synchronous yes-no dialog did not provide any results"); } switch (result) { case Messages.YES: return true; case Messages.NO: return false; default: throw new IllegalStateException("Encountered unknown dialog answer " + result); } }</code><technical_language>return result == Messages.YES ? I do get extra error handling. Is IntelliJ API buggy</technical_language>

Target:
public static boolean showYesNoDialog(Project project, final String message, final String title) throws IllegalAWTContextException { if (application.isWriteAccessAllowed()) { throw new IllegalAWTContextException("AWT events are not allowed inside write actions."); } LOG.info("Showing yes/no dialog: " + title + " - " + message); final AtomicReference<Integer> response = new AtomicReference<>(); application.invokeAndWait( () -> { Integer option = Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon()); response.set(option); }, ModalityState.defaultModalityState()); Integer result = response.get(); switch (result) { case Messages.YES: return true; case Messages.NO: return false; default: throw new IllegalStateException("Encountered unknown dialog answer " + result); } }
Source:
<code>public void anEvent(final int amount, final Map<String, String> data) throws Exception { final Device device = this.deviceRepository .findByDeviceIdentification(getString(data, Keys.KEY_DEVICE_IDENTIFICATION)); for (int i = 0; i < amount; i++) { final Event event = new Event(device, getDateTime(getString(data, Keys.TIMESTAMP, "now")).toDate(), getEnum(data, Keys.EVENT_TYPE, EventType.class, EventType.ALARM_NOTIFICATION), getString(data, Keys.KEY_DESCRIPTION, ""), getInteger(data, Keys.KEY_INDEX, Defaults.DEFAULT_INDEX)); this.eventRepository.save(event); } <START> <END> }</code><technical_language>Remove empty line</technical_language>

Target:
public void anEvent(final int amount, final Map<String, String> data) throws Exception { final Device device = this.deviceRepository .findByDeviceIdentification(getString(data, Keys.KEY_DEVICE_IDENTIFICATION)); for (int i = 0; i < amount; i++) { final Event event = new Event(device, getDateTime(getString(data, Keys.TIMESTAMP, Defaults.TIMESTAMP)).toDate(), getEnum(data, Keys.EVENT_TYPE, EventType.class, EventType.ALARM_NOTIFICATION), getString(data, Keys.KEY_DESCRIPTION), getInteger(data, Keys.KEY_INDEX, Defaults.DEFAULT_INDEX)); this.eventRepository.save(event); } }
Source:
<code>private void fetchCredentials(Intent intent) { final ListenableFuture<OAuthTokenCredential> future = oauthLoginManager.fetchOAuthTokenCredentialAsync(intent); future.addDoneListener(new Runnable() { @Override public void run() { try { oauthCred = future.get(); } catch (Exception e) { e.printStackTrace(); <START> return; <END> } } }); }</code><technical_language>Method returns void', return unnecessary</technical_language>

Target:
private void fetchCredentials(Intent intent) { final ListenableFuture<OAuthTokenCredential> future = oauthLoginManager.fetchOAuthTokenCredentialAsync(intent); future.addDoneListener(new Runnable() { @Override public void run() { try { oauthCred = future.get(); } catch (Exception e) { e.printStackTrace(); } } }); }
Source:
<code>public static List<IteratorTestCase> findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); <START> Reflections reflections = new Reflections(IteratorTestCase.class.getPackage().getName()); <END> final List<IteratorTestCase> testCases = new ArrayList<>(); final Set<Class<? extends IteratorTestCase>> classes = reflections.getSubTypesOf(IteratorTestCase.class); for (Class<? extends IteratorTestCase> clz : classes) { if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) { log.debug("Skipping " + clz); continue; } try { testCases.add(clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; }</code><technical_language>If this is a new dependency, Guava's [ClassPath.getAllClasses()](<LINK_0> iterator filter based type</technical_language>

Target:
public static List<IteratorTestCase> findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); ClassPath cp; try { cp = ClassPath.from(IteratorTestCaseFinder.class.getClassLoader()); } catch (IOException e) { throw new RuntimeException(e); } ImmutableSet<ClassInfo> classes = cp.getTopLevelClasses(IteratorTestCase.class.getPackage().getName()); final List<IteratorTestCase> testCases = new ArrayList<>(); for (ClassInfo classInfo : classes) { Class<?> clz; try { clz = Class.forName(classInfo.getName()); } catch (Exception e) { log.warn("Could not get class for " + classInfo.getName(), e); continue; } if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers()) || !IteratorTestCase.class.isAssignableFrom(clz)) { log.debug("Skipping " + clz); continue; } try { testCases.add((IteratorTestCase) clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; }
Source:
<code><START> public File getDatabasePath(String name) { <END> return new File(path); }</code><technical_language>This right method signature of base method -- name in some way. If want pass in full path db file, I DatabaseContext needs redesigned</technical_language>

Target:
public File getDatabasePath(String name) { return new File(path + File.separator + name); }
Source:
<code>protected VcloudClient newVcloudClient(String endpoint, String identity, String credential, String trustStore, String trustStorePassword, Level logLevel) { try { if (logLevel != null) { VcloudClient.setLogLevel(logLevel); } VcloudClient vcloudClient = null; boolean versionFound = false; for (Version version : VCLOUD_VERSIONS) { try { vcloudClient = new VcloudClient(endpoint, version); LOG.debug("VCloudClient - trying login to using {}", endpoint, version); vcloudClient.login(identity, credential); <START> if (trustStore != null && trustStorePassword != null) { <END> vcloudClient.registerScheme("https", 443, CustomSSLSocketFactory.getInstance(trustStore, trustStorePassword)); } else { LOG.warn("Ignoring the Certificate Validation using FakeSSLSocketFactory"); vcloudClient.registerScheme("https", 443, FakeSSLSocketFactory.getInstance()); } versionFound = true; LOG.info("VCloudClient - Logged into using version {}", endpoint, version); break; } catch (VCloudException e) { LOG.debug("VCloudClient - Cannot login to " + endpoint + " using " + version, e); } } if (!versionFound) { throw new IllegalStateException("Cannot login to " + endpoint + " using any of " + VCLOUD_VERSIONS); } return vcloudClient; } catch (Exception e) { throw Exceptions.propagate(e); } }</code><technical_language>if (Strings.isNonBlank(trustStore) && Strings.isNonBlank(trustStorePassword)). reason is if writes in properties file vchs.trustStore= I get a blank string null</technical_language>

Target:
protected VcloudClient newVcloudClient(String endpoint, String identity, String credential, String trustStore, String trustStorePassword, Level logLevel) { if (trustStore == null) { trustStore = getDefaultTrustStore(); } try { if (logLevel != null) { VcloudClient.setLogLevel(logLevel); } VcloudClient vcloudClient = null; boolean versionFound = false; for (Version version : VCLOUD_VERSIONS) { try { vcloudClient = new VcloudClient(endpoint, version); LOG.debug("VCloudClient - trying login to using {}", endpoint, version); if (Strings.isNonBlank(trustStorePassword)) { LOG.debug("Registering HTTPS scheme using trustStore ='{}'", trustStore); vcloudClient.registerScheme("https", 443, CustomSSLSocketFactory.getInstance(trustStore, trustStorePassword)); } else { LOG.warn("Registering HTTPS scheme using FakeSSLSocketFactory, as trustStore ='{}' and/or trustStorePassword are not valid.", trustStore); vcloudClient.registerScheme("https", 443, FakeSSLSocketFactory.getInstance()); } vcloudClient.login(identity, credential); versionFound = true; LOG.info("VCloudClient - Logged into using version {}", endpoint, version); break; } catch (VCloudException e) { LOG.debug("VCloudClient - Cannot login to " + endpoint + " using " + version, e); } } if (!versionFound) { throw new IllegalStateException("Cannot login to " + endpoint + " using any of " + VCLOUD_VERSIONS); } return vcloudClient; } catch (Exception e) { throw Exceptions.propagate(e); } }
Source:
<code>protected static void validateDisplaySizeIfNotNull(String displaySize, List<String> validationErrors) { <START> if (isNotBlank(displaySize) && (!StringUtils.isNumeric(displaySize) || Integer.valueOf(displaySize) < 1 || Integer.valueOf(displaySize) > 500)) { <END> validationErrors.add("display_size"); } }</code><technical_language>same,see isNumeric point</technical_language>

Target:
protected static void validateDisplaySizeIfNotNull(String displaySize, List<String> validationErrors) { if (isNotBlank(displaySize) && (!NumericValidator.isValid(displaySize) || Integer.valueOf(displaySize) < 1 || Integer.valueOf(displaySize) > 500)) { validationErrors.add("display_size"); } }
Source:
<code><START> public static List<String> getInputAlgo(HashMap<String, String> inputContent) throws IOException, DatasetsException, PathologyException { <END> List<String> nodesToBeChecked = new ArrayList<>(); String datasets; String[] userDatasets = null; String pathology = null; HashMap<String, String[]> nodeDatasets = new HashMap<>(); if (inputContent == null ) { for (ContainerProxy containerProxy : ArtRegistryLocator.getArtRegistryProxy().getContainers()) { System.out.println("ContainerProxy : " + containerProxy.getEntityName().getIP()); nodesToBeChecked.add(containerProxy.getEntityName().getIP()); } return nodesToBeChecked; } else if(inputContent.size()==1 && inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); for (ContainerProxy containerProxy : ArtRegistryLocator.getArtRegistryProxy().getContainers()) { System.out.println("ContainerProxy : " + containerProxy.getEntityName().getIP()); nodesToBeChecked.add(containerProxy.getEntityName().getIP()); } return nodesToBeChecked; } else { if (inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); } if (inputContent.containsKey("dataset")) { datasets = inputContent.get("dataset"); userDatasets = datasets.split(","); } nodesToBeChecked = checkDatasets(nodeDatasets, userDatasets, pathology); } return nodesToBeChecked; }</code><technical_language>refactor this function return a List<ContainerProxy> pingContainer search for container</technical_language>

Target:
public static List<ContainerProxy> getInputAlgo(HashMap<String, String> inputContent) throws IOException, DatasetsException, PathologyException { List<ContainerProxy> nodesToBeChecked = new ArrayList<>(); String datasets; String[] userDatasets = null; String pathology = null; HashMap<String, String[]> nodeDatasets = new HashMap<>(); if (inputContent == null ) { nodesToBeChecked.addAll(Arrays.asList(ArtRegistryLocator.getArtRegistryProxy().getContainers())); return nodesToBeChecked; } else if(inputContent.size()==1 && inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); nodesToBeChecked.addAll(Arrays.asList(ArtRegistryLocator.getArtRegistryProxy().getContainers())); return nodesToBeChecked; } else { if (inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); } else throw new PathologyException("The parameter pathology should not be blank"); if (inputContent.containsKey("dataset")) { datasets = inputContent.get("dataset"); userDatasets = datasets.split(","); } else throw new DatasetsException("The parameter dataset should not be blank"); if(nodeDatasets.isEmpty()){ throw new PathologyException("Existing nodes do not have data for pathology: "+pathology); } nodesToBeChecked = checkDatasets(nodeDatasets, userDatasets, pathology); } return nodesToBeChecked; }
Source:
<code>private void processShallow() throws IOException { DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(walk.getObjectReader(), depth); for (RevObject o : wantAll) { if (o instanceof RevCommit) depthWalk.markStart(depthWalk.parseCommit(o)); } RevObject o; while ((o = depthWalk.next()) != null) { DepthWalk.Commit c = (DepthWalk.Commit)o; <START> if (c.depth == depth && !clientShallowCommits.contains(c)) { <END> pckOut.writeString("shallow " + o.name()); } if (c.depth < depth && clientShallowCommits.contains(c)) { unshallowCommits.add(c); pckOut.writeString("unshallow " + c.name()); } } pckOut.end(); }</code><technical_language>This c.getDepth()</technical_language>

Target:
private void processShallow() throws IOException { DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(walk.getObjectReader(), depth); for (RevObject o : wantAll) { if (o instanceof RevCommit) depthWalk.markStart(depthWalk.parseCommit(o)); } RevObject o; while ((o = depthWalk.next()) != null) { DepthWalk.Commit c = (DepthWalk.Commit)o; if (c.getDepth() == depth && !clientShallowCommits.contains(c)) pckOut.writeString("shallow " + o.name()); if (c.getDepth() < depth && clientShallowCommits.contains(c)) { unshallowCommits.add(c.copy()); pckOut.writeString("unshallow " + c.name()); } } pckOut.end(); }
Source:
<code>public static Class<?>[] getClasses(Class<?> annotation, String... paths) { List<String> names = new FastClasspathScanner(paths).scan().getNamesOfClassesWithAnnotation(annotation); List<Class<?>> classes = new ArrayList<Class<?>>(); for (String c : names) { Class<?> classType; try { classType = Class.forName(c); } catch (ClassNotFoundException e) { throw new JaversException(JaversExceptionCode.CANT_FIND_CLASS_WITH_TYPENAME, c); } classes.add(classType); } <START> return null; <END> }</code><technical_language>this method (clue of PR) returns null. Write tests, check if fail, implement a new feature</technical_language>

Target:
public static List<Class<?>> getClasses(Class<?> annotation, String... paths) { List<String> names = new FastClasspathScanner(paths).scan().getNamesOfClassesWithAnnotation(annotation); List<Class<?>> classes = new ArrayList<Class<?>>(); for (String c : names) { Class<?> classType; try { classType = Class.forName(c); } catch (ClassNotFoundException e) { throw new JaversException(JaversExceptionCode.CANT_FIND_CLASS_WITH_TYPENAME, c); } classes.add(classType); } return classes; }
Source:
<code><START> public JobCoordinatorMetadata(String epochId, String configId, String jobModelId) { <END> this.configId = configId; this.epochId = epochId; this.jobModelId = jobModelId; }</code><technical_language>check notNull</technical_language>

Target:
public JobCoordinatorMetadata(String epochId, String configId, String jobModelId) { Preconditions.checkState(StringUtils.isNotBlank(epochId), "Epoch ID cannot be empty"); Preconditions.checkState(StringUtils.isNotBlank(configId), "Config ID cannot be empty"); Preconditions.checkState(StringUtils.isNotBlank(jobModelId), "Job Model ID cannot be empty"); this.configId = configId; this.epochId = epochId; this.jobModelId = jobModelId; }
Source:
<code><START> public VmTemplate readVmTemplateFromOvf(String ovf) throws OvfReaderException { <END> VmTemplate vmTemplate = new VmTemplate(); ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>(); ArrayList<VmNetworkInterface> interfaces = new ArrayList<VmNetworkInterface>(); ovfManager.ImportTemplate(ovf, vmTemplate, diskImages, interfaces); vmTemplate.setImages(diskImages); vmTemplate.setInterfaces(interfaces); Map<Guid, List<DiskImage>> images = ImagesHandler .getImagesLeaf(diskImages); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { List<DiskImage> list = entry.getValue(); vmTemplate.getDiskTemplateMap().put(entry.getKey(), list.get(list.size() - 1)); } return vmTemplate; }</code><technical_language>logic in /org/ovirt/engine/core/bll/storage/GetTemplatesFromExportDomainQuery.java (and query this instead duplicated).</technical_language>

Target:
public VmTemplate readVmTemplateFromOvf(String ovf) throws OvfReaderException { ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>(); ArrayList<VmNetworkInterface> interfaces = new ArrayList<VmNetworkInterface>(); VmTemplate template = new VmTemplate(); ovfManager.ImportTemplate(ovf, template, diskImages, interfaces); template.setInterfaces(interfaces); for (DiskImage disk : diskImages) { template.getDiskTemplateMap().put(disk.getId(), disk); } return template; }
Source:
<code>private String doLoad(String name, ClassLoader loader) { String ldLibraryPath = null; String dexPath = null; if (loader != null && loader instanceof BaseDexClassLoader) { <START> ldLibraryPath = ((BaseDexClassLoader) loader).getLdLibraryPath(); <END> dexPath = ((BaseDexClassLoader) loader).getDexPath(); } synchronized (this) { return nativeLoad(name, loader, ldLibraryPath, dexPath); } }</code><technical_language>want extract ((BaseDexClassLoader) loader) a local variable. call</technical_language>

Target:
private String doLoad(String name, ClassLoader loader) { String ldLibraryPath = null; String dexPath = null; if (loader != null && loader instanceof BaseDexClassLoader) { BaseDexClassLoader dexClassLoader = (BaseDexClassLoader) loader; ldLibraryPath = dexClassLoader.getLdLibraryPath(); dexPath = dexClassLoader.getDexPath(); } synchronized (this) { return nativeLoad(name, loader, ldLibraryPath, dexPath); } }
Source:
<code>private static boolean isValidAttributeName(String name) { if (name.length() == 0) return false; if (name.charAt(0) == '-') return false; for (int index = 0; index < name.length(); index++) { final char ch = name.charAt(index); <START> if (!(ch == '-' || ch == '.' || ch == '_' <END> || ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'))) return false; } return true; }</code><technical_language>This expression hard read. break out as: if ('0' <= ch && ch <= '9') continue; if ('a' <= ch && ch <= 'z') continue; if ('A' <= ch && ch <= 'Z') continue; ... return false; a table check validity: static boolean validChars[128]; static { for (char c = '0'; c <= '9'; c++) validChars[c] = true; validChars['-'] = true; ... } if (ch > 127 || !vaildChars[ch]) return false;</technical_language>

Target:
private static boolean isValidAttributeName(String name) { if (name.length() == 0) return false; if (name.charAt(0) == '-') return false; for (int index = 0; index < name.length(); index++) { final char ch = name.charAt(index); if ('0' <= ch && ch <= '9') continue; if ('a' <= ch && ch <= 'z') continue; if ('A' <= ch && ch <= 'Z') continue; if (ch == '-' || ch == '.' || ch == '_') continue; return false; } return true; }
Source:
<code>public void onItemClick(AdapterView<?> parent, View view, int position, long id) { position -= mDrawerList.getHeaderViewsCount(); mSelectedTag = mTagsAdapter.getItem(position); checkEmptyListText(false); setSelectedTagActive(); mDrawerLayout.closeDrawer(mNavigationView); updateNavigationDrawerItems(); if (mNoteListFragment.isHidden()) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.show(mNoteListFragment); ft.commitAllowingStateLoss(); <START> fm.executePendingTransactions(); <END> } if (mDrawerList.getCheckedItemPosition() == TRASH_SELECTED_ID) { getNoteListFragment().getListView().setLongClickable(false); } else { getNoteListFragment().getListView().setLongClickable(true); } getNoteListFragment().refreshListFromNavSelect(); if (position > 1) { AnalyticsTracker.track( AnalyticsTracker.Stat.LIST_TAG_VIEWED, AnalyticsTracker.CATEGORY_TAG, "selected_tag_in_navigation_drawer" ); } }</code><technical_language>This is another instance want replace ft.commitAllowingStateLoss(); fm.executePendingTransactions(); ft.commitNowAllowingStateLoss();</technical_language>

Target:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { position -= mDrawerList.getHeaderViewsCount(); mSelectedTag = mTagsAdapter.getItem(position); checkEmptyListText(false); setSelectedTagActive(); mDrawerLayout.closeDrawer(mNavigationView); updateNavigationDrawerItems(); if (mNoteListFragment.isHidden()) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.show(mNoteListFragment); ft.commitNowAllowingStateLoss(); } if (mDrawerList.getCheckedItemPosition() == TRASH_SELECTED_ID) { getNoteListFragment().getListView().setLongClickable(false); } else { getNoteListFragment().getListView().setLongClickable(true); } getNoteListFragment().refreshListFromNavSelect(); if (position > 1) { AnalyticsTracker.track( AnalyticsTracker.Stat.LIST_TAG_VIEWED, AnalyticsTracker.CATEGORY_TAG, "selected_tag_in_navigation_drawer" ); } }
Source:
<code>protected Promise<List<T>> run(final Context context) throws Exception { final SettablePromise<List<T>> result = Promises.settable(); if (_tasks.isEmpty()) { <START> result.done(Collections.<T>emptyList()); <END> return result; } final PromiseListener<?> listener = new PromiseListener<Object>() { @Override public void onResolved(Promise<Object> resolvedPromise) { boolean allEarlyFinish = true; final List<T> taskResult = new ArrayList<T>(); final List<Throwable> errors = new ArrayList<Throwable>(); for (Task<? extends T> task : _tasks) { if (task.isFailed()) { if (allEarlyFinish && ResultType.fromTask(task) != ResultType.EARLY_FINISH) { allEarlyFinish = false; } errors.add(task.getError()); } else { taskResult.add(task.get()); } } if (!errors.isEmpty()) { result .fail(allEarlyFinish ? errors.get(0) : new MultiException("Multiple errors in 'ParTask' task.", errors)); } else { result.done(taskResult); } } }; InternalUtil.after(listener, _tasks.toArray(new Task<?>[_tasks.size()])); for (Task<?> task : _tasks) { context.run(task); } return result; }</code><technical_language>return Promises.value(Collections.<T>emptyList()); move line 69</technical_language>

Target:
protected Promise<List<T>> run(final Context context) throws Exception { if (_tasks.isEmpty()) { return Promises.value(Collections.<T>emptyList()); } final SettablePromise<List<T>> result = Promises.settable(); final PromiseListener<?> listener = new PromiseListener<Object>() { @Override public void onResolved(Promise<Object> resolvedPromise) { boolean allEarlyFinish = true; final List<T> taskResult = new ArrayList<T>(); final List<Throwable> errors = new ArrayList<Throwable>(); for (Task<? extends T> task : _tasks) { if (task.isFailed()) { if (allEarlyFinish && ResultType.fromTask(task) != ResultType.EARLY_FINISH) { allEarlyFinish = false; } errors.add(task.getError()); } else { taskResult.add(task.get()); } } if (!errors.isEmpty()) { result .fail(allEarlyFinish ? errors.get(0) : new MultiException("Multiple errors in 'ParTask' task.", errors)); } else { result.done(taskResult); } } }; InternalUtil.after(listener, _tasks.toArray(new Task<?>[_tasks.size()])); for (Task<?> task : _tasks) { context.run(task); } return result; }
Source:
<code>public PageableResult search(RequestContext context) throws ResponseException { IdentifierSourceService identifierSourceService = Context.getService(IdentifierSourceService.class); UserService service = Context.getUserService(); String source = context.getRequest().getParameter("source"); String fromDate = context.getRequest().getParameter("fromDate"); String toDate = context.getRequest().getParameter("toDate"); String identifier = context.getRequest().getParameter("identifier"); String comment = context.getRequest().getParameter("comment"); String generatedBy = context.getRequest().getParameter("generatedBy"); List<LogEntry> logEntries = new ArrayList<LogEntry>(); IdentifierSource logSource = source != null ? identifierSourceService.getIdentifierSourceByUuid(source) : null; Date dateFrom = fromDate != null ? (Date) ConversionUtil.convert(fromDate, Date.class) : null; Date dateTo = toDate != null ? (Date) ConversionUtil.convert(toDate, Date.class) : null; User user = generatedBy != null ? service.getUserByUuid(generatedBy): null; if (logSource == null && identifier == null && comment == null && dateFrom == null && dateTo == null && user == null) { return new EmptySearchResult(); } logEntries = identifierSourceService.getLogEntries(logSource, dateFrom, dateTo, identifier, user, comment); return new NeedsPaging<LogEntry>(logEntries, context); <START> } <END></code><technical_language>add @override statement search search configuration</technical_language>

Target:
public PageableResult search(RequestContext context) throws ResponseException { IdentifierSourceService identifierSourceService = Context.getService(IdentifierSourceService.class); UserService service = Context.getUserService(); String source = context.getRequest().getParameter("source"); String fromDate = context.getRequest().getParameter("fromDate"); String toDate = context.getRequest().getParameter("toDate"); String identifier = context.getRequest().getParameter("identifier"); String comment = context.getRequest().getParameter("comment"); String generatedBy = context.getRequest().getParameter("generatedBy"); IdentifierSource logSource = source != null ? identifierSourceService.getIdentifierSourceByUuid(source) : null; Date dateFrom = fromDate != null ? (Date) ConversionUtil.convert(fromDate, Date.class) : null; Date dateTo = toDate != null ? (Date) ConversionUtil.convert(toDate, Date.class) : null; User user = generatedBy != null ? service.getUserByUuid(generatedBy): null; if (logSource == null && identifier == null && comment == null && dateFrom == null && dateTo == null && user == null) { return new EmptySearchResult(); } List<LogEntry> logEntries = identifierSourceService.getLogEntries(logSource, dateFrom, dateTo, identifier, user, comment); return new NeedsPaging<LogEntry>(logEntries, context); }
Source:
<code>protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { try { if (dataSink != null) { tupleWriter.open(dataSink.getOutputStream()); } <START> tupleWriter.writeColumnHeaders(getChild().getSchema().getColumnNames()); <END> } catch (IOException e) { throw new DbException(e); } }</code><technical_language>this succeed if tupleWriter.open() called (when dataSink is null)</technical_language>

Target:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { try { tupleWriter.open(dataSink.getOutputStream()); tupleWriter.writeColumnHeaders(getChild().getSchema().getColumnNames()); } catch (IOException e) { throw new DbException(e); } }
Source:
<code>private synchronized void load() { <START> try { <END> Map.Entry<ManagerSpec, Map<ResourceGroupIdTemplate, ResourceGroupSpec>> specsFromDb = buildSpecsFromDb(); ManagerSpec managerSpec = specsFromDb.getKey(); Map<ResourceGroupIdTemplate, ResourceGroupSpec> resourceGroupSpecs = specsFromDb.getValue(); Set<ResourceGroupIdTemplate> changedSpecs = new HashSet<>(); Set<ResourceGroupIdTemplate> deletedSpecs = Sets.difference(this.resourceGroupSpecs.keySet(), resourceGroupSpecs.keySet()); for (Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry : resourceGroupSpecs.entrySet()) { if (!entry.getValue().sameConfig(this.resourceGroupSpecs.get(entry.getKey()))) { changedSpecs.add(entry.getKey()); } } this.resourceGroupSpecs = resourceGroupSpecs; this.cpuQuotaPeriod.set(managerSpec.getCpuQuotaPeriod()); this.rootGroups.set(managerSpec.getRootGroups()); this.selectors.set(buildSelectors(managerSpec)); configureChangedGroups(changedSpecs); disableDeletedGroups(deletedSpecs); } catch (Exception ex) { log.error("Error loading resource groups: %s", ex); } }</code><technical_language>clear this change do queued running time limits</technical_language>

Target:
private synchronized void load() { Map.Entry<ManagerSpec, Map<ResourceGroupIdTemplate, ResourceGroupSpec>> specsFromDb = buildSpecsFromDb(); ManagerSpec managerSpec = specsFromDb.getKey(); Map<ResourceGroupIdTemplate, ResourceGroupSpec> resourceGroupSpecs = specsFromDb.getValue(); Set<ResourceGroupIdTemplate> changedSpecs = new HashSet<>(); Set<ResourceGroupIdTemplate> deletedSpecs = Sets.difference(this.resourceGroupSpecs.keySet(), resourceGroupSpecs.keySet()); for (Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry : resourceGroupSpecs.entrySet()) { if (!entry.getValue().sameConfig(this.resourceGroupSpecs.get(entry.getKey()))) { changedSpecs.add(entry.getKey()); } } this.resourceGroupSpecs = resourceGroupSpecs; this.cpuQuotaPeriod.set(managerSpec.getCpuQuotaPeriod()); this.rootGroups.set(managerSpec.getRootGroups()); this.selectors.set(buildSelectors(managerSpec)); configureChangedGroups(changedSpecs); disableDeletedGroups(deletedSpecs); }
Source:
<code>public void testPartialIterating() throws Exception { FileSystemSecurityRealm securityRealm = new FileSystemSecurityRealm(getRootPath(), 1); ModifiableRealmIdentity identity1 = securityRealm.getRealmIdentityForUpdate("firstUser", null, null); identity1.create(); ModifiableRealmIdentity identity2 = securityRealm.getRealmIdentityForUpdate("secondUser", null, null); identity2.create(); <START> Iterator<ModifiableRealmIdentity> iterator = securityRealm.getRealmIdentityIterator(); <END> Assert.assertTrue(iterator.hasNext()); Assert.assertTrue(iterator.next().exists()); Assert.assertTrue(iterator instanceof Closeable); ((Closeable) iterator).close(); getRootPath(); }</code><technical_language>I thinking of test a try-with-resources style - current test shows a normal iterator needs cast close it. nice a test close is called end is reached, handling automatically silently work implements Closeable close end</technical_language>

Target:
public void testPartialIterating() throws Exception { FileSystemSecurityRealm securityRealm = createRealmWithTwoIdentities(); Iterator<ModifiableRealmIdentity> iterator = securityRealm.getRealmIdentityIterator(); Assert.assertTrue(iterator.hasNext()); Assert.assertTrue(iterator.next().exists()); Assert.assertTrue(iterator instanceof Closeable); ((Closeable) iterator).close(); getRootPath(); }
Source:
<code>private DataFetcher<String> getNameDataFetcher() { return environment -> Optional.of(environment.getSource()) .filter(Viewpoint.class::isInstance) .map(Viewpoint.class::cast) <START> .map(viewpoint -> { return Optional.ofNullable(viewpoint.getLabel()).orElse(viewpoint.getName()); <END> }) .orElse(null); }</code><technical_language>org.eclipse.sirius.business.api.query.IdentifiedElementQuery.getLabel()</technical_language>

Target:
private DataFetcher<String> getNameDataFetcher() { return environment -> Optional.of(environment.getSource()) .filter(Viewpoint.class::isInstance) .map(Viewpoint.class::cast) .map(IdentifiedElementQuery::new) .map(IdentifiedElementQuery::getLabel) .orElse(null); }
Source:
<code>public static Collection<Object[]> ipAddressParams() { return Arrays.asList(new Object[][] { { new HashSet<String>(), true }, { null, true }, <START> { new HashSet<>(Collections.singletonList("abc")), true }, <END> { new HashSet<>(Arrays.asList("abc", "xyz")), true }, { new HashSet<>(Collections.singletonList("abc-_sc")), true }, { new HashSet<>(Collections.singletonList("")), false }, { new HashSet<>(Collections.singletonList(" ")), false }, { new HashSet<>(Collections.singletonList("abc*")), false }, { new HashSet<>(Arrays.asList("aaa", "abc*")), false } }); }</code><technical_language>please Collections.singleton(...) lines 44, 46, 47, 48 49</technical_language>

Target:
public static Collection<Object[]> ipAddressParams() { return Arrays.asList(new Object[][] { { Collections.emptySet(), true }, { null, true }, { Collections.singleton("abc"), true }, { new HashSet<>(Arrays.asList("abc", "xyz")), true }, { Collections.singleton("abc-_sc"), true }, { Collections.singleton(""), false }, { Collections.singleton(" "), false }, { Collections.singleton("abc*"), false }, { new HashSet<>(Arrays.asList("aaa", "abc*")), false } }); }
Source:
<code>public void getAllConceptStateConversion_shouldTestGetAllConceptStateConversion() { List<ConceptStateConversion> conceptStateConversions = pws.getAllConceptStateConversions(); <START> int len = conceptStateConversions.size(); <END> assertEquals(len, 1); }</code><technical_language>len is unnecessary variable name</technical_language>

Target:
public void getAllConceptStateConversion_shouldTestGetAllConceptStateConversion() { List<ConceptStateConversion> conceptStateConversions = pws.getAllConceptStateConversions(); assertEquals(conceptStateConversions.size(), 1); }
Source:
<code>public String getMessage() { <START> return "Annotation " + Jack.getUserFriendlyFormatter().getName(typeDef) <END> + "should be annotated with @Retention(RetentionPolicy.SOURCE)"; }</code><technical_language>@</technical_language>

Target:
public String getMessage() { return "Annotation @" + Jack.getUserFriendlyFormatter().getName(typeDef) + "should be annotated with @Retention(RetentionPolicy.SOURCE)"; }
Source:
<code>public void startProcess() throws IOException { ProcessBuilder builder = new ProcessBuilder(buildCommand()); builder.redirectErrorStream(true); <START> Process process = builder.start(); <END> InputStream out = process.getInputStream(); OutputStream in = process.getOutputStream(); int SIZE = resolution.width * resolution.height * 3; int CHUNK_SIZE = SIZE / 20; int cursor = 0; byte[] chunk = new byte[CHUNK_SIZE]; ByteBuffer buffer = ByteBuffer.allocate(SIZE); while (isAlive(process)) { int no = out.available(); if (no >= chunk.length) { int n = out.read(chunk, 0, chunk.length); cursor += n; if (cursor < SIZE) { buffer.put(chunk, 0, n); } else { byte[] bgr = buffer.array(); image.setData(Raster.createRaster(image.getSampleModel(), new DataBufferByte(bgr, bgr.length), new Point())); buffer.clear(); cursor = 0; } } } }</code><technical_language>process is a local variable main thread accessing device this.process (when invoking process.destroy() in line 155. This NPE leave process semi-open (semi die eventually due parent process killed, destroyed properly)</technical_language>

Target:
public void startProcess() throws IOException { ProcessBuilder builder = new ProcessBuilder(buildCommand()); builder.redirectErrorStream(true); process = builder.start(); }
Source:
<code>public void testCache() throws Exception { <START> assertTrue(atsVersionCache.cache(teamWf, atsVersionCache.getVersion(teamWf)).getHumanReadableId().equals("WSXZA")); <END> }</code><technical_language>above. Also, this split multiple lines</technical_language>

Target:
public void testCache() throws Exception { IAtsVersion testVersion = atsVersionCache.cache(teamWf, atsVersionCache.getVersion(teamWf)); String hrid = testVersion.getHumanReadableId(); assertEquals("WSXZA", hrid); }
Source:
<code>public void setDerivedProvidedProducts(Collection<Product> derivedProvidedProducts) { this.derivedProvidedProductDtos = null; if (derivedProvidedProducts != null) { this.derivedProvidedProducts = new HashSet<>(derivedProvidedProducts); } <START> } <END></code><technical_language>here; gotta do a clear a null set</technical_language>

Target:
public void setDerivedProvidedProducts(Collection<Product> derivedProvidedProducts) { this.derivedProvidedProductDtos = null; if (derivedProvidedProducts != null) { this.derivedProvidedProducts = new HashSet<>(derivedProvidedProducts); } else { this.derivedProvidedProducts = new HashSet<>(); } }
Source:
<code>public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { try { if("true".equals(System.getProperty(PROP_TRUST_STORE_UPDATE_REQUIRED))) { setupTrustManager(); } trustManager.checkServerTrusted(x509Certificates, s); <START> } catch (NoSuchAlgorithmException e) { <END> throw new CertificateException("Certificate validation failed due to " + e.getCause()); } catch (KeyStoreException e) { throw new CertificateException("Certificate validation failed due to " + e.getCause()); } catch (Exception e) { throw new CertificateException("Certificate validation failed due to " + e.getCause()); } }</code><technical_language>catch (NoSuchAlgorithmException | KeyStoreException e) multiple catch blocks output them. catching 'Exception' finally throwing exception message, 1st catch blocks redundant here. BTW practice catch Exception, catch specific exceptions handle them. reason for catching Exception</technical_language>

Target:
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { try { if("true".equals(System.getProperty(PROP_TRUST_STORE_UPDATE_REQUIRED))) { setupTrustManager(); } trustManager.checkServerTrusted(x509Certificates, s); } catch (NoSuchAlgorithmException | KeyStoreException e) { throw new CertificateException("Certificate validation failed due to " + e.getCause(), e); } catch (Exception e) { throw new CertificateException("Certificate validation failed due to " + e.getCause(), e); } }
Source:
<code>public Gson create() { List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>(this.factories.size() + this.hierarchyFactories.size() + 3); factories.addAll(this.factories); Collections.reverse(factories); List<TypeAdapterFactory> hierarchyFactories = new ArrayList<TypeAdapterFactory>(this.hierarchyFactories.size()); <START> hierarchyFactories.addAll(this.hierarchyFactories); <END> Collections.reverse(hierarchyFactories); factories.addAll(hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); }</code><technical_language>pass this constructor directly</technical_language>

Target:
public Gson create() { List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>(this.factories.size() + this.hierarchyFactories.size() + 3); factories.addAll(this.factories); Collections.reverse(factories); List<TypeAdapterFactory> hierarchyFactories = new ArrayList<TypeAdapterFactory>(this.hierarchyFactories); Collections.reverse(hierarchyFactories); factories.addAll(hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); }
Source:
<code>public void process(String vreName, boolean isAssertion, Triple triple) { Entity entity = database.findOrCreateEntity(vreName, triple.getSubject()); if (isAssertion) { entity.addToCollection(database.findOrCreateCollection(vreName, triple.getObject())); <START> entity.removeFromCollection(database.getDefaultCollection(vreName)); <END> } else { entity.removeFromCollection(database.findOrCreateCollection(vreName, triple.getObject())); } }</code><technical_language>discussed in chat log error add new collection if entity a collection</technical_language>

Target:
public void process(String vreName, boolean isAssertion, Triple triple) { Entity entity = database.findOrCreateEntity(vreName, triple.getSubject()); if (isAssertion) { if (entity.isInKnownCollection()) { rdfImportSession.getErrorReporter().multipleRdfTypes(triple); } else { entity.addToCollection(database.findOrCreateCollection(vreName, triple.getObject())); } entity.removeFromCollection(database.getDefaultCollection(vreName)); } else { entity.removeFromCollection(database.findOrCreateCollection(vreName, triple.getObject())); } }
Source:
<code>public InMemoryReactiveClientRegistrationRepository(ClientRegistration... registrations) { <START> this.clientIdToClientRegistration = toUnmodifiableMapByRegistrationId(Stream.of(checkEmptyRegistrations(registrations, Assert::notEmpty))); <END> }</code><technical_language>this changed this(Arrays.asList(registrations))</technical_language>

Target:
public InMemoryReactiveClientRegistrationRepository(ClientRegistration... registrations) { this.delegate = new InMemoryClientRegistrationRepository(registrations); }