auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static BigDecimal calculateExpression(ArrayDeque<Tokenizer.Token> expression) throws ArithmeticException { ArrayDeque<BigDecimal> stack = new ArrayDeque<>(); Iterator<Tokenizer.Token> iterator = expression.descendingIterator(); while (iterator.hasNext()) { Tokenizer.Token token = iterator.next(); BigDecimal operand2 = null; BigDecimal operand1 = null; switch (token.type) { case Tokenizer.Token.NUMBER_TOKEN: stack.push(token.number); break; case Tokenizer.Token.UNARY_PLUS_TOKEN: break; case Tokenizer.Token.UNARY_MINUS_TOKEN: stack.push(stack.pop().negate()); break; case Tokenizer.Token.SUM_TOKEN: operand2 = stack.pop(); operand1 = stack.pop(); stack.push(operand1.add(operand2)); break; case Tokenizer.Token.SUBTRACT_TOKEN: operand2 = stack.pop(); operand1 = stack.pop(); stack.push(operand1.subtract(operand2)); break; case Tokenizer.Token.MULTIPLY_TOKEN: operand2 = stack.pop(); operand1 = stack.pop(); stack.push(operand1.multiply(operand2)); break; case Tokenizer.Token.DIVIDE_TOKEN: operand2 = stack.pop(); operand1 = stack.pop(); stack.push(operand1.divide(operand2)); break; case Tokenizer.Token.EXP_TOKEN: operand2 = stack.pop(); operand1 = stack.pop(); stack.push(operand1.pow(operand2.intValueExact())); break; } } return stack.pop(); }

Target:
public static Result<BigDecimal> calculateExpression(ArrayDeque<Tokenizer.Token> expression) { try { return calculateExpressionThrowing(expression); } catch (ArithmeticException e) { return Result.arithmeticalError(); } }
Source:
public void run() { try { String hostName = System.getProperty("fake.host"); if (hostName == null) { hostName = "localhost"; } log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor; if (!encrypted) { reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); } else { reactor = ReactorFactory.getReactor(new FakeVDSMSSLProvider(System.getProperty("fake.keystore"), System.getProperty("fake.truststore"), "changeit", null), ReactorType.STOMP); } final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @Override public void onMessageReceived(byte[] message) { MessageHandler handler = new MessageHandler(client, message); service.submit(handler); } }); } }); listener = futureListener.get(TIMEOUT, TimeUnit.MILLISECONDS); } catch (Exception e) { log.error("Failure to start json server socket", e); } }

Target:
public void run() { try { String hostName = appConfig.getJsonHost(); if (appConfig.getJsonHost() == null) { hostName = "localhost"; } log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor; if (!encrypted) { reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); } else { reactor = ReactorFactory.getReactor(new FakeVDSMSSLProvider(System.getProperty("fake.keystore"), System.getProperty("fake.truststore"), "changeit", null), ReactorType.STOMP); } final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @Override public void onMessageReceived(byte[] message) { MessageHandler handler = new MessageHandler(client, message); service.submit(handler); } }); } }); listener = futureListener.get(TIMEOUT, TimeUnit.MILLISECONDS); log.info("vdsmfake initialized"); } catch (Exception e) { log.error("Failure to start json server socket", e); } }
Source:
public Response add(Host host) { validateEnums(Host.class, host); validateParameters(host, "name", "address", "rootPassword"); VdsStatic staticHost = getMapper(Host.class, VdsStatic.class).map(host, null); staticHost.setVdsGroupId(getClusterId(host)); AddVdsActionParameters addParams = new AddVdsActionParameters(staticHost, host.getRootPassword()); if (host.isSetOverrideIptables()) { addParams.setOverrideFirewall(host.isOverrideIptables()); } if (host.isSetRebootAfterInstallation()) { addParams.setRebootAfterInstallation(host.isRebootAfterInstallation()); } if (host.isSetSsh()) { if (host.getSsh().isSetUser()) { if (host.getSsh().getUser().isSetPassword()) { addParams.setRootPassword(host.getSsh().getUser().getPassword()); } } if (host.getSsh().isSetPort()) { addParams.getvds().setSshPort(host.getSsh().getPort().intValue()); } if (host.getSsh().isSetFingerprint()) { addParams.getvds().setSshKeyFingerprint(host.getSsh().getFingerprint()); } if (host.getSsh().isSetAuthenticationType()) { addParams.setAuthMethod(mapAuth(host.getSsh().getAuthenticationType().getAuthenticationType())); } } return performCreate(VdcActionType.AddVds, addParams, new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class)); }

