auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void assign(AssignableReplica assignableReplica) { if (!addToAssignmentRecord(assignableReplica, _currentAssignments)) { throw new HelixException(String .format("Resource %s already has a replica from partition %s on node %s", assignableReplica.getResourceName(), assignableReplica.getPartitionName(), getInstanceName())); } else { if (assignableReplica.isReplicaTopState()) { addToAssignmentRecord(assignableReplica, _currentTopStateAssignments); } assignableReplica.getCapacity().entrySet().stream().forEach( capacity -> updateCapacityAndUtilization(capacity.getKey(), capacity.getValue())); } }

Target:
void assign(AssignableReplica assignableReplica) { addToAssignmentRecord(assignableReplica); assignableReplica.getCapacity().entrySet().stream() .forEach(capacity -> updateCapacityAndUtilization(capacity.getKey(), capacity.getValue())); }
Source:
public MoveDiskCommand(MoveDiskParameters parameters) { super(parameters); diskValidator = new DiskValidator(getParameters().getDiskImageId()); vmValidator = new VmValidator(getParameters().getVmId()); sourceDomainValidator = new StorageDomainValidator(getParameters().getSourceDomainId(), getParameters().getStoragePoolId()); targetDomainValidator = new StorageDomainValidator(getParameters().getDestinationDomain(), getParameters().getStoragePoolId()); diskImage = DbFacade.getInstance().getDiskImageDAO().get(getParameters().getDiskImageId()); }

Target:
public MoveDiskCommand(MoveDiskParameters parameters) { super(parameters); }
Source:
private Promise<TemplateStore> loadTemplateStore() { Deferred<TemplateStore> deferred = new Deferred<>(); Promise<TemplateStore> promise = deferred.getPromise(); Executors.newSingleThreadExecutor().submit(()->{ TemplateStore templateStore = null; IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); boolean alreadyMigrated= store.getBoolean(CODE_TEMPLATES_MIGRATION_KEY); if (alreadyMigrated) templateStore= new ContributionTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY); else { templateStore= new CompatibilityTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY, getOldCodeTemplateStoreInstance()); store.setValue(CODE_TEMPLATES_MIGRATION_KEY, true); } try { templateStore.load(); } catch (IOException e) { JavaPlugin.log(e); } templateStore.startListeningForPreferenceChanges(); CompatibilityTemplateStore.pruneDuplicates(templateStore, true); deferred.resolve(templateStore); }); return promise.thenAccept((ts)->{ JavaManipulation.setCodeTemplateStore(ts); JavaManipulation.setCodeTemplateContextRegistry(getCodeTemplateContextRegistry()); }); }

Target:
public TemplateStore loadTemplateStore() { TemplateStore templateStore= null; IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); boolean alreadyMigrated= store.getBoolean(CODE_TEMPLATES_MIGRATION_KEY); if (alreadyMigrated) templateStore= new ContributionTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY); else { templateStore= new CompatibilityTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY, getOldCodeTemplateStoreInstance()); store.setValue(CODE_TEMPLATES_MIGRATION_KEY, true); } try { templateStore.load(); } catch (IOException e) { JavaPlugin.log(e); } templateStore.startListeningForPreferenceChanges(); CompatibilityTemplateStore.pruneDuplicates(templateStore, true); setTemplateStore(templateStore); return templateStore; }
Source:
IRuntimeClasspathEntry[] resolveClasspath0(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException { IJavaProject javaProject = JavaRuntime.getJavaProject(configuration); boolean isModularConfiguration = JavaRuntime.isModularConfiguration(configuration); int scope = configuration.hasAttribute(IJavaLaunchConfigurationConstants.ATTR_EXCLUDE_TEST_CODE) ? (configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_EXCLUDE_TEST_CODE, false) ? IClasspathManager.CLASSPATH_RUNTIME : IClasspathManager.CLASSPATH_TEST) : getArtifactScope(configuration); Set<IRuntimeClasspathEntry> all = new LinkedHashSet<IRuntimeClasspathEntry>(entries.length); for(IRuntimeClasspathEntry entry : entries) { if(entry.getType() == IRuntimeClasspathEntry.CONTAINER && MavenClasspathHelpers.isMaven2ClasspathContainer(entry.getPath())) { addMavenClasspathEntries(all, entry, configuration, scope, monitor, isModularConfiguration); } else if(entry.getType() == IRuntimeClasspathEntry.PROJECT) { if(javaProject.getPath().equals(entry.getPath())) { addProjectEntries(all, entry.getPath(), scope, THIS_PROJECT_CLASSIFIER, configuration, monitor, ModuleSupport.determineClasspathPropertyForMainProject(isModularConfiguration, javaProject)); } else { addStandardClasspathEntries(all, entry, configuration); } } else { addStandardClasspathEntries(all, entry, configuration); } } return all.toArray(new IRuntimeClasspathEntry[all.size()]); }

