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 |
|---|---|---|---|---|---|
/*
* WSO2 API Manager - Publisher API
* This specifies a **RESTful API** for WSO2 **API Manager** - Publisher. Please see [full swagger definition](https://raw.githubusercontent.com/wso2/carbon-apimgt/v6.0.4/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/resources/publisher-api.yaml) of the API which is written using [swagger 2.0](http://swagger.io/) specification.
*
* OpenAPI spec version: v1.0.0
* Contact: architecture@wso2.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.wso2.carbon.apimgt.rest.integration.tests.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
/**
* CORS configuration for the API
*/
@ApiModel(description = "CORS configuration for the API ")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-05-09T06:36:48.873Z")
public class APICorsConfiguration {
@SerializedName("corsConfigurationEnabled")
private Boolean corsConfigurationEnabled = false;
@SerializedName("accessControlAllowOrigins")
private List<String> accessControlAllowOrigins = new ArrayList<String>();
@SerializedName("accessControlAllowCredentials")
private Boolean accessControlAllowCredentials = false;
@SerializedName("accessControlAllowHeaders")
private List<String> accessControlAllowHeaders = new ArrayList<String>();
@SerializedName("accessControlAllowMethods")
private List<String> accessControlAllowMethods = new ArrayList<String>();
public APICorsConfiguration corsConfigurationEnabled(Boolean corsConfigurationEnabled) {
this.corsConfigurationEnabled = corsConfigurationEnabled;
return this;
}
/**
* Get corsConfigurationEnabled
* @return corsConfigurationEnabled
**/
@ApiModelProperty(example = "null", value = "")
public Boolean getCorsConfigurationEnabled() {
return corsConfigurationEnabled;
}
public void setCorsConfigurationEnabled(Boolean corsConfigurationEnabled) {
this.corsConfigurationEnabled = corsConfigurationEnabled;
}
public APICorsConfiguration accessControlAllowOrigins(List<String> accessControlAllowOrigins) {
this.accessControlAllowOrigins = accessControlAllowOrigins;
return this;
}
public APICorsConfiguration addAccessControlAllowOriginsItem(String accessControlAllowOriginsItem) {
this.accessControlAllowOrigins.add(accessControlAllowOriginsItem);
return this;
}
/**
* Get accessControlAllowOrigins
* @return accessControlAllowOrigins
**/
@ApiModelProperty(example = "null", value = "")
public List<String> getAccessControlAllowOrigins() {
return accessControlAllowOrigins;
}
public void setAccessControlAllowOrigins(List<String> accessControlAllowOrigins) {
this.accessControlAllowOrigins = accessControlAllowOrigins;
}
public APICorsConfiguration accessControlAllowCredentials(Boolean accessControlAllowCredentials) {
this.accessControlAllowCredentials = accessControlAllowCredentials;
return this;
}
/**
* Get accessControlAllowCredentials
* @return accessControlAllowCredentials
**/
@ApiModelProperty(example = "null", value = "")
public Boolean getAccessControlAllowCredentials() {
return accessControlAllowCredentials;
}
public void setAccessControlAllowCredentials(Boolean accessControlAllowCredentials) {
this.accessControlAllowCredentials = accessControlAllowCredentials;
}
public APICorsConfiguration accessControlAllowHeaders(List<String> accessControlAllowHeaders) {
this.accessControlAllowHeaders = accessControlAllowHeaders;
return this;
}
public APICorsConfiguration addAccessControlAllowHeadersItem(String accessControlAllowHeadersItem) {
this.accessControlAllowHeaders.add(accessControlAllowHeadersItem);
return this;
}
/**
* Get accessControlAllowHeaders
* @return accessControlAllowHeaders
**/
@ApiModelProperty(example = "null", value = "")
public List<String> getAccessControlAllowHeaders() {
return accessControlAllowHeaders;
}
public void setAccessControlAllowHeaders(List<String> accessControlAllowHeaders) {
this.accessControlAllowHeaders = accessControlAllowHeaders;
}
public APICorsConfiguration accessControlAllowMethods(List<String> accessControlAllowMethods) {
this.accessControlAllowMethods = accessControlAllowMethods;
return this;
}
public APICorsConfiguration addAccessControlAllowMethodsItem(String accessControlAllowMethodsItem) {
this.accessControlAllowMethods.add(accessControlAllowMethodsItem);
return this;
}
/**
* Get accessControlAllowMethods
* @return accessControlAllowMethods
**/
@ApiModelProperty(example = "null", value = "")
public List<String> getAccessControlAllowMethods() {
return accessControlAllowMethods;
}
public void setAccessControlAllowMethods(List<String> accessControlAllowMethods) {
this.accessControlAllowMethods = accessControlAllowMethods;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
APICorsConfiguration apICorsConfiguration = (APICorsConfiguration) o;
return Objects.equals(this.corsConfigurationEnabled, apICorsConfiguration.corsConfigurationEnabled) &&
Objects.equals(this.accessControlAllowOrigins, apICorsConfiguration.accessControlAllowOrigins) &&
Objects.equals(this.accessControlAllowCredentials, apICorsConfiguration.accessControlAllowCredentials) &&
Objects.equals(this.accessControlAllowHeaders, apICorsConfiguration.accessControlAllowHeaders) &&
Objects.equals(this.accessControlAllowMethods, apICorsConfiguration.accessControlAllowMethods);
}
@Override
public int hashCode() {
return Objects.hash(corsConfigurationEnabled, accessControlAllowOrigins, accessControlAllowCredentials, accessControlAllowHeaders, accessControlAllowMethods);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class APICorsConfiguration {\n");
sb.append(" corsConfigurationEnabled: ").append(toIndentedString(corsConfigurationEnabled)).append("\n");
sb.append(" accessControlAllowOrigins: ").append(toIndentedString(accessControlAllowOrigins)).append("\n");
sb.append(" accessControlAllowCredentials: ").append(toIndentedString(accessControlAllowCredentials)).append("\n");
sb.append(" accessControlAllowHeaders: ").append(toIndentedString(accessControlAllowHeaders)).append("\n");
sb.append(" accessControlAllowMethods: ").append(toIndentedString(accessControlAllowMethods)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| abimarank/product-apim | integration-tests/src/main/java/org/wso2/carbon/apimgt/rest/integration/tests/model/APICorsConfiguration.java | Java | apache-2.0 | 7,272 |
/*
* 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.
*/
package org.apache.camel.impl.engine;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.Validator;
import org.apache.camel.spi.ValidatorRegistry;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.service.ServiceHelper;
import org.apache.camel.util.ObjectHelper;
/**
* Default implementation of {@link org.apache.camel.spi.ValidatorRegistry}.
*/
public class DefaultValidatorRegistry extends AbstractDynamicRegistry<ValidatorKey, Validator>
implements ValidatorRegistry<ValidatorKey> {
public DefaultValidatorRegistry(CamelContext context) {
super(context, CamelContextHelper.getMaximumValidatorCacheSize(context));
}
@Override
public Validator resolveValidator(ValidatorKey key) {
Validator answer = get(key);
if (answer == null && ObjectHelper.isNotEmpty(key.getType().getName())) {
answer = get(new ValidatorKey(new DataType(key.getType().getModel())));
}
return answer;
}
@Override
public boolean isStatic(DataType type) {
return isStatic(new ValidatorKey(type));
}
@Override
public boolean isDynamic(DataType type) {
return isDynamic(new ValidatorKey(type));
}
@Override
public String toString() {
return "ValidatorRegistry for " + context.getName() + " [capacity: " + maxCacheSize + "]";
}
@Override
public Validator put(ValidatorKey key, Validator obj) {
// ensure validator is started before its being used
ServiceHelper.startService(obj);
return super.put(key, obj);
}
}
| nikhilvibhav/camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultValidatorRegistry.java | Java | apache-2.0 | 2,457 |
/**
* 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.
*/
package org.apache.nutch.protocol.ftp;
import java.net.URL;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
import org.apache.nutch.protocol.RobotRulesParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import crawlercommons.robots.BaseRobotRules;
import crawlercommons.robots.SimpleRobotRules;
/**
* This class is used for parsing robots for urls belonging to FTP protocol.
* It extends the generic {@link RobotRulesParser} class and contains
* Ftp protocol specific implementation for obtaining the robots file.
*/
public class FtpRobotRulesParser extends RobotRulesParser {
private static final String CONTENT_TYPE = "text/plain";
public static final Logger LOG = LoggerFactory.getLogger(FtpRobotRulesParser.class);
FtpRobotRulesParser() { }
public FtpRobotRulesParser(Configuration conf) {
super(conf);
}
/**
* The hosts for which the caching of robots rules is yet to be done,
* it sends a Ftp request to the host corresponding to the {@link URL}
* passed, gets robots file, parses the rules and caches the rules object
* to avoid re-work in future.
*
* @param ftp The {@link Protocol} object
* @param url URL
*
* @return robotRules A {@link BaseRobotRules} object for the rules
*/
public BaseRobotRules getRobotRulesSet(Protocol ftp, URL url) {
String protocol = url.getProtocol().toLowerCase(); // normalize to lower case
String host = url.getHost().toLowerCase(); // normalize to lower case
BaseRobotRules robotRules = (SimpleRobotRules) CACHE.get(protocol + ":" + host);
boolean cacheRule = true;
if (robotRules == null) { // cache miss
if (LOG.isTraceEnabled())
LOG.trace("cache miss " + url);
try {
Text robotsUrl = new Text(new URL(url, "/robots.txt").toString());
ProtocolOutput output = ((Ftp)ftp).getProtocolOutput(robotsUrl, new CrawlDatum());
ProtocolStatus status = output.getStatus();
if (status.getCode() == ProtocolStatus.SUCCESS) {
robotRules = parseRules(url.toString(), output.getContent().getContent(),
CONTENT_TYPE, agentNames);
} else {
robotRules = EMPTY_RULES; // use default rules
}
} catch (Throwable t) {
if (LOG.isInfoEnabled()) {
LOG.info("Couldn't get robots.txt for " + url + ": " + t.toString());
}
cacheRule = false;
robotRules = EMPTY_RULES;
}
if (cacheRule)
CACHE.put(protocol + ":" + host, robotRules); // cache rules for host
}
return robotRules;
}
}
| fogbeam/Heceta_nutch | src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java | Java | apache-2.0 | 3,708 |
/*
* 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.
*/
package org.apache.ignite.spi.systemview.view;
import org.apache.ignite.internal.managers.systemview.walker.Order;
import org.apache.ignite.internal.processors.query.QueryUtils;
import org.apache.ignite.internal.processors.query.h2.sys.view.SqlSystemView;
/**
* Sql view representation for a {@link SystemView}.
*/
public class SqlViewView {
/** Sql system view. */
private final SqlSystemView view;
/** @param view Sql system view. */
public SqlViewView(SqlSystemView view) {
this.view = view;
}
/** View name. */
@Order
public String name() {
return view.getTableName();
}
/** View description. */
@Order(2)
public String description() {
return view.getDescription();
}
/** View schema. */
@Order(1)
public String schema() {
return QueryUtils.SCHEMA_SYS;
}
}
| samaitra/ignite | modules/indexing/src/main/java/org/apache/ignite/spi/systemview/view/SqlViewView.java | Java | apache-2.0 | 1,673 |
#!/usr/bin/python
#
# 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.
#
import os, sys, subprocess, socket, fcntl, struct
from socket import gethostname
from xml.dom.minidom import parseString
from xmlrpclib import ServerProxy, Error
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
def is_it_up(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
s.connect((host, port))
s.close()
except:
print "host: %s:%s DOWN" % (host, port)
return False
print "host: %s:%s UP" % (host, port)
return True
# hmm master actions don't apply to a slave
master = "192.168.1.161"
port = 8899
user = "oracle"
password = "*******"
auth = "%s:%s" % (user, password)
server = ServerProxy("http://%s:%s" % ("localhost", port))
mserver = ServerProxy("http://%s@%s:%s" % (auth, master, port))
poolNode = True
interface = "c0a80100"
role = 'xen,utility'
hostname = gethostname()
ip = get_ip_address(interface)
poolMembers = []
xserver = server
print "setting up password"
server.update_agent_password(user, password)
if (is_it_up(master, port)):
print "master seems to be up, slaving"
xserver = mserver
else:
print "no master yet, will become master"
# other mechanism must be used to make interfaces equal...
try:
# pooling related same as primary storage!
poolalias = "Pool 0"
poolid = "0004fb0000020000ba9aaf00ae5e2d73"
poolfsnfsbaseuuid = "7718562d-872f-47a7-b454-8f9cac4ffa3a"
pooluuid = poolid
poolfsuuid = poolid
clusterid = "ba9aaf00ae5e2d72"
mgr = "d1a749d4295041fb99854f52ea4dea97"
poolmvip = master
poolfsnfsbaseuuid = "6824e646-5908-48c9-ba44-bb1a8a778084"
repoid = "6824e646590848c9ba44bb1a8a778084"
poolid = repoid
repo = "/OVS/Repositories/%s" % (repoid)
repomount = "cs-mgmt:/volumes/cs-data/secondary"
# primary
primuuid = "7718562d872f47a7b4548f9cac4ffa3a"
ssuuid = "7718562d-872f-47a7-b454-8f9cac4ffa3a"
fshost = "cs-mgmt"
fstarget = "/volumes/cs-data/primary"
fstype = "nfs"
fsname = "Primary storage"
fsmntpoint = "%s:%s" % (fshost, fstarget)
fsmnt = "/nfsmnt/%s" % (ssuuid)
fsplugin = "oracle.generic.NFSPlugin.GenericNFSPlugin"
# set the basics we require to "operate"
print server.take_ownership(mgr, '')
print server.update_server_roles(role,)
# if we're pooling pool...
if (poolNode == True):
poolCount = 0
pooled = False
# check pooling
try:
poolDom = parseString(xserver.discover_server_pool())
print xserver.discover_server_pool()
for node in poolDom.getElementsByTagName('Server_Pool'):
id = node.getElementsByTagName('Unique_Id')[0].firstChild.nodeValue
alias = node.getElementsByTagName('Pool_Alias')[0].firstChild.nodeValue
mvip = node.getElementsByTagName('Master_Virtual_Ip')[0].firstChild.nodeValue
print "pool: %s, %s, %s" % (id, mvip, alias)
members = node.getElementsByTagName('Member')
for member in members:
poolCount = poolCount + 1
mip = member.getElementsByTagName('Registered_IP')[0].firstChild.nodeValue
print "member: %s" % (mip)
if mip == ip:
pooled = True
else:
poolMembers.append(mip)
except Error, v:
print "no master will become master, %s" % v
if (pooled == False):
# setup the repository
print "setup repo"
print server.mount_repository_fs(repomount, repo)
try:
print "adding repo"
print server.add_repository(repomount, repo)
except Error, v:
print "will create the repo, as it's not there", v
print server.create_repository(repomount, repo, repoid, "repo")
print "not pooled!"
if (poolCount == 0):
print "no pool yet, create it"
# check if a pool exists already if not create
# pool if so add us to the pool
print "create pool fs"
print server.create_pool_filesystem(
fstype,
"%s/VirtualMachines/" % repomount,
clusterid,
poolfsuuid,
poolfsnfsbaseuuid,
mgr,
pooluuid
)
print "create pool"
print server.create_server_pool(poolalias,
pooluuid,
poolmvip,
poolCount,
hostname,
ip,
role
)
else:
print "join the pool"
print server.join_server_pool(poolalias,
pooluuid,
poolmvip,
poolCount,
hostname,
ip,
role
)
# add member to ip list ?
poolMembers.append(ip)
print "mambers for pool: %s" % poolMembers
print xserver.set_pool_member_ip_list(poolMembers)
print server.discover_server_pool()
except Error, v:
print "ERROR", v
| MissionCriticalCloud/cosmic-plugin-hypervisor-ovm3 | src/test/resources/scripts/repo_pool.py | Python | apache-2.0 | 6,325 |
/*
This file is part of ALIZE which is an open-source tool for
speaker recognition.
ALIZE is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or any later version.
ALIZE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with ALIZE.
If not, see <http://www.gnu.org/licenses/>.
ALIZE is a development project initiated by the ELISA consortium
[alize.univ-avignon.fr/] and funded by the French Research
Ministry in the framework of the TECHNOLANGUE program
[www.technolangue.net]
The ALIZE project team wants to highlight the limits of voice
authentication in a forensic context.
The "Person Authentification by Voice: A Need of Caution" paper
proposes a good overview of this point (cf. "Person
Authentification by Voice: A Need of Caution", Bonastre J.F.,
Bimbot F., Boe L.J., Campbell J.P., Douglas D.A., Magrin-
chagnolleau I., Eurospeech 2003, Genova].
The conclusion of the paper of the paper is proposed bellow:
[Currently, it is not possible to completely determine whether the
similarity between two recordings is due to the speaker or to other
factors, especially when: (a) the speaker does not cooperate, (b) there
is no control over recording equipment, (c) recording conditions are not
known, (d) one does not know whether the voice was disguised and, to a
lesser extent, (e) the linguistic content of the message is not
controlled. Caution and judgment must be exercised when applying speaker
recognition techniques, whether human or automatic, to account for these
uncontrolled factors. Under more constrained or calibrated situations,
or as an aid for investigative purposes, judicious application of these
techniques may be suitable, provided they are not considered as infallible.
At the present time, there is no scientific process that enables one to
uniquely characterize a person=92s voice or to identify with absolute
certainty an individual from his or her voice.]
Contact Jean-Francois Bonastre for more information about the licence or
the use of ALIZE
Copyright (C) 2003-2010
Laboratoire d'informatique d'Avignon [lia.univ-avignon.fr]
ALIZE admin [alize@univ-avignon.fr]
Jean-Francois Bonastre [jean-francois.bonastre@univ-avignon.fr]
*/
#if !defined(ALIZE_MixtureFileWriter_h)
#define ALIZE_MixtureFileWriter_h
#if defined(_WIN32)
#if defined(ALIZE_EXPORTS)
#define ALIZE_API __declspec(dllexport)
#else
#define ALIZE_API __declspec(dllimport)
#endif
#else
#define ALIZE_API
#endif
#include "FileWriter.h"
namespace alize
{
class Mixture;
class MixtureGD;
class Config;
class MixtureGF;
/// Convenient class used to save 1 mixture in a raw or xml file
///
/// @author Frederic Wils frederic.wils@lia.univ-avignon.fr
/// @version 1.0
/// @date 2003
class ALIZE_API MixtureFileWriter : public FileWriter
{
public :
/// Create a new MixtureFileWriter object to save a mixture
/// in a file
/// @param f the name of the file
/// @param c the configuration to use
///
explicit MixtureFileWriter(const FileName& f, const Config& c);
virtual ~MixtureFileWriter();
/// Write a mixture to the file
/// @param mixture the mixture to save
/// @exception IOException if an I/O error occurs
virtual void writeMixture(const Mixture& mixture);
virtual String getClassName() const;
private :
const Config& _config;
String getFullFileName(const Config&, const FileName&) const;
void writeMixtureGD_XML(const MixtureGD&);
void writeMixtureGD_RAW(const MixtureGD&);
void writeMixtureGD_ETAT(const MixtureGD&);
void writeMixtureGF_XML(const MixtureGF&);
void writeMixtureGF_RAW(const MixtureGF&);
MixtureFileWriter(const MixtureFileWriter&); /*!Not implemented*/
const MixtureFileWriter& operator=(
const MixtureFileWriter&); /*!Not implemented*/
bool operator==(const MixtureFileWriter&) const; /*!Not implemented*/
bool operator!=(const MixtureFileWriter&) const; /*!Not implemented*/
};
} // end namespace alize
#endif // !defined(ALIZE_MixtureFileWriter_h)
| nigel0913/EcustLock | jni/MixtureFileWriter.h | C | apache-2.0 | 4,540 |
<!--[metadata]>
+++
title = "service tasks"
description = "The service tasks command description and usage"
keywords = ["service, tasks"]
advisory = "rc"
[menu.main]
parent = "smn_cli"
+++
<![end-metadata]-->
# service tasks
```Markdown
Usage: docker service tasks [OPTIONS] SERVICE
List the tasks of a service
Options:
-a, --all Display all tasks
-f, --filter value Filter output based on conditions provided
--help Print usage
-n, --no-resolve Do not map IDs to Names
```
Lists the tasks that are running as part of the specified service. This command
has to be run targeting a manager node.
## Examples
### Listing the tasks that are part of a service
The following command shows all the tasks that are part of the `redis` service:
```bash
$ docker service tasks redis
ID NAME SERVICE IMAGE LAST STATE DESIRED STATE NODE
0qihejybwf1x5vqi8lgzlgnpq redis.1 redis redis:3.0.6 Running 8 seconds Running manager1
bk658fpbex0d57cqcwoe3jthu redis.2 redis redis:3.0.6 Running 9 seconds Running worker2
5ls5s5fldaqg37s9pwayjecrf redis.3 redis redis:3.0.6 Running 9 seconds Running worker1
8ryt076polmclyihzx67zsssj redis.4 redis redis:3.0.6 Running 9 seconds Running worker1
1x0v8yomsncd6sbvfn0ph6ogc redis.5 redis redis:3.0.6 Running 8 seconds Running manager1
71v7je3el7rrw0osfywzs0lko redis.6 redis redis:3.0.6 Running 9 seconds Running worker2
4l3zm9b7tfr7cedaik8roxq6r redis.7 redis redis:3.0.6 Running 9 seconds Running worker2
9tfpyixiy2i74ad9uqmzp1q6o redis.8 redis redis:3.0.6 Running 9 seconds Running worker1
3w1wu13yuplna8ri3fx47iwad redis.9 redis redis:3.0.6 Running 8 seconds Running manager1
8eaxrb2fqpbnv9x30vr06i6vt redis.10 redis redis:3.0.6 Running 8 seconds Running manager1
```
## Filtering
The filtering flag (`-f` or `--filter`) format is a `key=value` pair. If there
is more than one filter, then pass multiple flags (e.g. `--filter "foo=bar" --filter "bif=baz"`).
Multiple filter flags are combined as an `OR` filter. For example,
`-f type=custom -f type=builtin` returns both `custom` and `builtin` networks.
The currently supported filters are:
* [id](#id)
* [name](#name)
#### ID
The `id` filter matches on all or a prefix of a task's ID.
```bash
$ docker service tasks -f "id=8" redis
ID NAME SERVICE IMAGE LAST STATE DESIRED STATE NODE
8ryt076polmclyihzx67zsssj redis.4 redis redis:3.0.6 Running 4 minutes Running worker1
8eaxrb2fqpbnv9x30vr06i6vt redis.10 redis redis:3.0.6 Running 4 minutes Running manager1
```
#### Name
The `name` filter matches on task names.
```bash
$ docker service tasks -f "name=redis.1" redis
ID NAME SERVICE IMAGE DESIRED STATE LAST STATE NODE
0qihejybwf1x5vqi8lgzlgnpq redis.1 redis redis:3.0.6 Running Running 8 seconds manager1
```
## Related information
* [service create](service_create.md)
* [service inspect](service_inspect.md)
* [service ls](service_ls.md)
* [service rm](service_rm.md)
* [service scale](service_scale.md)
* [service update](service_update.md)
| pulcy/ha-redis | vendor/github.com/docker/docker/docs/reference/commandline/service_tasks.md | Markdown | apache-2.0 | 3,318 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual 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 io.undertow.protocols.ssl;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.Option;
import org.xnio.Options;
import io.undertow.connector.ByteBufferPool;
import org.xnio.SslClientAuthMode;
import org.xnio.StreamConnection;
import org.xnio.ssl.SslConnection;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.Set;
import java.util.concurrent.Executor;
/**
* @author Stuart Douglas
*/
class UndertowSslConnection extends SslConnection {
private static final Set<Option<?>> SUPPORTED_OPTIONS = Option.setBuilder().add(Options.SECURE, Options.SSL_CLIENT_AUTH_MODE).create();
private final StreamConnection delegate;
private final SslConduit sslConduit;
private final ChannelListener.SimpleSetter<SslConnection> handshakeSetter = new ChannelListener.SimpleSetter<>();
private final SSLEngine engine;
/**
* Construct a new instance.
*
* @param delegate the underlying connection
*/
UndertowSslConnection(StreamConnection delegate, SSLEngine engine, ByteBufferPool bufferPool, Executor delegatedTaskExecutor) {
super(delegate.getIoThread());
this.delegate = delegate;
this.engine = engine;
sslConduit = new SslConduit(this, delegate, engine, delegatedTaskExecutor, bufferPool, new HandshakeCallback());
setSourceConduit(sslConduit);
setSinkConduit(sslConduit);
}
@Override
public void startHandshake() throws IOException {
sslConduit.startHandshake();
}
@Override
public SSLSession getSslSession() {
return sslConduit.getSslSession();
}
@Override
public ChannelListener.Setter<? extends SslConnection> getHandshakeSetter() {
return handshakeSetter;
}
@Override
protected void notifyWriteClosed() {
sslConduit.notifyWriteClosed();
}
@Override
protected void notifyReadClosed() {
sslConduit.notifyReadClosed();
}
@Override
public SocketAddress getPeerAddress() {
return delegate.getPeerAddress();
}
@Override
public SocketAddress getLocalAddress() {
return delegate.getLocalAddress();
}
public SSLEngine getSSLEngine() {
return sslConduit.getSSLEngine();
}
SslConduit getSslConduit() {
return sslConduit;
}
/** {@inheritDoc} */
@Override
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
if (option == Options.SSL_CLIENT_AUTH_MODE) {
try {
return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED);
} finally {
engine.setWantClientAuth(false);
engine.setNeedClientAuth(false);
if (value == SslClientAuthMode.REQUESTED) {
engine.setWantClientAuth(true);
} else if (value == SslClientAuthMode.REQUIRED) {
engine.setNeedClientAuth(true);
}
}
} else if (option == Options.SECURE) {
throw new IllegalArgumentException();
} else {
return delegate.setOption(option, value);
}
}
/** {@inheritDoc} */
@Override
public <T> T getOption(final Option<T> option) throws IOException {
if (option == Options.SSL_CLIENT_AUTH_MODE) {
return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED);
} else {
return option == Options.SECURE ? (T)Boolean.TRUE : delegate.getOption(option);
}
}
/** {@inheritDoc} */
@Override
public boolean supportsOption(final Option<?> option) {
return SUPPORTED_OPTIONS.contains(option) || delegate.supportsOption(option);
}
@Override
protected boolean readClosed() {
return super.readClosed();
}
@Override
protected boolean writeClosed() {
return super.writeClosed();
}
protected void closeAction() {
sslConduit.close();
}
private final class HandshakeCallback implements Runnable {
@Override
public void run() {
final ChannelListener<? super SslConnection> listener = handshakeSetter.get();
if (listener == null) {
return;
}
ChannelListeners.<SslConnection>invokeChannelListener(UndertowSslConnection.this, listener);
}
}
}
| rhusar/undertow | core/src/main/java/io/undertow/protocols/ssl/UndertowSslConnection.java | Java | apache-2.0 | 5,435 |
/**
******************************************************************************
* @file stm32u5xx_hal_gtzc.h
* @author MCD Application Team
* @brief Header file of GTZC HAL module.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32U5xx_HAL_GTZC_H
#define STM32U5xx_HAL_GTZC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal_def.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @addtogroup GTZC
* @{
*/
/* Exported types ------------------------------------------------------------*/
/** @defgroup GTZC_Exported_Types GTZC Exported Types
* @{
*/
/*!< Values needed for MPCBB_Attribute_ConfigTypeDef structure sizing */
#define GTZC_MCPBB_NB_VCTR_REG_MAX (32U)
#define GTZC_MCPBB_NB_LCK_VCTR_REG_MAX (1U)
typedef struct
{
uint32_t MPCBB_SecConfig_array[GTZC_MCPBB_NB_VCTR_REG_MAX]; /*!< Each element specifies secure access mode for
a super-block. Each bit corresponds to a block
inside the super-block. 0 means non-secure,
1 means secure */
uint32_t MPCBB_PrivConfig_array[GTZC_MCPBB_NB_VCTR_REG_MAX]; /*!< Each element specifies privilege access mode for
a super-block. Each bit corresponds to a block
inside the super-block. 0 means non-privilege,
1 means privilege */
uint32_t MPCBB_LockConfig_array[GTZC_MCPBB_NB_LCK_VCTR_REG_MAX]; /*!< Each bit specifies the lock configuration of
a super-block (32 blocks). 0 means unlocked,
1 means locked */
} MPCBB_Attribute_ConfigTypeDef;
typedef struct
{
uint32_t SecureRWIllegalMode; /*!< Secure read/write illegal access
field. It can be a value of @ref GTZC_MPCBB_SecureRWIllegalMode */
uint32_t InvertSecureState; /*!< Default security state field (can be inverted or not).
It can be a value of @ref GTZC_MPCBB_InvertSecureState */
MPCBB_Attribute_ConfigTypeDef AttributeConfig; /*!< MPCBB attribute configuration sub-structure */
} MPCBB_ConfigTypeDef;
typedef struct
{
uint32_t AreaId; /*!< Area identifier field. It can be a value of @ref
GTZC_MPCWM_AreaId */
uint32_t Offset; /*!< Offset of the watermark area, starting from the selected
memory base address. It must aligned on 128KB for FMC
and OCTOSPI memories, and on 32-byte for BKPSRAM */
uint32_t Length; /*!< Length of the watermark area, starting from the selected
Offset. It must aligned on 128KB for FMC and OCTOSPI
memories, and on 32-byte for BKPSRAM */
uint32_t Attribute; /*!< Attributes of the watermark area. It can be a value
of @ref GTZC_MPCWM_Attribute */
uint32_t Lock; /*!< Lock of the watermark area. It can be a value
of @ref GTZC_MPCWM_Lock */
uint32_t AreaStatus; /*!< Status of the watermark area. It can be set to
ENABLE or DISABLE */
} MPCWM_ConfigTypeDef;
/**
* @}
*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup GTZC_Private_Constants GTZC Private Constants
* @{
*/
/** @defgroup GTZC_Private_PeriphId_composition GTZC Peripheral identifier composition
* @{
*/
/* composition definition for Peripheral identifier parameter (PeriphId) used in
* HAL_GTZC_TZSC_ConfigPeriphAttributes() and HAL_GTZC_TZSC_GetConfigPeriphAttributes()
* functions and also in all HAL_GTZC_TZIC relative functions.
* Bitmap Definition
* bits[31:28] Field "register". Define the register index a peripheral belongs to.
* Each bit is dedicated to a single register.
* bit[5] Field "all peripherals". If this bit is set then the PeriphId targets
* all peripherals within all registers.
* bits[4:0] Field "bit position". Define the bit position within the
* register dedicated to the peripheral, value from 0 to 31.
*/
#define GTZC_PERIPH_REG_SHIFT (28U)
#define GTZC_PERIPH_REG (0xF0000000U)
#define GTZC1_PERIPH_REG1 (0x00000000U)
#define GTZC1_PERIPH_REG2 (0x10000000U)
#define GTZC1_PERIPH_REG3 (0x20000000U)
#define GTZC1_PERIPH_REG4 (0x30000000U)
#define GTZC2_PERIPH_REG1 (0x40000000U)
#define GTZC2_PERIPH_REG2 (0x50000000U)
#define GTZC_PERIPH_BIT_POSITION (0x0000001FU)
/**
* @}
*/
/** @defgroup GTZC_Private_Attributes_Msk GTZC Attributes Masks
* @{
*/
#define GTZC_ATTR_SEC_MASK 0x100U
#define GTZC_ATTR_PRIV_MASK 0x200U
/**
* @}
*/
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup GTZC_Exported_Constants GTZC Exported Constants
* @{
*/
/** @defgroup GTZC_MPCBB_SecureRWIllegalMode GTZC MPCBB SRWILADIS values
* @{
*/
#define GTZC_MPCBB_SRWILADIS_ENABLE (0U)
#define GTZC_MPCBB_SRWILADIS_DISABLE (GTZC_MPCBB_CR_SRWILADIS_Msk)
/**
* @}
*/
/** @defgroup GTZC_MPCBB_InvertSecureState GTZC MPCBB INVSECSTATE values
* @{
*/
#define GTZC_MPCBB_INVSECSTATE_NOT_INVERTED (0U)
#define GTZC_MPCBB_INVSECSTATE_INVERTED (GTZC_MPCBB_CR_INVSECSTATE_Msk)
/**
* @}
*/
/** @defgroup GTZC_MPCWM_AreaId GTZC MPCWM area identifier values
* @{
*/
#define GTZC_TZSC_MPCWM_ID1 (0U)
#define GTZC_TZSC_MPCWM_ID2 (1U)
/**
* @}
*/
/** @defgroup GTZC_TZSC_TZIC_PeriphId GTZC TZSC and TZIC Peripheral identifier values
* @{
*/
/* GTZC1 */
#define GTZC_PERIPH_TIM2 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_TIM2_Pos)
#define GTZC_PERIPH_TIM3 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_TIM3_Pos)
#define GTZC_PERIPH_TIM4 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_TIM4_Pos)
#define GTZC_PERIPH_TIM5 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_TIM5_Pos)
#define GTZC_PERIPH_TIM6 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_TIM6_Pos)
#define GTZC_PERIPH_TIM7 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_TIM7_Pos)
#define GTZC_PERIPH_WWDG (GTZC1_PERIPH_REG1 | GTZC_CFGR1_WWDG_Pos)
#define GTZC_PERIPH_IWDG (GTZC1_PERIPH_REG1 | GTZC_CFGR1_IWDG_Pos)
#define GTZC_PERIPH_SPI2 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_SPI2_Pos)
#define GTZC_PERIPH_USART2 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_USART2_Pos)
#define GTZC_PERIPH_USART3 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_USART3_Pos)
#define GTZC_PERIPH_UART4 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_UART4_Pos)
#define GTZC_PERIPH_UART5 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_UART5_Pos)
#define GTZC_PERIPH_I2C1 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_I2C1_Pos)
#define GTZC_PERIPH_I2C2 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_I2C2_Pos)
#define GTZC_PERIPH_CRS (GTZC1_PERIPH_REG1 | GTZC_CFGR1_CRS_Pos)
#define GTZC_PERIPH_I2C4 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_I2C4_Pos)
#define GTZC_PERIPH_LPTIM2 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_LPTIM2_Pos)
#define GTZC_PERIPH_FDCAN1 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_FDCAN1_Pos)
#define GTZC_PERIPH_UCPD1 (GTZC1_PERIPH_REG1 | GTZC_CFGR1_UCPD1_Pos)
#define GTZC_PERIPH_TIM1 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_TIM1_Pos)
#define GTZC_PERIPH_SPI1 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_SPI1_Pos)
#define GTZC_PERIPH_TIM8 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_TIM8_Pos)
#define GTZC_PERIPH_USART1 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_USART1_Pos)
#define GTZC_PERIPH_TIM15 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_TIM15_Pos)
#define GTZC_PERIPH_TIM16 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_TIM16_Pos)
#define GTZC_PERIPH_TIM17 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_TIM17_Pos)
#define GTZC_PERIPH_SAI1 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_SAI1_Pos)
#define GTZC_PERIPH_SAI2 (GTZC1_PERIPH_REG2 | GTZC_CFGR2_SAI2_Pos)
#define GTZC_PERIPH_MDF1 (GTZC1_PERIPH_REG3 | GTZC_CFGR3_MDF1_Pos)
#define GTZC_PERIPH_CORDIC (GTZC1_PERIPH_REG3 | GTZC_CFGR3_CORDIC_Pos)
#define GTZC_PERIPH_FMAC (GTZC1_PERIPH_REG3 | GTZC_CFGR3_FMAC_Pos)
#define GTZC_PERIPH_CRC (GTZC1_PERIPH_REG3 | GTZC_CFGR3_CRC_Pos)
#define GTZC_PERIPH_TSC (GTZC1_PERIPH_REG3 | GTZC_CFGR3_TSC_Pos)
#define GTZC_PERIPH_DMA2D (GTZC1_PERIPH_REG3 | GTZC_CFGR3_DMA2D_Pos)
#define GTZC_PERIPH_ICACHE_REG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_ICACHE_REG_Pos)
#define GTZC_PERIPH_DCACHE1_REG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_DCACHE1_REG_Pos)
#define GTZC_PERIPH_ADC12 (GTZC1_PERIPH_REG3 | GTZC_CFGR3_ADC12_Pos)
#define GTZC_PERIPH_DCMI (GTZC1_PERIPH_REG3 | GTZC_CFGR3_DCMI_Pos)
#define GTZC_PERIPH_OTG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_OTG_Pos)
#define GTZC_PERIPH_AES (GTZC1_PERIPH_REG3 | GTZC_CFGR3_AES_Pos)
#define GTZC_PERIPH_HASH (GTZC1_PERIPH_REG3 | GTZC_CFGR3_HASH_Pos)
#define GTZC_PERIPH_RNG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_RNG_Pos)
#define GTZC_PERIPH_PKA (GTZC1_PERIPH_REG3 | GTZC_CFGR3_PKA_Pos)
#define GTZC_PERIPH_SAES (GTZC1_PERIPH_REG3 | GTZC_CFGR3_SAES_Pos)
#define GTZC_PERIPH_OCTOSPIM (GTZC1_PERIPH_REG3 | GTZC_CFGR3_OCTOSPIM_Pos)
#define GTZC_PERIPH_SDMMC1 (GTZC1_PERIPH_REG3 | GTZC_CFGR3_SDMMC1_Pos)
#define GTZC_PERIPH_SDMMC2 (GTZC1_PERIPH_REG3 | GTZC_CFGR3_SDMMC2_Pos)
#define GTZC_PERIPH_FSMC_REG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_FSMC_REG_Pos)
#define GTZC_PERIPH_OCTOSPI1_REG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_OCTOSPI1_REG_Pos)
#define GTZC_PERIPH_OCTOSPI2_REG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_OCTOSPI2_REG_Pos)
#define GTZC_PERIPH_RAMCFG (GTZC1_PERIPH_REG3 | GTZC_CFGR3_RAMCFG_Pos)
#define GTZC_PERIPH_GPDMA1 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_GPDMA1_Pos)
#define GTZC_PERIPH_FLASH_REG (GTZC1_PERIPH_REG4 | GTZC_CFGR4_FLASH_REG_Pos)
#define GTZC_PERIPH_FLASH (GTZC1_PERIPH_REG4 | GTZC_CFGR4_FLASH_Pos)
#define GTZC_PERIPH_OTFDEC2 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_OTFDEC2_Pos)
#define GTZC_PERIPH_OTFDEC1 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_OTFDEC1_Pos)
#define GTZC_PERIPH_TZSC1 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_TZSC1_Pos)
#define GTZC_PERIPH_TZIC1 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_TZIC1_Pos)
#define GTZC_PERIPH_OCTOSPI1_MEM (GTZC1_PERIPH_REG4 | GTZC_CFGR4_OCTOSPI1_MEM_Pos)
#define GTZC_PERIPH_FSMC_MEM (GTZC1_PERIPH_REG4 | GTZC_CFGR4_FSMC_MEM_Pos)
#define GTZC_PERIPH_BKPSRAM (GTZC1_PERIPH_REG4 | GTZC_CFGR4_BKPSRAM_Pos)
#define GTZC_PERIPH_OCTOSPI2_MEM (GTZC1_PERIPH_REG4 | GTZC_CFGR4_OCTOSPI2_MEM_Pos)
#define GTZC_PERIPH_SRAM1 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_SRAM1_Pos)
#define GTZC_PERIPH_MPCBB1_REG (GTZC1_PERIPH_REG4 | GTZC_CFGR4_MPCBB1_REG_Pos)
#define GTZC_PERIPH_SRAM2 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_SRAM2_Pos)
#define GTZC_PERIPH_MPCBB2_REG (GTZC1_PERIPH_REG4 | GTZC_CFGR4_MPCBB2_REG_Pos)
#define GTZC_PERIPH_SRAM3 (GTZC1_PERIPH_REG4 | GTZC_CFGR4_SRAM3_Pos)
#define GTZC_PERIPH_MPCBB3_REG (GTZC1_PERIPH_REG4 | GTZC_CFGR4_MPCBB3_REG_Pos)
/* GTZC2 */
#define GTZC_PERIPH_SPI3 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_SPI3_Pos)
#define GTZC_PERIPH_LPUART1 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_LPUART1_Pos)
#define GTZC_PERIPH_I2C3 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_I2C3_Pos)
#define GTZC_PERIPH_LPTIM1 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_LPTIM1_Pos)
#define GTZC_PERIPH_LPTIM3 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_LPTIM3_Pos)
#define GTZC_PERIPH_LPTIM4 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_LPTIM4_Pos)
#define GTZC_PERIPH_OPAMP (GTZC2_PERIPH_REG1 | GTZC_CFGR1_OPAMP_Pos)
#define GTZC_PERIPH_COMP (GTZC2_PERIPH_REG1 | GTZC_CFGR1_COMP_Pos)
#define GTZC_PERIPH_ADC4 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_ADC4_Pos)
#define GTZC_PERIPH_VREFBUF (GTZC2_PERIPH_REG1 | GTZC_CFGR1_VREFBUF_Pos)
#define GTZC_PERIPH_DAC1 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_DAC1_Pos)
#define GTZC_PERIPH_ADF1 (GTZC2_PERIPH_REG1 | GTZC_CFGR1_ADF1_Pos)
#define GTZC_PERIPH_SYSCFG (GTZC2_PERIPH_REG2 | GTZC_CFGR2_SYSCFG_Pos)
#define GTZC_PERIPH_RTC (GTZC2_PERIPH_REG2 | GTZC_CFGR2_RTC_Pos)
#define GTZC_PERIPH_TAMP (GTZC2_PERIPH_REG2 | GTZC_CFGR2_TAMP_Pos)
#define GTZC_PERIPH_PWR (GTZC2_PERIPH_REG2 | GTZC_CFGR2_PWR_Pos)
#define GTZC_PERIPH_RCC (GTZC2_PERIPH_REG2 | GTZC_CFGR2_RCC_Pos)
#define GTZC_PERIPH_LPDMA1 (GTZC2_PERIPH_REG2 | GTZC_CFGR2_LPDMA1_Pos)
#define GTZC_PERIPH_EXTI (GTZC2_PERIPH_REG2 | GTZC_CFGR2_EXTI_Pos)
#define GTZC_PERIPH_TZSC2 (GTZC2_PERIPH_REG2 | GTZC_CFGR2_TZSC2_Pos)
#define GTZC_PERIPH_TZIC2 (GTZC2_PERIPH_REG2 | GTZC_CFGR2_TZIC2_Pos)
#define GTZC_PERIPH_SRAM4 (GTZC2_PERIPH_REG2 | GTZC_CFGR2_SRAM4_Pos)
#define GTZC_PERIPH_MPCBB4_REG (GTZC2_PERIPH_REG2 | GTZC_CFGR2_MPCBB4_REG_Pos)
#define GTZC_PERIPH_ALL (0x00000020U)
/* Note that two maximum values are also defined here:
* - max number of securable AHB/APB peripherals or masters
* (used in TZSC sub-block)
* - max number of securable and TrustZone-aware AHB/APB peripherals or masters
* (used in TZIC sub-block)
*/
#define GTZC_TZSC_PERIPH_NUMBER (HAL_GTZC_TZSC_GET_ARRAY_INDEX(GTZC_PERIPH_ADF1 + 1U))
#define GTZC_TZIC_PERIPH_NUMBER (HAL_GTZC_TZIC_GET_ARRAY_INDEX(GTZC_PERIPH_MPCBB4_REG + 1U))
/**
* @}
*/
/** @defgroup GTZC_TZSC_PeriphAttributes GTZC TZSC peripheral attribute values
* @{
*/
/* user-oriented definitions for attribute parameter (PeriphAttributes) used in
* HAL_GTZC_TZSC_ConfigPeriphAttributes() and HAL_GTZC_TZSC_GetConfigPeriphAttributes()
* functions
*/
#define GTZC_TZSC_PERIPH_SEC (GTZC_ATTR_SEC_MASK | 0x00000001U) /*!< Secure attribute */
#define GTZC_TZSC_PERIPH_NSEC (GTZC_ATTR_SEC_MASK | 0x00000000U) /*!< Non-secure attribute */
#define GTZC_TZSC_PERIPH_PRIV (GTZC_ATTR_PRIV_MASK | 0x00000002U) /*!< Privilege attribute */
#define GTZC_TZSC_PERIPH_NPRIV (GTZC_ATTR_PRIV_MASK | 0x00000000U) /*!< Non-privilege attribute */
/**
* @}
*/
/** @defgroup GTZC_TZSC_Lock GTZC TZSC lock values
* @{
*/
/* user-oriented definitions for HAL_GTZC_TZSC_GetLock() returned value */
#define GTZC_TZSC_LOCK_OFF (0U)
#define GTZC_TZSC_LOCK_ON GTZC_TZSC_CR_LCK_Msk
/**
* @}
*/
/** @defgroup GTZC_MPCWM_Group GTZC MPCWM values
* @{
*/
/* user-oriented definitions for TZSC_MPCWM */
#define GTZC_TZSC_MPCWM_GRANULARITY_1 0x00020000U /* OCTOSPI & FMC granularity: 128 kbytes */
#define GTZC_TZSC_MPCWM_GRANULARITY_2 0x00000020U /* BKPSRAM granularity: 32 bytes */
/**
* @}
*/
/** @defgroup GTZC_MPCWM_Lock GTZC MPCWM Lock values
* @{
*/
/* user-oriented definitions for TZSC_MPCWM */
#define GTZC_TZSC_MPCWM_LOCK_OFF (0U)
#define GTZC_TZSC_MPCWM_LOCK_ON GTZC_TZSC_MPCWM_CFGR_SRLOCK_Msk
/**
* @}
*/
/** @defgroup GTZC_MPCWM_Attribute GTZC MPCWM Attribute values
* @{
*/
/* user-oriented definitions for TZSC_MPCWM */
#define GTZC_TZSC_MPCWM_REGION_NSEC (0U)
#define GTZC_TZSC_MPCWM_REGION_SEC (1U)
#define GTZC_TZSC_MPCWM_REGION_NPRIV (0U)
#define GTZC_TZSC_MPCWM_REGION_PRIV (2U)
/**
* @}
*/
/** @defgroup GTZC_MPCBB_Group GTZC MPCBB values
* @{
*/
/* user-oriented definitions for MPCBB */
#define GTZC_MPCBB_BLOCK_SIZE 0x200U /* 512 Bytes */
#define GTZC_MPCBB_SUPERBLOCK_SIZE (GTZC_MPCBB_BLOCK_SIZE * 32U) /* 16 KBytes */
#define GTZC_MCPBB_SUPERBLOCK_UNLOCKED (0U)
#define GTZC_MCPBB_SUPERBLOCK_LOCKED (1U)
#define GTZC_MCPBB_BLOCK_NSEC (GTZC_ATTR_SEC_MASK | 0U)
#define GTZC_MCPBB_BLOCK_SEC (GTZC_ATTR_SEC_MASK | 1U)
#define GTZC_MCPBB_BLOCK_NPRIV (GTZC_ATTR_PRIV_MASK | 0U)
#define GTZC_MCPBB_BLOCK_PRIV (GTZC_ATTR_PRIV_MASK | 2U)
/* user-oriented definitions for HAL_GTZC_MPCBB_GetLock() returned value */
#define GTZC_MCPBB_LOCK_OFF (0U)
#define GTZC_MCPBB_LOCK_ON (1U)
/**
* @}
*/
/** @defgroup GTZC_TZIC_Flag GTZC TZIC flag values
* @{
*/
/* user-oriented definitions for HAL_GTZC_TZIC_GetFlag() flag parameter */
#define GTZC_TZIC_NO_ILA_EVENT (0U)
#define GTZC_TZIC_ILA_EVENT_PENDING (1U)
/**
* @}
*/
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup GTZC_Private_Macros GTZC Private Macros
* @{
*/
/* retrieve information to access register for a specific PeriphId */
#define GTZC_GET_REG_INDEX(periph_id)\
(((periph_id) & GTZC_PERIPH_REG) >> GTZC_PERIPH_REG_SHIFT)
#define GTZC_GET_REG_INDEX_IN_INSTANCE(periph_id)\
((((periph_id) & GTZC_PERIPH_REG) <= GTZC1_PERIPH_REG4) ? \
(((periph_id) & GTZC_PERIPH_REG) >> GTZC_PERIPH_REG_SHIFT) : \
((((periph_id) & GTZC_PERIPH_REG) >> GTZC_PERIPH_REG_SHIFT) - 4U))
#define GTZC_GET_PERIPH_POS(periph_id) ((periph_id) & GTZC_PERIPH_BIT_POSITION)
#define IS_GTZC_BASE_ADDRESS(mem, address)\
( ( (uint32_t)(address) == (uint32_t)GTZC_BASE_ADDRESS_NS(mem) ) || \
( (uint32_t)(address) == (uint32_t)GTZC_BASE_ADDRESS_S(mem) ) )
#define GTZC_MEM_SIZE(mem)\
( mem ## _SIZE )
#define GTZC_BASE_ADDRESS_S(mem)\
( mem ## _BASE_S )
#define GTZC_BASE_ADDRESS_NS(mem)\
( mem ## _BASE_NS )
/**
* @}
*/
/* Exported macros -----------------------------------------------------------*/
/** @defgroup GTZC_Exported_Macros GTZC Exported Macros
* @{
*/
/* user-oriented macro to get array index of a specific PeriphId
* in case of GTZC_PERIPH_ALL usage in the two following functions:
* HAL_GTZC_TZSC_ConfigPeriphAttributes() and HAL_GTZC_TZSC_GetConfigPeriphAttributes()
*/
#define HAL_GTZC_TZSC_GET_ARRAY_INDEX(periph_id) \
(uint32_t)((HAL_GTZC_TZSC_GET_INSTANCE(periph_id) == GTZC_TZSC1)? \
((GTZC_GET_REG_INDEX(periph_id) * 32U) + GTZC_GET_PERIPH_POS(periph_id)) : \
(((GTZC_GET_REG_INDEX(periph_id) - 1U) * 32U) + GTZC_GET_PERIPH_POS(periph_id) ))
#define HAL_GTZC_TZIC_GET_ARRAY_INDEX(periph_id) \
( (GTZC_GET_REG_INDEX((periph_id)) * 32U) + GTZC_GET_PERIPH_POS((periph_id)) )
/* user-oriented macro to get TZSC instance of a specific PeriphId */
#define HAL_GTZC_TZSC_GET_INSTANCE(periph_id) \
((GTZC_GET_REG_INDEX(periph_id) <= (GTZC1_PERIPH_REG4 >> GTZC_PERIPH_REG_SHIFT))? \
GTZC_TZSC1 : GTZC_TZSC2)
/* user-oriented macro to get TZIC instance of a specific PeriphId */
#define HAL_GTZC_TZIC_GET_INSTANCE(periph_id) \
((GTZC_GET_REG_INDEX(periph_id) <= (GTZC1_PERIPH_REG4>> GTZC_PERIPH_REG_SHIFT))? \
GTZC_TZIC1 : GTZC_TZIC2)
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup GTZC_Exported_Functions
* @{
*/
/** @addtogroup GTZC_Exported_Functions_Group1
* @brief TZSC Initialization and Configuration functions
* @{
*/
HAL_StatusTypeDef HAL_GTZC_TZSC_ConfigPeriphAttributes(uint32_t PeriphId,
uint32_t PeriphAttributes);
HAL_StatusTypeDef HAL_GTZC_TZSC_GetConfigPeriphAttributes(uint32_t PeriphId,
uint32_t *PeriphAttributes);
/**
* @}
*/
#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/** @addtogroup GTZC_Exported_Functions_Group2
* @brief MPCWM Initialization and Configuration functions
* @{
*/
HAL_StatusTypeDef HAL_GTZC_TZSC_MPCWM_ConfigMemAttributes(uint32_t MemBaseAddress,
MPCWM_ConfigTypeDef *pMPCWM_Desc);
HAL_StatusTypeDef HAL_GTZC_TZSC_MPCWM_GetConfigMemAttributes(uint32_t MemBaseAddress,
MPCWM_ConfigTypeDef *pMPCWM_Desc);
/**
* @}
*/
/** @addtogroup GTZC_Exported_Functions_Group3
* @brief TZSC and TZSC-MPCWM Lock functions
* @{
*/
void HAL_GTZC_TZSC_Lock(GTZC_TZSC_TypeDef *TZSC_Instance);
uint32_t HAL_GTZC_TZSC_GetLock(GTZC_TZSC_TypeDef *TZSC_Instance);
/**
* @}
*/
#endif /* defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/** @addtogroup GTZC_Exported_Functions_Group4
* @brief MPCBB Initialization and Configuration functions
* @{
*/
HAL_StatusTypeDef HAL_GTZC_MPCBB_ConfigMem(uint32_t MemBaseAddress,
MPCBB_ConfigTypeDef *pMPCBB_desc);
HAL_StatusTypeDef HAL_GTZC_MPCBB_GetConfigMem(uint32_t MemBaseAddress,
MPCBB_ConfigTypeDef *pMPCBB_desc);
HAL_StatusTypeDef HAL_GTZC_MPCBB_ConfigMemAttributes(uint32_t MemAddress,
uint32_t NbBlocks,
uint32_t *pMemAttributes);
HAL_StatusTypeDef HAL_GTZC_MPCBB_GetConfigMemAttributes(uint32_t MemAddress,
uint32_t NbBlocks,
uint32_t *pMemAttributes);
#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
HAL_StatusTypeDef HAL_GTZC_MPCBB_LockConfig(uint32_t MemAddress,
uint32_t NbSuperBlocks,
uint32_t *pLockAttributes);
HAL_StatusTypeDef HAL_GTZC_MPCBB_GetLockConfig(uint32_t MemAddress,
uint32_t NbSuperBlocks,
uint32_t *pLockAttributes);
HAL_StatusTypeDef HAL_GTZC_MPCBB_Lock(uint32_t MemBaseAddress);
HAL_StatusTypeDef HAL_GTZC_MPCBB_GetLock(uint32_t MemBaseAddress,
uint32_t *pLockState);
#endif /* defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @}
*/
#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/** @addtogroup GTZC_Exported_Functions_Group5
* @brief TZIC functions
* @{
*/
HAL_StatusTypeDef HAL_GTZC_TZIC_DisableIT(uint32_t PeriphId);
HAL_StatusTypeDef HAL_GTZC_TZIC_EnableIT(uint32_t PeriphId);
HAL_StatusTypeDef HAL_GTZC_TZIC_GetFlag(uint32_t PeriphId, uint32_t *pFlag);
HAL_StatusTypeDef HAL_GTZC_TZIC_ClearFlag(uint32_t PeriphId);
/**
* @}
*/
/** @addtogroup GTZC_Exported_Functions_Group6
* @brief IRQ related Functions
* @{
*/
void HAL_GTZC_IRQHandler(void);
void HAL_GTZC_TZIC_Callback(uint32_t PeriphId);
/**
* @}
*/
#endif /* defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* STM32U5xx_HAL_GTZC_H */
| nongxiaoming/rt-thread | bsp/stm32/libraries/STM32U5xx_HAL/STM32U5xx_HAL_Driver/Inc/stm32u5xx_hal_gtzc.h | C | apache-2.0 | 23,389 |
<?php
if(!defined('IN_CB'))die('You are not allowed to access to this page.');
/**
* ean13.php
*--------------------------------------------------------------------
*
* Sub-Class - EAN-13
*
* You can provide a ISBN code (without dash), the code will transform
* it into a EAN13 format.
* EAN-13 contains
* - 2 system digits (1 not displayed but coded with parity)
* - 5 manufacturer code digits
* - 5 product digits
* - 1 checksum digit
*
*--------------------------------------------------------------------
* Revision History
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://other.lookstrike.com/barcode/
*/
class ean13 extends BarCode {
protected $keys = array(), $code = array(), $codeParity = array();
private $text;
private $textfont;
private $book;
/**
* Constructor
*
* @param int $maxHeight
* @param FColor $color1
* @param FColor $color2
* @param int $res
* @param string $text
* @param int $textfont
* @param bool $book
*/
public function __construct($maxHeight,FColor $color1,FColor $color2,$res,$text,$textfont,$book=false) {
BarCode::__construct($maxHeight,$color1,$color2,$res);
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
// Left-Hand Odd Parity starting with a space
// Left-Hand Even Parity is the inverse (0=0012) starting with a space
// Right-Hand is the same of Left-Hand starting with a bar
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
// Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit
$this->codeParity = array(
array(0,0,0,0,0), /* 0 */
array(0,1,0,1,1), /* 1 */
array(0,1,1,0,1), /* 2 */
array(0,1,1,1,0), /* 3 */
array(1,0,0,1,1), /* 4 */
array(1,1,0,0,1), /* 5 */
array(1,1,1,0,0), /* 6 */
array(1,0,1,0,1), /* 7 */
array(1,0,1,1,0), /* 8 */
array(1,1,0,1,0) /* 9 */
);
$this->setText($text);
$this->textfont = $textfont;
$this->book = $book;
}
/**
* Saves Text
*
* @param string $text
*/
public function setText($text){
$this->text = $text;
}
private function inverse($text,$inverse=1) {
if($inverse == 1)
$text = strrev($text);
return $text;
}
/**
* Draws the barcode
*
* @param ressource $im
*/
public function draw($im) {
$error_stop = false;
// Checking if all chars are allowed
for($i=0;$i<strlen($this->text);$i++) {
if(!is_int(array_search($this->text[$i],$this->keys))) {
$this->DrawError($im,'Char \''.$this->text[$i].'\' not allowed.');
$error_stop = true;
}
}
if($error_stop == false) {
if($this->book == true && strlen($this->text) != 10) {
$this->DrawError($im,'Must contains 10 chars if ISBN is true.');
$error_stop = true;
}
// If it's a book, we change the code to the right one
if($this->book==true && strlen($this->text)==10)
$this->text = '978'.substr($this->text,0,strlen($this->text)-1);
// Must contains 12 chars
if(strlen($this->text) != 12) {
$this->DrawError($im,'Must contains 12 chars, the 13th digit is automatically added.');
$error_stop = true;
}
if($error_stop == false) {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$odd = true;
$checksum=0;
for($i=strlen($this->text);$i>0;$i--) {
if($odd==true) {
$multiplier=3;
$odd=false;
}
else {
$multiplier=1;
$odd=true;
}
$checksum += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$checksum = 10 - $checksum % 10;
$checksum = ($checksum == 10)?0:$checksum;
$this->text .= $this->keys[$checksum];
// If we have to write text, we move the barcode to the right to have space to put system digit
$this->positionX = ($this->textfont == 0)?0:10;
// Starting Code
$this->DrawChar($im,'000',1);
// Draw Second Code
$this->DrawChar($im,$this->findCode($this->text[1]),2);
// Draw Manufacturer Code
for($i=0;$i<5;$i++)
$this->DrawChar($im,$this->inverse($this->findCode($this->text[$i + 2]),$this->codeParity[$this->text[0]][$i]),2);
// Draw Center Guard Bar
$this->DrawChar($im,'00000',2);
// Draw Product Code
for($i=7;$i<13;$i++){
$this->DrawChar($im,$this->findCode($this->text[$i]),1);
}
// Draw Right Guard Bar
$this->DrawChar($im,'000',1);
$this->lastX = $this->positionX;
$this->lastY = $this->maxHeight;
$this->DrawText($im);
}
}
}
/**
* Overloaded method for drawing special label
*
* @param ressource $im
*/
protected function DrawText($im) {
if($this->textfont != 0) {
$bar_color = (is_null($this->color1))?NULL:$this->color1->allocate($im);
if(!is_null($bar_color)) {
$rememberX = $this->positionX;
$rememberH = $this->maxHeight;
// We increase the bars
$this->maxHeight = $this->maxHeight + 9;
$this->positionX = 10;
$this->DrawSingleBar($im,$this->color1);
$this->positionX += $this->res*2;
$this->DrawSingleBar($im,$this->color1);
// Center Guard Bar
$this->positionX += $this->res*44;
$this->DrawSingleBar($im,$this->color1);
$this->positionX += $this->res*2;
$this->DrawSingleBar($im,$this->color1);
// Last Bars
$this->positionX += $this->res*44;
$this->DrawSingleBar($im,$this->color1);
$this->positionX += $this->res*2;
$this->DrawSingleBar($im,$this->color1);
$this->positionX = $rememberX;
$this->maxHeight = $rememberH;
imagechar($im,$this->textfont,1,$this->maxHeight-(imagefontheight($this->textfont)/2),$this->text[0],$bar_color);
imagestring($im,$this->textfont,10+(3*$this->res+48*$this->res)/2-imagefontwidth($this->textfont)*(6/2),$this->maxHeight+1,substr($this->text,1,6),$bar_color);
imagestring($im,$this->textfont,10+46*$this->res+(3*$this->res+46*$this->res)/2-imagefontwidth($this->textfont)*(6/2),$this->maxHeight+1,substr($this->text,7,6),$bar_color);
}
$this->lastY = $this->maxHeight + imagefontheight($this->textfont);
}
}
};
?> | blondprod/veganet | public/barcode/class/ean13.barcode.php | PHP | apache-2.0 | 6,651 |
/* Copyright 2019 The TensorFlow 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_KERNELS_EIG_OP_IMPL_H_
#define TENSORFLOW_CORE_KERNELS_EIG_OP_IMPL_H_
// See docs in ../ops/linalg_ops.cc.
#include "third_party/eigen3/Eigen/Core"
#include "third_party/eigen3/Eigen/Eigenvalues"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/denormal.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
template <class InputScalar, class OutputScalar>
class EigOp : public LinearAlgebraOp<InputScalar, OutputScalar> {
public:
typedef LinearAlgebraOp<InputScalar, OutputScalar> Base;
explicit EigOp(OpKernelConstruction* context) : Base(context) {
OP_REQUIRES_OK(context, context->GetAttr("compute_v", &compute_v_));
}
using TensorShapes = typename Base::TensorShapes;
using InputMatrix = typename Base::InputMatrix;
using InputMatrixMaps = typename Base::InputMatrixMaps;
using InputConstMatrixMap = typename Base::InputConstMatrixMap;
using InputConstMatrixMaps = typename Base::InputConstMatrixMaps;
using OutputMatrix = typename Base::OutputMatrix;
using OutputMatrixMaps = typename Base::OutputMatrixMaps;
using OutputConstMatrixMap = typename Base::OutputConstMatrixMap;
using OutputConstMatrixMaps = typename Base::OutputConstMatrixMaps;
TensorShapes GetOutputMatrixShapes(
const TensorShapes& input_matrix_shapes) const final {
int64 n = input_matrix_shapes[0].dim_size(0);
if (compute_v_) {
return TensorShapes({TensorShape({n}), TensorShape({n, n})});
} else {
return TensorShapes({TensorShape({n})});
}
}
void ComputeMatrix(OpKernelContext* context,
const InputConstMatrixMaps& inputs,
OutputMatrixMaps* outputs) final {
const int64 rows = inputs[0].rows();
if (rows == 0) {
// If X is an empty matrix (0 rows, 0 col), X * X' == X.
// Therefore, we return X.
return;
}
// This algorithm relies on denormals, so switch them back on locally.
port::ScopedDontFlushDenormal dont_flush_denormals;
Eigen::ComplexEigenSolver<OutputMatrix> eig(
inputs[0],
compute_v_ ? Eigen::ComputeEigenvectors : Eigen::EigenvaluesOnly);
// TODO(rmlarsen): Output more detailed error info on failure.
OP_REQUIRES(
context, eig.info() == Eigen::Success,
errors::InvalidArgument("Eigen decomposition was not "
"successful. The input might not be valid."));
outputs->at(0) = eig.eigenvalues().template cast<OutputScalar>();
if (compute_v_) {
outputs->at(1) = eig.eigenvectors();
}
}
private:
bool compute_v_;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_KERNELS_EIG_OP_IMPL_H_
| gunan/tensorflow | tensorflow/core/kernels/eig_op_impl.h | C | apache-2.0 | 3,642 |
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
#pragma once
#include <string>
#include <vector>
#include "rocksdb/rocksdb_namespace.h"
#include "rocksdb/slice.h"
#include "rocksdb/status.h"
#include "rocksdb/trace_record.h"
namespace ROCKSDB_NAMESPACE {
class IteratorTraceExecutionResult;
class MultiValuesTraceExecutionResult;
class SingleValueTraceExecutionResult;
class StatusOnlyTraceExecutionResult;
// Base class for the results of all types of trace records.
// Theses classes can be used to report the execution result of
// TraceRecord::Handler::Handle() or TraceRecord::Accept().
class TraceRecordResult {
public:
explicit TraceRecordResult(TraceType trace_type);
virtual ~TraceRecordResult() = default;
// Trace type of the corresponding TraceRecord.
virtual TraceType GetTraceType() const;
class Handler {
public:
virtual ~Handler() = default;
virtual Status Handle(const StatusOnlyTraceExecutionResult& result) = 0;
virtual Status Handle(const SingleValueTraceExecutionResult& result) = 0;
virtual Status Handle(const MultiValuesTraceExecutionResult& result) = 0;
virtual Status Handle(const IteratorTraceExecutionResult& result) = 0;
};
// Accept the handler.
virtual Status Accept(Handler* handler) = 0;
private:
TraceType trace_type_;
};
// Base class for the results from the trace record execution handler (created
// by TraceRecord::NewExecutionHandler()).
//
// The actual execution status or returned values may be hidden from
// TraceRecord::Handler::Handle and TraceRecord::Accept. For example, a
// GetQueryTraceRecord's execution calls DB::Get() internally. DB::Get() may
// return Status::NotFound() but TraceRecord::Handler::Handle() or
// TraceRecord::Accept() will still return Status::OK(). The actual status from
// DB::Get() and the returned value string may be saved in a
// SingleValueTraceExecutionResult.
class TraceExecutionResult : public TraceRecordResult {
public:
TraceExecutionResult(uint64_t start_timestamp, uint64_t end_timestamp,
TraceType trace_type);
// Execution start/end timestamps and request latency in microseconds.
virtual uint64_t GetStartTimestamp() const;
virtual uint64_t GetEndTimestamp() const;
inline uint64_t GetLatency() const {
return GetEndTimestamp() - GetStartTimestamp();
}
private:
uint64_t ts_start_;
uint64_t ts_end_;
};
// Result for operations that only return a single Status.
// Example operation: DB::Write()
class StatusOnlyTraceExecutionResult : public TraceExecutionResult {
public:
StatusOnlyTraceExecutionResult(Status status, uint64_t start_timestamp,
uint64_t end_timestamp, TraceType trace_type);
virtual ~StatusOnlyTraceExecutionResult() override = default;
// Return value of DB::Write(), etc.
virtual const Status& GetStatus() const;
virtual Status Accept(Handler* handler) override;
private:
Status status_;
};
// Result for operations that return a Status and a value.
// Example operation: DB::Get()
class SingleValueTraceExecutionResult : public TraceExecutionResult {
public:
SingleValueTraceExecutionResult(Status status, const std::string& value,
uint64_t start_timestamp,
uint64_t end_timestamp, TraceType trace_type);
SingleValueTraceExecutionResult(Status status, std::string&& value,
uint64_t start_timestamp,
uint64_t end_timestamp, TraceType trace_type);
virtual ~SingleValueTraceExecutionResult() override;
// Return status of DB::Get().
virtual const Status& GetStatus() const;
// Value for the searched key.
virtual const std::string& GetValue() const;
virtual Status Accept(Handler* handler) override;
private:
Status status_;
std::string value_;
};
// Result for operations that return multiple Status(es) and values as vectors.
// Example operation: DB::MultiGet()
class MultiValuesTraceExecutionResult : public TraceExecutionResult {
public:
MultiValuesTraceExecutionResult(std::vector<Status> multi_status,
std::vector<std::string> values,
uint64_t start_timestamp,
uint64_t end_timestamp, TraceType trace_type);
virtual ~MultiValuesTraceExecutionResult() override;
// Returned Status(es) of DB::MultiGet().
virtual const std::vector<Status>& GetMultiStatus() const;
// Returned values for the searched keys.
virtual const std::vector<std::string>& GetValues() const;
virtual Status Accept(Handler* handler) override;
private:
std::vector<Status> multi_status_;
std::vector<std::string> values_;
};
// Result for Iterator operations.
// Example operations: Iterator::Seek(), Iterator::SeekForPrev()
class IteratorTraceExecutionResult : public TraceExecutionResult {
public:
IteratorTraceExecutionResult(bool valid, Status status, PinnableSlice&& key,
PinnableSlice&& value, uint64_t start_timestamp,
uint64_t end_timestamp, TraceType trace_type);
IteratorTraceExecutionResult(bool valid, Status status,
const std::string& key, const std::string& value,
uint64_t start_timestamp, uint64_t end_timestamp,
TraceType trace_type);
virtual ~IteratorTraceExecutionResult() override;
// Return if the Iterator is valid.
virtual bool GetValid() const;
// Return the status of the Iterator.
virtual const Status& GetStatus() const;
// Key of the current iterating entry, empty if GetValid() is false.
virtual Slice GetKey() const;
// Value of the current iterating entry, empty if GetValid() is false.
virtual Slice GetValue() const;
virtual Status Accept(Handler* handler) override;
private:
bool valid_;
Status status_;
PinnableSlice key_;
PinnableSlice value_;
};
} // namespace ROCKSDB_NAMESPACE
| arangodb/arangodb | 3rdParty/rocksdb/6.29/include/rocksdb/trace_record_result.h | C | apache-2.0 | 6,266 |
#!/usr/bin/env python
# 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.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def test_gluon_trainer_type():
def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type')
if __name__ == "__main__":
test_gluon_trainer_type()
| szha/mxnet | tests/nightly/dist_async_kvstore.py | Python | apache-2.0 | 1,994 |
/*
* Copyright 2015 JBoss, by Red Hat, 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 org.uberfire.ext.wires.bpmn.client.commands.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.ext.wires.bpmn.client.commands.Command;
import org.uberfire.ext.wires.bpmn.client.commands.ResultType;
import org.uberfire.ext.wires.bpmn.client.commands.Results;
import org.uberfire.ext.wires.bpmn.client.rules.RuleManager;
/**
* A batch of Commands to be executed as an atomic unit
*/
public class BatchCommand implements Command {
private List<Command> commands;
public BatchCommand( final List<Command> commands ) {
this.commands = PortablePreconditions.checkNotNull( "commands",
commands );
}
public BatchCommand( final Command... commands ) {
this.commands = Arrays.asList( PortablePreconditions.checkNotNull( "commands",
commands ) );
}
@Override
public Results apply( final RuleManager ruleManager ) {
final Results results = new DefaultResultsImpl();
final Stack<Command> appliedCommands = new Stack<Command>();
for ( Command command : commands ) {
results.getMessages().addAll( command.apply( ruleManager ).getMessages() );
if ( results.contains( ResultType.ERROR ) ) {
for ( Command undo : appliedCommands ) {
undo.undo( ruleManager );
}
return results;
} else {
appliedCommands.add( command );
}
}
return results;
}
@Override
public Results undo( final RuleManager ruleManager ) {
final Results results = new DefaultResultsImpl();
final Stack<Command> appliedCommands = new Stack<Command>();
for ( Command command : commands ) {
results.getMessages().addAll( command.undo( ruleManager ).getMessages() );
if ( results.contains( ResultType.ERROR ) ) {
for ( Command cmd : appliedCommands ) {
cmd.apply( ruleManager );
}
return results;
} else {
appliedCommands.add( command );
}
}
return results;
}
}
| dgutierr/uberfire-extensions | uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/main/java/org/uberfire/ext/wires/bpmn/client/commands/impl/BatchCommand.java | Java | apache-2.0 | 2,980 |
/*
* Copyright 2010 Henry Coles
*
* 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.pitest.mutationtest;
public class MutableIncrement {
public static int increment() {
int i = 42;
i++;
return i;
}
}
| jacksonpradolima/pitest | pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java | Java | apache-2.0 | 735 |
#!/usr/bin/env bash
set -e
cd "$(dirname "$BASH_SOURCE")/.."
rm -rf vendor/
source 'hack/.vendor-helpers.sh'
# the following lines are in sorted order, FYI
clone git github.com/Azure/go-ansiterm 70b2c90b260171e829f1ebd7c17f600c11858dbe
clone git github.com/Sirupsen/logrus v0.8.2 # logrus is a common dependency among multiple deps
clone git github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a
clone git github.com/go-check/check 11d3bc7aa68e238947792f30573146a3231fc0f1
clone git github.com/gorilla/context 14f550f51a
clone git github.com/gorilla/mux e444e69cbd
clone git github.com/kr/pty 5cf931ef8f
clone git github.com/mattn/go-shellwords v1.0.0
clone git github.com/mattn/go-sqlite3 v1.1.0
clone git github.com/microsoft/hcsshim de43b42b5ce14dfdcbeedb0628b0032174d89caa
clone git github.com/mistifyio/go-zfs v2.1.1
clone git github.com/tchap/go-patricia v2.1.0
clone git github.com/vdemeester/shakers 3c10293ce22b900c27acad7b28656196fcc2f73b
clone git golang.org/x/net 47990a1ba55743e6ef1affd3a14e5bac8553615d https://github.com/golang/net.git
#get libnetwork packages
clone git github.com/docker/libnetwork 04cc1fa0a89f8c407b7be8cab883d4b17531ea7d
clone git github.com/armon/go-metrics eb0af217e5e9747e41dd5303755356b62d28e3ec
clone git github.com/hashicorp/go-msgpack 71c2886f5a673a35f909803f38ece5810165097b
clone git github.com/hashicorp/memberlist 9a1e242e454d2443df330bdd51a436d5a9058fc4
clone git github.com/hashicorp/serf 7151adcef72687bf95f451a2e0ba15cb19412bf2
clone git github.com/docker/libkv c2aac5dbbaa5c872211edea7c0f32b3bd67e7410
clone git github.com/vishvananda/netns 604eaf189ee867d8c147fafc28def2394e878d25
clone git github.com/vishvananda/netlink 4b5dce31de6d42af5bb9811c6d265472199e0fec
clone git github.com/BurntSushi/toml f706d00e3de6abe700c994cdd545a1a4915af060
clone git github.com/samuel/go-zookeeper d0e0d8e11f318e000a8cc434616d69e329edc374
clone git github.com/deckarep/golang-set ef32fa3046d9f249d399f98ebaf9be944430fd1d
clone git github.com/coreos/etcd v2.2.0
fix_rewritten_imports github.com/coreos/etcd
clone git github.com/ugorji/go 5abd4e96a45c386928ed2ca2a7ef63e2533e18ec
clone git github.com/hashicorp/consul v0.5.2
clone git github.com/boltdb/bolt v1.1.0
# get graph and distribution packages
clone git github.com/docker/distribution 568bf038af6d65b376165d02886b1c7fcaef1f61
clone git github.com/vbatts/tar-split v0.9.11
clone git github.com/docker/notary 45de2828b5e0083bfb4e9a5a781eddb05e2ef9d0
clone git google.golang.org/grpc 174192fc93efcb188fc8f46ca447f0da606b6885 https://github.com/grpc/grpc-go.git
clone git github.com/miekg/pkcs11 80f102b5cac759de406949c47f0928b99bd64cdf
clone git github.com/jfrazelle/go v1.5.1-1
clone git github.com/agl/ed25519 d2b94fd789ea21d12fac1a4443dd3a3f79cda72c
clone git github.com/opencontainers/runc v0.0.5 # libcontainer
clone git github.com/opencontainers/specs 46d949ea81080c5f60dfb72ee91468b1e9fb2998 # specs
clone git github.com/seccomp/libseccomp-golang 1b506fc7c24eec5a3693cdcbed40d9c226cfc6a1
# libcontainer deps (see src/github.com/opencontainers/runc/Godeps/Godeps.json)
clone git github.com/coreos/go-systemd v4
clone git github.com/godbus/dbus v3
clone git github.com/syndtr/gocapability 2c00daeb6c3b45114c80ac44119e7b8801fdd852
clone git github.com/golang/protobuf f7137ae6b19afbfd61a94b746fda3b3fe0491874
# gelf logging driver deps
clone git github.com/Graylog2/go-gelf 6c62a85f1d47a67f2a5144c0e745b325889a8120
clone git github.com/fluent/fluent-logger-golang v1.0.0
# fluent-logger-golang deps
clone git github.com/philhofer/fwd 899e4efba8eaa1fea74175308f3fae18ff3319fa
clone git github.com/tinylib/msgp 75ee40d2601edf122ef667e2a07d600d4c44490c
# fsnotify
clone git gopkg.in/fsnotify.v1 v1.2.0
# awslogs deps
clone git github.com/aws/aws-sdk-go v0.9.9
clone git github.com/vaughan0/go-ini a98ad7ee00ec53921f08832bc06ecf7fd600e6a1
clean
| Neverous/docker | hack/vendor.sh | Shell | apache-2.0 | 3,860 |
// Copyright 2016 The Bazel 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.
package com.google.devtools.build.android.desugar.testdata;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.stream.Collectors;
public interface InterfaceWithLambda {
String ZERO = String.valueOf(0);
List<String> DIGITS =
ImmutableList.of(0, 1)
.stream()
.map(i -> i == 0 ? ZERO : String.valueOf(i))
.collect(Collectors.toList());
}
| aehlig/bazel | src/test/java/com/google/devtools/build/android/desugar/testdata/InterfaceWithLambda.java | Java | apache-2.0 | 1,029 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>MPL Interoperability</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../index.html" title="Chapter 1. Boost.TypeTraits">
<link rel="up" href="../index.html" title="Chapter 1. Boost.TypeTraits">
<link rel="prev" href="intrinsics.html" title="Support for Compiler Intrinsics">
<link rel="next" href="examples.html" title="Examples">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="intrinsics.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="examples.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="boost_typetraits.mpl"></a><a class="link" href="mpl.html" title="MPL Interoperability">MPL Interoperability</a>
</h2></div></div></div>
<p>
All the value based traits in this library conform to MPL's requirements for
an <a href="../../../../../libs/mpl/doc/refmanual/integral-constant.html" target="_top">Integral
Constant type</a>: that includes a number of rather intrusive workarounds
for broken compilers.
</p>
<p>
Purely as an implementation detail, this means that <code class="computeroutput"><a class="link" href="reference/integral_constant.html" title="integral_constant">true_type</a></code>
inherits from <a href="../../../../../libs/mpl/doc/refmanual/bool.html" target="_top"><code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">mpl</span><span class="special">::</span><span class="identifier">true_</span></code></a>,
<code class="computeroutput"><a class="link" href="reference/integral_constant.html" title="integral_constant">false_type</a></code>
inherits from <a href="../../../../../libs/mpl/doc/refmanual/bool.html" target="_top"><code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">mpl</span><span class="special">::</span><span class="identifier">false_</span></code></a>,
and <code class="computeroutput"><a class="link" href="reference/integral_constant.html" title="integral_constant">integral_constant</a><span class="special"><</span><span class="identifier">T</span><span class="special">,</span>
<span class="identifier">v</span><span class="special">></span></code>
inherits from <a href="../../../../../libs/mpl/doc/refmanual/integral-c.html" target="_top"><code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">mpl</span><span class="special">::</span><span class="identifier">integral_c</span><span class="special"><</span><span class="identifier">T</span><span class="special">,</span><span class="identifier">v</span><span class="special">></span></code></a>
(provided <code class="computeroutput"><span class="identifier">T</span></code> is not <code class="computeroutput"><span class="keyword">bool</span></code>)
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2000, 2011 Adobe Systems Inc, David Abrahams,
Frederic Bron, Steve Cleary, Beman Dawes, Aleksey Gurtovoy, Howard Hinnant,
Jesse Jones, Mat Marcus, Itay Maman, John Maddock, Alexander Nasonov, Thorsten
Ottosen, Roman Perepelitsa, Robert Ramey, Jeremy Siek, Robert Stewart and Steven
Watanabe<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="intrinsics.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="examples.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| flingone/frameworks_base_cmds_remoted | libs/boost/libs/type_traits/doc/html/boost_typetraits/mpl.html | HTML | apache-2.0 | 5,421 |
/* Copyright 2016 The TensorFlow 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.
==============================================================================*/
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER5(UnaryOp, CPU, "Round", functor::round, Eigen::half, float, double,
int32, int64_t);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER5(UnaryOp, GPU, "Round", functor::round, Eigen::half, float, double,
int32, int64);
#endif
#endif
} // namespace tensorflow
| frreiss/tensorflow-fred | tensorflow/core/kernels/cwise_op_round.cc | C++ | apache-2.0 | 1,086 |
# Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate certain
bootstrapping issues. Unit tests are in test_collections.
"""
from abc import ABCMeta, abstractmethod
import sys
__all__ = ["Hashable", "Iterable", "Iterator",
"Sized", "Container", "Callable",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
]
### ONE-TRICK PONIES ###
class Hashable:
__metaclass__ = ABCMeta
@abstractmethod
def __hash__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Hashable:
for B in C.__mro__:
if "__hash__" in B.__dict__:
if B.__dict__["__hash__"]:
return True
break
return NotImplemented
class Iterable:
__metaclass__ = ABCMeta
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
if any("__iter__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
Iterable.register(str)
class Iterator(Iterable):
@abstractmethod
def __next__(self):
raise StopIteration
def __iter__(self):
return self
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
if any("next" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Sized:
__metaclass__ = ABCMeta
@abstractmethod
def __len__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
if any("__len__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Container:
__metaclass__ = ABCMeta
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if any("__contains__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Callable:
__metaclass__ = ABCMeta
@abstractmethod
def __call__(self, *args, **kwds):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Callable:
if any("__call__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
### SETS ###
class Set(Sized, Iterable, Container):
"""A set is a finite, iterable container.
This class provides concrete generic implementations of all
methods except for __contains__, __iter__ and __len__.
To override the comparisons (presumably for speed, as the
semantics are fixed), all you have to do is redefine __le__ and
then the other operations will automatically follow suit.
"""
def __le__(self, other):
if not isinstance(other, Set):
return NotImplemented
if len(self) > len(other):
return False
for elem in self:
if elem not in other:
return False
return True
def __lt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) < len(other) and self.__le__(other)
def __gt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other < self
def __ge__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other <= self
def __eq__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) == len(other) and self.__le__(other)
def __ne__(self, other):
return not (self == other)
@classmethod
def _from_iterable(cls, it):
'''Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.
'''
return cls(it)
def __and__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
return self._from_iterable(value for value in other if value in self)
def isdisjoint(self, other):
for value in other:
if value in self:
return False
return True
def __or__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
chain = (e for s in (self, other) for e in s)
return self._from_iterable(chain)
def __sub__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return self._from_iterable(value for value in self
if value not in other)
def __xor__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return (self - other) | (other - self)
# Sets are not hashable by default, but subclasses can change this
__hash__ = None
def _hash(self):
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
regardless of the order of the elements; so there's not much
freedom for __eq__ or __hash__. We match the algorithm used
by the built-in frozenset type.
"""
MAX = sys.maxint
MASK = 2 * MAX + 1
n = len(self)
h = 1927868237 * (n + 1)
h &= MASK
for x in self:
hx = hash(x)
h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
h &= MASK
h = h * 69069 + 907133923
h &= MASK
if h > MAX:
h -= MASK + 1
if h == -1:
h = 590923713
return h
Set.register(frozenset)
class MutableSet(Set):
@abstractmethod
def add(self, value):
"""Return True if it was added, False if already there."""
raise NotImplementedError
@abstractmethod
def discard(self, value):
"""Return True if it was deleted, False if not there."""
raise NotImplementedError
def remove(self, value):
"""Remove an element. If not a member, raise a KeyError."""
if value not in self:
raise KeyError(value)
self.discard(value)
def pop(self):
"""Return the popped value. Raise KeyError if empty."""
it = iter(self)
try:
value = it.__next__()
except StopIteration:
raise KeyError
self.discard(value)
return value
def clear(self):
"""This is slow (creates N new iterators!) but effective."""
try:
while True:
self.pop()
except KeyError:
pass
def __ior__(self, it):
for value in it:
self.add(value)
return self
def __iand__(self, c):
for value in self:
if value not in c:
self.discard(value)
return self
def __ixor__(self, it):
if not isinstance(it, Set):
it = self._from_iterable(it)
for value in it:
if value in self:
self.discard(value)
else:
self.add(value)
return self
def __isub__(self, it):
for value in it:
self.discard(value)
return self
MutableSet.register(set)
### MAPPINGS ###
class Mapping(Sized, Iterable, Container):
@abstractmethod
def __getitem__(self, key):
raise KeyError
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def iterkeys(self):
return iter(self)
def itervalues(self):
for key in self:
yield self[key]
def iteritems(self):
for key in self:
yield (key, self[key])
def keys(self):
return list(self)
def items(self):
return [(key, self[key]) for key in self]
def values(self):
return [self[key] for key in self]
# Mappings are not hashable by default, but subclasses can change this
__hash__ = None
def __eq__(self, other):
return isinstance(other, Mapping) and \
dict(self.items()) == dict(other.items())
def __ne__(self, other):
return not (self == other)
class MappingView(Sized):
def __init__(self, mapping):
self._mapping = mapping
def __len__(self):
return len(self._mapping)
class KeysView(MappingView, Set):
def __contains__(self, key):
return key in self._mapping
def __iter__(self):
for key in self._mapping:
yield key
class ItemsView(MappingView, Set):
def __contains__(self, item):
key, value = item
try:
v = self._mapping[key]
except KeyError:
return False
else:
return v == value
def __iter__(self):
for key in self._mapping:
yield (key, self._mapping[key])
class ValuesView(MappingView):
def __contains__(self, value):
for key in self._mapping:
if value == self._mapping[key]:
return True
return False
def __iter__(self):
for key in self._mapping:
yield self._mapping[key]
class MutableMapping(Mapping):
@abstractmethod
def __setitem__(self, key, value):
raise KeyError
@abstractmethod
def __delitem__(self, key):
raise KeyError
__marker = object()
def pop(self, key, default=__marker):
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError
value = self[key]
del self[key]
return key, value
def clear(self):
try:
while True:
self.popitem()
except KeyError:
pass
def update(self, other=(), **kwds):
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
def setdefault(self, key, default=None):
try:
return self[key]
except KeyError:
self[key] = default
return default
MutableMapping.register(dict)
### SEQUENCES ###
class Sequence(Sized, Iterable, Container):
"""All the operations on a read-only sequence.
Concrete subclasses must override __new__ or __init__,
__getitem__, and __len__.
"""
@abstractmethod
def __getitem__(self, index):
raise IndexError
def __iter__(self):
i = 0
try:
while True:
v = self[i]
yield v
i += 1
except IndexError:
return
def __contains__(self, value):
for v in self:
if v == value:
return True
return False
def __reversed__(self):
for i in reversed(range(len(self))):
yield self[i]
def index(self, value):
for i, v in enumerate(self):
if v == value:
return i
raise ValueError
def count(self, value):
return sum(1 for v in self if v == value)
Sequence.register(tuple)
Sequence.register(basestring)
Sequence.register(buffer)
class MutableSequence(Sequence):
@abstractmethod
def __setitem__(self, index, value):
raise IndexError
@abstractmethod
def __delitem__(self, index):
raise IndexError
@abstractmethod
def insert(self, index, value):
raise IndexError
def append(self, value):
self.insert(len(self), value)
def reverse(self):
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i]
def extend(self, values):
for v in values:
self.append(v)
def pop(self, index=-1):
v = self[index]
del self[index]
return v
def remove(self, value):
del self[self.index(value)]
def __iadd__(self, values):
self.extend(values)
MutableSequence.register(list)
| tempbottle/restcommander | play-1.2.4/python/Lib/_abcoll.py | Python | apache-2.0 | 13,666 |
<!DOCTYPE html>
<html lang="en" ng-app="jpm">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="/releases/5.0.0/css/style.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="/js/releases.js"></script>
<!-- Begin Jekyll SEO tag v2.6.1 -->
<title>basename ( ‘;’ FILEPATH ) +</title>
<meta name="generator" content="Jekyll v3.8.5" />
<meta property="og:title" content="basename ( ‘;’ FILEPATH ) +" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="public String _basename(String args[]) { if (args.length < 2) { domain.warning("Need at least one file name for ${basename;...}"); return null; } String del = ""; StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.length; i++) { File f = domain.getFile(args[i]); if (f.exists() && f.getParentFile().exists()) { sb.append(del); sb.append(f.getName()); del = ","; } } return sb.toString();" />
<meta property="og:description" content="public String _basename(String args[]) { if (args.length < 2) { domain.warning("Need at least one file name for ${basename;...}"); return null; } String del = ""; StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.length; i++) { File f = domain.getFile(args[i]); if (f.exists() && f.getParentFile().exists()) { sb.append(del); sb.append(f.getName()); del = ","; } } return sb.toString();" />
<script type="application/ld+json">
{"@type":"WebPage","headline":"basename ( ‘;’ FILEPATH ) +","url":"/releases/5.0.0/macros/basename.html","description":"public String _basename(String args[]) { if (args.length < 2) { domain.warning("Need at least one file name for ${basename;...}"); return null; } String del = ""; StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.length; i++) { File f = domain.getFile(args[i]); if (f.exists() && f.getParentFile().exists()) { sb.append(del); sb.append(f.getName()); del = ","; } } return sb.toString();","@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
</head>
<body>
<ul class="container12 menu-bar">
<li span=11><a class=menu-link href="/releases/5.0.0/"><img
class=menu-logo src="/releases/5.0.0/img/bnd-80x40-white.png"></a>
<a href="/releases/5.0.0/chapters/110-introduction.html">Intro
</a><a href="/releases/5.0.0/chapters/800-headers.html">Headers
</a><a href="/releases/5.0.0/chapters/825-instructions-ref.html">Instructions
</a><a href="/releases/5.0.0/chapters/855-macros-ref.html">Macros
</a><a href="/releases/5.0.0/chapters/400-commands.html">Commands
</a><div class="releases"><button class="dropbtn">5.0.0</button><div class="dropdown-content"></div></div>
<li class=menu-link span=1>
<a href="https://github.com/bndtools/bnd" target="_"><img
style="position:absolute;top:0;right:0;margin:0;padding:0;z-index:100"
src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67"
alt="Fork me on GitHub"
data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
</ul>
<ul class=container12>
<li span=3>
<div>
<ul class="side-nav">
<li><a href="/releases/5.0.0/chapters/110-introduction.html">Introduction</a>
<li><a href="/releases/5.0.0/chapters/120-install.html">How to install bnd</a>
<li><a href="/releases/5.0.0/chapters/123-tour-workspace.html">Guided Tour</a>
<li><a href="/releases/5.0.0/chapters/125-tour-features.html">Guided Tour Workspace & Projects</a>
<li><a href="/releases/5.0.0/chapters/130-concepts.html">Concepts</a>
<li><a href="/releases/5.0.0/chapters/140-best-practices.html">Best practices</a>
<li><a href="/releases/5.0.0/chapters/150-build.html">Build</a>
<li><a href="/releases/5.0.0/chapters/155-project-setup.html">Project Setup</a>
<li><a href="/releases/5.0.0/chapters/160-jars.html">Generating JARs</a>
<li><a href="/releases/5.0.0/chapters/170-versioning.html">Versioning</a>
<li><a href="/releases/5.0.0/chapters/180-baselining.html">Baselining</a>
<li><a href="/releases/5.0.0/chapters/200-components.html">Service Components</a>
<li><a href="/releases/5.0.0/chapters/210-metatype.html">Metatype</a>
<li><a href="/releases/5.0.0/chapters/220-contracts.html">Contracts</a>
<li><a href="/releases/5.0.0/chapters/230-manifest-annotations.html">Bundle Annotations</a>
<li><a href="/releases/5.0.0/chapters/235-accessor-properties.html">Accessor Properties</a>
<li><a href="/releases/5.0.0/chapters/240-spi-annotations.html">SPI Annotations</a>
<li><a href="/releases/5.0.0/chapters/250-resolving.html">Resolving Dependencies</a>
<li><a href="/releases/5.0.0/chapters/300-launching.html">Launching</a>
<li><a href="/releases/5.0.0/chapters/305-startlevels.html">Startlevels</a>
<li><a href="/releases/5.0.0/chapters/310-testing.html">Testing</a>
<li><a href="/releases/5.0.0/chapters/315-launchpad-testing.html">Testing with Launchpad</a>
<li><a href="/releases/5.0.0/chapters/320-packaging.html">Packaging Applications</a>
<li><a href="/releases/5.0.0/chapters/330-jpms.html">JPMS Libraries</a>
<li><a href="/releases/5.0.0/chapters/390-wrapping.html">Wrapping Libraries to OSGi Bundles</a>
<li><a href="/releases/5.0.0/chapters/395-generating-documentation.html">Generating Documentation</a>
<li><a href="/releases/5.0.0/chapters/400-commands.html">Commands</a>
<li><a href="/releases/5.0.0/chapters/600-developer.html">For Developers</a>
<li><a href="/releases/5.0.0/chapters/650-windows.html">Tips for Windows users</a>
<li><a href="/releases/5.0.0/chapters/700-tools.html">Tools bound to bnd</a>
<li><a href="/releases/5.0.0/chapters/800-headers.html">Headers</a>
<li><a href="/releases/5.0.0/chapters/820-instructions.html">Instruction Reference</a>
<li><a href="/releases/5.0.0/chapters/825-instructions-ref.html">Instruction Index</a>
<li><a href="/releases/5.0.0/chapters/850-macros.html">Macro Reference</a>
<li><a href="/releases/5.0.0/chapters/855-macros-ref.html">Macro Index</a>
<li><a href="/releases/5.0.0/chapters/870-plugins.html">Plugins</a>
<li><a href="/releases/5.0.0/chapters/880-settings.html">Settings</a>
<li><a href="/releases/5.0.0/chapters/900-errors.html">Errors</a>
<li><a href="/releases/5.0.0/chapters/910-warnings.html">Warnings</a>
<li><a href="/releases/5.0.0/chapters/920-faq.html">Frequently Asked Questions</a>
</ul>
</div>
<li span=9>
<div class=notes-margin>
<h1> basename ( ';' FILEPATH ) +</h1>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public String _basename(String args[]) {
if (args.length < 2) {
domain.warning("Need at least one file name for ${basename;...}");
return null;
}
String del = "";
StringBuilder sb = new StringBuilder();
for (int i = 1; i < args.length; i++) {
File f = domain.getFile(args[i]);
if (f.exists() && f.getParentFile().exists()) {
sb.append(del);
sb.append(f.getName());
del = ",";
}
}
return sb.toString();
}
</code></pre></div></div>
</div>
</ul>
<nav class=next-prev>
<a href='/releases/5.0.0/macros/basedir.html'></a> <a href='/releases/5.0.0/macros/basenameext.html'></a>
</nav>
<footer class="container12" style="border-top: 1px solid black;padding:10px 0">
<ul span=12 row>
<li span=12>
<ul>
<li><a href="/releases/5.0.0/">GitHub</a>
</ul>
</ul>
</footer>
</body>
</html>
| psoreide/bnd | docs/releases/5.0.0/macros/basename.html | HTML | apache-2.0 | 8,442 |
#ifndef _INCLUDED_CAMPAIGN_FRAME_H
#define _INCLUDED_CAMPAIGN_FRAME_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Frame.h>
class CampaignPanel;
// frame used to hold the campaign screen panels
class CampaignFrame : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CampaignFrame, vgui::Frame );
CampaignFrame(Panel *parent, const char *panelName, bool showTaskbarIcon = true);
virtual ~CampaignFrame();
virtual void PerformLayout();
virtual void ApplySchemeSettings( vgui::IScheme *scheme );
CampaignPanel* m_pCampaignPanel;
};
#endif // _INCLUDED_CAMPAIGN_FRAME_H | ppittle/AlienSwarmDirectorMod | trunk/src/game/client/swarm/vgui/campaignframe.h | C | apache-2.0 | 584 |
#import "MWMButton.h"
#import "MWMCircularProgress.h"
@interface MWMCircularProgressView : UIView
@property(nonatomic, readonly) BOOL animating;
@property(nonatomic) MWMCircularProgressState state;
@property(nonatomic) BOOL isInvertColor;
- (nonnull instancetype)initWithFrame:(CGRect)frame
__attribute__((unavailable("initWithFrame is not available")));
- (nonnull instancetype)init __attribute__((unavailable("init is not available")));
- (void)setSpinnerColoring:(MWMImageColoring)coloring;
- (void)setSpinnerBackgroundColor:(nonnull UIColor *)backgroundColor;
- (void)setImageName:(nonnull NSString *)imageName forState:(MWMCircularProgressState)state;
- (void)setColor:(nonnull UIColor *)color forState:(MWMCircularProgressState)state;
- (void)setColoring:(MWMButtonColoring)coloring forState:(MWMCircularProgressState)state;
- (void)animateFromValue:(CGFloat)fromValue toValue:(CGFloat)toValue;
- (void)updatePath:(CGFloat)progress;
@end
| dobriy-eeh/omim | iphone/Maps/Classes/CustomViews/CircularProgress/MWMCircularProgressView.h | C | apache-2.0 | 956 |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.wire;
/**
* Class to represent {@link FileSystemCommand} options.
*/
public final class FileSystemCommandOptions {
private PersistCommandOptions mPersistCommandOptions;
/**
* Creates a new instance of {@link FileSystemCommandOptions}.
*/
public FileSystemCommandOptions() {}
/**
* @return the persist options
*/
public PersistCommandOptions getPersistOptions() {
return mPersistCommandOptions;
}
/**
* Set the persist options.
*
* @param persistCommandOptions the persist options
*/
public void setPersistOptions(PersistCommandOptions persistCommandOptions) {
mPersistCommandOptions = persistCommandOptions;
}
}
| wwjiang007/alluxio | core/common/src/main/java/alluxio/wire/FileSystemCommandOptions.java | Java | apache-2.0 | 1,198 |
/*
* Copyright 2015-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.cxx;
import com.facebook.buck.rules.Tool;
import com.google.common.collect.ImmutableList;
import java.util.Optional;
public class ClangCompiler extends DefaultCompiler {
public ClangCompiler(Tool tool) {
super(tool);
}
@Override
public Optional<ImmutableList<String>> debugCompilationDirFlags(String debugCompilationDir) {
return Optional.of(
ImmutableList.of("-Xclang", "-fdebug-compilation-dir", "-Xclang", debugCompilationDir));
}
@Override
public Optional<ImmutableList<String>> getFlagsForColorDiagnostics() {
return Optional.of(ImmutableList.of("-fcolor-diagnostics"));
}
@Override
public boolean isArgFileSupported() {
return true;
}
}
| sdwilsh/buck | src/com/facebook/buck/cxx/ClangCompiler.java | Java | apache-2.0 | 1,330 |
/*
Copyright 2013-2014, JUMA Technology
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.bcsphere.bluetooth;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import org.bcsphere.bluetooth.tools.BluetoothDetection;
import org.bcsphere.bluetooth.tools.Tools;
public class BCBluetooth extends CordovaPlugin {
public Context myContext = null;
private SharedPreferences sp;
private boolean isSetContext = true;
private IBluetooth bluetoothAPI = null;
private String versionOfAPI;
private CallbackContext newadvpacketContext;
private CallbackContext disconnectContext;
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final String TAG = "BCBluetooth";
//classical interface relative data structure
public HashMap<String, BluetoothSerialService> classicalServices = new HashMap<String, BluetoothSerialService>();
//when the accept services construct a connection , the service will remove from this map & append into classicalServices map for read/write interface call
public HashMap<String, BluetoothSerialService> acceptServices = new HashMap<String, BluetoothSerialService>();
public BCBluetooth() {
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
myContext = this.webView.getContext();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
myContext.registerReceiver(receiver, intentFilter);
sp = myContext.getSharedPreferences("VERSION_OF_API", 1);
BluetoothDetection.detectionBluetoothAPI(myContext);
try {
if ((versionOfAPI = sp.getString("API", "no_google"))
.equals("google")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothG43plus")
.newInstance();
} else if ((versionOfAPI = sp.getString("API", "no_samsung"))
.equals("samsung")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothSam42").newInstance();
} else if ((versionOfAPI = sp.getString("API", "no_htc"))
.equals("htc")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothHTC41").newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean execute(final String action, final JSONArray json,
final CallbackContext callbackContext) throws JSONException {
try {
if(bluetoothAPI != null){
if (isSetContext) {
bluetoothAPI.setContext(myContext);
isSetContext = false;
}
if (action.equals("getCharacteristics")) {
bluetoothAPI.getCharacteristics(json, callbackContext);
} else if (action.equals("getDescriptors")) {
bluetoothAPI.getDescriptors(json, callbackContext);
} else if (action.equals("removeServices")) {
bluetoothAPI.removeServices(json, callbackContext);
}
if (action.equals("stopScan")) {
bluetoothAPI.stopScan(json, callbackContext);
} else if (action.equals("getConnectedDevices")) {
bluetoothAPI.getConnectedDevices(json, callbackContext);
}
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
if (action.equals("startScan")) {
bluetoothAPI.startScan(json, callbackContext);
} else if (action.equals("connect")) {
bluetoothAPI.connect(json, callbackContext);
} else if (action.equals("disconnect")) {
bluetoothAPI.disconnect(json, callbackContext);
} else if (action.equals("getServices")) {
bluetoothAPI.getServices(json, callbackContext);
} else if (action.equals("writeValue")) {
bluetoothAPI.writeValue(json, callbackContext);
} else if (action.equals("readValue")) {
bluetoothAPI.readValue(json, callbackContext);
} else if (action.equals("setNotification")) {
bluetoothAPI.setNotification(json, callbackContext);
} else if (action.equals("getDeviceAllData")) {
bluetoothAPI.getDeviceAllData(json, callbackContext);
} else if (action.equals("addServices")) {
bluetoothAPI.addServices(json, callbackContext);
} else if (action.equals("getRSSI")) {
bluetoothAPI.getRSSI(json, callbackContext);
}
}
});
}
if (action.equals("addEventListener")) {
String eventName = Tools.getData(json, Tools.EVENT_NAME);
if (eventName.equals("newadvpacket") ) {
newadvpacketContext = callbackContext;
}else if(eventName.equals("disconnect")){
disconnectContext = callbackContext;
}
if(bluetoothAPI != null){
bluetoothAPI.addEventListener(json, callbackContext);
}
return true;
}
if (action.equals("getEnvironment")) {
JSONObject jo = new JSONObject();
Tools.addProperty(jo, "appID", "com.test.yourappid");
Tools.addProperty(jo, "deviceAddress", "N/A");
Tools.addProperty(jo, "api", versionOfAPI);
callbackContext.success(jo);
return true;
}
if (action.equals("openBluetooth")) {
if(!bluetoothAdapter.isEnabled()){
bluetoothAdapter.enable();
}
Tools.sendSuccessMsg(callbackContext);
return true;
}
if (action.equals("closeBluetooth")) {
if(bluetoothAdapter.isEnabled()){
bluetoothAdapter.disable();
}
Tools.sendSuccessMsg(callbackContext);
return true;
}
if (action.equals("getBluetoothState")) {
Log.i(TAG, "getBluetoothState");
JSONObject obj = new JSONObject();
if (bluetoothAdapter.isEnabled()) {
Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_TRUE);
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_FALSE);
callbackContext.success(obj);
}
return true;
}
if(action.equals("startClassicalScan")){
Log.i(TAG,"startClassicalScan");
if(bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.startDiscovery()){
callbackContext.success();
}else{
callbackContext.error("start classical scan error!");
}
}else{
callbackContext.error("your bluetooth is not open!");
}
}
if(action.equals("stopClassicalScan")){
Log.i(TAG,"stopClassicalScan");
if(bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.cancelDiscovery()){
callbackContext.success();
}else{
callbackContext.error("stop classical scan error!");
}
}else{
callbackContext.error("your bluetooth is not open!");
}
}
if(action.equals("rfcommConnect")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
String securestr = Tools.getData(json, Tools.SECURE);
String uuidstr = Tools.getData(json, Tools.UUID);
boolean secure = false;
if(securestr != null && securestr.equals("true")){
secure = true;
}
Log.i(TAG,"connect to "+deviceAddress);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
BluetoothSerialService classicalService = classicalServices.get(deviceAddress);
if(device != null && classicalService == null){
classicalService = new BluetoothSerialService();
classicalService.disconnectCallback = disconnectContext;
classicalServices.put(deviceAddress, classicalService);
}
if (device != null) {
classicalService.connectCallback = callbackContext;
classicalService.connect(device,uuidstr,secure);
} else {
callbackContext.error("Could not connect to " + deviceAddress);
}
}
if (action.equals("rfcommDisconnect")) {
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.connectCallback = null;
service.stop();
classicalServices.remove(deviceAddress);
callbackContext.success();
}else{
callbackContext.error("Could not disconnect to " + deviceAddress);
}
}
if(action.equals("rfcommListen")){
String name = Tools.getData(json, Tools.NAME);
String uuidstr = Tools.getData(json, Tools.UUID);
String securestr = Tools.getData(json, Tools.SECURE);
boolean secure = false;
if(securestr.equals("true")){
secure = true;
}
BluetoothSerialService service = new BluetoothSerialService();
service.listen(name, uuidstr, secure, this);
acceptServices.put(name+uuidstr, service);
}
if(action.equals("rfcommUnListen")){
String name = Tools.getData(json, Tools.NAME);
String uuidstr = Tools.getData(json, Tools.UUID);
BluetoothSerialService service = acceptServices.get(name+uuidstr);
if(service != null){
service.stop();
}
}
if(action.equals("rfcommWrite")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
String data = Tools.getData(json, Tools.WRITE_VALUE);
service.write(Tools.decodeBase64(data));
callbackContext.success();
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if(action.equals("rfcommRead")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
byte[] data = new byte[2048];
byte[] predata = service.buffer.array();
for(int i = 0;i < service.bufferSize;i++){
data[i] = predata[i];
}
JSONObject obj = new JSONObject();
//Tools.addProperty(obj, Tools.DEVICE_ADDRESS, deviceAddress);
Tools.addProperty(obj, Tools.VALUE, Tools.encodeBase64(data));
Tools.addProperty(obj, Tools.DATE, Tools.getDateString());
callbackContext.success(obj);
service.bufferSize = 0;
service.buffer.clear();
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if(action.equals("rfcommSubscribe")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.dataAvailableCallback = callbackContext;
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if (action.equals("rfcommUnsubscribe")) {
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.dataAvailableCallback = null;
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if (action.equals("getPairedDevices")) {
try {
Log.i(TAG, "getPairedDevices");
JSONArray ary = new JSONArray();
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
Iterator<BluetoothDevice> it = devices.iterator();
while (it.hasNext()) {
BluetoothDevice device = (BluetoothDevice) it.next();
JSONObject obj = new JSONObject();
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName());
ary.put(obj);
}
callbackContext.success(ary);
} catch (Exception e) {
Tools.sendErrorMsg(callbackContext);
} catch (java.lang.Error e) {
Tools.sendErrorMsg(callbackContext);
}
} else if (action.equals("createPair")) {
Log.i(TAG, "createPair");
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
JSONObject obj = new JSONObject();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
if (Tools.creatBond(device.getClass(), device)) {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.error(obj);
}
} else if (action.equals("removePair")) {
Log.i(TAG, "removePair");
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
JSONObject obj = new JSONObject();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
if (Tools.removeBond(device.getClass(), device)) {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.error(obj);
}
}
} catch (Exception e) {
Tools.sendErrorMsg(callbackContext);
} catch(Error e){
Tools.sendErrorMsg(callbackContext);
}
return true;
}
public BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 11) {
JSONObject joOpen = new JSONObject();
try {
joOpen.put("state", "open");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webView.sendJavascript("cordova.fireDocumentEvent('bluetoothopen')");
} else if (intent.getIntExtra(
BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 13) {
JSONObject joClose = new JSONObject();
try {
joClose.put("state", "close");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webView.sendJavascript("cordova.fireDocumentEvent('bluetoothclose')");
}else if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("new classical bluetooth device found!"+device.getAddress());
// Add the name and address to an array adapter to show in a ListView
JSONObject obj = new JSONObject();
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName());
Tools.addProperty(obj, Tools.IS_CONNECTED, Tools.IS_FALSE);
Tools.addProperty(obj, Tools.TYPE, "Classical");
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK , obj);
pluginResult.setKeepCallback(true);
newadvpacketContext.sendPluginResult(pluginResult);
}
}
};
}
| bcsphere/bcexplorer | plugins/org/src/android/org/bcsphere/bluetooth/BCBluetooth.java | Java | apache-2.0 | 15,604 |
class AddSolutionToLevels < ActiveRecord::Migration
def change
add_column :levels, :solution_level_source_id, :integer
end
end
| giroto/teste | db/migrate/20140205192227_add_solution_to_levels.rb | Ruby | apache-2.0 | 135 |
/***************************************************************************/
/* */
/* ftvalid.h */
/* */
/* FreeType validation support (specification). */
/* */
/* Copyright 2004 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __FTVALID_H__
#define __FTVALID_H__
#include <ft2build.h>
#include FT_CONFIG_STANDARD_LIBRARY_H /* for ft_setjmp and ft_longjmp */
FT_BEGIN_HEADER
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** ****/
/**** V A L I D A T I O N ****/
/**** ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* handle to a validation object */
typedef struct FT_ValidatorRec_ volatile* FT_Validator;
/*************************************************************************/
/* */
/* There are three distinct validation levels defined here: */
/* */
/* FT_VALIDATE_DEFAULT :: */
/* A table that passes this validation level can be used reliably by */
/* FreeType. It generally means that all offsets have been checked to */
/* prevent out-of-bound reads, that array counts are correct, etc. */
/* */
/* FT_VALIDATE_TIGHT :: */
/* A table that passes this validation level can be used reliably and */
/* doesn't contain invalid data. For example, a charmap table that */
/* returns invalid glyph indices will not pass, even though it can */
/* be used with FreeType in default mode (the library will simply */
/* return an error later when trying to load the glyph). */
/* */
/* It also checks that fields which must be a multiple of 2, 4, or 8, */
/* don't have incorrect values, etc. */
/* */
/* FT_VALIDATE_PARANOID :: */
/* Only for font debugging. Checks that a table follows the */
/* specification by 100%. Very few fonts will be able to pass this */
/* level anyway but it can be useful for certain tools like font */
/* editors/converters. */
/* */
typedef enum FT_ValidationLevel_ {
FT_VALIDATE_DEFAULT = 0,
FT_VALIDATE_TIGHT,
FT_VALIDATE_PARANOID
} FT_ValidationLevel;
/* validator structure */
typedef struct FT_ValidatorRec_ {
const FT_Byte* base; /* address of table in memory */
const FT_Byte* limit; /* `base' + sizeof(table) in memory */
FT_ValidationLevel level; /* validation level */
FT_Error error; /* error returned. 0 means success */
ft_jmp_buf jump_buffer; /* used for exception handling */
} FT_ValidatorRec;
#define FT_VALIDATOR(x) ((FT_Validator)(x))
FT_BASE(void)
ft_validator_init(FT_Validator valid, const FT_Byte* base, const FT_Byte* limit,
FT_ValidationLevel level);
/* Do not use this. It's broken and will cause your validator to crash */
/* if you run it on an invalid font. */
FT_BASE(FT_Int)
ft_validator_run(FT_Validator valid);
/* Sets the error field in a validator, then calls `longjmp' to return */
/* to high-level caller. Using `setjmp/longjmp' avoids many stupid */
/* error checks within the validation routines. */
/* */
FT_BASE(void)
ft_validator_error(FT_Validator valid, FT_Error error);
/* Calls ft_validate_error. Assumes that the `valid' local variable */
/* holds a pointer to the current validator object. */
/* */
/* Use preprocessor prescan to pass FT_ERR_PREFIX. */
/* */
#define FT_INVALID(_prefix, _error) FT_INVALID_(_prefix, _error)
#define FT_INVALID_(_prefix, _error) ft_validator_error(valid, _prefix##_error)
/* called when a broken table is detected */
#define FT_INVALID_TOO_SHORT FT_INVALID(FT_ERR_PREFIX, Invalid_Table)
/* called when an invalid offset is detected */
#define FT_INVALID_OFFSET FT_INVALID(FT_ERR_PREFIX, Invalid_Offset)
/* called when an invalid format/value is detected */
#define FT_INVALID_FORMAT FT_INVALID(FT_ERR_PREFIX, Invalid_Table)
/* called when an invalid glyph index is detected */
#define FT_INVALID_GLYPH_ID FT_INVALID(FT_ERR_PREFIX, Invalid_Glyph_Index)
/* called when an invalid field value is detected */
#define FT_INVALID_DATA FT_INVALID(FT_ERR_PREFIX, Invalid_Table)
FT_END_HEADER
#endif /* __FTVALID_H__ */
/* END */
| googlearchive/tango-examples-c | third_party/libfreetype/include/freetype/internal/ftvalid.h | C | apache-2.0 | 6,699 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>buffered_write_stream::lowest_layer (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../lowest_layer.html" title="buffered_write_stream::lowest_layer">
<link rel="prev" href="overload1.html" title="buffered_write_stream::lowest_layer (1 of 2 overloads)">
<link rel="next" href="../lowest_layer_type.html" title="buffered_write_stream::lowest_layer_type">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lowest_layer.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../lowest_layer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.buffered_write_stream.lowest_layer.overload2"></a><a class="link" href="overload2.html" title="buffered_write_stream::lowest_layer (2 of 2 overloads)">buffered_write_stream::lowest_layer
(2 of 2 overloads)</a>
</h5></div></div></div>
<p>
Get a const reference to the lowest layer.
</p>
<pre class="programlisting"><span class="keyword">const</span> <span class="identifier">lowest_layer_type</span> <span class="special">&</span> <span class="identifier">lowest_layer</span><span class="special">()</span> <span class="keyword">const</span><span class="special">;</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lowest_layer.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../lowest_layer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| NixaSoftware/CVis | venv/bin/doc/html/boost_asio/reference/buffered_write_stream/lowest_layer/overload2.html | HTML | apache-2.0 | 3,531 |
#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
| certik/pyjamas | pygtkweb/demos/065-setselection.py | Python | apache-2.0 | 2,570 |
/*
* Copyright 2005 JBoss 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 org.drools.modelcompiler;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.drools.modelcompiler.domain.Address;
import org.drools.modelcompiler.domain.Employee;
import org.drools.modelcompiler.domain.Person;
import org.junit.Test;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieSession;
import static org.drools.modelcompiler.domain.Employee.createEmployee;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class OrTest extends BaseModelTest {
public OrTest( RUN_TYPE testRunType ) {
super( testRunType );
}
@Test
public void testOr() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age > $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Mario" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWhenStringFirst() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"rule R when\n" +
" $s : String(this == \"Go\")\n" +
" ( Person(name == \"Mark\") or \n" +
" (\n" +
" Person(name == \"Mario\") and\n" +
" Address(city == \"London\") ) )\n" +
"then\n" +
" System.out.println(\"Found: \" + $s.getClass());\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Go" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Mario", 100 ) );
ksession.insert( new Address( "London" ) );
assertEquals(2, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndex() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndexOffset() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $e : Person(name == \"Edson\")\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrConditional() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, address.city == 'Big City' )\n" +
" or " +
" Employee( $address: address, address.city == 'Small City' )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrConstraint() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, ( address.city == 'Big City' || address.city == 'Small City' ) )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrWithDuplicatedVariables() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R1 when\n" +
" Person( $name: name == \"Mark\", $age: age ) or\n" +
" Person( $name: name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $name + \" is \" + $age);\n" +
"end\n" +
"rule R2 when\n" +
" $p: Person( name == \"Mark\", $age: age ) or\n" +
" $p: Person( name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $p + \" has \" + $age + \" years\");\n" +
"end\n";
KieSession ksession = getKieSession( str );
List<String> results = new ArrayList<>();
ksession.setGlobal("list", results);
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
ksession.fireAllRules();
assertEquals(4, results.size());
assertTrue(results.contains("Mark is 37"));
assertTrue(results.contains("Mark has 37 years"));
assertTrue(results.contains("Mario is 40"));
assertTrue(results.contains("Mario has 40 years"));
}
@Test
public void generateErrorForEveryFieldInRHSNotDefinedInLHS() {
// JBRULES-3390
final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" +
"declare B\n" +
" field : int\n" +
"end\n" +
"declare C\n" +
" field : int\n" +
"end\n" +
"rule R when\n" +
"( " +
" ( B( $bField : field ) or C( $cField : field ) ) " +
")\n" +
"then\n" +
" System.out.println($bField);\n" +
"end\n";
Results results = getCompilationResults(drl1);
assertFalse(results.getMessages().isEmpty());
}
private Results getCompilationResults( String drl ) {
return createKieBuilder( drl ).getResults();
}
}
| jomarko/drools | drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/OrTest.java | Java | apache-2.0 | 9,484 |
/*
* Copyright 2000-2013 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 org.jetbrains.idea.maven.importing;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.utils.Path;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
import java.io.File;
public class MavenRootModelAdapter implements MavenRootModelAdapterInterface {
private final MavenRootModelAdapterInterface myDelegate;
public MavenRootModelAdapter(MavenRootModelAdapterInterface delegate) {myDelegate = delegate;}
@Override
public void init(boolean isNewlyCreatedModule) {
myDelegate.init(isNewlyCreatedModule);
}
@Override
public ModifiableRootModel getRootModel() {
return myDelegate.getRootModel();
}
@Override
public String @NotNull [] getSourceRootUrls(boolean includingTests) {
return myDelegate.getSourceRootUrls(includingTests);
}
@Override
public Module getModule() {
return myDelegate.getModule();
}
@Override
public void clearSourceFolders() {
myDelegate.clearSourceFolders();
}
@Override
public <P extends JpsElement> void addSourceFolder(String path,
JpsModuleSourceRootType<P> rootType) {
myDelegate.addSourceFolder(path, rootType);
}
@Override
public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType, boolean ifNotEmpty) {
myDelegate.addGeneratedJavaSourceFolder(path, rootType, ifNotEmpty);
}
@Override
public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType) {
myDelegate.addGeneratedJavaSourceFolder(path, rootType);
}
@Override
public boolean hasRegisteredSourceSubfolder(@NotNull File f) {
return myDelegate.hasRegisteredSourceSubfolder(f);
}
@Override
@Nullable
public SourceFolder getSourceFolder(File folder) {
return myDelegate.getSourceFolder(folder);
}
@Override
public boolean isAlreadyExcluded(File f) {
return myDelegate.isAlreadyExcluded(f);
}
@Override
public void addExcludedFolder(String path) {
myDelegate.addExcludedFolder(path);
}
@Override
public void unregisterAll(String path, boolean under, boolean unregisterSources) {
myDelegate.unregisterAll(path, under, unregisterSources);
}
@Override
public boolean hasCollision(String sourceRootPath) {
return myDelegate.hasCollision(sourceRootPath);
}
@Override
public void useModuleOutput(String production, String test) {
myDelegate.useModuleOutput(production, test);
}
@Override
public Path toPath(String path) {
return myDelegate.toPath(path);
}
@Override
public void addModuleDependency(@NotNull String moduleName, @NotNull DependencyScope scope, boolean testJar) {
myDelegate.addModuleDependency(moduleName, scope, testJar);
}
@Override
@Nullable
public Module findModuleByName(String moduleName) {
return myDelegate.findModuleByName(moduleName);
}
@Override
public void addSystemDependency(MavenArtifact artifact, DependencyScope scope) {
myDelegate.addSystemDependency(artifact, scope);
}
@Override
public LibraryOrderEntry addLibraryDependency(MavenArtifact artifact,
DependencyScope scope,
IdeModifiableModelsProvider provider,
MavenProject project) {
return myDelegate.addLibraryDependency(artifact, scope, provider, project);
}
@Override
public Library findLibrary(@NotNull MavenArtifact artifact) {
return myDelegate.findLibrary(artifact);
}
@Override
public void setLanguageLevel(LanguageLevel level) {
myDelegate.setLanguageLevel(level);
}
static boolean isChangedByUser(Library library) {
String[] classRoots = library.getUrls(
OrderRootType.CLASSES);
if (classRoots.length != 1) return true;
String classes = classRoots[0];
if (!classes.endsWith("!/")) return true;
int dotPos = classes.lastIndexOf("/", classes.length() - 2 /* trim ending !/ */);
if (dotPos == -1) return true;
String pathToJar = classes.substring(0, dotPos);
if (MavenRootModelAdapter
.hasUserPaths(OrderRootType.SOURCES, library, pathToJar)) {
return true;
}
if (MavenRootModelAdapter
.hasUserPaths(
JavadocOrderRootType
.getInstance(), library, pathToJar)) {
return true;
}
return false;
}
private static boolean hasUserPaths(OrderRootType rootType, Library library, String pathToJar) {
String[] sources = library.getUrls(rootType);
for (String each : sources) {
if (!FileUtil.startsWith(each, pathToJar)) return true;
}
return false;
}
public static boolean isMavenLibrary(@Nullable Library library) {
return library != null && MavenArtifact.isMavenLibrary(library.getName());
}
public static ProjectModelExternalSource getMavenExternalSource() {
return ExternalProjectSystemRegistry.getInstance().getSourceById(ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID);
}
@Nullable
public static OrderEntry findLibraryEntry(@NotNull Module m, @NotNull MavenArtifact artifact) {
String name = artifact.getLibraryName();
for (OrderEntry each : ModuleRootManager.getInstance(m).getOrderEntries()) {
if (each instanceof LibraryOrderEntry && name.equals(((LibraryOrderEntry)each).getLibraryName())) {
return each;
}
}
return null;
}
@Nullable
public static MavenArtifact findArtifact(@NotNull MavenProject project, @Nullable Library library) {
if (library == null) return null;
String name = library.getName();
if (!MavenArtifact.isMavenLibrary(name)) return null;
for (MavenArtifact each : project.getDependencies()) {
if (each.getLibraryName().equals(name)) return each;
}
return null;
}
}
| GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java | Java | apache-2.0 | 6,985 |
@charset "UTF-8";
/**
* Foundation for Sites by ZURB
* Version 6.2.3
* foundation.zurb.com
* Licensed under MIT Open Source
*/
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS and IE text size adjust after device orientation change,
* without disabling user zoom.
*/
html {
font-family: sans-serif;
/* 1 */
-ms-text-size-adjust: 100%;
/* 2 */
-webkit-text-size-adjust: 100%;
/* 2 */ }
/**
* Remove default margin.
*/
body {
margin: 0; }
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11
* and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block; }
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */ }
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0; }
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/10/11, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none; }
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background-color: transparent; }
/**
* Improve readability of focused elements when they are also in an
* active/hover state.
*/
a:active,
a:hover {
outline: 0; }
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted; }
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
b,
strong {
font-weight: bold; }
/**
* Address styling not present in Safari and Chrome.
*/
dfn {
font-style: italic; }
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0; }
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000; }
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%; }
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline; }
sup {
top: -0.5em; }
sub {
bottom: -0.25em; }
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
img {
border: 0; }
/**
* Correct overflow not hidden in IE 9/10/11.
*/
svg:not(:root) {
overflow: hidden; }
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
figure {
margin: 1em 40px; }
/**
* Address differences between Firefox and other browsers.
*/
hr {
box-sizing: content-box;
height: 0; }
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto; }
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em; }
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit;
/* 1 */
font: inherit;
/* 2 */
margin: 0;
/* 3 */ }
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
button {
overflow: visible; }
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none; }
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
/* 2 */
cursor: pointer;
/* 3 */ }
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: not-allowed; }
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0; }
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal; }
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */ }
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto; }
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome.
*/
input[type="search"] {
-webkit-appearance: textfield;
/* 1 */
box-sizing: content-box;
/* 2 */ }
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none; }
/**
* Define consistent border, margin, and padding.
* [NOTE] We don't enable this ruleset in Foundation, because we want the <fieldset> element to have plain styling.
*/
/* fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
} */
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0;
/* 1 */
padding: 0;
/* 2 */ }
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
textarea {
overflow: auto; }
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold; }
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0; }
td,
th {
padding: 0; }
.foundation-mq {
font-family: "small=0em&medium=40em&large=64em&xlarge=75em&xxlarge=90em"; }
html {
font-size: 100%;
box-sizing: border-box; }
*,
*::before,
*::after {
box-sizing: inherit; }
body {
padding: 0;
margin: 0;
font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
font-weight: normal;
line-height: 1.5;
color: #0a0a0a;
background: #fefefe;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; }
img {
max-width: 100%;
height: auto;
-ms-interpolation-mode: bicubic;
display: inline-block;
vertical-align: middle; }
textarea {
height: auto;
min-height: 50px;
border-radius: 3px; }
select {
width: 100%;
border-radius: 3px; }
#map_canvas img,
#map_canvas embed,
#map_canvas object,
.map_canvas img,
.map_canvas embed,
.map_canvas object,
.mqa-display img,
.mqa-display embed,
.mqa-display object {
max-width: none !important; }
button {
-webkit-appearance: none;
-moz-appearance: none;
background: transparent;
padding: 0;
border: 0;
border-radius: 3px;
line-height: 1; }
[data-whatinput='mouse'] button {
outline: 0; }
.is-visible {
display: block !important; }
.is-hidden {
display: none !important; }
div,
dl,
dt,
dd,
ul,
ol,
li,
h1,
h2,
h3,
h4,
h5,
h6,
pre,
form,
p,
blockquote,
th,
td {
margin: 0;
padding: 0; }
p {
font-size: inherit;
line-height: 1.6;
margin-bottom: 1rem;
text-rendering: optimizeLegibility; }
em,
i {
font-style: italic;
line-height: inherit; }
strong,
b {
font-weight: bold;
line-height: inherit; }
small {
font-size: 80%;
line-height: inherit; }
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
font-weight: normal;
font-style: normal;
color: inherit;
text-rendering: optimizeLegibility;
margin-top: 0;
margin-bottom: 0.5rem;
line-height: 1.4; }
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small {
color: #cacaca;
line-height: 0; }
h1 {
font-size: 1.5rem; }
h2 {
font-size: 1.25rem; }
h3 {
font-size: 1.1875rem; }
h4 {
font-size: 1.125rem; }
h5 {
font-size: 1.0625rem; }
h6 {
font-size: 1rem; }
@media screen and (min-width: 40em) {
h1 {
font-size: 3rem; }
h2 {
font-size: 2.5rem; }
h3 {
font-size: 1.9375rem; }
h4 {
font-size: 1.5625rem; }
h5 {
font-size: 1.25rem; }
h6 {
font-size: 1rem; } }
a {
color: #2ba6cb;
text-decoration: none;
line-height: inherit;
cursor: pointer; }
a:hover, a:focus {
color: #258faf; }
a img {
border: 0; }
hr {
max-width: 62.5rem;
height: 0;
border-right: 0;
border-top: 0;
border-bottom: 1px solid #cacaca;
border-left: 0;
margin: 1.25rem auto;
clear: both; }
ul,
ol,
dl {
line-height: 1.6;
margin-bottom: 1rem;
list-style-position: outside; }
li {
font-size: inherit; }
ul {
list-style-type: disc;
margin-left: 1.25rem; }
ol {
margin-left: 1.25rem; }
ul ul, ol ul, ul ol, ol ol {
margin-left: 1.25rem;
margin-bottom: 0; }
dl {
margin-bottom: 1rem; }
dl dt {
margin-bottom: 0.3rem;
font-weight: bold; }
blockquote {
margin: 0 0 1rem;
padding: 0.5625rem 1.25rem 0 1.1875rem;
border-left: 1px solid #cacaca; }
blockquote, blockquote p {
line-height: 1.6;
color: #8a8a8a; }
cite {
display: block;
font-size: 0.8125rem;
color: #8a8a8a; }
cite:before {
content: '\2014 \0020'; }
abbr {
color: #0a0a0a;
cursor: help;
border-bottom: 1px dotted #0a0a0a; }
code {
font-family: Consolas, "Liberation Mono", Courier, monospace;
font-weight: normal;
color: #0a0a0a;
background-color: #e6e6e6;
border: 1px solid #cacaca;
padding: 0.125rem 0.3125rem 0.0625rem; }
kbd {
padding: 0.125rem 0.25rem 0;
margin: 0;
background-color: #e6e6e6;
color: #0a0a0a;
font-family: Consolas, "Liberation Mono", Courier, monospace;
border-radius: 3px; }
.subheader {
margin-top: 0.2rem;
margin-bottom: 0.5rem;
font-weight: normal;
line-height: 1.4;
color: #8a8a8a; }
.lead {
font-size: 125%;
line-height: 1.6; }
.stat {
font-size: 2.5rem;
line-height: 1; }
p + .stat {
margin-top: -1rem; }
.no-bullet {
margin-left: 0;
list-style: none; }
.text-left {
text-align: left; }
.text-right {
text-align: right; }
.text-center {
text-align: center; }
.text-justify {
text-align: justify; }
@media screen and (min-width: 40em) {
.medium-text-left {
text-align: left; }
.medium-text-right {
text-align: right; }
.medium-text-center {
text-align: center; }
.medium-text-justify {
text-align: justify; } }
@media screen and (min-width: 64em) {
.large-text-left {
text-align: left; }
.large-text-right {
text-align: right; }
.large-text-center {
text-align: center; }
.large-text-justify {
text-align: justify; } }
.show-for-print {
display: none !important; }
@media print {
* {
background: transparent !important;
color: black !important;
box-shadow: none !important;
text-shadow: none !important; }
.show-for-print {
display: block !important; }
.hide-for-print {
display: none !important; }
table.show-for-print {
display: table !important; }
thead.show-for-print {
display: table-header-group !important; }
tbody.show-for-print {
display: table-row-group !important; }
tr.show-for-print {
display: table-row !important; }
td.show-for-print {
display: table-cell !important; }
th.show-for-print {
display: table-cell !important; }
a,
a:visited {
text-decoration: underline; }
a[href]:after {
content: " (" attr(href) ")"; }
.ir a:after,
a[href^='javascript:']:after,
a[href^='#']:after {
content: ''; }
abbr[title]:after {
content: " (" attr(title) ")"; }
pre,
blockquote {
border: 1px solid #8a8a8a;
page-break-inside: avoid; }
thead {
display: table-header-group; }
tr,
img {
page-break-inside: avoid; }
img {
max-width: 100% !important; }
@page {
margin: 0.5cm; }
p,
h2,
h3 {
orphans: 3;
widows: 3; }
h2,
h3 {
page-break-after: avoid; } }
[type='text'], [type='password'], [type='date'], [type='datetime'], [type='datetime-local'], [type='month'], [type='week'], [type='email'], [type='number'], [type='search'], [type='tel'], [type='time'], [type='url'], [type='color'],
textarea {
display: block;
box-sizing: border-box;
width: 100%;
height: 2.4375rem;
padding: 0.5rem;
border: 1px solid #cacaca;
margin: 0 0 1rem;
font-family: inherit;
font-size: 1rem;
color: #0a0a0a;
background-color: #fefefe;
box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.1);
border-radius: 3px;
transition: box-shadow 0.5s, border-color 0.25s ease-in-out;
-webkit-appearance: none;
-moz-appearance: none; }
[type='text']:focus, [type='password']:focus, [type='date']:focus, [type='datetime']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='week']:focus, [type='email']:focus, [type='number']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='url']:focus, [type='color']:focus,
textarea:focus {
border: 1px solid #8a8a8a;
background-color: #fefefe;
outline: none;
box-shadow: 0 0 5px #cacaca;
transition: box-shadow 0.5s, border-color 0.25s ease-in-out; }
textarea {
max-width: 100%; }
textarea[rows] {
height: auto; }
input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
color: #cacaca; }
input::-moz-placeholder,
textarea::-moz-placeholder {
color: #cacaca; }
input:-ms-input-placeholder,
textarea:-ms-input-placeholder {
color: #cacaca; }
input::placeholder,
textarea::placeholder {
color: #cacaca; }
input:disabled, input[readonly],
textarea:disabled,
textarea[readonly] {
background-color: #e6e6e6;
cursor: not-allowed; }
[type='submit'],
[type='button'] {
border-radius: 3px;
-webkit-appearance: none;
-moz-appearance: none; }
input[type='search'] {
box-sizing: border-box; }
[type='file'],
[type='checkbox'],
[type='radio'] {
margin: 0 0 1rem; }
[type='checkbox'] + label,
[type='radio'] + label {
display: inline-block;
margin-left: 0.5rem;
margin-right: 1rem;
margin-bottom: 0;
vertical-align: baseline; }
[type='checkbox'] + label[for],
[type='radio'] + label[for] {
cursor: pointer; }
label > [type='checkbox'],
label > [type='radio'] {
margin-right: 0.5rem; }
[type='file'] {
width: 100%; }
label {
display: block;
margin: 0;
font-size: 0.875rem;
font-weight: normal;
line-height: 1.8;
color: #0a0a0a; }
label.middle {
margin: 0 0 1rem;
padding: 0.5625rem 0; }
.help-text {
margin-top: -0.5rem;
font-size: 0.8125rem;
font-style: italic;
color: #0a0a0a; }
.input-group {
display: table;
width: 100%;
margin-bottom: 1rem; }
.input-group > :first-child {
border-radius: 3px 0 0 3px; }
.input-group > :last-child > * {
border-radius: 0 3px 3px 0; }
.input-group-label, .input-group-field, .input-group-button {
margin: 0;
white-space: nowrap;
display: table-cell;
vertical-align: middle; }
.input-group-label {
text-align: center;
padding: 0 1rem;
background: #e6e6e6;
color: #0a0a0a;
border: 1px solid #cacaca;
white-space: nowrap;
width: 1%;
height: 100%; }
.input-group-label:first-child {
border-right: 0; }
.input-group-label:last-child {
border-left: 0; }
.input-group-field {
border-radius: 0;
height: 2.5rem; }
.input-group-button {
padding-top: 0;
padding-bottom: 0;
text-align: center;
height: 100%;
width: 1%; }
.input-group-button a,
.input-group-button input,
.input-group-button button {
margin: 0; }
.input-group .input-group-button {
display: table-cell; }
fieldset {
border: 0;
padding: 0;
margin: 0; }
legend {
margin-bottom: 0.5rem;
max-width: 100%; }
.fieldset {
border: 1px solid #cacaca;
padding: 1.25rem;
margin: 1.125rem 0; }
.fieldset legend {
background: #fefefe;
padding: 0 0.1875rem;
margin: 0;
margin-left: -0.1875rem; }
select {
height: 2.4375rem;
padding: 0.5rem;
border: 1px solid #cacaca;
margin: 0 0 1rem;
font-size: 1rem;
font-family: inherit;
line-height: normal;
color: #0a0a0a;
background-color: #fefefe;
border-radius: 3px;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='32' height='24' viewBox='0 0 32 24'><polygon points='0,0 32,0 16,24' style='fill: rgb%28138, 138, 138%29'></polygon></svg>");
background-size: 9px 6px;
background-position: right -1rem center;
background-origin: content-box;
background-repeat: no-repeat;
padding-right: 1.5rem; }
@media screen and (min-width: 0\0) {
select {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAYAAACbU/80AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAIpJREFUeNrEkckNgDAMBBfRkEt0ObRBBdsGXUDgmQfK4XhH2m8czQAAy27R3tsw4Qfe2x8uOO6oYLb6GlOor3GF+swURAOmUJ+RwtEJs9WvTGEYxBXqI1MQAZhCfUQKRzDMVj+TwrAIV6jvSUEkYAr1LSkcyTBb/V+KYfX7xAeusq3sLDtGH3kEGACPWIflNZfhRQAAAABJRU5ErkJggg=="); } }
select:disabled {
background-color: #e6e6e6;
cursor: not-allowed; }
select::-ms-expand {
display: none; }
select[multiple] {
height: auto;
background-image: none; }
.is-invalid-input:not(:focus) {
background-color: rgba(198, 15, 19, 0.1);
border-color: #c60f13; }
.is-invalid-label {
color: #c60f13; }
.form-error {
display: none;
margin-top: -0.5rem;
margin-bottom: 1rem;
font-size: 0.75rem;
font-weight: bold;
color: #c60f13; }
.form-error.is-visible {
display: block; }
.float-left {
float: left !important; }
.float-right {
float: right !important; }
.float-center {
display: block;
margin-left: auto;
margin-right: auto; }
.clearfix::before, .clearfix::after {
content: ' ';
display: table; }
.clearfix::after {
clear: both; }
.hide {
display: none !important; }
.invisible {
visibility: hidden; }
@media screen and (max-width: 39.9375em) {
.hide-for-small-only {
display: none !important; } }
@media screen and (max-width: 0em), screen and (min-width: 40em) {
.show-for-small-only {
display: none !important; } }
@media screen and (min-width: 40em) {
.hide-for-medium {
display: none !important; } }
@media screen and (max-width: 39.9375em) {
.show-for-medium {
display: none !important; } }
@media screen and (min-width: 40em) and (max-width: 63.9375em) {
.hide-for-medium-only {
display: none !important; } }
@media screen and (max-width: 39.9375em), screen and (min-width: 64em) {
.show-for-medium-only {
display: none !important; } }
@media screen and (min-width: 64em) {
.hide-for-large {
display: none !important; } }
@media screen and (max-width: 63.9375em) {
.show-for-large {
display: none !important; } }
@media screen and (min-width: 64em) and (max-width: 74.9375em) {
.hide-for-large-only {
display: none !important; } }
@media screen and (max-width: 63.9375em), screen and (min-width: 75em) {
.show-for-large-only {
display: none !important; } }
.show-for-sr,
.show-on-focus {
position: absolute !important;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0, 0, 0, 0); }
.show-on-focus:active, .show-on-focus:focus {
position: static !important;
height: auto;
width: auto;
overflow: visible;
clip: auto; }
.show-for-landscape,
.hide-for-portrait {
display: block !important; }
@media screen and (orientation: landscape) {
.show-for-landscape,
.hide-for-portrait {
display: block !important; } }
@media screen and (orientation: portrait) {
.show-for-landscape,
.hide-for-portrait {
display: none !important; } }
.hide-for-landscape,
.show-for-portrait {
display: none !important; }
@media screen and (orientation: landscape) {
.hide-for-landscape,
.show-for-portrait {
display: none !important; } }
@media screen and (orientation: portrait) {
.hide-for-landscape,
.show-for-portrait {
display: block !important; } }
.button {
display: inline-block;
text-align: center;
line-height: 1;
cursor: pointer;
-webkit-appearance: none;
transition: background-color 0.25s ease-out, color 0.25s ease-out;
vertical-align: middle;
border: 1px solid transparent;
border-radius: 3px;
padding: 0.85em 1em;
margin: 0 0 1rem 0;
font-size: 0.9rem;
background-color: #2ba6cb;
color: #fefefe; }
[data-whatinput='mouse'] .button {
outline: 0; }
.button:hover, .button:focus {
background-color: #258dad;
color: #fefefe; }
.button.tiny {
font-size: 0.6rem; }
.button.small {
font-size: 0.75rem; }
.button.large {
font-size: 1.25rem; }
.button.expanded {
display: block;
width: 100%;
margin-left: 0;
margin-right: 0; }
.button.primary {
background-color: #2ba6cb;
color: #fefefe; }
.button.primary:hover, .button.primary:focus {
background-color: #2285a2;
color: #fefefe; }
.button.secondary {
background-color: #e9e9e9;
color: #0a0a0a; }
.button.secondary:hover, .button.secondary:focus {
background-color: #bababa;
color: #0a0a0a; }
.button.alert {
background-color: #c60f13;
color: #fefefe; }
.button.alert:hover, .button.alert:focus {
background-color: #9e0c0f;
color: #fefefe; }
.button.success {
background-color: #5da423;
color: #fefefe; }
.button.success:hover, .button.success:focus {
background-color: #4a831c;
color: #fefefe; }
.button.warning {
background-color: #ffae00;
color: #fefefe; }
.button.warning:hover, .button.warning:focus {
background-color: #cc8b00;
color: #fefefe; }
.button.body-font {
background-color: #222222;
color: #fefefe; }
.button.body-font:hover, .button.body-font:focus {
background-color: #1b1b1b;
color: #fefefe; }
.button.header {
background-color: #222222;
color: #fefefe; }
.button.header:hover, .button.header:focus {
background-color: #1b1b1b;
color: #fefefe; }
.button.hollow {
border: 1px solid #2ba6cb;
color: #2ba6cb; }
.button.hollow, .button.hollow:hover, .button.hollow:focus {
background-color: transparent; }
.button.hollow:hover, .button.hollow:focus {
border-color: #165366;
color: #165366; }
.button.hollow.primary {
border: 1px solid #2ba6cb;
color: #2ba6cb; }
.button.hollow.primary:hover, .button.hollow.primary:focus {
border-color: #165366;
color: #165366; }
.button.hollow.secondary {
border: 1px solid #e9e9e9;
color: #e9e9e9; }
.button.hollow.secondary:hover, .button.hollow.secondary:focus {
border-color: #757575;
color: #757575; }
.button.hollow.alert {
border: 1px solid #c60f13;
color: #c60f13; }
.button.hollow.alert:hover, .button.hollow.alert:focus {
border-color: #63080a;
color: #63080a; }
.button.hollow.success {
border: 1px solid #5da423;
color: #5da423; }
.button.hollow.success:hover, .button.hollow.success:focus {
border-color: #2f5212;
color: #2f5212; }
.button.hollow.warning {
border: 1px solid #ffae00;
color: #ffae00; }
.button.hollow.warning:hover, .button.hollow.warning:focus {
border-color: #805700;
color: #805700; }
.button.hollow.body-font {
border: 1px solid #222222;
color: #222222; }
.button.hollow.body-font:hover, .button.hollow.body-font:focus {
border-color: #111111;
color: #111111; }
.button.hollow.header {
border: 1px solid #222222;
color: #222222; }
.button.hollow.header:hover, .button.hollow.header:focus {
border-color: #111111;
color: #111111; }
.button.disabled, .button[disabled] {
opacity: 0.25;
cursor: not-allowed; }
.button.disabled:hover, .button.disabled:focus, .button[disabled]:hover, .button[disabled]:focus {
background-color: #2ba6cb;
color: #fefefe; }
.button.dropdown::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 0.4em;
border-color: #fefefe transparent transparent;
border-top-style: solid;
border-bottom-width: 0;
position: relative;
top: 0.4em;
float: right;
margin-left: 1em;
display: inline-block; }
.button.arrow-only::after {
margin-left: 0;
float: none;
top: -0.1em; }
.close-button {
position: absolute;
color: #8a8a8a;
right: 1rem;
top: 0.5rem;
font-size: 2em;
line-height: 1;
cursor: pointer; }
[data-whatinput='mouse'] .close-button {
outline: 0; }
.close-button:hover, .close-button:focus {
color: #0a0a0a; }
.button-group {
margin-bottom: 1rem;
font-size: 0; }
.button-group::before, .button-group::after {
content: ' ';
display: table; }
.button-group::after {
clear: both; }
.button-group .button {
margin: 0;
margin-right: 1px;
margin-bottom: 1px;
font-size: 0.9rem; }
.button-group .button:last-child {
margin-right: 0; }
.button-group.tiny .button {
font-size: 0.6rem; }
.button-group.small .button {
font-size: 0.75rem; }
.button-group.large .button {
font-size: 1.25rem; }
.button-group.expanded {
margin-right: -1px; }
.button-group.expanded::before, .button-group.expanded::after {
display: none; }
.button-group.expanded .button:first-child:nth-last-child(2), .button-group.expanded .button:first-child:nth-last-child(2):first-child:nth-last-child(2) ~ .button {
display: inline-block;
width: calc(50% - 1px);
margin-right: 1px; }
.button-group.expanded .button:first-child:nth-last-child(2):last-child, .button-group.expanded .button:first-child:nth-last-child(2):first-child:nth-last-child(2) ~ .button:last-child {
margin-right: -6px; }
.button-group.expanded .button:first-child:nth-last-child(3), .button-group.expanded .button:first-child:nth-last-child(3):first-child:nth-last-child(3) ~ .button {
display: inline-block;
width: calc(33.33333% - 1px);
margin-right: 1px; }
.button-group.expanded .button:first-child:nth-last-child(3):last-child, .button-group.expanded .button:first-child:nth-last-child(3):first-child:nth-last-child(3) ~ .button:last-child {
margin-right: -6px; }
.button-group.expanded .button:first-child:nth-last-child(4), .button-group.expanded .button:first-child:nth-last-child(4):first-child:nth-last-child(4) ~ .button {
display: inline-block;
width: calc(25% - 1px);
margin-right: 1px; }
.button-group.expanded .button:first-child:nth-last-child(4):last-child, .button-group.expanded .button:first-child:nth-last-child(4):first-child:nth-last-child(4) ~ .button:last-child {
margin-right: -6px; }
.button-group.expanded .button:first-child:nth-last-child(5), .button-group.expanded .button:first-child:nth-last-child(5):first-child:nth-last-child(5) ~ .button {
display: inline-block;
width: calc(20% - 1px);
margin-right: 1px; }
.button-group.expanded .button:first-child:nth-last-child(5):last-child, .button-group.expanded .button:first-child:nth-last-child(5):first-child:nth-last-child(5) ~ .button:last-child {
margin-right: -6px; }
.button-group.expanded .button:first-child:nth-last-child(6), .button-group.expanded .button:first-child:nth-last-child(6):first-child:nth-last-child(6) ~ .button {
display: inline-block;
width: calc(16.66667% - 1px);
margin-right: 1px; }
.button-group.expanded .button:first-child:nth-last-child(6):last-child, .button-group.expanded .button:first-child:nth-last-child(6):first-child:nth-last-child(6) ~ .button:last-child {
margin-right: -6px; }
.button-group.primary .button {
background-color: #2ba6cb;
color: #fefefe; }
.button-group.primary .button:hover, .button-group.primary .button:focus {
background-color: #2285a2;
color: #fefefe; }
.button-group.secondary .button {
background-color: #e9e9e9;
color: #0a0a0a; }
.button-group.secondary .button:hover, .button-group.secondary .button:focus {
background-color: #bababa;
color: #0a0a0a; }
.button-group.alert .button {
background-color: #c60f13;
color: #fefefe; }
.button-group.alert .button:hover, .button-group.alert .button:focus {
background-color: #9e0c0f;
color: #fefefe; }
.button-group.success .button {
background-color: #5da423;
color: #fefefe; }
.button-group.success .button:hover, .button-group.success .button:focus {
background-color: #4a831c;
color: #fefefe; }
.button-group.warning .button {
background-color: #ffae00;
color: #fefefe; }
.button-group.warning .button:hover, .button-group.warning .button:focus {
background-color: #cc8b00;
color: #fefefe; }
.button-group.body-font .button {
background-color: #222222;
color: #fefefe; }
.button-group.body-font .button:hover, .button-group.body-font .button:focus {
background-color: #1b1b1b;
color: #fefefe; }
.button-group.header .button {
background-color: #222222;
color: #fefefe; }
.button-group.header .button:hover, .button-group.header .button:focus {
background-color: #1b1b1b;
color: #fefefe; }
.button-group.stacked .button, .button-group.stacked-for-small .button, .button-group.stacked-for-medium .button {
width: 100%; }
.button-group.stacked .button:last-child, .button-group.stacked-for-small .button:last-child, .button-group.stacked-for-medium .button:last-child {
margin-bottom: 0; }
@media screen and (min-width: 40em) {
.button-group.stacked-for-small .button {
width: auto;
margin-bottom: 0; } }
@media screen and (min-width: 64em) {
.button-group.stacked-for-medium .button {
width: auto;
margin-bottom: 0; } }
@media screen and (max-width: 39.9375em) {
.button-group.stacked-for-small.expanded {
display: block; }
.button-group.stacked-for-small.expanded .button {
display: block;
margin-right: 0; } }
.slider {
position: relative;
height: 0.5rem;
margin-top: 1.25rem;
margin-bottom: 2.25rem;
background-color: #e6e6e6;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-ms-touch-action: none;
touch-action: none; }
.slider-fill {
position: absolute;
top: 0;
left: 0;
display: inline-block;
max-width: 100%;
height: 0.5rem;
background-color: #cacaca;
transition: all 0.2s ease-in-out; }
.slider-fill.is-dragging {
transition: all 0s linear; }
.slider-handle {
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
position: absolute;
left: 0;
z-index: 1;
display: inline-block;
width: 1.4rem;
height: 1.4rem;
background-color: #2ba6cb;
transition: all 0.2s ease-in-out;
-ms-touch-action: manipulation;
touch-action: manipulation;
border-radius: 3px; }
[data-whatinput='mouse'] .slider-handle {
outline: 0; }
.slider-handle:hover {
background-color: #258dad; }
.slider-handle.is-dragging {
transition: all 0s linear; }
.slider.disabled,
.slider[disabled] {
opacity: 0.25;
cursor: not-allowed; }
.slider.vertical {
display: inline-block;
width: 0.5rem;
height: 12.5rem;
margin: 0 1.25rem;
-webkit-transform: scale(1, -1);
-ms-transform: scale(1, -1);
transform: scale(1, -1); }
.slider.vertical .slider-fill {
top: 0;
width: 0.5rem;
max-height: 100%; }
.slider.vertical .slider-handle {
position: absolute;
top: 0;
left: 50%;
width: 1.4rem;
height: 1.4rem;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%); }
.switch {
margin-bottom: 1rem;
outline: 0;
position: relative;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
color: #fefefe;
font-weight: bold;
font-size: 0.875rem; }
.switch-input {
opacity: 0;
position: absolute; }
.switch-paddle {
background: #cacaca;
cursor: pointer;
display: block;
position: relative;
width: 4rem;
height: 2rem;
transition: all 0.25s ease-out;
border-radius: 3px;
color: inherit;
font-weight: inherit; }
input + .switch-paddle {
margin: 0; }
.switch-paddle::after {
background: #fefefe;
content: '';
display: block;
position: absolute;
height: 1.5rem;
left: 0.25rem;
top: 0.25rem;
width: 1.5rem;
transition: all 0.25s ease-out;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
border-radius: 3px; }
input:checked ~ .switch-paddle {
background: #2ba6cb; }
input:checked ~ .switch-paddle::after {
left: 2.25rem; }
[data-whatinput='mouse'] input:focus ~ .switch-paddle {
outline: 0; }
.switch-active, .switch-inactive {
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%); }
.switch-active {
left: 8%;
display: none; }
input:checked + label > .switch-active {
display: block; }
.switch-inactive {
right: 15%; }
input:checked + label > .switch-inactive {
display: none; }
.switch.tiny .switch-paddle {
width: 3rem;
height: 1.5rem;
font-size: 0.625rem; }
.switch.tiny .switch-paddle::after {
width: 1rem;
height: 1rem; }
.switch.tiny input:checked ~ .switch-paddle::after {
left: 1.75rem; }
.switch.small .switch-paddle {
width: 3.5rem;
height: 1.75rem;
font-size: 0.75rem; }
.switch.small .switch-paddle::after {
width: 1.25rem;
height: 1.25rem; }
.switch.small input:checked ~ .switch-paddle::after {
left: 2rem; }
.switch.large .switch-paddle {
width: 5rem;
height: 2.5rem;
font-size: 1rem; }
.switch.large .switch-paddle::after {
width: 2rem;
height: 2rem; }
.switch.large input:checked ~ .switch-paddle::after {
left: 2.75rem; }
.menu {
margin: 0;
list-style-type: none; }
.menu > li {
display: table-cell;
vertical-align: middle; }
[data-whatinput='mouse'] .menu > li {
outline: 0; }
.menu > li > a {
display: block;
padding: 0.7rem 1rem;
line-height: 1; }
.menu input,
.menu a,
.menu button {
margin-bottom: 0; }
.menu > li > a img,
.menu > li > a i,
.menu > li > a svg {
vertical-align: middle; }
.menu > li > a img + span,
.menu > li > a i + span,
.menu > li > a svg + span {
vertical-align: middle; }
.menu > li > a img,
.menu > li > a i,
.menu > li > a svg {
margin-right: 0.25rem;
display: inline-block; }
.menu > li {
display: table-cell; }
.menu.vertical > li {
display: block; }
@media screen and (min-width: 40em) {
.menu.medium-horizontal > li {
display: table-cell; }
.menu.medium-vertical > li {
display: block; } }
@media screen and (min-width: 64em) {
.menu.large-horizontal > li {
display: table-cell; }
.menu.large-vertical > li {
display: block; } }
.menu.simple li {
line-height: 1;
display: inline-block;
margin-right: 1rem; }
.menu.simple a {
padding: 0; }
.menu.align-right::before, .menu.align-right::after {
content: ' ';
display: table; }
.menu.align-right::after {
clear: both; }
.menu.align-right > li {
float: right; }
.menu.expanded {
width: 100%;
display: table;
table-layout: fixed; }
.menu.expanded > li:first-child:last-child {
width: 100%; }
.menu.icon-top > li > a {
text-align: center; }
.menu.icon-top > li > a img,
.menu.icon-top > li > a i,
.menu.icon-top > li > a svg {
display: block;
margin: 0 auto 0.25rem; }
.menu.nested {
margin-left: 1rem; }
.menu .active > a {
color: #fefefe;
background: #2ba6cb; }
.menu-text {
font-weight: bold;
color: inherit;
line-height: 1;
padding-top: 0;
padding-bottom: 0;
padding: 0.7rem 1rem; }
.menu-centered {
text-align: center; }
.menu-centered > .menu {
display: inline-block; }
.no-js [data-responsive-menu] ul {
display: none; }
.is-drilldown {
position: relative;
overflow: hidden; }
.is-drilldown li {
display: block !important; }
.is-drilldown-submenu {
position: absolute;
top: 0;
left: 100%;
z-index: -1;
height: 100%;
width: 100%;
background: #fefefe;
transition: -webkit-transform 0.15s linear;
transition: transform 0.15s linear; }
.is-drilldown-submenu.is-active {
z-index: 1;
display: block;
-webkit-transform: translateX(-100%);
-ms-transform: translateX(-100%);
transform: translateX(-100%); }
.is-drilldown-submenu.is-closing {
-webkit-transform: translateX(100%);
-ms-transform: translateX(100%);
transform: translateX(100%); }
.is-drilldown-submenu-parent > a {
position: relative; }
.is-drilldown-submenu-parent > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 6px;
border-color: transparent transparent transparent #2ba6cb;
border-left-style: solid;
border-right-width: 0;
position: absolute;
top: 50%;
margin-top: -6px;
right: 1rem; }
.js-drilldown-back > a::before {
content: '';
display: block;
width: 0;
height: 0;
border: inset 6px;
border-color: transparent #2ba6cb transparent transparent;
border-right-style: solid;
border-left-width: 0;
border-left-width: 0;
display: inline-block;
vertical-align: middle;
margin-right: 0.75rem; }
.is-accordion-submenu-parent > a {
position: relative; }
.is-accordion-submenu-parent > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 6px;
border-color: #2ba6cb transparent transparent;
border-top-style: solid;
border-bottom-width: 0;
position: absolute;
top: 50%;
margin-top: -4px;
right: 1rem; }
.is-accordion-submenu-parent[aria-expanded='true'] > a::after {
-webkit-transform-origin: 50% 50%;
-ms-transform-origin: 50% 50%;
transform-origin: 50% 50%;
-webkit-transform: scaleY(-1);
-ms-transform: scaleY(-1);
transform: scaleY(-1); }
.dropdown.menu > li.opens-left > .is-dropdown-submenu {
left: auto;
right: 0;
top: 100%; }
.dropdown.menu > li.opens-right > .is-dropdown-submenu {
right: auto;
left: 0;
top: 100%; }
.dropdown.menu > li.is-dropdown-submenu-parent > a {
padding-right: 1.5rem;
position: relative; }
.dropdown.menu > li.is-dropdown-submenu-parent > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: #2ba6cb transparent transparent;
border-top-style: solid;
border-bottom-width: 0;
right: 5px;
margin-top: -2px; }
[data-whatinput='mouse'] .dropdown.menu a {
outline: 0; }
.no-js .dropdown.menu ul {
display: none; }
.dropdown.menu.vertical > li .is-dropdown-submenu {
top: 0; }
.dropdown.menu.vertical > li.opens-left > .is-dropdown-submenu {
left: auto;
right: 100%; }
.dropdown.menu.vertical > li.opens-right > .is-dropdown-submenu {
right: auto;
left: 100%; }
.dropdown.menu.vertical > li > a::after {
right: 14px;
margin-top: -3px; }
.dropdown.menu.vertical > li.opens-left > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent #2ba6cb transparent transparent;
border-right-style: solid;
border-left-width: 0; }
.dropdown.menu.vertical > li.opens-right > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent transparent transparent #2ba6cb;
border-left-style: solid;
border-right-width: 0; }
@media screen and (min-width: 40em) {
.dropdown.menu.medium-horizontal > li.opens-left > .is-dropdown-submenu {
left: auto;
right: 0;
top: 100%; }
.dropdown.menu.medium-horizontal > li.opens-right > .is-dropdown-submenu {
right: auto;
left: 0;
top: 100%; }
.dropdown.menu.medium-horizontal > li.is-dropdown-submenu-parent > a {
padding-right: 1.5rem;
position: relative; }
.dropdown.menu.medium-horizontal > li.is-dropdown-submenu-parent > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: #2ba6cb transparent transparent;
border-top-style: solid;
border-bottom-width: 0;
right: 5px;
margin-top: -2px; }
.dropdown.menu.medium-vertical > li .is-dropdown-submenu {
top: 0; }
.dropdown.menu.medium-vertical > li.opens-left > .is-dropdown-submenu {
left: auto;
right: 100%; }
.dropdown.menu.medium-vertical > li.opens-right > .is-dropdown-submenu {
right: auto;
left: 100%; }
.dropdown.menu.medium-vertical > li > a::after {
right: 14px;
margin-top: -3px; }
.dropdown.menu.medium-vertical > li.opens-left > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent #2ba6cb transparent transparent;
border-right-style: solid;
border-left-width: 0; }
.dropdown.menu.medium-vertical > li.opens-right > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent transparent transparent #2ba6cb;
border-left-style: solid;
border-right-width: 0; } }
@media screen and (min-width: 64em) {
.dropdown.menu.large-horizontal > li.opens-left > .is-dropdown-submenu {
left: auto;
right: 0;
top: 100%; }
.dropdown.menu.large-horizontal > li.opens-right > .is-dropdown-submenu {
right: auto;
left: 0;
top: 100%; }
.dropdown.menu.large-horizontal > li.is-dropdown-submenu-parent > a {
padding-right: 1.5rem;
position: relative; }
.dropdown.menu.large-horizontal > li.is-dropdown-submenu-parent > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: #2ba6cb transparent transparent;
border-top-style: solid;
border-bottom-width: 0;
right: 5px;
margin-top: -2px; }
.dropdown.menu.large-vertical > li .is-dropdown-submenu {
top: 0; }
.dropdown.menu.large-vertical > li.opens-left > .is-dropdown-submenu {
left: auto;
right: 100%; }
.dropdown.menu.large-vertical > li.opens-right > .is-dropdown-submenu {
right: auto;
left: 100%; }
.dropdown.menu.large-vertical > li > a::after {
right: 14px;
margin-top: -3px; }
.dropdown.menu.large-vertical > li.opens-left > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent #2ba6cb transparent transparent;
border-right-style: solid;
border-left-width: 0; }
.dropdown.menu.large-vertical > li.opens-right > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent transparent transparent #2ba6cb;
border-left-style: solid;
border-right-width: 0; } }
.dropdown.menu.align-right .is-dropdown-submenu.first-sub {
top: 100%;
left: auto;
right: 0; }
.is-dropdown-menu.vertical {
width: 100px; }
.is-dropdown-menu.vertical.align-right {
float: right; }
.is-dropdown-submenu-parent {
position: relative; }
.is-dropdown-submenu-parent a::after {
position: absolute;
top: 50%;
right: 5px;
margin-top: -2px; }
.is-dropdown-submenu-parent.opens-inner > .is-dropdown-submenu {
top: 100%;
left: auto; }
.is-dropdown-submenu-parent.opens-left > .is-dropdown-submenu {
left: auto;
right: 100%; }
.is-dropdown-submenu-parent.opens-right > .is-dropdown-submenu {
right: auto;
left: 100%; }
.is-dropdown-submenu {
display: none;
position: absolute;
top: 0;
left: 100%;
min-width: 200px;
z-index: 1;
background: #fefefe;
border: 1px solid #cacaca; }
.is-dropdown-submenu .is-dropdown-submenu-parent > a::after {
right: 14px;
margin-top: -3px; }
.is-dropdown-submenu .is-dropdown-submenu-parent.opens-left > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent #2ba6cb transparent transparent;
border-right-style: solid;
border-left-width: 0; }
.is-dropdown-submenu .is-dropdown-submenu-parent.opens-right > a::after {
content: '';
display: block;
width: 0;
height: 0;
border: inset 5px;
border-color: transparent transparent transparent #2ba6cb;
border-left-style: solid;
border-right-width: 0; }
.is-dropdown-submenu .is-dropdown-submenu {
margin-top: -1px; }
.is-dropdown-submenu > li {
width: 100%; }
.is-dropdown-submenu.js-dropdown-active {
display: block; }
.title-bar {
background: #0a0a0a;
color: #fefefe;
padding: 0.5rem; }
.title-bar::before, .title-bar::after {
content: ' ';
display: table; }
.title-bar::after {
clear: both; }
.title-bar .menu-icon {
margin-left: 0.25rem;
margin-right: 0.25rem; }
.title-bar-left {
float: left; }
.title-bar-right {
float: right;
text-align: right; }
.title-bar-title {
font-weight: bold;
vertical-align: middle;
display: inline-block; }
.menu-icon.dark {
position: relative;
display: inline-block;
vertical-align: middle;
cursor: pointer;
width: 20px;
height: 16px; }
.menu-icon.dark::after {
content: '';
position: absolute;
display: block;
width: 100%;
height: 2px;
background: #0a0a0a;
top: 0;
left: 0;
box-shadow: 0 7px 0 #0a0a0a, 0 14px 0 #0a0a0a; }
.menu-icon.dark:hover::after {
background: #8a8a8a;
box-shadow: 0 7px 0 #8a8a8a, 0 14px 0 #8a8a8a; }
.top-bar {
padding: 0.5rem; }
.top-bar::before, .top-bar::after {
content: ' ';
display: table; }
.top-bar::after {
clear: both; }
.top-bar,
.top-bar ul {
background-color: #e6e6e6; }
.top-bar input {
max-width: 200px;
margin-right: 1rem; }
.top-bar .input-group-field {
width: 100%;
margin-right: 0; }
.top-bar input.button {
width: auto; }
.top-bar .top-bar-left,
.top-bar .top-bar-right {
width: 100%; }
@media screen and (min-width: 40em) {
.top-bar .top-bar-left,
.top-bar .top-bar-right {
width: auto; } }
@media screen and (max-width: 63.9375em) {
.top-bar.stacked-for-medium .top-bar-left,
.top-bar.stacked-for-medium .top-bar-right {
width: 100%; } }
@media screen and (max-width: 74.9375em) {
.top-bar.stacked-for-large .top-bar-left,
.top-bar.stacked-for-large .top-bar-right {
width: 100%; } }
.top-bar-title {
float: left;
margin-right: 1rem; }
.top-bar-left {
float: left; }
.top-bar-right {
float: right; }
.breadcrumbs {
list-style: none;
margin: 0 0 1rem 0; }
.breadcrumbs::before, .breadcrumbs::after {
content: ' ';
display: table; }
.breadcrumbs::after {
clear: both; }
.breadcrumbs li {
float: left;
color: #0a0a0a;
font-size: 0.6875rem;
cursor: default;
text-transform: uppercase; }
.breadcrumbs li:not(:last-child)::after {
color: #cacaca;
content: "/";
margin: 0 0.75rem;
position: relative;
top: 1px;
opacity: 1; }
.breadcrumbs a {
color: #2ba6cb; }
.breadcrumbs a:hover {
text-decoration: underline; }
.breadcrumbs .disabled {
color: #cacaca;
cursor: not-allowed; }
.pagination {
margin-left: 0;
margin-bottom: 1rem; }
.pagination::before, .pagination::after {
content: ' ';
display: table; }
.pagination::after {
clear: both; }
.pagination li {
font-size: 0.875rem;
margin-right: 0.0625rem;
border-radius: 3px;
display: none; }
.pagination li:last-child, .pagination li:first-child {
display: inline-block; }
@media screen and (min-width: 40em) {
.pagination li {
display: inline-block; } }
.pagination a,
.pagination button {
color: #0a0a0a;
display: block;
padding: 0.1875rem 0.625rem;
border-radius: 3px; }
.pagination a:hover,
.pagination button:hover {
background: #e6e6e6; }
.pagination .current {
padding: 0.1875rem 0.625rem;
background: #2ba6cb;
color: #fefefe;
cursor: default; }
.pagination .disabled {
padding: 0.1875rem 0.625rem;
color: #cacaca;
cursor: not-allowed; }
.pagination .disabled:hover {
background: transparent; }
.pagination .ellipsis::after {
content: '\2026';
padding: 0.1875rem 0.625rem;
color: #0a0a0a; }
.pagination-previous a::before,
.pagination-previous.disabled::before {
content: '\00ab';
display: inline-block;
margin-right: 0.5rem; }
.pagination-next a::after,
.pagination-next.disabled::after {
content: '\00bb';
display: inline-block;
margin-left: 0.5rem; }
.accordion {
list-style-type: none;
background: #fefefe;
margin-left: 0; }
.accordion-item:first-child > :first-child {
border-radius: 3px 3px 0 0; }
.accordion-item:last-child > :last-child {
border-radius: 0 0 3px 3px; }
.accordion-title {
display: block;
padding: 1.25rem 1rem;
line-height: 1;
font-size: 0.75rem;
color: #2ba6cb;
position: relative;
border: 1px solid #e6e6e6;
border-bottom: 0; }
:last-child:not(.is-active) > .accordion-title {
border-radius: 0 0 3px 3px;
border-bottom: 1px solid #e6e6e6; }
.accordion-title:hover, .accordion-title:focus {
background-color: #e6e6e6; }
.accordion-title::before {
content: '+';
position: absolute;
right: 1rem;
top: 50%;
margin-top: -0.5rem; }
.is-active > .accordion-title::before {
content: '–'; }
.accordion-content {
padding: 1rem;
display: none;
border: 1px solid #e6e6e6;
border-bottom: 0;
background-color: #fefefe;
color: #0a0a0a; }
:last-child > .accordion-content:last-child {
border-bottom: 1px solid #e6e6e6; }
.dropdown-pane {
background-color: #fefefe;
border: 1px solid #cacaca;
border-radius: 3px;
display: block;
font-size: 1rem;
padding: 1rem;
position: absolute;
visibility: hidden;
width: 300px;
z-index: 10; }
.dropdown-pane.is-open {
visibility: visible; }
.dropdown-pane.tiny {
width: 100px; }
.dropdown-pane.small {
width: 200px; }
.dropdown-pane.large {
width: 400px; }
html,
body {
height: 100%; }
.off-canvas-wrapper {
width: 100%;
overflow-x: hidden;
position: relative;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-overflow-scrolling: auto; }
.off-canvas-wrapper-inner {
position: relative;
width: 100%;
transition: -webkit-transform 0.5s ease;
transition: transform 0.5s ease; }
.off-canvas-wrapper-inner::before, .off-canvas-wrapper-inner::after {
content: ' ';
display: table; }
.off-canvas-wrapper-inner::after {
clear: both; }
.off-canvas-content,
.off-canvas-content {
min-height: 100%;
background: #fefefe;
transition: -webkit-transform 0.5s ease;
transition: transform 0.5s ease;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
z-index: 1;
padding-bottom: 0.1px;
box-shadow: 0 0 10px rgba(10, 10, 10, 0.5); }
.js-off-canvas-exit {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(254, 254, 254, 0.25);
cursor: pointer;
transition: background 0.5s ease; }
.off-canvas {
position: absolute;
background: #e6e6e6;
z-index: -1;
max-height: 100%;
overflow-y: auto;
-webkit-transform: translateX(0);
-ms-transform: translateX(0);
transform: translateX(0); }
[data-whatinput='mouse'] .off-canvas {
outline: 0; }
.off-canvas.position-left {
left: -250px;
top: 0;
width: 250px; }
.is-open-left {
-webkit-transform: translateX(250px);
-ms-transform: translateX(250px);
transform: translateX(250px); }
.off-canvas.position-right {
right: -250px;
top: 0;
width: 250px; }
.is-open-right {
-webkit-transform: translateX(-250px);
-ms-transform: translateX(-250px);
transform: translateX(-250px); }
@media screen and (min-width: 40em) {
.position-left.reveal-for-medium {
left: 0;
z-index: auto;
position: fixed; }
.position-left.reveal-for-medium ~ .off-canvas-content {
margin-left: 250px; }
.position-right.reveal-for-medium {
right: 0;
z-index: auto;
position: fixed; }
.position-right.reveal-for-medium ~ .off-canvas-content {
margin-right: 250px; } }
@media screen and (min-width: 64em) {
.position-left.reveal-for-large {
left: 0;
z-index: auto;
position: fixed; }
.position-left.reveal-for-large ~ .off-canvas-content {
margin-left: 250px; }
.position-right.reveal-for-large {
right: 0;
z-index: auto;
position: fixed; }
.position-right.reveal-for-large ~ .off-canvas-content {
margin-right: 250px; } }
.tabs {
margin: 0;
list-style-type: none;
background: #fefefe;
border: 1px solid #e6e6e6; }
.tabs::before, .tabs::after {
content: ' ';
display: table; }
.tabs::after {
clear: both; }
.tabs.vertical > li {
width: auto;
float: none;
display: block; }
.tabs.simple > li > a {
padding: 0; }
.tabs.simple > li > a:hover {
background: transparent; }
.tabs.primary {
background: #2ba6cb; }
.tabs.primary > li > a {
color: #fefefe; }
.tabs.primary > li > a:hover, .tabs.primary > li > a:focus {
background: #299ec1; }
.tabs-title {
float: left; }
.tabs-title > a {
display: block;
padding: 1.25rem 1.5rem;
line-height: 1;
font-size: 0.75rem; }
.tabs-title > a:hover {
background: #fefefe; }
.tabs-title > a:focus, .tabs-title > a[aria-selected='true'] {
background: #e6e6e6; }
.tabs-content {
background: #fefefe;
transition: all 0.5s ease;
border: 1px solid #e6e6e6;
border-top: 0; }
.tabs-content.vertical {
border: 1px solid #e6e6e6;
border-left: 0; }
.tabs-panel {
display: none;
padding: 1rem; }
.tabs-panel.is-active {
display: block; }
.callout {
margin: 0 0 1rem 0;
padding: 1rem;
border: 1px solid rgba(10, 10, 10, 0.25);
border-radius: 3px;
position: relative;
color: #0a0a0a;
background-color: white; }
.callout > :first-child {
margin-top: 0; }
.callout > :last-child {
margin-bottom: 0; }
.callout.primary {
background-color: #def2f8; }
.callout.secondary {
background-color: #fcfcfc; }
.callout.alert {
background-color: #fcd6d6; }
.callout.success {
background-color: #e6f7d9; }
.callout.warning {
background-color: #fff3d9; }
.callout.body-font {
background-color: #dedede; }
.callout.header {
background-color: #dedede; }
.callout.small {
padding-top: 0.5rem;
padding-right: 0.5rem;
padding-bottom: 0.5rem;
padding-left: 0.5rem; }
.callout.large {
padding-top: 3rem;
padding-right: 3rem;
padding-bottom: 3rem;
padding-left: 3rem; }
.media-object {
margin-bottom: 1rem;
display: block; }
.media-object img {
max-width: none; }
@media screen and (max-width: 39.9375em) {
.media-object.stack-for-small .media-object-section {
padding: 0;
padding-bottom: 1rem;
display: block; }
.media-object.stack-for-small .media-object-section img {
width: 100%; } }
.media-object-section {
display: table-cell;
vertical-align: top; }
.media-object-section:first-child {
padding-right: 1rem; }
.media-object-section:last-child:not(:nth-child(2)) {
padding-left: 1rem; }
.media-object-section > :last-child {
margin-bottom: 0; }
.media-object-section.middle {
vertical-align: middle; }
.media-object-section.bottom {
vertical-align: bottom; }
body.is-reveal-open {
overflow: hidden; }
html.is-reveal-open,
html.is-reveal-open body {
height: 100%;
overflow: hidden;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none; }
.reveal-overlay {
display: none;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 1005;
background-color: rgba(10, 10, 10, 0.45);
overflow-y: scroll; }
.reveal {
display: none;
z-index: 1006;
padding: 1rem;
border: 1px solid #cacaca;
background-color: #fefefe;
border-radius: 3px;
position: relative;
top: 100px;
margin-left: auto;
margin-right: auto;
overflow-y: auto; }
[data-whatinput='mouse'] .reveal {
outline: 0; }
@media screen and (min-width: 40em) {
.reveal {
min-height: 0; } }
.reveal .column, .reveal .columns,
.reveal .columns {
min-width: 0; }
.reveal > :last-child {
margin-bottom: 0; }
@media screen and (min-width: 40em) {
.reveal {
width: 600px;
max-width: 62.5rem; } }
@media screen and (min-width: 40em) {
.reveal .reveal {
left: auto;
right: auto;
margin: 0 auto; } }
.reveal.collapse {
padding: 0; }
@media screen and (min-width: 40em) {
.reveal.tiny {
width: 30%;
max-width: 62.5rem; } }
@media screen and (min-width: 40em) {
.reveal.small {
width: 50%;
max-width: 62.5rem; } }
@media screen and (min-width: 40em) {
.reveal.large {
width: 90%;
max-width: 62.5rem; } }
.reveal.full {
top: 0;
left: 0;
width: 100%;
height: 100%;
height: 100vh;
min-height: 100vh;
max-width: none;
margin-left: 0;
border: 0;
border-radius: 0; }
@media screen and (max-width: 39.9375em) {
.reveal {
top: 0;
left: 0;
width: 100%;
height: 100%;
height: 100vh;
min-height: 100vh;
max-width: none;
margin-left: 0;
border: 0;
border-radius: 0; } }
.reveal.without-overlay {
position: fixed; }
table {
width: 100%;
margin-bottom: 1rem;
border-radius: 3px; }
table thead,
table tbody,
table tfoot {
border: 1px solid #f1f1f1;
background-color: #fefefe; }
table caption {
font-weight: bold;
padding: 0.5rem 0.625rem 0.625rem; }
table thead,
table tfoot {
background: #f8f8f8;
color: #0a0a0a; }
table thead tr,
table tfoot tr {
background: transparent; }
table thead th,
table thead td,
table tfoot th,
table tfoot td {
padding: 0.5rem 0.625rem 0.625rem;
font-weight: bold;
text-align: left; }
table tbody tr:nth-child(even) {
background-color: #f1f1f1; }
table tbody th,
table tbody td {
padding: 0.5rem 0.625rem 0.625rem; }
@media screen and (max-width: 63.9375em) {
table.stack thead {
display: none; }
table.stack tfoot {
display: none; }
table.stack tr,
table.stack th,
table.stack td {
display: block; }
table.stack td {
border-top: 0; } }
table.scroll {
display: block;
width: 100%;
overflow-x: auto; }
table.hover tr:hover {
background-color: #f9f9f9; }
table.hover tr:nth-of-type(even):hover {
background-color: #ececec; }
.table-scroll {
overflow-x: auto; }
.table-scroll table {
width: auto; }
.badge {
display: inline-block;
padding: 0.3em;
min-width: 2.1em;
font-size: 0.6rem;
text-align: center;
border-radius: 50%;
background: #2ba6cb;
color: #fefefe; }
.badge.secondary {
background: #e9e9e9;
color: #0a0a0a; }
.badge.alert {
background: #c60f13;
color: #fefefe; }
.badge.success {
background: #5da423;
color: #fefefe; }
.badge.warning {
background: #ffae00;
color: #fefefe; }
.badge.body-font {
background: #222222;
color: #fefefe; }
.badge.header {
background: #222222;
color: #fefefe; }
.label {
display: inline-block;
padding: 0.33333rem 0.5rem;
font-size: 0.8rem;
line-height: 1;
white-space: nowrap;
cursor: default;
border-radius: 3px;
background: #2ba6cb;
color: #fefefe; }
.label.secondary {
background: #e9e9e9;
color: #0a0a0a; }
.label.alert {
background: #c60f13;
color: #fefefe; }
.label.success {
background: #5da423;
color: #fefefe; }
.label.warning {
background: #ffae00;
color: #fefefe; }
.label.body-font {
background: #222222;
color: #fefefe; }
.label.header {
background: #222222;
color: #fefefe; }
.progress {
background-color: #cacaca;
height: 1rem;
margin-bottom: 1rem;
border-radius: 3px; }
.progress.primary .progress-meter {
background-color: #2ba6cb; }
.progress.secondary .progress-meter {
background-color: #e9e9e9; }
.progress.alert .progress-meter {
background-color: #c60f13; }
.progress.success .progress-meter {
background-color: #5da423; }
.progress.warning .progress-meter {
background-color: #ffae00; }
.progress.body-font .progress-meter {
background-color: #222222; }
.progress.header .progress-meter {
background-color: #222222; }
.progress-meter {
position: relative;
display: block;
width: 0%;
height: 100%;
background-color: #2ba6cb;
border-radius: 3px; }
.progress-meter-text {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
position: absolute;
margin: 0;
font-size: 0.75rem;
font-weight: bold;
color: #fefefe;
white-space: nowrap;
border-radius: 3px; }
.has-tip {
border-bottom: dotted 1px #8a8a8a;
font-weight: bold;
position: relative;
display: inline-block;
cursor: help; }
.tooltip {
background-color: #0a0a0a;
color: #fefefe;
font-size: 80%;
padding: 0.75rem;
position: absolute;
z-index: 10;
top: calc(100% + 0.6495rem);
max-width: 10rem !important;
border-radius: 3px; }
.tooltip::before {
content: '';
display: block;
width: 0;
height: 0;
border: inset 0.75rem;
border-color: transparent transparent #0a0a0a;
border-bottom-style: solid;
border-top-width: 0;
bottom: 100%;
position: absolute;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%); }
.tooltip.top::before {
content: '';
display: block;
width: 0;
height: 0;
border: inset 0.75rem;
border-color: #0a0a0a transparent transparent;
border-top-style: solid;
border-bottom-width: 0;
top: 100%;
bottom: auto; }
.tooltip.left::before {
content: '';
display: block;
width: 0;
height: 0;
border: inset 0.75rem;
border-color: transparent transparent transparent #0a0a0a;
border-left-style: solid;
border-right-width: 0;
bottom: auto;
left: 100%;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%); }
.tooltip.right::before {
content: '';
display: block;
width: 0;
height: 0;
border: inset 0.75rem;
border-color: transparent #0a0a0a transparent transparent;
border-right-style: solid;
border-left-width: 0;
bottom: auto;
left: auto;
right: 100%;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%); }
.flex-video {
position: relative;
height: 0;
padding-bottom: 75%;
margin-bottom: 1rem;
overflow: hidden; }
.flex-video iframe,
.flex-video object,
.flex-video embed,
.flex-video video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%; }
.flex-video.widescreen {
padding-bottom: 56.25%; }
.flex-video.vimeo {
padding-top: 0; }
.orbit {
position: relative; }
.orbit-container {
position: relative;
margin: 0;
overflow: hidden;
list-style: none; }
.orbit-slide {
width: 100%;
max-height: 100%; }
.orbit-slide.no-motionui.is-active {
top: 0;
left: 0; }
.orbit-figure {
margin: 0; }
.orbit-image {
margin: 0;
width: 100%;
max-width: 100%; }
.orbit-caption {
position: absolute;
bottom: 0;
width: 100%;
padding: 1rem;
margin-bottom: 0;
color: #fefefe;
background-color: rgba(10, 10, 10, 0.5); }
.orbit-previous, .orbit-next {
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
z-index: 10;
padding: 1rem;
color: #fefefe; }
[data-whatinput='mouse'] .orbit-previous, [data-whatinput='mouse'] .orbit-next {
outline: 0; }
.orbit-previous:hover, .orbit-next:hover, .orbit-previous:active, .orbit-next:active, .orbit-previous:focus, .orbit-next:focus {
background-color: rgba(10, 10, 10, 0.5); }
.orbit-previous {
left: 0; }
.orbit-next {
left: auto;
right: 0; }
.orbit-bullets {
position: relative;
margin-top: 0.8rem;
margin-bottom: 0.8rem;
text-align: center; }
[data-whatinput='mouse'] .orbit-bullets {
outline: 0; }
.orbit-bullets button {
width: 1.2rem;
height: 1.2rem;
margin: 0.1rem;
background-color: #cacaca;
border-radius: 50%; }
.orbit-bullets button:hover {
background-color: #8a8a8a; }
.orbit-bullets button.is-active {
background-color: #8a8a8a; }
.thumbnail {
border: solid 4px #fefefe;
box-shadow: 0 0 0 1px rgba(10, 10, 10, 0.2);
display: inline-block;
line-height: 0;
max-width: 100%;
transition: box-shadow 200ms ease-out;
border-radius: 3px;
margin-bottom: 1rem; }
.thumbnail:hover, .thumbnail:focus {
box-shadow: 0 0 6px 1px rgba(43, 166, 203, 0.5); }
.sticky-container {
position: relative; }
.sticky {
position: absolute;
z-index: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0); }
.sticky.is-stuck {
position: fixed;
z-index: 5; }
.sticky.is-stuck.is-at-top {
top: 0; }
.sticky.is-stuck.is-at-bottom {
bottom: 0; }
.sticky.is-anchored {
position: absolute;
left: auto;
right: auto; }
.sticky.is-anchored.is-at-bottom {
bottom: 0; }
.row {
max-width: 62.5rem;
margin-left: auto;
margin-right: auto; }
.row::before, .row::after {
content: ' ';
display: table; }
.row::after {
clear: both; }
.row.collapse > .column, .row.collapse > .columns {
padding-left: 0;
padding-right: 0; }
.row .row {
max-width: none;
margin-left: -0.9375rem;
margin-right: -0.9375rem; }
.row .row.collapse {
margin-left: 0;
margin-right: 0; }
.row.expanded {
max-width: none; }
.row.expanded .row {
margin-left: auto;
margin-right: auto; }
.column, .columns {
width: 100%;
float: left;
padding-left: 0.9375rem;
padding-right: 0.9375rem; }
.column:last-child:not(:first-child), .columns:last-child:not(:first-child) {
float: right; }
.column.end:last-child:last-child, .end.columns:last-child:last-child {
float: left; }
.column.row.row, .row.row.columns {
float: none; }
.row .column.row.row, .row .row.row.columns {
padding-left: 0;
padding-right: 0;
margin-left: 0;
margin-right: 0; }
.small-1 {
width: 8.33333%; }
.small-push-1 {
position: relative;
left: 8.33333%; }
.small-pull-1 {
position: relative;
left: -8.33333%; }
.small-offset-0 {
margin-left: 0%; }
.small-2 {
width: 16.66667%; }
.small-push-2 {
position: relative;
left: 16.66667%; }
.small-pull-2 {
position: relative;
left: -16.66667%; }
.small-offset-1 {
margin-left: 8.33333%; }
.small-3 {
width: 25%; }
.small-push-3 {
position: relative;
left: 25%; }
.small-pull-3 {
position: relative;
left: -25%; }
.small-offset-2 {
margin-left: 16.66667%; }
.small-4 {
width: 33.33333%; }
.small-push-4 {
position: relative;
left: 33.33333%; }
.small-pull-4 {
position: relative;
left: -33.33333%; }
.small-offset-3 {
margin-left: 25%; }
.small-5 {
width: 41.66667%; }
.small-push-5 {
position: relative;
left: 41.66667%; }
.small-pull-5 {
position: relative;
left: -41.66667%; }
.small-offset-4 {
margin-left: 33.33333%; }
.small-6 {
width: 50%; }
.small-push-6 {
position: relative;
left: 50%; }
.small-pull-6 {
position: relative;
left: -50%; }
.small-offset-5 {
margin-left: 41.66667%; }
.small-7 {
width: 58.33333%; }
.small-push-7 {
position: relative;
left: 58.33333%; }
.small-pull-7 {
position: relative;
left: -58.33333%; }
.small-offset-6 {
margin-left: 50%; }
.small-8 {
width: 66.66667%; }
.small-push-8 {
position: relative;
left: 66.66667%; }
.small-pull-8 {
position: relative;
left: -66.66667%; }
.small-offset-7 {
margin-left: 58.33333%; }
.small-9 {
width: 75%; }
.small-push-9 {
position: relative;
left: 75%; }
.small-pull-9 {
position: relative;
left: -75%; }
.small-offset-8 {
margin-left: 66.66667%; }
.small-10 {
width: 83.33333%; }
.small-push-10 {
position: relative;
left: 83.33333%; }
.small-pull-10 {
position: relative;
left: -83.33333%; }
.small-offset-9 {
margin-left: 75%; }
.small-11 {
width: 91.66667%; }
.small-push-11 {
position: relative;
left: 91.66667%; }
.small-pull-11 {
position: relative;
left: -91.66667%; }
.small-offset-10 {
margin-left: 83.33333%; }
.small-12 {
width: 100%; }
.small-offset-11 {
margin-left: 91.66667%; }
.small-up-1 > .column, .small-up-1 > .columns {
width: 100%;
float: left; }
.small-up-1 > .column:nth-of-type(1n), .small-up-1 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-1 > .column:nth-of-type(1n+1), .small-up-1 > .columns:nth-of-type(1n+1) {
clear: both; }
.small-up-1 > .column:last-child, .small-up-1 > .columns:last-child {
float: left; }
.small-up-2 > .column, .small-up-2 > .columns {
width: 50%;
float: left; }
.small-up-2 > .column:nth-of-type(1n), .small-up-2 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-2 > .column:nth-of-type(2n+1), .small-up-2 > .columns:nth-of-type(2n+1) {
clear: both; }
.small-up-2 > .column:last-child, .small-up-2 > .columns:last-child {
float: left; }
.small-up-3 > .column, .small-up-3 > .columns {
width: 33.33333%;
float: left; }
.small-up-3 > .column:nth-of-type(1n), .small-up-3 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-3 > .column:nth-of-type(3n+1), .small-up-3 > .columns:nth-of-type(3n+1) {
clear: both; }
.small-up-3 > .column:last-child, .small-up-3 > .columns:last-child {
float: left; }
.small-up-4 > .column, .small-up-4 > .columns {
width: 25%;
float: left; }
.small-up-4 > .column:nth-of-type(1n), .small-up-4 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-4 > .column:nth-of-type(4n+1), .small-up-4 > .columns:nth-of-type(4n+1) {
clear: both; }
.small-up-4 > .column:last-child, .small-up-4 > .columns:last-child {
float: left; }
.small-up-5 > .column, .small-up-5 > .columns {
width: 20%;
float: left; }
.small-up-5 > .column:nth-of-type(1n), .small-up-5 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-5 > .column:nth-of-type(5n+1), .small-up-5 > .columns:nth-of-type(5n+1) {
clear: both; }
.small-up-5 > .column:last-child, .small-up-5 > .columns:last-child {
float: left; }
.small-up-6 > .column, .small-up-6 > .columns {
width: 16.66667%;
float: left; }
.small-up-6 > .column:nth-of-type(1n), .small-up-6 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-6 > .column:nth-of-type(6n+1), .small-up-6 > .columns:nth-of-type(6n+1) {
clear: both; }
.small-up-6 > .column:last-child, .small-up-6 > .columns:last-child {
float: left; }
.small-up-7 > .column, .small-up-7 > .columns {
width: 14.28571%;
float: left; }
.small-up-7 > .column:nth-of-type(1n), .small-up-7 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-7 > .column:nth-of-type(7n+1), .small-up-7 > .columns:nth-of-type(7n+1) {
clear: both; }
.small-up-7 > .column:last-child, .small-up-7 > .columns:last-child {
float: left; }
.small-up-8 > .column, .small-up-8 > .columns {
width: 12.5%;
float: left; }
.small-up-8 > .column:nth-of-type(1n), .small-up-8 > .columns:nth-of-type(1n) {
clear: none; }
.small-up-8 > .column:nth-of-type(8n+1), .small-up-8 > .columns:nth-of-type(8n+1) {
clear: both; }
.small-up-8 > .column:last-child, .small-up-8 > .columns:last-child {
float: left; }
.small-collapse > .column, .small-collapse > .columns {
padding-left: 0;
padding-right: 0; }
.small-collapse .row,
.expanded.row .small-collapse.row {
margin-left: 0;
margin-right: 0; }
.small-uncollapse > .column, .small-uncollapse > .columns {
padding-left: 0.9375rem;
padding-right: 0.9375rem; }
.small-centered {
float: none;
margin-left: auto;
margin-right: auto; }
.small-uncentered,
.small-push-0,
.small-pull-0 {
position: static;
margin-left: 0;
margin-right: 0;
float: left; }
@media screen and (min-width: 40em) {
.medium-1 {
width: 8.33333%; }
.medium-push-1 {
position: relative;
left: 8.33333%; }
.medium-pull-1 {
position: relative;
left: -8.33333%; }
.medium-offset-0 {
margin-left: 0%; }
.medium-2 {
width: 16.66667%; }
.medium-push-2 {
position: relative;
left: 16.66667%; }
.medium-pull-2 {
position: relative;
left: -16.66667%; }
.medium-offset-1 {
margin-left: 8.33333%; }
.medium-3 {
width: 25%; }
.medium-push-3 {
position: relative;
left: 25%; }
.medium-pull-3 {
position: relative;
left: -25%; }
.medium-offset-2 {
margin-left: 16.66667%; }
.medium-4 {
width: 33.33333%; }
.medium-push-4 {
position: relative;
left: 33.33333%; }
.medium-pull-4 {
position: relative;
left: -33.33333%; }
.medium-offset-3 {
margin-left: 25%; }
.medium-5 {
width: 41.66667%; }
.medium-push-5 {
position: relative;
left: 41.66667%; }
.medium-pull-5 {
position: relative;
left: -41.66667%; }
.medium-offset-4 {
margin-left: 33.33333%; }
.medium-6 {
width: 50%; }
.medium-push-6 {
position: relative;
left: 50%; }
.medium-pull-6 {
position: relative;
left: -50%; }
.medium-offset-5 {
margin-left: 41.66667%; }
.medium-7 {
width: 58.33333%; }
.medium-push-7 {
position: relative;
left: 58.33333%; }
.medium-pull-7 {
position: relative;
left: -58.33333%; }
.medium-offset-6 {
margin-left: 50%; }
.medium-8 {
width: 66.66667%; }
.medium-push-8 {
position: relative;
left: 66.66667%; }
.medium-pull-8 {
position: relative;
left: -66.66667%; }
.medium-offset-7 {
margin-left: 58.33333%; }
.medium-9 {
width: 75%; }
.medium-push-9 {
position: relative;
left: 75%; }
.medium-pull-9 {
position: relative;
left: -75%; }
.medium-offset-8 {
margin-left: 66.66667%; }
.medium-10 {
width: 83.33333%; }
.medium-push-10 {
position: relative;
left: 83.33333%; }
.medium-pull-10 {
position: relative;
left: -83.33333%; }
.medium-offset-9 {
margin-left: 75%; }
.medium-11 {
width: 91.66667%; }
.medium-push-11 {
position: relative;
left: 91.66667%; }
.medium-pull-11 {
position: relative;
left: -91.66667%; }
.medium-offset-10 {
margin-left: 83.33333%; }
.medium-12 {
width: 100%; }
.medium-offset-11 {
margin-left: 91.66667%; }
.medium-up-1 > .column, .medium-up-1 > .columns {
width: 100%;
float: left; }
.medium-up-1 > .column:nth-of-type(1n), .medium-up-1 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-1 > .column:nth-of-type(1n+1), .medium-up-1 > .columns:nth-of-type(1n+1) {
clear: both; }
.medium-up-1 > .column:last-child, .medium-up-1 > .columns:last-child {
float: left; }
.medium-up-2 > .column, .medium-up-2 > .columns {
width: 50%;
float: left; }
.medium-up-2 > .column:nth-of-type(1n), .medium-up-2 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-2 > .column:nth-of-type(2n+1), .medium-up-2 > .columns:nth-of-type(2n+1) {
clear: both; }
.medium-up-2 > .column:last-child, .medium-up-2 > .columns:last-child {
float: left; }
.medium-up-3 > .column, .medium-up-3 > .columns {
width: 33.33333%;
float: left; }
.medium-up-3 > .column:nth-of-type(1n), .medium-up-3 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-3 > .column:nth-of-type(3n+1), .medium-up-3 > .columns:nth-of-type(3n+1) {
clear: both; }
.medium-up-3 > .column:last-child, .medium-up-3 > .columns:last-child {
float: left; }
.medium-up-4 > .column, .medium-up-4 > .columns {
width: 25%;
float: left; }
.medium-up-4 > .column:nth-of-type(1n), .medium-up-4 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-4 > .column:nth-of-type(4n+1), .medium-up-4 > .columns:nth-of-type(4n+1) {
clear: both; }
.medium-up-4 > .column:last-child, .medium-up-4 > .columns:last-child {
float: left; }
.medium-up-5 > .column, .medium-up-5 > .columns {
width: 20%;
float: left; }
.medium-up-5 > .column:nth-of-type(1n), .medium-up-5 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-5 > .column:nth-of-type(5n+1), .medium-up-5 > .columns:nth-of-type(5n+1) {
clear: both; }
.medium-up-5 > .column:last-child, .medium-up-5 > .columns:last-child {
float: left; }
.medium-up-6 > .column, .medium-up-6 > .columns {
width: 16.66667%;
float: left; }
.medium-up-6 > .column:nth-of-type(1n), .medium-up-6 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-6 > .column:nth-of-type(6n+1), .medium-up-6 > .columns:nth-of-type(6n+1) {
clear: both; }
.medium-up-6 > .column:last-child, .medium-up-6 > .columns:last-child {
float: left; }
.medium-up-7 > .column, .medium-up-7 > .columns {
width: 14.28571%;
float: left; }
.medium-up-7 > .column:nth-of-type(1n), .medium-up-7 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-7 > .column:nth-of-type(7n+1), .medium-up-7 > .columns:nth-of-type(7n+1) {
clear: both; }
.medium-up-7 > .column:last-child, .medium-up-7 > .columns:last-child {
float: left; }
.medium-up-8 > .column, .medium-up-8 > .columns {
width: 12.5%;
float: left; }
.medium-up-8 > .column:nth-of-type(1n), .medium-up-8 > .columns:nth-of-type(1n) {
clear: none; }
.medium-up-8 > .column:nth-of-type(8n+1), .medium-up-8 > .columns:nth-of-type(8n+1) {
clear: both; }
.medium-up-8 > .column:last-child, .medium-up-8 > .columns:last-child {
float: left; }
.medium-collapse > .column, .medium-collapse > .columns {
padding-left: 0;
padding-right: 0; }
.medium-collapse .row,
.expanded.row .medium-collapse.row {
margin-left: 0;
margin-right: 0; }
.medium-uncollapse > .column, .medium-uncollapse > .columns {
padding-left: 0.9375rem;
padding-right: 0.9375rem; }
.medium-centered {
float: none;
margin-left: auto;
margin-right: auto; }
.medium-uncentered,
.medium-push-0,
.medium-pull-0 {
position: static;
margin-left: 0;
margin-right: 0;
float: left; } }
@media screen and (min-width: 64em) {
.large-1 {
width: 8.33333%; }
.large-push-1 {
position: relative;
left: 8.33333%; }
.large-pull-1 {
position: relative;
left: -8.33333%; }
.large-offset-0 {
margin-left: 0%; }
.large-2 {
width: 16.66667%; }
.large-push-2 {
position: relative;
left: 16.66667%; }
.large-pull-2 {
position: relative;
left: -16.66667%; }
.large-offset-1 {
margin-left: 8.33333%; }
.large-3 {
width: 25%; }
.large-push-3 {
position: relative;
left: 25%; }
.large-pull-3 {
position: relative;
left: -25%; }
.large-offset-2 {
margin-left: 16.66667%; }
.large-4 {
width: 33.33333%; }
.large-push-4 {
position: relative;
left: 33.33333%; }
.large-pull-4 {
position: relative;
left: -33.33333%; }
.large-offset-3 {
margin-left: 25%; }
.large-5 {
width: 41.66667%; }
.large-push-5 {
position: relative;
left: 41.66667%; }
.large-pull-5 {
position: relative;
left: -41.66667%; }
.large-offset-4 {
margin-left: 33.33333%; }
.large-6 {
width: 50%; }
.large-push-6 {
position: relative;
left: 50%; }
.large-pull-6 {
position: relative;
left: -50%; }
.large-offset-5 {
margin-left: 41.66667%; }
.large-7 {
width: 58.33333%; }
.large-push-7 {
position: relative;
left: 58.33333%; }
.large-pull-7 {
position: relative;
left: -58.33333%; }
.large-offset-6 {
margin-left: 50%; }
.large-8 {
width: 66.66667%; }
.large-push-8 {
position: relative;
left: 66.66667%; }
.large-pull-8 {
position: relative;
left: -66.66667%; }
.large-offset-7 {
margin-left: 58.33333%; }
.large-9 {
width: 75%; }
.large-push-9 {
position: relative;
left: 75%; }
.large-pull-9 {
position: relative;
left: -75%; }
.large-offset-8 {
margin-left: 66.66667%; }
.large-10 {
width: 83.33333%; }
.large-push-10 {
position: relative;
left: 83.33333%; }
.large-pull-10 {
position: relative;
left: -83.33333%; }
.large-offset-9 {
margin-left: 75%; }
.large-11 {
width: 91.66667%; }
.large-push-11 {
position: relative;
left: 91.66667%; }
.large-pull-11 {
position: relative;
left: -91.66667%; }
.large-offset-10 {
margin-left: 83.33333%; }
.large-12 {
width: 100%; }
.large-offset-11 {
margin-left: 91.66667%; }
.large-up-1 > .column, .large-up-1 > .columns {
width: 100%;
float: left; }
.large-up-1 > .column:nth-of-type(1n), .large-up-1 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-1 > .column:nth-of-type(1n+1), .large-up-1 > .columns:nth-of-type(1n+1) {
clear: both; }
.large-up-1 > .column:last-child, .large-up-1 > .columns:last-child {
float: left; }
.large-up-2 > .column, .large-up-2 > .columns {
width: 50%;
float: left; }
.large-up-2 > .column:nth-of-type(1n), .large-up-2 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-2 > .column:nth-of-type(2n+1), .large-up-2 > .columns:nth-of-type(2n+1) {
clear: both; }
.large-up-2 > .column:last-child, .large-up-2 > .columns:last-child {
float: left; }
.large-up-3 > .column, .large-up-3 > .columns {
width: 33.33333%;
float: left; }
.large-up-3 > .column:nth-of-type(1n), .large-up-3 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-3 > .column:nth-of-type(3n+1), .large-up-3 > .columns:nth-of-type(3n+1) {
clear: both; }
.large-up-3 > .column:last-child, .large-up-3 > .columns:last-child {
float: left; }
.large-up-4 > .column, .large-up-4 > .columns {
width: 25%;
float: left; }
.large-up-4 > .column:nth-of-type(1n), .large-up-4 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-4 > .column:nth-of-type(4n+1), .large-up-4 > .columns:nth-of-type(4n+1) {
clear: both; }
.large-up-4 > .column:last-child, .large-up-4 > .columns:last-child {
float: left; }
.large-up-5 > .column, .large-up-5 > .columns {
width: 20%;
float: left; }
.large-up-5 > .column:nth-of-type(1n), .large-up-5 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-5 > .column:nth-of-type(5n+1), .large-up-5 > .columns:nth-of-type(5n+1) {
clear: both; }
.large-up-5 > .column:last-child, .large-up-5 > .columns:last-child {
float: left; }
.large-up-6 > .column, .large-up-6 > .columns {
width: 16.66667%;
float: left; }
.large-up-6 > .column:nth-of-type(1n), .large-up-6 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-6 > .column:nth-of-type(6n+1), .large-up-6 > .columns:nth-of-type(6n+1) {
clear: both; }
.large-up-6 > .column:last-child, .large-up-6 > .columns:last-child {
float: left; }
.large-up-7 > .column, .large-up-7 > .columns {
width: 14.28571%;
float: left; }
.large-up-7 > .column:nth-of-type(1n), .large-up-7 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-7 > .column:nth-of-type(7n+1), .large-up-7 > .columns:nth-of-type(7n+1) {
clear: both; }
.large-up-7 > .column:last-child, .large-up-7 > .columns:last-child {
float: left; }
.large-up-8 > .column, .large-up-8 > .columns {
width: 12.5%;
float: left; }
.large-up-8 > .column:nth-of-type(1n), .large-up-8 > .columns:nth-of-type(1n) {
clear: none; }
.large-up-8 > .column:nth-of-type(8n+1), .large-up-8 > .columns:nth-of-type(8n+1) {
clear: both; }
.large-up-8 > .column:last-child, .large-up-8 > .columns:last-child {
float: left; }
.large-collapse > .column, .large-collapse > .columns {
padding-left: 0;
padding-right: 0; }
.large-collapse .row,
.expanded.row .large-collapse.row {
margin-left: 0;
margin-right: 0; }
.large-uncollapse > .column, .large-uncollapse > .columns {
padding-left: 0.9375rem;
padding-right: 0.9375rem; }
.large-centered {
float: none;
margin-left: auto;
margin-right: auto; }
.large-uncentered,
.large-push-0,
.large-pull-0 {
position: static;
margin-left: 0;
margin-right: 0;
float: left; } }
.menu-icon {
position: relative;
display: inline-block;
vertical-align: middle;
cursor: pointer;
width: 20px;
height: 16px; }
.menu-icon::after {
content: '';
position: absolute;
display: block;
width: 100%;
height: 2px;
background: #fefefe;
top: 0;
left: 0;
box-shadow: 0 7px 0 #fefefe, 0 14px 0 #fefefe; }
.menu-icon:hover::after {
background: #cacaca;
box-shadow: 0 7px 0 #cacaca, 0 14px 0 #cacaca; }
.menu-icon.dark {
position: relative;
display: inline-block;
vertical-align: middle;
cursor: pointer;
width: 20px;
height: 16px; }
.menu-icon.dark::after {
content: '';
position: absolute;
display: block;
width: 100%;
height: 2px;
background: #0a0a0a;
top: 0;
left: 0;
box-shadow: 0 7px 0 #0a0a0a, 0 14px 0 #0a0a0a; }
.menu-icon.dark:hover::after {
background: #8a8a8a;
box-shadow: 0 7px 0 #8a8a8a, 0 14px 0 #8a8a8a; }
.slide-in-down.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateY(-100%);
-ms-transform: translateY(-100%);
transform: translateY(-100%);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-in-down.mui-enter.mui-enter-active {
-webkit-transform: translateY(0);
-ms-transform: translateY(0);
transform: translateY(0); }
.slide-in-left.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateX(-100%);
-ms-transform: translateX(-100%);
transform: translateX(-100%);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-in-left.mui-enter.mui-enter-active {
-webkit-transform: translateX(0);
-ms-transform: translateX(0);
transform: translateX(0); }
.slide-in-up.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateY(100%);
-ms-transform: translateY(100%);
transform: translateY(100%);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-in-up.mui-enter.mui-enter-active {
-webkit-transform: translateY(0);
-ms-transform: translateY(0);
transform: translateY(0); }
.slide-in-right.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateX(100%);
-ms-transform: translateX(100%);
transform: translateX(100%);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-in-right.mui-enter.mui-enter-active {
-webkit-transform: translateX(0);
-ms-transform: translateX(0);
transform: translateX(0); }
.slide-out-down.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateY(0);
-ms-transform: translateY(0);
transform: translateY(0);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-out-down.mui-leave.mui-leave-active {
-webkit-transform: translateY(100%);
-ms-transform: translateY(100%);
transform: translateY(100%); }
.slide-out-right.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateX(0);
-ms-transform: translateX(0);
transform: translateX(0);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-out-right.mui-leave.mui-leave-active {
-webkit-transform: translateX(100%);
-ms-transform: translateX(100%);
transform: translateX(100%); }
.slide-out-up.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateY(0);
-ms-transform: translateY(0);
transform: translateY(0);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-out-up.mui-leave.mui-leave-active {
-webkit-transform: translateY(-100%);
-ms-transform: translateY(-100%);
transform: translateY(-100%); }
.slide-out-left.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: translateX(0);
-ms-transform: translateX(0);
transform: translateX(0);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
-webkit-backface-visibility: hidden;
backface-visibility: hidden; }
.slide-out-left.mui-leave.mui-leave-active {
-webkit-transform: translateX(-100%);
-ms-transform: translateX(-100%);
transform: translateX(-100%); }
.fade-in.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
opacity: 0;
transition-property: opacity; }
.fade-in.mui-enter.mui-enter-active {
opacity: 1; }
.fade-out.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
opacity: 1;
transition-property: opacity; }
.fade-out.mui-leave.mui-leave-active {
opacity: 0; }
.hinge-in-from-top.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotateX(-90deg);
transform: perspective(2000px) rotateX(-90deg);
-webkit-transform-origin: top;
-ms-transform-origin: top;
transform-origin: top;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.hinge-in-from-top.mui-enter.mui-enter-active {
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
opacity: 1; }
.hinge-in-from-right.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotateY(-90deg);
transform: perspective(2000px) rotateY(-90deg);
-webkit-transform-origin: right;
-ms-transform-origin: right;
transform-origin: right;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.hinge-in-from-right.mui-enter.mui-enter-active {
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
opacity: 1; }
.hinge-in-from-bottom.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotateX(90deg);
transform: perspective(2000px) rotateX(90deg);
-webkit-transform-origin: bottom;
-ms-transform-origin: bottom;
transform-origin: bottom;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.hinge-in-from-bottom.mui-enter.mui-enter-active {
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
opacity: 1; }
.hinge-in-from-left.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotateY(90deg);
transform: perspective(2000px) rotateY(90deg);
-webkit-transform-origin: left;
-ms-transform-origin: left;
transform-origin: left;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.hinge-in-from-left.mui-enter.mui-enter-active {
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
opacity: 1; }
.hinge-in-from-middle-x.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotateX(-90deg);
transform: perspective(2000px) rotateX(-90deg);
-webkit-transform-origin: center;
-ms-transform-origin: center;
transform-origin: center;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.hinge-in-from-middle-x.mui-enter.mui-enter-active {
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
opacity: 1; }
.hinge-in-from-middle-y.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotateY(-90deg);
transform: perspective(2000px) rotateY(-90deg);
-webkit-transform-origin: center;
-ms-transform-origin: center;
transform-origin: center;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.hinge-in-from-middle-y.mui-enter.mui-enter-active {
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
opacity: 1; }
.hinge-out-from-top.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
-webkit-transform-origin: top;
-ms-transform-origin: top;
transform-origin: top;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.hinge-out-from-top.mui-leave.mui-leave-active {
-webkit-transform: perspective(2000px) rotateX(-90deg);
transform: perspective(2000px) rotateX(-90deg);
opacity: 0; }
.hinge-out-from-right.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
-webkit-transform-origin: right;
-ms-transform-origin: right;
transform-origin: right;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.hinge-out-from-right.mui-leave.mui-leave-active {
-webkit-transform: perspective(2000px) rotateY(-90deg);
transform: perspective(2000px) rotateY(-90deg);
opacity: 0; }
.hinge-out-from-bottom.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
-webkit-transform-origin: bottom;
-ms-transform-origin: bottom;
transform-origin: bottom;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.hinge-out-from-bottom.mui-leave.mui-leave-active {
-webkit-transform: perspective(2000px) rotateX(90deg);
transform: perspective(2000px) rotateX(90deg);
opacity: 0; }
.hinge-out-from-left.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
-webkit-transform-origin: left;
-ms-transform-origin: left;
transform-origin: left;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.hinge-out-from-left.mui-leave.mui-leave-active {
-webkit-transform: perspective(2000px) rotateY(90deg);
transform: perspective(2000px) rotateY(90deg);
opacity: 0; }
.hinge-out-from-middle-x.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
-webkit-transform-origin: center;
-ms-transform-origin: center;
transform-origin: center;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.hinge-out-from-middle-x.mui-leave.mui-leave-active {
-webkit-transform: perspective(2000px) rotateX(-90deg);
transform: perspective(2000px) rotateX(-90deg);
opacity: 0; }
.hinge-out-from-middle-y.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: perspective(2000px) rotate(0deg);
transform: perspective(2000px) rotate(0deg);
-webkit-transform-origin: center;
-ms-transform-origin: center;
transform-origin: center;
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.hinge-out-from-middle-y.mui-leave.mui-leave-active {
-webkit-transform: perspective(2000px) rotateY(-90deg);
transform: perspective(2000px) rotateY(-90deg);
opacity: 0; }
.scale-in-up.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: scale(0.5);
-ms-transform: scale(0.5);
transform: scale(0.5);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.scale-in-up.mui-enter.mui-enter-active {
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
opacity: 1; }
.scale-in-down.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: scale(1.5);
-ms-transform: scale(1.5);
transform: scale(1.5);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.scale-in-down.mui-enter.mui-enter-active {
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
opacity: 1; }
.scale-out-up.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.scale-out-up.mui-leave.mui-leave-active {
-webkit-transform: scale(1.5);
-ms-transform: scale(1.5);
transform: scale(1.5);
opacity: 0; }
.scale-out-down.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.scale-out-down.mui-leave.mui-leave-active {
-webkit-transform: scale(0.5);
-ms-transform: scale(0.5);
transform: scale(0.5);
opacity: 0; }
.spin-in.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: rotate(-0.75turn);
-ms-transform: rotate(-0.75turn);
transform: rotate(-0.75turn);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.spin-in.mui-enter.mui-enter-active {
-webkit-transform: rotate(0);
-ms-transform: rotate(0);
transform: rotate(0);
opacity: 1; }
.spin-out.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: rotate(0);
-ms-transform: rotate(0);
transform: rotate(0);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.spin-out.mui-leave.mui-leave-active {
-webkit-transform: rotate(0.75turn);
-ms-transform: rotate(0.75turn);
transform: rotate(0.75turn);
opacity: 0; }
.spin-in-ccw.mui-enter {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: rotate(0.75turn);
-ms-transform: rotate(0.75turn);
transform: rotate(0.75turn);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 0; }
.spin-in-ccw.mui-enter.mui-enter-active {
-webkit-transform: rotate(0);
-ms-transform: rotate(0);
transform: rotate(0);
opacity: 1; }
.spin-out-ccw.mui-leave {
transition-duration: 500ms;
transition-timing-function: linear;
-webkit-transform: rotate(0);
-ms-transform: rotate(0);
transform: rotate(0);
transition-property: -webkit-transform, opacity;
transition-property: transform, opacity;
opacity: 1; }
.spin-out-ccw.mui-leave.mui-leave-active {
-webkit-transform: rotate(-0.75turn);
-ms-transform: rotate(-0.75turn);
transform: rotate(-0.75turn);
opacity: 0; }
.slow {
transition-duration: 750ms !important; }
.fast {
transition-duration: 250ms !important; }
.linear {
transition-timing-function: linear !important; }
.ease {
transition-timing-function: ease !important; }
.ease-in {
transition-timing-function: ease-in !important; }
.ease-out {
transition-timing-function: ease-out !important; }
.ease-in-out {
transition-timing-function: ease-in-out !important; }
.bounce-in {
transition-timing-function: cubic-bezier(0.485, 0.155, 0.24, 1.245) !important; }
.bounce-out {
transition-timing-function: cubic-bezier(0.485, 0.155, 0.515, 0.845) !important; }
.bounce-in-out {
transition-timing-function: cubic-bezier(0.76, -0.245, 0.24, 1.245) !important; }
.short-delay {
transition-delay: 300ms !important; }
.long-delay {
transition-delay: 700ms !important; }
.shake {
-webkit-animation-name: shake-7;
animation-name: shake-7; }
@-webkit-keyframes shake-7 {
0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% {
-webkit-transform: translateX(7%);
transform: translateX(7%); }
5%, 15%, 25%, 35%, 45%, 55%, 65%, 75%, 85%, 95% {
-webkit-transform: translateX(-7%);
transform: translateX(-7%); } }
@keyframes shake-7 {
0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% {
-webkit-transform: translateX(7%);
transform: translateX(7%); }
5%, 15%, 25%, 35%, 45%, 55%, 65%, 75%, 85%, 95% {
-webkit-transform: translateX(-7%);
transform: translateX(-7%); } }
.spin-cw {
-webkit-animation-name: spin-cw-1turn;
animation-name: spin-cw-1turn; }
@-webkit-keyframes spin-cw-1turn {
0% {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn); }
100% {
-webkit-transform: rotate(0);
transform: rotate(0); } }
@keyframes spin-cw-1turn {
0% {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn); }
100% {
-webkit-transform: rotate(0);
transform: rotate(0); } }
.spin-ccw {
-webkit-animation-name: spin-cw-1turn;
animation-name: spin-cw-1turn; }
@keyframes spin-cw-1turn {
0% {
-webkit-transform: rotate(0);
transform: rotate(0); }
100% {
-webkit-transform: rotate(1turn);
transform: rotate(1turn); } }
.wiggle {
-webkit-animation-name: wiggle-7deg;
animation-name: wiggle-7deg; }
@-webkit-keyframes wiggle-7deg {
40%, 50%, 60% {
-webkit-transform: rotate(7deg);
transform: rotate(7deg); }
35%, 45%, 55%, 65% {
-webkit-transform: rotate(-7deg);
transform: rotate(-7deg); }
0%, 30%, 70%, 100% {
-webkit-transform: rotate(0);
transform: rotate(0); } }
@keyframes wiggle-7deg {
40%, 50%, 60% {
-webkit-transform: rotate(7deg);
transform: rotate(7deg); }
35%, 45%, 55%, 65% {
-webkit-transform: rotate(-7deg);
transform: rotate(-7deg); }
0%, 30%, 70%, 100% {
-webkit-transform: rotate(0);
transform: rotate(0); } }
.shake,
.spin-cw,
.spin-ccw,
.wiggle {
-webkit-animation-duration: 500ms;
animation-duration: 500ms; }
.infinite {
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite; }
.slow {
-webkit-animation-duration: 750ms !important;
animation-duration: 750ms !important; }
.fast {
-webkit-animation-duration: 250ms !important;
animation-duration: 250ms !important; }
.linear {
-webkit-animation-timing-function: linear !important;
animation-timing-function: linear !important; }
.ease {
-webkit-animation-timing-function: ease !important;
animation-timing-function: ease !important; }
.ease-in {
-webkit-animation-timing-function: ease-in !important;
animation-timing-function: ease-in !important; }
.ease-out {
-webkit-animation-timing-function: ease-out !important;
animation-timing-function: ease-out !important; }
.ease-in-out {
-webkit-animation-timing-function: ease-in-out !important;
animation-timing-function: ease-in-out !important; }
.bounce-in {
-webkit-animation-timing-function: cubic-bezier(0.485, 0.155, 0.24, 1.245) !important;
animation-timing-function: cubic-bezier(0.485, 0.155, 0.24, 1.245) !important; }
.bounce-out {
-webkit-animation-timing-function: cubic-bezier(0.485, 0.155, 0.515, 0.845) !important;
animation-timing-function: cubic-bezier(0.485, 0.155, 0.515, 0.845) !important; }
.bounce-in-out {
-webkit-animation-timing-function: cubic-bezier(0.76, -0.245, 0.24, 1.245) !important;
animation-timing-function: cubic-bezier(0.76, -0.245, 0.24, 1.245) !important; }
.short-delay {
-webkit-animation-delay: 300ms !important;
animation-delay: 300ms !important; }
.long-delay {
-webkit-animation-delay: 700ms !important;
animation-delay: 700ms !important; }
| FabMo/FabMo-Engine | dashboard/static/css/foundation.css | CSS | apache-2.0 | 109,631 |
using System.Collections.Generic;
using System.Net.Http;
using InstaSharp.Extensions;
using InstaSharp.Models.Responses;
using System.Threading.Tasks;
namespace InstaSharp.Endpoints
{
/// <summary>
/// Comments Endpoint
/// </summary>
public class Comments : InstagramApi
{
/// <summary>
/// Comments Endpoints
/// </summary>
/// <param name="config">An instance of the InstagramConfig class.</param>
public Comments(InstagramConfig config)
: this(config, null)
{
}
/// <summary>
/// Comments Endpoints
/// </summary>
/// <param name="config">An instance of the InstagramConfig class.</param>
/// <param name="auth">An instance of the OAuthResponse class.</param>
public Comments(InstagramConfig config, OAuthResponse auth)
: base("media/", config, auth)
{
}
/// <summary>
/// Get a full list of comments on a media.
/// <para>Requires Authentication: False
/// </para>
/// <param>
/// <c>Required Scope: </c>comments
/// </param>
/// </summary>
/// <param name="mediaId">The id of the media on which to retrieve comments.</param>
/// <returns>CommentsResponse</returns>
public Task<CommentsResponse> Get(string mediaId)
{
var request = Request("{id}/comments");
request.AddUrlSegment("id", mediaId);
return Client.ExecuteAsync<CommentsResponse>(request);
}
/// <summary>
/// Create a comment on a media. Please email apidevelopers[at]instagram.com for access.
/// <para>
/// <c>Requires Authentication: </c>True
/// </para>
/// <param>
/// <c>Required Scope: </c>comments
/// </param>
/// </summary>
/// <param name="mediaId">The id of the media on which to post a comment.</param>
/// <param name="comment">Text to post as a comment on the media as specified in media-id.</param>
/// <returns>CommentsResponse</returns>
public Task<CommentResponse> Post(string mediaId, string comment)
{
AssertIsAuthenticated();
var request = Request("{id}/comments", HttpMethod.Post);
request.AddUrlSegment("id", mediaId);
request.Content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("text", comment) });
return Client.ExecuteAsync<CommentResponse>(request);
}
/// <summary>
/// Remove a comment either on the authenticated user's media or authored by the authenticated user.
/// <para>
/// <c>Requires Authentication: </c>True
/// </para>
/// <param>
/// <c>Required Scope: </c>comments
/// </param>
/// </summary>
/// <param name="mediaId">The id of the media from which to delete the comment.</param>
/// <param name="commentId">The id of the comment to delete.</param>
/// <returns>CommentResponse</returns>
public Task<CommentResponse> Delete(string mediaId, string commentId)
{
AssertIsAuthenticated();
var request = Request("{media-id}/comments/{comment-id}", HttpMethod.Delete);
request.AddUrlSegment("media-id", mediaId);
request.AddUrlSegment("comment-id", commentId);
return Client.ExecuteAsync<CommentResponse>(request);
}
}
}
| danielmundim/InstaSharp | src/InstaSharp/Endpoints/Comments.cs | C# | apache-2.0 | 3,563 |
#region License
/*
* Copyright © 2002-2011 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.
*/
#endregion
using System;
using System.Text;
using Spring.Util;
namespace Spring.Objects.Factory.Parsing
{
public class Problem
{
private string _message;
private Location _location;
private Exception _rootCause;
/// <summary>
/// Initializes a new instance of the <see cref="Problem"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="location">The location.</param>
public Problem(string message, Location location)
: this(message, location, null)
{
}
/// <summary>
/// Initializes a new instance of the Problem class.
/// </summary>
/// <param name="message"></param>
/// <param name="location"></param>
/// <param name="rootCause"></param>
public Problem(string message, Location location, Exception rootCause)
{
AssertUtils.ArgumentNotNull(message, "message");
AssertUtils.ArgumentNotNull(location, "resource");
_message = message;
_location = location;
_rootCause = rootCause;
}
public string Message
{
get
{
return _message;
}
}
public Location Location
{
get
{
return _location;
}
}
public string ResourceDescription
{
get { return _location.Resource != null ? _location.Resource.Description : string.Empty; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Configuration problem: ");
sb.Append(Message);
sb.Append("\nOffending resource: ").Append(ResourceDescription);
return sb.ToString();
}
}
}
| spring-projects/spring-net | src/Spring/Spring.Core/Objects/Factory/Parsing/Problem.cs | C# | apache-2.0 | 2,660 |
"use strict";
var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var noteRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = noteRole;
exports.default = _default; | GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/aria-query/lib/etc/roles/literal/noteRole.js | JavaScript | apache-2.0 | 627 |
/*
* Copyright (c) 2002 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2009 CACE Technologies, Inc. Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @(#) $Header: /tcpdump/master/libpcap/pcap-stdinc.h,v 1.10.2.1 2008-10-06 15:38:39 gianluca Exp $ (LBL)
*/
#define SIZEOF_CHAR 1
#define SIZEOF_SHORT 2
#define SIZEOF_INT 4
#ifndef _MSC_EXTENSIONS
#define SIZEOF_LONG_LONG 8
#endif
/*
* Avoids a compiler warning in case this was already defined
* (someone defined _WINSOCKAPI_ when including 'windows.h', in order
* to prevent it from including 'winsock.h')
*/
#ifdef _WINSOCKAPI_
#undef _WINSOCKAPI_
#endif
#include <winsock2.h>
#include <fcntl.h>
#include "bittypes.h"
#include <time.h>
#include <io.h>
#ifndef __MINGW32__
#include "IP6_misc.h"
#endif
#define caddr_t char*
#if _MSC_VER < 1500
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define strdup _strdup
#endif
#define inline __inline
#ifdef __MINGW32__
#include <stdint.h>
#else /*__MINGW32__*/
/* MSVC compiler */
#ifndef _UINTPTR_T_DEFINED
#ifdef _WIN64
typedef unsigned __int64 uintptr_t;
#else
typedef _W64 unsigned int uintptr_t;
#endif
#define _UINTPTR_T_DEFINED
#endif
#ifndef _INTPTR_T_DEFINED
#ifdef _WIN64
typedef __int64 intptr_t;
#else
typedef _W64 int intptr_t;
#endif
#define _INTPTR_T_DEFINED
#endif
#endif /*__MINGW32__*/
| armink/rt-thread | bsp/simulator/pcap/Include/pcap-stdinc.h | C | apache-2.0 | 2,865 |
/*
* Copyright 2000-2014 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.formatter.java;
import com.intellij.formatting.*;
import com.intellij.formatting.alignment.AlignmentStrategy;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.formatter.java.wrap.JavaWrapManager;
import com.intellij.psi.formatter.java.wrap.ReservedWrapsProvider;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.jsp.JspElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
import static com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper.findLastFieldInGroup;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock, ReservedWrapsProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock");
@NotNull protected final CommonCodeStyleSettings mySettings;
@NotNull protected final JavaCodeStyleSettings myJavaSettings;
protected final CommonCodeStyleSettings.IndentOptions myIndentSettings;
private final Indent myIndent;
protected Indent myChildIndent;
protected Alignment myChildAlignment;
protected boolean myUseChildAttributes = false;
@NotNull protected final AlignmentStrategy myAlignmentStrategy;
private boolean myIsAfterClassKeyword = false;
protected Alignment myReservedAlignment;
protected Alignment myReservedAlignment2;
private final JavaWrapManager myWrapManager;
private Map<IElementType, Wrap> myPreferredWraps;
private AbstractJavaBlock myParentBlock;
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
final Alignment alignment,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings)
{
this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, AlignmentStrategy.wrap(alignment));
}
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
@NotNull final AlignmentStrategy alignmentStrategy,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings)
{
this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, alignmentStrategy);
}
private AbstractJavaBlock(@NotNull ASTNode ignored,
@NotNull CommonCodeStyleSettings commonSettings,
@NotNull JavaCodeStyleSettings javaSettings) {
super(ignored, null, null);
mySettings = commonSettings;
myJavaSettings = javaSettings;
myIndentSettings = commonSettings.getIndentOptions();
myIndent = null;
myWrapManager = JavaWrapManager.INSTANCE;
myAlignmentStrategy = AlignmentStrategy.getNullStrategy();
}
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
final JavaWrapManager wrapManager,
@NotNull final AlignmentStrategy alignmentStrategy) {
super(node, wrap, createBlockAlignment(alignmentStrategy, node));
mySettings = settings;
myJavaSettings = javaSettings;
myIndentSettings = settings.getIndentOptions();
myIndent = indent;
myWrapManager = wrapManager;
myAlignmentStrategy = alignmentStrategy;
}
@Nullable
private static Alignment createBlockAlignment(@NotNull AlignmentStrategy strategy, @NotNull ASTNode node) {
// There is a possible case that 'implements' section is incomplete (e.g. ends with comma). We may want to align lbrace
// to the first implemented interface reference then.
if (node.getElementType() == JavaElementType.IMPLEMENTS_LIST) {
return null;
}
return strategy.getAlignment(node.getElementType());
}
@NotNull
public Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
@Nullable Wrap wrap,
Alignment alignment) {
return createJavaBlock(child, settings, javaSettings,indent, wrap, AlignmentStrategy.wrap(alignment));
}
@NotNull
public Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
final Indent indent,
@Nullable Wrap wrap,
@NotNull AlignmentStrategy alignmentStrategy) {
return createJavaBlock(child, settings, javaSettings, indent, wrap, alignmentStrategy, -1);
}
@NotNull
private Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
Wrap wrap,
@NotNull AlignmentStrategy alignmentStrategy,
int startOffset) {
Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)) : indent;
final IElementType elementType = child.getElementType();
Alignment alignment = alignmentStrategy.getAlignment(elementType);
if (child.getPsi() instanceof PsiWhiteSpace) {
String text = child.getText();
int start = CharArrayUtil.shiftForward(text, 0, " \t\n");
int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1;
LOG.assertTrue(start < end);
return new PartialWhitespaceBlock(child, new TextRange(start + child.getStartOffset(), end + child.getStartOffset()),
wrap, alignment, actualIndent, settings, javaSettings);
}
if (child.getPsi() instanceof PsiClass) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
if (isBlockType(elementType)) {
return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
if (isBuildInjectedBlocks() &&
child instanceof PsiComment &&
child instanceof PsiLanguageInjectionHost &&
InjectedLanguageUtil.hasInjections((PsiLanguageInjectionHost)child)) {
return new CommentWithInjectionBlock(child, wrap, alignment, indent, settings, javaSettings);
}
if (child instanceof LeafElement) {
final LeafBlock block = new LeafBlock(child, wrap, alignment, actualIndent);
block.setStartOffset(startOffset);
return block;
}
else if (isLikeExtendsList(elementType)) {
return new ExtendsListBlock(child, wrap, alignmentStrategy, settings, javaSettings);
}
else if (elementType == JavaElementType.CODE_BLOCK) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
else if (elementType == JavaElementType.LABELED_STATEMENT) {
return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
else if (elementType == JavaDocElementType.DOC_COMMENT) {
return new DocCommentBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
else {
final SimpleJavaBlock simpleJavaBlock = new SimpleJavaBlock(child, wrap, alignmentStrategy, actualIndent, settings, javaSettings);
simpleJavaBlock.setStartOffset(startOffset);
return simpleJavaBlock;
}
}
@NotNull
public static Block newJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings) {
final Indent indent = getDefaultSubtreeIndent(child, getJavaIndentOptions(settings));
return newJavaBlock(child, settings, javaSettings, indent, null, AlignmentStrategy.getNullStrategy());
}
@NotNull
public static Block newJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
@Nullable Wrap wrap,
@NotNull AlignmentStrategy strategy) {
return new AbstractJavaBlock(child, settings, javaSettings) {
@Override
protected List<Block> buildChildren() {
return null;
}
}.createJavaBlock(child, settings, javaSettings, indent, wrap, strategy);
}
@NotNull
private static CommonCodeStyleSettings.IndentOptions getJavaIndentOptions(CommonCodeStyleSettings settings) {
CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptions();
assert indentOptions != null : "Java indent options are not initialized";
return indentOptions;
}
private static boolean isLikeExtendsList(final IElementType elementType) {
return elementType == JavaElementType.EXTENDS_LIST
|| elementType == JavaElementType.IMPLEMENTS_LIST
|| elementType == JavaElementType.THROWS_LIST;
}
private static boolean isBlockType(final IElementType elementType) {
return elementType == JavaElementType.SWITCH_STATEMENT
|| elementType == JavaElementType.FOR_STATEMENT
|| elementType == JavaElementType.WHILE_STATEMENT
|| elementType == JavaElementType.DO_WHILE_STATEMENT
|| elementType == JavaElementType.TRY_STATEMENT
|| elementType == JavaElementType.CATCH_SECTION
|| elementType == JavaElementType.IF_STATEMENT
|| elementType == JavaElementType.METHOD
|| elementType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION
|| elementType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER
|| elementType == JavaElementType.CLASS_INITIALIZER
|| elementType == JavaElementType.SYNCHRONIZED_STATEMENT
|| elementType == JavaElementType.FOREACH_STATEMENT;
}
@Nullable
private static Indent getDefaultSubtreeIndent(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) {
final ASTNode parent = child.getTreeParent();
final IElementType childNodeType = child.getElementType();
if (childNodeType == JavaElementType.ANNOTATION) {
if (parent.getPsi() instanceof PsiArrayInitializerMemberValue) {
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
final ASTNode prevElement = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST) {
return Indent.getNoneIndent();
}
if (childNodeType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (childNodeType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1);
if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent();
if (parent != null) {
final Indent defaultChildIndent = getChildIndent(parent, indentOptions);
if (defaultChildIndent != null) return defaultChildIndent;
}
if (child.getTreeParent() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) {
return Indent.getNoneIndent();
}
return null;
}
@Nullable
private static Indent getChildIndent(@NotNull ASTNode parent, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) {
final IElementType parentType = parent.getElementType();
if (parentType == JavaElementType.MODIFIER_LIST) return Indent.getNoneIndent();
if (parentType == JspElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent();
if (parentType == JspElementType.JSP_CLASS_LEVEL_DECLARATION_STATEMENT) return Indent.getNormalIndent();
if (parentType == TokenType.DUMMY_HOLDER) return Indent.getNoneIndent();
if (parentType == JavaElementType.CLASS) return Indent.getNoneIndent();
if (parentType == JavaElementType.IF_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.TRY_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.CATCH_SECTION) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOR_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOREACH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.BLOCK_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.SWITCH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.METHOD) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent();
if (parentType == JavaElementType.IMPORT_LIST) return Indent.getNoneIndent();
if (parentType == JavaElementType.FIELD) return Indent.getContinuationWithoutFirstIndent(indentOptions.USE_RELATIVE_INDENTS);
if (parentType == JavaElementType.EXPRESSION_STATEMENT) return Indent.getNoneIndent();
if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) {
return Indent.getNoneIndent();
}
return null;
}
protected static boolean isRBrace(@NotNull final ASTNode child) {
return child.getElementType() == JavaTokenType.RBRACE;
}
@Nullable
@Override
public Spacing getSpacing(Block child1, @NotNull Block child2) {
return JavaSpacePropertyProcessor.getSpacing(getTreeNode(child2), mySettings, myJavaSettings);
}
@Override
public ASTNode getFirstTreeNode() {
return myNode;
}
@Override
public Indent getIndent() {
return myIndent;
}
protected static boolean isStatement(final ASTNode child, @Nullable final ASTNode parentNode) {
if (parentNode != null) {
final IElementType parentType = parentNode.getElementType();
if (parentType == JavaElementType.CODE_BLOCK) return false;
final int role = ((CompositeElement)parentNode).getChildRole(child);
if (parentType == JavaElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH;
if (parentType == JavaElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY;
}
return false;
}
@Nullable
protected Wrap createChildWrap() {
return myWrapManager.createChildBlockWrap(this, getSettings(), this);
}
@Nullable
protected Alignment createChildAlignment() {
IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION;
if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (myNode.getTreeParent() != null
&& myNode.getTreeParent().getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION
&& myAlignment != null) {
return myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null);
}
if (nodeType == JavaElementType.PARENTH_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null);
}
if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null);
}
if (nodeType == JavaElementType.FOR_STATEMENT) {
return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null);
}
if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
if (nodeType == JavaElementType.THROWS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null);
}
if (nodeType == JavaElementType.PARAMETER_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null);
}
if (nodeType == JavaElementType.RESOURCE_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_RESOURCES, null);
}
if (nodeType == JavaElementType.BINARY_EXPRESSION) {
Alignment defaultAlignment = null;
if (shouldInheritAlignment()) {
defaultAlignment = myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment);
}
if (nodeType == JavaElementType.CLASS || nodeType == JavaElementType.METHOD) {
return null;
}
return null;
}
@Nullable
protected Alignment chooseAlignment(@Nullable Alignment alignment, @Nullable Alignment alignment2, @NotNull ASTNode child) {
if (isTernaryOperatorToken(child)) {
return alignment2;
}
return alignment;
}
private boolean isTernaryOperatorToken(@NotNull final ASTNode child) {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
IElementType childType = child.getElementType();
return childType == JavaTokenType.QUEST || childType ==JavaTokenType.COLON;
}
else {
return false;
}
}
private boolean shouldInheritAlignment() {
if (myNode instanceof PsiPolyadicExpression) {
final ASTNode treeParent = myNode.getTreeParent();
if (treeParent instanceof PsiPolyadicExpression) {
return JavaFormatterUtil.areSamePriorityBinaryExpressions(myNode, treeParent);
}
}
return false;
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, AlignmentStrategy.wrap(defaultAlignment), defaultWrap, childIndent, -1);
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull AlignmentStrategy alignmentStrategy,
@Nullable final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, alignmentStrategy, defaultWrap, childIndent, -1);
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull AlignmentStrategy alignmentStrategy,
final Wrap defaultWrap,
final Indent childIndent,
int childOffset) {
final IElementType childType = child.getElementType();
if (childType == JavaTokenType.CLASS_KEYWORD || childType == JavaTokenType.INTERFACE_KEYWORD) {
myIsAfterClassKeyword = true;
}
if (childType == JavaElementType.METHOD_CALL_EXPRESSION) {
Alignment alignment = shouldAlignChild(child) ? alignmentStrategy.getAlignment(childType) : null;
result.add(createMethodCallExpressionBlock(child, arrangeChildWrap(child, defaultWrap), alignment, childIndent));
}
else {
IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION;
if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.EXPRESSION_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
if (mySettings.PREFER_PARAMETERS_WRAP && !isInsideMethodCall(myNode.getPsi())) {
wrap.ignoreParentWraps();
}
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) {
ASTNode parent = myNode.getTreeParent();
boolean isLambdaParameterList = parent != null && parent.getElementType() == JavaElementType.LAMBDA_EXPRESSION;
Wrap wrapToUse = isLambdaParameterList ? null : getMethodParametersWrap();
WrappingStrategy wrapStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(wrapToUse);
child = processParenthesisBlock(result, child, wrapStrategy, mySettings.ALIGN_MULTILINE_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.RESOURCE_LIST) {
Wrap wrap = Wrap.createWrap(getWrapType(mySettings.RESOURCE_LIST_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_RESOURCES);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) {
Wrap wrap = Wrap.createWrap(getWrapType(myJavaSettings.ANNOTATION_PARAMETER_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
myJavaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) {
child = processParenthesisBlock(result, child,
WrappingStrategy.DO_NOT_WRAP,
mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION);
}
else if (childType == JavaElementType.ENUM_CONSTANT && myNode instanceof ClassElement) {
child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace());
}
else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) {
child = processTernaryOperationRange(result, child, defaultWrap, childIndent);
}
else if (childType == JavaElementType.FIELD) {
child = processField(result, child, alignmentStrategy, defaultWrap, childIndent);
}
else if (childType == JavaElementType.LOCAL_VARIABLE
|| childType == JavaElementType.DECLARATION_STATEMENT
&& (nodeType == JavaElementType.METHOD || nodeType == JavaElementType.CODE_BLOCK))
{
result.add(new SimpleJavaBlock(child, defaultWrap, alignmentStrategy, childIndent, mySettings, myJavaSettings));
}
else {
Alignment alignment = alignmentStrategy.getAlignment(childType);
AlignmentStrategy alignmentStrategyToUse = shouldAlignChild(child)
? AlignmentStrategy.wrap(alignment)
: AlignmentStrategy.getNullStrategy();
if (myAlignmentStrategy.getAlignment(nodeType, childType) != null &&
(nodeType == JavaElementType.IMPLEMENTS_LIST || nodeType == JavaElementType.CLASS)) {
alignmentStrategyToUse = myAlignmentStrategy;
}
Wrap wrap = arrangeChildWrap(child, defaultWrap);
Block block = createJavaBlock(child, mySettings, myJavaSettings, childIndent, wrap, alignmentStrategyToUse, childOffset);
if (block instanceof AbstractJavaBlock) {
final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block;
if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION ||
nodeType == JavaElementType.REFERENCE_EXPRESSION && childType == JavaElementType.METHOD_CALL_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap(nodeType), nodeType);
javaBlock.setReservedWrap(getReservedWrap(childType), childType);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
javaBlock.setReservedWrap(defaultWrap, nodeType);
}
}
result.add(block);
}
}
return child;
}
private boolean isInsideMethodCall(@NotNull PsiElement element) {
PsiElement e = element.getParent();
int parentsVisited = 0;
while (e != null && !(e instanceof PsiStatement) && parentsVisited < 5) {
if (e instanceof PsiExpressionList) {
return true;
}
e = e.getParent();
parentsVisited++;
}
return false;
}
@NotNull
private Wrap getMethodParametersWrap() {
Wrap preferredWrap = getModifierListWrap();
if (preferredWrap == null) {
return Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
} else {
return Wrap.createChildWrap(preferredWrap, getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
}
}
@Nullable
private Wrap getModifierListWrap() {
AbstractJavaBlock parentBlock = getParentBlock();
if (parentBlock != null) {
return parentBlock.getReservedWrap(JavaElementType.MODIFIER_LIST);
}
return null;
}
private ASTNode processField(@NotNull final List<Block> result,
ASTNode child,
@NotNull final AlignmentStrategy alignmentStrategy,
final Wrap defaultWrap,
final Indent childIndent) {
ASTNode lastFieldInGroup = findLastFieldInGroup(child);
if (lastFieldInGroup == child) {
result.add(createJavaBlock(child, getSettings(), myJavaSettings, childIndent, arrangeChildWrap(child, defaultWrap), alignmentStrategy));
return child;
}
else {
final ArrayList<Block> localResult = new ArrayList<Block>();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
localResult.add(createJavaBlock(
child, getSettings(), myJavaSettings,
Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS),
arrangeChildWrap(child, defaultWrap),
alignmentStrategy
)
);
}
if (child == lastFieldInGroup) break;
child = child.getTreeNext();
}
if (!localResult.isEmpty()) {
result.add(new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, childIndent, null));
}
return lastFieldInGroup;
}
}
@Nullable
private ASTNode processTernaryOperationRange(@NotNull final List<Block> result,
@NotNull final ASTNode child,
final Wrap defaultWrap,
final Indent childIndent) {
final ArrayList<Block> localResult = new ArrayList<Block>();
final Wrap wrap = arrangeChildWrap(child, defaultWrap);
final Alignment alignment = myReservedAlignment;
final Alignment alignment2 = myReservedAlignment2;
localResult.add(new LeafBlock(child, wrap, chooseAlignment(alignment, alignment2, child), childIndent));
ASTNode current = child.getTreeNext();
while (current != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) {
if (isTernaryOperationSign(current)) break;
current = processChild(localResult, current, chooseAlignment(alignment, alignment2, current), defaultWrap, childIndent);
}
if (current != null) {
current = current.getTreeNext();
}
}
result.add(new SyntheticCodeBlock(localResult, chooseAlignment(alignment, alignment2, child), getSettings(), myJavaSettings, null, wrap));
if (current == null) {
return null;
}
return current.getTreePrev();
}
private boolean isTernaryOperationSign(@NotNull final ASTNode child) {
if (myNode.getElementType() != JavaElementType.CONDITIONAL_EXPRESSION) return false;
final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
@NotNull
private Block createMethodCallExpressionBlock(@NotNull ASTNode node, Wrap blockWrap, Alignment alignment, Indent indent) {
final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>();
collectNodes(nodes, node);
return new ChainMethodCallsBlockBuilder(alignment, blockWrap, indent, mySettings, myJavaSettings).build(nodes);
}
private static void collectNodes(@NotNull List<ASTNode> nodes, @NotNull ASTNode node) {
ASTNode child = node.getFirstChildNode();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
if (child.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION || child.getElementType() ==
JavaElementType
.REFERENCE_EXPRESSION) {
collectNodes(nodes, child);
}
else {
nodes.add(child);
}
}
child = child.getTreeNext();
}
}
private boolean shouldAlignChild(@NotNull final ASTNode child) {
int role = getChildRole(child);
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return true;
}
return false;
}
else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) {
return true;
}
return false;
}
else if (nodeType == JavaElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return true;
}
return false;
}
else if (nodeType == JavaElementType.CLASS) {
if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return true;
if (myIsAfterClassKeyword) return false;
if (role == ChildRole.MODIFIER_LIST) return true;
return false;
}
else if (JavaElementType.FIELD == nodeType) {
return shouldAlignFieldInColumns(child);
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.MODIFIER_LIST) return true;
if (role == ChildRole.TYPE_PARAMETER_LIST) return true;
if (role == ChildRole.TYPE) return true;
if (role == ChildRole.NAME) return true;
if (role == ChildRole.THROWS_LIST && mySettings.ALIGN_THROWS_KEYWORD) return true;
return false;
}
else if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (role == ChildRole.LOPERAND) return true;
if (role == ChildRole.ROPERAND && child.getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION) {
return true;
}
return false;
}
else if (child.getElementType() == JavaTokenType.END_OF_LINE_COMMENT) {
ASTNode previous = child.getTreePrev();
// There is a special case - comment block that is located at the very start of the line. We don't reformat such a blocks,
// hence, no alignment should be applied to them in order to avoid subsequent blocks aligned with the same alignment to
// be located at the left editor edge as well.
CharSequence prevChars;
if (previous != null && previous.getElementType() == TokenType.WHITE_SPACE && (prevChars = previous.getChars()).length() > 0
&& prevChars.charAt(prevChars.length() - 1) == '\n') {
return false;
}
return true;
}
else if (nodeType == JavaElementType.MODIFIER_LIST) {
// There is a possible case that modifier list contains from more than one elements, e.g. 'private final'. It's also possible
// that the list is aligned. We want to apply alignment rule only to the first element then.
ASTNode previous = child.getTreePrev();
if (previous == null || previous.getTreeParent() != myNode) {
return true;
}
return false;
}
else {
return true;
}
}
private static int getChildRole(@NotNull ASTNode child) {
return ((CompositeElement)child.getTreeParent()).getChildRole(child);
}
/**
* Encapsulates alignment retrieval logic for variable declaration use-case assuming that given node is a child node
* of basic variable declaration node.
*
* @param child variable declaration child node which alignment is to be defined
* @return alignment to use for the given node
* @see CodeStyleSettings#ALIGN_GROUP_FIELD_DECLARATIONS
*/
@Nullable
private boolean shouldAlignFieldInColumns(@NotNull ASTNode child) {
// The whole idea of variable declarations alignment is that complete declaration blocks which children are to be aligned hold
// reference to the same AlignmentStrategy object, hence, reuse the same Alignment objects. So, there is no point in checking
// if it's necessary to align sub-blocks if shared strategy is not defined.
if (!mySettings.ALIGN_GROUP_FIELD_DECLARATIONS) {
return false;
}
IElementType childType = child.getElementType();
// We don't want to align subsequent identifiers in single-line declarations like 'int i1, i2, i3'. I.e. only 'i1'
// should be aligned then.
ASTNode previousNode = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (childType == JavaTokenType.IDENTIFIER && (previousNode == null || previousNode.getElementType() == JavaTokenType.COMMA)) {
return false;
}
return true;
}
@Nullable
public static Alignment createAlignment(final boolean alignOption, @Nullable final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(null, defaultAlignment) : defaultAlignment;
}
@Nullable
public static Alignment createAlignment(Alignment base, final boolean alignOption, @Nullable final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(base, defaultAlignment) : defaultAlignment;
}
@Nullable
protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) {
return myWrapManager.arrangeChildWrap(child, myNode, mySettings, myJavaSettings, defaultWrap, this);
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull List<Block> result,
@NotNull ASTNode child,
@NotNull WrappingStrategy wrappingStrategy,
final boolean doAlign) {
myUseChildAttributes = true;
final IElementType from = JavaTokenType.LPARENTH;
final IElementType to = JavaTokenType.RPARENTH;
return processParenthesisBlock(from, to, result, child, wrappingStrategy, doAlign);
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull IElementType from,
@Nullable final IElementType to,
@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull final WrappingStrategy wrappingStrategy,
final boolean doAlign) {
final Indent externalIndent = Indent.getNoneIndent();
final Indent internalIndent = Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS);
final Indent internalIndentEnforcedToChildren = Indent.getIndent(Indent.Type.CONTINUATION, myIndentSettings.USE_RELATIVE_INDENTS, true);
AlignmentStrategy alignmentStrategy = AlignmentStrategy.wrap(createAlignment(doAlign, null), JavaTokenType.COMMA);
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean methodParametersBlock = true;
ASTNode lBracketParent = child.getTreeParent();
if (lBracketParent != null) {
ASTNode methodCandidate = lBracketParent.getTreeParent();
methodParametersBlock = methodCandidate != null && (methodCandidate.getElementType() == JavaElementType.METHOD
|| methodCandidate.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION);
}
Alignment bracketAlignment = methodParametersBlock && mySettings.ALIGN_MULTILINE_METHOD_BRACKETS ? Alignment.createAlignment() : null;
AlignmentStrategy anonymousClassStrategy = doAlign ? alignmentStrategy
: AlignmentStrategy.wrap(Alignment.createAlignment(),
false,
JavaTokenType.NEW_KEYWORD,
JavaElementType.NEW_EXPRESSION,
JavaTokenType.RBRACE);
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean isAfterIncomplete = false;
ASTNode prev = child;
boolean afterAnonymousClass = false;
final boolean enforceIndent = shouldEnforceIndentToChildren();
while (child != null) {
isAfterIncomplete = isAfterIncomplete || child.getElementType() == TokenType.ERROR_ELEMENT ||
child.getElementType() == JavaElementType.EMPTY_EXPRESSION;
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
if (child.getElementType() == from) {
result.add(createJavaBlock(child, mySettings, myJavaSettings, externalIndent, null, bracketAlignment));
}
else if (child.getElementType() == to) {
result.add(createJavaBlock(child, mySettings, myJavaSettings,
isAfterIncomplete && !afterAnonymousClass ? internalIndent : externalIndent,
null,
isAfterIncomplete ? alignmentStrategy.getAlignment(null) : bracketAlignment)
);
return child;
}
else {
final IElementType elementType = child.getElementType();
Indent indentToUse = enforceIndent ? internalIndentEnforcedToChildren : internalIndent;
AlignmentStrategy alignmentStrategyToUse = canUseAnonymousClassAlignment(child) ? anonymousClassStrategy : alignmentStrategy;
processChild(result, child, alignmentStrategyToUse.getAlignment(elementType), wrappingStrategy.getWrap(elementType), indentToUse);
if (to == null) {//process only one statement
return child;
}
}
isAfterIncomplete = false;
if (child.getElementType() != JavaTokenType.COMMA) {
afterAnonymousClass = isAnonymousClass(child);
}
}
prev = child;
child = child.getTreeNext();
}
return prev;
}
private static boolean canUseAnonymousClassAlignment(@NotNull ASTNode child) {
// The general idea is to handle situations like below:
// test(new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// );
// I.e. we want to align subsequent anonymous class argument to the previous one if it's not preceded by another argument
// at the same line, e.g.:
// test("this is a long argument", new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// );
if (!isAnonymousClass(child)) {
return false;
}
for (ASTNode node = child.getTreePrev(); node != null; node = node.getTreePrev()) {
if (node.getElementType() == TokenType.WHITE_SPACE) {
if (StringUtil.countNewLines(node.getChars()) > 0) {
return false;
}
}
else if (node.getElementType() == JavaTokenType.LPARENTH) {
// First method call argument.
return true;
}
else if (node.getElementType() != JavaTokenType.COMMA && !isAnonymousClass(node)) {
return false;
}
}
return true;
}
private boolean shouldEnforceIndentToChildren() {
if (myNode.getElementType() != JavaElementType.EXPRESSION_LIST) {
return false;
}
ASTNode parent = myNode.getTreeParent();
if (parent == null || parent.getElementType() != JavaElementType.METHOD_CALL_EXPRESSION) {
return false;
}
PsiExpression[] arguments = ((PsiExpressionList)myNode.getPsi()).getExpressions();
return JavaFormatterUtil.hasMultilineArguments(arguments) && JavaFormatterUtil.isMultilineExceptArguments(arguments);
}
private static boolean isAnonymousClass(@Nullable ASTNode node) {
if (node == null || node.getElementType() != JavaElementType.NEW_EXPRESSION) {
return false;
}
ASTNode lastChild = node.getLastChildNode();
return lastChild != null && lastChild.getElementType() == JavaElementType.ANONYMOUS_CLASS;
}
@Nullable
private ASTNode processEnumBlock(@NotNull List<Block> result,
@Nullable ASTNode child,
ASTNode last)
{
final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Wrap
.createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true));
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
result.add(createJavaBlock(child, mySettings, myJavaSettings, Indent.getNormalIndent(),
wrappingStrategy.getWrap(child.getElementType()), AlignmentStrategy.getNullStrategy()));
if (child == last) return child;
}
child = child.getTreeNext();
}
return null;
}
private void setChildAlignment(final Alignment alignment) {
myChildAlignment = alignment;
}
private void setChildIndent(final Indent internalIndent) {
myChildIndent = internalIndent;
}
@Nullable
private static Alignment createAlignmentOrDefault(@Nullable Alignment base, @Nullable final Alignment defaultAlignment) {
if (defaultAlignment == null) {
return base == null ? Alignment.createAlignment() : Alignment.createChildAlignment(base);
}
return defaultAlignment;
}
private int getBraceStyle() {
final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode);
if (psiNode instanceof PsiClass) {
return mySettings.CLASS_BRACE_STYLE;
}
if (psiNode instanceof PsiMethod
|| psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
return mySettings.BRACE_STYLE;
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) {
return getCodeBlockInternalIndent(baseChildrenIndent, false);
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent, boolean enforceParentIndent) {
if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) {
return Indent.getNoneIndent();
}
final int braceStyle = getBraceStyle();
return braceStyle == CommonCodeStyleSettings.NEXT_LINE_SHIFTED ?
createNormalIndent(baseChildrenIndent - 1, enforceParentIndent)
: createNormalIndent(baseChildrenIndent, enforceParentIndent);
}
protected static Indent createNormalIndent(final int baseChildrenIndent) {
return createNormalIndent(baseChildrenIndent, false);
}
protected static Indent createNormalIndent(final int baseChildrenIndent, boolean enforceIndentToChildren) {
if (baseChildrenIndent == 1) {
return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren);
}
else if (baseChildrenIndent <= 0) {
return Indent.getNoneIndent();
}
else {
LOG.assertTrue(false);
return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren);
}
}
private boolean isTopLevelClass() {
return myNode.getElementType() == JavaElementType.CLASS &&
SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile;
}
protected Indent getCodeBlockExternalIndent() {
final int braceStyle = getBraceStyle();
if (braceStyle == CommonCodeStyleSettings.END_OF_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE ||
braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
protected Indent getCodeBlockChildExternalIndent(final int newChildIndex) {
final int braceStyle = getBraceStyle();
if (!isAfterCodeBlock(newChildIndex)) {
return Indent.getNormalIndent();
}
if (braceStyle == CommonCodeStyleSettings.NEXT_LINE ||
braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED ||
braceStyle == CommonCodeStyleSettings.END_OF_LINE) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
private boolean isAfterCodeBlock(final int newChildIndex) {
if (newChildIndex == 0) return false;
Block blockBefore = getSubBlocks().get(newChildIndex - 1);
return blockBefore instanceof CodeBlockBlock;
}
/**
* <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing
* is refactored
*
* @param elementType target element type
* @return <code>null</code> all the time
*/
@Nullable
@Override
public Wrap getReservedWrap(IElementType elementType) {
return myPreferredWraps != null ? myPreferredWraps.get(elementType) : null;
}
/**
* Defines contract for associating operation type and particular wrap instance. I.e. given wrap object <b>may</b> be returned
* from subsequent {@link #getReservedWrap(IElementType)} call if given operation type is used as an argument there.
* <p/>
* Default implementation ({@link AbstractJavaBlock#setReservedWrap(Wrap, IElementType)}) does nothing.
* <p/>
* <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing
* is refactored
*
* @param reservedWrap reserved wrap instance
* @param operationType target operation type to associate with the given wrap instance
*/
public void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
if (myPreferredWraps == null) {
myPreferredWraps = ContainerUtil.newHashMap();
}
myPreferredWraps.put(operationType, reservedWrap);
}
@Nullable
protected static ASTNode getTreeNode(final Block child2) {
if (child2 instanceof JavaBlock) {
return ((JavaBlock)child2).getFirstTreeNode();
}
if (child2 instanceof LeafBlock) {
return ((LeafBlock)child2).getTreeNode();
}
return null;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myUseChildAttributes) {
return new ChildAttributes(myChildIndent, myChildAlignment);
}
if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) {
return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment);
}
return super.getChildAttributes(newChildIndex);
}
@Override
@Nullable
protected Indent getChildIndent() {
return getChildIndent(myNode, myIndentSettings);
}
@NotNull
public CommonCodeStyleSettings getSettings() {
return mySettings;
}
protected boolean isAfter(final int newChildIndex, @NotNull final IElementType[] elementTypes) {
if (newChildIndex == 0) return false;
final Block previousBlock = getSubBlocks().get(newChildIndex - 1);
if (!(previousBlock instanceof AbstractBlock)) return false;
final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType();
for (IElementType elementType : elementTypes) {
if (previousElementType == elementType) return true;
}
return false;
}
@Nullable
protected Alignment getUsedAlignment(final int newChildIndex) {
final List<Block> subBlocks = getSubBlocks();
for (int i = 0; i < newChildIndex; i++) {
if (i >= subBlocks.size()) return null;
final Block block = subBlocks.get(i);
final Alignment alignment = block.getAlignment();
if (alignment != null) return alignment;
}
return null;
}
@Override
public boolean isLeaf() {
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
}
@Nullable
protected ASTNode composeCodeBlock(@NotNull final List<Block> result,
ASTNode child,
final Indent indent,
final int childrenIndent,
@Nullable final Wrap childWrap) {
final ArrayList<Block> localResult = new ArrayList<Block>();
processChild(localResult, child, AlignmentStrategy.getNullStrategy(), null, Indent.getNoneIndent());
child = child.getTreeNext();
ChildAlignmentStrategyProvider alignmentStrategyProvider = getStrategyProvider();
while (child != null) {
if (FormatterUtil.containsWhiteSpacesOnly(child)) {
child = child.getTreeNext();
continue;
}
Indent childIndent = getIndentForCodeBlock(child, childrenIndent);
AlignmentStrategy alignmentStrategyToUse = alignmentStrategyProvider.getNextChildStrategy(child);
final boolean isRBrace = isRBrace(child);
child = processChild(localResult, child, alignmentStrategyToUse, childWrap, childIndent);
if (isRBrace) {
result.add(createCodeBlockBlock(localResult, indent, childrenIndent));
return child;
}
if (child != null) {
child = child.getTreeNext();
}
}
result.add(createCodeBlockBlock(localResult, indent, childrenIndent));
return null;
}
private ChildAlignmentStrategyProvider getStrategyProvider() {
if (mySettings.ALIGN_GROUP_FIELD_DECLARATIONS && myNode.getElementType() == JavaElementType.CLASS) {
return new SubsequentFieldAligner(mySettings);
}
ASTNode parent = myNode.getTreeParent();
IElementType parentType = parent != null ? parent.getElementType() : null;
if (mySettings.ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS && parentType == JavaElementType.METHOD) {
return new SubsequentVariablesAligner();
}
return ChildAlignmentStrategyProvider.NULL_STRATEGY_PROVIDER;
}
private Indent getIndentForCodeBlock(ASTNode child, int childrenIndent) {
if (child.getElementType() == JavaElementType.CODE_BLOCK
&& (getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED
|| getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED2))
{
return Indent.getNormalIndent();
}
return isRBrace(child) ? Indent.getNoneIndent() : getCodeBlockInternalIndent(childrenIndent, false);
}
public AbstractJavaBlock getParentBlock() {
return myParentBlock;
}
public void setParentBlock(@NotNull AbstractJavaBlock parentBlock) {
myParentBlock = parentBlock;
}
@NotNull
public SyntheticCodeBlock createCodeBlockBlock(final List<Block> localResult, final Indent indent, final int childrenIndent) {
final SyntheticCodeBlock result = new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, indent, null);
result.setChildAttributes(new ChildAttributes(getCodeBlockInternalIndent(childrenIndent), null));
return result;
}
}
| robovm/robovm-studio | java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java | Java | apache-2.0 | 55,736 |
<!---
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.
-->
The files in this directory are vendored from xxHash git tag v0.8.0
(https://github.com/Cyan4973/xxHash).
Includes https://github.com/Cyan4973/xxHash/pull/502 for Solaris compatibility | cpcloud/arrow | cpp/src/arrow/vendored/xxhash/README.md | Markdown | apache-2.0 | 978 |
<st-primary-sidebar-title class-icon="icon-cog">{{"_MENU_SETTINGS_TITLE_" | translate}}</st-primary-sidebar-title>
| fjsc/sparta | web/src/views/settings/settings_menu.html | HTML | apache-2.0 | 115 |
drop table a;
| lavjain/incubator-hawq | src/test/feature/Ranger/sql/admin/70.sql | SQL | apache-2.0 | 15 |
/*
* 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.presto.sql.relational;
import com.facebook.presto.Session;
import com.facebook.presto.metadata.FunctionKind;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.spi.type.DecimalParseResult;
import com.facebook.presto.spi.type.Decimals;
import com.facebook.presto.spi.type.TimeZoneKey;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.spi.type.TypeSignature;
import com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer;
import com.facebook.presto.sql.tree.ArithmeticBinaryExpression;
import com.facebook.presto.sql.tree.ArithmeticUnaryExpression;
import com.facebook.presto.sql.tree.ArrayConstructor;
import com.facebook.presto.sql.tree.AstVisitor;
import com.facebook.presto.sql.tree.BetweenPredicate;
import com.facebook.presto.sql.tree.BinaryLiteral;
import com.facebook.presto.sql.tree.BooleanLiteral;
import com.facebook.presto.sql.tree.Cast;
import com.facebook.presto.sql.tree.CharLiteral;
import com.facebook.presto.sql.tree.CoalesceExpression;
import com.facebook.presto.sql.tree.ComparisonExpression;
import com.facebook.presto.sql.tree.DecimalLiteral;
import com.facebook.presto.sql.tree.DereferenceExpression;
import com.facebook.presto.sql.tree.DoubleLiteral;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FieldReference;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.GenericLiteral;
import com.facebook.presto.sql.tree.IfExpression;
import com.facebook.presto.sql.tree.InListExpression;
import com.facebook.presto.sql.tree.InPredicate;
import com.facebook.presto.sql.tree.IntervalLiteral;
import com.facebook.presto.sql.tree.IsNotNullPredicate;
import com.facebook.presto.sql.tree.IsNullPredicate;
import com.facebook.presto.sql.tree.LambdaArgumentDeclaration;
import com.facebook.presto.sql.tree.LambdaExpression;
import com.facebook.presto.sql.tree.LikePredicate;
import com.facebook.presto.sql.tree.LogicalBinaryExpression;
import com.facebook.presto.sql.tree.LongLiteral;
import com.facebook.presto.sql.tree.NotExpression;
import com.facebook.presto.sql.tree.NullIfExpression;
import com.facebook.presto.sql.tree.NullLiteral;
import com.facebook.presto.sql.tree.Row;
import com.facebook.presto.sql.tree.SearchedCaseExpression;
import com.facebook.presto.sql.tree.SimpleCaseExpression;
import com.facebook.presto.sql.tree.StringLiteral;
import com.facebook.presto.sql.tree.SubscriptExpression;
import com.facebook.presto.sql.tree.SymbolReference;
import com.facebook.presto.sql.tree.TimeLiteral;
import com.facebook.presto.sql.tree.TimestampLiteral;
import com.facebook.presto.sql.tree.TryExpression;
import com.facebook.presto.sql.tree.WhenClause;
import com.facebook.presto.type.RowType;
import com.facebook.presto.type.RowType.RowField;
import com.facebook.presto.type.UnknownType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.IdentityHashMap;
import java.util.List;
import static com.facebook.presto.metadata.FunctionKind.SCALAR;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.type.CharType.createCharType;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static com.facebook.presto.spi.type.IntegerType.INTEGER;
import static com.facebook.presto.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE;
import static com.facebook.presto.spi.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE;
import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.spi.type.VarcharType.createVarcharType;
import static com.facebook.presto.sql.relational.Expressions.call;
import static com.facebook.presto.sql.relational.Expressions.constant;
import static com.facebook.presto.sql.relational.Expressions.constantNull;
import static com.facebook.presto.sql.relational.Expressions.field;
import static com.facebook.presto.sql.relational.Signatures.arithmeticExpressionSignature;
import static com.facebook.presto.sql.relational.Signatures.arithmeticNegationSignature;
import static com.facebook.presto.sql.relational.Signatures.arrayConstructorSignature;
import static com.facebook.presto.sql.relational.Signatures.betweenSignature;
import static com.facebook.presto.sql.relational.Signatures.castSignature;
import static com.facebook.presto.sql.relational.Signatures.coalesceSignature;
import static com.facebook.presto.sql.relational.Signatures.comparisonExpressionSignature;
import static com.facebook.presto.sql.relational.Signatures.dereferenceSignature;
import static com.facebook.presto.sql.relational.Signatures.likePatternSignature;
import static com.facebook.presto.sql.relational.Signatures.likeSignature;
import static com.facebook.presto.sql.relational.Signatures.logicalExpressionSignature;
import static com.facebook.presto.sql.relational.Signatures.nullIfSignature;
import static com.facebook.presto.sql.relational.Signatures.rowConstructorSignature;
import static com.facebook.presto.sql.relational.Signatures.subscriptSignature;
import static com.facebook.presto.sql.relational.Signatures.switchSignature;
import static com.facebook.presto.sql.relational.Signatures.tryCastSignature;
import static com.facebook.presto.sql.relational.Signatures.whenSignature;
import static com.facebook.presto.type.JsonType.JSON;
import static com.facebook.presto.type.LikePatternType.LIKE_PATTERN;
import static com.facebook.presto.util.DateTimeUtils.parseDayTimeInterval;
import static com.facebook.presto.util.DateTimeUtils.parseTimeWithTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseTimeWithoutTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithoutTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseYearMonthInterval;
import static com.facebook.presto.util.ImmutableCollectors.toImmutableList;
import static com.facebook.presto.util.Types.checkType;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.SliceUtf8.countCodePoints;
import static io.airlift.slice.Slices.utf8Slice;
import static java.util.Objects.requireNonNull;
public final class SqlToRowExpressionTranslator
{
private SqlToRowExpressionTranslator() {}
public static RowExpression translate(
Expression expression,
FunctionKind functionKind,
IdentityHashMap<Expression, Type> types,
FunctionRegistry functionRegistry,
TypeManager typeManager,
Session session,
boolean optimize)
{
RowExpression result = new Visitor(functionKind, types, typeManager, session.getTimeZoneKey()).process(expression, null);
requireNonNull(result, "translated expression is null");
if (optimize) {
ExpressionOptimizer optimizer = new ExpressionOptimizer(functionRegistry, typeManager, session);
return optimizer.optimize(result);
}
return result;
}
private static class Visitor
extends AstVisitor<RowExpression, Void>
{
private final FunctionKind functionKind;
private final IdentityHashMap<Expression, Type> types;
private final TypeManager typeManager;
private final TimeZoneKey timeZoneKey;
private Visitor(FunctionKind functionKind, IdentityHashMap<Expression, Type> types, TypeManager typeManager, TimeZoneKey timeZoneKey)
{
this.functionKind = functionKind;
this.types = types;
this.typeManager = typeManager;
this.timeZoneKey = timeZoneKey;
}
@Override
protected RowExpression visitExpression(Expression node, Void context)
{
throw new UnsupportedOperationException("not yet implemented: expression translator for " + node.getClass().getName());
}
@Override
protected RowExpression visitFieldReference(FieldReference node, Void context)
{
return field(node.getFieldIndex(), types.get(node));
}
@Override
protected RowExpression visitNullLiteral(NullLiteral node, Void context)
{
return constantNull(UnknownType.UNKNOWN);
}
@Override
protected RowExpression visitBooleanLiteral(BooleanLiteral node, Void context)
{
return constant(node.getValue(), BOOLEAN);
}
@Override
protected RowExpression visitLongLiteral(LongLiteral node, Void context)
{
if (node.getValue() >= Integer.MIN_VALUE && node.getValue() <= Integer.MAX_VALUE) {
return constant(node.getValue(), INTEGER);
}
return constant(node.getValue(), BIGINT);
}
@Override
protected RowExpression visitDoubleLiteral(DoubleLiteral node, Void context)
{
return constant(node.getValue(), DOUBLE);
}
@Override
protected RowExpression visitDecimalLiteral(DecimalLiteral node, Void context)
{
DecimalParseResult parseResult = Decimals.parse(node.getValue());
return constant(parseResult.getObject(), parseResult.getType());
}
@Override
protected RowExpression visitStringLiteral(StringLiteral node, Void context)
{
return constant(node.getSlice(), createVarcharType(countCodePoints(node.getSlice())));
}
@Override
protected RowExpression visitCharLiteral(CharLiteral node, Void context)
{
return constant(node.getSlice(), createCharType(node.getValue().length()));
}
@Override
protected RowExpression visitBinaryLiteral(BinaryLiteral node, Void context)
{
return constant(node.getValue(), VARBINARY);
}
@Override
protected RowExpression visitGenericLiteral(GenericLiteral node, Void context)
{
Type type = typeManager.getType(parseTypeSignature(node.getType()));
if (type == null) {
throw new IllegalArgumentException("Unsupported type: " + node.getType());
}
if (JSON.equals(type)) {
return call(
new Signature("json_parse", SCALAR, types.get(node).getTypeSignature(), VARCHAR.getTypeSignature()),
types.get(node),
constant(utf8Slice(node.getValue()), VARCHAR));
}
return call(
castSignature(types.get(node), VARCHAR),
types.get(node),
constant(utf8Slice(node.getValue()), VARCHAR));
}
@Override
protected RowExpression visitTimeLiteral(TimeLiteral node, Void context)
{
long value;
if (types.get(node).equals(TIME_WITH_TIME_ZONE)) {
value = parseTimeWithTimeZone(node.getValue());
}
else {
// parse in time zone of client
value = parseTimeWithoutTimeZone(timeZoneKey, node.getValue());
}
return constant(value, types.get(node));
}
@Override
protected RowExpression visitTimestampLiteral(TimestampLiteral node, Void context)
{
long value;
if (types.get(node).equals(TIMESTAMP_WITH_TIME_ZONE)) {
value = parseTimestampWithTimeZone(timeZoneKey, node.getValue());
}
else {
// parse in time zone of client
value = parseTimestampWithoutTimeZone(timeZoneKey, node.getValue());
}
return constant(value, types.get(node));
}
@Override
protected RowExpression visitIntervalLiteral(IntervalLiteral node, Void context)
{
long value;
if (node.isYearToMonth()) {
value = node.getSign().multiplier() * parseYearMonthInterval(node.getValue(), node.getStartField(), node.getEndField());
}
else {
value = node.getSign().multiplier() * parseDayTimeInterval(node.getValue(), node.getStartField(), node.getEndField());
}
return constant(value, types.get(node));
}
@Override
protected RowExpression visitComparisonExpression(ComparisonExpression node, Void context)
{
RowExpression left = process(node.getLeft(), context);
RowExpression right = process(node.getRight(), context);
return call(
comparisonExpressionSignature(node.getType(), left.getType(), right.getType()),
BOOLEAN,
left,
right);
}
@Override
protected RowExpression visitFunctionCall(FunctionCall node, Void context)
{
List<RowExpression> arguments = node.getArguments().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
List<TypeSignature> argumentTypes = arguments.stream()
.map(RowExpression::getType)
.map(Type::getTypeSignature)
.collect(toImmutableList());
Signature signature = new Signature(node.getName().getSuffix(), functionKind, types.get(node).getTypeSignature(), argumentTypes);
return call(signature, types.get(node), arguments);
}
@Override
protected RowExpression visitSymbolReference(SymbolReference node, Void context)
{
return new VariableReferenceExpression(node.getName(), types.get(node));
}
@Override
protected RowExpression visitLambdaExpression(LambdaExpression node, Void context)
{
RowExpression body = process(node.getBody(), context);
Type type = types.get(node);
List<Type> typeParameters = type.getTypeParameters();
List<Type> argumentTypes = typeParameters.subList(0, typeParameters.size() - 1);
List<String> argumentNames = node.getArguments().stream()
.map(LambdaArgumentDeclaration::getName)
.collect(toImmutableList());
return new LambdaDefinitionExpression(argumentTypes, argumentNames, body);
}
@Override
protected RowExpression visitArithmeticBinary(ArithmeticBinaryExpression node, Void context)
{
RowExpression left = process(node.getLeft(), context);
RowExpression right = process(node.getRight(), context);
return call(
arithmeticExpressionSignature(node.getType(), types.get(node), left.getType(), right.getType()),
types.get(node),
left,
right);
}
@Override
protected RowExpression visitArithmeticUnary(ArithmeticUnaryExpression node, Void context)
{
RowExpression expression = process(node.getValue(), context);
switch (node.getSign()) {
case PLUS:
return expression;
case MINUS:
return call(
arithmeticNegationSignature(types.get(node), expression.getType()),
types.get(node),
expression);
}
throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign());
}
@Override
protected RowExpression visitLogicalBinaryExpression(LogicalBinaryExpression node, Void context)
{
return call(
logicalExpressionSignature(node.getType()),
BOOLEAN,
process(node.getLeft(), context),
process(node.getRight(), context));
}
@Override
protected RowExpression visitCast(Cast node, Void context)
{
RowExpression value = process(node.getExpression(), context);
if (node.isTypeOnly()) {
return changeType(value, types.get(node));
}
if (node.isSafe()) {
return call(tryCastSignature(types.get(node), value.getType()), types.get(node), value);
}
return call(castSignature(types.get(node), value.getType()), types.get(node), value);
}
private static RowExpression changeType(RowExpression value, Type targetType)
{
ChangeTypeVisitor visitor = new ChangeTypeVisitor(targetType);
return value.accept(visitor, null);
}
private static class ChangeTypeVisitor
implements RowExpressionVisitor<Void, RowExpression>
{
private final Type targetType;
private ChangeTypeVisitor(Type targetType)
{
this.targetType = targetType;
}
@Override
public RowExpression visitCall(CallExpression call, Void context)
{
return new CallExpression(call.getSignature(), targetType, call.getArguments());
}
@Override
public RowExpression visitInputReference(InputReferenceExpression reference, Void context)
{
return new InputReferenceExpression(reference.getField(), targetType);
}
@Override
public RowExpression visitConstant(ConstantExpression literal, Void context)
{
return new ConstantExpression(literal.getValue(), targetType);
}
@Override
public RowExpression visitLambda(LambdaDefinitionExpression lambda, Void context)
{
throw new UnsupportedOperationException();
}
@Override
public RowExpression visitVariableReference(VariableReferenceExpression reference, Void context)
{
return new VariableReferenceExpression(reference.getName(), targetType);
}
}
@Override
protected RowExpression visitCoalesceExpression(CoalesceExpression node, Void context)
{
List<RowExpression> arguments = node.getOperands().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
List<Type> argumentTypes = arguments.stream().map(RowExpression::getType).collect(toImmutableList());
return call(coalesceSignature(types.get(node), argumentTypes), types.get(node), arguments);
}
@Override
protected RowExpression visitSimpleCaseExpression(SimpleCaseExpression node, Void context)
{
ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder();
arguments.add(process(node.getOperand(), context));
for (WhenClause clause : node.getWhenClauses()) {
arguments.add(call(whenSignature(types.get(clause)),
types.get(clause),
process(clause.getOperand(), context),
process(clause.getResult(), context)));
}
Type returnType = types.get(node);
arguments.add(node.getDefaultValue()
.map((value) -> process(value, context))
.orElse(constantNull(returnType)));
return call(switchSignature(returnType), returnType, arguments.build());
}
@Override
protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context)
{
/*
Translates an expression like:
case when cond1 then value1
when cond2 then value2
when cond3 then value3
else value4
end
To:
IF(cond1,
value1,
IF(cond2,
value2,
If(cond3,
value3,
value4)))
*/
RowExpression expression = node.getDefaultValue()
.map((value) -> process(value, context))
.orElse(constantNull(types.get(node)));
for (WhenClause clause : Lists.reverse(node.getWhenClauses())) {
expression = call(
Signatures.ifSignature(types.get(node)),
types.get(node),
process(clause.getOperand(), context),
process(clause.getResult(), context),
expression);
}
return expression;
}
@Override
protected RowExpression visitDereferenceExpression(DereferenceExpression node, Void context)
{
RowType rowType = checkType(types.get(node.getBase()), RowType.class, "type");
List<RowField> fields = rowType.getFields();
int index = -1;
for (int i = 0; i < fields.size(); i++) {
RowField field = fields.get(i);
if (field.getName().isPresent() && field.getName().get().equalsIgnoreCase(node.getFieldName())) {
checkArgument(index < 0, "Ambiguous field %s in type %s", field, rowType.getDisplayName());
index = i;
}
}
checkState(index >= 0, "could not find field name: %s", node.getFieldName());
Type returnType = types.get(node);
return call(dereferenceSignature(returnType, rowType), returnType, process(node.getBase(), context), constant(index, INTEGER));
}
@Override
protected RowExpression visitIfExpression(IfExpression node, Void context)
{
ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder();
arguments.add(process(node.getCondition(), context))
.add(process(node.getTrueValue(), context));
if (node.getFalseValue().isPresent()) {
arguments.add(process(node.getFalseValue().get(), context));
}
else {
arguments.add(constantNull(types.get(node)));
}
return call(Signatures.ifSignature(types.get(node)), types.get(node), arguments.build());
}
@Override
protected RowExpression visitTryExpression(TryExpression node, Void context)
{
return call(Signatures.trySignature(types.get(node)), types.get(node), process(node.getInnerExpression(), context));
}
@Override
protected RowExpression visitInPredicate(InPredicate node, Void context)
{
ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder();
arguments.add(process(node.getValue(), context));
InListExpression values = (InListExpression) node.getValueList();
for (Expression value : values.getValues()) {
arguments.add(process(value, context));
}
return call(Signatures.inSignature(), BOOLEAN, arguments.build());
}
@Override
protected RowExpression visitIsNotNullPredicate(IsNotNullPredicate node, Void context)
{
RowExpression expression = process(node.getValue(), context);
return call(
Signatures.notSignature(),
BOOLEAN,
call(Signatures.isNullSignature(expression.getType()), BOOLEAN, ImmutableList.of(expression)));
}
@Override
protected RowExpression visitIsNullPredicate(IsNullPredicate node, Void context)
{
RowExpression expression = process(node.getValue(), context);
return call(Signatures.isNullSignature(expression.getType()), BOOLEAN, expression);
}
@Override
protected RowExpression visitNotExpression(NotExpression node, Void context)
{
return call(Signatures.notSignature(), BOOLEAN, process(node.getValue(), context));
}
@Override
protected RowExpression visitNullIfExpression(NullIfExpression node, Void context)
{
RowExpression first = process(node.getFirst(), context);
RowExpression second = process(node.getSecond(), context);
return call(
nullIfSignature(types.get(node), first.getType(), second.getType()),
types.get(node),
first,
second);
}
@Override
protected RowExpression visitBetweenPredicate(BetweenPredicate node, Void context)
{
RowExpression value = process(node.getValue(), context);
RowExpression min = process(node.getMin(), context);
RowExpression max = process(node.getMax(), context);
return call(
betweenSignature(value.getType(), min.getType(), max.getType()),
BOOLEAN,
value,
min,
max);
}
@Override
protected RowExpression visitLikePredicate(LikePredicate node, Void context)
{
RowExpression value = process(node.getValue(), context);
RowExpression pattern = process(node.getPattern(), context);
if (node.getEscape() != null) {
RowExpression escape = process(node.getEscape(), context);
return call(likeSignature(), BOOLEAN, value, call(likePatternSignature(), LIKE_PATTERN, pattern, escape));
}
return call(likeSignature(), BOOLEAN, value, call(castSignature(LIKE_PATTERN, VARCHAR), LIKE_PATTERN, pattern));
}
@Override
protected RowExpression visitSubscriptExpression(SubscriptExpression node, Void context)
{
RowExpression base = process(node.getBase(), context);
RowExpression index = process(node.getIndex(), context);
return call(
subscriptSignature(types.get(node), base.getType(), index.getType()),
types.get(node),
base,
index);
}
@Override
protected RowExpression visitArrayConstructor(ArrayConstructor node, Void context)
{
List<RowExpression> arguments = node.getValues().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
List<Type> argumentTypes = arguments.stream()
.map(RowExpression::getType)
.collect(toImmutableList());
return call(arrayConstructorSignature(types.get(node), argumentTypes), types.get(node), arguments);
}
@Override
protected RowExpression visitRow(Row node, Void context)
{
List<RowExpression> arguments = node.getItems().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
Type returnType = types.get(node);
List<Type> argumentTypes = node.getItems().stream()
.map(value -> types.get(value))
.collect(toImmutableList());
return call(rowConstructorSignature(returnType, argumentTypes), returnType, arguments);
}
}
}
| marsorp/blog | presto166/presto-main/src/main/java/com/facebook/presto/sql/relational/SqlToRowExpressionTranslator.java | Java | apache-2.0 | 28,699 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>DataTables example - Pipelining data to reduce Ajax calls for paging</title>
<link rel="stylesheet" type="text/css" href="../../media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="../resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../resources/demo.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="../resources/syntax/shCore.js"></script>
<script type="text/javascript" language="javascript" src="../resources/demo.js"></script>
<script type="text/javascript" language="javascript" class="init">
//
// Pipelining function for DataTables. To be used to the `ajax` option of DataTables
//
$.fn.dataTable.pipeline = function ( opts ) {
// Configuration options
var conf = $.extend( {
pages: 5, // number of pages to cache
url: '', // script url
data: null, // function or object with parameters to send to the server
// matching how `ajax.data` works in DataTables
method: 'GET' // Ajax HTTP method
}, opts );
// Private variables for storing the cache
var cacheLower = -1;
var cacheUpper = null;
var cacheLastRequest = null;
var cacheLastJson = null;
return function ( request, drawCallback, settings ) {
var ajax = false;
var requestStart = request.start;
var drawStart = request.start;
var requestLength = request.length;
var requestEnd = requestStart + requestLength;
if ( settings.clearCache ) {
// API requested that the cache be cleared
ajax = true;
settings.clearCache = false;
}
else if ( cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper ) {
// outside cached data - need to make a request
ajax = true;
}
else if ( JSON.stringify( request.order ) !== JSON.stringify( cacheLastRequest.order ) ||
JSON.stringify( request.columns ) !== JSON.stringify( cacheLastRequest.columns ) ||
JSON.stringify( request.search ) !== JSON.stringify( cacheLastRequest.search )
) {
// properties changed (ordering, columns, searching)
ajax = true;
}
// Store the request for checking next time around
cacheLastRequest = $.extend( true, {}, request );
if ( ajax ) {
// Need data from the server
if ( requestStart < cacheLower ) {
requestStart = requestStart - (requestLength*(conf.pages-1));
if ( requestStart < 0 ) {
requestStart = 0;
}
}
cacheLower = requestStart;
cacheUpper = requestStart + (requestLength * conf.pages);
request.start = requestStart;
request.length = requestLength*conf.pages;
// Provide the same `data` options as DataTables.
if ( $.isFunction ( conf.data ) ) {
// As a function it is executed with the data object as an arg
// for manipulation. If an object is returned, it is used as the
// data object to submit
var d = conf.data( request );
if ( d ) {
$.extend( request, d );
}
}
else if ( $.isPlainObject( conf.data ) ) {
// As an object, the data given extends the default
$.extend( request, conf.data );
}
settings.jqXHR = $.ajax( {
"type": conf.method,
"url": conf.url,
"data": request,
"dataType": "json",
"cache": false,
"success": function ( json ) {
cacheLastJson = $.extend(true, {}, json);
if ( cacheLower != drawStart ) {
json.data.splice( 0, drawStart-cacheLower );
}
json.data.splice( requestLength, json.data.length );
drawCallback( json );
}
} );
}
else {
json = $.extend( true, {}, cacheLastJson );
json.draw = request.draw; // Update the echo for each response
json.data.splice( 0, requestStart-cacheLower );
json.data.splice( requestLength, json.data.length );
drawCallback(json);
}
}
};
// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. `table.clearPipeline().draw()`)
$.fn.dataTable.Api.register( 'clearPipeline()', function () {
return this.iterator( 'table', function ( settings ) {
settings.clearCache = true;
} );
} );
//
// DataTables initialisation
//
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": $.fn.dataTable.pipeline( {
url: 'scripts/server_processing.php',
pages: 5 // number of pages to cache
} )
} );
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>DataTables example <span>Pipelining data to reduce Ajax calls for paging</span></h1>
<div class="info">
<p>Sever-side processing can be quite hard on your server, since it makes an Ajax call to the server
for every draw request that is made. On sites with a large number of page views, you could potentially
end up DDoSing your own server with your own applications!</p>
<p>This example shows one technique to reduce the number of Ajax calls that are made to the server by
caching more data than is needed for each draw. This is done by intercepting the Ajax call and routing
it through a data cache control; using the data from the cache if available, and making the Ajax
request if not. This intercept of the Ajax request is performed by giving the <a href=
"//datatables.net/reference/option/ajax"><code class="option" title=
"DataTables initialisation option">ajax<span>DT</span></code></a> option as a function. This function
then performs the logic of deciding if another Ajax call is needed, or if data from the cache can be
used.</p>
<p>Keep in mind that this caching is for paging only; the pipeline must be cleared for other
interactions such as ordering and searching since the full data set, when using server-side processing,
is only available at the server.</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this
example:</p><code class="multiline brush: js;">//
// Pipelining function for DataTables. To be used to the `ajax` option of DataTables
//
$.fn.dataTable.pipeline = function ( opts ) {
// Configuration options
var conf = $.extend( {
pages: 5, // number of pages to cache
url: '', // script url
data: null, // function or object with parameters to send to the server
// matching how `ajax.data` works in DataTables
method: 'GET' // Ajax HTTP method
}, opts );
// Private variables for storing the cache
var cacheLower = -1;
var cacheUpper = null;
var cacheLastRequest = null;
var cacheLastJson = null;
return function ( request, drawCallback, settings ) {
var ajax = false;
var requestStart = request.start;
var drawStart = request.start;
var requestLength = request.length;
var requestEnd = requestStart + requestLength;
if ( settings.clearCache ) {
// API requested that the cache be cleared
ajax = true;
settings.clearCache = false;
}
else if ( cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper ) {
// outside cached data - need to make a request
ajax = true;
}
else if ( JSON.stringify( request.order ) !== JSON.stringify( cacheLastRequest.order ) ||
JSON.stringify( request.columns ) !== JSON.stringify( cacheLastRequest.columns ) ||
JSON.stringify( request.search ) !== JSON.stringify( cacheLastRequest.search )
) {
// properties changed (ordering, columns, searching)
ajax = true;
}
// Store the request for checking next time around
cacheLastRequest = $.extend( true, {}, request );
if ( ajax ) {
// Need data from the server
if ( requestStart < cacheLower ) {
requestStart = requestStart - (requestLength*(conf.pages-1));
if ( requestStart < 0 ) {
requestStart = 0;
}
}
cacheLower = requestStart;
cacheUpper = requestStart + (requestLength * conf.pages);
request.start = requestStart;
request.length = requestLength*conf.pages;
// Provide the same `data` options as DataTables.
if ( $.isFunction ( conf.data ) ) {
// As a function it is executed with the data object as an arg
// for manipulation. If an object is returned, it is used as the
// data object to submit
var d = conf.data( request );
if ( d ) {
$.extend( request, d );
}
}
else if ( $.isPlainObject( conf.data ) ) {
// As an object, the data given extends the default
$.extend( request, conf.data );
}
settings.jqXHR = $.ajax( {
"type": conf.method,
"url": conf.url,
"data": request,
"dataType": "json",
"cache": false,
"success": function ( json ) {
cacheLastJson = $.extend(true, {}, json);
if ( cacheLower != drawStart ) {
json.data.splice( 0, drawStart-cacheLower );
}
json.data.splice( requestLength, json.data.length );
drawCallback( json );
}
} );
}
else {
json = $.extend( true, {}, cacheLastJson );
json.draw = request.draw; // Update the echo for each response
json.data.splice( 0, requestStart-cacheLower );
json.data.splice( requestLength, json.data.length );
drawCallback(json);
}
}
};
// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. `table.clearPipeline().draw()`)
$.fn.dataTable.Api.register( 'clearPipeline()', function () {
return this.iterator( 'table', function ( settings ) {
settings.clearCache = true;
} );
} );
//
// DataTables initialisation
//
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": $.fn.dataTable.pipeline( {
url: 'scripts/server_processing.php',
pages: 5 // number of pages to cache
} )
} );
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this
example:</p>
<ul>
<li><a href="../../media/js/jquery.js">../../media/js/jquery.js</a></li>
<li><a href="../../media/js/jquery.dataTables.js">../../media/js/jquery.dataTables.js</a></li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by
DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library
files (below), in order to correctly display the table. The additional CSS used is shown
below:</p><code class="multiline brush: js;"></code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the
table:</p>
<ul>
<li><a href=
"../../media/css/jquery.dataTables.css">../../media/css/jquery.dataTables.css</a></li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data
will update automatically as any additional data is loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note
that this is just an example script using PHP. Server-side processing scripts can be written in any
language, using <a href="//datatables.net/manual/server-side">the protocol described in the
DataTables documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="../basic_init/index.html">Basic initialisation</a></h3>
<ul class="toc">
<li><a href="../basic_init/zero_configuration.html">Zero configuration</a></li>
<li><a href="../basic_init/filter_only.html">Feature enable / disable</a></li>
<li><a href="../basic_init/table_sorting.html">Default ordering (sorting)</a></li>
<li><a href="../basic_init/multi_col_sort.html">Multi-column ordering</a></li>
<li><a href="../basic_init/multiple_tables.html">Multiple tables</a></li>
<li><a href="../basic_init/hidden_columns.html">Hidden columns</a></li>
<li><a href="../basic_init/complex_header.html">Complex headers (rowspan and
colspan)</a></li>
<li><a href="../basic_init/dom.html">DOM positioning</a></li>
<li><a href="../basic_init/flexible_width.html">Flexible table width</a></li>
<li><a href="../basic_init/state_save.html">State saving</a></li>
<li><a href="../basic_init/alt_pagination.html">Alternative pagination</a></li>
<li><a href="../basic_init/scroll_y.html">Scroll - vertical</a></li>
<li><a href="../basic_init/scroll_x.html">Scroll - horizontal</a></li>
<li><a href="../basic_init/scroll_xy.html">Scroll - horizontal and vertical</a></li>
<li><a href="../basic_init/scroll_y_theme.html">Scroll - vertical with jQuery UI
ThemeRoller</a></li>
<li><a href="../basic_init/comma-decimal.html">Language - Comma decimal place</a></li>
<li><a href="../basic_init/language.html">Language options</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../advanced_init/index.html">Advanced initialisation</a></h3>
<ul class="toc">
<li><a href="../advanced_init/events_live.html">DOM / jQuery events</a></li>
<li><a href="../advanced_init/dt_events.html">DataTables events</a></li>
<li><a href="../advanced_init/column_render.html">Column rendering</a></li>
<li><a href="../advanced_init/length_menu.html">Page length options</a></li>
<li><a href="../advanced_init/dom_multiple_elements.html">Multiple table control
elements</a></li>
<li><a href="../advanced_init/complex_header.html">Complex headers (rowspan /
colspan)</a></li>
<li><a href="../advanced_init/html5-data-attributes.html">HTML5 data-* attributes</a></li>
<li><a href="../advanced_init/language_file.html">Language file</a></li>
<li><a href="../advanced_init/defaults.html">Setting defaults</a></li>
<li><a href="../advanced_init/row_callback.html">Row created callback</a></li>
<li><a href="../advanced_init/row_grouping.html">Row grouping</a></li>
<li><a href="../advanced_init/footer_callback.html">Footer callback</a></li>
<li><a href="../advanced_init/dom_toolbar.html">Custom toolbar elements</a></li>
<li><a href="../advanced_init/sort_direction_control.html">Order direction sequence
control</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../styling/index.html">Styling</a></h3>
<ul class="toc">
<li><a href="../styling/display.html">Base style</a></li>
<li><a href="../styling/no-classes.html">Base style - no styling classes</a></li>
<li><a href="../styling/cell-border.html">Base style - cell borders</a></li>
<li><a href="../styling/compact.html">Base style - compact</a></li>
<li><a href="../styling/hover.html">Base style - hover</a></li>
<li><a href="../styling/order-column.html">Base style - order-column</a></li>
<li><a href="../styling/row-border.html">Base style - row borders</a></li>
<li><a href="../styling/stripe.html">Base style - stripe</a></li>
<li><a href="../styling/bootstrap.html">Bootstrap</a></li>
<li><a href="../styling/foundation.html">Foundation</a></li>
<li><a href="../styling/jqueryUI.html">jQuery UI ThemeRoller</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../data_sources/index.html">Data sources</a></h3>
<ul class="toc">
<li><a href="../data_sources/dom.html">HTML (DOM) sourced data</a></li>
<li><a href="../data_sources/ajax.html">Ajax sourced data</a></li>
<li><a href="../data_sources/js_array.html">Javascript sourced data</a></li>
<li><a href="../data_sources/server_side.html">Server-side processing</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../api/index.html">API</a></h3>
<ul class="toc">
<li><a href="../api/add_row.html">Add rows</a></li>
<li><a href="../api/multi_filter.html">Individual column filtering (text inputs)</a></li>
<li><a href="../api/multi_filter_select.html">Individual column filtering (select
inputs)</a></li>
<li><a href="../api/highlight.html">Highlighting rows and columns</a></li>
<li><a href="../api/row_details.html">Child rows (show extra / detailed
information)</a></li>
<li><a href="../api/select_row.html">Row selection (multiple rows)</a></li>
<li><a href="../api/select_single_row.html">Row selection and deletion (single
row)</a></li>
<li><a href="../api/form.html">Form inputs</a></li>
<li><a href="../api/counter_columns.html">Index column</a></li>
<li><a href="../api/show_hide.html">Show / hide columns dynamically</a></li>
<li><a href="../api/api_in_init.html">Using API in callbacks</a></li>
<li><a href="../api/tabs_and_scrolling.html">Scrolling and jQuery UI tabs</a></li>
<li><a href="../api/regex.html">Filtering API (regular expressions)</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../ajax/index.html">Ajax</a></h3>
<ul class="toc">
<li><a href="../ajax/simple.html">Ajax data source (arrays)</a></li>
<li><a href="../ajax/objects.html">Ajax data source (objects)</a></li>
<li><a href="../ajax/deep.html">Nested object data (objects)</a></li>
<li><a href="../ajax/objects_subarrays.html">Nested object data (arrays)</a></li>
<li><a href="../ajax/orthogonal-data.html">Orthogonal data</a></li>
<li><a href="../ajax/null_data_source.html">Generated content for a column</a></li>
<li><a href="../ajax/custom_data_property.html">Custom data source property</a></li>
<li><a href="../ajax/custom_data_flat.html">Flat array data source</a></li>
<li><a href="../ajax/defer_render.html">Deferred rendering for speed</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="./index.html">Server-side</a></h3>
<ul class="toc active">
<li><a href="./simple.html">Server-side processing</a></li>
<li><a href="./custom_vars.html">Custom HTTP variables</a></li>
<li><a href="./post.html">POST data</a></li>
<li><a href="./ids.html">Automatic addition of row ID attributes</a></li>
<li><a href="./object_data.html">Object data source</a></li>
<li><a href="./row_details.html">Row details</a></li>
<li><a href="./select_rows.html">Row selection</a></li>
<li><a href="./jsonp.html">JSONP data source for remote domains</a></li>
<li><a href="./defer_loading.html">Deferred loading of data</a></li>
<li class="active"><a href="./pipeline.html">Pipelining data to reduce Ajax calls for
paging</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../plug-ins/index.html">Plug-ins</a></h3>
<ul class="toc">
<li><a href="../plug-ins/api.html">API plug-in methods</a></li>
<li><a href="../plug-ins/sorting_auto.html">Ordering plug-ins (with type
detection)</a></li>
<li><a href="../plug-ins/sorting_manual.html">Ordering plug-ins (no type
detection)</a></li>
<li><a href="../plug-ins/range_filtering.html">Custom filtering - range search</a></li>
<li><a href="../plug-ins/dom_sort.html">Live DOM ordering</a></li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full
information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and
<a href="http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of
DataTables.</p>
<p class="copyright">DataTables designed and created by <a href=
"http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2014<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | hyokun31/wisekb-management-platform | wisekb-uima-ducc/webserver/root/opensources/DataTables-1.10.1/examples/server_side/pipeline.html | HTML | apache-2.0 | 21,526 |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.CodeAnalysis.PasteTracking
<UseExportProvider>
Public Class PasteTrackingServiceTests
Private Const Project1Name = "Proj1"
Private Const Project2Name = "Proj2"
Private Const Class1Name = "Class1.cs"
Private Const Class2Name = "Class2.cs"
Private Const PastedCode As String = "
public void Main(string[] args)
{
}"
Private Const UnformattedPastedCode As String = "
public void Main(string[] args)
{
}"
Private ReadOnly Property SingleFileCode As XElement =
<Workspace>
<Project Language="C#" CommonReferences="True" AssemblyName="Proj1">
<Document FilePath="Class1.cs">
public class Class1
{
$$
}
</Document>
</Project>
</Workspace>
Private ReadOnly Property MultiFileCode As XElement =
<Workspace>
<Project Language="C#" CommonReferences="True" AssemblyName=<%= Project1Name %>>
<Document FilePath=<%= Class1Name %>>
public class Class1
{
$$
}
</Document>
<Document FilePath=<%= Class2Name %>>
public class Class2
{
public const string Greeting = "Hello";
$$
}
</Document>
</Project>
<Project Language="C#" CommonReferences="True" AssemblyName=<%= Project2Name %>>
<Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath=<%= Class1Name %>/>
</Project>
</Workspace>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_WhenNothingPasted() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterPaste() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterFormattingPaste() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim expectedTextSpan = testState.SendPaste(class1Document, UnformattedPastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterMultiplePastes() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim firstTextSpan = testState.SendPaste(class1Document, PastedCode)
Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode)
Assert.NotEqual(firstTextSpan, expectedTextSpan)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenEdit() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.InsertText(class1Document, "Foo")
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenClose() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenCloseThenOpen() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.OpenDocument(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterPasteThenCloseThenOpenThenPaste() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.OpenDocument(class1Document)
Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasMultipleTextSpan_AfterPasteInMultipleFiles() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class2Document = testState.OpenDocument(Project1Name, Class2Name)
Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode)
Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode)
Assert.NotEqual(expectedClass1TextSpan, expectedClass2TextSpan)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedClass1TextSpan)
Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasSingleTextSpan_AfterPasteInMultipleFilesThenOneClosed() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class2Document = testState.OpenDocument(Project1Name, Class2Name)
testState.SendPaste(class1Document, PastedCode)
Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode)
testState.CloseDocument(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteInMultipleFilesThenAllClosed() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class2Document = testState.OpenDocument(Project1Name, Class2Name)
testState.SendPaste(class1Document, PastedCode)
testState.SendPaste(class2Document, PastedCode)
testState.CloseDocument(class1Document)
testState.CloseDocument(class2Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class2Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPaste() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPasteThenClose() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpanForLinkedFile_AfterPasteThenCloseAll() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.CloseDocument(class1LinkedDocument)
Await testState.AssertMissingPastedTextSpanAsync(class1LinkedDocument)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenLinkedFileEdited() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.InsertText(class1LinkedDocument, "Foo")
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1LinkedDocument)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpanForLinkedFile_AfterPasteThenCloseAllThenOpenThenPaste() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.CloseDocument(class1LinkedDocument)
Await testState.AssertMissingPastedTextSpanAsync(class1LinkedDocument)
testState.OpenDocument(class1LinkedDocument)
Dim expectedTextSpan = testState.SendPaste(class1LinkedDocument, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedTextSpan)
End Using
End Function
End Class
End Namespace
| DustinCampbell/roslyn | src/EditorFeatures/Test2/PasteTracking/PasteTrackingServiceTests.vb | Visual Basic | apache-2.0 | 13,236 |
/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "RPC/OpaqueServerRPC.h"
#include "RPC/Server.h"
#include "RPC/ServerRPC.h"
#include "RPC/ThreadDispatchService.h"
namespace LogCabin {
namespace RPC {
////////// Server::RPCHandler //////////
Server::RPCHandler::RPCHandler(Server& server)
: server(server)
{
}
Server::RPCHandler::~RPCHandler()
{
}
void
Server::RPCHandler::handleRPC(OpaqueServerRPC opaqueRPC)
{
ServerRPC rpc(std::move(opaqueRPC));
if (!rpc.needsReply()) {
// The RPC may have had an invalid header, in which case it needs no
// further action.
return;
}
std::shared_ptr<Service> service;
{
std::lock_guard<std::mutex> lockGuard(server.mutex);
auto it = server.services.find(rpc.getService());
if (it != server.services.end())
service = it->second;
}
if (service)
service->handleRPC(std::move(rpc));
else
rpc.rejectInvalidService();
}
////////// Server //////////
Server::Server(Event::Loop& eventLoop, uint32_t maxMessageLength)
: mutex()
, services()
, rpcHandler(*this)
, opaqueServer(rpcHandler, eventLoop, maxMessageLength)
{
}
Server::~Server()
{
}
std::string
Server::bind(const Address& listenAddress)
{
return opaqueServer.bind(listenAddress);
}
void
Server::registerService(uint16_t serviceId,
std::shared_ptr<Service> service,
uint32_t maxThreads)
{
std::lock_guard<std::mutex> lockGuard(mutex);
services[serviceId] =
std::make_shared<ThreadDispatchService>(service, 0, maxThreads);
}
} // namespace LogCabin::RPC
} // namespace LogCabin
| Ghatage/peloton | third_party/logcabin/RPC/Server.cc | C++ | apache-2.0 | 2,408 |
#region License
/*
* Copyright 2002-2010 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.
*/
#endregion
using System;
using Spring.Core.TypeResolution;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;
using Spring.Util;
using TIBCO.EMS;
using Common.Logging;
namespace Spring.Messaging.Ems.Jndi
{
public class JndiLookupFactoryObject : JndiObjectLocator, IConfigurableFactoryObject
{
static JndiLookupFactoryObject()
{
TypeRegistry.RegisterType("LookupContext", typeof(LookupContext));
TypeRegistry.RegisterType("JndiContextType", typeof(JndiContextType));
}
private object defaultObject;
private Object jndiObject;
private IObjectDefinition productTemplate;
public JndiLookupFactoryObject()
{
this.logger = LogManager.GetLogger(GetType());
}
/// <summary>
/// Sets the default object to fall back to if the JNDI lookup fails.
/// Default is none.
/// </summary>
/// <remarks>
/// <para>This can be an arbitrary bean reference or literal value.
/// It is typically used for literal values in scenarios where the JNDI environment
/// might define specific config settings but those are not required to be present.
/// </para>
/// </remarks>
/// <value>The default object to use when lookup fails.</value>
public object DefaultObject
{
set { defaultObject = value; }
}
#region Implementation of IFactoryObject
/// <summary>
/// Return the Jndi object
/// </summary>
/// <returns>The Jndi object</returns>
public object GetObject()
{
return this.jndiObject;
}
/// <summary>
/// Return type of object retrieved from Jndi or the expected type if the Jndi retrieval
/// did not succeed.
/// </summary>
/// <value>Return value of retrieved object</value>
public Type ObjectType
{
get
{
if (this.jndiObject != null)
{
return this.jndiObject.GetType();
}
return ExpectedType;
}
}
/// <summary>
/// Returns true
/// </summary>
public bool IsSingleton
{
get { return true; }
}
#endregion
public override void AfterPropertiesSet()
{
base.AfterPropertiesSet();
TypeRegistry.RegisterType("LookupContext", typeof(LookupContext));
if (this.defaultObject != null && ExpectedType != null &&
!ObjectUtils.IsAssignable(ExpectedType, this.defaultObject))
{
throw new ArgumentException("Default object [" + this.defaultObject +
"] of type [" + this.defaultObject.GetType().Name +
"] is not of expected type [" + ExpectedType.Name + "]");
}
// Locate specified JNDI object.
this.jndiObject = LookupWithFallback();
}
protected virtual object LookupWithFallback()
{
try
{
return Lookup();
}
catch (TypeMismatchNamingException)
{
// Always let TypeMismatchNamingException through -
// we don't want to fall back to the defaultObject in this case.
throw;
}
catch (NamingException ex)
{
if (this.defaultObject != null)
{
if (logger.IsDebugEnabled)
{
logger.Debug("JNDI lookup failed - returning specified default object instead", ex);
}
else if (logger.IsInfoEnabled)
{
logger.Info("JNDI lookup failed - returning specified default object instead: " + ex);
}
return this.defaultObject;
}
throw;
}
}
/// <summary>
/// Gets the template object definition that should be used
/// to configure the instance of the object managed by this factory.
/// </summary>
/// <value></value>
public IObjectDefinition ProductTemplate
{
get { return productTemplate; }
set { productTemplate = value; }
}
}
} | dreamofei/spring-net | src/Spring/Spring.Messaging.Ems/Messaging/Ems/Jndi/JndiLookupFactoryObject.cs | C# | apache-2.0 | 5,343 |
package Mojo::URL;
use Mojo::Base -base;
use overload bool => sub {1}, '""' => sub { shift->to_string }, fallback => 1;
use Mojo::Parameters;
use Mojo::Path;
use Mojo::Util
qw(decode encode punycode_decode punycode_encode url_escape url_unescape);
has base => sub { Mojo::URL->new };
has [qw(fragment host port scheme userinfo)];
sub clone {
my $self = shift;
my $clone = $self->new;
@$clone{keys %$self} = values %$self;
$clone->{$_} && ($clone->{$_} = $clone->{$_}->clone) for qw(base path query);
return $clone;
}
sub host_port {
my ($self, $host_port) = @_;
if (defined $host_port) {
$self->port($1) if $host_port =~ s/:(\d+)$//;
my $host = url_unescape $host_port;
return $host =~ /[^\x00-\x7f]/ ? $self->ihost($host) : $self->host($host);
}
return undef unless defined(my $host = $self->ihost);
return $host unless defined(my $port = $self->port);
return "$host:$port";
}
sub ihost {
my $self = shift;
# Decode
return $self->host(join '.',
map { /^xn--(.+)$/ ? punycode_decode $1 : $_ } split(/\./, shift, -1))
if @_;
# Check if host needs to be encoded
return undef unless defined(my $host = $self->host);
return $host unless $host =~ /[^\x00-\x7f]/;
# Encode
return join '.',
map { /[^\x00-\x7f]/ ? ('xn--' . punycode_encode $_) : $_ }
split(/\./, $host, -1);
}
sub is_abs { !!shift->scheme }
sub new { @_ > 1 ? shift->SUPER::new->parse(@_) : shift->SUPER::new }
sub parse {
my ($self, $url) = @_;
# Official regex from RFC 3986
$url =~ m!^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?!;
$self->scheme($2) if defined $2;
$self->path($5) if defined $5;
$self->query($7) if defined $7;
$self->fragment(_decode(url_unescape $9)) if defined $9;
if (defined(my $auth = $4)) {
$self->userinfo(_decode(url_unescape $1)) if $auth =~ s/^([^\@]+)\@//;
$self->host_port($auth);
}
return $self;
}
sub password { (shift->userinfo // '') =~ /:(.*)$/ ? $1 : undef }
sub path {
my $self = shift;
# Old path
$self->{path} ||= Mojo::Path->new;
return $self->{path} unless @_;
# New path
$self->{path} = ref $_[0] ? $_[0] : $self->{path}->merge($_[0]);
return $self;
}
sub path_query {
my ($self, $pq) = @_;
if (defined $pq) {
return $self unless $pq =~ /^([^?#]*)(?:\?([^#]*))?/;
return defined $2 ? $self->path($1)->query($2) : $self->path($1);
}
my $query = $self->query->to_string;
return $self->path->to_string . (length $query ? "?$query" : '');
}
sub protocol { lc(shift->scheme // '') }
sub query {
my $self = shift;
# Old parameters
my $q = $self->{query} ||= Mojo::Parameters->new;
return $q unless @_;
# Replace with list
if (@_ > 1) { $q->pairs([])->parse(@_) }
# Merge with hash
elsif (ref $_[0] eq 'HASH') { $q->merge(%{$_[0]}) }
# Append array
elsif (ref $_[0] eq 'ARRAY') { $q->append(@{$_[0]}) }
# New parameters
else { $self->{query} = ref $_[0] ? $_[0] : $q->parse($_[0]) }
return $self;
}
sub to_abs {
my $self = shift;
my $abs = $self->clone;
return $abs if $abs->is_abs;
# Scheme
my $base = shift || $abs->base;
$abs->base($base)->scheme($base->scheme);
# Authority
return $abs if $abs->host;
$abs->userinfo($base->userinfo)->host($base->host)->port($base->port);
# Absolute path
my $path = $abs->path;
return $abs if $path->leading_slash;
# Inherit path
if (!@{$path->parts}) {
$abs->path($base->path->clone->canonicalize);
# Query
$abs->query($base->query->clone) unless length $abs->query->to_string;
}
# Merge paths
else { $abs->path($base->path->clone->merge($path)->canonicalize) }
return $abs;
}
sub to_string { shift->_string(0) }
sub to_unsafe_string { shift->_string(1) }
sub username { (shift->userinfo // '') =~ /^([^:]+)/ ? $1 : undef }
sub _decode { decode('UTF-8', $_[0]) // $_[0] }
sub _encode { url_escape encode('UTF-8', $_[0]), $_[1] }
sub _string {
my ($self, $unsafe) = @_;
# Scheme
my $url = '';
if (my $proto = $self->protocol) { $url .= "$proto:" }
# Authority
my $auth = $self->host_port;
$auth = _encode($auth, '^A-Za-z0-9\-._~!$&\'()*+,;=:\[\]') if defined $auth;
if ($unsafe && defined(my $info = $self->userinfo)) {
$auth = _encode($info, '^A-Za-z0-9\-._~!$&\'()*+,;=:') . '@' . $auth;
}
$url .= "//$auth" if defined $auth;
# Path and query
my $path = $self->path_query;
$url .= !$auth || !length $path || $path =~ m!^[/?]! ? $path : "/$path";
# Fragment
return $url unless defined(my $fragment = $self->fragment);
return $url . '#' . _encode($fragment, '^A-Za-z0-9\-._~!$&\'()*+,;=:@/?');
}
1;
=encoding utf8
=head1 NAME
Mojo::URL - Uniform Resource Locator
=head1 SYNOPSIS
use Mojo::URL;
# Parse
my $url = Mojo::URL->new('http://sri:foo@example.com:3000/foo?foo=bar#23');
say $url->scheme;
say $url->userinfo;
say $url->host;
say $url->port;
say $url->path;
say $url->query;
say $url->fragment;
# Build
my $url = Mojo::URL->new;
$url->scheme('http');
$url->host('example.com');
$url->port(3000);
$url->path('/foo/bar');
$url->query(foo => 'bar');
$url->fragment(23);
say "$url";
=head1 DESCRIPTION
L<Mojo::URL> implements a subset of
L<RFC 3986|http://tools.ietf.org/html/rfc3986>,
L<RFC 3987|http://tools.ietf.org/html/rfc3987> and the
L<URL Living Standard|https://url.spec.whatwg.org> for Uniform Resource
Locators with support for IDNA and IRIs.
=head1 ATTRIBUTES
L<Mojo::URL> implements the following attributes.
=head2 base
my $base = $url->base;
$url = $url->base(Mojo::URL->new);
Base of this URL, defaults to a L<Mojo::URL> object.
"http://example.com/a/b?c"
Mojo::URL->new("/a/b?c")->base(Mojo::URL->new("http://example.com"))->to_abs;
=head2 fragment
my $fragment = $url->fragment;
$url = $url->fragment('♥mojolicious♥');
Fragment part of this URL.
# "yada"
Mojo::URL->new('http://example.com/foo?bar=baz#yada')->fragment;
=head2 host
my $host = $url->host;
$url = $url->host('127.0.0.1');
Host part of this URL.
# "example.com"
Mojo::URL->new('http://sri:t3st@example.com:8080/foo')->host;
=head2 port
my $port = $url->port;
$url = $url->port(8080);
Port part of this URL.
# "8080"
Mojo::URL->new('http://sri:t3st@example.com:8080/foo')->port;
=head2 scheme
my $scheme = $url->scheme;
$url = $url->scheme('http');
Scheme part of this URL.
# "http"
Mojo::URL->new('http://example.com/foo')->scheme;
=head2 userinfo
my $info = $url->userinfo;
$url = $url->userinfo('root:♥');
Userinfo part of this URL.
# "sri:t3st"
Mojo::URL->new('https://sri:t3st@example.com/foo')->userinfo;
=head1 METHODS
L<Mojo::URL> inherits all methods from L<Mojo::Base> and implements the
following new ones.
=head2 clone
my $url2 = $url->clone;
Return a new L<Mojo::URL> object cloned from this URL.
=head2 host_port
my $host_port = $url->host_port;
$url = $url->host_port('example.com:8080');
Normalized version of L</"host"> and L</"port">.
# "xn--n3h.net:8080"
Mojo::URL->new('http://☃.net:8080/test')->host_port;
# "example.com"
Mojo::URL->new('http://example.com/test')->host_port;
=head2 ihost
my $ihost = $url->ihost;
$url = $url->ihost('xn--bcher-kva.ch');
Host part of this URL in punycode format.
# "xn--n3h.net"
Mojo::URL->new('http://☃.net')->ihost;
# "example.com"
Mojo::URL->new('http://example.com')->ihost;
=head2 is_abs
my $bool = $url->is_abs;
Check if URL is absolute.
# True
Mojo::URL->new('http://example.com')->is_abs;
Mojo::URL->new('http://example.com/test/index.html')->is_abs;
# False
Mojo::URL->new('test/index.html')->is_abs;
Mojo::URL->new('/test/index.html')->is_abs;
Mojo::URL->new('//example.com/test/index.html')->is_abs;
=head2 new
my $url = Mojo::URL->new;
my $url = Mojo::URL->new('http://127.0.0.1:3000/foo?f=b&baz=2#foo');
Construct a new L<Mojo::URL> object and L</"parse"> URL if necessary.
=head2 parse
$url = $url->parse('http://127.0.0.1:3000/foo/bar?fo=o&baz=23#foo');
Parse relative or absolute URL.
# "/test/123"
$url->parse('/test/123?foo=bar')->path;
# "example.com"
$url->parse('http://example.com/test/123?foo=bar')->host;
# "sri@example.com"
$url->parse('mailto:sri@example.com')->path;
=head2 password
my $password = $url->password;
Password part of L</"userinfo">.
# "s3cret"
Mojo::URL->new('http://isabel:s3cret@mojolicious.org')->password;
# "s:3:c:r:e:t"
Mojo::URL->new('http://isabel:s:3:c:r:e:t@mojolicious.org')->password;
=head2 path
my $path = $url->path;
$url = $url->path('foo/bar');
$url = $url->path('/foo/bar');
$url = $url->path(Mojo::Path->new);
Path part of this URL, relative paths will be merged with
L<Mojo::Path/"merge">, defaults to a L<Mojo::Path> object.
# "perldoc"
Mojo::URL->new('http://example.com/perldoc/Mojo')->path->parts->[0];
# "/perldoc/DOM/HTML"
Mojo::URL->new('http://example.com/perldoc/Mojo')->path->merge('DOM/HTML');
# "http://example.com/DOM/HTML"
Mojo::URL->new('http://example.com/perldoc/Mojo')->path('/DOM/HTML');
# "http://example.com/perldoc/DOM/HTML"
Mojo::URL->new('http://example.com/perldoc/Mojo')->path('DOM/HTML');
# "http://example.com/perldoc/Mojo/DOM/HTML"
Mojo::URL->new('http://example.com/perldoc/Mojo/')->path('DOM/HTML');
=head2 path_query
my $path_query = $url->path_query;
$url = $url->path_query('/foo/bar?a=1&b=2');
Normalized version of L</"path"> and L</"query">.
# "/test?a=1&b=2"
Mojo::URL->new('http://example.com/test?a=1&b=2')->path_query;
# "/"
Mojo::URL->new('http://example.com/')->path_query;
=head2 protocol
my $proto = $url->protocol;
Normalized version of L</"scheme">.
# "http"
Mojo::URL->new('HtTp://example.com')->protocol;
=head2 query
my $query = $url->query;
$url = $url->query({merge => 'to'});
$url = $url->query([append => 'with']);
$url = $url->query(replace => 'with');
$url = $url->query('a=1&b=2');
$url = $url->query(Mojo::Parameters->new);
Query part of this URL, key/value pairs in an array reference will be appended
with L<Mojo::Parameters/"append">, and key/value pairs in a hash reference
merged with L<Mojo::Parameters/"merge">, defaults to a L<Mojo::Parameters>
object.
# "2"
Mojo::URL->new('http://example.com?a=1&b=2')->query->param('b');
# "a=2&b=2&c=3"
Mojo::URL->new('http://example.com?a=1&b=2')->query->merge(a => 2, c => 3);
# "http://example.com?a=2&c=3"
Mojo::URL->new('http://example.com?a=1&b=2')->query(a => 2, c => 3);
# "http://example.com?a=2&a=3"
Mojo::URL->new('http://example.com?a=1&b=2')->query(a => [2, 3]);
# "http://example.com?a=2&b=2&c=3"
Mojo::URL->new('http://example.com?a=1&b=2')->query({a => 2, c => 3});
# "http://example.com?b=2"
Mojo::URL->new('http://example.com?a=1&b=2')->query({a => undef});
# "http://example.com?a=1&b=2&a=2&c=3"
Mojo::URL->new('http://example.com?a=1&b=2')->query([a => 2, c => 3]);
=head2 to_abs
my $abs = $url->to_abs;
my $abs = $url->to_abs(Mojo::URL->new('http://example.com/foo'));
Return a new L<Mojo::URL> object cloned from this relative URL and turn it into
an absolute one using L</"base"> or provided base URL.
# "http://example.com/foo/baz.xml?test=123"
Mojo::URL->new('baz.xml?test=123')
->to_abs(Mojo::URL->new('http://example.com/foo/bar.html'));
# "http://example.com/baz.xml?test=123"
Mojo::URL->new('/baz.xml?test=123')
->to_abs(Mojo::URL->new('http://example.com/foo/bar.html'));
# "http://example.com/foo/baz.xml?test=123"
Mojo::URL->new('//example.com/foo/baz.xml?test=123')
->to_abs(Mojo::URL->new('http://example.com/foo/bar.html'));
=head2 to_string
my $str = $url->to_string;
Turn URL into a string. Note that L</"userinfo"> will not be included for
security reasons.
# "http://mojolicious.org"
Mojo::URL->new->scheme('http')->host('mojolicious.org')->to_string;
# "http://mojolicious.org"
Mojo::URL->new('http://daniel:s3cret@mojolicious.org')->to_string;
=head2 to_unsafe_string
my $str = $url->to_unsafe_string;
Same as L</"to_string">, but includes L</"userinfo">.
# "http://daniel:s3cret@mojolicious.org"
Mojo::URL->new('http://daniel:s3cret@mojolicious.org')->to_unsafe_string;
=head2 username
my $username = $url->username;
Username part of L</"userinfo">.
# "isabel"
Mojo::URL->new('http://isabel:s3cret@mojolicious.org')->username;
=head1 OPERATORS
L<Mojo::URL> overloads the following operators.
=head2 bool
my $bool = !!$url;
Always true.
=head2 stringify
my $str = "$url";
Alias for L</"to_string">.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
=cut
| marcusramberg/mojo | lib/Mojo/URL.pm | Perl | artistic-2.0 | 12,871 |
# typed: false
# frozen_string_literal: true
require "rubocops/bottle"
describe RuboCop::Cop::FormulaAudit::BottleTagIndentation do
subject(:cop) { described_class.new }
it "reports no offenses for `bottle :uneeded`" do
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle :unneeded
end
RUBY
end
it "reports no offenses for `bottle` blocks without cellars" do
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 arm64_big_sur: "aaaaaaaa"
sha256 big_sur: "faceb00c"
sha256 catalina: "deadbeef"
end
end
RUBY
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
sha256 big_sur: "faceb00c"
end
end
RUBY
end
it "reports no offenses for properly aligned tags in `bottle` blocks with cellars" do
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
sha256 cellar: "/usr/local/Cellar", big_sur: "faceb00c"
sha256 catalina: "deadbeef"
end
end
RUBY
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
end
end
RUBY
end
it "reports and corrects misaligned tags in `bottle` block with cellars" do
expect_offense(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
^^^^^^^^^^^^^^^^^^^^^^^^^ Align bottle tags
sha256 cellar: "/usr/local/Cellar", big_sur: "faceb00c"
sha256 catalina: "deadbeef"
^^^^^^^^^^^^^^^^^^^^ Align bottle tags
end
end
RUBY
expect_correction(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
sha256 cellar: "/usr/local/Cellar", big_sur: "faceb00c"
sha256 catalina: "deadbeef"
end
end
RUBY
end
end
| EricFromCanada/brew | Library/Homebrew/test/rubocops/bottle/bottle_tag_indentation_spec.rb | Ruby | bsd-2-clause | 2,538 |
<?php
class Kwc_Shop_Cart_Checkout_Payment_Abstract_OrderTable_Component extends Kwc_Abstract
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['viewCache'] = false;
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$ret['order'] = $this->_getOrder();
$ret['items'] = $ret['order']->getProductsData();
$items = $ret['order']->getChildRows('Products');
$ret['items'] = array();
$ret['additionalOrderDataHeaders'] = array();
foreach ($items as $i) {
$addComponent = Kwf_Component_Data_Root::getInstance()
->getComponentByDbId($i->add_component_id);
$additionalOrderData = $addComponent->getComponent()->getAdditionalOrderData($i);
foreach ($additionalOrderData as $d) {
if (!isset($ret['additionalOrderDataHeaders'][$d['name']])) {
$ret['additionalOrderDataHeaders'][$d['name']] = array(
'class' => $d['class'],
'text' => $d['name']
);
}
}
$ret['items'][] = (object)array(
'product' => $addComponent->parent,
'row' => $i,
'additionalOrderData' => $additionalOrderData,
'price' => $i->getProductPrice(),
'text' => $i->getProductText(),
);
}
$ret['sumRows'] = $this->_getSumRows($this->_getOrder());
$ret['tableFooterText'] = '';
$ret['footerText'] = '';
return $ret;
}
protected function _getOrder()
{
return Kwf_Model_Abstract::getInstance(Kwc_Abstract::getSetting($this->getData()->getParentByClass('Kwc_Shop_Cart_Component')->componentClass, 'childModel'))
->getReferencedModel('Order')->getCartOrder();
}
protected function _getSumRows($order)
{
return $this->getData()->parent->parent->getComponent()->getSumRows($order);
}
}
| yacon/koala-framework | Kwc/Shop/Cart/Checkout/Payment/Abstract/OrderTable/Component.php | PHP | bsd-2-clause | 2,091 |
<?php
class Kwc_Menu_EditableItems_ExtConfig extends Kwc_Abstract_List_ExtConfigList
{
protected function _getConfig()
{
$ret = parent::_getConfig();
$ret['list']['listWidth'] = 120;
return $ret;
}
}
| yacon/koala-framework | Kwc/Menu/EditableItems/ExtConfig.php | PHP | bsd-2-clause | 236 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_EXO_TOUCH_H_
#define COMPONENTS_EXO_TOUCH_H_
#include "base/containers/flat_map.h"
#include "components/exo/surface_observer.h"
#include "ui/events/event_handler.h"
#include "ui/gfx/geometry/point_f.h"
namespace ui {
class LocatedEvent;
class TouchEvent;
}
namespace exo {
class Seat;
class TouchDelegate;
class TouchStylusDelegate;
// This class implements a client touch device that represents one or more
// touch devices.
class Touch : public ui::EventHandler, public SurfaceObserver {
public:
Touch(TouchDelegate* delegate, Seat* seat);
Touch(const Touch&) = delete;
Touch& operator=(const Touch&) = delete;
~Touch() override;
TouchDelegate* delegate() const { return delegate_; }
// Set delegate for stylus events.
void SetStylusDelegate(TouchStylusDelegate* delegate);
bool HasStylusDelegate() const;
// Overridden from ui::EventHandler:
void OnTouchEvent(ui::TouchEvent* event) override;
// Overridden from SurfaceObserver:
void OnSurfaceDestroying(Surface* surface) override;
private:
// Returns the effective target for |event|.
Surface* GetEffectiveTargetForEvent(ui::LocatedEvent* event) const;
// Cancels touches on all the surfaces.
void CancelAllTouches();
// The delegate instance that all events are dispatched to.
TouchDelegate* const delegate_;
Seat* const seat_;
// The delegate instance that all stylus related events are dispatched to.
TouchStylusDelegate* stylus_delegate_ = nullptr;
// Map of touch points to its focus surface.
base::flat_map<int, Surface*> touch_points_surface_map_;
// Map of a touched surface to the count of touch pointers on that surface.
base::flat_map<Surface*, int> surface_touch_count_map_;
};
} // namespace exo
#endif // COMPONENTS_EXO_TOUCH_H_
| scheib/chromium | components/exo/touch.h | C | bsd-3-clause | 1,955 |
/*
* General DV muxer/demuxer
* Copyright (c) 2003 Roman Shaposhnik
*
* Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
* of DV technical info.
*
* Raw DV format
* Copyright (c) 2002 Fabrice Bellard
*
* 50 Mbps (DVCPRO50) support
* Copyright (c) 2006 Daniel Maas <dmaas@maasdigital.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <time.h>
#include <stdarg.h>
#include "avformat.h"
#include "internal.h"
#include "libavcodec/dv_profile.h"
#include "libavcodec/dvdata.h"
#include "dv.h"
#include "libavutil/fifo.h"
#include "libavutil/mathematics.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/opt.h"
#include "libavutil/timecode.h"
#define MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio
struct DVMuxContext {
AVClass *av_class;
const DVprofile* sys; /* current DV profile, e.g.: 525/60, 625/50 */
int n_ast; /* number of stereo audio streams (up to 2) */
AVStream *ast[2]; /* stereo audio streams */
AVFifoBuffer *audio_data[2]; /* FIFO for storing excessive amounts of PCM */
int frames; /* current frame number */
int64_t start_time; /* recording start time */
int has_audio; /* frame under contruction has audio */
int has_video; /* frame under contruction has video */
uint8_t frame_buf[DV_MAX_FRAME_SIZE]; /* frame under contruction */
AVTimecode tc; /* timecode context */
};
static const int dv_aaux_packs_dist[12][9] = {
{ 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
{ 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
{ 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
{ 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
{ 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
{ 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
{ 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
{ 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
{ 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
{ 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
{ 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
{ 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
};
static int dv_audio_frame_size(const DVprofile* sys, int frame)
{
return sys->audio_samples_dist[frame % (sizeof(sys->audio_samples_dist) /
sizeof(sys->audio_samples_dist[0]))];
}
static int dv_write_pack(enum dv_pack_type pack_id, DVMuxContext *c, uint8_t* buf, ...)
{
struct tm tc;
time_t ct;
uint32_t timecode;
va_list ap;
buf[0] = (uint8_t)pack_id;
switch (pack_id) {
case dv_timecode:
timecode = av_timecode_get_smpte_from_framenum(&c->tc, c->frames);
timecode |= 1<<23 | 1<<15 | 1<<7 | 1<<6; // biphase and binary group flags
AV_WB32(buf + 1, timecode);
break;
case dv_audio_source: /* AAUX source pack */
va_start(ap, buf);
buf[1] = (1 << 7) | /* locked mode -- SMPTE only supports locked mode */
(1 << 6) | /* reserved -- always 1 */
(dv_audio_frame_size(c->sys, c->frames) -
c->sys->audio_min_samples[0]);
/* # of samples */
buf[2] = (0 << 7) | /* multi-stereo */
(0 << 5) | /* #of audio channels per block: 0 -- 1 channel */
(0 << 4) | /* pair bit: 0 -- one pair of channels */
!!va_arg(ap, int); /* audio mode */
buf[3] = (1 << 7) | /* res */
(1 << 6) | /* multi-language flag */
(c->sys->dsf << 5) | /* system: 60fields/50fields */
(c->sys->n_difchan & 2); /* definition: 0 -- 25Mbps, 2 -- 50Mbps */
buf[4] = (1 << 7) | /* emphasis: 1 -- off */
(0 << 6) | /* emphasis time constant: 0 -- reserved */
(0 << 3) | /* frequency: 0 -- 48kHz, 1 -- 44,1kHz, 2 -- 32kHz */
0; /* quantization: 0 -- 16bit linear, 1 -- 12bit nonlinear */
va_end(ap);
break;
case dv_audio_control:
buf[1] = (0 << 6) | /* copy protection: 0 -- unrestricted */
(1 << 4) | /* input source: 1 -- digital input */
(3 << 2) | /* compression: 3 -- no information */
0; /* misc. info/SMPTE emphasis off */
buf[2] = (1 << 7) | /* recording start point: 1 -- no */
(1 << 6) | /* recording end point: 1 -- no */
(1 << 3) | /* recording mode: 1 -- original */
7;
buf[3] = (1 << 7) | /* direction: 1 -- forward */
(c->sys->pix_fmt == PIX_FMT_YUV420P ? 0x20 : /* speed */
c->sys->ltc_divisor * 4);
buf[4] = (1 << 7) | /* reserved -- always 1 */
0x7f; /* genre category */
break;
case dv_audio_recdate:
case dv_video_recdate: /* VAUX recording date */
ct = c->start_time + av_rescale_rnd(c->frames, c->sys->time_base.num,
c->sys->time_base.den, AV_ROUND_DOWN);
ff_brktimegm(ct, &tc);
buf[1] = 0xff; /* ds, tm, tens of time zone, units of time zone */
/* 0xff is very likely to be "unknown" */
buf[2] = (3 << 6) | /* reserved -- always 1 */
((tc.tm_mday / 10) << 4) | /* Tens of day */
(tc.tm_mday % 10); /* Units of day */
buf[3] = /* we set high 4 bits to 0, shouldn't we set them to week? */
((tc.tm_mon / 10) << 4) | /* Tens of month */
(tc.tm_mon % 10); /* Units of month */
buf[4] = (((tc.tm_year % 100) / 10) << 4) | /* Tens of year */
(tc.tm_year % 10); /* Units of year */
break;
case dv_audio_rectime: /* AAUX recording time */
case dv_video_rectime: /* VAUX recording time */
ct = c->start_time + av_rescale_rnd(c->frames, c->sys->time_base.num,
c->sys->time_base.den, AV_ROUND_DOWN);
ff_brktimegm(ct, &tc);
buf[1] = (3 << 6) | /* reserved -- always 1 */
0x3f; /* tens of frame, units of frame: 0x3f - "unknown" ? */
buf[2] = (1 << 7) | /* reserved -- always 1 */
((tc.tm_sec / 10) << 4) | /* Tens of seconds */
(tc.tm_sec % 10); /* Units of seconds */
buf[3] = (1 << 7) | /* reserved -- always 1 */
((tc.tm_min / 10) << 4) | /* Tens of minutes */
(tc.tm_min % 10); /* Units of minutes */
buf[4] = (3 << 6) | /* reserved -- always 1 */
((tc.tm_hour / 10) << 4) | /* Tens of hours */
(tc.tm_hour % 10); /* Units of hours */
break;
default:
buf[1] = buf[2] = buf[3] = buf[4] = 0xff;
}
return 5;
}
static void dv_inject_audio(DVMuxContext *c, int channel, uint8_t* frame_ptr)
{
int i, j, d, of, size;
size = 4 * dv_audio_frame_size(c->sys, c->frames);
frame_ptr += channel * c->sys->difseg_size * 150 * 80;
for (i = 0; i < c->sys->difseg_size; i++) {
frame_ptr += 6 * 80; /* skip DIF segment header */
for (j = 0; j < 9; j++) {
dv_write_pack(dv_aaux_packs_dist[i][j], c, &frame_ptr[3], i >= c->sys->difseg_size/2);
for (d = 8; d < 80; d+=2) {
of = c->sys->audio_shuffle[i][j] + (d - 8)/2 * c->sys->audio_stride;
if (of*2 >= size)
continue;
frame_ptr[d] = *av_fifo_peek2(c->audio_data[channel], of*2+1); // FIXME: maybe we have to admit
frame_ptr[d+1] = *av_fifo_peek2(c->audio_data[channel], of*2); // that DV is a big-endian PCM
}
frame_ptr += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
}
}
}
static void dv_inject_metadata(DVMuxContext *c, uint8_t* frame)
{
int j, k;
uint8_t* buf;
for (buf = frame; buf < frame + c->sys->frame_size; buf += 150 * 80) {
/* DV subcode: 2nd and 3d DIFs */
for (j = 80; j < 80 * 3; j += 80) {
for (k = 6; k < 6 * 8; k += 8)
dv_write_pack(dv_timecode, c, &buf[j+k]);
if (((long)(buf-frame)/(c->sys->frame_size/(c->sys->difseg_size*c->sys->n_difchan))%c->sys->difseg_size) > 5) { /* FIXME: is this really needed ? */
dv_write_pack(dv_video_recdate, c, &buf[j+14]);
dv_write_pack(dv_video_rectime, c, &buf[j+22]);
dv_write_pack(dv_video_recdate, c, &buf[j+38]);
dv_write_pack(dv_video_rectime, c, &buf[j+46]);
}
}
/* DV VAUX: 4th, 5th and 6th 3DIFs */
for (j = 80*3 + 3; j < 80*6; j += 80) {
dv_write_pack(dv_video_recdate, c, &buf[j+5*2]);
dv_write_pack(dv_video_rectime, c, &buf[j+5*3]);
dv_write_pack(dv_video_recdate, c, &buf[j+5*11]);
dv_write_pack(dv_video_rectime, c, &buf[j+5*12]);
}
}
}
/*
* The following 3 functions constitute our interface to the world
*/
static int dv_assemble_frame(DVMuxContext *c, AVStream* st,
uint8_t* data, int data_size, uint8_t** frame)
{
int i, reqasize;
*frame = &c->frame_buf[0];
reqasize = 4 * dv_audio_frame_size(c->sys, c->frames);
switch (st->codec->codec_type) {
case AVMEDIA_TYPE_VIDEO:
/* FIXME: we have to have more sensible approach than this one */
if (c->has_video)
av_log(st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient audio data or severe sync problem.\n", c->frames);
memcpy(*frame, data, c->sys->frame_size);
c->has_video = 1;
break;
case AVMEDIA_TYPE_AUDIO:
for (i = 0; i < c->n_ast && st != c->ast[i]; i++);
/* FIXME: we have to have more sensible approach than this one */
if (av_fifo_size(c->audio_data[i]) + data_size >= 100*MAX_AUDIO_FRAME_SIZE)
av_log(st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient video data or severe sync problem.\n", c->frames);
av_fifo_generic_write(c->audio_data[i], data, data_size, NULL);
/* Let us see if we've got enough audio for one DV frame. */
c->has_audio |= ((reqasize <= av_fifo_size(c->audio_data[i])) << i);
break;
default:
break;
}
/* Let us see if we have enough data to construct one DV frame. */
if (c->has_video == 1 && c->has_audio + 1 == 1 << c->n_ast) {
dv_inject_metadata(c, *frame);
c->has_audio = 0;
for (i=0; i < c->n_ast; i++) {
dv_inject_audio(c, i, *frame);
av_fifo_drain(c->audio_data[i], reqasize);
c->has_audio |= ((reqasize <= av_fifo_size(c->audio_data[i])) << i);
}
c->has_video = 0;
c->frames++;
return c->sys->frame_size;
}
return 0;
}
static DVMuxContext* dv_init_mux(AVFormatContext* s)
{
DVMuxContext *c = s->priv_data;
AVStream *vst = NULL;
AVDictionaryEntry *t;
int i;
/* we support at most 1 video and 2 audio streams */
if (s->nb_streams > 3)
return NULL;
c->n_ast = 0;
c->ast[0] = c->ast[1] = NULL;
/* We have to sort out where audio and where video stream is */
for (i=0; i<s->nb_streams; i++) {
switch (s->streams[i]->codec->codec_type) {
case AVMEDIA_TYPE_VIDEO:
if (vst) return NULL;
vst = s->streams[i];
break;
case AVMEDIA_TYPE_AUDIO:
if (c->n_ast > 1) return NULL;
c->ast[c->n_ast++] = s->streams[i];
break;
default:
goto bail_out;
}
}
/* Some checks -- DV format is very picky about its incoming streams */
if (!vst || vst->codec->codec_id != AV_CODEC_ID_DVVIDEO)
goto bail_out;
for (i=0; i<c->n_ast; i++) {
if (c->ast[i] && (c->ast[i]->codec->codec_id != AV_CODEC_ID_PCM_S16LE ||
c->ast[i]->codec->sample_rate != 48000 ||
c->ast[i]->codec->channels != 2))
goto bail_out;
}
c->sys = avpriv_dv_codec_profile(vst->codec);
if (!c->sys)
goto bail_out;
if ((c->n_ast > 1) && (c->sys->n_difchan < 2)) {
/* only 1 stereo pair is allowed in 25Mbps mode */
goto bail_out;
}
/* Ok, everything seems to be in working order */
c->frames = 0;
c->has_audio = 0;
c->has_video = 0;
if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
c->start_time = ff_iso8601_to_unix_time(t->value);
for (i=0; i < c->n_ast; i++) {
if (c->ast[i] && !(c->audio_data[i]=av_fifo_alloc(100*MAX_AUDIO_FRAME_SIZE))) {
while (i > 0) {
i--;
av_fifo_free(c->audio_data[i]);
}
goto bail_out;
}
}
return c;
bail_out:
return NULL;
}
static void dv_delete_mux(DVMuxContext *c)
{
int i;
for (i=0; i < c->n_ast; i++)
av_fifo_free(c->audio_data[i]);
}
static int dv_write_header(AVFormatContext *s)
{
AVRational rate;
DVMuxContext *dvc = s->priv_data;
AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
if (!dv_init_mux(s)) {
av_log(s, AV_LOG_ERROR, "Can't initialize DV format!\n"
"Make sure that you supply exactly two streams:\n"
" video: 25fps or 29.97fps, audio: 2ch/48kHz/PCM\n"
" (50Mbps allows an optional second audio stream)\n");
return -1;
}
rate.num = dvc->sys->ltc_divisor;
rate.den = 1;
if (!tcr) { // no global timecode, look into the streams
int i;
for (i = 0; i < s->nb_streams; i++) {
tcr = av_dict_get(s->streams[i]->metadata, "timecode", NULL, 0);
if (tcr)
break;
}
}
if (tcr)
return av_timecode_init_from_string(&dvc->tc, rate, tcr->value, s);
return av_timecode_init(&dvc->tc, rate, 0, 0, s);
}
static int dv_write_packet(struct AVFormatContext *s, AVPacket *pkt)
{
uint8_t* frame;
int fsize;
fsize = dv_assemble_frame(s->priv_data, s->streams[pkt->stream_index],
pkt->data, pkt->size, &frame);
if (fsize > 0) {
avio_write(s->pb, frame, fsize);
avio_flush(s->pb);
}
return 0;
}
/*
* We might end up with some extra A/V data without matching counterpart.
* E.g. video data without enough audio to write the complete frame.
* Currently we simply drop the last frame. I don't know whether this
* is the best strategy of all
*/
static int dv_write_trailer(struct AVFormatContext *s)
{
dv_delete_mux(s->priv_data);
return 0;
}
AVOutputFormat ff_dv_muxer = {
.name = "dv",
.long_name = NULL_IF_CONFIG_SMALL("DV (Digital Video)"),
.extensions = "dv",
.priv_data_size = sizeof(DVMuxContext),
.audio_codec = AV_CODEC_ID_PCM_S16LE,
.video_codec = AV_CODEC_ID_DVVIDEO,
.write_header = dv_write_header,
.write_packet = dv_write_packet,
.write_trailer = dv_write_trailer,
};
| leighpauls/k2cro4 | third_party/ffmpeg/libavformat/dvenc.c | C | bsd-3-clause | 16,245 |
package org.motechproject.mds.builder.impl;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.NotFoundException;
import org.apache.commons.lang.reflect.FieldUtils;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.motechproject.mds.annotations.internal.samples.AnotherSample;
import org.motechproject.mds.builder.EntityMetadataBuilder;
import org.motechproject.mds.builder.Sample;
import org.motechproject.mds.builder.SampleWithIncrementStrategy;
import org.motechproject.mds.domain.ClassData;
import org.motechproject.mds.domain.EntityType;
import org.motechproject.mds.domain.OneToManyRelationship;
import org.motechproject.mds.domain.OneToOneRelationship;
import org.motechproject.mds.dto.EntityDto;
import org.motechproject.mds.dto.FieldBasicDto;
import org.motechproject.mds.dto.FieldDto;
import org.motechproject.mds.dto.LookupDto;
import org.motechproject.mds.dto.LookupFieldDto;
import org.motechproject.mds.dto.LookupFieldType;
import org.motechproject.mds.dto.MetadataDto;
import org.motechproject.mds.dto.SchemaHolder;
import org.motechproject.mds.dto.TypeDto;
import org.motechproject.mds.javassist.MotechClassPool;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceModifier;
import javax.jdo.metadata.ClassMetadata;
import javax.jdo.metadata.ClassPersistenceModifier;
import javax.jdo.metadata.CollectionMetadata;
import javax.jdo.metadata.FieldMetadata;
import javax.jdo.metadata.ForeignKeyMetadata;
import javax.jdo.metadata.IndexMetadata;
import javax.jdo.metadata.InheritanceMetadata;
import javax.jdo.metadata.JDOMetadata;
import javax.jdo.metadata.PackageMetadata;
import javax.jdo.metadata.UniqueMetadata;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.motechproject.mds.testutil.FieldTestHelper.fieldDto;
import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_CLASS;
import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_FIELD;
import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.CREATOR_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.CREATOR_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.DATANUCLEUS;
import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.OWNER_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.OWNER_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.VALUE_GENERATOR;
@RunWith(PowerMockRunner.class)
@PrepareForTest({MotechClassPool.class, FieldUtils.class})
public class EntityMetadataBuilderTest {
private static final String PACKAGE = "org.motechproject.mds.entity";
private static final String ENTITY_NAME = "Sample";
private static final String MODULE = "MrS";
private static final String NAMESPACE = "arrio";
private static final String TABLE_NAME = "";
private static final String CLASS_NAME = String.format("%s.%s", PACKAGE, ENTITY_NAME);
private static final String TABLE_NAME_1 = String.format("MDS_%s", ENTITY_NAME).toUpperCase();
private static final String TABLE_NAME_2 = String.format("%s_%s", MODULE, ENTITY_NAME).toUpperCase();
private static final String TABLE_NAME_3 = String.format("%s_%s_%s", MODULE, NAMESPACE, ENTITY_NAME).toUpperCase();
private EntityMetadataBuilder entityMetadataBuilder = new EntityMetadataBuilderImpl();
@Mock
private EntityDto entity;
@Mock
private FieldDto idField;
@Mock
private JDOMetadata jdoMetadata;
@Mock
private PackageMetadata packageMetadata;
@Mock
private ClassMetadata classMetadata;
@Mock
private FieldMetadata idMetadata;
@Mock
private InheritanceMetadata inheritanceMetadata;
@Mock
private IndexMetadata indexMetadata;
@Mock
private SchemaHolder schemaHolder;
@Before
public void setUp() {
initMocks(this);
when(entity.getClassName()).thenReturn(CLASS_NAME);
when(classMetadata.newFieldMetadata("id")).thenReturn(idMetadata);
when(idMetadata.getName()).thenReturn("id");
when(classMetadata.newInheritanceMetadata()).thenReturn(inheritanceMetadata);
when(schemaHolder.getFieldByName(entity, "id")).thenReturn(idField);
when(entity.isBaseEntity()).thenReturn(true);
}
@Test
public void shouldAddEntityMetadata() throws Exception {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getModule()).thenReturn(MODULE);
when(entity.getNamespace()).thenReturn(NAMESPACE);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(jdoMetadata).newPackageMetadata(PACKAGE);
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_3);
verifyCommonClassMetadata();
}
@Test
public void shouldAddToAnExistingPackage() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.getPackages()).thenReturn(new PackageMetadata[]{packageMetadata});
when(packageMetadata.getName()).thenReturn(PACKAGE);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(jdoMetadata, never()).newPackageMetadata(PACKAGE);
verify(jdoMetadata).getPackages();
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_1);
verifyCommonClassMetadata();
}
@Test
public void shouldSetAppropriateTableName() throws Exception {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(classMetadata).setTable(TABLE_NAME_1);
when(entity.getModule()).thenReturn(MODULE);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(classMetadata).setTable(TABLE_NAME_2);
when(entity.getNamespace()).thenReturn(NAMESPACE);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(classMetadata).setTable(TABLE_NAME_3);
}
@Test
public void shouldAddBaseEntityMetadata() throws Exception {
CtField ctField = mock(CtField.class);
CtClass ctClass = mock(CtClass.class);
CtClass superClass = mock(CtClass.class);
ClassData classData = mock(ClassData.class);
ClassPool pool = mock(ClassPool.class);
PowerMockito.mockStatic(MotechClassPool.class);
PowerMockito.when(MotechClassPool.getDefault()).thenReturn(pool);
when(classData.getClassName()).thenReturn(CLASS_NAME);
when(classData.getModule()).thenReturn(MODULE);
when(classData.getNamespace()).thenReturn(NAMESPACE);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(pool.getOrNull(CLASS_NAME)).thenReturn(ctClass);
when(ctClass.getField("id")).thenReturn(ctField);
when(ctClass.getSuperclass()).thenReturn(superClass);
when(superClass.getName()).thenReturn(Object.class.getName());
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addBaseMetadata(jdoMetadata, classData, EntityType.STANDARD, Sample.class);
verify(jdoMetadata).newPackageMetadata(PACKAGE);
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_3);
verifyCommonClassMetadata();
}
@Test
public void shouldAddOneToManyRelationshipMetadata() {
FieldDto oneToManyField = fieldDto("oneToManyName", OneToManyRelationship.class);
oneToManyField.addMetadata(new MetadataDto(RELATED_CLASS, "org.motechproject.test.MyClass"));
FieldMetadata fmd = mock(FieldMetadata.class);
CollectionMetadata collMd = mock(CollectionMetadata.class);
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getId()).thenReturn(2L);
when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToManyField));
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
when(classMetadata.newFieldMetadata("oneToManyName")).thenReturn(fmd);
when(fmd.getCollectionMetadata()).thenReturn(collMd);
when(fmd.getName()).thenReturn("oneToManyName");
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verifyCommonClassMetadata();
verify(fmd).setDefaultFetchGroup(true);
verify(collMd).setEmbeddedElement(false);
verify(collMd).setSerializedElement(false);
verify(collMd).setElementType("org.motechproject.test.MyClass");
}
@Test
public void shouldAddOneToOneRelationshipMetadata() throws NotFoundException, CannotCompileException {
final String relClassName = "org.motechproject.test.MyClass";
final String relFieldName = "myField";
FieldDto oneToOneField = fieldDto("oneToOneName", OneToOneRelationship.class);
oneToOneField.addMetadata(new MetadataDto(RELATED_CLASS, relClassName));
oneToOneField.addMetadata(new MetadataDto(RELATED_FIELD, relFieldName));
FieldMetadata fmd = mock(FieldMetadata.class);
when(fmd.getName()).thenReturn("oneToOneName");
ForeignKeyMetadata fkmd = mock(ForeignKeyMetadata.class);
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getId()).thenReturn(3L);
when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToOneField));
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
when(classMetadata.newFieldMetadata("oneToOneName")).thenReturn(fmd);
when(fmd.newForeignKeyMetadata()).thenReturn(fkmd);
/* We simulate configuration for the bi-directional relationship (the related class has got
a field that links back to the main class) */
CtClass myClass = mock(CtClass.class);
CtClass relatedClass = mock(CtClass.class);
CtField myField = mock(CtField.class);
CtField relatedField = mock(CtField.class);
when(myClass.getName()).thenReturn(relClassName);
when(myClass.getDeclaredFields()).thenReturn(new CtField[]{myField});
when(myField.getType()).thenReturn(relatedClass);
when(myField.getName()).thenReturn(relFieldName);
when(relatedClass.getDeclaredFields()).thenReturn(new CtField[]{relatedField});
when(relatedClass.getName()).thenReturn(CLASS_NAME);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verifyCommonClassMetadata();
verify(fmd).setDefaultFetchGroup(true);
verify(fmd).setPersistenceModifier(PersistenceModifier.PERSISTENT);
verify(fkmd).setName("fk_Sample_oneToOneName_3");
}
@Test
public void shouldSetIndexOnMetadataLookupField() throws Exception {
FieldDto lookupField = fieldDto("lookupField", String.class);
LookupDto lookup = new LookupDto();
lookup.setLookupName("A lookup");
lookup.setLookupFields(singletonList(new LookupFieldDto("lookupField", LookupFieldType.VALUE)));
lookup.setIndexRequired(true);
lookupField.setLookups(singletonList(lookup));
FieldMetadata fmd = mock(FieldMetadata.class);
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getId()).thenReturn(14L);
when(schemaHolder.getFields(entity)).thenReturn(singletonList(lookupField));
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
when(classMetadata.newFieldMetadata("lookupField")).thenReturn(fmd);
when(fmd.newIndexMetadata()).thenReturn(indexMetadata);
PowerMockito.mockStatic(FieldUtils.class);
when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg"));
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verifyCommonClassMetadata();
verify(fmd).newIndexMetadata();
verify(indexMetadata).setName("lkp_idx_" + ENTITY_NAME + "_lookupField_14");
}
@Test
public void shouldAddObjectValueGeneratorToAppropriateFields() throws Exception {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
List<FieldDto> fields = new ArrayList<>();
// for these fields the appropriate generator should be added
fields.add(fieldDto(1L, CREATOR_FIELD_NAME, String.class.getName(), CREATOR_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(2L, OWNER_FIELD_NAME, String.class.getName(), OWNER_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(3L, CREATION_DATE_FIELD_NAME, DateTime.class.getName(), CREATION_DATE_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(4L, MODIFIED_BY_FIELD_NAME, String.class.getName(), MODIFIED_BY_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(5L, MODIFICATION_DATE_FIELD_NAME, DateTime.class.getName(), MODIFICATION_DATE_DISPLAY_FIELD_NAME, null));
doReturn(fields).when(schemaHolder).getFields(CLASS_NAME);
final List<FieldMetadata> list = new ArrayList<>();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// we create a mock ...
FieldMetadata metadata = mock(FieldMetadata.class);
// ... and it should return correct name
doReturn(invocation.getArguments()[0]).when(metadata).getName();
// Because we want to check that appropriate methods was executed
// we added metadata to list and later we will verify conditions
list.add(metadata);
// in the end we have to return the mock
return metadata;
}
}).when(classMetadata).newFieldMetadata(anyString());
PowerMockito.mockStatic(FieldUtils.class);
when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg"));
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
for (FieldMetadata metadata : list) {
String name = metadata.getName();
// the id field should not have set object value generator metadata
int invocations = "id".equalsIgnoreCase(name) ? 0 : 1;
verify(classMetadata).newFieldMetadata(name);
verify(metadata, times(invocations)).setPersistenceModifier(PersistenceModifier.PERSISTENT);
verify(metadata, times(invocations)).setDefaultFetchGroup(true);
verify(metadata, times(invocations)).newExtensionMetadata(DATANUCLEUS, VALUE_GENERATOR, "ovg." + name);
}
}
@Test
public void shouldNotSetDefaultInheritanceStrategyIfUserDefinedOwn() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, AnotherSample.class, schemaHolder);
verifyZeroInteractions(inheritanceMetadata);
}
@Test
public void shouldNotSetDefaultFetchGroupIfSpecified() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
FieldDto field = fieldDto("notInDefFg", OneToOneRelationship.class);
when(schemaHolder.getFields(CLASS_NAME)).thenReturn(singletonList(field));
FieldMetadata fmd = mock(FieldMetadata.class);
when(fmd.getName()).thenReturn("notInDefFg");
when(classMetadata.newFieldMetadata("notInDefFg")).thenReturn(fmd);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(fmd, never()).setDefaultFetchGroup(anyBoolean());
}
@Test
public void shouldMarkEudeFieldsAsUnique() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
FieldDto eudeField = mock(FieldDto.class);
FieldBasicDto eudeBasic = mock(FieldBasicDto.class);
when(eudeField.getBasic()).thenReturn(eudeBasic);
when(eudeBasic.getName()).thenReturn("uniqueField");
when(eudeField.isReadOnly()).thenReturn(false);
when(eudeBasic.isUnique()).thenReturn(true);
when(eudeField.getType()).thenReturn(TypeDto.STRING);
FieldDto ddeField = mock(FieldDto.class);
FieldBasicDto ddeBasic = mock(FieldBasicDto.class);
when(ddeField.getBasic()).thenReturn(ddeBasic);
when(ddeBasic.getName()).thenReturn("uniqueField2");
when(ddeField.isReadOnly()).thenReturn(true);
when(ddeBasic.isUnique()).thenReturn(true);
when(ddeField.getType()).thenReturn(TypeDto.STRING);
when(schemaHolder.getFields(entity)).thenReturn(asList(ddeField, eudeField));
FieldMetadata fmdEude = mock(FieldMetadata.class);
when(fmdEude.getName()).thenReturn("uniqueField");
when(classMetadata.newFieldMetadata("uniqueField")).thenReturn(fmdEude);
FieldMetadata fmdDde = mock(FieldMetadata.class);
when(fmdDde.getName()).thenReturn("uniqueField2");
when(classMetadata.newFieldMetadata("uniqueField2")).thenReturn(fmdDde);
UniqueMetadata umd = mock(UniqueMetadata.class);
when(fmdEude.newUniqueMetadata()).thenReturn(umd);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(fmdDde, never()).newUniqueMetadata();
verify(fmdDde, never()).setUnique(anyBoolean());
verify(fmdEude).newUniqueMetadata();
verify(umd).setName("unq_Sample_uniqueField");
}
@Test
public void shouldSetIncrementStrategy() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getModule()).thenReturn(MODULE);
when(entity.getNamespace()).thenReturn(NAMESPACE);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, SampleWithIncrementStrategy.class, schemaHolder);
verify(jdoMetadata).newPackageMetadata(PACKAGE);
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_3);
verifyCommonClassMetadata(IdGeneratorStrategy.INCREMENT);
}
private void verifyCommonClassMetadata() {
verifyCommonClassMetadata(IdGeneratorStrategy.NATIVE);
}
private void verifyCommonClassMetadata(IdGeneratorStrategy expextedStrategy) {
verify(classMetadata).setDetachable(true);
verify(classMetadata).setIdentityType(IdentityType.APPLICATION);
verify(classMetadata).setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE);
verify(idMetadata).setPrimaryKey(true);
verify(idMetadata).setValueStrategy(expextedStrategy);
verify(inheritanceMetadata).setCustomStrategy("complete-table");
}
}
| sebbrudzinski/motech | platform/mds/mds/src/test/java/org/motechproject/mds/builder/impl/EntityMetadataBuilderTest.java | Java | bsd-3-clause | 22,796 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Variable = void 0;
const VariableBase_1 = require("./VariableBase");
/**
* A Variable represents a locally scoped identifier. These include arguments to functions.
*/
class Variable extends VariableBase_1.VariableBase {
/**
* `true` if the variable is valid in a type context, false otherwise
* @public
*/
get isTypeVariable() {
if (this.defs.length === 0) {
// we don't statically know whether this is a type or a value
return true;
}
return this.defs.some(def => def.isTypeDefinition);
}
/**
* `true` if the variable is valid in a value context, false otherwise
* @public
*/
get isValueVariable() {
if (this.defs.length === 0) {
// we don't statically know whether this is a type or a value
return true;
}
return this.defs.some(def => def.isVariableDefinition);
}
}
exports.Variable = Variable;
//# sourceMappingURL=Variable.js.map | ChromeDevTools/devtools-frontend | node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.js | JavaScript | bsd-3-clause | 1,070 |
/*
* Copyright (C) 2006, 2007, 2008 Apple Computer, Inc. All rights reserved.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CanvasGradient_h
#define CanvasGradient_h
#include "bindings/core/v8/ScriptWrappable.h"
#include "platform/graphics/Gradient.h"
#include "platform/heap/Handle.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
namespace blink {
class ExceptionState;
class CanvasGradient final : public RefCountedWillBeGarbageCollectedFinalized<CanvasGradient>, public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
static PassRefPtrWillBeRawPtr<CanvasGradient> create(const FloatPoint& p0, const FloatPoint& p1)
{
return adoptRefWillBeNoop(new CanvasGradient(p0, p1));
}
static PassRefPtrWillBeRawPtr<CanvasGradient> create(const FloatPoint& p0, float r0, const FloatPoint& p1, float r1)
{
return adoptRefWillBeNoop(new CanvasGradient(p0, r0, p1, r1));
}
Gradient* gradient() const { return m_gradient.get(); }
void addColorStop(float value, const String& color, ExceptionState&);
void trace(Visitor*) { }
private:
CanvasGradient(const FloatPoint& p0, const FloatPoint& p1);
CanvasGradient(const FloatPoint& p0, float r0, const FloatPoint& p1, float r1);
RefPtr<Gradient> m_gradient;
};
} // namespace blink
#endif // CanvasGradient_h
| mxOBS/deb-pkg_trusty_chromium-browser | third_party/WebKit/Source/core/html/canvas/CanvasGradient.h | C | bsd-3-clause | 2,668 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.Forms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Orchard")]
[assembly: AssemblyCopyright("Copyright © Outercurve Foundation 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7d9d33f6-ee65-4d41-b4c3-edbadaf0a658")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.7")]
[assembly: AssemblyFileVersion("1.7")]
| cryogen/orchard | src/Orchard.Web/Modules/Orchard.Forms/Properties/AssemblyInfo.cs | C# | bsd-3-clause | 1,391 |
//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "test_utils/ANGLETest.h"
using namespace angle;
class MaxTextureSizeTest : public ANGLETest
{
protected:
MaxTextureSizeTest()
{
setWindowWidth(512);
setWindowHeight(512);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
}
virtual void SetUp()
{
ANGLETest::SetUp();
const std::string vsSource = SHADER_SOURCE
(
precision highp float;
attribute vec4 position;
varying vec2 texcoord;
void main()
{
gl_Position = position;
texcoord = (position.xy * 0.5) + 0.5;
}
);
const std::string textureFSSource = SHADER_SOURCE
(
precision highp float;
uniform sampler2D tex;
varying vec2 texcoord;
void main()
{
gl_FragColor = texture2D(tex, texcoord);
}
);
const std::string blueFSSource = SHADER_SOURCE
(
precision highp float;
void main()
{
gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
}
);
mTextureProgram = CompileProgram(vsSource, textureFSSource);
mBlueProgram = CompileProgram(vsSource, blueFSSource);
if (mTextureProgram == 0 || mBlueProgram == 0)
{
FAIL() << "shader compilation failed.";
}
mTextureUniformLocation = glGetUniformLocation(mTextureProgram, "tex");
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTexture2DSize);
glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &mMaxTextureCubeSize);
glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &mMaxRenderbufferSize);
ASSERT_GL_NO_ERROR();
}
virtual void TearDown()
{
glDeleteProgram(mTextureProgram);
glDeleteProgram(mBlueProgram);
ANGLETest::TearDown();
}
GLuint mTextureProgram;
GLint mTextureUniformLocation;
GLuint mBlueProgram;
GLint mMaxTexture2DSize;
GLint mMaxTextureCubeSize;
GLint mMaxRenderbufferSize;
};
TEST_P(MaxTextureSizeTest, SpecificationTexImage)
{
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLsizei textureWidth = mMaxTexture2DSize;
GLsizei textureHeight = 64;
std::vector<GLubyte> data(textureWidth * textureHeight * 4);
for (int y = 0; y < textureHeight; y++)
{
for (int x = 0; x < textureWidth; x++)
{
GLubyte* pixel = &data[0] + ((y * textureWidth + x) * 4);
// Draw a gradient, red in direction, green in y direction
pixel[0] = static_cast<GLubyte>((float(x) / textureWidth) * 255);
pixel[1] = static_cast<GLubyte>((float(y) / textureHeight) * 255);
pixel[2] = 0;
pixel[3] = 255;
}
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
EXPECT_GL_NO_ERROR();
glUseProgram(mTextureProgram);
glUniform1i(mTextureUniformLocation, 0);
drawQuad(mTextureProgram, "position", 0.5f);
std::vector<GLubyte> pixels(getWindowWidth() * getWindowHeight() * 4);
glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]);
for (int y = 1; y < getWindowHeight(); y++)
{
for (int x = 1; x < getWindowWidth(); x++)
{
const GLubyte* prevPixel = &pixels[0] + (((y - 1) * getWindowWidth() + (x - 1)) * 4);
const GLubyte* curPixel = &pixels[0] + ((y * getWindowWidth() + x) * 4);
EXPECT_GE(curPixel[0], prevPixel[0]);
EXPECT_GE(curPixel[1], prevPixel[1]);
EXPECT_EQ(curPixel[2], prevPixel[2]);
EXPECT_EQ(curPixel[3], prevPixel[3]);
}
}
}
TEST_P(MaxTextureSizeTest, SpecificationTexStorage)
{
if (getClientVersion() < 3 && (!extensionEnabled("GL_EXT_texture_storage") || !extensionEnabled("GL_OES_rgb8_rgba8")))
{
return;
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLsizei textureWidth = 64;
GLsizei textureHeight = mMaxTexture2DSize;
std::vector<GLubyte> data(textureWidth * textureHeight * 4);
for (int y = 0; y < textureHeight; y++)
{
for (int x = 0; x < textureWidth; x++)
{
GLubyte* pixel = &data[0] + ((y * textureWidth + x) * 4);
// Draw a gradient, red in direction, green in y direction
pixel[0] = static_cast<GLubyte>((float(x) / textureWidth) * 255);
pixel[1] = static_cast<GLubyte>((float(y) / textureHeight) * 255);
pixel[2] = 0;
pixel[3] = 255;
}
}
if (getClientVersion() < 3)
{
glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, textureWidth, textureHeight);
}
else
{
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8_OES, textureWidth, textureHeight);
}
EXPECT_GL_NO_ERROR();
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, textureWidth, textureHeight, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
EXPECT_GL_NO_ERROR();
glUseProgram(mTextureProgram);
glUniform1i(mTextureUniformLocation, 0);
drawQuad(mTextureProgram, "position", 0.5f);
std::vector<GLubyte> pixels(getWindowWidth() * getWindowHeight() * 4);
glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]);
for (int y = 1; y < getWindowHeight(); y++)
{
for (int x = 1; x < getWindowWidth(); x++)
{
const GLubyte* prevPixel = &pixels[0] + (((y - 1) * getWindowWidth() + (x - 1)) * 4);
const GLubyte* curPixel = &pixels[0] + ((y * getWindowWidth() + x) * 4);
EXPECT_GE(curPixel[0], prevPixel[0]);
EXPECT_GE(curPixel[1], prevPixel[1]);
EXPECT_EQ(curPixel[2], prevPixel[2]);
EXPECT_EQ(curPixel[3], prevPixel[3]);
}
}
}
TEST_P(MaxTextureSizeTest, RenderToTexture)
{
if (getClientVersion() < 3 && (!extensionEnabled("GL_ANGLE_framebuffer_blit")))
{
std::cout << "Test skipped due to missing glBlitFramebuffer[ANGLE] support." << std::endl;
return;
}
GLuint fbo = 0;
GLuint textureId = 0;
// create a 1-level texture at maximum size
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
GLsizei textureWidth = 64;
GLsizei textureHeight = mMaxTexture2DSize;
// texture setup code
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT, textureWidth, textureHeight, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, NULL);
EXPECT_GL_NO_ERROR();
// create an FBO and attach the texture
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0);
EXPECT_GL_NO_ERROR();
EXPECT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER));
const int frameCount = 64;
for (int i = 0; i < frameCount; i++)
{
// clear the screen
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLubyte clearRed = static_cast<GLubyte>((float(i) / frameCount) * 255);
GLubyte clearGreen = 255 - clearRed;
GLubyte clearBlue = 0;
glClearColor(clearRed / 255.0f, clearGreen / 255.0f, clearBlue / 255.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// render blue into the texture
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
drawQuad(mBlueProgram, "position", 0.5f);
// copy corner of texture to LL corner of window
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_ANGLE, 0);
glBindFramebuffer(GL_READ_FRAMEBUFFER_ANGLE, fbo);
glBlitFramebufferANGLE(0, 0, textureWidth - 1, getWindowHeight() - 1,
0, 0, textureWidth - 1, getWindowHeight() - 1,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_READ_FRAMEBUFFER_ANGLE, 0);
EXPECT_GL_NO_ERROR();
EXPECT_PIXEL_EQ(textureWidth / 2, getWindowHeight() / 2, 0, 0, 255, 255);
EXPECT_PIXEL_EQ(textureWidth + 10, getWindowHeight() / 2, clearRed, clearGreen, clearBlue, 255);
swapBuffers();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteFramebuffers(1, &fbo);
glDeleteTextures(1, &textureId);
}
// Use this to select which configurations (e.g. which renderer, which GLES major version) these tests should be run against.
ANGLE_INSTANTIATE_TEST(MaxTextureSizeTest, ES2_D3D9(), ES2_D3D11(), ES2_D3D11_FL9_3());
| crezefire/angle | src/tests/gl_tests/MaxTextureSizeTest.cpp | C++ | bsd-3-clause | 9,742 |
/*
* This file is a part of the open source stm32plus library.
* Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk>
* Please see website for licensing terms.
*/
#pragma once
namespace stm32plus {
namespace usb {
/**
* Template base class for USB CDC devices. The usual control endpoint 0 is inherited
* as is the mandatory IN interrupt endpoint for notifications to the host at address 1.
* Subclasses should provide the endpoints they require in the features list. e.g. bulk
* IN/OUT endpoints.
*
* @tparam TPhy the PHY implementation
* @tparam TConfigurationDescriptor A structure that holds the complete config descriptor
* @tparam Features... The device feature classes
*/
template<class TPhy> using CdcDeviceInterruptInEndpoint=InterruptInEndpointFeature<2,Device<TPhy>>;
template<class TPhy,class TConfigurationDescriptor,template <class> class... Features>
class CdcDevice : public Device<TPhy>,
public ControlEndpointFeature<Device<TPhy>>,
public CdcDeviceInterruptInEndpoint<TPhy>,
public Features<Device<TPhy>>... {
public:
/*
* Parameters for the CDC device
*/
struct Parameters : Device<TPhy>::Parameters,
ControlEndpointFeature<Device<TPhy>>::Parameters,
CdcDeviceInterruptInEndpoint<TPhy>::Parameters,
Features<Device<TPhy>>::Parameters... {
uint8_t cdc_cmd_poll_interval; // default is 16ms
uint8_t cdc_cmd_buffer_size; // default is 16 bytes
uint8_t cdc_cmd_max_ep_packet_size; // default is 16 bytes
Parameters() {
cdc_cmd_poll_interval=16;
cdc_cmd_buffer_size=16;
cdc_cmd_max_ep_packet_size=16;
}
};
protected:
enum {
COMMAND_EP_ADDRESS = EndpointDescriptor::IN | 2 // command endpoint address
};
TConfigurationDescriptor _configurationDescriptor;
CdcControlCommand _opCode;
uint8_t _commandSize;
scoped_array<uint8_t> _commandBuffer;
protected:
void onEvent(UsbEventDescriptor& event);
void onCdcSetup(DeviceClassSdkSetupEvent& event);
public:
CdcDevice();
~CdcDevice();
bool initialise(Parameters& params);
};
/**
* Constructor
*/
template<class TPhy,class TConfigurationDescriptor,template <class> class... Features>
inline CdcDevice<TPhy,TConfigurationDescriptor,Features...>::CdcDevice()
: ControlEndpointFeature<Device<TPhy>>(static_cast<Device<TPhy>&>(*this)),
CdcDeviceInterruptInEndpoint<TPhy>(static_cast<Device<TPhy>&>(*this)),
Features<Device<TPhy>>(static_cast<Device<TPhy>&>(*this))... {
// subscribe to USB events
this->UsbEventSender.insertSubscriber(
UsbEventSourceSlot::bind(this,&CdcDevice<TPhy,TConfigurationDescriptor,Features...>::onEvent)
);
}
/**
* Destructor
*/
template<class TPhy,class TConfigurationDescriptor,template <class> class... Features>
inline CdcDevice<TPhy,TConfigurationDescriptor,Features...>::~CdcDevice() {
// unsubscribe from USB events
this->UsbEventSender.removeSubscriber(
UsbEventSourceSlot::bind(this,&CdcDevice<TPhy,TConfigurationDescriptor,Features...>::onEvent)
);
}
/**
* Initialise the class
* @param params The parameters class
* @return true if it worked
*/
template<class TPhy,class TConfigurationDescriptor,template <class> class... Features>
inline bool CdcDevice<TPhy,TConfigurationDescriptor,Features...>::initialise(Parameters& params) {
// initialise upwards
if(!Device<TPhy>::initialise(params) ||
!ControlEndpointFeature<Device<TPhy>>::initialise(params) ||
!CdcDeviceInterruptInEndpoint<TPhy>::initialise(params) ||
!RecursiveBoolInitWithParams<CdcDevice,Features<Device<TPhy>>...>::tinit(this,params))
return false;
// create the command buffer
_commandBuffer.reset(new uint8_t[params.cdc_cmd_buffer_size]);
// set up the command endpoint descriptor
_configurationDescriptor.commandEndpoint.bEndpointAddress=COMMAND_EP_ADDRESS;
_configurationDescriptor.commandEndpoint.bmAttributes=EndpointDescriptor::INTERRUPT;
_configurationDescriptor.commandEndpoint.wMaxPacketSize=params.cdc_cmd_max_ep_packet_size;
_configurationDescriptor.commandEndpoint.bInterval=params.cdc_cmd_poll_interval; // default is 16ms
// link UsbEventSource class into the SDK structure
USBD_RegisterClass(&this->_deviceHandle,static_cast<UsbEventSource *>(this));
return true;
}
/**
* Event handler for device events
* @param event The event descriptor
*/
template<class TPhy,class TConfigurationDescriptor,template <class> class... Features>
__attribute__((noinline)) inline void CdcDevice<TPhy,TConfigurationDescriptor,Features...>::onEvent(UsbEventDescriptor& event) {
// check for handled events
switch(event.eventType) {
case UsbEventDescriptor::EventType::CLASS_INIT:
USBD_LL_OpenEP(&this->_deviceHandle,COMMAND_EP_ADDRESS,EndpointDescriptor::INTERRUPT,_configurationDescriptor.commandEndpoint.wMaxPacketSize);
break;
case UsbEventDescriptor::EventType::CLASS_DEINIT:
USBD_LL_CloseEP(&this->_deviceHandle,COMMAND_EP_ADDRESS);
break;
case UsbEventDescriptor::EventType::CLASS_SETUP:
onCdcSetup(static_cast<DeviceClassSdkSetupEvent&>(event));
break;
default:
break;
}
}
/**
* Handle the CDC setup requests
* @param event the event containg value being requested
*/
template<class TPhy,class TConfigurationDescriptor,template <class> class... Features>
inline void CdcDevice<TPhy,TConfigurationDescriptor,Features...>::onCdcSetup(DeviceClassSdkSetupEvent& event) {
// interested in class requests
if((event.request.bmRequest & USB_REQ_TYPE_MASK)!=USB_REQ_TYPE_CLASS)
return;
if(event.request.wLength) {
if((event.request.bmRequest & 0x80)!=0) {
// raise the control event - this one requires a response
this->UsbEventSender.raiseEvent(
CdcControlEvent(static_cast<CdcControlCommand>(event.request.bRequest),
_commandBuffer.get(),
event.request.wLength)
);
// send the response message on the control endpoint
USBD_CtlSendData(&this->_deviceHandle,_commandBuffer.get(),event.request.wLength);
}
else {
// there is incoming data associated with this
_opCode=static_cast<CdcControlCommand>(event.request.bRequest);
_commandSize=event.request.wLength;
USBD_CtlPrepareRx(&this->_deviceHandle,_commandBuffer.get(),_commandSize);
}
}
else {
// raise the control event - no response is expected
this->UsbEventSender.raiseEvent(
CdcControlEvent(
static_cast<CdcControlCommand>(event.request.bRequest),
nullptr,
0));
}
}
}
}
| punkkeks/stm32plus | lib/include/usb/f4/device/cdc/CdcDevice.h | C | bsd-3-clause | 7,434 |
/*
* Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved.
* Copyright (C) 2006 Alexey Proskuryakov <ap@nypop.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TextCodec_h
#define TextCodec_h
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
#include "wtf/unicode/Unicode.h"
namespace WTF {
class TextEncoding;
// Specifies what will happen when a character is encountered that is
// not encodable in the character set.
enum UnencodableHandling {
// Substitutes the replacement character "?".
QuestionMarksForUnencodables,
// Encodes the character as an XML entity. For example, U+06DE
// would be "۞" (0x6DE = 1758 in octal).
EntitiesForUnencodables,
// Encodes the character as en entity as above, but escaped
// non-alphanumeric characters. This is used in URLs.
// For example, U+6DE would be "%26%231758%3B".
URLEncodedEntitiesForUnencodables
};
typedef char UnencodableReplacementArray[32];
enum FlushBehavior {
// More bytes are coming, don't flush the codec.
DoNotFlush = 0,
// A fetch has hit EOF. Some codecs handle fetches differently, for compat reasons.
FetchEOF,
// Do a full flush of the codec.
DataEOF
};
static_assert(!DoNotFlush, "DoNotFlush should be falsy");
static_assert(FetchEOF, "FetchEOF should be truthy");
static_assert(DataEOF, "DataEOF should be truthy");
class TextCodec {
WTF_MAKE_NONCOPYABLE(TextCodec); WTF_MAKE_FAST_ALLOCATED;
public:
TextCodec() { }
virtual ~TextCodec();
String decode(const char* str, size_t length, FlushBehavior flush = DoNotFlush)
{
bool ignored;
return decode(str, length, flush, false, ignored);
}
virtual String decode(const char*, size_t length, FlushBehavior, bool stopOnError, bool& sawError) = 0;
virtual CString encode(const UChar*, size_t length, UnencodableHandling) = 0;
virtual CString encode(const LChar*, size_t length, UnencodableHandling) = 0;
// Fills a null-terminated string representation of the given
// unencodable character into the given replacement buffer.
// The length of the string (not including the null) will be returned.
static int getUnencodableReplacement(unsigned codePoint, UnencodableHandling, UnencodableReplacementArray);
};
typedef void (*EncodingNameRegistrar)(const char* alias, const char* name);
typedef PassOwnPtr<TextCodec> (*NewTextCodecFunction)(const TextEncoding&, const void* additionalData);
typedef void (*TextCodecRegistrar)(const char* name, NewTextCodecFunction, const void* additionalData);
} // namespace WTF
using WTF::TextCodec;
#endif // TextCodec_h
| sgraham/nope | third_party/WebKit/Source/wtf/text/TextCodec.h | C | bsd-3-clause | 3,960 |
module StrategoAST2(module AST) where
import StrategoPattern as AST
import StrategoTerm as AST
import StrategoType as AST
import StrategoProp as AST
import StrategoDecl as AST
| forste/haReFork | tools/hs2stratego/AST/StrategoAST2.hs | Haskell | bsd-3-clause | 176 |
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class vtkRuledSurfaceFilter(SimpleVTKClassModuleBase):
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkRuledSurfaceFilter(), 'Processing.',
('vtkPolyData',), ('vtkPolyData',),
replaceDoc=True,
inputFunctions=None, outputFunctions=None)
| nagyistoce/devide | modules/vtk_basic/vtkRuledSurfaceFilter.py | Python | bsd-3-clause | 497 |
gRPC C#
=======
A C# implementation of gRPC.
Status
------
Alpha : Ready for early adopters.
Usage: Windows
--------------
- Prerequisites: .NET Framework 4.5+, Visual Studio 2013 with NuGet extension installed (VS2015 should work).
- Open Visual Studio and start a new project/solution.
- Add NuGet package `Grpc` as a dependency (Project options -> Manage NuGet Packages).
That will also pull all the transitive dependencies (including the native libraries that
gRPC C# is internally using).
- Helloworld project example can be found in https://github.com/grpc/grpc/tree/master/examples/csharp.
Usage: Linux (Mono)
--------------
- Prerequisites: Mono 3.2.8+, MonoDevelop 5.9 with NuGet add-in installed.
- Install Linuxbrew and gRPC C Core using instructions in https://github.com/grpc/homebrew-grpc
- gRPC C# depends on native shared library libgrpc_csharp_ext.so (Unix flavor of grpc_csharp_ext.dll).
This library will be installed to `~/.linuxbrew/lib` by the previous step.
To make it visible to mono, you need to:
- (preferred approach) add `libgrpc_csharp_ext.so` to `/etc/ld.so.cache` by running:
```sh
$ echo "$HOME/.linuxbrew/lib" | sudo tee /etc/ld.so.conf.d/zzz_brew_lib.conf
$ sudo ldconfig
```
- (adhoc approach) set `LD_LIBRARY_PATH` environment variable to point to directory containing `libgrpc_csharp_ext.so`:
```sh
$ export LD_LIBRARY_PATH=$HOME/.linuxbrew/lib:${LD_LIBRARY_PATH}
```
- (if you are contributor) installing gRPC from sources using `sudo make install_grpc_csharp_ext` also works.
- Open MonoDevelop and start a new project/solution.
- Add NuGet package `Grpc` as a dependency (Project -> Add NuGet packages).
- Helloworld project example can be found in https://github.com/grpc/grpc/tree/master/examples/csharp.
Usage: MacOS (Mono)
--------------
- WARNING: As of now gRPC C# only works on 64bit version of Mono (because we don't compile
the native extension for C# in 32bit mode yet). That means your development experience
with Xamarin Studio on MacOS will not be great, as you won't be able to run your
code directly from Xamarin Studio (which requires 32bit version of Mono).
- Prerequisites: Xamarin Studio with NuGet add-in installed.
- Install Homebrew and gRPC C Core using instructions in https://github.com/grpc/homebrew-grpc
- Install 64-bit version of mono with command `brew install mono` (assumes you've already installed Homebrew).
- Open Xamarin Studio and start a new project/solution.
- Add NuGet package `Grpc` as a dependency (Project -> Add NuGet packages).
- *You will be able to build your project in Xamarin Studio, but to run or test it,
you will need to run it under 64-bit version of Mono.*
- Helloworld project example can be found in https://github.com/grpc/grpc/tree/master/examples/csharp.
Building: Windows
-----------------
You only need to go through these steps if you are planning to develop gRPC C#.
If you are a user of gRPC C#, go to Usage section above.
- Prerequisites for development: NET Framework 4.5+, Visual Studio 2013 (with NuGet and NUnit extensions installed).
- The grpc_csharp_ext native library needs to be built so you can build the Grpc C# solution. You can
either build the native solution in `vsprojects/grpc.sln` from Visual Studio manually, or you can use
a convenience batch script that builds everything for you.
```
> buildall.bat
```
- Open Grpc.sln using Visual Studio 2013. NuGet dependencies will be restored
upon build (you need to have NuGet add-in installed).
Building: Linux (Mono)
----------------------
You only need to go through these steps if you are planning to develop gRPC C#.
If you are a user of gRPC C#, go to Usage section above.
- Prerequisites for development: Mono 3.2.8+, MonoDevelop 5.9 with NuGet and NUnit add-ins installed.
```sh
$ sudo apt-get install mono-devel
$ sudo apt-get install nunit nunit-console
```
You can use older versions of MonoDevelop, but then you might need to restore
NuGet dependencies manually (by `nuget restore`), because older versions of MonoDevelop
don't support NuGet add-in.
- Compile and install the gRPC C# extension library (that will be used via
P/Invoke from C#).
```sh
$ make grpc_csharp_ext
$ sudo make install_grpc_csharp_ext
```
- Use MonoDevelop to open the solution Grpc.sln
- Build the solution & run all the tests from test view.
Tests
-----
gRPC C# is using NUnit as the testing framework.
Under Visual Studio, make sure NUnit test adapter is installed (under "Extensions and Updates").
Then you should be able to run all the tests using Test Explorer.
Under Monodevelop, make sure you installed "NUnit support" in Add-in manager.
Then you should be able to run all the test from the Test View.
After building the solution, you can also run the tests from command line
using nunit-console tool.
```sh
# from Grpc.Core.Test/bin/Debug directory
$ nunit-console Grpc.Core.Tests.dll
```
Contents
--------
- ext:
The extension library that wraps C API to be more digestible by C#.
- Grpc.Auth:
gRPC OAuth2 support.
- Grpc.Core:
The main gRPC C# library.
- Grpc.Examples:
API examples for math.proto
- Grpc.Examples.MathClient:
An example client that sends some requests to math server.
- Grpc.Examples.MathServer:
An example client that sends some requests to math server.
- Grpc.IntegrationTesting:
Cross-language gRPC implementation testing (interop testing).
Troubleshooting
---------------
### Problem: Unable to load DLL 'grpc_csharp_ext.dll'
Internally, gRPC C# uses a native library written in C (gRPC C core) and invokes its functionality via P/Invoke. `grpc_csharp_ext` library is a native extension library that facilitates this by wrapping some C core API into a form that's more digestible for P/Invoke. If you get the above error, it means that the native dependencies could not be located by the C# runtime (or they are incompatible with the current runtime, so they could not be loaded). The solution to this is environment specific.
- If you are developing on Windows in Visual Studio, the `grpc_csharp_ext.dll` that is shipped by gRPC nuget packages should be automatically copied to your build destination folder once you build. By adjusting project properties in your VS project file, you can influence which exact configuration of `grpc_csharp_ext.dll` will be used (based on VS version, bitness, debug/release configuration).
- If you are running your application that is using gRPC on Windows machine that doesn't have Visual Studio installed, you might need to install [Visual C++ 2013 redistributable](https://www.microsoft.com/en-us/download/details.aspx?id=40784) that contains some system .dll libraries that `grpc_csharp_ext.dll` depends on (see #905 for more details).
- On Linux (or Docker), you need to first install gRPC C core and `libgrpc_csharp_ext.so` shared libraries. Currently, the libraries can be installed by `make install_grpc_csharp_ext` or using Linuxbrew (a Debian package is coming soon). Installation on a machine where your application is going to be deployed is no different.
- On Mac, you need to first install gRPC C core and `libgrpc_csharp_ext.dylib` shared libraries using Homebrew. See above for installation instruction. Installation on a machine where your application is going to be deployed is no different.
- Possible cause for the problem is that the `grpc_csharp_ext` library is installed, but it has different bitness (32/64bit) than your C# runtime (in case you are using mono) or C# application.
| ofrobots/grpc | src/csharp/README.md | Markdown | bsd-3-clause | 7,582 |
# Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.internal.app import possible_app
class PossibleBrowser(possible_app.PossibleApp):
"""A browser that can be controlled.
Call Create() to launch the browser and begin manipulating it..
"""
def __init__(self, browser_type, target_os, supports_tab_control):
super(PossibleBrowser, self).__init__(app_type=browser_type,
target_os=target_os)
self._supports_tab_control = supports_tab_control
self._credentials_path = None
def __repr__(self):
return 'PossibleBrowser(app_type=%s)' % self.app_type
@property
def browser_type(self):
return self.app_type
@property
def supports_tab_control(self):
return self._supports_tab_control
def _InitPlatformIfNeeded(self):
raise NotImplementedError()
def Create(self, finder_options):
raise NotImplementedError()
def SupportsOptions(self, browser_options):
"""Tests for extension support."""
raise NotImplementedError()
def IsRemote(self):
return False
def RunRemote(self):
pass
def UpdateExecutableIfNeeded(self):
pass
def last_modification_time(self):
return -1
def SetCredentialsPath(self, credentials_path):
self._credentials_path = credentials_path
| catapult-project/catapult-csm | telemetry/telemetry/internal/browser/possible_browser.py | Python | bsd-3-clause | 1,414 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_API_SYSTEM_DISPLAY_DISPLAY_INFO_PROVIDER_H_
#define EXTENSIONS_BROWSER_API_SYSTEM_DISPLAY_DISPLAY_INFO_PROVIDER_H_
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/memory/linked_ptr.h"
namespace gfx {
class Display;
class Screen;
}
namespace extensions {
namespace api {
namespace system_display {
struct DisplayProperties;
struct DisplayUnitInfo;
}
}
typedef std::vector<linked_ptr<api::system_display::DisplayUnitInfo>>
DisplayInfo;
class DisplayInfoProvider {
public:
virtual ~DisplayInfoProvider();
// Returns a pointer to DisplayInfoProvider or NULL if Create()
// or InitializeForTesting() or not called yet.
static DisplayInfoProvider* Get();
// This is for tests that run in its own process (e.g. browser_tests).
// Using this in other tests (e.g. unit_tests) will result in DCHECK failure.
static void InitializeForTesting(DisplayInfoProvider* display_info_provider);
// Updates the display with |display_id| according to |info|. Returns whether
// the display was successfully updated. On failure, no display parameters
// should be changed, and |error| should be set to the error string.
virtual bool SetInfo(const std::string& display_id,
const api::system_display::DisplayProperties& info,
std::string* error) = 0;
// Get the screen that is always active, which will be used for monitoring
// display changes events.
virtual gfx::Screen* GetActiveScreen() = 0;
// Enable the unified desktop feature.
virtual void EnableUnifiedDesktop(bool enable);
DisplayInfo GetAllDisplaysInfo();
protected:
DisplayInfoProvider();
private:
static DisplayInfoProvider* Create();
// Update the content of the |unit| obtained for |display| using
// platform specific method.
virtual void UpdateDisplayUnitInfoForPlatform(
const gfx::Display& display,
api::system_display::DisplayUnitInfo* unit) = 0;
DISALLOW_COPY_AND_ASSIGN(DisplayInfoProvider);
};
} // namespace extensions
#endif // EXTENSIONS_BROWSER_API_SYSTEM_DISPLAY_DISPLAY_INFO_PROVIDER_H_
| Chilledheart/chromium | extensions/browser/api/system_display/display_info_provider.h | C | bsd-3-clause | 2,296 |
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Implements a standard mechanism for Chrome Infra Python environment setup.
This library provides a central location to define Chrome Infra environment
setup. It also provides several faculties to install this environment.
Within a cooperating script, the environment can be setup by importing this
module and running its 'Install' method:
# Install Chrome-Infra environment (replaces 'sys.path').
sys.path.insert(0,
os.path.join(os.path.dirname(__file__), os.pardir, ...))
# (/path/to/build/scripts)
import common.env
common.env.Install()
When attempting to export the Chrome Infra path to external scripts, this
script can be invoked as an executable with various subcommands to emit a valid
PYTHONPATH clause.
In addition, this module has several functions to construct the path.
The goal is to deploy this module universally among Chrome-Infra scripts,
BuildBot configurations, tool invocations, and tests to ensure that they all
execute with the same centrally-defined environment.
"""
import argparse
import collections
import contextlib
import imp
import itertools
import os
import sys
import traceback
# Export for bootstrapping.
__all__ = [
'Install',
'PythonPath',
]
# Name of enviornment extension file to seek.
ENV_EXTENSION_NAME = 'environment.cfg.py'
# Standard directories (based on this file's location in the <build> tree).
def path_if(*args):
if not all(args):
return None
path = os.path.abspath(os.path.join(*args))
return (path) if os.path.exists(path) else (None)
# The path to the <build> directory in which this script resides.
Build = path_if(os.path.dirname(__file__), os.pardir, os.pardir)
# The path to the <build_internal> directory.
BuildInternal = path_if(Build, os.pardir, 'build_internal')
def SetPythonPathEnv(value):
"""Sets the system's PYTHONPATH environemnt variable.
Args:
value (str): The value to use. If this is empty/None, the system's
PYTHONPATH will be cleared.
"""
# Since we can't assign None to the environment "dictionary", we have to
# either set or delete the key depending on the original value.
if value is not None:
os.environ['PYTHONPATH'] = str(value)
else:
os.environ.pop('PYTHONPATH', None)
def Install(**kwargs):
"""Replaces the current 'sys.path' with a hermetic Chrome-Infra path.
Args:
kwargs (dict): See GetInfraPythonPath arguments.
Returns (PythonPath): The PythonPath object that was installed.
"""
infra_python_path = GetInfraPythonPath(**kwargs)
infra_python_path.Install()
return infra_python_path
def SplitPath(path):
"""Returns (list): A list of path elements.
Splits a path into path elements. For example (assuming '/' is the local
system path separator):
>>> print SplitPath('/a/b/c/d')
['/', 'a', 'b', 'c', 'd']
>>> print SplitPath('a/b/c')
['a', 'b,' 'c']
"""
parts = []
while True:
path, component = os.path.split(path)
if not component:
if path:
parts.append(path)
break
parts.append(component)
parts.reverse()
return parts
def ExtendPath(base, root_dir):
"""Returns (PythonPath): The extended python path.
This method looks for the ENV_EXTENSION_NAME file within "root_dir". If
present, it will be loaded as a Python module and have its "Extend" method
called.
If no extension is found, the base PythonPath will be returned.
Args:
base (PythonPath): The base python path.
root_dir (str): The path to check for an extension.
"""
extension_path = os.path.join(root_dir, ENV_EXTENSION_NAME)
if not os.path.isfile(extension_path):
return base
with open(extension_path, 'r') as fd:
extension = fd.read()
extension_module = imp.new_module('env-extension')
# Execute the enviornment extension.
try:
exec extension in extension_module.__dict__
extend_func = getattr(extension_module, 'Extend', None)
assert extend_func, (
"The environment extension module is missing the 'Extend()' method.")
base = extend_func(base, root_dir)
if not isinstance(base, PythonPath):
raise TypeError("Extension module returned non-PythonPath object (%s)" % (
type(base).__name__,))
except Exception:
# Re-raise the exception, but include the configuration file name.
tb = traceback.format_exc()
raise RuntimeError("Environment extension [%s] raised exception: %s" % (
extension_path, tb))
return base
def IsSystemPythonPath(path):
"""Returns (bool): If a python path is user-installed.
Paths that are known to be user-installed paths can be ignored when setting
up a hermetic Python path environment to avoid user libraries that would not
be present in other environments falsely affecting code.
This function can be updated as-needed to exclude other non-system paths
encountered on bots and in the wild.
"""
components = SplitPath(path)
for component in components:
if component in ('dist-packages', 'site-packages'):
return False
return True
class PythonPath(collections.Sequence):
"""An immutable set of Python path elements.
All paths represented in this structure are absolute. If a relative path
is passed into this structure, it will be converted to absolute based on
the current working directory (via os.path.abspath).
"""
def __init__(self, components=None):
"""Initializes a new PythonPath instance.
Args:
components (list): A list of path component strings.
"""
seen = set()
self._components = []
for component in (components or ()):
component = os.path.abspath(component)
assert isinstance(component, basestring), (
"Path component '%s' is not a string (%s)" % (
component, type(component).__name__))
if component in seen:
continue
seen.add(component)
self._components.append(component)
def __getitem__(self, value):
return self._components[value]
def __len__(self):
return len(self._components)
def __iadd__(self, other):
return self.Append(other)
def __repr__(self):
return self.pathstr
def __eq__(self, other):
assert isinstance(other, type(self))
return self._components == other._components
@classmethod
def Flatten(cls, *paths):
"""Returns (list): A single-level list containing flattened path elements.
>>> print PythonPath.Flatten('a', ['b', ['c', 'd']])
['a', 'b', 'c', 'd']
"""
result = []
for path in paths:
if not isinstance(path, basestring):
# Assume it's an iterable of paths.
result += cls.Flatten(*path)
else:
result.append(path)
return result
@classmethod
def FromPaths(cls, *paths):
"""Returns (PythonPath): A PythonPath instantiated from path elements.
Args:
paths (tuple): A tuple of path elements or iterables containing path
elements (e.g., PythonPath instances).
"""
return cls(cls.Flatten(*paths))
@classmethod
def FromPathStr(cls, pathstr):
"""Returns (PythonPath): A PythonPath instantiated from the path string.
Args:
pathstr (str): An os.pathsep()-delimited path string.
"""
return cls(pathstr.split(os.pathsep))
@property
def pathstr(self):
"""Returns (str): A path string for the instance's path elements."""
return os.pathsep.join(self)
def IsHermetic(self):
"""Returns (bool): True if this instance contains only system paths."""
return all(IsSystemPythonPath(p) for p in self)
def GetHermetic(self):
"""Returns (PythonPath): derivative PythonPath containing only system paths.
"""
return type(self).FromPaths(*(p for p in self if IsSystemPythonPath(p)))
def Append(self, *paths):
"""Returns (PythonPath): derivative PythonPath with paths added to the end.
Args:
paths (tuple): A tuple of path elements to append to the current instance.
"""
return type(self)(itertools.chain(self, self.FromPaths(*paths)))
def Override(self, *paths):
"""Returns (PythonPath): derivative PythonPath with paths prepended.
Args:
paths (tuple): A tuple of path elements to prepend to the current
instance.
"""
return self.FromPaths(*paths).Append(self)
def Install(self):
"""Overwrites Python runtime variables based on the current instance.
Performs the following operations:
- Replaces sys.path with the current instance's path.
- Replaces os.environ['PYTHONPATH'] with the current instance's path
string.
"""
sys.path = list(self)
SetPythonPathEnv(self.pathstr)
@contextlib.contextmanager
def Enter(self):
"""Context manager wrapper for Install.
On exit, the context manager will restore the original environment.
"""
orig_sys_path = sys.path[:]
orig_pythonpath = os.environ.get('PYTHONPATH')
try:
self.Install()
yield
finally:
sys.path = orig_sys_path
SetPythonPathEnv(orig_pythonpath)
def GetSysPythonPath(hermetic=True):
"""Returns (PythonPath): A path based on 'sys.path'.
Args:
hermetic (bool): If True, prune any non-system path.
"""
path = PythonPath.FromPaths(*sys.path)
if hermetic:
path = path.GetHermetic()
return path
def GetEnvPythonPath():
"""Returns (PythonPath): A path based on the PYTHONPATH environment variable.
"""
pythonpath = os.environ.get('PYTHONPATH')
if not pythonpath:
return PythonPath.FromPaths()
return PythonPath.FromPathStr(pythonpath)
def GetMasterPythonPath(master_dir):
"""Returns (PythonPath): A path including a BuildBot master's directory.
Args:
master_dir (str): The BuildBot master root directory.
"""
return PythonPath.FromPaths(master_dir)
def GetBuildPythonPath():
"""Returns (PythonPath): The Chrome Infra build path."""
build_path = PythonPath.FromPaths()
for extension_dir in (
Build,
BuildInternal,
):
if extension_dir:
build_path = ExtendPath(build_path, extension_dir)
return build_path
def GetInfraPythonPath(hermetic=True, master_dir=None):
"""Returns (PythonPath): The full working Chrome Infra utility path.
This path is consistent for master, slave, and tool usage. It includes (in
this order):
- Any environment PYTHONPATH overrides.
- If 'master_dir' is supplied, the master's python path component.
- The Chrome Infra build path.
- The system python path.
Args:
hermetic (bool): True, prune any non-system path from the system path.
master_dir (str): If not None, include a master path component.
"""
path = GetEnvPythonPath()
if master_dir:
path += GetMasterPythonPath(master_dir)
path += GetBuildPythonPath()
path += GetSysPythonPath(hermetic=hermetic)
return path
def _InfraPathFromArgs(args):
"""Returns (PythonPath): A PythonPath populated from command-line arguments.
Args:
args (argparse.Namespace): The command-line arguments constructed by 'main'.
"""
return GetInfraPythonPath(
master_dir=args.master_dir,
)
def _Command_Echo(args, path):
"""Returns (int): Return code.
Command function for the 'echo' subcommand. Outputs the path string for
'path'.
Args:
args (argparse.Namespace): The command-line arguments constructed by 'main'.
path (PythonPath): The python path to use.
"""
args.output.write(path.pathstr)
return 0
def _Command_Print(args, path):
"""Returns (int): Return code.
Command function for the 'print' subcommand. Outputs each path component in
path on a separate line.
Args:
args (argparse.Namespace): The command-line arguments constructed by 'main'.
path (PythonPath): The python path to use.
"""
for component in path:
print >>args.output, component
return 0
def main():
"""Main execution function."""
parser = argparse.ArgumentParser()
parser.add_argument('-M', '--master_dir',
help="Augment the path with the master's directory.")
parser.add_argument('-o', '--output', metavar='PATH',
type=argparse.FileType('w'), default='-',
help="File to output to (use '-' for STDOUT).")
subparsers = parser.add_subparsers()
# 'echo'
subparser = subparsers.add_parser('echo')
subparser.set_defaults(func=_Command_Echo)
# 'print'
subparser = subparsers.add_parser('print')
subparser.set_defaults(func=_Command_Print)
# Parse
args = parser.parse_args()
# Execute our subcommand function, which will return the exit code.
path = _InfraPathFromArgs(args)
return args.func(args, path)
if __name__ == '__main__':
sys.exit(main())
| hgl888/chromium-crosswalk | infra/scripts/legacy/scripts/common/env.py | Python | bsd-3-clause | 12,777 |
#!/usr/bin/env python
from translate.convert import xliff2po
from translate.misc import wStringIO
from translate.storage.test_base import headerless_len, first_translatable
class TestXLIFF2PO:
xliffskeleton = '''<?xml version="1.0" ?>
<xliff version="1.1" xmlns="urn:oasis:names:tc:xliff:document:1.1">
<file original="filename.po" source-language="en-US" datatype="po">
<body>
%s
</body>
</file>
</xliff>'''
def xliff2po(self, xliffsource):
"""helper that converts xliff source to po source without requiring files"""
inputfile = wStringIO.StringIO(xliffsource)
convertor = xliff2po.xliff2po()
outputpo = convertor.convertstore(inputfile)
print "The generated po:"
print type(outputpo)
print str(outputpo)
return outputpo
def test_minimal(self):
minixlf = self.xliffskeleton % '''<trans-unit>
<source>red</source>
<target>rooi</target>
</trans-unit>'''
pofile = self.xliff2po(minixlf)
assert headerless_len(pofile.units) == 1
assert pofile.translate("red") == "rooi"
assert pofile.translate("bla") is None
def test_basic(self):
headertext = '''Project-Id-Version: program 2.1-branch
Report-Msgid-Bugs-To:
POT-Creation-Date: 2006-01-09 07:15+0100
PO-Revision-Date: 2004-03-30 17:02+0200
Last-Translator: Zuza Software Foundation <xxx@translate.org.za>
Language-Team: Afrikaans <translate-discuss-xxx@lists.sourceforge.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit'''
minixlf = (self.xliffskeleton % '''<trans-unit id="1" restype="x-gettext-domain-header" approved="no" xml:space="preserve">
<source>%s</source>
<target>%s</target>
<note from="po-translator">Zulu translation of program ABC</note>
</trans-unit>
<trans-unit>
<source>gras</source>
<target>utshani</target>
</trans-unit>''') % (headertext, headertext)
print minixlf
pofile = self.xliff2po(minixlf)
assert pofile.translate("gras") == "utshani"
assert pofile.translate("bla") is None
potext = str(pofile)
assert potext.index('# Zulu translation of program ABC') == 0
assert potext.index('msgid "gras"\n')
assert potext.index('msgstr "utshani"\n')
assert potext.index('MIME-Version: 1.0\\n')
def test_translatorcomments(self):
"""Tests translator comments"""
minixlf = self.xliffskeleton % '''<trans-unit>
<source>nonsense</source>
<target>matlhapolosa</target>
<context-group name="po-entry" purpose="information">
<context context-type="x-po-trancomment">Couldn't do
it</context>
</context-group>
<note from="po-translator">Couldn't do
it</note>
</trans-unit>'''
pofile = self.xliff2po(minixlf)
assert pofile.translate("nonsense") == "matlhapolosa"
assert pofile.translate("bla") is None
unit = first_translatable(pofile)
assert unit.getnotes("translator") == "Couldn't do it"
potext = str(pofile)
assert potext.index("# Couldn't do it\n") >= 0
minixlf = self.xliffskeleton % '''<trans-unit xml:space="preserve">
<source>nonsense</source>
<target>matlhapolosa</target>
<context-group name="po-entry" purpose="information">
<context context-type="x-po-trancomment">Couldn't do
it</context>
</context-group>
<note from="po-translator">Couldn't do
it</note>
</trans-unit>'''
pofile = self.xliff2po(minixlf)
assert pofile.translate("nonsense") == "matlhapolosa"
assert pofile.translate("bla") is None
unit = first_translatable(pofile)
assert unit.getnotes("translator") == "Couldn't do\nit"
potext = str(pofile)
assert potext.index("# Couldn't do\n# it\n") >= 0
def test_autocomment(self):
"""Tests automatic comments"""
minixlf = self.xliffskeleton % '''<trans-unit>
<source>nonsense</source>
<target>matlhapolosa</target>
<context-group name="po-entry" purpose="information">
<context context-type="x-po-autocomment">Note that this is
garbage</context>
</context-group>
<note from="developer">Note that this is
garbage</note>
</trans-unit>'''
pofile = self.xliff2po(minixlf)
assert pofile.translate("nonsense") == "matlhapolosa"
assert pofile.translate("bla") is None
unit = first_translatable(pofile)
assert unit.getnotes("developer") == "Note that this is garbage"
potext = str(pofile)
assert potext.index("#. Note that this is garbage\n") >= 0
minixlf = self.xliffskeleton % '''<trans-unit xml:space="preserve">
<source>nonsense</source>
<target>matlhapolosa</target>
<context-group name="po-entry" purpose="information">
<context context-type="x-po-autocomment">Note that this is
garbage</context>
</context-group>
<note from="developer">Note that this is
garbage</note>
</trans-unit>'''
pofile = self.xliff2po(minixlf)
assert pofile.translate("nonsense") == "matlhapolosa"
assert pofile.translate("bla") is None
unit = first_translatable(pofile)
assert unit.getnotes("developer") == "Note that this is\ngarbage"
potext = str(pofile)
assert potext.index("#. Note that this is\n#. garbage\n") >= 0
def test_locations(self):
"""Tests location comments (#:)"""
minixlf = self.xliffskeleton % '''<trans-unit id="1">
<source>nonsense</source>
<target>matlhapolosa</target>
<context-group name="po-reference" purpose="location">
<context context-type="sourcefile">example.c</context>
<context context-type="linenumber">123</context>
</context-group>
<context-group name="po-reference" purpose="location">
<context context-type="sourcefile">place.py</context>
</context-group>
</trans-unit>'''
pofile = self.xliff2po(minixlf)
assert pofile.translate("nonsense") == "matlhapolosa"
assert pofile.translate("bla") is None
unit = first_translatable(pofile)
locations = unit.getlocations()
assert len(locations) == 2
assert "example.c:123" in locations
assert "place.py" in locations
def test_fuzzy(self):
"""Tests fuzzyness"""
minixlf = self.xliffskeleton % '''<trans-unit approved="no">
<source>book</source>
</trans-unit>
<trans-unit id="2" approved="yes">
<source>nonsense</source>
<target>matlhapolosa</target>
</trans-unit>
<trans-unit id="2" approved="no">
<source>verb</source>
<target state="needs-review-translation">lediri</target>
</trans-unit>'''
pofile = self.xliff2po(minixlf)
assert pofile.translate("nonsense") == "matlhapolosa"
assert pofile.translate("verb") == "lediri"
assert pofile.translate("book") is None
assert pofile.translate("bla") is None
assert headerless_len(pofile.units) == 3
#TODO: decide if this one should be fuzzy:
#assert pofile.units[0].isfuzzy()
assert not pofile.units[2].isfuzzy()
assert pofile.units[3].isfuzzy()
def test_plurals(self):
"""Tests fuzzyness"""
minixlf = self.xliffskeleton % '''<group id="1" restype="x-gettext-plurals">
<trans-unit id="1[0]" xml:space="preserve">
<source>cow</source>
<target>inkomo</target>
</trans-unit>
<trans-unit id="1[1]" xml:space="preserve">
<source>cows</source>
<target>iinkomo</target>
</trans-unit>
</group>'''
pofile = self.xliff2po(minixlf)
print str(pofile)
potext = str(pofile)
assert headerless_len(pofile.units) == 1
assert potext.index('msgid_plural "cows"')
assert potext.index('msgstr[0] "inkomo"')
assert potext.index('msgstr[1] "iinkomo"')
class TestBasicXLIFF2PO(TestXLIFF2PO):
"""This tests a basic XLIFF file without xmlns attribute"""
xliffskeleton = '''<?xml version="1.0" ?>
<xliff version="1.1">
<file original="filename.po" source-language="en-US" datatype="po">
<body>
%s
</body>
</file>
</xliff>'''
| dbbhattacharya/kitsune | vendor/packages/translate-toolkit/translate/convert/test_xliff2po.py | Python | bsd-3-clause | 8,448 |
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2002-2013, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
// GENERATED CODE: DO NOT EDIT. See scala.Function0 for timestamp.
package scala
object Product17 {
def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17](x: Product17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17]): Option[Product17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17]] =
Some(x)
}
/** Product17 is a Cartesian product of 17 components.
* @since 2.3
*/
trait Product17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17] extends Any with Product {
/** The arity of this product.
* @return 17
*/
override def productArity = 17
/** Returns the n-th projection of this product if 0 <= n < productArity,
* otherwise throws an `IndexOutOfBoundsException`.
*
* @param n number of the projection to be returned
* @return same as `._(n+1)`, for example `productElement(0)` is the same as `._1`.
* @throws IndexOutOfBoundsException
*/
@throws(classOf[IndexOutOfBoundsException])
override def productElement(n: Int) = n match {
case 0 => _1
case 1 => _2
case 2 => _3
case 3 => _4
case 4 => _5
case 5 => _6
case 6 => _7
case 7 => _8
case 8 => _9
case 9 => _10
case 10 => _11
case 11 => _12
case 12 => _13
case 13 => _14
case 14 => _15
case 15 => _16
case 16 => _17
case _ => throw new IndexOutOfBoundsException(n.toString())
}
/** A projection of element 1 of this Product.
* @return A projection of element 1.
*/
def _1: T1
/** A projection of element 2 of this Product.
* @return A projection of element 2.
*/
def _2: T2
/** A projection of element 3 of this Product.
* @return A projection of element 3.
*/
def _3: T3
/** A projection of element 4 of this Product.
* @return A projection of element 4.
*/
def _4: T4
/** A projection of element 5 of this Product.
* @return A projection of element 5.
*/
def _5: T5
/** A projection of element 6 of this Product.
* @return A projection of element 6.
*/
def _6: T6
/** A projection of element 7 of this Product.
* @return A projection of element 7.
*/
def _7: T7
/** A projection of element 8 of this Product.
* @return A projection of element 8.
*/
def _8: T8
/** A projection of element 9 of this Product.
* @return A projection of element 9.
*/
def _9: T9
/** A projection of element 10 of this Product.
* @return A projection of element 10.
*/
def _10: T10
/** A projection of element 11 of this Product.
* @return A projection of element 11.
*/
def _11: T11
/** A projection of element 12 of this Product.
* @return A projection of element 12.
*/
def _12: T12
/** A projection of element 13 of this Product.
* @return A projection of element 13.
*/
def _13: T13
/** A projection of element 14 of this Product.
* @return A projection of element 14.
*/
def _14: T14
/** A projection of element 15 of this Product.
* @return A projection of element 15.
*/
def _15: T15
/** A projection of element 16 of this Product.
* @return A projection of element 16.
*/
def _16: T16
/** A projection of element 17 of this Product.
* @return A projection of element 17.
*/
def _17: T17
}
| felixmulder/scala | src/library/scala/Product17.scala | Scala | bsd-3-clause | 3,941 |
<!DOCTYPE html>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<html>
<meta charset="utf-8">
<title>CSS Shape Test: sideways-lr, float left, circle(50% at right 40px bottom 40px)</title>
<link rel="author" title="Ting-Yu Lin" href="mailto:tlin@mozilla.com">
<link rel="author" title="Mozilla" href="http://www.mozilla.org/">
<link rel="help" href="https://drafts.csswg.org/css-shapes-1/#supported-basic-shapes">
<link rel="match" href="reference/shape-outside-circle-052-ref.html">
<meta name="flags" content="">
<meta name="assert" content="Test the boxes are wrapping around the left float shape defined by circle(50% at right 40px bottom 40px) value under sideways-lr writing-mode.">
<style>
.container {
writing-mode: sideways-lr;
inline-size: 200px;
line-height: 0;
}
.shape {
float: left;
shape-outside: circle(50% at right 40px bottom 40px) border-box;
clip-path: circle(50% at right 40px bottom 40px) border-box;
box-sizing: content-box;
block-size: 40px;
inline-size: 40px;
padding: 20px;
border: 20px solid lightgreen;
margin-inline-start: 20px;
margin-inline-end: 20px;
background-color: orange;
}
.box {
display: inline-block;
inline-size: 60px;
background-color: blue;
}
.long {
inline-size: 200px;
}
</style>
<main class="container">
<div class="shape"></div>
<div class="long box" style="block-size: 20px;"></div> <!-- Fill the border area due to the circle shifted -->
<div class="box" style="block-size: 12px;"></div> <!-- Box at corner -->
<div class="box" style="block-size: 12px;"></div> <!-- Box at corner -->
<div class="box" style="block-size: 36px;"></div>
<div class="box" style="block-size: 36px;"></div>
<div class="box" style="block-size: 12px;"></div> <!-- Box at corner -->
<div class="long box" style="block-size: 20px;"></div>
</main>
</html>
| scheib/chromium | third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/supported-shapes/circle/shape-outside-circle-052.html | HTML | bsd-3-clause | 1,990 |
<!--
Copyright (c) 2015 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are 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 Materials.
THE MATERIALS ARE 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
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
-->
<!--
This file is auto-generated from py/tex_image_test_generator.py
DO NOT EDIT!
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../../resources/js-test-style.css"/>
<script src="../../../js/js-test-pre.js"></script>
<script src="../../../js/webgl-test-utils.js"></script>
<script src="../../../js/tests/tex-image-and-sub-image-utils.js"></script>
<script src="../../../js/tests/tex-image-and-sub-image-2d-with-canvas.js"></script>
</head>
<body>
<canvas id="example" width="32" height="32"></canvas>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
function testPrologue(gl) {
return true;
}
generateTest("R16F", "RED", "HALF_FLOAT", testPrologue, "../../../resources/", 2)();
</script>
</body>
</html>
| endlessm/chromium-browser | third_party/webgl/src/conformance-suites/2.0.0/conformance2/textures/canvas/tex-2d-r16f-red-half_float.html | HTML | bsd-3-clause | 1,874 |
<!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.5"/>
<title>Core Plot (iOS): Source/CPTMutableNumericData+TypeConversion.h Source File</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="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</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="core-plot-logo.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Core Plot (iOS)
</div>
<div id="projectbrief">Cocoa plotting framework for Mac OS X and iOS</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.5 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Animation & Constants</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</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('_c_p_t_mutable_numeric_data_09_type_conversion_8h_source.html','');});
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">CPTMutableNumericData+TypeConversion.h</div> </div>
</div><!--header-->
<div class="contents">
<a href="_c_p_t_mutable_numeric_data_09_type_conversion_8h.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> <span class="preprocessor">#import "<a class="code" href="_c_p_t_mutable_numeric_data_8h.html">CPTMutableNumericData.h</a>"</span></div>
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> <span class="preprocessor">#import "<a class="code" href="_c_p_t_numeric_data_type_8h.html">CPTNumericDataType.h</a>"</span></div>
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span> </div>
<div class="line"><a name="l00007"></a><span class="lineno"><a class="line" href="category_c_p_t_mutable_numeric_data_07_type_conversion_08.html"> 7</a></span> <span class="keyword">@interface </span><a class="code" href="category_c_p_t_mutable_numeric_data_07_type_conversion_08.html">CPTMutableNumericData(TypeConversion)</a></div>
<div class="line"><a name="l00008"></a><span class="lineno"> 8</span> </div>
<div class="line"><a name="l00011"></a><span class="lineno"><a class="line" href="interface_c_p_t_mutable_numeric_data.html#a20604ff4fbb96365bb88d5a7823fca9a"> 11</a></span> <span class="keyword">@property</span> (readwrite, assign) <a class="code" href="struct_c_p_t_numeric_data_type.html">CPTNumericDataType</a> dataType;</div>
<div class="line"><a name="l00012"></a><span class="lineno"><a class="line" href="interface_c_p_t_mutable_numeric_data.html#a79edf7d82be402df822864d28f85e902"> 12</a></span> <span class="keyword">@property</span> (readwrite, assign) <a class="code" href="_c_p_t_numeric_data_type_8h.html#ac29c0caa2ac30299b2dd472b299ac663">CPTDataTypeFormat</a> dataTypeFormat;</div>
<div class="line"><a name="l00013"></a><span class="lineno"><a class="line" href="interface_c_p_t_mutable_numeric_data.html#af618712b9f0dfae3b55989cd89c7e2a7"> 13</a></span> <span class="keyword">@property</span> (readwrite, assign) <span class="keywordtype">size_t</span> sampleBytes;</div>
<div class="line"><a name="l00014"></a><span class="lineno"><a class="line" href="interface_c_p_t_mutable_numeric_data.html#a88bb429e8afe9968a23202599d7e8a8a"> 14</a></span> <span class="keyword">@property</span> (readwrite, assign) <a class="codeRef" href="https://developer.apple.com/library/ios/#documentation/corefoundation/Reference/CFByteOrderUtils/Reference/reference.html">CFByteOrder</a> byteOrder;</div>
<div class="line"><a name="l00016"></a><span class="lineno"> 16</span> </div>
<div class="line"><a name="l00019"></a><span class="lineno"> 19</span> -(void)convertToType:(<a class="code" href="_c_p_t_numeric_data_type_8h.html#ac29c0caa2ac30299b2dd472b299ac663">CPTDataTypeFormat</a>)newDataType sampleBytes:(<span class="keywordtype">size_t</span>)newSampleBytes byteOrder:(<a class="codeRef" href="https://developer.apple.com/library/ios/#documentation/corefoundation/Reference/CFByteOrderUtils/Reference/reference.html">CFByteOrder</a>)newByteOrder;</div>
<div class="line"><a name="l00021"></a><span class="lineno"> 21</span> </div>
<div class="line"><a name="l00022"></a><span class="lineno"> 22</span> <span class="keyword">@end</span></div>
<div class="ttc" id="_c_p_t_numeric_data_type_8h_html"><div class="ttname"><a href="_c_p_t_numeric_data_type_8h.html">CPTNumericDataType.h</a></div></div>
<div class="ttc" id="category_c_p_t_mutable_numeric_data_07_type_conversion_08_html"><div class="ttname"><a href="category_c_p_t_mutable_numeric_data_07_type_conversion_08.html">CPTMutableNumericData(TypeConversion)</a></div><div class="ttdoc">Type conversion methods for CPTMutableNumericData. </div><div class="ttdef"><b>Definition:</b> CPTMutableNumericData+TypeConversion.h:7</div></div>
<div class="ttc" id="_c_p_t_mutable_numeric_data_8h_html"><div class="ttname"><a href="_c_p_t_mutable_numeric_data_8h.html">CPTMutableNumericData.h</a></div></div>
<div class="ttc" id="reference_html"><div class="ttname"><a href="https://developer.apple.com/library/ios/#documentation/corefoundation/Reference/CFByteOrderUtils/Reference/reference.html">CFByteOrder</a></div></div>
<div class="ttc" id="struct_c_p_t_numeric_data_type_html"><div class="ttname"><a href="struct_c_p_t_numeric_data_type.html">CPTNumericDataType</a></div><div class="ttdoc">Structure that describes the encoding of numeric data samples. </div><div class="ttdef"><b>Definition:</b> CPTNumericDataType.h:29</div></div>
<div class="ttc" id="_c_p_t_numeric_data_type_8h_html_ac29c0caa2ac30299b2dd472b299ac663"><div class="ttname"><a href="_c_p_t_numeric_data_type_8h.html#ac29c0caa2ac30299b2dd472b299ac663">CPTDataTypeFormat</a></div><div class="ttdeci">CPTDataTypeFormat</div><div class="ttdoc">Enumeration of data formats for numeric data. </div><div class="ttdef"><b>Definition:</b> CPTNumericDataType.h:6</div></div>
</div><!-- fragment --></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_74389ed8173ad57b461b9d623a1f3867.html">Source</a></li><li class="navelem"><a class="el" href="_c_p_t_mutable_numeric_data_09_type_conversion_8h.html">CPTMutableNumericData+TypeConversion.h</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.5 </li>
</ul>
</div>
</body>
</html>
| LiDechao/core-plot | documentation/html/iOS/_c_p_t_mutable_numeric_data_09_type_conversion_8h_source.html | HTML | bsd-3-clause | 8,346 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/presentation/presentation_availability_state.h"
#include "third_party/blink/renderer/modules/presentation/presentation_availability_observer.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
namespace blink {
PresentationAvailabilityState::PresentationAvailabilityState(
mojom::blink::PresentationService* presentation_service)
: presentation_service_(presentation_service) {}
PresentationAvailabilityState::~PresentationAvailabilityState() = default;
void PresentationAvailabilityState::RequestAvailability(
const Vector<KURL>& urls,
PresentationAvailabilityCallbacks* callback) {
auto screen_availability = GetScreenAvailability(urls);
// Reject Promise if screen availability is unsupported for all URLs.
if (screen_availability == mojom::blink::ScreenAvailability::DISABLED) {
Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(
&PresentationAvailabilityCallbacks::RejectAvailabilityNotSupported,
WrapPersistent(callback)));
// Do not listen to urls if we reject the promise.
return;
}
auto* listener = GetAvailabilityListener(urls);
if (!listener) {
listener = MakeGarbageCollected<AvailabilityListener>(urls);
availability_listeners_.emplace_back(listener);
}
if (screen_availability != mojom::blink::ScreenAvailability::UNKNOWN) {
Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE, WTF::Bind(&PresentationAvailabilityCallbacks::Resolve,
WrapPersistent(callback),
screen_availability ==
mojom::blink::ScreenAvailability::AVAILABLE));
} else {
listener->availability_callbacks.push_back(callback);
}
for (const auto& availability_url : urls)
StartListeningToURL(availability_url);
}
void PresentationAvailabilityState::AddObserver(
PresentationAvailabilityObserver* observer) {
const auto& urls = observer->Urls();
auto* listener = GetAvailabilityListener(urls);
if (!listener) {
listener = MakeGarbageCollected<AvailabilityListener>(urls);
availability_listeners_.emplace_back(listener);
}
if (listener->availability_observers.Contains(observer))
return;
listener->availability_observers.push_back(observer);
for (const auto& availability_url : urls)
StartListeningToURL(availability_url);
}
void PresentationAvailabilityState::RemoveObserver(
PresentationAvailabilityObserver* observer) {
const auto& urls = observer->Urls();
auto* listener = GetAvailabilityListener(urls);
if (!listener) {
DLOG(WARNING) << "Stop listening for availability for unknown URLs.";
return;
}
wtf_size_t slot = listener->availability_observers.Find(observer);
if (slot != kNotFound) {
listener->availability_observers.EraseAt(slot);
}
for (const auto& availability_url : urls)
MaybeStopListeningToURL(availability_url);
TryRemoveAvailabilityListener(listener);
}
void PresentationAvailabilityState::UpdateAvailability(
const KURL& url,
mojom::blink::ScreenAvailability availability) {
auto* listening_status = GetListeningStatus(url);
if (!listening_status)
return;
if (listening_status->listening_state == ListeningState::kWaiting)
listening_status->listening_state = ListeningState::kActive;
if (listening_status->last_known_availability == availability)
return;
listening_status->last_known_availability = availability;
HeapVector<Member<AvailabilityListener>> listeners = availability_listeners_;
for (auto& listener : listeners) {
if (!listener->urls.Contains<KURL>(url))
continue;
auto screen_availability = GetScreenAvailability(listener->urls);
DCHECK(screen_availability != mojom::blink::ScreenAvailability::UNKNOWN);
HeapVector<Member<PresentationAvailabilityObserver>> observers =
listener->availability_observers;
for (auto& observer : observers) {
observer->AvailabilityChanged(screen_availability);
}
if (screen_availability == mojom::blink::ScreenAvailability::DISABLED) {
for (auto& callback_ptr : listener->availability_callbacks) {
callback_ptr->RejectAvailabilityNotSupported();
}
} else {
for (auto& callback_ptr : listener->availability_callbacks) {
callback_ptr->Resolve(screen_availability ==
mojom::blink::ScreenAvailability::AVAILABLE);
}
}
listener->availability_callbacks.clear();
for (const auto& availability_url : listener->urls)
MaybeStopListeningToURL(availability_url);
TryRemoveAvailabilityListener(listener);
}
}
void PresentationAvailabilityState::Trace(Visitor* visitor) const {
visitor->Trace(availability_listeners_);
}
void PresentationAvailabilityState::StartListeningToURL(const KURL& url) {
auto* listening_status = GetListeningStatus(url);
if (!listening_status) {
listening_status = new ListeningStatus(url);
availability_listening_status_.emplace_back(listening_status);
}
// Already listening.
if (listening_status->listening_state != ListeningState::kInactive)
return;
listening_status->listening_state = ListeningState::kWaiting;
presentation_service_->ListenForScreenAvailability(url);
}
void PresentationAvailabilityState::MaybeStopListeningToURL(const KURL& url) {
for (const auto& listener : availability_listeners_) {
if (!listener->urls.Contains(url))
continue;
// URL is still observed by some availability object.
if (!listener->availability_callbacks.IsEmpty() ||
!listener->availability_observers.IsEmpty()) {
return;
}
}
auto* listening_status = GetListeningStatus(url);
if (!listening_status) {
LOG(WARNING) << "Stop listening to unknown url: " << url.GetString();
return;
}
if (listening_status->listening_state == ListeningState::kInactive)
return;
listening_status->listening_state = ListeningState::kInactive;
presentation_service_->StopListeningForScreenAvailability(url);
}
mojom::blink::ScreenAvailability
PresentationAvailabilityState::GetScreenAvailability(
const Vector<KURL>& urls) const {
bool has_disabled = false;
bool has_source_not_supported = false;
bool has_unavailable = false;
for (const auto& url : urls) {
auto* status = GetListeningStatus(url);
auto screen_availability = status
? status->last_known_availability
: mojom::blink::ScreenAvailability::UNKNOWN;
switch (screen_availability) {
case mojom::blink::ScreenAvailability::AVAILABLE:
return mojom::blink::ScreenAvailability::AVAILABLE;
case mojom::blink::ScreenAvailability::DISABLED:
has_disabled = true;
break;
case mojom::blink::ScreenAvailability::SOURCE_NOT_SUPPORTED:
has_source_not_supported = true;
break;
case mojom::blink::ScreenAvailability::UNAVAILABLE:
has_unavailable = true;
break;
case mojom::blink::ScreenAvailability::UNKNOWN:
break;
}
}
if (has_disabled)
return mojom::blink::ScreenAvailability::DISABLED;
if (has_source_not_supported)
return mojom::blink::ScreenAvailability::SOURCE_NOT_SUPPORTED;
if (has_unavailable)
return mojom::blink::ScreenAvailability::UNAVAILABLE;
return mojom::blink::ScreenAvailability::UNKNOWN;
}
PresentationAvailabilityState::AvailabilityListener*
PresentationAvailabilityState::GetAvailabilityListener(
const Vector<KURL>& urls) {
auto* listener_it = std::find_if(
availability_listeners_.begin(), availability_listeners_.end(),
[&urls](const auto& listener) { return listener->urls == urls; });
return listener_it == availability_listeners_.end() ? nullptr : *listener_it;
}
void PresentationAvailabilityState::TryRemoveAvailabilityListener(
AvailabilityListener* listener) {
// URL is still observed by some availability object.
if (!listener->availability_callbacks.IsEmpty() ||
!listener->availability_observers.IsEmpty()) {
return;
}
wtf_size_t slot = availability_listeners_.Find(listener);
if (slot != kNotFound) {
availability_listeners_.EraseAt(slot);
}
}
PresentationAvailabilityState::ListeningStatus*
PresentationAvailabilityState::GetListeningStatus(const KURL& url) const {
auto* status_it =
std::find_if(availability_listening_status_.begin(),
availability_listening_status_.end(),
[&url](const std::unique_ptr<ListeningStatus>& status) {
return status->url == url;
});
return status_it == availability_listening_status_.end() ? nullptr
: status_it->get();
}
PresentationAvailabilityState::AvailabilityListener::AvailabilityListener(
const Vector<KURL>& availability_urls)
: urls(availability_urls) {}
PresentationAvailabilityState::AvailabilityListener::~AvailabilityListener() =
default;
void PresentationAvailabilityState::AvailabilityListener::Trace(
blink::Visitor* visitor) const {
visitor->Trace(availability_callbacks);
visitor->Trace(availability_observers);
}
PresentationAvailabilityState::ListeningStatus::ListeningStatus(
const KURL& availability_url)
: url(availability_url),
last_known_availability(mojom::blink::ScreenAvailability::UNKNOWN),
listening_state(ListeningState::kInactive) {}
PresentationAvailabilityState::ListeningStatus::~ListeningStatus() = default;
} // namespace blink
| chromium/chromium | third_party/blink/renderer/modules/presentation/presentation_availability_state.cc | C++ | bsd-3-clause | 9,801 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/http_negotiate.h"
#include <atlbase.h>
#include <atlcom.h>
#include <htiframe.h>
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome_frame/bho.h"
#include "chrome_frame/exception_barrier.h"
#include "chrome_frame/html_utils.h"
#include "chrome_frame/urlmon_moniker.h"
#include "chrome_frame/urlmon_url_request.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
bool HttpNegotiatePatch::modify_user_agent_ = true;
const char kUACompatibleHttpHeader[] = "x-ua-compatible";
const char kLowerCaseUserAgent[] = "user-agent";
// From the latest urlmon.h. Symbol name prepended with LOCAL_ to
// avoid conflict (and therefore build errors) for those building with
// a newer Windows SDK.
// TODO(robertshield): Remove this once we update our SDK version.
const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54;
static const int kHttpNegotiateBeginningTransactionIndex = 3;
BEGIN_VTABLE_PATCHES(IHttpNegotiate)
VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex,
HttpNegotiatePatch::BeginningTransaction)
END_VTABLE_PATCHES()
namespace {
class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>,
public IBindStatusCallback {
public:
BEGIN_COM_MAP(SimpleBindStatusCallback)
COM_INTERFACE_ENTRY(IBindStatusCallback)
END_COM_MAP()
// IBindStatusCallback implementation
STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) {
return E_NOTIMPL;
}
STDMETHOD(GetPriority)(LONG* priority) {
return E_NOTIMPL;
}
STDMETHOD(OnLowResource)(DWORD reserved) {
return E_NOTIMPL;
}
STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress,
ULONG status_code, LPCWSTR status_text) {
return E_NOTIMPL;
}
STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) {
return E_NOTIMPL;
}
STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {
return E_NOTIMPL;
}
STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc,
STGMEDIUM* storage) {
return E_NOTIMPL;
}
STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) {
return E_NOTIMPL;
}
};
} // end namespace
std::string AppendCFUserAgentString(LPCWSTR headers,
LPCWSTR additional_headers) {
using net::HttpUtil;
std::string ascii_headers;
if (additional_headers) {
ascii_headers = WideToASCII(additional_headers);
}
// Extract "User-Agent" from |additional_headers| or |headers|.
HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(),
ascii_headers.end(), "\r\n");
std::string user_agent_value;
if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) {
user_agent_value = headers_iterator.values();
} else if (headers != NULL) {
// See if there's a user-agent header specified in the original headers.
std::string original_headers(WideToASCII(headers));
HttpUtil::HeadersIterator original_it(original_headers.begin(),
original_headers.end(), "\r\n");
if (original_it.AdvanceTo(kLowerCaseUserAgent))
user_agent_value = original_it.values();
}
// Use the default "User-Agent" if none was provided.
if (user_agent_value.empty())
user_agent_value = http_utils::GetDefaultUserAgent();
// Now add chromeframe to it.
user_agent_value = http_utils::AddChromeFrameToUserAgentValue(
user_agent_value);
// Build new headers, skip the existing user agent value from
// existing headers.
std::string new_headers;
headers_iterator.Reset();
while (headers_iterator.GetNext()) {
std::string name(headers_iterator.name());
if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) {
new_headers += name + ": " + headers_iterator.values() + "\r\n";
}
}
new_headers += "User-Agent: " + user_agent_value;
new_headers += "\r\n";
return new_headers;
}
std::string ReplaceOrAddUserAgent(LPCWSTR headers,
const std::string& user_agent_value) {
using net::HttpUtil;
std::string new_headers;
if (headers) {
std::string ascii_headers(WideToASCII(headers));
// Extract "User-Agent" from the headers.
HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(),
ascii_headers.end(), "\r\n");
// Build new headers, skip the existing user agent value from
// existing headers.
while (headers_iterator.GetNext()) {
std::string name(headers_iterator.name());
if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) {
new_headers += name + ": " + headers_iterator.values() + "\r\n";
}
}
}
new_headers += "User-Agent: " + user_agent_value;
new_headers += "\r\n";
return new_headers;
}
HttpNegotiatePatch::HttpNegotiatePatch() {
}
HttpNegotiatePatch::~HttpNegotiatePatch() {
}
// static
bool HttpNegotiatePatch::Initialize() {
if (IS_PATCHED(IHttpNegotiate)) {
DLOG(WARNING) << __FUNCTION__ << " called more than once.";
return true;
}
// Use our SimpleBindStatusCallback class as we need a temporary object that
// implements IBindStatusCallback.
CComObjectStackEx<SimpleBindStatusCallback> request;
base::win::ScopedComPtr<IBindCtx> bind_ctx;
HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive());
DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx";
if (bind_ctx) {
base::win::ScopedComPtr<IUnknown> bscb_holder;
bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive());
if (bscb_holder) {
hr = PatchHttpNegotiate(bscb_holder);
} else {
NOTREACHED() << "Failed to get _BSCB_Holder_";
hr = E_UNEXPECTED;
}
bind_ctx.Release();
}
return SUCCEEDED(hr);
}
// static
void HttpNegotiatePatch::Uninitialize() {
vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo);
}
// static
HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) {
DCHECK(to_patch);
DCHECK_IS_NOT_PATCHED(IHttpNegotiate);
base::win::ScopedComPtr<IHttpNegotiate> http;
HRESULT hr = http.QueryFrom(to_patch);
if (FAILED(hr)) {
hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive());
}
if (http) {
hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo);
DLOG_IF(ERROR, FAILED(hr))
<< base::StringPrintf("HttpNegotiate patch failed 0x%08X", hr);
} else {
DLOG(WARNING)
<< base::StringPrintf("IHttpNegotiate not supported 0x%08X", hr);
}
return hr;
}
// static
HRESULT HttpNegotiatePatch::BeginningTransaction(
IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me,
LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) {
DVLOG(1) << __FUNCTION__ << " " << url << " headers:\n" << headers;
HRESULT hr = original(me, url, headers, reserved, additional_headers);
if (FAILED(hr)) {
DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error";
return hr;
}
if (modify_user_agent_) {
std::string updated_headers;
if (IsGcfDefaultRenderer() &&
RendererTypeForUrl(url) == RENDERER_TYPE_CHROME_DEFAULT_RENDERER) {
// Replace the user-agent header with Chrome's.
updated_headers = ReplaceOrAddUserAgent(*additional_headers,
http_utils::GetChromeUserAgent());
} else {
updated_headers = AppendCFUserAgentString(headers, *additional_headers);
}
*additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemRealloc(
*additional_headers,
(updated_headers.length() + 1) * sizeof(wchar_t)));
lstrcpyW(*additional_headers, ASCIIToWide(updated_headers).c_str());
} else {
// TODO(erikwright): Remove the user agent if it is present (i.e., because
// of PostPlatform setting in the registry).
}
return S_OK;
}
| aYukiSekiguchi/ACCESS-Chromium | chrome_frame/http_negotiate.cc | C++ | bsd-3-clause | 8,266 |
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "flutter/sky/engine/wtf/PartitionAlloc.h"
#include <string.h>
#ifndef NDEBUG
#include <stdio.h>
#endif
// Two partition pages are used as guard / metadata page so make sure the super
// page size is bigger.
COMPILE_ASSERT(WTF::kPartitionPageSize * 4 <= WTF::kSuperPageSize, ok_super_page_size);
COMPILE_ASSERT(!(WTF::kSuperPageSize % WTF::kPartitionPageSize), ok_super_page_multiple);
// Four system pages gives us room to hack out a still-guard-paged piece
// of metadata in the middle of a guard partition page.
COMPILE_ASSERT(WTF::kSystemPageSize * 4 <= WTF::kPartitionPageSize, ok_partition_page_size);
COMPILE_ASSERT(!(WTF::kPartitionPageSize % WTF::kSystemPageSize), ok_partition_page_multiple);
COMPILE_ASSERT(sizeof(WTF::PartitionPage) <= WTF::kPageMetadataSize, PartitionPage_not_too_big);
COMPILE_ASSERT(sizeof(WTF::PartitionBucket) <= WTF::kPageMetadataSize, PartitionBucket_not_too_big);
COMPILE_ASSERT(sizeof(WTF::PartitionSuperPageExtentEntry) <= WTF::kPageMetadataSize, PartitionSuperPageExtentEntry_not_too_big);
COMPILE_ASSERT(WTF::kPageMetadataSize * WTF::kNumPartitionPagesPerSuperPage <= WTF::kSystemPageSize, page_metadata_fits_in_hole);
// Check that some of our zanier calculations worked out as expected.
COMPILE_ASSERT(WTF::kGenericSmallestBucket == 8, generic_smallest_bucket);
COMPILE_ASSERT(WTF::kGenericMaxBucketed == 983040, generic_max_bucketed);
namespace WTF {
int PartitionRootBase::gInitializedLock = 0;
bool PartitionRootBase::gInitialized = false;
PartitionPage PartitionRootBase::gSeedPage;
PartitionBucket PartitionRootBase::gPagedBucket;
static size_t partitionBucketNumSystemPages(size_t size)
{
// This works out reasonably for the current bucket sizes of the generic
// allocator, and the current values of partition page size and constants.
// Specifically, we have enough room to always pack the slots perfectly into
// some number of system pages. The only waste is the waste associated with
// unfaulted pages (i.e. wasted address space).
// TODO: we end up using a lot of system pages for very small sizes. For
// example, we'll use 12 system pages for slot size 24. The slot size is
// so small that the waste would be tiny with just 4, or 1, system pages.
// Later, we can investigate whether there are anti-fragmentation benefits
// to using fewer system pages.
double bestWasteRatio = 1.0f;
size_t bestPages = 0;
if (size > kMaxSystemPagesPerSlotSpan * kSystemPageSize) {
ASSERT(!(size % kSystemPageSize));
return size / kSystemPageSize;
}
ASSERT(size <= kMaxSystemPagesPerSlotSpan * kSystemPageSize);
for (size_t i = kNumSystemPagesPerPartitionPage - 1; i <= kMaxSystemPagesPerSlotSpan; ++i) {
size_t pageSize = kSystemPageSize * i;
size_t numSlots = pageSize / size;
size_t waste = pageSize - (numSlots * size);
// Leaving a page unfaulted is not free; the page will occupy an empty page table entry.
// Make a simple attempt to account for that.
size_t numRemainderPages = i & (kNumSystemPagesPerPartitionPage - 1);
size_t numUnfaultedPages = numRemainderPages ? (kNumSystemPagesPerPartitionPage - numRemainderPages) : 0;
waste += sizeof(void*) * numUnfaultedPages;
double wasteRatio = (double) waste / (double) pageSize;
if (wasteRatio < bestWasteRatio) {
bestWasteRatio = wasteRatio;
bestPages = i;
}
}
ASSERT(bestPages > 0);
return bestPages;
}
static void parititonAllocBaseInit(PartitionRootBase* root)
{
ASSERT(!root->initialized);
spinLockLock(&PartitionRootBase::gInitializedLock);
if (!PartitionRootBase::gInitialized) {
PartitionRootBase::gInitialized = true;
// We mark the seed page as free to make sure it is skipped by our
// logic to find a new active page.
PartitionRootBase::gPagedBucket.activePagesHead = &PartitionRootGeneric::gSeedPage;
}
spinLockUnlock(&PartitionRootBase::gInitializedLock);
root->initialized = true;
root->totalSizeOfCommittedPages = 0;
root->totalSizeOfSuperPages = 0;
root->nextSuperPage = 0;
root->nextPartitionPage = 0;
root->nextPartitionPageEnd = 0;
root->firstExtent = 0;
root->currentExtent = 0;
memset(&root->globalEmptyPageRing, '\0', sizeof(root->globalEmptyPageRing));
root->globalEmptyPageRingIndex = 0;
// This is a "magic" value so we can test if a root pointer is valid.
root->invertedSelf = ~reinterpret_cast<uintptr_t>(root);
}
static void partitionBucketInitBase(PartitionBucket* bucket, PartitionRootBase* root)
{
bucket->activePagesHead = &PartitionRootGeneric::gSeedPage;
bucket->freePagesHead = 0;
bucket->numFullPages = 0;
bucket->numSystemPagesPerSlotSpan = partitionBucketNumSystemPages(bucket->slotSize);
}
void partitionAllocInit(PartitionRoot* root, size_t numBuckets, size_t maxAllocation)
{
parititonAllocBaseInit(root);
root->numBuckets = numBuckets;
root->maxAllocation = maxAllocation;
size_t i;
for (i = 0; i < root->numBuckets; ++i) {
PartitionBucket* bucket = &root->buckets()[i];
if (!i)
bucket->slotSize = kAllocationGranularity;
else
bucket->slotSize = i << kBucketShift;
partitionBucketInitBase(bucket, root);
}
}
void partitionAllocGenericInit(PartitionRootGeneric* root)
{
parititonAllocBaseInit(root);
root->lock = 0;
// Precalculate some shift and mask constants used in the hot path.
// Example: malloc(41) == 101001 binary.
// Order is 6 (1 << 6-1)==32 is highest bit set.
// orderIndex is the next three MSB == 010 == 2.
// subOrderIndexMask is a mask for the remaining bits == 11 (masking to 01 for the subOrderIndex).
size_t order;
for (order = 0; order <= kBitsPerSizet; ++order) {
size_t orderIndexShift;
if (order < kGenericNumBucketsPerOrderBits + 1)
orderIndexShift = 0;
else
orderIndexShift = order - (kGenericNumBucketsPerOrderBits + 1);
root->orderIndexShifts[order] = orderIndexShift;
size_t subOrderIndexMask;
if (order == kBitsPerSizet) {
// This avoids invoking undefined behavior for an excessive shift.
subOrderIndexMask = static_cast<size_t>(-1) >> (kGenericNumBucketsPerOrderBits + 1);
} else {
subOrderIndexMask = ((1 << order) - 1) >> (kGenericNumBucketsPerOrderBits + 1);
}
root->orderSubIndexMasks[order] = subOrderIndexMask;
}
// Set up the actual usable buckets first.
// Note that typical values (i.e. min allocation size of 8) will result in
// invalid buckets (size==9 etc. or more generally, size is not a multiple
// of the smallest allocation granularity).
// We avoid them in the bucket lookup map, but we tolerate them to keep the
// code simpler and the structures more generic.
size_t i, j;
size_t currentSize = kGenericSmallestBucket;
size_t currentIncrement = kGenericSmallestBucket >> kGenericNumBucketsPerOrderBits;
PartitionBucket* bucket = &root->buckets[0];
for (i = 0; i < kGenericNumBucketedOrders; ++i) {
for (j = 0; j < kGenericNumBucketsPerOrder; ++j) {
bucket->slotSize = currentSize;
partitionBucketInitBase(bucket, root);
// Disable invalid buckets so that touching them faults.
if (currentSize % kGenericSmallestBucket)
bucket->activePagesHead = 0;
currentSize += currentIncrement;
++bucket;
}
currentIncrement <<= 1;
}
ASSERT(currentSize == 1 << kGenericMaxBucketedOrder);
ASSERT(bucket == &root->buckets[0] + (kGenericNumBucketedOrders * kGenericNumBucketsPerOrder));
// Then set up the fast size -> bucket lookup table.
bucket = &root->buckets[0];
PartitionBucket** bucketPtr = &root->bucketLookups[0];
for (order = 0; order <= kBitsPerSizet; ++order) {
for (j = 0; j < kGenericNumBucketsPerOrder; ++j) {
if (order < kGenericMinBucketedOrder) {
// Use the bucket of finest granularity for malloc(0) etc.
*bucketPtr++ = &root->buckets[0];
} else if (order > kGenericMaxBucketedOrder) {
*bucketPtr++ = &PartitionRootGeneric::gPagedBucket;
} else {
PartitionBucket* validBucket = bucket;
// Skip over invalid buckets.
while (validBucket->slotSize % kGenericSmallestBucket)
validBucket++;
*bucketPtr++ = validBucket;
bucket++;
}
}
}
ASSERT(bucket == &root->buckets[0] + (kGenericNumBucketedOrders * kGenericNumBucketsPerOrder));
ASSERT(bucketPtr == &root->bucketLookups[0] + ((kBitsPerSizet + 1) * kGenericNumBucketsPerOrder));
// And there's one last bucket lookup that will be hit for e.g. malloc(-1),
// which tries to overflow to a non-existant order.
*bucketPtr = &PartitionRootGeneric::gPagedBucket;
}
static bool partitionAllocShutdownBucket(PartitionBucket* bucket)
{
// Failure here indicates a memory leak.
bool noLeaks = !bucket->numFullPages;
PartitionPage* page = bucket->activePagesHead;
while (page) {
if (page->numAllocatedSlots)
noLeaks = false;
page = page->nextPage;
}
return noLeaks;
}
static void partitionAllocBaseShutdown(PartitionRootBase* root)
{
ASSERT(root->initialized);
root->initialized = false;
// Now that we've examined all partition pages in all buckets, it's safe
// to free all our super pages. We first collect the super page pointers
// on the stack because some of them are themselves store in super pages.
char* superPages[kMaxPartitionSize / kSuperPageSize];
size_t numSuperPages = 0;
PartitionSuperPageExtentEntry* entry = root->firstExtent;
while (entry) {
char* superPage = entry->superPageBase;
while (superPage != entry->superPagesEnd) {
superPages[numSuperPages] = superPage;
numSuperPages++;
superPage += kSuperPageSize;
}
entry = entry->next;
}
ASSERT(numSuperPages == root->totalSizeOfSuperPages / kSuperPageSize);
for (size_t i = 0; i < numSuperPages; ++i)
freePages(superPages[i], kSuperPageSize);
}
bool partitionAllocShutdown(PartitionRoot* root)
{
bool noLeaks = true;
size_t i;
for (i = 0; i < root->numBuckets; ++i) {
PartitionBucket* bucket = &root->buckets()[i];
if (!partitionAllocShutdownBucket(bucket))
noLeaks = false;
}
partitionAllocBaseShutdown(root);
return noLeaks;
}
bool partitionAllocGenericShutdown(PartitionRootGeneric* root)
{
bool noLeaks = true;
size_t i;
for (i = 0; i < kGenericNumBucketedOrders * kGenericNumBucketsPerOrder; ++i) {
PartitionBucket* bucket = &root->buckets[i];
if (!partitionAllocShutdownBucket(bucket))
noLeaks = false;
}
partitionAllocBaseShutdown(root);
return noLeaks;
}
static NEVER_INLINE void partitionOutOfMemory()
{
IMMEDIATE_CRASH();
}
static NEVER_INLINE void partitionFull()
{
IMMEDIATE_CRASH();
}
static ALWAYS_INLINE void partitionDecommitSystemPages(PartitionRootBase* root, void* addr, size_t len)
{
decommitSystemPages(addr, len);
ASSERT(root->totalSizeOfCommittedPages > len);
root->totalSizeOfCommittedPages -= len;
}
static ALWAYS_INLINE void partitionRecommitSystemPages(PartitionRootBase* root, void* addr, size_t len)
{
recommitSystemPages(addr, len);
root->totalSizeOfCommittedPages += len;
}
static ALWAYS_INLINE void* partitionAllocPartitionPages(PartitionRootBase* root, int flags, size_t numPartitionPages)
{
ASSERT(!(reinterpret_cast<uintptr_t>(root->nextPartitionPage) % kPartitionPageSize));
ASSERT(!(reinterpret_cast<uintptr_t>(root->nextPartitionPageEnd) % kPartitionPageSize));
RELEASE_ASSERT(numPartitionPages <= kNumPartitionPagesPerSuperPage);
size_t totalSize = kPartitionPageSize * numPartitionPages;
root->totalSizeOfCommittedPages += totalSize;
size_t numPartitionPagesLeft = (root->nextPartitionPageEnd - root->nextPartitionPage) >> kPartitionPageShift;
if (LIKELY(numPartitionPagesLeft >= numPartitionPages)) {
// In this case, we can still hand out pages from the current super page
// allocation.
char* ret = root->nextPartitionPage;
root->nextPartitionPage += totalSize;
return ret;
}
// Need a new super page.
root->totalSizeOfSuperPages += kSuperPageSize;
if (root->totalSizeOfSuperPages > kMaxPartitionSize)
partitionFull();
char* requestedAddress = root->nextSuperPage;
char* superPage = reinterpret_cast<char*>(allocPages(requestedAddress, kSuperPageSize, kSuperPageSize));
if (UNLIKELY(!superPage)) {
if (flags & PartitionAllocReturnNull)
return 0;
partitionOutOfMemory();
}
root->nextSuperPage = superPage + kSuperPageSize;
char* ret = superPage + kPartitionPageSize;
root->nextPartitionPage = ret + totalSize;
root->nextPartitionPageEnd = root->nextSuperPage - kPartitionPageSize;
// Make the first partition page in the super page a guard page, but leave a
// hole in the middle.
// This is where we put page metadata and also a tiny amount of extent
// metadata.
setSystemPagesInaccessible(superPage, kSystemPageSize);
setSystemPagesInaccessible(superPage + (kSystemPageSize * 2), kPartitionPageSize - (kSystemPageSize * 2));
// Also make the last partition page a guard page.
setSystemPagesInaccessible(superPage + (kSuperPageSize - kPartitionPageSize), kPartitionPageSize);
// If we were after a specific address, but didn't get it, assume that
// the system chose a lousy address and re-randomize the next
// allocation.
if (requestedAddress && requestedAddress != superPage)
root->nextSuperPage = 0;
// We allocated a new super page so update super page metadata.
// First check if this is a new extent or not.
PartitionSuperPageExtentEntry* latestExtent = reinterpret_cast<PartitionSuperPageExtentEntry*>(partitionSuperPageToMetadataArea(superPage));
PartitionSuperPageExtentEntry* currentExtent = root->currentExtent;
bool isNewExtent = (superPage != requestedAddress);
if (UNLIKELY(isNewExtent)) {
latestExtent->next = 0;
if (UNLIKELY(!currentExtent)) {
root->firstExtent = latestExtent;
} else {
ASSERT(currentExtent->superPageBase);
currentExtent->next = latestExtent;
}
root->currentExtent = latestExtent;
currentExtent = latestExtent;
currentExtent->superPageBase = superPage;
currentExtent->superPagesEnd = superPage + kSuperPageSize;
} else {
// We allocated next to an existing extent so just nudge the size up a little.
currentExtent->superPagesEnd += kSuperPageSize;
ASSERT(ret >= currentExtent->superPageBase && ret < currentExtent->superPagesEnd);
}
// By storing the root in every extent metadata object, we have a fast way
// to go from a pointer within the partition to the root object.
latestExtent->root = root;
return ret;
}
static ALWAYS_INLINE void partitionUnusePage(PartitionRootBase* root, PartitionPage* page)
{
ASSERT(page->bucket->numSystemPagesPerSlotSpan);
void* addr = partitionPageToPointer(page);
partitionDecommitSystemPages(root, addr, page->bucket->numSystemPagesPerSlotSpan * kSystemPageSize);
}
static ALWAYS_INLINE size_t partitionBucketSlots(const PartitionBucket* bucket)
{
return (bucket->numSystemPagesPerSlotSpan * kSystemPageSize) / bucket->slotSize;
}
static ALWAYS_INLINE size_t partitionBucketPartitionPages(const PartitionBucket* bucket)
{
return (bucket->numSystemPagesPerSlotSpan + (kNumSystemPagesPerPartitionPage - 1)) / kNumSystemPagesPerPartitionPage;
}
static ALWAYS_INLINE void partitionPageReset(PartitionPage* page, PartitionBucket* bucket)
{
ASSERT(page != &PartitionRootGeneric::gSeedPage);
page->numAllocatedSlots = 0;
page->numUnprovisionedSlots = partitionBucketSlots(bucket);
ASSERT(page->numUnprovisionedSlots);
page->bucket = bucket;
page->nextPage = 0;
// NULLing the freelist is not strictly necessary but it makes an ASSERT in partitionPageFillFreelist simpler.
page->freelistHead = 0;
page->pageOffset = 0;
page->freeCacheIndex = -1;
size_t numPartitionPages = partitionBucketPartitionPages(bucket);
size_t i;
char* pageCharPtr = reinterpret_cast<char*>(page);
for (i = 1; i < numPartitionPages; ++i) {
pageCharPtr += kPageMetadataSize;
PartitionPage* secondaryPage = reinterpret_cast<PartitionPage*>(pageCharPtr);
secondaryPage->pageOffset = i;
}
}
static ALWAYS_INLINE char* partitionPageAllocAndFillFreelist(PartitionPage* page)
{
ASSERT(page != &PartitionRootGeneric::gSeedPage);
size_t numSlots = page->numUnprovisionedSlots;
ASSERT(numSlots);
PartitionBucket* bucket = page->bucket;
// We should only get here when _every_ slot is either used or unprovisioned.
// (The third state is "on the freelist". If we have a non-empty freelist, we should not get here.)
ASSERT(numSlots + page->numAllocatedSlots == partitionBucketSlots(bucket));
// Similarly, make explicitly sure that the freelist is empty.
ASSERT(!page->freelistHead);
ASSERT(page->numAllocatedSlots >= 0);
size_t size = bucket->slotSize;
char* base = reinterpret_cast<char*>(partitionPageToPointer(page));
char* returnObject = base + (size * page->numAllocatedSlots);
char* firstFreelistPointer = returnObject + size;
char* firstFreelistPointerExtent = firstFreelistPointer + sizeof(PartitionFreelistEntry*);
// Our goal is to fault as few system pages as possible. We calculate the
// page containing the "end" of the returned slot, and then allow freelist
// pointers to be written up to the end of that page.
char* subPageLimit = reinterpret_cast<char*>((reinterpret_cast<uintptr_t>(firstFreelistPointer) + kSystemPageOffsetMask) & kSystemPageBaseMask);
char* slotsLimit = returnObject + (size * page->numUnprovisionedSlots);
char* freelistLimit = subPageLimit;
if (UNLIKELY(slotsLimit < freelistLimit))
freelistLimit = slotsLimit;
size_t numNewFreelistEntries = 0;
if (LIKELY(firstFreelistPointerExtent <= freelistLimit)) {
// Only consider used space in the slot span. If we consider wasted
// space, we may get an off-by-one when a freelist pointer fits in the
// wasted space, but a slot does not.
// We know we can fit at least one freelist pointer.
numNewFreelistEntries = 1;
// Any further entries require space for the whole slot span.
numNewFreelistEntries += (freelistLimit - firstFreelistPointerExtent) / size;
}
// We always return an object slot -- that's the +1 below.
// We do not neccessarily create any new freelist entries, because we cross sub page boundaries frequently for large bucket sizes.
ASSERT(numNewFreelistEntries + 1 <= numSlots);
numSlots -= (numNewFreelistEntries + 1);
page->numUnprovisionedSlots = numSlots;
page->numAllocatedSlots++;
if (LIKELY(numNewFreelistEntries)) {
char* freelistPointer = firstFreelistPointer;
PartitionFreelistEntry* entry = reinterpret_cast<PartitionFreelistEntry*>(freelistPointer);
page->freelistHead = entry;
while (--numNewFreelistEntries) {
freelistPointer += size;
PartitionFreelistEntry* nextEntry = reinterpret_cast<PartitionFreelistEntry*>(freelistPointer);
entry->next = partitionFreelistMask(nextEntry);
entry = nextEntry;
}
entry->next = partitionFreelistMask(0);
} else {
page->freelistHead = 0;
}
return returnObject;
}
// This helper function scans the active page list for a suitable new active
// page, starting at the passed in page.
// When it finds a suitable new active page (one that has free slots), it is
// set as the new active page and true is returned. If there is no suitable new
// active page, false is returned and the current active page is set to null.
// As potential pages are scanned, they are tidied up according to their state.
// Freed pages are swept on to the free page list and full pages are unlinked
// from any list.
static ALWAYS_INLINE bool partitionSetNewActivePage(PartitionPage* page)
{
if (page == &PartitionRootBase::gSeedPage) {
ASSERT(!page->nextPage);
return false;
}
PartitionPage* nextPage = 0;
PartitionBucket* bucket = page->bucket;
for (; page; page = nextPage) {
nextPage = page->nextPage;
ASSERT(page->bucket == bucket);
ASSERT(page != bucket->freePagesHead);
ASSERT(!bucket->freePagesHead || page != bucket->freePagesHead->nextPage);
// Page is usable if it has something on the freelist, or unprovisioned
// slots that can be turned into a freelist.
if (LIKELY(page->freelistHead != 0) || LIKELY(page->numUnprovisionedSlots)) {
bucket->activePagesHead = page;
return true;
}
ASSERT(page->numAllocatedSlots >= 0);
if (LIKELY(page->numAllocatedSlots == 0)) {
ASSERT(page->freeCacheIndex == -1);
// We hit a free page, so shepherd it on to the free page list.
page->nextPage = bucket->freePagesHead;
bucket->freePagesHead = page;
} else {
// If we get here, we found a full page. Skip over it too, and also
// tag it as full (via a negative value). We need it tagged so that
// free'ing can tell, and move it back into the active page list.
ASSERT(page->numAllocatedSlots == static_cast<int>(partitionBucketSlots(bucket)));
page->numAllocatedSlots = -page->numAllocatedSlots;
++bucket->numFullPages;
// numFullPages is a uint16_t for efficient packing so guard against
// overflow to be safe.
RELEASE_ASSERT(bucket->numFullPages);
// Not necessary but might help stop accidents.
page->nextPage = 0;
}
}
bucket->activePagesHead = 0;
return false;
}
struct PartitionDirectMapExtent {
size_t mapSize; // Mapped size, not including guard pages and meta-data.
};
static ALWAYS_INLINE PartitionDirectMapExtent* partitionPageToDirectMapExtent(PartitionPage* page)
{
ASSERT(partitionBucketIsDirectMapped(page->bucket));
return reinterpret_cast<PartitionDirectMapExtent*>(reinterpret_cast<char*>(page) + 2 * kPageMetadataSize);
}
static ALWAYS_INLINE void* partitionDirectMap(PartitionRootBase* root, int flags, size_t size)
{
size = partitionDirectMapSize(size);
// Because we need to fake looking like a super page, We need to allocate
// a bunch of system pages more than "size":
// - The first few system pages are the partition page in which the super
// page metadata is stored. We fault just one system page out of a partition
// page sized clump.
// - We add a trailing guard page.
size_t mapSize = size + kPartitionPageSize + kSystemPageSize;
// Round up to the allocation granularity.
mapSize += kPageAllocationGranularityOffsetMask;
mapSize &= kPageAllocationGranularityBaseMask;
// TODO: we may want to let the operating system place these allocations
// where it pleases. On 32-bit, this might limit address space
// fragmentation and on 64-bit, this might have useful savings for TLB
// and page table overhead.
// TODO: if upsizing realloc()s are common on large sizes, we could
// consider over-allocating address space on 64-bit, "just in case".
// TODO: consider pre-populating page tables (e.g. MAP_POPULATE on Linux,
// MADV_WILLNEED on POSIX).
// TODO: these pages will be zero-filled. Consider internalizing an
// allocZeroed() API so we can avoid a memset() entirely in this case.
char* ptr = reinterpret_cast<char*>(allocPages(0, mapSize, kSuperPageSize));
if (!ptr) {
if (flags & PartitionAllocReturnNull)
return 0;
partitionOutOfMemory();
}
char* ret = ptr + kPartitionPageSize;
// TODO: due to all the guard paging, this arrangement creates 4 mappings.
// We could get it down to three by using read-only for the metadata page,
// or perhaps two by leaving out the trailing guard page on 64-bit.
setSystemPagesInaccessible(ptr, kSystemPageSize);
setSystemPagesInaccessible(ptr + (kSystemPageSize * 2), kPartitionPageSize - (kSystemPageSize * 2));
setSystemPagesInaccessible(ret + size, kSystemPageSize);
PartitionSuperPageExtentEntry* extent = reinterpret_cast<PartitionSuperPageExtentEntry*>(partitionSuperPageToMetadataArea(ptr));
extent->root = root;
PartitionPage* page = partitionPointerToPageNoAlignmentCheck(ret);
PartitionBucket* bucket = reinterpret_cast<PartitionBucket*>(reinterpret_cast<char*>(page) + kPageMetadataSize);
page->freelistHead = 0;
page->nextPage = 0;
page->bucket = bucket;
page->numAllocatedSlots = 1;
page->numUnprovisionedSlots = 0;
page->pageOffset = 0;
page->freeCacheIndex = 0;
bucket->activePagesHead = 0;
bucket->freePagesHead = 0;
bucket->slotSize = size;
bucket->numSystemPagesPerSlotSpan = 0;
bucket->numFullPages = 0;
PartitionDirectMapExtent* mapExtent = partitionPageToDirectMapExtent(page);
mapExtent->mapSize = mapSize - kPartitionPageSize - kSystemPageSize;
return ret;
}
static ALWAYS_INLINE void partitionDirectUnmap(PartitionPage* page)
{
size_t unmapSize = partitionPageToDirectMapExtent(page)->mapSize;
// Add on the size of the trailing guard page and preceeding partition
// page.
unmapSize += kPartitionPageSize + kSystemPageSize;
ASSERT(!(unmapSize & kPageAllocationGranularityOffsetMask));
char* ptr = reinterpret_cast<char*>(partitionPageToPointer(page));
// Account for the mapping starting a partition page before the actual
// allocation address.
ptr -= kPartitionPageSize;
freePages(ptr, unmapSize);
}
void* partitionAllocSlowPath(PartitionRootBase* root, int flags, size_t size, PartitionBucket* bucket)
{
// The slow path is called when the freelist is empty.
ASSERT(!bucket->activePagesHead->freelistHead);
// For the partitionAllocGeneric API, we have a bunch of buckets marked
// as special cases. We bounce them through to the slow path so that we
// can still have a blazing fast hot path due to lack of corner-case
// branches.
bool returnNull = flags & PartitionAllocReturnNull;
if (UNLIKELY(partitionBucketIsDirectMapped(bucket))) {
ASSERT(size > kGenericMaxBucketed);
ASSERT(bucket == &PartitionRootBase::gPagedBucket);
if (size > kGenericMaxDirectMapped) {
if (returnNull)
return 0;
RELEASE_ASSERT(false);
}
return partitionDirectMap(root, flags, size);
}
// First, look for a usable page in the existing active pages list.
// Change active page, accepting the current page as a candidate.
if (LIKELY(partitionSetNewActivePage(bucket->activePagesHead))) {
PartitionPage* newPage = bucket->activePagesHead;
if (LIKELY(newPage->freelistHead != 0)) {
PartitionFreelistEntry* ret = newPage->freelistHead;
newPage->freelistHead = partitionFreelistMask(ret->next);
newPage->numAllocatedSlots++;
return ret;
}
ASSERT(newPage->numUnprovisionedSlots);
return partitionPageAllocAndFillFreelist(newPage);
}
// Second, look in our list of freed but reserved pages.
PartitionPage* newPage = bucket->freePagesHead;
if (LIKELY(newPage != 0)) {
ASSERT(newPage != &PartitionRootGeneric::gSeedPage);
ASSERT(!newPage->freelistHead);
ASSERT(!newPage->numAllocatedSlots);
ASSERT(!newPage->numUnprovisionedSlots);
ASSERT(newPage->freeCacheIndex == -1);
bucket->freePagesHead = newPage->nextPage;
void* addr = partitionPageToPointer(newPage);
partitionRecommitSystemPages(root, addr, newPage->bucket->numSystemPagesPerSlotSpan * kSystemPageSize);
} else {
// Third. If we get here, we need a brand new page.
size_t numPartitionPages = partitionBucketPartitionPages(bucket);
void* rawNewPage = partitionAllocPartitionPages(root, flags, numPartitionPages);
if (UNLIKELY(!rawNewPage)) {
ASSERT(returnNull);
return 0;
}
// Skip the alignment check because it depends on page->bucket, which is not yet set.
newPage = partitionPointerToPageNoAlignmentCheck(rawNewPage);
}
partitionPageReset(newPage, bucket);
bucket->activePagesHead = newPage;
return partitionPageAllocAndFillFreelist(newPage);
}
static ALWAYS_INLINE void partitionFreePage(PartitionRootBase* root, PartitionPage* page)
{
ASSERT(page->freelistHead);
ASSERT(!page->numAllocatedSlots);
partitionUnusePage(root, page);
// We actually leave the freed page in the active list. We'll sweep it on
// to the free page list when we next walk the active page list. Pulling
// this trick enables us to use a singly-linked page list for all cases,
// which is critical in keeping the page metadata structure down to 32
// bytes in size.
page->freelistHead = 0;
page->numUnprovisionedSlots = 0;
}
static ALWAYS_INLINE void partitionRegisterEmptyPage(PartitionPage* page)
{
PartitionRootBase* root = partitionPageToRoot(page);
// If the page is already registered as empty, give it another life.
if (page->freeCacheIndex != -1) {
ASSERT(page->freeCacheIndex >= 0);
ASSERT(static_cast<unsigned>(page->freeCacheIndex) < kMaxFreeableSpans);
ASSERT(root->globalEmptyPageRing[page->freeCacheIndex] == page);
root->globalEmptyPageRing[page->freeCacheIndex] = 0;
}
size_t currentIndex = root->globalEmptyPageRingIndex;
PartitionPage* pageToFree = root->globalEmptyPageRing[currentIndex];
// The page might well have been re-activated, filled up, etc. before we get
// around to looking at it here.
if (pageToFree) {
ASSERT(pageToFree != &PartitionRootBase::gSeedPage);
ASSERT(pageToFree->freeCacheIndex >= 0);
ASSERT(static_cast<unsigned>(pageToFree->freeCacheIndex) < kMaxFreeableSpans);
ASSERT(pageToFree == root->globalEmptyPageRing[pageToFree->freeCacheIndex]);
if (!pageToFree->numAllocatedSlots && pageToFree->freelistHead) {
// The page is still empty, and not freed, so _really_ free it.
partitionFreePage(root, pageToFree);
}
pageToFree->freeCacheIndex = -1;
}
// We put the empty slot span on our global list of "pages that were once
// empty". thus providing it a bit of breathing room to get re-used before
// we really free it. This improves performance, particularly on Mac OS X
// which has subpar memory management performance.
root->globalEmptyPageRing[currentIndex] = page;
page->freeCacheIndex = currentIndex;
++currentIndex;
if (currentIndex == kMaxFreeableSpans)
currentIndex = 0;
root->globalEmptyPageRingIndex = currentIndex;
}
void partitionFreeSlowPath(PartitionPage* page)
{
PartitionBucket* bucket = page->bucket;
ASSERT(page != &PartitionRootGeneric::gSeedPage);
ASSERT(bucket->activePagesHead != &PartitionRootGeneric::gSeedPage);
if (LIKELY(page->numAllocatedSlots == 0)) {
// Page became fully unused.
if (UNLIKELY(partitionBucketIsDirectMapped(bucket))) {
partitionDirectUnmap(page);
return;
}
// If it's the current active page, attempt to change it. We'd prefer to leave
// the page empty as a gentle force towards defragmentation.
if (LIKELY(page == bucket->activePagesHead) && page->nextPage) {
if (partitionSetNewActivePage(page->nextPage)) {
ASSERT(bucket->activePagesHead != page);
// Link the empty page back in after the new current page, to
// avoid losing a reference to it.
// TODO: consider walking the list to link the empty page after
// all non-empty pages?
PartitionPage* currentPage = bucket->activePagesHead;
page->nextPage = currentPage->nextPage;
currentPage->nextPage = page;
} else {
bucket->activePagesHead = page;
page->nextPage = 0;
}
}
partitionRegisterEmptyPage(page);
} else {
// Ensure that the page is full. That's the only valid case if we
// arrive here.
ASSERT(page->numAllocatedSlots < 0);
// A transition of numAllocatedSlots from 0 to -1 is not legal, and
// likely indicates a double-free.
RELEASE_ASSERT(page->numAllocatedSlots != -1);
page->numAllocatedSlots = -page->numAllocatedSlots - 2;
ASSERT(page->numAllocatedSlots == static_cast<int>(partitionBucketSlots(bucket) - 1));
// Fully used page became partially used. It must be put back on the
// non-full page list. Also make it the current page to increase the
// chances of it being filled up again. The old current page will be
// the next page.
page->nextPage = bucket->activePagesHead;
bucket->activePagesHead = page;
--bucket->numFullPages;
// Special case: for a partition page with just a single slot, it may
// now be empty and we want to run it through the empty logic.
if (UNLIKELY(page->numAllocatedSlots == 0))
partitionFreeSlowPath(page);
}
}
bool partitionReallocDirectMappedInPlace(PartitionRootGeneric* root, PartitionPage* page, size_t newSize)
{
ASSERT(partitionBucketIsDirectMapped(page->bucket));
newSize = partitionCookieSizeAdjustAdd(newSize);
// Note that the new size might be a bucketed size; this function is called
// whenever we're reallocating a direct mapped allocation.
newSize = partitionDirectMapSize(newSize);
if (newSize < kGenericMinDirectMappedDownsize)
return false;
// bucket->slotSize is the current size of the allocation.
size_t currentSize = page->bucket->slotSize;
if (newSize == currentSize)
return true;
char* charPtr = static_cast<char*>(partitionPageToPointer(page));
if (newSize < currentSize) {
size_t mapSize = partitionPageToDirectMapExtent(page)->mapSize;
// Don't reallocate in-place if new size is less than 80 % of the full
// map size, to avoid holding on to too much unused address space.
if ((newSize / kSystemPageSize) * 5 < (mapSize / kSystemPageSize) * 4)
return false;
// Shrink by decommitting unneeded pages and making them inaccessible.
size_t decommitSize = currentSize - newSize;
partitionDecommitSystemPages(root, charPtr + newSize, decommitSize);
setSystemPagesInaccessible(charPtr + newSize, decommitSize);
} else if (newSize <= partitionPageToDirectMapExtent(page)->mapSize) {
// Grow within the actually allocated memory. Just need to make the
// pages accessible again.
size_t recommitSize = newSize - currentSize;
setSystemPagesAccessible(charPtr + currentSize, recommitSize);
partitionRecommitSystemPages(root, charPtr + currentSize, recommitSize);
#if ENABLE(ASSERT)
memset(charPtr + currentSize, kUninitializedByte, recommitSize);
#endif
} else {
// We can't perform the realloc in-place.
// TODO: support this too when possible.
return false;
}
#if ENABLE(ASSERT)
// Write a new trailing cookie.
partitionCookieWriteValue(charPtr + newSize - kCookieSize);
#endif
page->bucket->slotSize = newSize;
return true;
}
void* partitionReallocGeneric(PartitionRootGeneric* root, void* ptr, size_t newSize)
{
#if defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
return realloc(ptr, newSize);
#else
if (UNLIKELY(!ptr))
return partitionAllocGeneric(root, newSize);
if (UNLIKELY(!newSize)) {
partitionFreeGeneric(root, ptr);
return 0;
}
RELEASE_ASSERT(newSize <= kGenericMaxDirectMapped);
ASSERT(partitionPointerIsValid(partitionCookieFreePointerAdjust(ptr)));
PartitionPage* page = partitionPointerToPage(partitionCookieFreePointerAdjust(ptr));
if (UNLIKELY(partitionBucketIsDirectMapped(page->bucket))) {
// We may be able to perform the realloc in place by changing the
// accessibility of memory pages and, if reducing the size, decommitting
// them.
if (partitionReallocDirectMappedInPlace(root, page, newSize))
return ptr;
}
size_t actualNewSize = partitionAllocActualSize(root, newSize);
size_t actualOldSize = partitionAllocGetSize(ptr);
// TODO: note that tcmalloc will "ignore" a downsizing realloc() unless the
// new size is a significant percentage smaller. We could do the same if we
// determine it is a win.
if (actualNewSize == actualOldSize) {
// Trying to allocate a block of size newSize would give us a block of
// the same size as the one we've already got, so no point in doing
// anything here.
return ptr;
}
// This realloc cannot be resized in-place. Sadness.
void* ret = partitionAllocGeneric(root, newSize);
size_t copySize = actualOldSize;
if (newSize < copySize)
copySize = newSize;
memcpy(ret, ptr, copySize);
partitionFreeGeneric(root, ptr);
return ret;
#endif
}
#ifndef NDEBUG
void partitionDumpStats(const PartitionRoot& root)
{
size_t i;
size_t totalLive = 0;
size_t totalResident = 0;
size_t totalFreeable = 0;
for (i = 0; i < root.numBuckets; ++i) {
const PartitionBucket& bucket = root.buckets()[i];
if (bucket.activePagesHead == &PartitionRootGeneric::gSeedPage && !bucket.freePagesHead && !bucket.numFullPages) {
// Empty bucket with no freelist or full pages. Skip reporting it.
continue;
}
size_t numFreePages = 0;
PartitionPage* freePages = bucket.freePagesHead;
while (freePages) {
++numFreePages;
freePages = freePages->nextPage;
}
size_t bucketSlotSize = bucket.slotSize;
size_t bucketNumSlots = partitionBucketSlots(&bucket);
size_t bucketUsefulStorage = bucketSlotSize * bucketNumSlots;
size_t bucketPageSize = bucket.numSystemPagesPerSlotSpan * kSystemPageSize;
size_t bucketWaste = bucketPageSize - bucketUsefulStorage;
size_t numActiveBytes = bucket.numFullPages * bucketUsefulStorage;
size_t numResidentBytes = bucket.numFullPages * bucketPageSize;
size_t numFreeableBytes = 0;
size_t numActivePages = 0;
const PartitionPage* page = bucket.activePagesHead;
while (page) {
ASSERT(page != &PartitionRootGeneric::gSeedPage);
// A page may be on the active list but freed and not yet swept.
if (!page->freelistHead && !page->numUnprovisionedSlots && !page->numAllocatedSlots) {
++numFreePages;
} else {
++numActivePages;
numActiveBytes += (page->numAllocatedSlots * bucketSlotSize);
size_t pageBytesResident = (bucketNumSlots - page->numUnprovisionedSlots) * bucketSlotSize;
// Round up to system page size.
pageBytesResident = (pageBytesResident + kSystemPageOffsetMask) & kSystemPageBaseMask;
numResidentBytes += pageBytesResident;
if (!page->numAllocatedSlots)
numFreeableBytes += pageBytesResident;
}
page = page->nextPage;
}
totalLive += numActiveBytes;
totalResident += numResidentBytes;
totalFreeable += numFreeableBytes;
printf("bucket size %zu (pageSize %zu waste %zu): %zu alloc/%zu commit/%zu freeable bytes, %zu/%zu/%zu full/active/free pages\n", bucketSlotSize, bucketPageSize, bucketWaste, numActiveBytes, numResidentBytes, numFreeableBytes, static_cast<size_t>(bucket.numFullPages), numActivePages, numFreePages);
}
printf("total live: %zu bytes\n", totalLive);
printf("total resident: %zu bytes\n", totalResident);
printf("total freeable: %zu bytes\n", totalFreeable);
fflush(stdout);
}
#endif // !NDEBUG
} // namespace WTF
| mpcomplete/flutter_engine | sky/engine/wtf/PartitionAlloc.cpp | C++ | bsd-3-clause | 42,604 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Tests scripts panel file selectors.\n`);
await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
await TestRunner.loadTestModule('sdk_test_runner');
await TestRunner.showPanel('sources');
await TestRunner.addIframe(
'resources/post-message-listener.html', {name: 'childframe'});
Bindings.debuggerWorkspaceBinding.resetForTest(TestRunner.mainTarget);
Bindings.resourceMapping.resetForTest(TestRunner.mainTarget);
var subframe = TestRunner.mainFrame().childFrames[0];
var sourcesNavigatorView = new Sources.NetworkNavigatorView();
sourcesNavigatorView.show(UI.inspectorView.element);
var contentScriptsNavigatorView = new Sources.ContentScriptsNavigatorView();
contentScriptsNavigatorView.show(UI.inspectorView.element);
var uiSourceCodes = [];
async function addUISourceCode(url, isContentScript, frame) {
if (isContentScript) {
var uiSourceCode =
await SourcesTestRunner.addScriptUISourceCode(url, '', true, 42);
uiSourceCodes.push(uiSourceCode);
return;
}
TestRunner.addScriptForFrame(url, '', frame || TestRunner.mainFrame());
var uiSourceCode = await waitForUISourceCodeAdded(url);
uiSourceCodes.push(uiSourceCode);
}
async function addUISourceCode2(url) {
TestRunner.evaluateInPageAnonymously(`
window.workers = window.workers || [];
window.workers.push(new Worker('${url}'));
`);
var uiSourceCode = await waitForUISourceCodeAdded(url);
uiSourceCodes.push(uiSourceCode);
}
function waitForUISourceCodeAdded(url) {
var fulfill;
var promise = new Promise(x => fulfill = x);
Workspace.workspace.addEventListener(
Workspace.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded);
return promise;
function uiSourceCodeAdded(event) {
if (event.data.url() !== url)
return;
Workspace.workspace.removeEventListener(
Workspace.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded);
fulfill(event.data);
}
}
function revealUISourceCode(uiSourceCode) {
sourcesNavigatorView.revealUISourceCode(uiSourceCode);
contentScriptsNavigatorView.revealUISourceCode(uiSourceCode);
}
var rootURL = 'http://localhost:8080/LayoutTests/inspector/debugger/';
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding first resource:');
await addUISourceCode(rootURL + 'foo/bar/script.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding second resource:');
await addUISourceCode(rootURL + 'foo/bar/script.js?a=2', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding resources into another frame:');
await addUISourceCode(rootURL + 'foo/bar/script.js?a=1', false, subframe);
await addUISourceCode(rootURL + 'foo/baz/script.js', false, subframe);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding resources into another target:');
await addUISourceCode2(TestRunner.url('resources/script1.js?a=3'));
await addUISourceCode2(TestRunner.url('resources/script2.js'));
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding content scripts and some random resources:');
await addUISourceCode(rootURL + 'foo/bar/contentScript2.js?a=1', true);
await addUISourceCode(rootURL + 'foo/bar/contentScript.js?a=2', true);
await addUISourceCode(rootURL + 'foo/bar/contentScript.js?a=1', true);
await addUISourceCode('http://example.com/', false);
await addUISourceCode('http://example.com/?a=b', false);
await addUISourceCode(
'http://example.com/the%2fdir/foo?bar=100&baz=a%20%2fb', false);
// Verify that adding invalid URL does not throw exception.
await addUISourceCode(
'http://example.com/the%2fdir/foo?bar=100%&baz=a%20%2fb', false);
await addUISourceCode(
'http://example.com/path%20with%20spaces/white%20space.html', false);
await addUISourceCode('?a=b', false);
await addUISourceCode(
'very_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_url',
false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
SourcesTestRunner.dumpNavigatorViewInAllModes(contentScriptsNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Revealing first resource:');
revealUISourceCode(uiSourceCodes[0]);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
// Here we keep http://localhost:8080/LayoutTests/inspector/debugger2/ folder
// collapsed while adding resources into it.
TestRunner.addResult('\n\n================================================');
TestRunner.addResult(
'Adding some resources to change the way debugger folder looks like, first:');
var rootURL2 = 'http://localhost:8080/LayoutTests/inspector/debugger2/';
await addUISourceCode(rootURL2 + 'foo/bar/script.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Second:');
await addUISourceCode(rootURL2 + 'foo/bar/script.js?a=2', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Others:');
await addUISourceCode(rootURL2 + 'foo/bar/script.js?a=1', false);
await addUISourceCode(rootURL2 + 'foo/baz/script.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
var rootURL3 = 'http://localhost:8080/LayoutTests/inspector/debugger3/';
await addUISourceCode(
rootURL3 + 'hasOwnProperty/__proto__/constructor/foo.js', false);
await addUISourceCode(rootURL3 + 'hasOwnProperty/__proto__/foo.js', false);
await addUISourceCode(rootURL3 + 'hasOwnProperty/foo.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Revealing all resources:');
for (var i = 0; i < uiSourceCodes.length; ++i)
revealUISourceCode(uiSourceCodes[i]);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
SourcesTestRunner.dumpNavigatorViewInAllModes(contentScriptsNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Removing all resources:');
for (const target of SDK.targetManager.targets()) {
if (target !== TestRunner.mainTarget)
Bindings.debuggerWorkspaceBinding.resetForTest(target);
}
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
SourcesTestRunner.dumpNavigatorViewInAllModes(contentScriptsNavigatorView);
TestRunner.completeTest();
})();
| chromium/chromium | third_party/blink/web_tests/http/tests/devtools/sources/debugger/navigator-view.js | JavaScript | bsd-3-clause | 7,615 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function waitUntilIdle() {
return new Promise(resolve=>{
window.requestIdleCallback(()=>resolve());
});
}
(async function() {
TestRunner.addResult(`Tests V8 code cache for javascript resources\n`);
await TestRunner.loadLegacyModule('timeline'); await TestRunner.loadTestModule('performance_test_runner');
await TestRunner.showPanel('timeline');
// Clear browser cache to avoid any existing entries for the fetched
// scripts in the cache.
SDK.multitargetNetworkManager.clearBrowserCache();
// There are two scripts:
// [A] http://127.0.0.1:8000/devtools/resources/v8-cache-script.cgi
// [B] http://localhost:8000/devtools/resources/v8-cache-script.cgi
// An iframe that loads [A].
// The script is executed as a parser-inserted script,
// to keep the ScriptResource on the MemoryCache.
// ScriptResources for dynamically-inserted <script>s can be
// garbage-collected and thus removed from MemoryCache after its execution.
const scope = 'resources/same-origin-script.html';
// An iframe that loads [B].
const scopeCrossOrigin = 'resources/cross-origin-script.html';
TestRunner.addResult('--- Trace events related to code caches ------');
await PerformanceTestRunner.startTimeline();
async function stopAndPrintTimeline() {
await PerformanceTestRunner.stopTimeline();
await PerformanceTestRunner.printTimelineRecordsWithDetails(
TimelineModel.TimelineModel.RecordType.CompileScript,
TimelineModel.TimelineModel.RecordType.CacheScript);
}
async function expectationComment(msg) {
await stopAndPrintTimeline();
TestRunner.addResult(msg);
await PerformanceTestRunner.startTimeline();
}
// Load [A] thrice. With the current V8 heuristics (defined in
// third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc) we produce
// cache on second fetch and consume it in the third fetch. This tests these
// heuristics.
// Note that addIframe() waits for iframe's load event, which waits for the
// <script> loading.
await expectationComment('Load [A] 1st time. Produce timestamp. -->');
await TestRunner.addIframe(scope);
await expectationComment('Load [A] 2nd time. Produce code cache. -->');
await TestRunner.addIframe(scope);
await waitUntilIdle();
await expectationComment('Load [A] 3rd time. Consume code cache. -->');
await TestRunner.addIframe(scope);
await expectationComment('Load [B]. Should not use the cached code. -->');
await TestRunner.addIframe(scopeCrossOrigin);
await expectationComment('Load [A] again from MemoryCache. ' +
'Should use the cached code. -->');
await TestRunner.addIframe(scope);
await expectationComment('Clear [A] from MemoryCache. -->');
// Blink evicts previous Resource when a new request to the same URL but with
// different resource type is started. We fetch() to the URL of [A], and thus
// evicts the previous ScriptResource of [A].
await TestRunner.evaluateInPageAsync(
`fetch('/devtools/resources/v8-cache-script.cgi')`);
await expectationComment('Load [A] from Disk Cache. -->');
// As we cleared [A] from MemoryCache, this doesn't hit MemoryCache, but still
// hits Disk Cache.
await TestRunner.addIframe(scope);
await stopAndPrintTimeline();
TestRunner.addResult('-----------------------------------------------');
TestRunner.completeTest();
})();
| chromium/chromium | third_party/blink/web_tests/http/tests/devtools/isolated-code-cache/same-origin-test.js | JavaScript | bsd-3-clause | 3,533 |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
namespace WebsitePanel.Providers.HostedSolution
{
public class BaseStatistics
{
public string TopResellerName { get; set; }
public string ResellerName { get; set; }
public string CustomerName { get; set; }
public DateTime CustomerCreated { get; set; }
public string HostingSpace { get; set; }
public string OrganizationName { get; set; }
public DateTime OrganizationCreated { get; set; }
public string OrganizationID { get; set; }
public DateTime HostingSpaceCreated
{
get;
set;
}
}
}
| simonegli8/Websitepanel | WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/BaseStatistics.cs | C# | bsd-3-clause | 2,325 |
<?php
/**
* PEAR_Command_Auth (login, logout commands)
*
* PHP versions 4 and 5
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Auth.php,v 1.36 2009/02/24 23:39:29 dufuz Exp $
* @link http://pear.php.net/package/PEAR
* @since File available since Release 0.1
* @deprecated since 1.8.0alpha1
*/
/**
* base class
*/
require_once 'PEAR/Command/Channels.php';
/**
* PEAR commands for login/logout
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.8.1
* @link http://pear.php.net/package/PEAR
* @since Class available since Release 0.1
* @deprecated since 1.8.0alpha1
*/
class PEAR_Command_Auth extends PEAR_Command_Channels
{
var $commands = array(
'login' => array(
'summary' => 'Connects and authenticates to remote server [Deprecated in favor of channel-login]',
'shortcut' => 'li',
'function' => 'doLogin',
'options' => array(),
'doc' => '<channel name>
WARNING: This function is deprecated in favor of using channel-login
Log in to a remote channel server. If <channel name> is not supplied,
the default channel is used. To use remote functions in the installer
that require any kind of privileges, you need to log in first. The
username and password you enter here will be stored in your per-user
PEAR configuration (~/.pearrc on Unix-like systems). After logging
in, your username and password will be sent along in subsequent
operations on the remote server.',
),
'logout' => array(
'summary' => 'Logs out from the remote server [Deprecated in favor of channel-logout]',
'shortcut' => 'lo',
'function' => 'doLogout',
'options' => array(),
'doc' => '
WARNING: This function is deprecated in favor of using channel-logout
Logs out from the remote server. This command does not actually
connect to the remote server, it only deletes the stored username and
password from your user configuration.',
)
);
/**
* PEAR_Command_Auth constructor.
*
* @access public
*/
function PEAR_Command_Auth(&$ui, &$config)
{
parent::PEAR_Command_Channels($ui, $config);
}
} | PatidarWeb/pimcore | pimcore/lib/PEAR/Command/Auth.php | PHP | bsd-3-clause | 2,657 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Json_Server
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ResponseTest.php 24464 2011-09-24 14:06:34Z mcleod@spaceweb.nl $
*/
// Call Zend_Json_Server_ResponseTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
define("PHPUnit_MAIN_METHOD", "Zend_Json_Server_ResponseTest::main");
}
require_once 'Zend/Json/Server/Response.php';
require_once 'Zend/Json/Server/Error.php';
require_once 'Zend/Json.php';
/**
* Test class for Zend_Json_Server_Response
*
* @category Zend
* @package Zend_Json_Server
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Json
* @group Zend_Json_Server
*/
class Zend_Json_Server_ResponseTest extends PHPUnit_Framework_TestCase
{
/**
* Runs the test methods of this class.
*
* @return void
*/
public static function main()
{
$suite = new PHPUnit_Framework_TestSuite("Zend_Json_Server_ResponseTest");
$result = PHPUnit_TextUI_TestRunner::run($suite);
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*
* @return void
*/
public function setUp()
{
$this->response = new Zend_Json_Server_Response();
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*
* @return void
*/
public function tearDown()
{
}
public function testResultShouldBeNullByDefault()
{
$this->assertNull($this->response->getResult());
}
public function testResultAccessorsShouldWorkWithNormalInput()
{
foreach (array(true, 'foo', 2, 2.0, array(), array('foo' => 'bar')) as $result) {
$this->response->setResult($result);
$this->assertEquals($result, $this->response->getResult());
}
}
public function testResultShouldNotBeErrorByDefault()
{
$this->assertFalse($this->response->isError());
}
public function testSettingErrorShouldMarkRequestAsError()
{
$error = new Zend_Json_Server_Error();
$this->response->setError($error);
$this->assertTrue($this->response->isError());
}
public function testShouldBeAbleToRetrieveErrorObject()
{
$error = new Zend_Json_Server_Error();
$this->response->setError($error);
$this->assertSame($error, $this->response->getError());
}
public function testIdShouldBeNullByDefault()
{
$this->assertNull($this->response->getId());
}
public function testIdAccesorsShouldWorkWithNormalInput()
{
$this->response->setId('foo');
$this->assertEquals('foo', $this->response->getId());
}
public function testVersionShouldBeNullByDefault()
{
$this->assertNull($this->response->getVersion());
}
public function testVersionShouldBeLimitedToV2()
{
$this->response->setVersion('2.0');
$this->assertEquals('2.0', $this->response->getVersion());
foreach (array('a', 1, '1.0', array(), true) as $version) {
$this->response->setVersion($version);
$this->assertNull($this->response->getVersion());
}
}
public function testResponseShouldBeAbleToCastToJson()
{
$this->response->setResult(true)
->setId('foo')
->setVersion('2.0');
$json = $this->response->toJson();
$test = Zend_Json::decode($json);
$this->assertTrue(is_array($test));
$this->assertTrue(array_key_exists('result', $test));
// assertion changed to false, because 'error' may not coexist with 'result'
$this->assertFalse(array_key_exists('error', $test), "'error' may not coexist with 'result'");
$this->assertTrue(array_key_exists('id', $test));
$this->assertTrue(array_key_exists('jsonrpc', $test));
$this->assertTrue($test['result']);
$this->assertEquals($this->response->getId(), $test['id']);
$this->assertEquals($this->response->getVersion(), $test['jsonrpc']);
}
public function testResponseShouldCastErrorToJsonIfIsError()
{
$error = new Zend_Json_Server_Error();
$error->setCode(Zend_Json_Server_Error::ERROR_INTERNAL)
->setMessage('error occurred');
$this->response->setId('foo')
->setResult(true)
->setError($error);
$json = $this->response->toJson();
$test = Zend_Json::decode($json);
$this->assertTrue(is_array($test));
$this->assertFalse(array_key_exists('result', $test), "'result' may not coexist with 'error'");
$this->assertTrue(array_key_exists('id', $test));
$this->assertFalse(array_key_exists('jsonrpc', $test));
$this->assertEquals($this->response->getId(), $test['id']);
$this->assertEquals($error->getCode(), $test['error']['code']);
$this->assertEquals($error->getMessage(), $test['error']['message']);
}
public function testCastToStringShouldCastToJson()
{
$this->response->setResult(true)
->setId('foo');
$json = $this->response->__toString();
$test = Zend_Json::decode($json);
$this->assertTrue(is_array($test));
$this->assertTrue(array_key_exists('result', $test));
$this->assertFalse(array_key_exists('error', $test), "'error' may not coexist with 'result'");
$this->assertTrue(array_key_exists('id', $test));
$this->assertFalse(array_key_exists('jsonrpc', $test));
$this->assertTrue($test['result']);
$this->assertEquals($this->response->getId(), $test['id']);
}
}
// Call Zend_Json_Server_ResponseTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Json_Server_ResponseTest::main") {
Zend_Json_Server_ResponseTest::main();
}
| mridgway/Zend-Framework-1.x-Mirror | tests/Zend/Json/Server/ResponseTest.php | PHP | bsd-3-clause | 6,794 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ServiceBus.Amqp
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Amqp;
using Azure.Amqp.Encoding;
using Core;
using Framing;
using Primitives;
internal sealed class AmqpSubscriptionClient : IInnerSubscriptionClient
{
int prefetchCount;
readonly object syncLock;
MessageReceiver innerReceiver;
static AmqpSubscriptionClient()
{
AmqpCodec.RegisterKnownTypes(AmqpTrueFilterCodec.Name, AmqpTrueFilterCodec.Code, () => new AmqpTrueFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpFalseFilterCodec.Name, AmqpFalseFilterCodec.Code, () => new AmqpFalseFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpCorrelationFilterCodec.Name, AmqpCorrelationFilterCodec.Code, () => new AmqpCorrelationFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpSqlFilterCodec.Name, AmqpSqlFilterCodec.Code, () => new AmqpSqlFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpEmptyRuleActionCodec.Name, AmqpEmptyRuleActionCodec.Code, () => new AmqpEmptyRuleActionCodec());
AmqpCodec.RegisterKnownTypes(AmqpSqlRuleActionCodec.Name, AmqpSqlRuleActionCodec.Code, () => new AmqpSqlRuleActionCodec());
AmqpCodec.RegisterKnownTypes(AmqpRuleDescriptionCodec.Name, AmqpRuleDescriptionCodec.Code, () => new AmqpRuleDescriptionCodec());
}
public AmqpSubscriptionClient(
string path,
ServiceBusConnection servicebusConnection,
RetryPolicy retryPolicy,
ICbsTokenProvider cbsTokenProvider,
int prefetchCount = 0,
ReceiveMode mode = ReceiveMode.ReceiveAndDelete)
{
this.syncLock = new object();
this.Path = path;
this.ServiceBusConnection = servicebusConnection;
this.RetryPolicy = retryPolicy;
this.CbsTokenProvider = cbsTokenProvider;
this.PrefetchCount = prefetchCount;
this.ReceiveMode = mode;
}
public MessageReceiver InnerReceiver
{
get
{
if (this.innerReceiver == null)
{
lock (this.syncLock)
{
if (this.innerReceiver == null)
{
this.innerReceiver = new MessageReceiver(
this.Path,
MessagingEntityType.Subscriber,
this.ReceiveMode,
this.ServiceBusConnection,
this.CbsTokenProvider,
this.RetryPolicy,
this.PrefetchCount);
}
}
}
return this.innerReceiver;
}
}
/// <summary>
/// Gets or sets the number of messages that the subscription client can simultaneously request.
/// </summary>
/// <value>The number of messages that the subscription client can simultaneously request.</value>
public int PrefetchCount
{
get => this.prefetchCount;
set
{
if (value < 0)
{
throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0.");
}
this.prefetchCount = value;
if (this.innerReceiver != null)
{
this.innerReceiver.PrefetchCount = value;
}
}
}
ServiceBusConnection ServiceBusConnection { get; }
RetryPolicy RetryPolicy { get; }
ICbsTokenProvider CbsTokenProvider { get; }
ReceiveMode ReceiveMode { get; }
string Path { get; }
public Task CloseAsync()
{
return this.innerReceiver?.CloseAsync();
}
public async Task OnAddRuleAsync(RuleDescription description)
{
try
{
var amqpRequestMessage = AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.AddRuleOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = description.Name;
amqpRequestMessage.Map[ManagementConstants.Properties.RuleDescription] =
AmqpMessageConverter.GetRuleDescriptionMap(description);
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
if (response.StatusCode != AmqpResponseStatusCode.OK)
{
throw response.ToMessagingContractException();
}
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
public async Task OnRemoveRuleAsync(string ruleName)
{
try
{
var amqpRequestMessage =
AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.RemoveRuleOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = ruleName;
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
if (response.StatusCode != AmqpResponseStatusCode.OK)
{
throw response.ToMessagingContractException();
}
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
public async Task<IList<RuleDescription>> OnGetRulesAsync(int top, int skip)
{
try
{
var amqpRequestMessage =
AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.EnumerateRulesOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.Top] = top;
amqpRequestMessage.Map[ManagementConstants.Properties.Skip] = skip;
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
var ruleDescriptions = new List<RuleDescription>();
if (response.StatusCode == AmqpResponseStatusCode.OK)
{
var ruleList = response.GetListValue<AmqpMap>(ManagementConstants.Properties.Rules);
foreach (var entry in ruleList)
{
var amqpRule = (AmqpRuleDescriptionCodec)entry[ManagementConstants.Properties.RuleDescription];
var ruleDescription = AmqpMessageConverter.GetRuleDescription(amqpRule);
ruleDescriptions.Add(ruleDescription);
}
}
else if (response.StatusCode == AmqpResponseStatusCode.NoContent)
{
// Do nothing. Return empty list;
}
else
{
throw response.ToMessagingContractException();
}
return ruleDescriptions;
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
}
} | jamestao/azure-sdk-for-net | src/SDKs/ServiceBus/data-plane/src/Microsoft.Azure.ServiceBus/Amqp/AmqpSubscriptionClient.cs | C# | mit | 8,085 |
-- Function to test: Receive
-- Test against: Sending network card rate.
local luaunit = require "luaunit"
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local timer = require "timer"
local stats = require "stats"
local log = require "testlog"
local testlib = require "testlib"
local tconfig = require "tconfig"
local PKT_SIZE = 124
function master()
log:info( "Function to test: Receive" )
testlib:setRuntime( 10 )
testlib:masterPairMulti()
end
function slave1( txDev, rxDev )
-- Init queue
local txQueue = txDev:getTxQueue( 0 )
-- Init memory & bufs
local mem = memory.createMemPool( function( buf )
buf:getEthernetPacket():fill{
pktLength = PKT_SIZE,
ethSrc = txQueue,
ethDst = "10:11:12:13:14:15"
}
end)
local bufs = mem:bufArray()
-- Init counter & timer
local ctr = stats:newDevTxCounter( txDev , "plain" )
local runtime = timer:new( testlib.getRuntime() )
-- Send packets
while dpdk.running() and runtime:running() do
bufs:alloc( PKT_SIZE )
txQueue:send( bufs )
ctr:update()
end
-- Finalize counter and get stats
ctr:finalize()
local x , mbit = ctr:getStats()
-- Return measured rate
return mbit.avg
end
function slave2( txDev , rxDev )
-- Init queue
local queue = rxDev:getRxQueue( 0 )
-- Init bufs
local bufs = memory.bufArray()
-- Init counter & timer
local ctr = stats:newManualRxCounter(queue.dev, "plain")
local runtime = timer:new(10)
-- Receive packets
while runtime:running() and dpdk.running() do
local rx = queue:tryRecv(bufs, 10)
bufs:freeAll()
ctr:updateWithSize(rx, PKT_SIZE)
end
-- Finalize counter and get stats
ctr:finalize()
local x , mbit = ctr:getStats()
-- Return measured rate
return mbit.avg
end
-- Compare measured rates
function compare( sRate , rRate )
-- Round receive rate down
return2 = math.floor( rRate )
-- Round max rate down | substract 10 MBit/s (max. 1% of rate).
srate = math.floor( math.min( sRate - 10 , sRate * 99 / 100 ) )
-- Compare rates
log:info( "Expected receive rate: " .. math.floor( sRate ) .. " MBit/s" )
if ( sRate > rRate ) then
log:warn( "Measured receive rate: " .. rRate .. " MBit/s | Missing: " .. sRate - rRate .. " MBit/s")
else
log:info( "Measured receive rate: " .. math.floor( sRate ) .. " MBit/s")
end
-- Return result
return sRate <= rRate
end
| bmichalo/MoonGen | test/tests/02-receive.lua | Lua | mit | 2,364 |
require 'support/doubled_classes'
module RSpec
module Mocks
RSpec.describe 'An instance double with the doubled class loaded' do
include_context "with isolated configuration"
before do
RSpec::Mocks.configuration.verify_doubled_constant_names = true
end
it 'only allows instance methods that exist to be stubbed' do
o = instance_double('LoadedClass', :defined_instance_method => 1)
expect(o.defined_instance_method).to eq(1)
prevents(/does not implement the instance method/) { allow(o).to receive(:undefined_instance_method) }
prevents(/does not implement the instance method/) { allow(o).to receive(:defined_class_method) }
end
it 'only allows instance methods that exist to be expected' do
o = instance_double('LoadedClass')
expect(o).to receive(:defined_instance_method)
o.defined_instance_method
prevents { expect(o).to receive(:undefined_instance_method) }
prevents { expect(o).to receive(:defined_class_method) }
prevents { expect(o).to receive(:undefined_instance_method) }
prevents { expect(o).to receive(:defined_class_method) }
end
USE_CLASS_DOUBLE_MSG = "Perhaps you meant to use `class_double`"
it "suggests using `class_double` when a class method is stubbed" do
o = instance_double("LoadedClass")
prevents(a_string_including(USE_CLASS_DOUBLE_MSG)) { allow(o).to receive(:defined_class_method) }
end
it "doesn't suggest `class_double` when a non-class method is stubbed" do
o = instance_double("LoadedClass")
prevents(a_string_excluding(USE_CLASS_DOUBLE_MSG)) { allow(o).to receive(:undefined_class_method) }
end
it 'allows `send` to be stubbed if it is defined on the class' do
o = instance_double('LoadedClass')
allow(o).to receive(:send).and_return("received")
expect(o.send(:msg)).to eq("received")
end
it 'gives a descriptive error message for NoMethodError' do
o = instance_double("LoadedClass")
expect {
o.defined_private_method
}.to raise_error(NoMethodError,
a_string_including("InstanceDouble(LoadedClass)"))
end
it 'does not allow dynamic methods to be expected' do
# This isn't possible at the moment since an instance of the class
# would be required for the verification, and we only have the
# class itself.
#
# This spec exists as "negative" documentation of the absence of a
# feature, to highlight the asymmetry from class doubles (that do
# support this behaviour).
prevents {
instance_double('LoadedClass', :dynamic_instance_method => 1)
}
end
it 'checks the arity of stubbed methods' do
o = instance_double('LoadedClass')
prevents {
expect(o).to receive(:defined_instance_method).with(:a)
}
reset o
end
it 'checks that stubbed methods are invoked with the correct arity' do
o = instance_double('LoadedClass', :defined_instance_method => 25)
expect {
o.defined_instance_method(:a)
}.to raise_error(ArgumentError,
"Wrong number of arguments. Expected 0, got 1.")
end
if required_kw_args_supported?
it 'allows keyword arguments' do
o = instance_double('LoadedClass', :kw_args_method => true)
expect(o.kw_args_method(1, :required_arg => 'something')).to eq(true)
end
context 'for a method that only accepts keyword args' do
it 'allows hash matchers like `hash_including` to be used in place of the keywords arg hash' do
o = instance_double('LoadedClass')
expect(o).to receive(:kw_args_method).
with(1, hash_including(:required_arg => 1))
o.kw_args_method(1, :required_arg => 1)
end
it 'allows anything matcher to be used in place of the keywords arg hash' do
o = instance_double('LoadedClass')
expect(o).to receive(:kw_args_method).with(1, anything)
o.kw_args_method(1, :required_arg => 1)
end
it 'still checks positional arguments when matchers used for keyword args' do
o = instance_double('LoadedClass')
prevents(/Expected 1, got 3/) {
expect(o).to receive(:kw_args_method).
with(1, 2, 3, hash_including(:required_arg => 1))
}
reset o
end
it 'does not allow matchers to be used in an actual method call' do
o = instance_double('LoadedClass')
matcher = hash_including(:required_arg => 1)
allow(o).to receive(:kw_args_method).with(1, matcher)
expect {
o.kw_args_method(1, matcher)
}.to raise_error(ArgumentError)
end
end
context 'for a method that accepts a mix of optional keyword and positional args' do
it 'allows hash matchers like `hash_including` to be used in place of the keywords arg hash' do
o = instance_double('LoadedClass')
expect(o).to receive(:mixed_args_method).with(1, 2, hash_including(:optional_arg_1 => 1))
o.mixed_args_method(1, 2, :optional_arg_1 => 1)
end
end
it 'checks that stubbed methods with required keyword args are ' +
'invoked with the required arguments' do
o = instance_double('LoadedClass', :kw_args_method => true)
expect {
o.kw_args_method(:optional_arg => 'something')
}.to raise_error(ArgumentError)
end
end
it 'validates `with` args against the method signature when stubbing a method' do
dbl = instance_double(LoadedClass)
prevents(/Wrong number of arguments. Expected 2, got 3./) {
allow(dbl).to receive(:instance_method_with_two_args).with(3, :foo, :args)
}
end
it 'allows class to be specified by constant' do
o = instance_double(LoadedClass, :defined_instance_method => 1)
expect(o.defined_instance_method).to eq(1)
end
context "when the class const has been previously stubbed" do
before { class_double(LoadedClass).as_stubbed_const }
it "uses the original class to verify against for `instance_double('LoadedClass')`" do
o = instance_double("LoadedClass")
allow(o).to receive(:defined_instance_method)
prevents { allow(o).to receive(:undefined_method) }
end
it "uses the original class to verify against for `instance_double(LoadedClass)`" do
o = instance_double(LoadedClass)
allow(o).to receive(:defined_instance_method)
prevents { allow(o).to receive(:undefined_method) }
end
end
context "when given a class that has an overriden `#name` method" do
it "properly verifies" do
o = instance_double(LoadedClassWithOverridenName)
allow(o).to receive(:defined_instance_method)
prevents { allow(o).to receive(:undefined_method) }
end
end
context 'for null objects' do
let(:obj) { instance_double('LoadedClass').as_null_object }
it 'only allows defined methods' do
expect(obj.defined_instance_method).to eq(obj)
prevents { obj.undefined_method }
prevents { obj.send(:undefined_method) }
prevents { obj.__send__(:undefined_method) }
end
it 'verifies arguments' do
expect {
obj.defined_instance_method(:too, :many, :args)
}.to raise_error(ArgumentError, "Wrong number of arguments. Expected 0, got 3.")
end
it "includes the double's name in a private method error" do
expect {
obj.rand
}.to raise_error(NoMethodError, a_string_including("private", "InstanceDouble(LoadedClass)"))
end
it 'reports what public messages it responds to accurately' do
expect(obj.respond_to?(:defined_instance_method)).to be true
expect(obj.respond_to?(:defined_instance_method, true)).to be true
expect(obj.respond_to?(:defined_instance_method, false)).to be true
expect(obj.respond_to?(:undefined_method)).to be false
expect(obj.respond_to?(:undefined_method, true)).to be false
expect(obj.respond_to?(:undefined_method, false)).to be false
end
it 'reports that it responds to defined private methods when the appropriate arg is passed' do
expect(obj.respond_to?(:defined_private_method)).to be false
expect(obj.respond_to?(:defined_private_method, true)).to be true
expect(obj.respond_to?(:defined_private_method, false)).to be false
end
if RUBY_VERSION.to_f < 2.0 # respond_to?(:protected_method) changed behavior in Ruby 2.0.
it 'reports that it responds to protected methods' do
expect(obj.respond_to?(:defined_protected_method)).to be true
expect(obj.respond_to?(:defined_protected_method, true)).to be true
expect(obj.respond_to?(:defined_protected_method, false)).to be true
end
else
it 'reports that it responds to protected methods when the appropriate arg is passed' do
expect(obj.respond_to?(:defined_protected_method)).to be false
expect(obj.respond_to?(:defined_protected_method, true)).to be true
expect(obj.respond_to?(:defined_protected_method, false)).to be false
end
end
end
end
end
end
| ducthanh/rspec-mocks | spec/rspec/mocks/verifying_doubles/instance_double_with_class_loaded_spec.rb | Ruby | mit | 9,728 |
#!/bin/bash
wget -N https://berlintemplates.blob.core.windows.net/arm-templates/MultiNodeEthereumNetwork/scripts/configure-geth.sh
wget -N https://berlintemplates.blob.core.windows.net/arm-templates/MultiNodeEthereumNetwork/scripts/start-private-blockchain.sh
wget -N https://berlintemplates.blob.core.windows.net/arm-templates/MultiNodeEthereumNetwork/scripts/helpers/attach-geth.sh
wget -N https://berlintemplates.blob.core.windows.net/arm-templates/MultiNodeEthereumNetwork/scripts/helpers/start.sh
wget -N https://berlintemplates.blob.core.windows.net/arm-templates/MultiNodeEthereumNetwork/scripts/helpers/stop.sh
wget -N https://berlintemplates.blob.core.windows.net/arm-templates/MultiNodeEthereumNetwork/scripts/helpers/getenodeurl.sh
chmod 744 configure-geth.sh start-private-blockchain.sh attach-geth.sh start.sh stop.sh getenodeurl.sh
| netwmr01/azure-quickstart-templates | ethereum-consortium-blockchain-network/scripts/helpers/getfiles.sh | Shell | mit | 847 |
--------------------------------------------------------------------------------
-- form.lua, v0.3: generates html for forms
-- This file is a part of Sailor project
-- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net>
-- License: MIT
-- http://sailorproject.org
--------------------------------------------------------------------------------
local form = {}
local tinsert, tconcat = table.insert, table.concat
local model_name
local meta = {}
meta.__call = function(_,mname)
model_name = mname
return form
end
setmetatable(form,meta)
local function defaults(model,attribute,html_options)
return model[attribute] or '', model['@name']..':'..attribute, html_options or ''
end
function form.text(model,attribute,html_options)
local value, name, html_options = defaults(model,attribute,html_options)
return '<input type="text" value="'..value..'" name="'..name..'" '..html_options..' />'
end
function form.textarea(model,attribute,html_options)
local value, name, html_options = defaults(model,attribute,html_options)
return '<textarea name="'..name..'" '..html_options..'>'..value..'</textarea>'
end
function form.file(model,attribute,html_options)
local value, name, html_options = defaults(model,attribute,html_options)
return '<input type="file" name="'..name..'" '..html_options..'>'..value..'</textarea>'
end
function form.dropdown(model,attribute,list,prompt,html_options)
local value, name, html_options = defaults(model,attribute,html_options)
list = list or {}
local html = {}
tinsert(html,'<select name="'..name..'" '..html_options..'>')
if prompt then
tinsert(html,'<option value="" selected>'..prompt..'</option>')
end
for k,v in pairs(list) do
local selected = ''
if k == value then
selected = ' selected'
end
tinsert(html,'<option value="'..k..'"'..selected..'>'..v..'</option>')
end
tinsert(html,'</select>')
return tconcat(html)
end
function form.password(model,attribute,html_options)
local value, name, html_options = defaults(model,attribute,html_options)
return '<input type="password" value="'..value..'" name="'..name..'" '..html_options..' />'
end
-- layout: horizontal(default) or vertical
function form.radio_list(model,attribute,list,default,layout,html_options)
local value, name, html_options = defaults(model,attribute,html_options)
list = list or {}
local html = {}
for k,v in pairs(list) do
local check = ''
if k == value or (value == '' and k == default) then
check = ' checked'
end
tinsert(html, '<input type="radio" name="'..name..'" '..'value="'..k..'" '..check..html_options..'/> '..v)
end
if layout == 'vertical' then
return tconcat(html,'<br/>')
end
return tconcat(html,' ')
end
-- checked: boolean
function form.checkbox(model,attribute,label,checked,html_options)
local value, name, html_options = defaults(model,attribute,html_options)
label = label or attribute
local check = ''
if (value ~= nil and value ~= '' and value ~= 0 and value ~= '0') or checked == true then
check = ' checked '
end
return '<input type="checkbox" name="'..name..'"'..check..html_options..'/> '..label
end
function form.ify(data)
local new_data = {}
for k,v in pairs(data) do
new_data[model_name .. ':' .. k] = v
end
return new_data
end
return form
| jeary/sailor | src/sailor/form.lua | Lua | mit | 3,256 |
# encoding: utf-8
require 'test_helper'
class Filters
include Liquid::StandardFilters
end
class TestThing
attr_reader :foo
def initialize
@foo = 0
end
def to_s
"woot: #{@foo}"
end
def [](whatever)
to_s
end
def to_liquid
@foo += 1
self
end
end
class TestDrop < Liquid::Drop
def test
"testfoo"
end
end
class TestEnumerable < Liquid::Drop
include Enumerable
def each(&block)
[ { "foo" => 1, "bar" => 2 }, { "foo" => 2, "bar" => 1 }, { "foo" => 3, "bar" => 3 } ].each(&block)
end
end
class NumberLikeThing < Liquid::Drop
def initialize(amount)
@amount = amount
end
def to_number
@amount
end
end
class StandardFiltersTest < Minitest::Test
include Liquid
def setup
@filters = Filters.new
end
def test_size
assert_equal 3, @filters.size([1, 2, 3])
assert_equal 0, @filters.size([])
assert_equal 0, @filters.size(nil)
end
def test_downcase
assert_equal 'testing', @filters.downcase("Testing")
assert_equal '', @filters.downcase(nil)
end
def test_upcase
assert_equal 'TESTING', @filters.upcase("Testing")
assert_equal '', @filters.upcase(nil)
end
def test_slice
assert_equal 'oob', @filters.slice('foobar', 1, 3)
assert_equal 'oobar', @filters.slice('foobar', 1, 1000)
assert_equal '', @filters.slice('foobar', 1, 0)
assert_equal 'o', @filters.slice('foobar', 1, 1)
assert_equal 'bar', @filters.slice('foobar', 3, 3)
assert_equal 'ar', @filters.slice('foobar', -2, 2)
assert_equal 'ar', @filters.slice('foobar', -2, 1000)
assert_equal 'r', @filters.slice('foobar', -1)
assert_equal '', @filters.slice(nil, 0)
assert_equal '', @filters.slice('foobar', 100, 10)
assert_equal '', @filters.slice('foobar', -100, 10)
assert_equal 'oob', @filters.slice('foobar', '1', '3')
assert_raises(Liquid::ArgumentError) do
@filters.slice('foobar', nil)
end
assert_raises(Liquid::ArgumentError) do
@filters.slice('foobar', 0, "")
end
end
def test_slice_on_arrays
input = 'foobar'.split(//)
assert_equal %w(o o b), @filters.slice(input, 1, 3)
assert_equal %w(o o b a r), @filters.slice(input, 1, 1000)
assert_equal %w(), @filters.slice(input, 1, 0)
assert_equal %w(o), @filters.slice(input, 1, 1)
assert_equal %w(b a r), @filters.slice(input, 3, 3)
assert_equal %w(a r), @filters.slice(input, -2, 2)
assert_equal %w(a r), @filters.slice(input, -2, 1000)
assert_equal %w(r), @filters.slice(input, -1)
assert_equal %w(), @filters.slice(input, 100, 10)
assert_equal %w(), @filters.slice(input, -100, 10)
end
def test_truncate
assert_equal '1234...', @filters.truncate('1234567890', 7)
assert_equal '1234567890', @filters.truncate('1234567890', 20)
assert_equal '...', @filters.truncate('1234567890', 0)
assert_equal '1234567890', @filters.truncate('1234567890')
assert_equal "测试...", @filters.truncate("测试测试测试测试", 5)
assert_equal '12341', @filters.truncate("1234567890", 5, 1)
end
def test_split
assert_equal ['12', '34'], @filters.split('12~34', '~')
assert_equal ['A? ', ' ,Z'], @filters.split('A? ~ ~ ~ ,Z', '~ ~ ~')
assert_equal ['A?Z'], @filters.split('A?Z', '~')
assert_equal [], @filters.split(nil, ' ')
assert_equal ['A', 'Z'], @filters.split('A1Z', 1)
end
def test_escape
assert_equal '<strong>', @filters.escape('<strong>')
assert_equal '1', @filters.escape(1)
assert_equal '2001-02-03', @filters.escape(Date.new(2001, 2, 3))
assert_nil @filters.escape(nil)
end
def test_h
assert_equal '<strong>', @filters.h('<strong>')
assert_equal '1', @filters.h(1)
assert_equal '2001-02-03', @filters.h(Date.new(2001, 2, 3))
assert_nil @filters.h(nil)
end
def test_escape_once
assert_equal '<strong>Hulk</strong>', @filters.escape_once('<strong>Hulk</strong>')
end
def test_url_encode
assert_equal 'foo%2B1%40example.com', @filters.url_encode('foo+1@example.com')
assert_equal '1', @filters.url_encode(1)
assert_equal '2001-02-03', @filters.url_encode(Date.new(2001, 2, 3))
assert_nil @filters.url_encode(nil)
end
def test_url_decode
assert_equal 'foo bar', @filters.url_decode('foo+bar')
assert_equal 'foo bar', @filters.url_decode('foo%20bar')
assert_equal 'foo+1@example.com', @filters.url_decode('foo%2B1%40example.com')
assert_equal '1', @filters.url_decode(1)
assert_equal '2001-02-03', @filters.url_decode(Date.new(2001, 2, 3))
assert_nil @filters.url_decode(nil)
end
def test_truncatewords
assert_equal 'one two three', @filters.truncatewords('one two three', 4)
assert_equal 'one two...', @filters.truncatewords('one two three', 2)
assert_equal 'one two three', @filters.truncatewords('one two three')
assert_equal 'Two small (13” x 5.5” x 10” high) baskets fit inside one large basket (13”...', @filters.truncatewords('Two small (13” x 5.5” x 10” high) baskets fit inside one large basket (13” x 16” x 10.5” high) with cover.', 15)
assert_equal "测试测试测试测试", @filters.truncatewords('测试测试测试测试', 5)
assert_equal 'one two1', @filters.truncatewords("one two three", 2, 1)
end
def test_strip_html
assert_equal 'test', @filters.strip_html("<div>test</div>")
assert_equal 'test', @filters.strip_html("<div id='test'>test</div>")
assert_equal '', @filters.strip_html("<script type='text/javascript'>document.write('some stuff');</script>")
assert_equal '', @filters.strip_html("<style type='text/css'>foo bar</style>")
assert_equal 'test', @filters.strip_html("<div\nclass='multiline'>test</div>")
assert_equal 'test', @filters.strip_html("<!-- foo bar \n test -->test")
assert_equal '', @filters.strip_html(nil)
end
def test_join
assert_equal '1 2 3 4', @filters.join([1, 2, 3, 4])
assert_equal '1 - 2 - 3 - 4', @filters.join([1, 2, 3, 4], ' - ')
assert_equal '1121314', @filters.join([1, 2, 3, 4], 1)
end
def test_sort
assert_equal [1, 2, 3, 4], @filters.sort([4, 3, 2, 1])
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }], @filters.sort([{ "a" => 4 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a")
end
def test_sort_with_nils
assert_equal [1, 2, 3, 4, nil], @filters.sort([nil, 4, 3, 2, 1])
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }, {}], @filters.sort([{ "a" => 4 }, { "a" => 3 }, {}, { "a" => 1 }, { "a" => 2 }], "a")
end
def test_sort_when_property_is_sometimes_missing_puts_nils_last
input = [
{ "price" => 4, "handle" => "alpha" },
{ "handle" => "beta" },
{ "price" => 1, "handle" => "gamma" },
{ "handle" => "delta" },
{ "price" => 2, "handle" => "epsilon" }
]
expectation = [
{ "price" => 1, "handle" => "gamma" },
{ "price" => 2, "handle" => "epsilon" },
{ "price" => 4, "handle" => "alpha" },
{ "handle" => "delta" },
{ "handle" => "beta" }
]
assert_equal expectation, @filters.sort(input, "price")
end
def test_sort_natural
assert_equal ["a", "B", "c", "D"], @filters.sort_natural(["c", "D", "a", "B"])
assert_equal [{ "a" => "a" }, { "a" => "B" }, { "a" => "c" }, { "a" => "D" }], @filters.sort_natural([{ "a" => "D" }, { "a" => "c" }, { "a" => "a" }, { "a" => "B" }], "a")
end
def test_sort_natural_with_nils
assert_equal ["a", "B", "c", "D", nil], @filters.sort_natural([nil, "c", "D", "a", "B"])
assert_equal [{ "a" => "a" }, { "a" => "B" }, { "a" => "c" }, { "a" => "D" }, {}], @filters.sort_natural([{ "a" => "D" }, { "a" => "c" }, {}, { "a" => "a" }, { "a" => "B" }], "a")
end
def test_sort_natural_when_property_is_sometimes_missing_puts_nils_last
input = [
{ "price" => "4", "handle" => "alpha" },
{ "handle" => "beta" },
{ "price" => "1", "handle" => "gamma" },
{ "handle" => "delta" },
{ "price" => 2, "handle" => "epsilon" }
]
expectation = [
{ "price" => "1", "handle" => "gamma" },
{ "price" => 2, "handle" => "epsilon" },
{ "price" => "4", "handle" => "alpha" },
{ "handle" => "delta" },
{ "handle" => "beta" }
]
assert_equal expectation, @filters.sort_natural(input, "price")
end
def test_sort_natural_case_check
input = [
{ "key" => "X" },
{ "key" => "Y" },
{ "key" => "Z" },
{ "fake" => "t" },
{ "key" => "a" },
{ "key" => "b" },
{ "key" => "c" }
]
expectation = [
{ "key" => "a" },
{ "key" => "b" },
{ "key" => "c" },
{ "key" => "X" },
{ "key" => "Y" },
{ "key" => "Z" },
{ "fake" => "t" }
]
assert_equal expectation, @filters.sort_natural(input, "key")
assert_equal ["a", "b", "c", "X", "Y", "Z"], @filters.sort_natural(["X", "Y", "Z", "a", "b", "c"])
end
def test_sort_empty_array
assert_equal [], @filters.sort([], "a")
end
def test_sort_natural_empty_array
assert_equal [], @filters.sort_natural([], "a")
end
def test_legacy_sort_hash
assert_equal [{ a: 1, b: 2 }], @filters.sort({ a: 1, b: 2 })
end
def test_numerical_vs_lexicographical_sort
assert_equal [2, 10], @filters.sort([10, 2])
assert_equal [{ "a" => 2 }, { "a" => 10 }], @filters.sort([{ "a" => 10 }, { "a" => 2 }], "a")
assert_equal ["10", "2"], @filters.sort(["10", "2"])
assert_equal [{ "a" => "10" }, { "a" => "2" }], @filters.sort([{ "a" => "10" }, { "a" => "2" }], "a")
end
def test_uniq
assert_equal ["foo"], @filters.uniq("foo")
assert_equal [1, 3, 2, 4], @filters.uniq([1, 1, 3, 2, 3, 1, 4, 3, 2, 1])
assert_equal [{ "a" => 1 }, { "a" => 3 }, { "a" => 2 }], @filters.uniq([{ "a" => 1 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a")
testdrop = TestDrop.new
assert_equal [testdrop], @filters.uniq([testdrop, TestDrop.new], 'test')
end
def test_uniq_empty_array
assert_equal [], @filters.uniq([], "a")
end
def test_compact_empty_array
assert_equal [], @filters.compact([], "a")
end
def test_reverse
assert_equal [4, 3, 2, 1], @filters.reverse([1, 2, 3, 4])
end
def test_legacy_reverse_hash
assert_equal [{ a: 1, b: 2 }], @filters.reverse(a: 1, b: 2)
end
def test_map
assert_equal [1, 2, 3, 4], @filters.map([{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }], 'a')
assert_template_result 'abc', "{{ ary | map:'foo' | map:'bar' }}",
'ary' => [{ 'foo' => { 'bar' => 'a' } }, { 'foo' => { 'bar' => 'b' } }, { 'foo' => { 'bar' => 'c' } }]
end
def test_map_doesnt_call_arbitrary_stuff
assert_template_result "", '{{ "foo" | map: "__id__" }}'
assert_template_result "", '{{ "foo" | map: "inspect" }}'
end
def test_map_calls_to_liquid
t = TestThing.new
assert_template_result "woot: 1", '{{ foo | map: "whatever" }}', "foo" => [t]
end
def test_map_on_hashes
assert_template_result "4217", '{{ thing | map: "foo" | map: "bar" }}',
"thing" => { "foo" => [ { "bar" => 42 }, { "bar" => 17 } ] }
end
def test_legacy_map_on_hashes_with_dynamic_key
template = "{% assign key = 'foo' %}{{ thing | map: key | map: 'bar' }}"
hash = { "foo" => { "bar" => 42 } }
assert_template_result "42", template, "thing" => hash
end
def test_sort_calls_to_liquid
t = TestThing.new
Liquid::Template.parse('{{ foo | sort: "whatever" }}').render("foo" => [t])
assert t.foo > 0
end
def test_map_over_proc
drop = TestDrop.new
p = proc{ drop }
templ = '{{ procs | map: "test" }}'
assert_template_result "testfoo", templ, "procs" => [p]
end
def test_map_over_drops_returning_procs
drops = [
{
"proc" => ->{ "foo" },
},
{
"proc" => ->{ "bar" },
},
]
templ = '{{ drops | map: "proc" }}'
assert_template_result "foobar", templ, "drops" => drops
end
def test_map_works_on_enumerables
assert_template_result "123", '{{ foo | map: "foo" }}', "foo" => TestEnumerable.new
end
def test_sort_works_on_enumerables
assert_template_result "213", '{{ foo | sort: "bar" | map: "foo" }}', "foo" => TestEnumerable.new
end
def test_first_and_last_call_to_liquid
assert_template_result 'foobar', '{{ foo | first }}', 'foo' => [ThingWithToLiquid.new]
assert_template_result 'foobar', '{{ foo | last }}', 'foo' => [ThingWithToLiquid.new]
end
def test_truncate_calls_to_liquid
assert_template_result "wo...", '{{ foo | truncate: 5 }}', "foo" => TestThing.new
end
def test_date
assert_equal 'May', @filters.date(Time.parse("2006-05-05 10:00:00"), "%B")
assert_equal 'June', @filters.date(Time.parse("2006-06-05 10:00:00"), "%B")
assert_equal 'July', @filters.date(Time.parse("2006-07-05 10:00:00"), "%B")
assert_equal 'May', @filters.date("2006-05-05 10:00:00", "%B")
assert_equal 'June', @filters.date("2006-06-05 10:00:00", "%B")
assert_equal 'July', @filters.date("2006-07-05 10:00:00", "%B")
assert_equal '2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", "")
assert_equal '2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", "")
assert_equal '2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", "")
assert_equal '2006-07-05 10:00:00', @filters.date("2006-07-05 10:00:00", nil)
assert_equal '07/05/2006', @filters.date("2006-07-05 10:00:00", "%m/%d/%Y")
assert_equal "07/16/2004", @filters.date("Fri Jul 16 01:00:00 2004", "%m/%d/%Y")
assert_equal "#{Date.today.year}", @filters.date('now', '%Y')
assert_equal "#{Date.today.year}", @filters.date('today', '%Y')
assert_equal "#{Date.today.year}", @filters.date('Today', '%Y')
assert_nil @filters.date(nil, "%B")
assert_equal '', @filters.date('', "%B")
with_timezone("UTC") do
assert_equal "07/05/2006", @filters.date(1152098955, "%m/%d/%Y")
assert_equal "07/05/2006", @filters.date("1152098955", "%m/%d/%Y")
end
end
def test_first_last
assert_equal 1, @filters.first([1, 2, 3])
assert_equal 3, @filters.last([1, 2, 3])
assert_nil @filters.first([])
assert_nil @filters.last([])
end
def test_replace
assert_equal '2 2 2 2', @filters.replace('1 1 1 1', '1', 2)
assert_equal '2 2 2 2', @filters.replace('1 1 1 1', 1, 2)
assert_equal '2 1 1 1', @filters.replace_first('1 1 1 1', '1', 2)
assert_equal '2 1 1 1', @filters.replace_first('1 1 1 1', 1, 2)
assert_template_result '2 1 1 1', "{{ '1 1 1 1' | replace_first: '1', 2 }}"
end
def test_remove
assert_equal ' ', @filters.remove("a a a a", 'a')
assert_equal ' ', @filters.remove("1 1 1 1", 1)
assert_equal 'a a a', @filters.remove_first("a a a a", 'a ')
assert_equal ' 1 1 1', @filters.remove_first("1 1 1 1", 1)
assert_template_result 'a a a', "{{ 'a a a a' | remove_first: 'a ' }}"
end
def test_pipes_in_string_arguments
assert_template_result 'foobar', "{{ 'foo|bar' | remove: '|' }}"
end
def test_strip
assert_template_result 'ab c', "{{ source | strip }}", 'source' => " ab c "
assert_template_result 'ab c', "{{ source | strip }}", 'source' => " \tab c \n \t"
end
def test_lstrip
assert_template_result 'ab c ', "{{ source | lstrip }}", 'source' => " ab c "
assert_template_result "ab c \n \t", "{{ source | lstrip }}", 'source' => " \tab c \n \t"
end
def test_rstrip
assert_template_result " ab c", "{{ source | rstrip }}", 'source' => " ab c "
assert_template_result " \tab c", "{{ source | rstrip }}", 'source' => " \tab c \n \t"
end
def test_strip_newlines
assert_template_result 'abc', "{{ source | strip_newlines }}", 'source' => "a\nb\nc"
assert_template_result 'abc', "{{ source | strip_newlines }}", 'source' => "a\r\nb\nc"
end
def test_newlines_to_br
assert_template_result "a<br />\nb<br />\nc", "{{ source | newline_to_br }}", 'source' => "a\nb\nc"
end
def test_plus
assert_template_result "2", "{{ 1 | plus:1 }}"
assert_template_result "2.0", "{{ '1' | plus:'1.0' }}"
assert_template_result "5", "{{ price | plus:'2' }}", 'price' => NumberLikeThing.new(3)
end
def test_minus
assert_template_result "4", "{{ input | minus:operand }}", 'input' => 5, 'operand' => 1
assert_template_result "2.3", "{{ '4.3' | minus:'2' }}"
assert_template_result "5", "{{ price | minus:'2' }}", 'price' => NumberLikeThing.new(7)
end
def test_abs
assert_template_result "17", "{{ 17 | abs }}"
assert_template_result "17", "{{ -17 | abs }}"
assert_template_result "17", "{{ '17' | abs }}"
assert_template_result "17", "{{ '-17' | abs }}"
assert_template_result "0", "{{ 0 | abs }}"
assert_template_result "0", "{{ '0' | abs }}"
assert_template_result "17.42", "{{ 17.42 | abs }}"
assert_template_result "17.42", "{{ -17.42 | abs }}"
assert_template_result "17.42", "{{ '17.42' | abs }}"
assert_template_result "17.42", "{{ '-17.42' | abs }}"
end
def test_times
assert_template_result "12", "{{ 3 | times:4 }}"
assert_template_result "0", "{{ 'foo' | times:4 }}"
assert_template_result "6", "{{ '2.1' | times:3 | replace: '.','-' | plus:0}}"
assert_template_result "7.25", "{{ 0.0725 | times:100 }}"
assert_template_result "-7.25", '{{ "-0.0725" | times:100 }}'
assert_template_result "7.25", '{{ "-0.0725" | times: -100 }}'
assert_template_result "4", "{{ price | times:2 }}", 'price' => NumberLikeThing.new(2)
end
def test_divided_by
assert_template_result "4", "{{ 12 | divided_by:3 }}"
assert_template_result "4", "{{ 14 | divided_by:3 }}"
assert_template_result "5", "{{ 15 | divided_by:3 }}"
assert_equal "Liquid error: divided by 0", Template.parse("{{ 5 | divided_by:0 }}").render
assert_template_result "0.5", "{{ 2.0 | divided_by:4 }}"
assert_raises(Liquid::ZeroDivisionError) do
assert_template_result "4", "{{ 1 | modulo: 0 }}"
end
assert_template_result "5", "{{ price | divided_by:2 }}", 'price' => NumberLikeThing.new(10)
end
def test_modulo
assert_template_result "1", "{{ 3 | modulo:2 }}"
assert_raises(Liquid::ZeroDivisionError) do
assert_template_result "4", "{{ 1 | modulo: 0 }}"
end
assert_template_result "1", "{{ price | modulo:2 }}", 'price' => NumberLikeThing.new(3)
end
def test_round
assert_template_result "5", "{{ input | round }}", 'input' => 4.6
assert_template_result "4", "{{ '4.3' | round }}"
assert_template_result "4.56", "{{ input | round: 2 }}", 'input' => 4.5612
assert_raises(Liquid::FloatDomainError) do
assert_template_result "4", "{{ 1.0 | divided_by: 0.0 | round }}"
end
assert_template_result "5", "{{ price | round }}", 'price' => NumberLikeThing.new(4.6)
assert_template_result "4", "{{ price | round }}", 'price' => NumberLikeThing.new(4.3)
end
def test_ceil
assert_template_result "5", "{{ input | ceil }}", 'input' => 4.6
assert_template_result "5", "{{ '4.3' | ceil }}"
assert_raises(Liquid::FloatDomainError) do
assert_template_result "4", "{{ 1.0 | divided_by: 0.0 | ceil }}"
end
assert_template_result "5", "{{ price | ceil }}", 'price' => NumberLikeThing.new(4.6)
end
def test_floor
assert_template_result "4", "{{ input | floor }}", 'input' => 4.6
assert_template_result "4", "{{ '4.3' | floor }}"
assert_raises(Liquid::FloatDomainError) do
assert_template_result "4", "{{ 1.0 | divided_by: 0.0 | floor }}"
end
assert_template_result "5", "{{ price | floor }}", 'price' => NumberLikeThing.new(5.4)
end
def test_at_most
assert_template_result "4", "{{ 5 | at_most:4 }}"
assert_template_result "5", "{{ 5 | at_most:5 }}"
assert_template_result "5", "{{ 5 | at_most:6 }}"
assert_template_result "4.5", "{{ 4.5 | at_most:5 }}"
assert_template_result "5", "{{ width | at_most:5 }}", 'width' => NumberLikeThing.new(6)
assert_template_result "4", "{{ width | at_most:5 }}", 'width' => NumberLikeThing.new(4)
assert_template_result "4", "{{ 5 | at_most: width }}", 'width' => NumberLikeThing.new(4)
end
def test_at_least
assert_template_result "5", "{{ 5 | at_least:4 }}"
assert_template_result "5", "{{ 5 | at_least:5 }}"
assert_template_result "6", "{{ 5 | at_least:6 }}"
assert_template_result "5", "{{ 4.5 | at_least:5 }}"
assert_template_result "6", "{{ width | at_least:5 }}", 'width' => NumberLikeThing.new(6)
assert_template_result "5", "{{ width | at_least:5 }}", 'width' => NumberLikeThing.new(4)
assert_template_result "6", "{{ 5 | at_least: width }}", 'width' => NumberLikeThing.new(6)
end
def test_append
assigns = { 'a' => 'bc', 'b' => 'd' }
assert_template_result('bcd', "{{ a | append: 'd'}}", assigns)
assert_template_result('bcd', "{{ a | append: b}}", assigns)
end
def test_concat
assert_equal [1, 2, 3, 4], @filters.concat([1, 2], [3, 4])
assert_equal [1, 2, 'a'], @filters.concat([1, 2], ['a'])
assert_equal [1, 2, 10], @filters.concat([1, 2], [10])
assert_raises(Liquid::ArgumentError, "concat filter requires an array argument") do
@filters.concat([1, 2], 10)
end
end
def test_prepend
assigns = { 'a' => 'bc', 'b' => 'a' }
assert_template_result('abc', "{{ a | prepend: 'a'}}", assigns)
assert_template_result('abc', "{{ a | prepend: b}}", assigns)
end
def test_default
assert_equal "foo", @filters.default("foo", "bar")
assert_equal "bar", @filters.default(nil, "bar")
assert_equal "bar", @filters.default("", "bar")
assert_equal "bar", @filters.default(false, "bar")
assert_equal "bar", @filters.default([], "bar")
assert_equal "bar", @filters.default({}, "bar")
end
def test_cannot_access_private_methods
assert_template_result('a', "{{ 'a' | to_number }}")
end
def test_date_raises_nothing
assert_template_result('', "{{ '' | date: '%D' }}")
assert_template_result('abc', "{{ 'abc' | date: '%D' }}")
end
private
def with_timezone(tz)
old_tz = ENV['TZ']
ENV['TZ'] = tz
yield
ensure
ENV['TZ'] = old_tz
end
end # StandardFiltersTest
| tianwei-zhang/tianwei-zhang.github.io | vendor/bundle/ruby/2.6.0/gems/liquid-4.0.1/test/integration/standard_filter_test.rb | Ruby | mit | 22,260 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import EUCTWDistributionAnalysis
from .mbcssm import EUCTW_SM_MODEL
class EUCTWProber(MultiByteCharSetProber):
def __init__(self):
super(EUCTWProber, self).__init__()
self.coding_sm = CodingStateMachine(EUCTW_SM_MODEL)
self.distribution_analyzer = EUCTWDistributionAnalysis()
self.reset()
@property
def charset_name(self):
return "EUC-TW"
@property
def language(self):
return "Taiwan"
| ncos/lisa | src/lisa_drive/scripts/venv/lib/python3.5/site-packages/pip-10.0.1-py3.5.egg/pip/_vendor/chardet/euctwprober.py | Python | mit | 1,793 |
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems. Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL. It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
//
// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
// artificially, inherently leave the process in a
// state from which it is not safe to try and enter JS
// listeners.
module.exports = [
'SIGABRT',
'SIGALRM',
'SIGHUP',
'SIGINT',
'SIGTERM'
]
if (process.platform !== 'win32') {
module.exports.push(
'SIGVTALRM',
'SIGXCPU',
'SIGXFSZ',
'SIGUSR2',
'SIGTRAP',
'SIGSYS',
'SIGQUIT',
'SIGIOT'
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
)
}
if (process.platform === 'linux') {
module.exports.push(
'SIGIO',
'SIGPOLL',
'SIGPWR',
'SIGSTKFLT',
'SIGUNUSED'
)
}
| Moccine/global-service-plus.com | web/libariries/bootstrap/node_modules/signal-exit/signals.js | JavaScript | mit | 1,348 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace BlueYonderDemo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
PanelToggle.Click += PanelToggle_Click;
}
private void PanelToggle_Click(object sender, RoutedEventArgs e)
{
if (MenuSplitView.IsPaneOpen)
{
MenuSplitView.IsPaneOpen = false;
if (MenuSplitView.DisplayMode == SplitViewDisplayMode.Inline)
{
MenuSplitView.DisplayMode = SplitViewDisplayMode.CompactInline;
}
}
else
{
MenuSplitView.IsPaneOpen = true;
}
}
}
}
| tiagocostapt/WinDevWorkshop | Presentations/01. Introduction to UWP/Demos/AdaptiveUI/BlueYonderDemo/MainPage.xaml.cs | C# | mit | 1,383 |
import { css, StyleSheet } from 'aphrodite/no-important';
import React, { PropTypes } from 'react';
import octicons from './octicons';
import colors from './colors';
import sizes from './sizes';
import styles from './styles';
const classes = StyleSheet.create(styles);
// FIXME static octicon classes leaning on Elemental to avoid duplicate
// font and CSS; inflating the project size
function Glyph ({
aphroditeStyles,
className,
color,
component: Component,
name,
size,
style,
...props
}) {
const colorIsValidType = Object.keys(colors).includes(color);
props.className = css(
classes.glyph,
colorIsValidType && classes['color__' + color],
classes['size__' + size],
aphroditeStyles
) + ` ${octicons[name]}`;
if (className) {
props.className += (' ' + className);
}
// support random color strings
props.style = {
color: !colorIsValidType ? color : null,
...style,
};
return <Component {...props} />;
};
Glyph.propTypes = {
aphroditeStyles: PropTypes.shape({
_definition: PropTypes.object,
_name: PropTypes.string,
}),
color: PropTypes.oneOfType([
PropTypes.oneOf(Object.keys(colors)),
PropTypes.string, // support random color strings
]),
name: PropTypes.oneOf(Object.keys(octicons)).isRequired,
size: PropTypes.oneOf(Object.keys(sizes)),
};
Glyph.defaultProps = {
component: 'i',
color: 'inherit',
size: 'small',
};
module.exports = Glyph;
| linhanyang/keystone | admin/client/App/elemental/Glyph/index.js | JavaScript | mit | 1,398 |
"""The tests for the heat control thermostat."""
import unittest
from homeassistant.bootstrap import _setup_component
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
STATE_OFF,
TEMP_CELSIUS,
)
from homeassistant.components import thermostat
from tests.common import get_test_home_assistant
ENTITY = 'thermostat.test'
ENT_SENSOR = 'sensor.test'
ENT_SWITCH = 'switch.test'
MIN_TEMP = 3.0
MAX_TEMP = 65.0
TARGET_TEMP = 42.0
class TestSetupThermostatHeatControl(unittest.TestCase):
"""Test the Heat Control thermostat with custom config."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_missing_conf(self):
"""Test set up heat_control with missing config values."""
config = {
'name': 'test',
'target_sensor': ENT_SENSOR
}
self.assertFalse(_setup_component(self.hass, 'thermostat', {
'thermostat': config}))
def test_valid_conf(self):
"""Test set up heat_control with valid config values."""
self.assertTrue(_setup_component(self.hass, 'thermostat',
{'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR}}))
def test_setup_with_sensor(self):
"""Test set up heat_control with sensor to trigger update at init."""
self.hass.states.set(ENT_SENSOR, 22.0, {
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS
})
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR
}})
state = self.hass.states.get(ENTITY)
self.assertEqual(
TEMP_CELSIUS, state.attributes.get('unit_of_measurement'))
self.assertEqual(22.0, state.attributes.get('current_temperature'))
class TestThermostatHeatControl(unittest.TestCase):
"""Test the Heat Control thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR
}})
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_defaults_to_unknown(self):
"""Test the setting of defaults to unknown."""
self.assertEqual('unknown', self.hass.states.get(ENTITY).state)
def test_default_setup_params(self):
"""Test the setup with default parameters."""
state = self.hass.states.get(ENTITY)
self.assertEqual(7, state.attributes.get('min_temp'))
self.assertEqual(35, state.attributes.get('max_temp'))
self.assertEqual(None, state.attributes.get('temperature'))
def test_custom_setup_params(self):
"""Test the setup with custom parameters."""
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR,
'min_temp': MIN_TEMP,
'max_temp': MAX_TEMP,
'target_temp': TARGET_TEMP
}})
state = self.hass.states.get(ENTITY)
self.assertEqual(MIN_TEMP, state.attributes.get('min_temp'))
self.assertEqual(MAX_TEMP, state.attributes.get('max_temp'))
self.assertEqual(TARGET_TEMP, state.attributes.get('temperature'))
self.assertEqual(str(TARGET_TEMP), self.hass.states.get(ENTITY).state)
def test_set_target_temp(self):
"""Test the setting of the target temperature."""
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self.assertEqual('30.0', self.hass.states.get(ENTITY).state)
def test_sensor_bad_unit(self):
"""Test sensor that have bad unit."""
self._setup_sensor(22.0, unit='bad_unit')
self.hass.pool.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(None, state.attributes.get('unit_of_measurement'))
self.assertEqual(None, state.attributes.get('current_temperature'))
def test_sensor_bad_value(self):
"""Test sensor that have None as state."""
self._setup_sensor(None)
self.hass.pool.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(None, state.attributes.get('unit_of_measurement'))
self.assertEqual(None, state.attributes.get('current_temperature'))
def test_set_target_temp_heater_on(self):
"""Test if target temperature turn heater on."""
self._setup_switch(False)
self._setup_sensor(25)
self.hass.pool.block_till_done()
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_set_target_temp_heater_off(self):
"""Test if target temperature turn heater off."""
self._setup_switch(True)
self._setup_sensor(30)
self.hass.pool.block_till_done()
thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_set_temp_change_heater_on(self):
"""Test if temperature change turn heater on."""
self._setup_switch(False)
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self._setup_sensor(25)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_temp_change_heater_off(self):
"""Test if temperature change turn heater off."""
self._setup_switch(True)
thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done()
self._setup_sensor(30)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_switch(self, is_on):
"""Setup the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
def log_call(call):
"""Log service calls."""
self.calls.append(call)
self.hass.services.register('switch', SERVICE_TURN_ON, log_call)
self.hass.services.register('switch', SERVICE_TURN_OFF, log_call)
| deisi/home-assistant | tests/components/thermostat/test_heat_control.py | Python | mit | 7,976 |
package org.spongycastle.crypto.test;
import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.digests.SHA256Digest;
/**
* standard vector test for SHA-256 from FIPS Draft 180-2.
*
* Note, the first two vectors are _not_ from the draft, the last three are.
*/
public class SHA256DigestTest
extends DigestTest
{
private static String[] messages =
{
"",
"a",
"abc",
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
};
private static String[] digests =
{
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb",
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
};
// 1 million 'a'
static private String million_a_digest = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
SHA256DigestTest()
{
super(new SHA256Digest(), messages, digests);
}
public void performTest()
{
super.performTest();
millionATest(million_a_digest);
}
protected Digest cloneDigest(Digest digest)
{
return new SHA256Digest((SHA256Digest)digest);
}
protected Digest cloneDigest(byte[] encodedState)
{
return new SHA256Digest(encodedState);
}
public static void main(
String[] args)
{
runTest(new SHA256DigestTest());
}
}
| Skywalker-11/spongycastle | core/src/test/java/org/spongycastle/crypto/test/SHA256DigestTest.java | Java | mit | 1,536 |
<?php
namespace DesignPatterns\Tests\Specification;
use DesignPatterns\Specification\PriceSpecification;
use DesignPatterns\Specification\Item;
/**
* SpecificationTest tests the specification pattern
*/
class SpecificationTest extends \PHPUnit_Framework_TestCase
{
public function testSimpleSpecification()
{
$item = new Item(100);
$spec = new PriceSpecification();
$this->assertTrue($spec->isSatisfiedBy($item));
$spec->setMaxPrice(50);
$this->assertFalse($spec->isSatisfiedBy($item));
$spec->setMaxPrice(150);
$this->assertTrue($spec->isSatisfiedBy($item));
$spec->setMinPrice(101);
$this->assertFalse($spec->isSatisfiedBy($item));
$spec->setMinPrice(100);
$this->assertTrue($spec->isSatisfiedBy($item));
}
public function testNotSpecification()
{
$item = new Item(100);
$spec = new PriceSpecification();
$not = $spec->not();
$this->assertFalse($not->isSatisfiedBy($item));
$spec->setMaxPrice(50);
$this->assertTrue($not->isSatisfiedBy($item));
$spec->setMaxPrice(150);
$this->assertFalse($not->isSatisfiedBy($item));
$spec->setMinPrice(101);
$this->assertTrue($not->isSatisfiedBy($item));
$spec->setMinPrice(100);
$this->assertFalse($not->isSatisfiedBy($item));
}
public function testPlusSpecification()
{
$spec1 = new PriceSpecification();
$spec2 = new PriceSpecification();
$plus = $spec1->plus($spec2);
$item = new Item(100);
$this->assertTrue($plus->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMinPrice(50);
$this->assertTrue($plus->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMinPrice(101);
$this->assertFalse($plus->isSatisfiedBy($item));
$spec1->setMaxPrice(99);
$spec2->setMinPrice(50);
$this->assertFalse($plus->isSatisfiedBy($item));
}
public function testEitherSpecification()
{
$spec1 = new PriceSpecification();
$spec2 = new PriceSpecification();
$either = $spec1->either($spec2);
$item = new Item(100);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMaxPrice(150);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(150);
$spec2->setMaxPrice(0);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(0);
$spec2->setMaxPrice(150);
$this->assertTrue($either->isSatisfiedBy($item));
$spec1->setMaxPrice(99);
$spec2->setMaxPrice(99);
$this->assertFalse($either->isSatisfiedBy($item));
}
}
| nguyentienlong/DesignPatternsPHP | Tests/Specification/SpecificationTest.php | PHP | mit | 2,818 |
<!DOCTYPE html>
<html>
<body>
%username% edited item at board %boardname%:<br>
%title%<br>
%description%<br>
%duedate%<br>
%assignee%<br>
%category%<br>
%points%<br>
%position%<br>
<a href="http://%hostname%/#/boards/%boardid%">Navigate to board!</a>
</body>
</html>
| woodworker/TaskBoard | api/mail_templates/editItem.html | HTML | mit | 268 |
# $Id$
#
# Author:: Francis Cianfrocca (gmail: blackhedd)
# Homepage:: http://rubyeventmachine.com
# Date:: 8 April 2006
#
# See EventMachine and EventMachine::Connection for documentation and
# usage examples.
#
#----------------------------------------------------------------------------
#
# Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
# Gmail: blackhedd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of either: 1) the GNU General Public License
# as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version; or 2) Ruby's License.
#
# See the file COPYING for complete licensing information.
#
#---------------------------------------------------------------------------
#
#
#
$:.unshift "../lib"
require 'eventmachine'
require 'socket'
require 'test/unit'
class TestServers < Test::Unit::TestCase
Host = "127.0.0.1"
Port = 9555
module NetstatHelper
GlobalUdp4Rexp = /udp.*\s+(?:\*|(?:0\.){3}0)[:.](\d+)\s/i
GlobalTcp4Rexp = /tcp.*\s+(?:\*|(?:0\.){3}0)[:.](\d+)\s/i
LocalUdpRexp = /udp.*\s+(?:127\.0\.0\.1|::1)[:.](\d+)\s/i
LocalTcpRexp = /tcp.*\s+(?:127\.0\.0\.1|::1)[:.](\d+)\s/i
def grep_netstat(pattern)
`netstat -an`.scan(/^.*$/).grep(pattern)
end
end
include NetstatHelper
class TestStopServer < EM::Connection
def initialize *args
super
end
def post_init
# TODO,sucks that this isn't OOPy enough.
EM.stop_server @server_instance
end
end
def run_test_stop_server
EM.run {
sig = EM.start_server(Host, Port)
assert(grep_netstat(LocalTcpRexp).grep(%r(#{Port})).size >= 1, "Server didn't start")
EM.stop_server sig
# Give the server some time to shutdown.
EM.add_timer(0.1) {
assert(grep_netstat(LocalTcpRexp).grep(%r(#{Port})).empty?, "Servers didn't stop")
EM.stop
}
}
end
def test_stop_server
assert(grep_netstat(LocalTcpRexp).grep(Port).empty?, "Port already in use")
5.times {run_test_stop_server}
assert(grep_netstat(LocalTcpRexp).grep(%r(#{Port})).empty?, "Servers didn't stop")
end
end
| mattgraham/play-graham | vendor/gems/ruby/1.8/gems/eventmachine-0.12.10/tests/test_servers.rb | Ruby | mit | 2,198 |
/* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2015 */
#ifdef CAPSTONE_HAS_SPARC
#include "../../utils.h"
#include "../../MCRegisterInfo.h"
#include "SparcDisassembler.h"
#include "SparcInstPrinter.h"
#include "SparcMapping.h"
static cs_err init(cs_struct *ud)
{
MCRegisterInfo *mri;
// verify if requested mode is valid
if (ud->mode & ~(CS_MODE_BIG_ENDIAN | CS_MODE_V9))
return CS_ERR_MODE;
mri = cs_mem_malloc(sizeof(*mri));
Sparc_init(mri);
ud->printer = Sparc_printInst;
ud->printer_info = mri;
ud->getinsn_info = mri;
ud->disasm = Sparc_getInstruction;
ud->post_printer = Sparc_post_printer;
ud->reg_name = Sparc_reg_name;
ud->insn_id = Sparc_get_insn_id;
ud->insn_name = Sparc_insn_name;
ud->group_name = Sparc_group_name;
return CS_ERR_OK;
}
static cs_err option(cs_struct *handle, cs_opt_type type, size_t value)
{
if (type == CS_OPT_SYNTAX)
handle->syntax = (int) value;
return CS_ERR_OK;
}
void Sparc_enable(void)
{
arch_init[CS_ARCH_SPARC] = init;
arch_option[CS_ARCH_SPARC] = option;
// support this arch
all_arch |= (1 << CS_ARCH_SPARC);
}
#endif
| v3n/ProDBG | src/native/external/capstone/arch/Sparc/SparcModule.c | C | mit | 1,133 |
<!DOCTYPE html>
<html class="minimal">
<title>Canvas test: 2d.pattern.paint.norepeat.outside</title>
<script src="../tests.js"></script>
<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="minimal.2d.pattern.paint.norepeat.basic.html" title="2d.pattern.paint.norepeat.basic">
<link rel="next" href="minimal.2d.pattern.paint.norepeat.coord1.html" title="2d.pattern.paint.norepeat.coord1">
<body>
<p id="passtext">Pass</p>
<p id="failtext">Fail</p>
<!-- TODO: handle "script did not run" case -->
<p class="output">These images should be identical:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="green-100x50.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
_addTest(function(canvas, ctx) {
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
var img = document.getElementById('red.png');
var pattern = ctx.createPattern(img, 'no-repeat');
ctx.fillStyle = '#0f0';
ctx.fillRect(0, 0, 100, 50);
ctx.fillStyle = pattern;
ctx.fillRect(0, -50, 100, 50);
ctx.fillRect(-100, 0, 100, 50);
ctx.fillRect(0, 50, 100, 50);
ctx.fillRect(100, 0, 100, 50);
_assertPixel(canvas, 1,1, 0,255,0,255, "1,1", "0,255,0,255");
_assertPixel(canvas, 98,1, 0,255,0,255, "98,1", "0,255,0,255");
_assertPixel(canvas, 1,48, 0,255,0,255, "1,48", "0,255,0,255");
_assertPixel(canvas, 98,48, 0,255,0,255, "98,48", "0,255,0,255");
});
</script>
<img src="../images/red.png" id="red.png" class="resource">
| corbanbrook/webgl-2d | test/philip.html5.org/tests/minimal.2d.pattern.paint.norepeat.outside.html | HTML | mit | 1,549 |
"function"==typeof jQuery&&jQuery(document).ready(function(e){function n(){!1!==s?o():t()}function o(){r=new google.maps.LatLng(s[0],s[1]),a()}function t(){var e=new google.maps.Geocoder;e.geocode({address:d},function(e,n){n==google.maps.GeocoderStatus.OK&&(r=e[0].geometry.location,a())})}function a(){var n={zoom:parseInt(tribeEventsSingleMap.zoom),center:r,mapTypeId:google.maps.MapTypeId.ROADMAP};p.map=new google.maps.Map(i,n);var o={map:p.map,title:g,position:r};e("body").trigger("map-created.tribe",[p.map,i,n]),"undefined"!==tribeEventsSingleMap.pin_url&&tribeEventsSingleMap.pin_url&&(o.icon=tribeEventsSingleMap.pin_url),new google.maps.Marker(o)}var i,r,p,d,s,g;"undefined"!=typeof tribeEventsSingleMap&&e.each(tribeEventsSingleMap.addresses,function(e,o){i=document.getElementById("tribe-events-gmap-"+e),null!==i&&(p="undefined"!=typeof o?o:{},d="undefined"!=typeof o.address&&o.address,s="undefined"!=typeof o.coords&&o.coords,g=o.title,n())})}); | smpetrey/acredistilling.com | web/app/plugins/the-events-calendar/src/resources/js/embedded-map.min.js | JavaScript | mit | 961 |
angular.module('merchello.plugins.braintree').controller('Merchello.Plugins.GatewayProviders.Dialogs.PaymentMethodAddEditController',
['$scope', 'braintreeProviderSettingsBuilder',
function($scope, braintreeProviderSettingsBuilder) {
$scope.providerSettings = {};
function init() {
var json = JSON.parse($scope.dialogData.provider.extendedData.getValue('braintreeProviderSettings'));
$scope.providerSettings = braintreeProviderSettingsBuilder.transform(json);
$scope.$watch(function () {
return $scope.providerSettings;
}, function (newValue, oldValue) {
$scope.dialogData.provider.extendedData.setValue('braintreeProviderSettings', angular.toJson(newValue));
}, true);
}
// initialize the controller
init();
}]); | bjarnef/Merchello | src/Merchello.Web.UI/App_Plugins/Merchello.Braintree/payment.braintree.providersettings.controller.js | JavaScript | mit | 922 |
// (C) Copyright 1996-2006 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// DESCRIPTION:
//
// Source file for the ObjectARX application command "BRBBLOCK".
#include "brsample_pch.h" //precompiled header
//This is been defined for future use. all headers should be under this guard.
// include here
void
dumpBblock()
{
AcBr::ErrorStatus returnValue = AcBr::eOk;
// Select the entity by type
AcBrEntity* pEnt = NULL;
AcDb::SubentType subType = AcDb::kNullSubentType;
returnValue = selectEntityByType(pEnt, subType);
if (returnValue != AcBr::eOk) {
acutPrintf(ACRX_T("\n Error in selectEntityByType:"));
errorReport(returnValue);
delete pEnt;
return;
}
AcGeBoundBlock3d bblock;
returnValue = pEnt->getBoundBlock(bblock);
if (returnValue != AcBr::eOk) {
acutPrintf(ACRX_T("\n Error in AcBrEntity::getBoundBlock:"));
errorReport(returnValue);
delete pEnt;
return;
}
delete pEnt;
AcGePoint3d min, max;
bblock.getMinMaxPoints(min, max);
bblockReport(min, max);
return;
}
| kevinzhwl/ObjectARXCore | 2013/utils/brep/samples/brepsamp/brbblock.cpp | C++ | mit | 1,979 |
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="generator" content="JsDoc Toolkit" />
<title>JsDoc Reference - _global_</title>
<link rel="stylesheet" href="../static/default.css" type="text/css" media="screen" charset="utf-8" />
</head>
<body>
<!-- ============================== header ================================= -->
<!-- begin static/header.html -->
<div id="header">
</div>
<!-- end static/header.html -->
<!-- ============================== classes index ============================ -->
<div id="index">
<div id="docs">
</div>
<h2>Index</h2>
<ul class="classList">
<li><a href="../files.html">File Index</a></li>
<li><a href="../index.html">Class Index</a></li>
<li><a href="../symbolindex.html">Symbol Index</a></li>
</ul>
<h2>Classes</h2>
<ul class="classList">
<li><i><a href="../symbols/_global_.html">_global_</a></i></li>
<li><a href="../symbols/hasher.html">hasher</a></li>
</ul>
</div>
<div id="symbolList">
<!-- constructor list -->
<!-- end constructor list -->
<!-- properties list -->
<!-- end properties list -->
<!-- function summary -->
<!-- end function summary -->
<!-- events summary -->
<!-- end events summary -->
</div>
<div id="content">
<!-- ============================== class title ============================ -->
<h1 class="classTitle">
Built-In Namespace _global_
</h1>
<!-- ============================== class summary ========================== -->
<p class="description">
</p>
<!-- ============================== constructor details ==================== -->
<!-- ============================== field details ========================== -->
<!-- ============================== method details ========================= -->
<!-- ============================== event details ========================= -->
<hr />
</div>
<!-- ============================== footer ================================= -->
<div class="fineprint" style="clear:both;text-align:center">
Documentation generated by <a href="http://code.google.com/p/jsdoc-toolkit/" target="_blankt">JsDoc Toolkit</a> 2.4.0 on Mon Nov 11 2013 15:19:04 GMT-0200 (BRST)
| template based on Steffen Siering <a href="http://github.com/urso/jsdoc-simple">jsdoc-simple</a>.
</div>
</body>
</html>
| bluecloudy/Critical-Map | src/bower_modules/hasher/dist/docs/symbols/_global_.html | HTML | mit | 2,831 |
using ArmyOfCreatures.Logic.Creatures;
namespace ArmyOfCreatures.Logic
{
public interface ICreaturesFactory
{
Creature CreateCreature(string name);
}
}
| shopOFF/TelerikAcademyCourses | Unit-Testing/Unit-Testing/Topics/04. Workshop (Trainers)/ArmyOfCreatures-Evening-livedemo/ArmyOfCreatures-All/Solution/ArmyOfCreatures/Logic/ICreaturesFactory.cs | C# | mit | 176 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.