Target:
public Response add(Host host) { validateEnums(Host.class, host); validateParameters(host, "name", "address", "rootPassword"); VdsStatic staticHost = getMapper(Host.class, VdsStatic.class).map(host, null); staticHost.setVdsGroupId(getClusterId(host)); AddVdsActionParameters addParams = new AddVdsActionParameters(staticHost, host.getRootPassword()); if (host.isSetOverrideIptables()) { addParams.setOverrideFirewall(host.isOverrideIptables()); } if (host.isSetRebootAfterInstallation()) { addParams.setRebootAfterInstallation(host.isRebootAfterInstallation()); } if (host.isSetSsh()) { if (host.getSsh().isSetUser()) { if (host.getSsh().getUser().isSetPassword()) { addParams.setRootPassword(host.getSsh().getUser().getPassword()); } } if (host.getSsh().isSetPort()) { addParams.getvds().setSshPort(host.getSsh().getPort().intValue()); } if (host.getSsh().isSetFingerprint()) { addParams.getvds().setSshKeyFingerprint(host.getSsh().getFingerprint()); } if (host.getSsh().isSetAuthenticationMethod()) { AuthenticationMethod m = getMapper(String.class, AuthenticationMethod.class). map(host.getSsh().getAuthenticationMethod(), null); if (m != null) { addParams.setAuthMethod( getMapper(AuthenticationMethod.class, org.ovirt.engine.core.common.action.VdsOperationActionParameters.AuthenticationMethod.class).map(m, null)); } } } return performCreate(VdcActionType.AddVds, addParams, new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class)); }
Source:
void removeCurCompactionLog() { synchronized (compactionLogLock) { if (compactionLogChannel != null) { if (!compactionLogChannel.getLogFile().delete()) { LOG.warn("Could not delete compaction log file {}", compactionLogChannel.getLogFile()); } try { compactionLogChannel.close(); } catch (IOException e) { LOG.error("Failed to close file channel for compaction log {}: {}", compactionLogChannel.getLogId(), e.getMessage()); } compactionLogChannel = null; } } }

Target:
void removeCurCompactionLog() { synchronized (compactionLogLock) { if (compactionLogChannel != null) { if (!compactionLogChannel.getLogFile().delete()) { LOG.warn("Could not delete compaction log file {}", compactionLogChannel.getLogFile()); } try { compactionLogChannel.close(); } catch (IOException e) { LOG.error("Failed to close file channel for compaction log {}", compactionLogChannel.getLogId(), e); } compactionLogChannel = null; } } }
Source:
public String toString() { String result = ""; for (Id id : internalMap().keySet()) { result = result + ", " + "{" + id + "; " + internalMap().get(id).syncState() + "}"; } return result.substring(2); }

Target:
public String toString() { String result = ""; String delimiter = ", "; for (Id id : internalMap().keySet()) { result = result + delimiter + "{" + id + "; " + internalMap().get(id).syncState() + "}"; } return result.substring(delimiter.length()); }
Source:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); startSyncFolderOperation(directory, false); MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); if (DisplayUtils.isGridView(directory, getStorageManager())){ switchToGridView(); } else { switchToListView(); } }

Target:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); startSyncFolderOperation(directory, false); }
Source:
public void visitAnyBlock(Block block) { this.block = block; if (block instanceof ThenBlock) return; DeepBlockRewriter deep = new DeepBlockRewriter(this); deep.visit(block); methodHasCondition |= deep.isDeepConditionFound() || deep.isGroupConditionFound(); }

Target:
public void visitAnyBlock(Block block) { this.block = block; if (block instanceof ThenBlock) return; DeepBlockRewriter deep = new DeepBlockRewriter(this); deep.visit(block); methodHasCondition |= deep.isConditionFound(); methodHasDeepNonGroupedCondition |= deep.isDeepNonGroupedConditionFound(); }
Source:
protected Node visitShowTables(ShowTables showTables, Void context) { CatalogSchemaName schema = createCatalogSchemaName(session, showTables, showTables.getSchema()); accessControl.checkCanShowTablesMetadata(session.getRequiredTransactionId(), session.getIdentity(), schema); if (!metadata.catalogExists(session, schema.getCatalogName())) { throw new SemanticException(MISSING_CATALOG, showTables, "Catalog '%s' does not exist", schema.getCatalogName()); } if (!metadata.schemaExists(session, schema)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schema.getSchemaName()); } Expression predicate = equal(identifier("table_schema"), new StringLiteral(schema.getSchemaName())); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate; Optional<String> escape = showTables.getEscape(); if (escape.isPresent()) { likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), new StringLiteral(escape.get())); } else { likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), null); } predicate = logicalAnd(predicate, likePredicate); } return simpleQuery( selectList(aliasedName("table_name", "Table")), from(schema.getCatalogName(), TABLE_TABLES), predicate, ordering(ascending("table_name"))); }

Target:
protected Node visitShowTables(ShowTables showTables, Void context) { CatalogSchemaName schema = createCatalogSchemaName(session, showTables, showTables.getSchema()); accessControl.checkCanShowTablesMetadata(session.getRequiredTransactionId(), session.getIdentity(), schema); if (!metadata.catalogExists(session, schema.getCatalogName())) { throw new SemanticException(MISSING_CATALOG, showTables, "Catalog '%s' does not exist", schema.getCatalogName()); } if (!metadata.schemaExists(session, schema)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schema.getSchemaName()); } Expression predicate = equal(identifier("table_schema"), new StringLiteral(schema.getSchemaName())); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), null); predicate = logicalAnd(predicate, likePredicate); } return simpleQuery( selectList(aliasedName("table_name", "Table")), from(schema.getCatalogName(), TABLE_TABLES), predicate, ordering(ascending("table_name"))); }
Source:
private void disablePluginFormItems(NodeSourceConfiguration nodeSourceConfiguration) { PluginDescriptor focusedInfrastructurePlugin = nodeSourceConfiguration.getInfrastructurePluginDescriptor(); PluginDescriptor focusedPolicyPlugin = nodeSourceConfiguration.getPolicyPluginDescriptor(); List<String> dynamicParametersName = Stream.concat(getDynamicParametersName(focusedInfrastructurePlugin), getDynamicParametersName(focusedPolicyPlugin)) .collect(Collectors.toList()); for (FormItem formItem : this.nodeSourcePluginsForm.getFields()) { if (isNotDynamic(formItem, dynamicParametersName) && isFocusedPluginItem(focusedInfrastructurePlugin, focusedPolicyPlugin, formItem)) { formItem.disable(); } } }