Target:
IRuntimeClasspathEntry[] resolveClasspath0(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException { IJavaProject javaProject = JavaRuntime.getJavaProject(configuration); boolean isModularConfiguration = JavaRuntime.isModularConfiguration(configuration); int scope = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_EXCLUDE_TEST_CODE, false) ? IClasspathManager.CLASSPATH_RUNTIME : IClasspathManager.CLASSPATH_TEST; Set<IRuntimeClasspathEntry> all = new LinkedHashSet<IRuntimeClasspathEntry>(entries.length); for(IRuntimeClasspathEntry entry : entries) { if(entry.getType() == IRuntimeClasspathEntry.CONTAINER && MavenClasspathHelpers.isMaven2ClasspathContainer(entry.getPath())) { addMavenClasspathEntries(all, entry, configuration, scope, monitor, isModularConfiguration); } else if(entry.getType() == IRuntimeClasspathEntry.PROJECT) { if(javaProject.getPath().equals(entry.getPath())) { addProjectEntries(all, entry.getPath(), scope, THIS_PROJECT_CLASSIFIER, configuration, monitor, ModuleSupport.determineClasspathPropertyForMainProject(isModularConfiguration, javaProject)); } else { addStandardClasspathEntries(all, entry, configuration); } } else { addStandardClasspathEntries(all, entry, configuration); } } return all.toArray(new IRuntimeClasspathEntry[all.size()]); }
Source:
public void testPhiroMoveMotorBackwardBrick() { int SET_SPEED = 30; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_phiro_motor_backward_action); List<Integer> spinnerValuesResourceIds = Arrays.asList( R.string.phiro_motor_right, R.string.phiro_motor_left, R.string.phiro_motor_both); checkIfValuesAvailableInSpinnerOnBrick(spinnerValuesResourceIds, R.id.brick_phiro_motor_backward_action_spinner, brickPosition); enterValueInFormulaTextFieldOnBrickAtPosition(SET_SPEED, R.id.brick_phiro_motor_backward_action_speed_edit_text, brickPosition); }

Target:
public void testPhiroMoveMotorBackwardBrick() { int setSpeed = 30; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_phiro_motor_backward_action); List<Integer> spinnerValuesResourceIds = Arrays.asList( R.string.phiro_motor_right, R.string.phiro_motor_left, R.string.phiro_motor_both); checkIfValuesAvailableInSpinnerOnBrick(spinnerValuesResourceIds, R.id.brick_phiro_motor_backward_action_spinner, brickPosition); enterValueInFormulaTextFieldOnBrickAtPosition(setSpeed, R.id.brick_phiro_motor_backward_action_speed_edit_text, brickPosition); }
Source:
public static boolean pathMatches(@Nullable String pathA, @Nullable String pathB) { if (pathA == null || pathA.isEmpty()) { return true; } if (pathB == null || pathB.isEmpty()) { return false; } if (pathA.matches("/") && pathB.isEmpty()) { return true; } boolean exactMatch = pathA.endsWith("/") ? false : true; List<String> pathListA = Arrays.asList(pathA.split("/")); List<String> pathListB = Arrays.asList(pathB.split("/")); long countA = pathA.chars().filter(ch -> ch =='/').count(); long countB = pathB.chars().filter(ch -> ch =='/').count(); if (pathListA.size() > pathListB.size() || countA > countB) return false; if (exactMatch && (pathListA.size() != pathListB.size() || countA != countB)) { return false; } StringTokenizer st = new StringTokenizer(pathA, "/"); int z = st.countTokens(); Iterator it1 = pathListA.iterator(); Iterator it2 = pathListB.iterator(); while (it1.hasNext() && it2.hasNext()) { String a = decodeString((String) it1.next()); String b = decodeString((String) it2.next()); if (!a.equals(b)) { return false; } } return true; }

