text stringlengths 2 1.04M | meta dict |
|---|---|
[](https://travis-ci.org/weareinteractive/ansible-ufw)
[](https://galaxy.ansible.com/weareinteractive/ufw)
[](https://github.com/weareinteractive/ansible-ufw)
[](https://github.com/weareinteractive/ansible-ufw)
> `franklinkim.ufw` is an [Ansible](http://www.ansible.com) role which:
>
> * installs ufw
> * configures ufw
> * configures ufw rules
> * configures service
## Installation
Using `ansible-galaxy`:
```shell
$ ansible-galaxy install franklinkim.ufw
```
Using `requirements.yml`:
```yaml
- src: franklinkim.ufw
```
Using `git`:
```shell
$ git clone https://github.com/weareinteractive/ansible-ufw.git franklinkim.ufw
```
## Dependencies
* Ansible >= 2.4
## Variables
Here is a list of all the default variables for this role, which are also available in `defaults/main.yml`.
```yaml
---
# ufw_rules:
# - { [port: ""] [rule: allow] [proto: any] [from_ip: any] [to_ip: any] }
# ufw_applications:
# - { name: OpenSSH [rule: allow, from_ip: any] }
#
# package name (version)
# depricated: `ufw_package` will be removed in future releases! Use `ufw_packages`
ufw_package: ufw
# added to support systems where ufw packages are split up
ufw_packages:
- "{{ ufw_package }}"
# list of rules
ufw_rules: [{ port: 22, rule: allow }]
# list of profiles located in /etc/ufw/applications.d
ufw_applications: []
# /etc/defaut/ufw settings
ufw_ipv6: "yes"
ufw_default_input_policy: DROP
ufw_default_output_policy: ACCEPT
ufw_default_forward_policy: DROP
ufw_default_application_policy: SKIP
# firewall state: enabled | disabled
ufw_state: enabled
ufw_logging: "off"
# always reset the firewall
ufw_reset: yes
```
## Handlers
These are the handlers that are defined in `handlers/main.yml`.
```yaml
---
- name: reload ufw
ufw:
state: reloaded
when: ufw_state == 'enabled'
```
## Usage
This is an example playbook:
```yaml
---
- hosts: all
roles:
- franklinkim.ufw
vars:
ufw_rules:
- { port: 22, rule: allow }
- { port: 80, rule: allow }
- { from_ip: '127.0.0.1/8' }
- { from_ip: '127.0.42.0/24', rule: deny }
ufw_default_forward_policy: ACCEPT
ufw_logging: full
ufw_applications:
- { name: "OpenSSH" }
```
## Testing
```shell
$ git clone https://github.com/weareinteractive/ansible-ufw.git
$ cd ansible-ufw
$ make test
```
## Contributing
In lieu of a formal style guide, take care to maintain the existing coding style. Add unit tests and examples for any new or changed functionality.
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
*Note: To update the `README.md` file please install and run `ansible-role`:*
```shell
$ gem install ansible-role
$ ansible-role docgen
```
## License
Copyright (c) We Are Interactive under the MIT license.
| {
"content_hash": "7380d4f875e1f61c20e65d3692094e9b",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 147,
"avg_line_length": 23.554744525547445,
"alnum_prop": 0.6960024790827394,
"repo_name": "GetPhage/phage",
"id": "59b45182a4ff944e1fe2e0e45099c3ad53c8adb7",
"size": "3259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ansible/roles/franklinkim.ufw/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5099"
},
{
"name": "CoffeeScript",
"bytes": "4009"
},
{
"name": "Dockerfile",
"bytes": "341"
},
{
"name": "HTML",
"bytes": "65101"
},
{
"name": "JavaScript",
"bytes": "1308"
},
{
"name": "Jinja",
"bytes": "212146"
},
{
"name": "Makefile",
"bytes": "2133"
},
{
"name": "Procfile",
"bytes": "86"
},
{
"name": "Python",
"bytes": "289"
},
{
"name": "Ruby",
"bytes": "210129"
},
{
"name": "SCSS",
"bytes": "5350"
},
{
"name": "Shell",
"bytes": "6998"
}
],
"symlink_target": ""
} |
'use strict';
/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
, Sequelize = require('../../index')
, expect = chai.expect
, Support = require(__dirname + '/support')
, sinon = require('sinon')
, _ = require('lodash')
, moment = require('moment')
, current = Support.sequelize
, uuid = require('node-uuid')
, DataTypes = require('../../lib/data-types')
, dialect = Support.getTestDialect();
describe(Support.getTestDialectTeaser('DataTypes'), function() {
afterEach(function () {
// Restore some sanity by resetting all parsers
switch (dialect) {
case 'postgres':
var types = require('../../node_modules/pg/node_modules/pg-types');
_.each(DataTypes, function (dataType) {
if (dataType.types && dataType.types.postgres) {
dataType.types.postgres.oids.forEach(function (oid) {
types.setTypeParser(oid, _.identity);
});
}
});
require('../../node_modules/pg/node_modules/pg-types/lib/binaryParsers').init(function (oid, converter) {
types.setTypeParser(oid, 'binary', converter);
});
require('../../node_modules/pg/node_modules/pg-types/lib/textParsers').init(function (oid, converter) {
types.setTypeParser(oid, 'text', converter);
});
break;
default:
this.sequelize.connectionManager.$clearTypeParser();
}
this.sequelize.connectionManager.refreshTypeParser(DataTypes[dialect]); // Reload custom parsers
});
it('allows me to return values from a custom parse function', function () {
var parse = Sequelize.DATE.parse = sinon.spy(function (value) {
return moment(value, 'YYYY-MM-DD HH:mm:ss Z');
});
var stringify = Sequelize.DATE.prototype.stringify = sinon.spy(function (value, options) {
if (!moment.isMoment(value)) {
value = this.$applyTimezone(value, options);
}
return value.format('YYYY-MM-DD HH:mm:ss Z');
});
current.refreshTypes();
var User = current.define('user', {
dateField: Sequelize.DATE
}, {
timestamps: false
});
return current.sync({ force: true }).then(function () {
return User.create({
dateField: moment("2011 10 31", 'YYYY MM DD')
});
}).then(function () {
return User.findAll().get(0);
}).then(function (user) {
expect(parse).to.have.been.called;
expect(stringify).to.have.been.called;
expect(moment.isMoment(user.dateField)).to.be.ok;
delete Sequelize.DATE.parse;
});
});
var testSuccess = function (Type, value) {
var parse = Type.constructor.parse = sinon.spy(function (value) {
return value;
});
var stringify = Type.constructor.prototype.stringify = sinon.spy(function (value) {
return Sequelize.ABSTRACT.prototype.stringify.apply(this, arguments);
});
current.refreshTypes();
var User = current.define('user', {
field: Type
}, {
timestamps: false
});
return current.sync({ force: true }).then(function () {
return User.create({
field: value
});
}).then(function () {
return User.findAll().get(0);
}).then(function (user) {
expect(parse).to.have.been.called;
expect(stringify).to.have.been.called;
delete Type.constructor.parse;
delete Type.constructor.prototype.stringify;
});
};
var testFailure = function (Type, value) {
Type.constructor.parse = _.noop();
expect(function () {
current.refreshTypes();
}).to.throw('Parse function not supported for type ' + Type.key + ' in dialect ' + dialect);
delete Type.constructor.parse;
};
if (dialect === 'postgres') {
it('calls parse and stringify for JSON', function () {
var Type = new Sequelize.JSON();
return testSuccess(Type, { test: 42, nested: { foo: 'bar' }});
});
it('calls parse and stringify for JSONB', function () {
var Type = new Sequelize.JSONB();
return testSuccess(Type, { test: 42, nested: { foo: 'bar' }});
});
it('calls parse and stringify for HSTORE', function () {
var Type = new Sequelize.HSTORE();
return testSuccess(Type, { test: 42, nested: false });
});
it('calls parse and stringify for RANGE', function () {
var Type = new Sequelize.RANGE(new Sequelize.INTEGER());
return testSuccess(Type, [1, 2]);
});
}
it('calls parse and stringify for DATE', function () {
var Type = new Sequelize.DATE();
return testSuccess(Type, new Date());
});
it('calls parse and stringify for DATEONLY', function () {
var Type = new Sequelize.DATEONLY();
return testSuccess(Type, new Date());
});
it('calls parse and stringify for TIME', function () {
var Type = new Sequelize.TIME();
return testSuccess(Type, new Date());
});
it('calls parse and stringify for BLOB', function () {
var Type = new Sequelize.BLOB();
return testSuccess(Type, 'foobar');
});
it('calls parse and stringify for CHAR', function () {
var Type = new Sequelize.CHAR();
return testSuccess(Type, 'foobar');
});
it('calls parse and stringify for STRING', function () {
var Type = new Sequelize.STRING();
return testSuccess(Type, 'foobar');
});
it('calls parse and stringify for TEXT', function () {
var Type = new Sequelize.TEXT();
if (dialect === 'mssql') {
// Text uses nvarchar, same type as string
testFailure(Type);
} else {
return testSuccess(Type, 'foobar');
}
});
it('calls parse and stringify for BOOLEAN', function () {
var Type = new Sequelize.BOOLEAN();
return testSuccess(Type, true);
});
it('calls parse and stringify for INTEGER', function () {
var Type = new Sequelize.INTEGER();
return testSuccess(Type, 1);
});
it('calls parse and stringify for DECIMAL', function () {
var Type = new Sequelize.DECIMAL();
return testSuccess(Type, 1.5);
});
it('calls parse and stringify for BIGINT', function () {
var Type = new Sequelize.BIGINT();
if (dialect === 'mssql') {
// Same type as integer
testFailure(Type);
} else {
return testSuccess(Type, 1);
}
});
it('calls parse and stringify for DOUBLE', function () {
var Type = new Sequelize.DOUBLE();
return testSuccess(Type, 1.5);
});
it('calls parse and stringify for FLOAT', function () {
var Type = new Sequelize.FLOAT();
if (dialect === 'postgres') {
// Postgres doesn't have float, maps to either decimal or double
testFailure(Type);
} else {
return testSuccess(Type, 1.5);
}
});
it('calls parse and stringify for REAL', function () {
var Type = new Sequelize.REAL();
return testSuccess(Type, 1.5);
});
it('calls parse and stringify for GEOMETRY', function () {
var Type = new Sequelize.GEOMETRY();
if (['postgres', 'mysql', 'mariadb'].indexOf(dialect) !== -1) {
return testSuccess(Type, { type: "Point", coordinates: [125.6, 10.1] });
} else {
// Not implemented yet
testFailure(Type);
}
});
it('calls parse and stringify for UUID', function () {
var Type = new Sequelize.UUID();
if (['postgres', 'sqlite'].indexOf(dialect) !== -1) {
return testSuccess(Type, uuid.v4());
} else {
// No native uuid type
testFailure(Type);
}
});
it('calls parse and stringify for ENUM', function () {
var Type = new Sequelize.ENUM('hat', 'cat');
// No dialects actually allow us to identify that we get an enum back..
testFailure(Type);
});
it('should parse an empty GEOMETRY field', function () {
var Type = new Sequelize.GEOMETRY();
if (current.dialect.supports.GEOMETRY) {
current.refreshTypes();
var User = current.define('user', { field: Type }, { timestamps: false });
var point = { type: "Point", coordinates: [] };
return current.sync({ force: true }).then(function () {
return User.create({
//insert a null GEOMETRY type
field: point
});
}).then(function () {
//This case throw unhandled exception
return User.findAll();
}).then(function(users){
if (Support.dialectIsMySQL()) {
// MySQL will return NULL, becuase they lack EMPTY geometry data support.
expect(users[0].field).to.be.eql(null);
} else if (dialect === 'postgres' || dialect === 'postgres-native') {
//Empty Geometry data [0,0] as per https://trac.osgeo.org/postgis/ticket/1996
expect(users[0].field).to.be.deep.eql({ type: "Point", coordinates: [0,0] });
} else {
expect(users[0].field).to.be.deep.eql(point);
}
});
}
});
});
| {
"content_hash": "1573a16f1a3f33f0305d87ffab12f3f1",
"timestamp": "",
"source": "github",
"line_count": 307,
"max_line_length": 113,
"avg_line_length": 28.596091205211728,
"alnum_prop": 0.6026882332839731,
"repo_name": "hariprasadkulkarni/sequelize",
"id": "07f9609b2a4ff87803191542ddc30a134621a518",
"size": "8779",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "test/integration/data-types.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2326349"
}
],
"symlink_target": ""
} |
package de.zib.scalaris.executor;
import com.ericsson.otp.erlang.OtpErlangException;
import de.zib.scalaris.RequestList;
import de.zib.scalaris.ResultList;
import de.zib.scalaris.UnknownException;
import de.zib.scalaris.operations.WriteOp;
/**
* Implements a write operation.
*
* @param <T> the type of the value to write
*
* @author Nico Kruber, kruber@zib.de
* @version 3.13
* @since 3.13
*/
public class ScalarisWriteOp<T> implements ScalarisOp {
final protected String key;
final protected T value;
/**
* Creates a write operation.
*
* @param key
* the key to write to
* @param value
* the value to write
*/
public ScalarisWriteOp(final String key, final T value) {
this.key = key;
this.value = value;
}
public int workPhases() {
return 1;
}
public final int doPhase(final int phase, final int firstOp, final ResultList results,
final RequestList requests) throws OtpErlangException, UnknownException,
IllegalArgumentException {
switch (phase) {
case 0: return prepareWrite(requests);
case 1: return checkWrite(firstOp, results);
default:
throw new IllegalArgumentException("No phase " + phase);
}
}
/**
* Adds the write operation to the request list.
*
* @param requests the request list
*
* @return <tt>0</tt> (no operation processed)
*/
protected int prepareWrite(final RequestList requests) throws OtpErlangException,
UnknownException {
requests.addOp(new WriteOp(key, value));
return 0;
}
/**
* Verifies the write operations.
*
* @param firstOp the first operation to process inside the result list
* @param results the result list
*
* @return <tt>1</tt> operation processed (the write)
*/
protected int checkWrite(final int firstOp, final ResultList results)
throws OtpErlangException, UnknownException {
results.processWriteAt(firstOp);
return 1;
}
/* (non-Javadoc)
* @see de.zib.scalaris.examples.wikipedia.ScalarisOp#toString()
*/
@Override
public String toString() {
return "Scalaris.write(" + key + ", " + value + ")";
}
/**
* Gets the key to write to.
*
* @return the key
*/
public String getKey() {
return key;
}
/**
* Gets the value to write.
*
* @return the value that will (or has been) be written
*/
public T getValue() {
return value;
}
}
| {
"content_hash": "83f1fb79e13508e383fa81d1c6574269",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 90,
"avg_line_length": 25.365384615384617,
"alnum_prop": 0.6080363912054587,
"repo_name": "digshock/scalaris",
"id": "047fe8e8ca6ebc5763241aa27ad37f63e2ddacc3",
"size": "3262",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "java-api/src/de/zib/scalaris/executor/ScalarisWriteOp.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "442"
},
{
"name": "Batchfile",
"bytes": "41195"
},
{
"name": "CSS",
"bytes": "85843"
},
{
"name": "Erlang",
"bytes": "5450156"
},
{
"name": "HTML",
"bytes": "18762"
},
{
"name": "Java",
"bytes": "1902670"
},
{
"name": "JavaScript",
"bytes": "12067"
},
{
"name": "Makefile",
"bytes": "13738"
},
{
"name": "Perl",
"bytes": "1414"
},
{
"name": "Python",
"bytes": "182080"
},
{
"name": "Ruby",
"bytes": "127156"
},
{
"name": "Shell",
"bytes": "135483"
},
{
"name": "TeX",
"bytes": "282937"
}
],
"symlink_target": ""
} |
package org.apache.ignite.jdbc;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.affinity.AffinityKey;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.ConnectorConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.binary.BinaryMarshaller;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import static java.sql.Types.DATE;
import static java.sql.Types.DECIMAL;
import static java.sql.Types.INTEGER;
import static java.sql.Types.OTHER;
import static java.sql.Types.VARCHAR;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
* Metadata tests.
*/
public class JdbcMetadataSelfTest extends GridCommonAbstractTest {
/** URL. */
private static final String URL = "jdbc:ignite://127.0.0.1/pers";
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
cfg.setConnectorConfiguration(new ConnectorConfiguration());
return cfg;
}
/**
* @return Cache configuration.
*/
protected CacheConfiguration cacheConfiguration() {
CacheConfiguration<?,?> cache = defaultCacheConfiguration();
cache.setCacheMode(PARTITIONED);
cache.setBackups(1);
cache.setWriteSynchronizationMode(FULL_SYNC);
return cache;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGridsMultiThreaded(3);
IgniteCache<String, Organization> orgCache = jcache(grid(0), cacheConfiguration(), "org",
String.class, Organization.class);
assert orgCache != null;
orgCache.put("o1", new Organization(1, "A"));
orgCache.put("o2", new Organization(2, "B"));
IgniteCache<AffinityKey, Person> personCache = jcache(grid(0), cacheConfiguration(), "pers",
AffinityKey.class, Person.class);
assert personCache != null;
personCache.put(new AffinityKey<>("p1", "o1"), new Person("John White", 25, 1));
personCache.put(new AffinityKey<>("p2", "o1"), new Person("Joe Black", 35, 1));
personCache.put(new AffinityKey<>("p3", "o2"), new Person("Mike Green", 40, 2));
jcache(grid(0), cacheConfiguration(), "metaTest", AffinityKey.class, MetaTest.class);
}
/**
* @throws Exception If failed.
*/
@Test
public void testResultSetMetaData() throws Exception {
Statement stmt = DriverManager.getConnection(URL).createStatement();
ResultSet rs = stmt.executeQuery(
"select p.name, o.id as orgId from \"pers\".Person p, \"org\".Organization o where p.orgId = o.id");
assert rs != null;
ResultSetMetaData meta = rs.getMetaData();
assert meta != null;
assert meta.getColumnCount() == 2;
assert "Person".equalsIgnoreCase(meta.getTableName(1));
assert "name".equalsIgnoreCase(meta.getColumnName(1));
assert "name".equalsIgnoreCase(meta.getColumnLabel(1));
assert meta.getColumnType(1) == VARCHAR;
assert "VARCHAR".equals(meta.getColumnTypeName(1));
assert "java.lang.String".equals(meta.getColumnClassName(1));
assert "Organization".equalsIgnoreCase(meta.getTableName(2));
assert "orgId".equalsIgnoreCase(meta.getColumnName(2));
assert "orgId".equalsIgnoreCase(meta.getColumnLabel(2));
assert meta.getColumnType(2) == INTEGER;
assert "INTEGER".equals(meta.getColumnTypeName(2));
assert "java.lang.Integer".equals(meta.getColumnClassName(2));
}
/**
* @throws Exception If failed.
*/
@Test
public void testDecimalAndDateTypeMetaData() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"select t.decimal, t.date from \"metaTest\".MetaTest as t");
assert rs != null;
ResultSetMetaData meta = rs.getMetaData();
assert meta != null;
assert meta.getColumnCount() == 2;
assert "METATEST".equalsIgnoreCase(meta.getTableName(1));
assert "DECIMAL".equalsIgnoreCase(meta.getColumnName(1));
assert "DECIMAL".equalsIgnoreCase(meta.getColumnLabel(1));
assert meta.getColumnType(1) == DECIMAL;
assert "DECIMAL".equals(meta.getColumnTypeName(1));
assert "java.math.BigDecimal".equals(meta.getColumnClassName(1));
assert "METATEST".equalsIgnoreCase(meta.getTableName(2));
assert "DATE".equalsIgnoreCase(meta.getColumnName(2));
assert "DATE".equalsIgnoreCase(meta.getColumnLabel(2));
assert meta.getColumnType(2) == DATE;
assert "DATE".equals(meta.getColumnTypeName(2));
assert "java.sql.Date".equals(meta.getColumnClassName(2));
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetTables() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables("", "pers", "%", new String[]{"TABLE"});
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals("PERSON", rs.getString("TABLE_NAME"));
rs = meta.getTables("", "org", "%", new String[]{"TABLE"});
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals("ORGANIZATION", rs.getString("TABLE_NAME"));
rs = meta.getTables("", "pers", "%", null);
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals("PERSON", rs.getString("TABLE_NAME"));
rs = meta.getTables("", "org", "%", null);
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals("ORGANIZATION", rs.getString("TABLE_NAME"));
rs = meta.getTables("", "PUBLIC", "", new String[]{"WRONG"});
assertFalse(rs.next());
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetColumns() throws Exception {
final boolean primitivesInformationIsLostAfterStore = ignite(0).configuration().getMarshaller() instanceof BinaryMarshaller;
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns("", "pers", "Person", "%");
assert rs != null;
Collection<String> names = new ArrayList<>(2);
names.add("NAME");
names.add("AGE");
names.add("ORGID");
int cnt = 0;
while (rs.next()) {
String name = rs.getString("COLUMN_NAME");
assert names.remove(name);
if ("NAME".equals(name)) {
assert rs.getInt("DATA_TYPE") == VARCHAR;
assert "VARCHAR".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 1;
} else if ("AGE".equals(name) || "ORGID".equals(name)) {
assert rs.getInt("DATA_TYPE") == INTEGER;
assert "INTEGER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == (primitivesInformationIsLostAfterStore ? 1 : 0);
}
if ("_KEY".equals(name)) {
assert rs.getInt("DATA_TYPE") == OTHER;
assert "OTHER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
}
if ("_VAL".equals(name)) {
assert rs.getInt("DATA_TYPE") == OTHER;
assert "OTHER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
}
cnt++;
}
assert names.isEmpty();
assert cnt == 3;
rs = meta.getColumns("", "org", "Organization", "%");
assert rs != null;
names.add("ID");
names.add("NAME");
cnt = 0;
while (rs.next()) {
String name = rs.getString("COLUMN_NAME");
assert names.remove(name);
if ("id".equals(name)) {
assert rs.getInt("DATA_TYPE") == INTEGER;
assert "INTEGER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
} else if ("name".equals(name)) {
assert rs.getInt("DATA_TYPE") == VARCHAR;
assert "VARCHAR".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 1;
}
if ("_KEY".equals(name)) {
assert rs.getInt("DATA_TYPE") == VARCHAR;
assert "VARCHAR".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
}
if ("_VAL".equals(name)) {
assert rs.getInt("DATA_TYPE") == OTHER;
assert "OTHER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
}
cnt++;
}
assert names.isEmpty();
assert cnt == 2;
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testMetadataResultSetClose() throws Exception {
try (Connection conn = DriverManager.getConnection(URL);
ResultSet tbls = conn.getMetaData().getTables(null, null, "%", null)) {
int colCnt = tbls.getMetaData().getColumnCount();
while (tbls.next()) {
for (int i = 0; i < colCnt; i++)
tbls.getObject(i + 1);
}
}
catch (Exception ignored) {
fail();
}
}
/**
* Check JDBC support flags.
*/
@Test
public void testCheckSupports() throws SQLException {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
assertTrue(meta.supportsANSI92EntryLevelSQL());
assertTrue(meta.supportsAlterTableWithAddColumn());
assertTrue(meta.supportsAlterTableWithDropColumn());
assertTrue(meta.nullPlusNonNullIsNull());
}
}
/**
* Person.
*/
private static class Person implements Serializable {
/** Name. */
@QuerySqlField(index = false)
private final String name;
/** Age. */
@QuerySqlField
private final int age;
/** Organization ID. */
@QuerySqlField
private final int orgId;
/**
* @param name Name.
* @param age Age.
* @param orgId Organization ID.
*/
private Person(String name, int age, int orgId) {
assert !F.isEmpty(name);
assert age > 0;
assert orgId > 0;
this.name = name;
this.age = age;
this.orgId = orgId;
}
}
/**
* Organization.
*/
private static class Organization implements Serializable {
/** ID. */
@QuerySqlField
private final int id;
/** Name. */
@QuerySqlField(index = false)
private final String name;
/**
* @param id ID.
* @param name Name.
*/
private Organization(int id, String name) {
this.id = id;
this.name = name;
}
}
/**
* Meta Test.
*/
private static class MetaTest implements Serializable {
/** ID. */
@QuerySqlField
private final int id;
/** Date. */
@QuerySqlField
private final Date date;
/** decimal. */
@QuerySqlField
private final BigDecimal decimal;
/**
* @param id ID.
* @param date Date.
*/
private MetaTest(int id, Date date, BigDecimal decimal) {
this.id = id;
this.date = date;
this.decimal = decimal;
}
}
}
| {
"content_hash": "7487b58abca79b7336ef75e71299e466",
"timestamp": "",
"source": "github",
"line_count": 402,
"max_line_length": 132,
"avg_line_length": 33.12686567164179,
"alnum_prop": 0.5706240144176616,
"repo_name": "daradurvs/ignite",
"id": "7583aa7e8b10cc630513f1278688b994f0bd96a0",
"size": "14119",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcMetadataSelfTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "61105"
},
{
"name": "C",
"bytes": "5286"
},
{
"name": "C#",
"bytes": "6398736"
},
{
"name": "C++",
"bytes": "3684371"
},
{
"name": "CSS",
"bytes": "281251"
},
{
"name": "Dockerfile",
"bytes": "16105"
},
{
"name": "Groovy",
"bytes": "15081"
},
{
"name": "HTML",
"bytes": "821135"
},
{
"name": "Java",
"bytes": "42324953"
},
{
"name": "JavaScript",
"bytes": "1785625"
},
{
"name": "M4",
"bytes": "21724"
},
{
"name": "Makefile",
"bytes": "121296"
},
{
"name": "PHP",
"bytes": "486991"
},
{
"name": "PLpgSQL",
"bytes": "623"
},
{
"name": "PowerShell",
"bytes": "11844"
},
{
"name": "Python",
"bytes": "342274"
},
{
"name": "Scala",
"bytes": "1386030"
},
{
"name": "Shell",
"bytes": "615962"
},
{
"name": "TSQL",
"bytes": "6130"
},
{
"name": "TypeScript",
"bytes": "476855"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "74b08bf6c2a61603e2177c094cc554d5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "ffc796d2ad1b246986b846c78703fb673a217f1c",
"size": "192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Myrcia/Myrcia selloi/ Syn. Myrcia ramulosa microsiphonata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
- Polymorphic path now casts route into a symbol (prevents error on Rails 6)
## version 1.2.0
- Add _target_ option to custom actions
- Rework README documentation
## version 1.1.0
- Upgrade to Rails 6.1
- [FEATURE] Change style given a method (#25)
- Remove comma separator enforcer
- Force locale settings on numbers
- Add documentation
- Add comma separator option to numbers
## version 1.0.5
- Delete rails 5 restriction (#22)
## version 1.0.4
- Add class to td, for custom styles
## version 1.0.3
- Fix allow currency and sortable attributes work together
- Fix display format of data time
## version 1.0.2
- Fix application of ability model on record actions
## version 1.0.1
- Fix table headers for associated model with ransack
## version 0.1.13.beta
- Add whole row clikable link as an option
## version 0.1.12.beta
- Add option to don't truncate cell strings, passing `:no_truncate` as an attribute parameter
- added settings option to change trucate defaults such as `separator`, `length` and `omission`
## version 0.1.11.beta
- Add `localized` table cell, passing :l as an attribute parameter
## version 0.1.10.beta
- Fix table_for_cell_for_image_image_class in helper
## version 0.1.9.beta
- Remove `.capitalize` from `human_attribute_name("#{attribute}")`
- Add `percentage numeric_type cell` with `configurable precision decimals`
- Change `PaperClip class defintion` with `Paperclip class defintion`
- Add `setting image class` with `configurable class`
## version 0.1.8.beta
- Add Changelog.md
- Remove dependencies:
- Bootstrap
- Fontawesome
- include media
- Use `human_attribute_name` for attributes translations
- Check if Ransack is defined to apply `sort_link`
- Table_for optional settings in initializer
- Table_for configurable breakpoint
- Try title or name when attibute is an association and no asssciation attribute specified
- Customizable icon font and action icons
- Differentiate `Time` and `TimeWithZone` cells
- `Numeric` with `:currency` option to format with `number_to_currency`
| {
"content_hash": "7b5780c38afb25ac3a904b3902823b97",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 95,
"avg_line_length": 27,
"alnum_prop": 0.7456140350877193,
"repo_name": "CodiTramuntana/ct_table_for",
"id": "6f675730115acf862bf7a6a9d8011f25fbc7e08a",
"size": "2083",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "883"
},
{
"name": "JavaScript",
"bytes": "780"
},
{
"name": "Ruby",
"bytes": "17352"
}
],
"symlink_target": ""
} |
[](https://github.com/google/built_collection.dart/actions/workflows/build.yaml)
[](https://pub.dev/packages/built_collection)
[](https://pub.dev/packages/built_collection/publisher)
## Introduction
Built Collections are immutable collections using the
[builder pattern](https://en.wikipedia.org/wiki/Builder_pattern).
Each of the core SDK collections is split in two: a mutable builder class
and an immutable "built" class. Builders are for computation,
"built" classes are for safely sharing with no need to copy defensively.
Immutable collections work particularly well with immutable values. See
[built_value](https://github.com/google/built_value.dart#built-values-for-dart).
You can read more about built_collection
[on medium](https://medium.com/@davidmorgan_14314/darts-built-collection-for-immutable-collections-db662f705eff).
## Design
Built Collections:
* are immutable, if the elements/keys/values used are immutable;
* are comparable;
* are hashable;
* use copy-on-write to avoid copying unnecessarily.
See below for details on each of these points.
## Recommended Style
A project can benefit greatly from using Built Collections throughout.
Methods that will not mutate a collection can accept the "built" version,
making it clear that no mutation will happen and completely avoiding
the need for defensive copying.
For code that is public to other projects or teams not using
Built Collections, prefer to accept `Iterable` where possible. That way
your code is compatible with SDK collections, Built Collections and any
other collection implementation that builds on `Iterable`.
It's okay to accept `List`, `Set` or `Map` if needed. Built Collections
provide efficient conversion to their SDK counterparts via
`BuiltList.toList`, `BuiltListMultimap.toMap`, `BuiltSet.toSet`,
`BuiltMap.toMap` and `BuiltSetMultimap.toMap`.
## Built Collections are Immutable
Built Collections do not offer any methods that modify the collection. In
order to make changes, first call `toBuilder` to get a mutable builder.
In particular, Built Collections do not implement or extend their mutable
counterparts. `BuiltList` implements `Iterable`, but not `List`. `BuiltSet`
implements `Iterable`, but not `Set`. `BuiltMap`, `BuiltListMultimap` and
`BuiltSetMultimap` share no interface with the SDK collections.
Built Collections can contain mutable elements. However, this use is not
recommended, as mutations to the elements will break comparison and
hashing.
## Built Collections are Comparable
Core SDK collections do not offer equality checks by default.
Built Collections do a deep comparison against other Built Collections
of the same type, only. Hashing is used to make repeated comparisons fast.
## Built Collections are Hashable
Core SDK collections do not compute a deep hashCode.
Built Collections do compute, and cache, a deep hashCode. That means they
can be stored inside collections that need hashing, such as hash sets and
hash maps. They also use the cached hash code to speed up repeated
comparisons.
## Built Collections Avoid Copying Unnecessarily
Built Collections and their builder and helper types collaborate to avoid
copying unless it's necessary.
In particular, `BuiltList.toList`, `BuiltListMultimap.toMap`,
`BuiltSet.toSet`, `BuiltMap.toMap` and `BuiltSetMultimap.toMap` do not make
a copy, but return a copy-on-write wrapper. So, Built Collections can be
efficiently and easily used with code that needs core SDK collections but
does not mutate them.
When you want to provide a collection that explicitly _throws_ when a
mutation is attempted, use `BuiltList.asList`,
`BuiltListMultimap.asMap`, `BuiltSet.asSet`, `BuiltSetMultimap.asMap`
and `BuiltMap.asMap`.
## Features and bugs
Please file feature requests and bugs at the [issue tracker][tracker].
[tracker]: https://github.com/google/built_collection.dart/issues
| {
"content_hash": "63b498d1a33023729284751a086599ad",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 176,
"avg_line_length": 39.60576923076923,
"alnum_prop": 0.7926681233309055,
"repo_name": "google/built_collection.dart",
"id": "58bea48beb87453687e34e158b760e8384a34bc3",
"size": "4119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Dart",
"bytes": "248977"
},
{
"name": "HTML",
"bytes": "217"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
using CodeContracts;
namespace TestFoundations.IntegrationTests.Shared
{
public interface InterfaceWithProperties
{
byte PropertyWithoutAll { get; set; }
[Range(0, 500)]
byte PropertyWithRange0And500 { get; set; }
[Range(100uL, 200uL)]
byte PropertyWithRange100And200GetOnly { get; }
[Range(100u, 200u)]
byte PropertyWithRange100And200SetOnly { set; }
}
public class InterfaceWithPropertiesImplementation : InterfaceWithProperties
{
public byte PropertyWithoutAll { get; set; }
public byte PropertyWithRange0And500 { get; set; }
public byte FieldWithRange100And200GetOnly;
public byte PropertyWithRange100And200GetOnly
{
get { return FieldWithRange100And200GetOnly; }
}
public byte FieldWithRange100And200SetOnly;
public byte PropertyWithRange100And200SetOnly
{
set { FieldWithRange100And200SetOnly = value; }
}
}
}
| {
"content_hash": "7591760736dd4e0b5893462b10cf964b",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 80,
"avg_line_length": 27.1,
"alnum_prop": 0.6678966789667896,
"repo_name": "NickRusinov/CodeContracts.Fody",
"id": "c31e65dd988f93c9c553c6904be61dec2dfdbabb",
"size": "1086",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "TestFoundations/TestFoundations.IntegrationTests.Shared/InterfaceWithProperties.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "151"
},
{
"name": "C#",
"bytes": "726962"
},
{
"name": "F#",
"bytes": "2138"
},
{
"name": "PowerShell",
"bytes": "3577"
}
],
"symlink_target": ""
} |
var express = require('express');
var router = express.Router();
var fs = require('fs')
var User = require('../../models/User')
/* GET home page. */
router.get('/', function(req, res, next) {
User.find({}, function(err, users) {
res.render('admin/all-admins', {users: users})
});
});
router.delete('/:user_id', function(req, res, next) {
User.findById(req.params.user_id)
.exec(function(err, item){
if (err || !item) {
res.statusCode = 404;
res.send({message: '404'});
} else {
item.remove(function(err) {
if (err) {
res.statusCode = 403;
res.send(err);
} else {
res.redirect('/admin/all-admins');
if(item.avatarUrl){
fs.unlink(item.avatarUrl.path) // Delete post's image
}
}
});
}
})
});
module.exports = router; | {
"content_hash": "bf97582aa9ac5955c87da725522c68fb",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 73,
"avg_line_length": 27.64864864864865,
"alnum_prop": 0.4525904203323558,
"repo_name": "Eslam-nasser-wd/node-blog",
"id": "560e50cb5f515da6601af5b701702e9b0f18e395",
"size": "1023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "routes/admin/all-admins.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "933238"
},
{
"name": "CoffeeScript",
"bytes": "83631"
},
{
"name": "HTML",
"bytes": "434229"
},
{
"name": "JavaScript",
"bytes": "7019001"
},
{
"name": "PHP",
"bytes": "2157"
},
{
"name": "Shell",
"bytes": "444"
}
],
"symlink_target": ""
} |
The JaneSliderControl is a UIControl subclass that can be customized to fit the style of your app. It provides feedback for starting the slide, progress while sliding, canceling the slide and finishing the slide.

## Swift Version
For using swift version `3.0`, tags `0.2.*`
For using swift version `2.3`, tags `0.1.*`
## Setup
### Install using Cocoapods (recommended)
1. Add `JaneSliderControl` to your podfile and run `pod install`
2. Add a JaneSliderControl to your `UIViewController` either programmatically or using storyboards.
3. Add one or more of the `IBActions` listed in the Features section below
> To install without Cocoapods, add the `SliderControl.swift` file found in `JaneSliderControl/SliderControl/` then follow steps 2 and 3.
## Features
### IBActions
You can use the following IBActions with the JaneSliderControl:
|IBAction|Description|
|---|---|
|`.EditingDidBegin`|User has started sliding|
|`.ValueChanged`|User is sliding the control|
|`.PrimaryActionTriggered`|User finished sliding the control. <br/> (Note: this only works on iOS 9 and above)|
|`.EditingDidEnd`|User finished sliding the control. <br/> (Note: use in place of `.PrimaryActionTriggered` if you target a version of iOS below 9.0)|
|`.TouchCancel`|User did not finish sliding the control|
### Customize
The control has the following properties to customize the look of the slider control. They all have the IBInspectable tag, though IB does not currently support all the types used, so some items will have to be set programmatically.
> Note: in the descriptions below, we are calling the part of the slider control that slides over top the background "slider", the part that the slider slide over the "background", and the complete control is just called the "control"
|Variable|Can Set in IB|Description|
|---|:---:|---|
|sliderColor|**Yes**|The color of the slider|
|textColor|**Yes**|The color of the background text|
|cornerRadius|**Yes**|The corner radius for both the control and the slider|
|sliderText|**Yes**|The text that goes over the background|
|sliderWidth|**Yes**|The width of the slider (not the control)|
|sliderImage|**Yes**|An optional image to go on the slider. The image will stick to the in of the slider as it slides|
|sliderImageContentMode|No|ContentMode for the sliderImage|
|sliderFont|No|The font for the sliderText|
### Other Properties
The slider also has a read only property called `progress` that tells you the progress of the slider as it slides. The values range from 0 to 1.
You can manually set the progress using `.setProgress(1, animated: true)`. This works to toggle the slider on/off with values 1 and 0.
## License
This project is made available with the MIT License.
## Feedback
If you have any issues or feature request for this project, please create an issue and/or send us a pull request.
We hope you enjoy the JaneSliderControl!
| {
"content_hash": "2a5ef179de4ee7b0b5027e240133ded2",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 234,
"avg_line_length": 52.160714285714285,
"alnum_prop": 0.7627524820267032,
"repo_name": "jane/JaneSliderControl",
"id": "daff8b46cea41696231d16d6f6943d7daf8e6ad0",
"size": "2953",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "478"
},
{
"name": "Ruby",
"bytes": "557"
},
{
"name": "Swift",
"bytes": "14012"
}
],
"symlink_target": ""
} |
require.config({
//By default load any module IDs from js/lib
baseUrl: '/',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
"shim": {
},
map: {
'*': {
'css': "/plugin/require-css/require-css.js"
}
}
}); | {
"content_hash": "4d119ac11eef4f9fdee49d9947c554c6",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 55,
"avg_line_length": 26.058823529411764,
"alnum_prop": 0.5665914221218962,
"repo_name": "zodiac-xl/react-demo",
"id": "9450c3276272a5f7ead40beb2e4ae97011a397c7",
"size": "443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/static/base/source/require-config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2066"
},
{
"name": "HTML",
"bytes": "2416"
},
{
"name": "JavaScript",
"bytes": "105695"
}
],
"symlink_target": ""
} |
package org.apache.jmeter.testbeans.gui;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import org.apache.commons.lang3.ClassUtils;
import org.apache.jmeter.gui.ClearGui;
import org.apache.jmeter.testbeans.TestBeanHelper;
import org.apache.jmeter.util.JMeterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The GenericTestBeanCustomizer is designed to provide developers with a
* mechanism to quickly implement GUIs for new components.
* <p>
* It allows editing each of the public exposed properties of the edited type 'a
* la JavaBeans': as far as the types of those properties have an associated
* editor, there's no GUI development required.
* <p>
* This class understands the following PropertyDescriptor attributes:
* <dl>
* <dt>group: String</dt>
* <dd>Group under which the property should be shown in the GUI. The string is
* also used as a group title (but see comment on resourceBundle below). The
* default group is "".</dd>
* <dt>order: Integer</dt>
* <dd>Order in which the property will be shown in its group. A smaller
* integer means higher up in the GUI. The default order is 0. Properties of
* equal order are sorted alphabetically.</dd>
* <dt>tags: String[]</dt>
* <dd>List of values to be offered for the property in addition to those
* offered by its property editor.</dd>
* <dt>notUndefined: Boolean</dt>
* <dd>If true, the property should not be left undefined. A <b>default</b>
* attribute must be provided if this is set.</dd>
* <dt>notExpression: Boolean</dt>
* <dd>If true, the property content should always be constant: JMeter
* 'expressions' (strings using ${var}, etc...) can't be used.</dd>
* <dt>notOther: Boolean</dt>
* <dd>If true, the property content must always be one of the tags values or
* null.</dd>
* <dt>default: Object</dt>
* <dd>Initial value for the property's GUI. Must be provided and be non-null
* if <b>notUndefined</b> is set. Must be one of the provided tags (or null) if
* <b>notOther</b> is set.
* </dl>
* <p>
* The following BeanDescriptor attributes are also understood:
* <dl>
* <dt>group.<i>group</i>.order: Integer</dt>
* <dd>where <b><i>group</i></b> is a group name used in a <b>group</b>
* attribute in one or more PropertyDescriptors. Defines the order in which the
* group will be shown in the GUI. A smaller integer means higher up in the GUI.
* The default order is 0. Groups of equal order are sorted alphabetically.</dd>
* <dt>resourceBundle: ResourceBundle</dt>
* <dd>A resource bundle to be used for GUI localization: group display names
* will be obtained from property "<b><i>group</i>.displayName</b>" if
* available (where <b><i>group</i></b> is the group name).
* </dl>
*/
public class GenericTestBeanCustomizer extends JPanel implements SharedCustomizer {
private static final long serialVersionUID = 241L;
private static final Logger log = LoggerFactory.getLogger(GenericTestBeanCustomizer.class);
// Need to register Editors for Java classes because we cannot create them
// in the same package, nor can we create them in the built-in search patch of packages,
// as that is not part of the public API
static {
PropertyEditorManager.registerEditor(Long.class, LongPropertyEditor.class);
PropertyEditorManager.registerEditor(Integer.class, IntegerPropertyEditor.class);
PropertyEditorManager.registerEditor(Boolean.class, BooleanPropertyEditor.class);
}
public static final String GROUP = "group"; //$NON-NLS-1$
public static final String ORDER = "order"; //$NON-NLS-1$
/**
* Array of permissible values.
* <p>
* Must be provided if:
* <ul>
* <li>{@link #NOT_OTHER} is TRUE, and</li>
* <li>{@link PropertyEditor#getTags()} is null</li>
* </ul>
*/
public static final String TAGS = "tags"; //$NON-NLS-1$
/**
* Whether the field must be defined (i.e. is required);
* Boolean, defaults to FALSE
*/
public static final String NOT_UNDEFINED = "notUndefined"; //$NON-NLS-1$
/** Whether the field disallows JMeter expressions; Boolean, default FALSE */
public static final String NOT_EXPRESSION = "notExpression"; //$NON-NLS-1$
/** Whether the field disallows constant values different from the provided tags; Boolean, default FALSE */
public static final String NOT_OTHER = "notOther"; //$NON-NLS-1$
/** If specified, create a multi-line editor */
public static final String MULTILINE = "multiline";
/** Default value, must be provided if {@link #NOT_UNDEFINED} is TRUE */
public static final String DEFAULT = "default"; //$NON-NLS-1$
/** Default value is not saved; only non-defaults are saved */
public static final String DEFAULT_NOT_SAVED = "defaultNoSave"; //$NON-NLS-1$
/** Pointer to the resource bundle, if any (will generally be null) */
public static final String RESOURCE_BUNDLE = "resourceBundle"; //$NON-NLS-1$
/** Property editor override; must be an enum of type {@link TypeEditor} */
public static final String GUITYPE = "guiType"; // $NON-NLS-$
/** TextEditor property */
public static final String TEXT_LANGUAGE = "textLanguage"; //$NON-NLS-1$
public static String ORDER(String group) {
return "group." + group + ".order";
}
public static final String DEFAULT_GROUP = "";
@SuppressWarnings("unused") // TODO - use or remove
private int scrollerCount = 0;
/**
* BeanInfo object for the class of the objects being edited.
*/
private transient BeanInfo beanInfo;
/**
* Property descriptors from the beanInfo.
*/
private transient PropertyDescriptor[] descriptors;
/**
* Property editors -- or null if the property can't be edited. Unused if
* customizerClass==null.
*/
private transient PropertyEditor[] editors;
/**
* Message format for property field labels:
*/
private MessageFormat propertyFieldLabelMessage;
/**
* Message format for property tooltips:
*/
private MessageFormat propertyToolTipMessage;
/**
* The Map we're currently customizing. Set by setObject().
*/
private Map<String, Object> propertyMap;
/**
* @deprecated only for use by test code
*/
@Deprecated
public GenericTestBeanCustomizer(){
log.warn("Constructor only intended for use in testing"); // $NON-NLS-1$
}
/**
* Create a customizer for a given test bean type.
* @param beanInfo {@link BeanInfo}
* @see org.apache.jmeter.testbeans.TestBean
*/
GenericTestBeanCustomizer(BeanInfo beanInfo) {
super();
this.beanInfo = beanInfo;
// Get and sort the property descriptors:
descriptors = beanInfo.getPropertyDescriptors();
Arrays.sort(descriptors, new PropertyComparator(beanInfo));
// Obtain the propertyEditors:
editors = new PropertyEditor[descriptors.length];
int scriptLanguageIndex = 0;
int textAreaEditorIndex = 0;
for (int i = 0; i < descriptors.length; i++) { // Index is also used for accessing editors array
PropertyDescriptor descriptor = descriptors[i];
String name = descriptor.getName();
// Don't get editors for hidden or non-read-write properties:
if (TestBeanHelper.isDescriptorIgnored(descriptor)) {
log.debug("Skipping editor for property {}", name);
editors[i] = null;
continue;
}
PropertyEditor propertyEditor;
Object guiType = descriptor.getValue(GUITYPE);
if (guiType instanceof TypeEditor) {
propertyEditor = ((TypeEditor) guiType).getInstance(descriptor);
} else if (guiType instanceof Class && Enum.class.isAssignableFrom((Class<?>) guiType)) {
@SuppressWarnings("unchecked") // we check the class type above
final Class<? extends Enum<?>> enumClass = (Class<? extends Enum<?>>) guiType;
propertyEditor = new EnumEditor(descriptor, enumClass, (ResourceBundle) descriptor.getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE));
} else {
Class<?> editorClass = descriptor.getPropertyEditorClass();
log.debug("Property {} has editor class {}", name, editorClass);
if (editorClass != null) {
try {
propertyEditor = (PropertyEditor) editorClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.error("Can't create property editor.", e);
throw new Error(e.toString());
}
} else {
Class<?> c = descriptor.getPropertyType();
propertyEditor = PropertyEditorManager.findEditor(c);
}
}
if (propertyEditor == null) {
if (log.isWarnEnabled()) {
log.warn("No editor for property: {} type: {} in bean: {}", name, descriptor.getPropertyType(),
beanInfo.getBeanDescriptor().getDisplayName());
}
editors[i] = null;
continue;
}
log.debug("Property {} has property editor {}", name, propertyEditor);
validateAttributes(descriptor, propertyEditor);
if (!propertyEditor.supportsCustomEditor()) {
propertyEditor = createWrapperEditor(propertyEditor, descriptor);
log.debug("Editor for property {} is wrapped in {}", name, propertyEditor);
}
if(propertyEditor instanceof TestBeanPropertyEditor)
{
((TestBeanPropertyEditor)propertyEditor).setDescriptor(descriptor);
}
if (propertyEditor instanceof TextAreaEditor) {
textAreaEditorIndex = i;
}
if (propertyEditor.getCustomEditor() instanceof JScrollPane) {
scrollerCount++;
}
editors[i] = propertyEditor;
// Initialize the editor with the provided default value or null:
setEditorValue(i, descriptor.getValue(DEFAULT));
if (name.equals("scriptLanguage")) {
scriptLanguageIndex = i;
}
}
// In case of BSF and JSR elements i want to add textAreaEditor as a listener to scriptLanguage ComboBox.
String beanName = this.beanInfo.getBeanDescriptor().getName();
if (beanName.startsWith("BSF") || beanName.startsWith("JSR223")) { // $NON-NLS-1$ $NON-NLS-2$
WrapperEditor we = (WrapperEditor) editors[scriptLanguageIndex];
TextAreaEditor tae = (TextAreaEditor) editors[textAreaEditorIndex];
we.addChangeListener(tae);
}
// Obtain message formats:
propertyFieldLabelMessage = new MessageFormat(JMeterUtils.getResString("property_as_field_label")); //$NON-NLS-1$
propertyToolTipMessage = new MessageFormat(JMeterUtils.getResString("property_tool_tip")); //$NON-NLS-1$
// Initialize the GUI:
init();
}
/**
* Validate the descriptor attributes.
*
* @param pd the descriptor
* @param pe the propertyEditor
*/
private static void validateAttributes(PropertyDescriptor pd, PropertyEditor pe) {
final Object deflt = pd.getValue(DEFAULT);
if (deflt == null) {
if (notNull(pd)) {
if (log.isWarnEnabled()) {
log.warn("{} requires a value but does not provide a default.", getDetails(pd));
}
}
if (noSaveDefault(pd)) {
if (log.isWarnEnabled()) {
log.warn("{} specifies DEFAULT_NO_SAVE but does not provide a default.", getDetails(pd));
}
}
} else {
final Class<?> defltClass = deflt.getClass(); // the DEFAULT class
// Convert int to Integer etc:
final Class<?> propClass = ClassUtils.primitiveToWrapper(pd.getPropertyType());
if (!propClass.isAssignableFrom(defltClass) ){
if (log.isWarnEnabled()) {
log.warn("{} has a DEFAULT of class {}", getDetails(pd), defltClass.getCanonicalName());
}
}
}
if (notOther(pd) && pd.getValue(TAGS) == null && pe.getTags() == null) {
if (log.isWarnEnabled()) {
log.warn("{} does not have tags but other values are not allowed.", getDetails(pd));
}
}
if (!notNull(pd)) {
Class<?> propertyType = pd.getPropertyType();
if (propertyType.isPrimitive()) {
if (log.isWarnEnabled()) {
log.warn("{} allows null but is a primitive type", getDetails(pd));
}
}
}
if (!pd.attributeNames().hasMoreElements()) {
if (log.isWarnEnabled()) {
log.warn("{} does not appear to have been configured", getDetails(pd));
}
}
}
/**
* Identify the property from the descriptor.
*
* @param pd
* @return the property details
*/
private static String getDetails(PropertyDescriptor pd) {
return pd.getReadMethod().getDeclaringClass().getName() + '#'
+ pd.getName() + '(' + pd.getPropertyType().getCanonicalName()
+ ')';
}
/**
* Find the default typeEditor and a suitable guiEditor for the given
* property descriptor, and combine them in a WrapperEditor.
*
* @param typeEditor
* @param descriptor
* @return the wrapper editor
*/
private WrapperEditor createWrapperEditor(PropertyEditor typeEditor, PropertyDescriptor descriptor) {
String[] editorTags = typeEditor.getTags();
String[] additionalTags = (String[]) descriptor.getValue(TAGS);
String[] tags;
if (editorTags == null) {
tags = additionalTags;
} else if (additionalTags == null) {
tags = editorTags;
} else {
tags = new String[editorTags.length + additionalTags.length];
int j = 0;
for (String editorTag : editorTags) {
tags[j++] = editorTag;
}
for (String additionalTag : additionalTags) {
tags[j++] = additionalTag;
}
}
boolean notNull = notNull(descriptor);
boolean notExpression = notExpression(descriptor);
boolean notOther = notOther(descriptor);
PropertyEditor guiEditor;
if (notNull && tags == null) {
guiEditor = new FieldStringEditor();
} else {
guiEditor = new ComboStringEditor(tags, notExpression && notOther, notNull,
(ResourceBundle) descriptor.getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE));
}
return new WrapperEditor(typeEditor, guiEditor,
!notNull, // acceptsNull
!notExpression, // acceptsExpressions
!notOther, // acceptsOther
descriptor.getValue(DEFAULT));
}
/**
* Returns true if the property disallows constant values different from the provided tags.
*
* @param descriptor the property descriptor
* @return true if the attribute {@link #NOT_OTHER} is defined and equal to Boolean.TRUE;
* otherwise the default is false
*/
static boolean notOther(PropertyDescriptor descriptor) {
return Boolean.TRUE.equals(descriptor.getValue(NOT_OTHER));
}
/**
* Returns true if the property does not allow JMeter expressions.
*
* @param descriptor the property descriptor
* @return true if the attribute {@link #NOT_EXPRESSION} is defined and equal to Boolean.TRUE;
* otherwise the default is false
*/
static boolean notExpression(PropertyDescriptor descriptor) {
return Boolean.TRUE.equals(descriptor.getValue(NOT_EXPRESSION));
}
/**
* Returns true if the property must be defined (i.e. is required);
*
* @param descriptor the property descriptor
* @return true if the attribute {@link #NOT_UNDEFINED} is defined and equal to Boolean.TRUE;
* otherwise the default is false
*/
static boolean notNull(PropertyDescriptor descriptor) {
return Boolean.TRUE.equals(descriptor.getValue(NOT_UNDEFINED));
}
/**
* Returns true if the property default value is not saved
*
* @param descriptor the property descriptor
* @return true if the attribute {@link #DEFAULT_NOT_SAVED} is defined and equal to Boolean.TRUE;
* otherwise the default is false
*/
static boolean noSaveDefault(PropertyDescriptor descriptor) {
return Boolean.TRUE.equals(descriptor.getValue(DEFAULT_NOT_SAVED));
}
/**
* Set the value of the i-th property, properly reporting a possible
* failure.
*
* @param i
* the index of the property in the descriptors and editors
* arrays
* @param value
* the value to be stored in the editor
*
* @throws IllegalArgumentException
* if the editor refuses the value
*/
private void setEditorValue(int i, Object value) throws IllegalArgumentException {
editors[i].setValue(value);
}
/**
* {@inheritDoc}
* @param map must be an instance of Map<String, Object>
*/
@SuppressWarnings("unchecked")
@Override
public void setObject(Object map) {
propertyMap = (Map<String, Object>) map;
if (propertyMap.isEmpty()) {
// Uninitialized -- set it to the defaults:
for (PropertyDescriptor descriptor : descriptors) {
Object value = descriptor.getValue(DEFAULT);
String name = descriptor.getName();
if (value != null) {
propertyMap.put(name, value);
log.debug("Set {}={}", name, value);
}
firePropertyChange(name, null, value);
}
}
// Now set the editors to the element's values:
for (int i = 0; i < editors.length; i++) {
if (editors[i] == null) {
continue;
}
try {
setEditorValue(i, propertyMap.get(descriptors[i].getName()));
} catch (IllegalArgumentException e) {
// I guess this can happen as a result of a bad
// file read? In this case, it would be better to replace the
// incorrect value with anything valid, e.g. the default value
// for the property.
// But for the time being, I just prefer to be aware of any
// problems occurring here, most likely programming errors,
// so I'll bail out.
// (MS Note) Can't bail out - newly create elements have blank
// values and must get the defaults.
// Also, when loading previous versions of JMeter test scripts,
// some values
// may not be right, and should get default values - MS
// TODO: review this and possibly change to:
setEditorValue(i, descriptors[i].getValue(DEFAULT));
}
}
}
/**
* Initialize the GUI.
*/
private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
setLayout(new GridBagLayout());
GridBagConstraints cl = new GridBagConstraints(); // for labels
cl.gridx = 0;
cl.anchor = GridBagConstraints.EAST;
cl.insets = new Insets(0, 1, 0, 1);
GridBagConstraints ce = new GridBagConstraints(); // for editors
ce.fill = GridBagConstraints.BOTH;
ce.gridx = 1;
ce.weightx = 1.0;
ce.insets = new Insets(0, 1, 0, 1);
GridBagConstraints cp = new GridBagConstraints(); // for panels
cp.fill = GridBagConstraints.BOTH;
cp.gridx = 1;
cp.gridy = GridBagConstraints.RELATIVE;
cp.gridwidth = 2;
cp.weightx = 1.0;
JPanel currentPanel = this;
String currentGroup = DEFAULT_GROUP;
int y = 0;
for (int i = 0; i < editors.length; i++) {
if (editors[i] == null) {
continue;
}
if (log.isDebugEnabled()) {
log.debug("Laying property {}", descriptors[i].getName());
}
String g = group(descriptors[i]);
if (!currentGroup.equals(g)) {
if (currentPanel != this) {
add(currentPanel, cp);
}
currentGroup = g;
currentPanel = new JPanel(new GridBagLayout());
currentPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
groupDisplayName(g)));
cp.weighty = 0.0;
y = 0;
}
Component customEditor = editors[i].getCustomEditor();
boolean multiLineEditor = false;
if (customEditor.getPreferredSize().height > 50 || customEditor instanceof JScrollPane
|| descriptors[i].getValue(MULTILINE) != null) {
// TODO: the above works in the current situation, but it's
// just a hack. How to get each editor to report whether it
// wants to grow bigger? Whether the property label should
// be at the left or at the top of the editor? ...?
multiLineEditor = true;
}
JLabel label = createLabel(descriptors[i]);
label.setLabelFor(customEditor);
cl.gridy = y;
cl.gridwidth = multiLineEditor ? 2 : 1;
cl.anchor = multiLineEditor ? GridBagConstraints.CENTER : GridBagConstraints.EAST;
currentPanel.add(label, cl);
ce.gridx = multiLineEditor ? 0 : 1;
ce.gridy = multiLineEditor ? ++y : y;
ce.gridwidth = multiLineEditor ? 2 : 1;
ce.weighty = multiLineEditor ? 1.0 : 0.0;
cp.weighty += ce.weighty;
currentPanel.add(customEditor, ce);
y++;
}
if (currentPanel != this) {
add(currentPanel, cp);
}
// Add a 0-sized invisible component that will take all the vertical
// space that nobody wants:
cp.weighty = 0.0001;
add(Box.createHorizontalStrut(0), cp);
}
private JLabel createLabel(PropertyDescriptor desc) {
String text = desc.getDisplayName();
if (!"".equals(text)) {
text = propertyFieldLabelMessage.format(new Object[] { desc.getDisplayName() });
}
// if the displayName is the empty string, leave it like that.
JLabel label = new JLabel(text);
label.setHorizontalAlignment(SwingConstants.TRAILING);
label.setToolTipText(propertyToolTipMessage.format(new Object[] { desc.getShortDescription() }));
return label;
}
/**
* Obtain a property descriptor's group.
*
* @param descriptor
* @return the group String.
*/
private static String group(PropertyDescriptor descriptor) {
String group = (String) descriptor.getValue(GROUP);
if (group == null){
group = DEFAULT_GROUP;
}
return group;
}
/**
* Obtain a group's display name
*/
private String groupDisplayName(String group) {
ResourceBundle b = (ResourceBundle) beanInfo.getBeanDescriptor().getValue(RESOURCE_BUNDLE);
if (b == null) {
return group;
}
String key = group + ".displayName";
if (b.containsKey(key)) {
return b.getString(key);
} else {
return group;
}
}
/**
* Comparator used to sort properties for presentation in the GUI.
*/
private static class PropertyComparator implements Comparator<PropertyDescriptor>, Serializable {
private static final long serialVersionUID = 240L;
private final BeanInfo beanInfo;
public PropertyComparator(BeanInfo beanInfo) {
this.beanInfo = beanInfo;
}
@Override
public int compare(PropertyDescriptor d1, PropertyDescriptor d2) {
String g1 = group(d1);
String g2 = group(d2);
Integer go1 = groupOrder(g1);
Integer go2 = groupOrder(g2);
int result = go1.compareTo(go2);
if (result != 0) {
return result;
}
result = g1.compareTo(g2);
if (result != 0) {
return result;
}
Integer po1 = propertyOrder(d1);
Integer po2 = propertyOrder(d2);
result = po1.compareTo(po2);
if (result != 0) {
return result;
}
return d1.getName().compareTo(d2.getName());
}
/**
* Obtain a group's order.
*
* @param group
* group name
* @return the group's order (zero by default)
*/
private Integer groupOrder(String group) {
Integer order = (Integer) beanInfo.getBeanDescriptor().getValue(ORDER(group));
if (order == null) {
order = Integer.valueOf(0);
}
return order;
}
/**
* Obtain a property's order.
*
* @param d
* @return the property's order attribute (zero by default)
*/
private Integer propertyOrder(PropertyDescriptor d) {
Integer order = (Integer) d.getValue(ORDER);
if (order == null) {
order = Integer.valueOf(0);
}
return order;
}
}
/**
* Save values from the GUI fields into the property map
*/
void saveGuiFields() {
for (int i = 0; i < editors.length; i++) {
PropertyEditor propertyEditor=editors[i]; // might be null (e.g. in testing)
if (propertyEditor != null) {
Object value = propertyEditor.getValue();
String name = descriptors[i].getName();
if (value == null) {
propertyMap.remove(name);
log.debug("Unset {}", name);
} else {
propertyMap.put(name, value);
log.debug("Set {}={}", name, value);
}
}
}
}
void clearGuiFields() {
for (int i = 0; i < editors.length; i++) {
PropertyEditor propertyEditor=editors[i]; // might be null (e.g. in testing)
if (propertyEditor != null) {
try {
if (propertyEditor instanceof ClearGui) {
((ClearGui) propertyEditor).clearGui();
} else if (propertyEditor instanceof WrapperEditor){
WrapperEditor we = (WrapperEditor) propertyEditor;
String[] tags = we.getTags();
if (tags != null && tags.length > 0) {
we.setAsText(tags[0]);
} else {
we.resetValue();
}
} else {
propertyEditor.setAsText("");
}
} catch (IllegalArgumentException ex){
log.error("Failed to set field {}", descriptors[i].getName(), ex);
}
}
}
}
}
| {
"content_hash": "708eb8683d65c4fc37ceaba0ec8bb013",
"timestamp": "",
"source": "github",
"line_count": 761,
"max_line_length": 156,
"avg_line_length": 37.51905387647832,
"alnum_prop": 0.5867189688988512,
"repo_name": "vherilier/jmeter",
"id": "54b9502116bb6a8228ce9b02d049cfddcddb92aa",
"size": "29351",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "src/core/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25413"
},
{
"name": "CSS",
"bytes": "29800"
},
{
"name": "Groovy",
"bytes": "90513"
},
{
"name": "HTML",
"bytes": "93493"
},
{
"name": "Java",
"bytes": "8256350"
},
{
"name": "JavaScript",
"bytes": "36223"
},
{
"name": "Shell",
"bytes": "22701"
},
{
"name": "XSLT",
"bytes": "60761"
}
],
"symlink_target": ""
} |
package metadata
import (
"context"
"github.com/goharbor/harbor/src/common/security"
event2 "github.com/goharbor/harbor/src/controller/event"
"github.com/goharbor/harbor/src/pkg/notifier/event"
"time"
)
// DeleteRepositoryEventMetadata is the metadata from which the delete repository event can be resolved
type DeleteRepositoryEventMetadata struct {
Ctx context.Context
Repository string
ProjectID int64
}
// Resolve to the event from the metadata
func (d *DeleteRepositoryEventMetadata) Resolve(event *event.Event) error {
data := &event2.DeleteRepositoryEvent{
Repository: d.Repository,
ProjectID: d.ProjectID,
OccurAt: time.Now(),
}
cx, exist := security.FromContext(d.Ctx)
if exist {
data.Operator = cx.GetUsername()
}
event.Topic = event2.TopicDeleteRepository
event.Data = data
return nil
}
| {
"content_hash": "d7dfdad0bd4d92566fc531f75ec0b62f",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 103,
"avg_line_length": 26.15625,
"alnum_prop": 0.7574671445639187,
"repo_name": "reasonerjt/harbor",
"id": "e341bff0ca3d35889ff69dcba58bceb4a8372e27",
"size": "1431",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/controller/event/metadata/repository.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "98351"
},
{
"name": "Dockerfile",
"bytes": "18179"
},
{
"name": "Go",
"bytes": "4076064"
},
{
"name": "HTML",
"bytes": "486073"
},
{
"name": "JavaScript",
"bytes": "4784"
},
{
"name": "Makefile",
"bytes": "34745"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "PLSQL",
"bytes": "148"
},
{
"name": "PLpgSQL",
"bytes": "12834"
},
{
"name": "Python",
"bytes": "309187"
},
{
"name": "RobotFramework",
"bytes": "346744"
},
{
"name": "Shell",
"bytes": "69183"
},
{
"name": "Smarty",
"bytes": "26228"
},
{
"name": "TSQL",
"bytes": "7714"
},
{
"name": "TypeScript",
"bytes": "1544893"
}
],
"symlink_target": ""
} |
<form ng-submit="$event.preventDefault()"
class="search-form">
<md-autocomplete
ng-disabled="mgsc.isDisabled"
md-selected-item="mgsc.selectedItem"
md-search-text-change="mgsc.searchTextChange(mgsc.searchText)"
md-search-text="mgsc.searchText"
md-selected-item-change="mgsc.selectedItemChange(item)"
md-items="item in mgsc.querySearch(mgsc.searchText)"
md-item-text="item.name"
md-min-length="0"
placeholder="搜索GeoJSON?">
<md-item-template>
<span md-highlight-text="mgsc.searchText" md-highlight-flags="^i">{{item.name}}</span>
</md-item-template>
<md-not-found>
No matches found for "{{mgsc.searchText}}".
</md-not-found>
</md-autocomplete>
</form>
<md-content layout-fill
class="mmd-list ">
<md-list>
<md-list-item class="md-3-line"
ng-repeat="geoJSON in mgsc.geoJSONs"
ng-click="mgsc.display(geoJSON)">
<md-icon md-font-icon="pictogram activity-{{geoJSON.type}}"
class="leader"
alt="activity-1"
></md-icon>
<div class="md-list-item-text">
<h3 ng-click="$event.preventDefault();go('app.maps.geojson.display', {id: geoJSON.id})"> {{ geoJSON.name }} </h3>
<p> {{ geoJSON.description }} </p>
</div>
</md-list-item>
</md-list>
</md-content> | {
"content_hash": "1330e1e22c0851f612e71f51655f3e56",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 129,
"avg_line_length": 41.24324324324324,
"alnum_prop": 0.5373525557011796,
"repo_name": "anypossiblew/map-md-client",
"id": "157e556b4b43653e282281370b37887f1ed0ff70",
"size": "1530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/maps/geojson/search/search.tpl.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "77480"
},
{
"name": "HTML",
"bytes": "145781"
},
{
"name": "JavaScript",
"bytes": "560089"
},
{
"name": "Smarty",
"bytes": "798"
}
],
"symlink_target": ""
} |
"""Internal class for proxy query execution context implementation in the Azure
Cosmos database service.
"""
import json
from six.moves import xrange
from azure.cosmos.exceptions import CosmosHttpResponseError
from azure.cosmos._execution_context import multi_execution_aggregator
from azure.cosmos._execution_context.base_execution_context import _QueryExecutionContextBase
from azure.cosmos._execution_context.base_execution_context import _DefaultQueryExecutionContext
from azure.cosmos._execution_context.query_execution_info import _PartitionedQueryExecutionInfo
from azure.cosmos._execution_context import endpoint_component
from azure.cosmos.documents import _DistinctType
from azure.cosmos.http_constants import StatusCodes, SubStatusCodes
# pylint: disable=protected-access
def _is_partitioned_execution_info(e):
return (
e.status_code == StatusCodes.BAD_REQUEST and e.sub_status == SubStatusCodes.CROSS_PARTITION_QUERY_NOT_SERVABLE
)
def _get_partitioned_execution_info(e):
error_msg = json.loads(e.http_error_message)
return _PartitionedQueryExecutionInfo(json.loads(error_msg["additionalErrorInfo"]))
class _ProxyQueryExecutionContext(_QueryExecutionContextBase): # pylint: disable=abstract-method
"""Represents a proxy execution context wrapper.
By default, uses _DefaultQueryExecutionContext.
If backend responds a 400 error code with a Query Execution Info, switches
to _MultiExecutionContextAggregator
"""
def __init__(self, client, resource_link, query, options, fetch_function):
"""
Constructor
"""
super(_ProxyQueryExecutionContext, self).__init__(client, options)
self._execution_context = _DefaultQueryExecutionContext(client, options, fetch_function)
self._resource_link = resource_link
self._query = query
self._fetch_function = fetch_function
def __next__(self):
"""Returns the next query result.
:return: The next query result.
:rtype: dict
:raises StopIteration: If no more result is left.
"""
try:
return next(self._execution_context)
except CosmosHttpResponseError as e:
if _is_partitioned_execution_info(e):
query_to_use = self._query if self._query is not None else "Select * from root r"
query_execution_info = _PartitionedQueryExecutionInfo(self._client._GetQueryPlanThroughGateway
(query_to_use, self._resource_link))
self._execution_context = self._create_pipelined_execution_context(query_execution_info)
else:
raise e
return next(self._execution_context)
def fetch_next_block(self):
"""Returns a block of results.
This method only exists for backward compatibility reasons. (Because
QueryIterable has exposed fetch_next_block api).
:return: List of results.
:rtype: list
"""
try:
return self._execution_context.fetch_next_block()
except CosmosHttpResponseError as e:
if _is_partitioned_execution_info(e):
query_to_use = self._query if self._query is not None else "Select * from root r"
query_execution_info = _PartitionedQueryExecutionInfo(self._client._GetQueryPlanThroughGateway
(query_to_use, self._resource_link))
self._execution_context = self._create_pipelined_execution_context(query_execution_info)
else:
raise e
return self._execution_context.fetch_next_block()
def _create_pipelined_execution_context(self, query_execution_info):
assert self._resource_link, "code bug, resource_link is required."
if query_execution_info.has_aggregates() and not query_execution_info.has_select_value():
if self._options and ("enableCrossPartitionQuery" in self._options
and self._options["enableCrossPartitionQuery"]):
raise CosmosHttpResponseError(StatusCodes.BAD_REQUEST,
"Cross partition query only supports 'VALUE <AggregateFunc>' for aggregates")
execution_context_aggregator = multi_execution_aggregator._MultiExecutionContextAggregator(self._client,
self._resource_link,
self._query,
self._options,
query_execution_info)
return _PipelineExecutionContext(self._client, self._options, execution_context_aggregator,
query_execution_info)
next = __next__ # Python 2 compatibility.
class _PipelineExecutionContext(_QueryExecutionContextBase): # pylint: disable=abstract-method
DEFAULT_PAGE_SIZE = 1000
def __init__(self, client, options, execution_context, query_execution_info):
super(_PipelineExecutionContext, self).__init__(client, options)
if options.get("maxItemCount"):
self._page_size = options["maxItemCount"]
else:
self._page_size = _PipelineExecutionContext.DEFAULT_PAGE_SIZE
self._execution_context = execution_context
self._endpoint = endpoint_component._QueryExecutionEndpointComponent(execution_context)
order_by = query_execution_info.get_order_by()
if order_by:
self._endpoint = endpoint_component._QueryExecutionOrderByEndpointComponent(self._endpoint)
aggregates = query_execution_info.get_aggregates()
if aggregates:
self._endpoint = endpoint_component._QueryExecutionAggregateEndpointComponent(self._endpoint, aggregates)
offset = query_execution_info.get_offset()
if offset is not None:
self._endpoint = endpoint_component._QueryExecutionOffsetEndpointComponent(self._endpoint, offset)
top = query_execution_info.get_top()
if top is not None:
self._endpoint = endpoint_component._QueryExecutionTopEndpointComponent(self._endpoint, top)
limit = query_execution_info.get_limit()
if limit is not None:
self._endpoint = endpoint_component._QueryExecutionTopEndpointComponent(self._endpoint, limit)
distinct_type = query_execution_info.get_distinct_type()
if distinct_type != _DistinctType.NoneType:
if distinct_type == _DistinctType.Ordered:
self._endpoint = endpoint_component._QueryExecutionDistinctOrderedEndpointComponent(self._endpoint)
else:
self._endpoint = endpoint_component._QueryExecutionDistinctUnorderedEndpointComponent(self._endpoint)
def __next__(self):
"""Returns the next query result.
:return: The next query result.
:rtype: dict
:raises StopIteration: If no more result is left.
"""
return next(self._endpoint)
def fetch_next_block(self):
"""Returns a block of results.
This method only exists for backward compatibility reasons. (Because
QueryIterable has exposed fetch_next_block api).
This method internally invokes next() as many times required to collect
the requested fetch size.
:return: List of results.
:rtype: list
"""
results = []
for _ in xrange(self._page_size):
try:
results.append(next(self))
except StopIteration:
# no more results
break
return results
next = __next__ # Python 2 compatibility.
| {
"content_hash": "54eadf049f49520643469dff60e71e0f",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 120,
"avg_line_length": 42.80213903743316,
"alnum_prop": 0.627936031984008,
"repo_name": "Azure/azure-sdk-for-python",
"id": "c731d3535549dd2587b5b57f82160d3b03329332",
"size": "9126",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/execution_dispatcher.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1224"
},
{
"name": "Bicep",
"bytes": "24196"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "4892"
},
{
"name": "HTML",
"bytes": "12058"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "Jinja",
"bytes": "10377"
},
{
"name": "Jupyter Notebook",
"bytes": "272022"
},
{
"name": "PowerShell",
"bytes": "518535"
},
{
"name": "Python",
"bytes": "715484989"
},
{
"name": "Shell",
"bytes": "3631"
}
],
"symlink_target": ""
} |
package scouter.javassist.bytecode.analysis;
import java.util.Iterator;
import scouter.javassist.ClassPool;
import scouter.javassist.CtClass;
import scouter.javassist.CtMethod;
import scouter.javassist.NotFoundException;
import scouter.javassist.bytecode.AccessFlag;
import scouter.javassist.bytecode.BadBytecode;
import scouter.javassist.bytecode.CodeAttribute;
import scouter.javassist.bytecode.CodeIterator;
import scouter.javassist.bytecode.ConstPool;
import scouter.javassist.bytecode.Descriptor;
import scouter.javassist.bytecode.ExceptionTable;
import scouter.javassist.bytecode.MethodInfo;
import scouter.javassist.bytecode.Opcode;
import scouter.javassist.bytecode.analysis.Executor;
import scouter.javassist.bytecode.analysis.Frame;
import scouter.javassist.bytecode.analysis.FramePrinter;
import scouter.javassist.bytecode.analysis.Subroutine;
import scouter.javassist.bytecode.analysis.SubroutineScanner;
import scouter.javassist.bytecode.analysis.Type;
import scouter.javassist.bytecode.analysis.Util;
/**
* A data-flow analyzer that determines the type state of the stack and local
* variable table at every reachable instruction in a method. During analysis,
* bytecode verification is performed in a similar manner to that described
* in the JVM specification.
*
* <p>Example:</p>
*
* <pre>
* // Method to analyze
* public Object doSomething(int x) {
* Number n;
* if (x < 5) {
* n = new Double(0);
* } else {
* n = new Long(0);
* }
*
* return n;
* }
*
* // Which compiles to:
* // 0: iload_1
* // 1: iconst_5
* // 2: if_icmpge 17
* // 5: new #18; //class java/lang/Double
* // 8: dup
* // 9: dconst_0
* // 10: invokespecial #44; //Method java/lang/Double."<init>":(D)V
* // 13: astore_2
* // 14: goto 26
* // 17: new #16; //class java/lang/Long
* // 20: dup
* // 21: lconst_1
* // 22: invokespecial #47; //Method java/lang/Long."<init>":(J)V
* // 25: astore_2
* // 26: aload_2
* // 27: areturn
*
* public void analyzeIt(CtClass clazz, MethodInfo method) {
* Analyzer analyzer = new Analyzer();
* Frame[] frames = analyzer.analyze(clazz, method);
* frames[0].getLocal(0).getCtClass(); // returns clazz;
* frames[0].getLocal(1).getCtClass(); // returns java.lang.String
* frames[1].peek(); // returns Type.INTEGER
* frames[27].peek().getCtClass(); // returns java.lang.Number
* }
* </pre>
*
* @see FramePrinter
* @author Jason T. Greene
*/
public class Analyzer implements Opcode {
private final SubroutineScanner scanner = new SubroutineScanner();
private CtClass clazz;
private ExceptionInfo[] exceptions;
private Frame[] frames;
private Subroutine[] subroutines;
private static class ExceptionInfo {
private int end;
private int handler;
private int start;
private Type type;
private ExceptionInfo(int start, int end, int handler, Type type) {
this.start = start;
this.end = end;
this.handler = handler;
this.type = type;
}
}
/**
* Performs data-flow analysis on a method and returns an array, indexed by
* instruction position, containing the starting frame state of all reachable
* instructions. Non-reachable code, and illegal code offsets are represented
* as a null in the frame state array. This can be used to detect dead code.
*
* If the method does not contain code (it is either native or abstract), null
* is returned.
*
* @param clazz the declaring class of the method
* @param method the method to analyze
* @return an array, indexed by instruction position, of the starting frame state,
* or null if this method doesn't have code
* @throws BadBytecode if the bytecode does not comply with the JVM specification
*/
public Frame[] analyze(CtClass clazz, MethodInfo method) throws BadBytecode {
this.clazz = clazz;
CodeAttribute codeAttribute = method.getCodeAttribute();
// Native or Abstract
if (codeAttribute == null)
return null;
int maxLocals = codeAttribute.getMaxLocals();
int maxStack = codeAttribute.getMaxStack();
int codeLength = codeAttribute.getCodeLength();
CodeIterator iter = codeAttribute.iterator();
IntQueue queue = new IntQueue();
exceptions = buildExceptionInfo(method);
subroutines = scanner.scan(method);
Executor executor = new Executor(clazz.getClassPool(), method.getConstPool());
frames = new Frame[codeLength];
frames[iter.lookAhead()] = firstFrame(method, maxLocals, maxStack);
queue.add(iter.next());
while (!queue.isEmpty()) {
analyzeNextEntry(method, iter, queue, executor);
}
return frames;
}
/**
* Performs data-flow analysis on a method and returns an array, indexed by
* instruction position, containing the starting frame state of all reachable
* instructions. Non-reachable code, and illegal code offsets are represented
* as a null in the frame state array. This can be used to detect dead code.
*
* If the method does not contain code (it is either native or abstract), null
* is returned.
*
* @param method the method to analyze
* @return an array, indexed by instruction position, of the starting frame state,
* or null if this method doesn't have code
* @throws BadBytecode if the bytecode does not comply with the JVM specification
*/
public Frame[] analyze(CtMethod method) throws BadBytecode {
return analyze(method.getDeclaringClass(), method.getMethodInfo2());
}
private void analyzeNextEntry(MethodInfo method, CodeIterator iter,
IntQueue queue, Executor executor) throws BadBytecode {
int pos = queue.take();
iter.move(pos);
iter.next();
Frame frame = frames[pos].copy();
Subroutine subroutine = subroutines[pos];
try {
executor.execute(method, pos, iter, frame, subroutine);
} catch (RuntimeException e) {
throw new BadBytecode(e.getMessage() + "[pos = " + pos + "]", e);
}
int opcode = iter.byteAt(pos);
if (opcode == TABLESWITCH) {
mergeTableSwitch(queue, pos, iter, frame);
} else if (opcode == LOOKUPSWITCH) {
mergeLookupSwitch(queue, pos, iter, frame);
} else if (opcode == RET) {
mergeRet(queue, iter, pos, frame, subroutine);
} else if (Util.isJumpInstruction(opcode)) {
int target = Util.getJumpTarget(pos, iter);
if (Util.isJsr(opcode)) {
// Merge the state before the jsr into the next instruction
mergeJsr(queue, frames[pos], subroutines[target], pos, lookAhead(iter, pos));
} else if (! Util.isGoto(opcode)) {
merge(queue, frame, lookAhead(iter, pos));
}
merge(queue, frame, target);
} else if (opcode != ATHROW && ! Util.isReturn(opcode)) {
// Can advance to next instruction
merge(queue, frame, lookAhead(iter, pos));
}
// Merge all exceptions that are reachable from this instruction.
// The redundancy is intentional, since the state must be based
// on the current instruction frame.
mergeExceptionHandlers(queue, method, pos, frame);
}
private ExceptionInfo[] buildExceptionInfo(MethodInfo method) {
ConstPool constPool = method.getConstPool();
ClassPool classes = clazz.getClassPool();
ExceptionTable table = method.getCodeAttribute().getExceptionTable();
ExceptionInfo[] exceptions = new ExceptionInfo[table.size()];
for (int i = 0; i < table.size(); i++) {
int index = table.catchType(i);
Type type;
try {
type = index == 0 ? Type.THROWABLE : Type.get(classes.get(constPool.getClassInfo(index)));
} catch (NotFoundException e) {
throw new IllegalStateException(e.getMessage());
}
exceptions[i] = new ExceptionInfo(table.startPc(i), table.endPc(i), table.handlerPc(i), type);
}
return exceptions;
}
private Frame firstFrame(MethodInfo method, int maxLocals, int maxStack) {
int pos = 0;
Frame first = new Frame(maxLocals, maxStack);
if ((method.getAccessFlags() & AccessFlag.STATIC) == 0) {
first.setLocal(pos++, Type.get(clazz));
}
CtClass[] parameters;
try {
parameters = Descriptor.getParameterTypes(method.getDescriptor(), clazz.getClassPool());
} catch (NotFoundException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < parameters.length; i++) {
Type type = zeroExtend(Type.get(parameters[i]));
first.setLocal(pos++, type);
if (type.getSize() == 2)
first.setLocal(pos++, Type.TOP);
}
return first;
}
private int getNext(CodeIterator iter, int of, int restore) throws BadBytecode {
iter.move(of);
iter.next();
int next = iter.lookAhead();
iter.move(restore);
iter.next();
return next;
}
private int lookAhead(CodeIterator iter, int pos) throws BadBytecode {
if (! iter.hasNext())
throw new BadBytecode("Execution falls off end! [pos = " + pos + "]");
return iter.lookAhead();
}
private void merge(IntQueue queue, Frame frame, int target) {
Frame old = frames[target];
boolean changed;
if (old == null) {
frames[target] = frame.copy();
changed = true;
} else {
changed = old.merge(frame);
}
if (changed) {
queue.add(target);
}
}
private void mergeExceptionHandlers(IntQueue queue, MethodInfo method, int pos, Frame frame) {
for (int i = 0; i < exceptions.length; i++) {
ExceptionInfo exception = exceptions[i];
// Start is inclusive, while end is exclusive!
if (pos >= exception.start && pos < exception.end) {
Frame newFrame = frame.copy();
newFrame.clearStack();
newFrame.push(exception.type);
merge(queue, newFrame, exception.handler);
}
}
}
private void mergeJsr(IntQueue queue, Frame frame, Subroutine sub, int pos, int next) throws BadBytecode {
if (sub == null)
throw new BadBytecode("No subroutine at jsr target! [pos = " + pos + "]");
Frame old = frames[next];
boolean changed = false;
if (old == null) {
old = frames[next] = frame.copy();
changed = true;
} else {
for (int i = 0; i < frame.localsLength(); i++) {
// Skip everything accessed by a subroutine, mergeRet must handle this
if (!sub.isAccessed(i)) {
Type oldType = old.getLocal(i);
Type newType = frame.getLocal(i);
if (oldType == null) {
old.setLocal(i, newType);
changed = true;
continue;
}
newType = oldType.merge(newType);
// Always set the type, in case a multi-type switched to a standard type.
old.setLocal(i, newType);
if (!newType.equals(oldType) || newType.popChanged())
changed = true;
}
}
}
if (! old.isJsrMerged()) {
old.setJsrMerged(true);
changed = true;
}
if (changed && old.isRetMerged())
queue.add(next);
}
private void mergeLookupSwitch(IntQueue queue, int pos, CodeIterator iter, Frame frame) throws BadBytecode {
int index = (pos & ~3) + 4;
// default
merge(queue, frame, pos + iter.s32bitAt(index));
int npairs = iter.s32bitAt(index += 4);
int end = npairs * 8 + (index += 4);
// skip "match"
for (index += 4; index < end; index += 8) {
int target = iter.s32bitAt(index) + pos;
merge(queue, frame, target);
}
}
private void mergeRet(IntQueue queue, CodeIterator iter, int pos, Frame frame, Subroutine subroutine) throws BadBytecode {
if (subroutine == null)
throw new BadBytecode("Ret on no subroutine! [pos = " + pos + "]");
Iterator callerIter = subroutine.callers().iterator();
while (callerIter.hasNext()) {
int caller = ((Integer) callerIter.next()).intValue();
int returnLoc = getNext(iter, caller, pos);
boolean changed = false;
Frame old = frames[returnLoc];
if (old == null) {
old = frames[returnLoc] = frame.copyStack();
changed = true;
} else {
changed = old.mergeStack(frame);
}
for (Iterator i = subroutine.accessed().iterator(); i.hasNext(); ) {
int index = ((Integer)i.next()).intValue();
Type oldType = old.getLocal(index);
Type newType = frame.getLocal(index);
if (oldType != newType) {
old.setLocal(index, newType);
changed = true;
}
}
if (! old.isRetMerged()) {
old.setRetMerged(true);
changed = true;
}
if (changed && old.isJsrMerged())
queue.add(returnLoc);
}
}
private void mergeTableSwitch(IntQueue queue, int pos, CodeIterator iter, Frame frame) throws BadBytecode {
// Skip 4 byte alignment padding
int index = (pos & ~3) + 4;
// default
merge(queue, frame, pos + iter.s32bitAt(index));
int low = iter.s32bitAt(index += 4);
int high = iter.s32bitAt(index += 4);
int end = (high - low + 1) * 4 + (index += 4);
// Offset table
for (; index < end; index += 4) {
int target = iter.s32bitAt(index) + pos;
merge(queue, frame, target);
}
}
private Type zeroExtend(Type type) {
if (type == Type.SHORT || type == Type.BYTE || type == Type.CHAR || type == Type.BOOLEAN)
return Type.INTEGER;
return type;
}
}
| {
"content_hash": "0ccbcc44269d3f006de531275f407ea3",
"timestamp": "",
"source": "github",
"line_count": 417,
"max_line_length": 126,
"avg_line_length": 35.280575539568346,
"alnum_prop": 0.5865959760739532,
"repo_name": "yuyupapa/OpenSource",
"id": "9ba6984159d11707d5160c01554b4abdbd034f89",
"size": "15416",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "scouter.agent.java/src/scouter/javassist/bytecode/analysis/Analyzer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "71892"
},
{
"name": "CSS",
"bytes": "26064"
},
{
"name": "Groff",
"bytes": "8383"
},
{
"name": "HTML",
"bytes": "3089620"
},
{
"name": "Java",
"bytes": "29561111"
},
{
"name": "JavaScript",
"bytes": "128607"
},
{
"name": "NSIS",
"bytes": "41068"
},
{
"name": "Scala",
"bytes": "722545"
},
{
"name": "Shell",
"bytes": "90291"
},
{
"name": "XSLT",
"bytes": "105761"
}
],
"symlink_target": ""
} |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.autofill.prefeditor;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.widget.Toolbar.OnMenuItemClickListener;
import androidx.core.view.MarginLayoutParamsCompat;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.autofill.AutofillUiUtils;
import org.chromium.chrome.browser.autofill.settings.CreditCardNumberFormattingTextWatcher;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.util.ChromeAccessibilityUtil;
import org.chromium.components.autofill.prefeditor.EditorFieldModel;
import org.chromium.components.autofill.prefeditor.EditorFieldView;
import org.chromium.components.autofill.prefeditor.EditorObserverForTest;
import org.chromium.components.autofill.prefeditor.EditorTextField;
import org.chromium.components.browser_ui.settings.SettingsUtils;
import org.chromium.components.browser_ui.styles.SemanticColorUtils;
import org.chromium.components.browser_ui.widget.AlwaysDismissedDialog;
import org.chromium.components.browser_ui.widget.FadingEdgeScrollView;
import org.chromium.components.browser_ui.widget.FadingEdgeScrollView.EdgeType;
import org.chromium.components.browser_ui.widget.TintedDrawable;
import org.chromium.components.browser_ui.widget.animation.Interpolators;
import org.chromium.components.browser_ui.widget.displaystyle.UiConfig;
import org.chromium.components.browser_ui.widget.displaystyle.ViewResizer;
import org.chromium.ui.KeyboardVisibilityDelegate;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* The editor dialog. Can be used for editing contact information, shipping address,
* billing address, and credit cards.
*
* TODO(https://crbug.com/799905): Move payment specific functionality to separate class.
*/
public class EditorDialog
extends AlwaysDismissedDialog implements OnClickListener, DialogInterface.OnShowListener,
DialogInterface.OnDismissListener {
/** The indicator for input fields that are required. */
public static final String REQUIRED_FIELD_INDICATOR = "*";
/** Duration of the animation to show the UI to full height. */
private static final int DIALOG_ENTER_ANIMATION_MS = 300;
/** Duration of the animation to hide the UI. */
private static final int DIALOG_EXIT_ANIMATION_MS = 195;
private static EditorObserverForTest sObserverForTest;
private final Activity mActivity;
private final Handler mHandler;
private final TextView.OnEditorActionListener mEditorActionListener;
private final int mHalfRowMargin;
private final List<EditorFieldView> mFieldViews;
private final List<EditText> mEditableTextFields;
private final List<Spinner> mDropdownFields;
private final InputFilter mCardNumberInputFilter;
private final TextWatcher mCardNumberFormatter;
@Nullable
private TextWatcher mPhoneFormatter;
private View mLayout;
private EditorModel mEditorModel;
private Button mDoneButton;
private boolean mFormWasValid;
private boolean mShouldTriggerDoneCallbackBeforeCloseAnimation;
private ViewGroup mDataView;
private View mFooter;
@Nullable
private TextView mCardInput;
@Nullable
private TextView mPhoneInput;
private Animator mDialogInOutAnimator;
@Nullable
private Runnable mDeleteRunnable;
private boolean mIsDismissed;
private Profile mProfile;
@Nullable
private UiConfig mUiConfig;
/**
* Builds the editor dialog.
*
* @param activity The activity on top of which the UI should be displayed.
* @param deleteRunnable The runnable that when called will delete the profile.
* @param profile The current profile that creates EditorDialog.
*/
public EditorDialog(Activity activity, Runnable deleteRunnable, Profile profile) {
super(activity, R.style.ThemeOverlay_BrowserUI_Fullscreen);
// Sets transparent background for animating content view.
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mActivity = activity;
mHandler = new Handler();
mIsDismissed = false;
mEditorActionListener = new TextView.OnEditorActionListener() {
@Override
@SuppressWarnings("WrongConstant") // https://crbug.com/1038784
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
mDoneButton.performClick();
return true;
} else if (actionId == EditorInfo.IME_ACTION_NEXT) {
View next = v.focusSearch(View.FOCUS_FORWARD);
if (next != null) {
next.requestFocus();
return true;
}
}
return false;
}
};
mHalfRowMargin = activity.getResources().getDimensionPixelSize(
R.dimen.editor_dialog_section_large_spacing);
mFieldViews = new ArrayList<>();
mEditableTextFields = new ArrayList<>();
mDropdownFields = new ArrayList<>();
final Pattern cardNumberPattern = Pattern.compile("^[\\d- ]*$");
mCardNumberInputFilter = new InputFilter() {
@Override
public CharSequence filter(
CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// Accept deletions.
if (start == end) return null;
// Accept digits, "-", and spaces.
if (cardNumberPattern.matcher(source.subSequence(start, end)).matches()) {
return null;
}
// Reject everything else.
return "";
}
};
mCardNumberFormatter = new CreditCardNumberFormattingTextWatcher();
mDeleteRunnable = deleteRunnable;
mProfile = profile;
}
/** Prevents screenshots of this editor. */
public void disableScreenshots() {
WindowManager.LayoutParams attributes = getWindow().getAttributes();
attributes.flags |= WindowManager.LayoutParams.FLAG_SECURE;
getWindow().setAttributes(attributes);
}
/**
* @param shouldTrigger If true, done callback is triggered immediately after the user clicked
* on the done button. Otherwise, by default, it is triggered only after the dialog is
* dismissed with animation.
*/
public void setShouldTriggerDoneCallbackBeforeCloseAnimation(boolean shouldTrigger) {
mShouldTriggerDoneCallbackBeforeCloseAnimation = shouldTrigger;
}
/**
* Prepares the toolbar for use.
*
* Many of the things that would ideally be set as attributes don't work and need to be set
* programmatically. This is likely due to how we compile the support libraries.
*/
private void prepareToolbar() {
EditorDialogToolbar toolbar = (EditorDialogToolbar) mLayout.findViewById(R.id.action_bar);
toolbar.setBackgroundColor(SemanticColorUtils.getDefaultBgColor(toolbar.getContext()));
toolbar.setTitleTextAppearance(
toolbar.getContext(), R.style.TextAppearance_Headline_Primary);
toolbar.setTitle(mEditorModel.getTitle());
toolbar.setShowDeleteMenuItem(mDeleteRunnable != null);
// Show the help article when the help icon is clicked on, or delete
// the profile and go back when the delete icon is clicked on.
toolbar.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.delete_menu_id) {
mDeleteRunnable.run();
animateOutDialog();
} else if (item.getItemId() == R.id.help_menu_id) {
AutofillUiUtils.launchAutofillHelpPage(mActivity, mProfile);
}
return true;
}
});
// Cancel editing when the user hits the back arrow.
toolbar.setNavigationContentDescription(R.string.cancel);
toolbar.setNavigationIcon(getTintedBackIcon());
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
animateOutDialog();
}
});
// The top shadow is handled by the toolbar, so hide the one used in the field editor.
FadingEdgeScrollView scrollView =
(FadingEdgeScrollView) mLayout.findViewById(R.id.scroll_view);
scrollView.setEdgeVisibility(EdgeType.NONE, EdgeType.FADING);
// The shadow's top margin doesn't get picked up in the xml; set it programmatically.
View shadow = mLayout.findViewById(R.id.shadow);
LayoutParams params = (LayoutParams) shadow.getLayoutParams();
params.topMargin = toolbar.getLayoutParams().height;
shadow.setLayoutParams(params);
scrollView.getViewTreeObserver().addOnScrollChangedListener(
SettingsUtils.getShowShadowOnScrollListener(scrollView, shadow));
}
/**
* Checks if all of the fields in the form are valid and updates the displayed errors. If there
* are any invalid fields, makes sure that one of them is focused. Called when user taps [SAVE].
*
* @return Whether all fields contain valid information.
*/
public boolean validateForm() {
final List<EditorFieldView> invalidViews = getViewsWithInvalidInformation(true);
// Iterate over all the fields to update what errors are displayed, which is necessary to
// to clear existing errors on any newly valid fields.
for (int i = 0; i < mFieldViews.size(); i++) {
EditorFieldView fieldView = mFieldViews.get(i);
fieldView.updateDisplayedError(invalidViews.contains(fieldView));
}
if (!invalidViews.isEmpty()) {
// Make sure that focus is on an invalid field.
EditorFieldView focusedField = getEditorTextField(getCurrentFocus());
if (invalidViews.contains(focusedField)) {
// The focused field is invalid, but it may be scrolled off screen. Scroll to it.
focusedField.scrollToAndFocus();
} else {
// Some fields are invalid, but none of the are focused. Scroll to the first invalid
// field and focus it.
invalidViews.get(0).scrollToAndFocus();
}
}
if (!invalidViews.isEmpty() && sObserverForTest != null) {
sObserverForTest.onEditorValidationError();
}
return invalidViews.isEmpty();
}
/** @return The validatable item for the given view. */
private EditorFieldView getEditorTextField(View v) {
if (v instanceof TextView && v.getParent() != null
&& v.getParent() instanceof EditorFieldView) {
return (EditorFieldView) v.getParent();
} else if (v instanceof Spinner && v.getTag() != null) {
return (EditorFieldView) v.getTag();
} else {
return null;
}
}
@Override
public void onClick(View view) {
// Disable interaction during animation.
if (mDialogInOutAnimator != null) return;
if (view.getId() == R.id.editor_dialog_done_button) {
if (validateForm()) {
if (mShouldTriggerDoneCallbackBeforeCloseAnimation && mEditorModel != null) {
mEditorModel.done();
mEditorModel = null;
}
mFormWasValid = true;
animateOutDialog();
return;
}
} else if (view.getId() == R.id.payments_edit_cancel_button) {
animateOutDialog();
}
}
private void animateOutDialog() {
if (mDialogInOutAnimator != null || !isShowing()) return;
if (getCurrentFocus() != null) {
KeyboardVisibilityDelegate.getInstance().hideKeyboard(getCurrentFocus());
}
Animator dropDown =
ObjectAnimator.ofFloat(mLayout, View.TRANSLATION_Y, 0f, mLayout.getHeight());
Animator fadeOut = ObjectAnimator.ofFloat(mLayout, View.ALPHA, mLayout.getAlpha(), 0f);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(dropDown, fadeOut);
mDialogInOutAnimator = animatorSet;
mDialogInOutAnimator.setDuration(DIALOG_EXIT_ANIMATION_MS);
mDialogInOutAnimator.setInterpolator(Interpolators.FAST_OUT_LINEAR_IN_INTERPOLATOR);
mDialogInOutAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mDialogInOutAnimator = null;
dismiss();
}
});
mDialogInOutAnimator.start();
}
public void setAsNotDismissed() {
mIsDismissed = false;
}
public boolean isDismissed() {
return mIsDismissed;
}
@Override
public void onDismiss(DialogInterface dialog) {
mIsDismissed = true;
if (mEditorModel != null) {
if (mFormWasValid) {
mEditorModel.done();
mFormWasValid = false;
} else {
mEditorModel.cancel();
}
mEditorModel = null;
}
removeTextChangedListenersAndInputFilters();
}
private void prepareButtons() {
mDoneButton = (Button) mLayout.findViewById(R.id.button_primary);
mDoneButton.setId(R.id.editor_dialog_done_button);
mDoneButton.setOnClickListener(this);
if (mEditorModel.getCustomDoneButtonText() != null) {
mDoneButton.setText(mEditorModel.getCustomDoneButtonText());
}
Button cancelButton = (Button) mLayout.findViewById(R.id.button_secondary);
cancelButton.setId(R.id.payments_edit_cancel_button);
cancelButton.setOnClickListener(this);
}
private void prepareFooter() {
TextView requiredFieldsNotice = mLayout.findViewById(R.id.required_fields_notice);
int requiredFieldsNoticeVisibility = View.GONE;
for (int i = 0; i < mFieldViews.size(); i++) {
if (mFieldViews.get(i).isRequired()) {
requiredFieldsNoticeVisibility = View.VISIBLE;
break;
}
}
requiredFieldsNotice.setVisibility(requiredFieldsNoticeVisibility);
}
/**
* Create the visual representation of the EditorModel.
*
* This would be more optimal as a RelativeLayout, but because it's dynamically generated, it's
* much more human-parsable with inefficient LinearLayouts for half-width controls sharing rows.
*/
private void prepareEditor() {
assert mEditorModel != null;
// Ensure the layout is empty.
removeTextChangedListenersAndInputFilters();
mDataView = (ViewGroup) mLayout.findViewById(R.id.contents);
mDataView.removeAllViews();
mFieldViews.clear();
mEditableTextFields.clear();
mDropdownFields.clear();
// Add Views for each of the {@link EditorFields}.
for (int i = 0; i < mEditorModel.getFields().size(); i++) {
EditorFieldModel fieldModel = mEditorModel.getFields().get(i);
EditorFieldModel nextFieldModel = null;
boolean isLastField = i == mEditorModel.getFields().size() - 1;
boolean useFullLine = fieldModel.isFullLine();
if (!isLastField && !useFullLine) {
// If the next field isn't full, stretch it out.
nextFieldModel = mEditorModel.getFields().get(i + 1);
if (nextFieldModel.isFullLine()) useFullLine = true;
}
// Always keep dropdowns and text fields on different lines because of height
// differences.
if (!isLastField && !useFullLine
&& fieldModel.isDropdownField() != nextFieldModel.isDropdownField()) {
useFullLine = true;
}
if (useFullLine || isLastField) {
addFieldViewToEditor(mDataView, fieldModel);
} else {
// Create a LinearLayout to put it and the next view side by side.
LinearLayout rowLayout = new LinearLayout(mActivity);
mDataView.addView(rowLayout);
View firstView = addFieldViewToEditor(rowLayout, fieldModel);
View lastView = addFieldViewToEditor(rowLayout, nextFieldModel);
LinearLayout.LayoutParams firstParams =
(LinearLayout.LayoutParams) firstView.getLayoutParams();
LinearLayout.LayoutParams lastParams =
(LinearLayout.LayoutParams) lastView.getLayoutParams();
firstParams.width = 0;
firstParams.weight = 1;
MarginLayoutParamsCompat.setMarginEnd(firstParams, mHalfRowMargin);
lastParams.width = 0;
lastParams.weight = 1;
i = i + 1;
}
}
// Add the footer.
mDataView.addView(mFooter);
}
/**
* When this layout has a wide display style, it will be width constrained to
* {@link UiConfig#WIDE_DISPLAY_STYLE_MIN_WIDTH_DP}. If the current screen width is greater than
* UiConfig#WIDE_DISPLAY_STYLE_MIN_WIDTH_DP, the settings layout will be visually centered
* by adding padding to both sides.
*/
public void onConfigurationChanged() {
if (mUiConfig == null) {
if (mDataView != null) {
int minWidePaddingPixels = mActivity.getResources().getDimensionPixelSize(
R.dimen.settings_wide_display_min_padding);
mUiConfig = new UiConfig(mDataView);
ViewResizer.createAndAttach(mDataView, mUiConfig, 0, minWidePaddingPixels);
}
} else {
mUiConfig.updateDisplayStyle();
}
}
private void removeTextChangedListenersAndInputFilters() {
if (mCardInput != null) {
mCardInput.removeTextChangedListener(mCardNumberFormatter);
mCardInput.setFilters(new InputFilter[0]); // Null is not allowed.
mCardInput = null;
}
if (mPhoneInput != null) {
mPhoneInput.removeTextChangedListener(mPhoneFormatter);
mPhoneInput = null;
}
}
private View addFieldViewToEditor(ViewGroup parent, final EditorFieldModel fieldModel) {
View childView = null;
if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_ICONS) {
childView = new EditorIconsField(mActivity, parent, fieldModel).getLayout();
} else if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_LABEL) {
childView = new EditorLabelField(mActivity, parent, fieldModel).getLayout();
} else if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_DROPDOWN) {
Runnable prepareEditorRunnable = new Runnable() {
@Override
public void run() {
// The dialog has been dismissed.
if (mEditorModel == null) return;
// The fields may have changed.
prepareEditor();
prepareFooter();
if (sObserverForTest != null) sObserverForTest.onEditorReadyToEdit();
}
};
EditorDropdownField dropdownView =
new EditorDropdownField(mActivity, parent, fieldModel, prepareEditorRunnable);
mFieldViews.add(dropdownView);
mDropdownFields.add(dropdownView.getDropdown());
childView = dropdownView.getLayout();
} else if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_CHECKBOX) {
final CheckBox checkbox = new CheckBox(mLayout.getContext());
checkbox.setId(R.id.payments_edit_checkbox);
checkbox.setText(fieldModel.getLabel());
checkbox.setChecked(fieldModel.isChecked());
checkbox.setMinimumHeight(mActivity.getResources().getDimensionPixelSize(
R.dimen.editor_dialog_checkbox_min_height));
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
fieldModel.setIsChecked(isChecked);
if (sObserverForTest != null) sObserverForTest.onEditorReadyToEdit();
}
});
childView = checkbox;
} else {
InputFilter filter = null;
TextWatcher formatter = null;
if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_CREDIT_CARD) {
filter = mCardNumberInputFilter;
formatter = mCardNumberFormatter;
} else if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_PHONE) {
mPhoneFormatter = fieldModel.getFormatter();
assert mPhoneFormatter != null;
formatter = mPhoneFormatter;
}
EditorTextField inputLayout = new EditorTextField(mActivity, fieldModel,
mEditorActionListener, filter, formatter, /* focusAndShowKeyboard= */ false);
mFieldViews.add(inputLayout);
EditText input = inputLayout.getEditText();
mEditableTextFields.add(input);
if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_CREDIT_CARD) {
assert mCardInput == null;
mCardInput = input;
} else if (fieldModel.getInputTypeHint() == EditorFieldModel.INPUT_TYPE_HINT_PHONE) {
assert mPhoneInput == null;
mPhoneInput = input;
}
childView = inputLayout;
}
parent.addView(childView);
return childView;
}
/**
* Displays the editor user interface for the given model.
*
* @param editorModel The description of the editor user interface to display.
*/
public void show(EditorModel editorModel) {
// If an asynchronous task calls show, while the activity is already finishing, return.
if (mActivity.isFinishing()) return;
setOnShowListener(this);
setOnDismissListener(this);
mEditorModel = editorModel;
mLayout = LayoutInflater.from(mActivity).inflate(R.layout.payment_request_editor, null);
setContentView(mLayout);
mFooter = LayoutInflater.from(mActivity).inflate(
R.layout.editable_option_editor_footer, null, false);
prepareToolbar();
prepareEditor();
prepareFooter();
prepareButtons();
onConfigurationChanged();
// Temporarily hide the content to avoid blink before animation starts.
mLayout.setVisibility(View.INVISIBLE);
show();
}
/** Rereads the values in the model to update the UI. */
public void update() {
for (int i = 0; i < mFieldViews.size(); i++) {
mFieldViews.get(i).update();
}
}
@Override
public void onShow(DialogInterface dialog) {
if (mDialogInOutAnimator != null && mIsDismissed) return;
// Hide keyboard and disable EditText views for animation efficiency.
if (getCurrentFocus() != null) {
KeyboardVisibilityDelegate.getInstance().hideKeyboard(getCurrentFocus());
}
for (int i = 0; i < mEditableTextFields.size(); i++) {
mEditableTextFields.get(i).setEnabled(false);
}
mLayout.setVisibility(View.VISIBLE);
mLayout.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mLayout.buildLayer();
Animator popUp =
ObjectAnimator.ofFloat(mLayout, View.TRANSLATION_Y, mLayout.getHeight(), 0f);
Animator fadeIn = ObjectAnimator.ofFloat(mLayout, View.ALPHA, 0f, 1f);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(popUp, fadeIn);
mDialogInOutAnimator = animatorSet;
mDialogInOutAnimator.setDuration(DIALOG_ENTER_ANIMATION_MS);
mDialogInOutAnimator.setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN_INTERPOLATOR);
mDialogInOutAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLayout.setLayerType(View.LAYER_TYPE_NONE, null);
for (int i = 0; i < mEditableTextFields.size(); i++) {
mEditableTextFields.get(i).setEnabled(true);
}
mDialogInOutAnimator = null;
initFocus();
}
});
mDialogInOutAnimator.start();
}
private void initFocus() {
mHandler.post(() -> {
// If TalkBack is enabled, we want to keep the focus at the top
// because the user would not learn about the elements that are
// above the focused field.
if (!ChromeAccessibilityUtil.get().isAccessibilityEnabled()) {
List<EditorFieldView> invalidViews = getViewsWithInvalidInformation(false);
if (!invalidViews.isEmpty()) {
// Immediately focus the first invalid field to make it faster to edit.
invalidViews.get(0).scrollToAndFocus();
} else {
// Trigger default focus as it is not triggered automatically on Android P+.
mLayout.requestFocus();
}
}
// Note that keyboard will not be shown for dropdown field since it's not necessary.
if (getCurrentFocus() != null) {
KeyboardVisibilityDelegate.getInstance().showKeyboard(getCurrentFocus());
// Put the cursor to the end of the text.
if (getCurrentFocus() instanceof EditText) {
EditText focusedEditText = (EditText) getCurrentFocus();
focusedEditText.setSelection(focusedEditText.getText().length());
}
}
if (sObserverForTest != null) sObserverForTest.onEditorReadyToEdit();
});
}
private List<EditorFieldView> getViewsWithInvalidInformation(boolean findAll) {
List<EditorFieldView> invalidViews = new ArrayList<>();
for (int i = 0; i < mFieldViews.size(); i++) {
EditorFieldView fieldView = mFieldViews.get(i);
if (!fieldView.isValid()) {
invalidViews.add(fieldView);
if (!findAll) break;
}
}
return invalidViews;
}
/** @return All editable text fields in the editor. Used only for tests. */
@VisibleForTesting
public List<EditText> getEditableTextFieldsForTest() {
return mEditableTextFields;
}
/** @return All dropdown fields in the editor. Used only for tests. */
@VisibleForTesting
public List<Spinner> getDropdownFieldsForTest() {
return mDropdownFields;
}
@VisibleForTesting
public static void setEditorObserverForTest(EditorObserverForTest observerForTest) {
sObserverForTest = observerForTest;
EditorDropdownField.setEditorObserverForTest(sObserverForTest);
EditorTextField.setEditorObserverForTest(sObserverForTest);
}
private Drawable getTintedBackIcon() {
return TintedDrawable.constructTintedDrawable(getContext(),
R.drawable.ic_arrow_back_white_24dp, R.color.default_icon_color_tint_list);
}
}
| {
"content_hash": "6e9702f92c2ac92bd269595f2a9297f6",
"timestamp": "",
"source": "github",
"line_count": 703,
"max_line_length": 100,
"avg_line_length": 41.62304409672831,
"alnum_prop": 0.6415706913639315,
"repo_name": "nwjs/chromium.src",
"id": "607bb0269a005ddc2397edad1e9d9db4b9324cd6",
"size": "29261",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw70",
"path": "chrome/android/java/src/org/chromium/chrome/browser/autofill/prefeditor/EditorDialog.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
namespace app\models;
use Yii;
use yii\helpers\Url;
use yii\helpers\FileHelper;
use yii\helpers\ArrayHelper;
use yii\imagine\Image;
use app\models\MArticle;
use app\models\MArticleMultArticle;
use app\models\U;
/*
DROP TABLE IF EXISTS wx_article_mult;
CREATE TABLE IF NOT EXISTS wx_article_mult (
gh_id VARCHAR(32) NOT NULL DEFAULT '',
article_mult_id int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(128) NOT NULL DEFAULT '' COMMENT '标题',
create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
*/
class MArticleMult extends \yii\db\ActiveRecord
{
private $_oldArticleIds = [];
public $articleIds;
public $articleIdsStr;
public static function tableName()
{
return 'wx_article_mult';
}
public function rules()
{
return [
[['create_time', 'article_mult_id'], 'safe'],
[['title'], 'string', 'max' => 128],
[['articleIdsStr'], 'string', 'max' => 128],
];
}
public function attributeLabels()
{
return [
'article_mult_id' => Yii::t('app', 'ID'),
'create_time' => Yii::t('app', 'Create Time'),
'title' => Yii::t('app', 'title'),
];
}
public function getArticleMultArticles()
{
// return $this->hasMany(MArticleMultArticle::className(), ['article_mult_id' => 'article_mult_id']);
return $this->hasMany(MArticleMultArticle::className(), ['article_mult_id' => 'article_mult_id'])->orderBy(['sort_order'=>SORT_DESC, 'article_mult_article_id'=>SORT_DESC]);
}
public function afterFind()
{
$this->_oldArticleIds = ArrayHelper::getColumn($this->articleMultArticles, 'article_id');
$this->articleIdsStr = implode(',', $this->_oldArticleIds);
return parent::afterFind();
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($insert) {
$this->gh_id = Yii::$app->user->gh->gh_id;
}
return true;
}
return false;
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
$this->articleIds = explode(',', $this->articleIdsStr);
$deleteArticleIds = array_diff($this->_oldArticleIds, $this->articleIds);
$addArticleIds = array_diff($this->articleIds, $this->_oldArticleIds);
foreach($this->articleMultArticles as $articleMultArticle) {
if (in_array($articleMultArticle->article_id, $deleteArticleIds)) {
$articleMultArticle->delete();
}
}
foreach($addArticleIds as $articleId) {
$model = new MArticleMultArticle();
$model->article_mult_id = $this->article_mult_id;
$model->article_id = $articleId;
$model->save(false);
}
}
public function afterDelete()
{
foreach($this->articleMultArticles as $articleMultArticle) {
$articleMultArticle->delete();
}
parent::afterDelete();
}
public function getResp($wechat)
{
$FromUserName = $wechat->getRequest('FromUserName');
$openid = $wechat->getRequest('FromUserName');
$gh_id = $wechat->getRequest('ToUserName');
$MsgType = $wechat->getRequest('MsgType');
$Event = $wechat->getRequest('Event');
$EventKey = $wechat->getRequest('EventKey');
$user = $wechat->getUser();
$dict = [
'{nickname}' => empty($user->nickname) ? '' : $user->nickname,
'{openid}' => $openid,
'{gh_id}' => $gh_id,
];
$items = [];
foreach($this->articleMultArticles as $articleMultArticle) {
if (empty($articleMultArticle->article)) {
continue;
}
$article = $articleMultArticle->article;
$title = strtr($article->title, $dict);
$description = strtr($article->content, $dict);
$picUrl = empty($article->photo) ? '' : $this->$article->getPicUrl();
$url = strtr($article->content_source_url, $dict);
$items[] = new RespNewsItem($title, $description, $picUrl, $url);
}
return $wechat->responseNews($items);
}
public function getMediaId()
{
$wechat = Yii::$app->user->getWechat();
foreach($this->articleMultArticles as $articleMultArticle) {
if (empty($articleMultArticle->article)) {
continue;
}
$article = $articleMultArticle->article;
$articles[] = ['thumb_media_id' =>$article->photo->getMediaId(), 'author' =>$article->author, 'title' =>$article->title,'content_source_url' =>$article->content_source_url,'content' =>$article->content,'digest' =>$article->digest, 'show_cover_pic'=>$article->show_cover_pic];
}
$arr = $wechat->WxMediaUploadNews($articles);
return $arr['media_id'];
}
public function messageCustomSend($openids)
{
$wechat = Yii::$app->user->getWechat();
foreach($this->articleMultArticles as $articleMultArticle) {
if (empty($articleMultArticle->article)) {
continue;
}
$article = $articleMultArticle->article;
$articles[] = ['title' =>$article->title, 'description' =>$article->content, 'url' =>$article->content_source_url, 'picurl' =>$article->photo->getPicUrl()];
}
foreach($openids as $openid) {
$arr = $wechat->WxMessageCustomSendNews($openid, $articles);
}
}
public function messageMassSend($openids)
{
$wechat = Yii::$app->user->getWechat();
$media_id = $this->getMediaId();
$wechat->WxMessageMassSendNews($openids, $media_id);
}
public function messageMassPreview($openid)
{
$wechat = Yii::$app->user->getWechat();
$media_id = $this->getMediaId();
$wechat->WxMessageMassPreviewNews($openid, $media_id);
}
public function messageMassSendByGroupid($group_id)
{
$wechat = Yii::$app->user->getWechat();
$media_id = $this->getMediaId();
$wechat->WxMessageMassSendNewsByGroupid($group_id, $media_id);
}
}
| {
"content_hash": "51bf0f3ebb0190dc76151394da3dbd02",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 287,
"avg_line_length": 33.613756613756614,
"alnum_prop": 0.5786242719974815,
"repo_name": "yjhu/wowewe",
"id": "8fb70825c2f1c985135eb7a3824014fd48c6493d",
"size": "6357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/MArticleMult.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "518"
},
{
"name": "CSS",
"bytes": "1030227"
},
{
"name": "HTML",
"bytes": "7293935"
},
{
"name": "JavaScript",
"bytes": "1745719"
},
{
"name": "PHP",
"bytes": "5630846"
}
],
"symlink_target": ""
} |
class Sprite : public GameComponent
{
public:
Sprite(std::string filename, std::string name = "", GLfloat x = 0, GLfloat y = 0);
virtual ~Sprite(void);
Sprite(const Sprite &);
virtual GLfloat getPositionX(void);
virtual GLfloat getPositionY(void);
virtual GLfloat getRotation(void);
virtual void setPositionX(GLfloat x);
virtual void setPositionY(GLfloat y);
virtual void setRotation(GLfloat rotation);
virtual void LoadContent();
virtual void Draw();
// Color tint
GLfloat drawColor[4];
protected:
std::string filename;
// Texture fields
GLuint texture;
GLfloat width;
GLfloat height;
SDL_Rect bounds;
// Sprite Fields
GLfloat positionX;
GLfloat positionY;
GLfloat rotation;
GLfloat scaleX;
GLfloat scaleY;
// Loads an image using SDL
SDL_Surface* LoadImage(std::string filepath);
// Converts SDL image to OpenGL texture
GLuint CreateTexture(SDL_Surface* sdlSprite);
// Draw the currently bound texture
void DrawTexture();
};
| {
"content_hash": "49eb3633c79dadb2567e489571841306",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 83,
"avg_line_length": 21.108695652173914,
"alnum_prop": 0.7394438722966015,
"repo_name": "EvanCGriffin/soccergame",
"id": "27a7d21f76c001b0ca7bac972a65d1f97ae43ccf",
"size": "1166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Year3Engine/Sprite.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6402008"
},
{
"name": "C++",
"bytes": "1180480"
},
{
"name": "Objective-C",
"bytes": "23070"
}
],
"symlink_target": ""
} |
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "2.0.1 -sizzle,-css,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions,-deprecated",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*
* Optional (non-Sizzle) selector module for custom builds.
*
* Note that this DOES NOT SUPPORT many documented jQuery
* features in exchange for its smaller size:
*
* Attribute not equal selector
* Positional selectors (:first; :eq(n); :odd; etc.)
* Type selectors (:input; :checkbox; :button; etc.)
* State-based selectors (:animated; :visible; :hidden; etc.)
* :has(selector)
* :not(complex selector)
* custom selectors via Sizzle extensions
* Leading combinators (e.g., $collection.find("> *"))
* Reliable functionality on XML fragments
* Requiring all parts of a selector to match elements under context
* (e.g., $div.find("div > *") now matches children of $div)
* Matching against non-elements
* Reliable sorting of disconnected nodes
* querySelectorAll bug fixes (e.g., unreliable :focus on WebKit)
*
* If any of these are unacceptable tradeoffs, either use Sizzle or
* customize this stub for the project's specific needs.
*/
var selector_hasDuplicate,
matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector,
selector_sortOrder = function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
selector_hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ) {
// Choose the first element that is related to our document
if ( a === document || jQuery.contains(document, a) ) {
return -1;
}
if ( b === document || jQuery.contains(document, b) ) {
return 1;
}
// Maintain original order
return 0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
};
jQuery.extend({
find: function( selector, context, results, seed ) {
var elem, nodeType,
i = 0;
results = results || [];
context = context || document;
// Same basic safeguard as Sizzle
if ( !selector || typeof selector !== "string" ) {
return results;
}
// Early return if context is not an element or document
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( seed ) {
while ( (elem = seed[i++]) ) {
if ( jQuery.find.matchesSelector(elem, selector) ) {
results.push( elem );
}
}
} else {
jQuery.merge( results, context.querySelectorAll(selector) );
}
return results;
},
unique: function( results ) {
var elem,
duplicates = [],
i = 0,
j = 0;
selector_hasDuplicate = false;
results.sort( selector_sortOrder );
if ( selector_hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
},
text: function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += jQuery.text( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
return elem.textContent;
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
},
contains: function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) );
},
isXMLDoc: function( elem ) {
return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML";
},
expr: {
attrHandle: {},
match: {
bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i,
needsContext: /^[\x20\t\r\n\f]*[>+~]/
}
}
});
jQuery.extend( jQuery.find, {
matches: function( expr, elements ) {
return jQuery.find( expr, null, null, elements );
},
matchesSelector: function( elem, expr ) {
return matches.call( elem, expr );
},
attr: function( elem, name ) {
return elem.getAttribute( name );
}
});
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var input = document.createElement("input"),
fragment = document.createDocumentFragment(),
div = document.createElement("div"),
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") );
// Finish early in limited environments
if ( !input.type ) {
return support;
}
input.type = "checkbox";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Will be defined later
support.reliableMarginRight = true;
support.boxSizingReliable = true;
support.pixelPosition = false;
// Make sure checked status is properly cloned
// Support: IE9, IE10
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement("input");
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment.appendChild( input );
// Support: Safari 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: Firefox, Chrome, Safari
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
support.focusinBubbles = "onfocusin" in window;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv,
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",
body = document.getElementsByTagName("body")[ 0 ];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
// Check box-sizing and margin behavior.
body.appendChild( container ).appendChild( div );
div.innerHTML = "";
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
body.removeChild( container );
});
return support;
})( {} );
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var data_user, data_priv,
rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType ?
owner.nodeType === 1 || owner.nodeType === 9 : true;
};
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
return this.get( owner, key );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( core_rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
// These may be used throughout the jQuery core codebase
data_user = new Data();
data_priv = new Data();
jQuery.extend({
acceptData: Data.accepts,
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[ 0 ],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return jQuery.access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? JSON.parse( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
// Temporarily disable this handler to check existence
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
// Restore handler
jQuery.expr.attrHandle[ name ] = fn;
return ret;
};
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return core_indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return core_indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because core_push.apply(_, arraylike) throws
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
i = 0,
l = elems.length,
fragment = context.createDocumentFragment(),
nodes = [];
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.firstChild;
}
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, events, type, key, j,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( Data.accepts( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
events = Object.keys( data.events || {} );
if ( events.length ) {
for ( j = 0; (type = events[j]) !== undefined; j++ ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var l = elems.length,
i = 0;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
// If there is a window object, that at least has a document property,
// define jQuery and $ identifiers
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
}
})( window );
| {
"content_hash": "14376b9180a78f825323bae4da763750",
"timestamp": "",
"source": "github",
"line_count": 4348,
"max_line_length": 189,
"avg_line_length": 26.843146274149035,
"alnum_prop": 0.609412752540398,
"repo_name": "michael829/jquery-builder",
"id": "5723d5b4191df989eb7e5127f2694509cc15ac82",
"size": "117103",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "dist/2.0.1/jquery-ajax-css-deprecated-effects-event-alias-sizzle.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "12296"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.AlterField(
model_name='account',
name='username',
field=models.CharField(blank=True, help_text='Bitstamp login number', max_length=255),
),
migrations.AlterField(
model_name='order',
name='status',
field=models.CharField(choices=[('open', 'open'), ('cancelled', 'cancelled'), ('processed', 'processed')], db_index=True, default=None, max_length=255),
),
migrations.AlterField(
model_name='order',
name='type',
field=models.IntegerField(choices=[(0, 'buy'), (1, 'sell')], db_index=True),
),
migrations.AlterField(
model_name='transaction',
name='type',
field=models.PositiveSmallIntegerField(choices=[(0, 'deposit'), (1, 'withdrawal'), (2, 'trade')], db_index=True),
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(blank=True, max_length=254, verbose_name='email address'),
),
migrations.AlterField(
model_name='user',
name='groups',
field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'),
),
migrations.AlterField(
model_name='user',
name='last_login',
field=models.DateTimeField(blank=True, null=True, verbose_name='last login'),
),
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username'),
),
]
| {
"content_hash": "cbc33e412d9ddd9e181d4590efe49277",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 317,
"avg_line_length": 41.32786885245902,
"alnum_prop": 0.5894486314954384,
"repo_name": "jkbrzt/cointrol",
"id": "6025ee90b9180325f5ec7e57f17b48206e68870f",
"size": "2594",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cointrol/core/migrations/0002_auto_20171102_0054.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "649"
},
{
"name": "CoffeeScript",
"bytes": "15346"
},
{
"name": "HTML",
"bytes": "798"
},
{
"name": "Handlebars",
"bytes": "5892"
},
{
"name": "Python",
"bytes": "74502"
}
],
"symlink_target": ""
} |
package com.amatkivskiy.result.sample;
import com.amatkivskiy.result.Result;
public class Main {
public static void mainSimple(String[] args) {
System.out.println("Simplest way to create Result.");
Result.success("success");
Result.failure("failure");
Result.of("success");
Result.of(() -> "success");
Result.orDefault(() -> Integer.parseInt("invalid"), -1);
Result.orFailWith(() -> Integer.parseInt("invalid"), new IllegalArgumentException());
System.out.println("Transforming `Result`");
Result.of("success")
.map(String::length);
Result.of("success")
.flatMap(value -> {
if (value.isSuccess()) {
return Result.of(value.value()
.length());
} else {
return Result.failure(new IllegalArgumentException());
}
});
System.out.println("Consuming `Result`");
Result.success("success")
.value();
Result.failure("failure")
.error();
Result.of("success")
.onSuccess(System.out::println)
.onFailure(System.err::println);
String success = Result.<String, String>failure("failure").or("success");
}
public static void main(String[] args) {
System.out.println("Real life login example");
final String login = "username";
final String password = "password";
validateInputs(login, password).map(value -> new Credentials(login, password))
.flatMap(it -> {
if (it.isSuccess()) {
return performLogin(it.value());
} else {
return Result.failure(new Exception(it.error()));
}
})
.onSuccess(System.out::println)
.onFailure(System.err::println);
}
private static Result<String, Exception> performLogin(Credentials creds) {
if ("username".equalsIgnoreCase(creds.username) && "password".equalsIgnoreCase(creds.password)) {
return Result.success("hurrah");
} else {
return Result.failure(new Exception("Wrong login or password."));
}
}
private static Result<Object, String> validateInputs(String login, String password) {
if (login != null && password != null && !login.isEmpty() && !password.isEmpty()) {
return Result.success(null);
} else {
return Result.failure("Login or password is not valid.");
}
}
static class Credentials {
public final String username;
public final String password;
public Credentials(String username, String password) {
this.username = username;
this.password = password;
}
}
}
| {
"content_hash": "00fc753d04f0d4d8f2eab571cc0129b1",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 101,
"avg_line_length": 31.265060240963855,
"alnum_prop": 0.6169556840077072,
"repo_name": "amatkivskiy/ResultForJava",
"id": "424e19c75195ccda9acaf268929f3e9244ee129d",
"size": "2595",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "sample/src/main/java/com/amatkivskiy/result/sample/Main.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "20004"
}
],
"symlink_target": ""
} |
'use strict';
module.exports = {
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/demonodeserver',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
| {
"content_hash": "58b22fa4725a82df83f21664c327cd77",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 149,
"avg_line_length": 34.77049180327869,
"alnum_prop": 0.6619519094766619,
"repo_name": "castlewhitehall/meanjs-with-token-auth",
"id": "eaf48cdc4df93c931a007a4a6a07b1ed5db55a2e",
"size": "2121",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "config/env/production.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "500"
},
{
"name": "HTML",
"bytes": "25169"
},
{
"name": "JavaScript",
"bytes": "96611"
},
{
"name": "Shell",
"bytes": "414"
}
],
"symlink_target": ""
} |
@interface ImageToVidTests : XCTestCase
@end
@implementation ImageToVidTests
- (void)setUp
{
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample
{
XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
}
@end
| {
"content_hash": "93c343f80940b34714ed84a5b5bf6ce3",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 107,
"avg_line_length": 19.708333333333332,
"alnum_prop": 0.6955602536997886,
"repo_name": "HarrisonJackson/HJImagesToVideo",
"id": "392edb51548581d9ac4a0d46111919d892b2a192",
"size": "637",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ImageToVid/ImageToVidTests/ImageToVidTests.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9073"
},
{
"name": "Objective-C",
"bytes": "24812"
},
{
"name": "Perl",
"bytes": "69"
},
{
"name": "Shell",
"bytes": "388"
}
],
"symlink_target": ""
} |
// Copyright 2014 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.buildjar.javac.plugins.dependency;
import com.google.devtools.build.lib.view.proto.Deps;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.util.Context;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import javax.lang.model.util.SimpleTypeVisitor7;
import javax.tools.JavaFileObject;
/**
* A lightweight mechanism for extracting compile-time dependencies from javac, by performing a scan
* of the symbol table after compilation finishes. It only includes dependencies from jar files,
* which can be interface jars or regular third_party jars, matching the compilation model of Blaze.
* Note that JDK8 may provide support for extracting per-class, finer-grained dependencies, and if
* that implementation has reasonable overhead it may be a future option.
*/
public class ImplicitDependencyExtractor {
/** Set collecting dependencies names, used for the text output (soon to be removed) */
private final Set<Path> depsSet;
/** Map collecting dependency information, used for the proto output */
private final Map<Path, Deps.Dependency> depsMap;
private final TypeVisitor typeVisitor = new TypeVisitor();
private final Set<Path> platformJars;
/**
* ImplicitDependencyExtractor does not guarantee any ordering of the reported dependencies.
* Clients should preserve the original classpath ordering if trying to minimize their classpaths
* using this information.
*/
public ImplicitDependencyExtractor(
Set<Path> depsSet, Map<Path, Deps.Dependency> depsMap, Set<Path> platformJars) {
this.depsSet = depsSet;
this.depsMap = depsMap;
this.platformJars = platformJars;
}
/**
* Collects the implicit dependencies of the given set of ClassSymbol roots. As we're interested
* in differentiating between symbols that were just resolved vs. symbols that were fully
* completed by the compiler, we start the analysis by finding all the implicit dependencies
* reachable from the given set of roots. For completeness, we then walk the symbol table
* associated with the given context and collect the jar files of the remaining class symbols
* found there.
*
* @param context compilation context
* @param roots root classes in the implicit dependency collection
*/
public void accumulate(Context context, Set<ClassSymbol> roots) {
Symtab symtab = Symtab.instance(context);
// Collect transitive references for root types
for (ClassSymbol root : roots) {
root.type.accept(typeVisitor, null);
}
// Collect all other partially resolved types
for (ClassSymbol cs : symtab.getAllClasses()) {
// When recording we want to differentiate between jar references through completed symbols
// and incomplete symbols
boolean completed = cs.isCompleted();
if (cs.classfile != null) {
collectJarOf(cs.classfile, platformJars, completed);
} else if (cs.sourcefile != null) {
collectJarOf(cs.sourcefile, platformJars, completed);
}
}
}
/**
* Attempts to add the jar associated with the given JavaFileObject, if any, to the collection,
* filtering out jars on the compilation bootclasspath.
*
* @param reference JavaFileObject representing a class or source file
* @param platformJars classes on javac's bootclasspath
* @param completed whether the jar was referenced through a completed symbol
*/
private void collectJarOf(JavaFileObject reference, Set<Path> platformJars, boolean completed) {
Path path = getJarPath(reference);
if (path == null) {
return;
}
// Filter out classes in rt.jar
if (platformJars.contains(path)) {
return;
}
depsSet.add(path);
Deps.Dependency currentDep = depsMap.get(path);
// If the dep hasn't been recorded we add it to the map
// If it's been recorded as INCOMPLETE but is now complete we upgrade the dependency
if (currentDep == null
|| (completed && currentDep.getKind() == Deps.Dependency.Kind.INCOMPLETE)) {
depsMap.put(
path,
Deps.Dependency.newBuilder()
.setKind(completed ? Deps.Dependency.Kind.IMPLICIT : Deps.Dependency.Kind.INCOMPLETE)
.setPath(path.toString())
.build());
}
}
public static Path getJarPath(JavaFileObject file) {
if (file == null) {
return null;
}
try {
Field field = file.getClass().getDeclaredField("userJarPath");
field.setAccessible(true);
return (Path) field.get(file);
} catch (NoSuchFieldException e) {
return null;
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
private static class TypeVisitor extends SimpleTypeVisitor7<Void, Void> {
// TODO(bazel-team): Override the visitor methods we're interested in.
}
}
| {
"content_hash": "e9c3ae6557ea130ee4e90594b51e0661",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 100,
"avg_line_length": 39.0979020979021,
"alnum_prop": 0.7188338401001609,
"repo_name": "aehlig/bazel",
"id": "f08aeccf903b119a8df41300bdec4456af6f41b0",
"size": "5591",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/plugins/dependency/ImplicitDependencyExtractor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1588"
},
{
"name": "C",
"bytes": "27067"
},
{
"name": "C++",
"bytes": "1513394"
},
{
"name": "Dockerfile",
"bytes": "839"
},
{
"name": "HTML",
"bytes": "21053"
},
{
"name": "Java",
"bytes": "35178923"
},
{
"name": "Makefile",
"bytes": "248"
},
{
"name": "Objective-C",
"bytes": "10369"
},
{
"name": "Objective-C++",
"bytes": "1043"
},
{
"name": "PowerShell",
"bytes": "15438"
},
{
"name": "Python",
"bytes": "2519187"
},
{
"name": "Ruby",
"bytes": "639"
},
{
"name": "Shell",
"bytes": "1916092"
},
{
"name": "Smarty",
"bytes": "18683"
}
],
"symlink_target": ""
} |
<!--
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.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- **************************************************************** -->
<!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * -->
<!-- * i.e. only iterate & print data where possible. Thanks, Jez. * -->
<!-- **************************************************************** -->
<html>
<head>
<!-- Generated by groovydoc (2.4.4) on Tue Oct 20 05:52:32 CEST 2015 -->
<title>ArtifactResult (Gradle API 2.8)</title>
<meta name="date" content="2015-10-20">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<body class="center">
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ArtifactResult (Gradle API 2.8)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/artifacts/result/ArtifactResult" target="_top">Frames</a></li>
<li><a href="ArtifactResult.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">Package: <strong>org.gradle.api.artifacts.result</strong></div>
<h2 title="[Java] Interface ArtifactResult" class="title">[Java] Interface ArtifactResult</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<p> The result of resolving an artifact.
<DL><DT><B>Since:</B></DT><DD>2.0</DD></DL></p>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== NESTED CLASS SUMMARY =========== -->
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<!-- =========== FIELD SUMMARY =========== -->
<!-- =========== PROPERTY SUMMARY =========== -->
<!-- =========== ELEMENT SUMMARY =========== -->
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary"><!-- --></a>
<h3>Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Methods Summary table">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Type</th>
<th class="colLast" scope="col">Name and description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href='https://docs.oracle.com/javase/6/docs/api/java/lang/Class.html' title='Class'>Class</a><? extends <a href='../../../../../org/gradle/api/component/Artifact.html' title='Artifact'>Artifact</a>></strong></code></td>
<td class="colLast"><code><strong><a href="#getType()">getType</a></strong>()</code><br></td>
</tr>
</table>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- =========== METHOD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getType()"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>public <a href='https://docs.oracle.com/javase/6/docs/api/java/lang/Class.html' title='Class'>Class</a><? extends <a href='../../../../../org/gradle/api/component/Artifact.html' title='Artifact'>Artifact</a>> <strong>getType</strong>()</h4>
<p></p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/artifacts/result/ArtifactResult" target="_top">Frames</a></li>
<li><a href="ArtifactResult.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#method_detail">Method</a></li>
</ul>
</div>
<p>Gradle API 2.8</p>
<a name="skip-navbar_bottom">
<!-- -->
</a>
</div>
</div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "87025d3f281b890841ad94e494250d2b",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 287,
"avg_line_length": 36.83404255319149,
"alnum_prop": 0.48937153419593343,
"repo_name": "FinishX/coolweather",
"id": "39f6e5670619573532501bfe020cfb6248db9da4",
"size": "8656",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gradle/gradle-2.8/docs/groovydoc/org/gradle/api/artifacts/result/ArtifactResult.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "277"
},
{
"name": "C",
"bytes": "97569"
},
{
"name": "C++",
"bytes": "912105"
},
{
"name": "CSS",
"bytes": "105486"
},
{
"name": "CoffeeScript",
"bytes": "201"
},
{
"name": "GAP",
"bytes": "212"
},
{
"name": "Groovy",
"bytes": "1162135"
},
{
"name": "HTML",
"bytes": "35827007"
},
{
"name": "Java",
"bytes": "12908568"
},
{
"name": "JavaScript",
"bytes": "195155"
},
{
"name": "Objective-C",
"bytes": "2977"
},
{
"name": "Objective-C++",
"bytes": "442"
},
{
"name": "Scala",
"bytes": "12789"
},
{
"name": "Shell",
"bytes": "5398"
}
],
"symlink_target": ""
} |
"""Utility to handle vocabularies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import codecs
import os
import tensorflow as tf
from tensorflow.python.ops import lookup_ops
from third_party.nmt.utils import misc_utils as utils
UNK = "<unk>"
SOS = "<s>"
EOS = "</s>"
UNK_ID = 0
def load_vocab(vocab_file):
vocab = []
with codecs.getreader("utf-8")(tf.gfile.GFile(vocab_file, "rb")) as f:
vocab_size = 0
for word in f:
vocab_size += 1
vocab.append(word.strip())
return vocab, vocab_size
def check_vocab(vocab_file,
out_dir,
check_special_token=True,
sos=None,
eos=None,
unk=None,
context_delimiter=None):
"""Check if vocab_file doesn't exist, create from corpus_file."""
if tf.gfile.Exists(vocab_file):
utils.print_out("# Vocab file %s exists" % vocab_file)
vocab = []
with codecs.getreader("utf-8")(tf.gfile.GFile(vocab_file, "rb")) as f:
vocab_size = 0
for word in f:
word = word.rstrip("\n").rsplit("\t", 1)[0]
vocab_size += 1
vocab.append(word)
# add context delimiter if not exist yet
if context_delimiter is not None and context_delimiter not in vocab:
vocab += [context_delimiter]
vocab_size += 1
utils.print_out("Context delimiter {} does not exist"
.format(context_delimiter))
elif context_delimiter is not None and context_delimiter in vocab:
utils.print_out("Context delimiter {} already exists in vocab"
.format(context_delimiter))
if check_special_token:
# Verify if the vocab starts with unk, sos, eos
# If not, prepend those tokens & generate a new vocab file
if not unk:
unk = UNK
if not sos:
sos = SOS
if not eos:
eos = EOS
assert len(vocab) >= 3
if vocab[0] != unk or vocab[1] != sos or vocab[2] != eos:
utils.print_out("The first 3 vocab words [%s, %s, %s]"
" are not [%s, %s, %s]" % (vocab[0], vocab[1], vocab[2],
unk, sos, eos))
vocab = [unk, sos, eos] + vocab
vocab_size += 3
new_vocab_file = os.path.join(out_dir, os.path.basename(vocab_file))
with codecs.getwriter("utf-8")(tf.gfile.GFile(new_vocab_file,
"wb")) as f:
for word in vocab:
f.write("%s\n" % word)
vocab_file = new_vocab_file
else:
raise ValueError("vocab_file '%s' does not exist." % vocab_file)
vocab_size = len(vocab)
return vocab_size, vocab_file
def create_vocab_tables(src_vocab_file, tgt_vocab_file, share_vocab):
"""Creates vocab tables for src_vocab_file and tgt_vocab_file."""
src_vocab_table = lookup_ops.index_table_from_file(
src_vocab_file, default_value=UNK_ID)
if share_vocab:
tgt_vocab_table = src_vocab_table
else:
tgt_vocab_table = lookup_ops.index_table_from_file(
tgt_vocab_file, default_value=UNK_ID)
return src_vocab_table, tgt_vocab_table
def load_embed_txt(embed_file):
"""Load embed_file into a python dictionary.
Note: the embed_file should be a Glove/word2vec formatted txt file. Assuming
Here is an exampe assuming embed_size=5:
the -0.071549 0.093459 0.023738 -0.090339 0.056123
to 0.57346 0.5417 -0.23477 -0.3624 0.4037
and 0.20327 0.47348 0.050877 0.002103 0.060547
For word2vec format, the first line will be: <num_words> <emb_size>.
Args:
embed_file: file path to the embedding file.
Returns:
a dictionary that maps word to vector, and the size of embedding dimensions.
"""
emb_dict = dict()
emb_size = None
is_first_line = True
with codecs.getreader("utf-8")(tf.gfile.GFile(embed_file, "rb")) as f:
for line in f:
tokens = line.rstrip().split(" ")
if is_first_line:
is_first_line = False
if len(tokens) == 2: # header line
emb_size = int(tokens[1])
continue
word = tokens[0]
vec = list(map(float, tokens[1:]))
emb_dict[word] = vec
if emb_size:
if emb_size != len(vec):
utils.print_out(
"Ignoring %s since embeding size is inconsistent." % word)
del emb_dict[word]
else:
emb_size = len(vec)
return emb_dict, emb_size
| {
"content_hash": "d3960ef5bdfc9f8dd6aa42dc4839cf2d",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 80,
"avg_line_length": 32.30434782608695,
"alnum_prop": 0.5955585464333782,
"repo_name": "google/active-qa",
"id": "d07031177fb52608ea78716207329b755e989358",
"size": "5115",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "px/nmt/utils/vocab_utils.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "499394"
},
{
"name": "Shell",
"bytes": "980"
}
],
"symlink_target": ""
} |
from cupy.cuda import runtime
class Event(object):
"""CUDA event, a synchronization point of CUDA streams.
This class handles the CUDA event handle in RAII way, i.e., when an Event
instance is destroyed by the GC, its handle is also destroyed.
Args:
block (bool): If True, the event blocks on the
:meth:`~cupy.cuda.Event.synchronize` method.
disable_timing (bool): If True, the event does not prepare the timing
data.
interprocess (bool): If True, the event can be passed to other
processes.
Attributes:
ptr (cupy.cuda.runtime.Stream): Raw stream handle. It can be passed to
the CUDA Runtime API via ctypes.
"""
def __init__(self, block=False, disable_timing=False, interprocess=False):
self.ptr = None
if interprocess and not disable_timing:
raise ValueError('Timing must be disabled for interprocess events')
flag = ((block and runtime.eventBlockingSync) |
(disable_timing and runtime.eventDisableTiming) |
(interprocess and runtime.eventInterprocess))
self.ptr = runtime.eventCreateWithFlags(flag)
def __del__(self):
if self.ptr:
runtime.eventDestroy(self.ptr)
self.ptr = None
@property
def done(self):
"""True if the event is done."""
return bool(runtime.eventQuery(self.ptr))
def record(self, stream=None):
"""Records the event to a stream.
Args:
stream (cupy.cuda.Stream): CUDA stream to record event. The null
stream is used by default.
.. seealso:: :meth:`cupy.cuda.Stream.record`
"""
if stream is None:
stream = Stream(null=True)
runtime.eventRecord(self.ptr, stream.ptr)
def synchronize(self):
"""Synchronizes all device work to the event.
If the event is created as a blocking event, it also blocks the CPU
thread until the event is done.
"""
runtime.eventSynchronize(self.ptr)
def get_elapsed_time(start_event, end_event):
"""Gets the elapsed time between two events.
Args:
start_event (Event): Earlier event.
end_event (Event): Later event.
Returns:
float: Elapsed time in milliseconds.
"""
return runtime.eventElapsedTime(start_event.ptr, end_event.ptr)
class Stream(object):
"""CUDA stream.
This class handles the CUDA stream handle in RAII way, i.e., when an Stream
instance is destroyed by the GC, its handle is also destroyed.
Args:
null (bool): If True, the stream is a null stream (i.e. the default
stream that synchronizes with all streams). Otherwise, a plain new
stream is created.
non_blocking (bool): If True, the stream does not synchronize with the
NULL stream.
Attributes:
ptr (cupy.cuda.runtime.Stream): Raw stream handle. It can be passed to
the CUDA Runtime API via ctypes.
"""
def __init__(self, null=False, non_blocking=False):
if null:
self.ptr = None
elif non_blocking:
self.ptr = runtime.streamCreateWithFlags(runtime.streamNonBlocking)
else:
self.ptr = runtime.streamCreate()
def __del__(self):
if self.ptr:
runtime.streamDestroy(self.ptr)
self.ptr = None
@property
def done(self):
"""True if all work on this stream has been done."""
return bool(runtime.streamQuery(self.ptr))
def synchronize(self):
"""Waits for the stream completing all queued work."""
runtime.streamSynchronize(self.ptr)
def add_callback(self, callback, arg):
"""Adds a callback that is called when all queued work is done.
Args:
callback (function): Callback function. It must take three
arguments (Stream object, int error status, and user data
object), and returns nothing.
arg (object): Argument to the callback.
"""
runtime.streamAddCallback(self.ptr, callback, arg)
def record(self, event=None):
"""Records an event on the stream.
Args:
event (None or cupy.cuda.Event): CUDA event. If None, then a new
plain event is created and used.
Returns:
cupy.cuda.Event: The recorded event.
.. seealso:: :meth:`cupy.cuda.Event.record`
"""
if event is None:
event = Event()
runtime.eventRecord(event.ptr, self.ptr)
return event
def wait_event(self, event):
"""Makes the stream wait for an event.
The future work on this stream will be done after the event.
Args:
event (cupy.cuda.Event): CUDA event.
"""
runtime.streamWaitEvent(self.ptr, event)
| {
"content_hash": "3c7685a7707e62def92dcc70bb27dc94",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 79,
"avg_line_length": 30.395061728395063,
"alnum_prop": 0.6078391551584078,
"repo_name": "t-abe/chainer",
"id": "6cead5420867eaac27bd0dea3d3c314861d9160a",
"size": "4924",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "cupy/cuda/stream.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "18613"
},
{
"name": "Cuda",
"bytes": "6118"
},
{
"name": "Python",
"bytes": "1233416"
}
],
"symlink_target": ""
} |
* [Setting up your local environment](#setting-up-your-local-environment)
* [Step 1: Fork](#step-1-fork)
* [Step 2: Build](#step-2-build)
* [Step 3: Branch](#step-3-branch)
* [Making Changes](#making-changes)
* [Step 4: Code](#step-4-code)
* [Step 5: Commit](#step-5-commit)
* [Commit message guidelines](#commit-message-guidelines)
* [Step 6: Rebase](#step-6-rebase)
* [Step 7: Test](#step-7-test)
* [Step 8: Push](#step-8-push)
* [Step 9: Opening the Pull Request](#step-9-opening-the-pull-request)
* [Step 10: Discuss and Update](#step-10-discuss-and-update)
* [Approval and Request Changes Workflow](#approval-and-request-changes-workflow)
* [Step 11: Landing](#step-11-landing)
* [Continuous Integration Testing](#continuous-integration-testing)
## Setting up your local environment
### Step 1: Fork
Fork the project [on GitHub](https://github.com/electron/electron) and clone your fork
locally.
```sh
$ git clone git@github.com:username/electron.git
$ cd electron
$ git remote add upstream https://github.com/electron/electron.git
$ git fetch upstream
```
### Step 2: Build
Build steps and dependencies differ slightly depending on your operating system.
See these detailed guides on building Electron locally:
* [Building on MacOS](https://electronjs.org/docs/development/build-instructions-macos)
* [Building on Linux](https://electronjs.org/docs/development/build-instructions-linux)
* [Building on Windows](https://electronjs.org/docs/development/build-instructions-windows)
Once you've built the project locally, you're ready to start making changes!
### Step 3: Branch
To keep your development environment organized, create local branches to
hold your work. These should be branched directly off of the `master` branch.
```sh
$ git checkout -b my-branch -t upstream/master
```
## Making Changes
### Step 4: Code
Most pull requests opened against the `electron/electron` repository include
changes to either the C/C++ code in the `atom/` folder,
the JavaScript code in the `lib/` folder, the documentation in `docs/api/`
or tests in the `spec/` folder.
Please be sure to run `npm run lint` from time to time on any code changes
to ensure that they follow the project's code style.
See [coding style](https://electronjs.org/docs/development/coding-style) for
more information about best practice when modifying code in different parts of
the project.
### Step 5: Commit
It is recommended to keep your changes grouped logically within individual
commits. Many contributors find it easier to review changes that are split
across multiple commits. There is no limit to the number of commits in a
pull request.
```sh
$ git add my/changed/files
$ git commit
```
Note that multiple commits often get squashed when they are landed.
#### Commit message guidelines
A good commit message should describe what changed and why. The Electron project
uses [semantic commit messages](https://conventionalcommits.org/) to streamline
the release process.
Before a pull request can be merged, it **must** have a pull request title with a semantic prefix.
Examples of commit messages with semantic prefixes:
- `fix: don't overwrite prevent_default if default wasn't prevented`
- `feat: add app.isPackaged() method`
- `docs: app.isDefaultProtocolClient is now available on Linux`
Common prefixes:
- fix: A bug fix
- feat: A new feature
- docs: Documentation changes
- test: Adding missing tests or correcting existing tests
- build: Changes that affect the build system
- ci: Changes to our CI configuration files and scripts
- perf: A code change that improves performance
- refactor: A code change that neither fixes a bug nor adds a feature
- style: Changes that do not affect the meaning of the code (linting)
- vendor: Bumping a dependency like libchromiumcontent or node
Other things to keep in mind when writing a commit message:
1. The first line should:
- contain a short description of the change (preferably 50 characters or less,
and no more than 72 characters)
- be entirely in lowercase with the exception of proper nouns, acronyms, and
the words that refer to code, like function/variable names
2. Keep the second line blank.
3. Wrap all other lines at 72 columns.
#### Breaking Changes
A commit that has the text `BREAKING CHANGE:` at the beginning of its optional
body or footer section introduces a breaking API change (correlating with Major
in semantic versioning). A breaking change can be part of commits of any type.
e.g., a `fix:`, `feat:` & `chore:` types would all be valid, in addition to any
other type.
See [conventionalcommits.org](https://conventionalcommits.org) for more details.
### Step 6: Rebase
Once you have committed your changes, it is a good idea to use `git rebase`
(not `git merge`) to synchronize your work with the main repository.
```sh
$ git fetch upstream
$ git rebase upstream/master
```
This ensures that your working branch has the latest changes from `electron/electron`
master.
### Step 7: Test
Bug fixes and features should always come with tests. A
[testing guide](https://electronjs.org/docs/development/testing) has been
provided to make the process easier. Looking at other tests to see how they
should be structured can also help.
Before submitting your changes in a pull request, always run the full
test suite. To run the tests:
```sh
$ npm run test
```
Make sure the linter does not report any issues and that all tests pass.
Please do not submit patches that fail either check.
If you are updating tests and want to run a single spec to check it:
```sh
$ npm run test -match=menu
```
The above would only run spec modules matching `menu`, which is useful for
anyone who's working on tests that would otherwise be at the very end of
the testing cycle.
### Step 8: Push
Once your commits are ready to go -- with passing tests and linting --
begin the process of opening a pull request by pushing your working branch
to your fork on GitHub.
```sh
$ git push origin my-branch
```
### Step 9: Opening the Pull Request
From within GitHub, opening a new pull request will present you with a template
that should be filled out:
```markdown
<!--
Thank you for your pull request. Please provide a description above and review
the requirements below.
Bug fixes and new features should include tests and possibly benchmarks.
Contributors guide: https://github.com/electron/electron/blob/master/CONTRIBUTING.md
-->
```
### Step 10: Discuss and update
You will probably get feedback or requests for changes to your pull request.
This is a big part of the submission process so don't be discouraged! Some
contributors may sign off on the pull request right away. Others may have
detailed comments or feedback. This is a necessary part of the process
in order to evaluate whether the changes are correct and necessary.
To make changes to an existing pull request, make the changes to your local
branch, add a new commit with those changes, and push those to your fork.
GitHub will automatically update the pull request.
```sh
$ git add my/changed/files
$ git commit
$ git push origin my-branch
```
There are a number of more advanced mechanisms for managing commits using
`git rebase` that can be used, but are beyond the scope of this guide.
Feel free to post a comment in the pull request to ping reviewers if you are
awaiting an answer on something. If you encounter words or acronyms that
seem unfamiliar, refer to this
[glossary](https://sites.google.com/a/chromium.org/dev/glossary).
#### Approval and Request Changes Workflow
All pull requests require approval from a [Code Owner](https://github.com/orgs/electron/teams/code-owners) of the area you
modified in order to land. Whenever a maintainer reviews a pull request they
may request changes. These may be small, such as fixing a typo, or may involve
substantive changes. Such requests are intended to be helpful, but at times
may come across as abrupt or unhelpful, especially if they do not include
concrete suggestions on *how* to change them.
Try not to be discouraged. If you feel that a review is unfair, say so or seek
the input of another project contributor. Often such comments are the result of
a reviewer having taken insufficient time to review and are not ill-intended.
Such difficulties can often be resolved with a bit of patience. That said,
reviewers should be expected to provide helpful feeback.
### Step 11: Landing
In order to land, a pull request needs to be reviewed and approved by
at least one Electron Code Owner and pass CI. After that, if there are no
objections from other contributors, the pull request can be merged.
Congratulations and thanks for your contribution!
### Continuous Integration Testing
Every pull request is tested on the Continuous Integration (CI) system to
confirm that it works on Electron's supported platforms.
Ideally, the pull request will pass ("be green") on all of CI's platforms.
This means that all tests pass and there are no linting errors. However,
it is not uncommon for the CI infrastructure itself to fail on specific
platforms or for so-called "flaky" tests to fail ("be red"). Each CI
failure must be manually inspected to determine the cause.
CI starts automatically when you open a pull request, but only
[Releasers](https://github.com/orgs/electron/teams/releasers/members)
can restart a CI run. If you believe CI is giving a false negative,
ask a Releaser to restart the tests.
| {
"content_hash": "54ecfe692a4aed917584eb1cfc4764f7",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 122,
"avg_line_length": 36.75581395348837,
"alnum_prop": 0.7632605715490879,
"repo_name": "the-ress/electron",
"id": "19960889ff956f0976899486d434dbdf273f3207",
"size": "9500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/development/pull-requests.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1255"
},
{
"name": "C++",
"bytes": "2635834"
},
{
"name": "CSS",
"bytes": "2379"
},
{
"name": "Dockerfile",
"bytes": "1395"
},
{
"name": "HCL",
"bytes": "244"
},
{
"name": "HTML",
"bytes": "14882"
},
{
"name": "JavaScript",
"bytes": "946728"
},
{
"name": "Objective-C",
"bytes": "48789"
},
{
"name": "Objective-C++",
"bytes": "331379"
},
{
"name": "Python",
"bytes": "97441"
},
{
"name": "Shell",
"bytes": "23038"
},
{
"name": "TypeScript",
"bytes": "381037"
}
],
"symlink_target": ""
} |
package filters
import (
"bufio"
"bytes"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"reflect"
"regexp"
"strings"
"testing"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/kubernetes/pkg/genericapiserver/api/request"
)
type simpleResponseWriter struct {
http.ResponseWriter
}
func (*simpleResponseWriter) WriteHeader(code int) {}
type fancyResponseWriter struct {
simpleResponseWriter
}
func (*fancyResponseWriter) CloseNotify() <-chan bool { return nil }
func (*fancyResponseWriter) Flush() {}
func (*fancyResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return nil, nil, nil }
func TestConstructResponseWriter(t *testing.T) {
actual := decorateResponseWriter(&simpleResponseWriter{}, ioutil.Discard, "")
switch v := actual.(type) {
case *auditResponseWriter:
default:
t.Errorf("Expected auditResponseWriter, got %v", reflect.TypeOf(v))
}
actual = decorateResponseWriter(&fancyResponseWriter{}, ioutil.Discard, "")
switch v := actual.(type) {
case *fancyResponseWriterDelegator:
default:
t.Errorf("Expected fancyResponseWriterDelegator, got %v", reflect.TypeOf(v))
}
}
type fakeHTTPHandler struct{}
func (*fakeHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
}
func TestAudit(t *testing.T) {
var buf bytes.Buffer
handler := WithAudit(&fakeHTTPHandler{}, &fakeRequestContextMapper{
user: &user.DefaultInfo{Name: "admin"},
}, &buf)
req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil)
req.RemoteAddr = "127.0.0.1"
handler.ServeHTTP(httptest.NewRecorder(), req)
line := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(line) != 2 {
t.Fatalf("Unexpected amount of lines in audit log: %d", len(line))
}
match, err := regexp.MatchString(`[\d\:\-\.\+TZ]+ AUDIT: id="[\w-]+" ip="127.0.0.1" method="GET" user="admin" groups="<none>" as="<self>" asgroups="<lookup>" namespace="default" uri="/api/v1/namespaces/default/pods"`, line[0])
if err != nil {
t.Errorf("Unexpected error matching first line: %v", err)
}
if !match {
t.Errorf("Unexpected first line of audit: %s", line[0])
}
match, err = regexp.MatchString(`[\d\:\-\.\+TZ]+ AUDIT: id="[\w-]+" response="200"`, line[1])
if err != nil {
t.Errorf("Unexpected error matching second line: %v", err)
}
if !match {
t.Errorf("Unexpected second line of audit: %s", line[1])
}
}
type fakeRequestContextMapper struct {
user *user.DefaultInfo
}
func (m *fakeRequestContextMapper) Get(req *http.Request) (request.Context, bool) {
ctx := request.NewContext()
if m.user != nil {
ctx = request.WithUser(ctx, m.user)
}
resolver := newTestRequestInfoResolver()
info, err := resolver.NewRequestInfo(req)
if err == nil {
ctx = request.WithRequestInfo(ctx, info)
}
return ctx, true
}
func (*fakeRequestContextMapper) Update(req *http.Request, context request.Context) error {
return nil
}
func TestAuditNoPanicOnNilUser(t *testing.T) {
var buf bytes.Buffer
handler := WithAudit(&fakeHTTPHandler{}, &fakeRequestContextMapper{}, &buf)
req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil)
req.RemoteAddr = "127.0.0.1"
handler.ServeHTTP(httptest.NewRecorder(), req)
line := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(line) != 2 {
t.Fatalf("Unexpected amount of lines in audit log: %d", len(line))
}
match, err := regexp.MatchString(`[\d\:\-\.\+TZ]+ AUDIT: id="[\w-]+" ip="127.0.0.1" method="GET" user="<none>" groups="<none>" as="<self>" asgroups="<lookup>" namespace="default" uri="/api/v1/namespaces/default/pods"`, line[0])
if err != nil {
t.Errorf("Unexpected error matching first line: %v", err)
}
if !match {
t.Errorf("Unexpected first line of audit: %s", line[0])
}
match, err = regexp.MatchString(`[\d\:\-\.\+TZ]+ AUDIT: id="[\w-]+" response="200"`, line[1])
if err != nil {
t.Errorf("Unexpected error matching second line: %v", err)
}
if !match {
t.Errorf("Unexpected second line of audit: %s", line[1])
}
}
| {
"content_hash": "8f6bfec47f8ff6126134124c2a740035",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 228,
"avg_line_length": 28.942028985507246,
"alnum_prop": 0.686029043565348,
"repo_name": "hodovska/kubernetes",
"id": "6637629ed7c03f9abf871bd2429fe4ce9b6f2511",
"size": "4563",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "pkg/genericapiserver/api/filters/audit_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "978"
},
{
"name": "Go",
"bytes": "41073607"
},
{
"name": "HTML",
"bytes": "2587634"
},
{
"name": "Makefile",
"bytes": "77303"
},
{
"name": "Nginx",
"bytes": "1608"
},
{
"name": "Protocol Buffer",
"bytes": "590879"
},
{
"name": "Python",
"bytes": "1322148"
},
{
"name": "SaltStack",
"bytes": "54967"
},
{
"name": "Shell",
"bytes": "1634710"
}
],
"symlink_target": ""
} |
var IcecastSource, SourceIn, debug, express, net,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
net = require("net");
express = require("express");
debug = require("debug")("sm:master:source_in");
IcecastSource = require("../sources/icecast");
module.exports = SourceIn = (function(_super) {
__extends(SourceIn, _super);
function SourceIn(opts) {
this._trySource = __bind(this._trySource, this);
this._connection = __bind(this._connection, this);
this.core = opts.core;
this.log = this.core.log.child({
mode: "sourcein"
});
this.port = opts.port;
this.behind_proxy = opts.behind_proxy;
this.server = net.createServer((function(_this) {
return function(c) {
return _this._connection(c);
};
})(this));
}
SourceIn.prototype.listen = function(spec) {
if (spec == null) {
spec = this.port;
}
debug("SourceIn listening on " + spec);
return this.server.listen(spec);
};
SourceIn.prototype._connection = function(sock) {
var parser, readerF, timer;
this.log.debug("Incoming source attempt.");
sock.on("error", (function(_this) {
return function(err) {
return _this.log.debug("Source socket errored with " + err);
};
})(this));
timer = setTimeout((function(_this) {
return function() {
_this.log.debug("Incoming source connection failed to validate before timeout.");
sock.write("HTTP/1.0 400 Bad Request\r\n");
return sock.end("Unable to validate source connection.\r\n");
};
})(this), 2000);
parser = new SourceIn.IcyParser(SourceIn.IcyParser.REQUEST);
readerF = (function(_this) {
return function() {
var d, _results;
_results = [];
while (d = sock.read()) {
_results.push(parser.execute(d));
}
return _results;
};
})(this);
sock.on("readable", readerF);
parser.once("invalid", (function(_this) {
return function() {
sock.removeListener("readable", readerF);
return sock.end("HTTP/1.0 400 Bad Request\n\n");
};
})(this));
return parser.once("headersComplete", (function(_this) {
return function(headers) {
clearTimeout(timer);
if (/^(ICE|HTTP)$/.test(parser.info.protocol) && /^(SOURCE|PUT)$/.test(parser.info.method)) {
_this.log.debug("ICY SOURCE attempt.", {
url: parser.info.url
});
_this._trySource(sock, parser.info);
return sock.removeListener("readable", readerF);
}
};
})(this));
};
SourceIn.prototype._trySource = function(sock, info) {
var m, mount, _authFunc;
_authFunc = (function(_this) {
return function(mount) {
var source, source_ip;
_this.log.debug("Trying to authenticate ICY source for " + mount.key);
if (info.headers.authorization && _this._authorize(mount.password, info.headers.authorization)) {
sock.write("HTTP/1.0 200 OK\n\n");
_this.log.debug("ICY source authenticated for " + mount.key + ".");
source_ip = sock.remoteAddress;
if (_this.behind_proxy && info.headers['x-forwarded-for']) {
source_ip = info.headers['x-forwarded-for'];
}
source = new IcecastSource({
format: mount.opts.format,
sock: sock,
headers: info.headers,
logger: mount.log,
source_ip: source_ip
});
return mount.addSource(source);
} else {
_this.log.debug("ICY source failed to authenticate for " + mount.key + ".");
sock.write("HTTP/1.0 401 Unauthorized\r\n");
return sock.end("Invalid source or password.\r\n");
}
};
})(this);
if (Object.keys(this.core.source_mounts).length > 0 && (m = RegExp("^/(" + (Object.keys(this.core.source_mounts).join("|")) + ")").exec(info.url))) {
debug("Incoming source matched mount: " + m[1]);
mount = this.core.source_mounts[m[1]];
return _authFunc(mount);
} else {
debug("Incoming source matched nothing. Disconnecting.");
this.log.debug("ICY source attempted to connect to bad URL.", {
url: info.url
});
sock.write("HTTP/1.0 401 Unauthorized\r\n");
return sock.end("Invalid source or password.\r\n");
}
};
SourceIn.prototype._tmp = function() {
if (/^\/admin\/metadata/.match(req.url)) {
res.writeHead(200, headers);
return res.end("OK");
} else {
res.writeHead(400, headers);
return res.end("Invalid method " + res.method + ".");
}
};
SourceIn.prototype._authorize = function(stream_passwd, header) {
var pass, type, user, value, _ref, _ref1;
_ref = header.split(" "), type = _ref[0], value = _ref[1];
if (type.toLowerCase() === "basic") {
value = new Buffer(value, 'base64').toString('ascii');
_ref1 = value.split(":"), user = _ref1[0], pass = _ref1[1];
if (pass === stream_passwd) {
return true;
} else {
return false;
}
} else {
return false;
}
};
SourceIn.IcyParser = (function(_super1) {
__extends(IcyParser, _super1);
function IcyParser(type) {
this["INIT_" + type]();
this.offset = 0;
}
IcyParser.REQUEST = "REQUEST";
IcyParser.RESPONSE = "RESPONSE";
IcyParser.prototype.reinitialize = IcyParser;
IcyParser.prototype.execute = function(chunk) {
this.chunk = chunk;
this.offset = 0;
this.end = this.chunk.length;
while (this.offset < this.end) {
this[this.state]();
this.offset++;
}
return true;
};
IcyParser.prototype.INIT_REQUEST = function() {
this.state = "REQUEST_LINE";
this.lineState = "DATA";
return this.info = {
headers: {}
};
};
IcyParser.prototype.consumeLine = function() {
var byte, line;
if (this.captureStart == null) {
this.captureStart = this.offset;
}
byte = this.chunk[this.offset];
if (byte === 0x0d && this.lineState === "DATA") {
this.captureEnd = this.offset;
this.lineState = "ENDING";
return;
}
if (this.lineState === "ENDING") {
this.lineState = "DATA";
if (byte !== 0x0a) {
return;
}
line = this.chunk.toString("ascii", this.captureStart, this.captureEnd);
this.captureStart = void 0;
this.captureEnd = void 0;
debug("Parser request line: " + line);
return line;
}
};
IcyParser.prototype.requestExp = /^([A-Z]+) (.*) (ICE|HTTP)\/(1).(0|1)$/;
IcyParser.prototype.REQUEST_LINE = function() {
var line, match, _ref;
line = this.consumeLine();
if (line == null) {
return;
}
match = this.requestExp.exec(line);
if (match) {
_ref = match.slice(1, 6), this.info.method = _ref[0], this.info.url = _ref[1], this.info.protocol = _ref[2], this.info.versionMajor = _ref[3], this.info.versionMinor = _ref[4];
} else {
this.emit("invalid");
}
this.info.request_offset = this.offset;
this.info.request_line = line;
return this.state = "HEADER";
};
IcyParser.prototype.headerExp = /^([^:]+): *(.*)$/;
IcyParser.prototype.HEADER = function() {
var line, match;
line = this.consumeLine();
if (line == null) {
return;
}
if (line) {
match = this.headerExp.exec(line);
return this.info.headers[match[1].toLowerCase()] = match[2];
} else {
return this.emit("headersComplete", this.info.headers);
}
};
return IcyParser;
})(require("events").EventEmitter);
return SourceIn;
})(require("events").EventEmitter);
//# sourceMappingURL=source_in.js.map
| {
"content_hash": "39ae7a322ab561d6791800338e9bedd4",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 290,
"avg_line_length": 32.02734375,
"alnum_prop": 0.5721429442614953,
"repo_name": "cdgraff/StreamMachine",
"id": "af25dea7df57e2ee0a471bb6021687a52cdde789",
"size": "8199",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "js/src/streammachine/master/source_in.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "480319"
},
{
"name": "JavaScript",
"bytes": "413708"
},
{
"name": "Shell",
"bytes": "1931"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="BookmarkManager">
<bookmark url="file://$PROJECT_DIR$/tasks/roundhouse.js" line="57" mnemonic="9" />
</component>
<component name="ChangeListManager">
<list default="true" id="1a958000-7e0e-45ad-bbb5-8dc651b6b10d" name="Default" comment="" />
<ignored path="grunt_roundhouse.iws" />
<ignored path=".idea/workspace.xml" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="DaemonCodeAnalyzer">
<disable_hints />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
<component name="FavoritesManager">
<favorites_list name="grunt_roundhouse" />
</component>
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="roundhouse.js" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/tasks/roundhouse.js">
<provider selected="true" editor-type-id="text-editor">
<state line="87" column="0" selection-start="2739" selection-end="2739" vertical-scroll-proportion="0.0" vertical-offset="1088" max-vertical-offset="2091">
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="README.md" pinned="false" current="true" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/README.md">
<provider selected="true" editor-type-id="text-editor">
<state line="253" column="0" selection-start="9120" selection-end="9120" vertical-scroll-proportion="0.4172577" vertical-offset="3948" max-vertical-offset="4794">
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="package.json" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/package.json">
<provider selected="true" editor-type-id="text-editor">
<state line="3" column="19" selection-start="133" selection-end="133" vertical-scroll-proportion="-1.9615384" vertical-offset="0" max-vertical-offset="782">
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FindManager">
<FindUsagesManager>
<setting name="OPEN_NEW_TAB" value="false" />
</FindUsagesManager>
</component>
<component name="IdeDocumentHistory">
<option name="changedFiles">
<list>
<option value="$PROJECT_DIR$/Gruntfile.js" />
<option value="$PROJECT_DIR$/tasks/roundhouse.js" />
<option value="$PROJECT_DIR$/package.json" />
<option value="$PROJECT_DIR$/README.md" />
</list>
</option>
</component>
<component name="ProjectFrameBounds">
<option name="x" value="-8" />
<option name="y" value="-8" />
<option name="width" value="1936" />
<option name="height" value="1056" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectReloadState">
<option name="STATE" value="0" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1" splitterProportion="0.5">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
</navigator>
<panes>
<pane id="Scope" />
<pane id="ProjectPane">
<subPane>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="grunt_roundhouse" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="grunt_roundhouse" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="grunt_roundhouse" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="grunt_roundhouse" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="grunt_roundhouse" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="tasks" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
</subPane>
</pane>
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/../grunt_xunit_runner" />
</component>
<component name="RunManager">
<configuration default="true" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application">
<option name="VMOptions" />
<option name="arguments" />
<option name="filePath" />
<option name="name" value="Dart" />
<option name="saveOutputToFile" value="false" />
<option name="showConsoleOnStdErr" value="false" />
<option name="showConsoleOnStdOut" value="false" />
<method />
</configuration>
<configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit">
<option name="VMOptions" />
<option name="arguments" />
<option name="filePath" />
<option name="scope" value="ALL" />
<option name="testName" />
<method />
</configuration>
<configuration default="true" type="JavaScriptTestRunnerKarma" factoryName="Karma" singleton="true" config-file="">
<envs />
<method />
</configuration>
<configuration default="true" type="JSTestDriver:ConfigurationType" factoryName="JsTestDriver">
<setting name="configLocationType" value="CONFIG_FILE" />
<setting name="settingsFile" value="" />
<setting name="serverType" value="INTERNAL" />
<setting name="preferredDebugBrowser" value="CHROME" />
<method />
</configuration>
<configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug" singleton="true">
<method />
</configuration>
<configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" working-dir="">
<browser start="false" url="" with-js-debugger="false" />
<method />
</configuration>
<list size="0" />
</component>
<component name="ShelveChangesManager" show_recycled="false" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="1a958000-7e0e-45ad-bbb5-8dc651b6b10d" name="Default" comment="" />
<created>1403724341340</created>
<updated>1403724341340</updated>
</task>
<servers />
</component>
<component name="ToolWindowManager">
<frame x="-8" y="-8" width="1936" height="1056" extended-state="6" />
<editor active="true" />
<layout>
<window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.25" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
</layout>
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="VcsManagerConfiguration">
<option name="myTodoPanelSettings">
<TodoPanelSettings />
</option>
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<option name="time" value="1" />
</breakpoint-manager>
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/tasks/roundhouse.js">
<provider selected="true" editor-type-id="text-editor">
<state line="107" column="78" selection-start="4627" selection-end="4627" vertical-scroll-proportion="0.0" vertical-offset="1349" max-vertical-offset="2193">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Gruntfile.js">
<provider selected="true" editor-type-id="text-editor">
<state line="28" column="6" selection-start="543" selection-end="543" vertical-scroll-proportion="0.0" vertical-offset="476" max-vertical-offset="1343">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/package.json">
<provider selected="true" editor-type-id="text-editor">
<state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="782">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Gruntfile.js">
<provider selected="true" editor-type-id="text-editor">
<state line="28" column="6" selection-start="543" selection-end="543" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="1343">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/tasks/roundhouse.js">
<provider selected="true" editor-type-id="text-editor">
<state line="87" column="0" selection-start="2739" selection-end="2739" vertical-scroll-proportion="0.0" vertical-offset="1088" max-vertical-offset="2091">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/package.json">
<provider selected="true" editor-type-id="text-editor">
<state line="3" column="19" selection-start="133" selection-end="133" vertical-scroll-proportion="-1.9615384" vertical-offset="0" max-vertical-offset="782">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/README.md">
<provider selected="true" editor-type-id="text-editor">
<state line="253" column="0" selection-start="9120" selection-end="9120" vertical-scroll-proportion="0.4172577" vertical-offset="3948" max-vertical-offset="4794">
<folding />
</state>
</provider>
</entry>
</component>
</project>
| {
"content_hash": "84b81be49d4eac715cb19ee5bd40821c",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 221,
"avg_line_length": 54.39716312056738,
"alnum_prop": 0.6321382007822686,
"repo_name": "reharik/grunt_roundhouse",
"id": "af998e89b004e45b5b6964b0698c104020a2d939",
"size": "15340",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/workspace.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "8925"
}
],
"symlink_target": ""
} |
require File.dirname(__FILE__) + '/spec_helper'
require 'tempfile'
require 'ostruct'
include Humperdink
describe Tracker do
class TempfileEventListener
attr_accessor :tempfile
def initialize
super
@tempfile = Tempfile.new('tempfile.event.txt')
@tempfile.open
end
def on_event(event, data)
@tempfile.puts(event)
end
end
it 'should notify at_exit' do
listener = TempfileEventListener.new
fork do
Tracker.new(:event_listener => listener, :trigger_at_exit => true)
end
Process.wait
listener.tempfile.tap { |f| f.close; f.open; f.read.should == "exit\n"; f.close! }
end
it 'should not notify at_exit if configuration says no-no' do
listener = TempfileEventListener.new
fork do
Tracker.new(:event_listener => listener, :trigger_at_exit => false)
end
Process.wait
listener.tempfile.tap { |f| f.close; f.open; f.read.should == ''; f.close! }
end
it 'should instantiate with default config' do
tracker = Tracker.new
tracker.config[:enabled].should be_true
tracker.config[:trigger_at_exit].should be_true
tracker.config[:event_listener].should be_nil
end
it 'should be enabled by default' do
# I believe this is for backward compatibility with internal LS gem this
# is being extracted from, but perhaps should be changed to default to false.
Tracker.new.tracker_enabled.should be_true
end
it 'should reset config and enabled' do
tracker = Tracker.new
tracker.config[:enabled] = false
tracker.reset_tracker_config
tracker.config[:enabled] = true
end
it 'should reset_tracker when disabled' do
tracker = Tracker.new
def tracker.reset_tracker
@reset_called = true
end
def tracker.reset_called
@reset_called
end
tracker.config[:enabled] = false
tracker.tracker_enabled
tracker.reset_called.should be_true
end
it 'should shutdown and reset config and disable itself' do
listener = TestListener.new
tracker = Tracker.new
tracker.config[:event_listener] = listener
tracker.shutdown(Exception.new 'foobar')
listener.event.should == :shutdown
listener.data[:exception_message].should == 'foobar'
tracker.tracker_enabled.should be_false
end
end | {
"content_hash": "6a0a3cab89ca4fff550e8331f0358a58",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 86,
"avg_line_length": 26.264367816091955,
"alnum_prop": 0.6884026258205689,
"repo_name": "livingsocial/humperdink",
"id": "b89fc7dc88b8b467d6f179758aa2b5eba2bed92a",
"size": "2285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/tracker_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "22287"
}
],
"symlink_target": ""
} |
/**
* CSCIE99 TEAM 2
*/
package cscie99.team2.lingolearn.server.datastore;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Load;
import cscie99.team2.lingolearn.shared.Course;
import cscie99.team2.lingolearn.shared.SpacedRepetitionOption;
import cscie99.team2.lingolearn.shared.User;
/**
* This class represents Proxy for Course
*/
@Entity(name="ObjectifyableCourse")
public class ObjectifyableCourse implements Serializable {
private static final long serialVersionUID = -4995077387409263724L;
@Id Long courseId; // Unique course Id
@Index String courseDesc; // Course description
@Index String courseName; // Course name
Date courseStart, // Course start date
courseEnd; // Course end date
@Index
@Load
Ref<ObjectifyableUser> instructor;
@Index
@Load
List<Ref<ObjectifyableUser>> students;
SpacedRepetitionOption spacedRepetitionOption;
public ObjectifyableCourse() {
this.students = new ArrayList<Ref<ObjectifyableUser>>();
};
/**
* This method constructor creates Objectifyable Course from real object
* @param course Course object
*/
public ObjectifyableCourse (Course course) {
ObjectifyableUser instructor =
new ObjectifyableUser(course.getInstructor());
this.instructor = Ref.create(instructor);
this.students = new ArrayList<Ref<ObjectifyableUser>>();
for( User student : course.getStudents() ){
ObjectifyableUser storableStudent = new ObjectifyableUser(student);
Ref<ObjectifyableUser> studentRef = Ref.create(storableStudent);
this.students.add(studentRef);
}
this.courseId = course.getCourseId();
this.courseDesc = course.getCourseDesc();
this.courseName = course.getCourseName();
this.courseStart = course.getCourseStart();
this.courseEnd = course.getCourseEnd();
this.spacedRepetitionOption = course.getSpacedRepetitionOption();
}
/**
* This method reconstructs real object from Objectifyable Proxy
* @return Course object
*/
public Course getCourse() {
Course c = new Course();
c.setCourseId(this.courseId);
c.setCourseDesc(this.courseDesc);
c.setCourseName(this.courseName);
c.setCourseStart(this.courseStart);
c.setCourseEnd(this.courseEnd);
c.setSpacedRepetitionOption(this.spacedRepetitionOption);
ObjectifyableUser storedInstructor = this.instructor.get();
User instructor = storedInstructor.getUser();
c.setInstructor(instructor);
for( Ref<ObjectifyableUser> studentRef : this.students ){
ObjectifyableUser storedStudent = studentRef.get();
User student = storedStudent.getUser();
c.addStudent(student);
}
return c;
}
}
| {
"content_hash": "afbacdb3435d1e9010c1762521b9c32b",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 73,
"avg_line_length": 29.8659793814433,
"alnum_prop": 0.7559544356230583,
"repo_name": "lingolearn/lingolearn",
"id": "eea384b5ed4368368904cae42223e405e0cd787a",
"size": "2897",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/cscie99/team2/lingolearn/server/datastore/ObjectifyableCourse.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "68206"
},
{
"name": "Java",
"bytes": "495666"
}
],
"symlink_target": ""
} |
package org.apache.camel.processor.interceptor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
/**
* @version
*/
public class AdviceWithRouteIdTest extends AdviceWithTest {
@Test
public void testAdvised() throws Exception {
context.getRouteDefinition("myRoute").adviceWith(context, new RouteBuilder() {
@Override
public void configure() throws Exception {
interceptSendToEndpoint("mock:foo")
.skipSendToOriginalEndpoint()
.to("log:foo")
.to("mock:advised");
}
});
getMockEndpoint("mock:foo").expectedMessageCount(0);
getMockEndpoint("mock:advised").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").routeId("myRoute").to("mock:foo").to("mock:result");
from("direct:bar").to("mock:bar");
}
};
}
} | {
"content_hash": "7017f9240d2e66ef091508acffa4ba85",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 89,
"avg_line_length": 29.704545454545453,
"alnum_prop": 0.5960214231063504,
"repo_name": "jamesnetherton/camel",
"id": "f2fb60888ef18d656073f4dc5638bfe2d31b3c85",
"size": "2110",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithRouteIdTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1518"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "44835"
},
{
"name": "HTML",
"bytes": "903016"
},
{
"name": "Java",
"bytes": "74371250"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323982"
},
{
"name": "Shell",
"bytes": "17120"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "288715"
}
],
"symlink_target": ""
} |
<?php
class DynamoDbHandlerTest extends ehough_epilog_TestCase
{
public function setUp()
{
if (!class_exists('Aws\DynamoDb\DynamoDbClient')) {
$this->markTestSkipped('aws/aws-sdk-php not installed');
}
$this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient')
->setMethods(array('formatAttributes', '__call'))
->disableOriginalConstructor()->getMock();
}
public function testConstruct()
{
$this->assertInstanceOf('ehough_epilog_handler_DynamoDbHandler', new ehough_epilog_handler_DynamoDbHandler($this->client, 'foo'));
}
public function testInterface()
{
$this->assertInstanceOf('ehough_epilog_handler_DynamoDbHandler', new ehough_epilog_handler_DynamoDbHandler($this->client, 'foo'));
}
public function testGetFormatter()
{
$handler = new ehough_epilog_handler_DynamoDbHandler($this->client, 'foo');
$this->assertInstanceOf('ehough_epilog_formatter_ScalarFormatter', $handler->getFormatter());
}
public function testHandle()
{
$record = $this->getRecord();
$formatter = $this->getMock('ehough_epilog_formatter_FormatterInterface');
$formatted = array('foo' => 1, 'bar' => 2);
$handler = new ehough_epilog_handler_DynamoDbHandler($this->client, 'foo');
$handler->setFormatter($formatter);
$formatter
->expects($this->once())
->method('format')
->with($record)
->will($this->returnValue($formatted));
$this->client
->expects($this->once())
->method('formatAttributes')
->with($this->isType('array'))
->will($this->returnValue($formatted));
$this->client
->expects($this->once())
->method('__call')
->with('putItem', array(array(
'TableName' => 'foo',
'Item' => $formatted
)));
$handler->handle($record);
}
}
| {
"content_hash": "98ae994de1815388c42fe85af48a7009",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 138,
"avg_line_length": 32.44444444444444,
"alnum_prop": 0.5753424657534246,
"repo_name": "ehough/epilog",
"id": "2f11edeeca8f5b513a67d3492d9873174d759210",
"size": "2271",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/test/php/ehough/epilog/handler/DynamoDbHandlerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "432495"
}
],
"symlink_target": ""
} |
{% extends "helpdesk/base.html" %}{% load i18n bootstrap %}
{% block helpdesk_title %}{% trans "Edit Ticket" %}{% endblock %}
{% block helpdesk_body %}
<div class="col-xs-6">
<div class="panel panel-default">
<div class="panel-body"><h2>{% trans "Edit a Ticket" %}</h2>
<p>{% trans "Unless otherwise stated, all fields are required." %} {% trans "Please provide as descriptive a title and description as possible." %}</p>
<p><strong>{% trans "Note" %}:</strong> {% blocktrans %}Editing a ticket does <em>not</em> send an e-mail to the ticket owner or submitter. No new details should be entered, this form should only be used to fix incorrect details or clean up the submission.{% endblocktrans %}</p>
<form method='post' action='./'>
<fieldset>
{{ form|bootstrap }}
{% comment %}
{% for field in form %}
{% if field.is_hidden %}
{{ field }}
{% else %}
<dt><label for='id_{{ field.name }}'>{{ field.label }}</label>{% if not field.field.required %} <span class='form_optional'>{% trans "(Optional)" %}</span>{% endif %}</dt>
<dd>{{ field }}</dd>
{% if field.errors %}<dd class='error'>{{ field.errors }}</dd>{% endif %}
{% if field.help_text %}<dd class='form_help_text'>{{ field.help_text }}</dd>{% endif %}</label>
{% endif %}
{% endfor %}
</dl>
{% endcomment %}
<div class='buttons form-group'>
<input type='submit' class="btn btn-primary" value='{% trans "Save Changes" %}' />
</div>
</fieldset>
{% csrf_token %}</form>
</div>
</div>
</div>
{% endblock %}
| {
"content_hash": "b5f57b0ec076465b92e7bfa388cff424",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 279,
"avg_line_length": 40.925,
"alnum_prop": 0.5675015271838729,
"repo_name": "fjcapdevila/django-helpdesk",
"id": "a3087c99679b0958b3b112466b42cf9034d626c6",
"size": "1637",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "helpdesk/templates/helpdesk/edit_ticket.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "5926"
},
{
"name": "HTML",
"bytes": "108212"
},
{
"name": "JavaScript",
"bytes": "42249"
},
{
"name": "Python",
"bytes": "457805"
},
{
"name": "Shell",
"bytes": "708"
}
],
"symlink_target": ""
} |
module.exports = {
asyncName: 'export_data',
syncName: 'export_data_sync',
path: process.cwd(),
};
| {
"content_hash": "349de6bef9682aa30afbaffe8659b4f1",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 31,
"avg_line_length": 21,
"alnum_prop": 0.6476190476190476,
"repo_name": "bolt-design-system/bolt",
"id": "8e65bb634d98990deed5efc4e64fee079b46bde1",
"size": "105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/build-tools/plugins/sass-export-data/config.default.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "675605"
},
{
"name": "Dockerfile",
"bytes": "662"
},
{
"name": "HTML",
"bytes": "1692041"
},
{
"name": "JavaScript",
"bytes": "1555629"
},
{
"name": "PHP",
"bytes": "206992"
},
{
"name": "Shell",
"bytes": "15351"
},
{
"name": "TypeScript",
"bytes": "27125"
},
{
"name": "Vue",
"bytes": "6855"
}
],
"symlink_target": ""
} |
package storage::quantum::dxi::ssh::mode::health;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
sub custom_status_output {
my ($self, %options) = @_;
my $msg = "status is '" . $self->{result_values}->{status} . "' [state = " . $self->{result_values}->{state} . "]";
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_status'};
$self->{result_values}->{state} = $options{new_datas}->{$self->{instance} . '_state'};
$self->{result_values}->{name} = $options{new_datas}->{$self->{instance} . '_name'};
return 0;
}
sub prefix_output {
my ($self, %options) = @_;
return "Health check '" . $options{instance_value}->{name} . "' ";
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'global', type => 1, cb_prefix_output => 'prefix_output', message_multiple => 'All health check status are ok' },
];
$self->{maps_counters}->{global} = [
{ label => 'status', set => {
key_values => [ { name => 'status' }, { name => 'state' }, { name => 'name' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments =>
{
"hostname:s" => { name => 'hostname' },
"ssh-option:s@" => { name => 'ssh_option' },
"ssh-path:s" => { name => 'ssh_path' },
"ssh-command:s" => { name => 'ssh_command', default => 'ssh' },
"timeout:s" => { name => 'timeout', default => 30 },
"sudo" => { name => 'sudo' },
"command:s" => { name => 'command', default => 'syscli' },
"command-path:s" => { name => 'command_path' },
"command-options:s" => { name => 'command_options', default => '--list healthcheckstatus' },
"warning-status:s" => { name => 'warning_status' },
"critical-status:s" => { name => 'critical_status', default => '%{status} !~ /Ready|Success/i' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
if (defined($self->{option_results}->{hostname}) && $self->{option_results}->{hostname} ne '') {
$self->{option_results}->{remote} = 1;
}
$self->change_macros(macros => ['warning_status', 'critical_status']);
}
sub manage_selection {
my ($self, %options) = @_;
$self->{global} = {};
my ($stdout, $exit_code) = centreon::plugins::misc::execute(output => $self->{output},
options => $self->{option_results},
sudo => $self->{option_results}->{sudo},
command => $self->{option_results}->{command},
command_path => $self->{option_results}->{command_path},
command_options => $self->{option_results}->{command_options},
);
# Output data:
# Healthcheck Status
# Total count = 2
# [HealthCheck = 1]
# Healthcheck Name = De-Duplication
# State = enabled
# Started = Mon Dec 17 05:00:01 2018
# Finished = Mon Dec 17 05:02:01 2018
# Status = Success
# [HealthCheck = 2]
# Healthcheck Name = Integrity
# State = disabled
# Started =
# Finished =
# Status = Ready
my $id;
foreach (split(/\n/, $stdout)) {
$id = $1 if ($_ =~ /.*\[HealthCheck\s=\s(.*)\]$/i);
$self->{global}->{$id}->{status} = $1 if ($_ =~ /.*Status\s=\s(.*)$/i && defined($id) && $id ne '');
$self->{global}->{$id}->{state} = $1 if ($_ =~ /.*State\s=\s(.*)$/i && defined($id) && $id ne '');
$self->{global}->{$id}->{name} = $1 if ($_ =~ /.*Healthcheck\sName\s=\s(.*)$/i && defined($id) && $id ne '');
}
}
1;
__END__
=head1 MODE
Check health status.
=over 8
=item B<--hostname>
Hostname to query.
=item B<--warning-status>
Set warning threshold for status (Default: '').
Can used special variables like: %{name}, %{status}, %{state}
=item B<--critical-status>
Set critical threshold for status (Default: '%{status} !~ /Ready|Success/i').
Can used special variables like: %{name}, %{status}, %{state}
=item B<--ssh-option>
Specify multiple options like the user (example: --ssh-option='-l=centreon-engine' --ssh-option='-p=52').
=item B<--ssh-path>
Specify ssh command path (default: none)
=item B<--ssh-command>
Specify ssh command (default: 'ssh'). Useful to use 'plink'.
=item B<--timeout>
Timeout in seconds for the command (Default: 30).
=item B<--sudo>
Use 'sudo' to execute the command.
=item B<--command>
Command to get information (Default: 'syscli').
=item B<--command-path>
Command path.
=item B<--command-options>
Command options (Default: '--list healthcheckstatus').
=back
=cut
| {
"content_hash": "50bfd61accc37a056f4cfd11bbccb99d",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 133,
"avg_line_length": 33.69832402234637,
"alnum_prop": 0.48358753315649866,
"repo_name": "Sims24/centreon-plugins",
"id": "931c4bd9324cbf2acc17e837e0f91968d84d5eac",
"size": "6792",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "storage/quantum/dxi/ssh/mode/health.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "719"
},
{
"name": "Perl",
"bytes": "14312136"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TwilioTest {
public partial class SendMsg {
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// txtAccSid control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAccSid;
/// <summary>
/// txtAuthToken control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAuthToken;
/// <summary>
/// txtFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFrom;
/// <summary>
/// txtTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtTo;
/// <summary>
/// txtMsg control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMsg;
/// <summary>
/// Button1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button1;
}
}
| {
"content_hash": "a4c524389ca55ede654c00c029b183b2",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 84,
"avg_line_length": 35.01282051282051,
"alnum_prop": 0.5038447455144636,
"repo_name": "huanlin/Examples",
"id": "19c42d778d74127413547ecd8992026beae12f75",
"size": "2733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DotNet/Misc/TwilioTest/SendMsg.aspx.designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "7864"
},
{
"name": "C",
"bytes": "7229"
},
{
"name": "C#",
"bytes": "815053"
},
{
"name": "C++",
"bytes": "360577"
},
{
"name": "CSS",
"bytes": "27580"
},
{
"name": "HTML",
"bytes": "65651"
},
{
"name": "JavaScript",
"bytes": "4859624"
},
{
"name": "Pascal",
"bytes": "38856"
},
{
"name": "Pawn",
"bytes": "911"
},
{
"name": "PowerShell",
"bytes": "846"
},
{
"name": "QMake",
"bytes": "7744"
},
{
"name": "Ruby",
"bytes": "5958"
},
{
"name": "VBA",
"bytes": "5920"
}
],
"symlink_target": ""
} |
package mss
import (
"errors"
"fmt"
"io/ioutil"
"os"
"regexp"
"strconv"
"github.com/omniscale/magnacarto/color"
)
// Decoder decodes one or more MSS files. Parse/ParseFile can be called
// multiple times to decode dependent .mss files. MSS() returns the current
// decoded style.
type Decoder struct {
mss *MSS
vars *Properties
scanner *scanner
nextTok *token
lastTok *token
expr *expression
lastValue Value
warnings []warning
filename string // for warnings/errors only
filesParsed int
propertyIndex int
}
type warning struct {
line, col int
file string
msg string
}
type position struct {
line int
column int
filename string
filenum int
index int
}
func (w *warning) String() string {
file := w.file
if file == "" {
file = "?"
}
return fmt.Sprintf("%s in %s line: %d col: %d", w.msg, file, w.line, w.col)
}
// New will allocate a new MSS Decoder
func New() *Decoder {
mss := newMSS()
return &Decoder{mss: mss, vars: &Properties{}, expr: &expression{}}
}
// MSS returns the current decoded style.
func (d *Decoder) MSS() *MSS {
return d.mss
}
// Vars returns the current set of all variables.
// Call Evaluate first to resolve expressions, functions and variables.
func (d *Decoder) Vars() *Properties {
return d.vars
}
func (d *Decoder) next() *token {
if d.nextTok != nil {
tok := d.nextTok
d.nextTok = nil
d.lastTok = tok
return tok
}
for {
tok := d.scanner.Next()
if tok.t == tokenError {
d.error(d.pos(tok), tok.value)
}
if tok.t != tokenS && tok.t != tokenComment {
d.lastTok = tok
return tok
}
}
}
func (d *Decoder) backup() {
if d.nextTok != nil || d.lastTok == nil {
d.error(d.pos(d.nextTok), "internal parser bug: double backup (%v, %v)", d.nextTok, d.lastTok)
}
d.nextTok = d.lastTok
}
// ParseFile parses the given .mss file.
// Can be called multiple times to parse a style split into multiple files.
func (d *Decoder) ParseFile(filename string) error {
d.filename = filename
defer func() { d.filename = "" }()
r, err := os.Open(filename)
if err != nil {
return err
}
defer r.Close()
content, err := ioutil.ReadAll(r)
if err != nil {
return err
}
return d.ParseString(string(content))
}
func (d *Decoder) ParseString(content string) (err error) {
d.filesParsed += 1
d.scanner = newScanner(content)
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = fmt.Errorf("unexpected error: %v, %T", r, r)
}
}
}()
for {
tok := d.next()
if tok.t == tokenEOF {
break
}
if tok.t == tokenError {
return fmt.Errorf(tok.String())
}
d.topLevel(tok)
}
return err
}
// Evaluate evaluates all expressions and resolves all references to variables.
// Must be called after last ParseFile/ParseString call.
func (d *Decoder) Evaluate() (err error) {
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = fmt.Errorf("unexpected error: %v, %T", r, r)
}
}
}()
d.evaluateProperties(d.vars, false)
d.evaluateProperties(d.mss.Map(), true)
for _, b := range d.mss.root.blocks {
d.evaluateBlock(b)
}
return err
}
func (d *Decoder) evaluateBlock(b *block) {
d.evaluateProperties(b.properties, true)
for _, b := range b.blocks {
d.evaluateBlock(b)
}
}
func (d *Decoder) evaluateExpression(expr *expression) Value {
// resolve all vars in the expression before evaluating it
for i := range expr.code {
if expr.code[i].T == typeVar {
varname := expr.code[i].Value.(string)
v, _ := d.vars.get(varname)
if v == nil {
d.error(expr.pos, "missing var %s in expression", varname)
}
if expr, ok := v.(*expression); ok {
// evaluate recursive
v = d.evaluateExpression(expr)
d.vars.set(varname, v)
}
t := d.valueType(v)
if t == typeUnknown {
d.error(expr.pos, "unable to determine type of var %s (%v)", varname, v)
}
expr.code[i] = code{Value: v, T: t}
}
}
v, err := expr.evaluate()
if err != nil {
d.error(expr.pos, "expression error: %v", err)
}
return v
}
func (d *Decoder) valueType(v interface{}) codeType {
switch v.(type) {
case string:
return typeString
case float64:
return typeNum
case color.Color:
return typeColor
case bool:
return typeBool
case []Value:
return typeList // TODO convert v to typeList?
default:
return typeUnknown
}
}
func (d *Decoder) evaluateProperties(properties *Properties, validate bool) {
if properties == nil {
return
}
for _, k := range properties.keys() {
if expr, ok := properties.getKey(k).(*expression); ok {
v := d.evaluateExpression(expr)
if validate {
if validProp, validVal := validProperty(k.name, v); !validProp {
d.warn(properties.pos(k), "invalid property %v %v", k.name, v)
} else if !validVal {
d.warn(properties.pos(k), "invalid property value for %v %v", k.name, v)
}
}
attr := properties.values[k]
properties.setPos(k, v, attr.pos)
}
}
}
func (d *Decoder) topLevel(tok *token) {
switch tok.t {
case tokenAtKeyword:
keyword := tok.value[1:]
d.expect(tokenColon)
d.expressionList()
d.expect(tokenSemicolon)
d.vars.set(keyword, d.lastValue)
case tokenHash, tokenAttachment, tokenClass, tokenLBracket:
d.rule(tok)
case tokenIdent:
if tok.value != "Map" {
d.error(d.pos(tok), "only 'Map' identifier expected at top level, got %v", tok)
}
d.mss.pushMapBlock()
d.expect(tokenLBrace)
d.block()
d.mss.popBlock()
// todo mark block as Map
default:
d.error(d.pos(tok), "unexpected token at top level, got %v", tok)
}
}
func (d *Decoder) rule(tok *token) {
d.mss.pushBlock()
d.selectors(tok)
d.expect(tokenLBrace)
d.block()
d.mss.popBlock()
}
func (d *Decoder) block() {
for {
tok := d.next()
switch tok.t {
case tokenHash, tokenAttachment, tokenClass, tokenLBracket:
d.rule(tok)
case tokenIdent, tokenInstance:
keyword := tok.value
if tok.t == tokenInstance {
d.mss.setInstance(tok.value[:len(tok.value)-1]) // strip /
tok = d.next()
if tok.t != tokenIdent {
d.error(d.pos(tok), "expected property name for instance, found %v", tok)
}
keyword = tok.value
}
d.expect(tokenColon)
d.expressionList()
d.mss.setProperty(keyword, d.lastValue,
position{line: tok.line, column: tok.column, filename: d.filename, filenum: d.filesParsed, index: d.propertyIndex},
)
d.propertyIndex += 1
d.expectEndOfStatement()
case tokenRBrace:
return
default:
d.error(d.pos(tok), "unexpected token %v", tok)
}
}
}
// decode multiple selectors, eg:
// #foo, #bar[zoom=3]
func (d *Decoder) selectors(tok *token) {
for {
if tok.t == tokenHash || tok.t == tokenAttachment || tok.t == tokenClass || tok.t == tokenLBracket {
d.selector(tok)
tok = d.next()
if tok.t == tokenComma {
tok = d.next() // TODO non-selector after comma?
if tok.t == tokenLBrace {
// dangling comma
d.backup()
break
}
continue
}
d.backup()
} else {
d.error(d.pos(tok), "expected layer, attachment, class or filter, got %v", tok)
}
break
}
}
// decode single selector, eg:
// #foo::attachment[filter=foo][zoom>=12]
func (d *Decoder) selector(tok *token) {
d.mss.pushSelector()
for {
switch tok.t {
case tokenHash:
d.mss.addLayer(tok.value[1:]) // strip #
case tokenAttachment:
d.mss.addAttachment(tok.value[2:]) // strip ::
case tokenClass:
d.mss.addClass(tok.value[1:]) // strip .
case tokenLBracket:
d.filters(tok)
}
tok = d.next()
if tok.t == tokenHash || tok.t == tokenAttachment || tok.t == tokenClass || tok.t == tokenLBracket {
continue
} else {
d.backup()
break
}
}
}
// decode multiple filters. eg:
// [filter=foo][zoom>=12]
func (d *Decoder) filters(tok *token) {
for {
d.filter()
tok = d.next()
if tok.t == tokenLBracket {
continue
} else {
d.backup()
break
}
}
}
// decode single filters. eg:
// [filter=foo]
func (d *Decoder) filter() {
tok := d.next()
if tok.t == tokenIdent && tok.value == "zoom" {
compOp := d.comp()
tok = d.next()
if tok.t != tokenNumber {
d.error(d.pos(tok), "zoom requires num, got %v", tok)
}
level, err := strconv.ParseInt(tok.value, 10, 64)
if err != nil {
d.error(d.pos(tok), "invalid zoom level %v: %v", tok, err)
}
if compOp == REGEX {
d.error(d.pos(tok), "regular expressions are not allowed for zoom levels")
}
d.mss.addZoom(compOp, level)
d.expect(tokenRBracket)
return
}
var field string
switch tok.t {
case tokenString:
field = tok.value[1 : len(tok.value)-1]
case tokenIdent:
field = tok.value
default:
d.error(d.pos(tok), "expected zoom or field name in filter, got '%s'", tok.value)
}
compOp := d.comp()
var value interface{}
if compOp == MODULO {
// Modulo comparsions expect the divider, a comparsion and a value, eg: x % 2 = 1
// These extra values are stored in the filter value inside a ModuloComparsion struct.
tok = d.next()
if tok.t != tokenNumber {
d.error(d.pos(tok), "expected %v found %v", tokenNumber, tok)
}
div, err := strconv.ParseInt(tok.value, 10, 64)
if err != nil {
d.error(d.pos(tok), "expected integer for modulo, found %v", tok)
}
modCompOp := d.comp()
if modCompOp > NEQ {
d.error(d.pos(tok), "expected simple comparsion, found %v", modCompOp)
}
tok = d.next()
if tok.t != tokenNumber {
d.error(d.pos(tok), "expected %v found %v", tokenNumber, tok)
}
compValue, err := strconv.ParseInt(tok.value, 10, 64)
if err != nil {
d.error(d.pos(tok), "expected integer for modulo comparsion, found %v", tok)
}
value = ModuloComparsion{Div: int(div), CompOp: modCompOp, Value: int(compValue)}
} else {
// All other comparsions expect a single value.
tok = d.next()
switch tok.t {
case tokenString:
value = tok.value[1 : len(tok.value)-1]
case tokenNumber:
value, _ = strconv.ParseFloat(tok.value, 64)
case tokenIdent:
if tok.value == "null" {
value = nil
} else {
d.error(d.pos(tok), "unexpected value in filter '%s'", tok.value)
}
default:
d.error(d.pos(tok), "unexpected value in filter '%s'", tok.value)
}
}
d.expect(tokenRBracket)
d.mss.addFilter(field, compOp, value)
}
// decode comparision. eg:
// = or >=
func (d *Decoder) comp() CompOp {
tok := d.next()
if tok.t != tokenComp && tok.t != tokenModulo {
d.error(d.pos(tok), "expected comparsion, got '%s'", tok.value)
}
compOp, err := parseCompOp(tok.value)
if err != nil {
d.error(d.pos(tok), "invalid comparsion operator '%s': %v", tok.value, err)
}
return compOp
}
// expect consumes the next token checks that it is of type t
func (d *Decoder) expect(t tokenType) {
if tok := d.next(); tok.t != t {
d.error(d.pos(tok), "expected %v found %v", t, tok)
}
}
// expectEndOfStatement checks for semicolon or closing block `}`
func (d *Decoder) expectEndOfStatement() {
tok := d.next()
if tok.t == tokenRBrace {
d.backup()
return
}
d.backup()
d.expect(tokenSemicolon)
}
func (d *Decoder) expressionList() {
startTok := d.next()
d.backup()
d.expression()
for {
tok := d.next()
if tok.t == tokenComma {
d.expression()
} else if tok.t == tokenFunction && d.expr.code[len(d.expr.code)-1].T == typeFunctionEnd {
// non-comma separated list, only between functions, e.g. raster-colorizer-stops: stop(0, #47443e) stop(50, #77654a);
d.backup()
d.expression()
} else {
d.backup()
break
}
}
d.expr.pos = position{line: startTok.line, column: startTok.column, filename: d.filename, filenum: d.filesParsed, index: d.propertyIndex}
d.propertyIndex += 1
d.lastValue = d.expr
d.expr = &expression{}
}
func (d *Decoder) expression() {
d.exprPart()
}
func (d *Decoder) exprPart() {
d.mulExpr()
for {
tok := d.next()
if tok.t == tokenPlus {
d.mulExpr()
d.expr.addOperator(typeAdd)
} else if tok.t == tokenMinus {
d.mulExpr()
d.expr.addOperator(typeSubtract)
} else {
d.backup()
break
}
}
}
func (d *Decoder) mulExpr() {
d.negOrValue()
for {
tok := d.next()
if tok.t == tokenMultiply {
d.negOrValue()
d.expr.addOperator(typeMultiply)
} else if tok.t == tokenDivide {
d.negOrValue()
d.expr.addOperator(typeDivide)
} else {
d.backup()
break
}
}
}
func (d *Decoder) negOrValue() {
tok := d.next()
if tok.t == tokenMinus {
tok := d.next()
d.value(tok)
d.expr.addOperator(typeNegation)
} else {
d.value(tok)
}
}
var urlPath = regexp.MustCompile(`url\(['"]?(.*?)['"]?\)`) // TODO quote handling is borked, eg url('foo") or url('foo) is matched
func (d *Decoder) value(tok *token) {
switch tok.t {
case tokenString:
d.expr.addValue(tok.value[1:len(tok.value)-1], typeString)
case tokenNumber:
v, err := strconv.ParseFloat(tok.value, 64)
if err != nil {
d.error(d.pos(tok), "invalid float %v: %s", v, err)
}
d.expr.addValue(v, typeNum)
case tokenPercentage:
v, err := strconv.ParseFloat(tok.value[:len(tok.value)-1], 64)
if err != nil {
d.error(d.pos(tok), "invalid float %v: %s", v, err)
}
d.expr.addValue(v, typePercent)
case tokenIdent:
switch tok.value {
case "true":
d.expr.addValue(true, typeBool)
case "false":
d.expr.addValue(false, typeBool)
case "null":
d.expr.addValue(nil, typeKeyword)
default:
c, err := color.Parse(tok.value)
if err == nil {
d.expr.addValue(c, typeColor)
} else {
// TODO check for valid keywords
d.expr.addValue(tok.value, typeKeyword)
}
}
case tokenHash:
c, err := color.Parse(tok.value)
if err != nil {
d.error(d.pos(tok), "%v, got %v", err, tok)
}
d.expr.addValue(c, typeColor)
case tokenAtKeyword:
d.expr.addValue(tok.value[1:], typeVar)
case tokenURI:
match := urlPath.FindStringSubmatch(tok.value)
d.expr.addValue(match[1], typeURL)
case tokenLBracket:
// [field]
tok = d.next()
if tok.t != tokenIdent {
d.error(d.pos(tok), "expected identifier in field name, got %v", tok)
}
d.expr.addValue("["+tok.value+"]", typeField)
d.expect(tokenRBracket)
case tokenFunction:
d.expr.addValue(tok.value[:len(tok.value)-1], typeFunction) // strip lparen
d.functionParams()
case tokenLParen:
d.exprPart()
d.expect(tokenRParen)
default:
d.error(d.pos(tok), "unexpected value %v", tok)
}
}
func (d *Decoder) functionParams() {
for {
d.exprPart()
tok := d.next()
if tok.t == tokenRParen {
d.expr.addValue(nil, typeFunctionEnd)
break
}
if tok.t == tokenComma {
continue
}
d.error(d.pos(tok), "expected end of function or comma, got %v", tok)
}
}
type ParseError struct {
Filename string
Line int
Column int
Err string
}
func (p *ParseError) Error() string {
file := p.Filename
if file == "" {
file = "?"
}
return fmt.Sprintf("%s in %s line: %d col: %d", p.Err, file, p.Line, p.Column)
}
func (d *Decoder) pos(tok *token) position {
return position{
filename: d.filename,
line: tok.line,
column: tok.column,
filenum: d.filesParsed,
}
}
func (d *Decoder) error(pos position, format string, args ...interface{}) {
panic(&ParseError{
Filename: pos.filename,
Line: pos.line,
Column: pos.column,
Err: fmt.Sprintf(format, args...),
})
}
func (d *Decoder) warn(pos position, format string, args ...interface{}) {
d.warnings = append(d.warnings,
warning{
file: pos.filename,
line: pos.line,
col: pos.column,
msg: fmt.Sprintf(format, args...),
},
)
}
| {
"content_hash": "5baa43cd71bb29cc8336a6f2f97402c9",
"timestamp": "",
"source": "github",
"line_count": 682,
"max_line_length": 138,
"avg_line_length": 22.872434017595307,
"alnum_prop": 0.6327328674915058,
"repo_name": "omniscale/magnacarto",
"id": "abd050241732d5d700d98fdb81e817ffecc76783",
"size": "15599",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mss/decode.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10769"
},
{
"name": "CartoCSS",
"bytes": "16932"
},
{
"name": "Go",
"bytes": "328798"
},
{
"name": "HTML",
"bytes": "20176"
},
{
"name": "JavaScript",
"bytes": "961264"
},
{
"name": "Makefile",
"bytes": "3873"
},
{
"name": "Shell",
"bytes": "1651"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "591d4e27b921863e6bd3b3e16f99b788",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "c775522a8a41012ec0ca2770009dc75916f87282",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Vitales/Vitaceae/Cissus/Cissus perforata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.facebook.buck.testrunner;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
public class LoggingIntegrationTest {
@Rule public TemporaryPaths temp = new TemporaryPaths();
@Test
public void logOutputIsOnlyReportedForTestWhichFails() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "test_with_logging", temp);
workspace.setUp();
ProcessResult result = workspace.runBuckCommand("test", "//:logging");
result.assertTestFailure();
// stdout should get all debug messages and up when a test fails.
String testOutput = result.getStderr();
String[] testOutputBeforeAndAfterDebugLogs =
testOutput.split(JUnitRunner.JUL_DEBUG_LOGS_HEADER);
assertThat(testOutputBeforeAndAfterDebugLogs, arrayWithSize(2));
String testOutputAfterDebugLogs = testOutputBeforeAndAfterDebugLogs[1];
String[] testOutputBeforeAndAfterErrorLogs =
testOutputAfterDebugLogs.split(JUnitRunner.JUL_ERROR_LOGS_HEADER);
assertThat(testOutputBeforeAndAfterErrorLogs, arrayWithSize(2));
String debugLogs = testOutputBeforeAndAfterErrorLogs[0];
String errorLogs = testOutputBeforeAndAfterErrorLogs[1];
// debugLogs should get info messages and up when a test fails.
assertThat(debugLogs, containsString("This is an error in a failing test"));
assertThat(debugLogs, containsString("This is a warning in a failing test"));
assertThat(debugLogs, containsString("This is an info message in a failing test"));
assertThat(debugLogs, not(containsString("This is a debug message in a failing test")));
assertThat(debugLogs, not(containsString("This is a verbose message in a failing test")));
// errorLogs should get warnings and errors only when a test fails.
assertThat(errorLogs, containsString("This is an error in a failing test"));
assertThat(errorLogs, containsString("This is a warning in a failing test"));
assertThat(errorLogs, not(containsString("This is an info message in a failing test")));
assertThat(errorLogs, not(containsString("This is a debug message in a failing test")));
assertThat(errorLogs, not(containsString("This is a verbose message in a failing test")));
// None of the messages printed in the passing test should be in the output.
assertThat(debugLogs, not(containsString("in a passing test")));
assertThat(errorLogs, not(containsString("in a passing test")));
}
}
| {
"content_hash": "1a7cb52a45ad5d7fbad1106c15b6cd92",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 94,
"avg_line_length": 47.622950819672134,
"alnum_prop": 0.7690189328743545,
"repo_name": "rmaz/buck",
"id": "71c80535140ccf09ac51d855e4715944aebee274",
"size": "3510",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "test/com/facebook/buck/testrunner/LoggingIntegrationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1585"
},
{
"name": "Batchfile",
"bytes": "3875"
},
{
"name": "C",
"bytes": "281295"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "18966"
},
{
"name": "CSS",
"bytes": "56106"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Dockerfile",
"bytes": "2081"
},
{
"name": "Go",
"bytes": "10020"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "11252"
},
{
"name": "Haskell",
"bytes": "1008"
},
{
"name": "IDL",
"bytes": "480"
},
{
"name": "Java",
"bytes": "29307150"
},
{
"name": "JavaScript",
"bytes": "938678"
},
{
"name": "Kotlin",
"bytes": "25755"
},
{
"name": "Lex",
"bytes": "12772"
},
{
"name": "MATLAB",
"bytes": "47"
},
{
"name": "Makefile",
"bytes": "1916"
},
{
"name": "OCaml",
"bytes": "4935"
},
{
"name": "Objective-C",
"bytes": "176972"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "2244"
},
{
"name": "Prolog",
"bytes": "2087"
},
{
"name": "Python",
"bytes": "2075938"
},
{
"name": "Roff",
"bytes": "1207"
},
{
"name": "Rust",
"bytes": "5716"
},
{
"name": "Scala",
"bytes": "5082"
},
{
"name": "Shell",
"bytes": "77999"
},
{
"name": "Smalltalk",
"bytes": "194"
},
{
"name": "Swift",
"bytes": "11393"
},
{
"name": "Thrift",
"bytes": "48632"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
local ExclusionHelper, parent = torch.class('ExclusionHelper', 'OptsHelper')
function ExclusionHelper:__init(opts)
parent.__init(self, opts)
assert(self.ngoals[1]>0)
self.generators.ngoals = self.ngoalsgen
self.generators.ngoals_active = self.ngoals_activegen
end
function ExclusionHelper:ngoalsgen(lopts,name)
local ngoals = torch.random(self.ngoals[1],self.ngoals[2])
lopts.ngoals = ngoals
return 'none'
end
function ExclusionHelper:ngoals_activegen(lopts,name)
if not lopts.ngoals then return 'ngoals' end
local nga = torch.random(self.ngoals_active[1],self.ngoals_active[2])
nga = math.min(nga, lopts.ngoals-1)
lopts.ngoals_active = math.max(nga,1)
return 'none'
end
| {
"content_hash": "f56fed4850a30692c9d992970c0ca1e0",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 76,
"avg_line_length": 32.81818181818182,
"alnum_prop": 0.7271468144044322,
"repo_name": "Ardavans/DSR",
"id": "a5320bc1860a1cf83cd2d64424a5ac62f70a8b9f",
"size": "1025",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mbwrap/games/ExclusionHelper.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "308446"
},
{
"name": "Matlab",
"bytes": "16781"
},
{
"name": "Python",
"bytes": "10046"
},
{
"name": "Shell",
"bytes": "8174"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('Hindlebook', 'node_data'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='pubDate',
field=models.DateTimeField(default=django.utils.timezone.now, db_index=True, verbose_name='date published'),
preserve_default=True,
),
migrations.AlterField(
model_name='post',
name='pubDate',
field=models.DateTimeField(default=django.utils.timezone.now, db_index=True, verbose_name='date published'),
preserve_default=True,
),
]
| {
"content_hash": "cde46ca5cf3c03875eeb6d4f5e728cb0",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 120,
"avg_line_length": 29.23076923076923,
"alnum_prop": 0.6157894736842106,
"repo_name": "Roshack/cmput410-project",
"id": "ba800ae06c020b734d989f31ba3a1249a4af4fbb",
"size": "784",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "DistributedSocialNetworking/Hindlebook/migrations/0001_auto_20150328_2255.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "36523"
},
{
"name": "HTML",
"bytes": "29835"
},
{
"name": "JavaScript",
"bytes": "89893"
},
{
"name": "Python",
"bytes": "166628"
}
],
"symlink_target": ""
} |
Встреча разработчиков проходящая в г. Тюмень. | {
"content_hash": "c8995a3f99ebaaec5d329d73b15e100d",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 45,
"avg_line_length": 45,
"alnum_prop": 0.8444444444444444,
"repo_name": "tensor-tyumen/tensor-tyumen.github.io",
"id": "4411db0e1cba1d8dc563aa6e0694ff6e783ebd57",
"size": "106",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "48086"
},
{
"name": "HTML",
"bytes": "26664"
},
{
"name": "JavaScript",
"bytes": "77062"
},
{
"name": "Ruby",
"bytes": "3304"
}
],
"symlink_target": ""
} |
<?php
namespace Rcm\Factory;
use Interop\Container\ContainerInterface;
use Rcm\Service\DomainRedirectService;
use Rcm\Service\DomainService;
class ServiceDomainRedirectServiceFactory
{
/**
* __invoke
*
* @param ContainerInterface $container
*
* @return DomainRedirectService
*/
public function __invoke($container)
{
return new DomainRedirectService(
$container->get(DomainService::class)
);
}
}
| {
"content_hash": "1dbae338f49576edc2a40083e7e6b7f5",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 49,
"avg_line_length": 18.96,
"alnum_prop": 0.6603375527426161,
"repo_name": "innaDavis/Rcm",
"id": "880b617f65fd63ec3839ccb5ecb2068d02533ebf",
"size": "683",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/Factory/ServiceDomainRedirectServiceFactory.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "11"
},
{
"name": "HTML",
"bytes": "229"
},
{
"name": "JavaScript",
"bytes": "11"
},
{
"name": "PHP",
"bytes": "812924"
}
],
"symlink_target": ""
} |
from django.contrib import admin
# import your models
# Register your models here.
# admin.site.register(YourModel) | {
"content_hash": "243b77622a46b2224ab38a58a474c6f4",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 32,
"avg_line_length": 23.2,
"alnum_prop": 0.7931034482758621,
"repo_name": "datamade/la-metro-councilmatic",
"id": "6767362fddda0f6e69e7d295dd02e55295b2c9d0",
"size": "116",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lametro/admin.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6935"
},
{
"name": "Dockerfile",
"bytes": "1488"
},
{
"name": "HTML",
"bytes": "192898"
},
{
"name": "JavaScript",
"bytes": "13628"
},
{
"name": "Makefile",
"bytes": "2651"
},
{
"name": "Python",
"bytes": "251693"
},
{
"name": "Shell",
"bytes": "1300"
}
],
"symlink_target": ""
} |
const tabbableScopeQuery = (type: string, props: Object): boolean => {
if (props.tabIndex === -1 || props.disabled) {
return false;
}
if (props.tabIndex === 0 || props.contentEditable === true) {
return true;
}
if (type === 'a' || type === 'area') {
return !!props.href && props.rel !== 'ignore';
}
if (type === 'input') {
return props.type !== 'hidden' && props.type !== 'file';
}
return (
type === 'button' ||
type === 'textarea' ||
type === 'object' ||
type === 'select' ||
type === 'iframe' ||
type === 'embed'
);
};
export default tabbableScopeQuery;
| {
"content_hash": "cf3dcca16c50d920d290167833c40d09",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 70,
"avg_line_length": 23.807692307692307,
"alnum_prop": 0.529886914378029,
"repo_name": "TheBlasfem/react",
"id": "c6ab0d3e5446871aeafe12e7009adbab257cb27d",
"size": "819",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "packages/react-interactions/accessibility/src/TabbableScopeQuery.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5341"
},
{
"name": "C++",
"bytes": "44974"
},
{
"name": "CoffeeScript",
"bytes": "11606"
},
{
"name": "JavaScript",
"bytes": "1995401"
},
{
"name": "Makefile",
"bytes": "189"
},
{
"name": "Python",
"bytes": "8305"
},
{
"name": "Shell",
"bytes": "525"
},
{
"name": "TypeScript",
"bytes": "15258"
}
],
"symlink_target": ""
} |
//
// PNLineChart.m
// PNChartDemo
//
// Created by kevin on 11/7/13.
// Copyright (c) 2013年 kevinzhow. All rights reserved.
//
#import "PNLineChart.h"
#import "PNColor.h"
#import "PNChartLabel.h"
#import "PNLineChartData.h"
#import "PNLineChartDataItem.h"
@interface PNLineChart ()
@property (nonatomic) NSMutableArray *chartLineArray; // Array[CAShapeLayer]
@property (nonatomic) NSMutableArray *chartPointArray; // Array[CAShapeLayer] save the point layer
@property (nonatomic) NSMutableArray *chartPath; // Array of line path, one for each line.
@property (nonatomic) NSMutableArray *pointPath; // Array of point path, one for each line
@property (nonatomic) NSMutableArray *endPointsOfPath; // Array of start and end points of each line path, one for each line
@end
@implementation PNLineChart
#pragma mark initialization
- (id)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[self setupDefaultValues];
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupDefaultValues];
}
return self;
}
#pragma mark instance methods
- (void)setYLabels:(NSArray *)yLabels
{
CGFloat yStep = (_yValueMax - _yValueMin) / _yLabelNum;
CGFloat yStepHeight = _chartCavanHeight / _yLabelNum;
NSString *yLabelFormat = self.yLabelFormat ? : @"%1.f";
if (_yChartLabels) {
for (PNChartLabel * label in _yChartLabels) {
[label removeFromSuperview];
}
}else{
_yChartLabels = [NSMutableArray new];
}
#warning modify origin
if (yStep == 0.0) {
PNChartLabel *minLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger)_chartCavanHeight, (NSInteger)_chartMargin, (NSInteger)_yLabelHeight)];
minLabel.text = [NSString stringWithFormat:yLabelFormat, 0.0];
[self setCustomStyleForYLabel:minLabel];
[self addSubview:minLabel];
[_yChartLabels addObject:minLabel];
PNChartLabel *midLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger)(_chartCavanHeight / 2), (NSInteger)_chartMargin, (NSInteger)_yLabelHeight)];
midLabel.text = [NSString stringWithFormat:yLabelFormat, _yValueMax];
[self setCustomStyleForYLabel:midLabel];
[self addSubview:midLabel];
[_yChartLabels addObject:midLabel];
PNChartLabel *maxLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, 0.0, (NSInteger)_chartMargin, (NSInteger)_yLabelHeight)];
maxLabel.text = [NSString stringWithFormat:yLabelFormat, _yValueMax * 2];
[self setCustomStyleForYLabel:maxLabel];
[self addSubview:maxLabel];
[_yChartLabels addObject:maxLabel];
} else {
NSInteger index = 0;
NSInteger num = _yLabelNum + 1;
while (num > 0)
{
PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger)(_chartCavanHeight - index * yStepHeight), (NSInteger)_chartMargin, (NSInteger)_yLabelHeight)];
[label setTextAlignment:NSTextAlignmentRight];
label.text = [NSString stringWithFormat:yLabelFormat, _yValueMin + (yStep * index)];
[self setCustomStyleForYLabel:label];
[self addSubview:label];
[_yChartLabels addObject:label];
index += 1;
num -= 1;
}
}
}
- (CGFloat)computeEqualWidthForXLabels:(NSArray *)xLabels
{
CGFloat xLabelWidth;
if (_showLabel) {
xLabelWidth = _chartCavanWidth / [xLabels count];
} else {
xLabelWidth = (self.frame.size.width) / [xLabels count];
}
return xLabelWidth;
}
- (void)setXLabels:(NSArray *)xLabels
{
CGFloat xLabelWidth;
if (_showLabel) {
xLabelWidth = _chartCavanWidth / [xLabels count];
} else {
xLabelWidth = (self.frame.size.width) / [xLabels count];
}
return [self setXLabels:xLabels withWidth:xLabelWidth];
}
- (void)setXLabels:(NSArray *)xLabels withWidth:(CGFloat)width
{
_xLabels = xLabels;
_xLabelWidth = width;
if (_xChartLabels) {
for (PNChartLabel * label in _xChartLabels) {
[label removeFromSuperview];
}
}else{
_xChartLabels = [NSMutableArray new];
}
NSString *labelText;
if (_showLabel) {
for (int index = 0; index < xLabels.count; index++) {
labelText = xLabels[index];
#warning modify origin
NSInteger x = 2 * _chartMargin + (index * _xLabelWidth) - (_xLabelWidth / 2);
NSInteger y = _chartMargin + _chartCavanHeight;
PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectMake(x, y, (NSInteger)_xLabelWidth, (NSInteger)_chartMargin)];
[label setTextAlignment:NSTextAlignmentCenter];
label.text = labelText;
[self setCustomStyleForXLabel:label];
[self addSubview:label];
[_xChartLabels addObject:label];
}
}
}
- (void)setCustomStyleForXLabel:(UILabel *)label
{
if (_xLabelFont) {
label.font = _xLabelFont;
}
if (_xLabelColor) {
label.textColor = _xLabelColor;
}
}
- (void)setCustomStyleForYLabel:(UILabel *)label
{
if (_yLabelFont) {
label.font = _yLabelFont;
}
if (_yLabelColor) {
label.textColor = _yLabelColor;
}
}
#pragma mark - Touch at point
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchPoint:touches withEvent:event];
[self touchKeyPoint:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchPoint:touches withEvent:event];
[self touchKeyPoint:touches withEvent:event];
}
- (void)touchPoint:(NSSet *)touches withEvent:(UIEvent *)event
{
// Get the point user touched
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self];
for (NSInteger p = _pathPoints.count - 1; p >= 0; p--) {
NSArray *linePointsArray = _endPointsOfPath[p];
for (int i = 0; i < linePointsArray.count - 1; i += 2) {
CGPoint p1 = [linePointsArray[i] CGPointValue];
CGPoint p2 = [linePointsArray[i + 1] CGPointValue];
// Closest distance from point to line
float distance = fabsf(((p2.x - p1.x) * (touchPoint.y - p1.y)) - ((p1.x - touchPoint.x) * (p1.y - p2.y)));
distance /= hypot(p2.x - p1.x, p1.y - p2.y);
if (distance <= 5.0) {
// Conform to delegate parameters, figure out what bezier path this CGPoint belongs to.
for (UIBezierPath *path in _chartPath) {
BOOL pointContainsPath = CGPathContainsPoint(path.CGPath, NULL, p1, NO);
if (pointContainsPath) {
[_delegate userClickedOnLinePoint:touchPoint lineIndex:[_chartPath indexOfObject:path]];
return;
}
}
}
}
}
}
- (void)touchKeyPoint:(NSSet *)touches withEvent:(UIEvent *)event
{
// Get the point user touched
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self];
for (NSInteger p = _pathPoints.count - 1; p >= 0; p--) {
NSArray *linePointsArray = _pathPoints[p];
for (int i = 0; i < linePointsArray.count - 1; i += 1) {
CGPoint p1 = [linePointsArray[i] CGPointValue];
CGPoint p2 = [linePointsArray[i + 1] CGPointValue];
float distanceToP1 = fabsf(hypot(touchPoint.x - p1.x, touchPoint.y - p1.y));
float distanceToP2 = hypot(touchPoint.x - p2.x, touchPoint.y - p2.y);
float distance = MIN(distanceToP1, distanceToP2);
if (distance <= 10.0) {
[_delegate userClickedOnLineKeyPoint:touchPoint
lineIndex:p
pointIndex:(distance == distanceToP2 ? i + 1 : i)];
return;
}
}
}
}
#pragma mark - Draw Chart
- (void)strokeChart
{
_chartPath = [[NSMutableArray alloc] init];
_pointPath = [[NSMutableArray alloc] init];
[self calculateChartPath:_chartPath andPointsPath:_pointPath andPathKeyPoints:_pathPoints andPathStartEndPoints:_endPointsOfPath];
// Draw each line
for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) {
PNLineChartData *chartData = self.chartData[lineIndex];
CAShapeLayer *chartLine = (CAShapeLayer *)self.chartLineArray[lineIndex];
CAShapeLayer *pointLayer = (CAShapeLayer *)self.chartPointArray[lineIndex];
UIGraphicsBeginImageContext(self.frame.size);
// setup the color of the chart line
if (chartData.color) {
chartLine.strokeColor = [[chartData.color colorWithAlphaComponent:chartData.alpha]CGColor];
} else {
chartLine.strokeColor = [PNGreen CGColor];
pointLayer.strokeColor = [PNGreen CGColor];
}
UIBezierPath *progressline = [_chartPath objectAtIndex:lineIndex];
UIBezierPath *pointPath = [_pointPath objectAtIndex:lineIndex];
chartLine.path = progressline.CGPath;
pointLayer.path = pointPath.CGPath;
[CATransaction begin];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.0;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
pathAnimation.fromValue = @0.0f;
pathAnimation.toValue = @1.0f;
[chartLine addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
chartLine.strokeEnd = 1.0;
// if you want cancel the point animation, conment this code, the point will show immediately
if (chartData.inflexionPointStyle != PNLineChartPointStyleNone) {
[pointLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
}
[CATransaction commit];
UIGraphicsEndImageContext();
}
}
- (void)calculateChartPath:(NSMutableArray *)chartPath andPointsPath:(NSMutableArray *)pointsPath andPathKeyPoints:(NSMutableArray *)pathPoints andPathStartEndPoints:(NSMutableArray *)pointsOfPath
{
// Draw each line
for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) {
PNLineChartData *chartData = self.chartData[lineIndex];
CGFloat yValue;
CGFloat innerGrade;
UIBezierPath *progressline = [UIBezierPath bezierPath];
UIBezierPath *pointPath = [UIBezierPath bezierPath];
[chartPath insertObject:progressline atIndex:lineIndex];
[pointsPath insertObject:pointPath atIndex:lineIndex];
if (!_showLabel) {
_chartCavanHeight = self.frame.size.height - 2 * _yLabelHeight;
_chartCavanWidth = self.frame.size.width;
_chartMargin = chartData.inflexionPointWidth;
_xLabelWidth = (_chartCavanWidth / ([_xLabels count] - 1));
}
NSMutableArray *linePointsArray = [[NSMutableArray alloc] init];
NSMutableArray *lineStartEndPointsArray = [[NSMutableArray alloc] init];
int last_x = 0;
int last_y = 0;
CGFloat inflexionWidth = chartData.inflexionPointWidth;
for (NSUInteger i = 0; i < chartData.itemCount; i++) {
yValue = chartData.getData(i).y;
if (!(_yValueMax - _yValueMin)) {
innerGrade = 0.5;
} else {
innerGrade = (yValue - _yValueMin) / (_yValueMax - _yValueMin);
}
CGFloat offSetX = (_chartCavanWidth) / (chartData.itemCount);
#warning modify chart path
int x = 2 * _chartMargin + (i * offSetX);
int y = _chartCavanHeight - (innerGrade * _chartCavanHeight) + (_yLabelHeight / 2);
// Circular point
if (chartData.inflexionPointStyle == PNLineChartPointStyleCircle) {
CGRect circleRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth);
CGPoint circleCenter = CGPointMake(circleRect.origin.x + (circleRect.size.width / 2), circleRect.origin.y + (circleRect.size.height / 2));
[pointPath moveToPoint:CGPointMake(circleCenter.x + (inflexionWidth / 2), circleCenter.y)];
[pointPath addArcWithCenter:circleCenter radius:inflexionWidth / 2 startAngle:0 endAngle:2 * M_PI clockwise:YES];
if ( i != 0 ) {
// calculate the point for line
float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2) );
float last_x1 = last_x + (inflexionWidth / 2) / distance * (x - last_x);
float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y);
float x1 = x - (inflexionWidth / 2) / distance * (x - last_x);
float y1 = y - (inflexionWidth / 2) / distance * (y - last_y);
[progressline moveToPoint:CGPointMake(last_x1, last_y1)];
[progressline addLineToPoint:CGPointMake(x1, y1)];
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)]];
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x1, y1)]];
}
last_x = x;
last_y = y;
}
// Square point
else if (chartData.inflexionPointStyle == PNLineChartPointStyleSquare) {
CGRect squareRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth);
CGPoint squareCenter = CGPointMake(squareRect.origin.x + (squareRect.size.width / 2), squareRect.origin.y + (squareRect.size.height / 2));
[pointPath moveToPoint:CGPointMake(squareCenter.x - (inflexionWidth / 2), squareCenter.y - (inflexionWidth / 2))];
[pointPath addLineToPoint:CGPointMake(squareCenter.x + (inflexionWidth / 2), squareCenter.y - (inflexionWidth / 2))];
[pointPath addLineToPoint:CGPointMake(squareCenter.x + (inflexionWidth / 2), squareCenter.y + (inflexionWidth / 2))];
[pointPath addLineToPoint:CGPointMake(squareCenter.x - (inflexionWidth / 2), squareCenter.y + (inflexionWidth / 2))];
[pointPath closePath];
if ( i != 0 ) {
// calculate the point for line
float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2) );
float last_x1 = last_x + (inflexionWidth / 2);
float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y);
float x1 = x - (inflexionWidth / 2);
float y1 = y - (inflexionWidth / 2) / distance * (y - last_y);
[progressline moveToPoint:CGPointMake(last_x1, last_y1)];
[progressline addLineToPoint:CGPointMake(x1, y1)];
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)]];
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x1, y1)]];
}
last_x = x;
last_y = y;
}
// Triangle point
else if (chartData.inflexionPointStyle == PNLineChartPointStyleTriangle) {
CGRect squareRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth);
CGPoint startPoint = CGPointMake(squareRect.origin.x,squareRect.origin.y + squareRect.size.height);
CGPoint endPoint = CGPointMake(squareRect.origin.x + (squareRect.size.width / 2) , squareRect.origin.y);
CGPoint middlePoint = CGPointMake(squareRect.origin.x + (squareRect.size.width) , squareRect.origin.y + squareRect.size.height);
[pointPath moveToPoint:startPoint];
[pointPath addLineToPoint:middlePoint];
[pointPath addLineToPoint:endPoint];
[pointPath closePath];
if ( i != 0 ) {
// calculate the point for triangle
float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2) ) * 1.4 ;
float last_x1 = last_x + (inflexionWidth / 2) / distance * (x - last_x);
float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y);
float x1 = x - (inflexionWidth / 2) / distance * (x - last_x);
float y1 = y - (inflexionWidth / 2) / distance * (y - last_y);
[progressline moveToPoint:CGPointMake(last_x1, last_y1)];
[progressline addLineToPoint:CGPointMake(x1, y1)];
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)]];
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x1, y1)]];
}
last_x = x;
last_y = y;
} else {
if ( i != 0 ) {
[progressline addLineToPoint:CGPointMake(x, y)];
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
}
[progressline moveToPoint:CGPointMake(x, y)];
if(i != chartData.itemCount - 1){
[lineStartEndPointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
}
}
[linePointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
}
[pathPoints addObject:[linePointsArray copy]];
[pointsOfPath addObject:[lineStartEndPointsArray copy]];
}
}
#pragma mark - Set Chart Data
- (void)setChartData:(NSArray *)data
{
if (data != _chartData) {
// remove all shape layers before adding new ones
for (CALayer *layer in self.chartLineArray) {
[layer removeFromSuperlayer];
}
for (CALayer *layer in self.chartPointArray) {
[layer removeFromSuperlayer];
}
self.chartLineArray = [NSMutableArray arrayWithCapacity:data.count];
self.chartPointArray = [NSMutableArray arrayWithCapacity:data.count];
for (PNLineChartData *chartData in data) {
// create as many chart line layers as there are data-lines
CAShapeLayer *chartLine = [CAShapeLayer layer];
chartLine.lineCap = kCALineCapButt;
chartLine.lineJoin = kCALineJoinMiter;
chartLine.fillColor = [[UIColor whiteColor] CGColor];
chartLine.lineWidth = chartData.lineWidth;
chartLine.strokeEnd = 0.0;
[self.layer addSublayer:chartLine];
[self.chartLineArray addObject:chartLine];
// create point
CAShapeLayer *pointLayer = [CAShapeLayer layer];
pointLayer.strokeColor = [[chartData.color colorWithAlphaComponent:chartData.alpha]CGColor];
pointLayer.lineCap = kCALineCapRound;
pointLayer.lineJoin = kCALineJoinBevel;
pointLayer.fillColor = nil;
pointLayer.lineWidth = chartData.lineWidth;
[self.layer addSublayer:pointLayer];
[self.chartPointArray addObject:pointLayer];
}
_chartData = data;
[self prepareYLabelsWithData:data];
[self setNeedsDisplay];
}
}
-(void)prepareYLabelsWithData:(NSArray *)data
{
CGFloat yMax = 0.0f;
CGFloat yMin = MAXFLOAT;
NSMutableArray *yLabelsArray = [NSMutableArray new];
for (PNLineChartData *chartData in data) {
// create as many chart line layers as there are data-lines
for (NSUInteger i = 0; i < chartData.itemCount; i++) {
CGFloat yValue = chartData.getData(i).y;
[yLabelsArray addObject:[NSString stringWithFormat:@"%2f", yValue]];
yMax = fmaxf(yMax, yValue);
yMin = fminf(yMin, yValue);
}
}
// Min value for Y label
if (yMax < 5) {
yMax = 5.0f;
}
if (yMin < 0) {
yMin = 0.0f;
}
_yValueMin = _yFixedValueMin ? _yFixedValueMin : yMin ;
_yValueMax = _yFixedValueMax ? _yFixedValueMax : yMax + yMax / 10.0;
if (_showLabel) {
[self setYLabels:yLabelsArray];
}
}
#pragma mark - Update Chart Data
- (void)updateChartData:(NSArray *)data
{
_chartData = data;
[self prepareYLabelsWithData:data];
[self calculateChartPath:_chartPath andPointsPath:_pointPath andPathKeyPoints:_pathPoints andPathStartEndPoints:_endPointsOfPath];
for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) {
CAShapeLayer *chartLine = (CAShapeLayer *)self.chartLineArray[lineIndex];
CAShapeLayer *pointLayer = (CAShapeLayer *)self.chartPointArray[lineIndex];
UIBezierPath *progressline = [_chartPath objectAtIndex:lineIndex];
UIBezierPath *pointPath = [_pointPath objectAtIndex:lineIndex];
CABasicAnimation * pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
pathAnimation.fromValue = (id)chartLine.path;
pathAnimation.toValue = (id)[progressline CGPath];
pathAnimation.duration = 0.5f;
pathAnimation.autoreverses = NO;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[chartLine addAnimation:pathAnimation forKey:@"animationKey"];
CABasicAnimation * pointPathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
pointPathAnimation.fromValue = (id)pointLayer.path;
pointPathAnimation.toValue = (id)[pointPath CGPath];
pointPathAnimation.duration = 0.5f;
pointPathAnimation.autoreverses = NO;
pointPathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[pointLayer addAnimation:pointPathAnimation forKey:@"animationKey"];
chartLine.path = progressline.CGPath;
pointLayer.path = pointPath.CGPath;
}
}
#define IOS7_OR_LATER [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0
- (void)drawRect:(CGRect)rect
{
if (self.isShowCoordinateAxis) {
#warning modify
CGFloat yAxisOffset = 10.f;
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(ctx);
CGContextSetLineWidth(ctx, self.axisWidth);
CGContextSetStrokeColorWithColor(ctx, [self.axisColor CGColor]);
CGFloat xAxisWidth = CGRectGetWidth(rect) - _chartMargin / 2;
CGFloat yAxisHeight = _chartMargin + _chartCavanHeight;
// draw coordinate axis
CGContextMoveToPoint(ctx, _chartMargin + yAxisOffset, 0);
CGContextAddLineToPoint(ctx, _chartMargin + yAxisOffset, yAxisHeight);
CGContextAddLineToPoint(ctx, xAxisWidth, yAxisHeight);
CGContextStrokePath(ctx);
// draw y axis arrow
CGContextMoveToPoint(ctx, _chartMargin + yAxisOffset - 3, 6);
CGContextAddLineToPoint(ctx, _chartMargin + yAxisOffset, 0);
CGContextAddLineToPoint(ctx, _chartMargin + yAxisOffset + 3, 6);
CGContextStrokePath(ctx);
// draw x axis arrow
CGContextMoveToPoint(ctx, xAxisWidth - 6, yAxisHeight - 3);
CGContextAddLineToPoint(ctx, xAxisWidth, yAxisHeight);
CGContextAddLineToPoint(ctx, xAxisWidth - 6, yAxisHeight + 3);
CGContextStrokePath(ctx);
if (self.showLabel) {
// draw x axis separator
CGPoint point;
for (NSUInteger i = 0; i < [self.xLabels count]; i++) {
point = CGPointMake(2 * _chartMargin + (i * _xLabelWidth), _chartMargin + _chartCavanHeight);
CGContextMoveToPoint(ctx, point.x, point.y - 2);
CGContextAddLineToPoint(ctx, point.x, point.y);
CGContextStrokePath(ctx);
}
// draw y axis separator
CGFloat yStepHeight = _chartCavanHeight / _yLabelNum;
for (NSUInteger i = 0; i < [self.xLabels count]; i++) {
point = CGPointMake(_chartMargin + yAxisOffset, (_chartCavanHeight - i * yStepHeight + _yLabelHeight / 2));
CGContextMoveToPoint(ctx, point.x, point.y);
CGContextAddLineToPoint(ctx, point.x + 2, point.y);
CGContextStrokePath(ctx);
}
}
UIFont *font = [UIFont systemFontOfSize:11];
// draw y unit
if ([self.yUnit length]) {
CGFloat height = [PNLineChart sizeOfString:self.yUnit withWidth:30.f font:font].height;
CGRect drawRect = CGRectMake(_chartMargin + 10 + 5, 0, 30.f, height);
[self drawTextInContext:ctx text:self.yUnit inRect:drawRect font:font];
}
// draw x unit
if ([self.xUnit length]) {
CGFloat height = [PNLineChart sizeOfString:self.xUnit withWidth:30.f font:font].height;
CGRect drawRect = CGRectMake(CGRectGetWidth(rect) - _chartMargin + 5, _chartMargin + _chartCavanHeight - height / 2, 25.f, height);
[self drawTextInContext:ctx text:self.xUnit inRect:drawRect font:font];
}
}
[super drawRect:rect];
}
#pragma mark private methods
- (void)setupDefaultValues
{
// Initialization code
self.backgroundColor = [UIColor whiteColor];
self.clipsToBounds = YES;
self.chartLineArray = [NSMutableArray new];
_showLabel = YES;
_pathPoints = [[NSMutableArray alloc] init];
_endPointsOfPath = [[NSMutableArray alloc] init];
self.userInteractionEnabled = YES;
_yLabelNum = 5.0;
_yLabelHeight = [[[[PNChartLabel alloc] init] font] pointSize];
_chartMargin = 40;
_chartCavanWidth = self.frame.size.width - _chartMargin * 2;
_chartCavanHeight = self.frame.size.height - _chartMargin * 2;
// Coordinate Axis Default Values
_showCoordinateAxis = NO;
_axisColor = [UIColor colorWithRed:0.4f green:0.4f blue:0.4f alpha:1.f];
_axisWidth = 1.f;
}
#pragma mark - tools
+ (CGSize)sizeOfString:(NSString *)text withWidth:(float)width font:(UIFont *)font
{
NSInteger ch;
CGSize size = CGSizeMake(width, MAXFLOAT);
if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
NSDictionary *tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
size = [text boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:tdic
context:nil].size;
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
#pragma clang diagnostic pop
}
ch = size.height;
return size;
}
- (void)drawTextInContext:(CGContextRef )ctx text:(NSString *)text inRect:(CGRect)rect font:(UIFont *)font
{
if (IOS7_OR_LATER) {
NSMutableParagraphStyle *priceParagraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
priceParagraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
priceParagraphStyle.alignment = NSTextAlignmentLeft;
[text drawInRect:rect
withAttributes:@{ NSParagraphStyleAttributeName:priceParagraphStyle, NSFontAttributeName:font }];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[text drawInRect:rect
withFont:font
lineBreakMode:NSLineBreakByTruncatingTail
alignment:NSTextAlignmentLeft];
#pragma clang diagnostic pop
}
}
- (UIView*) getLegendWithMaxWidth:(CGFloat)mWidth{
if ([self.chartData count] < 1) {
return nil;
}
/* This is a short line that refers to the chart data */
CGFloat legendLineWidth = 40;
/* x and y are the coordinates of the starting point of each legend item */
CGFloat x = 0;
CGFloat y = 0;
/* accumulated width and height */
CGFloat totalWidth = 0;
CGFloat totalHeight = 0;
NSMutableArray *legendViews = [[NSMutableArray alloc] init];
/* Determine the max width of each legend item */
CGFloat maxLabelWidth = self.legendStyle == PNLegendItemStyleStacked ? (mWidth - legendLineWidth) : (mWidth / [self.chartData count] - legendLineWidth);
/* this is used when labels wrap text and the line
* should be in the middle of the first row */
CGFloat singleRowHeight = [PNLineChart sizeOfString:@"Test"
withWidth:MAXFLOAT
font:[UIFont systemFontOfSize:self.legendFontSize]].height;
for (PNLineChartData *pdata in self.chartData) {
/* Expected label size*/
CGSize labelsize = [PNLineChart sizeOfString:pdata.dataTitle
withWidth:maxLabelWidth
font:[UIFont systemFontOfSize:self.legendFontSize]];
/* draw lines */
/* If there is inflection decorator, the line is composed of two lines
* and this is the space that separates two lines in order to put inflection
* decorator */
CGFloat inflexionWidthSpacer = pdata.inflexionPointStyle == PNLineChartPointStyleTriangle ? pdata.inflexionPointWidth / 2 : pdata.inflexionPointWidth;
CGFloat halfLineLength;
if (pdata.inflexionPointStyle != PNLineChartPointStyleNone) {
halfLineLength = (legendLineWidth * 0.8 - inflexionWidthSpacer)/2;
}else{
halfLineLength = legendLineWidth * 0.8;
}
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(x + legendLineWidth * 0.1, y + (singleRowHeight - pdata.lineWidth) / 2, halfLineLength, pdata.lineWidth)];
line.backgroundColor = pdata.color;
line.alpha = pdata.alpha;
[legendViews addObject:line];
if (pdata.inflexionPointStyle != PNLineChartPointStyleNone) {
line = [[UIView alloc] initWithFrame:CGRectMake(x + legendLineWidth * 0.1 + halfLineLength + inflexionWidthSpacer, y + (singleRowHeight - pdata.lineWidth) / 2, halfLineLength, pdata.lineWidth)];
line.backgroundColor = pdata.color;
line.alpha = pdata.alpha;
[legendViews addObject:line];
}
// Add inflexion type
[legendViews addObject:[self drawInflexion:pdata.inflexionPointWidth
center:CGPointMake(x + legendLineWidth / 2, y + singleRowHeight / 2)
strokeWidth:pdata.lineWidth
inflexionStyle:pdata.inflexionPointStyle
andColor:pdata.color
andAlpha:pdata.alpha]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x + legendLineWidth, y, maxLabelWidth, labelsize.height)];
label.text = pdata.dataTitle;
label.font = [UIFont systemFontOfSize:self.legendFontSize];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
x += self.legendStyle == PNLegendItemStyleStacked ? 0 : labelsize.width + legendLineWidth;
y += self.legendStyle == PNLegendItemStyleStacked ? labelsize.height : 0;
totalWidth = self.legendStyle == PNLegendItemStyleStacked ? fmaxf(totalWidth, labelsize.width + legendLineWidth) : totalWidth + labelsize.width + legendLineWidth;
totalHeight = self.legendStyle == PNLegendItemStyleStacked ? fmaxf(totalHeight, labelsize.height) : totalHeight + labelsize.height;
[legendViews addObject:label];
}
UIView *legend = [[UIView alloc] initWithFrame:CGRectMake(0, 0, totalWidth, totalHeight)];
for (UIView* v in legendViews) {
[legend addSubview:v];
}
return legend;
}
- (UIImageView*)drawInflexion:(CGFloat)size center:(CGPoint)center strokeWidth: (CGFloat)sw inflexionStyle:(PNLineChartPointStyle)type andColor:(UIColor*)color andAlpha:(CGFloat) alfa
{
//Make the size a little bigger so it includes also border stroke
CGSize aSize = CGSizeMake(size + sw, size + sw);
UIGraphicsBeginImageContextWithOptions(aSize, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
if (type == PNLineChartPointStyleCircle) {
CGContextAddArc(context, (size + sw)/2, (size + sw) / 2, size/2, 0, M_PI*2, YES);
}else if (type == PNLineChartPointStyleSquare){
CGContextAddRect(context, CGRectMake(sw/2, sw/2, size, size));
}else if (type == PNLineChartPointStyleTriangle){
CGContextMoveToPoint(context, sw/2, size + sw/2);
CGContextAddLineToPoint(context, size + sw/2, size + sw/2);
CGContextAddLineToPoint(context, size/2 + sw/2, sw/2);
CGContextAddLineToPoint(context, sw/2, size + sw/2);
CGContextClosePath(context);
}
//Set some stroke properties
CGContextSetLineWidth(context, sw);
CGContextSetAlpha(context, alfa);
CGContextSetStrokeColorWithColor(context, color.CGColor);
//Finally draw
CGContextDrawPath(context, kCGPathStroke);
//now get the image from the context
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//// Translate origin
CGFloat originX = center.x - (size + sw) / 2.0;
CGFloat originY = center.y - (size + sw) / 2.0;
UIImageView *squareImageView = [[UIImageView alloc]initWithImage:squareImage];
[squareImageView setFrame:CGRectMake(originX, originY, size + sw, size + sw)];
return squareImageView;
}
@end
| {
"content_hash": "ec04c1e279986c1845aaf2b70a40f980",
"timestamp": "",
"source": "github",
"line_count": 888,
"max_line_length": 206,
"avg_line_length": 39.431306306306304,
"alnum_prop": 0.6136798514922176,
"repo_name": "wongzigii/Colo",
"id": "85c6f0b6329bfff98b806c7b039d56a36241f6cc",
"size": "35017",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Pods/PNChart/PNChart/PNLineChart.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "1192"
},
{
"name": "Objective-C",
"bytes": "119713"
},
{
"name": "Ruby",
"bytes": "240"
}
],
"symlink_target": ""
} |
/* jshint devel: true, indent: 2, undef: true, unused: strict, strict: false, eqeqeq: true, trailing: true, curly: true, latedef: true, quotmark: single, maxlen: 120 */
/* global define, $, _ */
define('views/submissions/edit',
[
'backbone',
'chimera/template',
'chimera/page',
'chimera/global',
'medium',
'marked',
'collections/filters',
'collections/folders'
],
function (
Backbone,
Template,
Page,
Chi,
MediumEditor,
marked,
FiltersCollection,
FoldersCollection
) {
var EditSubmissionView = Backbone.View.extend({
el: '#content',
template: new Template('submissions/edit').base(),
events: {
'click #publish' : 'publish',
'submit #edit-submission' : 'save'
},
initialize: function () {
this.filters = new FiltersCollection();
this.filters.url = Chi.currentProfile.get('filters_url');
this.listenTo(this.filters, 'reset', this.renderFilters);
this.folders = new FoldersCollection();
this.folders.url = Chi.currentProfile.get('submission_folders_url');
this.listenTo(this.folders, 'reset', this.renderFolders);
},
render: function () {
var submissions = [];
if (this.model.get('type') === 'SubmissionGroup') {
_.each(this.model.get('submissions'), function (submission, index) {
if (index > 0) {
submissions.push(submission);
}
}, this);
}
Page.changeTo(this.template({
submission: this.model.toJSON(),
submissions: submissions,
marked: marked
}), {
class: 'profile_submissions edit'
});
// Description
new MediumEditor('.editable', {
buttons: ['bold', 'italic', 'underline', 'strikethrough', 'anchor'],
buttonLabels: {
'anchor' : 'link'
},
placeholder: 'Start typing the description'
});
this.title = $('#submission_title');
this.description = $('#description_editable');
this.tags = $('#submission_tags');
this.filterList = $('#filter-list');
this.filters.fetch({reset: true});
this.folderList = $('#folder-list');
this.folders.fetch({reset: true});
},
renderFilters: function () {
var header = $('<p/>');
if (this.filters.length > 0) {
header.html('Groups');
this.filterList.append(header);
}
this.filters.each(function (filter) {
var label = $('<label/>'),
input = $('<input />'),
elemId = 'filter_ids_' + filter.id;
label.attr('for', elemId);
input.attr({
id: elemId,
name: 'submission[filter_ids][]',
type: 'checkbox',
value: filter.id
});
label.append(input);
label.append(' ' + filter.get('name'));
if (this.model.get('filters') && this.model.get('filters').indexOf(parseInt(filter.id, 10)) > -1) {
input.prop('checked', true);
}
this.filterList.append(label);
}, this);
},
renderFolders: function () {
var header = $('<p/>');
this.folderSelect = $('<select name="submission[submission_folder_id]" />');
if (this.folders.length > 0) {
header.html('Folder');
this.folderList.append(header);
this.folderList.append(this.folderSelect);
this.folderSelect.append($('<option/>'));
}
this.folders.each(function (folder) {
var option = $('<option/>');
option.val(folder.id);
option.html(folder.get('name'));
this.folderSelect.append(option);
}, this);
},
save: function (e) {
e.preventDefault();
this.saveSubmission(function () {
Chi.Router.navigate('/unpublished', {trigger: true});
});
},
publish: function (e) {
e.preventDefault();
this.saveSubmission(function () {
this.model.publish();
Chi.Router.navigate('/submissions/' + this.model.id, {trigger: true});
}.bind(this));
},
saveSubmission: function (callback) {
var filterIds = _.map($('#filter-list input'), function (filterInput) {
if (filterInput.checked) {
return filterInput.value;
}
});
filterIds = _.compact(filterIds);
var formData = {
title: this.title.val(),
description: this.description.html(),
tags: this.parseTags(this.tags.val()),
filter_ids: filterIds
};
if (this.folderSelect) {
formData.submission_folder_ids = [this.folderSelect.val()];
}
this.model.set(formData);
this.model.url = '/profiles/' + Chi.currentProfile.id + '/submissions/' + this.model.id;
this.model.save(null, {
success: callback
});
},
// Takes a string of tags and returns an array.
parseTags: function (tagString) {
if (tagString.trim() === '') {
return [];
}
var tags = tagString.replace(/#/g, '');
if (tags.match(',') !== null) {
tags = tags.split(',');
} else {
tags = tags.split(' ');
}
return _.map(tags, function (tag) {
return tag.trim();
});
}
});
return EditSubmissionView;
});
| {
"content_hash": "12ddfcfb5de6b5847f2a435cd2812506",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 168,
"avg_line_length": 29.63917525773196,
"alnum_prop": 0.5055652173913043,
"repo_name": "chimerao/web-frontend",
"id": "d3c860f6aae200b2615977b3be733894aae794f5",
"size": "5750",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/js/views/submissions/edit.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "62044"
},
{
"name": "HTML",
"bytes": "3901"
},
{
"name": "JavaScript",
"bytes": "1672174"
},
{
"name": "Ruby",
"bytes": "5558"
}
],
"symlink_target": ""
} |
package vsb.fou.kladd.serialization;
@SuppressWarnings("serial")
public class VsbSubSerializable extends VsbSuperSerializable {
private String b;
public void setB(String b) {
this.b = b;
}
public String getB() {
return b;
}
}
| {
"content_hash": "5c7fcdd405f3edb37bc9a66cd5df4b18",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 62,
"avg_line_length": 17.733333333333334,
"alnum_prop": 0.650375939849624,
"repo_name": "vegbye/vsb-fou-pom",
"id": "1ad94f72e26190b49ba038e942353b0d68e82b78",
"size": "266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vsb-fou-kladd/src/test/java/vsb/fou/kladd/serialization/VsbSubSerializable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "214896"
}
],
"symlink_target": ""
} |
"""
This code sample demonstrates how to write records in pending mode
using the low-level generated client for Python.
"""
from google.cloud import bigquery_storage_v1
from google.cloud.bigquery_storage_v1 import types
from google.cloud.bigquery_storage_v1 import writer
from google.protobuf import descriptor_pb2
# If you update the customer_record.proto protocol buffer definition, run:
#
# protoc --python_out=. customer_record.proto
#
# from the samples/snippets directory to generate the customer_record_pb2.py module.
from . import customer_record_pb2
def create_row_data(row_num: int, name: str):
row = customer_record_pb2.CustomerRecord()
row.row_num = row_num
row.customer_name = name
return row.SerializeToString()
def append_rows_pending(project_id: str, dataset_id: str, table_id: str):
"""Create a write stream, write some sample data, and commit the stream."""
write_client = bigquery_storage_v1.BigQueryWriteClient()
parent = write_client.table_path(project_id, dataset_id, table_id)
write_stream = types.WriteStream()
# When creating the stream, choose the type. Use the PENDING type to wait
# until the stream is committed before it is visible. See:
# https://cloud.google.com/bigquery/docs/reference/storage/rpc/google.cloud.bigquery.storage.v1#google.cloud.bigquery.storage.v1.WriteStream.Type
write_stream.type_ = types.WriteStream.Type.PENDING
write_stream = write_client.create_write_stream(
parent=parent, write_stream=write_stream
)
stream_name = write_stream.name
# Create a template with fields needed for the first request.
request_template = types.AppendRowsRequest()
# The initial request must contain the stream name.
request_template.write_stream = stream_name
# So that BigQuery knows how to parse the serialized_rows, generate a
# protocol buffer representation of your message descriptor.
proto_schema = types.ProtoSchema()
proto_descriptor = descriptor_pb2.DescriptorProto()
customer_record_pb2.CustomerRecord.DESCRIPTOR.CopyToProto(proto_descriptor)
proto_schema.proto_descriptor = proto_descriptor
proto_data = types.AppendRowsRequest.ProtoData()
proto_data.writer_schema = proto_schema
request_template.proto_rows = proto_data
# Some stream types support an unbounded number of requests. Construct an
# AppendRowsStream to send an arbitrary number of requests to a stream.
append_rows_stream = writer.AppendRowsStream(write_client, request_template)
# Create a batch of row data by appending proto2 serialized bytes to the
# serialized_rows repeated field.
proto_rows = types.ProtoRows()
proto_rows.serialized_rows.append(create_row_data(1, "Alice"))
proto_rows.serialized_rows.append(create_row_data(2, "Bob"))
# Set an offset to allow resuming this stream if the connection breaks.
# Keep track of which requests the server has acknowledged and resume the
# stream at the first non-acknowledged message. If the server has already
# processed a message with that offset, it will return an ALREADY_EXISTS
# error, which can be safely ignored.
#
# The first request must always have an offset of 0.
request = types.AppendRowsRequest()
request.offset = 0
proto_data = types.AppendRowsRequest.ProtoData()
proto_data.rows = proto_rows
request.proto_rows = proto_data
response_future_1 = append_rows_stream.send(request)
# Send another batch.
proto_rows = types.ProtoRows()
proto_rows.serialized_rows.append(create_row_data(3, "Charles"))
# Since this is the second request, you only need to include the row data.
# The name of the stream and protocol buffers DESCRIPTOR is only needed in
# the first request.
request = types.AppendRowsRequest()
proto_data = types.AppendRowsRequest.ProtoData()
proto_data.rows = proto_rows
request.proto_rows = proto_data
# Offset must equal the number of rows that were previously sent.
request.offset = 2
response_future_2 = append_rows_stream.send(request)
print(response_future_1.result())
print(response_future_2.result())
# Shutdown background threads and close the streaming connection.
append_rows_stream.close()
# A PENDING type stream must be "finalized" before being committed. No new
# records can be written to the stream after this method has been called.
write_client.finalize_write_stream(name=write_stream.name)
# Commit the stream you created earlier.
batch_commit_write_streams_request = types.BatchCommitWriteStreamsRequest()
batch_commit_write_streams_request.parent = parent
batch_commit_write_streams_request.write_streams = [write_stream.name]
write_client.batch_commit_write_streams(batch_commit_write_streams_request)
print(f"Writes to stream: '{write_stream.name}' have been committed.")
# [END bigquerystorage_append_rows_pending]
| {
"content_hash": "370b150bee32f12aa89b9356581759e2",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 149,
"avg_line_length": 41.705882352941174,
"alnum_prop": 0.7386661293572436,
"repo_name": "googleapis/python-bigquery-storage",
"id": "af780ffa5b92dcce761f75b04540585e6a19f0c1",
"size": "5585",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/snippets/append_rows_pending.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "1136897"
},
{
"name": "Shell",
"bytes": "30690"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("Neighbour War")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Neighbour War")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("0e0de20f-1981-4f84-8c6e-e60573344722")]
// 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 Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "f9357d36a3952de962301928520092ea",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.861111111111114,
"alnum_prop": 0.7441029306647605,
"repo_name": "mitaka00/SoftUni",
"id": "ab3443a1e9f4cecdf4a7042d4098dfe0899205fd",
"size": "1402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Programing Fundamentals/6-Conditional Statment and Loops Exc/Neighbour War/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "406"
},
{
"name": "Batchfile",
"bytes": "1402"
},
{
"name": "C#",
"bytes": "569621"
},
{
"name": "CSS",
"bytes": "559722"
},
{
"name": "HTML",
"bytes": "377215"
},
{
"name": "Handlebars",
"bytes": "52925"
},
{
"name": "Java",
"bytes": "20869"
},
{
"name": "JavaScript",
"bytes": "515839"
},
{
"name": "PHP",
"bytes": "173815"
},
{
"name": "Pug",
"bytes": "7460"
},
{
"name": "SCSS",
"bytes": "11519"
},
{
"name": "Twig",
"bytes": "12672"
},
{
"name": "TypeScript",
"bytes": "121095"
}
],
"symlink_target": ""
} |
public class Exception_1 {
public <T> Exception_1(T actual, T matcher) {
}
public Exception_1(String message) {
}
}
| {
"content_hash": "c3f4989757db7b99f80dd52ffd6e1242",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 49,
"avg_line_length": 19,
"alnum_prop": 0.6165413533834586,
"repo_name": "som-snytt/dotty",
"id": "6ee8500775ffc753eddb1e7b65574d3f7a4149b7",
"size": "133",
"binary": false,
"copies": "4",
"ref": "refs/heads/issue/update-commandlineparser",
"path": "tests/run/i7990/Exception_1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10592"
},
{
"name": "HTML",
"bytes": "26510"
},
{
"name": "Java",
"bytes": "251194"
},
{
"name": "JavaScript",
"bytes": "3691"
},
{
"name": "Scala",
"bytes": "13665316"
},
{
"name": "Shell",
"bytes": "12008"
},
{
"name": "TypeScript",
"bytes": "63197"
}
],
"symlink_target": ""
} |
layout: organization
category: local
title: Brooklyn Animal Resource Coalition
impact_area: Environment
keywords:
- Animals
location_services: Brooklyn
location_offices: Brooklyn
website: www.barcshelter.org
description: |
We are a no-kill animal shelter that helps and rescues animals from the streets of New York City.
mission: |
BARC's mission is to provide safe haven for homeless animals and find permanent, loving homes for these animals. The animals in our care receive quality food, shelter, and medical attention. We meet the needs of homeless animals through the assistance of dedicated volunteers, revenues generated from the success of our pet supply business, and from private donations.
cash_grants: yes
grants:
- |
Students can help purchase cleaning supplies as well as food and sleeping items for our dogs and cats. Also, students can help with the animals' medical supplies, which can be really add up. Then the students can come and help clean the animals living quarters and give them love and attention.
service_opp: yes
services:
- |
We can set up tours and volunteer helping hands to socialize and clean the animals' living environment. We can also arrange dog walking for the students with proper supervisors.
learn:
- Give students a tour of our office and facilities
cont_relationship:
- Help students develop a community service project with us
- Help students tell local newspapers and media about their grant and/or project with us
salutation: Mr.
first_name: Robert
last_name: Vazquez
title_contact_person: kennel supervisor
city: Brooklyn
state: ny
address: |
253 Wythe Avenue
Brooklyn ny 11249
lat: 40.716301
lng: -73.963896
phone: 7184867489
ext:
fax:
email: info@barcshelter.org
preferred_contact: email
contact_person_intro: |
My name is Robert Vazquez, I have been the Kennel supervisor, as well as the dog behaviorist, trainer and caretaker. I have been at BARC the last 11 years and have helped over 1000 dogs and cats find homes in Brooklyn. I also help educate the public about the necessity of adopting from a no-kill animal shelter.
---
We are a no-kill animal shelter that helps and rescues animals from the streets of New York City. | {
"content_hash": "355fd5c3a98821dc528a1456544558aa",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 370,
"avg_line_length": 42.73076923076923,
"alnum_prop": 0.7844284428442845,
"repo_name": "flipside-org/penny-harvest",
"id": "7e3f5dcf2d341a58d43d04420ba6c5e1f7668a7b",
"size": "2226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/organizations/2015-01-12-OFP50.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "392900"
},
{
"name": "JavaScript",
"bytes": "30565"
}
],
"symlink_target": ""
} |
<?php
namespace BingAds\CampaignManagement;
/**
* This feature is currently in pilot and will be generally available soon.
*
* @link http://msdn.microsoft.com/en-us/library/dn913121(v=msads.90).aspx UpdateCampaignCriterions Response Object
*
* @uses BatchError
* @used-by BingAdsCampaignManagementService::UpdateCampaignCriterions
*/
final class UpdateCampaignCriterionsResponse
{
/**
* An array of BatchError objects that contain details for any list items that were not successfully updated.
*
* @var BatchError[]
*/
public $PartialErrors;
}
| {
"content_hash": "7cce8ca652d7debcf0426a24109b1337",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 115,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.7383820998278829,
"repo_name": "onema/bing-ads-sdk-php",
"id": "87de46d298af5620c79e87ae5cfda022b602d203",
"size": "581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/CampaignManagement/UpdateCampaignCriterionsResponse.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "79806"
},
{
"name": "HTML",
"bytes": "20150"
},
{
"name": "PHP",
"bytes": "696385"
}
],
"symlink_target": ""
} |
package com.belling.base.service.impl;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import com.belling.base.exception.MapperException;
import com.belling.base.mapper.BaseMapper;
import com.belling.base.model.Pagination;
import com.belling.base.model.PersistentObject;
import com.belling.base.service.BaseService;
import com.belling.base.util.LoggerUtils;
/**
* Service基类,实现了数据的CRUD
*
* @param <DAO>
* @param <T>
* @param <ID>
* @author Sunny
*/
public abstract class BaseServiceImpl<Mapper extends BaseMapper<T, ID>, T extends PersistentObject, ID extends Serializable>
implements BaseService<T, ID> {
/**
* 由子类注入实体DAO
*/
protected Mapper mapper;
public abstract void setMapper(Mapper mapper);
/**
* 查询所有分页
*
* @param p
* @return
*/
public Pagination<T> findByAllPagination(Pagination<T> p) {
mapper.findByAll(p);
return p;
}
/**
* 通过主键查询实体
*
* @param PK pk
* @return T
*/
public T get(ID pk) {
return mapper.get(pk);
}
/**
* 通过主键集合查询实体
*
* @param List
* <PK> pks
* @return List<T>
*/
public List<T> get(Collection<ID> pks) {
List<T> list = new ArrayList<T>(pks.size());
for (ID pk : pks) {
list.add(get(pk));
}
return list;
}
/**
* 插入/更新实体
*
* @param T t
*
*/
public void save(T t) {
if (t.getId() == null) {
mapper.insert(t);
} else {
mapper.update(t);
}
}
/**
* 插入/更新实体集合
*
* @param List <T> ts
*/
public void save(Collection<T> ts) {
for (T t : ts) {
save(t);
}
}
/**
* 更新实体
*
* @param T t
*/
public void update(T t) {
verifyRows(mapper.update(t), 1, "数据库更新失败");
}
/**
* 更新实体集合
*
* @param List
* <T> ts
*/
public void update(Collection<T> ts) {
for (T t : ts) {
update(t);
}
}
/**
* 删除实体
*
* @param T
* t
*/
@SuppressWarnings("unchecked")
public void delete(T t) {
deleteById((ID) t.getId());
}
/**
* 删除实体集合
*
* @param List
* <T> ts
*/
public void delete(Collection<T> ts) {
for (T t : ts) {
delete(t);
}
}
/**
* 通过主键删除实体
*
* @param PK pk
* @return T
*/
public void deleteById(ID id) {
deleteById(Arrays.asList(id));
}
/**
* 通过主键集合删除实体 注:这里别把List改为Collection,会导致覆盖方法的List<ID>调用不到
*
* @param List <PK> pks
* @return List<T>
*/
public void deleteById(List<ID> idList) {
verifyRows(mapper.deleteById(idList), idList.size(), "数据库删除失败");
}
/**
* 为高并发环境出现的更新和删除操作,验证更新数据库记录条数
*
* @param updateRows
* @param rows
* @param message
*/
protected void verifyRows(int updateRows, int rows, String message) {
if (updateRows != rows) {
MapperException e = new MapperException(message);
LoggerUtils.fmtError(BaseService.class, e, "need update is {}, but real update rows is {}.", rows, updateRows);
throw e;
}
}
/**
* 集合排序
*
* 对List对象按照某个成员变量进行排序
*
* @param list List对象
* @param sortField 排序的属性名称
* @param sortMode 排序方式:ASC,DESC 任选其一
*/
@SuppressWarnings("hiding")
protected synchronized <T> void sortList(List<T> list, final String sortField, final String sortMode) {
Collections.sort(list, new Comparator<T>() {
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@SuppressWarnings("rawtypes")
@Override
public int compare(T o1, T o2) {
try {
Class clazz = o1.getClass();
Field field = clazz.getDeclaredField(sortField); // 获取成员变量
field.setAccessible(true); // 设置成可访问状态
String typeName = field.getType().getName().toLowerCase(); // 转换成小写
Object v1 = field.get(o1); // 获取field的值
Object v2 = field.get(o2); // 获取field的值
boolean ASC_order = (sortMode == null || "ASC".equalsIgnoreCase(sortMode));
// 判断字段数据类型,并比较大小
if (typeName.endsWith("string")) {
String value1 = v1.toString();
String value2 = v2.toString();
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("short")) {
Short value1 = Short.parseShort(v1.toString());
Short value2 = Short.parseShort(v2.toString());
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("byte")) {
Byte value1 = Byte.parseByte(v1.toString());
Byte value2 = Byte.parseByte(v2.toString());
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("char")) {
Integer value1 = (int) (v1.toString().charAt(0));
Integer value2 = (int) (v2.toString().charAt(0));
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("int") || typeName.endsWith("integer")) {
Integer value1 = Integer.parseInt(v1.toString());
Integer value2 = Integer.parseInt(v2.toString());
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("long")) {
Long value1 = Long.parseLong(v1.toString());
Long value2 = Long.parseLong(v2.toString());
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("float")) {
Float value1 = Float.parseFloat(v1.toString());
Float value2 = Float.parseFloat(v2.toString());
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("double")) {
Double value1 = Double.parseDouble(v1.toString());
Double value2 = Double.parseDouble(v2.toString());
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("boolean")) {
Boolean value1 = Boolean.parseBoolean(v1.toString());
Boolean value2 = Boolean.parseBoolean(v2.toString());
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("date")) {
Date value1 = (Date) (v1);
Date value2 = (Date) (v2);
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else if (typeName.endsWith("timestamp")) {
Timestamp value1 = (Timestamp) (v1);
Timestamp value2 = (Timestamp) (v2);
return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
} else {
// 调用对象的compareTo()方法比较大小
Method method = field.getType().getDeclaredMethod("compareTo", new Class[] { field.getType() });
method.setAccessible(true); // 设置可访问权限
int result = (Integer) method.invoke(v1, new Object[] { v2 });
return ASC_order ? result : result * (-1);
}
} catch (Exception e) {
String err = e.getLocalizedMessage();
System.out.println(err);
e.printStackTrace();
}
return 0; // 未知类型,无法比较大小
}
});
}
}
| {
"content_hash": "b2feb8938d88c8441b03cc7ebb95d427",
"timestamp": "",
"source": "github",
"line_count": 275,
"max_line_length": 124,
"avg_line_length": 25.52,
"alnum_prop": 0.6337988030777999,
"repo_name": "liuzongwen1/mss",
"id": "ec37df55f01113903d1071bb3059e9e808e7c307",
"size": "7544",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/belling/base/service/impl/BaseServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "356604"
},
{
"name": "FreeMarker",
"bytes": "127438"
},
{
"name": "Java",
"bytes": "1916630"
}
],
"symlink_target": ""
} |
import * as firebase from "firebase"
| {
"content_hash": "77ed8871ac685deb98241e300f04c026",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 36,
"avg_line_length": 13,
"alnum_prop": 0.717948717948718,
"repo_name": "wind85/waterandboards",
"id": "6f81f080802019c0bcba3c198bdba07d575feb7b",
"size": "39",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/auth/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "45701"
},
{
"name": "JavaScript",
"bytes": "70405"
},
{
"name": "Python",
"bytes": "1373"
}
],
"symlink_target": ""
} |
This directory contains the contiki driver for the sensors (light, humidity and temperature sensor) available on the
NXP DR1175 board. This board is part of the NXP JN516X Evaluation Kit (see http://www.nxp.com/documents/leaflet/75017368.pdf).
The dr1175 sensor code interfaces to the contiki `core/lib/sensors.c` framework.
The code is specificaly for the JN516X platform, because it makes use of the platform\DK4 libraries
of this JN516X SDK.
`examples/jn516x/rpl/coap-dr1175-node.c` shows an example on using this contiki driver.
Mapping of LEDs on JN516x DR1175/DR1174:
leds.h: led on DR1175/DR1174:
DR1174+DR1175:
LEDS_RED Red led in RGB-led with level control on DR1175
LEDS_GREEN Green led in RGB-led with level control on DR1175
LEDS_BLUE Blue led in RGB-led with level control on DR1175
LEDS_WHITE White power led with level control on DR1175
LEDS_GP0 LEDS D3 on DR1174
LEDS_GP1 LEDS D6 on DR1174
Note: LEDS_GPx and LEDS_WHITE definitions included in leds.h via platform-conf.h
| {
"content_hash": "0c37745139588d1f7617d736b02a6698",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 127,
"avg_line_length": 59.833333333333336,
"alnum_prop": 0.7325905292479109,
"repo_name": "miarcompanies/sdn-wise-contiki",
"id": "232e34768df583eec3bee96ebf3dc766cc2aa408",
"size": "1077",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "contiki/platform/jn516x/dev/dr1175/README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "150953"
},
{
"name": "Awk",
"bytes": "95"
},
{
"name": "Batchfile",
"bytes": "56"
},
{
"name": "C",
"bytes": "19590553"
},
{
"name": "C++",
"bytes": "1232938"
},
{
"name": "CSS",
"bytes": "10705"
},
{
"name": "GDB",
"bytes": "212"
},
{
"name": "Gnuplot",
"bytes": "1671"
},
{
"name": "HTML",
"bytes": "13655"
},
{
"name": "Java",
"bytes": "2862829"
},
{
"name": "JavaScript",
"bytes": "20835"
},
{
"name": "Makefile",
"bytes": "2349582"
},
{
"name": "Objective-C",
"bytes": "278368"
},
{
"name": "Perl",
"bytes": "97819"
},
{
"name": "Python",
"bytes": "617825"
},
{
"name": "Shell",
"bytes": "17305"
},
{
"name": "XSLT",
"bytes": "4947"
}
],
"symlink_target": ""
} |
FactoryGirl.define do
factory :organisation do
sequence(:api_id) { |n| "hmrc#{n}" }
title "HM Revenue & Customs"
format "Ministerial department"
slug "hmrc"
abbreviation "HMRC"
govuk_status "live"
web_url "https://www.gov.uk/government/organisations/hm-revenue-customs"
logo_formatted_name "HM Revenue & Customs"
organisation_brand_colour_class_name "hm-revenue-customs"
organisation_logo_type_class_name "hmrc"
api_updated_at "2013-08-22T11:02:18+01:00"
end
end
| {
"content_hash": "2854c9c029949aac3939ef492c9d80b8",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 76,
"avg_line_length": 34.06666666666667,
"alnum_prop": 0.6947162426614482,
"repo_name": "gds-attic/content-planner",
"id": "ea2bdbfd173f4ee9b5dcb64fb14428358e5cb2c5",
"size": "581",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spec/factories/organisations.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34495"
},
{
"name": "HTML",
"bytes": "34219"
},
{
"name": "JavaScript",
"bytes": "4084"
},
{
"name": "Ruby",
"bytes": "181325"
},
{
"name": "Shell",
"bytes": "262"
}
],
"symlink_target": ""
} |
package browser
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
)
// Stdout is the io.Writer to which executed commands write standard output.
var Stdout io.Writer = os.Stdout
// Stderr is the io.Writer to which executed commands write standard error.
var Stderr io.Writer = os.Stderr
// OpenFile opens new browser window for the file path.
func OpenFile(path string) error {
path, err := filepath.Abs(path)
if err != nil {
return err
}
return OpenURL("file://" + path)
}
// OpenReader consumes the contents of r and presents the
// results in a new browser window.
func OpenReader(r io.Reader) error {
f, err := ioutil.TempFile("", "browser")
if err != nil {
return fmt.Errorf("browser: could not create temporary file: %v", err)
}
if _, err := io.Copy(f, r); err != nil {
f.Close()
return fmt.Errorf("browser: caching temporary file failed: %v", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("browser: caching temporary file failed: %v", err)
}
oldname := f.Name()
newname := oldname + ".html"
if err := os.Rename(oldname, newname); err != nil {
return fmt.Errorf("browser: renaming temporary file failed: %v", err)
}
return OpenFile(newname)
}
// OpenURL opens a new browser window pointing to url.
func OpenURL(url string) error {
return openBrowser(url)
}
func runCmd(prog string, args ...string) error {
cmd := exec.Command(prog, args...)
cmd.Stdout = Stdout
cmd.Stderr = Stderr
setFlags(cmd)
return cmd.Run()
}
| {
"content_hash": "098de4d3f88479f903e7a416b82f4f70",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 76,
"avg_line_length": 24.883333333333333,
"alnum_prop": 0.6831882116543871,
"repo_name": "datawire/ambassador",
"id": "3e5969064258e8708c794153f90c0f9c6f294215",
"size": "1658",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "vendor/github.com/pkg/browser/browser.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "20990"
},
{
"name": "Go",
"bytes": "564752"
},
{
"name": "HTML",
"bytes": "25150"
},
{
"name": "JavaScript",
"bytes": "32368"
},
{
"name": "Makefile",
"bytes": "113905"
},
{
"name": "Python",
"bytes": "1158187"
},
{
"name": "Shell",
"bytes": "188832"
}
],
"symlink_target": ""
} |
package com.gmail.thelimeglass.Scoreboards;
import org.bukkit.event.Event;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.eclipse.jdt.annotation.Nullable;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
public class ExprScoreObjective extends SimpleExpression<Objective>{
//[the] (score[ ][board]|[skellett[ ]]board) objective (from|of) score %score%
//[the] (score[ ][board]|[skellett[ ]]board) %score%'s scores objective
private Expression<Score> score;
@Override
public Class<? extends Objective> getReturnType() {
return Objective.class;
}
@Override
public boolean isSingle() {
return true;
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] e, int matchedPattern, Kleenean isDelayed, ParseResult parser) {
score = (Expression<Score>) e[0];
return true;
}
@Override
public String toString(@Nullable Event e, boolean arg1) {
return "[the] (score[ ][board]|[skellett[ ]]board) objective (from|of) score %score%";
}
@Override
@Nullable
protected Objective[] get(Event e) {
return new Objective[]{score.getSingle(e).getObjective()};
}
} | {
"content_hash": "5c0a85dc0755f841398c293010f95eb8",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 101,
"avg_line_length": 30.166666666666668,
"alnum_prop": 0.7434885556432518,
"repo_name": "TheLimeGlass/Skellett",
"id": "7a377df7180acef2b9d0c26818b9123b7e42a10c",
"size": "1267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/gmail/thelimeglass/Scoreboards/ExprScoreObjective.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "522727"
}
],
"symlink_target": ""
} |
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OperatorFunction, TeardownLogic } from '../types';
/**
* Buffers the source Observable values until the size hits the maximum
* `bufferSize` given.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when its size reaches `bufferSize`.</span>
*
* <img src="./img/bufferCount.png" width="100%">
*
* Buffers a number of values from the source Observable by `bufferSize` then
* emits the buffer and clears it, and starts a new buffer each
* `startBufferEvery` values. If `startBufferEvery` is not provided or is
* `null`, then new buffers are started immediately at the start of the source
* and when each buffer closes and is emitted.
*
* ## Examples
*
* Emit the last two click events as an array
*
* ```javascript
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferCount(2));
* buffered.subscribe(x => console.log(x));
* ```
*
* On every click, emit the last two click events as an array
*
* ```javascript
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferCount(2, 1));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link pairwise}
* @see {@link windowCount}
*
* @param {number} bufferSize The maximum size of the buffer emitted.
* @param {number} [startBufferEvery] Interval at which to start a new buffer.
* For example if `startBufferEvery` is `2`, then a new buffer will be started
* on every other value from the source. A new buffer is started at the
* beginning of the source by default.
* @return {Observable<T[]>} An Observable of arrays of buffered values.
* @method bufferCount
* @owner Observable
*/
export function bufferCount<T>(bufferSize: number, startBufferEvery: number = null): OperatorFunction<T, T[]> {
return function bufferCountOperatorFunction(source: Observable<T>) {
return source.lift(new BufferCountOperator<T>(bufferSize, startBufferEvery));
};
}
class BufferCountOperator<T> implements Operator<T, T[]> {
private subscriberClass: any;
constructor(private bufferSize: number, private startBufferEvery: number) {
if (!startBufferEvery || bufferSize === startBufferEvery) {
this.subscriberClass = BufferCountSubscriber;
} else {
this.subscriberClass = BufferSkipCountSubscriber;
}
}
call(subscriber: Subscriber<T[]>, source: any): TeardownLogic {
return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferCountSubscriber<T> extends Subscriber<T> {
private buffer: T[] = [];
constructor(destination: Subscriber<T[]>, private bufferSize: number) {
super(destination);
}
protected _next(value: T): void {
const buffer = this.buffer;
buffer.push(value);
if (buffer.length == this.bufferSize) {
this.destination.next(buffer);
this.buffer = [];
}
}
protected _complete(): void {
const buffer = this.buffer;
if (buffer.length > 0) {
this.destination.next(buffer);
}
super._complete();
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferSkipCountSubscriber<T> extends Subscriber<T> {
private buffers: Array<T[]> = [];
private count: number = 0;
constructor(destination: Subscriber<T[]>, private bufferSize: number, private startBufferEvery: number) {
super(destination);
}
protected _next(value: T): void {
const { bufferSize, startBufferEvery, buffers, count } = this;
this.count++;
if (count % startBufferEvery === 0) {
buffers.push([]);
}
for (let i = buffers.length; i--; ) {
const buffer = buffers[i];
buffer.push(value);
if (buffer.length === bufferSize) {
buffers.splice(i, 1);
this.destination.next(buffer);
}
}
}
protected _complete(): void {
const { buffers, destination } = this;
while (buffers.length > 0) {
let buffer = buffers.shift();
if (buffer.length > 0) {
destination.next(buffer);
}
}
super._complete();
}
}
| {
"content_hash": "74d22df7a8fd1c6e18972c5e6413824d",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 111,
"avg_line_length": 29.17105263157895,
"alnum_prop": 0.670275146594497,
"repo_name": "mrtequino/JSW",
"id": "83282d8bff418bd88794c2750821031029cec295",
"size": "4434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nodejs/pos-server/node_modules/rxjs/src/internal/operators/bufferCount.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "243783"
},
{
"name": "HTML",
"bytes": "137440"
},
{
"name": "Java",
"bytes": "360339"
},
{
"name": "JavaScript",
"bytes": "93395"
},
{
"name": "TypeScript",
"bytes": "291910"
},
{
"name": "Vue",
"bytes": "14811"
}
],
"symlink_target": ""
} |
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a BootyCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
| {
"content_hash": "82295a80c854ca44fe599a92d0e89dac",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 109,
"avg_line_length": 24.43646408839779,
"alnum_prop": 0.6703594845127742,
"repo_name": "bootycoin-project/bootycoin",
"id": "de374b9d0da891c85e176731c8af3856fc10b0aa",
"size": "4423",
"binary": false,
"copies": "1",
"ref": "refs/heads/mastarrr",
"path": "src/qt/sendcoinsentry.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "103297"
},
{
"name": "C++",
"bytes": "2524351"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "14700"
},
{
"name": "Objective-C",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69719"
},
{
"name": "Shell",
"bytes": "9702"
},
{
"name": "TypeScript",
"bytes": "5240521"
}
],
"symlink_target": ""
} |
package org.apache.curator.framework.recipes.queue;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.EnsurePath;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* <p>
* Drop in replacement for: org.apache.zookeeper.recipes.queue.DistributedQueue that is part of
* the ZooKeeper distribution
* </p>
*
* <p>
* This class is data compatible with the ZK version. i.e. it uses the same naming scheme so
* it can read from an existing queue
* </p>
*/
public class SimpleDistributedQueue
{
private final Logger log = LoggerFactory.getLogger(getClass());
private final CuratorFramework client;
private final String path;
private final EnsurePath ensurePath;
private final String PREFIX = "qn-";
/**
* @param client the client
* @param path path to store queue nodes
*/
public SimpleDistributedQueue(CuratorFramework client, String path)
{
this.client = client;
this.path = path;
ensurePath = client.newNamespaceAwareEnsurePath(path);
}
/**
* Return the head of the queue without modifying the queue.
*
* @return the data at the head of the queue.
* @throws Exception errors
* @throws NoSuchElementException if the queue is empty
*/
public byte[] element() throws Exception
{
byte[] bytes = internalElement(false, null);
if ( bytes == null )
{
throw new NoSuchElementException();
}
return bytes;
}
/**
* Attempts to remove the head of the queue and return it.
*
* @return The former head of the queue
* @throws Exception errors
* @throws NoSuchElementException if the queue is empty
*/
public byte[] remove() throws Exception
{
byte[] bytes = internalElement(true, null);
if ( bytes == null )
{
throw new NoSuchElementException();
}
return bytes;
}
/**
* Removes the head of the queue and returns it, blocks until it succeeds.
*
* @return The former head of the queue
* @throws Exception errors
*/
public byte[] take() throws Exception
{
return internalPoll(0, null);
}
/**
* Inserts data into queue.
*
* @param data the data
* @return true if data was successfully added
* @throws Exception errors
*/
public boolean offer(byte[] data) throws Exception
{
ensurePath.ensure(client.getZookeeperClient());
String thisPath = ZKPaths.makePath(path, PREFIX);
client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(thisPath, data);
return true;
}
/**
* Returns the data at the first element of the queue, or null if the queue is empty.
*
* @return data at the first element of the queue, or null.
* @throws Exception errors
*/
public byte[] peek() throws Exception
{
try
{
return element();
}
catch ( NoSuchElementException e )
{
return null;
}
}
/**
* Retrieves and removes the head of this queue, waiting up to the
* specified wait time if necessary for an element to become available.
*
* @param timeout how long to wait before giving up, in units of
* <tt>unit</tt>
* @param unit a <tt>TimeUnit</tt> determining how to interpret the
* <tt>timeout</tt> parameter
* @return the head of this queue, or <tt>null</tt> if the
* specified waiting time elapses before an element is available
* @throws Exception errors
*/
public byte[] poll(long timeout, TimeUnit unit) throws Exception
{
return internalPoll(timeout, unit);
}
/**
* Attempts to remove the head of the queue and return it. Returns null if the queue is empty.
*
* @return Head of the queue or null.
* @throws Exception errors
*/
public byte[] poll() throws Exception
{
try
{
return remove();
}
catch ( NoSuchElementException e )
{
return null;
}
}
private byte[] internalPoll(long timeout, TimeUnit unit) throws Exception
{
ensurePath.ensure(client.getZookeeperClient());
long startMs = System.currentTimeMillis();
boolean hasTimeout = (unit != null);
long maxWaitMs = hasTimeout ? TimeUnit.MILLISECONDS.convert(timeout, unit) : Long.MAX_VALUE;
for(;;)
{
final CountDownLatch latch = new CountDownLatch(1);
Watcher watcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
latch.countDown();
}
};
byte[] bytes = internalElement(true, watcher);
if ( bytes != null )
{
return bytes;
}
if ( hasTimeout )
{
long elapsedMs = System.currentTimeMillis() - startMs;
long thisWaitMs = maxWaitMs - elapsedMs;
if ( thisWaitMs <= 0 )
{
return null;
}
latch.await(thisWaitMs, TimeUnit.MILLISECONDS);
}
else
{
latch.await();
}
}
}
private byte[] internalElement(boolean removeIt, Watcher watcher) throws Exception
{
ensurePath.ensure(client.getZookeeperClient());
List<String> nodes;
try
{
nodes = (watcher != null) ? client.getChildren().usingWatcher(watcher).forPath(path) : client.getChildren().forPath(path);
}
catch ( KeeperException.NoNodeException dummy )
{
return null;
}
Collections.sort(nodes);
for ( String node : nodes )
{
if ( !node.startsWith(PREFIX) )
{
log.warn("Foreign node in queue path: " + node);
continue;
}
String thisPath = ZKPaths.makePath(path, node);
try
{
byte[] bytes = client.getData().forPath(thisPath);
if ( removeIt )
{
client.delete().forPath(thisPath);
}
return bytes;
}
catch ( KeeperException.NoNodeException ignore )
{
//Another client removed the node first, try next
}
}
return null;
}
}
| {
"content_hash": "b19a72ec3eb5052235df7785bd38477b",
"timestamp": "",
"source": "github",
"line_count": 246,
"max_line_length": 134,
"avg_line_length": 29.020325203252032,
"alnum_prop": 0.5681467992716067,
"repo_name": "barkbay/incubator-curator",
"id": "5b008551e5ef2a75eb9649c18fa944d0851dbe75",
"size": "7947",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/SimpleDistributedQueue.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1449"
},
{
"name": "Java",
"bytes": "1460434"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2015 Actor LLC. <https://actor.im>
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="@+id/dividerTop"
android:layout_width="match_parent"
android:layout_height="@dimen/div_size" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="48dp">
<TextView
android:id="@+id/cancel"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/selector"
android:clickable="true"
android:gravity="center"
android:text="@string/add_contact_bar_cancel"
android:textAllCaps="true"
android:textSize="16sp" />
<View
android:id="@+id/dividerBot"
android:layout_width="@dimen/div_size"
android:layout_height="match_parent" />
<TextView
android:id="@+id/ok"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/selector"
android:clickable="true"
android:gravity="center"
android:text="@string/add_contact_bar_continue"
android:textAllCaps="true"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout> | {
"content_hash": "831ba09c9236b8d29f24f48dddf6aef0",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 72,
"avg_line_length": 31.764705882352942,
"alnum_prop": 0.5858024691358025,
"repo_name": "ljshj/actor-platform",
"id": "462c237f3331c4210c24b76eca1c193d37f75cfe",
"size": "1620",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "actor-sdk/sdk-core-android/android-sdk/src/main/res/layout/bar_search.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2575"
},
{
"name": "CSS",
"bytes": "84420"
},
{
"name": "HTML",
"bytes": "2562"
},
{
"name": "Java",
"bytes": "3685846"
},
{
"name": "JavaScript",
"bytes": "310291"
},
{
"name": "Makefile",
"bytes": "3630"
},
{
"name": "Objective-C",
"bytes": "239045"
},
{
"name": "PLSQL",
"bytes": "66"
},
{
"name": "Protocol Buffer",
"bytes": "29116"
},
{
"name": "Python",
"bytes": "5803"
},
{
"name": "Ruby",
"bytes": "2728"
},
{
"name": "SQLPL",
"bytes": "99"
},
{
"name": "Scala",
"bytes": "1241984"
},
{
"name": "Shell",
"bytes": "12028"
},
{
"name": "Swift",
"bytes": "638635"
}
],
"symlink_target": ""
} |
var services = require('../../lib/services.js');
module.exports = function (router, db, apiResponse, errorService) {
'use strict';
var User = db.user,
Operation = db.operation;
router.route('/')
/**
* @api {get} /user/ Get all users
* @apiName getAllUsers
* @apiGroup User
*
* @apiSuccess {Object[]} Users List of users
*/
.get(function getAllUsers(req, res, next) {
User.findAll().then(function (users) {
apiResponse.ok(res, users);
}, function (error) {
apiResponse.serverError(res, errorService.getDefault(error.message));
});
});
router.route('/test')
/**
* @api {post} /user/test Create a user for testing
* @apiName CreateTestUser
* @apiGroup User
*
* @apiSuccess {Object} user User created
*/
.post(function createTestUser(req, res, next) {
User.create({
email: 'testuser@ynov.com',
firstName: 'Test',
lastName: 'User',
balance: 300
}).then(function (user) {
apiResponse.ok(res, user);
}, function (error) {
apiResponse.serverError(res, errorService.getDefault(error.message));
});
})
/**
* @api {delete} /user/test delete the user for testing
* @apiName DeleteTestUser
* @apiGroup User
*
*/
.delete(function deleteTestUser(req, res, next) {
User.destroy({
where: {
email: 'testuser@ynov.com'
}
}).then(function(){
apiResponse.ok(res);
}, function (error) {
apiResponse.serverError(res, errorService.getDefault(error.message));
});
});
router.route('/:id/invoice')
/**
* @api {post} /user/id/cant Apply an invoice to a user
* @apiName InvoiceUser
* @apiGroup User
*
* @apiParam {Number} amount Amount of the invoice
* @apiParam {Number} expirationDate Expiration date of the card
* @apiParam {Number} cardNumber
* @apiParam {Number} cvv
*/
.post(function invoiceUser(req, res, next) {
//Vérification de la carte
if(!req.body.cvv || !req.body.cardNumber || !req.body.expirationDate || !req.body.amount){
apiResponse.badRequest(res, errorService.get('missingparameters'));
return;
}
var cvvRegex = new RegExp('^[0-9]{3}$');
var cardRegex = new RegExp('^[0-9]{16}$');
var exirationDateSplited = req.body.expirationDate.split('/');
var expirationMonth = exirationDateSplited[0];
var expirationYear = "20" + exirationDateSplited[1];
var today = new Date();
var isValidDate = true;
if (expirationYear < today.getFullYear() || expirationMonth < today.getMonth() + 1 && expirationYear <= today.getFullYear()){
isValidDate = false;
}
if (!cvvRegex.test(req.body.cvv) || !cardRegex.test(req.body.cardNumber) || !isValidDate){
apiResponse.badRequest(res, errorService.get('invalidcard'));
return;
}
//Débit de l'user
User.find({
where: { id: req.params.id }
}).then(function (user) {
if (!user){
apiResponse.badRequest(res, errorService.get('user.notfound'));
return;
}
if (user.balance < parseInt(req.body.amount) * 5){
apiResponse.badRequest(res, errorService.get('user.insufficientbalance'));
return;
}
var newBalance = user.balance - parseInt(req.body.amount);
user.updateAttributes({
balance: newBalance
})
.then(function (userUpdated) {
var today = new Date();
var invoiceDate = today.setDate(today.getDate() + 7);
Operation.create({
amount: parseInt(req.body.amount),
debitDate: services.formatDateTime(invoiceDate),
userId: req.params.id
}).then(function(operation){
apiResponse.ok(res);
},function(error){
apiResponse.serverError(res, errorService.getDefault(error.message));
});
}, function (error) {
apiResponse.serverError(res, errorService.getDefault(error.message));
});
}, function (error) {
apiResponse.serverError(res, errorService.getDefault(error.message));
});
});
}; | {
"content_hash": "cfdc1959e5efd594eb1be3c9ff018552",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 137,
"avg_line_length": 37.15555555555556,
"alnum_prop": 0.5003987240829346,
"repo_name": "Annihilator81/devops-bank-api",
"id": "704e8fe0b48b8231e83be2fc8efe028cffbd2ece",
"size": "5018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projet/app/routes/user.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "20468"
},
{
"name": "Shell",
"bytes": "707"
}
],
"symlink_target": ""
} |
package org.codeartisans.staticlet.core;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codeartisans.staticlet.core.http.etag.ETagger;
import org.codeartisans.staticlet.core.http.etag.HexMD5ETagger;
import org.codeartisans.staticlet.core.util.IOService;
import org.codeartisans.staticlet.core.util.RequestLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for Staticlet servlets.
*/
public abstract class AbstractStaticlet
extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger( AbstractStaticlet.class.getPackage().getName() );
private static final int DEFAULT_BUFFER_SIZE = 10240; // ..bytes = 10KB.
private static final long DEFAULT_EXPIRE_TIME = 604800000L; // ..ms = 1 week.
private StaticletConfiguration configuration;
// Subclasses contract ---------------------------------------------------------------------------------------------
/**
* @return The StaticletConfiguration to use
*/
protected abstract StaticletConfiguration getConfiguration();
/**
* By default the org.codeartisans.staticlet.core logger is used for
* requests logging. You can override this method to provide a logger
* of your choice.
*
* @return The Logger to use for requests logging
*/
protected Logger getLogger()
{
return LOGGER;
}
// Lifecycle -------------------------------------------------------------------------------------------------------
/**
* WARNING if you override this method remember to call super.destroy().
*/
@Override
public void init()
throws ServletException
{
beforeInit();
super.init();
validateConfiguration( getConfiguration() );
afterInit();
}
/**
* Test values in given StaticletConfiguration and set the configuration
* field with a copy if it validates.
*
* @param config The configuration to validate
* @throws ServletException if the configuration does not validates
*/
private void validateConfiguration( StaticletConfiguration config )
throws ServletException
{
String docRoot = config.getDocRoot();
if ( docRoot == null || docRoot.length() <= 0 ) {
throw new ServletException( "docRoot is required" );
}
File path = new File( docRoot );
if ( !path.exists() ) {
throw new ServletException( "'" + docRoot + "' does not exist" );
} else if ( !path.isDirectory() ) {
throw new ServletException( "'" + docRoot + "' is not a directory" );
} else if ( !path.canRead() ) {
throw new ServletException( "'" + docRoot + "' is not readable" );
}
Boolean directoryListing = config.isDirectoryListing();
if ( directoryListing == null ) {
directoryListing = Boolean.FALSE;
}
Integer bufferSize = config.getBufferSize();
if ( bufferSize == null ) {
bufferSize = DEFAULT_BUFFER_SIZE;
}
Long expireTime = config.getExpireTime();
if ( expireTime == null ) {
expireTime = DEFAULT_EXPIRE_TIME;
}
this.configuration = new StaticletConfiguration( docRoot, directoryListing, bufferSize, expireTime );
}
@Override
public final void destroy()
{
beforeDestroy();
configuration = null;
super.destroy();
}
/**
* Hook called before servlet init.
*
* @throws ServletException
*/
protected void beforeInit()
throws ServletException
{
}
/**
* Hook called after servlet init.
*
* @throws ServletException
*/
protected void afterInit()
throws ServletException
{
}
/**
* Hook called before servlet destroy.
*/
protected void beforeDestroy()
{
}
// Request processing ----------------------------------------------------------------------------------------------
@Override
protected final void doHead( HttpServletRequest httpRequest, HttpServletResponse httpResponse )
throws ServletException, IOException
{
processRequest( httpRequest, httpResponse, false );
}
@Override
protected final void doGet( HttpServletRequest httpRequest, HttpServletResponse httpResponse )
throws ServletException, IOException
{
processRequest( httpRequest, httpResponse, true );
}
private void processRequest( HttpServletRequest httpRequest, HttpServletResponse httpResponse, boolean writeBody )
throws IOException
{
Logger logger = new RequestLogger( getLogger(), UUID.randomUUID().toString() );
try {
// Ensure configuration ------------------------------------------------------------------------------------
if ( configuration == null ) {
logger.error( "Improperly configured, see logs outputed during servlet init, 500" );
throw new EarlyHttpStatusException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Improperly configured" );
}
// Set up FileSystemRequest and its dependencies -----------------------------------------------------------
ServletContext servletContext = getServletContext();
IOService io = new IOService( servletContext, logger );
ETagger eTagger = new HexMD5ETagger( logger, io );
StaticRequest fsRequest = new StaticRequest( configuration,
logger, io, eTagger,
httpRequest, httpResponse,
writeBody );
// Interaction ---------------------------------------------------------------------------------------------
fsRequest.validateRequest();
fsRequest.handleConditional();
fsRequest.represent();
} catch ( EarlyHttpStatusException earlyStatus ) {
// A http early status as been raised ----------------------------------------------------------------------
for ( Map.Entry<String, String> eachHeader : earlyStatus.headers.entrySet() ) {
httpResponse.setHeader( eachHeader.getKey(), eachHeader.getValue() );
}
httpResponse.sendError( earlyStatus.status, earlyStatus.reason );
}
}
}
| {
"content_hash": "29ee762fc2a31d0471c2b688f63bb35a",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 124,
"avg_line_length": 34.57575757575758,
"alnum_prop": 0.569967864446392,
"repo_name": "eskatos/staticlet",
"id": "3f9395dac9afa9e586bae9d435710766abf41411",
"size": "7457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "staticlet/core/src/main/java/org/codeartisans/staticlet/core/AbstractStaticlet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "86310"
}
],
"symlink_target": ""
} |
from v2ex import v2ex
| {
"content_hash": "11ab3de796c244be1d2144c7d4304abc",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 21,
"avg_line_length": 22,
"alnum_prop": 0.8181818181818182,
"repo_name": "littson/bee",
"id": "37e9c071cf224d1dbf663ddfb7618eff078fa4d8",
"size": "22",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bots/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "85"
},
{
"name": "Python",
"bytes": "2879"
}
],
"symlink_target": ""
} |
TODO: Write a gem description
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'parse_provision_profile'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install parse_provision_profile
## Usage
TODO: Write usage instructions here
## Contributing
1. Fork it ( https://github.com/[my-github-username]/parse_provision_profile/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
| {
"content_hash": "71a1c1f2d5b0e52d6e9553dd019b0290",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 83,
"avg_line_length": 20.724137931034484,
"alnum_prop": 0.7237936772046589,
"repo_name": "motobhakta/parse_provision_profile",
"id": "28f741bdaf6f4de66a6d4e88e62a32b10fa2daec",
"size": "626",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2475"
}
],
"symlink_target": ""
} |
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { APP_ROUTER_PROVIDERS, AppComponent, environment } from './app/';
import { HTTP_PROVIDERS} from '@angular/http';
import { HnService } from './app/hn.service';
import { LocalStorageService } from './app/local-storage.service';
if (environment.production) {
enableProdMode();
}
bootstrap(AppComponent, [HTTP_PROVIDERS, APP_ROUTER_PROVIDERS, HnService, LocalStorageService,
{ provide: LocationStrategy, useClass: HashLocationStrategy }
]).catch(err => console.error(err));
| {
"content_hash": "9eb4c9c0fa0ecd080a2c4ba07cda22de",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 94,
"avg_line_length": 39.529411764705884,
"alnum_prop": 0.7485119047619048,
"repo_name": "rgv151/hn",
"id": "a636352f2b9f81849372d30d77c43bc3af0a406c",
"size": "672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23878"
},
{
"name": "HTML",
"bytes": "7235"
},
{
"name": "JavaScript",
"bytes": "4246"
},
{
"name": "Shell",
"bytes": "146"
},
{
"name": "TypeScript",
"bytes": "20919"
}
],
"symlink_target": ""
} |
package com.impetus.kundera.entity.photo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Entity class for photo
*
* @author amresh.singh
*/
@Entity
@Table(name = "PHOTO", schema = "KunderaTest@kunderatest")
public class PhotoUni_1_1_1_M
{
@Id
@Column(name = "PHOTO_ID")
private String photoId;
@Column(name = "PHOTO_CAPTION")
private String photoCaption;
@Column(name = "PHOTO_DESC")
private String photoDescription;
public PhotoUni_1_1_1_M()
{
}
public PhotoUni_1_1_1_M(String photoId, String caption, String description)
{
this.photoId = photoId;
this.photoCaption = caption;
this.photoDescription = description;
}
/**
* @return the photoId
*/
public String getPhotoId()
{
return photoId;
}
/**
* @param photoId
* the photoId to set
*/
public void setPhotoId(String photoId)
{
this.photoId = photoId;
}
/**
* @return the photoCaption
*/
public String getPhotoCaption()
{
return photoCaption;
}
/**
* @param photoCaption
* the photoCaption to set
*/
public void setPhotoCaption(String photoCaption)
{
this.photoCaption = photoCaption;
}
/**
* @return the photoDescription
*/
public String getPhotoDescription()
{
return photoDescription;
}
/**
* @param photoDescription
* the photoDescription to set
*/
public void setPhotoDescription(String photoDescription)
{
this.photoDescription = photoDescription;
}
}
| {
"content_hash": "06f1e80555203c3c7814398dfefcfc2e",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 79,
"avg_line_length": 18.956521739130434,
"alnum_prop": 0.6003440366972477,
"repo_name": "impetus-opensource/Kundera",
"id": "84f6c4f965d7d8ee1d6ec8654ff34673fe41b49c",
"size": "2538",
"binary": false,
"copies": "4",
"ref": "refs/heads/trunk",
"path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_1_1_1_M.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "14971479"
},
{
"name": "Shell",
"bytes": "113"
}
],
"symlink_target": ""
} |
SHELL=/bin/sh
LIBS=nums.cmxa unix.cmxa str.cmxa
BITCODE=../bitcode
EXES=rawparse parse dltest llvm2smt
CORE=util.cmx llvm.cmx llvm_pp.cmx dl.cmx bc.cmx bc_manip.cmx bc_pp.cmx llparse.cmx lllex.cmx
TESTS=http_examples.i386 https_examples.darwin yices_main minigzip-3.5 minisat.darwin
all: ${EXES}
llvm2smt: ${CORE} llvm_parser.cmx prelude.cmx smt.cmx llvm2smt.cmx
ocamlopt $(LIBS) $^ -o $@
rawparse: ${CORE} rawparse.cmx
ocamlopt $(LIBS) $^ -o $@
parse: ${CORE} llvm_parser.cmx parse.cmx
ocamlopt $(LIBS) $^ -o $@
dltest: dl.cmx dltest.cmx
ocamlopt $(LIBS) $^ -o $@
test: llvm2smt
./llvm2smt ${BITCODE}/int_powers.ll > ${BITCODE}/int_powers.smt
./llvm2smt ${BITCODE}/structs.ll > ${BITCODE}/structs.smt
./llvm2smt ${BITCODE}/structs.i386.ll > ${BITCODE}/structs.i386.smt
bug: parse
./parse ${BITCODE}/int_powers.ll > ${BITCODE}/int_powers.out.ll
diff -w -I ModuleID ${BITCODE}/int_powers.ll ${BITCODE}/int_powers.out.ll
translate: parse
./parse ${BITCODE}/https_examples.darwin.ll > ${BITCODE}/https_examples.darwin.out.ll
diff -w -I ModuleID ${BITCODE}/https_examples.darwin.ll ${BITCODE}/https_examples.darwin.out.ll
stress: parse
for sourcebits in ${TESTS} ; do \
./parse ${BITCODE}/$${sourcebits}.ll > ${BITCODE}/$${sourcebits}.out.ll ; \
diff -w -I ModuleID ${BITCODE}/$${sourcebits}.ll ${BITCODE}/$${sourcebits}.out.ll ; \
echo "Success for $${sourcebits}\n"; \
done
smt: llvm2smt
./llvm2smt ${BITCODE}/sums_auto3.ll > ${BITCODE}/sums_auto3.smt
yices-smt2 ${BITCODE}/sums_auto3.smt
switch: llvm2smt
./llvm2smt ${BITCODE}/switch.ll > ${BITCODE}/switch.smt
yices-smt2 ${BITCODE}/switch.smt
rot13: llvm2smt
./llvm2smt ${BITCODE}/rot13.ll > ${BITCODE}/rot13.smt
yices-smt2 ${BITCODE}/rot13.smt
exponentiation: llvm2smt
./llvm2smt ${BITCODE}/exponentiation.ll > ${BITCODE}/exponentiation.smt
yices-smt2 ${BITCODE}/exponentiation.smt
./llvm2smt ${BITCODE}/exponentiation_auto3.ll > ${BITCODE}/exponentiation_auto3.smt
yices-smt2 ${BITCODE}/exponentiation_auto3.smt
structs: llvm2smt
./llvm2smt ${BITCODE}/structs.ll > ${BITCODE}/structs.smt
./llvm2smt ${BITCODE}/packed_structs.ll > ${BITCODE}/packed_structs.smt
./llvm2smt ${BITCODE}/structs2.ll > ${BITCODE}/structs2.smt
./llvm2smt ${BITCODE}/packed_structs2.ll > ${BITCODE}/packed_structs2.smt
int2ptr: llvm2smt
./llvm2smt ${BITCODE}/int2ptr.ll > ${BITCODE}/int2ptr.smt
yices-smt2 ${BITCODE}/int2ptr.smt
primes: llvm2smt
./llvm2smt ${BITCODE}/primes_opt_auto2.ll > ${BITCODE}/primes_opt_auto2.smt
# ./llvm2smt ${BITCODE}/primes_opt_auto3.ll > ${BITCODE}/primes_opt_auto3.smt
# ./llvm2smt ${BITCODE}/primes_opt_auto4.ll > ${BITCODE}/primes_opt_auto4.smt
yices: llvm2smt
./llvm2smt ${BITCODE}/yices_main.ll > ${BITCODE}/yices_main.smt
yices-smt2 ${BITCODE}/yices_main.smt
gepstress: llvm2smt
for sourcebits in ${TESTS} ; do \
./llvm2smt ${BITCODE}/$${sourcebits}.ll > ${BITCODE}/$${sourcebits}.smt ; \
done
clean:
$(RM) *~ *.cmx *.cmi *.cmo *.o llparse.ml llparse.mli llparse.mli lllex.ml ${EXES}
%.cmi: %.mli
ocamlc -c $<
%.cmx: %.ml
ocamlopt -c $< -o $@
%.ml: %.mll
ocamllex $< -o $@
%.ml: %.mly
ocamlyacc $<
%.mli: %.mly
ocamlyacc $<
include .depend
.depend: lllex.ml llparse.ml llparse.mli
ocamldep -native *.ml *.mli > $@
| {
"content_hash": "95983fc5606142ece2a24e7ecd6db015",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 97,
"avg_line_length": 28.747826086956522,
"alnum_prop": 0.6839080459770115,
"repo_name": "SRI-CSL/llvm2smt",
"id": "5a179f7b73686da2d2d5e5bd35b1539348f917c1",
"size": "3306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "LLVM",
"bytes": "119708182"
},
{
"name": "Makefile",
"bytes": "4136"
},
{
"name": "OCaml",
"bytes": "224008"
},
{
"name": "SMT",
"bytes": "602996"
},
{
"name": "Standard ML",
"bytes": "27688"
}
],
"symlink_target": ""
} |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-ultra-select"), require("deep-equal"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-ultra-select", "deep-equal"], factory);
else if(typeof exports === 'object')
exports["react-ultra-date-picker"] = factory(require("react"), require("react-ultra-select"), require("deep-equal"));
else
root["react-ultra-date-picker"] = factory(root["react"], root["react-ultra-select"], root["deep-equal"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.addLocaleConfig = exports.translateHour = exports.isPm = exports.padStartWith0 = exports.daysInMonth = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactUltraSelect = __webpack_require__(3);
var _reactUltraSelect2 = _interopRequireDefault(_reactUltraSelect);
var _deepEqual = __webpack_require__(4);
var _deepEqual2 = _interopRequireDefault(_deepEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
// import UltraSelect from './UltraSelect'
// http://stackoverflow.com/questions/1184334/get-number-days-in-a-specified-month-using-javascript
var daysInMonth = exports.daysInMonth = function daysInMonth(year, month) {
return new Date(year, month, 0).getDate();
};
var padStartWith0 = exports.padStartWith0 = function padStartWith0(num) {
return num >= 10 ? num.toString() : '0' + num;
};
var isPm = exports.isPm = function isPm(date) {
return date.getHours() >= 12;
};
var translateHour = exports.translateHour = function translateHour(hour, use24hours) {
if (use24hours) {
return padStartWith0(hour);
}
if (hour % 12 === 0) {
return '12';
}
return padStartWith0(hour % 12);
};
var enConfig = {
order: ['month', 'date', 'year', 'hour', 'minute', 'ampm'],
year: function year(_year) {
return _year;
},
month: function month(_month) {
return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][_month];
},
date: function date(_date) {
return padStartWith0(_date);
},
am: 'AM',
pm: 'PM',
hour: translateHour,
minute: function minute(_minute) {
return padStartWith0(_minute);
},
confirmButton: 'Confirm',
cancelButton: 'Cancel',
dateLabel: function dateLabel(fullDate, type, use24) {
var date = fullDate.date;
var noneSelected = fullDate.noneSelected;
var outOfRange = fullDate.outOfRange;
if (noneSelected) {
return 'Please select a date';
}
if (outOfRange) {
return 'Date out of range';
}
switch (type) {
case 'time':
return enConfig.hour(date.getHours(), use24) + ':' + enConfig.minute(date.getMinutes()) + (use24 ? '' : ' ' + (date.getHours() < 12 ? enConfig.am : enConfig.pm));
case 'month':
return enConfig.month(date.getMonth()) + ' ' + enConfig.year(date.getFullYear());
case 'datetime':
return enConfig.month(date.getMonth()) + ' ' + enConfig.date(date.getDate()) + ' ' + enConfig.year(date.getFullYear()) + ' ' + enConfig.hour(date.getHours(), use24) + ':' + enConfig.minute(date.getMinutes()) + (use24 ? '' : ' ' + (date.getHours() < 12 ? enConfig.am : enConfig.pm));
case 'date':
return enConfig.month(date.getMonth()) + ' ' + enConfig.date(date.getDate()) + ' ' + enConfig.year(date.getFullYear());
default:
return '';
}
}
};
var zhCNConfig = {
order: ['year', 'month', 'date', 'ampm', 'hour', 'minute'],
year: function year(_year2) {
return _year2 + '年';
},
month: function month(_month2) {
return _month2 + 1 + '月';
},
date: function date(_date2) {
return _date2 + '日';
},
am: '上午',
pm: '下午',
hour: translateHour,
minute: function minute(_minute2) {
return padStartWith0(_minute2);
},
confirmButton: '确定',
cancelButton: '取消',
dateLabel: function dateLabel(fullDate, type, use24) {
var date = fullDate.date;
var noneSelected = fullDate.noneSelected;
var outOfRange = fullDate.outOfRange;
if (noneSelected) {
return '请选择日期';
}
if (outOfRange) {
return '日期不在选择范围内';
}
var ampmStr = '';
if (!use24) {
ampmStr = date.getHours() < 12 ? zhCNConfig.am : zhCNConfig.pm;
}
switch (type) {
case 'time':
return '' + ampmStr + zhCNConfig.hour(date.getHours(), use24) + ':' + zhCNConfig.minute(date.getMinutes());
case 'month':
return '' + zhCNConfig.year(date.getFullYear()) + zhCNConfig.month(date.getMonth());
case 'datetime':
return '' + zhCNConfig.year(date.getFullYear()) + zhCNConfig.month(date.getMonth()) + zhCNConfig.date(date.getDate()) + ' ' + ampmStr + zhCNConfig.hour(date.getHours(), use24) + ':' + zhCNConfig.minute(date.getMinutes());
case 'date':
return '' + zhCNConfig.year(date.getFullYear()) + zhCNConfig.month(date.getMonth()) + zhCNConfig.date(date.getDate());
default:
return '';
}
}
};
var localeConfigs = {
en: enConfig,
'zh-cn': zhCNConfig
};
// to keep this library size small, expose a function to expand localeConfigs on demand
var addLocaleConfig = exports.addLocaleConfig = function addLocaleConfig(name, config) {
if (config && config.order instanceof Array && typeof config.year === 'function' && typeof config.month === 'function' && typeof config.date === 'function' && typeof config.hour === 'function' && typeof config.minute === 'function' && typeof config.dateLabel === 'function') {
localeConfigs[name] = config;
} else {
console.error('addLocaleConfig: invalid locale config provided');
}
};
var dateStringProp = function dateStringProp(props, propName, componentName) {
if (!props[propName]) return null;
if (typeof props[propName] === 'number') {
return null;
}
if (typeof props[propName] !== 'string') {
return new Error(componentName + ': ' + propName + ' invalid date string provided.');
}
if (props.type === 'time') {
if (props[propName].match(/\d{2}:\d{2}/) && props[propName].length === 5) {
return null;
}
}
if (Number.isNaN(new Date(props[propName]))) {
return new Error(componentName + ': ' + propName + ' invalid date string provided.');
}
return null;
};
var localeProp = function localeProp(props, propName, componentName) {
if (typeof props[propName] === 'string' && localeConfigs[props[propName]]) {
return null;
}
return new Error(componentName + ': ' + propName + ' invalid value provided.');
};
var DatePicker = function (_Component) {
_inherits(DatePicker, _Component);
function DatePicker(props) {
_classCallCheck(this, DatePicker);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(DatePicker).call(this, props));
_this.getStaticText = _this.getStaticText.bind(_this);
_this.getTitle = _this.getTitle.bind(_this);
_this.onSelect = _this.onSelect.bind(_this);
_this.onDidSelect = _this.onDidSelect.bind(_this);
_this.onOpen = _this.onOpen.bind(_this);
_this.onClose = _this.onClose.bind(_this);
_this.onConfirm = _this.onConfirm.bind(_this);
_this.onCancel = _this.onCancel.bind(_this);
var minDate = _this.parseDateString(props.min, props.type);
var maxDate = _this.parseDateString(props.max, props.type);
var defaultDate = _this.getDefaultDate(props);
_this.state = _this.calColumnsAndKeys(_this.props, defaultDate, minDate, maxDate, true);
return _this;
}
_createClass(DatePicker, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var minDate = this.parseDateString(nextProps.min, nextProps.type);
var maxDate = this.parseDateString(nextProps.max, nextProps.type);
var defaultDate = this.getDefaultDate(nextProps);
this.setState(this.calColumnsAndKeys(nextProps, defaultDate, minDate, maxDate, true));
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
if (Object.keys(this.props).length !== Object.keys(nextProps).length) {
return true;
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(nextProps)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (!key.startsWith('on') && nextProps[key] !== this.props[key]) {
return true;
}
}
// console.log('equal props')
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (Object.keys(this.state).length !== Object.keys(nextState).length) {
return true;
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = Object.keys(nextState)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var _key = _step2.value;
if (_key === 'keys' || _key === 'columns') {
if (!(0, _deepEqual2.default)(nextState[_key], this.state[_key])) {
return true;
}
} else if (_key === 'defaultDate' || _key === 'minDate' || _key === 'maxDate') {
if (nextState[_key].getTime() !== this.state[_key].getTime()) {
return true;
}
} else if (nextState[_key] !== this.state[_key]) {
return true;
}
}
// console.log('no need to update')
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return false;
}
}, {
key: 'onSelect',
value: function onSelect() {
var _this2 = this;
var date = new Date(this.state.defaultDate.getTime());
var values = this.refs.select.selectedValues;
// use sequence to ensure correctness
var sequence = ['year', 'month', 'date', 'ampm', 'hour', 'minute'];
var _loop = function _loop(i) {
var realIndex = _this2.state.keys.findIndex(function (e) {
return e === sequence[i];
});
if (realIndex !== -1) {
switch (sequence[i]) {
case 'year':
date.setFullYear(values[realIndex].key);
break;
case 'month':
date.setDate(1); // incase Apr 31 becomes May 01
date.setMonth(values[realIndex].key);
break;
case 'date':
{
var days = daysInMonth(date.getFullYear(), date.getMonth() + 1);
if (values[realIndex].key > days) {
date.setDate(days);
} else {
date.setDate(values[realIndex].key);
}
break;
}
case 'minute':
date.setMinutes(values[realIndex].key);
break;
case 'hour':
if (!_this2.props.use24hours) {
var ampmIndex = _this2.state.keys.findIndex(function (e) {
return e === 'ampm';
});
var ampm = _this2.refs.select.selectedValues[ampmIndex].key;
if (ampm === 'pm' && values[realIndex].key < 12) {
date.setHours(values[realIndex].key + 12);
break;
} else if (ampm === 'am' && values[realIndex].key >= 12) {
date.setHours(values[realIndex].key - 12);
break;
}
}
date.setHours(values[realIndex].key);
break;
case 'ampm':
default:
break;
}
}
};
for (var i = 0; i < sequence.length; i++) {
_loop(i);
}
if (date < this.state.minDate) {
date = this.state.minDate;
}
if (date > this.state.maxDate) {
date = this.state.maxDate;
}
// console.log('select new date', date)
this.setState(this.calColumnsAndKeys(this.props, date, this.state.minDate, this.state.maxDate));
if (this.props.onSelect) {
this.props.onSelect(this.date);
}
}
}, {
key: 'onDidSelect',
value: function onDidSelect() {
if (this.props.onDidSelect) {
this.props.onDidSelect(this.date);
}
}
}, {
key: 'onOpen',
value: function onOpen() {
this.mOnOpenDate = this.state.defaultDate;
if (this.props.onOpen) {
this.props.onOpen(this.date);
}
}
}, {
key: 'onClose',
value: function onClose() {
if (this.props.onClose) {
this.props.onClose(this.date);
}
}
}, {
key: 'onConfirm',
value: function onConfirm() {
this.setState({
noneSelected: false
});
if (this.props.onConfirm) {
this.props.onConfirm(this.date);
}
}
}, {
key: 'onCancel',
value: function onCancel() {
if (this.mOnOpenDate) {
this.setState(this.calColumnsAndKeys(this.props, this.mOnOpenDate, this.state.minDate, this.state.maxDate));
this.mOnOpenDate = null;
if (this.props.onCancel) {
this.props.onCancel(this.date);
}
}
}
}, {
key: 'getTitle',
value: function getTitle() {
if (this.props.getTitle) {
return this.props.getTitle(this.fullDate);
}
return this.props.title;
}
}, {
key: 'getStaticText',
value: function getStaticText() {
var _props = this.props;
var getStaticText = _props.getStaticText;
var outOfRangeLabel = _props.outOfRangeLabel;
var noneSelectedLabel = _props.noneSelectedLabel;
var type = _props.type;
var use24hours = _props.use24hours;
var _state = this.state;
var outOfRange = _state.outOfRange;
var noneSelected = _state.noneSelected;
if (getStaticText) {
return getStaticText(this.fullDate);
}
if (noneSelected && noneSelectedLabel) {
return noneSelectedLabel;
}
if (outOfRange && outOfRangeLabel) {
return outOfRangeLabel;
}
var locale = localeConfigs[this.props.locale];
if (!locale) return null;
return locale.dateLabel(this.fullDate, type, use24hours);
}
}, {
key: 'getDefaultDate',
value: function getDefaultDate(props) {
var p = props || this.props;
return this.parseDateString(p.defaultDate ? p.defaultDate : p.min, p.type);
}
}, {
key: 'parseDateString',
value: function parseDateString(dateString, type) {
var ret = void 0;
if (type === 'time') {
ret = new Date();
if (dateString.match(/\d{2}:\d{2}/) && dateString.length === 5) {
ret.setHours(parseInt(dateString.substring(0, 2), 10));
ret.setMinutes(parseInt(dateString.substring(3, 5), 10));
} else {
var temp = new Date(dateString);
ret.setHours(temp.getHours());
ret.setMinutes(temp.getMinutes());
}
} else if (type === 'date') {
ret = new Date(dateString);
ret.setHours(0);
ret.setMinutes(0);
} else if (type === 'month') {
ret = new Date(dateString);
ret.setDate(1);
ret.setHours(0);
ret.setMinutes(0);
} else if (type === 'datetime') {
ret = new Date(dateString);
}
ret.setSeconds(0);
ret.setMilliseconds(0);
return ret;
}
}, {
key: 'calColumnsAndKeys',
value: function calColumnsAndKeys(p, d, minDate, maxDate, hasPropsChanged) {
var props = p || this.props;
var defaultDate = d;
var type = props.type;
var use24hours = props.use24hours;
var locale = props.locale;
// 1. select keys
// WARNING: keys in selectedKeys should be arranged in order to ensure DatePicker work properly
// year -> month -> date -> ampm -> hour -> minute
// that is, from bigger scope to smaller scope
var selectedKeys = void 0;
switch (type) {
case 'date':
selectedKeys = ['year', 'month', 'date'];
break;
case 'datetime':
if (use24hours) {
selectedKeys = ['year', 'month', 'date', 'hour', 'minute'];
} else {
selectedKeys = ['year', 'month', 'date', 'ampm', 'hour', 'minute'];
}
break;
case 'time':
if (use24hours) {
selectedKeys = ['hour', 'minute'];
} else {
selectedKeys = ['ampm', 'hour', 'minute'];
}
break;
case 'month':
selectedKeys = ['year', 'month'];
break;
default:
break;
}
// 2. calculate range for each
var columnsDict = {};
// set min or max as default if out of range
var outOfRange = false;
if (defaultDate < minDate) {
outOfRange = true;
defaultDate = minDate;
} else if (defaultDate > maxDate) {
outOfRange = true;
defaultDate = maxDate;
}
for (var i = 0, l = selectedKeys.length; i < l; i++) {
switch (selectedKeys[i]) {
case 'year':
columnsDict[selectedKeys[i]] = this.calYear(minDate, maxDate, defaultDate, locale);
break;
case 'month':
columnsDict[selectedKeys[i]] = this.calMonth(minDate, maxDate, defaultDate, locale);
break;
case 'date':
columnsDict[selectedKeys[i]] = this.calDate(minDate, maxDate, defaultDate, locale);
break;
case 'ampm':
columnsDict[selectedKeys[i]] = this.calAMPM(minDate, maxDate, defaultDate, locale);
break;
case 'hour':
{
var ampm = void 0;
if (columnsDict.ampm) {
ampm = columnsDict.ampm.list[columnsDict.ampm.defaultIndex].key;
}
columnsDict[selectedKeys[i]] = this.calHour(minDate, maxDate, defaultDate, ampm, locale, use24hours);
break;
}
case 'minute':
columnsDict[selectedKeys[i]] = this.calMinute(minDate, maxDate, defaultDate, locale);
break;
default:
break;
}
}
// 3. order columns
var config = localeConfigs[locale];
var columns = [];
var keys = [];
for (var _i = 0, _l = config.order.length; _i < _l; _i++) {
if (columnsDict[config.order[_i]]) {
columns.push(columnsDict[config.order[_i]]);
keys.push(config.order[_i]);
}
}
return {
keys: keys,
columns: columns,
outOfRange: outOfRange,
defaultDate: defaultDate,
minDate: minDate,
maxDate: maxDate,
noneSelected: !(hasPropsChanged ? p.defaultDate : !this.state.noneSelected || p.defaultDate)
};
}
}, {
key: 'newDate',
value: function newDate(year, month, date, hour, minute) {
return new Date(year, month, date, hour, minute);
}
}, {
key: 'intersects',
value: function intersects(min1, max1, min2, max2) {
return !(max1.getTime() < min2.getTime() || min1.getTime() > max2.getTime());
}
}, {
key: 'calYear',
value: function calYear(min, max, defaults, locale) {
var ret = { list: [], defaultIndex: -1 };
for (var i = min.getFullYear(), l = max.getFullYear(), index = 0; i <= l; i++) {
var dMin = this.newDate(i, 0, 1, 0, 0);
var dMax = this.newDate(i, 11, 31, 23, 59);
if (this.intersects(dMin, dMax, min, max)) {
ret.list.push({
key: i,
value: localeConfigs[locale].year(i)
});
if (i === defaults.getFullYear()) {
ret.defaultIndex = index;
}
index++;
}
}
return ret;
}
}, {
key: 'calMonth',
value: function calMonth(min, max, defaults, locale) {
var ret = { list: [], defaultIndex: -1 };
for (var i = 0, index = 0; i < 12; i++) {
var dMin = this.newDate(defaults.getFullYear(), i, 1, 0, 0);
var dMax = this.newDate(defaults.getFullYear(), i, daysInMonth(defaults.getFullYear(), i + 1), 23, 59);
if (this.intersects(dMin, dMax, min, max)) {
ret.list.push({
key: i,
value: localeConfigs[locale].month(i)
});
if (i === defaults.getMonth()) {
ret.defaultIndex = index;
}
index++;
}
}
return ret;
}
}, {
key: 'calDate',
value: function calDate(min, max, defaults, locale) {
var ret = { list: [], defaultIndex: -1 };
var days = daysInMonth(defaults.getFullYear(), defaults.getMonth() + 1);
for (var i = 1, index = 0; i <= days; i++) {
var dMin = this.newDate(defaults.getFullYear(), defaults.getMonth(), i, 0, 0);
var dMax = this.newDate(defaults.getFullYear(), defaults.getMonth(), i, 23, 59);
if (this.intersects(dMin, dMax, min, max)) {
ret.list.push({
key: i,
value: localeConfigs[locale].date(i)
});
if (i === defaults.getDate()) {
ret.defaultIndex = index;
}
index++;
}
}
return ret;
}
}, {
key: 'calAMPM',
value: function calAMPM(min, max, defaults, locale) {
var ret = { list: [], defaultIndex: -1 };
var index = 0;
var dMin = this.newDate(defaults.getFullYear(), defaults.getMonth(), defaults.getDate(), 0, 0);
var dMax = this.newDate(defaults.getFullYear(), defaults.getMonth(), defaults.getDate(), 11, 59);
if (this.intersects(dMin, dMax, min, max)) {
ret.list.push({
key: 'am',
value: localeConfigs[locale].am
});
if (defaults.getHours() < 12) {
ret.defaultIndex = index;
}
index++;
}
dMin = this.newDate(defaults.getFullYear(), defaults.getMonth(), defaults.getDate(), 12, 0);
dMax = this.newDate(defaults.getFullYear(), defaults.getMonth(), defaults.getDate(), 23, 59);
if (this.intersects(dMin, dMax, min, max)) {
ret.list.push({
key: 'pm',
value: localeConfigs[locale].pm
});
if (defaults.getHours() >= 12) {
ret.defaultIndex = index;
}
}
return ret;
}
}, {
key: 'calHour',
value: function calHour(min, max, defaults, ampm, locale, use24hours) {
var ret = { list: [], defaultIndex: -1 };
var start = void 0;
var end = void 0;
if (this.props.use24hours) {
start = 0;
end = 23;
} else {
start = 0;
end = 11;
}
for (var i = start, index = 0; i <= end; i++) {
var hours = i;
if (!this.props.use24hours && ampm === 'pm') {
hours += 12;
}
var dMin = this.newDate(defaults.getFullYear(), defaults.getMonth(), defaults.getDate(), hours, 0);
var dMax = this.newDate(defaults.getFullYear(), defaults.getMonth(), defaults.getDate(), hours, 59);
if (this.intersects(dMin, dMax, min, max)) {
ret.list.push({
key: hours,
value: localeConfigs[locale].hour(hours, use24hours)
});
if (hours === defaults.getHours()) {
ret.defaultIndex = index;
}
index++;
}
}
return ret;
}
}, {
key: 'calMinute',
value: function calMinute(min, max, defaults, locale) {
var ret = { list: [], defaultIndex: -1 };
for (var i = 0, index = 0; i < 60; i++) {
var d = this.newDate(defaults.getFullYear(), defaults.getMonth(), defaults.getDate(), defaults.getHours(), i);
if (this.intersects(d, d, min, max)) {
ret.list.push({
key: i,
value: localeConfigs[locale].minute(i)
});
if (i === defaults.getMinutes()) {
ret.defaultIndex = index;
}
index++;
}
}
return ret;
}
}, {
key: 'render',
value: function render() {
var locale = localeConfigs[this.props.locale];
return _react2.default.createElement(_reactUltraSelect2.default, _extends({
columns: this.state.columns, ref: 'select',
confirmButton: locale.confirmButton,
cancelButton: locale.cancelButton
}, this.props, {
getStaticText: this.getStaticText,
getTitle: this.getTitle,
onSelect: this.onSelect,
onDidSelect: this.onDidSelect,
onOpen: this.onOpen,
onClose: this.onClose,
onConfirm: this.onConfirm,
onCancel: this.onCancel
}));
}
}, {
key: 'date',
get: function get() {
return this.state.outOfRange || this.state.noneSelected ? null : this.state.defaultDate;
}
}, {
key: 'fullDate',
get: function get() {
return {
date: this.date,
noneSelected: this.state.noneSelected,
outOfRange: this.state.outOfRange
};
}
}]);
return DatePicker;
}(_react.Component);
DatePicker.propTypes = {
max: dateStringProp,
min: dateStringProp,
defaultDate: dateStringProp,
type: _react.PropTypes.oneOf(['date', 'datetime', 'time', 'month']),
locale: localeProp,
use24hours: _react.PropTypes.bool,
title: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.node]),
outOfRangeLabel: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.node]),
noneSelectedLabel: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.node]),
getTitle: _react.PropTypes.func,
getStaticText: _react.PropTypes.func,
onSelect: _react.PropTypes.func,
onDidSelect: _react.PropTypes.func,
onOpen: _react.PropTypes.func,
onClose: _react.PropTypes.func,
onConfirm: _react.PropTypes.func,
onCancel: _react.PropTypes.func
};
DatePicker.defaultProps = {
min: '01 Jan 1970 00:00',
max: '19 Jan 2038 03:14',
type: 'date',
locale: 'en',
use24hours: false
};
exports.default = DatePicker;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
/***/ },
/* 4 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_4__;
/***/ }
/******/ ])
});
; | {
"content_hash": "25c992855da73b02e9dca3e86e0e5519",
"timestamp": "",
"source": "github",
"line_count": 891,
"max_line_length": 565,
"avg_line_length": 40.55331088664422,
"alnum_prop": 0.486950986632718,
"repo_name": "swenyang/react-date-picker",
"id": "8a82f8dc57b7a16118def89e826fc328a0a1e04b",
"size": "36183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/react-ultra-date-picker.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "25500"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CodeComb.Marked
{
internal class Token
{
public string Text { get; set; }
public string Type { get; set; }
public int Depth { get; set; }
public bool Escaped { get; set; }
public string Lang { get; set; }
public bool Ordered { get; set; }
public bool Pre { get; set; }
public IList<string> Header { get; set; }
public IList<string> Align { get; set; }
public IList<IList<string>> Cells { get; set; }
}
}
| {
"content_hash": "95d9d80629693583c234675c6b4c952f",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 55,
"avg_line_length": 23.03846153846154,
"alnum_prop": 0.5876460767946577,
"repo_name": "CodeComb/Marked",
"id": "ac2367f149f2ff8d1413088fb50d39f27422f025",
"size": "601",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/CodeComb.Marked/Token.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1524"
},
{
"name": "C#",
"bytes": "53129"
},
{
"name": "PowerShell",
"bytes": "3834"
},
{
"name": "Shell",
"bytes": "1004"
}
],
"symlink_target": ""
} |
#!/usr/bin/env bash
# Copyright 2014 The Kubernetes 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.
function kube::util::sourced_variable {
# Call this function to tell shellcheck that a variable is supposed to
# be used from other calling context. This helps quiet an "unused
# variable" warning from shellcheck and also document your code.
true
}
kube::util::sortable_date() {
date "+%Y%m%d-%H%M%S"
}
# arguments: target, item1, item2, item3, ...
# returns 0 if target is in the given items, 1 otherwise.
kube::util::array_contains() {
local search="$1"
local element
shift
for element; do
if [[ "${element}" == "${search}" ]]; then
return 0
fi
done
return 1
}
kube::util::wait_for_url() {
local url=$1
local prefix=${2:-}
local wait=${3:-1}
local times=${4:-30}
local maxtime=${5:-1}
command -v curl >/dev/null || {
kube::log::usage "curl must be installed"
exit 1
}
local i
for i in $(seq 1 "${times}"); do
local out
if out=$(curl --max-time "${maxtime}" -gkfs "${url}" 2>/dev/null); then
kube::log::status "On try ${i}, ${prefix}: ${out}"
return 0
fi
sleep "${wait}"
done
kube::log::error "Timed out waiting for ${prefix} to answer at ${url}; tried ${times} waiting ${wait} between each"
return 1
}
# Example: kube::util::wait_for_success 120 5 "kubectl get nodes|grep localhost"
# arguments: wait time, sleep time, shell command
# returns 0 if the shell command get output, 1 otherwise.
kube::util::wait_for_success(){
local wait_time="$1"
local sleep_time="$2"
local cmd="$3"
while [ "$wait_time" -gt 0 ]; do
if eval "$cmd"; then
return 0
else
sleep "$sleep_time"
wait_time=$((wait_time-sleep_time))
fi
done
return 1
}
# Example: kube::util::trap_add 'echo "in trap DEBUG"' DEBUG
# See: http://stackoverflow.com/questions/3338030/multiple-bash-traps-for-the-same-signal
kube::util::trap_add() {
local trap_add_cmd
trap_add_cmd=$1
shift
for trap_add_name in "$@"; do
local existing_cmd
local new_cmd
# Grab the currently defined trap commands for this trap
existing_cmd=$(trap -p "${trap_add_name}" | awk -F"'" '{print $2}')
if [[ -z "${existing_cmd}" ]]; then
new_cmd="${trap_add_cmd}"
else
new_cmd="${trap_add_cmd};${existing_cmd}"
fi
# Assign the test. Disable the shellcheck warning telling that trap
# commands should be single quoted to avoid evaluating them at this
# point instead evaluating them at run time. The logic of adding new
# commands to a single trap requires them to be evaluated right away.
# shellcheck disable=SC2064
trap "${new_cmd}" "${trap_add_name}"
done
}
# Opposite of kube::util::ensure-temp-dir()
kube::util::cleanup-temp-dir() {
rm -rf "${KUBE_TEMP}"
}
# Create a temp dir that'll be deleted at the end of this bash session.
#
# Vars set:
# KUBE_TEMP
kube::util::ensure-temp-dir() {
if [[ -z ${KUBE_TEMP-} ]]; then
KUBE_TEMP=$(mktemp -d 2>/dev/null || mktemp -d -t kubernetes.XXXXXX)
kube::util::trap_add kube::util::cleanup-temp-dir EXIT
fi
}
kube::util::host_os() {
local host_os
case "$(uname -s)" in
Darwin)
host_os=darwin
;;
Linux)
host_os=linux
;;
*)
kube::log::error "Unsupported host OS. Must be Linux or Mac OS X."
exit 1
;;
esac
echo "${host_os}"
}
kube::util::host_arch() {
local host_arch
case "$(uname -m)" in
x86_64*)
host_arch=amd64
;;
i?86_64*)
host_arch=amd64
;;
amd64*)
host_arch=amd64
;;
aarch64*)
host_arch=arm64
;;
arm64*)
host_arch=arm64
;;
arm*)
host_arch=arm
;;
i?86*)
host_arch=x86
;;
s390x*)
host_arch=s390x
;;
ppc64le*)
host_arch=ppc64le
;;
*)
kube::log::error "Unsupported host arch. Must be x86_64, 386, arm, arm64, s390x or ppc64le."
exit 1
;;
esac
echo "${host_arch}"
}
# This figures out the host platform without relying on golang. We need this as
# we don't want a golang install to be a prerequisite to building yet we need
# this info to figure out where the final binaries are placed.
kube::util::host_platform() {
echo "$(kube::util::host_os)/$(kube::util::host_arch)"
}
# looks for $1 in well-known output locations for the platform ($2)
# $KUBE_ROOT must be set
kube::util::find-binary-for-platform() {
local -r lookfor="$1"
local -r platform="$2"
local locations=(
"${KUBE_ROOT}/_output/bin/${lookfor}"
"${KUBE_ROOT}/_output/dockerized/bin/${platform}/${lookfor}"
"${KUBE_ROOT}/_output/local/bin/${platform}/${lookfor}"
"${KUBE_ROOT}/platforms/${platform}/${lookfor}"
)
# Also search for binary in bazel build tree.
# The bazel go rules place some binaries in subtrees like
# "bazel-bin/source/path/linux_amd64_pure_stripped/binaryname", so make sure
# the platform name is matched in the path.
while IFS=$'\n' read -r location; do
locations+=("$location");
done < <(find "${KUBE_ROOT}/bazel-bin/" -type f -executable \
\( -path "*/${platform/\//_}*/${lookfor}" -o -path "*/${lookfor}" \) 2>/dev/null || true)
# search for executables for non-GNU versions of find (eg. BSD)
while IFS=$'\n' read -r location; do
locations+=("$location");
done < <(find "${KUBE_ROOT}/bazel-bin/" -type f -perm -111 \
\( -path "*/${platform/\//_}*/${lookfor}" -o -path "*/${lookfor}" \) 2>/dev/null || true)
# List most recently-updated location.
local -r bin=$( (ls -t "${locations[@]}" 2>/dev/null || true) | head -1 )
echo -n "${bin}"
}
# looks for $1 in well-known output locations for the host platform
# $KUBE_ROOT must be set
kube::util::find-binary() {
kube::util::find-binary-for-platform "$1" "$(kube::util::host_platform)"
}
# Run all known doc generators (today gendocs and genman for kubectl)
# $1 is the directory to put those generated documents
kube::util::gen-docs() {
local dest="$1"
# Find binary
gendocs=$(kube::util::find-binary "gendocs")
genkubedocs=$(kube::util::find-binary "genkubedocs")
genman=$(kube::util::find-binary "genman")
genyaml=$(kube::util::find-binary "genyaml")
genfeddocs=$(kube::util::find-binary "genfeddocs")
# TODO: If ${genfeddocs} is not used from anywhere (it isn't used at
# least from k/k tree), remove it completely.
kube::util::sourced_variable "${genfeddocs}"
mkdir -p "${dest}/docs/user-guide/kubectl/"
"${gendocs}" "${dest}/docs/user-guide/kubectl/"
mkdir -p "${dest}/docs/admin/"
"${genkubedocs}" "${dest}/docs/admin/" "kube-apiserver"
"${genkubedocs}" "${dest}/docs/admin/" "kube-controller-manager"
"${genkubedocs}" "${dest}/docs/admin/" "kube-proxy"
"${genkubedocs}" "${dest}/docs/admin/" "kube-scheduler"
"${genkubedocs}" "${dest}/docs/admin/" "kubelet"
"${genkubedocs}" "${dest}/docs/admin/" "kubeadm"
mkdir -p "${dest}/docs/man/man1/"
"${genman}" "${dest}/docs/man/man1/" "kube-apiserver"
"${genman}" "${dest}/docs/man/man1/" "kube-controller-manager"
"${genman}" "${dest}/docs/man/man1/" "kube-proxy"
"${genman}" "${dest}/docs/man/man1/" "kube-scheduler"
"${genman}" "${dest}/docs/man/man1/" "kubelet"
"${genman}" "${dest}/docs/man/man1/" "kubectl"
"${genman}" "${dest}/docs/man/man1/" "kubeadm"
mkdir -p "${dest}/docs/yaml/kubectl/"
"${genyaml}" "${dest}/docs/yaml/kubectl/"
# create the list of generated files
pushd "${dest}" > /dev/null || return 1
touch docs/.generated_docs
find . -type f | cut -sd / -f 2- | LC_ALL=C sort > docs/.generated_docs
popd > /dev/null || return 1
}
# Removes previously generated docs-- we don't want to check them in. $KUBE_ROOT
# must be set.
kube::util::remove-gen-docs() {
if [ -e "${KUBE_ROOT}/docs/.generated_docs" ]; then
# remove all of the old docs; we don't want to check them in.
while read -r file; do
rm "${KUBE_ROOT}/${file}" 2>/dev/null || true
done <"${KUBE_ROOT}/docs/.generated_docs"
# The docs/.generated_docs file lists itself, so we don't need to explicitly
# delete it.
fi
}
# Takes a group/version and returns the path to its location on disk, sans
# "pkg". E.g.:
# * default behavior: extensions/v1beta1 -> apis/extensions/v1beta1
# * default behavior for only a group: experimental -> apis/experimental
# * Special handling for empty group: v1 -> api/v1, unversioned -> api/unversioned
# * Special handling for groups suffixed with ".k8s.io": foo.k8s.io/v1 -> apis/foo/v1
# * Very special handling for when both group and version are "": / -> api
#
# $KUBE_ROOT must be set.
kube::util::group-version-to-pkg-path() {
local group_version="$1"
while IFS=$'\n' read -r api; do
if [[ "${api}" = "${group_version/.*k8s.io/}" ]]; then
echo "vendor/k8s.io/api/${group_version/.*k8s.io/}"
return
fi
done < <(cd "${KUBE_ROOT}/staging/src/k8s.io/api" && find . -name types.go -exec dirname {} \; | sed "s|\./||g" | sort)
# "v1" is the API GroupVersion
if [[ "${group_version}" == "v1" ]]; then
echo "vendor/k8s.io/api/core/v1"
return
fi
# Special cases first.
# TODO(lavalamp): Simplify this by moving pkg/api/v1 and splitting pkg/api,
# moving the results to pkg/apis/api.
case "${group_version}" in
# both group and version are "", this occurs when we generate deep copies for internal objects of the legacy v1 API.
__internal)
echo "pkg/apis/core"
;;
meta/v1)
echo "vendor/k8s.io/apimachinery/pkg/apis/meta/v1"
;;
meta/v1beta1)
echo "vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1"
;;
*.k8s.io)
echo "pkg/apis/${group_version%.*k8s.io}"
;;
*.k8s.io/*)
echo "pkg/apis/${group_version/.*k8s.io/}"
;;
*)
echo "pkg/apis/${group_version%__internal}"
;;
esac
}
# Takes a group/version and returns the swagger-spec file name.
# default behavior: extensions/v1beta1 -> extensions_v1beta1
# special case for v1: v1 -> v1
kube::util::gv-to-swagger-name() {
local group_version="$1"
case "${group_version}" in
v1)
echo "v1"
;;
*)
echo "${group_version%/*}_${group_version#*/}"
;;
esac
}
# Returns the name of the upstream remote repository name for the local git
# repo, e.g. "upstream" or "origin".
kube::util::git_upstream_remote_name() {
git remote -v | grep fetch |\
grep -E 'github.com[/:]kubernetes/kubernetes|k8s.io/kubernetes' |\
head -n 1 | awk '{print $1}'
}
# Exits script if working directory is dirty. If it's run interactively in the terminal
# the user can commit changes in a second terminal. This script will wait.
kube::util::ensure_clean_working_dir() {
while ! git diff HEAD --exit-code &>/dev/null; do
echo -e "\nUnexpected dirty working directory:\n"
if tty -s; then
git status -s
else
git diff -a # be more verbose in log files without tty
exit 1
fi | sed 's/^/ /'
echo -e "\nCommit your changes in another terminal and then continue here by pressing enter."
read -r
done 1>&2
}
# Find the base commit using:
# $PULL_BASE_SHA if set (from Prow)
# current ref from the remote upstream branch
kube::util::base_ref() {
local -r git_branch=$1
if [[ -n ${PULL_BASE_SHA:-} ]]; then
echo "${PULL_BASE_SHA}"
return
fi
full_branch="$(kube::util::git_upstream_remote_name)/${git_branch}"
# make sure the branch is valid, otherwise the check will pass erroneously.
if ! git describe "${full_branch}" >/dev/null; then
# abort!
exit 1
fi
echo "${full_branch}"
}
# Checks whether there are any files matching pattern $2 changed between the
# current branch and upstream branch named by $1.
# Returns 1 (false) if there are no changes
# 0 (true) if there are changes detected.
kube::util::has_changes() {
local -r git_branch=$1
local -r pattern=$2
local -r not_pattern=${3:-totallyimpossiblepattern}
local base_ref
base_ref=$(kube::util::base_ref "${git_branch}")
echo "Checking for '${pattern}' changes against '${base_ref}'"
# notice this uses ... to find the first shared ancestor
if git diff --name-only "${base_ref}...HEAD" | grep -v -E "${not_pattern}" | grep "${pattern}" > /dev/null; then
return 0
fi
# also check for pending changes
if git status --porcelain | grep -v -E "${not_pattern}" | grep "${pattern}" > /dev/null; then
echo "Detected '${pattern}' uncommitted changes."
return 0
fi
echo "No '${pattern}' changes detected."
return 1
}
kube::util::download_file() {
local -r url=$1
local -r destination_file=$2
rm "${destination_file}" 2&> /dev/null || true
for i in $(seq 5)
do
if ! curl -fsSL --retry 3 --keepalive-time 2 "${url}" -o "${destination_file}"; then
echo "Downloading ${url} failed. $((5-i)) retries left."
sleep 1
else
echo "Downloading ${url} succeed"
return 0
fi
done
return 1
}
# Test whether openssl is installed.
# Sets:
# OPENSSL_BIN: The path to the openssl binary to use
function kube::util::test_openssl_installed {
if ! openssl version >& /dev/null; then
echo "Failed to run openssl. Please ensure openssl is installed"
exit 1
fi
OPENSSL_BIN=$(command -v openssl)
}
# creates a client CA, args are sudo, dest-dir, ca-id, purpose
# purpose is dropped in after "key encipherment", you usually want
# '"client auth"'
# '"server auth"'
# '"client auth","server auth"'
function kube::util::create_signing_certkey {
local sudo=$1
local dest_dir=$2
local id=$3
local purpose=$4
# Create client ca
${sudo} /usr/bin/env bash -e <<EOF
rm -f "${dest_dir}/${id}-ca.crt" "${dest_dir}/${id}-ca.key"
${OPENSSL_BIN} req -x509 -sha256 -new -nodes -days 365 -newkey rsa:2048 -keyout "${dest_dir}/${id}-ca.key" -out "${dest_dir}/${id}-ca.crt" -subj "/C=xx/ST=x/L=x/O=x/OU=x/CN=ca/emailAddress=x/"
echo '{"signing":{"default":{"expiry":"43800h","usages":["signing","key encipherment",${purpose}]}}}' > "${dest_dir}/${id}-ca-config.json"
EOF
}
# signs a client certificate: args are sudo, dest-dir, CA, filename (roughly), username, groups...
function kube::util::create_client_certkey {
local sudo=$1
local dest_dir=$2
local ca=$3
local id=$4
local cn=${5:-$4}
local groups=""
local SEP=""
shift 5
while [ -n "${1:-}" ]; do
groups+="${SEP}{\"O\":\"$1\"}"
SEP=","
shift 1
done
${sudo} /usr/bin/env bash -e <<EOF
cd ${dest_dir}
echo '{"CN":"${cn}","names":[${groups}],"hosts":[""],"key":{"algo":"rsa","size":2048}}' | ${CFSSL_BIN} gencert -ca=${ca}.crt -ca-key=${ca}.key -config=${ca}-config.json - | ${CFSSLJSON_BIN} -bare client-${id}
mv "client-${id}-key.pem" "client-${id}.key"
mv "client-${id}.pem" "client-${id}.crt"
rm -f "client-${id}.csr"
EOF
}
# signs a serving certificate: args are sudo, dest-dir, ca, filename (roughly), subject, hosts...
function kube::util::create_serving_certkey {
local sudo=$1
local dest_dir=$2
local ca=$3
local id=$4
local cn=${5:-$4}
local hosts=""
local SEP=""
shift 5
while [ -n "${1:-}" ]; do
hosts+="${SEP}\"$1\""
SEP=","
shift 1
done
${sudo} /usr/bin/env bash -e <<EOF
cd ${dest_dir}
echo '{"CN":"${cn}","hosts":[${hosts}],"key":{"algo":"rsa","size":2048}}' | ${CFSSL_BIN} gencert -ca=${ca}.crt -ca-key=${ca}.key -config=${ca}-config.json - | ${CFSSLJSON_BIN} -bare serving-${id}
mv "serving-${id}-key.pem" "serving-${id}.key"
mv "serving-${id}.pem" "serving-${id}.crt"
rm -f "serving-${id}.csr"
EOF
}
# creates a self-contained kubeconfig: args are sudo, dest-dir, ca file, host, port, client id, token(optional)
function kube::util::write_client_kubeconfig {
local sudo=$1
local dest_dir=$2
local ca_file=$3
local api_host=$4
local api_port=$5
local client_id=$6
local token=${7:-}
cat <<EOF | ${sudo} tee "${dest_dir}"/"${client_id}".kubeconfig > /dev/null
apiVersion: v1
kind: Config
clusters:
- cluster:
certificate-authority: ${ca_file}
server: https://${api_host}:${api_port}/
name: local-up-cluster
users:
- user:
token: ${token}
client-certificate: ${dest_dir}/client-${client_id}.crt
client-key: ${dest_dir}/client-${client_id}.key
name: local-up-cluster
contexts:
- context:
cluster: local-up-cluster
user: local-up-cluster
name: local-up-cluster
current-context: local-up-cluster
EOF
# flatten the kubeconfig files to make them self contained
username=$(whoami)
${sudo} /usr/bin/env bash -e <<EOF
$(kube::util::find-binary kubectl) --kubeconfig="${dest_dir}/${client_id}.kubeconfig" config view --minify --flatten > "/tmp/${client_id}.kubeconfig"
mv -f "/tmp/${client_id}.kubeconfig" "${dest_dir}/${client_id}.kubeconfig"
chown ${username} "${dest_dir}/${client_id}.kubeconfig"
EOF
}
# list_staging_repos outputs a sorted list of repos in staging/src/k8s.io
# each entry will just be the $repo portion of staging/src/k8s.io/$repo/...
# $KUBE_ROOT must be set.
function kube::util::list_staging_repos() {
(
cd "${KUBE_ROOT}/staging/src/k8s.io" && \
find . -mindepth 1 -maxdepth 1 -type d | cut -c 3- | sort
)
}
# Determines if docker can be run, failures may simply require that the user be added to the docker group.
function kube::util::ensure_docker_daemon_connectivity {
IFS=" " read -ra DOCKER <<< "${DOCKER_OPTS}"
# Expand ${DOCKER[@]} only if it's not unset. This is to work around
# Bash 3 issue with unbound variable.
DOCKER=(docker ${DOCKER[@]:+"${DOCKER[@]}"})
if ! "${DOCKER[@]}" info > /dev/null 2>&1 ; then
cat <<'EOF' >&2
Can't connect to 'docker' daemon. please fix and retry.
Possible causes:
- Docker Daemon not started
- Linux: confirm via your init system
- macOS w/ docker-machine: run `docker-machine ls` and `docker-machine start <name>`
- macOS w/ Docker for Mac: Check the menu bar and start the Docker application
- DOCKER_HOST hasn't been set or is set incorrectly
- Linux: domain socket is used, DOCKER_* should be unset. In Bash run `unset ${!DOCKER_*}`
- macOS w/ docker-machine: run `eval "$(docker-machine env <name>)"`
- macOS w/ Docker for Mac: domain socket is used, DOCKER_* should be unset. In Bash run `unset ${!DOCKER_*}`
- Other things to check:
- Linux: User isn't in 'docker' group. Add and relogin.
- Something like 'sudo usermod -a -G docker ${USER}'
- RHEL7 bug and workaround: https://bugzilla.redhat.com/show_bug.cgi?id=1119282#c8
EOF
return 1
fi
}
# Wait for background jobs to finish. Return with
# an error status if any of the jobs failed.
kube::util::wait-for-jobs() {
local fail=0
local job
for job in $(jobs -p); do
wait "${job}" || fail=$((fail + 1))
done
return ${fail}
}
# kube::util::join <delim> <list...>
# Concatenates the list elements with the delimiter passed as first parameter
#
# Ex: kube::util::join , a b c
# -> a,b,c
function kube::util::join {
local IFS="$1"
shift
echo "$*"
}
# Downloads cfssl/cfssljson into $1 directory if they do not already exist in PATH
#
# Assumed vars:
# $1 (cfssl directory) (optional)
#
# Sets:
# CFSSL_BIN: The path of the installed cfssl binary
# CFSSLJSON_BIN: The path of the installed cfssljson binary
#
function kube::util::ensure-cfssl {
if command -v cfssl &>/dev/null && command -v cfssljson &>/dev/null; then
CFSSL_BIN=$(command -v cfssl)
CFSSLJSON_BIN=$(command -v cfssljson)
return 0
fi
host_arch=$(kube::util::host_arch)
if [[ "${host_arch}" != "amd64" ]]; then
echo "Cannot download cfssl on non-amd64 hosts and cfssl does not appear to be installed."
echo "Please install cfssl and cfssljson and verify they are in \$PATH."
echo "Hint: export PATH=\$PATH:\$GOPATH/bin; go get -u github.com/cloudflare/cfssl/cmd/..."
exit 1
fi
# Create a temp dir for cfssl if no directory was given
local cfssldir=${1:-}
if [[ -z "${cfssldir}" ]]; then
kube::util::ensure-temp-dir
cfssldir="${KUBE_TEMP}/cfssl"
fi
mkdir -p "${cfssldir}"
pushd "${cfssldir}" > /dev/null || return 1
echo "Unable to successfully run 'cfssl' from ${PATH}; downloading instead..."
kernel=$(uname -s)
case "${kernel}" in
Linux)
curl --retry 10 -L -o cfssl https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
curl --retry 10 -L -o cfssljson https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
;;
Darwin)
curl --retry 10 -L -o cfssl https://pkg.cfssl.org/R1.2/cfssl_darwin-amd64
curl --retry 10 -L -o cfssljson https://pkg.cfssl.org/R1.2/cfssljson_darwin-amd64
;;
*)
echo "Unknown, unsupported platform: ${kernel}." >&2
echo "Supported platforms: Linux, Darwin." >&2
exit 2
esac
chmod +x cfssl || true
chmod +x cfssljson || true
CFSSL_BIN="${cfssldir}/cfssl"
CFSSLJSON_BIN="${cfssldir}/cfssljson"
if [[ ! -x ${CFSSL_BIN} || ! -x ${CFSSLJSON_BIN} ]]; then
echo "Failed to download 'cfssl'. Please install cfssl and cfssljson and verify they are in \$PATH."
echo "Hint: export PATH=\$PATH:\$GOPATH/bin; go get -u github.com/cloudflare/cfssl/cmd/..."
exit 1
fi
popd > /dev/null || return 1
}
# kube::util::ensure_dockerized
# Confirms that the script is being run inside a kube-build image
#
function kube::util::ensure_dockerized {
if [[ -f /kube-build-image ]]; then
return 0
else
echo "ERROR: This script is designed to be run inside a kube-build container"
exit 1
fi
}
# kube::util::ensure-gnu-sed
# Determines which sed binary is gnu-sed on linux/darwin
#
# Sets:
# SED: The name of the gnu-sed binary
#
function kube::util::ensure-gnu-sed {
# NOTE: the echo below is a workaround to ensure sed is executed before the grep.
# see: https://github.com/kubernetes/kubernetes/issues/87251
sed_help="$(LANG=C sed --help 2>&1 || true)"
if echo "${sed_help}" | grep -q "GNU\|BusyBox"; then
SED="sed"
elif command -v gsed &>/dev/null; then
SED="gsed"
else
kube::log::error "Failed to find GNU sed as sed or gsed. If you are on Mac: brew install gnu-sed." >&2
return 1
fi
kube::util::sourced_variable "${SED}"
}
# kube::util::check-file-in-alphabetical-order <file>
# Check that the file is in alphabetical order
#
function kube::util::check-file-in-alphabetical-order {
local failure_file="$1"
if ! diff -u "${failure_file}" <(LC_ALL=C sort "${failure_file}"); then
{
echo
echo "${failure_file} is not in alphabetical order. Please sort it:"
echo
echo " LC_ALL=C sort -o ${failure_file} ${failure_file}"
echo
} >&2
false
fi
}
# kube::util::require-jq
# Checks whether jq is installed.
function kube::util::require-jq {
if ! command -v jq &>/dev/null; then
echo "jq not found. Please install." 1>&2
return 1
fi
}
# outputs md5 hash of $1, works on macOS and Linux
function kube::util::md5() {
if which md5 >/dev/null 2>&1; then
md5 -q "$1"
else
md5sum "$1" | awk '{ print $1 }'
fi
}
# kube::util::read-array
# Reads in stdin and adds it line by line to the array provided. This can be
# used instead of "mapfile -t", and is bash 3 compatible.
#
# Assumed vars:
# $1 (name of array to create/modify)
#
# Example usage:
# kube::util::read-array files < <(ls -1)
#
function kube::util::read-array {
local i=0
unset -v "$1"
while IFS= read -r "$1[i++]"; do :; done
eval "[[ \${$1[--i]} ]]" || unset "$1[i]" # ensures last element isn't empty
}
# Some useful colors.
if [[ -z "${color_start-}" ]]; then
declare -r color_start="\033["
declare -r color_red="${color_start}0;31m"
declare -r color_yellow="${color_start}0;33m"
declare -r color_green="${color_start}0;32m"
declare -r color_blue="${color_start}1;34m"
declare -r color_cyan="${color_start}1;36m"
declare -r color_norm="${color_start}0m"
kube::util::sourced_variable "${color_start}"
kube::util::sourced_variable "${color_red}"
kube::util::sourced_variable "${color_yellow}"
kube::util::sourced_variable "${color_green}"
kube::util::sourced_variable "${color_blue}"
kube::util::sourced_variable "${color_cyan}"
kube::util::sourced_variable "${color_norm}"
fi
# ex: ts=2 sw=2 et filetype=sh
| {
"content_hash": "304de8a0348884b904c7f0f5568c18f5",
"timestamp": "",
"source": "github",
"line_count": 791,
"max_line_length": 212,
"avg_line_length": 31.448798988622,
"alnum_prop": 0.6310500080398778,
"repo_name": "sethpollack/kubernetes",
"id": "01f8b4bc76515264cff1e3346fbeae740fae608f",
"size": "24876",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "hack/lib/util.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2539"
},
{
"name": "Go",
"bytes": "43063645"
},
{
"name": "HTML",
"bytes": "2600590"
},
{
"name": "Makefile",
"bytes": "78516"
},
{
"name": "Nginx",
"bytes": "1608"
},
{
"name": "PowerShell",
"bytes": "4261"
},
{
"name": "Protocol Buffer",
"bytes": "651242"
},
{
"name": "Python",
"bytes": "1345694"
},
{
"name": "SaltStack",
"bytes": "55288"
},
{
"name": "Shell",
"bytes": "1724335"
}
],
"symlink_target": ""
} |
#ifndef IVW_VOLUMEGRADIENT_H
#define IVW_VOLUMEGRADIENT_H
#include <modules/base/basemoduledefine.h>
#include <memory>
namespace inviwo {
class Volume;
namespace util {
IVW_MODULE_BASE_API std::shared_ptr<Volume> gradientVolume(std::shared_ptr<const Volume> volume,
int channel);
} // namespace util
} // namespace inviwo
#endif // IVW_VOLUMEGRADIENT_H
| {
"content_hash": "23f54ba3ac92775d07c14631094fc366",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 96,
"avg_line_length": 19.318181818181817,
"alnum_prop": 0.6423529411764706,
"repo_name": "Sparkier/inviwo",
"id": "d4499c3c9717f8d69412c233a371cb16f0b764f3",
"size": "2008",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/base/include/modules/base/algorithm/volume/volumegradient.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "146426"
},
{
"name": "C++",
"bytes": "11871087"
},
{
"name": "CMake",
"bytes": "574616"
},
{
"name": "CSS",
"bytes": "18058"
},
{
"name": "GLSL",
"bytes": "504032"
},
{
"name": "Groovy",
"bytes": "11430"
},
{
"name": "HTML",
"bytes": "79818"
},
{
"name": "JavaScript",
"bytes": "173791"
},
{
"name": "Mathematica",
"bytes": "109319"
},
{
"name": "Python",
"bytes": "1817954"
},
{
"name": "QMake",
"bytes": "172"
},
{
"name": "TeX",
"bytes": "5813"
}
],
"symlink_target": ""
} |
'use strict'
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const os = require('os')
const qs = require('querystring')
const http = require('http')
const {closeWindow} = require('./window-helpers')
const {ipcRenderer, remote, screen} = require('electron')
const {app, ipcMain, BrowserWindow, protocol, webContents} = remote
const isCI = remote.getGlobal('isCi')
const nativeModulesEnabled = remote.getGlobal('nativeModulesEnabled')
describe('BrowserWindow module', function () {
var fixtures = path.resolve(__dirname, 'fixtures')
var w = null
var server, postData
before(function (done) {
const filePath = path.join(fixtures, 'pages', 'a.html')
const fileStats = fs.statSync(filePath)
postData = [
{
type: 'rawData',
bytes: new Buffer('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
]
server = http.createServer(function (req, res) {
function respond () {
if (req.method === 'POST') {
let body = ''
req.on('data', (data) => {
if (data) {
body += data
}
})
req.on('end', () => {
let parsedData = qs.parse(body)
fs.readFile(filePath, (err, data) => {
if (err) return
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end()
}
})
})
} else {
res.end()
}
}
setTimeout(respond, req.url.includes('slow') ? 200 : 0)
})
server.listen(0, '127.0.0.1', function () {
server.url = 'http://127.0.0.1:' + server.address().port
done()
})
})
after(function () {
server.close()
server = null
})
beforeEach(function () {
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
})
})
afterEach(function () {
return closeWindow(w).then(function () { w = null })
})
describe('BrowserWindow.close()', function () {
let server
before(function (done) {
server = http.createServer((request, response) => {
switch (request.url) {
case '/404':
response.statusCode = '404'
response.end()
break
case '/301':
response.statusCode = '301'
response.setHeader('Location', '/200')
response.end()
break
case '/200':
response.statusCode = '200'
response.end('hello')
break
case '/title':
response.statusCode = '200'
response.end('<title>Hello</title>')
break
default:
done('unsupported endpoint')
}
}).listen(0, '127.0.0.1', () => {
server.url = 'http://127.0.0.1:' + server.address().port
done()
})
})
after(function () {
server.close()
server = null
})
it('should emit unload handler', function (done) {
w.webContents.on('did-finish-load', function () {
w.close()
})
w.once('closed', function () {
var test = path.join(fixtures, 'api', 'unload')
var content = fs.readFileSync(test)
fs.unlinkSync(test)
assert.equal(String(content), 'unload')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'unload.html'))
})
it('should emit beforeunload handler', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.webContents.on('did-finish-load', function () {
w.close()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false.html'))
})
it('should not crash when invoked synchronously inside navigation observer', function (done) {
const events = [
{ name: 'did-start-loading', url: `${server.url}/200` },
{ name: 'did-get-redirect-request', url: `${server.url}/301` },
{ name: 'did-get-response-details', url: `${server.url}/200` },
{ name: 'dom-ready', url: `${server.url}/200` },
{ name: 'page-title-updated', url: `${server.url}/title` },
{ name: 'did-stop-loading', url: `${server.url}/200` },
{ name: 'did-finish-load', url: `${server.url}/200` },
{ name: 'did-frame-finish-load', url: `${server.url}/200` },
{ name: 'did-fail-load', url: `${server.url}/404` }
]
const responseEvent = 'window-webContents-destroyed'
function* genNavigationEvent () {
let eventOptions = null
while ((eventOptions = events.shift()) && events.length) {
let w = new BrowserWindow({show: false})
eventOptions.id = w.id
eventOptions.responseEvent = responseEvent
ipcRenderer.send('test-webcontents-navigation-observer', eventOptions)
yield 1
}
}
let gen = genNavigationEvent()
ipcRenderer.on(responseEvent, function () {
if (!gen.next().value) done()
})
gen.next()
})
})
describe('window.close()', function () {
it('should emit unload handler', function (done) {
w.once('closed', function () {
var test = path.join(fixtures, 'api', 'close')
var content = fs.readFileSync(test)
fs.unlinkSync(test)
assert.equal(String(content), 'close')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close.html'))
})
it('should emit beforeunload handler', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html'))
})
})
describe('BrowserWindow.destroy()', function () {
it('prevents users to access methods of webContents', function () {
const contents = w.webContents
w.destroy()
assert.throws(function () {
contents.getId()
}, /Object has been destroyed/)
})
})
describe('BrowserWindow.loadURL(url)', function () {
it('should emit did-start-loading event', function (done) {
w.webContents.on('did-start-loading', function () {
done()
})
w.loadURL('about:blank')
})
it('should emit ready-to-show event', function (done) {
w.on('ready-to-show', function () {
done()
})
w.loadURL('about:blank')
})
it('should emit did-get-response-details event', function (done) {
// expected {fileName: resourceType} pairs
var expectedResources = {
'did-get-response-details.html': 'mainFrame',
'logo.png': 'image'
}
var responses = 0
w.webContents.on('did-get-response-details', function (event, status, newUrl, oldUrl, responseCode, method, referrer, headers, resourceType) {
responses++
var fileName = newUrl.slice(newUrl.lastIndexOf('/') + 1)
var expectedType = expectedResources[fileName]
assert(!!expectedType, `Unexpected response details for ${newUrl}`)
assert(typeof status === 'boolean', 'status should be boolean')
assert.equal(responseCode, 200)
assert.equal(method, 'GET')
assert(typeof referrer === 'string', 'referrer should be string')
assert(!!headers, 'headers should be present')
assert(typeof headers === 'object', 'headers should be object')
assert.equal(resourceType, expectedType, 'Incorrect resourceType')
if (responses === Object.keys(expectedResources).length) {
done()
}
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'did-get-response-details.html'))
})
it('should emit did-fail-load event for files that do not exist', function (done) {
w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) {
assert.equal(code, -6)
assert.equal(desc, 'ERR_FILE_NOT_FOUND')
assert.equal(isMainFrame, true)
done()
})
w.loadURL('file://a.txt')
})
it('should emit did-fail-load event for invalid URL', function (done) {
w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) {
assert.equal(desc, 'ERR_INVALID_URL')
assert.equal(code, -300)
assert.equal(isMainFrame, true)
done()
})
w.loadURL('http://example:port')
})
it('should set `mainFrame = false` on did-fail-load events in iframes', function (done) {
w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) {
assert.equal(isMainFrame, false)
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'did-fail-load-iframe.html'))
})
it('does not crash in did-fail-provisional-load handler', function (done) {
w.webContents.once('did-fail-provisional-load', function () {
w.loadURL('http://127.0.0.1:11111')
done()
})
w.loadURL('http://127.0.0.1:11111')
})
it('should emit did-fail-load event for URL exceeding character limit', function (done) {
w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) {
assert.equal(desc, 'ERR_INVALID_URL')
assert.equal(code, -300)
assert.equal(isMainFrame, true)
done()
})
const data = new Buffer(2 * 1024 * 1024).toString('base64')
w.loadURL(`data:image/png;base64,${data}`)
})
describe('POST navigations', function () {
afterEach(() => {
w.webContents.session.webRequest.onBeforeSendHeaders(null)
})
it('supports specifying POST data', function (done) {
w.webContents.on('did-finish-load', () => done())
w.loadURL(server.url, {postData: postData})
})
it('sets the content type header on URL encoded forms', function (done) {
w.webContents.on('did-finish-load', () => {
w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
assert.equal(details.requestHeaders['content-type'], 'application/x-www-form-urlencoded')
done()
})
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.submit()
`)
})
w.loadURL(server.url)
})
it('sets the content type header on multi part forms', function (done) {
w.webContents.on('did-finish-load', () => {
w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
assert(details.requestHeaders['content-type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary'))
done()
})
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`)
})
w.loadURL(server.url)
})
})
it('should support support base url for data urls', (done) => {
ipcMain.once('answer', function (event, test) {
assert.equal(test, 'test')
done()
})
w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', {baseURLForDataURL: `file://${path.join(fixtures, 'api')}${path.sep}`})
})
})
describe('will-navigate event', function () {
it('allows the window to be closed from the event listener', (done) => {
ipcRenderer.send('close-on-will-navigate', w.id)
ipcRenderer.once('closed-on-will-navigate', () => {
done()
})
w.loadURL('file://' + fixtures + '/pages/will-navigate.html')
})
})
describe('BrowserWindow.show()', function () {
if (isCI) {
return
}
it('should focus on window', function () {
w.show()
assert(w.isFocused())
})
it('should make the window visible', function () {
w.show()
assert(w.isVisible())
})
it('emits when window is shown', function (done) {
w.once('show', function () {
assert.equal(w.isVisible(), true)
done()
})
w.show()
})
})
describe('BrowserWindow.hide()', function () {
if (isCI) {
return
}
it('should defocus on window', function () {
w.hide()
assert(!w.isFocused())
})
it('should make the window not visible', function () {
w.show()
w.hide()
assert(!w.isVisible())
})
it('emits when window is hidden', function (done) {
w.show()
w.once('hide', function () {
assert.equal(w.isVisible(), false)
done()
})
w.hide()
})
})
describe('BrowserWindow.showInactive()', function () {
it('should not focus on window', function () {
w.showInactive()
assert(!w.isFocused())
})
})
describe('BrowserWindow.focus()', function () {
it('does not make the window become visible', function () {
assert.equal(w.isVisible(), false)
w.focus()
assert.equal(w.isVisible(), false)
})
})
describe('BrowserWindow.blur()', function () {
it('removes focus from window', function () {
w.blur()
assert(!w.isFocused())
})
})
describe('BrowserWindow.capturePage(rect, callback)', function () {
it('calls the callback with a Buffer', function (done) {
w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
}, function (image) {
assert.equal(image.isEmpty(), true)
done()
})
})
})
describe('BrowserWindow.setSize(width, height)', function () {
it('sets the window size', function (done) {
var size = [300, 400]
w.once('resize', function () {
assertBoundsEqual(w.getSize(), size)
done()
})
w.setSize(size[0], size[1])
})
})
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', function () {
it('sets the maximum and minimum size of the window', function () {
assert.deepEqual(w.getMinimumSize(), [0, 0])
assert.deepEqual(w.getMaximumSize(), [0, 0])
w.setMinimumSize(100, 100)
assertBoundsEqual(w.getMinimumSize(), [100, 100])
assertBoundsEqual(w.getMaximumSize(), [0, 0])
w.setMaximumSize(900, 600)
assertBoundsEqual(w.getMinimumSize(), [100, 100])
assertBoundsEqual(w.getMaximumSize(), [900, 600])
})
})
describe('BrowserWindow.setAspectRatio(ratio)', function () {
it('resets the behaviour when passing in 0', function (done) {
var size = [300, 400]
w.setAspectRatio(1 / 2)
w.setAspectRatio(0)
w.once('resize', function () {
assertBoundsEqual(w.getSize(), size)
done()
})
w.setSize(size[0], size[1])
})
})
describe('BrowserWindow.setPosition(x, y)', function () {
it('sets the window position', function (done) {
var pos = [10, 10]
w.once('move', function () {
var newPos = w.getPosition()
assert.equal(newPos[0], pos[0])
assert.equal(newPos[1], pos[1])
done()
})
w.setPosition(pos[0], pos[1])
})
})
describe('BrowserWindow.setContentSize(width, height)', function () {
it('sets the content size', function () {
var size = [400, 400]
w.setContentSize(size[0], size[1])
var after = w.getContentSize()
assert.equal(after[0], size[0])
assert.equal(after[1], size[1])
})
it('works for a frameless window', function () {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
})
var size = [400, 400]
w.setContentSize(size[0], size[1])
var after = w.getContentSize()
assert.equal(after[0], size[0])
assert.equal(after[1], size[1])
})
})
describe('BrowserWindow.setContentBounds(bounds)', function () {
it('sets the content size and position', function (done) {
var bounds = {x: 10, y: 10, width: 250, height: 250}
w.once('resize', function () {
assertBoundsEqual(w.getContentBounds(), bounds)
done()
})
w.setContentBounds(bounds)
})
it('works for a frameless window', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
})
var bounds = {x: 10, y: 10, width: 250, height: 250}
w.once('resize', function () {
assert.deepEqual(w.getContentBounds(), bounds)
done()
})
w.setContentBounds(bounds)
})
})
describe('BrowserWindow.setProgressBar(progress)', function () {
it('sets the progress', function () {
assert.doesNotThrow(function () {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'))
}
w.setProgressBar(0.5)
if (process.platform === 'darwin') {
app.dock.setIcon(null)
}
w.setProgressBar(-1)
})
})
it('sets the progress using "paused" mode', function () {
assert.doesNotThrow(function () {
w.setProgressBar(0.5, {mode: 'paused'})
})
})
it('sets the progress using "error" mode', function () {
assert.doesNotThrow(function () {
w.setProgressBar(0.5, {mode: 'error'})
})
})
it('sets the progress using "normal" mode', function () {
assert.doesNotThrow(function () {
w.setProgressBar(0.5, {mode: 'normal'})
})
})
})
describe('BrowserWindow.setAlwaysOnTop(flag, level)', function () {
it('sets the window as always on top', function () {
assert.equal(w.isAlwaysOnTop(), false)
w.setAlwaysOnTop(true, 'screen-saver')
assert.equal(w.isAlwaysOnTop(), true)
w.setAlwaysOnTop(false)
assert.equal(w.isAlwaysOnTop(), false)
w.setAlwaysOnTop(true)
assert.equal(w.isAlwaysOnTop(), true)
})
it('raises an error when relativeLevel is out of bounds', function () {
if (process.platform !== 'darwin') return
assert.throws(function () {
w.setAlwaysOnTop(true, '', -2147483644)
})
assert.throws(function () {
w.setAlwaysOnTop(true, '', 2147483632)
})
})
})
describe('BrowserWindow.alwaysOnTop() resets level on minimize', function () {
if (process.platform !== 'darwin') {
return
}
it('resets the windows level on minimize', function () {
assert.equal(w.isAlwaysOnTop(), false)
w.setAlwaysOnTop(true, 'screen-saver')
assert.equal(w.isAlwaysOnTop(), true)
w.minimize()
assert.equal(w.isAlwaysOnTop(), false)
w.restore()
assert.equal(w.isAlwaysOnTop(), true)
})
})
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
if (process.platform !== 'darwin') {
it('is not available on non-macOS platforms', () => {
assert.ok(!w.setAutoHideCursor)
})
return
}
it('allows changing cursor auto-hiding', () => {
assert.doesNotThrow(() => {
w.setAutoHideCursor(false)
w.setAutoHideCursor(true)
})
})
})
describe('BrowserWindow.setVibrancy(type)', function () {
it('allows setting, changing, and removing the vibrancy', function () {
assert.doesNotThrow(function () {
w.setVibrancy('light')
w.setVibrancy('dark')
w.setVibrancy(null)
w.setVibrancy('ultra-dark')
w.setVibrancy('')
})
})
})
describe('BrowserWindow.setAppDetails(options)', function () {
it('supports setting the app details', function () {
if (process.platform !== 'win32') return
const iconPath = path.join(fixtures, 'assets', 'icon.ico')
assert.doesNotThrow(function () {
w.setAppDetails({appId: 'my.app.id'})
w.setAppDetails({appIconPath: iconPath, appIconIndex: 0})
w.setAppDetails({appIconPath: iconPath})
w.setAppDetails({relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name'})
w.setAppDetails({relaunchCommand: 'my-app.exe arg1 arg2'})
w.setAppDetails({relaunchDisplayName: 'My app name'})
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
})
w.setAppDetails({})
})
assert.throws(function () {
w.setAppDetails()
}, /Insufficient number of arguments\./)
})
})
describe('BrowserWindow.fromId(id)', function () {
it('returns the window with id', function () {
assert.equal(w.id, BrowserWindow.fromId(w.id).id)
})
})
describe('BrowserWindow.fromWebContents(webContents)', function () {
let contents = null
beforeEach(function () {
contents = webContents.create({})
})
afterEach(function () {
contents.destroy()
})
it('returns the window with the webContents', function () {
assert.equal(BrowserWindow.fromWebContents(w.webContents).id, w.id)
assert.equal(BrowserWindow.fromWebContents(contents), undefined)
})
})
describe('BrowserWindow.fromDevToolsWebContents(webContents)', function () {
let contents = null
beforeEach(function () {
contents = webContents.create({})
})
afterEach(function () {
contents.destroy()
})
it('returns the window with the webContents', function (done) {
w.webContents.once('devtools-opened', () => {
assert.equal(BrowserWindow.fromDevToolsWebContents(w.devToolsWebContents).id, w.id)
assert.equal(BrowserWindow.fromDevToolsWebContents(w.webContents), undefined)
assert.equal(BrowserWindow.fromDevToolsWebContents(contents), undefined)
done()
})
w.webContents.openDevTools()
})
})
describe('"useContentSize" option', function () {
it('make window created with content size when used', function () {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
})
var contentSize = w.getContentSize()
assert.equal(contentSize[0], 400)
assert.equal(contentSize[1], 400)
})
it('make window created with window size when not used', function () {
var size = w.getSize()
assert.equal(size[0], 400)
assert.equal(size[1], 400)
})
it('works for a frameless window', function () {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
})
var contentSize = w.getContentSize()
assert.equal(contentSize[0], 400)
assert.equal(contentSize[1], 400)
var size = w.getSize()
assert.equal(size[0], 400)
assert.equal(size[1], 400)
})
})
describe('"titleBarStyle" option', function () {
if (process.platform !== 'darwin') {
return
}
if (parseInt(os.release().split('.')[0]) < 14) {
return
}
it('creates browser window with hidden title bar', function () {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
})
var contentSize = w.getContentSize()
assert.equal(contentSize[1], 400)
})
it('creates browser window with hidden inset title bar', function () {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden-inset'
})
var contentSize = w.getContentSize()
assert.equal(contentSize[1], 400)
})
})
describe('enableLargerThanScreen" option', function () {
if (process.platform === 'linux') {
return
}
beforeEach(function () {
w.destroy()
w = new BrowserWindow({
show: true,
width: 400,
height: 400,
enableLargerThanScreen: true
})
})
it('can move the window out of screen', function () {
w.setPosition(-10, -10)
var after = w.getPosition()
assert.equal(after[0], -10)
assert.equal(after[1], -10)
})
it('can set the window larger than screen', function () {
var size = screen.getPrimaryDisplay().size
size.width += 100
size.height += 100
w.setSize(size.width, size.height)
assertBoundsEqual(w.getSize(), [size.width, size.height])
})
})
describe('"zoomToPageWidth" option', function () {
it('sets the window width to the page width when used', function () {
if (process.platform !== 'darwin') return
w.destroy()
w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
})
w.maximize()
assert.equal(w.getSize()[0], 500)
})
})
describe('"tabbingIdentifier" option', function () {
it('can be set on a window', function () {
w.destroy()
w = new BrowserWindow({
tabbingIdentifier: 'group1'
})
w.destroy()
w = new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
})
})
})
describe('"webPreferences" option', function () {
afterEach(function () {
ipcMain.removeAllListeners('answer')
})
describe('"preload" option', function () {
it('loads the script before other scripts in window', function (done) {
var preload = path.join(fixtures, 'module', 'set-global.js')
ipcMain.once('answer', function (event, test) {
assert.equal(test, 'preload')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html'))
})
it('can successfully delete the Buffer global', function (done) {
var preload = path.join(fixtures, 'module', 'delete-buffer.js')
ipcMain.once('answer', function (event, test) {
assert.equal(test.toString(), 'buffer')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html'))
})
})
describe('"node-integration" option', function () {
it('disables node integration when specified to false', function (done) {
var preload = path.join(fixtures, 'module', 'send-later.js')
ipcMain.once('answer', function (event, typeofProcess, typeofBuffer) {
assert.equal(typeofProcess, 'undefined')
assert.equal(typeofBuffer, 'undefined')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload,
nodeIntegration: false
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'blank.html'))
})
})
describe('"sandbox" option', function () {
function waitForEvents (emitter, events, callback) {
let count = events.length
for (let event of events) {
emitter.once(event, () => {
if (!--count) callback()
})
}
}
const preload = path.join(fixtures, 'module', 'preload-sandbox.js')
// http protocol to simulate accessing another domain. This is required
// because the code paths for cross domain popups is different.
function crossDomainHandler (request, callback) {
callback({
mimeType: 'text/html',
data: `<html><body><h1>${request.url}</h1></body></html>`
})
}
before(function (done) {
protocol.interceptStringProtocol('http', crossDomainHandler, function () {
done()
})
})
after(function (done) {
protocol.uninterceptProtocol('http', function () {
done()
})
})
it('exposes ipcRenderer to preload script', function (done) {
ipcMain.once('answer', function (event, test) {
assert.equal(test, 'preload')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preload
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html'))
})
it('exposes "exit" event to preload script', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preload
}
})
let htmlPath = path.join(fixtures, 'api', 'sandbox.html?exit-event')
const pageUrl = 'file://' + htmlPath
w.loadURL(pageUrl)
ipcMain.once('answer', function (event, url) {
let expectedUrl = pageUrl
if (process.platform === 'win32') {
expectedUrl = 'file:///' + htmlPath.replace(/\\/g, '/')
}
assert.equal(url, expectedUrl)
done()
})
})
it('should open windows in same domain with cross-scripting enabled', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preload
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
let htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open')
const pageUrl = 'file://' + htmlPath
w.loadURL(pageUrl)
w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
let expectedUrl = pageUrl
if (process.platform === 'win32') {
expectedUrl = 'file:///' + htmlPath.replace(/\\/g, '/')
}
assert.equal(url, expectedUrl)
assert.equal(frameName, 'popup!')
assert.equal(options.x, 50)
assert.equal(options.y, 60)
assert.equal(options.width, 500)
assert.equal(options.height, 600)
ipcMain.once('answer', function (event, html) {
assert.equal(html, '<h1>scripting from opener</h1>')
done()
})
})
})
it('should open windows in another domain with cross-scripting disabled', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preload
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
let htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open-external')
const pageUrl = 'file://' + htmlPath
let popupWindow
w.loadURL(pageUrl)
w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
assert.equal(url, 'http://www.google.com/#q=electron')
assert.equal(options.x, 55)
assert.equal(options.y, 65)
assert.equal(options.width, 505)
assert.equal(options.height, 605)
ipcMain.once('child-loaded', function (event, openerIsNull, html) {
assert(openerIsNull)
assert.equal(html, '<h1>http://www.google.com/#q=electron</h1>')
ipcMain.once('answer', function (event, exceptionMessage) {
assert(/Blocked a frame with origin/.test(exceptionMessage))
// FIXME this popup window should be closed in sandbox.html
closeWindow(popupWindow, {assertSingleWindow: false}).then(() => {
popupWindow = null
done()
})
})
w.webContents.send('child-loaded')
})
})
app.once('browser-window-created', function (event, window) {
popupWindow = window
})
})
it('should inherit the sandbox setting in opened windows', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcMain.once('answer', (event, args) => {
assert.equal(args.includes('--enable-sandbox'), true)
done()
})
w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
})
it('should open windows with the options configured via new-window event listeners', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'foo', 'bar')
ipcMain.once('answer', (event, args, webPreferences) => {
assert.equal(webPreferences.foo, 'bar')
done()
})
w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
})
it('should set ipc event sender correctly', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preload
}
})
let htmlPath = path.join(fixtures, 'api', 'sandbox.html?verify-ipc-sender')
const pageUrl = 'file://' + htmlPath
w.loadURL(pageUrl)
w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
let parentWc = w.webContents
let childWc = options.webContents
assert.notEqual(parentWc, childWc)
ipcMain.once('parent-ready', function (event) {
assert.equal(parentWc, event.sender)
parentWc.send('verified')
})
ipcMain.once('child-ready', function (event) {
assert.equal(childWc, event.sender)
childWc.send('verified')
})
waitForEvents(ipcMain, [
'parent-answer',
'child-answer'
], done)
})
})
describe('event handling', function () {
it('works for window events', function (done) {
waitForEvents(w, [
'page-title-updated'
], done)
w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?window-events'))
})
it('works for web contents events', function (done) {
waitForEvents(w.webContents, [
'did-navigate',
'did-fail-load',
'did-stop-loading'
], done)
w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?webcontents-stop'))
waitForEvents(w.webContents, [
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
], done)
w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?webcontents-events'))
})
})
it('can get printer list', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preload
}
})
w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
w.webContents.once('did-finish-load', function () {
const printers = w.webContents.getPrinters()
assert.equal(Array.isArray(printers), true)
done()
})
})
it('can print to PDF', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preload
}
})
w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
w.webContents.once('did-finish-load', function () {
w.webContents.printToPDF({}, function (error, data) {
assert.equal(error, null)
assert.equal(data instanceof Buffer, true)
assert.notEqual(data.length, 0)
done()
})
})
})
it('supports calling preventDefault on new-window events', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
const initialWebContents = webContents.getAllWebContents()
ipcRenderer.send('prevent-next-new-window', w.webContents.id)
w.webContents.once('new-window', () => {
assert.deepEqual(webContents.getAllWebContents(), initialWebContents)
done()
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'window-open.html'))
})
it('releases memory after popup is closed', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload,
sandbox: true
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?allocate-memory'))
ipcMain.once('answer', function (event, {bytesBeforeOpen, bytesAfterOpen, bytesAfterClose}) {
const memoryIncreaseByOpen = bytesAfterOpen - bytesBeforeOpen
const memoryDecreaseByClose = bytesAfterOpen - bytesAfterClose
// decreased memory should be less than increased due to factors we
// can't control, but given the amount of memory allocated in the
// fixture, we can reasonably expect decrease to be at least 70% of
// increase
assert(memoryDecreaseByClose > memoryIncreaseByOpen * 0.7)
done()
})
})
// see #9387
it('properly manages remote object references after page reload', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload,
sandbox: true
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?reload-remote'))
ipcMain.on('get-remote-module-path', (event) => {
event.returnValue = path.join(fixtures, 'module', 'hello.js')
})
let reload = false
ipcMain.on('reloaded', (event) => {
event.returnValue = reload
reload = !reload
})
ipcMain.once('reload', (event) => {
event.sender.reload()
})
ipcMain.once('answer', (event, arg) => {
ipcMain.removeAllListeners('reloaded')
ipcMain.removeAllListeners('get-remote-module-path')
assert.equal(arg, 'hi')
done()
})
})
it('properly manages remote object references after page reload in child window', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload,
sandbox: true
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?reload-remote-child'))
ipcMain.on('get-remote-module-path', (event) => {
event.returnValue = path.join(fixtures, 'module', 'hello-child.js')
})
let reload = false
ipcMain.on('reloaded', (event) => {
event.returnValue = reload
reload = !reload
})
ipcMain.once('reload', (event) => {
event.sender.reload()
})
ipcMain.once('answer', (event, arg) => {
ipcMain.removeAllListeners('reloaded')
ipcMain.removeAllListeners('get-remote-module-path')
assert.equal(arg, 'hi child window')
done()
})
})
})
describe('nativeWindowOpen option', () => {
beforeEach(() => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true
}
})
})
it('opens window of about:blank with cross-scripting enabled', (done) => {
ipcMain.once('answer', (event, content) => {
assert.equal(content, 'Hello')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'native-window-open-blank.html'))
})
it('opens window of same domain with cross-scripting enabled', (done) => {
ipcMain.once('answer', (event, content) => {
assert.equal(content, 'Hello')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'native-window-open-file.html'))
})
it('blocks accessing cross-origin frames', (done) => {
ipcMain.once('answer', (event, content) => {
assert.equal(content, 'Blocked a frame with origin "file://" from accessing a cross-origin frame.')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'native-window-open-cross-origin.html'))
})
it('opens window from <iframe> tags', (done) => {
ipcMain.once('answer', (event, content) => {
assert.equal(content, 'Hello')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'native-window-open-iframe.html'))
})
it('loads native addons correctly after reload', (done) => {
if (!nativeModulesEnabled) return done()
ipcMain.once('answer', (event, content) => {
assert.equal(content, 'function')
ipcMain.once('answer', (event, content) => {
assert.equal(content, 'function')
done()
})
w.reload()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'native-window-open-native-addon.html'))
})
it('should inherit the nativeWindowOpen setting in opened windows', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcMain.once('answer', (event, args) => {
assert.equal(args.includes('--native-window-open'), true)
done()
})
w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
})
it('should open windows with the options configured via new-window event listeners', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'foo', 'bar')
ipcMain.once('answer', (event, args, webPreferences) => {
assert.equal(webPreferences.foo, 'bar')
done()
})
w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
})
it('retains the original web preferences when window.location is changed to a new origin', async function () {
await serveFileFromProtocol('foo', path.join(fixtures, 'api', 'window-open-location-change.html'))
await serveFileFromProtocol('bar', path.join(fixtures, 'api', 'window-open-location-final.html'))
w.destroy()
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: false,
nativeWindowOpen: true
}
})
return new Promise((resolve, reject) => {
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', path.join(fixtures, 'api', 'window-open-preload.js'))
ipcMain.once('answer', (event, args, typeofProcess) => {
assert.equal(args.includes('--node-integration=false'), true)
assert.equal(args.includes('--native-window-open'), true)
assert.equal(typeofProcess, 'undefined')
resolve()
})
w.loadURL(`file://${path.join(fixtures, 'api', 'window-open-location-open.html')}`)
})
})
})
})
describe('nativeWindowOpen + contextIsolation options', () => {
beforeEach(() => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
})
})
it('opens window with cross-scripting enabled from isolated context', (done) => {
ipcMain.once('answer', (event, content) => {
assert.equal(content, 'Hello')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'native-window-open-isolated.html'))
})
})
describe('beforeunload handler', function () {
it('returning undefined would not prevent close', function (done) {
w.once('closed', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-undefined.html'))
})
it('returning false would prevent close', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html'))
})
it('returning empty string would prevent close', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-empty-string.html'))
})
it('emits for each close attempt', function (done) {
var beforeUnloadCount = 0
w.on('onbeforeunload', function () {
beforeUnloadCount++
if (beforeUnloadCount < 3) {
w.close()
} else if (beforeUnloadCount === 3) {
done()
}
})
w.webContents.once('did-finish-load', function () {
w.close()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false-prevent3.html'))
})
it('emits for each reload attempt', function (done) {
var beforeUnloadCount = 0
w.on('onbeforeunload', function () {
beforeUnloadCount++
if (beforeUnloadCount < 3) {
w.reload()
} else if (beforeUnloadCount === 3) {
done()
}
})
w.webContents.once('did-finish-load', function () {
w.webContents.once('did-finish-load', function () {
assert.fail('Reload was not prevented')
})
w.reload()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false-prevent3.html'))
})
it('emits for each navigation attempt', function (done) {
var beforeUnloadCount = 0
w.on('onbeforeunload', function () {
beforeUnloadCount++
if (beforeUnloadCount < 3) {
w.loadURL('about:blank')
} else if (beforeUnloadCount === 3) {
done()
}
})
w.webContents.once('did-finish-load', function () {
w.webContents.once('did-finish-load', function () {
assert.fail('Navigation was not prevented')
})
w.loadURL('about:blank')
})
w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false-prevent3.html'))
})
})
describe('document.visibilityState/hidden', function () {
beforeEach(function () {
w.destroy()
})
function onVisibilityChange (callback) {
ipcMain.on('pong', function (event, visibilityState, hidden) {
if (event.sender.id === w.webContents.id) {
callback(visibilityState, hidden)
}
})
}
function onNextVisibilityChange (callback) {
ipcMain.once('pong', function (event, visibilityState, hidden) {
if (event.sender.id === w.webContents.id) {
callback(visibilityState, hidden)
}
})
}
afterEach(function () {
ipcMain.removeAllListeners('pong')
})
it('visibilityState is initially visible despite window being hidden', function (done) {
w = new BrowserWindow({ show: false, width: 100, height: 100 })
let readyToShow = false
w.once('ready-to-show', function () {
readyToShow = true
})
onNextVisibilityChange(function (visibilityState, hidden) {
assert.equal(readyToShow, false)
assert.equal(visibilityState, 'visible')
assert.equal(hidden, false)
done()
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'visibilitychange.html'))
})
it('visibilityState changes when window is hidden', function (done) {
w = new BrowserWindow({width: 100, height: 100})
onNextVisibilityChange(function (visibilityState, hidden) {
assert.equal(visibilityState, 'visible')
assert.equal(hidden, false)
onNextVisibilityChange(function (visibilityState, hidden) {
assert.equal(visibilityState, 'hidden')
assert.equal(hidden, true)
done()
})
w.hide()
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'visibilitychange.html'))
})
it('visibilityState changes when window is shown', function (done) {
w = new BrowserWindow({width: 100, height: 100})
onNextVisibilityChange(function (visibilityState, hidden) {
onVisibilityChange(function (visibilityState, hidden) {
if (!hidden) {
assert.equal(visibilityState, 'visible')
done()
}
})
w.hide()
w.show()
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'visibilitychange.html'))
})
it('visibilityState changes when window is shown inactive', function (done) {
if (isCI && process.platform === 'win32') return done()
w = new BrowserWindow({width: 100, height: 100})
onNextVisibilityChange(function (visibilityState, hidden) {
onVisibilityChange(function (visibilityState, hidden) {
if (!hidden) {
assert.equal(visibilityState, 'visible')
done()
}
})
w.hide()
w.showInactive()
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'visibilitychange.html'))
})
it('visibilityState changes when window is minimized', function (done) {
if (isCI && process.platform === 'linux') return done()
w = new BrowserWindow({width: 100, height: 100})
onNextVisibilityChange(function (visibilityState, hidden) {
assert.equal(visibilityState, 'visible')
assert.equal(hidden, false)
onNextVisibilityChange(function (visibilityState, hidden) {
assert.equal(visibilityState, 'hidden')
assert.equal(hidden, true)
done()
})
w.minimize()
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'visibilitychange.html'))
})
it('visibilityState remains visible if backgroundThrottling is disabled', function (done) {
w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false
}
})
onNextVisibilityChange(function (visibilityState, hidden) {
assert.equal(visibilityState, 'visible')
assert.equal(hidden, false)
onNextVisibilityChange(function (visibilityState, hidden) {
done(new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`))
})
})
w.once('show', () => {
w.once('hide', () => {
w.once('show', () => {
done()
})
w.show()
})
w.hide()
})
w.show()
w.loadURL('file://' + path.join(fixtures, 'pages', 'visibilitychange.html'))
})
})
describe('new-window event', function () {
if (isCI && process.platform === 'darwin') {
return
}
it('emits when window.open is called', function (done) {
w.webContents.once('new-window', function (e, url, frameName, disposition, options, additionalFeatures) {
e.preventDefault()
assert.equal(url, 'http://host/')
assert.equal(frameName, 'host')
assert.equal(additionalFeatures[0], 'this-is-not-a-standard-feature')
done()
})
w.loadURL('file://' + fixtures + '/pages/window-open.html')
})
it('emits when window.open is called with no webPreferences', function (done) {
w.destroy()
w = new BrowserWindow({ show: false })
w.webContents.once('new-window', function (e, url, frameName, disposition, options, additionalFeatures) {
e.preventDefault()
assert.equal(url, 'http://host/')
assert.equal(frameName, 'host')
assert.equal(additionalFeatures[0], 'this-is-not-a-standard-feature')
done()
})
w.loadURL('file://' + fixtures + '/pages/window-open.html')
})
it('emits when link with target is called', function (done) {
w.webContents.once('new-window', function (e, url, frameName) {
e.preventDefault()
assert.equal(url, 'http://host/')
assert.equal(frameName, 'target')
done()
})
w.loadURL('file://' + fixtures + '/pages/target-name.html')
})
})
describe('maximize event', function () {
if (isCI) {
return
}
it('emits when window is maximized', function (done) {
w.once('maximize', function () {
done()
})
w.show()
w.maximize()
})
})
describe('unmaximize event', function () {
if (isCI) {
return
}
it('emits when window is unmaximized', function (done) {
w.once('unmaximize', function () {
done()
})
w.show()
w.maximize()
w.unmaximize()
})
})
describe('minimize event', function () {
if (isCI) {
return
}
it('emits when window is minimized', function (done) {
w.once('minimize', function () {
done()
})
w.show()
w.minimize()
})
})
describe('sheet-begin event', function () {
if (process.platform !== 'darwin') {
return
}
let sheet = null
afterEach(function () {
return closeWindow(sheet, {assertSingleWindow: false}).then(function () { sheet = null })
})
it('emits when window opens a sheet', function (done) {
w.show()
w.once('sheet-begin', function () {
sheet.close()
done()
})
sheet = new BrowserWindow({
modal: true,
parent: w
})
})
})
describe('sheet-end event', function () {
if (process.platform !== 'darwin') {
return
}
let sheet = null
afterEach(function () {
return closeWindow(sheet, {assertSingleWindow: false}).then(function () { sheet = null })
})
it('emits when window has closed a sheet', function (done) {
w.show()
sheet = new BrowserWindow({
modal: true,
parent: w
})
w.once('sheet-end', function () {
done()
})
sheet.close()
})
})
describe('beginFrameSubscription method', function () {
// This test is too slow, only test it on CI.
if (!isCI) return
it('subscribes to frame updates', function (done) {
let called = false
w.loadURL('file://' + fixtures + '/api/frame-subscriber.html')
w.webContents.on('dom-ready', function () {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return
called = true
assert.notEqual(data.length, 0)
w.webContents.endFrameSubscription()
done()
})
})
})
it('subscribes to frame updates (only dirty rectangle)', function (done) {
let called = false
w.loadURL('file://' + fixtures + '/api/frame-subscriber.html')
w.webContents.on('dom-ready', function () {
w.webContents.beginFrameSubscription(true, function (data) {
// This callback might be called twice.
if (called) return
called = true
assert.notEqual(data.length, 0)
w.webContents.endFrameSubscription()
done()
})
})
})
it('throws error when subscriber is not well defined', function (done) {
w.loadURL('file://' + fixtures + '/api/frame-subscriber.html')
try {
w.webContents.beginFrameSubscription(true, true)
} catch (e) {
done()
}
})
})
describe('savePage method', function () {
const savePageDir = path.join(fixtures, 'save_page')
const savePageHtmlPath = path.join(savePageDir, 'save_page.html')
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js')
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css')
after(function () {
try {
fs.unlinkSync(savePageCssPath)
fs.unlinkSync(savePageJsPath)
fs.unlinkSync(savePageHtmlPath)
fs.rmdirSync(path.join(savePageDir, 'save_page_files'))
fs.rmdirSync(savePageDir)
} catch (e) {
// Ignore error
}
})
it('should save page to disk', function (done) {
w.webContents.on('did-finish-load', function () {
w.webContents.savePage(savePageHtmlPath, 'HTMLComplete', function (error) {
assert.equal(error, null)
assert(fs.existsSync(savePageHtmlPath))
assert(fs.existsSync(savePageJsPath))
assert(fs.existsSync(savePageCssPath))
done()
})
})
w.loadURL('file://' + fixtures + '/pages/save_page/index.html')
})
})
describe('BrowserWindow options argument is optional', function () {
it('should create a window with default size (800x600)', function () {
w.destroy()
w = new BrowserWindow()
var size = w.getSize()
assert.equal(size[0], 800)
assert.equal(size[1], 600)
})
})
describe('window states', function () {
it('does not resize frameless windows when states change', function () {
w.destroy()
w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
})
w.setMinimizable(false)
w.setMinimizable(true)
assert.deepEqual(w.getSize(), [300, 200])
w.setResizable(false)
w.setResizable(true)
assert.deepEqual(w.getSize(), [300, 200])
w.setMaximizable(false)
w.setMaximizable(true)
assert.deepEqual(w.getSize(), [300, 200])
w.setFullScreenable(false)
w.setFullScreenable(true)
assert.deepEqual(w.getSize(), [300, 200])
w.setClosable(false)
w.setClosable(true)
assert.deepEqual(w.getSize(), [300, 200])
})
describe('resizable state', function () {
it('can be changed with resizable option', function () {
w.destroy()
w = new BrowserWindow({show: false, resizable: false})
assert.equal(w.isResizable(), false)
if (process.platform === 'darwin') {
assert.equal(w.isMaximizable(), true)
}
})
it('can be changed with setResizable method', function () {
assert.equal(w.isResizable(), true)
w.setResizable(false)
assert.equal(w.isResizable(), false)
w.setResizable(true)
assert.equal(w.isResizable(), true)
})
it('works for a frameless window', () => {
w.destroy()
w = new BrowserWindow({show: false, frame: false})
assert.equal(w.isResizable(), true)
if (process.platform === 'win32') {
w.destroy()
w = new BrowserWindow({show: false, thickFrame: false})
assert.equal(w.isResizable(), false)
}
})
})
describe('loading main frame state', function () {
it('is true when the main frame is loading', function (done) {
w.webContents.on('did-start-loading', function () {
assert.equal(w.webContents.isLoadingMainFrame(), true)
done()
})
w.webContents.loadURL(server.url)
})
it('is false when only a subframe is loading', function (done) {
w.webContents.once('did-finish-load', function () {
assert.equal(w.webContents.isLoadingMainFrame(), false)
w.webContents.on('did-start-loading', function () {
assert.equal(w.webContents.isLoadingMainFrame(), false)
done()
})
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/page2'
document.body.appendChild(iframe)
`)
})
w.webContents.loadURL(server.url)
})
it('is true when navigating to pages from the same origin', function (done) {
w.webContents.once('did-finish-load', function () {
assert.equal(w.webContents.isLoadingMainFrame(), false)
w.webContents.on('did-start-loading', function () {
assert.equal(w.webContents.isLoadingMainFrame(), true)
done()
})
w.webContents.loadURL(`${server.url}/page2`)
})
w.webContents.loadURL(server.url)
})
})
})
describe('window states (excluding Linux)', function () {
// Not implemented on Linux.
if (process.platform === 'linux') return
describe('movable state', function () {
it('can be changed with movable option', function () {
w.destroy()
w = new BrowserWindow({show: false, movable: false})
assert.equal(w.isMovable(), false)
})
it('can be changed with setMovable method', function () {
assert.equal(w.isMovable(), true)
w.setMovable(false)
assert.equal(w.isMovable(), false)
w.setMovable(true)
assert.equal(w.isMovable(), true)
})
})
describe('minimizable state', function () {
it('can be changed with minimizable option', function () {
w.destroy()
w = new BrowserWindow({show: false, minimizable: false})
assert.equal(w.isMinimizable(), false)
})
it('can be changed with setMinimizable method', function () {
assert.equal(w.isMinimizable(), true)
w.setMinimizable(false)
assert.equal(w.isMinimizable(), false)
w.setMinimizable(true)
assert.equal(w.isMinimizable(), true)
})
})
describe('maximizable state', function () {
it('can be changed with maximizable option', function () {
w.destroy()
w = new BrowserWindow({show: false, maximizable: false})
assert.equal(w.isMaximizable(), false)
})
it('can be changed with setMaximizable method', function () {
assert.equal(w.isMaximizable(), true)
w.setMaximizable(false)
assert.equal(w.isMaximizable(), false)
w.setMaximizable(true)
assert.equal(w.isMaximizable(), true)
})
it('is not affected when changing other states', function () {
w.setMaximizable(false)
assert.equal(w.isMaximizable(), false)
w.setMinimizable(false)
assert.equal(w.isMaximizable(), false)
w.setClosable(false)
assert.equal(w.isMaximizable(), false)
w.setMaximizable(true)
assert.equal(w.isMaximizable(), true)
w.setClosable(true)
assert.equal(w.isMaximizable(), true)
w.setFullScreenable(false)
assert.equal(w.isMaximizable(), true)
w.setResizable(false)
assert.equal(w.isMaximizable(), true)
})
})
describe('fullscreenable state', function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') return
it('can be changed with fullscreenable option', function () {
w.destroy()
w = new BrowserWindow({show: false, fullscreenable: false})
assert.equal(w.isFullScreenable(), false)
})
it('can be changed with setFullScreenable method', function () {
assert.equal(w.isFullScreenable(), true)
w.setFullScreenable(false)
assert.equal(w.isFullScreenable(), false)
w.setFullScreenable(true)
assert.equal(w.isFullScreenable(), true)
})
})
describe('kiosk state', function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') return
it('can be changed with setKiosk method', function (done) {
w.destroy()
w = new BrowserWindow()
w.setKiosk(true)
assert.equal(w.isKiosk(), true)
w.once('enter-full-screen', () => {
w.setKiosk(false)
assert.equal(w.isKiosk(), false)
})
w.once('leave-full-screen', () => {
done()
})
})
})
describe('fullscreen state', function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') return
it('can be changed with setFullScreen method', function (done) {
w.destroy()
w = new BrowserWindow()
w.once('enter-full-screen', () => {
assert.equal(w.isFullScreen(), true)
w.setFullScreen(false)
})
w.once('leave-full-screen', () => {
assert.equal(w.isFullScreen(), false)
done()
})
w.setFullScreen(true)
})
it('should not be changed by setKiosk method', function (done) {
w.destroy()
w = new BrowserWindow()
w.once('enter-full-screen', () => {
assert.equal(w.isFullScreen(), true)
w.setKiosk(true)
w.setKiosk(false)
assert.equal(w.isFullScreen(), true)
w.setFullScreen(false)
})
w.once('leave-full-screen', () => {
assert.equal(w.isFullScreen(), false)
done()
})
w.setFullScreen(true)
})
})
describe('closable state', function () {
it('can be changed with closable option', function () {
w.destroy()
w = new BrowserWindow({show: false, closable: false})
assert.equal(w.isClosable(), false)
})
it('can be changed with setClosable method', function () {
assert.equal(w.isClosable(), true)
w.setClosable(false)
assert.equal(w.isClosable(), false)
w.setClosable(true)
assert.equal(w.isClosable(), true)
})
})
describe('hasShadow state', function () {
// On Window there is no shadow by default and it can not be changed
// dynamically.
it('can be changed with hasShadow option', function () {
w.destroy()
let hasShadow = process.platform !== 'darwin'
w = new BrowserWindow({show: false, hasShadow: hasShadow})
assert.equal(w.hasShadow(), hasShadow)
})
it('can be changed with setHasShadow method', function () {
if (process.platform !== 'darwin') return
assert.equal(w.hasShadow(), true)
w.setHasShadow(false)
assert.equal(w.hasShadow(), false)
w.setHasShadow(true)
assert.equal(w.hasShadow(), true)
})
})
})
describe('BrowserWindow.restore()', function () {
it('should restore the previous window size', function () {
if (w != null) w.destroy()
w = new BrowserWindow({
minWidth: 800,
width: 800
})
const initialSize = w.getSize()
w.minimize()
w.restore()
assertBoundsEqual(w.getSize(), initialSize)
})
})
describe('BrowserWindow.unmaximize()', function () {
it('should restore the previous window position', function () {
if (w != null) w.destroy()
w = new BrowserWindow()
const initialPosition = w.getPosition()
w.maximize()
w.unmaximize()
assertBoundsEqual(w.getPosition(), initialPosition)
})
})
describe('BrowserWindow.setFullScreen(false)', function () {
// only applicable to windows: https://github.com/electron/electron/issues/6036
if (process.platform !== 'win32') return
it('should restore a normal visible window from a fullscreen startup state', function (done) {
w.webContents.once('did-finish-load', function () {
// start fullscreen and hidden
w.setFullScreen(true)
w.once('show', function () {
// restore window to normal state
w.setFullScreen(false)
})
w.once('leave-full-screen', function () {
assert.equal(w.isVisible(), true)
assert.equal(w.isFullScreen(), false)
done()
})
w.show()
})
w.loadURL('about:blank')
})
it('should keep window hidden if already in hidden state', function (done) {
w.webContents.once('did-finish-load', function () {
w.once('leave-full-screen', () => {
assert.equal(w.isVisible(), false)
assert.equal(w.isFullScreen(), false)
done()
})
w.setFullScreen(false)
})
w.loadURL('about:blank')
})
})
describe('parent window', function () {
let c = null
beforeEach(function () {
if (c != null) c.destroy()
c = new BrowserWindow({show: false, parent: w})
})
afterEach(function () {
if (c != null) c.destroy()
c = null
})
describe('parent option', function () {
it('sets parent window', function () {
assert.equal(c.getParentWindow(), w)
})
it('adds window to child windows of parent', function () {
assert.deepEqual(w.getChildWindows(), [c])
})
it('removes from child windows of parent when window is closed', function (done) {
c.once('closed', () => {
assert.deepEqual(w.getChildWindows(), [])
done()
})
c.close()
})
})
describe('win.setParentWindow(parent)', function () {
if (process.platform === 'win32') return
beforeEach(function () {
if (c != null) c.destroy()
c = new BrowserWindow({show: false})
})
it('sets parent window', function () {
assert.equal(w.getParentWindow(), null)
assert.equal(c.getParentWindow(), null)
c.setParentWindow(w)
assert.equal(c.getParentWindow(), w)
c.setParentWindow(null)
assert.equal(c.getParentWindow(), null)
})
it('adds window to child windows of parent', function () {
assert.deepEqual(w.getChildWindows(), [])
c.setParentWindow(w)
assert.deepEqual(w.getChildWindows(), [c])
c.setParentWindow(null)
assert.deepEqual(w.getChildWindows(), [])
})
it('removes from child windows of parent when window is closed', function (done) {
c.once('closed', () => {
assert.deepEqual(w.getChildWindows(), [])
done()
})
c.setParentWindow(w)
c.close()
})
})
describe('modal option', function () {
// The isEnabled API is not reliable on macOS.
if (process.platform === 'darwin') return
beforeEach(function () {
if (c != null) c.destroy()
c = new BrowserWindow({show: false, parent: w, modal: true})
})
it('disables parent window', function () {
assert.equal(w.isEnabled(), true)
c.show()
assert.equal(w.isEnabled(), false)
})
it('enables parent window when closed', function (done) {
c.once('closed', () => {
assert.equal(w.isEnabled(), true)
done()
})
c.show()
c.close()
})
it('disables parent window recursively', function () {
let c2 = new BrowserWindow({show: false, parent: w, modal: true})
c.show()
assert.equal(w.isEnabled(), false)
c2.show()
assert.equal(w.isEnabled(), false)
c.destroy()
assert.equal(w.isEnabled(), false)
c2.destroy()
assert.equal(w.isEnabled(), true)
})
})
})
describe('window.webContents.send(channel, args...)', function () {
it('throws an error when the channel is missing', function () {
assert.throws(function () {
w.webContents.send()
}, 'Missing required channel argument')
assert.throws(function () {
w.webContents.send(null)
}, 'Missing required channel argument')
})
})
describe('dev tool extensions', function () {
let showPanelTimeoutId
const showLastDevToolsPanel = () => {
w.webContents.once('devtools-opened', function () {
const show = function () {
if (w == null || w.isDestroyed()) {
return
}
const {devToolsWebContents} = w
if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
return
}
const showLastPanel = function () {
const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id
UI.inspectorView.showPanel(lastPanelId)
}
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false, () => {
showPanelTimeoutId = setTimeout(show, 100)
})
}
showPanelTimeoutId = setTimeout(show, 100)
})
}
afterEach(function () {
clearTimeout(showPanelTimeoutId)
})
describe('BrowserWindow.addDevToolsExtension', function () {
beforeEach(function () {
BrowserWindow.removeDevToolsExtension('foo')
assert.equal(BrowserWindow.getDevToolsExtensions().hasOwnProperty('foo'), false)
var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
BrowserWindow.addDevToolsExtension(extensionPath)
assert.equal(BrowserWindow.getDevToolsExtensions().hasOwnProperty('foo'), true)
showLastDevToolsPanel()
w.loadURL('about:blank')
})
it('throws errors for missing manifest.json files', function () {
assert.throws(function () {
BrowserWindow.addDevToolsExtension(path.join(__dirname, 'does-not-exist'))
}, /ENOENT: no such file or directory/)
})
it('throws errors for invalid manifest.json files', function () {
assert.throws(function () {
BrowserWindow.addDevToolsExtension(path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest'))
}, /Unexpected token }/)
})
describe('when the devtools is docked', function () {
it('creates the extension', function (done) {
w.webContents.openDevTools({mode: 'bottom'})
ipcMain.once('answer', function (event, message) {
assert.equal(message.runtimeId, 'foo')
assert.equal(message.tabId, w.webContents.id)
assert.equal(message.i18nString, 'foo - bar (baz)')
assert.deepEqual(message.storageItems, {
local: {
set: {hello: 'world', world: 'hello'},
remove: {world: 'hello'},
clear: {}
},
sync: {
set: {foo: 'bar', bar: 'foo'},
remove: {foo: 'bar'},
clear: {}
}
})
done()
})
})
})
describe('when the devtools is undocked', function () {
it('creates the extension', function (done) {
w.webContents.openDevTools({mode: 'undocked'})
ipcMain.once('answer', function (event, message, extensionId) {
assert.equal(message.runtimeId, 'foo')
assert.equal(message.tabId, w.webContents.id)
done()
})
})
})
})
it('works when used with partitions', function (done) {
if (w != null) {
w.destroy()
}
w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'temp'
}
})
var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
BrowserWindow.removeDevToolsExtension('foo')
BrowserWindow.addDevToolsExtension(extensionPath)
showLastDevToolsPanel()
w.loadURL('about:blank')
w.webContents.openDevTools({mode: 'bottom'})
ipcMain.once('answer', function (event, message) {
assert.equal(message.runtimeId, 'foo')
done()
})
})
it('serializes the registered extensions on quit', function () {
var extensionName = 'foo'
var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', extensionName)
var serializedPath = path.join(app.getPath('userData'), 'DevTools Extensions')
BrowserWindow.addDevToolsExtension(extensionPath)
app.emit('will-quit')
assert.deepEqual(JSON.parse(fs.readFileSync(serializedPath)), [extensionPath])
BrowserWindow.removeDevToolsExtension(extensionName)
app.emit('will-quit')
assert.equal(fs.existsSync(serializedPath), false)
})
})
describe('window.webContents.executeJavaScript', function () {
var expected = 'hello, world!'
var expectedErrorMsg = 'woops!'
var code = `(() => "${expected}")()`
var asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`
var badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`
it('doesnt throw when no calback is provided', function () {
const result = ipcRenderer.sendSync('executeJavaScript', code, false)
assert.equal(result, 'success')
})
it('returns result when calback is provided', function (done) {
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-response', function (event, result) {
assert.equal(result, expected)
done()
})
})
it('returns result if the code returns an asyncronous promise', function (done) {
ipcRenderer.send('executeJavaScript', asyncCode, true)
ipcRenderer.once('executeJavaScript-response', function (event, result) {
assert.equal(result, expected)
done()
})
})
it('resolves the returned promise with the result when a callback is specified', function (done) {
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-promise-response', function (event, result) {
assert.equal(result, expected)
done()
})
})
it('resolves the returned promise with the result when no callback is specified', function (done) {
ipcRenderer.send('executeJavaScript', code, false)
ipcRenderer.once('executeJavaScript-promise-response', function (event, result) {
assert.equal(result, expected)
done()
})
})
it('resolves the returned promise with the result if the code returns an asyncronous promise', function (done) {
ipcRenderer.send('executeJavaScript', asyncCode, true)
ipcRenderer.once('executeJavaScript-promise-response', function (event, result) {
assert.equal(result, expected)
done()
})
})
it('rejects the returned promise if an async error is thrown', function (done) {
ipcRenderer.send('executeJavaScript', badAsyncCode, true)
ipcRenderer.once('executeJavaScript-promise-error', function (event, error) {
assert.equal(error, expectedErrorMsg)
done()
})
})
it('works after page load and during subframe load', function (done) {
w.webContents.once('did-finish-load', function () {
// initiate a sub-frame load, then try and execute script during it
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/slow'
document.body.appendChild(iframe)
`, function () {
w.webContents.executeJavaScript('console.log(\'hello\')', function () {
done()
})
})
})
w.loadURL(server.url)
})
it('executes after page load', function (done) {
w.webContents.executeJavaScript(code, function (result) {
assert.equal(result, expected)
done()
})
w.loadURL(server.url)
})
it('works with result objects that have DOM class prototypes', function (done) {
w.webContents.executeJavaScript('document.location', function (result) {
assert.equal(result.origin, server.url)
assert.equal(result.protocol, 'http:')
done()
})
w.loadURL(server.url)
})
})
describe('previewFile', function () {
it('opens the path in Quick Look on macOS', function () {
if (process.platform !== 'darwin') return
assert.doesNotThrow(function () {
w.previewFile(__filename)
w.closeFilePreview()
})
})
})
describe('contextIsolation option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
}
beforeEach(() => {
if (w != null) w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
})
})
it('separates the page context from the Electron/preload context', (done) => {
ipcMain.once('isolated-world', (event, data) => {
assert.deepEqual(data, expectedContextData)
done()
})
w.loadURL('file://' + fixtures + '/api/isolated.html')
})
it('recreates the contexts on reload', (done) => {
w.webContents.once('did-finish-load', () => {
ipcMain.once('isolated-world', (event, data) => {
assert.deepEqual(data, expectedContextData)
done()
})
w.webContents.reload()
})
w.loadURL('file://' + fixtures + '/api/isolated.html')
})
it('enables context isolation on child windows', function (done) {
app.once('browser-window-created', function (event, window) {
assert.equal(window.webContents.getWebPreferences().contextIsolation, true)
done()
})
w.loadURL('file://' + fixtures + '/pages/window-open.html')
})
})
describe('offscreen rendering', function () {
const isOffscreenRenderingDisabled = () => {
const contents = webContents.create({})
const disabled = typeof contents.isOffscreen !== 'function'
contents.destroy()
return disabled
}
// Offscreen rendering can be disabled in the build
if (isOffscreenRenderingDisabled()) return
beforeEach(function () {
if (w != null) w.destroy()
w = new BrowserWindow({
width: 100,
height: 100,
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
})
})
it('creates offscreen window with correct size', function (done) {
w.webContents.once('paint', function (event, rect, data) {
assert.notEqual(data.length, 0)
let size = data.getSize()
assertWithinDelta(size.width, 100, 2, 'width')
assertWithinDelta(size.height, 100, 2, 'height')
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
describe('window.webContents.isOffscreen()', function () {
it('is true for offscreen type', function () {
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
assert.equal(w.webContents.isOffscreen(), true)
})
it('is false for regular window', function () {
let c = new BrowserWindow({show: false})
assert.equal(c.webContents.isOffscreen(), false)
c.destroy()
})
})
describe('window.webContents.isPainting()', function () {
it('returns whether is currently painting', function (done) {
w.webContents.once('paint', function (event, rect, data) {
assert.equal(w.webContents.isPainting(), true)
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.stopPainting()', function () {
it('stops painting', function (done) {
w.webContents.on('dom-ready', function () {
w.webContents.stopPainting()
assert.equal(w.webContents.isPainting(), false)
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.startPainting()', function () {
it('starts painting', function (done) {
w.webContents.on('dom-ready', function () {
w.webContents.stopPainting()
w.webContents.startPainting()
w.webContents.once('paint', function (event, rect, data) {
assert.equal(w.webContents.isPainting(), true)
done()
})
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.getFrameRate()', function () {
it('has default frame rate', function (done) {
w.webContents.once('paint', function (event, rect, data) {
assert.equal(w.webContents.getFrameRate(), 60)
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.setFrameRate(frameRate)', function () {
it('sets custom frame rate', function (done) {
w.webContents.on('dom-ready', function () {
w.webContents.setFrameRate(30)
w.webContents.once('paint', function (event, rect, data) {
assert.equal(w.webContents.getFrameRate(), 30)
done()
})
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
})
})
const assertBoundsEqual = (actual, expect) => {
if (!isScaleFactorRounding()) {
assert.deepEqual(expect, actual)
} else if (Array.isArray(actual)) {
assertWithinDelta(actual[0], expect[0], 1, 'x')
assertWithinDelta(actual[1], expect[1], 1, 'y')
} else {
assertWithinDelta(actual.x, expect.x, 1, 'x')
assertWithinDelta(actual.y, expect.y, 1, 'y')
assertWithinDelta(actual.width, expect.width, 1, 'width')
assertWithinDelta(actual.height, expect.height, 1, 'height')
}
}
const assertWithinDelta = (actual, expect, delta, label) => {
const result = Math.abs(actual - expect)
assert.ok(result <= delta, `${label} value of ${actual} was not within ${delta} of ${expect}`)
}
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
const {scaleFactor} = screen.getPrimaryDisplay()
// Return true if scale factor is non-integer value
if (Math.round(scaleFactor) !== scaleFactor) return true
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1
}
function serveFileFromProtocol (protocolName, filePath) {
return new Promise((resolve, reject) => {
protocol.registerBufferProtocol(protocolName, (request, callback) => {
callback({
mimeType: 'text/html',
data: fs.readFileSync(filePath)
})
}, (error) => {
if (error != null) {
reject(error)
} else {
resolve()
}
})
})
}
| {
"content_hash": "643835d2d022043880d0ee9417e0e0e0",
"timestamp": "",
"source": "github",
"line_count": 2826,
"max_line_length": 152,
"avg_line_length": 31.515923566878982,
"alnum_prop": 0.5709040689841013,
"repo_name": "renaesop/electron",
"id": "d378850d88e0b896510bf49541b210beebe91973",
"size": "89064",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/api-browser-window-spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4055"
},
{
"name": "C++",
"bytes": "2719308"
},
{
"name": "HTML",
"bytes": "14554"
},
{
"name": "JavaScript",
"bytes": "786278"
},
{
"name": "Objective-C",
"bytes": "50166"
},
{
"name": "Objective-C++",
"bytes": "265661"
},
{
"name": "PowerShell",
"bytes": "99"
},
{
"name": "Python",
"bytes": "201139"
},
{
"name": "Shell",
"bytes": "3439"
}
],
"symlink_target": ""
} |
import { connect } from 'react-redux';
import ModalProfileComponent from './component';
import * as actions from './actions';
import { getProfileModalProps } from './selectors';
export default connect(getProfileModalProps, actions)(ModalProfileComponent);
| {
"content_hash": "a0fb4543a9434f7d42e1eed8e9fbc805",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 77,
"avg_line_length": 36.857142857142854,
"alnum_prop": 0.7751937984496124,
"repo_name": "Vizzuality/gfw",
"id": "0c934b3426b512c9a0d437b4710a282668f0c8ed",
"size": "258",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "components/modals/profile/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "53"
},
{
"name": "JavaScript",
"bytes": "2151093"
},
{
"name": "SCSS",
"bytes": "264210"
}
],
"symlink_target": ""
} |
from celery.utils.log import get_task_logger
import datetime
from redash.worker import celery
from redash import utils
from redash import models, settings
from .base import BaseTask
logger = get_task_logger(__name__)
def base_url(org):
if settings.MULTI_ORG:
return "https://{}/{}".format(settings.HOST, org.slug)
return "http://{}".format(settings.HOST)
@celery.task(name="redash.tasks.check_alerts_for_query", base=BaseTask)
def check_alerts_for_query(query_id):
from redash.wsgi import app
logger.debug("Checking query %d for alerts", query_id)
query = models.Query.get_by_id(query_id)
for alert in query.alerts:
alert.query = query
new_state = alert.evaluate()
passed_rearm_threshold = False
if alert.rearm and alert.last_triggered_at:
passed_rearm_threshold = alert.last_triggered_at + datetime.timedelta(seconds=alert.rearm) < utils.utcnow()
if new_state != alert.state or (alert.state == models.Alert.TRIGGERED_STATE and passed_rearm_threshold ):
logger.info("Alert %d new state: %s", alert.id, new_state)
old_state = alert.state
alert.update_instance(state=new_state, last_triggered_at=utils.utcnow())
if old_state == models.Alert.UNKNOWN_STATE and new_state == models.Alert.OK_STATE:
logger.debug("Skipping notification (previous state was unknown and now it's ok).")
continue
host = base_url(alert.query.org)
for subscription in alert.subscriptions:
try:
subscription.notify(alert, query, subscription.user, new_state, app, host)
except Exception as e:
logger.exception("Error with processing destination")
| {
"content_hash": "d9a99bd64bdb930e56146b8ba6e5b270",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 119,
"avg_line_length": 38.869565217391305,
"alnum_prop": 0.6521252796420581,
"repo_name": "guaguadev/redash",
"id": "97b84a63e25b2f78f634ee31c46a92e1934ecd59",
"size": "1788",
"binary": false,
"copies": "1",
"ref": "refs/heads/guagua",
"path": "redash/tasks/alerts.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "239783"
},
{
"name": "HTML",
"bytes": "121423"
},
{
"name": "JavaScript",
"bytes": "279730"
},
{
"name": "Makefile",
"bytes": "955"
},
{
"name": "Nginx",
"bytes": "577"
},
{
"name": "Python",
"bytes": "501609"
},
{
"name": "Ruby",
"bytes": "709"
},
{
"name": "Shell",
"bytes": "43388"
}
],
"symlink_target": ""
} |
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MySite
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| {
"content_hash": "5be4c5ae775a3adc95ba3d7e6cf4d1b0",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 99,
"avg_line_length": 42.47826086956522,
"alnum_prop": 0.7134083930399181,
"repo_name": "mcbrooks95/Ruby_On_Rails",
"id": "cdb048eda743bf3aee7b487ecfd32c83fc14f86c",
"size": "977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MySite/config/application.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4153"
},
{
"name": "CoffeeScript",
"bytes": "1688"
},
{
"name": "HTML",
"bytes": "22789"
},
{
"name": "JavaScript",
"bytes": "2632"
},
{
"name": "Ruby",
"bytes": "87885"
}
],
"symlink_target": ""
} |
<template>
<h2>
${title}
<span class="float-end">
<a style="font-size: 18px"
target="_blank"
href="https://github.com/ghiscoding/aurelia-slickgrid/blob/master/src/examples/slickgrid/example8.ts">
<span class="fa fa-link"></span> code
</a>
</span>
</h2>
<div class="subtitle" innerhtml.bind="subTitle"></div>
<button class="btn btn-outline-secondary btn-sm" click.delegate="switchLanguage()">
<i class="fa fa-language"></i>
Switch Language
</button>
<b>Locale:</b> <span style="font-style: italic" data-test="selected-locale">${selectedLanguage + '.json'}</span>
<aurelia-slickgrid grid-id="grid8"
column-definitions.bind="columnDefinitions"
grid-options.bind="gridOptions"
dataset.bind="dataset"
on-aurelia-grid-created.delegate="aureliaGridReady($event.detail)">
</aurelia-slickgrid>
</template>
| {
"content_hash": "1d76a7ea4dc66a47557a220032530964",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 114,
"avg_line_length": 36.80769230769231,
"alnum_prop": 0.61337513061651,
"repo_name": "ghiscoding/aurelia-slickgrid",
"id": "50741f1376410d1292b8614bc942df24e94d71aa",
"size": "957",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/examples/slickgrid/example8.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "EJS",
"bytes": "526"
},
{
"name": "HTML",
"bytes": "91257"
},
{
"name": "JavaScript",
"bytes": "409155"
},
{
"name": "SCSS",
"bytes": "11826"
},
{
"name": "TypeScript",
"bytes": "746529"
}
],
"symlink_target": ""
} |
package org.springframework.core.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* {@link Resource} implementation for a given byte array. Creates a ByteArrayInputStreams for the given byte array.
*
* <p>
* Useful for loading content from any given byte array, without having to resort to a single-use
* {@link InputStreamResource}.
*
* @author Juergen Hoeller
* @since 1.0
* @see java.io.ByteArrayInputStream
* @see InputStreamResource
*/
public class ByteArrayResource extends AbstractResource {
private final byte[] byteArray;
private final String description;
/**
* Create a new ByteArrayResource.
* @param byteArray the byte array to wrap
*/
public ByteArrayResource(byte[] byteArray) {
this(byteArray, "resource loaded from byte array");
}
/**
* Create a new ByteArrayResource.
* @param byteArray the byte array to wrap
* @param description where the byte array comes from
*/
public ByteArrayResource(byte[] byteArray, String description) {
if (byteArray == null) {
throw new IllegalArgumentException("Byte array must not be null");
}
this.byteArray = byteArray;
this.description = (description != null ? description : "");
}
/**
* Return the underlying byte array.
*/
public final byte[] getByteArray() {
return this.byteArray;
}
/**
* This implementation always returns <code>true</code>.
*/
@Override
public boolean exists() {
return true;
}
/**
* This implementation returns the length of the underlying byte array.
*/
@Override
public long contentLength() {
return this.byteArray.length;
}
/**
* This implementation returns a ByteArrayInputStream for the underlying byte array.
* @see java.io.ByteArrayInputStream
*/
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(this.byteArray);
}
/**
* This implementation returns the passed-in description, if any.
*/
public String getDescription() {
return this.description;
}
/**
* This implementation compares the underlying byte array.
* @see java.util.Arrays#equals(byte[], byte[])
*/
@Override
public boolean equals(Object obj) {
return (obj == this || (obj instanceof ByteArrayResource && Arrays.equals(((ByteArrayResource) obj).byteArray, this.byteArray)));
}
/**
* This implementation returns the hash code based on the underlying byte array.
*/
@Override
public int hashCode() {
return (byte[].class.hashCode() * 29 * this.byteArray.length);
}
}
| {
"content_hash": "1731abceb36aa04ceb7ef77893a4a437",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 131,
"avg_line_length": 23.94392523364486,
"alnum_prop": 0.7142857142857143,
"repo_name": "eric-stanley/spring-android",
"id": "31bcbc0fba848c56a2a34a586b36f979de7a2696",
"size": "3182",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spring-android-core/src/main/java/org/springframework/core/io/ByteArrayResource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.amazonaws.services.support.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.support.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DescribeAttachmentResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAttachmentResultJsonUnmarshaller implements Unmarshaller<DescribeAttachmentResult, JsonUnmarshallerContext> {
public DescribeAttachmentResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DescribeAttachmentResult describeAttachmentResult = new DescribeAttachmentResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return describeAttachmentResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("attachment", targetDepth)) {
context.nextToken();
describeAttachmentResult.setAttachment(AttachmentJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return describeAttachmentResult;
}
private static DescribeAttachmentResultJsonUnmarshaller instance;
public static DescribeAttachmentResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeAttachmentResultJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "4337de0bdcf2b44fe70830aa7f00a9bf",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 136,
"avg_line_length": 36.36507936507937,
"alnum_prop": 0.6669576604103011,
"repo_name": "jentfoo/aws-sdk-java",
"id": "3f7c9b534bc76e29e373ad2fd202a8553e006f16",
"size": "2871",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-support/src/main/java/com/amazonaws/services/support/model/transform/DescribeAttachmentResultJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "FreeMarker",
"bytes": "173637"
},
{
"name": "Gherkin",
"bytes": "25063"
},
{
"name": "Java",
"bytes": "356214839"
},
{
"name": "Scilab",
"bytes": "3924"
},
{
"name": "Shell",
"bytes": "295"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Septoria gardeniae B.V. Patil, Sukapure & Thirum.
### Remarks
null | {
"content_hash": "ce96bbdecbb6e463ee0fd49b67848cf7",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 49,
"avg_line_length": 11.846153846153847,
"alnum_prop": 0.7012987012987013,
"repo_name": "mdoering/backbone",
"id": "a6eb7fec53de432e9d61c06edecae97fff4a2755",
"size": "227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Septoria/Septoria gardeniae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package sdk
import (
"encoding/base64"
"time"
)
// Operation is the main business object use in repositories service
type Operation struct {
UUID string `json:"uuid"`
VCSServer string `json:"vcs_server,omitempty"`
RepoFullName string `json:"repo_fullname,omitempty"`
URL string `json:"url"`
RepositoryStrategy RepositoryStrategy `json:"strategy,omitempty"`
Setup OperationSetup `json:"setup,omitempty"`
LoadFiles OperationLoadFiles `json:"load_files,omitempty"`
Status OperationStatus `json:"status"`
Error *OperationError `json:"error_details,omitempty"`
DeprecatedError string `json:"error,omitempty"`
RepositoryInfo *OperationRepositoryInfo `json:"repository_info,omitempty"`
Date *time.Time `json:"date,omitempty"`
User struct {
Username string `json:"username,omitempty" db:"-" cli:"-"`
Fullname string `json:"fullname,omitempty" db:"-" cli:"-"`
Email string `json:"email,omitempty" db:"-" cli:"-"`
} `json:"user,omitempty"`
RequestID string `json:"request_id,omitempty"`
NbRetries int `json:"nb_retries,omitempty"`
}
type OperationError struct {
ID int `json:"id"`
Status int `json:"status,omitempty"`
Message string `json:"message"`
StackTrace string `json:"stack_trace,omitempty"`
From string `json:"from,omitempty"`
}
func ToOperationError(err error) *OperationError {
if err == nil {
return nil
}
sdkError := ExtractHTTPError(err)
return &OperationError{
ID: sdkError.ID,
Status: sdkError.Status,
From: sdkError.From,
Message: sdkError.Message,
StackTrace: sdkError.StackTrace,
}
}
func (opError *OperationError) ToError() error {
if opError == nil {
return nil
}
return &Error{
ID: opError.ID,
Status: opError.Status,
Message: opError.Message,
From: opError.From,
}
}
// OperationSetup is the setup for an operation basically its a checkout
type OperationSetup struct {
Checkout OperationCheckout `json:"checkout,omitempty"`
Push OperationPush `json:"push,omitempty"`
}
// OperationRepositoryInfo represents global information about the repository
type OperationRepositoryInfo struct {
Name string `json:"name,omitempty"`
FetchURL string `json:"fetch_url,omitempty"`
DefaultBranch string `json:"default_branch,omitempty"`
}
// OperationLoadFiles represents files loading from a globbing pattern
type OperationLoadFiles struct {
Pattern string `json:"pattern,omitempty"`
Results map[string][]byte `json:"results,omitempty"`
}
// OperationCheckout represents a smart git checkout
type OperationCheckout struct {
Tag string `json:"tag,omitempty"`
Branch string `json:"branch,omitempty"`
Commit string `json:"commit,omitempty"`
CheckSignature bool `json:"check_signature,omitempty"`
Result struct {
SignKeyID string `json:"sign_key_id"`
CommitVerified bool `json:"verified"`
Msg string `json:"msg"`
} `json:"result"`
}
// OperationPush represents information about push operation
type OperationPush struct {
FromBranch string `json:"from_branch,omitempty"`
ToBranch string `json:"to_branch,omitempty"`
Message string `json:"message,omitempty"`
PRLink string `json:"pr_link,omitempty"`
Update bool `json:"update,omitempty"`
}
// OperationStatus is the status of an operation
type OperationStatus int
// There are the different OperationStatus values
const (
OperationStatusPending OperationStatus = iota
OperationStatusProcessing
OperationStatusDone
OperationStatusError
)
// OperationRepo is an operation
type OperationRepo struct {
Basedir string
URL string
RepositoryStrategy RepositoryStrategy
}
// ID returns a generated ID for a Operation
func (r OperationRepo) ID() string {
return base64.StdEncoding.EncodeToString([]byte(r.URL))
}
| {
"content_hash": "c063bfd64b48710bd7dd7226bed8de7e",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 79,
"avg_line_length": 32.41732283464567,
"alnum_prop": 0.6737915958222006,
"repo_name": "ovh/cds",
"id": "8c4388b2ab1b3ac35088d2adbfb6572a0b944093",
"size": "4117",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/repositories_operation.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "1616"
},
{
"name": "Go",
"bytes": "7822995"
},
{
"name": "HTML",
"bytes": "594997"
},
{
"name": "JavaScript",
"bytes": "47672"
},
{
"name": "Less",
"bytes": "793"
},
{
"name": "Makefile",
"bytes": "79754"
},
{
"name": "PLpgSQL",
"bytes": "38853"
},
{
"name": "SCSS",
"bytes": "114372"
},
{
"name": "Shell",
"bytes": "14838"
},
{
"name": "TypeScript",
"bytes": "1760477"
}
],
"symlink_target": ""
} |
ActiveRecord::Schema.define(version: 0) do
create_table "access_keys", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.string "name", limit: 255, null: false
t.string "info", limit: 255
t.string "url", limit: 255
t.string "encrypted_password", limit: 255
t.string "access_token", limit: 32
t.string "encrypted_account_name", limit: 255
end
add_index "access_keys", ["access_token"], name: "access_token", unique: true, using: :btree
add_index "access_keys", ["name"], name: "name", unique: true, using: :btree
create_table "databases", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.integer "db_subject_id", limit: 2
t.string "name", limit: 255, null: false
t.string "url", limit: 255
t.string "aai_url", limit: 255
t.text "info", limit: 65535
t.string "notice", limit: 255
t.string "notice_type", limit: 7
t.date "notice_start"
t.date "notice_end"
t.string "help", limit: 510
t.string "help_url", limit: 255
t.string "mobile_info", limit: 255
t.string "mobile_url", limit: 255
t.boolean "sfx", default: false, null: false
t.string "access_type", limit: 6, null: false
t.boolean "test", default: false, null: false
t.date "test_end"
t.integer "last_http_code", limit: 2
t.boolean "url_notified", default: false, null: false
t.date "checked"
t.string "bad_codes", limit: 30
t.string "access_help", limit: 255
t.string "query_url", limit: 255
t.string "query_fields", limit: 255
t.string "query_and", limit: 255
t.string "query_or", limit: 255
end
add_index "databases", ["name"], name: "name", unique: true, using: :btree
create_table "databases_db_groups", id: false, force: :cascade do |t|
t.integer "database_id", limit: 2, null: false
t.integer "db_group_id", limit: 2, null: false
end
add_index "databases_db_groups", ["db_group_id"], name: "databases_db_groups_db_group_id_fk", using: :btree
create_table "databases_db_periods", id: false, force: :cascade do |t|
t.integer "database_id", limit: 2, null: false
t.integer "db_period_id", limit: 2, null: false
end
add_index "databases_db_periods", ["db_period_id"], name: "databases_db_periods_db_period_id_fk", using: :btree
create_table "databases_db_regions", id: false, force: :cascade do |t|
t.integer "database_id", limit: 2, null: false
t.integer "db_region_id", limit: 2, null: false
end
add_index "databases_db_regions", ["db_region_id"], name: "databases_regions_region_id_fk", using: :btree
create_table "databases_db_types", id: false, force: :cascade do |t|
t.integer "database_id", limit: 2, null: false
t.integer "db_type_id", limit: 2, null: false
end
add_index "databases_db_types", ["db_type_id"], name: "databases_db_types_db_type_id_fk", using: :btree
create_table "db_group_des", force: :cascade do |t|
t.integer "db_group_id", limit: 2, null: false
t.string "name", limit: 255
t.string "url", limit: 255
end
add_index "db_group_des", ["db_group_id"], name: "db_group_id", unique: true, using: :btree
add_index "db_group_des", ["name"], name: "name", unique: true, using: :btree
create_table "db_group_ens", force: :cascade do |t|
t.integer "db_group_id", limit: 2, null: false
t.string "name", limit: 255
t.string "url", limit: 255
end
add_index "db_group_ens", ["db_group_id"], name: "db_group_id", unique: true, using: :btree
add_index "db_group_ens", ["name"], name: "name", unique: true, using: :btree
create_table "db_groups", force: :cascade do |t|
t.string "name", limit: 255
t.string "url", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
end
add_index "db_groups", ["name"], name: "name", unique: true, using: :btree
create_table "db_period_des", force: :cascade do |t|
t.integer "db_period_id", limit: 2, null: false
t.string "name", limit: 255
end
add_index "db_period_des", ["db_period_id"], name: "db_period_id", unique: true, using: :btree
add_index "db_period_des", ["name"], name: "name", unique: true, using: :btree
create_table "db_period_ens", force: :cascade do |t|
t.integer "db_period_id", limit: 2, null: false
t.string "name", limit: 255
end
add_index "db_period_ens", ["db_period_id"], name: "db_period_id", unique: true, using: :btree
add_index "db_period_ens", ["name"], name: "name", unique: true, using: :btree
create_table "db_periods", force: :cascade do |t|
t.integer "sort_key", limit: 1
t.string "name", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
end
add_index "db_periods", ["name"], name: "name", unique: true, using: :btree
add_index "db_periods", ["sort_key"], name: "index_time_periods_on_sort_key", unique: true, using: :btree
create_table "db_region_des", force: :cascade do |t|
t.integer "db_region_id", limit: 2, null: false
t.string "name", limit: 255
end
add_index "db_region_des", ["db_region_id"], name: "db_region_id", unique: true, using: :btree
add_index "db_region_des", ["name"], name: "name", unique: true, using: :btree
create_table "db_region_ens", force: :cascade do |t|
t.integer "db_region_id", limit: 2, null: false
t.string "name", limit: 255
end
add_index "db_region_ens", ["db_region_id"], name: "db_region_id", unique: true, using: :btree
add_index "db_region_ens", ["name"], name: "name", unique: true, using: :btree
create_table "db_regions", force: :cascade do |t|
t.string "catalog_number", limit: 3
t.string "name", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
end
add_index "db_regions", ["catalog_number"], name: "index_regions_on_catalog_number", unique: true, using: :btree
add_index "db_regions", ["name"], name: "name", unique: true, using: :btree
create_table "db_subj_weights", force: :cascade do |t|
t.integer "db_subject_id", limit: 2, null: false
t.integer "database_id", limit: 2, null: false
t.integer "importance", limit: 2, null: false
end
add_index "db_subj_weights", ["database_id"], name: "weights_database_id_fk", using: :btree
add_index "db_subj_weights", ["db_subject_id", "database_id", "importance"], name: "db_subject_id", unique: true, using: :btree
create_table "db_subject_des", force: :cascade do |t|
t.integer "db_subject_id", limit: 2, null: false
t.string "name", limit: 80
end
add_index "db_subject_des", ["db_subject_id"], name: "db_subject_id", unique: true, using: :btree
add_index "db_subject_des", ["name"], name: "index_subjects_on_name", unique: true, using: :btree
create_table "db_subject_ens", force: :cascade do |t|
t.integer "db_subject_id", limit: 2, null: false
t.string "name", limit: 80
end
add_index "db_subject_ens", ["db_subject_id"], name: "db_subject_id", unique: true, using: :btree
add_index "db_subject_ens", ["name"], name: "index_subjects_on_name", unique: true, using: :btree
create_table "db_subject_groups", force: :cascade do |t|
t.integer "subj_area_id", limit: 1, null: false
t.string "name", limit: 80
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0, null: false
end
add_index "db_subject_groups", ["name"], name: "index_subjects_on_name", unique: true, using: :btree
add_index "db_subject_groups", ["subj_area_id"], name: "subj_area_id", using: :btree
create_table "db_subjects", force: :cascade do |t|
t.integer "subj_area_id", limit: 1, null: false
t.boolean "general", default: false, null: false
t.string "name", limit: 80
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0, null: false
end
add_index "db_subjects", ["name"], name: "index_subjects_on_name", unique: true, using: :btree
add_index "db_subjects", ["subj_area_id"], name: "subj_area_id", using: :btree
create_table "db_subjects_users", id: false, force: :cascade do |t|
t.integer "user_id", limit: 2, null: false
t.integer "db_subject_id", limit: 2, null: false
end
add_index "db_subjects_users", ["db_subject_id"], name: "db_subjects_users_db_subject_id_fk", using: :btree
create_table "db_type_des", force: :cascade do |t|
t.integer "db_type_id", limit: 2, null: false
t.string "name", limit: 255
end
add_index "db_type_des", ["db_type_id"], name: "db_type_id", unique: true, using: :btree
add_index "db_type_des", ["name"], name: "name", unique: true, using: :btree
create_table "db_type_ens", force: :cascade do |t|
t.integer "db_type_id", limit: 2, null: false
t.string "name", limit: 255
end
add_index "db_type_ens", ["db_type_id"], name: "db_type_id", unique: true, using: :btree
add_index "db_type_ens", ["name"], name: "name", unique: true, using: :btree
create_table "db_types", force: :cascade do |t|
t.string "sort_key", limit: 3, null: false
t.string "name", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
end
add_index "db_types", ["name"], name: "name", unique: true, using: :btree
add_index "db_types", ["sort_key"], name: "index_database_types_on_sort_key", unique: true, using: :btree
create_table "faculties", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
end
create_table "faculties_libraries", id: false, force: :cascade do |t|
t.integer "faculty_id", limit: 2, null: false
t.integer "library_id", limit: 2, null: false
end
create_table "faculty_des", force: :cascade do |t|
t.integer "faculty_id", limit: 2, null: false
t.string "name", limit: 255, null: false
end
add_index "faculty_des", ["name"], name: "name", unique: true, using: :btree
create_table "faculty_ens", force: :cascade do |t|
t.integer "faculty_id", limit: 2, null: false
t.string "name", limit: 255, null: false
end
add_index "faculty_ens", ["name"], name: "name", unique: true, using: :btree
create_table "libraries", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.boolean "active", default: true, null: false
t.boolean "reserve_by_email", default: false, null: false
t.boolean "reserve_by_phone", default: false, null: false
t.boolean "reserve_onsite", default: false, null: false
t.boolean "acquisition_suggest", default: false, null: false
t.string "acquisition_email", limit: 100
t.string "lib_code", limit: 6, null: false
t.string "email_1", limit: 255
t.string "email_2", limit: 255
t.string "fax", limit: 255
t.string "seal", limit: 10
t.string "telephone_1", limit: 255, null: false
t.string "telephone_2", limit: 255
end
add_index "libraries", ["lib_code"], name: "lib_code", unique: true, using: :btree
create_table "libraries_library_properties", id: false, force: :cascade do |t|
t.integer "library_id", limit: 2, null: false
t.integer "library_property_id", limit: 2, null: false
end
create_table "library_cat_des", force: :cascade do |t|
t.integer "library_cat_id", limit: 2
t.string "name", limit: 255
end
add_index "library_cat_des", ["name"], name: "name", unique: true, using: :btree
create_table "library_cat_ens", force: :cascade do |t|
t.integer "library_cat_id", limit: 2
t.string "name", limit: 255
end
add_index "library_cat_ens", ["name"], name: "name", unique: true, using: :btree
create_table "library_cats", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0, null: false
t.integer "library_id", limit: 2
t.string "lib_code", limit: 7, default: "", null: false
t.string "call_number", limit: 255
t.boolean "single_subject", default: true, null: false
t.boolean "active", null: false
t.string "query_type", limit: 3, default: "nel", null: false
end
add_index "library_cats", ["library_id", "lib_code", "call_number"], name: "library_id", unique: true, using: :btree
create_table "library_cats_subjs", id: false, force: :cascade do |t|
t.integer "library_subj_id", limit: 2, null: false
t.integer "library_cat_id", limit: 2, null: false
end
create_table "library_des", force: :cascade do |t|
t.integer "library_id", limit: 2, null: false
t.string "name", limit: 255, null: false
t.string "short_name", limit: 63
t.text "focus", limit: 65535
t.string "postal_address", limit: 255
t.string "postal_delivery", limit: 255
t.text "setup", limit: 65535
t.text "information", limit: 65535
t.string "online_catalog", limit: 255
t.string "subject_catalog", limit: 255
t.string "contact", limit: 255
t.text "interlibrary_loan", limit: 65535
t.text "loan", limit: 65535
t.string "website_1", limit: 255
t.string "website_2", limit: 255
t.string "reservation_url", limit: 255
end
add_index "library_des", ["name"], name: "name_de", unique: true, using: :btree
create_table "library_ens", force: :cascade do |t|
t.integer "library_id", limit: 2, null: false
t.string "name", limit: 255, null: false
t.string "short_name", limit: 63
t.text "focus", limit: 65535
t.string "postal_address", limit: 255
t.string "postal_delivery", limit: 255
t.text "setup", limit: 65535
t.text "information", limit: 65535
t.string "online_catalog", limit: 255
t.string "subject_catalog", limit: 255
t.string "contact", limit: 255
t.text "interlibrary_loan", limit: 65535
t.text "loan", limit: 65535
t.string "website_1", limit: 255
t.string "website_2", limit: 255
t.string "reservation_url", limit: 255
end
add_index "library_ens", ["name"], name: "name_de", unique: true, using: :btree
create_table "library_events", force: :cascade do |t|
t.integer "library_schedule_id", limit: 2, null: false
t.integer "lock_version", limit: 2, default: 0
t.integer "day_number", limit: 1
t.integer "event_number", limit: 1, null: false
t.string "minutes_start", limit: 4
t.string "minutes_end", limit: 4
end
create_table "library_location_des", force: :cascade do |t|
t.integer "library_location_id", limit: 2, null: false
t.text "access_info", limit: 65535
t.string "identifier", limit: 255, null: false
t.text "holdings", limit: 65535
t.string "street_number", limit: 255
t.string "website_1", limit: 255
t.string "zip_town", limit: 255
t.string "plan_url", limit: 255
end
add_index "library_location_des", ["identifier"], name: "name", unique: true, using: :btree
add_index "library_location_des", ["library_location_id"], name: "library_location_id", unique: true, using: :btree
create_table "library_location_ens", force: :cascade do |t|
t.integer "library_location_id", limit: 2, null: false
t.text "access_info", limit: 65535
t.string "identifier", limit: 255, null: false
t.text "holdings", limit: 65535
t.string "street_number", limit: 255
t.string "website_1", limit: 255
t.string "zip_town", limit: 255
t.string "plan_url", limit: 255
end
add_index "library_location_ens", ["identifier"], name: "name", unique: true, using: :btree
add_index "library_location_ens", ["library_location_id"], name: "library_location_id", unique: true, using: :btree
create_table "library_locations", force: :cascade do |t|
t.integer "library_id", limit: 2
t.integer "library_user_group_id", limit: 2
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.boolean "show_map", default: true, null: false
t.string "access_type", limit: 11, default: "public", null: false
t.string "email_1", limit: 255
t.string "longitude", limit: 10, default: "", null: false
t.string "latitude", limit: 10, default: "", null: false
t.string "telephone_1", limit: 255
t.string "telephone_2", limit: 255
t.string "mensa_website", limit: 255
end
add_index "library_locations", ["library_id"], name: "library_id", using: :btree
create_table "library_locations_properties", id: false, force: :cascade do |t|
t.integer "library_location_id", limit: 2, null: false
t.integer "library_property_id", limit: 2, null: false
end
create_table "library_locations_user_groups", id: false, force: :cascade do |t|
t.integer "library_location_id", limit: 2, null: false
t.integer "library_user_group_id", limit: 2, null: false
end
create_table "library_properties", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.boolean "library_context", default: false, null: false
t.boolean "location_context", default: false, null: false
t.boolean "room_context", default: false, null: false
t.string "property_type", limit: 4, default: "text", null: false
t.string "icon_file_name", limit: 255
t.string "icon_name", limit: 255
t.integer "sort_key", limit: 1, null: false
t.string "identifier", limit: 8, null: false
end
add_index "library_properties", ["identifier"], name: "identifier", unique: true, using: :btree
add_index "library_properties", ["sort_key"], name: "sort_key", using: :btree
create_table "library_properties_rooms", id: false, force: :cascade do |t|
t.integer "library_property_id", limit: 2, null: false
t.integer "library_room_id", limit: 2, null: false
end
create_table "library_property_des", force: :cascade do |t|
t.integer "library_property_id", limit: 2, null: false
t.string "name", limit: 255, null: false
end
add_index "library_property_des", ["library_property_id"], name: "library_property_id", unique: true, using: :btree
add_index "library_property_des", ["name"], name: "name_de", unique: true, using: :btree
create_table "library_property_ens", force: :cascade do |t|
t.integer "library_property_id", limit: 2, null: false
t.string "name", limit: 255, null: false
end
add_index "library_property_ens", ["library_property_id"], name: "library_property_id", unique: true, using: :btree
add_index "library_property_ens", ["name"], name: "name_en", unique: true, using: :btree
create_table "library_room_des", force: :cascade do |t|
t.integer "library_room_id", limit: 2, null: false
t.string "name", limit: 255
t.string "identifier", limit: 255, null: false
t.text "info", limit: 65535
end
add_index "library_room_des", ["library_room_id"], name: "library_room_id", unique: true, using: :btree
create_table "library_room_ens", force: :cascade do |t|
t.integer "library_room_id", limit: 2, null: false
t.string "name", limit: 255
t.string "identifier", limit: 255
t.text "info", limit: 65535
end
add_index "library_room_ens", ["library_room_id", "name", "identifier"], name: "library_room_id", unique: true, using: :btree
create_table "library_rooms", force: :cascade do |t|
t.integer "library_location_id", limit: 2
t.integer "library_user_group_id", limit: 2
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.boolean "reservable", default: false, null: false
t.boolean "restricted_group", default: false, null: false
t.boolean "own_entry", default: false, null: false
t.string "room_type", limit: 10, default: "group", null: false
t.string "security_type", limit: 5, default: "open", null: false
t.integer "capacity", limit: 2
t.integer "occupancy", limit: 2
end
create_table "library_rooms_user_groups", id: false, force: :cascade do |t|
t.integer "library_room_id", limit: 2, null: false
t.integer "library_user_group_id", limit: 2, null: false
end
create_table "library_schedules", force: :cascade do |t|
t.integer "scheduleable_id", limit: 2
t.string "scheduleable_type", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.string "opening_type", limit: 16, null: false
t.date "date_start"
t.date "date_end"
t.string "time_start", limit: 4
t.string "time_end", limit: 4
end
create_table "library_subj_des", force: :cascade do |t|
t.integer "library_subj_id", limit: 2, null: false
t.string "name", limit: 255, null: false
t.string "url", limit: 255
end
add_index "library_subj_des", ["name"], name: "fachname", unique: true, using: :btree
create_table "library_subj_ens", force: :cascade do |t|
t.integer "library_subj_id", limit: 2, null: false
t.string "name", limit: 255, null: false
t.string "url", limit: 255
end
add_index "library_subj_ens", ["name"], name: "fachname", unique: true, using: :btree
create_table "library_subjs", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0, null: false
t.boolean "active", null: false
t.string "themes", limit: 255, null: false
t.string "format", limit: 255
t.string "note", limit: 255
end
create_table "library_user_group_des", force: :cascade do |t|
t.integer "library_user_group_id", limit: 2, null: false
t.string "identifier", limit: 255, null: false
end
add_index "library_user_group_des", ["identifier"], name: "identifier", unique: true, using: :btree
add_index "library_user_group_des", ["library_user_group_id"], name: "library_user_group_id", unique: true, using: :btree
create_table "library_user_group_ens", force: :cascade do |t|
t.integer "library_user_group_id", limit: 2, null: false
t.string "identifier", limit: 255, null: false
end
add_index "library_user_group_ens", ["identifier"], name: "identifier", unique: true, using: :btree
add_index "library_user_group_ens", ["library_user_group_id"], name: "library_user_group_id", unique: true, using: :btree
create_table "library_user_groups", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
end
create_table "library_vcats", id: false, force: :cascade do |t|
t.integer "id", limit: 2, default: 0, null: false
t.integer "library_id", limit: 2
t.string "lib_code", limit: 7
t.string "call_number", limit: 255
t.string "query_type", limit: 3, default: "nel", null: false
t.boolean "active", null: false
t.boolean "single_subject", default: true, null: false
end
create_table "link_check_aai_urls", force: :cascade do |t|
t.integer "database_id", limit: 2
t.integer "last_http_code", limit: 2
t.boolean "url_notified", default: false, null: false
t.date "checked"
t.string "bad_codes", limit: 30
end
add_index "link_check_aai_urls", ["database_id"], name: "database_id", unique: true, using: :btree
create_table "link_check_help_urls", force: :cascade do |t|
t.integer "database_id", limit: 2
t.integer "last_http_code", limit: 2
t.boolean "url_notified", default: false, null: false
t.date "checked"
t.string "bad_codes", limit: 30
end
add_index "link_check_help_urls", ["database_id"], name: "database_id", unique: true, using: :btree
create_table "link_check_mobile_urls", force: :cascade do |t|
t.integer "database_id", limit: 2, null: false
t.integer "last_http_code", limit: 2
t.boolean "url_notified", default: false, null: false
t.date "checked"
t.string "bad_codes", limit: 30
end
add_index "link_check_mobile_urls", ["database_id"], name: "database_id", unique: true, using: :btree
create_table "music_composers", force: :cascade do |t|
t.string "name", limit: 255, default: "", null: false
t.integer "birth_year", limit: 2
t.string "birth_year_comment", limit: 15
t.integer "death_year", limit: 2
t.string "death_year_comment", limit: 15
t.string "biography_file_name", limit: 5
t.string "url", limit: 255
end
create_table "music_composers_works", id: false, force: :cascade do |t|
t.integer "music_composer_id", limit: 2, default: 0, null: false
t.integer "music_work_id", limit: 2, null: false
end
add_index "music_composers_works", ["music_work_id"], name: "music_work_id", using: :btree
create_table "music_instrumentation_types", force: :cascade do |t|
t.string "name", limit: 255, default: "", null: false
end
create_table "music_instrumentation_types_works", id: false, force: :cascade do |t|
t.integer "music_work_id", limit: 2, default: 0, null: false
t.integer "music_instrumentation_type_id", limit: 2, default: 0, null: false
end
add_index "music_instrumentation_types_works", ["music_work_id"], name: "music_instrumentation_types_works_music_work_id_fk", using: :btree
create_table "music_works", force: :cascade do |t|
t.string "name", limit: 255
t.string "name_order", limit: 63, default: "", null: false
t.string "opus_number", limit: 31
t.string "publication_year", limit: 31
t.string "instrumentation", limit: 255
t.string "publication_place", limit: 255
t.string "location", limit: 255
t.string "keywords_1", limit: 255
t.string "keywords_2", limit: 255
t.string "keywords_3", limit: 255
end
add_index "music_works", ["name_order"], name: "name_order", using: :btree
create_table "redirects", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.integer "access_key_sort", limit: 4, default: 0, null: false
t.string "access_key", limit: 31, null: false
t.string "target", limit: 255, null: false
end
add_index "redirects", ["access_key"], name: "access_key", unique: true, using: :btree
add_index "redirects", ["access_key"], name: "access_key_2", using: :btree
create_table "roles", force: :cascade do |t|
t.string "name", limit: 63
t.string "description", limit: 255
t.integer "lock_version", limit: 2, default: 0
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
end
add_index "roles", ["description"], name: "description", unique: true, using: :btree
add_index "roles", ["name"], name: "index_roles_on_name", unique: true, using: :btree
create_table "roles_users", id: false, force: :cascade do |t|
t.integer "user_id", limit: 2, null: false
t.integer "role_id", limit: 2, null: false
end
add_index "roles_users", ["role_id"], name: "roles_users_role_id_fk", using: :btree
create_table "subj_areas", force: :cascade do |t|
t.string "name", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
end
add_index "subj_areas", ["name"], name: "name", unique: true, using: :btree
create_table "users", force: :cascade do |t|
t.string "username", limit: 31
t.string "password_digest", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "updated_by", limit: 2
t.integer "lock_version", limit: 2, default: 0
t.string "first_last_name", limit: 255
t.string "email", limit: 255
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree
add_foreign_key "music_composers_works", "music_composers", name: "music_composers_works_music_composer_id_fk"
add_foreign_key "music_composers_works", "music_works", name: "music_composers_works_ibfk_1"
add_foreign_key "music_instrumentation_types_works", "music_instrumentation_types", name: "music_instrumentation_types_works_instrumentation_type_id_fk"
add_foreign_key "music_instrumentation_types_works", "music_works", name: "music_instrumentation_types_works_music_work_id_fk"
end
| {
"content_hash": "c9c7c0985047fafc584f2afa6d951ef2",
"timestamp": "",
"source": "github",
"line_count": 732,
"max_line_length": 154,
"avg_line_length": 43.61748633879781,
"alnum_prop": 0.593460285642696,
"repo_name": "UB-Bern/uni-bern-ub-pub",
"id": "9baf2786fe4c4c22be939602caed50078385f8de",
"size": "32669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/schema.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "44099"
},
{
"name": "CoffeeScript",
"bytes": "486"
},
{
"name": "HTML",
"bytes": "218245"
},
{
"name": "JavaScript",
"bytes": "8659"
},
{
"name": "Ruby",
"bytes": "198782"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.peering.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.resourcemanager.peering.fluent.models.PeeringServiceCountryInner;
/** An instance of this class provides access to all the operations defined in PeeringServiceCountriesClient. */
public interface PeeringServiceCountriesClient {
/**
* Lists all of the available countries for peering service.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the paginated list of peering service countries.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<PeeringServiceCountryInner> list();
/**
* Lists all of the available countries for peering service.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the paginated list of peering service countries.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<PeeringServiceCountryInner> list(Context context);
}
| {
"content_hash": "e7839cdc19f5488c22c5226bb2be8ce8",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 115,
"avg_line_length": 48.611111111111114,
"alnum_prop": 0.7685714285714286,
"repo_name": "Azure/azure-sdk-for-java",
"id": "83b9d54e207f083b6d967dbf43aaa3398384768c",
"size": "1750",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/peering/azure-resourcemanager-peering/src/main/java/com/azure/resourcemanager/peering/fluent/PeeringServiceCountriesClient.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
<html lang="en">
<head>
<title>ARM Mapping Symbols - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="ARM_002dDependent.html#ARM_002dDependent" title="ARM-Dependent">
<link rel="prev" href="ARM-Opcodes.html#ARM-Opcodes" title="ARM Opcodes">
<link rel="next" href="ARM-Unwinding-Tutorial.html#ARM-Unwinding-Tutorial" title="ARM Unwinding Tutorial">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2014 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<a name="ARM-Mapping-Symbols"></a>
<p>
Next: <a rel="next" accesskey="n" href="ARM-Unwinding-Tutorial.html#ARM-Unwinding-Tutorial">ARM Unwinding Tutorial</a>,
Previous: <a rel="previous" accesskey="p" href="ARM-Opcodes.html#ARM-Opcodes">ARM Opcodes</a>,
Up: <a rel="up" accesskey="u" href="ARM_002dDependent.html#ARM_002dDependent">ARM-Dependent</a>
<hr>
</div>
<h4 class="subsection">9.4.6 Mapping Symbols</h4>
<p>The ARM ELF specification requires that special symbols be inserted
into object files to mark certain features:
<a name="index-g_t_0040code_007b_0024a_007d-706"></a>
<dl><dt><code>$a</code><dd>At the start of a region of code containing ARM instructions.
<p><a name="index-g_t_0040code_007b_0024t_007d-707"></a><br><dt><code>$t</code><dd>At the start of a region of code containing THUMB instructions.
<p><a name="index-g_t_0040code_007b_0024d_007d-708"></a><br><dt><code>$d</code><dd>At the start of a region of data.
</dl>
<p>The assembler will automatically insert these symbols for you - there
is no need to code them yourself. Support for tagging symbols ($b,
$f, $p and $m) which is also mentioned in the current ARM ELF
specification is not implemented. This is because they have been
dropped from the new EABI and so tools cannot rely upon their
presence.
</body></html>
| {
"content_hash": "9f569190159d18284b54f245e395b605",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 151,
"avg_line_length": 42.929577464788736,
"alnum_prop": 0.7267060367454068,
"repo_name": "ExploreEmbedded/Tit-Windows",
"id": "6ac8113b604e60be5685077bc4ff02cc61288ca4",
"size": "3048",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tools/doc/binutils/as.html/ARM-Mapping-Symbols.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arduino",
"bytes": "36420"
},
{
"name": "C",
"bytes": "68039"
},
{
"name": "C++",
"bytes": "59295"
},
{
"name": "Objective-C",
"bytes": "13990"
}
],
"symlink_target": ""
} |
'use strict';
const Systrace = require('../Performance/Systrace');
const infoLog = require('./infoLog');
const performanceNow =
global.nativeQPLTimestamp ||
global.nativePerformanceNow ||
require('fbjs/lib/performanceNow');
type Timespan = {
description?: string,
totalTime?: number,
startTime?: number,
endTime?: number,
...
};
export type IPerformanceLogger = {
addTimespan(string, number, string | void): void,
startTimespan(string, string | void): void,
stopTimespan(string, options?: {update?: boolean}): void,
clear(): void,
clearCompleted(): void,
clearExceptTimespans(Array<string>): void,
currentTimestamp(): number,
getTimespans(): {[key: string]: Timespan, ...},
hasTimespan(string): boolean,
logTimespans(): void,
addTimespans(Array<number>, Array<string>): void,
setExtra(string, any): void,
getExtras(): {[key: string]: any, ...},
removeExtra(string): ?any,
logExtras(): void,
markPoint(string, number | void): void,
getPoints(): {[key: string]: number, ...},
logPoints(): void,
logEverything(): void,
...
};
const _cookies: {[key: string]: number, ...} = {};
const PRINT_TO_CONSOLE: false = false; // Type as false to prevent accidentally committing `true`;
/**
* This function creates performance loggers that can be used to collect and log
* various performance data such as timespans, points and extras.
* The loggers need to have minimal overhead since they're used in production.
*/
function createPerformanceLogger(): IPerformanceLogger {
const result: IPerformanceLogger & {
_timespans: {[key: string]: Timespan, ...},
_extras: {[key: string]: any, ...},
_points: {[key: string]: number, ...},
...
} = {
_timespans: {},
_extras: {},
_points: {},
addTimespan(key: string, lengthInMs: number, description?: string) {
if (this._timespans[key]) {
if (PRINT_TO_CONSOLE && __DEV__) {
infoLog(
'PerformanceLogger: Attempting to add a timespan that already exists ',
key,
);
}
return;
}
this._timespans[key] = {
description: description,
totalTime: lengthInMs,
};
},
startTimespan(key: string, description?: string) {
if (this._timespans[key]) {
if (PRINT_TO_CONSOLE && __DEV__) {
infoLog(
'PerformanceLogger: Attempting to start a timespan that already exists ',
key,
);
}
return;
}
this._timespans[key] = {
description: description,
startTime: performanceNow(),
};
_cookies[key] = Systrace.beginAsyncEvent(key);
if (PRINT_TO_CONSOLE) {
infoLog('PerformanceLogger.js', 'start: ' + key);
}
},
stopTimespan(key: string, options?: {update?: boolean}) {
const timespan = this._timespans[key];
if (!timespan || !timespan.startTime) {
if (PRINT_TO_CONSOLE && __DEV__) {
infoLog(
'PerformanceLogger: Attempting to end a timespan that has not started ',
key,
);
}
return;
}
if (timespan.endTime && !options?.update) {
if (PRINT_TO_CONSOLE && __DEV__) {
infoLog(
'PerformanceLogger: Attempting to end a timespan that has already ended ',
key,
);
}
return;
}
timespan.endTime = performanceNow();
timespan.totalTime = timespan.endTime - (timespan.startTime || 0);
if (PRINT_TO_CONSOLE) {
infoLog('PerformanceLogger.js', 'end: ' + key);
}
if (_cookies[key] != null) {
Systrace.endAsyncEvent(key, _cookies[key]);
delete _cookies[key];
}
},
clear() {
this._timespans = {};
this._extras = {};
this._points = {};
if (PRINT_TO_CONSOLE) {
infoLog('PerformanceLogger.js', 'clear');
}
},
clearCompleted() {
for (const key in this._timespans) {
if (this._timespans[key].totalTime) {
delete this._timespans[key];
}
}
this._extras = {};
this._points = {};
if (PRINT_TO_CONSOLE) {
infoLog('PerformanceLogger.js', 'clearCompleted');
}
},
clearExceptTimespans(keys: Array<string>) {
this._timespans = Object.keys(this._timespans).reduce(function(
previous,
key,
) {
if (keys.indexOf(key) !== -1) {
previous[key] = this._timespans[key];
}
return previous;
},
{});
this._extras = {};
this._points = {};
if (PRINT_TO_CONSOLE) {
infoLog('PerformanceLogger.js', 'clearExceptTimespans', keys);
}
},
currentTimestamp() {
return performanceNow();
},
getTimespans() {
return this._timespans;
},
hasTimespan(key: string) {
return !!this._timespans[key];
},
logTimespans() {
if (PRINT_TO_CONSOLE) {
for (const key in this._timespans) {
if (this._timespans[key].totalTime) {
infoLog(key + ': ' + this._timespans[key].totalTime + 'ms');
}
}
}
},
addTimespans(newTimespans: Array<number>, labels: Array<string>) {
for (let ii = 0, l = newTimespans.length; ii < l; ii += 2) {
const label = labels[ii / 2];
this.addTimespan(label, newTimespans[ii + 1] - newTimespans[ii], label);
}
},
setExtra(key: string, value: any) {
if (this._extras[key]) {
if (PRINT_TO_CONSOLE && __DEV__) {
infoLog(
'PerformanceLogger: Attempting to set an extra that already exists ',
{key, currentValue: this._extras[key], attemptedValue: value},
);
}
return;
}
this._extras[key] = value;
},
getExtras() {
return this._extras;
},
removeExtra(key: string): ?any {
const value = this._extras[key];
delete this._extras[key];
return value;
},
logExtras() {
if (PRINT_TO_CONSOLE) {
infoLog(this._extras);
}
},
markPoint(key: string, timestamp?: number) {
if (this._points[key]) {
if (PRINT_TO_CONSOLE && __DEV__) {
infoLog(
'PerformanceLogger: Attempting to mark a point that has been already logged ',
key,
);
}
return;
}
this._points[key] = timestamp ?? performanceNow();
},
getPoints() {
return this._points;
},
logPoints() {
if (PRINT_TO_CONSOLE) {
for (const key in this._points) {
infoLog(key + ': ' + this._points[key] + 'ms');
}
}
},
logEverything() {
this.logTimespans();
this.logExtras();
this.logPoints();
},
};
return result;
}
module.exports = createPerformanceLogger;
| {
"content_hash": "55c2e97956aa23d30028bde917baf020",
"timestamp": "",
"source": "github",
"line_count": 267,
"max_line_length": 98,
"avg_line_length": 25.741573033707866,
"alnum_prop": 0.5528881129055725,
"repo_name": "exponent/react-native",
"id": "2bfdb34258169e87112a24acb6f8800d90944bae",
"size": "7084",
"binary": false,
"copies": "3",
"ref": "refs/heads/exp-latest",
"path": "Libraries/Utilities/createPerformanceLogger.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "15612"
},
{
"name": "Awk",
"bytes": "121"
},
{
"name": "Batchfile",
"bytes": "683"
},
{
"name": "C",
"bytes": "182631"
},
{
"name": "C++",
"bytes": "738469"
},
{
"name": "CSS",
"bytes": "31486"
},
{
"name": "HTML",
"bytes": "34338"
},
{
"name": "IDL",
"bytes": "897"
},
{
"name": "Java",
"bytes": "2734102"
},
{
"name": "JavaScript",
"bytes": "3521229"
},
{
"name": "Makefile",
"bytes": "8493"
},
{
"name": "Objective-C",
"bytes": "1405671"
},
{
"name": "Objective-C++",
"bytes": "204752"
},
{
"name": "Prolog",
"bytes": "287"
},
{
"name": "Python",
"bytes": "123976"
},
{
"name": "Ruby",
"bytes": "7013"
},
{
"name": "Shell",
"bytes": "29715"
}
],
"symlink_target": ""
} |
@interface MXStatusCell : UITableViewCell
@property(nonatomic,strong) MXStatusFrame *statusFrame;
+(instancetype)createCellTableView:(UITableView *)tableView;
@end
| {
"content_hash": "2c67f668191d8347b494317eedbf2ddc",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 60,
"avg_line_length": 33,
"alnum_prop": 0.8303030303030303,
"repo_name": "moixxsyc/MXWeiboTest",
"id": "ec920ffdaada02eb4363e1e3322969a4c4cec112",
"size": "350",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MXWeiboTest/MXWeiboTest/class/home/view/MXStatusCell.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "30543"
},
{
"name": "Objective-C",
"bytes": "1049349"
},
{
"name": "Ruby",
"bytes": "118"
},
{
"name": "Shell",
"bytes": "8163"
}
],
"symlink_target": ""
} |
// Type definitions for Select2 3.2
// Project: http://ivaynberg.github.com/select2/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface Select2QueryOptions {
term?: string;
page?: number;
context?: any;
callback?: (result: { results: any; more?: boolean; context?: any; }) => void;
}
interface AjaxFunction {
(settings: JQueryAjaxSettings): JQueryXHR;
(url: string, settings?: JQueryAjaxSettings): JQueryXHR;
}
interface Select2AjaxOptions {
transport?: AjaxFunction;
/**
* Url to make request to, Can be string or a function returning a string.
*/
url?: any;
dataType?: string;
quietMillis?: number;
data?: (term: string, page: number, context: any) => any;
results?: (term: any, page: number, context: any) => any;
}
interface IdTextPair {
id: any;
text: string;
}
interface Select2Options {
width?: string;
dropdownAutoWidth?: boolean;
minimumInputLength?: number;
minimumResultsForSearch?: number;
maximumSelectionSize?: number;
placeholder?: string;
separator?: string;
allowClear?: boolean;
multiple?: boolean;
closeOnSelect?: boolean;
openOnEnter?: boolean;
id?: (object: any) => string;
matcher?: (term: string, text: string, option: any) => boolean;
formatSelection?: (object: any, container: JQuery, escapeMarkup:(markup: string) => string) => string;
formatResult?: (object: any, container: JQuery, query: any, escapeMarkup: (markup: string) => string) => string;
formatResultCssClass?: (object: any) => string;
formatNoMatches?: (term: string) => string;
formatSearching?: () => string;
formatInputTooShort?: (term: string, minLength: number) => string;
formatSelectionTooBig?: (maxSize: number) => string;
formatLoadMore?: (pageNumber: number) => string;
createSearchChoice?: (term: string, data: any) => any;
initSelection?: (element: JQuery, callback: (data: any) => void ) => void;
tokenizer?: (input: string, selection: any[], selectCallback: () => void , options: Select2Options) => string;
tokenSeparators?: string[];
query?: (options: Select2QueryOptions) => void;
ajax?: Select2AjaxOptions;
data?: any;
tags?: any;
containerCss?: any;
containerCssClass?: any;
dropdownCss?: any;
dropdownCssClass?: any;
escapeMarkup?: (markup: string) => string;
}
interface Select2JQueryEventObject extends JQueryEventObject {
val: any;
added: any;
removed: any;
}
interface JQuery {
off(events?: "change", selector?: any, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
on(events: "change", selector?: string, data?: any, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
on(events: "change", selector?: string, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
on(events: "change", handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
select2(): JQuery;
select2(it: IdTextPair): JQuery;
/**
* Get the id value of the current selection
*/
select2(method: 'val'): any;
/**
* Set the id value of the current selection
* @params value Value to set the id to
* @params triggerChange Should a change event be triggered
*/
select2(method: 'val', value: any, triggerChange?: boolean): any;
/**
* Get the data object of the current selection
*/
select2(method: 'data'): any;
/**
* Set the data of the current selection
* @params value Object to set the data to
* @params triggerChange Should a change event be triggered
*/
select2(method: 'data', value: any, triggerChange?: boolean): any;
/**
* Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved.
*/
select2(method: 'destroy'): JQuery;
/**
* Opens the dropdown
*/
select2(method: 'open'): JQuery;
/**
* Closes the dropdown
*/
select2(method: 'close'): JQuery;
/**
* Enables or disables Select2 and its underlying form component
* @param value True if it should be enabled false if it should be disabled
*/
select2(method: 'enable', value: boolean): JQuery;
/**
* Toggles readonly mode on Select2 and its underlying form component
* @param value True if it should be readonly false if it should be read write
*/
select2(method: 'readonly', value: boolean): JQuery;
/**
* Retrieves the main container element that wraps all of DOM added by Select2
*/
select2(method: 'container'): JQuery;
/**
* Notifies Select2 that a drag and drop sorting operation has started
*/
select2(method: 'onSortStart'): JQuery;
/**
* Notifies Select2 that a drag and drop sorting operation has finished
*/
select2(method: 'onSortEnd'): JQuery;
select2(method: string): any;
select2(method: string, value: any, trigger?: boolean): any;
select2(options: Select2Options): JQuery;
}
| {
"content_hash": "0a8c30f39ddfe5576d4d54e9b5d4a2ab",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 122,
"avg_line_length": 34.38926174496644,
"alnum_prop": 0.6598360655737705,
"repo_name": "kostat/ng-forms",
"id": "0f931e9efcd02238ba40879dfdec2f92cd34cb29",
"size": "5124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "forms/forms/Scripts/typings/select2/select2.d.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "95"
},
{
"name": "C#",
"bytes": "13182"
},
{
"name": "CSS",
"bytes": "82562"
},
{
"name": "JavaScript",
"bytes": "792840"
},
{
"name": "PowerShell",
"bytes": "111017"
},
{
"name": "Puppet",
"bytes": "132698"
},
{
"name": "TypeScript",
"bytes": "29646"
}
],
"symlink_target": ""
} |
@implementation DTAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
DTRootViewController *controller = [[DTRootViewController alloc] initWithStyle:UITableViewStylePlain];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
| {
"content_hash": "ba2a46e7d4f841f1f833a6b0c6f13b07",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 281,
"avg_line_length": 49.55555555555556,
"alnum_prop": 0.7878923766816144,
"repo_name": "diogot/DynamicsExamples",
"id": "da2e1d8a364010d1ee76740dfaade6e27f553535",
"size": "2447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DynamicsExamples/DTAppDelegate.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "23562"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace YoannBlot\Framework\Controller;
/**
* Class DefaultController.
*
* @package YoannBlot\Framework\Controller
* @author Yoann Blot
*
* @path("/default-controller/this-path-should-never-be-used/")
*/
class DefaultController extends AbstractController {
const NOT_FOUND = 'notFound';
/**
* @return array
*
* @path("(.*)")
*/
public function notFoundRoute () : array {
return [];
}
} | {
"content_hash": "a682eeb46e7d9c2b76b46a6cf0b1ba6b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 63,
"avg_line_length": 18.23076923076923,
"alnum_prop": 0.6286919831223629,
"repo_name": "yoannblot/houseFinder",
"id": "53541555352a21b6fe2ec5af90ea6c367806c90e",
"size": "474",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/YoannBlot/Framework/Controller/DefaultController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "32857"
},
{
"name": "PHP",
"bytes": "215982"
}
],
"symlink_target": ""
} |
EXTERN_C const GUID CLSID_CommandExecuteImpl;
// CommandExecuteImpl
// This class implements the IExecuteCommand and related interfaces for
// handling ShellExecute launches of the Chrome browser, i.e. whether to
// launch Chrome in metro mode or desktop mode.
// The CLSID here is a dummy CLSID not used for anything, since we register
// the class with a dynamic CLSID. However, a static CLSID is necessary
// so that we can force at least one entry into ATL's object map (it will
// treat a 0-element object map as an initialization failure case).
class ATL_NO_VTABLE DECLSPEC_UUID("071BB5F2-85A4-424F-BFE7-5F1609BE4C2C")
CommandExecuteImpl
: public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CommandExecuteImpl, &CLSID_CommandExecuteImpl>,
public IExecuteCommand,
public IObjectWithSiteImpl<CommandExecuteImpl>,
public IInitializeCommand,
public IObjectWithSelection,
public IExecuteCommandApplicationHostEnvironment,
public IForegroundTransfer {
public:
CommandExecuteImpl();
DECLARE_REGISTRY_RESOURCEID(IDR_COMMANDEXECUTEIMPL)
BEGIN_COM_MAP(CommandExecuteImpl)
COM_INTERFACE_ENTRY(IExecuteCommand)
COM_INTERFACE_ENTRY(IObjectWithSite)
COM_INTERFACE_ENTRY(IInitializeCommand)
COM_INTERFACE_ENTRY(IObjectWithSelection)
COM_INTERFACE_ENTRY(IExecuteCommandApplicationHostEnvironment)
COM_INTERFACE_ENTRY(IForegroundTransfer)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct() {
return S_OK;
}
void FinalRelease() {
}
public:
// IExecuteCommand
STDMETHOD(SetKeyState)(DWORD key_state);
STDMETHOD(SetParameters)(LPCWSTR params);
STDMETHOD(SetPosition)(POINT pt);
STDMETHOD(SetShowWindow)(int show);
STDMETHOD(SetNoShowUI)(BOOL no_show_ui);
STDMETHOD(SetDirectory)(LPCWSTR directory);
STDMETHOD(Execute)(void);
// IInitializeCommand
STDMETHOD(Initialize)(LPCWSTR name, IPropertyBag* bag);
// IObjectWithSelection
STDMETHOD(SetSelection)(IShellItemArray* item_array);
STDMETHOD(GetSelection)(REFIID riid, void** selection);
// IExecuteCommandApplicationHostEnvironment
STDMETHOD(GetValue)(enum AHE_TYPE* pahe);
// IForegroundTransfer
STDMETHOD(AllowForegroundTransfer)(void* reserved);
static bool FindChromeExe(base::FilePath* chrome_exe);
private:
static bool path_provider_initialized_;
bool GetLaunchScheme(base::string16* display_name, INTERNET_SCHEME* scheme);
HRESULT LaunchDesktopChrome();
// Returns the launch mode, i.e. desktop launch/metro launch, etc.
EC_HOST_UI_MODE GetLaunchMode();
CComPtr<IShellItemArray> item_array_;
base::CommandLine parameters_;
base::FilePath chrome_exe_;
STARTUPINFO start_info_;
base::string16 verb_;
base::string16 display_name_;
INTERNET_SCHEME launch_scheme_;
base::IntegrityLevel integrity_level_;
};
OBJECT_ENTRY_AUTO(__uuidof(CommandExecuteImpl), CommandExecuteImpl)
| {
"content_hash": "2dd5be1f93a2ce0205548769f24428b0",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 78,
"avg_line_length": 32.93258426966292,
"alnum_prop": 0.7659501876492665,
"repo_name": "fujunwei/chromium-crosswalk",
"id": "d2486d45ee393e07ab1e8edaa2b191e13ca52fff",
"size": "3396",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "win8/delegate_execute/command_execute_impl.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "23829"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "4116349"
},
{
"name": "C++",
"bytes": "233601977"
},
{
"name": "CSS",
"bytes": "931025"
},
{
"name": "Emacs Lisp",
"bytes": "988"
},
{
"name": "HTML",
"bytes": "28881204"
},
{
"name": "Java",
"bytes": "9824090"
},
{
"name": "JavaScript",
"bytes": "19683742"
},
{
"name": "Makefile",
"bytes": "68017"
},
{
"name": "Objective-C",
"bytes": "1478432"
},
{
"name": "Objective-C++",
"bytes": "8653645"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "171186"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "456460"
},
{
"name": "Python",
"bytes": "7963013"
},
{
"name": "Shell",
"bytes": "468673"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
<?php
/**
* @author MyBB Group
* @version 2.0.0
* @package mybb/core
* @license http://www.mybb.com/licenses/bsd3 BSD-3
*/
namespace MyBB\Core\Database\Repositories;
use Illuminate\Support\Collection;
use MyBB\Core\Database\Models\ProfileFieldGroup;
interface ProfileFieldGroupRepositoryInterface
{
/**
* @return Collection
*/
public function getAll() : Collection;
/**
* @param string $slug
*
* @return ProfileFieldGroup
*/
public function getBySlug(string $slug) : ProfileFieldGroup;
/**
* @return array
*/
public function getAllForSelectElement() : array;
/**
* @param array $data
*
* @return ProfileFieldGroup
*/
public function create(array $data) : ProfileFieldGroup;
}
| {
"content_hash": "194b29f7cc1b736475a674a90721357c",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 64,
"avg_line_length": 20.205128205128204,
"alnum_prop": 0.6383248730964467,
"repo_name": "Matslom/mybb2",
"id": "71324c1db2d2f18ed63609c43bbc010aeae67a5a",
"size": "788",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/Database/Repositories/ProfileFieldGroupRepositoryInterface.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "CSS",
"bytes": "465023"
},
{
"name": "HTML",
"bytes": "255157"
},
{
"name": "JavaScript",
"bytes": "624622"
},
{
"name": "PHP",
"bytes": "841459"
},
{
"name": "TypeScript",
"bytes": "4645"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace PomodoroKeeper.Common
{
public sealed class BooleanToVisibilityConverterReverse : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
bool bModel = (bool)value;
return bModel ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
| {
"content_hash": "87670e74c458e3028d2a7e4c7d127de7",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 93,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.7925,
"repo_name": "xinjiguaike/pomodoro-keeper",
"id": "f8ad7d44caa61e3dbddd4d0edf3e52243e052940",
"size": "802",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PomodoroKeeper/Common/BooleanToVisibilityConverterReverse.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "456365"
}
],
"symlink_target": ""
} |
import os
import yaml
from extended_uva_judge import errors
def get_problem_directory(app_config):
"""Gets the directory containing the problem configs.
:return: The path to the problem configs.
:rtype: str
"""
problem_directory = app_config['problem_directory']
if not problem_directory:
raise errors.MissingConfigEntryError('problem_directory')
# Check for full windows or *nix directory path
if not (problem_directory.startswith('/') or ':' in problem_directory):
# assume it's relative to the current working directory
problem_directory = os.path.join(os.getcwd(), problem_directory)
return problem_directory
def get_problem_config(app_config, problem_id):
"""Gets the configuration for this objects corresponding problem.
:return: The configuration for the users selected problem
:rtype: dict
"""
problem_directory = get_problem_directory(app_config)
problem_config_path = os.path.join(
problem_directory, '%s.yaml' % problem_id)
problem_config = yaml.load(open(problem_config_path))
return problem_config
def does_problem_config_exist(app_config, problem_id):
"""Checks to see if the problem configuration exists in the system.
:return: True if it exists, false otherwise
:rtype: bool
"""
problem_directory = get_problem_directory(app_config)
problem_config_path = os.path.join(
problem_directory, '%s.yaml' % problem_id)
return os.path.exists(problem_config_path)
| {
"content_hash": "7fa451574e9dcc35fc3a8bd88405d54e",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 75,
"avg_line_length": 29.862745098039216,
"alnum_prop": 0.6999343401181878,
"repo_name": "fritogotlayed/Extended-UVA-Judge",
"id": "899e62389d7e3e73d0a9cac9e6a927bac137f515",
"size": "1523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "extended_uva_judge/utilities.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "802"
},
{
"name": "Python",
"bytes": "34882"
}
],
"symlink_target": ""
} |
#include "sky/engine/config.h"
#include "sky/engine/core/css/SelectorChecker.h"
#include "sky/engine/core/css/CSSSelector.h"
#include "sky/engine/core/css/CSSSelectorList.h"
#include "sky/engine/core/dom/Document.h"
#include "sky/engine/core/dom/shadow/ShadowRoot.h"
#include "sky/engine/core/editing/FrameSelection.h"
#include "sky/engine/core/frame/LocalFrame.h"
#include "sky/engine/core/html/parser/HTMLParserIdioms.h"
#include "sky/engine/core/page/FocusController.h"
#include "sky/engine/core/rendering/style/RenderStyle.h"
namespace blink {
static bool matchesFocusPseudoClass(const Element& element)
{
if (!element.focused())
return false;
LocalFrame* frame = element.document().frame();
if (!frame)
return false;
if (!frame->selection().isFocusedAndActive())
return false;
return true;
}
SelectorChecker::SelectorChecker(const Element& element)
: m_element(element)
, m_matchedAttributeSelector(false)
, m_matchedFocusSelector(false)
, m_matchedHoverSelector(false)
, m_matchedActiveSelector(false)
{
}
bool SelectorChecker::match(const CSSSelector& selector)
{
const CSSSelector* current = &selector;
do {
if (!checkOne(*current))
return false;
current = current->tagHistory();
} while (current);
return true;
}
static bool anyAttributeMatches(const Element& element, CSSSelector::Match match, const CSSSelector& selector)
{
const QualifiedName& selectorAttr = selector.attribute();
ASSERT(selectorAttr.localName() != starAtom); // Should not be possible from the CSS grammar.
if (match == CSSSelector::Set)
return element.hasAttribute(selectorAttr);
ASSERT(match == CSSSelector::Exact);
const AtomicString& selectorValue = selector.value();
const AtomicString& value = element.getAttribute(selectorAttr);
if (value.isNull())
return false;
if (selector.attributeMatchType() == CSSSelector::CaseInsensitive)
return equalIgnoringCase(selectorValue, value);
return selectorValue == value;
}
bool SelectorChecker::checkOne(const CSSSelector& selector)
{
switch (selector.match()) {
case CSSSelector::Tag:
{
const AtomicString& localName = selector.tagQName().localName();
return localName == starAtom || localName == m_element.localName();
}
case CSSSelector::Class:
return m_element.hasClass() && m_element.classNames().contains(selector.value());
case CSSSelector::Id:
return m_element.hasID() && m_element.idForStyleResolution() == selector.value();
case CSSSelector::Exact:
case CSSSelector::Set:
if (anyAttributeMatches(m_element, selector.match(), selector)) {
m_matchedAttributeSelector = true;
return true;
}
return false;
case CSSSelector::PseudoClass:
return checkPseudoClass(selector);
// FIXME(sky): Remove pseudo elements completely.
case CSSSelector::PseudoElement:
case CSSSelector::Unknown:
return false;
}
ASSERT_NOT_REACHED();
return false;
}
bool SelectorChecker::checkPseudoClass(const CSSSelector& selector)
{
switch (selector.pseudoType()) {
case CSSSelector::PseudoFocus:
m_matchedFocusSelector = true;
return matchesFocusPseudoClass(m_element);
case CSSSelector::PseudoHover:
m_matchedHoverSelector = true;
return m_element.hovered();
case CSSSelector::PseudoActive:
m_matchedActiveSelector = true;
return m_element.active();
case CSSSelector::PseudoLang:
{
AtomicString value = m_element.computeInheritedLanguage();
const AtomicString& argument = selector.argument();
if (value.isEmpty() || !value.startsWith(argument, false))
break;
if (value.length() != argument.length() && value[argument.length()] != '-')
break;
return true;
}
case CSSSelector::PseudoHost:
{
// We can only get here if the selector was defined in the right
// scope so we don't need to check it.
// For empty parameter case, i.e. just :host or :host().
if (!selector.selectorList())
return true;
for (const CSSSelector* current = selector.selectorList()->first(); current; current = CSSSelectorList::next(*current)) {
if (match(*current))
return true;
}
return false;
}
case CSSSelector::PseudoUnknown:
case CSSSelector::PseudoNotParsed:
case CSSSelector::PseudoUserAgentCustomElement:
return false;
}
ASSERT_NOT_REACHED();
return false;
}
}
| {
"content_hash": "cb302f94bacb938d707408a5cb840bf6",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 133,
"avg_line_length": 31.394736842105264,
"alnum_prop": 0.654233025984912,
"repo_name": "collinjackson/mojo",
"id": "9fc4a49987465e9cb3feef25d268563bd01d559a",
"size": "6187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sky/engine/core/css/SelectorChecker.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Bison",
"bytes": "31162"
},
{
"name": "C",
"bytes": "1870198"
},
{
"name": "C++",
"bytes": "36473977"
},
{
"name": "CSS",
"bytes": "1897"
},
{
"name": "Dart",
"bytes": "508640"
},
{
"name": "Go",
"bytes": "181090"
},
{
"name": "Groff",
"bytes": "29030"
},
{
"name": "HTML",
"bytes": "6258864"
},
{
"name": "Java",
"bytes": "1187123"
},
{
"name": "JavaScript",
"bytes": "204155"
},
{
"name": "Makefile",
"bytes": "402"
},
{
"name": "Objective-C",
"bytes": "74603"
},
{
"name": "Objective-C++",
"bytes": "370763"
},
{
"name": "Protocol Buffer",
"bytes": "1048"
},
{
"name": "Python",
"bytes": "5515876"
},
{
"name": "Shell",
"bytes": "143302"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.