Target:
private void disablePluginFormItems(NodeSourceConfiguration nodeSourceConfiguration) { PluginDescriptor focusedInfrastructurePlugin = nodeSourceConfiguration.getInfrastructurePluginDescriptor(); PluginDescriptor focusedPolicyPlugin = nodeSourceConfiguration.getPolicyPluginDescriptor(); List<String> dynamicParametersName = Stream.concat(getDynamicParametersName(focusedInfrastructurePlugin), getDynamicParametersName(focusedPolicyPlugin)) .collect(Collectors.toList()); Arrays.stream(this.nodeSourcePluginsForm.getFields()) .filter(formItem -> isNotDynamic(formItem.getName(), dynamicParametersName) && isFocusedPluginItem(focusedInfrastructurePlugin, focusedPolicyPlugin, formItem)) .forEach(FormItem::disable); }
Source:
protected void confirmAndWaitForRefresh() { waitExplicitly(1000); confirmDialog(); waitUntil(stalenessOf(getDriver().findElement(By.tagName("html")))); }

Target:
protected void confirmAndWaitForRefresh() { waitUntil(visibilityOf(getDriver().findElement(By.id("ok")))); confirmDialog(); waitUntil(stalenessOf(getDriver().findElement(By.tagName("html")))); }
Source:
public void testTwoCompensationHandlers() throws Exception { ParticipantCompletionCoordinatorRules.setParticipantCount(6); MyCompensationHandler.expectedData = "blah"; MyConfirmationHandler.expectedData = "blah"; getBAControler().beginBusinessActivity(); service.doWork("blah"); service.doWork("blah"); getBAControler().cancelBusinessActivity(); Assert.assertEquals(true, MyCompensationHandler.dataAvailable); Assert.assertEquals(false, MyConfirmationHandler.dataAvailable); }

Target:
public void testTwoCompensationHandlers() throws Exception { ParticipantCompletionCoordinatorRules.setParticipantCount(6); MyCompensationHandler.expectedData = "blah"; MyConfirmationHandler.expectedData = "blah"; getBAControler().beginBusinessActivity(); service.doWork("blah"); service.doWork("blah"); getBAControler().cancelBusinessActivity(); Assert.assertTrue(MyCompensationHandler.dataAvailable); Assert.assertFalse(MyConfirmationHandler.dataAvailable); }
Source:
public boolean playersDead() { if(!this.isRunning()) { return false; } boolean b = true; for(Player p : this.players) { if (p.playerAlive()) { b = false; } } return b; }

Target:
public boolean playersDead() { if (!this.isRunning()) { return false; } for (Player p : this.players) { if (p.hasLives()) { return false; } } return true; }
Source:
public void write(final Interval interval) throws IOException { out.write(interval.getContig()); out.write(TAB); out.write(Integer.toString(interval.getStart())); out.write(TAB); out.write(Integer.toString(interval.getEnd())); out.write(TAB); out.write(interval.isPositiveStrand() ? '+' : '-'); out.write(TAB); out.write(interval.getName() != null ? interval.getName() : "."); out.newLine(); }

Target:
public void write(final Interval interval) throws IOException { out.write(interval.getContig()); out.write(TAB); out.write(Integer.toString(interval.getStart())); out.write(TAB); out.write(Integer.toString(interval.getEnd())); out.write(TAB); out.write(interval.getStrand().encode()); out.write(TAB); out.write(interval.getName() != null ? interval.getName() : "."); out.newLine(); }
Source:
protected void init() { super.init(); getApplicationSettings().setUploadProgressUpdatesEnabled(true); getResourceSettings().setThrowExceptionOnMissingResource(false); getRequestCycleSettings().addResponseFilter(new AjaxServerAndClientTimeFilter()); getDebugSettings().setAjaxDebugModeEnabled(true); setHeaderResponseDecorator(response -> { return new ResourceAggregator(new JavaScriptDeferHeaderResponse(response)); }); getComponentInitializationListeners().add(new IComponentInitializationListener() { @Override public void onInitialize(Component component) { if (component instanceof WebPage) { component.add(new AjaxNewWindowNotifyingBehavior()); } } }); mountPage("autocomplete", AutoCompletePage.class); mountPage("choice", ChoicePage.class); mountPage("clock", ClockPage.class); mountPage("editable-label", EditableLabelPage.class); mountPage("effects", EffectsPage.class); mountPage("form", FormPage.class); mountPage("guest-book", GuestBook.class); mountPage("lazy-loading", LazyLoadingPage.class); mountPage("links", LinksPage.class); mountPage("modal-window", ModalWindowPage.class); mountPage("on-change-ajax-behavior", OnChangeAjaxBehaviorPage.class); mountPage("pageables", PageablesPage.class); mountPage("ratings", RatingsPage.class); mountPage("tabbed-panel", TabbedPanelPage.class); mountPage("todo-list", TodoList.class); mountPage("world-clock", WorldClockPage.class); mountPage("upload", FileUploadPage.class); mountPage("download", AjaxDownloadPage.class); }