Target:
public static boolean pathMatches(@Nullable String pathA, @Nullable String pathB) { if (pathA == null || pathA.isEmpty()) { return true; } if (pathB == null || pathB.isEmpty()) { return false; } if (pathA.matches("/") && pathB.isEmpty()) { return true; } boolean exactMatch = pathA.endsWith("/") ? false : true; List<String> pathListA = splitBySpec(pathA, '/'); List<String> pathListB = splitBySpec(pathB, '/'); if (pathListA.size() > pathListB.size()) return false; if (exactMatch && pathListA.size() != pathListB.size()) { return false; } if (!exactMatch) { pathListA.remove(pathListA.size() - 1); } Iterator it1 = pathListA.iterator(); Iterator it2 = pathListB.iterator(); while (it1.hasNext()) { String a = decodeString((String) it1.next()); String b = decodeString((String) it2.next()); if (!a.equals(b)) { return false; } } return true; }
Source:
public void execute() throws MojoExecutionException, MojoFailureException { copyContents(); try (FileInputStream configStream = new FileInputStream(new File(project.getBasedir(), configFile))) { Properties properties = new Properties(); properties.putAll(project.getProperties()); properties.putAll(System.getProperties()); properties.put("project.version", project.getVersion()); final FeaturePackBuild build = new FeaturePackBuildModelParser(new MapPropertyResolver(properties)).parse(configStream); File target = new File(buildName, serverName); FeaturePackBuilder.build(build, target, new MavenProjectArtifactResolver(project), new AetherArtifactFileResolver(repoSystem, repoSession, remoteRepos)); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public void execute() throws MojoExecutionException, MojoFailureException { if (!resourcesDir.isEmpty()) { switch (resourcesDir.charAt(0)) { case '/': case '\\': break; default: resourcesDir = "/" + resourcesDir; break; } } copyContents(); try (FileInputStream configStream = new FileInputStream(new File(configDir, configFile))) { Properties properties = new Properties(); properties.putAll(project.getProperties()); properties.putAll(System.getProperties()); properties.put("project.version", project.getVersion()); final FeaturePackBuild build = new FeaturePackBuildModelParser(new MapPropertyResolver(properties)).parse(configStream); File target = new File(buildName, serverName); FeaturePackBuilder.build(build, target, new MavenProjectArtifactResolver(project), new AetherArtifactFileResolver(repoSystem, repoSession, remoteRepos)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { Class<?> clazz = type.getRawType(); while (clazz != null && !Collection.class.isAssignableFrom(clazz) && !clazz.isArray()) { for (final Method method : clazz.getDeclaredMethods()) { if(method.isAnnotationPresent(EventListener.class)) { if(method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 1 && ApplicationEvent.class.isAssignableFrom(method.getParameterTypes()[0])) { encounter.register(new InjectionListener<Object>() { @Override public void afterInjection(Object injectee) { GuavaSubscriberProxy proxy = new GuavaSubscriberProxy(injectee, method); eventBus.register(proxy); } }); } else { LOG.warn("@EventListener {}.{} skipped. Methods must be public, void, and accept exactly" + " one argument extending com.netflix.governator.event.ApplicationEvent.", clazz.getName(), method.getName()); } } } clazz = clazz.getSuperclass(); } }

Target:
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { final Class<?> clazz = type.getRawType(); final List<Method> handlerMethods = getAllDeclaredHandlerMethods(clazz); if(!handlerMethods.isEmpty()) { encounter.register(new InjectionListener<Object>() { @Override public void afterInjection(Object injectee) { for (final Method handlerMethod : handlerMethods) { dispatcherProvider.get().registerListener(injectee, handlerMethod, (Class<? extends ApplicationEvent>) handlerMethod.getParameterTypes()[0]); } } }); } }
Source:
private FileAlterationObserver createObserver(String fileName) { File file = new File(fileName); if (file.isDirectory()) { return new FileAlterationObserver(file); } else { return new FileAlterationObserver(FilenameUtils.getFullPathNoEndSeparator(fileName), FileFilterUtils .nameFileFilter(FilenameUtils.getName(fileName))); } }

Target:
private FileAlterationObserver createObserver(String fileName) { final File file = new File(fileName); if (file.isDirectory()) { return new FileAlterationObserver(file); } else { return new FileAlterationObserver(FilenameUtils.getFullPathNoEndSeparator(fileName), FileFilterUtils .nameFileFilter(FilenameUtils.getName(fileName))); } }
Source:
@Override public Session create(CassandraStorage cassandra) { Closer closer = Closer.create(); try { Cluster cluster = closer.register(buildCluster(cassandra)); cluster.register(new QueryLogger.Builder().build()); Session session; if (cassandra.ensureSchema()) { session = closer.register(cluster.connect()); Schema.ensureExists(cassandra.keyspace(), cassandra.searchEnabled(), session); Schema.ensureExists(DEFAULT_KEYSPACE + "_udts", false, session); session.execute("USE " + cassandra.keyspace()); } else { session = cluster.connect(cassandra.keyspace()); } initializeUDTs(session); return session; } catch (RuntimeException e) { try { closer.close(); } catch (IOException ignored) { } throw e; } }

Target:
@Override public Session create(CassandraStorage cassandra) { Closer closer = Closer.create(); try { Cluster cluster = closer.register(buildCluster(cassandra)); cluster.register(new QueryLogger.Builder().build()); Session session; String keyspace = cassandra.keyspace(); if (cassandra.ensureSchema()) { session = closer.register(cluster.connect()); Schema.ensureExists(keyspace, cassandra.searchEnabled(), session); Schema.ensureExists(DEFAULT_KEYSPACE + "_udts", false, session); session.execute("USE " + keyspace); } else { LOG.debug("Skipping schema check on keyspace as ensureSchema was false", keyspace); session = cluster.connect(keyspace); } initializeUDTs(session); return session; } catch (RuntimeException e) { try { closer.close(); } catch (IOException ignored) { } throw e; } }
Source:
public void createsARefundTransactionEntityFromRefundEntity() throws Exception { long amount = 123L; String externalId = "someExternalId"; RefundEntity refundEntity = RefundEntityFixture.aValidRefundEntity() .withAmount(amount) .withExternalId(externalId) .withStatus(RefundStatus.REFUND_ERROR) .build(); RefundTransactionEntity transactionEntity = RefundTransactionEntity.from(refundEntity); assertThat(transactionEntity.getAmount(), is(amount)); assertThat(transactionEntity.getRefundExternalId(), is(externalId)); assertThat(transactionEntity.getUserExternalId(), is(refundEntity.getUserExternalId())); assertThat(transactionEntity.getStatus(), is(RefundStatus.REFUND_ERROR)); }

Target:
public void createsARefundTransactionEntityFromRefundEntity() throws Exception { long amount = 123L; String externalId = "someExternalId"; String refundReference = "refundReference"; RefundEntity refundEntity = RefundEntityFixture.aValidRefundEntity() .withAmount(amount) .withExternalId(externalId) .withStatus(RefundStatus.REFUND_ERROR) .withReference(refundReference) .build(); RefundTransactionEntity transactionEntity = RefundTransactionEntity.from(refundEntity); assertThat(transactionEntity.getAmount(), is(amount)); assertThat(transactionEntity.getRefundExternalId(), is(externalId)); assertThat(transactionEntity.getUserExternalId(), is(RefundEntityFixture.userExternalId)); assertThat(transactionEntity.getStatus(), is(RefundStatus.REFUND_ERROR)); }
Source:
protected Position handlePosition(Position position) { String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", Position.KEY_DRIVER_UNIQUE_ID + ",", true); Position last = getLastPosition(position.getDeviceId()); if (last != null) { for (String attribute : attributesString.split("[ ,]")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }

Target:
protected Position handlePosition(Position position) { String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", "", true); Position last = getLastPosition(position.getDeviceId()); if (attributesString.isEmpty()) { attributesString = Position.KEY_DRIVER_UNIQUE_ID; } else { attributesString += "," + Position.KEY_DRIVER_UNIQUE_ID; } if (last != null) { for (String attribute : attributesString.split("[ ,]")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }
Source:
public <T> Flowable<T> method(String name, Entity<?> entity, GenericType<T> responseType) { Flowable<T> flowable = Flowable.create(new FlowableOnSubscribe<T>() { @Override public void subscribe(FlowableEmitter<T> emitter) throws Exception { try { T response = syncInvoker.method(name, entity, responseType); emitter.onNext(response); emitter.onComplete(); } catch (Throwable e) { emitter.onError(e); } } }, BackpressureStrategy.DROP); if (sc == null) { return flowable; } return flowable.subscribeOn(sc).observeOn(sc); }

Target:
public <T> Flowable<T> method(String name, Entity<?> entity, GenericType<T> responseType) { return create(() -> syncInvoker.method(name, entity, responseType)); }
Source:
private void setRowStateOnDownload(ViewHolder row, DownloadEntry.DownloadedState state , View.OnClickListener listener) { switch (state) { case DOWNLOADING: row.bulkDownload.setIcon(Iconify.IconValue.fa_spinner); row.bulkDownload.setRotating(true); row.bulkDownload.setIconColorResource(R.color.edx_brand_primary_base); row.numOfVideoAndDownloadArea.setOnClickListener(listener); break; case DOWNLOADED: row.bulkDownload.setIcon(Iconify.IconValue.fa_check); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); row.numOfVideoAndDownloadArea.setOnClickListener(listener); break; default: row.bulkDownload.setIcon(Iconify.IconValue.fa_arrow_down); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); row.numOfVideoAndDownloadArea.setOnClickListener(listener); break; } }

Target:
private void setRowStateOnDownload(ViewHolder row, DownloadEntry.DownloadedState state , View.OnClickListener listener) { switch (state) { case DOWNLOADING: row.bulkDownload.setIcon(Iconify.IconValue.fa_spinner); row.bulkDownload.setRotating(true); row.bulkDownload.setIconColorResource(R.color.edx_brand_primary_base); break; case DOWNLOADED: row.bulkDownload.setIcon(Iconify.IconValue.fa_check); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); break; case ONLINE: row.bulkDownload.setIcon(Iconify.IconValue.fa_arrow_down); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); break; } row.numOfVideoAndDownloadArea.setOnClickListener(listener); }
Source:
protected IContributionItem[] getContributionItems() { Set<String> selectedTraceTypes = new HashSet<String>(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); ISelection selection = page.getSelection(); boolean forTraces = false, forExperiments = false; if (selection instanceof StructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof TmfTraceElement) { TmfTraceElement trace = (TmfTraceElement) element; selectedTraceTypes.add(trace.getTraceType()); forTraces = true; } else if (element instanceof TmfExperimentElement) { TmfExperimentElement trace = (TmfExperimentElement) element; selectedTraceTypes.add(trace.getTraceType()); forExperiments = true; } } } if (forTraces && forExperiments) { throw new RuntimeException(Messages.SelectElementTypeContributionItem_ElementSelection); } if (forExperiments) { return getExperimentContributionItems(selectedTraceTypes); } return getTraceContributionItems(selectedTraceTypes); }

Target:
protected IContributionItem[] getContributionItems() { Set<String> selectedTraceTypes = new HashSet<String>(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); ISelection selection = page.getSelection(); boolean forTraces = false, forExperiments = false; if (selection instanceof StructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof TmfTraceElement) { TmfTraceElement trace = (TmfTraceElement) element; selectedTraceTypes.add(trace.getTraceType()); forTraces = true; } else if (element instanceof TmfExperimentElement) { TmfExperimentElement trace = (TmfExperimentElement) element; selectedTraceTypes.add(trace.getTraceType()); forExperiments = true; } } } if (forTraces && forExperiments) { throw new RuntimeException("You must select only experiments or only traces to set the element type"); } if (forExperiments) { return getExperimentContributionItems(selectedTraceTypes); } return getTraceContributionItems(selectedTraceTypes); }
Source:
public Serializable retrieveConfigurationObjects(final ClientConnection conn, final DlmsDevice device, final RetrieveConfigurationObjectsRequest request) throws OsgpException, ProtocolAdapterException, SessionProviderException { return this.retrieveConfigurationObjectsCommandExecutor.execute(conn, device, null); }

