code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <folly/stats/TDigest.h>
#include <folly/stats/detail/BufferedStat.h>
namespace folly {
struct QuantileEstimates {
public:
double sum;
double count;
// vector of {quantile, value}
std::vector<std::pair<double, double>> quantiles;
};
/*
* A QuantileEstimator that buffers writes for 1 second.
*/
template <typename ClockT = std::chrono::steady_clock>
class SimpleQuantileEstimator {
public:
using TimePoint = typename ClockT::time_point;
SimpleQuantileEstimator();
QuantileEstimates estimateQuantiles(
Range<const double*> quantiles, TimePoint now = ClockT::now());
void addValue(double value, TimePoint now = ClockT::now());
/// Flush buffered values
void flush() { bufferedDigest_.flush(); }
// Get point-in-time TDigest
TDigest getDigest(TimePoint now = ClockT::now()) {
return bufferedDigest_.get(now);
}
private:
detail::BufferedDigest<TDigest, ClockT> bufferedDigest_;
};
/*
* A QuantileEstimator that keeps values for nWindows * windowDuration (see
* constructor). Values are buffered for windowDuration.
*/
template <typename ClockT = std::chrono::steady_clock>
class SlidingWindowQuantileEstimator {
public:
using TimePoint = typename ClockT::time_point;
using Duration = typename ClockT::duration;
SlidingWindowQuantileEstimator(Duration windowDuration, size_t nWindows = 60);
QuantileEstimates estimateQuantiles(
Range<const double*> quantiles, TimePoint now = ClockT::now());
void addValue(double value, TimePoint now = ClockT::now());
/// Flush buffered values
void flush() { bufferedSlidingWindow_.flush(); }
// Get point-in-time TDigest
TDigest getDigest(TimePoint now = ClockT::now()) {
return TDigest::merge(bufferedSlidingWindow_.get(now));
}
private:
detail::BufferedSlidingWindow<TDigest, ClockT> bufferedSlidingWindow_;
};
} // namespace folly
#include <folly/stats/QuantileEstimator-inl.h>
| facebook/folly | folly/stats/QuantileEstimator.h | C | apache-2.0 | 2,552 |
ace.define("ace/snippets/d",["require","exports","module"],function(r,e,m){"use strict";e.snippetText=undefined;e.scope="d";});
| thbonk/electron-openui5-boilerplate | libs/openui5-runtime/resources/sap/ui/codeeditor/js/ace/snippets/d.js | JavaScript | apache-2.0 | 128 |
/*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cd.go.authentication.ldap;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.thoughtworks.go.plugin.api.request.DefaultGoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.codec.binary.Base64;
import org.junit.Before;
import org.junit.Test;
import static cd.go.authentication.ldap.executor.RequestFromServer.*;
import static cd.go.plugin.base.ResourceReader.readResource;
import static cd.go.plugin.base.ResourceReader.readResourceBytes;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.skyscreamer.jsonassert.JSONAssert.assertEquals;
public class LdapPluginIntegrationTest extends BaseIntegrationTest {
private LdapPlugin ldapPlugin;
@Before
public void setUp() {
ldapPlugin = new LdapPlugin();
ldapPlugin.initializeGoApplicationAccessor(null);
}
@Test
public void shouldHandleGetPluginIconRequestAndReturnPluginIcon() throws Exception {
final GoPluginApiResponse response = ldapPlugin.handle(buildRequest(REQUEST_GET_PLUGIN_ICON.requestName()));
final String expectedJSON = format("{\"content_type\":\"image/png\",\"data\":\"%s\"}", Base64.encodeBase64String(readResourceBytes("/gocd_72_72_icon.png")));
assertThat(response.responseCode()).isNotNull();
assertThat(response.responseCode()).isEqualTo(SUCCESS_RESPONSE_CODE);
assertEquals(expectedJSON, response.responseBody(), true);
}
@Test
public void shouldHandleGetCapabilitiesRequestAndReturnPluginCapabilities() throws Exception {
final GoPluginApiResponse response = ldapPlugin.handle(buildRequest(REQUEST_GET_CAPABILITIES.requestName()));
final String expectedJSON = "{\n" +
" \"can_search\": true,\n" +
" \"can_authorize\": false,\n" +
" \"can_get_user_roles\": false,\n" +
" \"supported_auth_type\": \"password\"\n" +
"}";
assertThat(response.responseCode()).isNotNull();
assertThat(response.responseCode()).isEqualTo(SUCCESS_RESPONSE_CODE);
assertEquals(expectedJSON, response.responseBody(), true);
}
@Test
public void shouldHandleGetAuthConfigViewRequestAndReturnAuthConfigTemplate() throws Exception {
final GoPluginApiResponse response = ldapPlugin.handle(buildRequest(REQUEST_AUTH_CONFIG_VIEW.requestName()));
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("template", readResource("/auth_config.template.html"));
String expectedJSON = new Gson().toJson(jsonObject);
assertThat(response.responseCode()).isNotNull();
assertThat(response.responseCode()).isEqualTo(SUCCESS_RESPONSE_CODE);
assertEquals(expectedJSON, response.responseBody(), true);
}
private DefaultGoPluginApiRequest buildRequest(String requestName) {
return new DefaultGoPluginApiRequest(Constants.EXTENSION_TYPE, "1.0", requestName);
}
}
| bdpiparva/gocd-ldap-authentication-plugin | src/integration/cd/go/authentication/ldap/LdapPluginIntegrationTest.java | Java | apache-2.0 | 3,775 |
/*
* Copyright 2011-2018 Chris de Vreeze
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.cdevreeze.nta.ntarule.rules_2_02
import java.net.URI
import scala.collection.immutable
import eu.cdevreeze.nta.common.taxonomy.Taxonomy
import eu.cdevreeze.nta.common.validator.Result
import eu.cdevreeze.nta.common.validator.TaxonomyDocumentValidator
import eu.cdevreeze.nta.common.validator.TaxonomyValidatorFactory
import eu.cdevreeze.nta.common.validator.ValidationScope
import eu.cdevreeze.nta.ntarule.NtaRuleConfigWrapper
import eu.cdevreeze.nta.ntarule.NtaRules
import eu.cdevreeze.tqa.ENames
import eu.cdevreeze.tqa.base.dom.TaxonomyDocument
import eu.cdevreeze.tqa.base.dom.XsdSchema
/**
* Validator of rule 2.02.00.09. The rule says that the the schema document must have a @attributeFormDefault attribute
* with value unqualified and a @elementFormDefault attribute with value qualified.
*
* @author Chris de Vreeze
*/
final class Validator_2_02_00_09(val excludedDocumentUris: Set[URI]) extends TaxonomyDocumentValidator {
def ruleName: String = NtaRules.extractRuleName(getClass)
def validateDocument(
doc: TaxonomyDocument,
taxonomy: Taxonomy,
validationScope: ValidationScope): immutable.IndexedSeq[Result] = {
require(isTypeOfDocumentToValidate(doc, taxonomy), s"Document ${doc.uri} should not be validated")
val elementFormDefaultOption = doc.documentElement.attributeOption(ENames.ElementFormDefaultEName)
val attributeFormDefaultOption = doc.documentElement.attributeOption(ENames.AttributeFormDefaultEName)
val elementFormErrors =
if (elementFormDefaultOption.isEmpty) {
immutable.IndexedSeq(Result.makeErrorResult(
ruleName,
"missing-element-form-default",
s"Missing elementFormDefault in '${doc.uri}'"))
} else if (elementFormDefaultOption.contains("qualified")) {
immutable.IndexedSeq()
} else {
immutable.IndexedSeq(Result.makeErrorResult(
ruleName,
"wrong-element-form-default",
s"Wrong elementFormDefault in '${doc.uri}'"))
}
val attributeFormErrors =
if (attributeFormDefaultOption.isEmpty) {
immutable.IndexedSeq(Result.makeErrorResult(
ruleName,
"missing-attribute-form-default",
s"Missing attributeFormDefault in '${doc.uri}'"))
} else if (attributeFormDefaultOption.contains("unqualified")) {
immutable.IndexedSeq()
} else {
immutable.IndexedSeq(Result.makeErrorResult(
ruleName,
"wrong-attribute-form-default",
s"Wrong attributeFormDefault in '${doc.uri}'"))
}
elementFormErrors ++ attributeFormErrors
}
def isTypeOfDocumentToValidate(doc: TaxonomyDocument, taxonomy: Taxonomy): Boolean = {
doc.documentElement.isInstanceOf[XsdSchema]
}
}
object Validator_2_02_00_09 extends TaxonomyValidatorFactory {
type Validator = Validator_2_02_00_09
type CfgWrapper = NtaRuleConfigWrapper
def ruleName: String = {
NtaRules.extractRuleName(classOf[Validator_2_02_00_09])
}
def create(configWrapper: NtaRuleConfigWrapper): Validator_2_02_00_09 = {
new Validator_2_02_00_09(
configWrapper.excludedDocumentUrisForRule(ruleName))
}
}
| dvreeze/nta | src/main/scala/eu/cdevreeze/nta/ntarule/rules_2_02/Validator_2_02_00_09.scala | Scala | apache-2.0 | 3,776 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models.utils;
import org.jboss.logging.Logger;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.AuthorizationProviderFactory;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PolicyStore;
import org.keycloak.authorization.store.ResourceServerStore;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.authorization.store.ScopeStore;
import org.keycloak.authorization.store.StoreFactory;
import org.keycloak.common.enums.SslRequired;
import org.keycloak.common.util.Base64;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.common.util.UriUtils;
import org.keycloak.component.ComponentModel;
import org.keycloak.credential.CredentialModel;
import org.keycloak.keys.KeyProvider;
import org.keycloak.migration.MigrationProvider;
import org.keycloak.migration.migrators.MigrationUtils;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.AuthenticatorConfigModel;
import org.keycloak.models.BrowserSecurityHeaders;
import org.keycloak.models.ClaimMask;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientTemplateModel;
import org.keycloak.models.Constants;
import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.IdentityProviderMapperModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.ModelException;
import org.keycloak.models.OTPPolicy;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredActionProviderModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.ScopeContainerModel;
import org.keycloak.models.UserConsentModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.representations.idm.ApplicationRepresentation;
import org.keycloak.representations.idm.AuthenticationExecutionExportRepresentation;
import org.keycloak.representations.idm.AuthenticationExecutionRepresentation;
import org.keycloak.representations.idm.AuthenticationFlowRepresentation;
import org.keycloak.representations.idm.AuthenticatorConfigRepresentation;
import org.keycloak.representations.idm.ClaimRepresentation;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ClientTemplateRepresentation;
import org.keycloak.representations.idm.ComponentExportRepresentation;
import org.keycloak.representations.idm.ComponentRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.FederatedIdentityRepresentation;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.IdentityProviderMapperRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.OAuthClientRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RequiredActionProviderRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.RolesRepresentation;
import org.keycloak.representations.idm.ScopeMappingRepresentation;
import org.keycloak.representations.idm.SocialLinkRepresentation;
import org.keycloak.representations.idm.UserConsentRepresentation;
import org.keycloak.representations.idm.UserFederationMapperRepresentation;
import org.keycloak.representations.idm.UserFederationProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.authorization.PolicyEnforcementMode;
import org.keycloak.representations.idm.authorization.PolicyRepresentation;
import org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation;
import org.keycloak.representations.idm.authorization.ResourceRepresentation;
import org.keycloak.representations.idm.authorization.ResourceServerRepresentation;
import org.keycloak.representations.idm.authorization.ScopeRepresentation;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.storage.UserStorageProviderModel;
import org.keycloak.storage.federated.UserFederatedStorageProvider;
import org.keycloak.util.JsonSerialization;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class RepresentationToModel {
private static Logger logger = Logger.getLogger(RepresentationToModel.class);
public static OTPPolicy toPolicy(RealmRepresentation rep) {
OTPPolicy policy = new OTPPolicy();
if (rep.getOtpPolicyType() != null) policy.setType(rep.getOtpPolicyType());
if (rep.getOtpPolicyLookAheadWindow() != null) policy.setLookAheadWindow(rep.getOtpPolicyLookAheadWindow());
if (rep.getOtpPolicyInitialCounter() != null) policy.setInitialCounter(rep.getOtpPolicyInitialCounter());
if (rep.getOtpPolicyAlgorithm() != null) policy.setAlgorithm(rep.getOtpPolicyAlgorithm());
if (rep.getOtpPolicyDigits() != null) policy.setDigits(rep.getOtpPolicyDigits());
if (rep.getOtpPolicyPeriod() != null) policy.setPeriod(rep.getOtpPolicyPeriod());
return policy;
}
public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) {
convertDeprecatedSocialProviders(rep);
convertDeprecatedApplications(session, rep);
newRealm.setName(rep.getRealm());
if (rep.getDisplayName() != null) newRealm.setDisplayName(rep.getDisplayName());
if (rep.getDisplayNameHtml() != null) newRealm.setDisplayNameHtml(rep.getDisplayNameHtml());
if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled());
if (rep.isBruteForceProtected() != null) newRealm.setBruteForceProtected(rep.isBruteForceProtected());
if (rep.getMaxFailureWaitSeconds() != null) newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
if (rep.getMinimumQuickLoginWaitSeconds() != null) newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
if (rep.getWaitIncrementSeconds() != null) newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
if (rep.getQuickLoginCheckMilliSeconds() != null) newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
if (rep.getMaxDeltaTimeSeconds() != null) newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
if (rep.getFailureFactor() != null) newRealm.setFailureFactor(rep.getFailureFactor());
if (rep.isEventsEnabled() != null) newRealm.setEventsEnabled(rep.isEventsEnabled());
if (rep.getEventsExpiration() != null) newRealm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getEventsListeners() != null) newRealm.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
if (rep.isAdminEventsEnabled() != null) newRealm.setAdminEventsEnabled(rep.isAdminEventsEnabled());
if (rep.isAdminEventsDetailsEnabled() != null) newRealm.setAdminEventsDetailsEnabled(rep.isAdminEventsDetailsEnabled());
if (rep.getNotBefore() != null) newRealm.setNotBefore(rep.getNotBefore());
if (rep.getRevokeRefreshToken() != null) newRealm.setRevokeRefreshToken(rep.getRevokeRefreshToken());
else newRealm.setRevokeRefreshToken(false);
if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
else newRealm.setAccessTokenLifespan(300);
if (rep.getAccessTokenLifespanForImplicitFlow() != null) newRealm.setAccessTokenLifespanForImplicitFlow(rep.getAccessTokenLifespanForImplicitFlow());
else newRealm.setAccessTokenLifespanForImplicitFlow(Constants.DEFAULT_ACCESS_TOKEN_LIFESPAN_FOR_IMPLICIT_FLOW_TIMEOUT);
if (rep.getSsoSessionIdleTimeout() != null) newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
else newRealm.setSsoSessionIdleTimeout(1800);
if (rep.getSsoSessionMaxLifespan() != null) newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
else newRealm.setSsoSessionMaxLifespan(36000);
if (rep.getOfflineSessionIdleTimeout() != null) newRealm.setOfflineSessionIdleTimeout(rep.getOfflineSessionIdleTimeout());
else newRealm.setOfflineSessionIdleTimeout(Constants.DEFAULT_OFFLINE_SESSION_IDLE_TIMEOUT);
if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
else newRealm.setAccessCodeLifespan(60);
if (rep.getAccessCodeLifespanUserAction() != null)
newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
else newRealm.setAccessCodeLifespanUserAction(300);
if (rep.getAccessCodeLifespanLogin() != null)
newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
else newRealm.setAccessCodeLifespanLogin(1800);
if (rep.getSslRequired() != null) newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed());
if (rep.isRegistrationEmailAsUsername() != null)
newRealm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
if (rep.isRememberMe() != null) newRealm.setRememberMe(rep.isRememberMe());
if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail());
if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
if (rep.isEditUsernameAllowed() != null) newRealm.setEditUsernameAllowed(rep.isEditUsernameAllowed());
if (rep.getLoginTheme() != null) newRealm.setLoginTheme(rep.getLoginTheme());
if (rep.getAccountTheme() != null) newRealm.setAccountTheme(rep.getAccountTheme());
if (rep.getAdminTheme() != null) newRealm.setAdminTheme(rep.getAdminTheme());
if (rep.getEmailTheme() != null) newRealm.setEmailTheme(rep.getEmailTheme());
// todo remove this stuff as its all deprecated
if (rep.getRequiredCredentials() != null) {
for (String requiredCred : rep.getRequiredCredentials()) {
newRealm.addRequiredCredential(requiredCred);
}
} else {
newRealm.addRequiredCredential(CredentialRepresentation.PASSWORD);
}
if (rep.getPasswordPolicy() != null) newRealm.setPasswordPolicy(PasswordPolicy.parse(session, rep.getPasswordPolicy()));
if (rep.getOtpPolicyType() != null) newRealm.setOTPPolicy(toPolicy(rep));
else newRealm.setOTPPolicy(OTPPolicy.DEFAULT_POLICY);
importAuthenticationFlows(newRealm, rep);
if (rep.getRequiredActions() != null) {
for (RequiredActionProviderRepresentation action : rep.getRequiredActions()) {
RequiredActionProviderModel model = toModel(action);
MigrationUtils.updateOTPRequiredAction(model);
newRealm.addRequiredActionProvider(model);
}
} else {
DefaultRequiredActions.addActions(newRealm);
}
importIdentityProviders(rep, newRealm);
importIdentityProviderMappers(rep, newRealm);
if (rep.getClientTemplates() != null) {
createClientTemplates(session, rep, newRealm);
}
if (rep.getClients() != null) {
createClients(session, rep, newRealm);
}
importRoles(rep.getRoles(), newRealm);
// Setup realm default roles
if (rep.getDefaultRoles() != null) {
for (String roleString : rep.getDefaultRoles()) {
newRealm.addDefaultRole(roleString.trim());
}
}
// Setup client default roles
if (rep.getClients() != null) {
for (ClientRepresentation resourceRep : rep.getClients()) {
if (resourceRep.getDefaultRoles() != null) {
ClientModel clientModel = newRealm.getClientByClientId(resourceRep.getClientId());
clientModel.updateDefaultRoles(resourceRep.getDefaultRoles());
}
}
}
// Now that all possible roles and clients are created, create scope mappings
//Map<String, ClientModel> appMap = newRealm.getClientNameMap();
if (rep.getClientScopeMappings() != null) {
for (Map.Entry<String, List<ScopeMappingRepresentation>> entry : rep.getClientScopeMappings().entrySet()) {
ClientModel app = newRealm.getClientByClientId(entry.getKey());
if (app == null) {
throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
}
createClientScopeMappings(newRealm, app, entry.getValue());
}
}
if (rep.getScopeMappings() != null) {
for (ScopeMappingRepresentation scope : rep.getScopeMappings()) {
ScopeContainerModel scopeContainer = getScopeContainerHavingScope(newRealm, scope);
for (String roleString : scope.getRoles()) {
RoleModel role = newRealm.getRole(roleString.trim());
if (role == null) {
role = newRealm.addRole(roleString.trim());
}
scopeContainer.addScopeMapping(role);
}
}
}
if (rep.getClients() != null) {
rep.getClients().forEach(clientRepresentation -> {
ClientModel client = newRealm.getClientByClientId(clientRepresentation.getClientId());
importAuthorizationSettings(clientRepresentation, client, session);
});
}
if (rep.getSmtpServer() != null) {
newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer()));
}
if (rep.getBrowserSecurityHeaders() != null) {
newRealm.setBrowserSecurityHeaders(rep.getBrowserSecurityHeaders());
} else {
newRealm.setBrowserSecurityHeaders(BrowserSecurityHeaders.defaultHeaders);
}
if (rep.getComponents() != null) {
MultivaluedHashMap<String, ComponentExportRepresentation> components = rep.getComponents();
String parentId = newRealm.getId();
importComponents(newRealm, components, parentId);
}
importUserFederationProvidersAndMappers(session, rep, newRealm);
if (rep.getGroups() != null) {
importGroups(newRealm, rep);
if (rep.getDefaultGroups() != null) {
for (String path : rep.getDefaultGroups()) {
GroupModel found = KeycloakModelUtils.findGroupByPath(newRealm, path);
if (found == null) throw new RuntimeException("default group in realm rep doesn't exist: " + path);
newRealm.addDefaultGroup(found);
}
}
}
// create users and their role mappings and social mappings
if (rep.getUsers() != null) {
for (UserRepresentation userRep : rep.getUsers()) {
UserModel user = createUser(session, newRealm, userRep);
}
}
if (rep.getFederatedUsers() != null) {
for (UserRepresentation userRep : rep.getFederatedUsers()) {
importFederatedUser(session, newRealm, userRep);
}
}
if(rep.isInternationalizationEnabled() != null){
newRealm.setInternationalizationEnabled(rep.isInternationalizationEnabled());
}
if(rep.getSupportedLocales() != null){
newRealm.setSupportedLocales(new HashSet<String>(rep.getSupportedLocales()));
}
if(rep.getDefaultLocale() != null){
newRealm.setDefaultLocale(rep.getDefaultLocale());
}
// import attributes
if (rep.getAttributes() != null) {
for (Map.Entry<String, String> attr : rep.getAttributes().entrySet()) {
newRealm.setAttribute(attr.getKey(), attr.getValue());
}
}
if (newRealm.getComponents(newRealm.getId(), KeyProvider.class.getName()).isEmpty()) {
if (rep.getPrivateKey() != null) {
DefaultKeyProviders.createProviders(newRealm, rep.getPrivateKey(), rep.getCertificate());
} else {
DefaultKeyProviders.createProviders(newRealm);
}
}
}
public static void importUserFederationProvidersAndMappers(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) {
// providers to convert to component model
Set<String> convertSet = new HashSet<>();
convertSet.add(LDAPConstants.LDAP_PROVIDER);
convertSet.add("kerberos");
Map<String, String> mapperConvertSet = new HashMap<>();
mapperConvertSet.put(LDAPConstants.LDAP_PROVIDER, "org.keycloak.storage.ldap.mappers.LDAPStorageMapper");
Map<String, ComponentModel> userStorageModels = new HashMap<>();
if (rep.getUserFederationProviders() != null) {
for (UserFederationProviderRepresentation fedRep : rep.getUserFederationProviders()) {
if (convertSet.contains(fedRep.getProviderName())) {
ComponentModel component = convertFedProviderToComponent(newRealm.getId(), fedRep);
userStorageModels.put(fedRep.getDisplayName(), newRealm.importComponentModel(component));
}
}
}
// This is for case, when you have hand-written JSON file with LDAP userFederationProvider, but WITHOUT any userFederationMappers configured. Default LDAP mappers need to be created in that case.
Set<String> storageProvidersWhichShouldImportDefaultMappers = new HashSet<>(userStorageModels.keySet());
if (rep.getUserFederationMappers() != null) {
for (UserFederationMapperRepresentation representation : rep.getUserFederationMappers()) {
if (userStorageModels.containsKey(representation.getFederationProviderDisplayName())) {
ComponentModel parent = userStorageModels.get(representation.getFederationProviderDisplayName());
String newMapperType = mapperConvertSet.get(parent.getProviderId());
ComponentModel mapper = convertFedMapperToComponent(newRealm, parent, representation, newMapperType);
newRealm.importComponentModel(mapper);
storageProvidersWhichShouldImportDefaultMappers.remove(representation.getFederationProviderDisplayName());
}
}
}
for (String providerDisplayName : storageProvidersWhichShouldImportDefaultMappers) {
ComponentUtil.notifyCreated(session, newRealm, userStorageModels.get(providerDisplayName));
}
}
protected static void importComponents(RealmModel newRealm, MultivaluedHashMap<String, ComponentExportRepresentation> components, String parentId) {
for (Map.Entry<String, List<ComponentExportRepresentation>> entry : components.entrySet()) {
String providerType = entry.getKey();
for (ComponentExportRepresentation compRep : entry.getValue()) {
ComponentModel component = new ComponentModel();
component.setId(compRep.getId());
component.setName(compRep.getName());
component.setConfig(compRep.getConfig());
component.setProviderType(providerType);
component.setProviderId(compRep.getProviderId());
component.setSubType(compRep.getSubType());
component.setParentId(parentId);
component = newRealm.importComponentModel(component);
if (compRep.getSubComponents() != null) {
importComponents(newRealm, compRep.getSubComponents(), component.getId());
}
}
}
}
public static void importRoles(RolesRepresentation realmRoles, RealmModel realm) {
if (realmRoles == null) return;
if (realmRoles.getRealm() != null) { // realm roles
for (RoleRepresentation roleRep : realmRoles.getRealm()) {
createRole(realm, roleRep);
}
}
if (realmRoles.getClient() != null) {
for (Map.Entry<String, List<RoleRepresentation>> entry : realmRoles.getClient().entrySet()) {
ClientModel client = realm.getClientByClientId(entry.getKey());
if (client == null) {
throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey());
}
for (RoleRepresentation roleRep : entry.getValue()) {
// Application role may already exists (for example if it is defaultRole)
RoleModel role = roleRep.getId()!=null ? client.addRole(roleRep.getId(), roleRep.getName()) : client.addRole(roleRep.getName());
role.setDescription(roleRep.getDescription());
boolean scopeParamRequired = roleRep.isScopeParamRequired()==null ? false : roleRep.isScopeParamRequired();
role.setScopeParamRequired(scopeParamRequired);
}
}
}
// now that all roles are created, re-iterate and set up composites
if (realmRoles.getRealm() != null) { // realm roles
for (RoleRepresentation roleRep : realmRoles.getRealm()) {
RoleModel role = realm.getRole(roleRep.getName());
addComposites(role, roleRep, realm);
}
}
if (realmRoles.getClient() != null) {
for (Map.Entry<String, List<RoleRepresentation>> entry : realmRoles.getClient().entrySet()) {
ClientModel client = realm.getClientByClientId(entry.getKey());
if (client == null) {
throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey());
}
for (RoleRepresentation roleRep : entry.getValue()) {
RoleModel role = client.getRole(roleRep.getName());
addComposites(role, roleRep, realm);
}
}
}
}
public static void importGroups(RealmModel realm, RealmRepresentation rep) {
List<GroupRepresentation> groups = rep.getGroups();
if (groups == null) return;
GroupModel parent = null;
for (GroupRepresentation group : groups) {
importGroup(realm, parent, group);
}
}
public static void importGroup(RealmModel realm, GroupModel parent, GroupRepresentation group) {
GroupModel newGroup = realm.createGroup(group.getId(), group.getName());
if (group.getAttributes() != null) {
for (Map.Entry<String, List<String>> attr : group.getAttributes().entrySet()) {
newGroup.setAttribute(attr.getKey(), attr.getValue());
}
}
realm.moveGroup(newGroup, parent);
if (group.getRealmRoles() != null) {
for (String roleString : group.getRealmRoles()) {
RoleModel role = realm.getRole(roleString.trim());
if (role == null) {
role = realm.addRole(roleString.trim());
}
newGroup.grantRole(role);
}
}
if (group.getClientRoles() != null) {
for (Map.Entry<String, List<String>> entry : group.getClientRoles().entrySet()) {
ClientModel client = realm.getClientByClientId(entry.getKey());
if (client == null) {
throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
}
List<String> roleNames = entry.getValue();
for (String roleName : roleNames) {
RoleModel role = client.getRole(roleName.trim());
if (role == null) {
role = client.addRole(roleName.trim());
}
newGroup.grantRole(role);
}
}
}
if (group.getSubGroups() != null) {
for (GroupRepresentation subGroup : group.getSubGroups()) {
importGroup(realm, newGroup, subGroup);
}
}
}
public static void importAuthenticationFlows(RealmModel newRealm, RealmRepresentation rep) {
if (rep.getAuthenticationFlows() == null) {
// assume this is an old version being imported
DefaultAuthenticationFlows.migrateFlows(newRealm);
} else {
for (AuthenticatorConfigRepresentation configRep : rep.getAuthenticatorConfig()) {
AuthenticatorConfigModel model = toModel(configRep);
newRealm.addAuthenticatorConfig(model);
}
for (AuthenticationFlowRepresentation flowRep : rep.getAuthenticationFlows()) {
AuthenticationFlowModel model = toModel(flowRep);
// make sure new id is generated for new AuthenticationFlowModel instance
model.setId(null);
model = newRealm.addAuthenticationFlow(model);
}
for (AuthenticationFlowRepresentation flowRep : rep.getAuthenticationFlows()) {
AuthenticationFlowModel model = newRealm.getFlowByAlias(flowRep.getAlias());
for (AuthenticationExecutionExportRepresentation exeRep : flowRep.getAuthenticationExecutions()) {
AuthenticationExecutionModel execution = toModel(newRealm, exeRep);
execution.setParentFlow(model.getId());
newRealm.addAuthenticatorExecution(execution);
}
}
}
if (rep.getBrowserFlow() == null) {
newRealm.setBrowserFlow(newRealm.getFlowByAlias(DefaultAuthenticationFlows.BROWSER_FLOW));
} else {
newRealm.setBrowserFlow(newRealm.getFlowByAlias(rep.getBrowserFlow()));
}
if (rep.getRegistrationFlow() == null) {
newRealm.setRegistrationFlow(newRealm.getFlowByAlias(DefaultAuthenticationFlows.REGISTRATION_FLOW));
} else {
newRealm.setRegistrationFlow(newRealm.getFlowByAlias(rep.getRegistrationFlow()));
}
if (rep.getDirectGrantFlow() == null) {
newRealm.setDirectGrantFlow(newRealm.getFlowByAlias(DefaultAuthenticationFlows.DIRECT_GRANT_FLOW));
} else {
newRealm.setDirectGrantFlow(newRealm.getFlowByAlias(rep.getDirectGrantFlow()));
}
// reset credentials + client flow needs to be more defensive as they were added later (in 1.5 )
if (rep.getResetCredentialsFlow() == null) {
AuthenticationFlowModel resetFlow = newRealm.getFlowByAlias(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW);
if (resetFlow == null) {
DefaultAuthenticationFlows.resetCredentialsFlow(newRealm);
} else {
newRealm.setResetCredentialsFlow(resetFlow);
}
} else {
newRealm.setResetCredentialsFlow(newRealm.getFlowByAlias(rep.getResetCredentialsFlow()));
}
if (rep.getClientAuthenticationFlow() == null) {
AuthenticationFlowModel clientFlow = newRealm.getFlowByAlias(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW);
if (clientFlow == null) {
DefaultAuthenticationFlows.clientAuthFlow(newRealm);
} else {
newRealm.setClientAuthenticationFlow(clientFlow);
}
} else {
newRealm.setClientAuthenticationFlow(newRealm.getFlowByAlias(rep.getClientAuthenticationFlow()));
}
// Added in 1.7
if (newRealm.getFlowByAlias(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW) == null) {
DefaultAuthenticationFlows.firstBrokerLoginFlow(newRealm, true);
}
// Added in 2.2
String defaultProvider = null;
if (rep.getIdentityProviders() != null) {
for (IdentityProviderRepresentation i : rep.getIdentityProviders()) {
if (i.isEnabled() && i.isAuthenticateByDefault()) {
defaultProvider = i.getProviderId();
break;
}
}
}
DefaultAuthenticationFlows.addIdentityProviderAuthenticator(newRealm, defaultProvider);
}
private static void convertDeprecatedSocialProviders(RealmRepresentation rep) {
if (rep.isSocial() != null && rep.isSocial() && rep.getSocialProviders() != null && !rep.getSocialProviders().isEmpty() && rep.getIdentityProviders() == null) {
Boolean updateProfileFirstLogin = rep.isUpdateProfileOnInitialSocialLogin() != null && rep.isUpdateProfileOnInitialSocialLogin();
if (rep.getSocialProviders() != null) {
logger.warn("Using deprecated 'social' configuration in JSON representation. It will be removed in future versions");
List<IdentityProviderRepresentation> identityProviders = new LinkedList<>();
for (String k : rep.getSocialProviders().keySet()) {
if (k.endsWith(".key")) {
String providerId = k.split("\\.")[0];
String key = rep.getSocialProviders().get(k);
String secret = rep.getSocialProviders().get(k.replace(".key", ".secret"));
IdentityProviderRepresentation identityProvider = new IdentityProviderRepresentation();
identityProvider.setAlias(providerId);
identityProvider.setProviderId(providerId);
identityProvider.setEnabled(true);
identityProvider.setUpdateProfileFirstLogin(updateProfileFirstLogin);
Map<String, String> config = new HashMap<>();
config.put("clientId", key);
config.put("clientSecret", secret);
identityProvider.setConfig(config);
identityProviders.add(identityProvider);
}
}
rep.setIdentityProviders(identityProviders);
}
}
}
private static void convertDeprecatedSocialProviders(UserRepresentation user) {
if (user.getSocialLinks() != null && !user.getSocialLinks().isEmpty() && user.getFederatedIdentities() == null) {
logger.warnf("Using deprecated 'socialLinks' configuration in JSON representation for user '%s'. It will be removed in future versions", user.getUsername());
List<FederatedIdentityRepresentation> federatedIdentities = new LinkedList<>();
for (SocialLinkRepresentation social : user.getSocialLinks()) {
FederatedIdentityRepresentation federatedIdentity = new FederatedIdentityRepresentation();
federatedIdentity.setIdentityProvider(social.getSocialProvider());
federatedIdentity.setUserId(social.getSocialUserId());
federatedIdentity.setUserName(social.getSocialUsername());
federatedIdentities.add(federatedIdentity);
}
user.setFederatedIdentities(federatedIdentities);
}
user.setSocialLinks(null);
}
private static void convertDeprecatedApplications(KeycloakSession session, RealmRepresentation realm) {
if (realm.getApplications() != null || realm.getOauthClients() != null) {
if (realm.getClients() == null) {
realm.setClients(new LinkedList<ClientRepresentation>());
}
List<ApplicationRepresentation> clients = new LinkedList<>();
if (realm.getApplications() != null) {
clients.addAll(realm.getApplications());
}
if (realm.getOauthClients() != null) {
clients.addAll(realm.getOauthClients());
}
for (ApplicationRepresentation app : clients) {
app.setClientId(app.getName());
app.setName(null);
if (app instanceof OAuthClientRepresentation) {
app.setConsentRequired(true);
app.setFullScopeAllowed(false);
}
if (app.getProtocolMappers() == null && app.getClaims() != null) {
long mask = getClaimsMask(app.getClaims());
List<ProtocolMapperRepresentation> convertedProtocolMappers = session.getProvider(MigrationProvider.class).getMappersForClaimMask(mask);
app.setProtocolMappers(convertedProtocolMappers);
app.setClaims(null);
}
realm.getClients().add(app);
}
}
if (realm.getApplicationScopeMappings() != null && realm.getClientScopeMappings() == null) {
realm.setClientScopeMappings(realm.getApplicationScopeMappings());
}
if (realm.getRoles() != null && realm.getRoles().getApplication() != null && realm.getRoles().getClient() == null) {
realm.getRoles().setClient(realm.getRoles().getApplication());
}
if (realm.getUsers() != null) {
for (UserRepresentation user : realm.getUsers()) {
if (user.getApplicationRoles() != null && user.getClientRoles() == null) {
user.setClientRoles(user.getApplicationRoles());
}
}
}
if (realm.getRoles() != null && realm.getRoles().getRealm() != null) {
for (RoleRepresentation role : realm.getRoles().getRealm()) {
if (role.getComposites() != null && role.getComposites().getApplication() != null && role.getComposites().getClient() == null) {
role.getComposites().setClient(role.getComposites().getApplication());
}
}
}
if (realm.getRoles() != null && realm.getRoles().getClient() != null) {
for (Map.Entry<String, List<RoleRepresentation>> clientRoles : realm.getRoles().getClient().entrySet()) {
for (RoleRepresentation role : clientRoles.getValue()) {
if (role.getComposites() != null && role.getComposites().getApplication() != null && role.getComposites().getClient() == null) {
role.getComposites().setClient(role.getComposites().getApplication());
}
}
}
}
}
public static void renameRealm(RealmModel realm, String name) {
if (name.equals(realm.getName())) return;
String oldName = realm.getName();
ClientModel masterApp = realm.getMasterAdminClient();
masterApp.setClientId(KeycloakModelUtils.getMasterRealmAdminApplicationClientId(name));
realm.setName(name);
ClientModel adminClient = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
if (adminClient != null) {
if (adminClient.getBaseUrl() != null) {
adminClient.setBaseUrl(adminClient.getBaseUrl().replace("/admin/" + oldName + "/", "/admin/" + name + "/"));
}
Set<String> adminRedirectUris = new HashSet<>();
for (String r : adminClient.getRedirectUris()) {
adminRedirectUris.add(replace(r, "/admin/" + oldName + "/", "/admin/" + name + "/"));
}
adminClient.setRedirectUris(adminRedirectUris);
}
ClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
if (accountClient != null) {
if (accountClient.getBaseUrl() != null) {
accountClient.setBaseUrl(accountClient.getBaseUrl().replace("/realms/" + oldName + "/", "/realms/" + name + "/"));
}
Set<String> accountRedirectUris = new HashSet<>();
for (String r : accountClient.getRedirectUris()) {
accountRedirectUris.add(replace(r, "/realms/" + oldName + "/", "/realms/" + name + "/"));
}
accountClient.setRedirectUris(accountRedirectUris);
}
}
private static String replace(String url, String target, String replacement) {
return url != null ? url.replace(target, replacement) : null;
}
public static void updateRealm(RealmRepresentation rep, RealmModel realm, KeycloakSession session) {
if (rep.getRealm() != null) {
renameRealm(realm, rep.getRealm());
}
// Import attributes first, so the stuff saved directly on representation (displayName, bruteForce etc) has bigger priority
if (rep.getAttributes() != null) {
Set<String> attrsToRemove = new HashSet<>(realm.getAttributes().keySet());
attrsToRemove.removeAll(rep.getAttributes().keySet());
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
realm.setAttribute(entry.getKey(), entry.getValue());
}
for (String attr : attrsToRemove) {
realm.removeAttribute(attr);
}
}
if (rep.getDisplayName() != null) realm.setDisplayName(rep.getDisplayName());
if (rep.getDisplayNameHtml() != null) realm.setDisplayNameHtml(rep.getDisplayNameHtml());
if (rep.isEnabled() != null) realm.setEnabled(rep.isEnabled());
if (rep.isBruteForceProtected() != null) realm.setBruteForceProtected(rep.isBruteForceProtected());
if (rep.getMaxFailureWaitSeconds() != null) realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
if (rep.getMinimumQuickLoginWaitSeconds() != null) realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
if (rep.getWaitIncrementSeconds() != null) realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
if (rep.getQuickLoginCheckMilliSeconds() != null) realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
if (rep.getMaxDeltaTimeSeconds() != null) realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
if (rep.getFailureFactor() != null) realm.setFailureFactor(rep.getFailureFactor());
if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed());
if (rep.isRegistrationEmailAsUsername() != null) realm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
if (rep.isRememberMe() != null) realm.setRememberMe(rep.isRememberMe());
if (rep.isVerifyEmail() != null) realm.setVerifyEmail(rep.isVerifyEmail());
if (rep.isResetPasswordAllowed() != null) realm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
if (rep.isEditUsernameAllowed() != null) realm.setEditUsernameAllowed(rep.isEditUsernameAllowed());
if (rep.getSslRequired() != null) realm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
if (rep.getAccessCodeLifespanUserAction() != null) realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
if (rep.getAccessCodeLifespanLogin() != null) realm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
if (rep.getNotBefore() != null) realm.setNotBefore(rep.getNotBefore());
if (rep.getRevokeRefreshToken() != null) realm.setRevokeRefreshToken(rep.getRevokeRefreshToken());
if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
if (rep.getAccessTokenLifespanForImplicitFlow() != null) realm.setAccessTokenLifespanForImplicitFlow(rep.getAccessTokenLifespanForImplicitFlow());
if (rep.getSsoSessionIdleTimeout() != null) realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
if (rep.getSsoSessionMaxLifespan() != null) realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
if (rep.getOfflineSessionIdleTimeout() != null) realm.setOfflineSessionIdleTimeout(rep.getOfflineSessionIdleTimeout());
if (rep.getRequiredCredentials() != null) {
realm.updateRequiredCredentials(rep.getRequiredCredentials());
}
if (rep.getLoginTheme() != null) realm.setLoginTheme(rep.getLoginTheme());
if (rep.getAccountTheme() != null) realm.setAccountTheme(rep.getAccountTheme());
if (rep.getAdminTheme() != null) realm.setAdminTheme(rep.getAdminTheme());
if (rep.getEmailTheme() != null) realm.setEmailTheme(rep.getEmailTheme());
if (rep.isEventsEnabled() != null) realm.setEventsEnabled(rep.isEventsEnabled());
if (rep.getEventsExpiration() != null) realm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getEventsListeners() != null) realm.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
if (rep.getEnabledEventTypes() != null) realm.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
if (rep.isAdminEventsEnabled() != null) realm.setAdminEventsEnabled(rep.isAdminEventsEnabled());
if (rep.isAdminEventsDetailsEnabled() != null) realm.setAdminEventsDetailsEnabled(rep.isAdminEventsDetailsEnabled());
if (rep.getPasswordPolicy() != null) realm.setPasswordPolicy(PasswordPolicy.parse(session, rep.getPasswordPolicy()));
if (rep.getOtpPolicyType() != null) realm.setOTPPolicy(toPolicy(rep));
if (rep.getDefaultRoles() != null) {
realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()]));
}
if (rep.getSmtpServer() != null) {
Map<String, String> config = new HashMap(rep.getSmtpServer());
if (rep.getSmtpServer().containsKey("password") && ComponentRepresentation.SECRET_VALUE.equals(rep.getSmtpServer().get("password"))) {
String passwordValue = realm.getSmtpConfig() != null ? realm.getSmtpConfig().get("password") : null;
config.put("password", passwordValue);
}
realm.setSmtpConfig(config);
}
if (rep.getBrowserSecurityHeaders() != null) {
realm.setBrowserSecurityHeaders(rep.getBrowserSecurityHeaders());
}
if(rep.isInternationalizationEnabled() != null){
realm.setInternationalizationEnabled(rep.isInternationalizationEnabled());
}
if(rep.getSupportedLocales() != null){
realm.setSupportedLocales(new HashSet<String>(rep.getSupportedLocales()));
}
if(rep.getDefaultLocale() != null){
realm.setDefaultLocale(rep.getDefaultLocale());
}
if (rep.getBrowserFlow() != null) {
realm.setBrowserFlow(realm.getFlowByAlias(rep.getBrowserFlow()));
}
if (rep.getRegistrationFlow() != null) {
realm.setRegistrationFlow(realm.getFlowByAlias(rep.getRegistrationFlow()));
}
if (rep.getDirectGrantFlow() != null) {
realm.setDirectGrantFlow(realm.getFlowByAlias(rep.getDirectGrantFlow()));
}
if (rep.getResetCredentialsFlow() != null) {
realm.setResetCredentialsFlow(realm.getFlowByAlias(rep.getResetCredentialsFlow()));
}
if (rep.getClientAuthenticationFlow() != null) {
realm.setClientAuthenticationFlow(realm.getFlowByAlias(rep.getClientAuthenticationFlow()));
}
}
// Basic realm stuff
public static ComponentModel convertFedProviderToComponent(String realmId, UserFederationProviderRepresentation fedModel) {
UserStorageProviderModel model = new UserStorageProviderModel();
model.setId(fedModel.getId());
model.setName(fedModel.getDisplayName());
model.setParentId(realmId);
model.setProviderId(fedModel.getProviderName());
model.setProviderType(UserStorageProvider.class.getName());
model.setFullSyncPeriod(fedModel.getFullSyncPeriod());
model.setPriority(fedModel.getPriority());
model.setChangedSyncPeriod(fedModel.getChangedSyncPeriod());
model.setLastSync(fedModel.getLastSync());
if (fedModel.getConfig() != null) {
for (Map.Entry<String, String> entry : fedModel.getConfig().entrySet()) {
model.getConfig().putSingle(entry.getKey(), entry.getValue());
}
}
return model;
}
public static ComponentModel convertFedMapperToComponent(RealmModel realm, ComponentModel parent, UserFederationMapperRepresentation rep, String newMapperType) {
ComponentModel mapper = new ComponentModel();
mapper.setId(rep.getId());
mapper.setName(rep.getName());
mapper.setProviderId(rep.getFederationMapperType());
mapper.setProviderType(newMapperType);
mapper.setParentId(parent.getId());
if (rep.getConfig() != null) {
for (Map.Entry<String, String> entry : rep.getConfig().entrySet()) {
mapper.getConfig().putSingle(entry.getKey(), entry.getValue());
}
}
return mapper;
}
// Roles
public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) {
RoleModel role = roleRep.getId()!=null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm.addRole(roleRep.getName());
if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription());
boolean scopeParamRequired = roleRep.isScopeParamRequired() == null ? false : roleRep.isScopeParamRequired();
role.setScopeParamRequired(scopeParamRequired);
}
private static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm) {
if (roleRep.getComposites() == null) return;
if (roleRep.getComposites().getRealm() != null) {
for (String roleStr : roleRep.getComposites().getRealm()) {
RoleModel realmRole = realm.getRole(roleStr);
if (realmRole == null) throw new RuntimeException("Unable to find composite realm role: " + roleStr);
role.addCompositeRole(realmRole);
}
}
if (roleRep.getComposites().getClient() != null) {
for (Map.Entry<String, List<String>> entry : roleRep.getComposites().getClient().entrySet()) {
ClientModel client = realm.getClientByClientId(entry.getKey());
if (client == null) {
throw new RuntimeException("App doesn't exist in role definitions: " + roleRep.getName());
}
for (String roleStr : entry.getValue()) {
RoleModel clientRole = client.getRole(roleStr);
if (clientRole == null) throw new RuntimeException("Unable to find composite client role: " + roleStr);
role.addCompositeRole(clientRole);
}
}
}
}
// CLIENTS
private static Map<String, ClientModel> createClients(KeycloakSession session, RealmRepresentation rep, RealmModel realm) {
Map<String, ClientModel> appMap = new HashMap<String, ClientModel>();
for (ClientRepresentation resourceRep : rep.getClients()) {
ClientModel app = createClient(session, realm, resourceRep, false);
appMap.put(app.getClientId(), app);
}
return appMap;
}
/**
* Does not create scope or role mappings!
*
* @param realm
* @param resourceRep
* @return
*/
public static ClientModel createClient(KeycloakSession session, RealmModel realm, ClientRepresentation resourceRep, boolean addDefaultRoles) {
logger.debug("Create client: {0}" + resourceRep.getClientId());
ClientModel client = resourceRep.getId()!=null ? realm.addClient(resourceRep.getId(), resourceRep.getClientId()) : realm.addClient(resourceRep.getClientId());
if (resourceRep.getName() != null) client.setName(resourceRep.getName());
if(resourceRep.getDescription() != null) client.setDescription(resourceRep.getDescription());
if (resourceRep.isEnabled() != null) client.setEnabled(resourceRep.isEnabled());
client.setManagementUrl(resourceRep.getAdminUrl());
if (resourceRep.isSurrogateAuthRequired() != null)
client.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired());
if (resourceRep.getRootUrl() != null) client.setRootUrl(resourceRep.getRootUrl());
if (resourceRep.getBaseUrl() != null) client.setBaseUrl(resourceRep.getBaseUrl());
if (resourceRep.isBearerOnly() != null) client.setBearerOnly(resourceRep.isBearerOnly());
if (resourceRep.isConsentRequired() != null) client.setConsentRequired(resourceRep.isConsentRequired());
// Backwards compatibility only
if (resourceRep.isDirectGrantsOnly() != null) {
logger.warn("Using deprecated 'directGrantsOnly' configuration in JSON representation. It will be removed in future versions");
client.setStandardFlowEnabled(!resourceRep.isDirectGrantsOnly());
client.setDirectAccessGrantsEnabled(resourceRep.isDirectGrantsOnly());
}
if (resourceRep.isStandardFlowEnabled() != null) client.setStandardFlowEnabled(resourceRep.isStandardFlowEnabled());
if (resourceRep.isImplicitFlowEnabled() != null) client.setImplicitFlowEnabled(resourceRep.isImplicitFlowEnabled());
if (resourceRep.isDirectAccessGrantsEnabled() != null) client.setDirectAccessGrantsEnabled(resourceRep.isDirectAccessGrantsEnabled());
if (resourceRep.isServiceAccountsEnabled() != null) client.setServiceAccountsEnabled(resourceRep.isServiceAccountsEnabled());
if (resourceRep.isPublicClient() != null) client.setPublicClient(resourceRep.isPublicClient());
if (resourceRep.isFrontchannelLogout() != null) client.setFrontchannelLogout(resourceRep.isFrontchannelLogout());
if (resourceRep.getProtocol() != null) client.setProtocol(resourceRep.getProtocol());
if (resourceRep.getNodeReRegistrationTimeout() != null) {
client.setNodeReRegistrationTimeout(resourceRep.getNodeReRegistrationTimeout());
} else {
client.setNodeReRegistrationTimeout(-1);
}
if (resourceRep.getNotBefore() != null) {
client.setNotBefore(resourceRep.getNotBefore());
}
if (resourceRep.getClientAuthenticatorType() != null) {
client.setClientAuthenticatorType(resourceRep.getClientAuthenticatorType());
} else {
client.setClientAuthenticatorType(KeycloakModelUtils.getDefaultClientAuthenticatorType());
}
client.setSecret(resourceRep.getSecret());
if (client.getSecret() == null) {
KeycloakModelUtils.generateSecret(client);
}
if (resourceRep.getAttributes() != null) {
for (Map.Entry<String, String> entry : resourceRep.getAttributes().entrySet()) {
client.setAttribute(entry.getKey(), entry.getValue());
}
}
if (resourceRep.getRedirectUris() != null) {
for (String redirectUri : resourceRep.getRedirectUris()) {
client.addRedirectUri(redirectUri);
}
}
if (resourceRep.getWebOrigins() != null) {
for (String webOrigin : resourceRep.getWebOrigins()) {
logger.debugv("Client: {0} webOrigin: {1}", resourceRep.getClientId(), webOrigin);
client.addWebOrigin(webOrigin);
}
} else {
// add origins from redirect uris
if (resourceRep.getRedirectUris() != null) {
Set<String> origins = new HashSet<String>();
for (String redirectUri : resourceRep.getRedirectUris()) {
logger.debugv("add redirect-uri to origin: {0}", redirectUri);
if (redirectUri.startsWith("http")) {
String origin = UriUtils.getOrigin(redirectUri);
logger.debugv("adding default client origin: {0}" , origin);
origins.add(origin);
}
}
if (origins.size() > 0) {
client.setWebOrigins(origins);
}
}
}
if (resourceRep.getRegisteredNodes() != null) {
for (Map.Entry<String, Integer> entry : resourceRep.getRegisteredNodes().entrySet()) {
client.registerNode(entry.getKey(), entry.getValue());
}
}
if (addDefaultRoles && resourceRep.getDefaultRoles() != null) {
client.updateDefaultRoles(resourceRep.getDefaultRoles());
}
if (resourceRep.getProtocolMappers() != null) {
// first, remove all default/built in mappers
Set<ProtocolMapperModel> mappers = client.getProtocolMappers();
for (ProtocolMapperModel mapper : mappers) client.removeProtocolMapper(mapper);
for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) {
client.addProtocolMapper(toModel(mapper));
}
MigrationUtils.updateProtocolMappers(client);
}
if (resourceRep.getClientTemplate() != null) {
for (ClientTemplateModel template : realm.getClientTemplates()) {
if (template.getName().equals(resourceRep.getClientTemplate())) {
client.setClientTemplate(template);
break;
}
MigrationUtils.updateProtocolMappers(template);
}
}
if (resourceRep.isFullScopeAllowed() != null) {
client.setFullScopeAllowed(resourceRep.isFullScopeAllowed());
} else {
if (client.getClientTemplate() != null) {
client.setFullScopeAllowed(!client.isConsentRequired() && client.getClientTemplate().isFullScopeAllowed());
} else {
client.setFullScopeAllowed(!client.isConsentRequired());
}
}
if (resourceRep.isUseTemplateConfig() != null) client.setUseTemplateConfig(resourceRep.isUseTemplateConfig());
else client.setUseTemplateConfig(false); // default to false for now
if (resourceRep.isUseTemplateScope() != null) client.setUseTemplateScope(resourceRep.isUseTemplateScope());
else client.setUseTemplateScope(resourceRep.getClientTemplate() != null);
if (resourceRep.isUseTemplateMappers() != null) client.setUseTemplateMappers(resourceRep.isUseTemplateMappers());
else client.setUseTemplateMappers(resourceRep.getClientTemplate() != null);
client.updateClient();
return client;
}
public static void updateClient(ClientRepresentation rep, ClientModel resource) {
if (rep.getClientId() != null) resource.setClientId(rep.getClientId());
if (rep.getName() != null) resource.setName(rep.getName());
if (rep.getDescription() != null) resource.setDescription(rep.getDescription());
if (rep.isEnabled() != null) resource.setEnabled(rep.isEnabled());
if (rep.isBearerOnly() != null) resource.setBearerOnly(rep.isBearerOnly());
if (rep.isConsentRequired() != null) resource.setConsentRequired(rep.isConsentRequired());
if (rep.isStandardFlowEnabled() != null) resource.setStandardFlowEnabled(rep.isStandardFlowEnabled());
if (rep.isImplicitFlowEnabled() != null) resource.setImplicitFlowEnabled(rep.isImplicitFlowEnabled());
if (rep.isDirectAccessGrantsEnabled() != null) resource.setDirectAccessGrantsEnabled(rep.isDirectAccessGrantsEnabled());
if (rep.isServiceAccountsEnabled() != null) resource.setServiceAccountsEnabled(rep.isServiceAccountsEnabled());
if (rep.isPublicClient() != null) resource.setPublicClient(rep.isPublicClient());
if (rep.isFullScopeAllowed() != null) resource.setFullScopeAllowed(rep.isFullScopeAllowed());
if (rep.isFrontchannelLogout() != null) resource.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.getRootUrl() != null) resource.setRootUrl(rep.getRootUrl());
if (rep.getAdminUrl() != null) resource.setManagementUrl(rep.getAdminUrl());
if (rep.getBaseUrl() != null) resource.setBaseUrl(rep.getBaseUrl());
if (rep.isSurrogateAuthRequired() != null) resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired());
if (rep.getNodeReRegistrationTimeout() != null) resource.setNodeReRegistrationTimeout(rep.getNodeReRegistrationTimeout());
if (rep.getClientAuthenticatorType() != null) resource.setClientAuthenticatorType(rep.getClientAuthenticatorType());
if (rep.getProtocol() != null) resource.setProtocol(rep.getProtocol());
if (rep.getAttributes() != null) {
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
resource.setAttribute(entry.getKey(), entry.getValue());
}
}
if (rep.getNotBefore() != null) {
resource.setNotBefore(rep.getNotBefore());
}
if (rep.getDefaultRoles() != null) {
resource.updateDefaultRoles(rep.getDefaultRoles());
}
List<String> redirectUris = rep.getRedirectUris();
if (redirectUris != null) {
resource.setRedirectUris(new HashSet<String>(redirectUris));
}
List<String> webOrigins = rep.getWebOrigins();
if (webOrigins != null) {
resource.setWebOrigins(new HashSet<String>(webOrigins));
}
if (rep.getRegisteredNodes() != null) {
for (Map.Entry<String, Integer> entry : rep.getRegisteredNodes().entrySet()) {
resource.registerNode(entry.getKey(), entry.getValue());
}
}
if (rep.isUseTemplateConfig() != null) resource.setUseTemplateConfig(rep.isUseTemplateConfig());
if (rep.isUseTemplateScope() != null) resource.setUseTemplateScope(rep.isUseTemplateScope());
if (rep.isUseTemplateMappers() != null) resource.setUseTemplateMappers(rep.isUseTemplateMappers());
if (rep.getClientTemplate() != null) {
if (rep.getClientTemplate().equals(ClientTemplateRepresentation.NONE)) {
resource.setClientTemplate(null);
} else {
RealmModel realm = resource.getRealm();
for (ClientTemplateModel template : realm.getClientTemplates()) {
if (template.getName().equals(rep.getClientTemplate())) {
resource.setClientTemplate(template);
if (rep.isUseTemplateConfig() == null) resource.setUseTemplateConfig(true);
if (rep.isUseTemplateScope() == null) resource.setUseTemplateScope(true);
if (rep.isUseTemplateMappers() == null) resource.setUseTemplateMappers(true);
break;
}
}
}
}
resource.updateClient();
}
// CLIENT TEMPLATES
private static Map<String, ClientTemplateModel> createClientTemplates(KeycloakSession session, RealmRepresentation rep, RealmModel realm) {
Map<String, ClientTemplateModel> appMap = new HashMap<>();
for (ClientTemplateRepresentation resourceRep : rep.getClientTemplates()) {
ClientTemplateModel app = createClientTemplate(session, realm, resourceRep);
appMap.put(app.getName(), app);
}
return appMap;
}
public static ClientTemplateModel createClientTemplate(KeycloakSession session, RealmModel realm, ClientTemplateRepresentation resourceRep) {
logger.debug("Create client template: {0}" + resourceRep.getName());
ClientTemplateModel client = resourceRep.getId()!=null ? realm.addClientTemplate(resourceRep.getId(), resourceRep.getName()) : realm.addClientTemplate(resourceRep.getName());
if (resourceRep.getName() != null) client.setName(resourceRep.getName());
if(resourceRep.getDescription() != null) client.setDescription(resourceRep.getDescription());
if (resourceRep.getProtocol() != null) client.setProtocol(resourceRep.getProtocol());
if (resourceRep.isFullScopeAllowed() != null) client.setFullScopeAllowed(resourceRep.isFullScopeAllowed());
if (resourceRep.getProtocolMappers() != null) {
// first, remove all default/built in mappers
Set<ProtocolMapperModel> mappers = client.getProtocolMappers();
for (ProtocolMapperModel mapper : mappers) client.removeProtocolMapper(mapper);
for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) {
client.addProtocolMapper(toModel(mapper));
}
}
if (resourceRep.isBearerOnly() != null) client.setBearerOnly(resourceRep.isBearerOnly());
if (resourceRep.isConsentRequired() != null) client.setConsentRequired(resourceRep.isConsentRequired());
if (resourceRep.isStandardFlowEnabled() != null) client.setStandardFlowEnabled(resourceRep.isStandardFlowEnabled());
if (resourceRep.isImplicitFlowEnabled() != null) client.setImplicitFlowEnabled(resourceRep.isImplicitFlowEnabled());
if (resourceRep.isDirectAccessGrantsEnabled() != null) client.setDirectAccessGrantsEnabled(resourceRep.isDirectAccessGrantsEnabled());
if (resourceRep.isServiceAccountsEnabled() != null) client.setServiceAccountsEnabled(resourceRep.isServiceAccountsEnabled());
if (resourceRep.isPublicClient() != null) client.setPublicClient(resourceRep.isPublicClient());
if (resourceRep.isFrontchannelLogout() != null) client.setFrontchannelLogout(resourceRep.isFrontchannelLogout());
if (resourceRep.getAttributes() != null) {
for (Map.Entry<String, String> entry : resourceRep.getAttributes().entrySet()) {
client.setAttribute(entry.getKey(), entry.getValue());
}
}
return client;
}
public static void updateClientTemplate(ClientTemplateRepresentation rep, ClientTemplateModel resource) {
if (rep.getName() != null) resource.setName(rep.getName());
if (rep.getDescription() != null) resource.setDescription(rep.getDescription());
if (rep.isFullScopeAllowed() != null) {
resource.setFullScopeAllowed(rep.isFullScopeAllowed());
}
if (rep.getProtocol() != null) resource.setProtocol(rep.getProtocol());
if (rep.isBearerOnly() != null) resource.setBearerOnly(rep.isBearerOnly());
if (rep.isConsentRequired() != null) resource.setConsentRequired(rep.isConsentRequired());
if (rep.isStandardFlowEnabled() != null) resource.setStandardFlowEnabled(rep.isStandardFlowEnabled());
if (rep.isImplicitFlowEnabled() != null) resource.setImplicitFlowEnabled(rep.isImplicitFlowEnabled());
if (rep.isDirectAccessGrantsEnabled() != null) resource.setDirectAccessGrantsEnabled(rep.isDirectAccessGrantsEnabled());
if (rep.isServiceAccountsEnabled() != null) resource.setServiceAccountsEnabled(rep.isServiceAccountsEnabled());
if (rep.isPublicClient() != null) resource.setPublicClient(rep.isPublicClient());
if (rep.isFullScopeAllowed() != null) resource.setFullScopeAllowed(rep.isFullScopeAllowed());
if (rep.isFrontchannelLogout() != null) resource.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.getAttributes() != null) {
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
resource.setAttribute(entry.getKey(), entry.getValue());
}
}
}
public static long getClaimsMask(ClaimRepresentation rep) {
long mask = ClaimMask.ALL;
if (rep.getAddress()) {
mask |= ClaimMask.ADDRESS;
} else {
mask &= ~ClaimMask.ADDRESS;
}
if (rep.getEmail()) {
mask |= ClaimMask.EMAIL;
} else {
mask &= ~ClaimMask.EMAIL;
}
if (rep.getGender()) {
mask |= ClaimMask.GENDER;
} else {
mask &= ~ClaimMask.GENDER;
}
if (rep.getLocale()) {
mask |= ClaimMask.LOCALE;
} else {
mask &= ~ClaimMask.LOCALE;
}
if (rep.getName()) {
mask |= ClaimMask.NAME;
} else {
mask &= ~ClaimMask.NAME;
}
if (rep.getPhone()) {
mask |= ClaimMask.PHONE;
} else {
mask &= ~ClaimMask.PHONE;
}
if (rep.getPicture()) {
mask |= ClaimMask.PICTURE;
} else {
mask &= ~ClaimMask.PICTURE;
}
if (rep.getProfile()) {
mask |= ClaimMask.PROFILE;
} else {
mask &= ~ClaimMask.PROFILE;
}
if (rep.getUsername()) {
mask |= ClaimMask.USERNAME;
} else {
mask &= ~ClaimMask.USERNAME;
}
if (rep.getWebsite()) {
mask |= ClaimMask.WEBSITE;
} else {
mask &= ~ClaimMask.WEBSITE;
}
return mask;
}
// Scope mappings
public static void createClientScopeMappings(RealmModel realm, ClientModel clientModel, List<ScopeMappingRepresentation> mappings) {
for (ScopeMappingRepresentation mapping : mappings) {
ScopeContainerModel scopeContainer = getScopeContainerHavingScope(realm, mapping);
for (String roleString : mapping.getRoles()) {
RoleModel role = clientModel.getRole(roleString.trim());
if (role == null) {
role = clientModel.addRole(roleString.trim());
}
scopeContainer.addScopeMapping(role);
}
}
}
private static ScopeContainerModel getScopeContainerHavingScope(RealmModel realm, ScopeMappingRepresentation scope) {
if (scope.getClient() != null) {
ClientModel client = realm.getClientByClientId(scope.getClient());
if (client == null) {
throw new RuntimeException("Unknown client specification in scope mappings: " + scope.getClient());
}
return client;
} else if (scope.getClientTemplate() != null) {
ClientTemplateModel clientTemplate = KeycloakModelUtils.getClientTemplateByName(realm, scope.getClientTemplate());
if (clientTemplate == null) {
throw new RuntimeException("Unknown clientTemplate specification in scope mappings: " + scope.getClientTemplate());
}
return clientTemplate;
} else {
throw new RuntimeException("Either client or clientTemplate needs to be specified in scope mappings");
}
}
// Users
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
convertDeprecatedSocialProviders(userRep);
// Import users just to user storage. Don't federate
UserModel user = session.userLocalStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false, false);
user.setEnabled(userRep.isEnabled() != null && userRep.isEnabled());
user.setCreatedTimestamp(userRep.getCreatedTimestamp());
user.setEmail(userRep.getEmail());
if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
user.setFirstName(userRep.getFirstName());
user.setLastName(userRep.getLastName());
user.setFederationLink(userRep.getFederationLink());
if (userRep.getAttributes() != null) {
for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
List<String> value = entry.getValue();
if (value != null) {
user.setAttribute(entry.getKey(), new ArrayList<>(value));
}
}
}
if (userRep.getRequiredActions() != null) {
for (String requiredAction : userRep.getRequiredActions()) {
user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction));
}
}
createCredentials(userRep, session, newRealm, user);
if (userRep.getFederatedIdentities() != null) {
for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
session.users().addFederatedIdentity(newRealm, user, mappingModel);
}
}
createRoleMappings(userRep, user, newRealm);
if (userRep.getClientConsents() != null) {
for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
UserConsentModel consentModel = toModel(newRealm, consentRep);
session.users().addConsent(newRealm, user.getId(), consentModel);
}
}
if (userRep.getServiceAccountClientId() != null) {
String clientId = userRep.getServiceAccountClientId();
ClientModel client = newRealm.getClientByClientId(clientId);
if (client == null) {
throw new RuntimeException("Unable to find client specified for service account link. Client: " + clientId);
}
user.setServiceAccountClientLink(client.getId());;
}
if (userRep.getGroups() != null) {
for (String path : userRep.getGroups()) {
GroupModel group = KeycloakModelUtils.findGroupByPath(newRealm, path);
if (group == null) {
throw new RuntimeException("Unable to find group specified by path: " + path);
}
user.joinGroup(group);
}
}
return user;
}
public static void createCredentials(UserRepresentation userRep, KeycloakSession session, RealmModel realm,UserModel user) {
if (userRep.getCredentials() != null) {
for (CredentialRepresentation cred : userRep.getCredentials()) {
updateCredential(session, realm, user, cred);
}
}
}
// Detect if it is "plain-text" or "hashed" representation and update model according to it
private static void updateCredential(KeycloakSession session, RealmModel realm, UserModel user, CredentialRepresentation cred) {
if (cred.getValue() != null) {
UserCredentialModel plainTextCred = convertCredential(cred);
session.userCredentialManager().updateCredential(realm, user, plainTextCred);
} else {
CredentialModel hashedCred = new CredentialModel();
hashedCred.setType(cred.getType());
hashedCred.setDevice(cred.getDevice());
if (cred.getHashIterations() != null) hashedCred.setHashIterations(cred.getHashIterations());
try {
if (cred.getSalt() != null) hashedCred.setSalt(Base64.decode(cred.getSalt()));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
hashedCred.setValue(cred.getHashedSaltedValue());
if (cred.getCounter() != null) hashedCred.setCounter(cred.getCounter());
if (cred.getDigits() != null) hashedCred.setDigits(cred.getDigits());
if (cred.getAlgorithm() != null) {
// Could happen when migrating from some early version
if ((UserCredentialModel.PASSWORD.equals(cred.getType()) || UserCredentialModel.PASSWORD_HISTORY.equals(cred.getType())) &&
(cred.getAlgorithm().equals(HmacOTP.HMAC_SHA1))) {
hashedCred.setAlgorithm("pbkdf2");
} else {
hashedCred.setAlgorithm(cred.getAlgorithm());
}
} else {
if (UserCredentialModel.PASSWORD.equals(cred.getType()) || UserCredentialModel.PASSWORD_HISTORY.equals(cred.getType())) {
hashedCred.setAlgorithm("pbkdf2");
} else if (UserCredentialModel.isOtp(cred.getType())) {
hashedCred.setAlgorithm(HmacOTP.HMAC_SHA1);
}
}
if (cred.getPeriod() != null) hashedCred.setPeriod(cred.getPeriod());
if (cred.getDigits() == null && UserCredentialModel.isOtp(cred.getType())) {
hashedCred.setDigits(6);
}
if (cred.getPeriod() == null && UserCredentialModel.TOTP.equals(cred.getType())) {
hashedCred.setPeriod(30);
}
hashedCred.setCreatedDate(cred.getCreatedDate());
session.userCredentialManager().createCredential(realm, user, hashedCred);
}
}
public static UserCredentialModel convertCredential(CredentialRepresentation cred) {
UserCredentialModel credential = new UserCredentialModel();
credential.setType(cred.getType());
credential.setValue(cred.getValue());
return credential;
}
public static CredentialModel toModel(CredentialRepresentation cred) {
CredentialModel model = new CredentialModel();
model.setHashIterations(cred.getHashIterations());
model.setCreatedDate(cred.getCreatedDate());
model.setType(cred.getType());
model.setDigits(cred.getDigits());
model.setConfig(cred.getConfig());
model.setDevice(cred.getDevice());
model.setAlgorithm(cred.getAlgorithm());
model.setCounter(cred.getCounter());
model.setPeriod(cred.getPeriod());
if (cred.getSalt() != null) {
try {
model.setSalt(Base64.decode(cred.getSalt()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
model.setValue(cred.getValue());
if (cred.getHashedSaltedValue() != null) {
model.setValue(cred.getHashedSaltedValue());
}
return model;
}
// Role mappings
public static void createRoleMappings(UserRepresentation userRep, UserModel user, RealmModel realm) {
if (userRep.getRealmRoles() != null) {
for (String roleString : userRep.getRealmRoles()) {
RoleModel role = realm.getRole(roleString.trim());
if (role == null) {
role = realm.addRole(roleString.trim());
}
user.grantRole(role);
}
}
if (userRep.getClientRoles() != null) {
for (Map.Entry<String, List<String>> entry : userRep.getClientRoles().entrySet()) {
ClientModel client = realm.getClientByClientId(entry.getKey());
if (client == null) {
throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
}
createClientRoleMappings(client, user, entry.getValue());
}
}
}
public static void createClientRoleMappings(ClientModel clientModel, UserModel user, List<String> roleNames) {
if (user == null) {
throw new RuntimeException("User not found");
}
for (String roleName : roleNames) {
RoleModel role = clientModel.getRole(roleName.trim());
if (role == null) {
role = clientModel.addRole(roleName.trim());
}
user.grantRole(role);
}
}
private static void importIdentityProviders(RealmRepresentation rep, RealmModel newRealm) {
if (rep.getIdentityProviders() != null) {
for (IdentityProviderRepresentation representation : rep.getIdentityProviders()) {
newRealm.addIdentityProvider(toModel(newRealm, representation));
}
}
}
private static void importIdentityProviderMappers(RealmRepresentation rep, RealmModel newRealm) {
if (rep.getIdentityProviderMappers() != null) {
for (IdentityProviderMapperRepresentation representation : rep.getIdentityProviderMappers()) {
newRealm.addIdentityProviderMapper(toModel(representation));
}
}
}
public static IdentityProviderModel toModel(RealmModel realm, IdentityProviderRepresentation representation) {
IdentityProviderModel identityProviderModel = new IdentityProviderModel();
identityProviderModel.setInternalId(representation.getInternalId());
identityProviderModel.setAlias(representation.getAlias());
identityProviderModel.setDisplayName(representation.getDisplayName());
identityProviderModel.setProviderId(representation.getProviderId());
identityProviderModel.setEnabled(representation.isEnabled());
identityProviderModel.setTrustEmail(representation.isTrustEmail());
identityProviderModel.setAuthenticateByDefault(representation.isAuthenticateByDefault());
identityProviderModel.setStoreToken(representation.isStoreToken());
identityProviderModel.setAddReadTokenRoleOnCreate(representation.isAddReadTokenRoleOnCreate());
identityProviderModel.setConfig(new HashMap<>(representation.getConfig()));
String flowAlias = representation.getFirstBrokerLoginFlowAlias();
if (flowAlias == null) {
flowAlias = DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW;
}
AuthenticationFlowModel flowModel = realm.getFlowByAlias(flowAlias);
if (flowModel == null) {
throw new ModelException("No available authentication flow with alias: " + flowAlias);
}
identityProviderModel.setFirstBrokerLoginFlowId(flowModel.getId());
flowAlias = representation.getPostBrokerLoginFlowAlias();
if (flowAlias == null || flowAlias.trim().length() == 0) {
identityProviderModel.setPostBrokerLoginFlowId(null);
} else {
flowModel = realm.getFlowByAlias(flowAlias);
if (flowModel == null) {
throw new ModelException("No available authentication flow with alias: " + flowAlias);
}
identityProviderModel.setPostBrokerLoginFlowId(flowModel.getId());
}
return identityProviderModel;
}
public static ProtocolMapperModel toModel(ProtocolMapperRepresentation rep) {
ProtocolMapperModel model = new ProtocolMapperModel();
model.setId(rep.getId());
model.setName(rep.getName());
model.setConsentRequired(rep.isConsentRequired());
model.setConsentText(rep.getConsentText());
model.setProtocol(rep.getProtocol());
model.setProtocolMapper(rep.getProtocolMapper());
model.setConfig(rep.getConfig());
return model;
}
public static IdentityProviderMapperModel toModel(IdentityProviderMapperRepresentation rep) {
IdentityProviderMapperModel model = new IdentityProviderMapperModel();
model.setId(rep.getId());
model.setName(rep.getName());
model.setIdentityProviderAlias(rep.getIdentityProviderAlias());
model.setIdentityProviderMapper(rep.getIdentityProviderMapper());
model.setConfig(rep.getConfig());
return model;
}
public static UserConsentModel toModel(RealmModel newRealm, UserConsentRepresentation consentRep) {
ClientModel client = newRealm.getClientByClientId(consentRep.getClientId());
if (client == null) {
throw new RuntimeException("Unable to find client consent mappings for client: " + consentRep.getClientId());
}
UserConsentModel consentModel = new UserConsentModel(client);
consentModel.setCreatedDate(consentRep.getCreatedDate());
consentModel.setLastUpdatedDate(consentRep.getLastUpdatedDate());
if (consentRep.getGrantedRealmRoles() != null) {
for (String roleName : consentRep.getGrantedRealmRoles()) {
RoleModel role = newRealm.getRole(roleName);
if (role == null) {
throw new RuntimeException("Unable to find realm role referenced in consent mappings of user. Role name: " + roleName);
}
consentModel.addGrantedRole(role);
}
}
if (consentRep.getGrantedClientRoles() != null) {
for (Map.Entry<String, List<String>> entry : consentRep.getGrantedClientRoles().entrySet()) {
String clientId2 = entry.getKey();
ClientModel client2 = newRealm.getClientByClientId(clientId2);
if (client2 == null) {
throw new RuntimeException("Unable to find client referenced in consent mappings. Client ID: " + clientId2);
}
for (String clientRoleName : entry.getValue()) {
RoleModel clientRole = client2.getRole(clientRoleName);
if (clientRole == null) {
throw new RuntimeException("Unable to find client role referenced in consent mappings of user. Role name: " + clientRole + ", Client: " + clientId2);
}
consentModel.addGrantedRole(clientRole);
}
}
}
if (consentRep.getGrantedProtocolMappers() != null) {
for (Map.Entry<String, List<String>> protocolEntry : consentRep.getGrantedProtocolMappers().entrySet()) {
String protocol = protocolEntry.getKey();
for (String protocolMapperName : protocolEntry.getValue()) {
ProtocolMapperModel protocolMapper = client.getProtocolMapperByName(protocol, protocolMapperName);
if (protocolMapper == null) {
throw new RuntimeException("Unable to find protocol mapper for protocol " + protocol + ", mapper name " + protocolMapperName);
}
consentModel.addGrantedProtocolMapper(protocolMapper);
}
}
}
return consentModel;
}
public static AuthenticationFlowModel toModel(AuthenticationFlowRepresentation rep) {
AuthenticationFlowModel model = new AuthenticationFlowModel();
model.setId(rep.getId());
model.setBuiltIn(rep.isBuiltIn());
model.setTopLevel(rep.isTopLevel());
model.setProviderId(rep.getProviderId());
model.setAlias(rep.getAlias());
model.setDescription(rep.getDescription());
return model;
}
public static AuthenticationExecutionModel toModel(RealmModel realm, AuthenticationExecutionExportRepresentation rep) {
AuthenticationExecutionModel model = new AuthenticationExecutionModel();
if (rep.getAuthenticatorConfig() != null) {
AuthenticatorConfigModel config = realm.getAuthenticatorConfigByAlias(rep.getAuthenticatorConfig());
model.setAuthenticatorConfig(config.getId());
}
model.setAuthenticator(rep.getAuthenticator());
model.setAuthenticatorFlow(rep.isAutheticatorFlow());
if (rep.getFlowAlias() != null) {
AuthenticationFlowModel flow = realm.getFlowByAlias(rep.getFlowAlias());
model.setFlowId(flow.getId());
}
model.setPriority(rep.getPriority());
model.setRequirement(AuthenticationExecutionModel.Requirement.valueOf(rep.getRequirement()));
return model;
}
public static AuthenticationExecutionModel toModel(RealmModel realm, AuthenticationExecutionRepresentation rep) {
AuthenticationExecutionModel model = new AuthenticationExecutionModel();
model.setId(rep.getId());
model.setFlowId(rep.getFlowId());
model.setAuthenticator(rep.getAuthenticator());
model.setPriority(rep.getPriority());
model.setParentFlow(rep.getParentFlow());
model.setAuthenticatorFlow(rep.isAutheticatorFlow());
model.setRequirement(AuthenticationExecutionModel.Requirement.valueOf(rep.getRequirement()));
if (rep.getAuthenticatorConfig() != null) {
AuthenticatorConfigModel cfg = realm.getAuthenticatorConfigByAlias(rep.getAuthenticatorConfig());
model.setAuthenticatorConfig(cfg.getId());
}
return model;
}
public static AuthenticatorConfigModel toModel(AuthenticatorConfigRepresentation rep) {
AuthenticatorConfigModel model = new AuthenticatorConfigModel();
model.setAlias(rep.getAlias());
model.setConfig(rep.getConfig());
return model;
}
public static RequiredActionProviderModel toModel(RequiredActionProviderRepresentation rep) {
RequiredActionProviderModel model = new RequiredActionProviderModel();
model.setConfig(rep.getConfig());
model.setDefaultAction(rep.isDefaultAction());
model.setEnabled(rep.isEnabled());
model.setProviderId(rep.getProviderId());
model.setName(rep.getName());
model.setAlias(rep.getAlias());
return model;
}
public static ComponentModel toModel(KeycloakSession session, ComponentRepresentation rep) {
ComponentModel model = new ComponentModel();
model.setParentId(rep.getParentId());
model.setProviderType(rep.getProviderType());
model.setProviderId(rep.getProviderId());
model.setConfig(new MultivaluedHashMap<>());
model.setName(rep.getName());
model.setSubType(rep.getSubType());
if (rep.getConfig() != null) {
Set<String> keys = new HashSet<>(rep.getConfig().keySet());
for (String k : keys) {
List<String> values = rep.getConfig().get(k);
if (values != null) {
ListIterator<String> itr = values.listIterator();
while (itr.hasNext()) {
String v = itr.next();
if (v == null || v.trim().isEmpty()) {
itr.remove();
}
}
if (!values.isEmpty()) {
model.getConfig().put(k, values);
}
}
}
}
return model;
}
public static void updateComponent(KeycloakSession session, ComponentRepresentation rep, ComponentModel component, boolean internal) {
if (rep.getName() != null) {
component.setName(rep.getName());
}
if (rep.getParentId() != null) {
component.setParentId(rep.getParentId());
}
if (rep.getProviderType() != null) {
component.setProviderType(rep.getProviderType());
}
if (rep.getProviderId() != null) {
component.setProviderId(rep.getProviderId());
}
if (rep.getSubType() != null) {
component.setSubType(rep.getSubType());
}
Map<String, ProviderConfigProperty> providerConfiguration = null;
if (!internal) {
providerConfiguration = ComponentUtil.getComponentConfigProperties(session, component);
}
if (rep.getConfig() != null) {
Set<String> keys = new HashSet<>(rep.getConfig().keySet());
for (String k : keys) {
if (!internal && !providerConfiguration.containsKey(k)) {
break;
}
List<String> values = rep.getConfig().get(k);
if (values == null || values.isEmpty() || values.get(0) == null || values.get(0).trim().isEmpty()) {
component.getConfig().remove(k);
} else {
ListIterator<String> itr = values.listIterator();
while (itr.hasNext()) {
String v = itr.next();
if (v == null || v.trim().isEmpty() || v.equals(ComponentRepresentation.SECRET_VALUE)) {
itr.remove();
}
}
if (!values.isEmpty()) {
component.getConfig().put(k, values);
}
}
}
}
}
public static void importAuthorizationSettings(ClientRepresentation clientRepresentation, ClientModel client, KeycloakSession session) {
if (Boolean.TRUE.equals(clientRepresentation.getAuthorizationServicesEnabled())) {
AuthorizationProviderFactory authorizationFactory = (AuthorizationProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(AuthorizationProvider.class);
AuthorizationProvider authorization = authorizationFactory.create(session, client.getRealm());
client.setServiceAccountsEnabled(true);
client.setBearerOnly(false);
client.setPublicClient(false);
ResourceServerRepresentation rep = clientRepresentation.getAuthorizationSettings();
if (rep == null) {
rep = new ResourceServerRepresentation();
}
rep.setClientId(client.getId());
toModel(rep, authorization);
}
}
public static void toModel(ResourceServerRepresentation rep, AuthorizationProvider authorization) {
ResourceServerStore resourceServerStore = authorization.getStoreFactory().getResourceServerStore();
ResourceServer resourceServer;
ResourceServer existing = resourceServerStore.findByClient(rep.getClientId());
if (existing == null) {
resourceServer = resourceServerStore.create(rep.getClientId());
resourceServer.setAllowRemoteResourceManagement(true);
resourceServer.setPolicyEnforcementMode(PolicyEnforcementMode.ENFORCING);
} else {
resourceServer = existing;
}
resourceServer.setPolicyEnforcementMode(rep.getPolicyEnforcementMode());
resourceServer.setAllowRemoteResourceManagement(rep.isAllowRemoteResourceManagement());
StoreFactory storeFactory = authorization.getStoreFactory();
ScopeStore scopeStore = storeFactory.getScopeStore();
rep.getScopes().forEach(scope -> {
toModel(scope, resourceServer, authorization);
});
KeycloakSession session = authorization.getKeycloakSession();
RealmModel realm = authorization.getRealm();
rep.getResources().forEach(resourceRepresentation -> {
ResourceOwnerRepresentation owner = resourceRepresentation.getOwner();
if (owner == null) {
owner = new ResourceOwnerRepresentation();
resourceRepresentation.setOwner(owner);
}
owner.setId(resourceServer.getClientId());
if (owner.getName() != null) {
UserModel user = session.users().getUserByUsername(owner.getName(), realm);
if (user != null) {
owner.setId(user.getId());
}
}
toModel(resourceRepresentation, resourceServer, authorization);
});
importPolicies(authorization, resourceServer, rep.getPolicies(), null);
}
private static Policy importPolicies(AuthorizationProvider authorization, ResourceServer resourceServer, List<PolicyRepresentation> policiesToImport, String parentPolicyName) {
StoreFactory storeFactory = authorization.getStoreFactory();
KeycloakSession session = authorization.getKeycloakSession();
RealmModel realm = authorization.getRealm();
for (PolicyRepresentation policyRepresentation : policiesToImport) {
if (parentPolicyName != null && !parentPolicyName.equals(policyRepresentation.getName())) {
continue;
}
Map<String, String> config = policyRepresentation.getConfig();
String roles = config.get("roles");
if (roles != null && !roles.isEmpty()) {
try {
List<Map> rolesMap = JsonSerialization.readValue(roles, List.class);
config.put("roles", JsonSerialization.writeValueAsString(rolesMap.stream().map(roleConfig -> {
String roleName = roleConfig.get("id").toString();
String clientId = null;
int clientIdSeparator = roleName.indexOf("/");
if (clientIdSeparator != -1) {
clientId = roleName.substring(0, clientIdSeparator);
roleName = roleName.substring(clientIdSeparator + 1);
}
RoleModel role;
if (clientId == null) {
role = realm.getRole(roleName);
} else {
role = realm.getClientByClientId(clientId).getRole(roleName);
}
// fallback to find any client role with the given name
if (role == null) {
String finalRoleName = roleName;
role = realm.getClients().stream().map(clientModel -> clientModel.getRole(finalRoleName)).filter(roleModel -> roleModel != null)
.findFirst().orElse(null);
}
if (role == null) {
role = realm.getRoleById(roleName);
if (role == null) {
String finalRoleName1 = roleName;
role = realm.getClients().stream().map(clientModel -> clientModel.getRole(finalRoleName1)).filter(roleModel -> roleModel != null)
.findFirst().orElse(null);
}
}
if (role == null) {
throw new RuntimeException("Error while importing configuration. Role [" + roleName + "] could not be found.");
}
roleConfig.put("id", role.getId());
return roleConfig;
}).collect(Collectors.toList())));
} catch (Exception e) {
throw new RuntimeException("Error while exporting policy [" + policyRepresentation.getName() + "].", e);
}
}
String users = config.get("users");
if (users != null && !users.isEmpty()) {
try {
List<String> usersMap = JsonSerialization.readValue(users, List.class);
config.put("users", JsonSerialization.writeValueAsString(usersMap.stream().map(userId -> {
UserModel user = session.users().getUserByUsername(userId, realm);
if (user == null) {
user = session.users().getUserById(userId, realm);
}
if (user == null) {
throw new RuntimeException("Error while importing configuration. User [" + userId + "] could not be found.");
}
return user.getId();
}).collect(Collectors.toList())));
} catch (Exception e) {
throw new RuntimeException("Error while exporting policy [" + policyRepresentation.getName() + "].", e);
}
}
String scopes = config.get("scopes");
if (scopes != null && !scopes.isEmpty()) {
try {
ScopeStore scopeStore = storeFactory.getScopeStore();
List<String> scopesMap = JsonSerialization.readValue(scopes, List.class);
config.put("scopes", JsonSerialization.writeValueAsString(scopesMap.stream().map(scopeName -> {
Scope newScope = scopeStore.findByName(scopeName, resourceServer.getId());
if (newScope == null) {
newScope = scopeStore.findById(scopeName);
}
if (newScope == null) {
throw new RuntimeException("Scope with name [" + scopeName + "] not defined.");
}
return newScope.getId();
}).collect(Collectors.toList())));
} catch (Exception e) {
throw new RuntimeException("Error while exporting policy [" + policyRepresentation.getName() + "].", e);
}
}
String policyResources = config.get("resources");
if (policyResources != null && !policyResources.isEmpty()) {
ResourceStore resourceStore = storeFactory.getResourceStore();
try {
List<String> resources = JsonSerialization.readValue(policyResources, List.class);
config.put("resources", JsonSerialization.writeValueAsString(resources.stream().map(new Function<String, String>() {
@Override
public String apply(String resourceName) {
Resource resource = resourceStore.findByName(resourceName, resourceServer.getId());
if (resource == null) {
resource = resourceStore.findById(resourceName);
}
if (resource == null) {
throw new RuntimeException("Resource with name [" + resourceName + "] not defined.");
}
return resource.getId();
}
}).collect(Collectors.toList())));
} catch (Exception e) {
throw new RuntimeException("Error while exporting policy [" + policyRepresentation.getName() + "].", e);
}
}
String applyPolicies = config.get("applyPolicies");
if (applyPolicies != null && !applyPolicies.isEmpty()) {
PolicyStore policyStore = storeFactory.getPolicyStore();
try {
List<String> policies = JsonSerialization.readValue(applyPolicies, List.class);
config.put("applyPolicies", JsonSerialization.writeValueAsString(policies.stream().map(policyName -> {
Policy policy = policyStore.findByName(policyName, resourceServer.getId());
if (policy == null) {
policy = policyStore.findById(policyName);
}
if (policy == null) {
policy = importPolicies(authorization, resourceServer, policiesToImport, policyName);
if (policy == null) {
throw new RuntimeException("Policy with name [" + policyName + "] not defined.");
}
}
return policy.getId();
}).collect(Collectors.toList())));
} catch (Exception e) {
throw new RuntimeException("Error while exporting policy [" + policyRepresentation.getName() + "].", e);
}
}
if (parentPolicyName == null) {
toModel(policyRepresentation, resourceServer, authorization);
} else if (parentPolicyName.equals(policyRepresentation.getName())) {
return toModel(policyRepresentation, resourceServer, authorization);
}
}
return null;
}
public static Policy toModel(PolicyRepresentation policy, ResourceServer resourceServer, AuthorizationProvider authorization) {
PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
Policy existing;
if (policy.getId() != null) {
existing = policyStore.findById(policy.getId());
} else {
existing = policyStore.findByName(policy.getName(), resourceServer.getId());
}
if (existing != null) {
existing.setName(policy.getName());
existing.setDescription(policy.getDescription());
existing.setConfig(policy.getConfig());
existing.setDecisionStrategy(policy.getDecisionStrategy());
existing.setLogic(policy.getLogic());
updateResources(existing, authorization);
updateAssociatedPolicies(existing, resourceServer, authorization);
updateScopes(existing, authorization);
return existing;
}
Policy model = policyStore.create(policy.getName(), policy.getType(), resourceServer);
model.setDescription(policy.getDescription());
model.setDecisionStrategy(policy.getDecisionStrategy());
model.setLogic(policy.getLogic());
model.setConfig(policy.getConfig());
updateResources(model, authorization);
updateAssociatedPolicies(model, resourceServer, authorization);
updateScopes(model, authorization);
policy.setId(model.getId());
return model;
}
private static void updateScopes(Policy policy, AuthorizationProvider authorization) {
String scopes = policy.getConfig().get("scopes");
if (scopes != null) {
String[] scopeIds;
try {
scopeIds = JsonSerialization.readValue(scopes, String[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
StoreFactory storeFactory = authorization.getStoreFactory();
for (String scopeId : scopeIds) {
boolean hasScope = false;
for (Scope scopeModel : new HashSet<Scope>(policy.getScopes())) {
if (scopeModel.getId().equals(scopeId)) {
hasScope = true;
}
}
if (!hasScope) {
policy.addScope(storeFactory.getScopeStore().findById(scopeId));
}
}
for (Scope scopeModel : new HashSet<Scope>(policy.getScopes())) {
boolean hasScope = false;
for (String scopeId : scopeIds) {
if (scopeModel.getId().equals(scopeId)) {
hasScope = true;
}
}
if (!hasScope) {
policy.removeScope(scopeModel);
}
}
}
}
private static void updateAssociatedPolicies(Policy policy, ResourceServer resourceServer, AuthorizationProvider authorization) {
String policies = policy.getConfig().get("applyPolicies");
if (policies != null) {
String[] policyIds;
try {
policyIds = JsonSerialization.readValue(policies, String[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
StoreFactory storeFactory = authorization.getStoreFactory();
PolicyStore policyStore = storeFactory.getPolicyStore();
for (String policyId : policyIds) {
boolean hasPolicy = false;
for (Policy policyModel : new HashSet<Policy>(policy.getAssociatedPolicies())) {
if (policyModel.getId().equals(policyId) || policyModel.getName().equals(policyId)) {
hasPolicy = true;
}
}
if (!hasPolicy) {
Policy associatedPolicy = policyStore.findById(policyId);
if (associatedPolicy == null) {
associatedPolicy = policyStore.findByName(policyId, resourceServer.getId());
}
policy.addAssociatedPolicy(associatedPolicy);
}
}
for (Policy policyModel : new HashSet<Policy>(policy.getAssociatedPolicies())) {
boolean hasPolicy = false;
for (String policyId : policyIds) {
if (policyModel.getId().equals(policyId) || policyModel.getName().equals(policyId)) {
hasPolicy = true;
}
}
if (!hasPolicy) {
policy.removeAssociatedPolicy(policyModel);;
}
}
}
}
private static void updateResources(Policy policy, AuthorizationProvider authorization) {
String resources = policy.getConfig().get("resources");
if (resources != null) {
String[] resourceIds;
try {
resourceIds = JsonSerialization.readValue(resources, String[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
StoreFactory storeFactory = authorization.getStoreFactory();
for (String resourceId : resourceIds) {
boolean hasResource = false;
for (Resource resourceModel : new HashSet<Resource>(policy.getResources())) {
if (resourceModel.getId().equals(resourceId)) {
hasResource = true;
}
}
if (!hasResource && !"".equals(resourceId)) {
policy.addResource(storeFactory.getResourceStore().findById(resourceId));
}
}
for (Resource resourceModel : new HashSet<Resource>(policy.getResources())) {
boolean hasResource = false;
for (String resourceId : resourceIds) {
if (resourceModel.getId().equals(resourceId)) {
hasResource = true;
}
}
if (!hasResource) {
policy.removeResource(resourceModel);
}
}
}
}
public static Resource toModel(ResourceRepresentation resource, ResourceServer resourceServer, AuthorizationProvider authorization) {
ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
Resource existing;
if (resource.getId() != null) {
existing = resourceStore.findById(resource.getId());
} else {
existing = resourceStore.findByName(resource.getName(), resourceServer.getId());
}
if (existing != null) {
existing.setName(resource.getName());
existing.setType(resource.getType());
existing.setUri(resource.getUri());
existing.setIconUri(resource.getIconUri());
existing.updateScopes(resource.getScopes().stream()
.map((ScopeRepresentation scope) -> toModel(scope, resourceServer, authorization))
.collect(Collectors.toSet()));
return existing;
}
ResourceOwnerRepresentation owner = resource.getOwner();
if (owner == null) {
owner = new ResourceOwnerRepresentation();
owner.setId(resourceServer.getClientId());
}
if (owner.getId() == null) {
throw new RuntimeException("No owner specified for resource [" + resource.getName() + "].");
}
Resource model = resourceStore.create(resource.getName(), resourceServer, owner.getId());
model.setType(resource.getType());
model.setUri(resource.getUri());
model.setIconUri(resource.getIconUri());
Set<ScopeRepresentation> scopes = resource.getScopes();
if (scopes != null) {
model.updateScopes(scopes.stream().map((Function<ScopeRepresentation, Scope>) scope -> toModel(scope, resourceServer, authorization)).collect(Collectors.toSet()));
}
resource.setId(model.getId());
return model;
}
public static Scope toModel(ScopeRepresentation scope, ResourceServer resourceServer, AuthorizationProvider authorization) {
StoreFactory storeFactory = authorization.getStoreFactory();
ScopeStore scopeStore = storeFactory.getScopeStore();
Scope existing;
if (scope.getId() != null) {
existing = scopeStore.findById(scope.getId());
} else {
existing = scopeStore.findByName(scope.getName(), resourceServer.getId());
}
if (existing != null) {
existing.setName(scope.getName());
existing.setIconUri(scope.getIconUri());
return existing;
}
Scope model = scopeStore.create(scope.getName(), resourceServer);
model.setIconUri(scope.getIconUri());
scope.setId(model.getId());
return model;
}
public static void importFederatedUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
UserFederatedStorageProvider federatedStorage = session.userFederatedStorage();
if (userRep.getAttributes() != null) {
for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
String key = entry.getKey();
List<String> value = entry.getValue();
if (value != null) {
federatedStorage.setAttribute(newRealm, userRep.getId(), key, new LinkedList<>(value));
}
}
}
if (userRep.getRequiredActions() != null) {
for (String action: userRep.getRequiredActions()) {
federatedStorage.addRequiredAction(newRealm, userRep.getId(), action);
}
}
if (userRep.getCredentials() != null) {
for (CredentialRepresentation cred : userRep.getCredentials()) {
federatedStorage.createCredential(newRealm, userRep.getId(), toModel(cred));
}
}
createFederatedRoleMappings(federatedStorage, userRep, newRealm);
if (userRep.getGroups() != null) {
for (String path : userRep.getGroups()) {
GroupModel group = KeycloakModelUtils.findGroupByPath(newRealm, path);
if (group == null) {
throw new RuntimeException("Unable to find group specified by path: " + path);
}
federatedStorage.joinGroup(newRealm, userRep.getId(), group);
}
}
if (userRep.getFederatedIdentities() != null) {
for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
federatedStorage.addFederatedIdentity(newRealm, userRep.getId(), mappingModel);
}
}
if (userRep.getClientConsents() != null) {
for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
UserConsentModel consentModel = toModel(newRealm, consentRep);
federatedStorage.addConsent(newRealm, userRep.getId(), consentModel);
}
}
}
public static void createFederatedRoleMappings(UserFederatedStorageProvider federatedStorage, UserRepresentation userRep, RealmModel realm) {
if (userRep.getRealmRoles() != null) {
for (String roleString : userRep.getRealmRoles()) {
RoleModel role = realm.getRole(roleString.trim());
if (role == null) {
role = realm.addRole(roleString.trim());
}
federatedStorage.grantRole(realm, userRep.getId(), role);
}
}
if (userRep.getClientRoles() != null) {
for (Map.Entry<String, List<String>> entry : userRep.getClientRoles().entrySet()) {
ClientModel client = realm.getClientByClientId(entry.getKey());
if (client == null) {
throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
}
createFederatedClientRoleMappings(federatedStorage, realm, client, userRep, entry.getValue());
}
}
}
public static void createFederatedClientRoleMappings(UserFederatedStorageProvider federatedStorage, RealmModel realm, ClientModel clientModel, UserRepresentation userRep, List<String> roleNames) {
if (userRep == null) {
throw new RuntimeException("User not found");
}
for (String roleName : roleNames) {
RoleModel role = clientModel.getRole(roleName.trim());
if (role == null) {
role = clientModel.addRole(roleName.trim());
}
federatedStorage.grantRole(realm, userRep.getId(), role);
}
}
}
| manuel-palacio/keycloak | server-spi-private/src/main/java/org/keycloak/models/utils/RepresentationToModel.java | Java | apache-2.0 | 114,856 |
# -*- encoding: utf-8 -*-
# Copyright © 2012 New Dream Network, LLC (DreamHost)
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import keystonemiddleware.audit as audit_middleware
from oslo_config import cfg
import oslo_middleware.cors as cors_middleware
import pecan
from ironic.api import config
from ironic.api.controllers import base
from ironic.api import hooks
from ironic.api import middleware
from ironic.api.middleware import auth_token
from ironic.common import exception
from ironic.conf import CONF
class IronicCORS(cors_middleware.CORS):
"""Ironic-specific CORS class
We're adding the Ironic-specific version headers to the list of simple
headers in order that a request bearing those headers might be accepted by
the Ironic REST API.
"""
simple_headers = cors_middleware.CORS.simple_headers + [
'X-Auth-Token',
base.Version.max_string,
base.Version.min_string,
base.Version.string
]
def get_pecan_config():
# Set up the pecan configuration
filename = config.__file__.replace('.pyc', '.py')
return pecan.configuration.conf_from_file(filename)
def setup_app(pecan_config=None, extra_hooks=None):
app_hooks = [hooks.ConfigHook(),
hooks.DBHook(),
hooks.ContextHook(pecan_config.app.acl_public_routes),
hooks.RPCHook(),
hooks.NoExceptionTracebackHook(),
hooks.PublicUrlHook()]
if extra_hooks:
app_hooks.extend(extra_hooks)
if not pecan_config:
pecan_config = get_pecan_config()
pecan.configuration.set_config(dict(pecan_config), overwrite=True)
app = pecan.make_app(
pecan_config.app.root,
debug=CONF.pecan_debug,
static_root=pecan_config.app.static_root if CONF.pecan_debug else None,
force_canonical=getattr(pecan_config.app, 'force_canonical', True),
hooks=app_hooks,
wrap_app=middleware.ParsableErrorMiddleware,
)
if CONF.audit.enabled:
try:
app = audit_middleware.AuditMiddleware(
app,
audit_map_file=CONF.audit.audit_map_file,
ignore_req_list=CONF.audit.ignore_req_list
)
except (EnvironmentError, OSError,
audit_middleware.PycadfAuditApiConfigError) as e:
raise exception.InputFileError(
file_name=CONF.audit.audit_map_file,
reason=e
)
if CONF.auth_strategy == "keystone":
app = auth_token.AuthTokenMiddleware(
app, dict(cfg.CONF),
public_api_routes=pecan_config.app.acl_public_routes)
# Create a CORS wrapper, and attach ironic-specific defaults that must be
# included in all CORS responses.
app = IronicCORS(app, CONF)
cors_middleware.set_defaults(
allow_methods=['GET', 'PUT', 'POST', 'DELETE', 'PATCH'],
expose_headers=[base.Version.max_string, base.Version.min_string,
base.Version.string]
)
return app
class VersionSelectorApplication(object):
def __init__(self):
pc = get_pecan_config()
self.v1 = setup_app(pecan_config=pc)
def __call__(self, environ, start_response):
return self.v1(environ, start_response)
| SauloAislan/ironic | ironic/api/app.py | Python | apache-2.0 | 3,844 |
/**
* Copyright 2013 Andreas Stenius
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "qte.h"
#include "qteevent.h"
QtE::QtE(QObject *parent)
: QObject(parent)
{
if (parent)
parent->setObjectName("::root");
}
void QtE::init(QtEStateId id)
{
insertObject(id, parent());
}
void QtE::clear(QtEStateId id)
{
root.remove(id, parent());
foreach(QObject *o, getObjects(id))
o->deleteLater();
root.remove(id);
}
void QtE::insertObject(QtEStateId id, QObject *object)
{
root.insert(id, object);
}
QList<QObject *> QtE::getObjects(QtEStateId id)
{
return root.values(id);
}
template<typename T>
T QtE::find(QtEStateId id, const QString &name)
{
Qt::FindChildOption opt = Qt::FindChildrenRecursively;
QStringList path = name.split('/');
while (!path.first().size())
{
opt = Qt::FindDirectChildrenOnly;
path.pop_front();
}
foreach (QObject *o, getObjects(id))
{
T t = dynamic_cast<T>(o);
if (t &&
opt == Qt::FindDirectChildrenOnly &&
(path.first() == o->objectName()))
return t;
foreach (QString p, path)
{
if (!p.size())
{
opt = Qt::FindChildrenRecursively;
continue;
}
t = o->findChild<T>(p, opt);
if (t)
{
o = dynamic_cast<QObject *>(t);
if (!o)
break;
}
opt = Qt::FindDirectChildrenOnly;
}
if (t)
return t;
}
return 0;
}
QObject *QtE::findObject(QtEStateId id, const QString &name)
{
return find<QObject *>(id, name);
}
QWidget *QtE::findWidget(QtEStateId id, const QString &name)
{
return find<QWidget *>(id, name);
}
void QtE::customEvent(QEvent *event)
{
if (event->type() != QtEEvent::EventType())
return;
QtEEvent *e = dynamic_cast<QtEEvent *>(event);
if (e)
e->execute(this);
}
void QtE::loaded(QWidget *widget, QtEAbstractState *state)
{
(void) state;
// drop this? might wanna create it hidden, and show it later
widget->show();
// top-level widget?
if (!widget->parent())
insertObject(state, widget);
}
| kaos/QtErl | c_src/libqte/qte.cpp | C++ | apache-2.0 | 2,580 |
// Copyright 2017 Secure Decisions, a division of Applied Visions, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// This material is based on research sponsored by the Department of Homeland
// Security (DHS) Science and Technology Directorate, Cyber Security Division
// (DHS S&T/CSD) via contract number HHSP233201600058C.
using System;
namespace CodePulse.Client.Errors
{
public interface IErrorHandler
{
event EventHandler<Tuple<string, Exception>> ErrorOccurred;
void HandleError(string errorMessage);
void HandleError(string errorMessage, Exception exception);
}
}
| secdec/codepulse | dotnet-tracer/main/CodePulse.Client/Errors/IErrorHandler.cs | C# | apache-2.0 | 1,659 |
package fr.javatronic.blog.massive.annotation1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_120 {
}
| lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_120.java | Java | apache-2.0 | 145 |
/**
* @license Copyright 2019 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/** @typedef {import('./common.js').Result} Result */
/** @typedef {import('./common.js').Summary} Summary */
/** @typedef {import('../run-on-all-assets.js').Golden} Golden */
import fs from 'fs';
import * as common from './common.js';
/**
* @template T
* @param {number} percentile 0 - 1
* @param {T[]} values
* @param {(sortValue: T) => number} mapper
*/
function getPercentileBy(percentile, values, mapper) {
const resultsWithValue = values.map(value => {
return {sortValue: mapper(value), value};
});
resultsWithValue.sort((a, b) => a.sortValue - b.sortValue);
const pos = Math.floor((values.length - 1) * percentile);
return resultsWithValue[pos].value;
}
/**
* Returns run w/ the %ile based on FCP.
* @param {number} percentile
* @param {Result[]} results
*/
function getPercentileResult(percentile, results) {
const resultsWithMetrics = results.map(result => {
const metrics = common.getMetrics(loadLhr(result.lhr));
if (!metrics) throw new Error('could not find metrics'); // This shouldn't happen.
return {result, metrics};
});
return getPercentileBy(
percentile, resultsWithMetrics, ({metrics}) => Number(metrics.firstContentfulPaint)).result;
}
/**
* @param {string} filename
* @return {LH.Result}
*/
function loadLhr(filename) {
return JSON.parse(fs.readFileSync(`${common.collectFolder}/${filename}`, 'utf-8'));
}
/**
* @param {string} filename
*/
function copyToGolden(filename) {
fs.copyFileSync(`${common.collectFolder}/${filename}`, `${common.goldenFolder}/${filename}`);
}
/**
* @param {string} filename
* @param {string} data
*/
function saveGoldenData(filename, data) {
fs.writeFileSync(`${common.goldenFolder}/${filename}`, data);
}
/** @type {typeof common.ProgressLogger['prototype']} */
let log;
async function main() {
log = new common.ProgressLogger();
/** @type {Summary} */
const summary = common.loadSummary();
const goldenSites = [];
for (const [index, {url, wpt, unthrottled}] of Object.entries(summary.results)) {
log.progress(`finding median ${Number(index) + 1} / ${summary.results.length}`);
// Use the nearly-best-case run from WPT, to match the optimistic viewpoint of lantern, and
// avoid variability that is not addressable by Lighthouse. Don't use the best case because
// that increases liklihood of using a run that failed to load an important subresource.
const medianWpt = getPercentileResult(0.25, wpt);
// Use the median run for unthrottled.
const medianUnthrottled = getPercentileResult(0.5, unthrottled);
if (!medianWpt || !medianUnthrottled) continue;
if (!medianUnthrottled.devtoolsLog) throw new Error(`missing devtoolsLog for ${url}`);
const wptMetrics = common.getMetrics(loadLhr(medianWpt.lhr));
if (!wptMetrics) {
throw new Error('expected wptMetrics');
}
goldenSites.push({
url,
wpt3g: {
firstContentfulPaint: wptMetrics.firstContentfulPaint,
firstMeaningfulPaint: wptMetrics.firstMeaningfulPaint,
timeToConsistentlyInteractive: wptMetrics.interactive,
speedIndex: wptMetrics.speedIndex,
largestContentfulPaint: wptMetrics.largestContentfulPaint,
},
unthrottled: {
tracePath: medianUnthrottled.trace,
devtoolsLogPath: medianUnthrottled.devtoolsLog,
},
});
}
/** @type {Golden} */
const golden = {sites: goldenSites};
fs.rmSync(common.goldenFolder, {recursive: true, force: true});
fs.mkdirSync(common.goldenFolder);
saveGoldenData('site-index-plus-golden-expectations.json', JSON.stringify(golden, null, 2));
for (const result of goldenSites) {
log.progress('making site-index-plus-golden-expectations.json');
copyToGolden(result.unthrottled.devtoolsLogPath);
copyToGolden(result.unthrottled.tracePath);
}
log.progress('archiving ...');
await common.archive(common.goldenFolder);
log.closeProgress();
}
main();
| GoogleChrome/lighthouse | lighthouse-core/scripts/lantern/collect/golden.js | JavaScript | apache-2.0 | 4,553 |
/*
* Copyright 2013 The Kava Project Developers. See the COPYRIGHT file at the top-level directory of this distribution
* and at http://kavaproject.org/COPYRIGHT.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the
* MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied,
* modified, or distributed except according to those terms.
*/
package org.kavaproject.kavatouch.uikit;
import org.kavaproject.kavatouch.coregraphics.*;
import org.kavaproject.kavatouch.foundation.Coding;
import org.kavaproject.kavatouch.internal.*;
import org.kavaproject.kavatouch.runtime.Creatable;
import org.kavaproject.kavatouch.runtime.SEL;
import org.kavaproject.kavatouch.uikit.staging.ProcessingImage;
import java.nio.ByteBuffer;
import java.util.List;
@Header("UIImage")
@OccClass("UIImage")
public interface UIImage extends Coding, Creatable {
@OccInstanceMethod("imageWithAlignmentRectInsets:")
UIImage createImage(UIEdgeInsets alignmentInsets);
@OccInstanceMethod("resizableImageWithCapInsets:")
UIImage resizableImage(UIEdgeInsets capInsets);
@OccInstanceMethod("resizableImageWithCapInsets:resizingMode:")
UIImage resizableImage(UIEdgeInsets capInsets, UIImageResizingMode resizingMode);
@OccInstanceMethod("stretchableImageWithLeftCapWidth:topCapHeight:")
@Deprecated
UIImage stretchableImage(int leftCapWidth, int toCapWidth);
@OccInstanceProperty(value = "imageOrientation")
UIImageOrientation getImageOrientation();
@OccInstanceProperty(value = "scale")
float getScale();
@OccInstanceProperty(value = "resizingMode")
UIImageResizingMode getResizingMode();
@OccInstanceProperty(value = "CIImage")
ProcessingImage toProcessingImage();
@OccInstanceProperty(value = "images")
List<UIImage> getImages();
@OccInstanceProperty(value = "duration")
double getDuration();
@OccInstanceProperty(value = "capInsets")
UIEdgeInsets getCapInsets();
@OccInstanceProperty(value = "alignmentRectInsets")
UIEdgeInsets getAlignmentRectInsets();
@OccInstanceProperty(value = "leftCapWidth")
@Deprecated
int getLeftCapWidth();
@OccInstanceProperty(value = "topCapHeight")
@Deprecated
int getTopCapHeight();
@OccInstanceMethod("drawAtPoint:")
void draw(GraphicsPoint point);
@OccInstanceMethod("drawInRect:")
void draw(GraphicsRect rect);
@OccInstanceProperty(value = "CGImage")
GraphicsImage toGraphicsImage();
@OccInstanceProperty(value = "size")
GraphicsSize getSize();
@OccInstanceMethod("drawAtPoint:blendMode:alpha:")
void draw(GraphicsPoint point, GraphicsBlendMode blendMode, float alpha);
@OccInstanceMethod("drawInRect:blendMode:alpha:")
void draw(GraphicsRect rect, GraphicsBlendMode blendMode, float alpha);
@OccInstanceMethod("drawAsPatternInRect:")
void drawAsPattern(GraphicsRect rect);
@CFunction(value = "UIImageJPEGRepresentation", tokenGroup = "UIKit")
ByteBuffer jpegRepresentation(float compressionQuality);
@CFunction(value = "UIImagePNGRepresentation", tokenGroup = "UIKit")
ByteBuffer pngRepresentation();
@Header("UIImagePickerController")
@CFunction(value = "UIImagePNGRepresentation", tokenGroup = "UIKit")
void writeToSavedPhotosAlbum(Object completionTarget, SEL completionSelector, Object contextInfo);
@Override
UIImageFactory getFactory();
}
| KavaProject/KavaTouch | src/main/java/org/kavaproject/kavatouch/uikit/UIImage.java | Java | apache-2.0 | 3,517 |
CREATE TABLE hasfk (
id int(10) unsigned NOT NULL,
customer_id int(10) unsigned DEFAULT NULL,
PRIMARY KEY (id),
KEY customer (customer_id),
CONSTRAINT customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE SET NULL /* annotations: has-fk */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE hasfks (
id int unsigned NOT NULL,
customer_id int unsigned DEFAULT NULL,
product_id int unsigned,
PRIMARY KEY (id),
KEY customer (customer_id),
KEY product (product_id),
FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE SET NULL, /* annotations: has-fk */
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
| skeema/skeema | internal/linter/testdata/validcfg/hasfk.sql | SQL | apache-2.0 | 719 |
package ru.asemenov.filter.servlets;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import ru.asemenov.filter.ConnectSql;
import ru.asemenov.filter.models.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DeleteUserTest {
@Before
public void addUser() throws ServletException, IOException {
AddUser addUser = new AddUser();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter("name")).thenReturn("test");
when(request.getParameter("login")).thenReturn("test");
when(request.getParameter("password")).thenReturn("test");
when(request.getParameter("email")).thenReturn("test@mail");
when(request.getParameter("role_id")).thenReturn("2");
addUser.doPost(request, response);
}
@Test
public void delete() throws ServletException, IOException {
DeleteUser deleteUser = new DeleteUser();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter("login")).thenReturn("test");
deleteUser.doPost(request, response);
List<User> users = ConnectSql.getInstance().getUser();
Assert.assertEquals(users.size(), 2);
}
} | Apeksi1990/asemenov | chapter_009/filter_security/src/test/java/ru/asemenov/filter/servlets/DeleteUserTest.java | Java | apache-2.0 | 1,613 |
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Text.RegularExpressions.IntervalCollection/CostDelegate
struct CostDelegate_t3008899218;
// System.Object
struct Il2CppObject;
// System.IAsyncResult
struct IAsyncResult_t537683269;
// System.AsyncCallback
struct AsyncCallback_t1363551830;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Object837106420.h"
#include "mscorlib_System_IntPtr676692020.h"
#include "System_System_Text_RegularExpressions_Interval63637216.h"
#include "System_System_Text_RegularExpressions_Interval63637216MethodDeclarations.h"
#include "mscorlib_System_AsyncCallback1363551830.h"
// System.Void System.Text.RegularExpressions.IntervalCollection/CostDelegate::.ctor(System.Object,System.IntPtr)
extern "C" void CostDelegate__ctor_m731467895 (CostDelegate_t3008899218 * __this, Il2CppObject * ___object, IntPtr_t ___method, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Double System.Text.RegularExpressions.IntervalCollection/CostDelegate::Invoke(System.Text.RegularExpressions.Interval)
extern "C" double CostDelegate_Invoke_m212988972 (CostDelegate_t3008899218 * __this, Interval_t63637216 ___i, const MethodInfo* method) IL2CPP_METHOD_ATTR;
extern "C" double pinvoke_delegate_wrapper_CostDelegate_t3008899218(Il2CppObject* delegate, Interval_t63637216 ___i);
// System.IAsyncResult System.Text.RegularExpressions.IntervalCollection/CostDelegate::BeginInvoke(System.Text.RegularExpressions.Interval,System.AsyncCallback,System.Object)
extern "C" Il2CppObject * CostDelegate_BeginInvoke_m1041332600 (CostDelegate_t3008899218 * __this, Interval_t63637216 ___i, AsyncCallback_t1363551830 * ___callback, Il2CppObject * ___object, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Double System.Text.RegularExpressions.IntervalCollection/CostDelegate::EndInvoke(System.IAsyncResult)
extern "C" double CostDelegate_EndInvoke_m917297514 (CostDelegate_t3008899218 * __this, Il2CppObject * ___result, const MethodInfo* method) IL2CPP_METHOD_ATTR;
| moixxsyc/Unity3dLearningDemos | 01Dongzuo/Temp/il2cppOutput/il2cppOutput/System_System_Text_RegularExpressions_IntervalColl3008899218MethodDeclarations.h | C | apache-2.0 | 2,147 |
# Login User with Limited Access
You can initiate user login with Limited Access.
### Initialize CitrusLoginApi
```groovy
String emailId = "email@gmail.com";
String mobileNo = "9999999999";
CitrusLoginApi citrusLoginApi = new CitrusLoginApi.Builder(getActivity())
.mobile(mobileNo)
.email(emailId)
.accessType(AccessType.LIMITED)
.environment(Environment.SANDBOX)
.build();
```
### Initiate Login
```groovy
citrusClient.doLogin(citrusLoginApi);
```
### Listening to different login events
```groovy
citrusLoginApi.setListener(new CitrusLoginApi.CitrusLoginApiListener() {
@Override
public void onLoginSuccess() {
// The user is logged in now. You may proceed to payment screen.
}
@Override
public void onError(CitrusError error) {
// Show some error to the user.
}
@Override
public void onLoginCancelled() {
// If the user has cancelled the login, you can ask user to login again.
}
});
```
For further details please refer <a href="Unified%20Login%20API.md#unified-login-api-interface-document" target="_blank">here</a>.
| citruspay/citrus-android-sdk | docs/login_with_limited_access.md | Markdown | apache-2.0 | 1,227 |
/*
* Copyright 2012-2016 JetBrains s.r.o
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.jetpad.model.property;
/**
* implementations of {@link ReadableProperty#get()} method shouldn't return null
*/
public interface TextProperty extends ReadableProperty<String> {
/**
* @throws IllegalArgumentException in the following cases:
* {@param text} is null
* {@param index} is negative
* {@param index} is greater than property text length
*/
void insert(int index, String text);
/**
* @throws IllegalArgumentException in the following cases:
* {@param index} is negative
* {@param length} is negative
* {@param index} + {@param length} is greater than property text length
*/
void delete(int index, int length);
} | timzam/jetpad-mapper | model/src/main/java/jetbrains/jetpad/model/property/TextProperty.java | Java | apache-2.0 | 1,330 |
package hook
import (
"regexp"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
// When holds hook-injection conditions.
type When struct {
Always *bool `json:"always,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
Commands []string `json:"commands,omitempty"`
HasBindMounts *bool `json:"hasBindMounts,omitempty"`
// Or enables any-of matching.
//
// Deprecated: this property is for is backwards-compatibility with
// 0.1.0 hooks. It will be removed when we drop support for them.
Or bool `json:"-"`
}
// Match returns true if the given conditions match the configuration.
func (when *When) Match(config *rspec.Spec, annotations map[string]string, hasBindMounts bool) (match bool, err error) {
matches := 0
if when.Always != nil {
if *when.Always {
if when.Or {
return true, nil
}
matches++
} else if !when.Or {
return false, nil
}
}
if when.HasBindMounts != nil {
if *when.HasBindMounts && hasBindMounts {
if when.Or {
return true, nil
}
matches++
} else if !when.Or {
return false, nil
}
}
for keyPattern, valuePattern := range when.Annotations {
match := false
for key, value := range annotations {
match, err = regexp.MatchString(keyPattern, key)
if err != nil {
return false, errors.Wrap(err, "annotation key")
}
if match {
match, err = regexp.MatchString(valuePattern, value)
if err != nil {
return false, errors.Wrap(err, "annotation value")
}
if match {
break
}
}
}
if match {
if when.Or {
return true, nil
}
matches++
} else if !when.Or {
return false, nil
}
}
if config.Process != nil {
if len(config.Process.Args) == 0 {
return false, errors.New("process.args must have at least one entry")
}
command := config.Process.Args[0]
for _, cmdPattern := range when.Commands {
match, err := regexp.MatchString(cmdPattern, command)
if err != nil {
return false, errors.Wrap(err, "command")
}
if match {
return true, nil
}
}
return false, nil
}
return matches > 0, nil
}
| jwhonce/ocid | vendor/github.com/projectatomic/libpod/pkg/hooks/1.0.0/when.go | GO | apache-2.0 | 2,171 |
/*
* Copyright 2012 Shared Learning Collaborative, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.04.20 at 03:09:04 PM EDT
//
package org.slc.sli.sample.entities;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Additional credits or units of value awarded for the completion of a course (e.g., AP, IB, Dual credits)
*
* <p>Java class for AdditionalCredits complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AdditionalCredits">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Credit">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <minInclusive value="0"/>
* <fractionDigits value="2"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* <attribute name="AdditionalCreditType" use="required" type="{http://ed-fi.org/0100}AdditionalCreditType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AdditionalCredits", propOrder = {
"credit"
})
public class AdditionalCredits {
@XmlElement(name = "Credit", required = true)
protected BigDecimal credit;
@XmlAttribute(name = "AdditionalCreditType", required = true)
protected AdditionalCreditType additionalCreditType;
/**
* Gets the value of the credit property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getCredit() {
return credit;
}
/**
* Sets the value of the credit property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setCredit(BigDecimal value) {
this.credit = value;
}
/**
* Gets the value of the additionalCreditType property.
*
* @return
* possible object is
* {@link AdditionalCreditType }
*
*/
public AdditionalCreditType getAdditionalCreditType() {
return additionalCreditType;
}
/**
* Sets the value of the additionalCreditType property.
*
* @param value
* allowed object is
* {@link AdditionalCreditType }
*
*/
public void setAdditionalCreditType(AdditionalCreditType value) {
this.additionalCreditType = value;
}
}
| inbloom/csv2xml | src/org/slc/sli/sample/entities/AdditionalCredits.java | Java | apache-2.0 | 3,691 |
/*
* Copyright 2017 Long Term Software LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ltsllc.miranda.event;
import com.ltsllc.miranda.Message;
import com.ltsllc.miranda.State;
import com.ltsllc.miranda.clientinterface.MirandaException;
import com.ltsllc.miranda.event.messages.NewEventMessage;
import com.ltsllc.miranda.miranda.Miranda;
import com.ltsllc.miranda.operations.events.NewEventOperation;
/**
* Created by Clark on 5/14/2017.
*/
public class EventManagerReadyState extends State {
public EventManager getEventManager() {
return (EventManager) getContainer();
}
public EventManagerReadyState(EventManager eventManager) throws MirandaException {
super(eventManager);
}
public State processMessage(Message message) throws MirandaException {
State nextState = getEventManager().getCurrentState();
switch (message.getSubject()) {
case NewEvent: {
NewEventMessage newEventMessage = (NewEventMessage) message;
nextState = processNewEventMessage(newEventMessage);
break;
}
default: {
nextState = super.processMessage(message);
break;
}
}
return nextState;
}
public State processNewEventMessage(NewEventMessage message) throws MirandaException {
NewEventOperation newEventOperation = new NewEventOperation(getEventManager(),
Miranda.getInstance().getTopicManager(), Miranda.getInstance().getCluster(), message.getSession(),
message.getSender(), message.getEvent());
newEventOperation.start();
return getEventManager().getCurrentState();
}
}
| miranda-messaging/miranda | src/main/java/com/ltsllc/miranda/event/EventManagerReadyState.java | Java | apache-2.0 | 2,252 |
/*
* Copyright 2018 prasenjit-net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.prasenjit.identity.controller;
import com.nimbusds.jose.jwk.JWKSet;
import lombok.RequiredArgsConstructor;
import net.minidev.json.JSONObject;
import net.prasenjit.identity.service.openid.CryptographyService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class CryptographyController {
private final CryptographyService cryptographyService;
@RequestMapping(value = "api/keys", method = {RequestMethod.GET, RequestMethod.POST}, produces = JWKSet.MIME_TYPE)
public JSONObject keys() {
JWKSet jwkSet = cryptographyService.loadJwkKeys();
return jwkSet.toPublicJWKSet().toJSONObject();
}
}
| identityOrg/identity | src/main/java/net/prasenjit/identity/controller/CryptographyController.java | Java | apache-2.0 | 1,450 |
package hijackhelpers
import (
"strings"
"github.com/concourse/atc"
)
type ContainerSorter []atc.Container
func (sorter ContainerSorter) Len() int {
return len(sorter)
}
func (sorter ContainerSorter) Swap(i, j int) {
sorter[i], sorter[j] = sorter[j], sorter[i]
}
func (sorter ContainerSorter) Less(i, j int) bool {
switch {
case sorter[i].BuildID < sorter[j].BuildID:
return true
case sorter[i].BuildID > sorter[j].BuildID:
return false
case strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == -1:
return true
case strings.Compare(sorter[i].ResourceName, sorter[j].ResourceName) == 1:
return false
case strings.Compare(sorter[i].StepName, sorter[j].StepName) == -1:
return true
case strings.Compare(sorter[i].StepName, sorter[j].StepName) == 1:
return false
case strings.Compare(sorter[i].Type, sorter[j].Type) == -1:
return true
default:
return false
}
}
| zachgersh/fly | commands/internal/hijackhelpers/container_sorter.go | GO | apache-2.0 | 907 |
namespace CorePhoto.Tiff
{
public struct TiffIfd
{
public TiffIfdEntry[] Entries;
public TiffIfdReference? NextIfdReference;
}
} | Andy-Wilkinson/CorePhoto | src/CorePhoto/Tiff/TiffIfd.cs | C# | apache-2.0 | 156 |
digitaljedi.ca
==============
Public Website
Nothing to see here really...
nothing at all
| digitaljedi2/digitaljedi.ca | README.md | Markdown | apache-2.0 | 92 |
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.androidbrowserhelper.playbilling.digitalgoods;
import android.app.Activity;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.PriceChangeConfirmationListener;
import com.android.billingclient.api.PurchaseHistoryResponseListener;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.google.androidbrowserhelper.playbilling.provider.BillingWrapper;
import com.google.androidbrowserhelper.playbilling.provider.MethodData;
import java.util.ArrayList;
import java.util.List;
/**
* A wrapper around {@link BillingWrapper} that ensures it is connected before calling
* {@link #querySkuDetails}, {@link #acknowledge} or {@link #consume}.
*/
public class ConnectedBillingWrapper implements BillingWrapper {
private final BillingWrapper mInner;
private static final int NOT_CONNECTED = 0;
private static final int CONNECTING = 1;
private static final int CONNECTED = 2;
private int mState = NOT_CONNECTED;
private final List<Runnable> mPendingCallbacks = new ArrayList<>();
public ConnectedBillingWrapper(BillingWrapper mInner) {
this.mInner = mInner;
}
private void execute(Runnable callback) {
if (mState == CONNECTED) {
callback.run();
return;
}
mPendingCallbacks.add(callback);
if (mState == CONNECTING) return;
mState = CONNECTING;
mInner.connect(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
Logging.logConnected();
mState = CONNECTED;
for (Runnable callback : mPendingCallbacks) {
callback.run();
}
mPendingCallbacks.clear();
}
@Override
public void onBillingServiceDisconnected() {
Logging.logDisconnected();
mState = NOT_CONNECTED;
}
});
}
@Override
public void connect(BillingClientStateListener callback) {
execute(() -> {});
}
@Override
public void querySkuDetails(@BillingClient.SkuType String skuType, List<String> skus,
SkuDetailsResponseListener callback) {
execute(() -> mInner.querySkuDetails(skuType, skus, callback));
}
@Override
public void queryPurchases(String skuType, PurchasesResponseListener callback) {
execute(() -> mInner.queryPurchases(skuType, callback));
}
@Override
public void queryPurchaseHistory(String skuType, PurchaseHistoryResponseListener callback) {
execute(() -> mInner.queryPurchaseHistory(skuType, callback));
}
@Override
public void acknowledge(String token, AcknowledgePurchaseResponseListener callback) {
execute(() -> mInner.acknowledge(token, callback));
}
@Override
public void consume(String token, ConsumeResponseListener callback) {
execute(() -> mInner.consume(token, callback));
}
@Override
public boolean launchPaymentFlow(Activity activity, SkuDetails sku, MethodData data) {
throw new IllegalStateException(
"EnsuredConnectionBillingWrapper doesn't handle launch Payment flow");
}
@Override
public void launchPriceChangeConfirmationFlow(Activity activity, SkuDetails sku,
PriceChangeConfirmationListener listener) {
throw new IllegalStateException("EnsuredConnectionBillingWrapper doesn't handle the " +
"price change confirmation flow");
}
}
| GoogleChrome/android-browser-helper | playbilling/src/main/java/com/google/androidbrowserhelper/playbilling/digitalgoods/ConnectedBillingWrapper.java | Java | apache-2.0 | 4,590 |
<?php
/**
* Represents a Proximity Criterion.
*
* A proximity is an area within a certain radius of a point with the center point being described
* by a lat/long pair. The caller may also alternatively provide address fields which will be
* geocoded into a lat/long pair. Note: If a geoPoint value is provided, the address is not
* used for calculating the lat/long to target.
* <p>
* <span class="constraint AdxEnabled">This is enabled for AdX.</span>
*
*
*
* Structure to specify an address location.
* @package Google_Api_Ads_AdWords_v201605
* @subpackage v201605
*/
class Proximity extends Criterion
{
const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
const XSI_TYPE = "Proximity";
/**
* @access public
* @var GeoPoint
*/
public $geoPoint;
/**
* @access public
* @var tnsProximityDistanceUnits
*/
public $radiusDistanceUnits;
/**
* @access public
* @var double
*/
public $radiusInUnits;
/**
* @access public
* @var Address
*/
public $address;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace()
{
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName()
{
return self::XSI_TYPE;
}
public function __construct(
$geoPoint = null,
$radiusDistanceUnits = null,
$radiusInUnits = null,
$address = null,
$id = null,
$type = null,
$CriterionType = null
) {
parent::__construct();
$this->geoPoint = $geoPoint;
$this->radiusDistanceUnits = $radiusDistanceUnits;
$this->radiusInUnits = $radiusInUnits;
$this->address = $address;
$this->id = $id;
$this->type = $type;
$this->CriterionType = $CriterionType;
}
} | SonicGD/google-adwords-api-light | Google/Api/Ads/AdWords/v201605/classes/Proximity.php | PHP | apache-2.0 | 2,035 |
package ru.stqa.pft.mantis.tests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.lanwen.verbalregex.VerbalExpression;
import ru.stqa.pft.mantis.model.MailMessage;
import ru.stqa.pft.mantis.model.User;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.List;
import static org.testng.Assert.assertTrue;
/**
* Created by Alexander Gorny on 3/19/2017.
*/
public class PasswordChangeTests extends TestBase{
@BeforeMethod
public void startMailServer() {
app.mail().start();
}
@Test
public void testUserPasswordChange() throws IOException, MessagingException {
//login as admin, select a user, and click Reset Password button
app.admin().login(app.getProperty("web.adminLogin"), app.getProperty("web.adminPassword"));
app.admin().selectUser();
User user = app.admin().userFromEditFom();
app.admin().resetUserPassword();
//wai for an email
List<MailMessage> mailMessages = app.mail().waitForMail(1, 10000);
//generate a new password
long now = System.currentTimeMillis();
String newPassword = "new_password" + now;
//change password using information from email
String confirmationLink = findConfirmationLink(mailMessages, User.getEmail());
app.registration().finish(confirmationLink, newPassword);
//verify that user can login with the new password
assertTrue(app.newSession().login(User.getUsername(), newPassword));
}
private String findConfirmationLink(List<MailMessage> mailMessages, String email) {
MailMessage mailMessage = mailMessages.stream().filter((m) -> m.to.equals(email)).findFirst().get();
VerbalExpression regex = VerbalExpression.regex().find("http://").nonSpace().oneOrMore().build();
return regex.getText(mailMessage.text);
}
@AfterMethod(alwaysRun = true)
public void stopMailServer() {
app.mail().stop();
}
}
| GornyAlex/pdt_37 | mantis-tests/src/test/java/ru/stqa/pft/mantis/tests/PasswordChangeTests.java | Java | apache-2.0 | 1,959 |
package controllers.algorithm.req_and_course;
public class ReqListForCourse {
public ReqNode first; // head node
private int pos; // Node's position
public ReqListForCourse() {
this.first = null;
}
/**
* Initialize the course link list: course1->req1->re2
*
* @param courseID
* course id
*
* @return null
*/
public ReqListForCourse(int courseID) {
addFirstNode(courseID);
}
/**
* add the first node of course link list
*
* @param cId
* course id
*
* @return null
*/
public void addFirstNode(int cId) {
ReqNode node = new ReqNode(cId);
node.beChosen = false;// initialize the course has not been selected by
// any requirement.
node.next = first;
first = node;
}
/**
* delete the first node of course link list
*
* @param null
*
* @return the new first node
*/
public ReqNode deleteFirstNode() {
ReqNode tempnode = first;
tempnode.next = first.next;
return tempnode;
}
/**
* insert a simple and complex requirement node into course link list
*
* @param SimpleAndCompleReq
* requirement node includes simple requirement and complex
* requirement
* @return null
*/
public void insertNode(ReqNode SimpleAndCompleReq) {
ReqNode current = first;
SimpleAndCompleReq.next = current.next;
current.next = SimpleAndCompleReq;
}
public ReqNode deleteByPos(int index) {
ReqNode current = first;
ReqNode previous = first;
while (pos != index) {
pos++;
previous = current;
current = current.next;
}
if (current == first) {
first = first.next;
} else {
pos = 0;
previous.next = current.next;
}
return current;
}
/**
* Delete a requirement node from course link list, which means that the
* course is no longer belonging to this requirement
*
* @param rId
* requirement id
* @return null
*/
public void deleteByData(int rId) {
ReqNode current = first;
ReqNode previous = first;
while (current.rId != rId) {
if (current.next == null) {
return;
}
previous = current;
current = current.next;
}
if (current == first) {
first = first.next;
} else {
previous.next = current.next;
}
return;
}
/**
* Display all requirements that the course belongs to
*
* @param null
*
* @return null
*/
public void displayAllNodes() {
int flag = 1;
ReqNode current = first;
while (current != null) {
if (flag == 1) {
current.showFirstNode();
current = current.next;
++flag;
} else {
current.showNode();
current = current.next;
}
}
System.out.println();// 输出空行,美观
}
public ReqNode findByPos(int index) {
ReqNode current = first;
if (pos != index) {
current = current.next;
pos++;
}
return current;
}
/**
* Find the specific requirement that the course is belonging to
*
* @param rId
* requirement id
* @return requirement node
*/
public ReqNode findByData(int rId) {
ReqNode current = first;
while (current.rId != rId) {
if (current.next == null)
return null;
current = current.next;
}
return current;
}
/**
* Once a course is chosen in requirement link list, there will be a
* function call this function to update the head node of "course link list"
* as true.
*
* @param rId
* requirement id
* @return null
*/
public void set_course_be_chosen(int reqID) {
ReqNode temp = this.first;
temp.beChosen = true;
while (temp.rId != reqID) {
temp = temp.next;
}
// this.first.beChosen = true;
temp.beChosen = true;
}
/**
* Every time we need to choose a course in requirement link list, we will
* first call this function to check is the course have been chosen.
*
* @param null
*
* @return true if this course has been chosen
*
*/
public boolean checkChosen() {
if (this.first.beChosen == true) {
return true; // this course has been chosen.
}
return false;
}
}
| xixixhalu/sss | app/controllers/algorithm/req_and_course/ReqListForCourse.java | Java | apache-2.0 | 4,004 |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from oslo_policy import opts
from oslo_service import wsgi
from manila.common import config
CONF = config.CONF
def set_defaults(conf):
_safe_set_of_opts(conf, 'verbose', True)
_safe_set_of_opts(conf, 'state_path', os.path.abspath(
os.path.join(os.path.dirname(__file__),
'..',
'..')))
_safe_set_of_opts(conf, 'connection', "sqlite://", group='database')
_safe_set_of_opts(conf, 'sqlite_synchronous', False)
_POLICY_PATH = os.path.abspath(os.path.join(CONF.state_path,
'manila/tests/policy.json'))
opts.set_defaults(conf, policy_file=_POLICY_PATH)
_safe_set_of_opts(conf, 'share_export_ip', '0.0.0.0')
_safe_set_of_opts(conf, 'service_instance_user', 'fake_user')
_API_PASTE_PATH = os.path.abspath(os.path.join(CONF.state_path,
'etc/manila/api-paste.ini'))
wsgi.register_opts(conf)
_safe_set_of_opts(conf, 'api_paste_config', _API_PASTE_PATH)
_safe_set_of_opts(conf, 'share_driver',
'manila.tests.fake_driver.FakeShareDriver')
_safe_set_of_opts(conf, 'auth_strategy', 'noauth')
_safe_set_of_opts(conf, 'zfs_share_export_ip', '1.1.1.1')
_safe_set_of_opts(conf, 'zfs_service_ip', '2.2.2.2')
_safe_set_of_opts(conf, 'zfs_zpool_list', ['foo', 'bar'])
_safe_set_of_opts(conf, 'zfs_share_helpers', 'NFS=foo.bar.Helper')
_safe_set_of_opts(conf, 'zfs_replica_snapshot_prefix', 'foo_prefix_')
_safe_set_of_opts(conf, 'hitachi_hsp_host', '172.24.47.190')
_safe_set_of_opts(conf, 'hitachi_hsp_username', 'hsp_user')
_safe_set_of_opts(conf, 'hitachi_hsp_password', 'hsp_password')
_safe_set_of_opts(conf, 'qnap_management_url', 'http://1.2.3.4:8080')
_safe_set_of_opts(conf, 'qnap_share_ip', '1.2.3.4')
_safe_set_of_opts(conf, 'qnap_nas_login', 'admin')
_safe_set_of_opts(conf, 'qnap_nas_password', 'qnapadmin')
_safe_set_of_opts(conf, 'qnap_poolname', 'Storage Pool 1')
def _safe_set_of_opts(conf, *args, **kwargs):
try:
conf.set_default(*args, **kwargs)
except config.cfg.NoSuchOptError:
# Assumed that opt is not imported and not used
pass
| bswartz/manila | manila/tests/conf_fixture.py | Python | apache-2.0 | 2,989 |
# Copyright 2014 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import contextlib
import copy
import os
import mock
from cinder import exception
from cinder.image import image_utils
from cinder import test
from cinder.volume.drivers import smbfs
class SmbFsTestCase(test.TestCase):
_FAKE_SHARE = '//1.2.3.4/share1'
_FAKE_MNT_BASE = '/mnt'
_FAKE_VOLUME_NAME = 'volume-4f711859-4928-4cb7-801a-a50c37ceaccc'
_FAKE_TOTAL_SIZE = '2048'
_FAKE_TOTAL_AVAILABLE = '1024'
_FAKE_TOTAL_ALLOCATED = 1024
_FAKE_VOLUME = {'id': '4f711859-4928-4cb7-801a-a50c37ceaccc',
'size': 1,
'provider_location': _FAKE_SHARE,
'name': _FAKE_VOLUME_NAME,
'status': 'available'}
_FAKE_MNT_POINT = os.path.join(_FAKE_MNT_BASE, 'fake_hash')
_FAKE_VOLUME_PATH = os.path.join(_FAKE_MNT_POINT, _FAKE_VOLUME_NAME)
_FAKE_SNAPSHOT_ID = '5g811859-4928-4cb7-801a-a50c37ceacba'
_FAKE_SNAPSHOT = {'id': _FAKE_SNAPSHOT_ID,
'volume': _FAKE_VOLUME,
'status': 'available',
'volume_size': 1}
_FAKE_SNAPSHOT_PATH = (
_FAKE_VOLUME_PATH + '-snapshot' + _FAKE_SNAPSHOT_ID)
_FAKE_SHARE_OPTS = '-o username=Administrator,password=12345'
_FAKE_OPTIONS_DICT = {'username': 'Administrator',
'password': '12345'}
_FAKE_LISTDIR = [_FAKE_VOLUME_NAME, _FAKE_VOLUME_NAME + '.vhd',
_FAKE_VOLUME_NAME + '.vhdx', 'fake_folder']
_FAKE_SMBFS_CONFIG = mock.MagicMock()
_FAKE_SMBFS_CONFIG.smbfs_oversub_ratio = 2
_FAKE_SMBFS_CONFIG.smbfs_used_ratio = 0.5
_FAKE_SMBFS_CONFIG.smbfs_shares_config = '/fake/config/path'
_FAKE_SMBFS_CONFIG.smbfs_default_volume_format = 'raw'
_FAKE_SMBFS_CONFIG.smbfs_sparsed_volumes = False
def setUp(self):
super(SmbFsTestCase, self).setUp()
smbfs.SmbfsDriver.__init__ = lambda x: None
self._smbfs_driver = smbfs.SmbfsDriver()
self._smbfs_driver._remotefsclient = mock.Mock()
self._smbfs_driver._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
self._smbfs_driver._execute = mock.Mock()
self._smbfs_driver.base = self._FAKE_MNT_BASE
def test_delete_volume(self):
drv = self._smbfs_driver
fake_vol_info = self._FAKE_VOLUME_PATH + '.info'
drv._ensure_share_mounted = mock.MagicMock()
fake_ensure_mounted = drv._ensure_share_mounted
drv._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
drv.get_active_image_from_info = mock.Mock(
return_value=self._FAKE_VOLUME_NAME)
drv._delete = mock.Mock()
drv._local_path_volume_info = mock.Mock(
return_value=fake_vol_info)
with mock.patch('os.path.exists', lambda x: True):
drv.delete_volume(self._FAKE_VOLUME)
fake_ensure_mounted.assert_called_once_with(self._FAKE_SHARE)
drv._delete.assert_any_call(
self._FAKE_VOLUME_PATH)
drv._delete.assert_any_call(fake_vol_info)
def _test_setup(self, config, share_config_exists=True):
fake_exists = mock.Mock(return_value=share_config_exists)
fake_ensure_mounted = mock.MagicMock()
self._smbfs_driver._ensure_shares_mounted = fake_ensure_mounted
self._smbfs_driver.configuration = config
with mock.patch('os.path.exists', fake_exists):
if not (config.smbfs_shares_config and share_config_exists and
config.smbfs_oversub_ratio > 0 and
0 <= config.smbfs_used_ratio <= 1):
self.assertRaises(exception.SmbfsException,
self._smbfs_driver.do_setup,
None)
else:
self._smbfs_driver.do_setup(None)
self.assertEqual(self._smbfs_driver.shares, {})
fake_ensure_mounted.assert_called_once()
def test_setup_missing_shares_config_option(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_shares_config = None
self._test_setup(fake_config, None)
def test_setup_missing_shares_config_file(self):
self._test_setup(self._FAKE_SMBFS_CONFIG, False)
def test_setup_invlid_oversub_ratio(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_oversub_ratio = -1
self._test_setup(fake_config)
def test_setup_invalid_used_ratio(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_used_ratio = -1
self._test_setup(fake_config)
def _test_create_volume(self, volume_exists=False, volume_format=None):
fake_method = mock.MagicMock()
self._smbfs_driver.configuration = copy.copy(self._FAKE_SMBFS_CONFIG)
self._smbfs_driver._set_rw_permissions_for_all = mock.MagicMock()
fake_set_permissions = self._smbfs_driver._set_rw_permissions_for_all
self._smbfs_driver.get_volume_format = mock.MagicMock()
windows_image_format = False
fake_vol_path = self._FAKE_VOLUME_PATH
self._smbfs_driver.get_volume_format.return_value = volume_format
if volume_format:
if volume_format in ('vhd', 'vhdx'):
windows_image_format = volume_format
if volume_format == 'vhd':
windows_image_format = 'vpc'
method = '_create_windows_image'
fake_vol_path += '.' + volume_format
else:
method = '_create_%s_file' % volume_format
if volume_format == 'sparsed':
self._smbfs_driver.configuration.smbfs_sparsed_volumes = (
True)
else:
method = '_create_regular_file'
setattr(self._smbfs_driver, method, fake_method)
with mock.patch('os.path.exists', new=lambda x: volume_exists):
if volume_exists:
self.assertRaises(exception.InvalidVolume,
self._smbfs_driver._do_create_volume,
self._FAKE_VOLUME)
return
self._smbfs_driver._do_create_volume(self._FAKE_VOLUME)
if windows_image_format:
fake_method.assert_called_once_with(
fake_vol_path,
self._FAKE_VOLUME['size'],
windows_image_format)
else:
fake_method.assert_called_once_with(
fake_vol_path, self._FAKE_VOLUME['size'])
fake_set_permissions.assert_called_once_with(fake_vol_path)
def test_create_existing_volume(self):
self._test_create_volume(volume_exists=True)
def test_create_vhdx(self):
self._test_create_volume(volume_format='vhdx')
def test_create_qcow2(self):
self._test_create_volume(volume_format='qcow2')
def test_create_sparsed(self):
self._test_create_volume(volume_format='sparsed')
def test_create_regular(self):
self._test_create_volume()
def _test_find_share(self, existing_mounted_shares=True,
eligible_shares=True):
if existing_mounted_shares:
mounted_shares = ('fake_share1', 'fake_share2', 'fake_share3')
else:
mounted_shares = None
self._smbfs_driver._mounted_shares = mounted_shares
self._smbfs_driver._is_share_eligible = mock.Mock(
return_value=eligible_shares)
fake_capacity_info = ((2, 1, 5), (2, 1, 4), (2, 1, 1))
self._smbfs_driver._get_capacity_info = mock.Mock(
side_effect=fake_capacity_info)
if not mounted_shares:
self.assertRaises(exception.SmbfsNoSharesMounted,
self._smbfs_driver._find_share,
self._FAKE_VOLUME['size'])
elif not eligible_shares:
self.assertRaises(exception.SmbfsNoSuitableShareFound,
self._smbfs_driver._find_share,
self._FAKE_VOLUME['size'])
else:
ret_value = self._smbfs_driver._find_share(
self._FAKE_VOLUME['size'])
# The eligible share with the minimum allocated space
# will be selected
self.assertEqual(ret_value, 'fake_share3')
def test_find_share(self):
self._test_find_share()
def test_find_share_missing_mounted_shares(self):
self._test_find_share(existing_mounted_shares=False)
def test_find_share_missing_eligible_shares(self):
self._test_find_share(eligible_shares=False)
def _test_is_share_eligible(self, capacity_info, volume_size):
self._smbfs_driver._get_capacity_info = mock.Mock(
return_value=[float(x << 30) for x in capacity_info])
self._smbfs_driver.configuration = self._FAKE_SMBFS_CONFIG
return self._smbfs_driver._is_share_eligible(self._FAKE_SHARE,
volume_size)
def test_share_volume_above_used_ratio(self):
fake_capacity_info = (4, 1, 1)
fake_volume_size = 2
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, False)
def test_eligible_share(self):
fake_capacity_info = (4, 4, 0)
fake_volume_size = 1
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, True)
def test_share_volume_above_oversub_ratio(self):
fake_capacity_info = (4, 4, 7)
fake_volume_size = 2
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, False)
def test_share_reserved_above_oversub_ratio(self):
fake_capacity_info = (4, 4, 10)
fake_volume_size = 1
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, False)
def test_parse_options(self):
(opt_list,
opt_dict) = self._smbfs_driver.parse_options(
self._FAKE_SHARE_OPTS)
expected_ret = ([], self._FAKE_OPTIONS_DICT)
self.assertEqual(expected_ret, (opt_list, opt_dict))
def test_parse_credentials(self):
fake_smb_options = r'-o user=MyDomain\Administrator,noperm'
expected_flags = '-o username=Administrator,noperm'
flags = self._smbfs_driver.parse_credentials(fake_smb_options)
self.assertEqual(expected_flags, flags)
def test_get_volume_path(self):
self._smbfs_driver.get_volume_format = mock.Mock(
return_value='vhd')
self._smbfs_driver._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
expected = self._FAKE_VOLUME_PATH + '.vhd'
ret_val = self._smbfs_driver.local_path(self._FAKE_VOLUME)
self.assertEqual(expected, ret_val)
def test_initialize_connection(self):
self._smbfs_driver.get_active_image_from_info = mock.Mock(
return_value=self._FAKE_VOLUME_NAME)
self._smbfs_driver._get_mount_point_base = mock.Mock(
return_value=self._FAKE_MNT_BASE)
self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}
self._smbfs_driver._qemu_img_info = mock.Mock(
return_value=mock.Mock(file_format='raw'))
fake_data = {'export': self._FAKE_SHARE,
'format': 'raw',
'name': self._FAKE_VOLUME_NAME,
'options': self._FAKE_SHARE_OPTS}
expected = {
'driver_volume_type': 'smbfs',
'data': fake_data,
'mount_point_base': self._FAKE_MNT_BASE}
ret_val = self._smbfs_driver.initialize_connection(
self._FAKE_VOLUME, None)
self.assertEqual(expected, ret_val)
def _test_extend_volume(self, extend_failed=False, image_format='raw'):
drv = self._smbfs_driver
drv.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH)
drv._check_extend_volume_support = mock.Mock(
return_value=True)
drv._is_file_size_equal = mock.Mock(
return_value=not extend_failed)
drv._qemu_img_info = mock.Mock(
return_value=mock.Mock(file_format=image_format))
with contextlib.nested(
mock.patch.object(image_utils, 'resize_image'),
mock.patch.object(image_utils, 'convert_image')) as (
fake_resize, fake_convert):
if extend_failed:
self.assertRaises(exception.ExtendVolumeError,
drv._extend_volume,
self._FAKE_VOLUME, mock.sentinel.new_size)
else:
drv._extend_volume(
self._FAKE_VOLUME,
mock.sentinel.new_size)
if image_format in (drv._DISK_FORMAT_VHDX,
drv._DISK_FORMAT_VHD_LEGACY):
fake_tmp_path = self._FAKE_VOLUME_PATH + '.tmp'
fake_convert.assert_any_call(self._FAKE_VOLUME_PATH,
fake_tmp_path, 'raw')
fake_resize.assert_called_once_with(
fake_tmp_path, mock.sentinel.new_size)
fake_convert.assert_any_call(fake_tmp_path,
self._FAKE_VOLUME_PATH,
image_format)
else:
fake_resize.assert_called_once_with(
self._FAKE_VOLUME_PATH, mock.sentinel.new_size)
def test_extend_volume(self):
self._test_extend_volume()
def test_extend_volume_failed(self):
self._test_extend_volume(extend_failed=True)
def test_extend_vhd_volume(self):
self._test_extend_volume(image_format='vpc')
def _test_check_extend_support(self, has_snapshots=False,
is_eligible=True):
self._smbfs_driver.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH)
if has_snapshots:
active_file_path = self._FAKE_SNAPSHOT_PATH
else:
active_file_path = self._FAKE_VOLUME_PATH
self._smbfs_driver.get_active_image_from_info = mock.Mock(
return_value=active_file_path)
self._smbfs_driver._is_share_eligible = mock.Mock(
return_value=is_eligible)
if has_snapshots:
self.assertRaises(exception.InvalidVolume,
self._smbfs_driver._check_extend_volume_support,
self._FAKE_VOLUME, 2)
elif not is_eligible:
self.assertRaises(exception.ExtendVolumeError,
self._smbfs_driver._check_extend_volume_support,
self._FAKE_VOLUME, 2)
else:
self._smbfs_driver._check_extend_volume_support(
self._FAKE_VOLUME, 2)
self._smbfs_driver._is_share_eligible.assert_called_once_with(
self._FAKE_SHARE, 1)
def test_check_extend_support(self):
self._test_check_extend_support()
def test_check_extend_volume_with_snapshots(self):
self._test_check_extend_support(has_snapshots=True)
def test_check_extend_volume_uneligible_share(self):
self._test_check_extend_support(is_eligible=False)
def test_create_volume_from_in_use_snapshot(self):
fake_snapshot = {'status': 'in-use'}
self.assertRaises(
exception.InvalidSnapshot,
self._smbfs_driver.create_volume_from_snapshot,
self._FAKE_VOLUME, fake_snapshot)
def test_copy_volume_from_snapshot(self):
drv = self._smbfs_driver
fake_volume_info = {self._FAKE_SNAPSHOT_ID: 'fake_snapshot_file_name'}
fake_img_info = mock.MagicMock()
fake_img_info.backing_file = self._FAKE_VOLUME_NAME
drv.get_volume_format = mock.Mock(
return_value='raw')
drv._local_path_volume_info = mock.Mock(
return_value=self._FAKE_VOLUME_PATH + '.info')
drv._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
drv._read_info_file = mock.Mock(
return_value=fake_volume_info)
drv._qemu_img_info = mock.Mock(
return_value=fake_img_info)
drv.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH[:-1])
drv._extend_volume = mock.Mock()
drv._set_rw_permissions_for_all = mock.Mock()
with mock.patch.object(image_utils, 'convert_image') as (
fake_convert_image):
drv._copy_volume_from_snapshot(
self._FAKE_SNAPSHOT, self._FAKE_VOLUME,
self._FAKE_VOLUME['size'])
drv._extend_volume.assert_called_once_with(
self._FAKE_VOLUME, self._FAKE_VOLUME['size'])
fake_convert_image.assert_called_once_with(
self._FAKE_VOLUME_PATH, self._FAKE_VOLUME_PATH[:-1], 'raw')
def test_ensure_mounted(self):
self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}
self._smbfs_driver._ensure_share_mounted(self._FAKE_SHARE)
self._smbfs_driver._remotefsclient.mount.assert_called_once_with(
self._FAKE_SHARE, self._FAKE_SHARE_OPTS.split())
def _test_copy_image_to_volume(self, unsupported_qemu_version=False,
wrong_size_after_fetch=False):
drv = self._smbfs_driver
vol_size_bytes = self._FAKE_VOLUME['size'] << 30
fake_image_service = mock.MagicMock()
fake_image_service.show.return_value = (
{'id': 'fake_image_id', 'disk_format': 'raw'})
fake_img_info = mock.MagicMock()
if wrong_size_after_fetch:
fake_img_info.virtual_size = 2 * vol_size_bytes
else:
fake_img_info.virtual_size = vol_size_bytes
if unsupported_qemu_version:
qemu_version = [1, 5]
else:
qemu_version = [1, 7]
drv.get_volume_format = mock.Mock(
return_value=drv._DISK_FORMAT_VHDX)
drv.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH)
drv.get_qemu_version = mock.Mock(
return_value=qemu_version)
drv._do_extend_volume = mock.Mock()
drv.configuration = mock.MagicMock()
drv.configuration.volume_dd_blocksize = (
mock.sentinel.block_size)
exc = None
with contextlib.nested(
mock.patch.object(image_utils,
'fetch_to_volume_format'),
mock.patch.object(image_utils,
'qemu_img_info')) as (
fake_fetch,
fake_qemu_img_info):
if wrong_size_after_fetch:
exc = exception.ImageUnacceptable
elif unsupported_qemu_version:
exc = exception.InvalidVolume
fake_qemu_img_info.return_value = fake_img_info
if exc:
self.assertRaises(
exc, drv.copy_image_to_volume,
mock.sentinel.context, self._FAKE_VOLUME,
fake_image_service,
mock.sentinel.image_id)
else:
drv.copy_image_to_volume(
mock.sentinel.context, self._FAKE_VOLUME,
fake_image_service,
mock.sentinel.image_id)
fake_fetch.assert_called_once_with(
mock.sentinel.context, fake_image_service,
mock.sentinel.image_id, self._FAKE_VOLUME_PATH,
drv._DISK_FORMAT_VHDX,
mock.sentinel.block_size)
drv._do_extend_volume.assert_called_once_with(
self._FAKE_VOLUME_PATH, self._FAKE_VOLUME['size'])
def test_copy_image_to_volume(self):
self._test_copy_image_to_volume()
def test_copy_image_to_volume_wrong_size_after_fetch(self):
self._test_copy_image_to_volume(wrong_size_after_fetch=True)
def test_copy_image_to_volume_unsupported_qemu_version(self):
self._test_copy_image_to_volume(unsupported_qemu_version=True)
def test_get_capacity_info(self):
fake_block_size = 4096.0
fake_total_blocks = 1024
fake_avail_blocks = 512
fake_total_allocated = fake_total_blocks * fake_block_size
fake_df = ('%s %s %s' % (fake_block_size, fake_total_blocks,
fake_avail_blocks), None)
fake_du = (str(fake_total_allocated), None)
self._smbfs_driver._get_mount_point_for_share = mock.Mock(
return_value=self._FAKE_MNT_POINT)
self._smbfs_driver._execute = mock.Mock(
side_effect=(fake_df, fake_du))
ret_val = self._smbfs_driver._get_capacity_info(self._FAKE_SHARE)
expected = (fake_block_size * fake_total_blocks,
fake_block_size * fake_avail_blocks,
fake_total_allocated)
self.assertEqual(expected, ret_val)
| e0ne/cinder | cinder/tests/test_smbfs.py | Python | apache-2.0 | 22,226 |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tink.python.tink._keyset_reader."""
from typing import cast
from absl.testing import absltest
from tink.proto import tink_pb2
import tink
from tink import core
class JsonKeysetReaderTest(absltest.TestCase):
def test_read(self):
json_keyset = """
{
"primaryKeyId": 42,
"key": [
{
"keyData": {
"typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey",
"keyMaterialType": "SYMMETRIC",
"value": "GhCS/1+ejWpx68NfGt6ziYHd"
},
"outputPrefixType": "TINK",
"keyId": 42,
"status": "ENABLED"
}
]
}"""
reader = tink.JsonKeysetReader(json_keyset)
keyset = reader.read()
self.assertEqual(keyset.primary_key_id, 42)
self.assertLen(keyset.key, 1)
def test_read_invalid(self):
reader = tink.JsonKeysetReader('not json')
with self.assertRaises(core.TinkError):
reader.read()
def test_read_encrypted(self):
# encryptedKeyset is a base64-encoding of 'some ciphertext with keyset'
json_encrypted_keyset = """
{
"encryptedKeyset": "c29tZSBjaXBoZXJ0ZXh0IHdpdGgga2V5c2V0",
"keysetInfo": {
"primaryKeyId": 42,
"keyInfo": [
{
"typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey",
"outputPrefixType": "TINK",
"keyId": 42,
"status": "ENABLED"
}
]
}
}"""
reader = tink.JsonKeysetReader(json_encrypted_keyset)
enc_keyset = reader.read_encrypted()
self.assertEqual(enc_keyset.encrypted_keyset,
b'some ciphertext with keyset')
self.assertLen(enc_keyset.keyset_info.key_info, 1)
self.assertEqual(enc_keyset.keyset_info.key_info[0].type_url,
'type.googleapis.com/google.crypto.tink.AesGcmKey')
def test_read_encrypted_invalid(self):
reader = tink.JsonKeysetReader('not json')
with self.assertRaises(core.TinkError):
reader.read_encrypted()
class BinaryKeysetReaderTest(absltest.TestCase):
def test_read(self):
keyset = tink_pb2.Keyset()
keyset.primary_key_id = 42
key = keyset.key.add()
key.key_data.type_url = 'type.googleapis.com/google.crypto.tink.AesGcmKey'
key.key_data.key_material_type = tink_pb2.KeyData.SYMMETRIC
key.key_data.value = b'GhCS/1+ejWpx68NfGt6ziYHd'
key.output_prefix_type = tink_pb2.TINK
key.key_id = 42
key.status = tink_pb2.ENABLED
reader = tink.BinaryKeysetReader(keyset.SerializeToString())
self.assertEqual(keyset, reader.read())
def test_read_none(self):
with self.assertRaises(core.TinkError):
reader = tink.BinaryKeysetReader(cast(bytes, None))
reader.read()
def test_read_empty(self):
with self.assertRaises(core.TinkError):
reader = tink.BinaryKeysetReader(b'')
reader.read()
def test_read_invalid(self):
with self.assertRaises(core.TinkError):
reader = tink.BinaryKeysetReader(b'some weird data')
reader.read()
def test_read_encrypted(self):
encrypted_keyset = tink_pb2.EncryptedKeyset()
encrypted_keyset.encrypted_keyset = b'c29tZSBjaXBoZXJ0ZXh0IHdpdGgga2V5c2V0'
encrypted_keyset.keyset_info.primary_key_id = 42
key_info = encrypted_keyset.keyset_info.key_info.add()
key_info.type_url = 'type.googleapis.com/google.crypto.tink.AesGcmKey'
key_info.output_prefix_type = tink_pb2.TINK
key_info.key_id = 42
key_info.status = tink_pb2.ENABLED
reader = tink.BinaryKeysetReader(
encrypted_keyset.SerializeToString())
self.assertEqual(encrypted_keyset, reader.read_encrypted())
def test_read_encrypted_none(self):
with self.assertRaises(core.TinkError):
reader = tink.BinaryKeysetReader(cast(bytes, None))
reader.read_encrypted()
def test_read_encrypted_empty(self):
with self.assertRaises(core.TinkError):
reader = tink.BinaryKeysetReader(b'')
reader.read_encrypted()
def test_read_encrypted_invalid(self):
with self.assertRaises(core.TinkError):
reader = tink.BinaryKeysetReader(b'some weird data')
reader.read_encrypted()
if __name__ == '__main__':
absltest.main()
| google/tink | python/tink/_keyset_reader_test.py | Python | apache-2.0 | 4,878 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of compound:prt in UD_Irish-TwittIrish</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/ga_twittirish/ga_twittirish-dep-compound-prt.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_irish-twittirish-relations-compoundprt">Treebank Statistics: UD_Irish-TwittIrish: Relations: <code class="language-plaintext highlighter-rouge">compound:prt</code></h2>
<p>This relation is a language-specific subtype of <tt><a href="ga_twittirish-dep-compound.html">compound</a></tt>.</p>
<p>6 nodes (0%) are attached to their parents as <code class="language-plaintext highlighter-rouge">compound:prt</code>.</p>
<p>6 instances of <code class="language-plaintext highlighter-rouge">compound:prt</code> (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 1.5.</p>
<p>The following 5 pairs of parts of speech are connected with <code class="language-plaintext highlighter-rouge">compound:prt</code>: <tt><a href="ga_twittirish-pos-VERB.html">VERB</a></tt>-<tt><a href="ga_twittirish-pos-ADV.html">ADV</a></tt> (2; 33% instances), <tt><a href="ga_twittirish-pos-NOUN.html">NOUN</a></tt>-<tt><a href="ga_twittirish-pos-ADV.html">ADV</a></tt> (1; 17% instances), <tt><a href="ga_twittirish-pos-NOUN.html">NOUN</a></tt>-<tt><a href="ga_twittirish-pos-NOUN.html">NOUN</a></tt> (1; 17% instances), <tt><a href="ga_twittirish-pos-PROPN.html">PROPN</a></tt>-<tt><a href="ga_twittirish-pos-ADP.html">ADP</a></tt> (1; 17% instances), <tt><a href="ga_twittirish-pos-VERB.html">VERB</a></tt>-<tt><a href="ga_twittirish-pos-NOUN.html">NOUN</a></tt> (1; 17% instances).</p>
<pre><code class="language-conllu"># visual-style 20 bgColor:blue
# visual-style 20 fgColor:white
# visual-style 19 bgColor:blue
# visual-style 19 fgColor:white
# visual-style 19 20 compound:prt color:blue
1 RT RT SYM _ _ 4 parataxis:rt _ _
2 @Fiontar @Fiontar PROPN _ _ 4 vocative:mention _ SpaceAfter=No
3 : : PUNCT _ _ 4 punct _ _
4 Oíche oíche NOUN _ _ 0 root _ Lang=ga
5 eolais eolas NOUN _ _ 4 nmod _ Lang=ga
6 CAO CAO PROPN _ _ 5 nmod _ Lang=ga
7 ar ar ADP _ _ 8 case _ Lang=ga
8 siúl siúl NOUN _ _ 4 xcomp _ Lang=ga
9 i i ADP _ _ 10 case _ Lang=ga
10 DCU DCU PROPN _ _ 8 nmod _ Lang=ga
11 ar ar ADP _ _ 13 case _ Lang=ga
12 an an DET _ _ 13 det _ Lang=ga
13 Déardaoin Déardaoin NOUN _ _ 8 nmod _ Lang=ga
14 seo seo DET _ _ 13 det _ Lang=ga
15 , , PUNCT _ _ 16 punct _ _
16 17ú 17ú NUM _ _ 13 appos _ Lang=ga
17 Eanáir Eanáir NOUN _ _ 16 flat _ Lang=ga|SpaceAfter=No
18 . . PUNCT _ _ 19 punct _ _
19 Buail buail VERB _ _ 1 parataxis:sentence _ Lang=ga
20 isteach isteach ADV _ _ 19 compound:prt _ Lang=ga
21 againn ag ADP _ _ 19 obl:prep _ Lang=ga
22 chun chun ADP _ _ 23 case _ Lang=ga
23 labhairt labhairt NOUN _ _ 19 xcomp _ Lang=ga
24 faoi faoi ADP _ _ 25 case _ Lang=ga
25 bunchéimeanna bunchéim NOUN _ _ 23 obl _ CorrectForm=bhunchéimeanna|Lang=ga
26 Fiontar Fiontar PROPN _ _ 25 nmod _ Lang=ga|SpaceAfter=No
27 . . PUNCT _ _ 19 punct _ _
</code></pre>
<pre><code class="language-conllu"># visual-style 5 bgColor:blue
# visual-style 5 fgColor:white
# visual-style 4 bgColor:blue
# visual-style 4 fgColor:white
# visual-style 4 5 compound:prt color:blue
1 Leis le ADP _ _ 3 case _ Lang=ga
2 an an DET _ _ 3 det _ Lang=ga
3 méid méid NOUN _ _ 15 obl _ Lang=ga
4 tabhairt tabhairt NOUN _ _ 3 xcomp _ Lang=ga
5 amach amach ADV _ _ 4 compound:prt _ Lang=ga
6 a a PART _ _ 7 nsubj _ Lang=ga
7 bhíonn bí VERB _ _ 3 acl:relcl _ Lang=ga
8 ráite ráite ADJ _ _ 7 xcomp:pred _ Lang=ga
9 maidir maidir ADP _ _ 12 case _ Lang=ga
10 leis le ADP _ _ 9 fixed _ Lang=ga
11 an an DET _ _ 12 det _ Lang=ga
12 seirbhís seirbhís NOUN _ _ 7 obl _ Lang=ga
13 sláinte sláinte NOUN _ _ 12 nmod _ Lang=ga|SpaceAfter=No
14 , , PUNCT _ _ 15 punct _ _
15 tá bí VERB _ _ 0 root _ Lang=ga
16 na an DET _ _ 17 det _ Lang=ga
17 daoine duine NOUN _ _ 15 nsubj _ Lang=ga
18 atá bí VERB _ _ 17 acl:relcl _ Lang=ga
19 ag ag ADP _ _ 20 case _ Lang=ga
20 obair obair NOUN _ _ 18 xcomp _ Lang=ga
21 ann ann ADV _ _ 22 obl:prep _ Lang=ga
22 an-chairdiúil cairdiúil ADJ _ _ 18 xcomp:pred _ Lang=ga
</code></pre>
<pre><code class="language-conllu"># visual-style 17 bgColor:blue
# visual-style 17 fgColor:white
# visual-style 15 bgColor:blue
# visual-style 15 fgColor:white
# visual-style 15 17 compound:prt color:blue
1 Comhghairdeas comhghairdeas NOUN _ _ 0 root _ Lang=ga
2 libh le ADP _ _ 1 obl:prep _ Lang=ga
3 agus agus CCONJ _ _ 5 cc _ Lang=ga
4 le le ADP _ _ 5 case _ Lang=ga
5 Brian brian PROPN _ _ 2 conj _ _
6 Mac Mac PART _ _ 5 flat:name _ SpaceAfter=No
7 Cuarta Cuarta PROPN _ _ 5 flat:name _ _
8 SJ sj PROPN _ _ 5 flat:name _ _
9 as as ADP _ _ 15 case _ Lang=ga
10 an an DET _ _ 11 det _ Lang=ga
11 obair obair NOUN _ _ 15 obj _ Lang=ga
12 mhór mór ADJ _ _ 11 amod _ Lang=ga
13 seo seo DET _ _ 11 det _ Lang=ga
14 a a PART _ _ 15 mark _ Lang=ga
15 chur cur NOUN _ _ 1 xcomp _ Lang=ga
16 i i ADP _ _ 17 case _ Lang=ga
17 gcrích crích NOUN _ _ 15 compound:prt _ Lang=ga|SpaceAfter=No
18 . . PUNCT _ _ 1 punct _ _
19 https://t.co/jpzGJ2pX91 https://t.co/jpzgj2px91 SYM _ _ 1 parataxis:url _ _
</code></pre>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
| UniversalDependencies/universaldependencies.github.io | treebanks/ga_twittirish/ga_twittirish-dep-compound-prt.html | HTML | apache-2.0 | 11,071 |
---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
---
globalization.getLocaleName
===========
Get the string identifier for the client's current locale setting.
navigator.globalization.getLocaleName(successCallback, errorCallback);
Description
-----------
Returns the locale identifier string to the `successCallback` with a
`properties` object as a parameter. That object should have a `value`
property with a `String` value.
If there is an error getting the locale, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.UNKNOWN\_ERROR`.
Supported Platforms
-------------------
- Android
- BlackBerry WebWorks (OS 5.0 and higher)
- iOS
- Windows Phone 8
Quick Example
-------------
When the browser is set to the `en\_US` locale, this displays a popup
dialog with the text `locale: en\_US`.
navigator.globalization.getLocaleName(
function (locale) {alert('locale: ' + locale.value + '\n');},
function () {alert('Error getting locale\n');}
);
Full Example
------------
<!DOCTYPE HTML>
<html>
<head>
<title>getLocaleName Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-3.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
function checkLocale() {
navigator.globalization.getLocaleName(
function (locale) {alert('locale: ' + locale.value + '\n');},
function () {alert('Error getting locale\n');}
);
}
</script>
</head>
<body>
<button onclick="checkLocale()">Click for locale</button>
</body>
</html>
Windows Phone 8 Quirks
---------------------
- Returns the two-letter code defined in ISO 3166 for the current country/region.
| maveriklko9719/Coffee-Spills | docs/en/3.0.0rc1/cordova/globalization/globalization.getLocaleName.md | Markdown | apache-2.0 | 2,663 |
package sghelm
import (
"context"
"encoding/json"
"sort"
"strings"
"github.com/imdario/mergo"
"github.com/pkg/errors"
"k8s.io/helm/pkg/proto/hapi/chart"
"k8s.io/helm/pkg/repo"
"github.com/supergiant/control/pkg/model"
"github.com/supergiant/control/pkg/sgerrors"
"github.com/supergiant/control/pkg/sghelm/repositories"
"github.com/supergiant/control/pkg/storage"
)
const (
readmeFileName = "readme.md"
repoPrefix = "/helm/repositories/"
)
var _ Servicer = &Service{}
// Servicer is an interface for the helm service.
type Servicer interface {
CreateRepo(ctx context.Context, e *repo.Entry) (*model.RepositoryInfo, error)
UpdateRepo(ctx context.Context, name string, opts *repo.Entry) (*model.RepositoryInfo, error)
GetRepo(ctx context.Context, repoName string) (*model.RepositoryInfo, error)
ListRepos(ctx context.Context) ([]model.RepositoryInfo, error)
DeleteRepo(ctx context.Context, repoName string) (*model.RepositoryInfo, error)
GetChartData(ctx context.Context, repoName, chartName, chartVersion string) (*model.ChartData, error)
ListCharts(ctx context.Context, repoName string) ([]model.ChartInfo, error)
GetChart(ctx context.Context, repoName, chartName, chartVersion string) (*chart.Chart, error)
}
// Service manages helm repositories.
type Service struct {
storage storage.Interface
repos repositories.Interface
}
// NewService constructs a Service for helm repository.
func NewService(s storage.Interface) (*Service, error) {
repos, err := repositories.New(repositories.DefaultHome)
if err != nil {
return nil, errors.Wrap(err, "setup repositories manager")
}
return &Service{
storage: s,
repos: repos,
}, nil
}
// CreateRepo stores a helm repository in the provided storage.
func (s Service) CreateRepo(ctx context.Context, e *repo.Entry) (*model.RepositoryInfo, error) {
if e == nil {
return nil, sgerrors.ErrNilEntity
}
r, err := s.GetRepo(ctx, e.Name)
if err != nil && !sgerrors.IsNotFound(err) {
return nil, err
}
if r != nil && r.Config.Name == e.Name {
return nil, sgerrors.ErrAlreadyExists
}
ind, err := s.repos.GetIndexFile(e)
if err != nil {
return nil, errors.Wrap(err, "get repository index")
}
// store the index file
r = toRepoInfo(e, ind)
rawJSON, err := json.Marshal(r)
if err != nil {
return nil, errors.Wrap(err, "marshal index file")
}
if err = s.storage.Put(ctx, repoPrefix, e.Name, rawJSON); err != nil {
return nil, errors.Wrap(err, "storage")
}
return r, nil
}
// UpdateRepo downloads the latest index file and update a helm repository in the provided storage.
func (s Service) UpdateRepo(ctx context.Context, name string, opts *repo.Entry) (*model.RepositoryInfo, error) {
r, err := s.GetRepo(ctx, name)
if err != nil {
return nil, err
}
// mergo panics on nil entry
if opts == nil {
opts = &repo.Entry{}
}
opts.Name = "" // prevent updating the repo name
// merge configs
if err = mergo.Merge(&r.Config, opts, mergo.WithOverride); err != nil {
return nil, err
}
ind, err := s.repos.GetIndexFile(&r.Config)
if err != nil {
return nil, errors.Wrap(err, "get repository index")
}
// store the index file
r = toRepoInfo(&r.Config, ind)
rawJSON, err := json.Marshal(r)
if err != nil {
return nil, errors.Wrap(err, "marshal index file")
}
if err = s.storage.Put(ctx, repoPrefix, name, rawJSON); err != nil {
return nil, errors.Wrap(err, "storage")
}
return r, nil
}
// GetRepo retrieves the repository index file for provided nam.
func (s Service) GetRepo(ctx context.Context, repoName string) (*model.RepositoryInfo, error) {
res, err := s.storage.Get(ctx, repoPrefix, repoName)
if err != nil {
return nil, errors.Wrap(err, "storage")
}
// not found
if res == nil {
return nil, errors.Wrap(sgerrors.ErrNotFound, "repo not found")
}
r := &model.RepositoryInfo{}
if err = json.Unmarshal(res, r); err != nil {
return nil, errors.Wrap(err, "unmarshal")
}
return r, nil
}
// ListRepos retrieves all helm repositories from the storage.
func (s Service) ListRepos(ctx context.Context) ([]model.RepositoryInfo, error) {
rawRepos, err := s.storage.GetAll(ctx, repoPrefix)
if err != nil {
return nil, errors.Wrap(err, "storage")
}
repos := make([]model.RepositoryInfo, len(rawRepos))
for i, raw := range rawRepos {
r := &model.RepositoryInfo{}
err = json.Unmarshal(raw, r)
if err != nil {
return nil, errors.Wrap(err, "unmarshal")
}
repos[i] = *r
}
return repos, nil
}
// DeleteRepo removes a helm repository from the storage by its name.
func (s Service) DeleteRepo(ctx context.Context, repoName string) (*model.RepositoryInfo, error) {
hrepo, err := s.GetRepo(ctx, repoName)
if err != nil {
return nil, errors.Wrap(err, "get repository")
}
return hrepo, s.storage.Delete(ctx, repoPrefix, repoName)
}
func (s Service) GetChartData(ctx context.Context, repoName, chartName, chartVersion string) (*model.ChartData, error) {
chrt, err := s.GetChart(ctx, repoName, chartName, chartVersion)
if err != nil {
return nil, err
}
return toChartData(chrt), nil
}
func (s Service) ListCharts(ctx context.Context, repoName string) ([]model.ChartInfo, error) {
hrepo, err := s.GetRepo(ctx, repoName)
if err != nil {
return nil, errors.Wrapf(err, "get %s repository info", repoName)
}
return hrepo.Charts, nil
}
func (s Service) GetChart(ctx context.Context, repoName, chartName, chartVersion string) (*chart.Chart, error) {
hrepo, err := s.GetRepo(ctx, repoName)
if err != nil {
return nil, errors.Wrapf(err, "get %s repository info", repoName)
}
ref, err := findChartURL(hrepo.Charts, chartName, chartVersion)
if err != nil {
return nil, errors.Wrapf(err, "get %s(%s) chart", chartName, chartVersion)
}
chrt, err := s.repos.GetChart(hrepo.Config, ref)
if err != nil {
return nil, errors.Wrapf(err, "get %s chart", ref)
}
return chrt, nil
}
func (s Service) GetChartRef(ctx context.Context, repoName, chartName, chartVersion string) (string, error) {
hrepo, err := s.GetRepo(ctx, repoName)
if err != nil {
return "", errors.Wrapf(err, "get %s repository info", repoName)
}
ref, err := findChartURL(hrepo.Charts, chartName, chartVersion)
if err != nil {
return "", errors.Wrapf(err, "get %s(%s) chart", chartName, chartVersion)
}
return ref, nil
}
func toChartData(chrt *chart.Chart) *model.ChartData {
if chrt == nil {
return nil
}
out := &model.ChartData{
Metadata: chrt.Metadata,
}
if chrt.Values != nil {
out.Values = chrt.Values.Raw
}
if chrt.Files != nil {
for _, f := range chrt.Files {
if f != nil && strings.ToLower(f.TypeUrl) == readmeFileName {
out.Readme = string(f.Value)
}
}
}
return out
}
func findChartURL(charts []model.ChartInfo, chartName, chartVersion string) (string, error) {
for _, chrt := range charts {
if chrt.Name != chartName {
continue
}
if len(chrt.Versions) == 0 {
break
}
chrtVer := findChartVersion(chrt.Versions, chartVersion)
if len(chrtVer.URLs) != 0 {
// charts are sorted in descending order
return chrtVer.URLs[0], nil
}
}
return "", sgerrors.ErrNotFound
}
func findChartVersion(chrtVers []model.ChartVersion, version string) model.ChartVersion {
version = strings.TrimSpace(version)
if len(chrtVers) > 0 && version == "" {
return chrtVers[len(chrtVers)-1]
}
for _, v := range chrtVers {
if v.Version == version {
return v
}
}
return model.ChartVersion{}
}
func toRepoInfo(e *repo.Entry, index *repo.IndexFile) *model.RepositoryInfo {
r := &model.RepositoryInfo{
Config: *e,
}
if index == nil || len(index.Entries) == 0 {
return r
}
r.Charts = make([]model.ChartInfo, 0, len(index.Entries))
for name, entry := range index.Entries {
if len(entry) == 0 {
continue
}
// ensure chart versions are sorted in descending order
sort.SliceStable(entry, func(i, j int) bool {
return entry[i].Version > entry[j].Version
})
if entry[0].Deprecated {
continue
}
r.Charts = append(r.Charts, model.ChartInfo{
Name: name,
Repo: e.Name,
Icon: iconFrom(entry),
Description: descriptionFrom(entry),
Versions: toChartVersions(entry),
})
}
// chartVersins received from the helm is a map
// sort the results by name to ensure ordering
sort.SliceStable(r.Charts, func(i, j int) bool {
return r.Charts[i].Name < r.Charts[j].Name
})
return r
}
func iconFrom(cvs repo.ChartVersions) string {
// chartVersions are sorted, use the latest one
if len(cvs) > 0 {
return cvs[0].Icon
}
return ""
}
func descriptionFrom(cvs repo.ChartVersions) string {
// chartVersions are sorted, use the latest one
if len(cvs) > 0 {
return cvs[0].Description
}
return ""
}
func toChartVersions(cvs repo.ChartVersions) []model.ChartVersion {
if len(cvs) == 0 {
return nil
}
chartVersions := make([]model.ChartVersion, 0, len(cvs))
for _, cv := range cvs {
chartVersions = append(chartVersions, model.ChartVersion{
Version: cv.Version,
AppVersion: cv.AppVersion,
Created: cv.Created,
Digest: cv.Digest,
URLs: cv.URLs,
})
}
return chartVersions
}
| supergiant/supergiant | pkg/sghelm/service.go | GO | apache-2.0 | 9,092 |
/**
* Copyright 2011 Modeliosoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modelio.juniper.ide.mongodbmodeler.command.diagram.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.modelio.api.diagram.IDiagramGraphic;
import org.modelio.api.diagram.IDiagramHandle;
import org.modelio.api.diagram.IDiagramNode;
import org.modelio.api.diagram.dg.IDiagramDG;
import org.modelio.api.diagram.tools.DefaultBoxTool;
import org.modelio.api.model.IModelingSession;
import org.modelio.api.model.ITransaction;
import org.modelio.api.modelio.Modelio;
import org.modelio.api.module.IModule;
import org.modelio.api.module.commands.CommandScope;
import org.modelio.juniper.ide.mongodbmodeler.impl.MDACConfigurator;
import org.modelio.metamodel.uml.infrastructure.ModelElement;
import org.modelio.vcore.smkernel.mapi.MObject;
public class SimpleBoxTool extends DefaultBoxTool {
private ElementCreatorCommand command;
private String ownerStereotypeModule;
private String ownerStereotypeName;
public void initialize(List<CommandScope> sourceScopes, List<CommandScope> targetScopes, Map<String,String> parameters, IModule module) {
super.initialize(sourceScopes, targetScopes, parameters, module);
if ("elementFactory".equals(this.getParameter("type"))) {
command = new MDACConfigurator.CallElementFactoryMdacCommand(
this.getParameter("name"));
} else if ("element".equals(this.getParameter("type"))) {
try {
command = new MDACConfigurator.CreateSingleElementMdacCommand(
this.getParameter("metaclass"),
this.getParameter("stereotypeModule"),
this.getParameter("stereotype"),
this.getParameter("addOp"));
} catch (Exception e) {
e.printStackTrace();
}
} else if ("script".equals(this.getParameter("type"))) {
command = new MDACConfigurator.RunScriptMdacCommand(
this.getParameter("path"));
} else if ("java".equals(this.getParameter("type"))) {
command = new MDACConfigurator.RunJavaMdacCommand(
this.getParameter("command"));
}
System.out.println("====> Initialized: " + this.getParameters());
ownerStereotypeModule = this.getParameter("ownerStereotypeModule");
ownerStereotypeName = this.getParameter("ownerStereotype");
}
@Override
public boolean acceptElement(IDiagramHandle representation, IDiagramGraphic graphic) {
ModelElement owner = null;
if (graphic instanceof IDiagramDG) {
owner = representation.getDiagram().getOrigin();
} else {
owner = (ModelElement) graphic.getElement();
}
return acceptElement(owner);
}
protected boolean acceptElement(ModelElement owner) {
if (command != null) {
List<MObject> selectedElements = new ArrayList<MObject>();
selectedElements.add(owner);
boolean accepts = command.accept(selectedElements, getModule());
boolean ownerStereotype = owner.isStereotyped(ownerStereotypeModule, ownerStereotypeName );
return accepts && ownerStereotype;
} else {
return false;
}
}
@Override
public void actionPerformed(final IDiagramHandle representation,
final IDiagramGraphic graphic, final Rectangle rec) {
ModelElement parent = null;
if (graphic instanceof IDiagramDG) {
parent = representation.getDiagram().getOrigin();
} else {
parent = (ModelElement) graphic.getElement();
}
if (command == null) {
ModelElement child = createElement(parent);
unmaskElement(representation, rec, child);
} else {
List<MObject> selectedElements = new ArrayList<MObject>();
selectedElements.add(parent);
command.setElementCreationListener(new IElementCreationListener() {
@Override
public void lastCreatedElementChanged(ModelElement element) {
if (element != null) {
unmaskElement(representation, rec, element);
}
}
});
command.actionPerformed(selectedElements, getModule());
}
}
private void unmaskElement(final IDiagramHandle representation, final Rectangle rec,
final ModelElement child) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
IModelingSession session = Modelio.getInstance().getModelingSession();
try (ITransaction transaction = session.createTransaction("");) {
List<IDiagramGraphic> graph = representation.unmask(child, rec.x,
rec.y);
if (graph.size() > 0)
((IDiagramNode) graph.get(0)).setBounds(rec);
representation.save();
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
protected ModelElement createElement(ModelElement owner) {
throw new RuntimeException("Command not implemented!");
}
}
| juniper-project/modelling-mongodb | src/main/java/org/modelio/juniper/ide/mongodbmodeler/command/diagram/util/SimpleBoxTool.java | Java | apache-2.0 | 5,253 |
#EQUIPE 2
#Nahan Trindade Passos - 1615310021
#Ana Beatriz Frota - 1615310027
#
#
#
#
#
#
import math
print("Digite os termos da equacao ax2+bx+c")
a = float(input("Digite o valor de A:\n"))
if(a==0):
print("Nao e uma equacao de segundo grau")
else:
b = float(input("Valor de B:\n"))
c = float(input("Valor de C:\n"))
delta = (math.pow(b,2) - (4*a*c))
if(delta<0):
print("A equacao nao possui raizes reais")
elif(delta == 0):
raiz = ((-1)*b + math.sqrt(delta))/(2*a)
print("A equacao possui apenas uma raiz",raiz)
else:
raiz1 = ((-1)*b + math.sqrt(delta))/(2*a)
raiz2 = ((-1)*b - math.sqrt(delta))/(2*a)
print("A equacao possui duas raizes")
print("Primeira raiz:",raiz1)
print("Segunda raiz:",raiz2)
| any1m1c/ipc20161 | lista2/ipc_lista2.16.py | Python | apache-2.0 | 824 |
```jsx
const initialState = {
typing: null
};
function toggleTyping() {
if (state.typing) {
setState({ typing: null });
} else {
setState({
typing: {
typing: 'Someone is typing'
}
});
}
}
<div>
<Button theme="primary" onClick={toggleTyping} size="small">toggle</Button>
<br />
<Typing typing={state.typing} />
</div>
```
| dialogs/dialog-web-components | src/components/Typing/README.md | Markdown | apache-2.0 | 369 |
package com.alxgrk.ressign.error.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class OrgNotFoundException extends RuntimeException {
public OrgNotFoundException(String orgId) {
super("could not find organization '" + orgId + "'.");
}
}
| alxgrk/ressign | src/main/java/com/alxgrk/ressign/error/exceptions/OrgNotFoundException.java | Java | apache-2.0 | 373 |
$(function(){
// 设置jQuery Ajax全局的参数
$.ajaxSetup({
type: "POST",
error: function(jqXHR, textStatus, errorThrown){
switch (jqXHR.status){
case(500):
alert("服务器系统内部错误");
break;
case(401):
alert("未登录");
window.location.href = webRoot;
break;
case(403):
alert("无权限执行此操作");
case(404):
alert("找不到处理的方法");
break;
case(408):
alert("请求超时");
break;
case(518):
alert("登录超时");
window.location.href = webRoot;
break;
default:
alert("未知错误");
}
}
});
// 点击表头排序
$('th[class^=sorting]').click(function(){
var className = $(this).attr('class');
var sort = $(this).attr('title');
if(sort != ''){
$(this).parent().find('th').removeClass();
if(className == 'sorting'){
$(this).addClass('sorting_asc');
sort += ' asc';
}
else if(className == 'sorting_asc'){
$(this).addClass('sorting_desc');
sort += ' desc';
}
else if(className == 'sorting_desc'){
$(this).addClass('sorting_asc');
sort += ' asc';
}
var url = $('.panel-search form').attr('action');
if(url.indexOf('?') > -1){
url += '&sort=' + sort;
}
else{
url += '?sort=' + sort;
}
$.ajax({
type: 'post',
url: webRoot+url,
data: $('.panel-search form').serialize(),
dataType: 'html',
success: function(data){
$(".panel-content").html(data);
}
});
}
});
});
/**
* 菜单跳转
* @param obj 菜单本身(A标签)
* @param url 菜单访问地址
*/
function menu(obj,url){
$('.page-sidebar-menu li').removeClass('active');
rootliActive(obj);
$(obj).parent().addClass('active');
var header = '<li><i class="fa fa-home"> </i></li>' + getHeader(obj,'','');
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'html',
success: function(data){
$('.page-title').html($(obj).find('.title').text());
$('.content-header').html(header);
$('.content-panel').html(data);
}
});
}
/**
* 当前菜单的根目录选中
* @param obj
*/
function rootliActive(obj){
if($(obj).parent().parent().attr('class') == 'sub-menu'){
rootliActive($(obj).parent().parent().prev());
}
else{
$(obj).parent().addClass('active');
$(obj).parent().find('.title').after('<span class="selected"></span>');
}
}
/**
* 初始化页面的头
* @param obj
* @param header
* @param fa
* @returns {String}
*/
function getHeader(obj,header,fa){
var title = '<li><span>' + $(obj).find('.title').text() + '</span>' + fa + '</li>' + header;
if($(obj).parent().parent().attr('class') == 'sub-menu'){
return getHeader($(obj).parent().parent().prev(), title, '<i class="fa fa-angle-right"></i>');
}
else{
return title;
}
}
/**
* 分页查询
* @param pageNo 页码
*/
function page(pageNo){
var url = $('.panel-search form').attr('action');
if(url.indexOf('?') > -1){
url += '&pageNo=' + pageNo;
}
else{
url += '?pageNo=' + pageNo;
}
$.ajax({
type: 'post',
url: webRoot+url,
data: $('.panel-search form').serialize(),
dataType: 'html',
success: function(data){
$(".panel-content").html(data);
}
});
}
/**
* 查询
*/
function search(){
$.ajax({
type: 'post',
url: webRoot+$('.panel-search form').attr('action'),
data: $('.panel-search form').serialize(),
dataType: 'html',
success: function(data){
$(".panel-content").html(data);
}
});
}
/**
* 重置
*/
function reset(){
$('.panel-search form')[0].reset();
search();
}
/**
* 新增
* @param url 新增请求路径
*/
function add(url){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'html',
success: function(data){
$(".panel-search").hide();
$(".panel-content").html(data);
}
});
}
/**
* 修改
* @param url 修改请求路径
*/
function update(url){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'html',
success: function(data){
$(".panel-search").hide();
$(".panel-content").html(data);
}
});
}
/**
* 保存
* @param obj 保存按钮(按钮需要在form表单中)
*/
function save(obj){
if($(obj).closest('form').valid()){
$.ajax({
type: 'post',
url: webRoot+$(obj).closest('form').attr('action'),
data: $(obj).closest('form').serialize(),
dataType: 'json',
success: function(data){
alert(messages[data.result]);
search();
$(".panel-search").show();
}
});
}
}
/**
* 取消返回
*/
function cancel(){
search();
$(".panel-search").show();
}
/**
* 删除
* @param url 删除请求路径
* @param message 删除前提示信息
* @returns
*/
function del(url){
if(confirm(messages.delete_confirm)){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'json',
success: function(data){
alert(messages[data.result]);
search();
}
});
}
}
/**
* ajax 提交
* @param url 请求路径
* @param isRefreshList 是否刷新列表
*/
function ajaxSubmit(url,isRefreshList){
$.ajax({
type: 'post',
url: webRoot+url,
dataType: 'json',
success: function(data){
alert(messages[data.result]);
if(isRefreshList){
search();
}
}
});
} | jiangyuanlin/hello | src/main/webapp/static/custom/common.js | JavaScript | apache-2.0 | 5,440 |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.guvnor.m2repo.client.upload;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.guvnor.m2repo.client.event.M2RepoSearchEvent;
import org.gwtbootstrap3.client.shared.event.ModalHideEvent;
import org.gwtbootstrap3.client.shared.event.ModalHideHandler;
import org.gwtbootstrap3.client.ui.base.form.AbstractForm;
import org.jboss.errai.ioc.client.container.SyncBeanManager;
import static org.guvnor.m2repo.model.HTMLFileManagerFields.*;
import static org.guvnor.m2repo.utils.FileNameUtilities.*;
@Dependent
public class UploadFormPresenter implements UploadFormView.Presenter {
private Event<M2RepoSearchEvent> searchEvent;
private UploadFormView view;
@Inject
public UploadFormPresenter( final UploadFormView view,
final Event<M2RepoSearchEvent> searchEvent,
final SyncBeanManager iocManager ) {
this.view = view;
//When pop-up is closed destroy bean to avoid memory leak
view.addHideHandler( new ModalHideHandler() {
@Override
public void onHide( ModalHideEvent hideEvent ) {
iocManager.destroyBean( UploadFormPresenter.this );
}
} );
this.searchEvent = searchEvent;
}
@PostConstruct
public void init() {
view.init( this );
}
@Override
public void handleSubmitComplete( final AbstractForm.SubmitCompleteEvent event ) {
view.hideUploadingBusy();
if ( UPLOAD_OK.equalsIgnoreCase( event.getResults() ) ) {
view.showUploadedSuccessfullyMessage();
view.hideGAVInputs();
fireSearchEvent();
view.hide();
} else if ( UPLOAD_MISSING_POM.equalsIgnoreCase( event.getResults() ) ) {
view.showInvalidJarNoPomWarning();
view.showGAVInputs();
} else if ( UPLOAD_UNABLE_TO_PARSE_POM.equalsIgnoreCase( event.getResults() ) ) {
view.showInvalidPomWarning();
view.hide();
} else {
view.showUploadFailedError( event.getResults() );
view.hideGAVInputs();
view.hide();
}
}
@Override
public void handleSubmit( final AbstractForm.SubmitEvent event ) {
String fileName = view.getFileName();
if ( fileName == null || "".equals( fileName ) ) {
view.showSelectFileUploadWarning();
event.cancel();
} else if ( !( isValid( fileName ) ) ) {
view.showUnsupportedFileTypeWarning();
event.cancel();
} else {
view.showUploadingBusy();
}
}
public void showView() {
view.show();
}
public void fireSearchEvent() {
searchEvent.fire( new M2RepoSearchEvent() );
}
}
| porcelli-forks/guvnor | guvnor-m2repo-editor/guvnor-m2repo-editor-client/src/main/java/org/guvnor/m2repo/client/upload/UploadFormPresenter.java | Java | apache-2.0 | 3,510 |
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class FullInspiration(object):
"""
NOTE: This class is auto generated by the systran code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
Systran model
:param dict systran_types: The key is attribute name and the value is attribute type.
:param dict attribute_map: The key is attribute name and the value is json key in definition.
"""
self.systran_types = {
'id': 'str',
'location': 'FullLocation',
'type': 'str',
'title': 'str',
'introduction': 'str',
'content': 'str',
'photos': 'list[Photo]',
'videos': 'list[Video]'
}
self.attribute_map = {
'id': 'id',
'location': 'location',
'type': 'type',
'title': 'title',
'introduction': 'introduction',
'content': 'content',
'photos': 'photos',
'videos': 'videos'
}
# Inspiration Identifier
self.id = None # str
# Location
self.location = None # FullLocation
# Inspiration type
self.type = None # str
# Title
self.title = None # str
# Introduction
self.introduction = None # str
# Content
self.content = None # str
# Array of Photos
self.photos = None # list[Photo]
# Array of Videos
self.videos = None # list[Video]
def __repr__(self):
properties = []
for p in self.__dict__:
if p != 'systran_types' and p != 'attribute_map':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))
| SYSTRAN/geographic-api-python-client | systran_geographic_api/models/full_inspiration.py | Python | apache-2.0 | 2,585 |
package org.bndtools.rt.rest;
import java.util.HashMap;
import java.util.Map;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.namespace.extender.ExtenderNamespace;
public final class BundleConstants {
public static final String EXTENDER_ID = "bndtools.rt.rest";
public static final Version VERSION = new Version("2.0.0");
public static final Map<String, Object> CAPABILITIES;
static {
CAPABILITIES = new HashMap<String, Object>();
CAPABILITIES.put(ExtenderNamespace.EXTENDER_NAMESPACE, EXTENDER_ID);
CAPABILITIES.put(Constants.VERSION_ATTRIBUTE, VERSION);
}
}
| bndtools/bndtools-rt | org.bndtools.rt.rest/src/org/bndtools/rt/rest/BundleConstants.java | Java | apache-2.0 | 617 |
/*--------------------------------------------------------------------------
* Copyright 2009 utgenome.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// utgb-core Project
//
// TrackGenTrack.java
// Since: 2009/05/21
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.gwt.utgb.client.track.lib;
import org.utgenome.gwt.utgb.client.track.Track;
import org.utgenome.gwt.utgb.client.track.TrackBase;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
public class TrackGenTrack extends TrackBase {
public static TrackFactory factory() {
return new TrackFactory() {
public Track newInstance() {
return new TrackGenTrack();
}
};
}
final FlexTable layoutTable = new FlexTable();
final ListBox trackSelector = new ListBox();
public TrackGenTrack() {
super("Track Factory");
trackSelector.addItem("DAS Track", "das");
trackSelector.addItem("BED Track", "bed");
trackSelector.addItem("Read Track", "read");
trackSelector.addItem("Image Track", "image");
trackSelector.addItem("IFrame Track", "frame");
layoutTable.setWidget(0, 0, trackSelector);
}
public Widget getWidget() {
return layoutTable;
}
}
| utgenome/utgb | utgb-core/src/main/java/org/utgenome/gwt/utgb/client/track/lib/TrackGenTrack.java | Java | apache-2.0 | 1,973 |
/*--------------------------------------------------------------------------
* Copyright 2008 utgenome.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// utgb-widget Project
//
// Icon.java
// Since: Apr 24, 2008
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.gwt.widget.client;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Image;
/**
* Icon image which flips on mouse over events
*
* @author leo
*
*/
public class Icon extends FocusPanel {
private Element currentFace = null;
private Image iconImage;
private Image mouseOverIconImage;
//private ArrayList<ClickHandler> clickListenerList = new ArrayList<ClickHandler>();
// icon state
private boolean isFocusing = false;
private boolean isCapturing = false;
private boolean isHovering = false;
public Icon(Image iconImage, Image mouseOverIconImage) {
this.iconImage = iconImage;
this.mouseOverIconImage = mouseOverIconImage;
Style.cursor(this, Style.CURSOR_POINTER);
updateIconFace(iconImage.getElement());
}
public void setIcon(Icon newIcon) {
this.iconImage = newIcon.getIconImage();
this.mouseOverIconImage = newIcon.getMouseOverIconImage();
updateIconFace(iconImage.getElement());
}
public void setIconImage(Image newIconImage) {
this.iconImage = newIconImage;
this.mouseOverIconImage = newIconImage;
updateIconFace(iconImage.getElement());
}
private void updateIconFace(Element newFace) {
if (currentFace != newFace) {
if (currentFace != null)
DOM.removeChild(getElement(), currentFace);
currentFace = newFace;
DOM.appendChild(getElement(), currentFace);
}
}
public Image getIconImage() {
return iconImage;
}
public Image getMouseOverIconImage() {
return mouseOverIconImage;
}
public void addClickHanlder(ClickHandler listener) {
this.addClickHandler(listener);
}
private void setHovering(boolean hovering) {
this.isHovering = hovering;
updateIconFace(isHovering ? mouseOverIconImage.getElement() : iconImage.getElement());
}
/**
* Called when the user finishes clicking on this button. The default behavior is to fire the click event to
* listeners. Subclasses that override {@link #onClickStart()} should override this method to restore the normal
* widget display.
*/
protected void onClick() {
NativeEvent e = Document.get().createClickEvent(1, 0, 0, 0, 0, false, false, false, false);
}
/**
* Called when the user aborts a click in progress; for example, by dragging the mouse outside of the button before
* releasing the mouse button. Subclasses that override {@link #onClickStart()} should override this method to
* restore the normal widget display.
*/
protected void onClickCancel() {
}
/**
* Called when the user begins to click on this button. Subclasses may override this method to display the start of
* the click visually; such subclasses should also override {@link #onClick()} and {@link #onClickCancel()} to
* restore normal visual state. Each <code>onClickStart</code> will eventually be followed by either
* <code>onClick</code> or <code>onClickCancel</code>, depending on whether the click is completed.
*/
protected void onClickStart() {
}
@Override
public void onBrowserEvent(Event event) {
// Should not act on button if disabled.
int type = DOM.eventGetType(event);
switch (type) {
case Event.ONMOUSEDOWN:
isFocusing = true;
onClickStart();
// DOM.setCapture(getElement());
isCapturing = true;
// Prevent dragging (on some browsers);
DOM.eventPreventDefault(event);
break;
case Event.ONMOUSEUP:
if (isCapturing) {
isCapturing = false;
// DOM.releaseCapture(getElement());
if (isHovering) {
onClick();
}
}
break;
case Event.ONMOUSEMOVE:
if (isCapturing) {
// Prevent dragging (on other browsers);
DOM.eventPreventDefault(event);
}
break;
case Event.ONMOUSEOUT:
Element to = DOM.eventGetToElement(event);
if (DOM.isOrHasChild(getElement(), DOM.eventGetTarget(event)) && (to == null || !DOM.isOrHasChild(getElement(), to))) {
if (isCapturing) {
onClickCancel();
// DOM.releaseCapture(getElement());
}
}
setHovering(false);
break;
case Event.ONMOUSEOVER:
if (DOM.isOrHasChild(getElement(), DOM.eventGetTarget(event))) {
setHovering(true);
if (isCapturing) {
onClickStart();
}
}
break;
case Event.ONCLICK:
// we handle clicks ourselves
return;
case Event.ONBLUR:
if (isFocusing) {
isFocusing = false;
onClickCancel();
}
break;
case Event.ONLOSECAPTURE:
if (isCapturing) {
isCapturing = false;
onClickCancel();
}
break;
case Event.ONERROR:
setHovering(false);
break;
}
super.onBrowserEvent(event);
// Synthesize clicks based on keyboard events AFTER the normal key handling.
char keyCode = (char) DOM.eventGetKeyCode(event);
switch (type) {
case Event.ONKEYDOWN:
if (keyCode == ' ') {
isFocusing = true;
onClickStart();
}
break;
case Event.ONKEYUP:
if (isFocusing && keyCode == ' ') {
isFocusing = false;
onClick();
}
break;
case Event.ONKEYPRESS:
if (keyCode == '\n' || keyCode == '\r') {
onClickStart();
onClick();
}
break;
}
}
}
| utgenome/utgb | utgb-core/src/main/java/org/utgenome/gwt/widget/client/Icon.java | Java | apache-2.0 | 6,208 |
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nanoframework.core.component.exception;
/**
* 重复组件服务异常
*
* @author yanghe
* @since 1.0
*/
public class ComponentServiceRepeatException extends RuntimeException {
private static final long serialVersionUID = -4050783744076776903L;
public ComponentServiceRepeatException() {
}
public ComponentServiceRepeatException(String message) {
super(message);
}
public ComponentServiceRepeatException(String message, Throwable cause) {
super(message, cause);
}
}
| nano-projects/nano-framework | nano-core/src/main/java/org/nanoframework/core/component/exception/ComponentServiceRepeatException.java | Java | apache-2.0 | 1,156 |
# frozen_string_literal: true
# Copyright 2015 Australian National Botanic Gardens
#
# This file is part of the NSL Editor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "test_helper"
load "test/models/search/users.rb"
# Single Search model test on Instance search.
class SearchOnInstanceCommentsSimpleTest < ActiveSupport::TestCase
test "search on instance comments simple" do
params = ActiveSupport::HashWithIndifferentAccess.new(
query_target: "instance",
query_string: "comments: instance MyText xYz",
include_common_and_cultivar_session: true,
current_user: build_edit_user
)
search = Search::Base.new(params)
assert !search.executed_query.results.empty?,
"Instances with comment expected."
end
end
| bio-org-au/nsl-editor | test/models/search/on_instance/comments/simple_test.rb | Ruby | apache-2.0 | 1,289 |
<!DOCTYPE html>
<?php
require_once ('/var/www/html/app/library/function.php');
if(!isset($_SESSION['current_user_name']) && !isset($_COOKIE[$cookie_name])) {
header('Location: ../login.php');
exit();
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Researcher</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<!-- ZONE -->
<h2>Researcher list</h2>
<div class="modal-body">
<table class="table table-striped order-table">
<thead>
<tr>
<!-- Name of columns on the screen -->
<th>Employee ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Animal</th>
<th>Animal ID</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="myTable">
<?php
require_once ('/var/www/html/app/model/connect.php');
$sql = "select EMM_ZOO.employee.empid, firstname, lastname, animalname, EMM_ZOO.animal.animalid from EMM_ZOO.employee, EMM_ZOO.researcher, EMM_ZOO.animal where EMM_ZOO.employee.empid=EMM_ZOO.researcher.empid and EMM_ZOO.animal.animalid=EMM_ZOO.researcher.animalid order by EMM_ZOO.employee.empid;";
if ($conn) {
$stmt = db2_exec($conn, $sql);
if($stmt) {
while ($row = db2_fetch_assoc($stmt)) {
#print "<form type='post' name='alter_form'>";
#Edit here for adding columns, use the name of column
print "<tr><td>" . $row['EMPID']. "</td><td>" . $row['FIRSTNAME']. "</td><td>" . $row['LASTNAME']. "</td><td>" . $row['ANIMALNAME']. "</td><td>" . $row['ANIMALID']. "</td>";
print "<td><form><button type='submit' name='edit' class='btn btn-default btn-sm'><span class='glyphicon glyphicon-pencil'></span></button></form></td>";
print "<td><form method='POST' action='delete_row_researcher.php' onsubmit='setTimeout(function () { window.location.reload(); }, 10)'> <input type='hidden' value=". $row['EMPID']." name='EMPID'><input type='hidden' value=". $row['ANIMALID']." name='ANIMALID'>
<button type='submit' name='delete' class='btn btn-default btn-sm'><span class='glyphicon glyphicon-remove'></span></button></form></td></tr>";
#print "</form>";
}
}
db2_free_stmt($stmt);
}
else {
echo db2_conn_errormsg($conn);
}
?>
</tbody>
<tbody id="myTable">
<div class="row">
<tr></tr>
<tr><td><b>Add Employee (EmpID)</b></td> <td><b>Add animal (AnimalID)</b></td>
<tr>
<form method="post" action="addEmpAnimalRes.php" onsubmit="setTimeout(function () { window.location.reload(); }, 10)">
<td>
<select class='form-control' name='add_EMPID'>
<?php
require_once ('/var/www/html/app/model/connect.php');
$sql = "SELECT empid FROM EMM_ZOO.employee ORDER BY empid;";
if ($conn) {
$stmt = db2_exec($conn, $sql);
if($stmt) {
while ($row = db2_fetch_assoc($stmt)) {
print "<option value='". $row['EMPID']. "'>" .$row['EMPID']. "</option>";
}
}
db2_free_stmt($stmt);
}
else {
echo db2_conn_errormsg($conn);
}
?>
</select>
</td>
<td>
<select class='form-control' name='add_ANIMALID'>
<?php
require_once ('/var/www/html/app/model/connect.php');
$sql = "SELECT animalid FROM EMM_ZOO.animal ORDER BY animalid;";
if ($conn) {
$stmt = db2_exec($conn, $sql);
if($stmt) {
while ($row = db2_fetch_assoc($stmt)) {
print "<option value='". $row['ANIMALID']. "'>" .$row['ANIMALID']. "</option>";
}
}
db2_free_stmt($stmt);
}
else {
echo db2_conn_errormsg($conn);
}
?>
</select>
</td>
<td> </td>
<td><button type="submit" class="btn btn-info">Add</button></td>
</form>
</tr>
</div>
</table>
<div class="text-center">
| Juklab/emmaline | html/app/research/animal_character.php | PHP | apache-2.0 | 4,741 |
/*
* Copyright(C) 2014 tAsktoys. All rights reserved.
*/
package com.tasktoys.archelon.data.dao;
import com.tasktoys.archelon.data.entity.Category;
import java.util.List;
/**
* Interface of category data operations.
*
* @author mikan
* @since 0.1
*/
public interface CategoryDao {
/**
* Find category entity by main category id.
*
* @param id main category id
* @return main category's entity, or <code>null</code> if not found.
*/
public Category findMainCategoryByID(int id);
/**
* Find list of main categories.
*
* @return list of main categories, or empty list if not found categories.
*/
public List<Category> findMainCategories();
/**
* Find list of sub categories by specified main category.
*
* @param mainCategoryId main category's id
* @return list of sub categories, or empty list if not found categories.
*/
public List<Category> findSubCategories(int mainCategoryId);
}
| tAsktoys/Archelon | src/main/java/com/tasktoys/archelon/data/dao/CategoryDao.java | Java | apache-2.0 | 1,004 |
/**
* Copyright 2016 Nikita Koksharov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.api;
import java.util.List;
/**
*
* @author Nikita Koksharov
*
*/
public interface RExecutorBatchFuture extends RFuture<Void> {
List<RExecutorFuture<?>> getTaskFutures();
}
| zhoffice/redisson | redisson/src/main/java/org/redisson/api/RExecutorBatchFuture.java | Java | apache-2.0 | 811 |
/*
* File: IAS-DataModelLib/src/dm/json/exception/JSONHelperException.cpp
*
* Copyright (C) 2015, Albert Krzymowski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "../../../dm/json/exception/JSONHelperException.h"
#include <commonlib/commonlib.h>
namespace IAS{
namespace DM {
namespace JSON {
/*************************************************************************/
JSONHelperException::JSONHelperException(const String& strInfo){
IAS_TRACER;
this->setInfo(strInfo);
}
/*************************************************************************/
JSONHelperException::JSONHelperException(const String& strInfo, int iLine){
IAS_TRACER;
StringStream ssTmp;
ssTmp<<strInfo<<", line:"<<iLine;
this->setInfo(ssTmp.str());
}
/*************************************************************************/
JSONHelperException::~JSONHelperException() throw(){
IAS_TRACER;
}
/*************************************************************************/
const char* JSONHelperException::getName(){
IAS_TRACER;
return "JSONHelperException";
}
/*************************************************************************/
} /* namespace Impl */
} /* namespace DM */
} /* namespace IAS */
| InvenireAude/IAS-Base-OSS | IAS-DataModelLib/src/dm/json/exception/JSONHelperException.cpp | C++ | apache-2.0 | 1,711 |
package com.example.shz.hainuo_ims.fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.example.shz.hainuo_ims.R;
import com.example.shz.hainuo_ims.activity.MainActivity;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
/**
* Created by shz on 2017/8/12.
*/
public class LocationFragment extends BaseTabFragment {
public AMapLocationClientOption mLocationOption;
public AMapLocationClient mLocationClient;
public AMapLocationListener mLocationListener;
private MapView mMapView;
private AMap mAMap;
private TextView mTvLoction;
private double lat;
private double lon;
private String country;
private String province;
private String city;
private StringBuilder mStringBuilder;
@Override
protected void init() {
if (mAMap == null) {
mAMap = mMapView.getMap();
setupMap();
}
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.navi_map_gps_locked);
// BitmapDescriptor descriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
// MyLocationStyle myLocationStyle = new MyLocationStyle(descriptor);
// myLocationStyle.interval(2000);
// mAMap.setMyLocationStyle(myLocationStyle);
initLocationOption();
initLocation();
}
private void initLocationOption() {
if (mLocationOption == null) {
mLocationOption = new AMapLocationClientOption();
}
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
mLocationOption.setNeedAddress(true);
mLocationOption.setInterval(2000);
}
private void initLocation() {
mLocationClient = new AMapLocationClient(getContext());
mLocationClient.setLocationOption(mLocationOption);
mLocationListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation != null) {
if (aMapLocation.getErrorCode() == 0) {
lat = aMapLocation.getLatitude();//获取纬度
lon = aMapLocation.getLongitude();//获取经度
country = aMapLocation.getCountry();//国家信息
province = aMapLocation.getProvince();//省信息
city = aMapLocation.getCity();//城市信息
if (mStringBuilder == null) {
mStringBuilder = new StringBuilder();
mStringBuilder.append("经度:");
mStringBuilder.append(lon);
mStringBuilder.append(" ");
mStringBuilder.append("纬度:" + lat + "\n");
mStringBuilder.append("国家:" + country + " ");
mStringBuilder.append("省:" + province + " ");
mStringBuilder.append("城市:" + city);
}
// mAMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lon)));
mTvLoction.post(new Runnable() {
@Override
public void run() {
mTvLoction.setText(mStringBuilder.toString());
}
});
}
}
}
};
mLocationClient.setLocationListener(mLocationListener);
mLocationClient.startLocation();
}
private void setupMap() {
mAMap.moveCamera(CameraUpdateFactory.zoomTo(14));
mAMap.getUiSettings().setMyLocationButtonEnabled(true);
mAMap.setMyLocationEnabled(true);
setupLocationStyle();
}
private void setupLocationStyle() {
// 自定义系统定位蓝点
MyLocationStyle myLocationStyle = new MyLocationStyle();
// 自定义定位蓝点图标
myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
fromResource(R.drawable.gps_point));
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
// 自定义精度范围的圆形边框颜色
// myLocationStyle.strokeColor(STROKE_COLOR);
//自定义精度范围的圆形边框宽度
// myLocationStyle.strokeWidth(5);
// 设置圆形的填充颜色
// myLocationStyle.radiusFillColor(FILL_COLOR);
// 将自定义的 myLocationStyle 对象添加到地图上
mAMap.setMyLocationStyle(myLocationStyle);
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_location_query, container, false);
mMapView = (MapView) inflate.findViewById(R.id.map);
mTvLoction = (TextView) inflate.findViewById(R.id.tv_location);
mMapView.onCreate(savedInstanceState);
return inflate;
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
mLocationClient.stopLocation();
mLocationClient.onDestroy();
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onStop() {
super.onStop();
mLocationClient.stopLocation();
}
}
| shzLoveyjw/HAINUO_IMS | app/src/main/java/com/example/shz/hainuo_ims/fragment/LocationFragment.java | Java | apache-2.0 | 6,413 |
/*!
* Bootstrap v3.3.6 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
html {
font-family: sans-serif;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background-color: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
margin: .67em 0;
font-size: 2em;
}
mark {
color: #000;
background: #ff0;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sup {
top: -.5em;
}
sub {
bottom: -.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
height: 0;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
margin: 0;
font: inherit;
color: inherit;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
padding: 0;
border: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: textfield;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
padding: .35em .625em .75em;
margin: 0 2px;
border: 1px solid #c0c0c0;
}
legend {
padding: 0;
border: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
td,
th {
padding: 0;
}
/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
@media print {
*,
*:before,
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\002a";
}
.glyphicon-plus:before {
content: "\002b";
}
.glyphicon-euro:before,
.glyphicon-eur:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
.glyphicon-cd:before {
content: "\e201";
}
.glyphicon-save-file:before {
content: "\e202";
}
.glyphicon-open-file:before {
content: "\e203";
}
.glyphicon-level-up:before {
content: "\e204";
}
.glyphicon-copy:before {
content: "\e205";
}
.glyphicon-paste:before {
content: "\e206";
}
.glyphicon-alert:before {
content: "\e209";
}
.glyphicon-equalizer:before {
content: "\e210";
}
.glyphicon-king:before {
content: "\e211";
}
.glyphicon-queen:before {
content: "\e212";
}
.glyphicon-pawn:before {
content: "\e213";
}
.glyphicon-bishop:before {
content: "\e214";
}
.glyphicon-knight:before {
content: "\e215";
}
.glyphicon-baby-formula:before {
content: "\e216";
}
.glyphicon-tent:before {
content: "\26fa";
}
.glyphicon-blackboard:before {
content: "\e218";
}
.glyphicon-bed:before {
content: "\e219";
}
.glyphicon-apple:before {
content: "\f8ff";
}
.glyphicon-erase:before {
content: "\e221";
}
.glyphicon-hourglass:before {
content: "\231b";
}
.glyphicon-lamp:before {
content: "\e223";
}
.glyphicon-duplicate:before {
content: "\e224";
}
.glyphicon-piggy-bank:before {
content: "\e225";
}
.glyphicon-scissors:before {
content: "\e226";
}
.glyphicon-bitcoin:before {
content: "\e227";
}
.glyphicon-btc:before {
content: "\e227";
}
.glyphicon-xbt:before {
content: "\e227";
}
.glyphicon-yen:before {
content: "\00a5";
}
.glyphicon-jpy:before {
content: "\00a5";
}
.glyphicon-ruble:before {
content: "\20bd";
}
.glyphicon-rub:before {
content: "\20bd";
}
.glyphicon-scale:before {
content: "\e230";
}
.glyphicon-ice-lolly:before {
content: "\e231";
}
.glyphicon-ice-lolly-tasted:before {
content: "\e232";
}
.glyphicon-education:before {
content: "\e233";
}
.glyphicon-option-horizontal:before {
content: "\e234";
}
.glyphicon-option-vertical:before {
content: "\e235";
}
.glyphicon-menu-hamburger:before {
content: "\e236";
}
.glyphicon-modal-window:before {
content: "\e237";
}
.glyphicon-oil:before {
content: "\e238";
}
.glyphicon-grain:before {
content: "\e239";
}
.glyphicon-sunglasses:before {
content: "\e240";
}
.glyphicon-text-size:before {
content: "\e241";
}
.glyphicon-text-color:before {
content: "\e242";
}
.glyphicon-text-background:before {
content: "\e243";
}
.glyphicon-object-align-top:before {
content: "\e244";
}
.glyphicon-object-align-bottom:before {
content: "\e245";
}
.glyphicon-object-align-horizontal:before {
content: "\e246";
}
.glyphicon-object-align-left:before {
content: "\e247";
}
.glyphicon-object-align-vertical:before {
content: "\e248";
}
.glyphicon-object-align-right:before {
content: "\e249";
}
.glyphicon-triangle-right:before {
content: "\e250";
}
.glyphicon-triangle-left:before {
content: "\e251";
}
.glyphicon-triangle-bottom:before {
content: "\e252";
}
.glyphicon-triangle-top:before {
content: "\e253";
}
.glyphicon-console:before {
content: "\e254";
}
.glyphicon-superscript:before {
content: "\e255";
}
.glyphicon-subscript:before {
content: "\e256";
}
.glyphicon-menu-left:before {
content: "\e257";
}
.glyphicon-menu-right:before {
content: "\e258";
}
.glyphicon-menu-down:before {
content: "\e259";
}
.glyphicon-menu-up:before {
content: "\e260";
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #337ab7;
text-decoration: none;
}
a:hover,
a:focus {
color: #23527c;
text-decoration: underline;
}
a:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 6px;
}
.img-thumbnail {
display: inline-block;
max-width: 100%;
height: auto;
padding: 4px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
[role="button"] {
cursor: pointer;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #777;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 10px;
margin-bottom: 10px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 36px;
}
h2,
.h2 {
font-size: 30px;
}
h3,
.h3 {
font-size: 24px;
}
h4,
.h4 {
font-size: 18px;
}
h5,
.h5 {
font-size: 14px;
}
h6,
.h6 {
font-size: 12px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 300;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
small,
.small {
font-size: 85%;
}
mark,
.mark {
padding: .2em;
background-color: #fcf8e3;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-muted {
color: #777;
}
.text-primary {
color: #337ab7;
}
a.text-primary:hover,
a.text-primary:focus {
color: #286090;
}
.text-success {
color: #3c763d;
}
a.text-success:hover,
a.text-success:focus {
color: #2b542c;
}
.text-info {
color: #31708f;
}
a.text-info:hover,
a.text-info:focus {
color: #245269;
}
.text-warning {
color: #8a6d3b;
}
a.text-warning:hover,
a.text-warning:focus {
color: #66512c;
}
.text-danger {
color: #a94442;
}
a.text-danger:hover,
a.text-danger:focus {
color: #843534;
}
.bg-primary {
color: #fff;
background-color: #337ab7;
}
a.bg-primary:hover,
a.bg-primary:focus {
background-color: #286090;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover,
a.bg-success:focus {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover,
a.bg-info:focus {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover,
a.bg-warning:focus {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover,
a.bg-danger:focus {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
border-bottom: 1px solid #eee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 10px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
margin-left: -5px;
list-style: none;
}
.list-inline > li {
display: inline-block;
padding-right: 5px;
padding-left: 5px;
}
dl {
margin-top: 0;
margin-bottom: 20px;
}
dt,
dd {
line-height: 1.42857143;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 768px) {
.dl-horizontal dt {
float: left;
width: 160px;
overflow: hidden;
clear: left;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #777;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #777;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
text-align: right;
border-right: 5px solid #eee;
border-left: 0;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
address {
margin-bottom: 20px;
font-style: normal;
line-height: 1.42857143;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 4px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #fff;
background-color: #333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
}
kbd kbd {
padding: 0;
font-size: 100%;
font-weight: bold;
-webkit-box-shadow: none;
box-shadow: none;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170;
}
}
.container-fluid {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
.row {
margin-right: -15px;
margin-left: -15px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: auto;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: auto;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: auto;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: auto;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: auto;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: auto;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: auto;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: auto;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0;
}
}
table {
background-color: transparent;
}
caption {
padding-top: 8px;
padding-bottom: 8px;
color: #777;
text-align: left;
}
th {
text-align: left;
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #ddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #ddd;
}
.table .table {
background-color: #fff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-of-type(odd) {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
display: table-column;
float: none;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
display: table-cell;
float: none;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr:hover > .active,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr:hover > .success,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr:hover > .info,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr:hover > .warning,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr:hover > .danger,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
.table-responsive {
min-height: .01%;
overflow-x: auto;
}
@media screen and (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-y: hidden;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 7px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
}
.form-control {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
}
.form-control::-moz-placeholder {
color: #999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999;
}
.form-control::-webkit-input-placeholder {
color: #999;
}
.form-control::-ms-expand {
background-color: transparent;
border: 0;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
background-color: #eee;
opacity: 1;
}
.form-control[disabled],
fieldset[disabled] .form-control {
cursor: not-allowed;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
@media screen and (-webkit-min-device-pixel-ratio: 0) {
input[type="date"].form-control,
input[type="time"].form-control,
input[type="datetime-local"].form-control,
input[type="month"].form-control {
line-height: 34px;
}
input[type="date"].input-sm,
input[type="time"].input-sm,
input[type="datetime-local"].input-sm,
input[type="month"].input-sm,
.input-group-sm input[type="date"],
.input-group-sm input[type="time"],
.input-group-sm input[type="datetime-local"],
.input-group-sm input[type="month"] {
line-height: 30px;
}
input[type="date"].input-lg,
input[type="time"].input-lg,
input[type="datetime-local"].input-lg,
input[type="month"].input-lg,
.input-group-lg input[type="date"],
.input-group-lg input[type="time"],
.input-group-lg input[type="datetime-local"],
.input-group-lg input[type="month"] {
line-height: 46px;
}
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
position: relative;
display: block;
margin-top: 10px;
margin-bottom: 10px;
}
.radio label,
.checkbox label {
min-height: 20px;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
position: absolute;
margin-top: 4px \9;
margin-left: -20px;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
position: relative;
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
vertical-align: middle;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
input[type="radio"].disabled,
input[type="checkbox"].disabled,
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"] {
cursor: not-allowed;
}
.radio-inline.disabled,
.checkbox-inline.disabled,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.radio.disabled label,
.checkbox.disabled label,
fieldset[disabled] .radio label,
fieldset[disabled] .checkbox label {
cursor: not-allowed;
}
.form-control-static {
min-height: 34px;
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0;
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-right: 0;
padding-left: 0;
}
.input-sm {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-sm {
height: 30px;
line-height: 30px;
}
textarea.input-sm,
select[multiple].input-sm {
height: auto;
}
.form-group-sm .form-control {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.form-group-sm select.form-control {
height: 30px;
line-height: 30px;
}
.form-group-sm textarea.form-control,
.form-group-sm select[multiple].form-control {
height: auto;
}
.form-group-sm .form-control-static {
height: 30px;
min-height: 32px;
padding: 6px 10px;
font-size: 12px;
line-height: 1.5;
}
.input-lg {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
select.input-lg {
height: 46px;
line-height: 46px;
}
textarea.input-lg,
select[multiple].input-lg {
height: auto;
}
.form-group-lg .form-control {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
.form-group-lg select.form-control {
height: 46px;
line-height: 46px;
}
.form-group-lg textarea.form-control,
.form-group-lg select[multiple].form-control {
height: auto;
}
.form-group-lg .form-control-static {
height: 46px;
min-height: 38px;
padding: 11px 16px;
font-size: 18px;
line-height: 1.3333333;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 42.5px;
}
.form-control-feedback {
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
pointer-events: none;
}
.input-lg + .form-control-feedback,
.input-group-lg + .form-control-feedback,
.form-group-lg .form-control + .form-control-feedback {
width: 46px;
height: 46px;
line-height: 46px;
}
.input-sm + .form-control-feedback,
.input-group-sm + .form-control-feedback,
.form-group-sm .form-control + .form-control-feedback {
width: 30px;
height: 30px;
line-height: 30px;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline,
.has-success.radio label,
.has-success.checkbox label,
.has-success.radio-inline label,
.has-success.checkbox-inline label {
color: #3c763d;
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
}
.has-success .input-group-addon {
color: #3c763d;
background-color: #dff0d8;
border-color: #3c763d;
}
.has-success .form-control-feedback {
color: #3c763d;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline,
.has-warning.radio label,
.has-warning.checkbox label,
.has-warning.radio-inline label,
.has-warning.checkbox-inline label {
color: #8a6d3b;
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
}
.has-warning .input-group-addon {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #8a6d3b;
}
.has-warning .form-control-feedback {
color: #8a6d3b;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline,
.has-error.radio label,
.has-error.checkbox label,
.has-error.radio-inline label,
.has-error.checkbox-inline label {
color: #a94442;
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
}
.has-error .input-group-addon {
color: #a94442;
background-color: #f2dede;
border-color: #a94442;
}
.has-error .form-control-feedback {
color: #a94442;
}
.has-feedback label ~ .form-control-feedback {
top: 25px;
}
.has-feedback label.sr-only ~ .form-control-feedback {
top: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .form-control-static {
display: inline-block;
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle;
}
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn,
.form-inline .input-group .form-control {
width: auto;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio label,
.form-inline .checkbox label {
padding-left: 0;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
padding-top: 7px;
margin-top: 0;
margin-bottom: 0;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 27px;
}
.form-horizontal .form-group {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
padding-top: 7px;
margin-bottom: 0;
text-align: right;
}
}
.form-horizontal .has-feedback .form-control-feedback {
right: 15px;
}
@media (min-width: 768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 11px;
font-size: 18px;
}
}
@media (min-width: 768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
font-size: 12px;
}
}
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn.active.focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus,
.btn.focus {
color: #333;
text-decoration: none;
}
.btn:active,
.btn.active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}
a.btn.disabled,
fieldset[disabled] a.btn {
pointer-events: none;
}
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
.btn-default:focus,
.btn-default.focus {
color: #333;
background-color: #e6e6e6;
border-color: #8c8c8c;
}
.btn-default:hover {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active:hover,
.btn-default.active:hover,
.open > .dropdown-toggle.btn-default:hover,
.btn-default:active:focus,
.btn-default.active:focus,
.open > .dropdown-toggle.btn-default:focus,
.btn-default:active.focus,
.btn-default.active.focus,
.open > .dropdown-toggle.btn-default.focus {
color: #333;
background-color: #d4d4d4;
border-color: #8c8c8c;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
background-image: none;
}
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus {
background-color: #fff;
border-color: #ccc;
}
.btn-default .badge {
color: #fff;
background-color: #333;
}
.btn-primary {
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
.btn-primary:focus,
.btn-primary.focus {
color: #fff;
background-color: #286090;
border-color: #122b40;
}
.btn-primary:hover {
color: #fff;
background-color: #286090;
border-color: #204d74;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
color: #fff;
background-color: #286090;
border-color: #204d74;
}
.btn-primary:active:hover,
.btn-primary.active:hover,
.open > .dropdown-toggle.btn-primary:hover,
.btn-primary:active:focus,
.btn-primary.active:focus,
.open > .dropdown-toggle.btn-primary:focus,
.btn-primary:active.focus,
.btn-primary.active.focus,
.open > .dropdown-toggle.btn-primary.focus {
color: #fff;
background-color: #204d74;
border-color: #122b40;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus {
background-color: #337ab7;
border-color: #2e6da4;
}
.btn-primary .badge {
color: #337ab7;
background-color: #fff;
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success:focus,
.btn-success.focus {
color: #fff;
background-color: #449d44;
border-color: #255625;
}
.btn-success:hover {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active:hover,
.btn-success.active:hover,
.open > .dropdown-toggle.btn-success:hover,
.btn-success:active:focus,
.btn-success.active:focus,
.open > .dropdown-toggle.btn-success:focus,
.btn-success:active.focus,
.btn-success.active.focus,
.open > .dropdown-toggle.btn-success.focus {
color: #fff;
background-color: #398439;
border-color: #255625;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
background-image: none;
}
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled.focus,
.btn-success[disabled].focus,
fieldset[disabled] .btn-success.focus {
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success .badge {
color: #5cb85c;
background-color: #fff;
}
.btn-info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info:focus,
.btn-info.focus {
color: #fff;
background-color: #31b0d5;
border-color: #1b6d85;
}
.btn-info:hover {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active:hover,
.btn-info.active:hover,
.open > .dropdown-toggle.btn-info:hover,
.btn-info:active:focus,
.btn-info.active:focus,
.open > .dropdown-toggle.btn-info:focus,
.btn-info:active.focus,
.btn-info.active.focus,
.open > .dropdown-toggle.btn-info.focus {
color: #fff;
background-color: #269abc;
border-color: #1b6d85;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
background-image: none;
}
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled.focus,
.btn-info[disabled].focus,
fieldset[disabled] .btn-info.focus {
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info .badge {
color: #5bc0de;
background-color: #fff;
}
.btn-warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning:focus,
.btn-warning.focus {
color: #fff;
background-color: #ec971f;
border-color: #985f0d;
}
.btn-warning:hover {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active:hover,
.btn-warning.active:hover,
.open > .dropdown-toggle.btn-warning:hover,
.btn-warning:active:focus,
.btn-warning.active:focus,
.open > .dropdown-toggle.btn-warning:focus,
.btn-warning:active.focus,
.btn-warning.active.focus,
.open > .dropdown-toggle.btn-warning.focus {
color: #fff;
background-color: #d58512;
border-color: #985f0d;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
background-image: none;
}
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled.focus,
.btn-warning[disabled].focus,
fieldset[disabled] .btn-warning.focus {
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #fff;
}
.btn-danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger:focus,
.btn-danger.focus {
color: #fff;
background-color: #c9302c;
border-color: #761c19;
}
.btn-danger:hover {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active:hover,
.btn-danger.active:hover,
.open > .dropdown-toggle.btn-danger:hover,
.btn-danger:active:focus,
.btn-danger.active:focus,
.open > .dropdown-toggle.btn-danger:focus,
.btn-danger:active.focus,
.btn-danger.active.focus,
.open > .dropdown-toggle.btn-danger.focus {
color: #fff;
background-color: #ac2925;
border-color: #761c19;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
background-image: none;
}
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled.focus,
.btn-danger[disabled].focus,
fieldset[disabled] .btn-danger.focus {
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger .badge {
color: #d9534f;
background-color: #fff;
}
.btn-link {
font-weight: normal;
color: #337ab7;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link.active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #23527c;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #777;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-block {
display: block;
width: 100%;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity .15s linear;
-o-transition: opacity .15s linear;
transition: opacity .15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
}
.collapse.in {
display: block;
}
tr.collapse.in {
display: table-row;
}
tbody.collapse.in {
display: table-row-group;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition-timing-function: ease;
-o-transition-timing-function: ease;
transition-timing-function: ease;
-webkit-transition-duration: .35s;
-o-transition-duration: .35s;
transition-duration: .35s;
-webkit-transition-property: height, visibility;
-o-transition-property: height, visibility;
transition-property: height, visibility;
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px dashed;
border-top: 4px solid \9;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropup,
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #fff;
text-decoration: none;
background-color: #337ab7;
outline: 0;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #777;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
right: 0;
left: auto;
}
.dropdown-menu-left {
right: auto;
left: 0;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777;
white-space: nowrap;
}
.dropdown-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
content: "";
border-top: 0;
border-bottom: 4px dashed;
border-bottom: 4px solid \9;
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 2px;
}
@media (min-width: 768px) {
.navbar-right .dropdown-menu {
right: 0;
left: auto;
}
.navbar-right .dropdown-menu-left {
right: auto;
left: 0;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn,
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-right: 8px;
padding-left: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-right: 12px;
padding-left: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
display: table-cell;
float: none;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
.btn-group-justified > .btn-group .dropdown-menu {
left: auto;
}
[data-toggle="buttons"] > .btn input[type="radio"],
[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
[data-toggle="buttons"] > .btn input[type="checkbox"],
[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
position: absolute;
clip: rect(0, 0, 0, 0);
pointer-events: none;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-right: 0;
padding-left: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group .form-control:focus {
z-index: 3;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 46px;
line-height: 46px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 30px;
line-height: 30px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 6px 12px;
font-size: 14px;
font-weight: normal;
line-height: 1;
color: #555;
text-align: center;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 4px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 3px;
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 18px;
border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
z-index: 2;
margin-left: -1px;
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eee;
}
.nav > li.disabled > a {
color: #777;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #777;
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eee;
border-color: #337ab7;
}
.nav .nav-divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #ddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eee #eee #ddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555;
cursor: default;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 4px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #fff;
background-color: #337ab7;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
border: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 4px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
padding-right: 15px;
padding-left: 15px;
overflow-x: visible;
-webkit-overflow-scrolling: touch;
border-top: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-right: 0;
padding-left: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-device-width: 480px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
}
.navbar-toggle {
position: relative;
float: right;
padding: 9px 10px;
margin-top: 8px;
margin-right: 15px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 768px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 7.5px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
}
.navbar-form {
padding: 10px 15px;
margin-top: 8px;
margin-right: -15px;
margin-bottom: 8px;
margin-left: -15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .form-control-static {
display: inline-block;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-left: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
.navbar-form .form-group:last-child {
margin-bottom: 0;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
margin-bottom: 0;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 8px;
margin-bottom: 8px;
}
.navbar-btn.btn-sm {
margin-top: 10px;
margin-bottom: 10px;
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-text {
margin-top: 15px;
margin-bottom: 15px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-right: 15px;
margin-left: 15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
margin-right: -15px;
}
.navbar-right ~ .navbar-right {
margin-right: 0;
}
}
.navbar-default {
background-color: #f8f8f8;
border-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5e5e5e;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777;
}
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #ddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #ddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: #555;
background-color: #e7e7e7;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777;
}
.navbar-default .navbar-link:hover {
color: #333;
}
.navbar-default .btn-link {
color: #777;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #333;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #ccc;
}
.navbar-inverse {
background-color: #222;
border-color: #080808;
}
.navbar-inverse .navbar-brand {
color: #9d9d9d;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #444;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #333;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #333;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
color: #fff;
background-color: #080808;
}
@media (max-width: 767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #9d9d9d;
}
.navbar-inverse .navbar-link:hover {
color: #fff;
}
.navbar-inverse .btn-link {
color: #9d9d9d;
}
.navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link:focus {
color: #fff;
}
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link[disabled]:focus,
fieldset[disabled] .navbar-inverse .btn-link:focus {
color: #444;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 20px;
list-style: none;
background-color: #f5f5f5;
border-radius: 4px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
padding: 0 5px;
color: #ccc;
content: "/\00a0";
}
.breadcrumb > .active {
color: #777;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #337ab7;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
z-index: 2;
color: #23527c;
background-color: #eee;
border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 3;
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.pager {
padding-left: 0;
margin: 20px 0;
text-align: center;
list-style: none;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
a.label:hover,
a.label:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #777;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #5e5e5e;
}
.label-primary {
background-color: #337ab7;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #286090;
}
.label-success {
background-color: #5cb85c;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #449d44;
}
.label-info {
background-color: #5bc0de;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #31b0d5;
}
.label-warning {
background-color: #f0ad4e;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #ec971f;
}
.label-danger {
background-color: #d9534f;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #c9302c;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: middle;
background-color: #777;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge,
.btn-group-xs > .btn .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #337ab7;
background-color: #fff;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding-top: 30px;
padding-bottom: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-right: 15px;
padding-left: 15px;
border-radius: 6px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-right: 60px;
padding-left: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 63px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: border .2s ease-in-out;
-o-transition: border .2s ease-in-out;
transition: border .2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-right: auto;
margin-left: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #337ab7;
}
.thumbnail .caption {
padding: 9px;
color: #333;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px;
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #2b542c;
}
.alert-info {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #245269;
}
.alert-warning {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.alert-warning hr {
border-top-color: #f7e1b5;
}
.alert-warning .alert-link {
color: #66512c;
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.alert-danger hr {
border-top-color: #e4b9c0;
}
.alert-danger .alert-link {
color: #843534;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@-o-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #337ab7;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
.progress-striped .progress-bar,
.progress-bar-striped {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
-webkit-background-size: 40px 40px;
background-size: 40px 40px;
}
.progress.active .progress-bar,
.progress-bar.active {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar-success {
background-color: #5cb85c;
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-info {
background-color: #5bc0de;
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-warning {
background-color: #f0ad4e;
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-danger {
background-color: #d9534f;
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media,
.media-body {
overflow: hidden;
zoom: 1;
}
.media-body {
width: 10000px;
}
.media-object {
display: block;
}
.media-object.img-thumbnail {
max-width: none;
}
.media-right,
.media > .pull-right {
padding-left: 10px;
}
.media-left,
.media > .pull-left {
padding-right: 10px;
}
.media-left,
.media-right,
.media-body {
display: table-cell;
vertical-align: top;
}
.media-middle {
vertical-align: middle;
}
.media-bottom {
vertical-align: bottom;
}
.media-heading {
margin-top: 0;
margin-bottom: 5px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
padding-left: 0;
margin-bottom: 20px;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd;
}
.list-group-item:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
a.list-group-item,
button.list-group-item {
color: #555;
}
a.list-group-item .list-group-item-heading,
button.list-group-item .list-group-item-heading {
color: #333;
}
a.list-group-item:hover,
button.list-group-item:hover,
a.list-group-item:focus,
button.list-group-item:focus {
color: #555;
text-decoration: none;
background-color: #f5f5f5;
}
button.list-group-item {
width: 100%;
text-align: left;
}
.list-group-item.disabled,
.list-group-item.disabled:hover,
.list-group-item.disabled:focus {
color: #777;
cursor: not-allowed;
background-color: #eee;
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading {
color: inherit;
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text {
color: #777;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
z-index: 2;
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active .list-group-item-heading > small,
.list-group-item.active:hover .list-group-item-heading > small,
.list-group-item.active:focus .list-group-item-heading > small,
.list-group-item.active .list-group-item-heading > .small,
.list-group-item.active:hover .list-group-item-heading > .small,
.list-group-item.active:focus .list-group-item-heading > .small {
color: inherit;
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:hover .list-group-item-text,
.list-group-item.active:focus .list-group-item-text {
color: #c7ddef;
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8;
}
a.list-group-item-success,
button.list-group-item-success {
color: #3c763d;
}
a.list-group-item-success .list-group-item-heading,
button.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
button.list-group-item-success:hover,
a.list-group-item-success:focus,
button.list-group-item-success:focus {
color: #3c763d;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
button.list-group-item-success.active,
a.list-group-item-success.active:hover,
button.list-group-item-success.active:hover,
a.list-group-item-success.active:focus,
button.list-group-item-success.active:focus {
color: #fff;
background-color: #3c763d;
border-color: #3c763d;
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7;
}
a.list-group-item-info,
button.list-group-item-info {
color: #31708f;
}
a.list-group-item-info .list-group-item-heading,
button.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
button.list-group-item-info:hover,
a.list-group-item-info:focus,
button.list-group-item-info:focus {
color: #31708f;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
button.list-group-item-info.active,
a.list-group-item-info.active:hover,
button.list-group-item-info.active:hover,
a.list-group-item-info.active:focus,
button.list-group-item-info.active:focus {
color: #fff;
background-color: #31708f;
border-color: #31708f;
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3;
}
a.list-group-item-warning,
button.list-group-item-warning {
color: #8a6d3b;
}
a.list-group-item-warning .list-group-item-heading,
button.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
button.list-group-item-warning:hover,
a.list-group-item-warning:focus,
button.list-group-item-warning:focus {
color: #8a6d3b;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
button.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
button.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus,
button.list-group-item-warning.active:focus {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b;
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede;
}
a.list-group-item-danger,
button.list-group-item-danger {
color: #a94442;
}
a.list-group-item-danger .list-group-item-heading,
button.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
button.list-group-item-danger:hover,
a.list-group-item-danger:focus,
button.list-group-item-danger:focus {
color: #a94442;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
button.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
button.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus,
button.list-group-item-danger.active:focus {
color: #fff;
background-color: #a94442;
border-color: #a94442;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 20px;
background-color: #fff;
border: 1px solid transparent;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color: inherit;
}
.panel-title > a,
.panel-title > small,
.panel-title > .small,
.panel-title > small > a,
.panel-title > .small > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .list-group,
.panel > .panel-collapse > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item,
.panel > .panel-collapse > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child,
.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .list-group:last-child .list-group-item:last-child,
.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .panel-heading + .panel-collapse > .list-group .list-group-item:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.list-group + .panel-footer {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table,
.panel > .panel-collapse > .table {
margin-bottom: 0;
}
.panel > .table caption,
.panel > .table-responsive > .table caption,
.panel > .panel-collapse > .table caption {
padding-right: 15px;
padding-left: 15px;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 3px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 3px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive,
.panel > .table + .panel-body,
.panel > .table-responsive + .panel-body {
border-top: 1px solid #ddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
margin-bottom: 0;
border: 0;
}
.panel-group {
margin-bottom: 20px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 4px;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse > .panel-body,
.panel-group .panel-heading + .panel-collapse > .list-group {
border-top: 1px solid #ddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #ddd;
}
.panel-default {
border-color: #ddd;
}
.panel-default > .panel-heading {
color: #333;
background-color: #f5f5f5;
border-color: #ddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ddd;
}
.panel-default > .panel-heading .badge {
color: #f5f5f5;
background-color: #333;
}
.panel-default > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ddd;
}
.panel-primary {
border-color: #337ab7;
}
.panel-primary > .panel-heading {
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #337ab7;
}
.panel-primary > .panel-heading .badge {
color: #337ab7;
background-color: #fff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #337ab7;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-heading .badge {
color: #dff0d8;
background-color: #3c763d;
}
.panel-success > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-heading .badge {
color: #d9edf7;
background-color: #31708f;
}
.panel-info > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #faebcc;
}
.panel-warning > .panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.panel-warning > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #faebcc;
}
.panel-warning > .panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b;
}
.panel-warning > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #faebcc;
}
.panel-danger {
border-color: #ebccd1;
}
.panel-danger > .panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.panel-danger > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ebccd1;
}
.panel-danger > .panel-heading .badge {
color: #f2dede;
background-color: #a94442;
}
.panel-danger > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ebccd1;
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
padding-bottom: 75%;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, .15);
}
.well-lg {
padding: 24px;
border-radius: 6px;
}
.well-sm {
padding: 9px;
border-radius: 3px;
}
.close {
float: right;
font-size: 21px;
font-weight: bold;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
filter: alpha(opacity=20);
opacity: .2;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
filter: alpha(opacity=50);
opacity: .5;
}
button.close {
-webkit-appearance: none;
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
}
.modal-open {
overflow: hidden;
}
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
display: none;
overflow: hidden;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transition: -webkit-transform .3s ease-out;
-o-transition: -o-transform .3s ease-out;
transition: transform .3s ease-out;
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
-o-transform: translate(0, -25%);
transform: translate(0, -25%);
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
-o-transform: translate(0, 0);
transform: translate(0, 0);
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #999;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
outline: 0;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000;
}
.modal-backdrop.fade {
filter: alpha(opacity=0);
opacity: 0;
}
.modal-backdrop.in {
filter: alpha(opacity=50);
opacity: .5;
}
.modal-header {
padding: 15px;
border-bottom: 1px solid #e5e5e5;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.42857143;
}
.modal-body {
position: relative;
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-bottom: 0;
margin-left: 5px;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: normal;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
letter-spacing: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
white-space: normal;
filter: alpha(opacity=0);
opacity: 0;
line-break: auto;
}
.tooltip.in {
filter: alpha(opacity=90);
opacity: .9;
}
.tooltip.top {
padding: 5px 0;
margin-top: -3px;
}
.tooltip.right {
padding: 0 5px;
margin-left: 3px;
}
.tooltip.bottom {
padding: 5px 0;
margin-top: 3px;
}
.tooltip.left {
padding: 0 5px;
margin-left: -3px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #fff;
text-align: center;
background-color: #000;
border-radius: 4px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-left .tooltip-arrow {
right: 5px;
bottom: 0;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-right .tooltip-arrow {
bottom: 0;
left: 5px;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
right: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
left: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
font-style: normal;
font-weight: normal;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
letter-spacing: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
white-space: normal;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
line-break: auto;
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
padding: 8px 14px;
margin: 0;
font-size: 14px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
content: "";
border-width: 10px;
}
.popover.top > .arrow {
bottom: -11px;
left: 50%;
margin-left: -11px;
border-top-color: #999;
border-top-color: rgba(0, 0, 0, .25);
border-bottom-width: 0;
}
.popover.top > .arrow:after {
bottom: 1px;
margin-left: -10px;
content: " ";
border-top-color: #fff;
border-bottom-width: 0;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-right-color: #999;
border-right-color: rgba(0, 0, 0, .25);
border-left-width: 0;
}
.popover.right > .arrow:after {
bottom: -10px;
left: 1px;
content: " ";
border-right-color: #fff;
border-left-width: 0;
}
.popover.bottom > .arrow {
top: -11px;
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999;
border-bottom-color: rgba(0, 0, 0, .25);
}
.popover.bottom > .arrow:after {
top: 1px;
margin-left: -10px;
content: " ";
border-top-width: 0;
border-bottom-color: #fff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999;
border-left-color: rgba(0, 0, 0, .25);
}
.popover.left > .arrow:after {
right: 1px;
bottom: -10px;
content: " ";
border-right-width: 0;
border-left-color: #fff;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
-o-transition: .6s ease-in-out left;
transition: .6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-inner > .item {
-webkit-transition: -webkit-transform .6s ease-in-out;
-o-transition: -o-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-perspective: 1000px;
perspective: 1000px;
}
.carousel-inner > .item.next,
.carousel-inner > .item.active.right {
left: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
.carousel-inner > .item.prev,
.carousel-inner > .item.active.left {
left: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
.carousel-inner > .item.next.left,
.carousel-inner > .item.prev.right,
.carousel-inner > .item.active {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
background-color: rgba(0, 0, 0, 0);
filter: alpha(opacity=50);
opacity: .5;
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control.right {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control:hover,
.carousel-control:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
margin-top: -10px;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
margin-left: -10px;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
margin-right: -10px;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
font-family: serif;
line-height: 1;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
padding-left: 0;
margin-left: -30%;
text-align: center;
list-style: none;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
border: 1px solid #fff;
border-radius: 10px;
}
.carousel-indicators .active {
width: 12px;
height: 12px;
margin: 0;
background-color: #fff;
}
.carousel-caption {
position: absolute;
right: 15%;
bottom: 20px;
left: 15%;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -10px;
font-size: 30px;
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -10px;
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -10px;
}
.carousel-caption {
right: 20%;
left: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
.clearfix:before,
.clearfix:after,
.dl-horizontal dd:before,
.dl-horizontal dd:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-header:before,
.modal-header:after,
.modal-footer:before,
.modal-footer:after {
display: table;
content: " ";
}
.clearfix:after,
.dl-horizontal dd:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-header:after,
.modal-footer:after {
clear: both;
}
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
}
.affix {
position: fixed;
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table !important;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.visible-xs-block {
display: block !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline {
display: inline !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline-block {
display: inline-block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table !important;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline {
display: inline !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline-block {
display: inline-block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table !important;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-block {
display: block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline {
display: inline !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline-block {
display: inline-block !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table !important;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg-block {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline {
display: inline !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline-block {
display: inline-block !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table !important;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
.visible-print-block {
display: none !important;
}
@media print {
.visible-print-block {
display: block !important;
}
}
.visible-print-inline {
display: none !important;
}
@media print {
.visible-print-inline {
display: inline !important;
}
}
.visible-print-inline-block {
display: none !important;
}
@media print {
.visible-print-inline-block {
display: inline-block !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
/*# sourceMappingURL=bootstrap.css.map */
| loucilvr/npf-leadership | css/bootstrap.css | CSS | apache-2.0 | 145,720 |
/***
DEVSIM
Copyright 2013 Devsim LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***/
#ifndef DS_MATH_TYPES_HH
#define DS_MATH_TYPES_HH
#include <vector>
#include <complex>
namespace dsMath
{
template <typename DoubleType>
using ComplexDouble_t = std::complex<DoubleType>;
template <typename DoubleType>
using ComplexDoubleVec_t = std::vector<std::complex<DoubleType>>;
template <typename DoubleType>
using DoubleVec_t = std::vector<DoubleType>;
typedef std::vector<int> IntVec_t;
template <typename T, class U >
void CopySTLVectorToRaw(T *nv, const U &ov)
{
T *p = nv;
typename U::const_iterator it = ov.begin();
for (it = ov.begin(); it != ov.end(); ++it)
{
#if 0
*(p++) = *it;
#endif
*(p++) = *(reinterpret_cast<const T *>(&(*it)));
}
}
//// Destination must be correct size
template <typename T, class U >
void CopyRawToSTLVector(T *nv, U &ov)
{
T *p = nv;
typename U::iterator it = ov.begin();
for (it = ov.begin(); it != ov.end(); ++it)
{
#if 0
*it = *(p++);
#endif
*(reinterpret_cast<T *>(&(*it))) = *(p++);
}
}
}
#endif
| devsim/devsim | src/math/dsMathTypes.hh | C++ | apache-2.0 | 1,592 |
#===============================================================================
# Copyright 2019-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================
# Security Linker flags
set(LINK_FLAG_SECURITY "")
# Data relocation and protection (RELRO)
set(LINK_FLAG_SECURITY "${LINK_FLAG_SECURITY} -Wl,-z,relro -Wl,-z,now")
# Stack execution protection
set(LINK_FLAG_SECURITY "${LINK_FLAG_SECURITY} -Wl,-z,noexecstack")
# Security Compiler flags
set(CMAKE_C_FLAGS_SECURITY "")
# Format string vulnerabilities
set(CMAKE_C_FLAGS_SECURITY "${CMAKE_C_FLAGS_SECURITY} -Wformat -Wformat-security -Werror=format-security")
# Security flag that adds compile-time and run-time checks
set(CMAKE_C_FLAGS_SECURITY "${CMAKE_C_FLAGS_SECURITY} -D_FORTIFY_SOURCE=2")
# Stack-based Buffer Overrun Detection
set(CMAKE_C_FLAGS_SECURITY "${CMAKE_C_FLAGS_SECURITY} -fstack-protector")
# Position Independent Execution (PIE)
set(CMAKE_C_FLAGS_SECURITY "${CMAKE_C_FLAGS_SECURITY} -fpic -fPIC")
# Enable Control-flow Enforcement Technology (CET) protection
set(CMAKE_C_FLAGS_SECURITY "${CMAKE_C_FLAGS_SECURITY} -fcf-protection=full")
# Enables important warning and error messages relevant to security during compilation
set(CMAKE_C_FLAGS_SECURITY "${CMAKE_C_FLAGS_SECURITY} -Wall")
# Warnings=errors
set(CMAKE_C_FLAGS_SECURITY "${CMAKE_C_FLAGS_SECURITY} -Werror")
# Linker flags
# Create shared library
set(LINK_FLAGS_DYNAMIC "-Wl,-shared")
# Add export files
set(LINK_FLAGS_DYNAMIC "${LINK_FLAGS_DYNAMIC} ${CRYPTO_MB_SOURCES_DIR}/cmake/dll_export/crypto_mb.linux.lib-export")
if(NOT OPENSSL_DISABLE)
set(LINK_FLAGS_DYNAMIC "${LINK_FLAGS_DYNAMIC} ${CRYPTO_MB_SOURCES_DIR}/cmake/dll_export/crypto_mb_ssl.linux.lib-export")
endif()
# Compiler flags
# Tells the compiler to align functions and loops
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -falign-functions=32 -falign-loops=32")
# Optimization level = 3, no-debug definition (turns off asserts)
set (CMAKE_C_FLAGS_RELEASE " -O3 -DNDEBUG" CACHE STRING "" FORCE)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}")
# Suppress warnings from casts from a pointer to an integer type of a different size
set(AVX512_CFLAGS "-Wno-pointer-to-int-cast")
# Optimisation dependent flags
set(AVX512_CFLAGS "${AVX512_CFLAGS} -xCORE-AVX512 -qopt-zmm-usage:high")
| Intel-EPID-SDK/epid-sdk | ext/ipp-crypto/sources/ippcp/crypto_mb/src/cmake/linux/Intel.cmake | CMake | apache-2.0 | 2,883 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `Mem` struct in crate `ocl_core`.">
<meta name="keywords" content="rust, rustlang, rust-lang, Mem">
<title>ocl_core::types::abs::Mem - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../normalize.css">
<link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../main.css">
</head>
<body class="rustdoc struct">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../../index.html'>ocl_core</a>::<wbr><a href='../index.html'>types</a>::<wbr><a href='index.html'>abs</a></p><script>window.sidebarCurrent = {name: 'Mem', ty: 'struct', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content">
<h1 class='fqn'><span class='in-band'>Struct <a href='../../index.html'>ocl_core</a>::<wbr><a href='../index.html'>types</a>::<wbr><a href='index.html'>abs</a>::<wbr><a class="struct" href=''>Mem</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#652' title='goto source code'>[src]</a></span></h1>
<pre class='rust struct'><div class="docblock attributes">#[repr(C)]
</div>pub struct Mem(_);</pre><div class='docblock'><p>cl_mem</p>
</div><h2 id='methods'>Methods</h2><h3 class='impl'><span class='in-band'><code>impl <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#654-676' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'><h4 id='method.from_raw_create_ptr' class="method"><span id='from_raw_create_ptr.v' class='invisible'><code>unsafe fn <a href='#method.from_raw_create_ptr' class='fnname'>from_raw_create_ptr</a>(ptr: <a class="type" href="../../../cl_sys/cl_h/type.cl_mem.html" title="type cl_sys::cl_h::cl_mem">cl_mem</a>) -> <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span></h4>
<div class='docblock'><p>Only call this when passing <strong>the original</strong> newly created pointer
directly from <code>clCreate...</code>. Do not use this to clone or copy.</p>
</div><h4 id='method.from_raw_copied_ptr' class="method"><span id='from_raw_copied_ptr.v' class='invisible'><code>unsafe fn <a href='#method.from_raw_copied_ptr' class='fnname'>from_raw_copied_ptr</a>(ptr: <a class="type" href="../../../cl_sys/cl_h/type.cl_mem.html" title="type cl_sys::cl_h::cl_mem">cl_mem</a>) -> <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span></h4>
<div class='docblock'><p>Only call this when passing a copied pointer such as from an
<code>clGet*****Info</code> function.</p>
</div><h4 id='method.as_ptr' class="method"><span id='as_ptr.v' class='invisible'><code>fn <a href='#method.as_ptr' class='fnname'>as_ptr</a>(&self) -> <a class="type" href="../../../cl_sys/cl_h/type.cl_mem.html" title="type cl_sys::cl_h::cl_mem">cl_mem</a></code></span></h4>
<div class='docblock'><p>Returns a pointer, do not store it.</p>
</div></div><h2 id='implementations'>Trait Implementations</h2><h3 class='impl'><span class='in-band'><code>impl <a class="trait" href="https://doc.rust-lang.org/nightly/core/fmt/trait.Debug.html" title="trait core::fmt::Debug">Debug</a> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#651' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'><h4 id='method.fmt' class="method"><span id='fmt.v' class='invisible'><code>fn <a href='https://doc.rust-lang.org/nightly/core/fmt/trait.Debug.html#tymethod.fmt' class='fnname'>fmt</a>(&self, __arg_0: &mut <a class="struct" href="https://doc.rust-lang.org/nightly/core/fmt/struct.Formatter.html" title="struct core::fmt::Formatter">Formatter</a>) -> <a class="type" href="https://doc.rust-lang.org/nightly/core/fmt/type.Result.html" title="type core::fmt::Result">Result</a></code></span></h4>
<div class='docblock'><p>Formats the value using the given formatter.</p>
</div></div><h3 class='impl'><span class='in-band'><code>impl <a class="trait" href="https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html" title="trait core::clone::Clone">Clone</a> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#678-683' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'><h4 id='method.clone' class="method"><span id='clone.v' class='invisible'><code>fn <a href='https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#tymethod.clone' class='fnname'>clone</a>(&self) -> <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span></h4>
<div class='docblock'><p>Returns a copy of the value. <a href="https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#tymethod.clone">Read more</a></p>
</div><h4 id='method.clone_from' class="method"><span id='clone_from.v' class='invisible'><code>fn <a href='https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#method.clone_from' class='fnname'>clone_from</a>(&mut self, source: &Self)</code><div class='since' title='Stable since Rust version 1.0.0'>1.0.0</div></span></h4>
<div class='docblock'><p>Performs copy-assignment from <code>source</code>. <a href="https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#method.clone_from">Read more</a></p>
</div></div><h3 class='impl'><span class='in-band'><code>impl <a class="trait" href="https://doc.rust-lang.org/nightly/core/ops/trait.Drop.html" title="trait core::ops::Drop">Drop</a> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#685-689' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'><h4 id='method.drop' class="method"><span id='drop.v' class='invisible'><code>fn <a href='https://doc.rust-lang.org/nightly/core/ops/trait.Drop.html#tymethod.drop' class='fnname'>drop</a>(&mut self)</code></span></h4>
<div class='docblock'><p>A method called when the value goes out of scope. <a href="https://doc.rust-lang.org/nightly/core/ops/trait.Drop.html#tymethod.drop">Read more</a></p>
</div></div><h3 class='impl'><span class='in-band'><code>impl<T> <a class="trait" href="../../../ocl_core/types/abs/trait.AsMem.html" title="trait ocl_core::types::abs::AsMem">AsMem</a><T> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a> <span class="where fmt-newline">where<br> T: <a class="trait" href="../../../ocl_core/trait.OclPrm.html" title="trait ocl_core::OclPrm">OclPrm</a>, </span></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#691-696' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'><h4 id='method.as_mem' class="method"><span id='as_mem.v' class='invisible'><code>fn <a href='../../../ocl_core/types/abs/trait.AsMem.html#tymethod.as_mem' class='fnname'>as_mem</a>(&self) -> &<a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span></h4>
</div><h3 class='impl'><span class='in-band'><code>impl<'a> <a class="trait" href="../../../ocl_core/types/abs/trait.MemCmdRw.html" title="trait ocl_core::types::abs::MemCmdRw">MemCmdRw</a> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#699' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl<'a> <a class="trait" href="../../../ocl_core/types/abs/trait.MemCmdRw.html" title="trait ocl_core::types::abs::MemCmdRw">MemCmdRw</a> for &'a <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#700' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl<'a> <a class="trait" href="../../../ocl_core/types/abs/trait.MemCmdRw.html" title="trait ocl_core::types::abs::MemCmdRw">MemCmdRw</a> for &'a mut <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#701' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl<'a> <a class="trait" href="../../../ocl_core/types/abs/trait.MemCmdAll.html" title="trait ocl_core::types::abs::MemCmdAll">MemCmdAll</a> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#702' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl<'a> <a class="trait" href="../../../ocl_core/types/abs/trait.MemCmdAll.html" title="trait ocl_core::types::abs::MemCmdAll">MemCmdAll</a> for &'a <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#703' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl<'a> <a class="trait" href="../../../ocl_core/types/abs/trait.MemCmdAll.html" title="trait ocl_core::types::abs::MemCmdAll">MemCmdAll</a> for &'a mut <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#704' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl <a class="trait" href="https://doc.rust-lang.org/nightly/core/marker/trait.Sync.html" title="trait core::marker::Sync">Sync</a> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#705' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl <a class="trait" href="https://doc.rust-lang.org/nightly/core/marker/trait.Send.html" title="trait core::marker::Send">Send</a> for <a class="struct" href="../../../ocl_core/types/abs/struct.Mem.html" title="struct ocl_core::types::abs::Mem">Mem</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../src/ocl_core/types/abs.rs.html#706' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'></div></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../";
window.currentCrate = "ocl_core";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script defer src="../../../search-index.js"></script>
</body>
</html> | liebharc/clFFT | docs/bindings/ocl_core/types/abs/struct.Mem.html | HTML | apache-2.0 | 15,138 |
# Schroeteria decaisneana (Boud.) De Toni, 1888 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
in Berlese, De Toni & Fischer, Syll. fung. (Abellini) 7: 501 (1888)
#### Original name
Geminella decaisneana Boud.
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Schroeteria/Schroeteria decaisneana/README.md | Markdown | apache-2.0 | 289 |
package io.corbel.eventbus.ioc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import io.corbel.eventbus.EventHandler;
import io.corbel.eventbus.service.EventBusRegistry;
/**
* @author Alexander De Leon
*
*/
public class EventBusRegistrar implements ApplicationContextAware {
private static final Logger LOG = LoggerFactory.getLogger(EventBusRegistrar.class);
private final EventBusRegistry registry;
public EventBusRegistrar(EventBusRegistry registry) {
this.registry = registry;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
for (EventHandler<?> handler : context.getBeansOfType(EventHandler.class).values()) {
LOG.info("Registering event handler {} for events of type {}", handler.getClass().getName(), handler.getEventType().getName());
registry.register(handler);
}
}
}
| corbel-platform/event-bus | src/main/java/io/corbel/eventbus/ioc/EventBusRegistrar.java | Java | apache-2.0 | 1,087 |
# -*- coding: utf-8 -*-
##############################################################################################
# This file is deprecated because Python 2.x is deprecated #
# A Python 3.x version of this file can be found at: #
# #
# https://github.com/Guymer/PyGuymer3/blob/master/load_GPS_EXIF.py #
##############################################################################################
def load_GPS_EXIF(fname, python = True):
# Load sub-functions ...
from .load_GPS_EXIF1 import load_GPS_EXIF1
from .load_GPS_EXIF2 import load_GPS_EXIF2
# Check what the user wants ...
if python:
# Will use the Python module "exifread" ...
return load_GPS_EXIF1(fname)
else:
# Will use the binary "exiftool" ...
return load_GPS_EXIF2(fname)
| Guymer/PyGuymer | load_GPS_EXIF.py | Python | apache-2.0 | 993 |
/**
* Copyright 2014
* SMEdit https://github.com/StarMade/SMEdit
* SMTools https://github.com/StarMade/SMTools
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
**/
package jo.util.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import javax.tools.ToolProvider;
import jo.util.GlobalConfiguration;
import jo.util.OperatingSystem;
import jo.util.Paths;
/**
* @author Robert Barefoot - version 1.0
*/
public class JavaCompiler {
private final static String JAVACARGS = "-g:none";
private static int compileNative(final javax.tools.JavaCompiler javac,
final InputStream source, final String classPath)
throws FileNotFoundException {
final FileOutputStream[] out = new FileOutputStream[2];
for (int i = 0; i < 2; i++) {
out[i] = new FileOutputStream(new File(
Paths.getCollectDirectory(), "compile."
+ Integer.toString(i) + ".txt"));
}
return javac.run(source, out[0], out[1], JAVACARGS, "-cp", classPath);
}
private static void compileSystem(final File source, final String classPath)
throws IOException {
final String javac = findJavac();
if (javac == null) {
throw new IOException();
}
Runtime.getRuntime().exec(
new String[]{javac, JAVACARGS, "-cp", classPath,
source.getAbsolutePath()});
}
public static boolean compileWeb(final String source, final File out) {
try {
HttpClient.download(
new URL(
source
+ "?v="
+ GlobalConfiguration.getVersion() + "&s="
+ URLEncoder.encode(source, "UTF-8")), out);
} catch (final IOException ignored) {
return false;
}
if (out.length() == 0) {
out.delete();
}
return out.exists();
}
private static String findJavac() {
try {
if (GlobalConfiguration.getCurrentOperatingSystem() == OperatingSystem.WINDOWS) {
String currentVersion = readProcess("REG QUERY \"HKLM\\SOFTWARE\\JavaSoft\\Java Development Kit\" /v CurrentVersion");
currentVersion = currentVersion.substring(
currentVersion.indexOf("REG_SZ") + 6).trim();
String binPath = readProcess("REG QUERY \"HKLM\\SOFTWARE\\JavaSoft\\Java Development Kit\\"
+ currentVersion + "\" /v JavaHome");
binPath = binPath.substring(binPath.indexOf("REG_SZ") + 6)
.trim() + "\\bin\\javac.exe";
return new File(binPath).exists() ? binPath : null;
} else {
final String whichQuery = readProcess("which javac");
return whichQuery == null || whichQuery.length() == 0 ? null
: whichQuery.trim();
}
} catch (final IOException ignored) {
return null;
}
}
public static boolean isAvailable() {
return !(ToolProvider.getSystemJavaCompiler() == null && findJavac() == null);
}
private static String readProcess(final String exec) throws IOException {
final Process compiler = Runtime.getRuntime().exec(exec);
final InputStream is = compiler.getInputStream();
try {
compiler.waitFor();
} catch (final InterruptedException ignored) {
return null;
}
final StringBuilder result = new StringBuilder(256);
int r;
while ((r = is.read()) != -1) {
result.append((char) r);
}
return result.toString();
}
public static boolean run(final File source, final String classPath) {
final javax.tools.JavaCompiler javac = ToolProvider
.getSystemJavaCompiler();
try {
if (javac != null) {
return compileNative(javac, new FileInputStream(source),
classPath) == 0;
} else {
compileSystem(source, classPath);
return true;
}
} catch (final IOException ignored) {
}
return false;
}
}
| skunkiferous/SMEdit | jo_sm/src/main/java/jo/util/io/JavaCompiler.java | Java | apache-2.0 | 4,979 |
<?php
/**
* ECSHOP 标签云
* ============================================================================
* * 版权所有 2005-2012 上海商派网络科技有限公司,并保留所有权利。
* 网站地址: http://www.ecshop.com;
* ----------------------------------------------------------------------------
* 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和
* 使用;不允许对程序代码以任何形式任何目的的再发布。
* ============================================================================
* $Author: liubo $
* $Id: tag_cloud.php 17217 2011-01-19 06:29:08Z liubo $
*/
define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
assign_template();
$position = assign_ur_here(0, $_LANG['tag_cloud']);
$smarty->assign('page_title', $position['title']); // 页面标题
$smarty->assign('ur_here', $position['ur_here']); // 当前位置
$smarty->assign('categories', get_categories_tree()); // 分类树
$smarty->assign('helps', get_shop_help()); // 网店帮助
$smarty->assign('top_goods', get_top10()); // 销售排行
$smarty->assign('promotion_info', get_promotion_info());
/* 调查 */
$vote = get_vote();
if (!empty($vote))
{
$smarty->assign('vote_id', $vote['id']);
$smarty->assign('vote', $vote['content']);
}
assign_dynamic('tag_cloud');
$tags = get_tags();
if (!empty($tags))
{
include_once(ROOT_PATH . 'includes/lib_clips.php');
color_tag($tags);
}
$smarty->assign('tags', $tags);
$smarty->display('tag_cloud.dwt');
?> | lvguocai/ec | tag_cloud.php | PHP | apache-2.0 | 1,745 |
#!/bin/bash
###############################################################################
#Variables
export PROJECT_LIST=$(find project | grep "GCC/Makefile")
export BOARD_LIST="project/*"
export OUT="$PWD/out"
export FLASHGENERATOR="tools/flashgen/flashgen.pl"
feature_mk=""
platform=$(uname)
if [[ "$platform" =~ "MINGW" ]]; then
export EXTRA_VAR=-j
else
# export EXTRA_VAR=-j`cat /proc/cpuinfo |grep ^processor|wc -l`
export EXTRA_VAR=-j
fi
###############################################################################
#Functions
show_usage () {
echo "==============================================================="
echo "Build Project"
echo "==============================================================="
echo "Usage: $0 <board> <project> [bl|clean] <argument>"
echo ""
echo "Example:"
echo " $0 mt7687_hdk iot_sdk_demo"
echo " $0 mt7687_hdk iot_sdk_demo bl (build with bootloader)"
echo " $0 clean (clean folder: out)"
echo " $0 mt7687_hdk clean (clean folder: out/mt7687_hdk)"
echo " $0 mt7687_hdk iot_sdk_demo clean (clean folder: out/mt7687_hdk/iot_sdk_demo)"
echo ""
echo "Argument:"
echo " -f=<feature makefile> or --feature=<feature makefile>"
echo " Replace feature.mk with other makefile. For example, "
echo " the feature_example.mk is under project folder, -f=feature_example.mk"
echo " will replace feature.mk with feature_example.mk."
echo ""
echo " -o=<make option> or --option=<make option>"
echo " Assign additional make option. For example, "
echo " to compile module sequentially, use -o=-j1."
echo " to turn on specific feature in feature makefile, use -o=<feature_name>=y"
echo " to assign more than one options, use -o=<option_1> -o=<option_2>."
echo ""
echo "==============================================================="
echo "List Available Example Projects"
echo "==============================================================="
echo "Usage: $0 list"
echo ""
}
show_available_proj () {
echo "==============================================================="
echo "Available Build Projects:"
echo "==============================================================="
for b in $BOARD_LIST
do
project_path=""
project_name_list=""
p=$(echo $PROJECT_LIST | tr " " "\n" | grep "$b")
if [ ! -z "$p" ]; then
echo " "`basename $b`
fi
for q in $p
do
if [ -e "$q" ]; then
project_path=$(echo $q | sed 's/GCC\/Makefile//')
project_name_list="${project_name_list} $(basename $project_path)"
fi
done
for i in `echo $project_name_list | tr " " "\n" | sort`
do
echo " "" "$i
done
done
}
target_check () {
for p in $PROJECT_LIST
do
q=$(echo $p | grep "project/$1")
if [ ! -z "$q" ]; then
r=$(echo $q | sed 's/GCC\/Makefile//')
s=`basename $r`
if [ "$s" == "$2" ]; then
echo "Build board:$1 project:$2"
OUT=$OUT/$1/$2
BUILD=project/$1/$2
export TARGET_PATH=$(dirname $q)
return 0
fi
fi
done
return 1
}
# support MinGW
mingw_check () {
echo "platform=$platform"
if [[ "$platform" =~ "MINGW" ]]; then
pwdpath=$(pwd)
echo $pwdpath
if [[ "$pwdpath" =~ "\[|\]| " ]]; then
echo "Build.sh Exception: The codebase folder name should not have spacing, [ or ]."
exit 1
fi
fi
}
clean_out () {
rm -rf $1
echo "rm -rf $1"
if [ -d "middleware/MTK/minisupp" ]; then
make -C middleware/MTK/minisupp clean
fi
}
###############################################################################
#Begin here
if [ "$#" -eq "0" ]; then
show_usage
exit 1
fi
# parsing arguments
declare -a argv=($0)
ori_argv=$@
do_make_clean="FALSE"
for i in $@
do
case $i in
-o=*|--option=*)
extra_opt+=" ${i#*=}"
echo "$extra_opt" | grep -q -E "OUT"
if [[ $? -eq 0 ]]; then
OUT=`echo $extra_opt | grep -o "\s*OUT=[^\s]*" | cut -d '=' -f2 | tr -d ' '`
OUT=$PWD/$OUT
echo "output folder change to: $OUT"
fi
do_make_clean="TRUE"
shift
;;
-f=*|--feature=*)
feature_mk="${i#*=}"
shift
;;
list)
show_available_proj
exit 0
;;
-*)
echo "Error: unknown parameter \"$i\""
show_usage
exit 1
;;
*)
argv+=($i)
;;
esac
done
export PROJ_NAME=${argv[2]}
###############################################################################
if [ "${argv[3]}" == "bl" ]; then
target_check ${argv[1]} ${argv[2]}
if [ "$?" -ne "0" ]; then
echo "Error: ${argv[1]} ${argv[2]} is not available board & project"
show_usage
exit 1
fi
if [ $do_make_clean == "TRUE" ]; then
clean_out $OUT
fi
mingw_check
where_to_find_feature_mk=$TARGET_PATH
if [ ! -z $feature_mk ]; then
if [ ! -e "$TARGET_PATH/$feature_mk" ]; then
echo "Error: cannot find $feature_mk under $TARGET_PATH."
exit 1
fi
EXTRA_VAR+=" FEATURE=$feature_mk"
else
where_to_find_feature_mk=`grep "^TARGET_PATH\ *[?:]\{0,1\}=\ *" $TARGET_PATH/Makefile | cut -d '=' -f2 | tr -d ' ' | tail -1`
if [ -z $where_to_find_feature_mk ]; then
where_to_find_feature_mk=$TARGET_PATH
fi
feature_mk=`grep "^FEATURE\ *[?:]\{0,1\}=\ *" $TARGET_PATH/Makefile | cut -d '=' -f2 | tr -d ' ' | tail -1`
echo "FEATURE=$feature_mk"
fi
if [ ! -e "$OUT/obj/$TARGET_PATH/tmp.mk" ]; then
mkdir -p $OUT/obj/$TARGET_PATH
cp $where_to_find_feature_mk/$feature_mk $OUT/obj/$TARGET_PATH/tmp.mk
else
diff -q $where_to_find_feature_mk/$feature_mk $OUT/obj/$TARGET_PATH/tmp.mk
if [ $? -ne 0 ]; then
clean_out $OUT
fi
fi
CM4_TARGET_PATH_BAK=$TARGET_PATH
TARGET_PATH="project/${argv[1]}/apps/bootloader/GCC"
if [ "${argv[2]}" == "iot_sdk_lite" ]; then
TARGET_PATH="project/${argv[1]}/apps/bootloader_lite/GCC"
fi
mkdir -p $OUT/log
echo "$0 $ori_argv" > $OUT/log/build_time.log
echo "Start Build: "`date` >> $OUT/log/build_time.log
echo "Build bootloader..."
# Check if the source dir is existed
if [ ! -d "project/${argv[1]}/apps/bootloader" ]; then
echo "Error: no bootloader source in project/${argv[1]}/apps/bootloader"
exit 1
fi
mkdir -p $OUT
make -C $TARGET_PATH BUILD_DIR=$OUT/obj/bootloader OUTPATH=$OUT BL_MAIN_PROJECT=${argv[2]} 2>> $OUT/err.log
BUILD_RESULT=$?
mkdir -p $OUT/lib
mv -f $OUT/*.a $OUT/lib/ 2> /dev/null
mkdir -p $OUT/log
mv -f $OUT/*.log $OUT/log/ 2> /dev/null
if [ $BUILD_RESULT -ne 0 ]; then
echo "Error: bootloader build failed!!"
echo "BOOTLOADER BUILD : FAIL" >> $OUT/log/build_time.log
exit 2;
else
echo "BOOTLOADER BUILD : PASS" >> $OUT/log/build_time.log
fi
echo "Build bootloader...Done"
# build cm4 firmware
echo "Build CM4 Firmware..."
TARGET_PATH=$CM4_TARGET_PATH_BAK
mkdir -p $OUT/autogen
EXTRA_VAR+="$extra_opt"
#echo "make -C $TARGET_PATH BUILD_DIR=$OUT/obj OUTPATH=$OUT $EXTRA_VAR"
make -C $TARGET_PATH BUILD_DIR=$OUT/obj OUTPATH=$OUT $EXTRA_VAR 2>> $OUT/err.log
BUILD_RESULT=$?
mkdir -p $OUT/lib
mv -f $OUT/*.a $OUT/lib/ 2> /dev/null
mkdir -p $OUT/log
mv -f $OUT/*.log $OUT/log/ 2> /dev/null
echo "Build CM4 Firmware...Done"
echo "End Build: "`date` >> $OUT/log/build_time.log
cat $OUT/log/build.log | grep "MODULE BUILD" >> $OUT/log/build_time.log
if [ "$BUILD_RESULT" -eq "0" ]; then
echo "TOTAL BUILD: PASS" >> $OUT/log/build_time.log
else
echo "TOTAL BUILD: FAIL" >> $OUT/log/build_time.log
fi
echo "=============================================================="
cat $OUT/log/build_time.log
exit $BUILD_RESULT
elif [ "${argv[3]}" == "clean" ]; then
rm -rf $OUT/${argv[1]}/${argv[2]}
if [ -d "middleware/MTK/minisupp" ]; then
make -C middleware/MTK/minisupp clean
fi
elif [ "${argv[2]}" == "clean" ]; then
rm -rf $OUT/${argv[1]}
if [ -d "middleware/MTK/minisupp" ]; then
make -C middleware/MTK/minisupp clean
fi
elif [ "${argv[1]}" == "clean" ]; then
rm -rf $OUT
if [ -d "middleware/MTK/minisupp" ]; then
make -C middleware/MTK/minisupp clean
fi
else
target_check ${argv[1]} ${argv[2]}
if [ "$?" -ne "0" ]; then
echo "Error: ${argv[1]} ${argv[2]} is not available board & project or module"
show_usage
exit 1
fi
if [ $do_make_clean == "TRUE" ]; then
clean_out $OUT
fi
mingw_check
where_to_find_feature_mk=$TARGET_PATH
if [ ! -z $feature_mk ]; then
if [ ! -e "$TARGET_PATH/$feature_mk" ]; then
echo "Error: cannot find $feature_mk under $TARGET_PATH."
exit 1
fi
EXTRA_VAR+=" FEATURE=$feature_mk"
else
where_to_find_feature_mk=`grep "^TARGET_PATH\ *[?:]\{0,1\}=\ *" $TARGET_PATH/Makefile | cut -d '=' -f2 | tr -d ' ' | tail -1`
if [ -z $where_to_find_feature_mk ]; then
where_to_find_feature_mk=$TARGET_PATH
fi
feature_mk=`grep "^FEATURE\ *[?:]\{0,1\}=\ *" $TARGET_PATH/Makefile | cut -d '=' -f2 | tr -d ' ' | tail -1`
echo "FEATURE=$feature_mk"
fi
if [ ! -e "$OUT/obj/$TARGET_PATH/tmp.mk" ]; then
mkdir -p $OUT/obj/$TARGET_PATH
cp $where_to_find_feature_mk/$feature_mk $OUT/obj/$TARGET_PATH/tmp.mk
else
diff -q $where_to_find_feature_mk/$feature_mk $OUT/obj/$TARGET_PATH/tmp.mk
if [ $? -ne 0 ]; then
clean_out $OUT
fi
fi
mkdir -p $OUT/autogen
mkdir -p $OUT/log
echo "$0 $ori_argv" > $OUT/log/build_time.log
echo "Start Build: "`date` >> $OUT/log/build_time.log
if [ ! -z $feature_mk ]; then
EXTRA_VAR+=" FEATURE=$feature_mk"
fi
EXTRA_VAR+="$extra_opt"
#echo "make -C $TARGET_PATH BUILD_DIR=$OUT/obj OUTPATH=$OUT $EXTRA_VAR"
make -C $TARGET_PATH BUILD_DIR=$OUT/obj OUTPATH=$OUT $EXTRA_VAR 2>> $OUT/err.log
BUILD_RESULT=$?
mkdir -p $OUT/lib
mv -f $OUT/*.a $OUT/lib/ 2> /dev/null
mv -f $OUT/*.log $OUT/log/ 2> /dev/null
echo "End Build: "`date` >> $OUT/log/build_time.log
cat $OUT/log/build.log | grep "MODULE BUILD" >> $OUT/log/build_time.log
if [ "$BUILD_RESULT" -eq "0" ]; then
echo "TOTAL BUILD: PASS" >> $OUT/log/build_time.log
else
echo "TOTAL BUILD: FAIL" >> $OUT/log/build_time.log
fi
echo "=============================================================="
cat $OUT/log/build_time.log
exit $BUILD_RESULT
fi
| iamblue/ml-mt7687-config | templates/build_sdk.sh | Shell | apache-2.0 | 11,280 |
package org.jboss.aerogear.unifiedpush.service.spring;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.validateMockitoUsage;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.jboss.aerogear.unifiedpush.service.AbstractBaseServiceTest;
import org.jboss.aerogear.unifiedpush.service.annotations.LoggedInUser;
import org.jboss.aerogear.unifiedpush.service.impl.spring.IKeycloakService;
import org.jboss.aerogear.unifiedpush.service.impl.spring.KeycloakServiceImpl;
import org.jboss.aerogear.unifiedpush.service.impl.spring.OAuth2Configuration;
import org.jboss.aerogear.unifiedpush.service.impl.spring.OAuth2Configuration.DomainMatcher;
import org.jboss.aerogear.unifiedpush.service.spring.KeycloakServiceTest.KeycloakServiceTestConfig;
import org.jboss.aerogear.unifiedpush.spring.ServiceCacheConfig;
import org.jboss.aerogear.unifiedpush.system.ConfigurationEnvironment;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { KeycloakServiceTestConfig.class, ServiceCacheConfig.class })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
public class KeycloakServiceTest {
private static final LoggedInUser account = new LoggedInUser(AbstractBaseServiceTest.DEFAULT_USER);
@Autowired
private IKeycloakService kcServiceMock;
@Autowired
private MockProvider mockProvider;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
when(mockProvider.get().getVariantIdsFromClient(eq(account), eq("test-client-1")))
.thenReturn(Arrays.asList("variant-1", "variant-2"));
when(mockProvider.get().getVariantIdsFromClient(eq(account), eq("test-client-2")))
.thenReturn(Arrays.asList("variant-3", "variant-4"));
when(mockProvider.get().setPortalMode(anyBoolean())).thenCallRealMethod();
when(mockProvider.get().stripAccountName(any())).thenCallRealMethod();
when(mockProvider.get().stripApplicationName(any())).thenCallRealMethod();
}
@Test
public void cacheTest() {
List<String> firstInvocation = kcServiceMock.getVariantIdsFromClient(account, "test-client-1");
assertThat(firstInvocation.get(0), is("variant-1"));
List<String> secondInvocation = kcServiceMock.getVariantIdsFromClient(account, "test-client-1");
assertThat(secondInvocation.get(0), is("variant-1"));
verify(mockProvider.get(), times(1)).getVariantIdsFromClient(account, "test-client-1");
}
@Test
public void testDomains() {
assertThat(DomainMatcher.DOT.matches("aerobase.io", "test.aerobase.io"), is("test"));
assertThat(DomainMatcher.DOT.matches("aerobase.io", "a-bc.test.aerobase.io"), is("a-bc"));
assertThat(DomainMatcher.DASH.matches("aerobase.io", "test-aerobase.io"), is("test"));
assertThat(DomainMatcher.DASH.matches("aerobase.io", "a-bc-test-aerobase.io"), is("a-bc-test"));
assertThat(DomainMatcher.DASH.matches("aerobase.io", "a-bc-test-aerobase.io"), is("a-bc-test"));
}
@Test
public void testSccounts() {
assertThat(KeycloakServiceImpl.toRealm("admin", new LoggedInUser("admin"), null), is("master"));
assertThat(KeycloakServiceImpl.toRealm("admin", new LoggedInUser("test@aerobase.org"), null),
is("test-aerobase-org"));
assertThat(KeycloakServiceImpl.toRealm("admin", new LoggedInUser("test_123_123@aerobase.org"), null),
is("test-123-123-aerobase-org"));
assertThat(KeycloakServiceImpl.toRealm("admin", new LoggedInUser("test__--123@aerobase.org"), null),
is("test----123-aerobase-org"));
}
@Test
public void testStripAccounts() {
kcServiceMock.setPortalMode(true);
assertThat(kcServiceMock.stripAccountName("test1.aerobase.io"), is("test1"));
assertThat(kcServiceMock.stripAccountName("app_name.test1.aerobase.io"), is("test1"));
kcServiceMock.setPortalMode(false);
assertThat(kcServiceMock.stripAccountName("test1.aerobase.io"), is("master"));
assertThat(kcServiceMock.stripAccountName("teatapp.test1.aerobase.io"), is("master"));
kcServiceMock.setPortalMode(true);
// Performance check
for (int i = 1; i < 10000; i++) {
assertThat(kcServiceMock.stripAccountName("app_name.test" + i + ".aerobase.io"), is("test" + i));
}
}
@Test
public void testStripApplication() {
kcServiceMock.setPortalMode(true);
assertThat(kcServiceMock.stripApplicationName("test1.aerobase.io"), is("test1"));
assertThat(kcServiceMock.stripApplicationName("app_name.test1.aerobase.io"), is("app_name"));
kcServiceMock.setPortalMode(false);
assertThat(kcServiceMock.stripApplicationName("app_name.aerobase.io"), is("app_name"));
assertThat(kcServiceMock.stripApplicationName("app_name.test1.aerobase.io"), is("app_name"));
// Performance check
for (int i = 1; i < 10000; i++) {
assertThat(kcServiceMock.stripApplicationName("app_name.test" + i + ".aerobase.io"), is("app_name"));
}
}
@After
public void validate() {
validateMockitoUsage();
}
@Configuration
@Import({ ConfigurationEnvironment.class, OAuth2Configuration.class })
static class KeycloakServiceTestConfig {
private KeycloakServiceImpl mockKcService = mock(KeycloakServiceImpl.class);
@Bean
public KeycloakServiceImpl kcServiceMock() {
return mockKcService;
}
@Bean
public MockProvider mockProvider() {
return new MockProvider(mockKcService);
}
}
public static class MockProvider {
private final IKeycloakService repository;
public MockProvider(IKeycloakService repository) {
this.repository = repository;
}
public IKeycloakService get() {
return this.repository;
}
}
}
| aerobase/unifiedpush-server | service/src/test/java/org/jboss/aerogear/unifiedpush/service/spring/KeycloakServiceTest.java | Java | apache-2.0 | 6,468 |
package com.camnter.easycountdowntextureview.demo.adapter;
import android.widget.TextView;
import com.camnter.easycountdowntextureview.demo.R;
import com.camnter.easyrecyclerview.adapter.EasyRecyclerViewAdapter;
import com.camnter.easyrecyclerview.holder.EasyRecyclerViewHolder;
/**
* Description:MainAdapter
* Created by:CaMnter
* Time:2016-03-18 13:21
*/
public class MainAdapter extends EasyRecyclerViewAdapter {
@Override public int[] getItemLayouts() {
return new int[] { R.layout.item_main };
}
@Override public void onBindRecycleViewHolder(EasyRecyclerViewHolder viewHolder, int position) {
Class c = (Class) this.getList().get(position);
if (c == null) return;
TextView textView = viewHolder.findViewById(R.id.main_item_tv);
textView.setText(c.getSimpleName());
}
@Override public int getRecycleViewItemType(int position) {
return 0;
}
}
| CaMnter/EasyCountDownTextureView | samples/src/main/java/com/camnter/easycountdowntextureview/demo/adapter/MainAdapter.java | Java | apache-2.0 | 935 |
import merge from 'deepmerge';
import { grey4, lightBlack, blue1 } from '../../../../../styles/modules/variables';
import commonCss, { avatar } from '../../../common.styles';
export default merge(
commonCss,
{
row: {
paddingBottom: 20,
maxHeight: 177,
borderTop: `1px solid ${grey4}`,
},
avatar: {
...avatar(),
},
engineSelect: {
position: 'absolute',
top: 0,
left: 0,
},
primary: {
borderRight: `2px solid ${grey4}`,
},
icon: {
height: '100%',
},
title: {
'&:hover': {
cursor: 'pointer',
color: blue1,
},
},
secondary: {
flexWrap: 'wrap',
flexDirection: 'row',
justifyContent: 'space-between',
minWidth: '37%',
maxWidth: '37%',
padding: '0 20px',
paddingRight: 0,
},
description: {
fontSize: 13,
lineHeight: '20px',
color: lightBlack,
marginTop: 2,
},
logos: {
flexWrap: 'wrap',
alignContent: 'flex-start',
justifyContent: 'space-between',
width: 122,
marginRight: 15,
},
logo: {
'&:first-child': {
marginBottom: 20,
}
},
main: {
display: 'flex',
justifyContent: 'space-between',
},
}
)
| veritone/veritone-sdk | packages/veritone-widgets/src/widgets/EngineSelection/EngineListView/EngineListContainer/EngineSelectionRow/styles.js | JavaScript | apache-2.0 | 1,293 |
/*
* Copyright 1999-2011 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.bvt.sql.oracle;
import java.util.List;
import org.junit.Assert;
import com.alibaba.druid.sql.OracleTest;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
public class OracleInsertTest1 extends OracleTest {
public void test_0() throws Exception {
String sql = "INSERT INTO bonuses(employee_id)" +
" (SELECT e.employee_id FROM employees e, orders o" +
" WHERE e.employee_id = o.sales_rep_id" +
" GROUP BY e.employee_id); ";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement statemen = statementList.get(0);
print(statementList);
Assert.assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
statemen.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("bonuses")));
Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("employees")));
Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("orders")));
Assert.assertEquals(3, visitor.getTables().size());
Assert.assertEquals(3, visitor.getColumns().size());
Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("bonuses", "employee_id")));
Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("employees", "employee_id")));
Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("orders", "sales_rep_id")));
}
}
| xiaomozhang/druid | druid-1.0.9/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleInsertTest1.java | Java | apache-2.0 | 2,713 |
/* tables */
table.tablesorter {
font-family:arial;
background-color: #CDCDCD;
margin:10px 0pt 15px;
font-size: 8pt;
width: 100%;
text-align: left;
}
table.tablesorter thead tr th, table.tablesorter tfoot tr th {
background-color: #e6EEEE;
border: 1px solid #FFF;
font-size: 8pt;
padding: 4px;
}
table.tablesorter thead tr .header {
background-image: url(tablesorter/bg.gif);
background-repeat: no-repeat;
background-position: center right;
cursor: pointer;
}
table.tablesorter tbody td {
color: #3D3D3D;
padding: 4px;
background-color: #FFF;
vertical-align: top;
}
table.tablesorter tbody tr.odd td {
background-color:#F0F0F6;
}
table.tablesorter thead tr .headerSortUp {
background-image: url(tablesorter/asc.gif);
}
table.tablesorter thead tr .headerSortDown {
background-image: url(tablesorter/desc.gif);
}
table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp {
background-color: #8dbdd8;
}
| majkilde/LogFileReader | nsf/Resources/Files/tablesorter_2fstyle.css | CSS | apache-2.0 | 948 |
/*
* Copyright 2019-2021 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.fhir.tests;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import com.b2international.snowowl.core.date.Dates;
import com.b2international.snowowl.fhir.core.FhirDates;
import com.b2international.snowowl.fhir.core.model.dt.Instant;
import com.b2international.snowowl.fhir.core.model.typedproperty.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import io.restassured.path.json.JsonPath;
/**
* Custom unwrapping serializer tests to manage fields that are 'typed' e.g. on ElementDefinition.defaultValue[x].
*
* @since 7.1
*/
public class TypedPropertySerializationTest extends FhirTest {
@Test
public void stringTypedPropertyTest() throws Exception {
final class TestClass {
@JsonProperty
private String testString = "test";
@JsonUnwrapped
@JsonProperty
private TypedProperty<?> value = new StringProperty("stringValue");
}
TestClass testObject = new TestClass();
printPrettyJson(testObject);
JsonPath jsonPath = JsonPath.from(objectMapper.writeValueAsString(testObject));
assertThat(jsonPath.getString("testString"), equalTo("test"));
assertThat(jsonPath.getString("valueString"), equalTo("stringValue"));
}
@Test
public void dateTypedPropertyTest() throws Exception {
Date date = Dates.parse(TEST_DATE_STRING, FhirDates.DATE_SHORT_FORMAT);
final class TestClass {
@JsonUnwrapped
@JsonProperty
private TypedProperty<?> value = new DateProperty(date);
}
TestClass testObject = new TestClass();
JsonPath jsonPath = JsonPath.from(objectMapper.writeValueAsString(testObject));
assertThat(jsonPath.getString("valueDate"), equalTo("2018-03-23T00:00:00.000+0000"));
}
@Test
public void dateTimeTypedPropertyTest() throws Exception {
Date date = Dates.parse(TEST_DATE_STRING, FhirDates.DATE_TIME_FORMAT);
final class TestClass {
@JsonUnwrapped
@JsonProperty
private TypedProperty<?> value = new DateTimeProperty(date);
}
TestClass testObject = new TestClass();
JsonPath jsonPath = JsonPath.from(objectMapper.writeValueAsString(testObject));
assertThat(jsonPath.getString("valueDate"), equalTo(TEST_DATE_STRING));
}
@Test
public void instantTypedPropertyTest() throws Exception {
Date date = Dates.parse(TEST_DATE_STRING, FhirDates.DATE_TIME_FORMAT);
Instant instant = Instant.builder().instant(date).build();
final class TestClass {
@JsonUnwrapped
@JsonProperty
private TypedProperty<?> value = new InstantProperty(instant);
}
TestClass testObject = new TestClass();
printPrettyJson(testObject);
JsonPath jsonPath = JsonPath.from(objectMapper.writeValueAsString(testObject));
assertThat(jsonPath.getString("valueInstant"), equalTo("2018-03-23T07:49:40Z"));
}
}
| b2ihealthcare/snow-owl | fhir/com.b2international.snowowl.fhir.rest.tests/src/com/b2international/snowowl/fhir/tests/TypedPropertySerializationTest.java | Java | apache-2.0 | 3,595 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `P762` type in crate `typenum`.">
<meta name="keywords" content="rust, rustlang, rust-lang, P762">
<title>typenum::consts::P762 - Rust</title>
<link rel="stylesheet" type="text/css" href="../../normalize.css">
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc type">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>typenum</a>::<wbr><a href='index.html'>consts</a></p><script>window.sidebarCurrent = {name: 'P762', ty: 'type', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content">
<h1 class='fqn'><span class='in-band'>Type Definition <a href='../index.html'>typenum</a>::<wbr><a href='index.html'>consts</a>::<wbr><a class="type" href=''>P762</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../../src/typenum/home/jacob/nitro-game-engine/target/debug/build/typenum-cb7a8e569dce0703/out/consts.rs.html#1584' title='goto source code'>[src]</a></span></h1>
<pre class='rust typedef'>type P762 = <a class="struct" href="../../typenum/int/struct.PInt.html" title="struct typenum::int::PInt">PInt</a><<a class="type" href="../../typenum/consts/type.U762.html" title="type typenum::consts::U762">U762</a>>;</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "typenum";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html> | nitro-devs/nitro-game-engine | docs/typenum/consts/type.P762.html | HTML | apache-2.0 | 4,364 |
package com.superSaller.controller;
import java.util.Set;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.superSaller.beans.outsideSupportSys.entities.Good;
/**
* @author 邱依强
* @version 1.0
* @created 24-05-2017 8:44:39
*/
@Controller
@RequestMapping("/cashier")
public class CashierController {
public String createOrder() {
return "";
}
public String doPayment() {
return "";
}
public String importCustomer() {
return "";
}
/**
*
* @param goods
*/
public String importGoods(Set<Good> goods) {
return "";
}
public String printTickets() {
return "";
}
@RequestMapping(value = "/start", method = RequestMethod.GET)
public String startCheckout() {
return "/cashier/checkout";
}
} | ArvinSiChuan/SupperSaller | SuperSaller/src/com/superSaller/controller/CashierController.java | Java | apache-2.0 | 869 |
docker-ptoceti
==============
Docker source script to build an image for the Ptoceti project
| lathil/docker-ptoceti | README.md | Markdown | apache-2.0 | 94 |
package ru.job4j.specialty;
/**
* Profession.
*
* @author Vitaly Zubov (mailto:Zubov.VP@yandex.ru).
* @version $Id$
* @since 0.1
*/
public class Profession {
/**
* Добавления переменнной age.
*/
public int age;
/**
* Добавления переменнной name.
*/
public String name;
/**
* Добавления переменнной skill.
*/
public String skill;
/**
* Конструктор.
*/
public Profession() {
}
/**
* Конструктор.
* @param name - имя объекта
* @param age - возраст объекта
* @param skill - навык
*/
public Profession(String name, int age, String skill) {
this.name = name;
this.age = age;
this.skill = skill;
}
/**
* Конструктор.
* @param name - имя объекта
*/
public Profession(String name) {
this.name = name;
}
/**
* Геттер.
* @return age - позволяет использовать переменную age
*/
public int getAge() {
return this.age;
}
/**
* Геттер.
* @return name - позволяет использовать переменную name
*/
public String getName() {
return this.name;
}
/**
* Геттер.
* @return skill - позволяет использовать переменную skill
*/
public String getSkill() {
return this.skill;
}
} | ZubovVP/ZubovVP | chapter_002/src/main/java/ru/job4j/specialty/Profession.java | Java | apache-2.0 | 1,453 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Neodroid: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="neodroidcropped124.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Neodroid
 <span id="projectnumber">0.2.0</span>
</div>
<div id="projectbrief">Machine Learning Environment Prototyping Tool</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classdroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_camera_1_1_uber_camera_sensor.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">droid.Runtime.Prototyping.Sensors.Camera.UberCameraSensor Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classdroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_camera_1_1_uber_camera_sensor.html">droid.Runtime.Prototyping.Sensors.Camera.UberCameraSensor</a>, including all inherited members.</p>
<table class="directory">
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
| sintefneodroid/droid | docs/cvs/classdroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_camera_1_1_uber_camera_sensor-members.html | HTML | apache-2.0 | 4,019 |
#include "nit.common.h"
#define COLOR_nit__location__SourceFile___filename 0
extern const char FILE_nit__location[];
#define COLOR_nit__location__SourceFile___string 1
#define COLOR_nit__location__SourceFile___stream 2
val* standard___standard__BufferedIStream___IStream__read_all(val* self);
#define COLOR_nit__location__SourceFile___line_starts 3
val* BOX_standard__Int(long);
void standard___standard__Array___standard__abstract_collection__Sequence___91d_93d_61d(val* self, long p0, val* p1);
#define COLOR_nit__location__Location___file 0
#define COLOR_nit__location__Location___line_start 1
#define COLOR_nit__location__Location___line_end 2
#define COLOR_nit__location__Location___column_start 3
#define COLOR_nit__location__Location___column_end 4
extern const struct type type_standard__Int;
extern const char FILE_standard__kernel[];
val* standard___standard__Array___standard__abstract_collection__SequenceRead___91d_93d(val* self, long p0);
#define COLOR_nit__location__Location___text_cache 5
#define COLOR_standard__kernel__Object___61d_61d 2
long nit___nit__Location___pstart(val* self);
long nit___nit__Location___pend(val* self);
#define COLOR_standard__string__Text__substring 48
extern const struct type type_nit__Location;
short int nit___nit__Location___standard__kernel__Object___61d_61d(val* self, val* p0);
val* standard___standard__NativeString___to_s_with_length(char* self, long p0);
#define COLOR_standard__string__Text__length 47
#define COLOR_standard__string__String___43d 82
val* NEW_standard__Array(const struct type* type);
extern const struct type type_standard__Array__standard__Object;
val* NEW_standard__NativeArray(int length, const struct type* type);
extern const struct type type_standard__NativeArray__standard__Object;
#define COLOR_standard__array__Array__with_native 73
#define COLOR_standard__string__Object__to_s 9
#define COLOR_standard__kernel__Comparable__OTHER 0
short int nit___nit__Location___located_in(val* self, val* p0);
val* BOX_standard__Char(char);
#define COLOR_standard__string__Text__chars 46
#define COLOR_standard__abstract_collection__SequenceRead___91d_93d 45
extern const struct class class_standard__Char;
val* NEW_standard__FlatBuffer(const struct type* type);
extern const struct type type_standard__FlatBuffer;
#define COLOR_standard___standard__FlatBuffer___standard__kernel__Object__init 96
void standard___standard__FlatBuffer___Buffer__add(val* self, char p0);
long standard___standard__Int___Discrete__successor(long self, long p0);
#define COLOR_nit___nit__Location___standard__kernel__Object__init 54
| colinvidal/nit | c_src/nit__location.sep.0.h | C | apache-2.0 | 2,581 |
'''
Copyright 2013 George Caley
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import codecs
import os
import re
import sqlite3
# woo regular expressions
PREREQS_RE = re.compile(r"Pre-?req(?:uisites?)?:(.*?)(?:</p>|;)")
EXCLUSIONS_RE = re.compile(r"((?:Excluded|Exclusion|Exclusions|(?:and )?Excludes)[: ](.*?))(?:</p>|<br />)", re.IGNORECASE)
COREQS_RE = re.compile(r"Co-?requisite:(.*?)</p>", re.IGNORECASE)
NAME_RE = re.compile(r"<title>UNSW Handbook Course - (.*?) - [A-Z]{4}[0-9]{4}</title>", re.DOTALL)
DESC_RE = re.compile(r"<!-- Start Course Description -->(.*?)<!-- End Course description -->", re.DOTALL | re.IGNORECASE)
GENED_RE = re.compile(r"Available for General Education:")
OUTLINE_RE = re.compile(r"Course Outline:.*?<a .*?href=[\"'](.*?)[\"']")
UOC_RE = re.compile(r"Units of Credit:.*?([0-9]+)")
COURSE_RE = re.compile(r"[A-Z]{4}[0-9]{4}", re.IGNORECASE)
BR_RE = re.compile(r"<br ?/?>", re.IGNORECASE)
TAG_RE = re.compile(r"</?.*?>")
TYPE_PREREQUISITE = "prerequisite"
TYPE_COREQUISITE = "corequisite"
TYPE_EXCLUSION = "exclusion"
DATABASE_FILENAME = "courses.db"
COURSE_DIR = "courses"
if os.path.exists(DATABASE_FILENAME):
print "Deleting existing database"
os.unlink(DATABASE_FILENAME)
print "Creating new database"
conn = sqlite3.connect(DATABASE_FILENAME)
cur = conn.cursor()
print "Creating tables"
cur.execute("CREATE TABLE courses (code text primary key, name text, description text, prerequisites text, corequisites text, exclusions text, gened integer, outline text, uoc integer)")
cur.execute("CREATE TABLE relationships (source text, destination text, type text)")
print "Loading course list"
print
filenames = os.listdir(COURSE_DIR)
i = 0
for filename in filenames:
i += 1
code = filename.rstrip(".html")
print "Reading %s (%d/%d)" % (code, i, len(filenames))
# open with unicode support
f = codecs.open("%s/%s" % (COURSE_DIR, filename), encoding="utf-8", mode="r")
data = f.read()
f.close()
# strip 's and <strong> tags
data = data.replace(" ", " ")
data = data.replace("<strong>", "")
data = data.replace("</strong>", "")
# find name
match = re.search(NAME_RE, data)
if match:
name = match.group(1).strip().replace("\n", "")
print "Found name:", name
else:
name = None
print "Couldn't find name"
print "Fatal error!"
quit()
# find exclusions. all of them.
exclusions = ""
exclusions_list = []
while True:
match = re.search(EXCLUSIONS_RE, data)
if match:
exclusions = match.group(2).strip()
print "Found exclusions:", exclusions
data = data.replace(match.group(1), "")
exclusions_list = re.findall(COURSE_RE, exclusions)
print "Exclusions list:", exclusions_list
else:
#exclusions = None
#exclusions_list = []
#print "Couldn't find exclusions"
break
# find corequisites
match = re.search(COREQS_RE, data)
if match:
coreqs = match.group(1).strip()
print "Found corequisites:", coreqs
data = data.replace(match.group(0), "")
coreqs_list = map(unicode.upper, re.findall(COURSE_RE, coreqs))
print "Corequisites list:", coreqs_list
else:
coreqs = None
coreqs_list = []
print "Couldn't find corequisites"
# find prerequisites
match = re.search(PREREQS_RE, data)
if match:
prereqs = match.group(1).strip()
print "Found prerequisites:", prereqs
data = data.replace(match.group(0), "")
prereqs_list = map(unicode.upper, re.findall(COURSE_RE, prereqs))
print "Prerequisites list:", prereqs_list
else:
prereqs = None
prereqs_list = []
print "Couldn't find prerequisites"
# find description
match = re.search(DESC_RE, data)
if match:
desc = match.group(1).strip()
# change <br>'s
#desc = re.sub(BR_RE, "\n", desc)
# strip tags
#desc = re.sub(TAG_RE, "", desc)
#print "Found description:", desc
print "Found description"
else:
desc = None
print "Couldn't find description"
# find general education statement
match = re.search(GENED_RE, data)
if match:
gened = 1
else:
gened = 0
# find course outline
match = re.search(OUTLINE_RE, data)
if match:
outline = match.group(1).strip()
print "Found course outline:", outline
else:
outline = None
print "Couldn't find course outline"
# find uoc
match = re.search(UOC_RE, data)
if match:
uoc = match.group(1).strip()
try:
uoc = int(uoc)
print "Found UoC:", uoc
except:
print "UoC was not an integer: '%s'" % uoc
uoc = None
else:
uoc = None
print "Couldn't find UoC"
print "Writing to database"
cur.execute("INSERT INTO courses (code, name, description, prerequisites, corequisites, exclusions, gened, outline, uoc) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (code, name, desc, prereqs, coreqs, exclusions, gened, outline, uoc))
for prereq in prereqs_list:
cur.execute("INSERT INTO relationships (source, destination, type) VALUES (?, ?, ?)", (code, prereq, TYPE_PREREQUISITE))
for coreq in coreqs_list:
cur.execute("INSERT INTO relationships (source, destination, type) VALUES (?, ?, ?)", (code, coreq, TYPE_COREQUISITE))
for exclusion in exclusions_list:
cur.execute("INSERT INTO relationships (source, destination, type) VALUES (?, ?, ?)", (code, exclusion, TYPE_EXCLUSION))
print
conn.commit()
conn.close()
| spake/pathways | binder.py | Python | apache-2.0 | 6,253 |
package com.cloud.agent;
import com.cloud.legacymodel.communication.answer.AgentControlAnswer;
import com.cloud.legacymodel.communication.answer.Answer;
import com.cloud.legacymodel.communication.command.Command;
import com.cloud.legacymodel.communication.command.agentcontrol.AgentControlCommand;
import com.cloud.legacymodel.communication.command.startup.StartupCommand;
import com.cloud.legacymodel.dc.Host;
import com.cloud.legacymodel.dc.HostStatus;
import com.cloud.legacymodel.exceptions.ConnectionException;
/**
* There are several types of events that the AgentManager forwards
* <p>
* 1. Agent Connect & Disconnect
* 2. Commands sent by the agent.
* 3. Answers sent by the agent.
*/
public interface Listener {
/**
* @param agentId id of the agent
* @param seq sequence number return by the send() method.
* @param answers answers to the commands.
* @return true if processed. false if not.
*/
boolean processAnswers(long agentId, long seq, Answer[] answers);
/**
* This method is called by the AgentManager when an agent sent
* a command to the server. In order to process these commands,
* the Listener must be registered for host commands.
*
* @param agentId id of the agent.
* @param seq sequence number of the command sent.
* @param commands commands that were sent.
* @return true if you processed the commands. false if not.
*/
boolean processCommands(long agentId, long seq, Command[] commands);
/**
* process control command sent from agent under its management
*
* @param agentId
* @param cmd
* @return
*/
AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd);
/**
* This method is called by AgentManager when an agent made a
* connection to this server if the listener has
* been registered for host events.
*
* @param cmd command sent by the agent to the server on startup.
* @param forRebalance TODO
* @param agentId id of the agent
* @throws ConnectionException if host has problems and needs to put into maintenance state.
*/
void processConnect(Host host, StartupCommand[] cmd, boolean forRebalance) throws ConnectionException;
/**
* This method is called by AgentManager when an agent disconnects
* from this server if the listener has been registered for host events.
* <p>
* If the Listener is passed to the send() method, this method is
* also called by AgentManager if the agent disconnected.
*
* @param agentId id of the agent
* @param state the current state of the agent.
*/
boolean processDisconnect(long agentId, HostStatus state);
/**
* If this Listener is passed to the send() method, this method
* is called by AgentManager after processing an answer
* from the agent. Returning true means you're expecting more
* answers from the agent using the same sequence number.
*
* @return true if expecting more answers using the same sequence number.
*/
boolean isRecurring();
/**
* If the Listener is passed to the send() method, this method is
* called to determine how long to wait for the reply. The value
* is in seconds. -1 indicates to wait forever. 0 indicates to
* use the default timeout. If the timeout is
* reached, processTimeout on this same Listener is called.
*
* @return timeout in seconds before processTimeout is called.
*/
int getTimeout();
/**
* If the Listener is passed to the send() method, this method is
* called by the AgentManager to process a command timeout.
*
* @param agentId id of the agent
* @param seq sequence number returned by the send().
* @return true if processed; false if not.
*/
boolean processTimeout(long agentId, long seq);
}
| MissionCriticalCloud/cosmic | cosmic-core/engine/components-api/src/main/java/com/cloud/agent/Listener.java | Java | apache-2.0 | 3,949 |
# Lecania disceptans (Nyl.) Lynge SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Lecania/Lecania disceptans/README.md | Markdown | apache-2.0 | 164 |
/*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.graph.TopologicalSort;
import com.facebook.buck.java.JavacInMemoryStep;
import com.facebook.buck.java.JavacOptions;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractDependencyVisitor;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.DependencyGraph;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.WriteFileStep;
import com.facebook.buck.util.BuckConstant;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Creates the {@link Step}s needed to generate an uber {@code R.java} file.
* <p>
* Buck builds two types of {@code R.java} files: temporary ones and uber ones. A temporary
* {@code R.java} file's values are garbage and correspond to a single Android libraries. An uber
* {@code R.java} file represents the transitive closure of Android libraries that are being
* packaged into an APK and has the real values for that APK.
*/
public class UberRDotJavaUtil {
private static final ImmutableSet<BuildRuleType> TRAVERSABLE_TYPES = ImmutableSet.of(
BuildRuleType.ANDROID_BINARY,
BuildRuleType.ANDROID_INSTRUMENTATION_APK,
BuildRuleType.ANDROID_LIBRARY,
BuildRuleType.ANDROID_RESOURCE,
BuildRuleType.APK_GENRULE,
BuildRuleType.JAVA_LIBRARY,
BuildRuleType.JAVA_TEST,
BuildRuleType.ROBOLECTRIC_TEST
);
/** Utility class: do not instantiate. */
private UberRDotJavaUtil() {}
/**
* Adds the commands to generate and compile the {@code R.java} files. The {@code .class} files
* will be written to {@link #getPathToCompiledRDotJavaFiles(BuildTarget)}.
*/
public static void generateRDotJavaFiles(
Set<String> resDirectories,
Set<String> rDotJavaPackages,
BuildTarget buildTarget,
ImmutableList.Builder<Step> commands) {
// Create the path where the R.java files will be generated.
String rDotJavaSrc = String.format("%s/%s__%s_uber_rdotjava_src__",
BuckConstant.BIN_DIR,
buildTarget.getBasePathWithSlash(),
buildTarget.getShortName());
commands.add(new MakeCleanDirectoryStep(rDotJavaSrc));
// Generate the R.java files.
GenRDotJavaStep genRDotJava = new GenRDotJavaStep(
resDirectories,
rDotJavaSrc,
rDotJavaPackages.iterator().next(),
/* isTempRDotJava */ false,
rDotJavaPackages);
commands.add(genRDotJava);
// Create the path where the R.java files will be compiled.
String rDotJavaBin = getPathToCompiledRDotJavaFiles(buildTarget);
commands.add(new MakeCleanDirectoryStep(rDotJavaBin));
// Compile the R.java files.
Set<String> javaSourceFilePaths = Sets.newHashSet();
for (String rDotJavaPackage : rDotJavaPackages) {
String path = rDotJavaSrc + "/" + rDotJavaPackage.replace('.', '/') + "/R.java";
javaSourceFilePaths.add(path);
}
JavacInMemoryStep javac = createJavacInMemoryCommandForRDotJavaFiles(
javaSourceFilePaths, rDotJavaBin);
commands.add(javac);
}
public static String getPathToCompiledRDotJavaFiles(BuildTarget buildTarget) {
return String.format("%s/%s__%s_uber_rdotjava_bin__",
BuckConstant.BIN_DIR,
buildTarget.getBasePathWithSlash(),
buildTarget.getShortName());
}
/**
* Finds the transitive set of {@code rule}'s {@link AndroidResourceRule} dependencies with
* non-null {@code res} directories, which can also include {@code rule} itself.
* This set will be returned as an {@link ImmutableList} with the rules topologically sorted as
* determined by {@code graph}. Rules will be ordered from least dependent to most dependent.
*/
public static ImmutableList<HasAndroidResourceDeps> getAndroidResourceDeps(
BuildRule rule,
DependencyGraph graph) {
final Set<HasAndroidResourceDeps> allAndroidResourceRules = findAllAndroidResourceDeps(rule);
// Now that we have the transitive set of AndroidResourceRules, we need to return them in
// topologically sorted order. This is critical because the order in which -S flags are passed
// to aapt is significant and must be consistent.
Predicate<BuildRule> inclusionPredicate = new Predicate<BuildRule>() {
@Override
public boolean apply(BuildRule rule) {
return allAndroidResourceRules.contains(rule);
}
};
ImmutableList<BuildRule> sortedAndroidResourceRules = TopologicalSort.sort(graph,
inclusionPredicate);
// TopologicalSort.sort() returns rules in leaves-first order, which is the opposite of what we
// want, so we must reverse the list and cast BuildRules to AndroidResourceRules.
return ImmutableList.copyOf(
Iterables.transform(
sortedAndroidResourceRules.reverse(),
CAST_TO_ANDROID_RESOURCE_RULE)
);
}
private static Function<BuildRule, HasAndroidResourceDeps> CAST_TO_ANDROID_RESOURCE_RULE =
new Function<BuildRule, HasAndroidResourceDeps>() {
@Override
public HasAndroidResourceDeps apply(BuildRule rule) {
return (HasAndroidResourceDeps)rule;
}
};
private static ImmutableSet<HasAndroidResourceDeps> findAllAndroidResourceDeps(BuildRule buildRule) {
final ImmutableSet.Builder<HasAndroidResourceDeps> androidResources = ImmutableSet.builder();
AbstractDependencyVisitor visitor = new AbstractDependencyVisitor(buildRule) {
@Override
public boolean visit(BuildRule rule) {
if (rule instanceof HasAndroidResourceDeps) {
HasAndroidResourceDeps androidResourceRule = (HasAndroidResourceDeps)rule;
if (androidResourceRule.getRes() != null) {
androidResources.add(androidResourceRule);
}
}
// Only certain types of rules should be considered as part of this traversal.
BuildRuleType type = rule.getType();
return TRAVERSABLE_TYPES.contains(type);
}
};
visitor.start();
return androidResources.build();
}
/**
* Aggregate information about a list of {@link AndroidResourceRule}s.
*/
public static class AndroidResourceDetails {
/**
* The {@code res} directories associated with the {@link AndroidResourceRule}s.
* <p>
* An {@link Iterator} over this collection will reflect the order of the original list of
* {@link AndroidResourceRule}s that were specified.
*/
public final ImmutableSet<String> resDirectories;
public final ImmutableSet<String> rDotJavaPackages;
@Beta
public AndroidResourceDetails(ImmutableList<HasAndroidResourceDeps> androidResourceDeps) {
ImmutableSet.Builder<String> resDirectoryBuilder = ImmutableSet.builder();
ImmutableSet.Builder<String> rDotJavaPackageBuilder = ImmutableSet.builder();
for (HasAndroidResourceDeps androidResource : androidResourceDeps) {
String resDirectory = androidResource.getRes();
if (resDirectory != null) {
resDirectoryBuilder.add(resDirectory);
rDotJavaPackageBuilder.add(androidResource.getRDotJavaPackage());
}
}
resDirectories = resDirectoryBuilder.build();
rDotJavaPackages = rDotJavaPackageBuilder.build();
}
}
public static void createDummyRDotJavaFiles(
ImmutableList<HasAndroidResourceDeps> androidResourceDeps,
BuildTarget buildTarget,
ImmutableList.Builder<Step> commands) {
// Clear out the folder for the .java files.
String rDotJavaSrcFolder = getRDotJavaSrcFolder(buildTarget);
commands.add(new MakeCleanDirectoryStep(rDotJavaSrcFolder));
// Generate the .java files and record where they will be written in javaSourceFilePaths.
Set<String> javaSourceFilePaths = Sets.newHashSet();
if (androidResourceDeps.isEmpty()) {
// In this case, the user is likely running a Robolectric test that does not happen to
// depend on any resources. However, if Robolectric doesn't find an R.java file, it flips
// out, so we have to create one, anyway.
// TODO(mbolin): Stop hardcoding com.facebook. This should match the package in the
// associated TestAndroidManifest.xml file.
String rDotJavaPackage = "com.facebook";
String javaCode = MergeAndroidResourcesStep.generateJavaCodeForPackageWithoutResources(
rDotJavaPackage);
commands.add(new MakeCleanDirectoryStep(rDotJavaSrcFolder + "/com/facebook"));
String rDotJavaFile = rDotJavaSrcFolder + "/com/facebook/R.java";
commands.add(new WriteFileStep(javaCode, rDotJavaFile));
javaSourceFilePaths.add(rDotJavaFile);
} else {
Map<String, String> symbolsFileToRDotJavaPackage = Maps.newHashMap();
for (HasAndroidResourceDeps res : androidResourceDeps) {
String rDotJavaPackage = res.getRDotJavaPackage();
symbolsFileToRDotJavaPackage.put(res.getPathToTextSymbolsFile(), rDotJavaPackage);
String rDotJavaFilePath = MergeAndroidResourcesStep.getOutputFilePath(
rDotJavaSrcFolder, rDotJavaPackage);
javaSourceFilePaths.add(rDotJavaFilePath);
}
commands.add(new MergeAndroidResourcesStep(symbolsFileToRDotJavaPackage,
rDotJavaSrcFolder));
}
// Clear out the directory where the .class files will be generated.
String rDotJavaClassesDirectory = getRDotJavaBinFolder(buildTarget);
commands.add(new MakeCleanDirectoryStep(rDotJavaClassesDirectory));
// Compile the .java files.
JavacInMemoryStep javac = createJavacInMemoryCommandForRDotJavaFiles(
javaSourceFilePaths, rDotJavaClassesDirectory);
commands.add(javac);
}
static String getRDotJavaSrcFolder(BuildTarget buildTarget) {
return String.format("%s/%s__%s_rdotjava_src__",
BuckConstant.BIN_DIR,
buildTarget.getBasePathWithSlash(),
buildTarget.getShortName());
}
public static String getRDotJavaBinFolder(BuildTarget buildTarget) {
return String.format("%s/%s__%s_rdotjava_bin__",
BuckConstant.BIN_DIR,
buildTarget.getBasePathWithSlash(),
buildTarget.getShortName());
}
static JavacInMemoryStep createJavacInMemoryCommandForRDotJavaFiles(
Set<String> javaSourceFilePaths, String outputDirectory) {
ImmutableSet<String> classpathEntries = ImmutableSet.of();
return new JavacInMemoryStep(
outputDirectory,
javaSourceFilePaths,
classpathEntries,
JavacOptions.DEFAULTS,
/* pathToOutputAbiFile */ Optional.<String>absent());
}
}
| denizt/buck | src/com/facebook/buck/android/UberRDotJavaUtil.java | Java | apache-2.0 | 11,628 |
package bader;
public abstract class Mammal extends Animal {/*är också animal ärver från Animalklassen*/
private int gestationTime;
public Mammal(String latinName, int gestationTime) {
super (latinName);
// TODO Auto-generated constructor stub
}
public int getGestationTime(){
return this.gestationTime;
}
}
| Kaoscillator/KDA405_Marcus_B | KD405A_Bader_M_uppgift4B/src/bader/Mammal.java | Java | apache-2.0 | 331 |
# Sagittaria trifolia f. longiloba FORM
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Alismataceae/Sagittaria/Sagittaria trifolia/ Syn. Sagittaria trifolia longiloba/README.md | Markdown | apache-2.0 | 186 |
<?php
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace Vpc\Request\V20160428;
class DeleteCustomerGatewayRequest extends \RpcAcsRequest
{
function __construct()
{
parent::__construct("Vpc", "2016-04-28", "DeleteCustomerGateway", "vpc", "openAPI");
$this->setMethod("POST");
}
private $resourceOwnerId;
private $resourceOwnerAccount;
private $clientToken;
private $ownerAccount;
private $ownerId;
private $customerGatewayId;
public function getResourceOwnerId() {
return $this->resourceOwnerId;
}
public function setResourceOwnerId($resourceOwnerId) {
$this->resourceOwnerId = $resourceOwnerId;
$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
}
public function getResourceOwnerAccount() {
return $this->resourceOwnerAccount;
}
public function setResourceOwnerAccount($resourceOwnerAccount) {
$this->resourceOwnerAccount = $resourceOwnerAccount;
$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
}
public function getClientToken() {
return $this->clientToken;
}
public function setClientToken($clientToken) {
$this->clientToken = $clientToken;
$this->queryParameters["ClientToken"]=$clientToken;
}
public function getOwnerAccount() {
return $this->ownerAccount;
}
public function setOwnerAccount($ownerAccount) {
$this->ownerAccount = $ownerAccount;
$this->queryParameters["OwnerAccount"]=$ownerAccount;
}
public function getOwnerId() {
return $this->ownerId;
}
public function setOwnerId($ownerId) {
$this->ownerId = $ownerId;
$this->queryParameters["OwnerId"]=$ownerId;
}
public function getCustomerGatewayId() {
return $this->customerGatewayId;
}
public function setCustomerGatewayId($customerGatewayId) {
$this->customerGatewayId = $customerGatewayId;
$this->queryParameters["CustomerGatewayId"]=$customerGatewayId;
}
} | houdunwang/hdphp | vendor/houdunwang/aliyun/aliyun-openapi-php-sdk-master/aliyun-php-sdk-vpc/Vpc/Request/V20160428/DeleteCustomerGatewayRequest.php | PHP | apache-2.0 | 2,692 |
// ============================================================================
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataprep.api.service;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.talend.dataprep.dataset.DatasetConfiguration.Service.Provider.CATALOG;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.talend.dataprep.api.service.version.DatasetVersionSupplier;
import org.talend.dataprep.api.service.version.VersionsSupplier;
import org.talend.dataprep.info.BuildDetails;
import org.talend.dataprep.info.Version;
import org.talend.dataprep.metrics.Timed;
import org.talend.dataprep.security.PublicAPI;
import io.swagger.annotations.ApiOperation;
@RestController
public class VersionServiceAPI extends APIService {
@Value("${dataprep.display.version}")
private String applicationVersion;
@Autowired
private Environment environment;
@Autowired
private List<VersionsSupplier> versionsSuppliers;
/**
* Returns all the versions of the different services (api, dataset, preparation and transformation) and the global
* application version.
*
* @return an array of service versions
*/
@RequestMapping(value = "/api/version", method = GET)
@ApiOperation(value = "Get the version of all services (including underlying low level services)",
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@PublicAPI
public BuildDetails allVersions() {
Stream<VersionsSupplier> supplierStream = versionsSuppliers.stream();
final String datasetProvider = environment.getProperty("dataset.service.provider");
if (CATALOG.name().equalsIgnoreCase(datasetProvider)) {
supplierStream =
supplierStream.filter(versionsSupplier -> !(versionsSupplier instanceof DatasetVersionSupplier));
}
final Version[] versions = supplierStream //
.map(VersionsSupplier::getVersions)
.flatMap(List::stream)
.filter(Objects::nonNull)
.toArray(Version[]::new);
return new BuildDetails(applicationVersion, versions);
}
}
| Talend/data-prep | dataprep-api/src/main/java/org/talend/dataprep/api/service/VersionServiceAPI.java | Java | apache-2.0 | 2,942 |
/*
* Copyright (c) 2014-2020 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monix.execution
import monix.execution.annotations.{UnsafeBecauseImpure, UnsafeProtocol}
import monix.execution.atomic.PaddingStrategy
import monix.execution.atomic.PaddingStrategy.NoPadding
import monix.execution.internal.GenericSemaphore.Listener
import monix.execution.internal.GenericSemaphore
import monix.execution.schedulers.TrampolineExecutionContext.immediate
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.control.NonFatal
/** The `AsyncSemaphore` is an asynchronous semaphore implementation that
* limits the parallelism on `Future` execution.
*
* The following example instantiates a semaphore with a
* maximum parallelism of 10:
*
* {{{
* val semaphore = AsyncSemaphore(maxParallelism = 10)
*
* def makeRequest(r: HttpRequest): Future[HttpResponse] = ???
*
* // For such a task no more than 10 requests
* // are allowed to be executed in parallel.
* val future = semaphore.greenLight(() => makeRequest(???))
* }}}
*/
final class AsyncSemaphore private (provisioned: Long, ps: PaddingStrategy)
extends GenericSemaphore[Cancelable](provisioned, ps) {
require(provisioned >= 0, "provisioned >= 0")
import AsyncSemaphore.executionContext
protected def emptyCancelable: Cancelable =
Cancelable.empty
protected def makeCancelable(f: (Listener[Unit]) => Unit, p: Listener[Unit]): Cancelable =
new Cancelable { def cancel() = f(p) }
/** Returns the number of permits currently available. Always non-negative.
*
* The protocol is unsafe, the semaphore is used in concurrent settings
* and thus the value returned isn't stable or reliable. Use with care.
*/
@UnsafeProtocol
@UnsafeBecauseImpure
def available(): Long = unsafeAvailable()
/** Obtains a snapshot of the current count. Can be negative.
*
* Like [[available]] when permits are available but returns the
* number of permits callers are waiting for when there are no permits
* available.
*/
@UnsafeProtocol
@UnsafeBecauseImpure
def count(): Long = unsafeCount()
/** Returns a new future, ensuring that the given source
* acquires an available permit from the semaphore before
* it is executed.
*
* The returned future also takes care of resource handling,
* releasing its permit after being complete.
*
* @param f is a function returning the `Future` instance we
* want to evaluate after we get the permit from the
* semaphore
*/
@UnsafeBecauseImpure
def withPermit[A](f: () => Future[A]): CancelableFuture[A] =
withPermitN(1)(f)
/** Returns a new future, ensuring that the given source
* acquires `n` available permits from the semaphore before
* it is executed.
*
* The returned future also takes care of resource handling,
* releasing its permits after being complete.
*
* @param n is the number of permits required for the given
* function to be executed
*
* @param f is a function returning the `Future` instance we
* want to evaluate after we get the permit from the
* semaphore
*/
@UnsafeBecauseImpure
def withPermitN[A](n: Long)(f: () => Future[A]): CancelableFuture[A] =
acquireN(n).flatMap { _ =>
val result =
try f()
catch { case NonFatal(e) => Future.failed(e) }
FutureUtils.transform[A, A](result, r => { releaseN(n); r })
}
/** Acquires a single permit. Alias for `[[acquireN]](1)`.
*
* @see [[withPermit]], the preferred way to acquire and release
* @see [[acquireN]] for a version that can acquire multiple permits
*/
@UnsafeBecauseImpure
def acquire(): CancelableFuture[Unit] = acquireN(1)
/** Acquires `n` permits.
*
* The returned effect semantically blocks until all requested permits are
* available. Note that acquires are satisfied in strict FIFO order, so given
* an `AsyncSemaphore` with 2 permits available, an `acquireN(3)` will
* always be satisfied before a later call to `acquireN(1)`.
*
* @see [[withPermit]], the preferred way to acquire and release
* @see [[acquire]] for a version acquires a single permit
*
* @param n number of permits to acquire - must be >= 0
*
* @return a future that will complete when the acquisition has succeeded
* or that can be cancelled, removing the listener from the queue
* (to prevent memory leaks in race conditions)
*/
@UnsafeBecauseImpure
def acquireN(n: Long): CancelableFuture[Unit] = {
if (unsafeTryAcquireN(n)) {
CancelableFuture.unit
} else {
val p = Promise[Unit]()
unsafeAcquireN(n, Callback.fromPromise(p)) match {
case Cancelable.empty => CancelableFuture.unit
case c => CancelableFuture(p.future, c)
}
}
}
/** Alias for `[[tryAcquireN]](1)`.
*
* The protocol is unsafe, because with the "try*" methods the user needs a
* firm grasp of what race conditions are and how they manifest and usage of
* such methods can lead to very fragile logic.
*
* @see [[tryAcquireN]] for the version that can acquire multiple permits
* @see [[acquire]] for the version that can wait for acquisition
* @see [[withPermit]] the preferred way to acquire and release
*/
@UnsafeProtocol
@UnsafeBecauseImpure
def tryAcquire(): Boolean = tryAcquireN(1)
/** Acquires `n` permits now and returns `true`, or returns `false`
* immediately. Error if `n < 0`.
*
* The protocol is unsafe, because with the "try*" methods the user needs a
* firm grasp of what race conditions are and how they manifest and usage of
* such methods can lead to very fragile logic.
*
* @see [[tryAcquire]] for the alias that acquires a single permit
* @see [[acquireN]] for the version that can wait for acquisition
* @see [[withPermit]], the preferred way to acquire and release
*
* @param n number of permits to acquire - must be >= 0
*/
@UnsafeProtocol
@UnsafeBecauseImpure
def tryAcquireN(n: Long): Boolean = unsafeTryAcquireN(n)
/** Releases a permit, returning it to the pool.
*
* If there are consumers waiting on permits being available,
* then the first in the queue will be selected and given
* a permit immediately.
*
* @see [[withPermit]], the preferred way to acquire and release
*/
@UnsafeBecauseImpure
def release(): Unit = releaseN(1)
/** Releases `n` permits, potentially unblocking up to `n`
* outstanding acquires.
*
* @see [[withPermit]], the preferred way to acquire and release
*
* @param n number of permits to release - must be >= 0
*/
@UnsafeBecauseImpure
def releaseN(n: Long): Unit = unsafeReleaseN(n)
/** Returns a future that will be complete when the specified
* number of permits are available.
*
* The protocol is unsafe because by the time the returned
* future completes, some other process might have already
* acquired the available permits and thus usage of `awaitAvailable`
* can lead to fragile concurrent logic. Use with care.
*
* Can be useful for termination logic, for example to execute
* a piece of logic once all available permits have been released.
*
* @param n is the number of permits waited on
*/
@UnsafeProtocol
@UnsafeBecauseImpure
def awaitAvailable(n: Long): CancelableFuture[Unit] = {
val p = Promise[Unit]()
unsafeAwaitAvailable(n, Callback.fromPromise(p)) match {
case Cancelable.empty => CancelableFuture.unit
case c => CancelableFuture(p.future, c)
}
}
}
object AsyncSemaphore {
/** Builder for [[AsyncSemaphore]].
*
* @param provisioned is the number of permits initially available
*
* @param ps is an optional padding strategy for avoiding the
* "false sharing problem", a common JVM effect when multiple threads
* read and write in shared variables
*/
def apply(provisioned: Long, ps: PaddingStrategy = NoPadding): AsyncSemaphore =
new AsyncSemaphore(provisioned, ps)
/** Used internally for flatMapping futures. */
private implicit def executionContext: ExecutionContext =
immediate
}
| alexandru/monifu | monix-execution/shared/src/main/scala/monix/execution/AsyncSemaphore.scala | Scala | apache-2.0 | 8,921 |
//
// AppDelegate.h
// Droider
//
// Created by Adam Jensen on 9/25/13.
// Copyright (c) 2013 Adam Jensen. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate, NSMenuDelegate> {
NSOperationQueue *queue;
NSStatusItem *statusItem;
}
- (void)deviceListRefreshed:(NSArray *)deviceList;
- (void)menuWillOpen:(NSMenu *)menu;
+ (id)shared;
@property (strong, nonatomic) IBOutlet NSMenu *statusMenu;
@property (strong, nonatomic) NSMutableDictionary *devices;
@end
| acj/droider | Droider/AppDelegate.h | C | apache-2.0 | 533 |
# integration-test-driver | hm1rafael/integration-test-driver | README.md | Markdown | apache-2.0 | 25 |
/*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.data2.datafabric.dataset.service;
import co.cask.cdap.api.dataset.DatasetSpecification;
import co.cask.cdap.common.DatasetAlreadyExistsException;
import co.cask.cdap.common.DatasetTypeNotFoundException;
import co.cask.cdap.common.HandlerException;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.data2.datafabric.dataset.service.executor.DatasetAdminOpResponse;
import co.cask.cdap.data2.transaction.queue.QueueConstants;
import co.cask.cdap.proto.DatasetInstanceConfiguration;
import co.cask.cdap.proto.DatasetMeta;
import co.cask.cdap.proto.DatasetSpecificationSummary;
import co.cask.cdap.proto.Id;
import co.cask.http.AbstractHttpHandler;
import co.cask.http.HttpResponder;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.inject.Inject;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import javax.annotation.Nullable;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
/**
* Handles dataset instance management calls.
*/
// todo: do we want to make it authenticated? or do we treat it always as "internal" piece?
@Path(Constants.Gateway.API_VERSION_3 + "/namespaces/{namespace-id}")
public class DatasetInstanceHandler extends AbstractHttpHandler {
private static final Logger LOG = LoggerFactory.getLogger(DatasetInstanceHandler.class);
private static final Gson GSON = new Gson();
private final DatasetInstanceService instanceService;
@Inject
public DatasetInstanceHandler(DatasetInstanceService instanceService) {
this.instanceService = instanceService;
}
@GET
@Path("/data/datasets/")
public void list(HttpRequest request, HttpResponder responder,
@PathParam("namespace-id") String namespaceId) throws Exception {
responder.sendJson(HttpResponseStatus.OK, spec2Summary(instanceService.list(Id.Namespace.from(namespaceId))));
}
/**
* Gets the {@link DatasetMeta} for a dataset instance.
*
* @param namespaceId namespace of the dataset instance
* @param name name of the dataset instance
* @param owners a list of owners of the dataset instance, in the form @{code <type>::<id>}
* (e.g. "program::namespace:default/application:PurchaseHistory/program:flow:PurchaseFlow")
* @throws Exception if the dataset instance was not found
*/
@GET
@Path("/data/datasets/{name}")
public void get(HttpRequest request, HttpResponder responder,
@PathParam("namespace-id") String namespaceId,
@PathParam("name") String name,
@QueryParam("owner") List<String> owners) throws Exception {
Id.DatasetInstance instance = Id.DatasetInstance.from(namespaceId, name);
responder.sendJson(HttpResponseStatus.OK,
instanceService.get(instance, strings2Ids(owners)),
DatasetMeta.class, GSON);
}
/**
* Creates a new dataset instance.
*
* @param namespaceId namespace of the new dataset instance
* @param name name of the new dataset instance
*/
@PUT
@Path("/data/datasets/{name}")
public void create(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId,
@PathParam("name") String name) throws Exception {
DatasetInstanceConfiguration creationProperties = getInstanceConfiguration(request);
Id.Namespace namespace = Id.Namespace.from(namespaceId);
LOG.info("Creating dataset {}.{}, type name: {}, typeAndProps: {}",
namespaceId, name, creationProperties.getTypeName(), creationProperties.getProperties());
try {
instanceService.create(namespace, name, creationProperties);
responder.sendStatus(HttpResponseStatus.OK);
} catch (DatasetAlreadyExistsException e) {
responder.sendString(HttpResponseStatus.CONFLICT, e.getMessage());
} catch (DatasetTypeNotFoundException e) {
responder.sendString(HttpResponseStatus.NOT_FOUND, e.getMessage());
} catch (HandlerException e) {
responder.sendString(e.getFailureStatus(), e.getMessage());
}
}
/**
* Updates an existing dataset specification properties.
*
* @param namespaceId namespace of the dataset instance
* @param name name of the dataset instance
* @throws Exception
*/
@PUT
@Path("/data/datasets/{name}/properties")
public void update(HttpRequest request, HttpResponder responder,
@PathParam("namespace-id") String namespaceId,
@PathParam("name") String name) throws Exception {
Id.DatasetInstance instance = Id.DatasetInstance.from(namespaceId, name);
Map<String, String> properties = getProperties(request);
LOG.info("Update dataset {}, type name: {}, props: {}", name, GSON.toJson(properties));
instanceService.update(instance, properties);
responder.sendStatus(HttpResponseStatus.OK);
}
/**
* Deletes a dataset instance, which also deletes the data owned by it.
*
* @param namespaceId namespace of the dataset instance
* @param name name of the dataset instance
* @throws Exception
*/
@DELETE
@Path("/data/datasets/{name}")
public void drop(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId,
@PathParam("name") String name) throws Exception {
LOG.info("Deleting dataset {}.{}", namespaceId, name);
Id.DatasetInstance instance = Id.DatasetInstance.from(namespaceId, name);
instanceService.drop(instance);
responder.sendStatus(HttpResponseStatus.OK);
}
/**
* Executes an admin operation on a dataset instance.
*
* @param namespaceId namespace of the dataset instance
* @param name name of the dataset instance
* @param method the admin operation to execute (e.g. "exists", "truncate", "upgrade")
* @throws Exception
*/
@POST
@Path("/data/datasets/{name}/admin/{method}")
public void executeAdmin(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId,
@PathParam("name") String name,
@PathParam("method") String method) throws Exception {
Id.DatasetInstance instance = Id.DatasetInstance.from(namespaceId, name);
try {
DatasetAdminOpResponse response = instanceService.executeAdmin(instance, method);
responder.sendJson(HttpResponseStatus.OK, response);
} catch (HandlerException e) {
responder.sendStatus(e.getFailureStatus());
}
}
/**
* Executes a data operation on a dataset instance. Not yet implemented.
*
* @param namespaceId namespace of the dataset instance
* @param name name of the dataset instance
* @param method the data operation to execute
*/
@POST
@Path("/data/datasets/{name}/data/{method}")
public void executeDataOp(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId,
@PathParam("name") String name, @PathParam("method") String method) {
// todo: execute data operation
responder.sendStatus(HttpResponseStatus.NOT_IMPLEMENTED);
}
private List<? extends Id> strings2Ids(List<String> strings) {
return Lists.transform(strings, new Function<String, Id>() {
@Nullable
@Override
public Id apply(@Nullable String input) {
if (input == null) {
return null;
}
return Id.fromString(input, Id.Program.class);
}
});
}
private Collection<DatasetSpecificationSummary> spec2Summary(Collection<DatasetSpecification> specs) {
List<DatasetSpecificationSummary> datasetSummaries = Lists.newArrayList();
for (DatasetSpecification spec : specs) {
// TODO: (CDAP-3097) handle system datasets specially within a namespace instead of filtering them out
// by the handler. This filter is only in the list endpoint because the other endpoints are used by
// HBaseQueueAdmin through DatasetFramework.
if (QueueConstants.STATE_STORE_NAME.equals(spec.getName())) {
continue;
}
datasetSummaries.add(new DatasetSpecificationSummary(spec.getName(), spec.getType(), spec.getProperties()));
}
return datasetSummaries;
}
private DatasetInstanceConfiguration getInstanceConfiguration(HttpRequest request) {
Reader reader = new InputStreamReader(new ChannelBufferInputStream(request.getContent()), Charsets.UTF_8);
DatasetInstanceConfiguration creationProperties = GSON.fromJson(reader, DatasetInstanceConfiguration.class);
return creationProperties;
}
private Map<String, String> getProperties(HttpRequest request) {
Reader reader = new InputStreamReader(new ChannelBufferInputStream(request.getContent()), Charsets.UTF_8);
Map<String, String> properties = GSON.fromJson(reader, new TypeToken<Map<String, String>>() { }.getType());
return properties;
}
}
| mpouttuclarke/cdap | cdap-data-fabric/src/main/java/co/cask/cdap/data2/datafabric/dataset/service/DatasetInstanceHandler.java | Java | apache-2.0 | 10,272 |
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.testng.SkipException;
import java.io.IOException;
import java.util.Set;
/**
* Created by serg on 10.05.2017.
*/
public class TestBase {
public void skipIfNotFixed(int issueId) throws IOException {
if (isIssueOpen(issueId)) {
throw new SkipException("Ignored because of issue " + issueId);
}
}
public boolean isIssueOpen(int issueId) throws IOException {
String issueStatus = getIssueData(issueId).iterator().next().getStatus();
if (issueStatus.equals("Resolved") || issueStatus.equals("Closed"))
return false;
else
return true;
}
private Set<Issue> getIssueData(int id) throws IOException {
String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues/"+id+".json"))
.returnContent().asString();
JsonElement parsed = new JsonParser().parse(json);
JsonElement issues = parsed.getAsJsonObject().get("issues");
return new Gson().fromJson(issues, new TypeToken<Set<Issue>>() {}.getType());
}
private Executor getExecutor() {
return Executor.newInstance().auth("LSGjeU4yP1X493ud1hNniA==", "");
}
} | sergeiden/java_training | rest-sample/src/test/java/TestBase.java | Java | apache-2.0 | 1,355 |
/******************************************************************************
Redis dispatch client
*******************************************************************************/
'use strict';
var _ = require('underscore'),
Base = require('./base'),
logger = require('../../logger'),
redis = require('redis');
module.exports = function(options) {
_.extend(this, new Base(options));
//abort if we do not have an api key
if (!options.redis.host) return;
var sub = redis.createClient({
host: options.redis.host,
port: options.redis.port,
password: options.redis.password
});
var pub = redis.createClient({
host: options.redis.host,
port: options.redis.port,
password: options.redis.password
});
var ready = false, that = this;
sub.on('subscribe', function(channel) {
if (channel === 'fruum') {
ready = true;
logger.system('Redis dispatch connected');
}
});
sub.on('message', function(channel, message) {
if (channel !== 'fruum') return;
try {
message = JSON.parse(message);
_.each(that.getCallbacks(), function(cb) {
cb(message);
});
}
catch(err) {}
});
sub.subscribe('fruum');
//override emit function
this.emit = function(payload) {
if (!ready) return;
pub.publish('fruum', JSON.stringify(payload));
}
}
| wgrmath/forum | server/backends/dispatch/redis.js | JavaScript | apache-2.0 | 1,353 |
// What is the optimal angle at which to shoot off a point mass to get it to
// go as far as possible? (45 degrees)
#include <iostream>
#include <PSim/osimPSim.h>
#include <OpenSim/OpenSim.h>
#include <OpenSim/Simulation/SimbodyEngine/PlanarJoint.h>
// Parameters.
// ===========
// Angle of the projectile's initial velocity with the horizontal, in degrees.
class Angle : public OpenSim::PSimParameter {
OpenSim_DECLARE_CONCRETE_OBJECT(Angle, OpenSim::PSimParameter);
void extendApplyToInitialState(const double param,
const Model& model, SimTK::State& initState) const override {
const double angle = param * SimTK::Pi / 180.0;
const double v = 3;
const double vx = v * cos(angle);
const double vy = v * sin(angle);
const Coordinate& cx = model.getCoordinateSet().get("x");
cx.setSpeedValue(initState, vx);
const Coordinate& cy = model.getCoordinateSet().get("y");
cy.setSpeedValue(initState, vy);
}
};
// Objectives.
// ===========
class Range : public OpenSim::PSimGoal {
OpenSim_DECLARE_CONCRETE_OBJECT(Range, OpenSim::PSimGoal);
SimTK::Real extendEvaluate(const OpenSim::PSimParameterValueSet & pvalset,
const OpenSim::StateTrajectory& states) const override
{
const Coordinate& c = getModel().getCoordinateSet().get("x");
return -c.getValue(states.back());
}
};
// TODO put this in a different example.
class Test : public OpenSim::IntegratingGoal {
OpenSim_DECLARE_CONCRETE_OBJECT(Test, OpenSim::IntegratingGoal);
SimTK::Real integrand(const SimTK::State& s) const override {
return 1;
}
void realizeReport(const SimTK::State& s) const {
// TODO std::cout << "DEBUG report" << std::endl;
}
};
class MaxHeight : public OpenSim::PSimGoal {
OpenSim_DECLARE_CONCRETE_OBJECT(MaxHeight, OpenSim::PSimGoal);
public:
class Max : public OpenSim::Maximum {
OpenSim_DECLARE_CONCRETE_OBJECT(Max, OpenSim::Maximum);
public:
Max(const MaxHeight* mh) : mh(mh) {}
double getInputVirtual(const SimTK::State& s) const override {
return mh->height(s);
}
SimTK::Stage getDependsOnStageVirtual() const override {
return SimTK::Stage::Position;
}
private:
const MaxHeight* mh;
};
MaxHeight() : m_max(this) {
//constructInfrastructure();
}
MaxHeight(const MaxHeight& mh) : OpenSim::PSimGoal(mh), m_max(this) {}
SimTK::Real extendEvaluate(const OpenSim::PSimParameterValueSet & pvalset,
const OpenSim::StateTrajectory& states) const override {
return -m_max.maximum(states.back());
}
double height(const SimTK::State& s) const {
return getModel().getCoordinateSet().get("y").getValue(s);
}
private:
/*
// TODO should not be necessary.
void constructProperties() override {}
void constructOutputs() override {
constructOutput<double>("height", &MaxHeight::height,
SimTK::Stage::Position);
}
*/
void connectToModel(Model& model) override {
Super::connectToModel(model);
addComponent(&m_max);
// m_max.getInput("input").connect(getOutput("height"));
}
Max m_max;
};
// Event handlers.
// ===============
namespace OpenSim {
class TriggeredEventHandler : public ModelComponent
{
OpenSim_DECLARE_ABSTRACT_OBJECT(TriggeredEventHandler, ModelComponent);
public:
OpenSim_DECLARE_PROPERTY(required_stage, int,
"The stage at which the event occurs.");
TriggeredEventHandler() {
constructProperties();
}
virtual void handleEvent(SimTK::State& state, SimTK::Real accuracy,
bool& shouldTerminate) const = 0;
virtual SimTK::Real getValue(const SimTK::State& s) const = 0;
private:
void constructProperties() {
constructProperty_required_stage(SimTK::Stage::Dynamics);
}
void extendAddToSystem(SimTK::MultibodySystem& system) const override {
// TODO is this okay for memory?
system.addEventHandler(
new SimbodyHandler(SimTK::Stage(get_required_stage()), this));
}
class SimbodyHandler : public SimTK::TriggeredEventHandler {
public:
SimbodyHandler(SimTK::Stage requiredStage,
const OpenSim::TriggeredEventHandler* handler) :
SimTK::TriggeredEventHandler(requiredStage), m_handler(handler) {}
void handleEvent(SimTK::State& state, SimTK::Real accuracy,
bool& shouldTerminate) const override
{ m_handler->handleEvent(state, accuracy, shouldTerminate); }
SimTK::Real getValue(const SimTK::State& s) const override
{ return m_handler->getValue(s); }
private:
const OpenSim::TriggeredEventHandler* m_handler;
};
};
} // namespace OpenSim
// End the simulation when y = 0.
class HitGround : public TriggeredEventHandler {
OpenSim_DECLARE_CONCRETE_OBJECT(HitGround, TriggeredEventHandler);
public:
void handleEvent(SimTK::State& state, SimTK::Real accuracy,
bool& shouldTerminate) const override
{ shouldTerminate = true; }
SimTK::Real getValue(const SimTK::State& s) const override {
const Coordinate& c = getModel().getCoordinateSet().get("y");
return c.getValue(s);
}
};
Model createModel()
{
Model model;
Body* body = new Body("projectile", 1, SimTK::Vec3(0), SimTK::Inertia(1));
model.addBody(body);
Joint* joint = new PlanarJoint("joint",
model.getGroundBody(), SimTK::Vec3(0), SimTK::Vec3(0),
*body, SimTK::Vec3(0), SimTK::Vec3(0));
joint->getCoordinateSet().get(0).setName("theta");
joint->getCoordinateSet().get(1).setName("x");
joint->getCoordinateSet().get(2).setName("y");
model.addJoint(joint);
model.addModelComponent(new HitGround());
return model;
}
int main()
{
// Set up tool.
// ============
OpenSim::PSimTool pstool;
//pstool.set_visualize(true);
pstool.setBaseModel(createModel());
// Set up parameters.
// ==================
Angle angle;
angle.setName("angle");
angle.set_default_value(80);
angle.set_lower_limit(1);
angle.set_upper_limit(90);
angle.set_lower_opt(0);
angle.set_upper_opt(90);
pstool.append_parameters(angle);
// Set up objectives.
// ==================
Range range;
range.set_weight(1);
pstool.append_goals(range);
Test integratingObj;
integratingObj.set_weight(0);
pstool.append_goals(integratingObj);
MaxHeight maxHeight;
maxHeight.set_weight(0);
pstool.append_goals(maxHeight);
// Wrap up.
// ========
pstool.setSerializeAllDefaults(true);
pstool.print("PSimToolSetup.xml");
OpenSim::PSimParameterValueSet soln = pstool.solve();
soln.print("solution.xml");
return 0;
}
| stanfordnmbl/psim | examples/projectile/projectile.cpp | C++ | apache-2.0 | 6,867 |
<?php
namespace CursoLaravel\Http\Controllers;
use CursoLaravel\Exceptions\Enums\Error;
use CursoLaravel\Services\ProjectTaskService;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use CursoLaravel\Http\Requests;
use Illuminate\Http\Response;
class ProjectTaskController extends Controller
{
/**
* @var ProjectTaskService
*/
private $service;
/**
* @param ProjectTaskService $service
*/
public function __construct(ProjectTaskService $service)
{
$this->service = $service;
}
/**
* @return mixed
*/
public function index()
{
return $this->service->all();
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
return $this->service->create($request->all());
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
try {
return $this->service->find($id);
} catch(ModelNotFoundException $mnf) {
return response()->json([
'message' => Error::RECORD_NOT_FOUND,
], Response::HTTP_NOT_FOUND);
} catch(\Exception $e) {
return response()->json([
'message' => Error::UNEXPECTED_ERROR,
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param int $id
* @return Response
*/
public function update(Request $request, $id)
{
try {
return $this->service->update($request->all(), $id);
} catch(ModelNotFoundException $mnf) {
return response()->json([
'message' => Response::HTTP_NOT_FOUND,
], Response::HTTP_NOT_FOUND);
} catch(\Exception $e) {
return response()->json([
'message' => Error::UNEXPECTED_ERROR,
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
try {
$this->service->destroy($id);
} catch(ModelNotFoundException $mnf) {
return response()->json([
'message' => Error::RECORD_NOT_FOUND,
], Response::HTTP_NOT_FOUND);
} catch(\Exception $e) {
return response()->json([
'message' => Error::UNEXPECTED_ERROR,
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
} | DiloWagner/laravel-rest-client | app/Http/Controllers/ProjectTaskController.php | PHP | apache-2.0 | 2,772 |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/trajectory/publishable_trajectory.h"
#include <string>
#include "google/protobuf/util/message_differencer.h"
#include "gtest/gtest.h"
#include "modules/common/util/file.h"
namespace apollo {
namespace planning {
TEST(basic_test, DiscretizedTrajectory) {
const std::string path_of_standard_trajectory =
"modules/planning/testdata/trajectory_data/standard_trajectory.pb.txt";
ADCTrajectory trajectory;
EXPECT_TRUE(
common::util::GetProtoFromFile(path_of_standard_trajectory, &trajectory));
DiscretizedTrajectory discretized_trajectory(trajectory);
PublishableTrajectory publishable_trajectory(12349834.26,
discretized_trajectory);
EXPECT_EQ(publishable_trajectory.header_time(), 12349834.26);
ADCTrajectory output_trajectory;
publishable_trajectory.PopulateTrajectoryProtobuf(&output_trajectory);
google::protobuf::util::MessageDifferencer differencer;
for (int i = 0; i < output_trajectory.trajectory_point_size(); ++i) {
EXPECT_TRUE(differencer.Compare(output_trajectory.trajectory_point(i),
trajectory.trajectory_point(i)));
}
}
} // namespace planning
} // namespace apollo
| startcode/apollo | modules/planning/common/trajectory/publishable_trajectory_test.cc | C++ | apache-2.0 | 2,035 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl;
import com.intellij.diagnostic.ThreadDumper;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.mock.MockDocument;
import com.intellij.mock.MockPsiFile;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.ex.PrioritizedDocumentListener;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.impl.TrailingSpacesStripper;
import com.intellij.openapi.editor.impl.event.DocumentEventImpl;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileTypes.PlainTextFileType;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.io.FileTooBigException;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.testFramework.LeakHunter;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.exceptionCases.AbstractExceptionCase;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
public class PsiDocumentManagerImplTest extends PlatformTestCase {
private static final int TIMEOUT = 30000;
private PsiDocumentManagerImpl getPsiDocumentManager() {
return (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(getProject());
}
@Override
protected void setUp() throws Exception {
super.setUp();
DocumentCommitThread.getInstance();
UIUtil.dispatchAllInvocationEvents();
}
@Override
protected void tearDown() throws Exception {
try {
LaterInvocator.leaveAllModals();
}
finally {
super.tearDown();
}
}
public void testGetCachedPsiFile_NoFile() {
final PsiFile file = getPsiDocumentManager().getCachedPsiFile(new MockDocument());
assertNull(file);
}
public void testGetPsiFile_NotRegisteredDocument() {
final PsiFile file = getPsiDocumentManager().getPsiFile(new MockDocument());
assertNull(file);
}
public void testGetDocument_FirstGet() {
VirtualFile vFile = createFile();
final PsiFile file = new MockPsiFile(vFile, getPsiManager());
final Document document = getDocument(file);
assertNotNull(document);
assertSame(document, FileDocumentManager.getInstance().getDocument(vFile));
}
private static LightVirtualFile createFile() {
return new LightVirtualFile("foo.txt");
}
public void testDocumentGced() throws Exception {
VirtualFile vFile = getVirtualFile(createTempFile("txt", "abc"));
PsiDocumentManagerImpl documentManager = getPsiDocumentManager();
long id = System.identityHashCode(documentManager.getDocument(findFile(vFile)));
documentManager.commitAllDocuments();
UIUtil.dispatchAllInvocationEvents();
assertEmpty(documentManager.getUncommittedDocuments());
LeakHunter.checkLeak(documentManager, DocumentImpl.class, doc -> id == System.identityHashCode(doc));
LeakHunter.checkLeak(documentManager, PsiFileImpl.class, psiFile -> vFile.equals(psiFile.getVirtualFile()));
PlatformTestUtil.tryGcSoftlyReachableObjects();
assertNull(documentManager.getCachedDocument(findFile(vFile)));
Document newDoc = documentManager.getDocument(findFile(vFile));
assertTrue(id != System.identityHashCode(newDoc));
}
private PsiFile findFile(@NotNull VirtualFile vFile) {
return getPsiManager().findFile(vFile);
}
public void testGetUncommittedDocuments_noDocuments() {
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
}
public void testGetUncommittedDocuments_documentChanged_DontProcessEvents() {
final PsiFile file = findFile(createFile());
final Document document = getDocument(file);
WriteCommandAction.runWriteCommandAction(null, () -> PsiToDocumentSynchronizer
.performAtomically(file, () -> changeDocument(document, getPsiDocumentManager())));
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
}
public void testGetUncommittedDocuments_documentNotRegistered() {
final Document document = new MockDocument();
WriteCommandAction.runWriteCommandAction(null, () -> changeDocument(document, getPsiDocumentManager()));
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
}
public void testCommitDocument_RemovesFromUncommittedList() {
PsiFile file = findFile(createFile());
final Document document = getDocument(file);
WriteCommandAction.runWriteCommandAction(null, () -> changeDocument(document, getPsiDocumentManager()));
getPsiDocumentManager().commitDocument(document);
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
}
private Document getDocument(PsiFile file) {
return getPsiDocumentManager().getDocument(file);
}
private static void changeDocument(Document document, PsiDocumentManagerImpl manager) {
DocumentEventImpl event = new DocumentEventImpl(document, 0, "", "", document.getModificationStamp(), false);
manager.beforeDocumentChange(event);
manager.documentChanged(event);
}
public void testCommitAllDocument_RemovesFromUncommittedList() {
PsiFile file = findFile(createFile());
final Document document = getDocument(file);
WriteCommandAction.runWriteCommandAction(null, () -> changeDocument(document, getPsiDocumentManager()));
getPsiDocumentManager().commitAllDocuments();
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
}
public void testDocumentFromAlienProjectDoesNotEndUpInMyUncommittedList() throws Exception {
PsiFile file = findFile(createFile());
final Document document = getDocument(file);
File temp = createTempDirectory();
final Project alienProject = createProject(temp + "/alien.ipr", DebugUtil.currentStackTrace());
boolean succ2 = ProjectManagerEx.getInstanceEx().openProject(alienProject);
assertTrue(succ2);
UIUtil.dispatchAllInvocationEvents(); // startup activities
try {
PsiManager alienManager = PsiManager.getInstance(alienProject);
final String alienText = "alien";
LightVirtualFile alienVirt = new LightVirtualFile("foo.txt", alienText);
final PsiFile alienFile = alienManager.findFile(alienVirt);
final PsiDocumentManagerImpl alienDocManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(alienProject);
final Document alienDocument = alienDocManager.getDocument(alienFile);
assertEquals(0, alienDocManager.getUncommittedDocuments().length);
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
WriteCommandAction.runWriteCommandAction(null, () -> {
changeDocument(alienDocument, getPsiDocumentManager());
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
assertEquals(0, alienDocManager.getUncommittedDocuments().length);
changeDocument(alienDocument, alienDocManager);
assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
assertEquals(1, alienDocManager.getUncommittedDocuments().length);
changeDocument(document, getPsiDocumentManager());
assertEquals(1, getPsiDocumentManager().getUncommittedDocuments().length);
assertEquals(1, alienDocManager.getUncommittedDocuments().length);
changeDocument(document, alienDocManager);
assertEquals(1, getPsiDocumentManager().getUncommittedDocuments().length);
assertEquals(1, alienDocManager.getUncommittedDocuments().length);
});
}
finally {
ProjectUtil.closeAndDispose(alienProject);
}
}
public void testCommitInBackground() {
PsiFile file = findFile(createFile());
assertNotNull(file);
assertTrue(file.isPhysical());
final Document document = getDocument(file);
assertNotNull(document);
final Semaphore semaphore = new Semaphore();
semaphore.down();
getPsiDocumentManager().performWhenAllCommitted(() -> {
assertTrue(getPsiDocumentManager().isCommitted(document));
semaphore.up();
});
waitAndPump(semaphore, TIMEOUT);
assertTrue(getPsiDocumentManager().isCommitted(document));
WriteCommandAction.runWriteCommandAction(null, () -> document.insertString(0, "class X {}"));
semaphore.down();
getPsiDocumentManager().performWhenAllCommitted(() -> {
assertTrue(getPsiDocumentManager().isCommitted(document));
semaphore.up();
});
waitAndPump(semaphore, TIMEOUT);
assertTrue(getPsiDocumentManager().isCommitted(document));
final AtomicInteger count = new AtomicInteger();
WriteCommandAction.runWriteCommandAction(null, () -> {
document.insertString(0, "/**/");
boolean executed = getPsiDocumentManager().cancelAndRunWhenAllCommitted("xxx", count::incrementAndGet);
assertFalse(executed);
executed = getPsiDocumentManager().cancelAndRunWhenAllCommitted("xxx", count::incrementAndGet);
assertFalse(executed);
assertEquals(0, count.get());
});
while (!getPsiDocumentManager().isCommitted(document)) {
UIUtil.dispatchAllInvocationEvents();
}
assertTrue(getPsiDocumentManager().isCommitted(document));
assertEquals(1, count.get());
count.set(0);
WriteCommandAction.runWriteCommandAction(null, () -> {
document.insertString(0, "/**/");
boolean executed = getPsiDocumentManager().performWhenAllCommitted(count::incrementAndGet);
assertFalse(executed);
executed = getPsiDocumentManager().performWhenAllCommitted(count::incrementAndGet);
assertFalse(executed);
assertEquals(0, count.get());
});
while (!getPsiDocumentManager().isCommitted(document)) {
UIUtil.dispatchAllInvocationEvents();
}
assertTrue(getPsiDocumentManager().isCommitted(document));
assertEquals(2, count.get());
}
public void testDocumentCommittedInBackgroundEventuallyEvenDespiteTyping() throws IOException {
VirtualFile virtualFile = getVirtualFile(createTempFile("X.java", ""));
PsiFile file = findFile(virtualFile);
assertNotNull(file);
assertTrue(file.isPhysical());
final Document document = getDocument(file);
assertNotNull(document);
WriteCommandAction.runWriteCommandAction(null, () -> document
.insertString(0, "class X {" + StringUtil.repeat("public int IIII = 222;\n", 10000) + "}"));
waitForCommits();
assertEquals(StdFileTypes.JAVA.getLanguage(), file.getLanguage());
for (int i = 0; i < 300; i++) {
assertTrue("Still not committed: " + document, getPsiDocumentManager().isCommitted(document));
WriteCommandAction.runWriteCommandAction(null, () -> {
document.insertString(0, "/**/");
assertFalse(getPsiDocumentManager().isCommitted(document));
});
waitForCommits();
WriteCommandAction.runWriteCommandAction(null, () -> document.deleteString(0, "/**/".length()));
waitForCommits();
String dumpBefore = ThreadDumper.dumpThreadsToString();
if (!getPsiDocumentManager().isCommitted(document)) {
System.err.println("Thread dump1:\n" + dumpBefore + "\n;Thread dump2:\n" + ThreadDumper.dumpThreadsToString());
fail("Still not committed: " + document);
}
}
}
private static void waitAndPump(Semaphore semaphore, int timeout) {
final long limit = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < limit) {
if (semaphore.waitFor(1)) return;
UIUtil.dispatchAllInvocationEvents();
}
fail("Timeout");
}
public void testDocumentFromAlienProjectGetsCommittedInBackground() throws Exception {
LightVirtualFile virtualFile = createFile();
PsiFile file = findFile(virtualFile);
final Document document = getDocument(file);
File temp = createTempDirectory();
final Project alienProject = createProject(temp + "/alien.ipr", DebugUtil.currentStackTrace());
boolean succ2 = ProjectManagerEx.getInstanceEx().openProject(alienProject);
assertTrue(succ2);
UIUtil.dispatchAllInvocationEvents(); // startup activities
try {
PsiManager alienManager = PsiManager.getInstance(alienProject);
final PsiFile alienFile = alienManager.findFile(virtualFile);
assertNotNull(alienFile);
final PsiDocumentManagerImpl alienDocManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(alienProject);
final Document alienDocument = alienDocManager.getDocument(alienFile);
assertSame(document, alienDocument);
assertEmpty(alienDocManager.getUncommittedDocuments());
assertEmpty(getPsiDocumentManager().getUncommittedDocuments());
WriteCommandAction.runWriteCommandAction(null, () -> {
document.setText("xxx");
assertOrderedEquals(getPsiDocumentManager().getUncommittedDocuments(), document);
assertOrderedEquals(alienDocManager.getUncommittedDocuments(), alienDocument);
});
assertEquals("xxx", document.getText());
assertEquals("xxx", alienDocument.getText());
waitForCommits();
assertTrue("Still not committed: " + document, getPsiDocumentManager().isCommitted(document));
long t2 = System.currentTimeMillis() + TIMEOUT;
while (!alienDocManager.isCommitted(alienDocument) && System.currentTimeMillis() < t2) {
UIUtil.dispatchAllInvocationEvents();
}
assertTrue("Still not committed: " + alienDocument, alienDocManager.isCommitted(alienDocument));
}
finally {
ProjectUtil.closeAndDispose(alienProject);
}
}
public void testCommitThreadGetSuspendedDuringWriteActions() {
final DocumentCommitThread commitThread = DocumentCommitThread.getInstance();
assertTrue(commitThread.isEnabled());
WriteCommandAction.runWriteCommandAction(null, () -> {
if (commitThread.isEnabled()) {
System.err.println("commitThread: " + commitThread + ";\n" + ThreadDumper.dumpThreadsToString());
}
assertFalse(commitThread.isEnabled());
WriteCommandAction.runWriteCommandAction(null, () -> assertFalse(commitThread.isEnabled()));
assertFalse(commitThread.isEnabled());
});
assertTrue(commitThread.isEnabled());
}
public void testFileChangesToText() throws IOException {
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", "abc"));
PsiFile psiFile = findFile(vFile);
Document document = getDocument(psiFile);
rename(vFile, "a.xml");
assertFalse(psiFile.isValid());
assertNotSame(psiFile, findFile(vFile));
psiFile = findFile(vFile);
assertSame(document, FileDocumentManager.getInstance().getDocument(vFile));
assertSame(document, getDocument(psiFile));
}
public void testFileChangesToBinary() throws IOException {
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", "abc"));
PsiFile psiFile = findFile(vFile);
Document document = getDocument(psiFile);
rename(vFile, "a.zip");
assertFalse(psiFile.isValid());
psiFile = findFile(vFile);
assertInstanceOf(psiFile, PsiBinaryFile.class);
assertNoFileDocumentMapping(vFile, psiFile, document);
assertEquals("abc", document.getText());
}
public void testFileBecomesTooLarge() throws Exception {
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", "abc"));
PsiFile psiFile = findFile(vFile);
Document document = getDocument(psiFile);
makeFileTooLarge(vFile);
assertFalse(psiFile.isValid());
psiFile = findFile(vFile);
assertInstanceOf(psiFile, PsiLargeTextFile.class);
assertLargeFileContentLimited(getTooLargeContent(), vFile, document);
}
private void makeFileTooLarge(final VirtualFile vFile) throws Exception {
WriteCommandAction.runWriteCommandAction(myProject, (ThrowableComputable<Object, Exception>)() -> {
setFileText(vFile, getTooLargeContent());
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
return null;
});
}
public void testFileTooLarge() throws Exception {
String content = getTooLargeContent();
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", content));
PsiFile psiFile = findFile(vFile);
Document document = getDocument(psiFile);
assertNotNull(document);
assertInstanceOf(psiFile, PsiLargeTextFile.class);
assertLargeFileContentLimited(content, vFile, document);
}
public void testBinaryFileTooLarge() throws Exception {
VirtualFile vFile = getVirtualFile(createTempFile("a.zip", getTooLargeContent()));
PsiFile psiFile = findFile(vFile);
Document document = getDocument(psiFile);
assertNull(document);
assertInstanceOf(psiFile, PsiLargeBinaryFile.class);
}
public void testLargeFileException() throws Throwable {
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", getTooLargeContent()));
assertException(new FileTooBigExceptionCase() {
@Override
public void tryClosure() throws Throwable {
vFile.getOutputStream(this);
}
});
assertException(new FileTooBigExceptionCase() {
@Override
public void tryClosure() throws Throwable {
vFile.setBinaryContent(new byte[]{});
}
});
assertException(new FileTooBigExceptionCase() {
@Override
public void tryClosure() throws Throwable {
vFile.setBinaryContent(ArrayUtil.EMPTY_BYTE_ARRAY, 1, 2);
}
});
assertException(new FileTooBigExceptionCase() {
@Override
public void tryClosure() throws Throwable {
vFile.setBinaryContent(ArrayUtil.EMPTY_BYTE_ARRAY, 1, 2, this);
}
});
assertException(new FileTooBigExceptionCase() {
@Override
public void tryClosure() throws Throwable {
vFile.contentsToByteArray();
}
});
assertException(new FileTooBigExceptionCase() {
@Override
public void tryClosure() throws Throwable {
vFile.contentsToByteArray(false);
}
});
}
private void assertNoFileDocumentMapping(VirtualFile vFile, PsiFile psiFile, Document document) {
assertNull(FileDocumentManager.getInstance().getDocument(vFile));
assertNull(FileDocumentManager.getInstance().getFile(document));
assertNull(getPsiDocumentManager().getPsiFile(document));
assertNull(getDocument(psiFile));
}
public void testCommitDocumentInModalDialog() throws IOException {
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", "abc"));
PsiFile psiFile = findFile(vFile);
final Document document = getDocument(psiFile);
final DialogWrapper dialog = new DialogWrapper(getProject()) {
@Nullable
@Override
protected JComponent createCenterPanel() {
return null;
}
};
disposeOnTearDown(() -> dialog.close(DialogWrapper.OK_EXIT_CODE));
ApplicationManager.getApplication().runWriteAction(() -> {
// commit thread is paused
document.setText("xx");
LaterInvocator.enterModal(dialog);
});
assertNotSame(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState());
// may or may not be committed until exit modal dialog
waitForCommits();
LaterInvocator.leaveModal(dialog);
assertEquals(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState());
// must commit
waitForCommits();
assertTrue(getPsiDocumentManager().isCommitted(document));
// check that inside modal dialog commit is possible
ApplicationManager.getApplication().runWriteAction(() -> {
// commit thread is paused
LaterInvocator.enterModal(dialog);
document.setText("yyy");
});
assertNotSame(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState());
// must commit
waitForCommits();
assertTrue(getPsiDocumentManager().isCommitted(document));
}
public void testBackgroundCommitInDialogInTransaction() throws IOException {
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", "abc"));
PsiFile psiFile = findFile(vFile);
Document document = getDocument(psiFile);
TransactionGuard.submitTransaction(myProject, () -> {
WriteCommandAction.runWriteCommandAction(myProject, () -> {
document.insertString(0, "x");
LaterInvocator.enterModal(new Object());
assertFalse(getPsiDocumentManager().isCommitted(document));
});
waitForCommits();
assertTrue(getPsiDocumentManager().isCommitted(document));
});
UIUtil.dispatchAllInvocationEvents();
}
public void testChangeDocumentThenEnterModalDialogThenCallPerformWhenAllCommittedShouldFireWhileInsideModal() throws IOException {
VirtualFile vFile = getVirtualFile(createTempFile("a.txt", "abc"));
PsiFile psiFile = findFile(vFile);
final Document document = getDocument(psiFile);
final DialogWrapper dialog = new DialogWrapper(getProject()) {
@Nullable
@Override
protected JComponent createCenterPanel() {
return null;
}
};
disposeOnTearDown(() -> dialog.close(DialogWrapper.OK_EXIT_CODE));
ApplicationManager.getApplication().runWriteAction(() -> {
// commit thread is paused
document.setText("xx");
LaterInvocator.enterModal(dialog);
});
assertNotSame(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState());
// may or may not commit in background by default when modality changed
waitForCommits();
// but, when performWhenAllCommitted() in modal context called, should re-add documents into queue nevertheless
boolean[] calledPerformWhenAllCommitted = new boolean[1];
getPsiDocumentManager().performWhenAllCommitted(() -> calledPerformWhenAllCommitted[0] = true);
// must commit now
waitForCommits();
assertTrue(getPsiDocumentManager().isCommitted(document));
assertTrue(calledPerformWhenAllCommitted[0]);
}
private static void waitForCommits() {
try {
DocumentCommitThread.getInstance().waitForAllCommits();
}
catch (ExecutionException | InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
}
}
public void testReparseDoesNotModifyDocument() throws Exception {
VirtualFile file = createTempFile("txt", null, "1\n2\n3\n", Charset.forName("UTF-8"));
file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, EditorSettingsExternalizable.STRIP_TRAILING_SPACES_CHANGED);
final Document document = FileDocumentManager.getInstance().getDocument(file);
assertNotNull(document);
WriteCommandAction.runWriteCommandAction(myProject, () -> document.insertString(document.getTextLength(), " "));
PsiDocumentManager.getInstance(myProject).reparseFiles(Collections.singleton(file), false);
assertEquals("1\n2\n3\n ", VfsUtilCore.loadText(file));
WriteCommandAction.runWriteCommandAction(myProject, () -> document.insertString(0, "-"));
FileDocumentManager.getInstance().saveDocument(document);
assertEquals("-1\n2\n3\n", VfsUtilCore.loadText(file));
}
public void testPerformWhenAllCommittedMustNotNest() {
PsiFile file = findFile(createFile());
assertNotNull(file);
assertTrue(file.isPhysical());
final Document document = getDocument(file);
assertNotNull(document);
WriteCommandAction.runWriteCommandAction(null, () -> document.insertString(0, "class X {}"));
getPsiDocumentManager().performWhenAllCommitted(() -> {
try {
getPsiDocumentManager().performWhenAllCommitted(() -> {
});
fail("Must fail");
}
catch (IncorrectOperationException ignored) {
}
});
getPsiDocumentManager().commitAllDocuments();
assertTrue(getPsiDocumentManager().isCommitted(document));
}
public void testUndoShouldAddToCommitQueue() throws IOException {
VirtualFile virtualFile = getVirtualFile(createTempFile("X.java", ""));
PsiFile file = findFile(virtualFile);
assertEquals("JAVA", file.getFileType().getName());
assertNotNull(file);
assertTrue(file.isPhysical());
Editor editor = FileEditorManager.getInstance(myProject).openTextEditor(new OpenFileDescriptor(getProject(), virtualFile, 0), false);
((EditorImpl)editor).setCaretActive();
final Document document = editor.getDocument(); //getDocument(file);
String text = "class X {" + StringUtil.repeat("void fff() {}\n", 1000) +
"}";
WriteCommandAction.runWriteCommandAction(null, () -> document.insertString(0, text));
for (int i = 0; i < 300; i++) {
getPsiDocumentManager().commitAllDocuments();
assertTrue(getPsiDocumentManager().isCommitted(document));
String insert = "ddfdkjh";
WriteCommandAction.runWriteCommandAction(getProject(), () -> document.insertString(0, insert));
TimeoutUtil.sleep(50);
WriteCommandAction.runWriteCommandAction(getProject(), () -> document.replaceString(0, insert.length(), ""));
FileDocumentManager.getInstance().saveDocument(document);
assertEquals(text, editor.getDocument().getText());
waitForCommits();
assertTrue("Still not committed: " + document, getPsiDocumentManager().isCommitted(document));
}
}
public void testCommitNonPhysicalPsiWithoutWriteAction() throws IOException {
assertFalse(ApplicationManager.getApplication().isWriteAccessAllowed());
PsiFile original = getPsiManager().findFile(getVirtualFile(createTempFile("X.txt", "")));
assertNotNull(original);
assertTrue(original.getViewProvider().isEventSystemEnabled());
long modCount = getPsiManager().getModificationTracker().getModificationCount();
PsiFile copy = (PsiFile)original.copy();
assertFalse(copy.getViewProvider().isEventSystemEnabled());
Document document = copy.getViewProvider().getDocument();
assertNotNull(document);
document.setText("class A{}");
PsiDocumentManager.getInstance(myProject).commitDocument(document);
assertEquals(modCount, getPsiManager().getModificationTracker().getModificationCount());
assertEquals(document.getText(), copy.getText());
assertTrue(PsiDocumentManager.getInstance(myProject).isCommitted(document));
}
public void testCommitNonPhysicalCopyOnPerformWhenAllCommitted() throws Exception {
assertFalse(ApplicationManager.getApplication().isWriteAccessAllowed());
PsiFile original = getPsiManager().findFile(getVirtualFile(createTempFile("X.txt", "")));
assertNotNull(original);
PsiFile copy = (PsiFile)original.copy();
assertEquals("", copy.getText());
Document document = copy.getViewProvider().getDocument();
assertNotNull(document);
document.setText("class A{}");
PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(() -> assertEquals(document.getText(), copy.getText()));
DocumentCommitThread.getInstance().waitForAllCommits();
assertTrue(PsiDocumentManager.getInstance(myProject).isCommitted(document));
}
@SuppressWarnings("ConstantConditions")
public void testPerformLaterWhenAllCommittedFromCommitHandler() throws Exception {
Document document = createDocument();
PsiDocumentManager pdm = PsiDocumentManager.getInstance(myProject);
WriteCommandAction.runWriteCommandAction(null, () -> document.insertString(0, "a"));
pdm.performWhenAllCommitted(
() -> pdm.performLaterWhenAllCommitted(
() -> WriteCommandAction.runWriteCommandAction(null, () -> document.insertString(1, "b"))));
assertTrue(pdm.hasUncommitedDocuments());
assertEquals("a", document.getText());
DocumentCommitThread.getInstance().waitForAllCommits();
assertEquals("ab", document.getText());
}
public void testBackgroundCommitDoesNotChokeByWildChangesWhichInvalidatePsiFile() throws Exception {
@Language("JAVA")
String text = "\n\nclass X {\npublic static final String string =null;\n public void x() {}\n}";
VirtualFile virtualFile = getVirtualFile(createTempFile("X.java", text));
PsiFile file = getPsiManager().findFile(virtualFile);
DocumentEx document = (DocumentEx)file.getViewProvider().getDocument();
PsiDocumentManager pdm = PsiDocumentManager.getInstance(myProject);
pdm.commitAllDocuments();
WriteCommandAction.runWriteCommandAction(null, () -> {
try {
virtualFile.setBinaryContent("\n txt txt txt".getBytes("UTF-8"));
virtualFile.rename(this, "X.txt");
}
catch (IOException e) {
throw new RuntimeException(e);
}
});
DocumentCommitThread.getInstance().waitForAllCommits();
assertTrue(pdm.isCommitted(document));
assertFalse(file.isValid());
WriteCommandAction.runWriteCommandAction(null, () ->
document.replaceString(0, document.getTextLength(), "xxxxxxxxxxxxxxxxxxxx"));
pdm.commitAllDocuments();
assertTrue(pdm.isCommitted(document));
PsiFile file2 = getPsiManager().findFile(virtualFile);
assertEquals(PlainTextLanguage.INSTANCE, file2.getLanguage());
}
public void testAsyncCommitHappensInProgressStartedFromTransaction() {
Document document = createDocument();
Semaphore semaphore = new Semaphore(1);
TransactionGuard.submitTransaction(getTestRootDisposable(), () ->
WriteCommandAction.runWriteCommandAction(myProject, () -> {
document.insertString(0, "x");
ProgressManager.getInstance().runProcessWithProgressAsynchronously(new Task.Backgroundable(myProject, "Title", false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
getPsiDocumentManager().commitAndRunReadAction(semaphore::up);
}
}, new ProgressWindow(false, myProject));
}));
int iteration = 0;
while (!semaphore.waitFor(10)) {
UIUtil.dispatchAllInvocationEvents();
if (++iteration > 3000) {
printThreadDump();
fail("Couldn't wait for commit");
}
}
}
public void testNoLeaksAfterPCEInListener() {
Document document = createDocument();
document.addDocumentListener(new PrioritizedDocumentListener() {
@Override
public int getPriority() {
return 0;
}
@Override
public void beforeDocumentChange(DocumentEvent event) {
throw new ProcessCanceledException();
}
});
try {
document.insertString(0, "a");
fail("PCE expected");
}
catch (ProcessCanceledException ignored) {
}
waitForCommits();
LeakHunter.checkLeak(getPsiDocumentManager(), Document.class, d -> d == document);
}
private Document createDocument() {
PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText("a.txt", PlainTextFileType.INSTANCE, "");
return file.getViewProvider().getDocument();
}
private static void assertLargeFileContentLimited(@NotNull String content, @NotNull VirtualFile vFile, @NotNull Document document) {
Charset charset = EncodingManager.getInstance().getEncoding(vFile, false);
float bytesPerChar = charset == null ? 2 : charset.newEncoder().averageBytesPerChar();
int contentSize = (int)(FileUtilRt.LARGE_FILE_PREVIEW_SIZE / bytesPerChar);
String substring = content.substring(0, contentSize);
assertEquals(substring, document.getText());
}
@NotNull
private static String getTooLargeContent() {
return StringUtil.repeat("a", FileUtilRt.LARGE_FOR_CONTENT_LOADING + 1);
}
private abstract static class FileTooBigExceptionCase extends AbstractExceptionCase {
@Override
public Class getExpectedExceptionClass() {
return FileTooBigException.class;
}
}
public void testRestartingCommitWithDifferentTransactionIdShouldFinish() throws IOException {
VirtualFile vFile = getVirtualFile(createTempFile("a.java", ""));
PsiFile psiFile = findFile(vFile);
assertEquals(StdFileTypes.JAVA, psiFile.getFileType());
final Document document = getDocument(psiFile);
Random random = new Random();
for (int i=0; i<1000;i++) {
ApplicationManager.getApplication().runWriteAction(() -> {
@Language(value = "JAVA", prefix = "class c {", suffix = "}")
String body = "@NotNull\n" +
" private static String getTooLargeContent() {\n" +
" return StringUtil.repeat(\"a\", FileUtilRt.LARGE_FOR_CONTENT_LOADING + 1);\n" +
" }\n" +
"private abstract static class FileTooBigExceptionCase extends AbstractExceptionCase {\n" +
" @Override\n" +
" public Class getExpectedExceptionClass() {\n" +
" return FileTooBigException.class;\n" +
" }\n" +
" }";
document.setText("class c {" + StringUtil.repeat(body, 10000) + "}");
});
TimeoutUtil.sleep(random.nextInt(50));
TransactionGuard.getInstance().submitTransactionAndWait(() -> {
boolean[] calledPerformWhenAllCommitted = new boolean[1];
getPsiDocumentManager().performWhenAllCommitted(() -> calledPerformWhenAllCommitted[0] = true);
// the old commit should be either canceled, or eventually end by itself
waitForCommits();
assertTrue(calledPerformWhenAllCommitted[0]);
});
}
ApplicationManager.getApplication().runWriteAction(() -> document.setText(""));
waitForCommits();
}
public void testDefaultProjectDocumentsAreAutoCommitted() throws IOException {
Project defaultProject = ProjectManager.getInstance().getDefaultProject();
VirtualFile vFile = getVirtualFile(createTempFile("a.java", ""));
PsiFile psiFile = PsiManager.getInstance(defaultProject).findFile(vFile);
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(defaultProject);
Document document = documentManager.getDocument(psiFile);
ApplicationManager.getApplication().runWriteAction(() -> document.setText("// things"));
waitForCommits();
assertTrue(documentManager.isCommitted(document));
PsiElement firstChild = psiFile.getFirstChild();
assertTrue(firstChild instanceof PsiComment);
}
} | xfournet/intellij-community | platform/platform-tests/testSrc/com/intellij/psi/impl/PsiDocumentManagerImplTest.java | Java | apache-2.0 | 36,768 |
/*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.runtime.api.event.internal;
import java.util.List;
import java.util.Optional;
import org.activiti.api.process.model.events.MessageSubscriptionCancelledEvent;
import org.activiti.api.process.runtime.events.listener.ProcessRuntimeEventListener;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntity;
import org.activiti.runtime.api.event.impl.ToMessageSubscriptionCancelledConverter;
public class MessageSubscriptionCancelledListenerDelegate implements ActivitiEventListener {
private List<ProcessRuntimeEventListener<MessageSubscriptionCancelledEvent>> processRuntimeEventListeners;
private ToMessageSubscriptionCancelledConverter converter;
public MessageSubscriptionCancelledListenerDelegate(List<ProcessRuntimeEventListener<MessageSubscriptionCancelledEvent>> processRuntimeEventListeners,
ToMessageSubscriptionCancelledConverter converter) {
this.processRuntimeEventListeners = processRuntimeEventListeners;
this.converter = converter;
}
@Override
public void onEvent(ActivitiEvent event) {
if (isValidEvent(event)) {
converter.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
processRuntimeEventListeners.forEach(listener -> listener.onEvent(convertedEvent));
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
protected boolean isValidEvent(ActivitiEvent event) {
return Optional.ofNullable(event)
.filter(ActivitiEntityEvent.class::isInstance)
.map(e -> ((ActivitiEntityEvent) event).getEntity() instanceof MessageEventSubscriptionEntity)
.orElse(false);
}
}
| Activiti/Activiti | activiti-core/activiti-api-impl/activiti-api-process-runtime-impl/src/main/java/org/activiti/runtime/api/event/internal/MessageSubscriptionCancelledListenerDelegate.java | Java | apache-2.0 | 2,653 |
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.agent.common.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.message.BasicHeader;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class HeaderUtilTest {
@Test
public void shouldGetExtraPropertiesFromHeader() {
assertExtraPropertiesWithoutBase64(null, new HashMap<>());
assertExtraPropertiesWithoutBase64("", new HashMap<>());
assertExtraProperties("", new HashMap<>());
assertExtraProperties("Key1=Value1 key2=value2", new HashMap<String, String>() {{
put("Key1", "Value1");
put("key2", "value2");
}});
assertExtraProperties(" Key1=Value1 key2=value2 ", new HashMap<String, String>() {{
put("Key1", "Value1");
put("key2", "value2");
}});
assertExtraProperties("Key1=Value1 key2=value2 key2=value3", new HashMap<String, String>() {{
put("Key1", "Value1");
put("key2", "value2");
}});
assertExtraProperties("Key1%20WithSpace=Value1%20WithSpace key2=value2", new HashMap<String, String>() {{
put("Key1 WithSpace", "Value1 WithSpace");
put("key2", "value2");
}});
}
@Test
public void shouldNotFailIfExtraPropertiesAreNotFormattedProperly() {
assertExtraProperties("abc", new HashMap<>());
}
private void assertExtraProperties(String actualHeaderValueBeforeBase64, Map<String, String> expectedProperties) {
String headerValueInBase64 = Base64.encodeBase64String(actualHeaderValueBeforeBase64.getBytes(UTF_8));
assertExtraPropertiesWithoutBase64(headerValueInBase64, expectedProperties);
}
private void assertExtraPropertiesWithoutBase64(String actualHeaderValue, Map<String, String> expectedProperties) {
Map<String, String> actualResult = HeaderUtil.parseExtraProperties(new BasicHeader("some-key", actualHeaderValue));
assertThat(actualResult, is(expectedProperties));
}
} | GaneshSPatil/gocd | agent-common/src/test/java/com/thoughtworks/go/agent/common/util/HeaderUtilTest.java | Java | apache-2.0 | 2,802 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pt">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Mon Jun 22 15:50:35 BRT 2015 -->
<title>LLDPTest</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="LLDPTest";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/LLDPTest.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../net/floodlightcontroller/packet/LLDPOrganizationalTLVTest.html" title="class in net.floodlightcontroller.packet"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../net/floodlightcontroller/packet/LLDPTLV.html" title="class in net.floodlightcontroller.packet"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?net/floodlightcontroller/packet/LLDPTest.html" target="_top">Frames</a></li>
<li><a href="LLDPTest.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">net.floodlightcontroller.packet</div>
<h2 title="Class LLDPTest" class="title">Class LLDPTest</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>net.floodlightcontroller.packet.LLDPTest</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">LLDPTest</span>
extends java.lang.Object</pre>
<dl><dt><span class="strong">Author:</span></dt>
<dd>David Erickson (daviderickson@cs.stanford.edu)</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../net/floodlightcontroller/packet/LLDPTest.html#LLDPTest()">LLDPTest</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../net/floodlightcontroller/packet/LLDPTest.html#testDeserialize()">testDeserialize</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../net/floodlightcontroller/packet/LLDPTest.html#testSerialize()">testSerialize</a></strong>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="LLDPTest()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>LLDPTest</h4>
<pre>public LLDPTest()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="testSerialize()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>testSerialize</h4>
<pre>public void testSerialize()
throws java.lang.Exception</pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.Exception</code></dd></dl>
</li>
</ul>
<a name="testDeserialize()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>testDeserialize</h4>
<pre>public void testDeserialize()
throws java.lang.Exception</pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.Exception</code></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/LLDPTest.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../net/floodlightcontroller/packet/LLDPOrganizationalTLVTest.html" title="class in net.floodlightcontroller.packet"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../net/floodlightcontroller/packet/LLDPTLV.html" title="class in net.floodlightcontroller.packet"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?net/floodlightcontroller/packet/LLDPTest.html" target="_top">Frames</a></li>
<li><a href="LLDPTest.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| paulorvj/sdnvoip | doc/net/floodlightcontroller/packet/LLDPTest.html | HTML | apache-2.0 | 9,024 |
/*
* Copyright 1999-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.serialization.serializer.binary.impl.index;
import java.io.IOException;
import java.util.List;
import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;
import com.orientechnologies.orient.core.serialization.OMemoryInputStream;
import com.orientechnologies.orient.core.serialization.serializer.binary.OBinarySerializer;
import com.orientechnologies.orient.core.serialization.serializer.binary.OBinarySerializerFactory;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OIntegerSerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerStringAbstract;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
/**
* Serializer that is used for serialization of {@link OCompositeKey} keys in index.
*
* @author Andrey Lomakin
* @since 29.07.11
*/
public class OCompositeKeySerializer implements OBinarySerializer<OCompositeKey>, OStreamSerializer {
public static final String NAME = "cks";
public static final OCompositeKeySerializer INSTANCE = new OCompositeKeySerializer();
public static final byte ID = 14;
public int getObjectSize(OCompositeKey compositeKey) {
final List<Comparable> keys = compositeKey.getKeys();
int size = 2 * OIntegerSerializer.INT_SIZE;
final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE;
for (final Comparable key : keys) {
final OType type = OType.getTypeByClass(key.getClass());
size += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE + factory.getObjectSerializer(type).getObjectSize(key);
}
return size;
}
public void serialize(OCompositeKey compositeKey, byte[] stream, int startPosition) {
final List<Comparable> keys = compositeKey.getKeys();
final int keysSize = keys.size();
final int oldStartPosition = startPosition;
startPosition += OIntegerSerializer.INT_SIZE;
OIntegerSerializer.INSTANCE.serialize(keysSize, stream, startPosition);
startPosition += OIntegerSerializer.INT_SIZE;
final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE;
for (final Comparable key : keys) {
final OType type = OType.getTypeByClass(key.getClass());
OBinarySerializer binarySerializer = factory.getObjectSerializer(type);
stream[startPosition] = binarySerializer.getId();
startPosition += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE;
binarySerializer.serialize(key, stream, startPosition);
startPosition += binarySerializer.getObjectSize(key);
}
OIntegerSerializer.INSTANCE.serialize((startPosition - oldStartPosition), stream, oldStartPosition);
}
public OCompositeKey deserialize(byte[] stream, int startPosition) {
final OCompositeKey compositeKey = new OCompositeKey();
startPosition += OIntegerSerializer.INT_SIZE;
final int keysSize = OIntegerSerializer.INSTANCE.deserialize(stream, startPosition);
startPosition += OIntegerSerializer.INSTANCE.getObjectSize(keysSize);
final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE;
for (int i = 0; i < keysSize; i++) {
final byte serializerId = stream[startPosition];
startPosition += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE;
OBinarySerializer binarySerializer = factory.getObjectSerializer(serializerId);
final Comparable key = (Comparable)binarySerializer.deserialize(stream, startPosition);
compositeKey.addKey(key);
startPosition += binarySerializer.getObjectSize(key);
}
return compositeKey;
}
public int getObjectSize(byte[] stream, int startPosition) {
return OIntegerSerializer.INSTANCE.deserialize(stream, startPosition);
}
public byte getId() {
return ID;
}
public byte[] toStream(final Object iObject) throws IOException {
throw new UnsupportedOperationException("CSV storage format is out of dated and is not supported.");
}
public Object fromStream(final byte[] iStream) throws IOException {
final OCompositeKey compositeKey = new OCompositeKey();
final OMemoryInputStream inputStream = new OMemoryInputStream(iStream);
final int keysSize = inputStream.getAsInteger();
for (int i = 0; i < keysSize; i++) {
final byte[] keyBytes = inputStream.getAsByteArray();
final String keyString = OBinaryProtocol.bytes2string(keyBytes);
final int typeSeparatorPos = keyString.indexOf( ',' );
final OType type = OType.valueOf( keyString.substring( 0, typeSeparatorPos ) );
compositeKey.addKey((Comparable) ORecordSerializerStringAbstract.simpleValueFromStream(keyString.substring(typeSeparatorPos + 1), type));
}
return compositeKey;
}
public String getName() {
return NAME;
}
}
| vivosys/orientdb | core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/index/OCompositeKeySerializer.java | Java | apache-2.0 | 5,585 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `KeyCountWriter` struct in crate `aws_sdk_rust`.">
<meta name="keywords" content="rust, rustlang, rust-lang, KeyCountWriter">
<title>aws_sdk_rust::aws::common::common::KeyCountWriter - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../../normalize.css">
<link rel="stylesheet" type="text/css" href="../../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../../main.css">
<link rel="shortcut icon" href="https://lambdastackio.github.io/static/images/favicon.ico">
</head>
<body class="rustdoc struct">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../../../aws_sdk_rust/index.html'><img src='https://lambdastackio.github.io/static/images/lambdastack-200x200.png' alt='logo' width='100'></a>
<p class='location'>Struct KeyCountWriter</p><div class="block items"><ul><li><a href="#methods">Methods</a></li></ul></div><p class='location'><a href='../../../index.html'>aws_sdk_rust</a>::<wbr><a href='../../index.html'>aws</a>::<wbr><a href='../index.html'>common</a>::<wbr><a href='index.html'>common</a></p><script>window.sidebarCurrent = {name: 'KeyCountWriter', ty: 'struct', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content">
<h1 class='fqn'><span class='in-band'>Struct <a href='../../../index.html'>aws_sdk_rust</a>::<wbr><a href='../../index.html'>aws</a>::<wbr><a href='../index.html'>common</a>::<wbr><a href='index.html'>common</a>::<wbr><a class="struct" href=''>KeyCountWriter</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../../../../src/aws_sdk_rust/aws/common/common.rs.html#83' title='goto source code'>[src]</a></span></h1>
<pre class='rust struct'>pub struct KeyCountWriter;</pre><div class='docblock'><p>Write <code>KeyCount</code> contents to a <code>SignedRequest</code></p>
</div><h2 id='methods'>Methods</h2><h3 class='impl'><span class='in-band'><code>impl <a class="struct" href="../../../../aws_sdk_rust/aws/common/common/struct.KeyCountWriter.html" title="struct aws_sdk_rust::aws::common::common::KeyCountWriter">KeyCountWriter</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../../../../src/aws_sdk_rust/aws/common/common.rs.html#256-260' title='goto source code'>[src]</a></span></h3>
<div class='impl-items'><h4 id='method.write_params' class="method"><span id='write_params.v' class='invisible'><code>fn <a href='#method.write_params' class='fnname'>write_params</a>(params: &mut <a class="type" href="../../../../aws_sdk_rust/aws/common/params/type.Params.html" title="type aws_sdk_rust::aws::common::params::Params">Params</a>, name: &<a class="primitive" href="https://doc.rust-lang.org/nightly/std/primitive.str.html">str</a>, obj: &<a class="type" href="../../../../aws_sdk_rust/aws/common/common/type.KeyCount.html" title="type aws_sdk_rust::aws::common::common::KeyCount">KeyCount</a>)</code></span></h4>
</div></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../../";
window.currentCrate = "aws_sdk_rust";
</script>
<script src="../../../../main.js"></script>
<script defer src="../../../../search-index.js"></script>
</body>
</html> | lambdastackio/aws-sdk-rust | docs/aws_sdk_rust/aws/common/common/struct.KeyCountWriter.html | HTML | apache-2.0 | 5,940 |
<!-- About Section -->
<section id="about" class="container content-section text-center">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<h2>What We Do</h2>
<p>The Sophia Project is part of a nationwide action initiative designed to empower students to take charge of their own education.</p>
<h4>face the challenges of living & working in the 21st century</h4>
<p>Come together with students of all ages and majors to find out what the teaching and learning scholars already know about your college experience;<br> <strong>it’s not enough to just get a degree anymore.</strong></p>
<h4>Learn the Behind the Scenes of College</h4>
<p>Through a process of lessons, discussion, and the careful guidance of mentors, TSP helps students expand their perspective on college and beyond. We help passionate students develop intellectual flexibility, encounter new perspectives, and connect with new people and opportunities.</p>
<p>Our goal is to empower students to embrace their passion and potential on a deeper level by exciting curiosity, encouraging exposure to new ideas, and sparking engagement in a contemporary world.</p>
</div>
</div>
</section>
| emutsp/emutsp.github.io | _includes/about.html | HTML | apache-2.0 | 1,325 |
package org.hl7.v3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for PRPA_MT201306UV02.MatchAlgorithm complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PRPA_MT201306UV02.MatchAlgorithm">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{urn:hl7-org:v3}InfrastructureRootElements"/>
* <element name="value" type="{urn:hl7-org:v3}ANY"/>
* <element name="semanticsText" type="{urn:hl7-org:v3}st"/>
* </sequence>
* <attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/>
* <attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PRPA_MT201306UV02.MatchAlgorithm", propOrder = {
"realmCode",
"typeId",
"templateId",
"value",
"semanticsText"
})
public class PRPAMT201306UV02MatchAlgorithm {
protected List<CS> realmCode;
protected II typeId;
protected List<II> templateId;
@XmlElement(required = true)
protected ANY value;
@XmlElement(required = true)
protected String semanticsText;
@XmlAttribute(name = "nullFlavor")
protected List<String> nullFlavor;
/**
* Gets the value of the realmCode property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the realmCode property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRealmCode().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CS }
*
*
*/
public List<CS> getRealmCode() {
if (realmCode == null) {
realmCode = new ArrayList<CS>();
}
return this.realmCode;
}
/**
* Gets the value of the typeId property.
*
* @return
* possible object is
* {@link II }
*
*/
public II getTypeId() {
return typeId;
}
/**
* Sets the value of the typeId property.
*
* @param value
* allowed object is
* {@link II }
*
*/
public void setTypeId(II value) {
this.typeId = value;
}
/**
* Gets the value of the templateId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the templateId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTemplateId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link II }
*
*
*/
public List<II> getTemplateId() {
if (templateId == null) {
templateId = new ArrayList<II>();
}
return this.templateId;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link ANY }
*
*/
public ANY getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link ANY }
*
*/
public void setValue(ANY value) {
this.value = value;
}
/**
* Gets the value of the semanticsText property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSemanticsText() {
return semanticsText;
}
/**
* Sets the value of the semanticsText property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSemanticsText(String value) {
this.semanticsText = value;
}
/**
* Gets the value of the nullFlavor property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nullFlavor property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNullFlavor().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNullFlavor() {
if (nullFlavor == null) {
nullFlavor = new ArrayList<String>();
}
return this.nullFlavor;
}
}
| KRMAssociatesInc/eHMP | lib/mvi/org/hl7/v3/PRPAMT201306UV02MatchAlgorithm.java | Java | apache-2.0 | 5,669 |
package org.nkumar.ssql.model;
public abstract class CreateEntityStatement implements DdlStatement
{
protected final String name;
protected Comment[] comments;
protected PlaceHolder openingPlaceHolder;
protected PlaceHolder closingPlaceHolder;
protected CreateEntityStatement(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public Comment[] getComments()
{
return comments;
}
public void setComments(Comment[] comments)
{
this.comments = comments;
}
public PlaceHolder getOpeningPlaceHolder()
{
return openingPlaceHolder;
}
public void setOpeningPlaceHolder(PlaceHolder openingPlaceHolder)
{
this.openingPlaceHolder = openingPlaceHolder;
}
public PlaceHolder getClosingPlaceHolder()
{
return closingPlaceHolder;
}
public void setClosingPlaceHolder(PlaceHolder closingPlaceHolder)
{
this.closingPlaceHolder = closingPlaceHolder;
}
}
| knishant/ssql | src/main/java/org/nkumar/ssql/model/CreateEntityStatement.java | Java | apache-2.0 | 1,045 |
# How to install Obdi from source
This is currently the recommended way to install Obdi.
## Install Obdi on CentOS 7
Follow these instructions to get Obdi installed on Centos 7. Broadly,
installation involves:
1. Install OS.
2. Download Obdi source using Git.
3. Run a script to create an RPM.
4. Install that RPM.
The RPM could be stored in a yum repository on the network to make
updating the Obdi master and worker(s) easy.
### Install OS
This can be done in many ways. The video gives an example of how to accomplish
this task using the Amazon AWS management console.
<video src="/videos/centos7install_installos.webm" style="width: 100%" controls preload></video>
### Download Obdi source using Git
Now log into the new Linux box and type, or copy/paste, the next commands
into the linux terminal.
Switch user to the super user:
```
sudo su
```
Go to your home directory:
```
cd
```
Install the [EPEL](https://fedoraproject.org/wiki/EPEL) repository so that
extra dependencies can be installed:
```
rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
```
Install some dependencies:
```
yum install rpmdevtools gcc golang tar git
```
Download obdi using Git:
```
git clone https://github.com/mclarkson/obdi.git
```
The following video shows the previous commands being run.
<video src="/videos/centos7install_downloadsource.webm" style="width: 100%" controls preload></video>
### Run a script to create an RPM
Build the RPM:
```
cd obdi
./dist/jenkins-build-redhat7.sh
```
The following video shows the build in action.
<video src="/videos/centos7install_runscript.webm" style="width: 100%" controls preload></video>
### Install that RPM
Find the RPM files:
```
cd ~/obdi
TheRpm=$(find rpmbuild/RPMS -name "*.rpm")
echo $TheRpm
```
Finally, so long as the last echo line, above, managed to
output the location then install the RPM:
```
rpm -ivh $TheRpm
```
And here's the video for this step:
<video src="/videos/centos7install_installrpm.webm" style="width: 100%" controls preload></video>
To start obdi:
```
systemctl start obdi
systemctl start obdi-worker
```
If you installed Centos 7 in Amazon, as shown at the top of this page, then you will probably need to open the HTTPS port 443 in the AWS EC2 security group using the Amazon AWS management console, and also in the Centos 7 virtual machine like so:
```
# -- IF THIS IS AN AMAZON INSTANCE USING OFFICIAL CENTOS 7 --
# -- NOTE THAT I DID NOT NEED TO DO THIS! MAYBE YOU WILL? --
# -- CHECK 'iptables -L' AND IF EMPTY DON'T DO THE FOLLOWING --
# Get the line number of the last item in the INPUT chain, minus 1
num=$(iptables -L INPUT --line-numbers | tail -1 | awk '{print $1-1}')
# Then insert before the last item
iptables -I INPUT $num -p tcp -m tcp --dport 443 -j ACCEPT
# And make it survive reboots
service iptables save
```
Now you can test the Obdi user interfaces by opening your Web Browser and connecting to 'https://MACHINE_ADDRESS/manager/run' and 'https//MACHINE_ADDRESS/manager/admin'.
That's it!
| mclarkson/obdi | doc/Obdi_Core_Centos_7_Installation.md | Markdown | apache-2.0 | 3,050 |
import inspect
import json
import os
import random
import subprocess
import time
import requests
import ast
import paramiko
import rancher
from rancher import ApiError
from lib.aws import AmazonWebServices
DEFAULT_TIMEOUT = 120
DEFAULT_MULTI_CLUSTER_APP_TIMEOUT = 300
CATTLE_TEST_URL = os.environ.get('CATTLE_TEST_URL', "http://localhost:80")
CATTLE_API_URL = CATTLE_TEST_URL + "/v3"
ADMIN_TOKEN = os.environ.get('ADMIN_TOKEN', "None")
kube_fname = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"k8s_kube_config")
MACHINE_TIMEOUT = float(os.environ.get('RANCHER_MACHINE_TIMEOUT', "1200"))
TEST_IMAGE = os.environ.get('RANCHER_TEST_IMAGE', "sangeetha/mytestcontainer")
CLUSTER_NAME = os.environ.get("RANCHER_CLUSTER_NAME", "")
CLUSTER_NAME_2 = os.environ.get("RANCHER_CLUSTER_NAME_2", "")
RANCHER_CLEANUP_CLUSTER = \
ast.literal_eval(os.environ.get('RANCHER_CLEANUP_CLUSTER', "True"))
env_file = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"rancher_env.config")
def random_str():
return 'random-{0}-{1}'.format(random_num(), int(time.time()))
def random_num():
return random.randint(0, 1000000)
def random_int(start, end):
return random.randint(start, end)
def random_test_name(name="test"):
return name + "-" + str(random_int(10000, 99999))
def get_admin_client():
return rancher.Client(url=CATTLE_API_URL, token=ADMIN_TOKEN, verify=False)
def get_client_for_token(token):
return rancher.Client(url=CATTLE_API_URL, token=token, verify=False)
def get_project_client_for_token(project, token):
p_url = project.links['self'] + '/schemas'
p_client = rancher.Client(url=p_url, token=token, verify=False)
return p_client
def get_cluster_client_for_token(cluster, token):
c_url = cluster.links['self'] + '/schemas'
c_client = rancher.Client(url=c_url, token=token, verify=False)
return c_client
def up(cluster, token):
c_url = cluster.links['self'] + '/schemas'
c_client = rancher.Client(url=c_url, token=token, verify=False)
return c_client
def wait_state(client, obj, state, timeout=DEFAULT_TIMEOUT):
wait_for(lambda: client.reload(obj).state == state, timeout)
return client.reload(obj)
def wait_for_condition(client, resource, check_function, fail_handler=None,
timeout=DEFAULT_TIMEOUT):
start = time.time()
resource = client.reload(resource)
while not check_function(resource):
if time.time() - start > timeout:
exceptionMsg = 'Timeout waiting for ' + resource.baseType + \
' to satisfy condition: ' + \
inspect.getsource(check_function)
if fail_handler:
exceptionMsg = exceptionMsg + fail_handler(resource)
raise Exception(exceptionMsg)
time.sleep(.5)
resource = client.reload(resource)
return resource
def wait_for(callback, timeout=DEFAULT_TIMEOUT, timeout_message=None):
start = time.time()
ret = callback()
while ret is None or ret is False:
time.sleep(.5)
if time.time() - start > timeout:
if timeout_message:
raise Exception(timeout_message)
else:
raise Exception('Timeout waiting for condition')
ret = callback()
return ret
def random_name():
return "test" + "-" + str(random_int(10000, 99999))
def create_project_and_ns(token, cluster, project_name=None, ns_name=None):
client = get_client_for_token(token)
p = create_project(client, cluster, project_name)
c_client = get_cluster_client_for_token(cluster, token)
ns = create_ns(c_client, cluster, p, ns_name)
return p, ns
def create_project(client, cluster, project_name=None):
if project_name is None:
project_name = random_name()
p = client.create_project(name=project_name,
clusterId=cluster.id)
time.sleep(5)
p = wait_until_available(client, p)
assert p.state == 'active'
return p
def create_project_with_pspt(client, cluster, pspt):
p = client.create_project(name=random_name(),
clusterId=cluster.id)
p = wait_until_available(client, p)
assert p.state == 'active'
return set_pspt_for_project(p, client, pspt)
def set_pspt_for_project(project, client, pspt):
project.setpodsecuritypolicytemplate(podSecurityPolicyTemplateId=pspt.id)
project = wait_until_available(client, project)
assert project.state == 'active'
return project
def create_ns(client, cluster, project, ns_name=None):
if ns_name is None:
ns_name = random_name()
ns = client.create_namespace(name=ns_name,
clusterId=cluster.id,
projectId=project.id)
wait_for_ns_to_become_active(client, ns)
ns = client.reload(ns)
assert ns.state == 'active'
return ns
def assign_members_to_cluster(client, user, cluster, role_template_id):
crtb = client.create_cluster_role_template_binding(
clusterId=cluster.id,
roleTemplateId=role_template_id,
subjectKind="User",
userId=user.id)
return crtb
def assign_members_to_project(client, user, project, role_template_id):
prtb = client.create_project_role_template_binding(
projectId=project.id,
roleTemplateId=role_template_id,
subjectKind="User",
userId=user.id)
return prtb
def change_member_role_in_cluster(client, user, crtb, role_template_id):
crtb = client.update(
crtb,
roleTemplateId=role_template_id,
userId=user.id)
return crtb
def change_member_role_in_project(client, user, prtb, role_template_id):
prtb = client.update(
prtb,
roleTemplateId=role_template_id,
userId=user.id)
return prtb
def create_kubeconfig(cluster):
generateKubeConfigOutput = cluster.generateKubeconfig()
print(generateKubeConfigOutput.config)
file = open(kube_fname, "w")
file.write(generateKubeConfigOutput.config)
file.close()
def validate_psp_error_worklaod(p_client, workload, error_message):
workload = wait_for_wl_transitioning(p_client, workload)
assert workload.state == "updating"
assert workload.transitioning == "error"
print(workload.transitioningMessage)
assert error_message in workload.transitioningMessage
def validate_workload(p_client, workload, type, ns_name, pod_count=1,
wait_for_cron_pods=60):
workload = wait_for_wl_to_active(p_client, workload)
assert workload.state == "active"
# For cronjob, wait for the first pod to get created after
# scheduled wait time
if type == "cronJob":
time.sleep(wait_for_cron_pods)
pods = p_client.list_pod(workloadId=workload.id).data
assert len(pods) == pod_count
for pod in pods:
wait_for_pod_to_running(p_client, pod)
wl_result = execute_kubectl_cmd(
"get " + type + " " + workload.name + " -n " + ns_name)
if type == "deployment" or type == "statefulSet":
assert wl_result["status"]["readyReplicas"] == pod_count
if type == "daemonSet":
assert wl_result["status"]["currentNumberScheduled"] == pod_count
if type == "cronJob":
assert len(wl_result["status"]["active"]) >= pod_count
return
for key, value in workload.workloadLabels.items():
label = key + "=" + value
get_pods = "get pods -l" + label + " -n " + ns_name
pods_result = execute_kubectl_cmd(get_pods)
assert len(pods_result["items"]) == pod_count
for pod in pods_result["items"]:
assert pod["status"]["phase"] == "Running"
return pods_result["items"]
def validate_workload_with_sidekicks(p_client, workload, type, ns_name,
pod_count=1):
workload = wait_for_wl_to_active(p_client, workload)
assert workload.state == "active"
pods = wait_for_pods_in_workload(p_client, workload, pod_count)
assert len(pods) == pod_count
for pod in pods:
wait_for_pod_to_running(p_client, pod)
wl_result = execute_kubectl_cmd(
"get " + type + " " + workload.name + " -n " + ns_name)
assert wl_result["status"]["readyReplicas"] == pod_count
for key, value in workload.workloadLabels.items():
label = key + "=" + value
get_pods = "get pods -l" + label + " -n " + ns_name
execute_kubectl_cmd(get_pods)
pods_result = execute_kubectl_cmd(get_pods)
assert len(pods_result["items"]) == pod_count
for pod in pods_result["items"]:
assert pod["status"]["phase"] == "Running"
assert len(pod["status"]["containerStatuses"]) == 2
assert "running" in pod["status"]["containerStatuses"][0]["state"]
assert "running" in pod["status"]["containerStatuses"][1]["state"]
def validate_workload_paused(p_client, workload, expectedstatus):
workloadStatus = p_client.list_workload(uuid=workload.uuid).data[0].paused
assert workloadStatus == expectedstatus
def validate_pod_images(expectedimage, workload, ns_name):
for key, value in workload.workloadLabels.items():
label = key + "=" + value
get_pods = "get pods -l" + label + " -n " + ns_name
pods = execute_kubectl_cmd(get_pods)
for pod in pods["items"]:
assert pod["spec"]["containers"][0]["image"] == expectedimage
def validate_pods_are_running_by_id(expectedpods, workload, ns_name):
for key, value in workload.workloadLabels.items():
label = key + "=" + value
get_pods = "get pods -l" + label + " -n " + ns_name
pods = execute_kubectl_cmd(get_pods)
curpodnames = []
for pod in pods["items"]:
curpodnames.append(pod["metadata"]["name"])
for expectedpod in expectedpods["items"]:
assert expectedpod["metadata"]["name"] in curpodnames
def validate_workload_image(client, workload, expectedImage, ns):
workload = client.list_workload(uuid=workload.uuid).data[0]
assert workload.containers[0].image == expectedImage
validate_pod_images(expectedImage, workload, ns.name)
def execute_kubectl_cmd(cmd, json_out=True, stderr=False):
command = 'kubectl --kubeconfig {0} {1}'.format(
kube_fname, cmd)
if json_out:
command += ' -o json'
if stderr:
result = run_command_with_stderr(command)
else:
result = run_command(command)
if json_out:
result = json.loads(result)
print(result)
return result
def run_command(command):
return subprocess.check_output(command, shell=True, text=True)
def run_command_with_stderr(command):
try:
output = subprocess.check_output(command, shell=True,
stderr=subprocess.PIPE)
returncode = 0
except subprocess.CalledProcessError as e:
output = e.output
returncode = e.returncode
print(returncode)
return output
def wait_for_wl_to_active(client, workload, timeout=DEFAULT_TIMEOUT):
start = time.time()
workloads = client.list_workload(uuid=workload.uuid).data
assert len(workloads) == 1
wl = workloads[0]
while wl.state != "active":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
workloads = client.list_workload(uuid=workload.uuid).data
assert len(workloads) == 1
wl = workloads[0]
return wl
def wait_for_ingress_to_active(client, ingress, timeout=DEFAULT_TIMEOUT):
start = time.time()
ingresses = client.list_ingress(uuid=ingress.uuid).data
assert len(ingresses) == 1
wl = ingresses[0]
while wl.state != "active":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
ingresses = client.list_ingress(uuid=ingress.uuid).data
assert len(ingresses) == 1
wl = ingresses[0]
return wl
def wait_for_wl_transitioning(client, workload, timeout=DEFAULT_TIMEOUT,
state="error"):
start = time.time()
workloads = client.list_workload(uuid=workload.uuid).data
assert len(workloads) == 1
wl = workloads[0]
while wl.transitioning != state:
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
workloads = client.list_workload(uuid=workload.uuid).data
assert len(workloads) == 1
wl = workloads[0]
return wl
def wait_for_pod_to_running(client, pod, timeout=DEFAULT_TIMEOUT):
start = time.time()
pods = client.list_pod(uuid=pod.uuid).data
assert len(pods) == 1
p = pods[0]
while p.state != "running":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
pods = client.list_pod(uuid=pod.uuid).data
assert len(pods) == 1
p = pods[0]
return p
def get_schedulable_nodes(cluster):
client = get_admin_client()
nodes = client.list_node(clusterId=cluster.id).data
schedulable_nodes = []
for node in nodes:
if node.worker:
schedulable_nodes.append(node)
return schedulable_nodes
def get_role_nodes(cluster, role):
etcd_nodes = []
control_nodes = []
worker_nodes = []
node_list = []
client = get_admin_client()
nodes = client.list_node(clusterId=cluster.id).data
for node in nodes:
if node.etcd:
etcd_nodes.append(node)
if node.controlPlane:
control_nodes.append(node)
if node.worker:
worker_nodes.append(node)
if role == "etcd":
node_list = etcd_nodes
if role == "control":
node_list = control_nodes
if role == "worker":
node_list = worker_nodes
return node_list
def validate_ingress(p_client, cluster, workloads, host, path,
insecure_redirect=False):
time.sleep(10)
curl_args = " "
if (insecure_redirect):
curl_args = " -L --insecure "
if len(host) > 0:
curl_args += " --header 'Host: " + host + "'"
nodes = get_schedulable_nodes(cluster)
target_name_list = get_target_names(p_client, workloads)
for node in nodes:
host_ip = node.externalIpAddress
cmd = curl_args + " http://" + host_ip + path
validate_http_response(cmd, target_name_list)
def validate_ingress_using_endpoint(p_client, ingress, workloads,
timeout=300):
target_name_list = get_target_names(p_client, workloads)
start = time.time()
fqdn_available = False
url = None
while not fqdn_available:
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for endpoint to be available")
time.sleep(.5)
ingress_list = p_client.list_ingress(uuid=ingress.uuid).data
assert len(ingress_list) == 1
ingress = ingress_list[0]
if hasattr(ingress, 'publicEndpoints'):
for public_endpoint in ingress.publicEndpoints:
if public_endpoint["hostname"].startswith(ingress.name):
fqdn_available = True
url = \
public_endpoint["protocol"].lower() + "://" + \
public_endpoint["hostname"]
if "path" in public_endpoint.keys():
url += public_endpoint["path"]
time.sleep(10)
validate_http_response(url, target_name_list)
def get_target_names(p_client, workloads):
pods = []
for workload in workloads:
pod_list = p_client.list_pod(workloadId=workload.id).data
pods.extend(pod_list)
target_name_list = []
for pod in pods:
target_name_list.append(pod.name)
print("target name list:" + str(target_name_list))
return target_name_list
def get_endpoint_url_for_workload(p_client, workload, timeout=600):
fqdn_available = False
url = ""
start = time.time()
while not fqdn_available:
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for endpoint to be available")
time.sleep(.5)
workload_list = p_client.list_workload(uuid=workload.uuid).data
assert len(workload_list) == 1
workload = workload_list[0]
if hasattr(workload, 'publicEndpoints'):
assert len(workload.publicEndpoints) > 0
url = "http://"
url = url + workload.publicEndpoints[0]["addresses"][0] + ":"
url = url + str(workload.publicEndpoints[0]["port"])
fqdn_available = True
return url
def wait_until_lb_is_active(url, timeout=300):
start = time.time()
while check_for_no_access(url):
time.sleep(.5)
print("No access yet")
if time.time() - start > timeout:
raise Exception('Timed out waiting for LB to become active')
return
def check_for_no_access(url, verify=False):
try:
requests.get(url, verify=verify)
return False
except requests.ConnectionError:
print("Connection Error - " + url)
return True
def wait_until_active(url, timeout=120):
start = time.time()
while check_for_no_access(url):
time.sleep(.5)
print("No access yet")
if time.time() - start > timeout:
raise Exception('Timed out waiting for url '
'to become active')
return
def validate_http_response(cmd, target_name_list, client_pod=None):
if client_pod is None and cmd.startswith("http://"):
wait_until_active(cmd, 60)
target_hit_list = target_name_list[:]
count = 5 * len(target_name_list)
for i in range(1, count):
if len(target_hit_list) == 0:
break
if client_pod is None:
curl_cmd = "curl " + cmd
result = run_command(curl_cmd)
else:
wget_cmd = "wget -qO- " + cmd
result = kubectl_pod_exec(client_pod, wget_cmd)
result = result.decode()
result = result.rstrip()
print("cmd: \t" + cmd)
print("result: \t" + result)
assert result in target_name_list
if result in target_hit_list:
target_hit_list.remove(result)
print("After removing all, the rest is: ", target_hit_list)
assert len(target_hit_list) == 0
def validate_cluster(client, cluster, intermediate_state="provisioning",
check_intermediate_state=True, skipIngresscheck=True,
nodes_not_in_active_state=[], k8s_version=""):
cluster = validate_cluster_state(
client, cluster,
check_intermediate_state=check_intermediate_state,
intermediate_state=intermediate_state,
nodes_not_in_active_state=nodes_not_in_active_state)
# Create Daemon set workload and have an Ingress with Workload
# rule pointing to this daemonset
create_kubeconfig(cluster)
if k8s_version != "":
check_cluster_version(cluster, k8s_version)
if hasattr(cluster, 'rancherKubernetesEngineConfig'):
check_cluster_state(len(get_role_nodes(cluster, "etcd")))
project, ns = create_project_and_ns(ADMIN_TOKEN, cluster)
p_client = get_project_client_for_token(project, ADMIN_TOKEN)
con = [{"name": "test1",
"image": TEST_IMAGE}]
name = random_test_name("default")
workload = p_client.create_workload(name=name,
containers=con,
namespaceId=ns.id,
daemonSetConfig={})
validate_workload(p_client, workload, "daemonSet", ns.name,
len(get_schedulable_nodes(cluster)))
if not skipIngresscheck:
host = "test" + str(random_int(10000, 99999)) + ".com"
path = "/name.html"
rule = {"host": host,
"paths":
[{"workloadIds": [workload.id], "targetPort": "80"}]}
ingress = p_client.create_ingress(name=name,
namespaceId=ns.id,
rules=[rule])
wait_for_ingress_to_active(p_client, ingress)
validate_ingress(p_client, cluster, [workload], host, path)
return cluster
def check_cluster_version(cluster, version):
cluster_k8s_version = \
cluster.appliedSpec["rancherKubernetesEngineConfig"][
"kubernetesVersion"]
assert cluster_k8s_version == version, \
"cluster_k8s_version: " + cluster_k8s_version + \
" Expected: " + version
expected_k8s_version = version[:version.find("-")]
k8s_version = execute_kubectl_cmd("version")
kubectl_k8s_version = k8s_version["serverVersion"]["gitVersion"]
assert kubectl_k8s_version == expected_k8s_version, \
"kubectl version: " + kubectl_k8s_version + \
" Expected: " + expected_k8s_version
def check_cluster_state(etcd_count):
css_resp = execute_kubectl_cmd("get cs")
css = css_resp["items"]
components = ["scheduler", "controller-manager"]
for i in range(0, etcd_count):
components.append("etcd-" + str(i))
print("components to check - " + str(components))
for cs in css:
component_name = cs["metadata"]["name"]
assert component_name in components
components.remove(component_name)
assert cs["conditions"][0]["status"] == "True"
assert cs["conditions"][0]["type"] == "Healthy"
assert len(components) == 0
def validate_dns_record(pod, record, expected):
# requires pod with `dig` available - TEST_IMAGE
host = '{0}.{1}.svc.cluster.local'.format(
record["name"], record["namespaceId"])
validate_dns_entry(pod, host, expected)
def validate_dns_entry(pod, host, expected):
# requires pod with `dig` available - TEST_IMAGE
cmd = 'ping -c 1 -W 1 {0}'.format(host)
ping_output = kubectl_pod_exec(pod, cmd)
ping_validation_pass = False
for expected_value in expected:
if expected_value in str(ping_output):
ping_validation_pass = True
break
assert ping_validation_pass is True
assert " 0% packet loss" in str(ping_output)
dig_cmd = 'dig {0} +short'.format(host)
dig_output = kubectl_pod_exec(pod, dig_cmd)
for expected_value in expected:
assert expected_value in str(dig_output)
def wait_for_nodes_to_become_active(client, cluster, exception_list=[],
retry_count=0):
nodes = client.list_node(clusterId=cluster.id).data
node_auto_deleted = False
for node in nodes:
if node.requestedHostname not in exception_list:
node = wait_for_node_status(client, node, "active")
if node is None:
print("Need to re-evalauate new node list")
node_auto_deleted = True
retry_count += 1
print("Retry Count:" + str(retry_count))
if node_auto_deleted and retry_count < 5:
wait_for_nodes_to_become_active(client, cluster, exception_list,
retry_count)
def wait_for_node_status(client, node, state):
uuid = node.uuid
start = time.time()
nodes = client.list_node(uuid=uuid).data
node_count = len(nodes)
# Handle the case of nodes getting auto deleted when they are part of
# nodepools
if node_count == 1:
node_status = nodes[0].state
else:
print("Node does not exist anymore -" + uuid)
return None
while node_status != state:
if time.time() - start > MACHINE_TIMEOUT:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(5)
nodes = client.list_node(uuid=uuid).data
node_count = len(nodes)
if node_count == 1:
node_status = nodes[0].state
else:
print("Node does not exist anymore -" + uuid)
return None
return node
def wait_for_node_to_be_deleted(client, node, timeout=300):
uuid = node.uuid
start = time.time()
nodes = client.list_node(uuid=uuid).data
node_count = len(nodes)
while node_count != 0:
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
nodes = client.list_node(uuid=uuid).data
node_count = len(nodes)
def wait_for_cluster_node_count(client, cluster, expected_node_count,
timeout=300):
start = time.time()
nodes = client.list_node(clusterId=cluster.id).data
node_count = len(nodes)
while node_count != expected_node_count:
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
nodes = client.list_node(clusterId=cluster.id).data
node_count = len(nodes)
def get_custom_host_registration_cmd(client, cluster, roles, node):
allowed_roles = ["etcd", "worker", "controlplane"]
cluster_tokens = client.list_cluster_registration_token(
clusterId=cluster.id).data
if len(cluster_tokens) > 0:
cluster_token = cluster_tokens[0]
else:
cluster_token = create_custom_host_registration_token(client, cluster)
cmd = cluster_token.nodeCommand
for role in roles:
assert role in allowed_roles
cmd += " --" + role
additional_options = " --address " + node.public_ip_address + \
" --internal-address " + node.private_ip_address
cmd += additional_options
return cmd
def create_custom_host_registration_token(client, cluster):
cluster_token = client.create_cluster_registration_token(
clusterId=cluster.id)
cluster_token = client.wait_success(cluster_token)
assert cluster_token.state == 'active'
return cluster_token
def get_cluster_type(client, cluster):
cluster_configs = [
"amazonElasticContainerServiceConfig",
"azureKubernetesServiceConfig",
"googleKubernetesEngineConfig",
"rancherKubernetesEngineConfig"
]
if "rancherKubernetesEngineConfig" in cluster:
nodes = client.list_node(clusterId=cluster.id).data
if len(nodes) > 0:
if nodes[0].nodeTemplateId is None:
return "Custom"
for cluster_config in cluster_configs:
if cluster_config in cluster:
return cluster_config
return "Imported"
def delete_cluster(client, cluster):
nodes = client.list_node(clusterId=cluster.id).data
# Delete Cluster
client.delete(cluster)
# Delete nodes(in cluster) from AWS for Imported and Custom Cluster
if (len(nodes) > 0):
cluster_type = get_cluster_type(client, cluster)
print(cluster_type)
if get_cluster_type(client, cluster) in ["Imported", "Custom"]:
nodes = client.list_node(clusterId=cluster.id).data
filters = [
{'Name': 'tag:Name',
'Values': ['testcustom*', 'teststess*']}]
ip_filter = {}
ip_list = []
ip_filter['Name'] = \
'network-interface.addresses.association.public-ip'
ip_filter['Values'] = ip_list
filters.append(ip_filter)
for node in nodes:
ip_list.append(node.externalIpAddress)
assert len(ip_filter) > 0
print(ip_filter)
aws_nodes = AmazonWebServices().get_nodes(filters)
for node in aws_nodes:
print(node.public_ip_address)
AmazonWebServices().delete_nodes(aws_nodes)
def check_connectivity_between_workloads(p_client1, workload1, p_client2,
workload2, allow_connectivity=True):
wl1_pods = p_client1.list_pod(workloadId=workload1.id).data
wl2_pods = p_client2.list_pod(workloadId=workload2.id).data
for pod in wl1_pods:
for o_pod in wl2_pods:
check_connectivity_between_pods(pod, o_pod, allow_connectivity)
def check_connectivity_between_workload_pods(p_client, workload):
pods = p_client.list_pod(workloadId=workload.id).data
for pod in pods:
for o_pod in pods:
check_connectivity_between_pods(pod, o_pod)
def check_connectivity_between_pods(pod1, pod2, allow_connectivity=True):
pod_ip = pod2.status.podIp
cmd = "ping -c 1 -W 1 " + pod_ip
response = kubectl_pod_exec(pod1, cmd)
print("Actual ping Response from " + pod1.name + ":" + str(response))
if allow_connectivity:
assert pod_ip in str(response) and " 0% packet loss" in str(response)
else:
assert pod_ip in str(response) and " 100% packet loss" in str(response)
def kubectl_pod_exec(pod, cmd):
command = "exec " + pod.name + " -n " + pod.namespaceId + " -- " + cmd
return execute_kubectl_cmd(command, json_out=False, stderr=True)
def exec_shell_command(ip, port, cmd, password, user="root", sshKey=None):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if sshKey:
ssh.connect(ip, username=user, key_filename=sshKey, port=port)
else:
ssh.connect(ip, username=user, password=password, port=port)
stdin, stdout, stderr = ssh.exec_command(cmd)
response = stdout.readlines()
return response
def wait_for_ns_to_become_active(client, ns, timeout=DEFAULT_TIMEOUT):
start = time.time()
time.sleep(2)
nss = client.list_namespace(uuid=ns.uuid).data
assert len(nss) == 1
ns = nss[0]
while ns.state != "active":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
nss = client.list_namespace(uuid=ns.uuid).data
assert len(nss) == 1
ns = nss[0]
return ns
def wait_for_pod_images(p_client, workload, ns_name, expectedimage, numofpods,
timeout=DEFAULT_TIMEOUT):
start = time.time()
for key, value in workload.workloadLabels.items():
label = key + "=" + value
get_pods = "get pods -l" + label + " -n " + ns_name
pods = execute_kubectl_cmd(get_pods)
for x in range(0, numofpods - 1):
pod = pods["items"][x]
podimage = pod["spec"]["containers"][0]["image"]
while podimage != expectedimage:
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for correct pod images")
time.sleep(.5)
pods = execute_kubectl_cmd(get_pods)
pod = pods["items"][x]
podimage = pod["spec"]["containers"][0]["image"]
def wait_for_pods_in_workload(p_client, workload, pod_count,
timeout=DEFAULT_TIMEOUT):
start = time.time()
pods = p_client.list_pod(workloadId=workload.id).data
while len(pods) != pod_count:
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
pods = p_client.list_pod(workloadId=workload.id).data
return pods
def get_admin_client_and_cluster():
client = get_admin_client()
if CLUSTER_NAME == "":
clusters = client.list_cluster().data
else:
clusters = client.list_cluster(name=CLUSTER_NAME).data
assert len(clusters) > 0
cluster = clusters[0]
return client, cluster
def validate_cluster_state(client, cluster,
check_intermediate_state=True,
intermediate_state="provisioning",
nodes_not_in_active_state=[]):
if check_intermediate_state:
cluster = wait_for_condition(
client, cluster,
lambda x: x.state == intermediate_state,
lambda x: 'State is: ' + x.state,
timeout=MACHINE_TIMEOUT)
assert cluster.state == intermediate_state
cluster = wait_for_condition(
client, cluster,
lambda x: x.state == "active",
lambda x: 'State is: ' + x.state,
timeout=MACHINE_TIMEOUT)
assert cluster.state == "active"
wait_for_nodes_to_become_active(client, cluster,
exception_list=nodes_not_in_active_state)
return cluster
def wait_until_available(client, obj, timeout=DEFAULT_TIMEOUT):
start = time.time()
sleep = 0.01
while True:
time.sleep(sleep)
sleep *= 2
if sleep > 2:
sleep = 2
try:
obj = client.reload(obj)
except ApiError as e:
if e.error.status != 403:
raise e
else:
return obj
delta = time.time() - start
if delta > timeout:
msg = 'Timeout waiting for [{}:{}] for condition after {}' \
' seconds'.format(obj.type, obj.id, delta)
raise Exception(msg)
def delete_node(aws_nodes):
for node in aws_nodes:
AmazonWebServices().delete_node(node)
def cluster_cleanup(client, cluster, aws_nodes=None):
if RANCHER_CLEANUP_CLUSTER:
client.delete(cluster)
if aws_nodes is not None:
delete_node(aws_nodes)
else:
env_details = "env.CATTLE_TEST_URL='" + CATTLE_TEST_URL + "'\n"
env_details += "env.ADMIN_TOKEN='" + ADMIN_TOKEN + "'\n"
env_details += "env.CLUSTER_NAME='" + cluster.name + "'\n"
create_config_file(env_details)
def create_config_file(env_details):
file = open(env_file, "w")
file.write(env_details)
file.close()
def validate_hostPort(p_client, workload, source_port, cluster):
pods = p_client.list_pod(workloadId=workload.id).data
nodes = get_schedulable_nodes(cluster)
for node in nodes:
target_name_list = []
for pod in pods:
print(pod.nodeId + " check " + node.id)
if pod.nodeId == node.id:
target_name_list.append(pod.name)
break
if len(target_name_list) > 0:
host_ip = node.externalIpAddress
curl_cmd = " http://" + host_ip + ":" + \
str(source_port) + "/name.html"
validate_http_response(curl_cmd, target_name_list)
def validate_lb(p_client, workload):
url = get_endpoint_url_for_workload(p_client, workload)
target_name_list = get_target_names(p_client, [workload])
wait_until_lb_is_active(url)
validate_http_response(url + "/name.html", target_name_list)
def validate_nodePort(p_client, workload, cluster):
get_endpoint_url_for_workload(p_client, workload, 60)
wl = p_client.list_workload(uuid=workload.uuid).data[0]
source_port = wl.publicEndpoints[0]["port"]
nodes = get_schedulable_nodes(cluster)
pods = p_client.list_pod(workloadId=wl.id).data
target_name_list = []
for pod in pods:
target_name_list.append(pod.name)
print("target name list:" + str(target_name_list))
for node in nodes:
host_ip = node.externalIpAddress
curl_cmd = " http://" + host_ip + ":" + \
str(source_port) + "/name.html"
validate_http_response(curl_cmd, target_name_list)
def validate_clusterIp(p_client, workload, cluster_ip, test_pods):
pods = p_client.list_pod(workloadId=workload.id).data
target_name_list = []
for pod in pods:
target_name_list.append(pod["name"])
curl_cmd = "http://" + cluster_ip + "/name.html"
for pod in test_pods:
validate_http_response(curl_cmd, target_name_list, pod)
def wait_for_pv_to_be_available(c_client, pv_object, timeout=DEFAULT_TIMEOUT):
start = time.time()
time.sleep(2)
list = c_client.list_persistent_volume(uuid=pv_object.uuid).data
assert len(list) == 1
pv = list[0]
while pv.state != "available":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to available")
time.sleep(.5)
list = c_client.list_persistent_volume(uuid=pv_object.uuid).data
assert len(list) == 1
pv = list[0]
return pv
def wait_for_pvc_to_be_bound(p_client, pvc_object, timeout=DEFAULT_TIMEOUT):
start = time.time()
time.sleep(2)
list = p_client.list_persistent_volume_claim(uuid=pvc_object.uuid).data
assert len(list) == 1
pvc = list[0]
while pvc.state != "bound":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to bound")
time.sleep(.5)
list = p_client.list_persistent_volume_claim(uuid=pvc_object.uuid).data
assert len(list) == 1
pvc = list[0]
return pvc
def create_wl_with_nfs(p_client, ns_id, pvc_name, wl_name,
mount_path, sub_path, is_daemonSet=False):
volumes = [{"type": "volume",
"name": "vol1",
"persistentVolumeClaim": {
"readOnly": "false",
"type": "persistentVolumeClaimVolumeSource",
"persistentVolumeClaimId": pvc_name
}}]
volumeMounts = [{"readOnly": "False",
"type": "volumeMount",
"mountPath": mount_path,
"subPath": sub_path,
"name": "vol1"
}]
con = [{"name": "test1",
"image": TEST_IMAGE,
"volumeMounts": volumeMounts
}]
if is_daemonSet:
workload = p_client.create_workload(name=wl_name,
containers=con,
namespaceId=ns_id,
volumes=volumes,
daemonSetConfig={})
else:
workload = p_client.create_workload(name=wl_name,
containers=con,
namespaceId=ns_id,
volumes=volumes)
return workload
def write_content_to_file(pod, content, filename):
cmd_write = "/bin/bash -c 'echo {1} > {0}'".format(filename, content)
output = kubectl_pod_exec(pod, cmd_write)
assert output.strip().decode('utf-8') == ""
def validate_file_content(pod, content, filename):
cmd_get_content = "/bin/bash -c 'cat {0}' ".format(filename)
output = kubectl_pod_exec(pod, cmd_get_content)
assert output.strip().decode('utf-8') == content
def wait_for_mcapp_to_active(client, multiClusterApp,
timeout=DEFAULT_MULTI_CLUSTER_APP_TIMEOUT):
time.sleep(5)
mcapps = client.list_multiClusterApp(uuid=multiClusterApp.uuid,
name=multiClusterApp.name).data
start = time.time()
assert len(mcapps) == 1, "Cannot find multi cluster app"
mapp = mcapps[0]
while mapp.state != "active":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
multiclusterapps = client.list_multiClusterApp(
uuid=multiClusterApp.uuid, name=multiClusterApp.name).data
assert len(multiclusterapps) == 1
mapp = multiclusterapps[0]
return mapp
def wait_for_app_to_active(client, app_id,
timeout=DEFAULT_MULTI_CLUSTER_APP_TIMEOUT):
app_data = client.list_app(name=app_id).data
start = time.time()
assert len(app_data) == 1, "Cannot find app"
application = app_data[0]
while application.state != "active":
if time.time() - start > timeout:
raise AssertionError(
"Timed out waiting for state to get to active")
time.sleep(.5)
app = client.list_app(name=app_id).data
assert len(app) == 1
application = app[0]
return application
def validate_response_app_endpoint(p_client, appId):
ingress_list = p_client.list_ingress(namespaceId=appId).data
assert len(ingress_list) == 1
ingress = ingress_list[0]
if hasattr(ingress, 'publicEndpoints'):
for public_endpoint in ingress.publicEndpoints:
url = \
public_endpoint["protocol"].lower() + "://" + \
public_endpoint["hostname"]
print(url)
try:
r = requests.head(url)
assert r.status_code == 200, \
"Http response is not 200. Failed to launch the app"
except requests.ConnectionError:
print("failed to connect")
assert False, "failed to connect to the app"
| sabiodelhielo/rancher-validation | tests/v3_api/common.py | Python | apache-2.0 | 41,077 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.