Target:
protected void init() { super.init(); getApplicationSettings().setUploadProgressUpdatesEnabled(true); getResourceSettings().setThrowExceptionOnMissingResource(false); getRequestCycleSettings().addResponseFilter(new AjaxServerAndClientTimeFilter()); getDebugSettings().setAjaxDebugModeEnabled(true); setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response))); getComponentInitializationListeners().add(new IComponentInitializationListener() { @Override public void onInitialize(Component component) { if (component instanceof WebPage) { component.add(new AjaxNewWindowNotifyingBehavior()); } } }); mountPage("autocomplete", AutoCompletePage.class); mountPage("choice", ChoicePage.class); mountPage("clock", ClockPage.class); mountPage("editable-label", EditableLabelPage.class); mountPage("effects", EffectsPage.class); mountPage("form", FormPage.class); mountPage("guest-book", GuestBook.class); mountPage("lazy-loading", LazyLoadingPage.class); mountPage("links", LinksPage.class); mountPage("modal-window", ModalWindowPage.class); mountPage("on-change-ajax-behavior", OnChangeAjaxBehaviorPage.class); mountPage("pageables", PageablesPage.class); mountPage("ratings", RatingsPage.class); mountPage("tabbed-panel", TabbedPanelPage.class); mountPage("todo-list", TodoList.class); mountPage("world-clock", WorldClockPage.class); mountPage("upload", FileUploadPage.class); mountPage("download", AjaxDownloadPage.class); }
Source:
public void testTask() throws Exception { ScriptingManager scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); ScriptingTest.loadScript(scriptingManager, TEST_SCRIPT); String result = (String) taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a")).get(); assertEquals("a", result); }

Target:
public void testTask() throws Exception { ScriptingManager scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); loadScript(scriptingManager, TEST_SCRIPT); String result = (String) taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a")).get(); assertEquals("a", result); }
Source:
protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getStorageType(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getConnection(), null)) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && StringUtils.isEmpty(conn.getVfsType())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getIqn())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getPort())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); if (!validate(validateVolumeIdAndupdatePath(conn)) && !validate(validator.canVDSConnectToGlusterfs(getVds()))) { return false; } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }

Target:
protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getStorageType(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getConnection(), null)) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && StringUtils.isEmpty(conn.getVfsType())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getIqn())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getPort())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); if (!validate(validateVolumeIdAndUpdatePath(conn)) && !validate(validator.canVDSConnectToGlusterfs(getVds()))) { return false; } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }
Source:
private static String getTemporaryDir(ITmfTrace trace) { String name = trace.getName(); String path = trace.getPath(); if (path == null) { String prefix = FilenameUtils.getPrefix(trace.getPath()); if (prefix != null) { name = trace.getPath().substring(prefix.length()); } } String pathName = getTemporaryDirPath() + File.separator + name + File.separator; File dir = new File(pathName); if (!dir.exists()) { dir.mkdirs(); } return pathName; }

Target:
private static String getTemporaryDir(ITmfTrace trace) { String name = trace.getName(); String path = trace.getPath(); if (path != null) { String prefix = FilenameUtils.getPrefix(trace.getPath()); if (prefix != null) { name = trace.getPath().substring(prefix.length()); } } String pathName = getTemporaryDirPath() + File.separator + name + File.separator; File dir = new File(pathName); if (!dir.exists()) { dir.mkdirs(); } return pathName; }
Source:
public void waitForReplication() { try { allPushTasksFinished.await(); } catch (InterruptedException e) { log.error("It is interrupted while waiting replication to be completed");; } }

Target:
public void waitForReplication() throws InterruptedException { allPushTasksFinished.await(); }
Source:
private static ManifestElement[] getGenericCapabilities(Dictionary<String, String> manifest, String[][] genericAliases) throws BundleException { ManifestElement[] genericCapabilities = ManifestElement.parseHeader(GENERIC_CAPABILITY, manifest.get(GENERIC_CAPABILITY)); List<ManifestElement> aliasList = null; if (genericAliases.length > 0) { aliasList = new ArrayList<>(genericCapabilities == null ? 0 : genericCapabilities.length); for (String[] genericAliase : genericAliases) { ManifestElement[] aliasCapabilities = ManifestElement.parseHeader(genericAliase[0], manifest.get(genericAliase[0])); if (aliasCapabilities == null) continue; for (ManifestElement aliasCapabilitie : aliasCapabilities) { StringBuffer strBuf = new StringBuffer(); strBuf.append(aliasCapabilitie.getValue()).append(':').append(genericAliase[2]); for (Enumeration<String> keys = aliasCapabilitie.getKeys(); keys != null && keys.hasMoreElements();) { String key = keys.nextElement(); strBuf.append("; ").append(key).append("=\"").append(aliasCapabilitie.getAttribute(key)).append("\""); } ManifestElement[] withTypes = ManifestElement.parseHeader(genericAliase[0], strBuf.toString()); aliasList.add(withTypes[0]); } } } if (aliasList == null || aliasList.size() == 0) return genericCapabilities; if (genericCapabilities != null) for (ManifestElement genericCapabilitie : genericCapabilities) { aliasList.add(genericCapabilitie); } return aliasList.toArray(new ManifestElement[aliasList.size()]); }