Target:
public Serializable retrieveConfigurationObjects(final ClientConnection conn, final DlmsDevice device, final RetrieveConfigurationObjectsRequest request) throws ProtocolAdapterException { return this.retrieveConfigurationObjectsCommandExecutor.execute(conn, device, null); }
Source:
public static void fetchViewers(final String blogId, final int localTableBlogId, final int offset, final FetchViewersCallback callback) { com.wordpress.rest.RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (jsonObject != null && callback != null) { try { JSONArray jsonArray = jsonObject.getJSONArray("viewers"); List<Person> people = peopleListFromJSON(jsonArray, localTableBlogId, false, false, true); int numberOfUsers = jsonObject.optInt("found"); boolean isEndOfList = (people.size() + offset) >= numberOfUsers; callback.onSuccess(people, isEndOfList); } catch (JSONException e) { AppLog.e(T.API, "JSON exception occurred while parsing the response for " + "sites/%s/viewers: " + e); callback.onError(); } } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(T.API, volleyError); if (callback != null) { callback.onError(); } } }; int page = (int) Math.floor(offset / FETCH_LIMIT) + 1; Map<String, String> params = new HashMap<>(); params.put("number", Integer.toString(FETCH_LIMIT)); params.put("page", Integer.toString(page)); String path = String.format("sites/%s/viewers", blogId); WordPress.getRestClientUtilsV1_1().get(path, params, null, listener, errorListener); }

Target:
public static void fetchViewers(final String blogId, final int localTableBlogId, final int offset, final FetchViewersCallback callback) { com.wordpress.rest.RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (jsonObject != null && callback != null) { try { JSONArray jsonArray = jsonObject.getJSONArray("viewers"); List<Person> people = peopleListFromJSON(jsonArray, localTableBlogId, Person.PersonType.VIEWER); int numberOfUsers = jsonObject.optInt("found"); boolean isEndOfList = (people.size() + offset) >= numberOfUsers; callback.onSuccess(people, isEndOfList); } catch (JSONException e) { AppLog.e(T.API, "JSON exception occurred while parsing the response for " + "sites/%s/viewers: " + e); callback.onError(); } } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(T.API, volleyError); if (callback != null) { callback.onError(); } } }; int page = (offset / FETCH_LIMIT) + 1; Map<String, String> params = new HashMap<>(); params.put("number", Integer.toString(FETCH_LIMIT)); params.put("page", Integer.toString(page)); String path = String.format("sites/%s/viewers", blogId); WordPress.getRestClientUtilsV1_1().get(path, params, null, listener, errorListener); }
Source:
private synchronized void validate(String partitionKey, String rowKey) { if (this.frozen) { throw logger.logExceptionAsError( new IllegalStateException("Operations can't be modified once a batch is submitted.")); } if (!this.partitionKey.equals(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("All operations in a batch must share the same partition key.")); } if (rowKey == null || rowKey.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("The row key must not be null or empty.")); } if (rowKeys.contains(rowKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("Every operation in a batch must use a different row key.")); } else { rowKeys.add(rowKey); } }

Target:
private synchronized void validate(String partitionKey, String rowKey) { if (this.frozen) { throw logger.logExceptionAsError( new IllegalStateException("Operations can't be modified once a batch is submitted.")); } if (!this.partitionKey.equals(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("All operations in a batch must share the same partition key.")); } if (CoreUtils.isNullOrEmpty(rowKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("The row key must not be null or empty.")); } if (rowKeys.contains(rowKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("Every operation in a batch must use a different row key.")); } else { rowKeys.add(rowKey); } }
Source:
@Override public Response load(Uri uri, int networkPolicy) throws IOException { CacheControl cacheControl; if (NetworkPolicy.isOfflineOnly(networkPolicy)) { cacheControl = CacheControl.FORCE_CACHE; } else { CacheControl.Builder builder = new CacheControl.Builder(); if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) { builder.noCache(); } if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) { builder.noStore(); } cacheControl = builder.build(); } com.squareup.okhttp.Request.Builder requestBuilder = new com.squareup.okhttp.Request.Builder().cacheControl(cacheControl).url(uri.toString()); com.squareup.okhttp.Response response = client.newCall(requestBuilder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }

Target:
@Override public Response load(Uri uri, int networkPolicy) throws IOException { CacheControl cacheControl = null; if (networkPolicy != 0) { if (NetworkPolicy.isOfflineOnly(networkPolicy)) { cacheControl = CacheControl.FORCE_CACHE; } else { CacheControl.Builder builder = new CacheControl.Builder(); if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) { builder.noCache(); } if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) { builder.noStore(); } cacheControl = builder.build(); } } Request.Builder builder = new Request.Builder().url(uri.toString()); if (cacheControl != null) { builder.cacheControl(cacheControl); } com.squareup.okhttp.Response response = client.newCall(builder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }
Source:
public void setTextShouldNotAddClearKeysForTextInputWithEmptyText() { when(webElement.getAttribute("value")).thenReturn(""); textInput.setText("qwerty"); }

Target:
public void setTextShouldNotAddClearKeysForTextInputWithEmptyText() { when(webElement.getAttribute("value")).thenReturn(""); textInput.setText("qwerty"); verify(webElement).sendKeys("qwerty"); }
Source:
public void testInitRepository() { String directory = new File(trash, "test1").getPath(); try { InitCommand command = new InitCommand(); command.setDirectory(directory); Repository repository = command.call().getRepository(); assertNotNull(repository); } catch (Exception e) { fail(e.getMessage()); } }

Target:
public void testInitRepository() { try { File directory = createTempDirectory("testInitRepository"); InitCommand command = new InitCommand(); command.setDirectory(directory); Repository repository = command.call().getRepository(); assertNotNull(repository); } catch (Exception e) { fail(e.getMessage()); } }
Source:
public void testExecScriptScriptDirFlagIsRespected() throws Exception { final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi"; LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", true, null).orNull(); SshMachineLocation sm = lhp.obtain(); Map<String, Object> props = ImmutableMap.<String, Object>builder() .put(SshTool.PROP_SCRIPT_DIR.getName(), "/var/tmp") .build(); sm.execScript(props, "Test script directory execution", ImmutableList.of(command)); }

Target:
public void testExecScriptScriptDirFlagIsRespected() throws Exception { final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi"; LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", true, null).orNull(); SshMachineLocation sm = lhp.obtain(); Map<String, Object> props = ImmutableMap.<String, Object>builder() .put(SshTool.PROP_SCRIPT_DIR.getName(), "/var/tmp") .build(); int rc = sm.execScript(props, "Test script directory execution", ImmutableList.of(command)); assertEquals(rc, 0); }
Source:
@Override protected void executeQueryCommand() { try { executeQueryCommandChecked(); } catch (IOException ex) { throw new RuntimeException("Failed to create signed websocket proxy ticket.", ex); } }