Target:
private static ManifestElement[] getGenericCapabilities(Dictionary<String, String> manifest, String[][] genericAliases) throws BundleException { ManifestElement[] genericCapabilities = ManifestElement.parseHeader(GENERIC_CAPABILITY, manifest.get(GENERIC_CAPABILITY)); List<ManifestElement> aliasList = null; if (genericAliases.length > 0) { aliasList = new ArrayList<>(genericCapabilities == null ? 0 : genericCapabilities.length); for (String[] genericAlias : genericAliases) { ManifestElement[] aliasCapabilities = ManifestElement.parseHeader(genericAlias[0], manifest.get(genericAlias[0])); if (aliasCapabilities == null) continue; for (ManifestElement aliasCapability : aliasCapabilities) { StringBuffer strBuf = new StringBuffer(); strBuf.append(aliasCapability.getValue()).append(':').append(genericAlias[2]); for (Enumeration<String> keys = aliasCapability.getKeys(); keys != null && keys.hasMoreElements();) { String key = keys.nextElement(); strBuf.append("; ").append(key).append("=\"").append(aliasCapability.getAttribute(key)).append("\""); } ManifestElement[] withTypes = ManifestElement.parseHeader(genericAlias[0], strBuf.toString()); aliasList.add(withTypes[0]); } } } if (aliasList == null || aliasList.size() == 0) return genericCapabilities; if (genericCapabilities != null) for (ManifestElement genericCapability : genericCapabilities) { aliasList.add(genericCapability); } return aliasList.toArray(new ManifestElement[aliasList.size()]); }
Source:
private static FacesMessage msgForSelectEdit(String ofType) { return HelperUtil.getMsgWarn(MessageFormat.format("Select a {0} for edit.", ofType.toLowerCase())); }

Target:
private static FacesMessage msgForSelectEdit(String ofType) { return HelperUtil.getMsgWarn(MessageFormat.format("Select {0} for edit.", ofType.toLowerCase())); }
Source:
GoCommand(ArtifactoryBuildInfoClientBuilder clientBuilder, Path path, Log logger) throws IOException { this.clientBuilder = clientBuilder; this.logger = logger; this.path = path; }

Target:
GoCommand(ArtifactoryBuildInfoClientBuilder clientBuilder, Path path, Log logger) { this.clientBuilder = clientBuilder; this.logger = logger; this.path = path; }
Source:
private DMSVariableType addDataTypeVariableTypeIfNecessary(final VariableTypeList variableTypeList, final String programUUID) throws MiddlewareException { DMSVariableType variableType = variableTypeList.findById(TermId.DATASET_TYPE); if (variableType == null) { variableType = new DMSVariableType("DATASET_TYPE", "Dataset type", this.getStandardVariable(TermId.DATASET_TYPE, programUUID), 3); variableType.setRole(PhenotypicType.DATASET); variableTypeList.makeRoom(3); variableTypeList.add(variableType); } return variableType; }

Target:
private DMSVariableType addDataTypeVariableTypeIfNecessary(final VariableTypeList variableTypeList, final String programUUID) throws MiddlewareQueryException { DMSVariableType variableType = variableTypeList.findById(TermId.DATASET_TYPE); if (variableType == null) { variableType = new DMSVariableType("DATASET_TYPE", "Dataset type", this.getStandardVariable(TermId.DATASET_TYPE, programUUID), 3); variableType.setRole(PhenotypicType.DATASET); variableTypeList.makeRoom(3); variableTypeList.add(variableType); } return variableType; }
Source:
protected ActionResult execute() throws EntityDoesNotExistException { new GateKeeper().verifyAdminPrivileges(account); String instructorGoogleId = this.getRequestParamValue("googleId"); Map<String, ArrayList<InstructorAttributes>> instructorCoursesTable = new HashMap<String, ArrayList<InstructorAttributes>>(); Map<String, AccountAttributes> instructorAccountsTable = new HashMap<String, AccountAttributes>(); if (instructorGoogleId == null) { instructorGoogleId = ""; } List<InstructorAttributes> instructorsList = logic.getInstructorsForGoogleId(instructorGoogleId); AccountAttributes instructorAccount = logic.getAccount(instructorGoogleId); boolean isToShowAll = this.getRequestParamAsBoolean("all"); boolean isAccountExisting = instructorAccount != null && !instructorsList.isEmpty(); if (isAccountExisting) { instructorAccountsTable.put(instructorAccount.googleId, instructorAccount); for(InstructorAttributes instructor : instructorsList){ ArrayList<InstructorAttributes> courseList = instructorCoursesTable.get(instructor.googleId); if (courseList == null){ courseList = new ArrayList<InstructorAttributes>(); instructorCoursesTable.put(instructor.googleId, courseList); } courseList.add(instructor); } } AdminAccountManagementPageData data = new AdminAccountManagementPageData(account, instructorAccountsTable, instructorCoursesTable, isToShowAll); statusToAdmin = "Admin Account Management Page Load<br>" + "<span class=\"bold\">Total Instructors:</span> " + instructorAccountsTable.size(); return createShowPageResult(Const.ViewURIs.ADMIN_ACCOUNT_MANAGEMENT, data); }