Target:
@Override protected void executeQueryCommand() { try { executeQueryCommandChecked(); } catch (IOException ex) { throw new EngineException(EngineError.FailedToCreateWebsocketProxyTicket, new RuntimeException(ex)); } }
Source:
public IQ handleIQ(IQ iq) throws Exception { org.jivesoftware.smack.packet.IQ resultIQ = null; if (callControl == null) { logger.warn("Call controller not initialized"); } else { resultIQ = callControl.handleIQ(IQUtils.convert(iq)); } if (resultIQ != null) return IQUtils.convert(resultIQ); return super.handleIQSet(iq); }

Target:
public IQ handleIQ(IQ iq) throws Exception { org.jivesoftware.smack.packet.IQ resultIQ = null; if (callControl == null) { logger.warn("Call controller not initialized"); IQ error = IQ.createResultIQ(iq); error.setError(PacketError.Condition.service_unavailable); return error; } else { resultIQ = callControl.handleIQ(IQUtils.convert(iq)); } if (resultIQ != null) return IQUtils.convert(resultIQ); return super.handleIQSet(iq); }
Source:
public BBContainer poll(OutputContainerFactory ocf) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Reader " + m_cursorId + " has been closed"); } assertions(); BBContainer retcont = null; PBDSegment segment = null; long firstSegmentId = peekFirstSegment().segmentId(); while (m_segmentId < firstSegmentId) m_segmentId++; long currSegmentId = m_segmentId; while (m_segments.containsKey(currSegmentId)) { PBDSegment s = m_segments.get(currSegmentId); if (!s.isOpenForReading(m_cursorId)) { s.openForRead(m_cursorId); } if (s.hasMoreEntries(m_cursorId)) { segment = s; retcont = segment.poll(m_cursorId, ocf); m_segmentId = currSegmentId; break; } currSegmentId++; } if (retcont == null) { return null; } decrementNumObjects(); assertions(); assert (retcont.b() != null); return wrapRetCont(segment, retcont); } }

Target:
public BBContainer poll(OutputContainerFactory ocf) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Reader " + m_cursorId + " has been closed"); } assertions(); moveToValidSegment(); PBDSegmentReader segmentReader = m_segment.getReader(m_cursorId); if (segmentReader == null) { segmentReader = m_segment.openForRead(m_cursorId); } long lastSegmentId = peekLastSegment().segmentId(); while (!segmentReader.hasMoreEntries()) { if (m_segment.segmentId() == lastSegmentId) { return null; } segmentReader.close(); m_segment = m_segments.higherEntry(m_segment.segmentId()).getValue(); segmentReader = m_segment.getReader(m_cursorId); if (segmentReader == null) segmentReader = m_segment.openForRead(m_cursorId); } BBContainer retcont = segmentReader.poll(ocf); m_numRead++; assertions(); assert (retcont.b() != null); return wrapRetCont(m_segment, retcont); } }
Source:
public List<IAtsConfigObject> getInsertionFeatures(@PathParam("programUuid") long programUuid, @PathParam("insertionUuid") long insertionUuid) throws Exception { ArtifactReadable insertion = atsServer.getQuery().andUuid(insertionUuid).getResults().getExactlyOne(); if (!insertion.getArtifactType().equals(AtsArtifactTypes.Insertion)) { throw new OseeCoreException("Given uuid not insertion type"); } ResultSet<ArtifactReadable> results = insertion.getRelated(AtsRelationTypes.InsertionToInsertionFeature_InsertionFeature); List<IAtsConfigObject> insertionFeatures = new LinkedList<IAtsConfigObject>(); for (ArtifactReadable insertionFeature : results) { insertionFeatures.add(atsServer.getConfigItemFactory().getInsertionFeature(insertionFeature)); } return insertionFeatures; }

Target:
public Response getInsertionFeatures(@PathParam("programUuid") long programUuid, @PathParam("insertionUuid") long insertionUuid) throws Exception { ArtifactReadable insertion = atsServer.getArtifactByUuid(insertionUuid); if (insertion == null) { throw new OseeCoreException("Given insertion uuid not found"); } if (!insertion.getArtifactType().equals(AtsArtifactTypes.Insertion)) { throw new OseeCoreException("Given uuid not insertion type"); } ResultSet<ArtifactReadable> results = insertion.getRelated(AtsRelationTypes.InsertionToInsertionFeature_InsertionFeature); List<IAtsConfigObject> insertionFeatures = new LinkedList<IAtsConfigObject>(); for (ArtifactReadable insertionFeature : results) { insertionFeatures.add(atsServer.getConfigItemFactory().getInsertionFeature(insertionFeature)); } GenericEntity<List<IAtsConfigObject>> entity = new GenericEntity<List<IAtsConfigObject>>(insertionFeatures) { }; return Response.ok(entity).build(); }
Source:
public ModuleDefinitionService(WritableModuleRegistry registry, XDStreamParser parser, ModuleDependencyRepository dependencyRepository) { this.registry = registry; this.parser = parser; this.dependencyRepository = dependencyRepository; composedJobParser = new JobParser(); }

Target:
public ModuleDefinitionService(WritableModuleRegistry registry, XDStreamParser parser, ModuleDependencyRepository dependencyRepository) { this.registry = registry; this.parser = parser; this.dependencyRepository = dependencyRepository; this.composedJobParser = new JobParser(); }
Source:
protected void execute() { logger.debug("execute() method is called!"); for (WemoBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { logger.trace("Wemo switch '{}' state will be updated", itemName); try { String resp = wemoCall(itemName, "urn:Belkin:service:basicevent:1#GetBinaryState", IOUtils.toString(getClass().getResourceAsStream( "GetRequest.xml"))); String state = resp.replaceAll( "[\\d\\D]*<BinaryState>(.*)</BinaryState>[\\d\\D]*", "$1"); isOn = state.equals("1") ? true : false; logger.trace("{} state on = {}", itemName, isOn); if (state.equals("0")) { State itemState = OnOffType.valueOf("OFF"); logger.trace("Transformed state for item = {}", itemName, state); eventPublisher.postUpdate(itemName, itemState); } if (state.equals("1")) { State itemState = OnOffType.valueOf("ON"); logger.trace("Transformed state for item = {}", itemName, state); eventPublisher.postUpdate(itemName, itemState); } } catch (IOException e) { e.printStackTrace(); } } } }

Target:
protected void execute() { logger.debug("execute() method is called!"); for (WemoBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { logger.trace("Wemo switch '{}' state will be updated", itemName); try { String resp = wemoCall(itemName, "urn:Belkin:service:basicevent:1#GetBinaryState", IOUtils.toString(getClass().getResourceAsStream( "GetRequest.xml"))); String state = resp.replaceAll( "[\\d\\D]*<BinaryState>(.*)</BinaryState>[\\d\\D]*", "$1"); State itemState = state.equals("1") ? OnOffType.ON : OnOffType.OFF; eventPublisher.postUpdate(itemName, itemState); } catch (IOException e) { e.printStackTrace(); } } } }
Source:
void foo() { if (x == 0) { } else if (x == 1) { if(x == 2) { } else if(x == 3) { if (x == 5) { }else { } } } else { } if(x == 0) { }else if( x == 1) { } if(x==0) { } for(;;){ if(x == 10) { } if(x == 11) { } else if(x == 12){ } } }

Target:
void foo() { if (x == 0) { } else if (x == 1) { if(x == 2) { } else if(x == 3) { if (x == 5) { }else { } } } else { } if(x == 0) { }else if( x == 1) { } if(x==0) { } for(;;){ if(x == 10) { } if(x == 11) { }else if(x == 12){ } } if(x == 0) else if(x == 13) { } else { if(x == 14) { }else if(x == 15) { } } if(x ==16) { }else if(x == 17) { }else if(x == 18) { } if(x ==16) { }else if(x == 17) { }else if(x == 18) { }else if(x ==16) { }else if(x == 17) { }else if(x == 18) { }else if(x == 19){} }
Source:
private S3AFileSystem createUnguardedFS() throws Exception { S3AFileSystem testFS = getFileSystem(); Configuration config = new Configuration(testFS.getConf()); URI uri = testFS.getUri(); removeBaseAndBucketOverrides(uri.getHost(), config, S3_METADATA_STORE_IMPL); removeBaseAndBucketOverrides(uri.getHost(), config, METADATASTORE_AUTHORITATIVE); S3AFileSystem fs2 = new S3AFileSystem(); fs2.initialize(uri, config); return fs2; }

Target:
private S3AFileSystem createUnguardedFS() throws Exception { S3AFileSystem testFS = getFileSystem(); Configuration config = new Configuration(testFS.getConf()); URI uri = testFS.getUri(); removeBaseAndBucketOverrides(uri.getHost(), config, S3_METADATA_STORE_IMPL, METADATASTORE_AUTHORITATIVE, AUTHORITATIVE_PATH); S3AFileSystem fs2 = new S3AFileSystem(); fs2.initialize(uri, config); return fs2; }
Source:
public void validateTeams(List<StudentAttributes> studentList, String courseId) throws EntityDoesNotExistException, EnrollException { List<StudentAttributes> mergedList = getMergedList(studentList, courseId); if (mergedList.size() < 2) { return; } StringBuilder errorMessage = new StringBuilder(); errorMessage.append(getTeamInvalidityInfo(mergedList)); if (errorMessage.length() > 0) { throw new EnrollException(errorMessage.toString()); } }

Target:
public void validateTeams(List<StudentAttributes> studentList, String courseId) throws EntityDoesNotExistException, EnrollException { List<StudentAttributes> mergedList = getMergedList(studentList, courseId); if (mergedList.size() < 2) { return; } String errorMessage = getTeamInvalidityInfo(mergedList); if (errorMessage.length() > 0) { throw new EnrollException(errorMessage); } }
Source:
public MissingAmmoBin(int tonnage, EquipmentType et, int equipNum, boolean singleShot, boolean omniPodded, Campaign c) { super(tonnage, et, equipNum, c, 1.0, 1, omniPodded); this.oneShot = singleShot; if(null != name) { this.name += " Bin"; } }

Target:
public MissingAmmoBin(int tonnage, EquipmentType et, int equipNum, boolean singleShot, boolean omniPodded, Campaign c) { super(tonnage, et, equipNum, c, 1.0, 1.0, omniPodded); this.oneShot = singleShot; if(null != name) { this.name += " Bin"; } }
Source:
private Set<LocalizedDescription> transformDescriptions( Set<org.atlasapi.media.entity.simple.LocalizedDescription> simpleLocalizedDescriptions ) { return simpleLocalizedDescriptions.stream() .map(input -> { LocalizedDescription localizedDescription = new LocalizedDescription(); localizedDescription.setDescription(input.getDescription()); localizedDescription.setShortDescription(input.getDescription()); localizedDescription.setMediumDescription(input.getMediumDescription()); localizedDescription.setLongDescription(input.getLongDescription()); localizedDescription.setLocale( Strings.nullToEmpty(input.getLanguage()), Strings.nullToEmpty(input.getRegion()) ); return localizedDescription; }) .collect(MoreCollectors.toImmutableSet()); }