Target:
protected ActionResult execute() throws EntityDoesNotExistException { new GateKeeper().verifyAdminPrivileges(account); String instructorGoogleId = this.getRequestParamValue("googleId"); if (instructorGoogleId == null) { instructorGoogleId = ""; } Map<String, ArrayList<InstructorAttributes>> instructorCoursesTable = new HashMap<String, ArrayList<InstructorAttributes>>(); Map<String, AccountAttributes> instructorAccountsTable = new HashMap<String, AccountAttributes>(); List<InstructorAttributes> instructorsList = logic.getInstructorsForGoogleId(instructorGoogleId); AccountAttributes instructorAccount = logic.getAccount(instructorGoogleId); boolean isToShowAll = this.getRequestParamAsBoolean("all"); boolean isAccountExisting = instructorAccount != null; if (isAccountExisting) { instructorAccountsTable.put(instructorAccount.googleId, instructorAccount); for (InstructorAttributes instructor : instructorsList) { ArrayList<InstructorAttributes> courseList = instructorCoursesTable.get(instructor.googleId); if (courseList == null) { courseList = new ArrayList<InstructorAttributes>(); instructorCoursesTable.put(instructor.googleId, courseList); } courseList.add(instructor); } } AdminAccountManagementPageData data = new AdminAccountManagementPageData(account, instructorAccountsTable, instructorCoursesTable, isToShowAll); statusToAdmin = "Admin Account Management Page Load<br>" + "<span class=\"bold\">Total Instructors:</span> " + instructorAccountsTable.size(); return createShowPageResult(Const.ViewURIs.ADMIN_ACCOUNT_MANAGEMENT, data); }
Source:
private void initVmInitEnabled(VmInit vmInit, boolean isInitialized) { if (vmInit == null) { getIsCloudInitEnabled().setEntity(false); getIsSysprepEnabled().setEntity(false); getAttachFloppy().setEntity(false); } else if (!isInitialized) { if (!vm.getCompatibilityVersion().greaterOrEquals(Version.v4_4) && getIsWindowsOS()) { getIsSysprepEnabled().setEntity(true); getAttachFloppy().setEntity(true); } else { getIsCloudInitEnabled().setEntity(true); } } }

Target:
private void initVmInitEnabled(VmInit vmInit, boolean isInitialized) { if (vmInit == null) { getIsCloudInitEnabled().setEntity(false); getIsSysprepEnabled().setEntity(false); getAttachFloppy().setEntity(false); } else if (!isInitialized) { if (getIsWindowsOS()) { getIsSysprepEnabled().setEntity(true); getAttachFloppy().setEntity(true); } else { getIsCloudInitEnabled().setEntity(true); } } }
Source:
private void createHybridRole(String roleName, String[] userList, org.wso2.carbon.user.api.Permission[] permissions) throws UserStoreException { try { hybridRoleManager.addHybridRole(roleName, userList); } catch (UserStoreException e) { if (hybridRoleManager.isExistingRole(roleName)) { handleRoleAlreadyExistException(roleName, userList, permissions); } throw e; } }

Target:
private void createHybridRole(String roleName, String[] userList, org.wso2.carbon.user.api.Permission[] permissions) throws UserStoreException { try { hybridRoleManager.addHybridRole(roleName, userList); } catch (UserStoreException e) { if (ERROR_CODE_ROLE_ALREADY_EXISTS.getCode().equals(e.getErrorCode())) { handleRoleAlreadyExistException(roleName, userList, permissions); } throw e; } }
Source:
public View getView(int position, View convertView, ViewGroup parent) { View element = convertView; if(element == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); element = inflater.inflate(R.layout.song_item, null); } View userColor = (View) element.findViewById(R.id.userColor); TextView title = (TextView)element.findViewById(R.id.title); TextView artist = (TextView) element.findViewById(R.id.artist); TextView album = (TextView) element.findViewById(R.id.album); ImageButton addButton = (ImageButton) element.findViewById(R.id.add_to_playlist); addButton.setOnClickListener(this); addButton.setTag(position); userColor.setBackgroundColor(Color.parseColor(users.get(metadataList.get(position).getUsername()))); title.setText(metadataList.get(position).getTitle()); artist.setText(metadataList.get(position).getArtist()); album.setText(metadataList.get(position).getAlbum()); return element; }

Target:
public View getView(int position, View convertView, ViewGroup parent) { View element = convertView; if(element == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); element = inflater.inflate(R.layout.song_item, null); } View userColor = (View) element.findViewById(R.id.user_color); TextView title = (TextView)element.findViewById(R.id.title); TextView artist = (TextView) element.findViewById(R.id.artist); TextView album = (TextView) element.findViewById(R.id.album); ImageButton addButton = (ImageButton) element.findViewById(R.id.add_to_playlist); addButton.setTag(position); userColor.setBackgroundColor(Color.parseColor(users.get(metadataList.get(position).getUsername()))); title.setText(metadataList.get(position).getTitle()); artist.setText(metadataList.get(position).getArtist()); album.setText(metadataList.get(position).getAlbum()); artist.setMaxWidth(parent.getWidth()/2); return element; }
Source:
public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { URI uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null); HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); if (useSsl && !validateSsl) { X509TrustManager trustAllCert = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{trustAllCert}, new java.security.SecureRandom()); ((HttpsURLConnection)connection).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection)connection).setHostnameVerifier(new HostnameVerifier(){ public boolean verify(String host, SSLSession session){ return true; } }); } connection.addRequestProperty("Accept", mimeType); connection.addRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(userInfo.getBytes())); StringBuilder str = new StringBuilder(); InputStream in = new BufferedInputStream(connection.getInputStream()); try { for(;;) { int b = in.read(); if ( b < 0 ) { break; } str.append((char)(b & 0xff)); } } finally { CloseableUtils.closeQuietly(in); } return str.toString(); }

Target:
public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { URI uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null); HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); if (useSsl && !validateSsl) { X509TrustManager trustAllCert = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{trustAllCert}, new java.security.SecureRandom()); ((HttpsURLConnection)connection).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection)connection).setHostnameVerifier(new HostnameVerifier(){ public boolean verify(String host, SSLSession session){ return true; } }); } connection.addRequestProperty("Accept", mimeType); connection.addRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(userInfo.getBytes())); Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream())); try { return CharStreams.toString(in); } finally { CloseableUtils.closeQuietly(in); } }
Source:
public int compare(TestdataObject a, TestdataObject b) { return new CompareToBuilder() .append(a.getCode(), b.getCode()) .toComparison(); }

Target:
public int compare(TestdataObject a, TestdataObject b) { return COMPARATOR.compare(a, b); }
Source:
default <T> CompletableFuture<Long> parseLimitedStreamRecurse(byte[] prefix, Function<Cborable, T> fromCbor, Consumer<T> accumulator, int objectsToSkip, int maxObjectsToRead, long maxBytesToRead) { if (maxObjectsToRead == 0) return CompletableFuture.completedFuture(0L); byte[] buf = new byte[Chunk.MAX_SIZE]; System.arraycopy(prefix, 0, buf, 0, prefix.length); ByteArrayInputStream in = new ByteArrayInputStream(buf); return readIntoArray(buf, prefix.length, (int) Math.min((long)(buf.length - prefix.length), maxBytesToRead)) .thenCompose(bytesRead -> { int toSkip = objectsToSkip; int objectsToRead = maxObjectsToRead; for (int localOffset = 0; localOffset < bytesRead;) { try { CborObject readObject = CborObject.read(in, bytesRead); if (toSkip > 0) toSkip--; else { objectsToRead--; accumulator.accept(fromCbor.apply(readObject)); } localOffset += readObject.toByteArray().length; } catch (RuntimeException e) { int fromThisChunk = localOffset; return parseLimitedStreamRecurse(Arrays.copyOfRange(buf, localOffset, bytesRead), fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + fromThisChunk); } } return parseLimitedStream(fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + bytesRead); }); }

Target:
default <T> CompletableFuture<Long> parseLimitedStreamRecurse(byte[] prefix, Function<Cborable, T> fromCbor, Consumer<T> accumulator, int objectsToSkip, int maxObjectsToRead, long maxBytesToRead) { if (maxObjectsToRead == 0) return CompletableFuture.completedFuture(0L); byte[] buf = new byte[Chunk.MAX_SIZE]; System.arraycopy(prefix, 0, buf, 0, prefix.length); ByteArrayInputStream in = new ByteArrayInputStream(buf); return readIntoArray(buf, prefix.length, (int) Math.min((long)(buf.length - prefix.length), maxBytesToRead)) .thenCompose(bytesRead -> { int toSkip = objectsToSkip; int objectsToRead = maxObjectsToRead; for (int localOffset = 0; localOffset < bytesRead;) { try { CborObject readObject = CborObject.read(in, bytesRead); if (toSkip > 0) toSkip--; else { objectsToRead--; accumulator.accept(fromCbor.apply(readObject)); } localOffset += readObject.toByteArray().length; if (objectsToRead == 0) return Futures.of((long)localOffset); } catch (RuntimeException e) { int fromThisChunk = localOffset; return parseLimitedStreamRecurse(Arrays.copyOfRange(buf, localOffset, bytesRead), fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + fromThisChunk); } } return parseLimitedStream(fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + bytesRead); }); }
Source:
public static void sendSmsCbReceivedBroadcast(@NonNull Context context, @Nullable UserHandle user, @NonNull SmsCbMessage smsCbMessage, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, int slotIndex) { int status = context.checkCallingOrSelfPermission( "android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS"); if (status == PackageManager.PERMISSION_DENIED) { throw new SecurityException( "Caller does not have permission to send SMS_CB_RECEIVED_ACTION broadcast " + "for background receivers"); } Intent backgroundIntent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION); backgroundIntent.putExtra(EXTRA_MESSAGE, smsCbMessage); backgroundIntent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); putPhoneIdAndSubIdExtra(context, backgroundIntent, slotIndex); String receiverPermission = Manifest.permission.RECEIVE_SMS; String receiverAppOp = AppOpsManager.OPSTR_RECEIVE_SMS; if (user != null) { context.createContextAsUser(user, 0).sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } else { context.sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } }

Target:
public static void sendSmsCbReceivedBroadcast(@NonNull Context context, @Nullable UserHandle user, @NonNull SmsCbMessage smsCbMessage, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, int slotIndex) { Intent backgroundIntent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION); backgroundIntent.putExtra(EXTRA_MESSAGE, smsCbMessage); backgroundIntent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); putPhoneIdAndSubIdExtra(context, backgroundIntent, slotIndex); String receiverPermission = Manifest.permission.RECEIVE_SMS; String receiverAppOp = AppOpsManager.OPSTR_RECEIVE_SMS; if (user != null) { context.createContextAsUser(user, 0).sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } else { context.sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } }
Source:
protected void hotCodeError(int code, IJavaDebugTarget target, Exception exception) { int behavior = server.getAttribute(PROPERTY_HOTCODE_BEHAVIOR, PROMPT); if( behavior == PROMPT ) { Object result = getPrompter().promptUser(code, server, exception); if( result instanceof Integer) { behavior = ((Integer)result).intValue(); } } if( behavior == RESTART_MODULE) { restartModules(); } else if( behavior == RESTART_SERVER) { restartServer(); } }

Target:
protected void hotCodeError(int code, IJavaDebugTarget target, Exception exception) { int behavior = server.getAttribute(PROPERTY_HOTCODE_BEHAVIOR, PROMPT); if( behavior == PROMPT ) { Object result = getPrompter().promptUser(code, server, exception); if( result instanceof Integer) { behavior = ((Integer)result).intValue(); } } if( behavior == RESTART_MODULE) { restartModules(); } else if( behavior == RESTART_SERVER) { restartServer(); } else if( behavior == TERMINATE ) { server.stop(true); } }
Source:
private boolean checkAndDisableCLIScheduler() { GlusterVolumeEntity metaVolume = getGlusterVolumeDao().getByName(getVdsGroupId(), GlusterConstants.GLUSTER_META_VOLUME_NAME); if (metaVolume != null) { VDSGroup cluster = getVdsGroup(); if (cluster.getGlusterCliBasedScheduling()) { VDSReturnValue retValue = runVdsCommand(VDSCommandType.OverrideGlusterVolumeSnapshotSchedule, new GlusterVolumeSnapshotSchedulingVDSParameters(getUpServer().getId(), true)); setSucceeded(retValue.getSucceeded()); if (!retValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_CLI_SNAPSHOT_SCHEDULE_DISABLE_FAILED, retValue.getVdsError() .getMessage()); return false; } else { cluster.setGlusterCliBasedScheduling(false); getVdsGroupDAO().update(cluster); } } } return true; }

Target:
private boolean checkAndDisableCLIScheduler() { GlusterVolumeEntity metaVolume = getGlusterVolumeDao().getByName(getVdsGroupId(), Config.<String> getValue(ConfigValues.GlusterMetaVolumeName)); VDSGroup cluster = getVdsGroup(); if (metaVolume != null && cluster.getIsGlusterCliBasedSchedulingOn()) { VdcReturnValueBase returnValue = runInternalAction(VdcActionType.DisableGlusterCliSnapshotScheduleInternal, new DisableGlusterCliSnapshotScheduleParameters(getGlusterVolumeId(), true)); return returnValue.getSucceeded(); } return true; }
Source:
public IResource findMember(IReferencePoint referencePoint, IPath referencePointRelativePath) { if (referencePoint == null) throw new IllegalArgumentException("Reference point is null"); if (referencePointRelativePath == null) throw new IllegalArgumentException("Path is null"); org.eclipse.core.resources.IProject project = getProject(referencePoint); if (project == null) throw new NullPointerException( "For reference point " + referencePoint + " does'nt exist a project."); return project.findMember(referencePointRelativePath); }

Target:
public IResource findMember(IReferencePoint referencePoint, IPath referencePointRelativePath) { checkArgument(referencePoint, "Reference point is null"); checkArgument(referencePointRelativePath, "ReferencePointsRelativePath is null"); IProject project = Objects.requireNonNull(getProject(referencePoint)); return project.findMember(referencePointRelativePath); }
Source:
private VolumeType getVolumeTypeForDomain() { if (null == volumeTypeForDomain) { StorageDomainStatic sdStatic = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId); volumeTypeForDomain = HibernateVmCommand.getMemoryVolumeTypeForStorageDomain(sdStatic.getStorageType()); } return volumeTypeForDomain; }

Target:
private VolumeType getVolumeTypeForDomain() { if (volumeTypeForDomain == null) { StorageDomainStatic sdStatic = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId); volumeTypeForDomain = HibernateVmCommand.getMemoryVolumeTypeForStorageDomain(sdStatic.getStorageType()); } return volumeTypeForDomain; }
Source:
private void startPoller() { poller = new Timer() { private int delay = REFRESH_POLL_PERIOD; @Override public void run() { if (!isAttached()) { return; } else if (!UserActivityMonitor.isActive()) { cancel(); delay = REFRESH_IDLE_PERIOD; scheduleRepeating(delay); } loadChangeInfo(false, new AsyncCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo info) { if (isAttached() && !info.updated().equals(lastDisplayedUpdate)) { showUpdates(info); } } @Override public void onFailure(Throwable caught) { if (isAttached()) { cancel(); delay = (int) Math.max( delay * (1.5 + Math.random()), REFRESH_MAX_PERIOD); scheduleRepeating(delay); } } }); } }; poller.scheduleRepeating(REFRESH_POLL_PERIOD); }

Target:
private void startPoller() { updateCheck = new UpdateCheckTimer(this); updateCheck.schedule(); handlers.add(UserActivityMonitor.addValueChangeHandler(updateCheck)); }