Target:
private Set<LocalizedDescription> transformDescriptions( Set<org.atlasapi.media.entity.simple.LocalizedDescription> simpleLocalizedDescriptions ) { return simpleLocalizedDescriptions.stream() .map(input -> { LocalizedDescription localizedDescription = new LocalizedDescription(); localizedDescription.setDescription(input.getDescription()); localizedDescription.setShortDescription(input.getDescription()); localizedDescription.setMediumDescription(input.getMediumDescription()); localizedDescription.setLongDescription(input.getLongDescription()); localizedDescription.setLocale(input.getLanguage(), input.getRegion()); return localizedDescription; }) .collect(MoreCollectors.toImmutableSet()); }
Source:
private String readFromAlias(String alias, List<String> excludeIdentifiers) { if (readIf("AS")) { alias = readAliasIdentifier(); } else if (currentTokenType == IDENTIFIER && !excludeIdentifiers.contains(currentToken)) { alias = readAliasIdentifier(); } return alias; }

Target:
private String readFromAlias(String alias, List<String> excludeIdentifiers) { if (readIf("AS")) { alias = readAliasIdentifier(); } else if (currentTokenType == IDENTIFIER && !isTokenInList(excludeIdentifiers)) { alias = readAliasIdentifier(); } return alias; }
Source:
private Set<Column> findOriginatingColumnsOfInputColumn(InputColumn<?> inputColumn) { final Set<Column> cachedOriginatingColumns = originatingColumnsOfInputColumnCache.get(inputColumn); if (cachedOriginatingColumns != null) { return cachedOriginatingColumns; } Set<Column> originatingColumns = new HashSet<>(); if (inputColumn != null) { if (inputColumn.isPhysicalColumn()) { originatingColumns.add(inputColumn.getPhysicalColumn()); } else { InputColumnSourceJob source = findInputColumnSource(inputColumn); originatingColumns.addAll(findOriginatingColumnsOfSource(source)); } } originatingColumnsOfInputColumnCache.put(inputColumn, originatingColumns); return originatingColumns; }

Target:
private Set<Column> findOriginatingColumnsOfInputColumn(InputColumn<?> inputColumn) { final Set<Column> cachedOriginatingColumns = originatingColumnsOfInputColumnCache.get(inputColumn); if (cachedOriginatingColumns != null) { return cachedOriginatingColumns; } final Set<Column> originatingColumns = new HashSet<>(); if (inputColumn != null) { if (inputColumn.isPhysicalColumn()) { originatingColumns.add(inputColumn.getPhysicalColumn()); } else { InputColumnSourceJob source = findInputColumnSource(inputColumn); originatingColumns.addAll(findOriginatingColumnsOfSource(source)); } } originatingColumnsOfInputColumnCache.put(inputColumn, originatingColumns); return originatingColumns; }
Source:
public Object convert(Class<? extends PersistableBusinessObject> businessObjectClass, RassPropertyDefinition propertyMapping, Object propertyValue) { List<RassXMLAwardPiCoPiEntry> rassAwardPiCoPiEntries = (List<RassXMLAwardPiCoPiEntry>) propertyValue; List<CGProjectDirector> projectDirectors = new ArrayList<>(); if (rassAwardPiCoPiEntries != null && rassAwardPiCoPiEntries.size() > 0) { for (RassXMLAwardPiCoPiEntry rassAwardPiCoPi : rassAwardPiCoPiEntries) { CGProjectDirector projectDirector = createNewProjectDirectorInstance(); Person projectDirectorPerson = personService.getPersonByPrincipalName(rassAwardPiCoPi.getProjectDirectorPrincipalName()); if (ObjectUtils.isNull(projectDirectorPerson)) { throw new RuntimeException("Cannot find person with principal name \"" + rassAwardPiCoPi.getProjectDirectorPrincipalName() + "\""); } if (!doesPersonHaveProjectDirectRole(projectDirectorPerson)) { LOG.info("convert, " + projectDirectorPerson.getPrincipalName() + " needs to be added to the project director role"); roleService.assignPrincipalToRole(projectDirectorPerson.getPrincipalId(), KFSConstants.CoreModuleNamespaces.KFS, KFSConstants.SysKimApiConstants.CONTRACTS_AND_GRANTS_PROJECT_DIRECTOR, new HashMap<String, String>()); } projectDirector.setPrincipalId(projectDirectorPerson.getPrincipalId()); ObjectPropertyUtils.setPropertyValue(projectDirector, projectDirectorPrimaryIndicatorPropertyName, getNullSafePrimaryDirectorFlag(rassAwardPiCoPi)); projectDirectors.add(projectDirector); } } return projectDirectors; }

Target:
public Object convert(Class<? extends PersistableBusinessObject> businessObjectClass, RassPropertyDefinition propertyMapping, Object propertyValue) { List<RassXMLAwardPiCoPiEntry> rassAwardPiCoPiEntries = (List<RassXMLAwardPiCoPiEntry>) propertyValue; List<CGProjectDirector> projectDirectors = new ArrayList<>(); if (rassAwardPiCoPiEntries != null && rassAwardPiCoPiEntries.size() > 0) { for (RassXMLAwardPiCoPiEntry rassAwardPiCoPi : rassAwardPiCoPiEntries) { CGProjectDirector projectDirector = buildProjectDirector(rassAwardPiCoPi); projectDirectors.add(projectDirector); } } return projectDirectors; }