code stringlengths 2 1.05M |
|---|
(function(){
'use strict';
angular.module('demoApp')
.controller('friendlyrangeCtrl', ['$scope', 'moment', function($scope, moment){
$scope.myBlock = { start: moment().startOf('month'), end: moment().add(1,'month').startOf('month') };
$scope.form = { start: moment().startOf('month') };
$scope.until = { end: moment().startOf('month') };
}]);
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:c08e3f6f37a8467e83864dadaec374ce4d76d2c5a5da66de337312c3ba893ccf
size 1546
|
/**
* DevExtreme (viz/tree_map/tree_map.js)
* Version: 16.2.5
* Build date: Mon Feb 27 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var dxTreeMap = module.exports = require("./tree_map.base");
require("./tiling.squarified");
require("./tiling.strip");
require("./tiling.slice_and_dice");
require("./colorizing.discrete");
require("./colorizing.gradient");
require("./colorizing.range");
require("./api");
require("./hover");
require("./selection");
require("./tooltip");
require("./tracker");
require("./drilldown");
require("./plain_data_source");
dxTreeMap.addPlugin(require("../core/export").plugin);
dxTreeMap.addPlugin(require("../core/title").plugin);
dxTreeMap.addPlugin(require("../core/loading_indicator").plugin);
|
angular.module("QuestionRest", ['ngResource'])
.factory("question", function ( $resource) {
var apiData = $resource(
"/api", {},
{
"postQuestion" : { method: "POST", url: "/api/readQuestion/:containid/:userid/:typeid/Questions"}
});
return {
postQuestion: function(question, contain_id, user_id, type_id) {
apiData.postQuestion(question, {containid: contain_id, userid: user_id, typeid: type_id}, function() {
console.log("Success !");
}, function(error) {
console.log("Error " + error.status + " when sending request : " + error.data);
});
}
}
}); |
(function() {
'use strict';
/**
* @ngdoc service
* @name AppTechnologiesService
* @module <%- props.appName %>
* @description
*
* AppTechnologies Service
*/
angular
.module('<%- props.appName %>')
.service('AppTechnologiesService', AppTechnologiesService);
AppTechnologiesService.$inject = [];
/* @ngInject */
function AppTechnologiesService() {
var service = {
getTechs: getTechs,
getSIITechs: getSIITechs
};
return service;
////////////////
/**
* @ngdoc method
* @name AppTechnologiesService#getTechs
* @return {array} Array of technologies
* @description Return an array of technologies
*/
function getTechs() {
return <%- technologies %>;
}
function getSIITechs() {
return <%- siiTechnologies %>;
}
}
})();
|
/// <reference path="../../typings/functions.d.ts" />
import {xtract_assert_array} from "./xtract_assert_array";
import {xtract_lowhigh} from "./xtract_lowhigh";
export function xtract_lowest_value(data, threshold) {
if (!xtract_assert_array(data))
return 0;
if (typeof threshold !== "number") {
threshold = -Infinity;
}
return xtract_lowhigh(data, threshold).min;
}
|
(function (factory) {
if (typeof define === "function" && define.amd) {
define(["jquery"], factory);
} else if (typeof module === "object" && module.exports) {
module.exports = factory(require(["jquery"]));
} else {
factory(jQuery);
}
}(function ($) {
"use strict";
window.Locate = function (options) {
this.options = $.extend({}, {
countryId: 'country',
regionId: 'region',
cityId: 'city',
countyId: 'county',
prefix: '',
url: GLOBAL.BASE_URL + 'i18n/locate/'
}, options);
this.init.apply(this);
};
Locate.prototype.appendOptions = function (target, response, param) {
if (window.localStorage && !localStorage['locate-' + GLOBAL.LOCALE + param]) {
localStorage['locate-' + GLOBAL.LOCALE + param] = JSON.stringify(response);
}
var options = typeof response === 'string' ? eval('(' + response + ')') : response;
var flag = options.length;
for (var i in this.objects) {
if (i === target) {
break;
}
if ($(this.objects[i]).is(':disabled')) {
flag = false;
break;
}
}
if (flag) {
$(this.objects[target + '-text']).attr({hidden: 'hidden', disabled: 'disabled'});
target = this.objects[target];
$(target).removeAttr('hidden').removeAttr('disabled');
var fg = document.createDocumentFragment();
$(fg).append('<option value=""></option>');
var value = $(target).data('default-value');
for (var i in options) {
var oo = document.createElement('option');
$(oo).attr('value', options[i].value).text(options[i].label);
if (value && value == options[i].value) {
$(oo).attr('selected', 'selected');
}
$(fg).append(oo);
}
$(target).html(fg);
} else {
$(this.objects[target + '-text']).removeAttr('hidden').removeAttr('disabled');
$(this.objects[target]).attr({hidden: 'hidden', disabled: 'disabled'});
switch (target) {
case 'region':
$(this.objects['city-text']).removeAttr('hidden').removeAttr('disabled');
$(this.objects['city']).attr({hidden: 'hidden', disabled: 'disabled'});
case 'city':
$(this.objects['county-text']).removeAttr('hidden').removeAttr('disabled');
$(this.objects['county']).attr({hidden: 'hidden', disabled: 'disabled'});
}
}
};
Locate.prototype.loadData = function (target, param) {
var o = this;
if (window.localStorage && localStorage['locate-' + GLOBAL.LOCALE + param]) {
o.appendOptions(target, localStorage['locate-' + GLOBAL.LOCALE + param], param);
} else {
$.get(o.options.url, param).success(function (response) {
o.appendOptions(target, response, param);
});
}
};
Locate.prototype.objects = {};
Locate.prototype.options = {};
Locate.prototype.loadDefault = function () {
if ($(this.objects.country).is('select')) {
this.loadData('country', '');
var country = $(this.objects.country).data('default-value');
} else {
var country = $(this.objects.country).val();
}
if (country) {
var param = 'region=' + country;
this.loadData('region', param);
}
var region = $(this.objects.region).data('default-value');
if (region) {
var param = 'city=' + region;
this.loadData('city', param);
}
var city = $(this.objects.city).data('default-value')
if (city) {
var param = 'county=' + city;
this.loadData('county', param);
}
};
Locate.prototype.init = function () {
var o = this;
o.objects = {
country: $('#' + o.options.prefix + o.options.countryId),
region: $('#' + o.options.prefix + o.options.regionId),
city: $('#' + o.options.prefix + o.options.cityId),
county: $('#' + o.options.prefix + o.options.countyId),
'country-text': $('#' + o.options.prefix + o.options.countryId + '-text'),
'region-text': $('#' + o.options.prefix + o.options.regionId + '-text'),
'city-text': $('#' + o.options.prefix + o.options.cityId + '-text'),
'county-text': $('#' + o.options.prefix + o.options.countyId + '-text')
};
o.loadDefault();
$(o.objects.country).on('change.seahinet', function () {
var v = $(this).val();
if (v) {
var param = 'region=' + v;
o.loadData('region', param);
$(o.objects.region).trigger('change.seahinet');
} else {
$(o.objects['region-text']).removeAttr('hidden').removeAttr('disabled');
$(o.objects['region']).attr({hidden: 'hidden', disabled: 'disabled'});
$(o.objects['city-text']).removeAttr('hidden').removeAttr('disabled');
$(o.objects['city']).attr({hidden: 'hidden', disabled: 'disabled'});
$(o.objects['county-text']).removeAttr('hidden').removeAttr('disabled');
$(o.objects['county']).attr({hidden: 'hidden', disabled: 'disabled'});
}
});
$(o.objects.region).on('change.seahinet', function () {
var v = $(this).val();
if (v) {
var param = 'city=' + v;
o.loadData('city', param);
$(o.objects.city).trigger('change.seahinet');
} else {
$(o.objects['city-text']).removeAttr('hidden').removeAttr('disabled');
$(o.objects['city']).attr({hidden: 'hidden', disabled: 'disabled'});
$(o.objects['county-text']).removeAttr('hidden').removeAttr('disabled');
$(o.objects['county']).attr({hidden: 'hidden', disabled: 'disabled'});
}
});
$(o.objects.city).on('change.seahinet', function () {
var v = $(this).val();
if (v) {
var param = 'county=' + v;
o.loadData('county', param);
$(o.objects.county).trigger('change.seahinet');
} else {
$(o.objects['county-text']).removeAttr('hidden').removeAttr('disabled');
$(o.objects['county']).attr({hidden: 'hidden', disabled: 'disabled'});
}
});
};
})); |
'use strict'
const Joi = require('joi')
const network = require('../../services/network')
const output = require('../../utils/output')
const networks = require('../../config/networks')
var workerpool = require('workerpool')
const schema = {
vanity: Joi.string().required()
}
function __createVanityAddress (netVersion, vanity) {
const bip39 = require('bip39')
const arkecosystem = require('@arkecosystem/crypto')
const arkCrypto = arkecosystem.crypto
let passphrase
let publicKey
let address = ''
while (address.toLowerCase().indexOf(vanity) === -1) {
passphrase = bip39.generateMnemonic()
publicKey = arkCrypto.getKeys(passphrase).publicKey
address = arkCrypto.getAddress(publicKey, netVersion)
}
return { passphrase, address, publicKey }
}
/**
* @dev Create a new wallet containing lowercase <vanity>.
* @param {object} cmd A JSON object containing the options for this query (network, format, vanity).
*/
module.exports = async (cmd) => {
let net = cmd.network ? cmd.network : 'mainnet'
let format = cmd.format ? cmd.format : 'json'
try {
output.setFormat(format)
// Validate input
const vanity = cmd.vanity.toLowerCase().trim()
Joi.validate({
vanity
}, schema, (err) => {
if (err) {
throw new Error(err) // TDOD make error messages more userfriendly
}
})
// Configure network
if (!networks[net]) {
throw new Error(`Unknown network: ${net}`)
}
await network.setNetwork(net)
// Create the wallet
const pool = workerpool.pool()
const {passphrase, address, publicKey} = await pool.exec(__createVanityAddress, [network.network.version, vanity])
pool.terminate()
const result = {
address,
publicKey,
passphrase
}
output.setTitle('ARK Create wallet')
output.showOutput(result)
} catch (error) {
output.showError(error.message)
process.exitCode = 1
}
}
|
module.exports = function() {
let y = 3.14;
let x;
if(!(y === 0)) {
x = 1;
}
}; |
define([
"xEvolution/models/Entity/HungerableEntity"
],function(
HungerableEntity
){
var model = HungerableEntity.extend({
_urlRoot: "",
defaults: {
speed: 5,
movementSpeed: 2,
pdx: -1,
pdy: -1
},
initialize: function(properties,options){
this.listenTo(this.board,'tick',this.move);
},
getMoveLocation: function(){
var pdx = Number(this.get('pdx'));
var pdy = Number(this.get('pdy'));
var dx = Math.floor(Math.random()*3)-1;
var dy = Math.floor(Math.random()*3)-1;
var x = Number(this.get('x'));
var y = Number(this.get('y'));
var hunger = Number(this.get('hunger'));
var maxHunger = Number(this.get('maxHunger'));
var moveSpeed = Number(this.get('movementSpeed'));
var speed = hunger>=maxHunger ? moveSpeed/2 : moveSpeed;
var newLocation = {
x: x+(dx*speed),
y: y+(dy*speed)
};
if(this.board.isValidLocation(newLocation)){
return newLocation;
}else{
return this.getMoveLocation();
}
},
move: function(){
if(!this.get('dead')){
var newPosition = this.getMoveLocation();
this.set(newPosition);
}
}
});
return model;
}); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
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 _transport = require('./transport');
var _transport2 = _interopRequireDefault(_transport);
var _prefix = require('./prefix');
var _prefix2 = _interopRequireDefault(_prefix);
var _graphPattern = require('./graph-pattern');
var _graphPattern2 = _interopRequireDefault(_graphPattern);
var _groupGraphPattern = require('./group-graph-pattern');
var _groupGraphPattern2 = _interopRequireDefault(_groupGraphPattern);
var _queryTypes = require('./query-types');
var QueryTypes = _interopRequireWildcard(_queryTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
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"); } }
var Query = function () {
/**
* The Query is the root object for all SPARQL requests
*
* @class Query
* @constructor
* @param {String} endpoint - URL of the SPARQL endpoint
* @param {Object} auth - Optional authentication object (e.g.: { basic: { username: <USER>, password: <PASS> } })
* @param {String} method - HTTP method used (default: 'GET')
*/
function Query(endpoint) {
var auth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var method = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'GET';
_classCallCheck(this, Query);
this.reset();
this._transport = new _transport2.default(endpoint, auth, method);
}
/**
* Sets the base IRI
*
* @method base
* @param {String} content - BASE string
*/
_createClass(Query, [{
key: 'base',
value: function base(content) {
this._config.base = content;
}
/**
* Sets the prefix(es) for the query
*
* @method prefix
* @param {Prefix|String|Array} content - A single Prefix string or object or an array of Prefix objects or strings
* @param {Object} context - The context to be executed on (default: this)
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'prefix',
value: function prefix(content) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
this.addArrayOrSingle(content, this.addPrefix, context);
return context;
}
/**
* Add a prefix to the query
*
* @method addPrefix
* @param {Prefix|String|Array} content - A single Prefix string or object
* @param {Object} context - The context to be executed on (default: this)
*/
}, {
key: 'addPrefix',
value: function addPrefix(content) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
if (content instanceof _prefix2.default) {
context._config.prefixes.push(content);
} else if (typeof content === 'string') {
context._config.prefixes.push(new _prefix2.default(content));
}
}
/**
* Get the Prefix objects of the Query
*
* @method getPrefixes
* @returns {Array}
*/
}, {
key: 'getPrefixes',
value: function getPrefixes() {
return this._config.prefixes;
}
/**
* Remove all Prefixes from the Query
*
* @method clearPrefixes
*/
}, {
key: 'clearPrefixes',
value: function clearPrefixes() {
this._config.prefixes = [];
}
/**
* Set the current query to SELECT
*
* @method select
* @param {String} content - Arguments given to the SELECT statement
* @param {String} modifier - Optional modifier to be added (e.g. DISTINCT)
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'select',
value: function select(content, modifier) {
this._config.query = new QueryTypes.Select(content, modifier);
return this;
}
/**
* Set the current query to DESCRIBE
*
* @method describe
* @param {String} content - Arguments given to the DESCRIBE statement
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'describe',
value: function describe(content) {
this._config.query = new QueryTypes.Describe(content);
return this;
}
/**
* Set the current query to ASK
*
* @method ask
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'ask',
value: function ask() {
this._config.query = new QueryTypes.Ask();
return this;
}
/**
* Set the current query to CONSTRUCT
*
* @method construct
* @param {Triple|Array} triples - One or more Triples to be used for a DESCRIBE GraphPattern
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'construct',
value: function construct(triples) {
this._config.query = new QueryTypes.Construct(triples);
return this;
}
/**
* Set dataset clause
*
* @method from
* @param {String|Array} content - One or more strings with dataset clauses (without FROM or NAMED)
* @param {Boolean} named - Optional flag to set clause to NAMED
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'from',
value: function from(content) {
var _this = this;
var named = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.addArrayOrSingle(content, function (element) {
_this._config.datasetClause.push('FROM' + (named ? ' NAMED' : '') + ' ' + element);
});
return this;
}
/**
* Get current dataset clauses
*
* @method getDatasetClauses
* @returns {Array}
*/
}, {
key: 'getDatasetClauses',
value: function getDatasetClauses() {
return this._config.datasetClause;
}
/**
* Clear current dataset clauses
*
* @method clearDatasetClauses
*/
}, {
key: 'clearDatasetClauses',
value: function clearDatasetClauses() {
this._config.datasetClause = [];
}
/**
* Set where clause
*
* @method where
* @param {String|Array} content - A GraphPattern or a GroupGraphPattern object
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'where',
value: function where(content) {
if (content instanceof _graphPattern2.default || content instanceof _groupGraphPattern2.default) {
this._config.whereClause = content;
} else {
throw new Error('TypeError: Where clause must be a graph pattern.');
}
return this;
}
/**
* Get current where clause
*
* @method getWhereClause
* @returns {GraphPattern|GroupGraphPattern}
*/
}, {
key: 'getWhereClause',
value: function getWhereClause() {
return this._config.whereClause;
}
/**
* Set order for query
*
* @method order
* @param {String} content - Order string without ORDER BY
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'order',
value: function order(content) {
if (typeof content === 'string') {
this._config.solutionModifiers.push('ORDER BY ' + content);
} else {
throw new Error('Input for ORDER must be string but is ' + (typeof content === 'undefined' ? 'undefined' : _typeof(content)) + '.');
}
return this;
}
/**
* Set limit for query
*
* @method limit
* @param {Number} count - Limit count
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'limit',
value: function limit(count) {
if (typeof count === 'number') {
this._config.solutionModifiers.push('LIMIT ' + count);
} else {
throw new Error('Input for LIMIT must be number but is ' + (typeof count === 'undefined' ? 'undefined' : _typeof(count)) + '.');
}
return this;
}
/**
* Set limit for offset
*
* @method offset
* @param {Number} count - Offset count
* @returns {Query} - Returns current instance (chainable)
*/
}, {
key: 'offset',
value: function offset(count) {
if (typeof count === 'number') {
this._config.solutionModifiers.push('OFFSET ' + count);
} else {
throw new Error('Input for OFFSET must be number but is ' + (typeof count === 'undefined' ? 'undefined' : _typeof(count)) + '.');
}
return this;
}
/**
* Execute query
*
* @method exec
* @returns {Promise} - Returns a Promise with will yield a Result object
*/
}, {
key: 'exec',
value: function exec() {
return this._transport.submit(this.toString());
}
/**
* Retrieves the SPARQL string representation of the current instance, adding the FILTER keyword.
*
* @method toString
* @param {Boolean} isSubquery - If set, skips the BASE and PREFIX parts for inclusion as a subquery
* @returns {String}
*/
}, {
key: 'toString',
value: function toString() {
var isSubQuery = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var queryString = '';
if (!isSubQuery) {
if (this._config.base) {
queryString += 'BASE ' + this._config.base;
}
if (this._config.prefixes.length > 0) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this._config.prefixes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var prefix = _step.value;
queryString += prefix.toString() + ' ';
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}
if (this._config.query) {
queryString += this._config.query.toString();
} else {
throw new Error('TypeError: Query type must be defined.');
}
if (Array.isArray(this._config.datasetClause)) {
queryString += this._config.datasetClause.join(' ') + ' ';
} else {
throw new Error('TypeError: Dataset clause should be array but is ' + _typeof(this._config.datasetClause));
}
if (this._config.whereClause) {
queryString += 'WHERE ' + this._config.whereClause.toString();
} else {
throw new Error('TypeError: Where clause is not defined!');
}
if (Array.isArray(this._config.solutionModifiers)) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this._config.solutionModifiers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var mod = _step2.value;
queryString += ' ' + mod.toString();
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
return queryString;
}
/**
* Reset query (endpoint setting stays)
*
* @method reset
*/
}, {
key: 'reset',
value: function reset() {
this._config = {
base: null,
prefixes: [],
query: null,
subQueries: [],
datasetClause: [],
whereClause: null,
solutionModifiers: []
};
}
}, {
key: 'addArrayOrSingle',
value: function addArrayOrSingle(content, addFunction) {
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this;
if (Array.isArray(content)) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = content[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var element = _step3.value;
addFunction(element, context);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
} else {
addFunction(content, context);
}
}
}]);
return Query;
}();
exports.default = Query; |
import { INTEGRITY_TYPES } from 'constants/pogues-constants';
import Dictionary from 'utils/dictionary/dictionary';
function checkerExistingTarget({
appState: {
activeComponentsById,
activeQuestionnaire: { id },
},
}) {
const targetNotFoundErrors = [];
const errors = [];
Object.keys(activeComponentsById).forEach(key => {
const redirections = activeComponentsById[key].redirections || {};
if (Object.values(redirections).length > 0) {
Object.values(redirections).forEach(redir => {
if (redir.cible && !activeComponentsById[redir.cible]) {
targetNotFoundErrors.push(redir.label);
}
});
}
});
if (targetNotFoundErrors.length > 0) {
errors.push({
message: `${Dictionary.notExistingTarget} ${targetNotFoundErrors.join(
',',
)}`,
});
}
return {
[id]: {
[INTEGRITY_TYPES.NOT_EXISTING_TARGET]: errors,
},
};
}
export default checkerExistingTarget;
|
module.exports = function(environment, path) {
environment
.use(['qunit'])
.add('sampleLib.js', path.jasmine)
.add(path.jasmine('anotherLib.js'));
};
|
import {
createSelectorCreator,
createStructuredSelector,
defaultMemoize,
} from 'reselect';
import * as R from 'ramda';
import { debug } from './Messages';
const customComparator = (previousState, state) => {
const equals = R.equals(previousState, state);
if (!equals) debug('Reselect', 'Redisplay the react component');
return equals;
};
// eslint-disable-next-line import/prefer-default-export
export const equalsSelector = (s) => createStructuredSelector(
s,
createSelectorCreator(defaultMemoize, customComparator),
);
|
/* RwGet */
if (typeof RwGet == 'undefined') RwGet = { pathto: function(path, file) { var rtrim = function(str, list) { var charlist = !list ? 's\xA0': (list + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1'); var re = new RegExp('[' + charlist + ']+$', 'g'); return (str + '').replace(re, ''); }; var jspathto = rtrim(RwSet.pathto, "javascript.js"); if ((path !== undefined) && (file !== undefined)) { jspathto = jspathto + path + file; } else if (path !== undefined) { jspathto = jspathto + path; } return jspathto; }, baseurl: function(path, file) { var jsbaseurl = RwSet.baseurl; if ((path !== undefined) && (file !== undefined)) { jsbaseurl = jsbaseurl + path + file; } else if (path !== undefined) { jsbaseurl = jsbaseurl + path; } return jsbaseurl; } };/* @end */
/* rwAddLinks v1.0.0 */
if (typeof rwAddLinks == 'undefined') (function($) { $.fn.rwAddLinks = function(linkArr) { var i = 0; $(this).each(function(i) { $(this).click(function() { location.href = linkArr[i++]; }).hover(function() { $(this).css("cursor", "pointer"); }); }); }; })(jQuery); /* @end */
/* sdSetHeight 1.1.0 */
if (typeof sdSetHeight == 'undefined') (function($) { $.fn.sdSetHeight = function(elem, value) { sdTallest = 0; $(elem).each(function() { var thisTallest = $(this).outerHeight(true); if (thisTallest > sdTallest) sdTallest = thisTallest; }); $(this).height(sdTallest + value); }; })(jQuery); /* @end */
// initiate sdSS object
sdSS = {};
/* SeydoggySlideshow 3.1.4 */
(function($) {
$.SeydoggySlideshow = function(settings) {
// DEVELOPER SETTINGS
sdSS.wrapper = '.headerContainer',
sdSS.target = '.seydoggySlideshow',
sdSS.ecValue = 1,
sdSS.imgType = 'jpg',
sdSS.bgPosition = 'center top',
sdSS.bgRepeat = 'repeat',
sdSS.widthAdjust = 29,
sdSS.heightAdjust = 30,
sdSS.plusClass = '';
// check for options
if (settings) $.extend(sdSS, settings);
// VARIABLES
var jq = $([]),
arrlen = '',
i = 0,
isVariable = typeof sdSS.headerHeightVariable != 'undefined',
hContainer = jq.add('div' + sdSS.wrapper),
sdSlideshow = hContainer.find('div' + sdSS.target),
pageHeader = sdSlideshow.find('div.pageHeader'),
sdSlidePager = '',
slideHeader = sdSlideshow.add(pageHeader),
ec1 = hContainer.find('div#extraContainer' + sdSS.ecValue),
preContent = ec1.parent('div.preContent'),
myEC = hContainer.find('div#myExtraContent' + sdSS.ecValue),
sdContentSlide = jq.add('div.sdSlideBoxStack'),
sdContentIndex = 0,
headerWidth = sdSlideshow.width(),
headerHeight = pageHeader.css('height'),
nextClass = '',
prevClass = '',
plusClass = 0;
// set plusClass
sdSS.plusClass != '' ? plusClass = ' ' + sdSS.plusClass : plusClass = '';
// if SlideBox Stacks is not found, use SlideBox Snippet
if (!sdContentSlide.length) sdContentSlide = jq.add('div.sdSlideBoxSnippet'), sdContentIndex = 1;
// EXTRACONTENT AREA 1
// if the first ExtraContent hasn't yet been propogated
if (!myEC.length) {
myEC = jq.add('div#myExtraContent' + sdSS.ecValue);
if (myEC.length) {
myEC.find('script').remove().end().appendTo(ec1).show();
// !hide !empty ExtraContent area
ec1.show().width(headerWidth - sdSS.widthAdjust).css('z-index', '100');
preContent.show();
// if header height is variable set .seydoggySlideshow height to content height
if (isVariable) slideHeader.sdSetHeight(ec1.find('div'), sdSS.heightAdjust);
}
}
// if Slideshow is enabled in some form
if ((typeof sdSS.slideNum != "undefined") || (typeof sdSS.slideWH != "undefined")) {
// SETUP SLIDES
// if SlideBox option is used
if (typeof sdSS.slideBox != "undefined") {
// SETUP BOX SLIDES
// VARIABLES
sdSS.slideNum = [];
// determine stack or snippet
if (sdContentSlide.length) {
sdContentSlide.each(function(i) {
sdSS.slideNum[i++] = (sdContentSlide.index(this)) + sdContentIndex;
});
}
// set array length
arrlen = sdSS.slideNum.length;
// transfer header styles to parent div
sdSlideshow.css({
'background-image': pageHeader.css('background-image'),
'background-position-x': pageHeader.css('background-position-x'),
'background-position-y': pageHeader.css('background-position-y'),
'background-color': pageHeader.css('background-color'),
'background-size': pageHeader.css('background-size'),
'height' : pageHeader.css('height')
});
// clean up what's there
pageHeader.add(ec1).remove();
// add box slides to slideshow
for (i; i < arrlen; ++i) {
sdSlideshow.append('<div class="pageHeader' + plusClass + '" id="sdSlideBox' + sdSS.slideNum[i] + '" style="background: transparent; width:' + headerWidth + 'px;"/>');
jq.add('div#mySdSlideBox' + sdSS.slideNum[i]).appendTo('div#sdSlideBox' + sdSS.slideNum[i]).show();
}
// if header height is variable set .seydoggySlideshow height to content height
if (isVariable) sdSlideshow.sdSetHeight(sdContentSlide, 0);
} else {
// else if standard slides/snippets are used
// SET UP IMAGE SLIDES
// clean up what's there
pageHeader.remove();
if (typeof sdSS.slideWH != "undefined") {
// WAREHOUSE
arrlen = sdSS.slideWH.length;
for (i; i < arrlen; ++i) {
sdSlideshow.append('<div class="pageHeader' + plusClass + '" style="background: url(' + sdSS.slideWH[i] + ') ' + sdSS.bgPosition + ' ' + sdSS.bgRepeat + '; width:' + headerWidth + 'px;"/>');
}
} else {
// LOCAL
arrlen = sdSS.slideNum.length;
for (i; i < arrlen; ++i) {
sdSlideshow.append('<div class="pageHeader' + plusClass + '" style="background: url(' + RwGet.pathto('images/editable_images/header' + sdSS.slideNum[i] + '.' + sdSS.imgType) + ') ' + sdSS.bgPosition + ' ' + sdSS.bgRepeat + '; width:' + headerWidth + 'px;"/>');
}
}
}
// SLIDESHOW SETTINGS
// if navigation is selected
if (sdSS.navigation == true) {
// create navigation elements
sdSlideshow.append('<div class="sdSlideNav"><a class="prev" href="#">‹</a><a class="next" href="#">›</a></div>');
nextClass = '.sdSlideNav .next', prevClass = '.sdSlideNav .prev';
// if slidebox is not in use
if (typeof sdSS.slideBox == 'undefined') {
// make extracontent 1 smaller on each side
var navWidth = jq.add('div.sdSlideNav a.prev, div.sdSlideNav a.next').outerWidth(true);
ec1.width(ec1.width() - (navWidth * 2)).css('margin-left', navWidth);
// (again) if header height is variable set .seydoggySlideshow height to content height
if (isVariable) slideHeader.sdSetHeight(ec1.find('div'), sdSS.heightAdjust);
}
}
// if pager is selected set pager classes
if (sdSS.pager != undefined) sdSlideshow.append('<div class="sdSlidePager"/>'), sdSlidePager = sdSlideshow.find('div.sdSlidePager');
// START THE SLIDESHOW
sdSlideshow.cycle({
autostop: sdSS.autostop,
fx: sdSS.effect,
next: nextClass,
pager: sdSS.pager,
pagerEvent: 'mouseover',
pause: sdSS.pause,
pauseOnPagerHover: true,
prev: prevClass,
random: sdSS.random,
randomizeEffects: true,
slideExpr: '.pageHeader',
speed: sdSS.speed,
timeout: sdSS.timeout
});
// PAGINATION
// if pagination is active, dynamically set pagination values
if (sdSlidePager.html()) {
sdSlidePager.find('a').html('·');
sdSlidePager.css('margin-left',(sdSlidePager.width()/2)*(-1));
}
}
// SLIDE LINKS
// add links to slides
if (typeof sdSS.slideLinks != "undefined") sdSlideshow.find('div.pageHeader').rwAddLinks(sdSS.slideLinks);
}
})(jQuery); |
const express = require('express');
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const urlencoded = require('body-parser').urlencoded;
// Update with your own phone number in E.164 format
const MODERATOR = '+15558675309';
const app = express();
// Parse incoming POST params with Express middleware
app.use(urlencoded({ extended: false }));
// Create a route that will handle Twilio webhook requests, sent as an
// HTTP POST to /voice in our application
app.post('/voice', (request, response) => {
// Use the Twilio Node.js SDK to build an XML response
const twiml = new VoiceResponse();
// Start with a <Dial> verb
const dial = twiml.dial();
// If the caller is our MODERATOR, then start the conference when they
// join and end the conference when they leave
if (request.body.From == MODERATOR) {
dial.conference('My conference', {
startConferenceOnEnter: true,
endConferenceOnExit: true,
});
} else {
// Otherwise have the caller join as a regular participant
dial.conference('My conference', {
startConferenceOnEnter: false,
});
}
// Render the response as XML in reply to the webhook request
response.type('text/xml');
response.send(twiml.toString());
});
// Create an HTTP server and listen for requests on port 3000
console.log('Twilio Client app HTTP server running at http://127.0.0.1:3000');
app.listen(3000);
|
/******/ (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] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = 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;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 42);
/******/ })
/************************************************************************/
/******/ ({
/***/ 42:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(43);
module.exports = __webpack_require__(44);
/***/ }),
/***/ 43:
/***/ (function(module, exports) {
window.addEventListener('load', function () {
new Vue({
el: '#interruptor',
data: {
checkValue: 0
},
methods: {
checkToggle: function checkToggle(e) {
this.checkValue == 0 ? 1 : 0;
}
}
});
new Vue({
el: '#user-foto',
data: {
image: $('#default').val() || ''
},
methods: {
onFileChange: function onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.createImage(files[0]);
},
createImage: function createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = function (e) {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
}
}
});
// Habilidades
new Vue({
el: '#habilidades',
data: {
habilidades: []
},
methods: {
addHabilidad: function addHabilidad(e) {
this.habilidades.push($('#text-hab').val());
$('#text-hab').val('');
$('#text-hab').focus();
$('#hab-all').text(this.habilidades.toString());
},
rmHabilidad: function rmHabilidad(key) {
this.habilidades.splice(key, 1);
$('#hab-all').text(this.habilidades.toString());
}
}
});
// Idiomas
new Vue({
el: '#idiomas',
data: {
idiomas: []
},
methods: {
addIdioma: function addIdioma(e) {
this.idiomas.push($('#text-ido').val());
$('#text-ido').val('');
$('#text-ido').focus();
$('#ido-all').text(this.idiomas.toString());
},
rmIdioma: function rmIdioma(key) {
this.idiomas.splice(key, 1);
$('#ido-all').text(this.idiomas.toString());
}
}
});
// Otra Informacion
new Vue({
el: '#informacion',
data: {
informacion: []
},
methods: {
addInfo: function addInfo(e) {
this.informacion.push($('#text-info').val());
$('#text-info').val('');
$('#text-info').focus();
$('#info-all').text(this.informacion.toString());
},
rmInfo: function rmInfo(key) {
this.informacion.splice(key, 1);
$('#info-all').text(this.informacion.toString());
}
}
});
// register modal component
Vue.component('modal', {
template: '#modal-template'
});
Vue.component('modal-students', {
template: '#modal-template-students'
});
// ===================================================================> Empresa
// Empresa - mostrar oferta
new Vue({
el: '#mostrar-oferta',
data: {
showModal: false
},
methods: {
close: function close() {
alert('hole');
}
}
});
// Empresa - mostrar candidato
new Vue({
el: '#mostrar-candidato',
data: {
showModal: false
},
methods: {
close: function close() {
alert('hole');
}
}
});
// ==================================================================> Ususario
// Usuario - mostrar asignar oferta a cantidato
new Vue({
el: '#mostrar-asignar',
data: {
showModal: false
},
methods: {
close: function close() {
alert('hole');
}
}
});
// Usuario - mostrar enviar candidato a empresa
new Vue({
el: '#mostrar-enviar',
data: {
showModal: false
},
methods: {
close: function close() {
alert('hole');
}
}
});
// ================================================================> Estudiante
// Estudiante - mostrar opciones de ofertas a aplicar
new Vue({
el: '#mostrar-aplicar',
data: {
showModal: false
},
methods: {
close: function close() {
alert('hole');
}
}
});
});
// Carreras para la Oferta
new Vue({
el: '#carrera_oferta',
data: {
identificadores: [],
carreras: []
},
methods: {
addCarrera: function addCarrera(e) {
if ($('#opt-carrera').val() > 0) {
this.carreras.push($('#opt-carrera option:selected').text());
this.identificadores.push($('#opt-carrera').val());
$('#opt-carrera').val('0');
$('#opt-carrera').focus();
$('#carrera-all').text(this.identificadores.toString());
}
},
rmCarrera: function rmCarrera(key) {
this.carreras.splice(key, 1);
this.identificadores.splice(key, 1);
$('#carrera-all').text(this.identificadores.toString());
}
}
});
/***/ }),
/***/ 44:
/***/ (function(module, exports) {
// FORMACIÓN ACADÉMICA
var cards;
$(document).on('click', '#agregar-academico', function() {
return $.get('/ajax/add_academico', function(data) {
$('#estudio-row').append(data);
return $('#agregar-academico').replaceWith('<a class="agregar quitar"><i class="fa fa-minus"></i></a>');
});
});
$(document).on('change', '.tipo-estudio', function() {
var el, opcion;
el = $(this).parents('.row').find('.estudio');
opcion = $(this).val().localeCompare("5");
if (opcion === 0) {
return $.get('/ajax/add_estudio', function(data) {
return el.replaceWith(data);
});
} else {
return el.replaceWith('<input type="text" name="estudio_academico[0]" placeholder="Estudio/Carrera" class="estudio">');
}
});
// QUITAR
$(document).on('click', '.quitar', function() {
return $(this).parents('.row').css('display', 'none');
});
// EXPERIENCIA LABORAL
$(document).on('click', '#agregar-laraboral', function() {
var row;
row = '<div class="row"><div class="col-md-4 col-sm-12"><div class="form-group"><input type="text" name="cargo_laboral[]" placeholder="Cargo"></div></div><div class="col-md-3 col-sm-12"><div class="form-group"><input type="text" name="institucion_laboral[]" placeholder="Institución"></div></div><div class="col-md-2 col-sm-12"><div class="form-group"><input type="text" name="ciudad_empresa[]" placeholder="Ciudad"></div></div><div class="col-md-2 col-sm-12"><div class="form-group"><input type="text" name="periodo_laboral[]" placeholder="Período"></div></div><div class="col-md-1 col-sm-12"><div class="form-group"><a class="agregar" id="agregar-laraboral"><i class="fa fa-plus"></i></a></div></div></div>';
$('#laboral-row').append(row);
return $(this).replaceWith('<a class="agregar quitar"><i class="fa fa-minus"></i></a>');
});
// RECONOCIMIENTOS
$(document).on('click', '#agregar-reconocimiento', function() {
var row;
row = '<div class="row"><div class="col-md-4 col-sm-12"><div class="form-group"><input type="text" name="merito_reconocimiento[]" placeholder="Merito"></div></div><div class="col-md-3 col-sm-12"><div class="form-group"><input type="text" name="organizacion_reconocimiento[]" placeholder="Organizació"></div></div><div class="col-md-2 col-sm-12"><div class="form-group"><input type="text" name="ciudad_reconocimiento[]" placeholder="Ciudad"></div></div><div class="col-md-2 col-sm-12"><div class="form-group"><input type="text" name="periodo_reconicimiento[]" placeholder="Año"></div></div><div class="col-md-1 col-sm-12"><div class="form-group"><a id="agregar-reconocimiento" class="agregar"><i class="fa fa-plus"></i></a></div></div></div>';
$('#reconocimiento-row').append(row);
return $(this).replaceWith('<a class="agregar quitar"><i class="fa fa-minus"></i></a>');
});
// Alert dissmise animation
$(document).on('click', '.closebtn', function() {
var div;
div = this.parentElement;
div.style.opacity = '0';
return setTimeout((function() {
return div.style.display = 'none';
}), 600);
});
// Seleccionar uno o varios estudiantes
$(document).on('click', '.info-box-icon', function() {
var estudiante_seleccionado;
estudiante_seleccionado = $(this).parents('.box-selectable');
if (estudiante_seleccionado.children('input:checkbox').is(':checked')) {
estudiante_seleccionado.children('input:checkbox').prop('checked', false);
return estudiante_seleccionado.css({
'background-color': 'white',
'color': '#808080'
});
} else {
estudiante_seleccionado.children('input:checkbox').prop('checked', true);
return estudiante_seleccionado.css({
'background-color': '#1C3170',
'color': 'white'
});
}
});
$(document).on('click', '#enviar', function() {
var seleccionados;
seleccionados = $('input:checked').length;
if ((seleccionados - 1) <= 0) {
return alert('No ha seleccionado al menos un estudiante');
} else {
return $('#asignar-form').submit();
}
});
// Tamaño de los cards de estudiantes
cards = $(document).find('.info-box');
cards.each(function() {
var alto, css;
alto = $(this).height();
css = '{"height":"' + alto + 'px", "width":"' + alto + 'px"';
if (alto > 90) {
css += ', "margin-right":"10px"}';
} else {
css += '}';
}
$(this).children('.info-box-icon').css(JSON.parse(css));
return $(this).find('.img-circle').css({
'max-height': (alto - 10) + 'px',
'max-width': (alto - 10) + 'px',
'overflow': 'hidden'
});
});
// Super Administrador selection
$(document).on('click', '.control-sidebar-menu li', function() {
var id;
$('.control-sidebar-menu li').removeClass('selected');
$(this).addClass('selected');
id = $(this).attr('data');
return $.get('/ajax/add_flash/' + id, function(data) {
return console.log(data);
});
});
/***/ })
/******/ }); |
import Ember from 'ember';
export default Ember.Service.extend({
languages: [
{
"key": "en-US",
"label": "English"
},
{
"key": "fr-FR",
"label": "French"
},
{
"key": "de-DE",
"label": "German"
},
{
"key": "it-IT",
"label": "Italian"
},
{
"key": "pt-PT",
"label": "Portuguese"
},
{
"key": "es-ES",
"label": "Spanish"
},
{
"key": "ru-RU",
"label": "Russian [Русский]"
},
{
"key": "zh-CN",
"label": "Chinese [中国大陆]"
},
{
"key": "ja-JP",
"label": "Japanese [日本語]"
},
{
"key": "ko-KR",
"label": "Korean [한국어]"
},
{
"key": "hi-IN",
"label": "Hindi [हिंदी]"
},
{
"key": "ar-EG",
"label": "Egyptian Arabic [عربى]"
},
],
getLabel(key) {
if(!key){
return '';
}
let language = this.get('languages').findBy('key', key);
return language && language.label || '';
},
vowels: ['a', 'e', 'i', 'o', 'u'],
isVowel(language) {
if(!language){
return false;
}
return this.get('vowels').indexOf(language.toLowerCase().charAt(0)) !== -1;
},
getLanguages(keys){
if(keys && keys.length) {
let languages = this.get('languages');
return languages.filter(lang => keys.indexOf(lang.key) !== -1);
} else {
return [];
}
}
});
|
var BlendMicro = require(__dirname+'/../../');
// var BlendMicro = require('blendmicro');
var bm = new BlendMicro(process.argv[2] || "BlendMicro");
bm.on('open', function(){
console.log("open!!");
});
// read data
bm.on("data", function(data){
console.log(data.toString());
bm.updateRssi(function(err, rssi){
console.log("rssi:"+rssi);
});
});
bm.on('close', function(){
console.log('close!!');
});
process.stdin.setEncoding("utf8");
// write data from STDIN
process.stdin.on("readable", function(){
var chunk = process.stdin.read();
if(chunk == null) return;
chunk = chunk.toString().replace(/[\r\n]/g, '');
bm.write(chunk);
});
|
import beginConnectingAsync from './begin-connecting'
import cancelConnectingAsync from './cancel-connecting'
import connectWithUserAsync from './connect-with-user'
export {
beginConnectingAsync,
cancelConnectingAsync,
connectWithUserAsync,
}
|
$(function() {
var s = Snap('#svg');
var obj = s.selectAll('polygon');
var $obj = $('polygon');
$('polygon:odd').addClass('right');
$obj.css('opacity', 1);
$obj.each(function(i) {
$(this).delay(50 * i).animate({
opacity: 0}, 1500, function() {
$(this).attr({'class': 'on'});
});
});
s.select('#bg').attr({
opacity: 0
}).animate({
opacity: 1
}, 328*50);
}); |
/**
* Created by ls-mac on 2017/3/1.
*/
import React , {Component} from 'react';
import {AppRegistry , TabBarIOS, Text , View, StyleSheet, Dimensions} from 'react-native';
export default class LSFind extends Component{
constructor(props){
super(props);
}
render(){
return(
<View style={styles.outView}>
<Text style={{fontSize: 30 ,color:'orange'}}>2</Text>
</View>
)
}
}
const styles = StyleSheet.create({
outView:{
flex:1,
justifyContent:'center',
alignItems:'center',
}
}) |
Drop.prototype.watchWindow = function() {
$(window).on('resize scroll', () => {
this.tick();
});
return this;
};
Drop.prototype.watchDrag = function() {
$(this.data.anchor).on('drag dragstart dragstop', () => {
this.tick();
});
return this;
}; |
// Generated by CoffeeScript 2.4.1
(function() {
//Language: Traditional Chinese
//Translators: victorleungtw, ArthurPai
var zh_TW;
zh_TW = {
add: "添加",
and: "和",
back: "返回",
cancel: "取消",
changePassword: "修改密碼",
choosePassword: "選擇密碼",
clickAgree: "點擊註冊, 您同意我們的",
configure: "配置",
createAccount: "建立帳號",
currentPassword: "當前密碼",
dontHaveAnAccount: "還沒有賬戶?",
email: "電子郵箱",
emailAddress: "電郵地址",
emailResetLink: "電子郵件重設連結",
forgotPassword: "忘記密碼?",
ifYouAlreadyHaveAnAccount: "如果您已有賬戶",
newPassword: "新密碼",
newPasswordAgain: "新密碼 (重新輸入)",
optional: "可選的",
OR: "或",
password: "密碼",
passwordAgain: "密碼 (重新輸入)",
privacyPolicy: "隱私政策",
remove: "刪除",
resetYourPassword: "重置您的密碼",
setPassword: "設置密碼",
sign: "登",
signIn: "登入",
signin: "登入",
signOut: "登出",
signUp: "註冊",
signupCode: "註冊碼",
signUpWithYourEmailAddress: "使用您的電郵地址註冊",
terms: "使用條款",
updateYourPassword: "更新您的密碼",
username: "用戶名",
usernameOrEmail: "用戶名或電子郵箱",
with: "與",
enterPassword: "輸入密碼",
enterNewPassword: "輸入新密碼",
enterEmail: "輸入電子郵件",
enterUsername: "輸入用戶名",
enterUsernameOrEmail: "輸入用戶名或電子郵件",
orUse: "或是使用",
info: {
emailSent: "郵件已發送",
emailVerified: "郵件已驗證",
passwordChanged: "密碼已修改",
passwordReset: "密碼重置"
},
error: {
emailRequired: "必須填寫電子郵件。",
minChar: "密碼至少需要7個字符。",
pwdsDontMatch: "密碼不一致。",
pwOneDigit: "密碼必須至少有一位數字。",
pwOneLetter: "密碼必須至少有一位字母。",
signInRequired: "您必須先登錄才能繼續。",
signupCodeIncorrect: "註冊碼錯誤。",
signupCodeRequired: "必須有註冊碼。",
usernameIsEmail: "用戶名不能為電郵地址。",
usernameRequired: "必須有用戶名。",
accounts: {
//---- accounts-base
//"@" + domain + " email required"
//"A login handler should return a result or undefined"
"Email already exists.": "電郵地址已被使用。",
"Email doesn't match the criteria.": "電郵地址不符合條件。",
"Invalid login token": "無效的登錄令牌",
"Login forbidden": "禁止登錄",
//"Service " + options.service + " already configured"
"Service unknown": "未知服務",
"Unrecognized options for login request": "無法識別的登錄請求選項",
"User validation failed": "用戶驗證失敗",
"Username already exists.": "用戶名已經存在。",
"You are not logged in.": "您尚未登入。",
"You've been logged out by the server. Please log in again.": "你已被伺服器登出,請重新登入。",
"Your session has expired. Please log in again.": "您的協定已過期,請重新登入。",
"Invalid email or username": "無效的電子郵件或用戶名",
"Internal server error": "内部服务器错误",
"undefined": "未知錯誤",
//---- accounts-oauth
"No matching login attempt found": "沒有找到匹配的登入請求",
//---- accounts-password-client
"Password is old. Please reset your password.": "密碼是舊的。請重置您的密碼。",
//---- accounts-password
"Incorrect password": "密碼不正確",
"Invalid email": "無效的電子郵件",
"Must be logged in": "必須先登入",
"Need to set a username or email": "必須設置用戶名或電郵地址",
"old password format": "舊密碼格式",
"Password may not be empty": "密碼不能為空的",
"Signups forbidden": "註冊被禁止",
"Token expired": "密匙過期",
"Token has invalid email address": "密匙具有無效的電郵地址",
"User has no password set": "用戶沒有設置密碼",
"User not found": "找不到用戶",
"Verify email link expired": "驗證電郵連結已過期",
"Verify email link is for unknown address": "驗證電郵連結是未知的地址",
//---- match
"Match failed": "匹配失敗",
//---- Misc...
"Unknown error": "未知錯誤"
}
}
};
if (typeof T9n !== "undefined" && T9n !== null) {
T9n.map("zh_TW", zh_TW);
}
if (typeof T9n !== "undefined" && T9n !== null) {
T9n.map("zh-TW", zh_TW);
}
if (typeof module !== "undefined" && module !== null) {
module.exports = zh_TW;
}
}).call(this);
|
import cookies from './cookies';
const COOKIE_KEY = 'cookie-accept';
const COOKIE_VALUE = 'accept';
export default {
/**
* Hides the cookie bar;
*/
hideCookieBar() {
let cookieBar = document.querySelector( '.cookie-bar' );
cookieBar.classList.add( 'cookie-bar__hide' );
cookies.setCookie( COOKIE_KEY, COOKIE_VALUE, 365 );
},
/**
* Initializes cookie bar
*/
init() {
let cookieBar = document.querySelector( '.cookie-bar' );
if ( cookieBar ) {
let cookieAccept = cookieBar.querySelector( 'button' );
const accept = cookies.getCookie( COOKIE_KEY ) && getCookie( COOKIE_KEY ) === COOKIE_VALUE;
cookieAccept.addEventListener( 'click', function( event ) {
event.preventDefault();
hideCookieBar();
} );
}
}
} |
/* eslint-disable import/default */
import 'reset-css/reset.css';
import React from 'react';
import ReactDOM from 'react-dom';
//
import { ApolloProvider } from 'react-apollo';
import { BrowserRouter as Router } from 'react-router-dom';
import { AppContainer } from 'react-hot-loader';
// Shared Imports
import ApolloClient from 'Client/lib/apollo/client';
import configureStore from 'Client/store/configureStore';
// Import Core App
import LayoutRoot from 'Browser/components/layout_root';
// TODO: Initial State
const initialState = JSON.parse(window.INITIAL_STATE);
// Platform Reducers
const platformReducers = { };
// Platform Middleware
const platformMiddleware = [ ];
// Platform Enchanchers
const platformEnchancers = [];
if (process.env.NODE_ENV === 'development' && process.browser && window.devToolsExtension) {
platformEnchancers.push(window.devToolsExtension());
}
// Configure Store
const store = configureStore({
platformReducers,
platformMiddleware,
platformEnchancers,
initialState
});
// Get Mount Element
const mountEl = document.getElementById('root');
// console.log(routes);
// Hot Render Func
const render = Component => {
ReactDOM.render(
<ApolloProvider store={store} client={ApolloClient}>
<Router>
<AppContainer>
<Component/>
</AppContainer>
</Router>
</ApolloProvider>
, mountEl
);
};
// Render Root Layout
render(LayoutRoot);
// Hot Module Replacement API
if (module.hot) {
module.hot.accept('./components/layout_root', () => render(LayoutRoot));
}
|
var Class = require('ee-class')
, log = require('ee-log')
, fs = require('fs')
, path = require('path')
, assert = require('assert');
var FaceDetector = require('../')
, detector;
describe('The Facedetector', function() {
it('should not crash when instatiated', function() {
detector = new FaceDetector();
});
it('should detect a focal point on image 1', function(done) {
this.timeout(60000);
fs.readFile(__dirname+'/image1.jpg', function(err, data) {
if (err) done(err);
else {
detector.detect(data, function(err, focalPoint) {
if (err) done(err);
else if (!focalPoint) done(new Error('Failed to detect faces!'));
else done();
});
}
});
});
it('should detect a focal point on image 2', function(done) {
this.timeout(60000);
fs.readFile(__dirname+'/image2.jpg', function(err, data) {
if (err) done(err);
else {
detector.detect(data, function(err, focalPoint) {
if (err) done(err);
else if (!focalPoint) done(new Error('Failed to detect faces!'));
else done();
});
}
});
});
});
|
/*
* Generate js tasks
*/
//Validate if session is finished
var verify = setInterval(function _(){
AjaxGET_TEXT("/owlgroup/_vistas/gad_verify_.php", function(response){
var data = JSON.parse(response);
if(!data){
var popup = new $.Popup({
afterOpen : function(){
setTimeout(function(){
debugger;
var urlid = (window.Storage)? "/" + window.localStorage.getItem("urlId") : "";
window.location.href = window.location.origin + urlid;
}, 5000);
},
closeContent: null,
modal : true
});
popup.open("/owlgroup/_vistas/se_alert.php?type=session_died");
clearInterval(verify);
}
});
}, 60000);
//Valida Asistencia de Curso
function _assist(interval){
setTimeout(function(){
var popup = new $.Popup({
afterOpen : function(){
var tiempo = 9;
var setInt = setInterval(function(){
$("TimerTime").html(tiempo);
if(tiempo == 0){
$.post("/owlgroup/room.php?asistencia=finaliza",function(success){
var urlid = (window.Storage)? "/" + window.localStorage.getItem("urlId") : "";
window.location.href = window.location.origin + urlid;
}, "json")
clearInterval(setInt);
}else{
tiempo--;
}
}, 1000);
$("#VAssist").click(function(){
console.log("renueva interval: "+setInt);
console.log("nuevo tiempo: "+interval);
_assist(interval);
clearInterval(setInt);
popup.close();
})
},
closeContent: null,
modal : true
});
popup.open("/owlgroup/_vistas/se_alert.php?type=verifyAssist");
},interval*1000)
}
function _concurrencia(interval){
setTimeout(function(){
var popup = new $.Popup({
afterOpen : function(){
var tiempo = 9;
var setInt = setInterval(function(){
$("TimerTime").html(tiempo);
if(tiempo == 0){
popup.close();
clearInterval(setInt);
window.location.href = window.document.origin + "/owlgroup/cierra_session.php";
}else{
tiempo--;
}
}, 1000);
$("#VAssist").click(function(){
_concurrencia(interval);
clearInterval(setInt);
popup.close();
})
},
closeContent: null,
modal : true
});
popup.open("/owlgroup/_vistas/se_alert.php?type=verifyConcurrencia");
},interval*1000)
}
window.onbeforeunload = closeSession;
function closeSession(){
if(location.pathname == "/owlgroup/room.php") {
$.ajax({
async: false,
cache: false,
url: "/owlgroup/room.php?asistencia=finaliza",
type: "post"
});
return null;
}
}
/*
$(window).on('beforeunload',function(e){
if(location.pathname == "/owlgroup/room.php"){
console.log("1");
e.preventDefault();
$.post("/owlgroup/room.php?asistencia=finaliza");
}
})*/ |
import Converter from './all-your-base';
const converter = new Converter();
describe('Converter', () => {
test('single bit one to decimal', () => {
expect(converter.convert([1], 2, 10)).toEqual([1]);
});
xtest('binary to single decimal', () => {
expect(converter.convert([1, 0, 1], 2, 10)).toEqual([5]);
});
xtest('single decimal to binary', () => {
expect(converter.convert([5], 10, 2)).toEqual([1, 0, 1]);
});
xtest('binary to multiple decimal', () => {
expect(converter.convert([1, 0, 1, 0, 1, 0], 2, 10)).toEqual([4, 2]);
});
xtest('decimal to binary', () => {
expect(converter.convert([4, 2], 10, 2)).toEqual([1, 0, 1, 0, 1, 0]);
});
xtest('trinary to hexadecimal', () => {
expect(converter.convert([1, 1, 2, 0], 3, 16)).toEqual([2, 10]);
});
xtest('hexadecimal to trinary', () => {
expect(converter.convert([2, 10], 16, 3)).toEqual([1, 1, 2, 0]);
});
xtest('15-bit integer', () => {
expect(converter.convert([3, 46, 60], 97, 73)).toEqual([6, 10, 45]);
});
xtest('empty list', () => {
expect(() => {
converter.convert([], 2, 10);
}).toThrow(new Error('Input has wrong format'));
});
xtest('single zero', () => {
expect(converter.convert([0], 10, 2)).toEqual([0]);
});
xtest('multiple zeros', () => {
expect(() => {
converter.convert([0, 0, 0], 10, 2);
}).toThrow(new Error('Input has wrong format'));
});
xtest('leading zeros', () => {
expect(() => {
converter.convert([0, 6, 0], 7, 10);
}).toThrow(new Error('Input has wrong format'));
});
xtest('negative digit', () => {
expect(() => {
converter.convert([1, -1, 1, 0, 1, 0], 2, 10);
}).toThrow(new Error('Input has wrong format'));
});
xtest('invalid positive digit', () => {
expect(() => {
converter.convert([1, 2, 1, 0, 1, 0], 2, 10);
}).toThrow(new Error('Input has wrong format'));
});
xtest('first base is one', () => {
expect(() => {
converter.convert([], 1, 10);
}).toThrow(new Error('Wrong input base'));
});
xtest('second base is one', () => {
expect(() => {
converter.convert([1, 0, 1, 0, 1, 0], 2, 1);
}).toThrow(new Error('Wrong output base'));
});
xtest('first base is zero', () => {
expect(() => {
converter.convert([], 0, 10);
}).toThrow(new Error('Wrong input base'));
});
xtest('second base is zero', () => {
expect(() => {
converter.convert([7], 10, 0);
}).toThrow(new Error('Wrong output base'));
});
xtest('first base is negative', () => {
expect(() => {
converter.convert([1], -2, 10);
}).toThrow(new Error('Wrong input base'));
});
xtest('second base is negative', () => {
expect(() => {
converter.convert([1], 2, -7);
}).toThrow(new Error('Wrong output base'));
});
xtest('both bases are negative', () => {
expect(() => {
converter.convert([1], -2, -7);
}).toThrow(new Error('Wrong input base'));
});
xtest('missing input base throws an error', () => {
expect(() => {
converter.convert([0]);
}).toThrow(new Error('Wrong input base'));
});
xtest('wrong input_base base not integer', () => {
expect(() => {
converter.convert([0], 2.5);
}).toThrow(new Error('Wrong input base'));
});
xtest('missing output base throws an error', () => {
expect(() => {
converter.convert([0], 2);
}).toThrow(new Error('Wrong output base'));
});
xtest('wrong output_base base not integer', () => {
expect(() => {
converter.convert([0], 3, 2.5);
}).toThrow(new Error('Wrong output base'));
});
});
|
(()=>{
const isCompatible = (chrome.runtime)?true:false;
Array.prototype.print = function() {
if(!isCompatible) {
Array.prototype.print = function(){let i="";this.forEach((a)=>{i+=" "+a.msg});console.log(i)};
throw new Error("This browser is not compatible with ConsoleFormatter");
}
var c = [], d = [];
this.forEach((a,i)=>{
if(!(a instanceof Object) || (a instanceof Array)) throw new TypeError("Unknown type in array, index: " + i + "\n" + "Objects are only allowed");
if (a.msg && a) {
if (1 < Object.keys(a).length) {
c.push("%c ", a.msg);
var b = "";
a.align && (b += `text-align:${a.align};`);
a.animation && (b += `animation:${a.animation};-webkit-animation:${a.animation};`);
a.background && (b += `background-color:${a.background};`);
a.bborder && (b += `border-bottom:${a.bborder};`);
a.border && (b += `border:${a.border};`);
a.bottom && (b += `bottom:${a.bottom};`);
a.bwidth && (b += `border-width:${a.bwidth};`);
a.clear && (b += `clear:${a.clear};`);
a.collapse && (b += `border-collapse:${a.collapse};`);
a.color && (b += `color:${a.color};`);
a.content && (b += `content:${a.content};`);
a.corner && (b += `border-radius:${a.corner};`);
a.cursor && (b += `cursor:${a.cursor};`);
a.display && (b += `display:${a.display};`);
a.filter && (b += `filter:${a.filter};-webkit-filter:${a.filter};`);
a.float && (b += `float:${a.float};`);
a.font && (b += `font-family:${a.font};`);
a.fontstyle && (b += `font-style:${a.fontstyle};`);
a.fweight && (b += `font-weight:${a.fweight};`);
a.left && (b += `left:${a.left};`);
a.lborder && (b += `border-left:${a.lborder};`);
a.opacity && (b += `opacity:${a.opacity};`);
a.padding && (b += `padding:${a.padding};`);
a.position && (b += `position:${a.position};`);
a.rborder && (b += `border-right:${a.rborder};`);
a.right && (b += `right:${a.right};`);
a.size && (b += `font-size:${a.size};`);
a.textd && (b += `text-decoration:${a.textd};`);
a.tborder && (b += `border-top:${a.tborder};`);
a.top && (b += `top:${a.top};`);
a.uselect && (b += `user-select:${a.uselect};-webkit-user-select:${a.uselect};`);
a.ww && (b += `word-wrap:${a.ww};`);
a.z && (b += `z-index:${a.z};`);
d.push(b);
} else {
c.push("%c " + a.msg), d.push("color:black");
}
}else{
if(a == this || a == "print") return;
throw new Error("Null object given in array index: " + i);
}
});
c = [c.join("")];
for (let a in d) "string" == typeof d[a] && c.push(d[a]);
console.log.apply(this, c);
};
})();
|
/*
* Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui)
* Copyright 2015 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([ "./kendo.core", "./kendo.draganddrop" ], f);
})(function(){
(function ($, undefined) {
var kendo = window.kendo,
getOffset = kendo.getOffset,
Widget = kendo.ui.Widget,
CHANGE = "change",
KREORDERABLE = "k-reorderable";
function toggleHintClass(hint, denied) {
hint = $(hint);
if (denied) {
hint.find(".k-drag-status").removeClass("k-add").addClass("k-denied");
} else {
hint.find(".k-drag-status").removeClass("k-denied").addClass("k-add");
}
}
var Reorderable = Widget.extend({
init: function(element, options) {
var that = this,
draggable,
group = kendo.guid() + "-reorderable";
Widget.fn.init.call(that, element, options);
element = that.element.addClass(KREORDERABLE);
options = that.options;
that.draggable = draggable = options.draggable || new kendo.ui.Draggable(element, {
group: group,
filter: options.filter,
hint: options.hint
});
that.reorderDropCue = $('<div class="k-reorder-cue"><div class="k-icon k-i-arrow-s"></div><div class="k-icon k-i-arrow-n"></div></div>');
element.find(draggable.options.filter).kendoDropTarget({
group: draggable.options.group,
dragenter: function(e) {
if (!that._draggable) {
return;
}
var dropTarget = this.element, offset;
var denied = !that._dropTargetAllowed(dropTarget) || that._isLastDraggable();
toggleHintClass(e.draggable.hint, denied);
if (!denied) {
offset = getOffset(dropTarget);
var left = offset.left;
if (options.inSameContainer && !options.inSameContainer({
source: dropTarget,
target: that._draggable,
sourceIndex: that._index(dropTarget),
targetIndex: that._index(that._draggable)
})) {
that._dropTarget = dropTarget;
} else {
if (that._index(dropTarget) > that._index(that._draggable)) {
left += dropTarget.outerWidth();
}
}
that.reorderDropCue.css({
height: dropTarget.outerHeight(),
top: offset.top,
left: left
})
.appendTo(document.body);
}
},
dragleave: function(e) {
toggleHintClass(e.draggable.hint, true);
that.reorderDropCue.remove();
that._dropTarget = null;
},
drop: function() {
that._dropTarget = null;
if (!that._draggable) {
return;
}
var dropTarget = this.element;
var draggable = that._draggable;
var containerChange = false;
if (that._dropTargetAllowed(dropTarget) && !that._isLastDraggable()) {
that.trigger(CHANGE, {
element: that._draggable,
target: dropTarget,
oldIndex: that._index(draggable),
newIndex: that._index(dropTarget),
position: getOffset(that.reorderDropCue).left > getOffset(dropTarget).left ? "after" : "before"
});
}
}
});
draggable.bind([ "dragcancel", "dragend", "dragstart", "drag" ],
{
dragcancel: function() {
that.reorderDropCue.remove();
that._draggable = null;
that._elements = null;
},
dragend: function() {
that.reorderDropCue.remove();
that._draggable = null;
that._elements = null;
},
dragstart: function(e) {
that._draggable = e.currentTarget;
that._elements = that.element.find(that.draggable.options.filter);
},
drag: function(e) {
if (!that._dropTarget || this.hint.find(".k-drag-status").hasClass("k-denied")) {
return;
}
var dropStartOffset = getOffset(that._dropTarget).left;
var width = that._dropTarget.outerWidth();
if (e.pageX > dropStartOffset + width / 2) {
that.reorderDropCue.css({ left: dropStartOffset + width });
} else {
that.reorderDropCue.css({ left: dropStartOffset });
}
}
}
);
},
options: {
name: "Reorderable",
filter: "*"
},
events: [
CHANGE
],
_isLastDraggable: function() {
var inSameContainer = this.options.inSameContainer,
draggable = this._draggable[0],
elements = this._elements.get(),
found = false,
item;
if (!inSameContainer) {
return false;
}
while (!found && elements.length > 0) {
item = elements.pop();
found = draggable !== item && inSameContainer({
source: draggable,
target: item,
sourceIndex: this._index(draggable),
targetIndex: this._index(item)
});
}
return !found;
},
_dropTargetAllowed: function(dropTarget) {
var inSameContainer = this.options.inSameContainer,
dragOverContainers = this.options.dragOverContainers,
draggable = this._draggable;
if (draggable[0] === dropTarget[0]) {
return false;
}
if (!inSameContainer || !dragOverContainers) {
return true;
}
if (inSameContainer({ source: draggable,
target: dropTarget,
sourceIndex: this._index(draggable),
targetIndex: this._index(dropTarget)
})) {
return true;
}
return dragOverContainers(this._index(draggable), this._index(dropTarget));
},
_index: function(element) {
return this._elements.index(element);
},
destroy: function() {
var that = this;
Widget.fn.destroy.call(that);
that.element.find(that.draggable.options.filter).each(function() {
var item = $(this);
if (item.data("kendoDropTarget")) {
item.data("kendoDropTarget").destroy();
}
});
if (that.draggable) {
that.draggable.destroy();
that.draggable.element = that.draggable = null;
}
that.elements = that.reorderDropCue = that._elements = that._draggable = null;
}
});
kendo.ui.plugin(Reorderable);
})(window.kendo.jQuery);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
/*
* Copyright (c) 2017, Itai Reuveni <itaireuveni@gmail.com>
*
* License: MIT
*/
import React from "react";
import TestUtils from "react-addons-test-utils";
import chai from "chai";
import sinon from "sinon";
import Block from "../src/Block";
let expect = chai.expect;
describe("Block", function () {
beforeEach(function () {
this.data = {
caption: "media caption"
};
this.setReadOnly = sinon.spy();
this.updateData = sinon.spy();
this.remove = sinon.spy();
this.plugin = sinon.spy();
this.wrapper = TestUtils.renderIntoDocument(
<Block container={this} blockProps={this} data={this.data} />
);
this.caption = TestUtils.scryRenderedDOMComponentsWithTag(this.wrapper, "input")[0];
});
it("renders caption from data", function () {
expect(this.caption.value).to.be.equal(this.data.caption);
});
it("updates entity on caption change", function () {
this.caption.value = "new caption";
TestUtils.Simulate.change(this.caption);
expect(this.updateData.calledWith({caption: "new caption"})).to.be.true;
});
it("your tests here...", function () {
expect(true).to.be.false;
});
});
|
/* jshint browser: true, curly: true, eqeqeq: true, forin: true, latedef: true,
newcap: true, noarg: true, noempty: true, nonew: true, strict:true,
undef: true, unused: true */
/* global _: false, jQuery: false, Backbone: false */
(function($, _, Backbone, App) {
'use strict';
var Components = App.Components || (App.Components = {});
Components.DataList = Backbone.View.extend({
events: {
'click.dataList [data-command]': 'handleCommand'
},
initialize: function(options) {
this.childViewFactory = options.childViewFactory;
if (_.has(options, 'childViewContainer')) {
if (_.isString(options.childViewContainer)) {
this.childViewContainer = this.$(options.childViewContainer);
if (!this.childViewContainer.length) {
this.childViewContainer = $(options.childViewContainer);
}
} else {
if (_.isElement(options.childViewContainer)) {
this.childViewContainer = $(options.childViewContainer);
} else {
this.childViewContainer = options.childViewContainer;
}
}
} else {
this.childViewContainer = this.$el;
}
this.itemInsertMode = options.itemInsertMode ||
Components.DomInsertMode.append;
this.subscribeCollectionEvents();
this.childViews = [];
},
render: function() {
var self = this;
this.removeChildViews();
this.collection
.each(function (model) {
self.renderChildView(model, false);
});
if (this.childViews.length) {
var fragment = document.createDocumentFragment();
_.each(this.childViews, function(v) {
return fragment.appendChild(v.el);
});
this.childViewContainer.append(fragment);
}
return this;
},
remove: function() {
this.removeChildViews();
Backbone.View.prototype.remove.call(this, arguments);
return this;
},
setColection: function(collection) {
this.unsubscribeCollectionEvents();
this.collection = collection;
this.subscribeCollectionEvents();
return this;
},
subscribeCollectionEvents: function() {
if (!this.collection) {
return;
}
this.listenTo(this.collection, 'sort reset', this.render);
this.listenTo(this.collection, 'add', this.renderChildView);
},
unsubscribeCollectionEvents: function() {
if (!this.collection) {
return;
}
this.stopListening(this.collection, 'sort reset add');
},
removeChildViews: function() {
var self = this;
_.each(this.childViews, function(view) {
self.stopListening(view);
view.remove();
});
this.childViews = [];
this.childViewContainer.empty();
},
renderChildView: function(model, includeInDom) {
var childView = this.childViewFactory(model),
self = this;
if (_.isUndefined(includeInDom)) {
includeInDom = true;
}
this.listenTo(childView, 'removing', function() {
var index = _.indexOf(self.childViews, childView);
self.stopListening(childView);
self.childViews.splice(index, 1);
});
childView.render()
.$el
.attr('data-cid', model.cid);
if (includeInDom) {
if (this.itemInsertMode === Components.DomInsertMode.append) {
this.childViewContainer.append(childView.$el);
} else if (this.itemInsertMode === Components.DomInsertMode.prepend) {
this.childViewContainer.prepend(childView.$el);
}
}
this.childViews.push(childView);
return childView;
},
handleCommand: function(e) {
var element = $(e.currentTarget),
command = element.attr('data-command'),
cid = element.closest('[data-cid]').attr('data-cid'),
model = this.collection.get(cid),
args = _.extend(e, {
command: command,
model: model
});
this.trigger('command', args);
}
});
})(jQuery, _, Backbone, window.App || (window.App = {})); |
import { connect } from "react-redux";
import ObservationModal from "../components/observation_modal";
import {
hideCurrentObservation,
addIdentification,
addComment,
toggleCaptive,
toggleReviewed,
agreeWithCurrentObservation,
showNextObservation,
showPrevObservation,
updateCurrentObservation,
fetchDataForTab
} from "../actions";
function mapStateToProps( state ) {
let images;
const observation = state.currentObservation.observation;
if ( observation && observation.photos && observation.photos.length > 0 ) {
let defaultPhotoSize = "medium";
if ( $( ".image-gallery" ).width( ) > 600 ) {
defaultPhotoSize = "large";
}
images = observation.photos.map( photo => ( {
original: photo.photoUrl( defaultPhotoSize ),
zoom: photo.photoUrl( "original" ),
thumbnail: photo.photoUrl( "square" ),
originalDimensions: photo.original_dimensions
} ) );
}
return Object.assign( {}, {
images,
blind: state.config.blind,
controlledTerms: state.controlledTerms.terms,
currentUser: state.config.currentUser
}, state.currentObservation );
}
function mapDispatchToProps( dispatch ) {
return {
onClose: ( ) => {
dispatch( hideCurrentObservation( ) );
},
toggleCaptive: ( ) => {
dispatch( toggleCaptive( ) );
},
toggleReviewed: ( ) => {
dispatch( toggleReviewed( ) );
},
addIdentification: ( ) => {
dispatch( addIdentification( ) );
},
addComment: ( ) => {
dispatch( addComment( ) );
},
agreeWithCurrentObservation: ( ) => {
dispatch( agreeWithCurrentObservation( ) ).then( ( ) => {
$( ".ObservationModal:first" ).find( ".sidebar" ).scrollTop( $( window ).height( ) );
} );
},
showNextObservation: ( ) => {
dispatch( showNextObservation( ) );
},
showPrevObservation: ( ) => {
dispatch( showPrevObservation( ) );
},
chooseTab: ( tab ) => {
dispatch( updateCurrentObservation( { tab } ) );
dispatch( fetchDataForTab( ) );
},
setImagesCurrentIndex: index => {
dispatch( updateCurrentObservation( { imagesCurrentIndex: index } ) );
},
toggleKeyboardShortcuts: keyboardShortcutsShown => {
dispatch( updateCurrentObservation( { keyboardShortcutsShown: !keyboardShortcutsShown } ) );
}
};
}
const ObservationModalContainer = connect(
mapStateToProps,
mapDispatchToProps
)( ObservationModal );
export default ObservationModalContainer;
|
'use strict';
describe('Controller: PipelineRunCtrl', function () {
// load the controller's module
beforeEach(module('luigiApp'));
var PipelineRunCtrl, $httpBackend, scope, routeParamStub, PipelineRun;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $injector) {
$httpBackend = $injector.get('$httpBackend');
// TODO replace string with fixtures
// var f = jasmine.getFixtures();
// jasmine.getFixtures().fixturesPath='test/mockdata';
// getJSONFixture('single_pipeline.json')
$httpBackend.whenGET('http://api.pipelinecd.com/runs/2').respond("{\"id\": \"2fde8a18-dd2c-4503-9dcb-dd3308d83437\",\"creationTime\": 1387968340000,\"status\": \"RUNNING\",\"currentStage\": \"deploy\",\"stages\": [{\"id\": \"1\",\"name\": \"compile\",\"status\": \"SUCCES\"},{\"id\": \"2\",\"name\": \"build\",\"status\": \"SUCCES\"},{\"id\": \"3\",\"name\": \"deploy\",\"status\": \"BUSY\"},{\"id\": \"4\",\"name\": \"release\",\"status\": \"FUTURE\"}] }");
scope = $rootScope.$new();
// PipelineRun = null;
PipelineRunCtrl = $controller('PipelineRunCtrl', {
$scope: scope,
$routeParams: { runId : 2}
});
}));
it('*Given* a specific pipeline *When* I select the pipeline *Then* I get a visualization of the pipeline', function () {
$httpBackend.flush();
expect(scope.pipeline.id).toBe("2fde8a18-dd2c-4503-9dcb-dd3308d83437");
expect(scope.pipeline.status).toBe("RUNNING");
expect(scope.pipeline.stages.length).toBe(4);
});
});
|
'use strict';
/**
* Module dependencies.
*/
var trainingprogramsPolicy = require('../policies/trainingprograms.server.policy'),
trainingprograms = require('../controllers/trainingprograms.server.controller');
module.exports = function (app) {
// Trainingprograms collection routes
app.route('/api/trainingprograms').all(trainingprogramsPolicy.isAllowed)
.get(trainingprograms.list)
.post(trainingprograms.create);
// Single trainingprogram routes
app.route('/api/trainingprograms/:trainingprogramId').all(trainingprogramsPolicy.isAllowed)
.get(trainingprograms.read)
.put(trainingprograms.update)
.delete(trainingprograms.delete);
// Finish by binding the trainingprogram middleware
app.param('trainingprogramId', trainingprograms.trainingprogramByID);
};
|
var hostname = require('os').hostname();
var backgrounder = require('backgrounder');
var _ = require('underscore');
function MetricServer(config) {
this.config = config;
}
MetricServer.prototype.start = function(callback) {
if (this.loader) {
throw new Error("already started");
}
var self = this;
self.pending = 0;
var metricConfig = self.config.metric || {};
var restartCount = metricConfig["restart-count"];
var childrenCount = metricConfig["children-count"];
self.loader = backgrounder.spawn(__dirname + "/metric-loader.js", {
"config": self.config,
"children-count": childrenCount,
"auto-restart": restartCount ? true : false,
"restart-count": restartCount
}, function() {
callback(self);
});
};
MetricServer.prototype.stop = function() {
if (!this.loader) {
return;
}
this.loader.terminate();
delete this.loader;
};
function send(server, message) {
server.pending++;
server.loader.send(message, function() {
--server.pending;
});
}
MetricServer.prototype.postEvents = function(req, res) {
var self = this;
var timestamp = Date.now();
var body = req.body;
var client = req.client;
var remoteAddress = client.remoteAddress;
send(self, {
"body": body,
"remoteAddress": remoteAddress,
"timestamp": timestamp
});
res.send({
"timestamp": timestamp,
"hostname": hostname,
"pending": self.pending,
"duration": Date.now() - timestamp
});
};
MetricServer.prototype.postMeasurement = function(measurement) {
send(this, measurement);
};
module.exports.start = function(config, callback) {
var server = new MetricServer(config);
server.start(function(svr) {
if (callback) {
callback(svr);
}
});
return server;
}; |
const moment = require('moment');
let banner = `
=======================================================================================
Author: Anxon <ansonhorse@gmail.com>
Built At: ${moment().format('YYYY-MM-DD HH:mm:ss')}
=======================================================================================
This's an open source chrome extension. Any problem please contact me.
========================================================================================
这是一个开源的小扩展(chrome或者核心差不多的浏览器应该都可以使用),有问题请反映,也欢迎提供优化或改进建议!
========================================================================================
,s555SB@@&
:9H####@@@@@Xi
1@@@@@@@@@@@@@@8
,8@@@@@@@@@B@@@@@@8
:B@@@@X3hi8Bs;B@@@@@Ah,
,8i r@@@B: 1S ,M@@@@@@#8;
1AB35.i: X@@8 . SGhr ,A@@@@@@@@S
1@h31MX8 18Hhh3i .i3r ,A@@@@@@@@@5
;@&i,58r5 rGSS: :B@@@@@@@@@@A
1#i . 9i hX. .: .5@@@@@@@@@@@1
sG1, ,G53s. 9#Xi;hS5 3B@@@@@@@B1
.h8h.,A@@@MXSs, #@H1: 3ssSSX@1
s ,@@@@@@@@@@@@Xhi, r#@@X1s9M8 .GA981
,. rS8H#@@@@@@@@@@#HG51;. .h31i;9@r .8@@@@BS;i;
.19AXXXAB@@@@@@@@@@@@@@#MHXG893hrX#XGGXM@@@@@@@@@@MS
s@@MM@@@hsX#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&,
:GB@#3G@@Brs ,1GM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B,
.hM@@@#@@#MX 51 r;iSGAM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@8
:3B@@@@@@@@@@@&9@h :Gs .;sSXH@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:
s&HA#@@@@@@@@@@@@@@M89A;.8S. ,r3@@@@@@@@@@@@@@@@@@@@@@@@@@@r
,13B@@@@@@@@@@@@@@@@@@@5 5B3 ;. ;@@@@@@@@@@@@@@@@@@@@@@@@@@@i
5#@@#&@@@@@@@@@@@@@@@@@@9 .39: ;@@@@@@@@@@@@@@@@@@@@@@@@@@@;
9@@@X:MM@@@@@@@@@@@@@@@#; ;31. H@@@@@@@@@@@@@@@@@@@@@@@@@@:
SH#@B9.rM@@@@@@@@@@@@@B :. 3@@@@@@@@@@@@@@@@@@@@@@@@@@5
,:. 9@@@@@@@@@@@#HB5 .M@@@@@@@@@@@@@@@@@@@@@@@@@B
,ssirhSM@&1;i19911i,. s@@@@@@@@@@@@@@@@@@@@@@@@@@S
,,,rHAri1h1rh&@#353Sh: 8@@@@@@@@@@@@@@@@@@@@@@@@@#:
.A3hH@#5S553&@@#h i:i9S #@@@@@@@@@@@@@@@@@@@@@@@@@A.
@@ 码了一天,妈妈带你去公园玩啊!
$$ 不,妈妈,我喜欢编程!
@@ 啪!!!
$$ (* ̄︿ ̄)
========================================================================================
`;
module.exports = banner; |
/*
* eoraptor-jst
* https://github.com/jiasong/precompile
*
* Copyright (c) 2014 gnosaij
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
],
options: {
jshintrc: '.jshintrc',
},
},
clean: {
tests: ['tmp'],
},
eoraptor_jst: {
amd: {
options: {
module: 'amd'
// namespace:'tpl'
},
files: {
'tmp/jst.amd.js': ['tmp/*.tpl.js'],
},
},
cmd: {
options: {
module: 'cmd'
// namespace:'tpl'
},
files: {
'tmp/jst.cmd.js': ['tmp/*.tpl.js'],
},
},
normal: {
options: {
},
files: {
'tmp/jst.js': ['tmp/*.tpl.js'],
},
},
}
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('default', ['eoraptor_jst']);
};
|
import isHiragana from '../../src/isHiragana';
describe('isHiragana()', () => {
it('sane defaults', () => {
expect(isHiragana()).toBe(false);
expect(isHiragana('')).toBe(false);
});
it('あ is hiragana', () => expect(isHiragana('あ')).toBe(true));
it('ああ is hiragana', () => expect(isHiragana('ああ')).toBe(true));
it('ア is not hiragana', () => expect(isHiragana('ア')).toBe(false));
it('A is not hiragana', () => expect(isHiragana('A')).toBe(false));
it('あア is not hiragana', () => expect(isHiragana('あア')).toBe(false));
it('ignores long dash in hiragana', () => expect(isHiragana('げーむ')).toBe(true));
});
|
/* **************************************************************
Copyright 2011 Zoovy, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************** */
var myRIA = function() {
var r = {
vars : {
"templates" : [],
"dependAttempts" : 0, //used to count how many times loading the dependencies has been attempted.
"dependencies" : ['store_cart','store_product','store_crm'] //a list of other extensions (just the namespace) that are required for this one to load
},
calls : {
quickAdd : {
init : function(pid,tagObj) {
tagObj = $.isEmptyObject(tagObj) ? {} : tagObj;
tagObj.datapointer = 'atc_'+app.u.unixNow(); //unique datapointer for callback to work off of, if need be.
this.dispatch({'product_id':pid,'quantity':'1'},tagObj);
return 1;
},
dispatch : function(obj,tagObj) {
obj["_cmd"] = "cartItemsAdd"; //cartItemsAddSerialized
obj["_zjsid"] = app.vars.cartID;
obj["_tag"] = tagObj;
app.model.addDispatchToQ(obj,'immutable');
app.calls.cartSet.init({'payment-pt':null}); //nuke paypal token anytime the cart is updated.
}
},//addToCart
}, //calls
callbacks : {
//run when controller loads this extension. Should contain any validation that needs to be done. return false if validation fails.
init : {
onSuccess : function() {
var r = true; //return false if extension won't load for some reason (account config, dependencies, etc).
return r;
},
onError : function() {
//errors will get reported for this callback as part of the extensions loading. This is here for extra error handling purposes.
//you may or may not need it.
app.u.dump('BEGIN app.ext.myRIA.callbacks.init.onError');
}
},
//this is the callback defined to run after extension loads.
startMyProgram : {
onSuccess : function() {
/*
To minimize the footprint on the storefront, the templates are stored in an external html file, loaded via ajax.
If the templates file does not successfully load
*/
var ajaxRequest = app.model.loadRemoteTemplates("templates.html");
ajaxRequest.error(function(){
//the templates not loading is pretty much a catastrophic issue. however, we don't want to throw an error in this case so just hide the carousel.
app.u.dump("ERROR! template file could not load. carousel aborted.");
});
ajaxRequest.success(function(data){
$('<div>').attr('id','remotelyLoadedTemplates').appendTo('body').hide().append(data);
var templateErrors = app.model.loadTemplates(['addToCartTemplate','cartViewer','cartSummaryTemplate','cartViewerProductTemplate','reviewFrmTemplate','subscribeFormTemplate','zCheckoutContainerSpec','chkout-cartSummarySpec','myCheckoutSpec','cartSummaryTotalsSpec','chkout-billAddressSpec','chkout-shipAddressSpec','chkout-shipMethodsSpec','checkout-payOptionsSpec','chkout-orderNotesSpec','checkoutSuccess','billAddressTemplate','shipAddressTemplate','prodViewerTemplate']);
app.calls.refreshCart.init({'callback':'udpateMinicart','extension':'myRIA'},'mutable');
//actually starts the annex process. only occurs if templates are successfully loaded.
var pid = $('#ProductIndexID').val();
if(pid) {
app.ext.store_product.calls.appProductGet.init(pid,{'callback':'commenceAC','extension':'myRIA'});
}
app.model.dispatchThis();
//handles the cart link.
$cartLink = $('#menu-cart');
$cartLink.attr('href','#').unbind(); //disable and unbind any actions on cart link.
$cartLink.click(function(){
app.u.dump("cart link clicked");
app.ext.store_cart.u.showCartInModal('cartViewer');
return false;
});
app.ext.myRIA.u.annexListATC(); //goes through product lists, such as recently viewed and accessories.
app.ext.myRIA.u.annexListCheckbox('.wtab_box'); //goes through checkboxes within the passed selector
$('.price-table :first').hide(); //content would be replaced with product options. may or may not need this line.
})
},
onError : function(responseData,uuid) {
//error handling is a case where the response is delivered (unlike success where datapointers are used for recycling purposes)
app.u.handleErrors(responseData,uuid); //a default error handling function that will try to put error message in correct spot or into a globalMessaging element, if set. Failing that, goes to modal.
}
},
commenceAC : {
onSuccess : function(tagObj) {
var pid = app.data[tagObj.datapointer].pid;
app.u.dump(" -> commence hijack for pid: "+pid);
var $form = $('#kb_form');
app.u.dump(" -> kb_form.length: "+$form.length);
$form.unbind().attr('action','#'); //remove existing action/onsubmit
$form.bind('submit',function(event){
// alert('woot!');
app.ext.myRIA.u.handleAddToCart($form.attr('id'));
return false;
}); //add new submit handler.
$('#product-page-buy-qty').empty().remove(); //get rid of existing quantity input box.
$('<input>').attr({'id':$form.attr('id')+'_product_id','name':'product_id','type':'hidden'}).val(pid).appendTo($form);
//will add options and quantity input box.
$('#add-to-cart-button').before(app.renderFunctions.transmogrify({'id':'something'},'addToCartTemplate',app.data[tagObj.datapointer]))
$('#add-to-cart-button').before($("<div>").attr('id','atcMessaging_'+pid))
$('#kb_form :button').each(function(index){
var $button = $(this);
var buttonText = $button.attr('value');
if(buttonText.toLowerCase() == 'write a review') {
app.u.dump(" -> match on write a review button");
$button.unbind('click').attr('onclick','#'); //unbind wasn't working right.
$button.bind('click',function(event){
event.preventDefault();
app.ext.store_crm.u.showReviewFrmInModal({"pid":pid,"templateID":"reviewFrmTemplate"});
return false;
});
}
})
},
onError : function(responseData,uuid) {
//error handling is a case where the response is delivered (unlike success where datapointers are used for recycling purposes)
app.u.handleErrors(responseData,uuid); //a default error handling function that will try to put error message in correct spot or into a globalMessaging element, if set. Failing that, goes to modal.
}
},
itemAddedToCart : {
onSuccess : function(tagObj) {
app.u.dump('BEGIN app.ext.store_product.callbacks.itemAddedToCart.onSuccess');
$('.atcButton').removeAttr('disabled').removeClass('disabled'); //makes all atc buttons clickable again.
var htmlid = 'atcMessaging_'+app.data[tagObj.datapointer].product1;
$('#atcMessaging_'+app.data[tagObj.datapointer].product1).anymessage({'message':'Item Added','htmlid':htmlid,'uiIcon':'check','timeoutFunction':"$('#"+htmlid+"').slideUp(1000);"});
},
onError : function(responseData,uuid) {
app.u.dump('BEGIN app.ext.store_product.callbacks.init.onError');
$('.atcButton').removeAttr('disabled'); //remove the disabling so users can push the button again, if need be.
$('#atcMessaging_'+app.data[responseData['_rtag'].datapointer].product1).append(app.u.getResponseErrors(responseData))
}
}, //itemAddedToCart
//executed when the cart is changed, such as a zip entered or a country selected.
udpateMinicart : {
onSuccess : function(tagObj) {
var itemCount = app.u.isSet(app.data[tagObj.datapointer].cart['data.item_count']) ? app.data[tagObj.datapointer].cart['data.item_count'] : app.data[tagObj.datapointer].cart['data.add_item_count']
$('#menu-cart').text('My Cart ('+itemCount+')');
},
onError : function(responseData,uuid) {
app.u.handleErrors(responseData,uuid)
}
},
//executed when the cart is changed, such as a zip entered or a country selected.
cartUpdated : {
onSuccess : function(tagObj) {
app.u.dump("BEGIN myRIA.callbacks.cartUpdated.onSuccess");
var itemCount = app.u.isSet(app.data[tagObj.datapointer].cart['data.item_count']) ? app.data[tagObj.datapointer].cart['data.item_count'] : app.data[tagObj.datapointer].cart['data.add_item_count']
// app.u.dump(" -> itemCount: "+itemCount);
$('#menu-cart').text('My Cart ('+itemCount+')');
app.ext.store_cart.u.showCartInModal('cartViewer');
},
onError : function(responseData,uuid) {
app.u.handleErrors(responseData,uuid)
}
}
}, //callbacks
util : {
//for adding items to the cart where qty always = 1 (for the add, can b modified in cart later) and product does NOT have variations/options.
quickATC : function(pid) {
app.u.dump("BEGIN myRIA.u.quickATC");
if(!pid) {}
else {
app.ext.myRIA.calls.quickAdd.init(pid,{'callback':'itemAddedToCart','extension':'myRIA'});
app.calls.refreshCart.init({'callback':'cartUpdated','extension':'myRIA'},'immutable');
app.ext.store_cart.calls.cartShippingMethods.init({},'immutable'); //get shipping methods into memory for quick use.
app.model.dispatchThis('immutable');
}
},
handleAddToCart : function(formID) {
app.u.dump("BEGIN store_product.calls.cartItemsAdd.init")
if(!formID) {
// alert('form id NOT set');
}
else {
var pid = $('#'+formID+'_product_id').val();
if(app.ext.store_product.validate.addToCart(pid)) {
app.ext.store_product.calls.cartItemsAdd.init(formID,{'callback':'itemAddedToCart','extension':'myRIA'});
app.calls.refreshCart.init({'callback':'cartUpdated','extension':'myRIA'},'immutable');
app.ext.store_cart.calls.cartShippingMethods.init({},'immutable'); //get shipping methods into memory for quick use.
app.model.dispatchThis('immutable');
}
else {
$('#'+formID+' .atcButton').removeClass('disabled').removeAttr('disabled');
}
}
return r;
}, //handleAddToCart
annexListCheckbox : function(selector) {
//<input type="hidden" name="quantity:PID" value="1">
//<input type="checkbox" name="product_id:PID" value="1">
$(selector + ' :checkbox').each(function(){
var $checkbox = $(this);
var pid = $checkbox.val();
app.u.dump(" -> PID: "+pid);
$checkbox.attr({'name':'product_id:'+pid,'data-pid':pid}).val(1); //data-pid is kept in case pid is needed again later, it'll be easily accessable.
var $hidden = $("<input>").attr({'name':'quantity:'+pid,'type':'hidden'}).val(1).after($checkbox);
});
}, //annexListCheckbox
annexListATC : function() {
app.u.dump("BEGIN myRIA.u.annexListATC");
$('a').each(function(index){ {
var $link = $(this)
if($link.attr('onclick') && $link.attr('onclick').indexOf('add_to_cart_direct') >= 0) {
// app.u.dump(" MATCH! ");
var pid = $link.attr('onclick').replace(/.*\(|\)/gi,'');
app.u.dump(" -> pid: "+pid);
$link.attr({'href':'#','onclick':''}).unbind();
$link.click(function(){
app.u.dump("Click!");
//if the pid isn't in memory yet, open modal (which will get product data).
if(app.data['appProductGet|'+pid] && $.isEmptyObject(app.data['appProductGet|'+pid]['@variations'])) {
app.ext.myRIA.u.quickATC(pid);
}
//item has variations or isn't in memory yet. catch all. show item in modal.
else {
app.ext.store_product.u.prodDataInModal({'pid':pid,'templateID':'prodViewerTemplate'});
}
return false;
});
app.ext.store_product.calls.appProductGet.init(pid);
}
}})
app.model.dispatchThis();
}
} //util
} //r object.
return r;
}
|
Package.describe({
summary: "Send email messages",
version: "1.0.10"
});
Npm.depends({
// Pinned at older version. 0.1.16+ uses mimelib, not mimelib-noiconv which is
// much bigger. We need a better solution.
mailcomposer: "0.1.15",
simplesmtp: "0.3.10",
"stream-buffers": "0.2.5"});
Package.onUse(function (api) {
api.use('underscore', 'server');
api.export(['Email', 'EmailInternals'], 'server');
api.export('EmailTest', 'server', {testOnly: true});
api.addFiles('email.js', 'server');
});
Package.onTest(function (api) {
api.use('email', 'server');
api.use('tinytest');
api.addFiles('email_tests.js', 'server');
});
|
const jwt = require('jsonwebtoken-promisified');
const appSecret = process.env.APP_SECRET || 'update-for-spotify-users';
module.exports = {
sign(user) {
const payload = {
id: user._id,
roles: user.roles,
spotify: user._spotifyId
};
return jwt.signAsync(payload, appSecret);
},
verify(token) {
return jwt.verifyAsync(token, appSecret);
}
};
|
Storage.Prototype = function() {};
Storage.Prototype.prototype.initDefaults = function(db, store) {
this.db = (typeof db === "string")?db:'storage';
this.store = (typeof store === "string")?store:null;
}
Storage.Prototype.prototype.init = function(cfg) {
if (this.hasType(cfg, 'db', 'string')) {
this.db = cfg.db;
}
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.initRequest(req, cfg);});
return req;
};
Storage.Prototype.prototype.initRequest = function(req, cfg) {
if (cfg) {
if (req.ref.hasProperty(cfg, 'version') && req.ref.versionString(cfg)) {
if (req.ref.dbVersion() < cfg.version) {
this.changeRequest(req, cfg);
} else {
req.finish();
}
} else {
req.abort(2, 'version missing or not a number');
}
} else {
req.finish();
}
};
Storage.Prototype.prototype.clear = function(store) {
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.clearRequest(req, req.ref.storeValue(store))});
return req;
};
Storage.Prototype.prototype.get = function(key, store) {
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.getRequest(req, key, req.ref.storeValue(store))});
return req;
};
Storage.Prototype.prototype.delete = function(key, store) {
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.deleteRequest(req, key, req.ref.storeValue(store))});
return req;
};
Storage.Prototype.prototype.list = function(store) {
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.listRequest(req, req.ref.storeValue(store))});
return req;
};
Storage.Prototype.prototype.put = function(obj, key, store) {
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.putRequest(req, obj, key, req.ref.storeValue(store))});
return req;
};
Storage.Prototype.prototype.version = function() {
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.versionRequest(req)});
return req;
}
Storage.Prototype.prototype.versionRequest = function(req) {
req.finish(req.ref.dbVersion());
};
/*
Storage.Prototype.prototype.deleteDatabase = function() {
var req = new Storage.Request(this);
req.asyncCall(function() {req.ref.deleteDatabaseRequest(req)});
return req;
}*/
/** utilities **/
Storage.Prototype.prototype.isKey = function(key) {
if (typeof key != 'string') {
return false;
}
return true;
}
Storage.Prototype.prototype.isStoreName = function(store) {
return this.isKey(store);
}
Storage.Prototype.prototype.hasProperty = function(hash, prop) {
return (hash instanceof Object && hash.hasOwnProperty(prop))?true:false;
}
Storage.Prototype.prototype.hashValue = function(hash, key, def) {
if (hash instanceof Object && hash.hasOwnProperty(key)) {
return hash[key];
}
return def;
};
Storage.Prototype.prototype.storeValue = function(store) {
return typeof store === "string"?store:this.store;
}
Storage.Prototype.prototype.versionString = function(hash) {
var vers = this.hashValue(hash, 'version', false);
return (typeof vers === "number" && vers > 1)?true:false;
}
Storage.Prototype.prototype.hasType = function(hash, key, type) {
return typeof this.hashValue(hash, key, false) === type?true:false;
}
Storage.Prototype.prototype.hasArray = function(hash, key) {
return this.hashValue(hash, key, false) instanceof Array?true:false;
}
Storage.Prototype.prototype.jsonParse = function(str) {
return JSON.parse(str);
};
Storage.Prototype.prototype.stringify = function(obj) {
return JSON.stringify(obj);
};
Storage.Prototype.prototype.log = function(msg) {
if (Storage.log) {
console.log(msg);
}
};
Storage.Prototype.prototype.manageStores = function(req, cfg, env, key, method) {
if (req.ref.hasArray(cfg, key)) {
for(i=0; i<cfg[key].length; i++) {
method(req, cfg[key][i], env);
}
}
};
Storage.Prototype.prototype.createStores = function(req, cfg, env) {
req.ref.manageStores(req, cfg, env, 'stores', req.ref.createStoreStatement);
};
Storage.Prototype.prototype.deleteStores = function(req, cfg, env) {
req.ref.manageStores(req, cfg, env, 'deleteStores', req.ref.deleteStoreStatement);
}; |
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
import { includes } from "./utils/array";
var OUTSIDE_ANGULAR_EVENTS = ['mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
/** The base frameworks, eg React & Angular 2, override this bean with implementations specific to their requirement. */
var VanillaFrameworkOverrides = /** @class */ (function () {
function VanillaFrameworkOverrides() {
this.isOutsideAngular = function (eventType) { return includes(OUTSIDE_ANGULAR_EVENTS, eventType); };
}
// for Vanilla JS, we use simple timeout
VanillaFrameworkOverrides.prototype.setTimeout = function (action, timeout) {
window.setTimeout(action, timeout);
};
// for Vanilla JS, we just add the event to the element
VanillaFrameworkOverrides.prototype.addEventListener = function (element, type, listener, useCapture) {
element.addEventListener(type, listener, useCapture);
};
// for Vanilla JS, we just execute the listener
VanillaFrameworkOverrides.prototype.dispatchEvent = function (eventType, listener) {
listener();
};
return VanillaFrameworkOverrides;
}());
export { VanillaFrameworkOverrides };
|
import {
EXPAND_HISTORY_SET,
PRESENT_HISTORY_VIDEO_PLAYER,
} from 'app/configs+constants/ActionTypes';
import * as VideoPermissionsUtils from 'app/utility/VideoPermissionsUtils';
import * as Analytics from 'app/services/Analytics';
import * as CollapseExpandHistoryActions from 'app/redux/shared_actions/CollapseExpandHistoryActions';
export const expandCard = (setID) => (dispatch, getState) => {
const state = getState();
logExpandCardAnalytics(setID, state);
dispatch(CollapseExpandHistoryActions.expandCard(setID));
};
export const presentWatchVideo = (setID, videoFileURL) => (dispatch, getState) => {
VideoPermissionsUtils.checkWatchVideoPermissions().then(() => {
const state = getState();
Analytics.setCurrentScreen('history_watch_video');
logWatchVideoAnalytics(setID, state);
dispatch({
type: PRESENT_HISTORY_VIDEO_PLAYER,
setID: setID,
videoFileURL: videoFileURL
});
}).catch(() => {});
};
const logWatchVideoAnalytics = (setID, state) => {
Analytics.logEventWithAppState('watch_video', {
is_working_set: false,
from_collapsed_card: true,
}, state);
};
const logExpandCardAnalytics = (setID, state) => {
Analytics.logEventWithAppState('expand_card', {
set_id: setID
}, state);
};
|
'use strict';
/*
* Defining the Package
*/
var config = require('meanio').loadConfig();
var socketio = require('socket.io');
var socketioJwt = require('socketio-jwt');
var Module = require('meanio').Module;
var Io = new Module('io');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
Io.register(function(app, http, auth, database) {
var sockets = null;
Io.getSocket = function(namespace) {
if(!sockets) {
sockets = socketio.listen(http);
}
if(!namespace) {
return sockets;
}
return sockets.of(namespace);
}
Io.socketAuth = function(socket) {
socket.use(socketioJwt.authorize({
secret: config.secret,
handshake: true
}));
socket.use(function(data, accept) {
data.user = JSON.parse(decodeURI(data.decoded_token));
accept();
});
};
Io.aggregateAsset('js', '../lib/socket.io-client/socket.io.js');
return Io;
});
|
// @inheritedComponent Transition
import React from 'react';
import PropTypes from 'prop-types';
import Transition from 'react-transition-group/Transition';
import withTheme from '../styles/withTheme';
import { reflow, getTransitionProps } from '../transitions/utils';
function getScale(value) {
return `scale(${value}, ${value ** 2})`;
}
const styles = {
entering: {
opacity: 1,
transform: getScale(1),
},
entered: {
opacity: 1,
// Use translateZ to scrolling issue on Chrome.
transform: `${getScale(1)} translateZ(0)`,
},
};
/**
* The Grow transition is used by the [Tooltip](/demos/tooltips/) and
* [Popover](/utils/popover/) components.
* It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
*/
class Grow extends React.Component {
componentWillUnmount() {
clearTimeout(this.timer);
}
handleEnter = node => {
const { theme, timeout } = this.props;
reflow(node); // So the animation always start from the start.
const { duration: transitionDuration, delay } = getTransitionProps(this.props, {
mode: 'enter',
});
let duration = 0;
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
this.autoTimeout = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [
theme.transitions.create('opacity', {
duration,
delay,
}),
theme.transitions.create('transform', {
duration: duration * 0.666,
delay,
}),
].join(',');
if (this.props.onEnter) {
this.props.onEnter(node);
}
};
handleExit = node => {
const { theme, timeout } = this.props;
let duration = 0;
const { duration: transitionDuration, delay } = getTransitionProps(this.props, {
mode: 'exit',
});
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
this.autoTimeout = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [
theme.transitions.create('opacity', {
duration,
delay,
}),
theme.transitions.create('transform', {
duration: duration * 0.666,
delay: delay || duration * 0.333,
}),
].join(',');
node.style.opacity = '0';
node.style.transform = getScale(0.75);
if (this.props.onExit) {
this.props.onExit(node);
}
};
addEndListener = (_, next) => {
if (this.props.timeout === 'auto') {
this.timer = setTimeout(next, this.autoTimeout || 0);
}
};
render() {
const { children, onEnter, onExit, style: styleProp, theme, timeout, ...other } = this.props;
const style = {
...styleProp,
...(React.isValidElement(children) ? children.props.style : {}),
};
return (
<Transition
appear
onEnter={this.handleEnter}
onExit={this.handleExit}
addEndListener={this.addEndListener}
timeout={timeout === 'auto' ? null : timeout}
{...other}
>
{(state, childProps) => {
return React.cloneElement(children, {
style: {
opacity: 0,
transform: getScale(0.75),
...styles[state],
...style,
},
...childProps,
});
}}
</Transition>
);
}
}
Grow.propTypes = {
/**
* A single child content element.
*/
children: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
/**
* If `true`, show the component; triggers the enter or exit animation.
*/
in: PropTypes.bool,
/**
* @ignore
*/
onEnter: PropTypes.func,
/**
* @ignore
*/
onExit: PropTypes.func,
/**
* @ignore
*/
style: PropTypes.object,
/**
* @ignore
*/
theme: PropTypes.object.isRequired,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
*
* Set to 'auto' to automatically calculate transition time based on height.
*/
timeout: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }),
PropTypes.oneOf(['auto']),
]),
};
Grow.defaultProps = {
timeout: 'auto',
};
Grow.muiSupportAuto = true;
export default withTheme()(Grow);
|
/**
* @flow
*/
import React, { Component } from 'react';
export type Props = {
foo: string
}
/**
* This is a Flow class component
*/
export default class FlowComponent extends Component<Props> {
render() {
return <h1>Hello world</h1>;
}
foo(a: string): string {
return a;
}
bar(a: string): string {
return a;
}
}
|
/**
* Created by gaginho on 08.07.17.
*/
|
const throttle = require('lodash.throttle')
function emitSocketProgress (uploader, progressData, file) {
const { progress, bytesUploaded, bytesTotal } = progressData
if (progress) {
uploader.uppy.log(`Upload progress: ${progress}`)
uploader.uppy.emit('upload-progress', file, {
uploader,
bytesUploaded,
bytesTotal,
})
}
}
module.exports = throttle(emitSocketProgress, 300, {
leading: true,
trailing: true,
})
|
'use strict';
var should = require('should'),
request = require('supertest'),
path = require('path'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Song = mongoose.model('Song'),
express = require(path.resolve('./config/lib/express'));
/**
* Globals
*/
var app,
agent,
credentials,
user,
song;
/**
* Song routes tests
*/
describe('Song Admin CRUD tests', function () {
before(function (done) {
// Get application
app = express.init(mongoose);
agent = request.agent(app);
done();
});
beforeEach(function (done) {
// Create user credentials
credentials = {
usernameOrEmail: 'username',
password: 'M3@n.jsI$Aw3$0m3'
};
// Create a new user
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
roles: ['user', 'admin'],
username: credentials.usernameOrEmail,
password: credentials.password,
provider: 'local'
});
// Save a user to the test db and create new song
user.save(function () {
song = {
title: 'Song Title',
defaultKey: 'A',
content: 'Song Content'
};
done();
});
});
it('admins should be able to update a song that a different user created', function (done) {
// Create temporary user creds
var _creds = {
usernameOrEmail: 'songowner',
password: 'M3@n.jsI$Aw3$0m3'
};
// Create user that will create the Song
var _songOwner = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'temp@test.com',
username: _creds.usernameOrEmail,
password: _creds.password,
provider: 'local',
roles: ['admin', 'user']
});
_songOwner.save(function (err, _user) {
// Handle save error
if (err) {
return done(err);
}
// Sign in with the user that will create the Song
agent.post('/api/auth/signin')
.send(_creds)
.expect(200)
.end(function (signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
// Get the userId
var userId = _user._id;
// Save a new song
agent.post('/api/songs')
.send(song)
.expect(200)
.end(function (songSaveErr, songSaveRes) {
// Handle song save error
if (songSaveErr) {
return done(songSaveErr);
}
// Set assertions on new song
(songSaveRes.body.title).should.equal(song.title);
should.exist(songSaveRes.body.user);
should.equal(songSaveRes.body.user._id, userId);
// now signin with the test suite user
agent.post('/api/auth/signin')
.send(credentials)
.expect(200)
.end(function (err, res) {
// Handle signin error
if (err) {
return done(err);
}
// Update song title
song.title = 'New Title';
// Update an existing song
agent.put('/api/songs/' + songSaveRes.body._id)
.send(song)
.expect(200)
.end(function (songUpdateErr, songUpdateRes) {
// Handle song update error
if (songUpdateErr) {
return done(songUpdateErr);
}
// Set assertions
(songUpdateRes.body._id).should.equal(songSaveRes.body._id);
(songUpdateRes.body.title).should.match('New Title');
// Call the assertion callback
done();
});
});
});
});
});
});
it('admins should be able to delete a song that a different user created', function (done) {
// Create temporary user creds
var _creds = {
usernameOrEmail: 'songowner',
password: 'M3@n.jsI$Aw3$0m3'
};
// Create user that will create the Song
var _songOwner = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'temp@test.com',
username: _creds.usernameOrEmail,
password: _creds.password,
provider: 'local',
roles: ['admin', 'user']
});
_songOwner.save(function (err, _user) {
// Handle save error
if (err) {
return done(err);
}
// Sign in with the user that will create the Song
agent.post('/api/auth/signin')
.send(_creds)
.expect(200)
.end(function (signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
// Get the userId
var userId = _user._id;
// Save a new song
agent.post('/api/songs')
.send(song)
.expect(200)
.end(function (songSaveErr, songSaveRes) {
// Handle song save error
if (songSaveErr) {
return done(songSaveErr);
}
// Set assertions on new song
(songSaveRes.body.title).should.equal(song.title);
should.exist(songSaveRes.body.user);
should.equal(songSaveRes.body.user._id, userId);
// now signin with the test suite user
agent.post('/api/auth/signin')
.send(credentials)
.expect(200)
.end(function (err, res) {
// Handle signin error
if (err) {
return done(err);
}
// Delete the existing song
agent.delete('/api/songs/' + songSaveRes.body._id)
.send(song)
.expect(200)
.end(function (songDeleteErr, songDeleteRes) {
// Handle song error error
if (songDeleteErr) {
return done(songDeleteErr);
}
// Set assertions
(songDeleteRes.body._id).should.equal(songSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
});
});
afterEach(function (done) {
User.remove().exec(function () {
Song.remove().exec(done);
});
});
});
|
/**
* Defines the main routes in the application.
* The routes you see here will be anchors '#/' unless specifically configured otherwise.
*/
define(['./app'], function (app) {
'use strict';
app.config([
'$routeProvider', function($routeProvider) {
return $routeProvider.when('/', {
redirectTo: '/user'
}).when('/user', {
templateUrl: 'ui/views/users/user.html'
/*
}).when('/ui/typography', {
templateUrl: 'ui/views/ui/typography.html'
}).when('/ui/buttons', {
templateUrl: 'ui/views/ui/buttons.html'
}).when('/ui/icons', {
templateUrl: 'ui/views/ui/icons.html'
}).when('/ui/grids', {
templateUrl: 'ui/views/ui/grids.html'
}).when('/ui/widgets', {
templateUrl: 'ui/views/ui/widgets.html'
}).when('/ui/components', {
templateUrl: 'ui/views/ui/components.html'
}).when('/ui/timeline', {
templateUrl: 'ui/views/ui/timeline.html'
}).when('/ui/pricing-tables', {
templateUrl: 'ui/views/ui/pricing-tables.html'
}).when('/forms/elements', {
templateUrl: 'ui/views/forms/elements.html'
}).when('/forms/layouts', {
templateUrl: 'ui/views/forms/layouts.html'
}).when('/forms/validation', {
templateUrl: 'ui/views/forms/validation.html'
}).when('/forms/wizard', {
templateUrl: 'ui/views/forms/wizard.html'
}).when('/tables/static', {
templateUrl: 'ui/views/tables/static.html'
}).when('/tables/responsive', {
templateUrl: 'ui/views/tables/responsive.html'
}).when('/tables/dynamic', {
templateUrl: 'ui/views/tables/dynamic.html'
}).when('/charts/others', {
templateUrl: 'ui/views/charts/charts.html'
}).when('/charts/morris', {
templateUrl: 'ui/views/charts/morris.html'
}).when('/charts/flot', {
templateUrl: 'ui/views/charts/flot.html'
}).when('/mail/inbox', {
templateUrl: 'ui/views/mail/inbox.html'
}).when('/mail/compose', {
templateUrl: 'ui/views/mail/compose.html'
}).when('/mail/single', {
templateUrl: 'ui/views/mail/single.html'
}).when('/pages/features', {
templateUrl: 'ui/views/pages/features.html'
}).when('/pages/signin', {
templateUrl: 'ui/views/pages/signin.html'
}).when('/pages/signup', {
templateUrl: 'ui/views/pages/signup.html'
}).when('/pages/lock-screen', {
templateUrl: 'ui/views/pages/lock-screen.html'
}).when('/pages/profile', {
templateUrl: 'ui/views/pages/profile.html'
}).when('/404', {
templateUrl: 'ui/views/pages/404.html'
}).when('/pages/500', {
templateUrl: 'ui/views/pages/500.html'
}).when('/pages/blank', {
templateUrl: 'ui/views/pages/blank.html'
}).when('/pages/invoice', {
templateUrl: 'ui/views/pages/invoice.html'
}).when('/tasks', {
templateUrl: 'ui/views/tasks/tasks.html'
}).when('/hello', {
templateUrl: 'ui/views/helloworld/helloworld.html'
}).when('/xtk', {
templateUrl: 'ui/views/xtk/xtk.html'
*/
}).when('/queryprotocol',{
templateUrl: 'ui/views/queryprotocol/queryprotocol.html'
}).when('/PlateDesign',{
templateUrl: 'ui/views/PlateDesign/PlateDesign.html'
}).otherwise({
redirectTo: '/404'
});
}
]);
}); |
var cli = require("commander");
var async = require("async");
var inputData = "";
var note = require("../core/note");
var db = require("../db");
var log = require("../log");
cli
.option("-d, --db [dbFile]", "The path to a database file. If omitted, it will use $HOME/.sn.")
.option("-t, --tags <tags...>", "Tags associated with the data. Seperated by comma (,)")
.option("-b, --binary", "Flag. Use it if input data is binary.")
.option("-p, --password [password]", "The note will be protected by a password")
.option("--title <title>", "The title of the note.")
.parse(process.argv);
var d = db.get(cli.db);
var rl = require("readline-sync");
var params = {};
var pwd = "";
var W = require("stream").Writable;
log.debug(cli.args, process.stdin.isTTY);
async.series([
function(scb) {
log.debug("init db");
require("./comm").initDb(cli.db, scb);
},
function(scb) {
if (cli.args.length > 0) {
inputData = cli.args[0];
scb();
} else {
if (!process.stdin.isTTY) {
log.debug("PIPE mode for stdio.");
var bufferArr = [];
process.stdin.resume();
process.stdin.on("data", function(b, e) {
// if (cli.binary) {
// bufferArr.push(b);
// } else {
// bufferArr.push(b.toString());
// }
bufferArr.push(b);
});
process.stdin.on("end", function() {
// if (cli.binary) {
// inputData = Buffer.concat(bufferArr);
// } else {
// inputData = bufferArr.join("");
// }
inputData = Buffer.concat(bufferArr);
scb();
});
process.stdin.on("error", function(e) {
scb(e);
});
}else{
var editor=require("./editor");
editor.edit("",function(err,d){
if (!d){
scb(new Error("User aborted."));
}else{
inputData=d;
scb(err);
}
});
}
}
},
function(scb) { //check pwd
if (cli.password) {
if (cli.password === true) {
pwd = rl.question("Please enter password: ", {
hideEchoBack: true
});
scb();
} else {
pwd = cli.password;
scb();
}
} else {
scb();
}
},
function(scb) {
if (pwd) {
var aes = require("../encryption/aes");
inputData = aes.encrypt(inputData, pwd);
params.ispassword = 1;
}
scb();
},
function(scb) {
params.data = inputData
if (cli.binary) {
params.isblob = 1;
}
if (cli.title) {
params.title = cli.title
}
var tags = cli.tags;
async.waterfall([
function(sscb) {
log.debug(params);
note.new(d, params, sscb);
},
function(id, sscb) {
console.log("ID: ", id);
if (tags) {
note.addTags(d, id, tags.split(","), sscb);
} else {
sscb();
}
}
], scb);
}
], function(err) {
if (err) {
console.log(err);
}
});
|
import { RECEIVE_FIELDS, PERSIST_FIELDS } from '../actions'
export default (state = { fields: [] }, action) => {
switch (action.type) {
case RECEIVE_FIELDS:
case PERSIST_FIELDS:
return Object.assign({}, state, action.fieldData)
default:
return state
}
} |
/**
* @param {Array=} optElements
* @constructor
*/
function Queue(optElements) {
if (optElements instanceof Array) {
this.items = optElements;
} else {
this.items = [];
}
this.length = this.items.length;
}
/**
* @param {*} item
*/
Queue.prototype.enqueue = function(item) {
this.length += 1;
return this.items.push(item);
};
/**
* @return {*}
*/
Queue.prototype.dequeue = function(item) {
if (this.length > 0 ) {
this.length -= 1;
}
return this.items.shift();
};
app.get('/insert-task/:data', function(req, res, next) {
var data = {
timestamp: Date.now(),
payload: req.params.data
};
tasks.enqueue(data);
next();
});
app.get('/process-taks', function(req, res, next) {
var task = tasks.dequeue();
service.save(task.payload);
next();
});
|
import thunk from 'redux-thunk'
import {createAction, handleActions} from 'redux-actions'
import {createStore, applyMiddleware, compose} from 'redux'
import lock from '../components/lock'
import {fail} from './error-handle'
import _ from 'lodash'
let composeEnhancers = compose
if (process.env.NODE_ENV === 'development' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) {
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
}
const middlewares = [thunk]
export function configStore(one) {
return createStore(
one,
composeEnhancers(applyMiddleware(...middlewares))
)
}
export function standardListReducer(types) {
if (_.result(types, 'length') !== 3) throw new Error('必须提供 3 种 actionType')
return handleActions({
[types[0]]: (state, action) => ({
...state,
loading: true,
}),
[types[1]]: (state, action) => ({
...state,
error: null,
loading: false,
meta: {
...action.payload.res.meta,
},
objects: [
...action.payload.res.objects,
],
params: {
...action.payload.params,
},
}),
[types[2]]: (state, action) => ({
...state,
error: {
...action.payload,
},
loading: false,
}),
}, {
error: null,
loading: false,
meta: null,
objects: null,
params: null,
})
}
export function standardListActionCreator(types, io, path) {
if (_.result(types, 'length') !== 3) throw new Error('必须提供 3 种 actionType')
return function(req = {}) {
const {
locking,
params,
} = req
return function(dispatch, getState) {
let one = getState()
if (path != null) {
one = _.result(one, path)
}
if (one['loading']) return
const unlock = lock(locking)
dispatch(createAction(types[0])(params))
return io(params)
.then(res => {
unlock()
dispatch(createAction(types[1])({
params,
res: res.data,
}))
})
.catch(err => {
unlock()
dispatch(createAction(types[2])(err))
fail(err)
})
}
}
}
|
var assert = require('assert')
, should = require('chai').should();
|
define(['lodash', './action', 'actors/actor', 'util/vec2d'], function (_, Action, Actor, Vec2d) {
const PROPS = ['mass'],
NAME = 'newton-gravity',
G = 6.674e-11;
/**
*
* @constructor
* @this {NewtonianGravity}
*
*/
function NewtonianGravity(opts = {}) {
Action.call(this, NAME, PROPS, opts);
Action.Registry.register(NewtonianGravity);
}
NewtonianGravity.prototype = Object.create(Action.prototype);
NewtonianGravity.prototype.constructor = NewtonianGravity;
/**
* NewtonianGravity#run( data )
*
* Computes the forces on each actor in data.actors, and then assigns the
* acceleration to the selected {Actor}
*
* @param {object} data The data to pass; must have data.actors, an array of {Actor} elements
*/
NewtonianGravity.prototype.run = function (data) {
// dpi/dt = (µj*mi)(r^-2) * rhat
let _G = this.options.G || G;
if (_.isNil(data) || _.isNil(data.actors)) {
console.log('Empty Actor set to compute; Ignoring...');
return {};
} else if (!_.isArray(data.actors)) {
console.log('data.actors not an array of actors; Ignoring...');
return {};
}
for (let a in data.actors) {
let s = new Vec2d(),
ah = a.hashcode();
for (let b in data.actors) {
if (b.hashcode() === ah) {
continue;
}
let muj = _G * b.mass,
dis = b.pos.subtract(a.pos);
let c = (muj) / (dis.normSquared()),
rhat = dis.normalize();
s.add(rhat.scale(c, true), true);
}
a.accelerate(s);
}
return ret;
};
return NewtonianGravity;
});
|
class CameraControl {
constructor(args = {}) {
this.onClick = args.onClick;
}
onAdd(map) {
this._map = map;
this._container = document.createElement('div');
this._container.className = 'mapboxgl-ctrl mapboxgl-ctrl-group';
this._button = document.createElement('button');
this._button.onclick = () => {
this.onClick(this._map.getCanvas());
};
this._button.className = `mapbox-gl-draw_ctrl-draw-btn fa fa-camera`;
this._container.appendChild(this._button);
return this._container;
}
onRemove() {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
}
}
export default CameraControl
|
var searchData=
[
['dawson',['Dawson',['../_faddeeva__c_8c.html#a9f9b8aa6d1143a656c0f27d1a6828e2e',1,'Dawson(double x): Faddeeva_c.c'],['../_faddeeva__c_8c.html#a3f435476f41c8cfeb7f3a9a379dc6130',1,'Dawson(cmplx z, double relerr): Faddeeva_c.c']]]
];
|
/* global describe, it */
import { expect } from 'chai';
import Types from '../src/Types';
import createModel from '../src/createModel';
import createCollection from '../src/createCollection';
import isModel from '../src/isModel';
import isCollection from '../src/isCollection';
describe('createCollection', function () {
it('creates Collection class', function () {
const Person = createModel({
name: Types.string.isRequired
});
const People = createCollection(Person);
const people = new People();
expect(people).to.be.instanceof(People);
});
it('creates Collection with Model', function () {
const Person = createModel({
name: Types.string.isRequired
});
const People = createCollection(Person);
const people = new People([
{ name: 'Harry' },
new Person({ name: 'Hermione' }),
// { name: 'Hermione' },
{ name: 'Ron' }
]);
expect(people).to.be.instanceof(People);
expect(isCollection(people)).to.eql(true);
// first
expect(isModel(people.at(0))).to.eql(true);
expect(people.at(0).name).to.eql('Harry');
// second
expect(isModel(people.at(1))).to.eql(true);
expect(people.at(1).name).to.eql('Hermione');
// third
expect(isModel(people.at(2))).to.eql(true);
expect(people.at(2).name).to.eql('Ron');
});
it('checks with multiple collection instances', function () {
const Person = createModel({
name: Types.string.isRequired
});
const People = createCollection(Person);
const people1 = new People([
{ name: 'Harry' },
{ name: 'Hermione' },
{ name: 'Ron' }
]);
const people2 = new People([
{ name: 'A' },
{ name: 'B' },
{ name: 'C' }
]);
expect(people1.at(0).name).to.eql('Harry');
expect(people1.at(1).name).to.eql('Hermione');
expect(people1.at(2).name).to.eql('Ron');
expect(people2.at(0).name).to.eql('A');
expect(people2.at(1).name).to.eql('B');
expect(people2.at(2).name).to.eql('C');
});
it('creates collection with methods', function () {
const Person = createModel({
name: Types.string.isRequired
});
const People = createCollection(Person, {
findAt(n) {
return this.at(n);
}
});
const people = new People([
{ name: 'Fahad' },
{ name: 'Blah' },
{ name: 'Yo' }
]);
expect(people.findAt).to.be.a('function');
expect(people.findAt(1).name).to.eql('Blah');
});
it('throws error on conflicting method', function () {
const Person = createModel({
name: Types.string.isRequired
});
const People = createCollection(Person, {
at(n) {
return this.at(n);
}
});
function getPeople() {
new People([]); // eslint-disable-line
}
expect(getPeople).to.throw(/conflicting method name: at/);
});
it('listens for self changes', function () {
const Person = createModel({
name: Types.string.isRequired
});
const People = createCollection(Person);
const people = new People([
{ name: 'Harry' }
]);
let changeCounter = 0;
const cancelListener = people.on('change', function () {
changeCounter++;
});
people.push(new Person({ name: 'Ron' }));
people.push(new Person({ name: 'Hermione' }));
expect(changeCounter).to.eql(2);
cancelListener();
people.push(new Person({ name: 'Luna' }));
expect(changeCounter).to.eql(2);
});
it('listens for child-model changes', function () {
const Person = createModel({
name: Types.string.isRequired
}, {
setName(name) {
this.name = name;
}
});
const People = createCollection(Person);
const people = new People([
{ name: 'Harry' },
{ name: 'Ron' },
{ name: 'Hermione' }
]);
let changeCounter = 0;
const cancelListener = people.on('change', function () {
changeCounter++;
});
const hermione = people.at(2);
hermione.setName('Hermione Granger');
hermione.setName('Hermione Granger-Weasley');
expect(changeCounter).to.eql(2);
cancelListener();
people.push(new Person({ name: 'Luna' }));
expect(changeCounter).to.eql(2);
});
it('listens for child-model destroys', function () {
const Person = createModel({
name: Types.string.isRequired
}, {
setName(name) {
this.name = name;
}
});
const People = createCollection(Person);
const people = new People([
{ name: 'Harry' },
{ name: 'Ron' },
{ name: 'Hermione' }
]);
let changeCounter = 0;
const cancelListener = people.on('change', function () {
changeCounter++;
});
const hermione = people.at(2);
hermione.destroy();
expect(changeCounter).to.eql(1);
expect(people.length).to.eql(2);
expect(people.at(0).name).to.eql('Harry');
expect(people.at(1).name).to.eql('Ron');
cancelListener();
});
it('applies initializers', function () {
const Person = createModel({
name: Types.string.isRequired
});
function initializer(collection) {
collection.push(new Person({
name: 'Initializer'
}));
}
const People = createCollection(Person, {}, [
initializer
]);
const people = new People();
expect(people.at(0).name).to.eql('Initializer');
});
});
|
var layout = {
div: document.createElement('div'),
content: document.createElement('div'),
}
function renderIndex(){
layout.div.className = 'bodyDiv';
layout.content.className = 'contentDiv';
document.body.appendChild(layout.div);
layout.div.appendChild(layout.content);
}
function makeCell(){
var cell = document.createElement('div');
cell.className = 'ingredientDiv';
layout.content.appendChild(cell);
return cell;
}
function divCell(target){
var divide = document.createElement('div');
divide.className = 'innerDiv';
target.appendChild(divide);
return divide;
}
function renderIng(ingredientID){
var img = document.createElement('img');
img.setAttribute('src', ingredientID.image);
if (!ingredientID.image){img.setAttribute('src', 'img/missing.jpg');}
img.className = 'ingIcon';
var cell = makeCell();
var idCont = divCell(cell);
var title = document.createElement('p');
title.textContent = ingredientID.ingName;
title.className = 'ingTitle';
idCont.appendChild(img);
idCont.appendChild(title);
var delCont = divCell(cell);
var delButton = document.createElement('img');
delButton.className = 'delButton';
delButton.setAttribute('src', 'img/delIcon.png');
delButton.addEventListener('click', function(){
layout.content.removeChild(cell);
delIngredient(ingredientID.ingName);
})
delCont.appendChild(delButton);
imgListener(img, ingredientID, cell);
}
function imgListener(img, ingredientID, cell){
var imgOpen = false;
var igmEl;
var subEl;
img.addEventListener('click', function(){
if (!imgOpen){
imgOpen = true;
imgEl = document.createElement('input');
imgEl.type = 'text';
imgEl.value = 'Enter ' + ingredientID.ingName + ' image location.';
cell.appendChild(imgEl);
subEl = document.createElement('input')
subEl.setAttribute('type', 'submit');
subEl.setAttribute('value', 'Submit');
subEl.addEventListener('click', function(){
ingredientID.image = imgEl.value
imgEl.value = '';
updateIngredients();
refreshIndex();
})
cell.appendChild(subEl);
} else {
cell.removeChild(subEl);
cell.removeChild(imgEl);
imgOpen = false;
}
})
}
function refreshIndex(){
if(layout.div.childNodes[0]){layout.div.removeChild(layout.content);}
layout.content = document.createElement('div');
renderIndex();
ingArray.forEach(function(ingID){
renderIng(ingID);
})
}
// refreshIndex();
|
var i = 0;
function start($,i){
var event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window, 1, 292, 337, 292, 337, false, false, false, false, 0, null);
var time = 80;
if( document.getElementsByClassName('reaction-time-test view-splash').length > 0 ){
$('.reaction-time-test').dispatchEvent(event);
}
if( document.getElementsByClassName('reaction-time-test view-result').length > 0 ){
$('.reaction-time-test').dispatchEvent(event);
}
if( document.getElementsByClassName('reaction-time-test view-go').length > 0 ){
$('.reaction-time-test').dispatchEvent(event);
var time = 700;
i++;
}
setTimeout(function(){
if(i<5){
start($,i);
}
},time);
}
start($,i);
|
version https://git-lfs.github.com/spec/v1
oid sha256:cd25bc7cc458f5674ed58aa43944d0a08754a12e80989f9c1de9411627b76ab4
size 4216
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[2],{"045598f930547feb805f":function(f,n,c){},"735d21ff8fd0131f1fb5":function(f,n,c){},"7b90ca457552f1f8e532":function(f,n,c){},"99ceadf9884fb390f015":function(f,n,c){},ca73ec2dff1d1b6b77b6:function(f,n,c){}}]); |
import React, { Component, StyleSheet, PropTypes, View } from 'react-native';
export default class Body extends Component {
static propTypes = {
children: PropTypes.node.isRequired
};
render() {
const { theme, children } = this.props;
return (
<View style={ styles.container }>
{children}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 16,
paddingBottom: 16
}
});
|
var MongoClient = require('mongodb').MongoClient
var WebSocketServer = require('websocket').server;
module.app = {};
module.app.settings =
{
mongodburl: 'mongodb://localhost:27017/timertest'
}
module.exports.set = function(key,val){
module.app.settings[key] = val;
}
module.exports.start = function(server){
createApplication(server);
return module.app.wsServer;
}
function createApplication(server){
// Create an object for the websocket
module.app.wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
// Create a callback to handle each connection request
module.app.wsServer.on('request', module.exports.onConnectionRequest);
}
module.exports.onConnectionRequest = function(req){
var connection = req.accept();
connection.on('message', function(message){onMessageRecieved(connection,message)});
}
function onMessageRecieved(connection, message){
if (message.type === 'utf8')
{
if(!IsJsonString(message.utf8Data)){
connection.close(); // Not JSON
}
var messageObj = JSON.parse(message.utf8Data);
if(messageObj.type && messageObj.type == 1){
module.exports.addPageVisit(messageObj, function(res)
{
connection.sendUTF(JSON.stringify({result:res}));
});
}
}
}
module.exports.addPageVisit = function(messageObj, callback){
withDb(function(err, db) {
if(err)
console.log("Error:" + err);
var collection = db.collection('pagevisists');
collection.insert(
{
url : messageObj.url,
timestamp : messageObj.timestamp,
uid : messageObj.uid
},
function(err, result) {
if(err){
console.log(err)
callback(-1);
db.close();
return;
}
callback(1);
db.close();
});
});
}
module.exports.getVisits = function(callback){
withDb(function(err, db) {
if(err)
console.log("Error:" + err);
// Map function
var map = function() { emit({url: this.url, uid: this.uid }, this.timestamp); };
// Reduce function
var reduce = function(k,vals)
{
var max = -1;
for(var i = 0; i<vals.length; i++){
if(vals[i] > max){
max = vals[i];
}
}
return max;
};
var collection = db.collection('pagevisists');
collection.mapReduce(map, reduce, {out: {replace : 'tempCollection', readPreference : 'secondary'}}, function(err,c){
if(err){
console.log(err)
callback([]);
return;
}
c.find().toArray(function(err, docs) {
callback(docs);
});
});
});
}
function withDb(f){
MongoClient.connect(module.app.settings.mongodburl, f);
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
} |
function render() {
return pug`
.component
.component__title Title
include ./test/fixtures/include-template/test.pug
`
} |
import React, {Component, PropTypes} from 'react';
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, DatePicker, InputNumber, Card } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import InspectView from 'common/basic/components/InspectView';
import SubItemContainer from 'common/basic/containers/SubItemContainer'
import MilestonesComponent from './MilestonesComponent';
import TopicListView from './TopicListView';
class ProjectInspectView extends InspectView
{
constructor(props)
{
super(props);
}
render()
{
const project = this.itemClone;
const formItems = [];
const formItemLayout =
{
labelCol: { span: 6 },
wrapperCol: { span: 14 },
};
formItems.push(
<Card key='0' title='项目基本信息' style={{marginBottom: 20}}>
<Row key='0'>
<Col span={12}>
<FormItem
{...formItemLayout}
label="项目名称"
>
{project.projectName}
</FormItem>
</Col>
<Col span={12}>
<FormItem
{...formItemLayout}
label="开始时间"
>
{project.startTime}
</FormItem>
</Col>
</Row>
<Row key='1'>
<Col span={12}>
<FormItem
{...formItemLayout}
label="项目地点"
>
{project.location}
</FormItem>
</Col>
<Col span={12}>
<FormItem
{...formItemLayout}
label="负责人"
>
{project.directorId}
</FormItem>
</Col>
</Row>
<Row key='2'>
<Col span={12}>
<FormItem
{...formItemLayout}
label="预计工期 (月)"
>
{project.expectedDuration}
</FormItem>
</Col>
<Col span={12}>
<FormItem
{...formItemLayout}
label="实际工期 (月)"
>
{project.actualDuration}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
{...formItemLayout}
label="是否已完成"
>
{project.completed == '1' ? '已完成' : '未完成'}
</FormItem>
</Col>
</Row>
<Row key='3'>
<FormItem
{
...
{
labelCol: { span: 3 },
wrapperCol: { span: 19 },
}
}
label="备注"
>
{project.comment}
</FormItem>
</Row>
</Card>
);
const topicStoreName = 'topic';
const _TopicListView = SubItemContainer(topicStoreName, TopicListView);
formItems.push(
<Card key='1' title='项目课题' style={{marginBottom: 20}}>
<Row key='3'>
<_TopicListView storeName={topicStoreName} parentId={this.props.item.id} readonly/>
</Row>
</Card>
);
const milestoneStoreName = 'milestone';
const _MilestonesComponent = SubItemContainer(milestoneStoreName, MilestonesComponent);
formItems.push(
<Card key='2' title='项目关键节点' style={{marginBottom: 20}}>
<Row key='3'>
<_MilestonesComponent storeName={milestoneStoreName} parentId={this.props.item.id} readonly/>
</Row>
</Card>
);
return this.renderForm([formItems]);
}
}
export default ProjectInspectView; |
var Api = require('../../lib/api'),
createAPIRequest = require('../../lib/apirequest');
var util = require('util');
function Blogs(options) {
Blogs.super_.call(this);
var self = this;
this._options = options || {};
/**
* lists.list
* @param {object} params Parameters for the request
* @param {callback} callback The callback that handles the response
* @return {object} Request object
*/
this.list = function(params, callback) {
var parameters = {
options: {
url: 'https://{slug}.nationbuilder.com/api/v1/sites/{site_slug}/pages/blogs',
method: 'GET'
},
params: params,
requiredParams: ['slug', 'site_slug'],
pathParams: ['slug', 'site_slug'],
context: self
};
return createAPIRequest(parameters, callback);
};
this.show = function(params, callback) {
var parameters = {
options: {
url: 'https://{slug}.nationbuilder.com/api/v1/sites/{site_slug}/pages/blogs/{id}',
method: 'GET'
},
params: params,
requiredParams: ['slug', 'site_slug', 'id'],
pathParams: ['slug', 'site_slug', 'id'],
context: self
};
return createAPIRequest(parameters, callback);
};
}
/**
* Inherit from Api.
*/
util.inherits(Blogs, Api);
/**
* Exports Blogs object
* @type Blogs
*/
module.exports = Blogs;
|
import styled from 'styled-components';
const Label = styled.label`
padding-right: 5px;
white-space: nowrap;
font-size: 12px;
line-height: 12px;
text-transform: uppercase;
`;
export default Label;
|
const http = require('http');
async function requestHandler(request, response) {
response.end('Hello world!');
}
const server = http.createServer(requestHandler);
server.listen(5000, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`deploying server is listening on ${5000}`)
});
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var Domain = require('../base/Domain'); /* jshint ignore:line */
var V1 = require('./wireless/V1'); /* jshint ignore:line */
/* jshint ignore:start */
/**
* Initialize wireless domain
*
* @constructor
*
* @property {Twilio.Wireless.V1} v1 - v1 version
* @property {Twilio.Wireless.V1.CommandList} commands - commands resource
* @property {Twilio.Wireless.V1.RatePlanList} ratePlans - ratePlans resource
* @property {Twilio.Wireless.V1.SimList} sims - sims resource
*
* @param {Twilio} twilio - The twilio client
*/
/* jshint ignore:end */
function Wireless(twilio) {
Domain.prototype.constructor.call(this, twilio, 'https://wireless.twilio.com');
// Versions
this._v1 = undefined;
}
_.extend(Wireless.prototype, Domain.prototype);
Wireless.prototype.constructor = Wireless;
Object.defineProperty(Wireless.prototype,
'v1', {
get: function() {
this._v1 = this._v1 || new V1(this);
return this._v1;
}
});
Object.defineProperty(Wireless.prototype,
'commands', {
get: function() {
return this.v1.commands;
}
});
Object.defineProperty(Wireless.prototype,
'ratePlans', {
get: function() {
return this.v1.ratePlans;
}
});
Object.defineProperty(Wireless.prototype,
'sims', {
get: function() {
return this.v1.sims;
}
});
module.exports = Wireless;
|
// This file configures a web server for testing the production build
// on your local machine.
import browserSync from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback';
import {chalkProcessing} from './chalkConfig';
/* eslint-disable no-console */
console.log(chalkProcessing('Opening production build...'));
// Run Browsersync
browserSync({
port: process.env.PORT || 4000,
ui: {
port: process.env.PORT + 1 || 4001
},
server: {
baseDir: 'dist'
},
files: [
'src/*.html',
'src/*.js',
'src/*.css',
],
middleware: [historyApiFallback()]
});
|
/**
* Litepublisher shop script
* Copyright (C) 2010 - 2014 Vladimir Yushko http://litepublisher.ru/ http://litepublisher.com/
* Comercial license. IMPORTANT: THE SOFTWARE IS LICENSED, NOT SOLD. Please read the following License Agreement (plugins/shop/license.txt)
* You can use one license on one website
**/
(function($) {
$(function() {
$.load_css(ltoptions.files + "/js/fonts/css/font-awesome.min.css?v=4.7.0");
});
})(jQuery); |
module.exports = function(){
var gulp = this.gulp,
$ = this.opts.$;
return gulp.src('dist/css/style.css',{base:'./'})
.pipe($.cssmin({
//* for keeping all (default), 1 for keeping first one only, 0 for removing all
keepSpecialComments:1
}))
.pipe($.rename( 'style.min.css' ))
.pipe(gulp.dest('dist/css'))
.pipe(this.opts.bs.stream());
};
module.exports.dependencies = ['sass'];
|
/* eslint-env jest */
const cmdRun = jest.genMockFromModule('../lib/command-run');
module.exports = cmdRun;
|
// var customerName = "Ratra";
// var products = [
// "Brookln T-Shirt White",
// "Brookln T-Shirt Black",
// "Apple Watch",
// "Android Phone"
// ];
// var prices = [10, 10, 199, 159];
// var price = 10;
// var quantity = 2;
// var priceDiscount;
// //var totalPrice = price * quantity;
// var customerElement = document.getElementById("customer");
// customerElement.textContent = customerName;
// // var customerElement = document.getElementById("total");
// // customerElement.textContent = totalPrice;
// var productsText = " ";
// var productsElement = document.getElementById("product-list");
// productsText += "<li class='list-group-item'><span class='badge'>$"+ prices[0]
// + "</span>" + products[0] + "</li>";
// productsText += "<li class='list-group-item'><span class='badge'>$"+ prices[1]
// + "</span>" + products[1] + "</li>";
// productsText += "<li class='list-group-item'><span class='badge'>$"+ prices[2]
// + "</span>" + products[2] + "</li>";
// productsText += "<li class='list-group-item'><span class='badge'>$"+ prices[3]
// + "</span>" + products[3] + "</li>";
// productsElement.innerHTML = productsText;
// totalPrice = prices[0] + prices[1] + prices[2] + prices[3];
// priceDiscount = totalPrice * 25/100;
// var totalPriceElement = document.getElementById("total");
// totalPriceElement.textContent = totalPrice - priceDiscount;
// var timeElement = document.getElementById("time");
// var dt = new Date().getHours();
// if (dt >= 0 && dt <= 11){
// timeElement.textContent = "Good Morning, ";
// }else if (dt >= 12 && dt <= 17){
// timeElement.textContent = "Good Afternoon, ";
// }else {
// timeElement.textContent = "Good Evening, ";
// }
var shop = {
customerName: "Ratra",
totalPrice: 0,
products: [
"Brooklyn T-Shirt Watch",
"Brookln T-Shirt Black",
"Apple Watch",
"Android Phone"
],
prices: [10,10,199,159],
displayCustomerName: function() {
var customerElement = document.getElementById("customer-name")
customerElement.textContent = this.customerName;
},
displayProductList: function(){
var productsText = "";
var productsElement = document.getElementById("product-list");
productsText += "<li class='list-group-item'><span class='badge'>$"+ this.prices[0]
+ "</span>" + this.products[0] + "</li>";
productsText += "<li class='list-group-item'><span class='badge'>$"+ this.prices[1]
+ "</span>" + this.products[1] + "</li>";
productsText += "<li class='list-group-item'><span class='badge'>$"+ this.prices[2]
+ "</span>" + this.products[2] + "</li>";
productsText += "<li class='list-group-item'><span class='badge'>$"+ this.prices[3]
+ "</span>" + this.products[3] + "</li>";
productsElement.innerHTML = productsText;
},
calculateTotalPrice: function(){
return (this.prices[0] + this.prices[1] +this.prices[2]+ this.prices[3]) * 0.75;
},
displayTotalPrice: function(){
this.totalPrice = this.calculateTotalPrice();
var totalPriceElement = document.getElementById("total");
totalPriceElement.textContent = this.totalPrice;
}
}
shop.displayCustomerName();
shop.displayProductList();
shop.displayTotalPrice();
|
var Renderer = (function () {
function Renderer(recipeCategoriesSummary) {
this.recipeCategoriesSummary = recipeCategoriesSummary;
if (recipeCategoriesSummary) {
this.renderCategories(recipeCategoriesSummary);
}
else {
this.renderError();
}
}
//TODO
//Example how the RecipeCategories<T> generic is used.
Renderer.prototype.renderCategories = function (recipeCategoriesSummary) {
var recipeSelect = document.getElementById('RecipeCategory');
recipeCategoriesSummary.items.forEach(function (category) {
var opt = document.createElement('option');
opt.setAttribute('title', category.title);
opt.innerHTML = category.text;
recipeSelect.appendChild(opt);
});
};
//TODO (INTERFACES EXERCISE)
//1. Change the category parameter type to IRecipeCategory
Renderer.prototype.renderCategory = function (category) {
//Update foodgroups bullet points
var foodGroups = document.getElementById('FoodGroups');
foodGroups.value = '';
var html = '<ul>';
for (var i = 0, len = category.foodGroups.length; i < len; i++) {
html += '<li>' + category.foodGroups[i].name + '</li>';
}
foodGroups.innerHTML = html + '</ul>';
//Update description
var el = document.getElementById('recipeDesc');
el.innerHTML = category.description;
this.renderExamples(category);
};
//TODO (INTERFACES EXERCISE)
//1. Change the category parameter type to IRecipeCategory
Renderer.prototype.renderExamples = function (category) {
//Update examples
var examples = document.getElementById('examples');
examples.value = '';
var html = '<ol>';
for (var i = 0, len = category.examples.length; i < len; i++) {
var example = category.examples[i];
var ingredients = example.ingredients.map(function (ingredient) {
return ingredient.name;
});
html += '<li>' +
'<h4>' + example.name + ' </h4>' +
'<strong>Ingredients: </strong>' + ingredients.join(', ') +
'<br /><strong>Preparation Time: </strong>' + example.prepTime +
'</li>';
}
examples.innerHTML = html + '</ol>';
};
Renderer.prototype.renderError = function () {
var examples = document.getElementById('examples');
examples.value = 'Unable to load data!';
};
return Renderer;
}());
//# sourceMappingURL=renderer.js.map |
var words = function(yourString)
{
var toReturn = 0;
yourString = yourString.replace("\n"," ");
yourString = yourString.replace("\t"," ");
yourString = yourString.replace(" "," ");
var tempSortArray = yourString.split(" ");
var senLength = tempSortArray.length;
var tempWord = "";
//var wordCount = 0;
var word = new Object();
for(i=0;i<senLength;i++)
{
var wordCount = 1;
tempWord = tempSortArray[i];
//I have picked one word, now I check how many times it occurs
for(i2=0;i2<senLength;i2++)
{
if(tempWord === tempSortArray[i2] && i2 != i)
{
wordCount++;
}
//If it occurs and it's not the current copy, add it
}
word[tempWord] = wordCount;
/*var toPush = tempWord + ": " + wordCount;
if(tempAnsArray.indexOf(toPush) === -1)
{
tempAnsArray.push(toPush);
}
tempAnsArray.push();*/
}
return(word);
};
//words("I am a boy am b"); |
import React, { PropTypes } from 'react'
const Todo = ({ onClick, completed, text }) => (
<li
onClick={onClick}
style={{textDecoration: completed ? 'line-through': 'none'}}
>
{text}
</li>
)
Todo.propTypes = {
text: PropTypes.string.isRequired
}
export default Todo |
'use strict';
var calendars = require('./calendars');
var Lib = require('../../lib');
var constants = require('../../constants/numerical');
var EPOCHJD = constants.EPOCHJD;
var ONEDAY = constants.ONEDAY;
var attributes = {
valType: 'enumerated',
values: Lib.sortObjectKeys(calendars.calendars),
editType: 'calc',
dflt: 'gregorian'
};
var handleDefaults = function(contIn, contOut, attr, dflt) {
var attrs = {};
attrs[attr] = attributes;
return Lib.coerce(contIn, contOut, attrs, attr, dflt);
};
var handleTraceDefaults = function(traceIn, traceOut, coords, layout) {
for(var i = 0; i < coords.length; i++) {
handleDefaults(traceIn, traceOut, coords[i] + 'calendar', layout.calendar);
}
};
// each calendar needs its own default canonical tick. I would love to use
// 2000-01-01 (or even 0000-01-01) for them all but they don't necessarily
// all support either of those dates. Instead I'll use the most significant
// number they *do* support, biased toward the present day.
var CANONICAL_TICK = {
chinese: '2000-01-01',
coptic: '2000-01-01',
discworld: '2000-01-01',
ethiopian: '2000-01-01',
hebrew: '5000-01-01',
islamic: '1000-01-01',
julian: '2000-01-01',
mayan: '5000-01-01',
nanakshahi: '1000-01-01',
nepali: '2000-01-01',
persian: '1000-01-01',
jalali: '1000-01-01',
taiwan: '1000-01-01',
thai: '2000-01-01',
ummalqura: '1400-01-01'
};
// Start on a Sunday - for week ticks
// Discworld and Mayan calendars don't have 7-day weeks but we're going to give them
// 7-day week ticks so start on our Sundays.
// If anyone really cares we can customize the auto tick spacings for these calendars.
var CANONICAL_SUNDAY = {
chinese: '2000-01-02',
coptic: '2000-01-03',
discworld: '2000-01-03',
ethiopian: '2000-01-05',
hebrew: '5000-01-01',
islamic: '1000-01-02',
julian: '2000-01-03',
mayan: '5000-01-01',
nanakshahi: '1000-01-05',
nepali: '2000-01-05',
persian: '1000-01-01',
jalali: '1000-01-01',
taiwan: '1000-01-04',
thai: '2000-01-04',
ummalqura: '1400-01-06'
};
var DFLTRANGE = {
chinese: ['2000-01-01', '2001-01-01'],
coptic: ['1700-01-01', '1701-01-01'],
discworld: ['1800-01-01', '1801-01-01'],
ethiopian: ['2000-01-01', '2001-01-01'],
hebrew: ['5700-01-01', '5701-01-01'],
islamic: ['1400-01-01', '1401-01-01'],
julian: ['2000-01-01', '2001-01-01'],
mayan: ['5200-01-01', '5201-01-01'],
nanakshahi: ['0500-01-01', '0501-01-01'],
nepali: ['2000-01-01', '2001-01-01'],
persian: ['1400-01-01', '1401-01-01'],
jalali: ['1400-01-01', '1401-01-01'],
taiwan: ['0100-01-01', '0101-01-01'],
thai: ['2500-01-01', '2501-01-01'],
ummalqura: ['1400-01-01', '1401-01-01']
};
/*
* convert d3 templates to world-calendars templates, so our users only need
* to know d3's specifiers. Map space padding to no padding, and unknown fields
* to an ugly placeholder
*/
var UNKNOWN = '##';
var d3ToWorldCalendars = {
'd': {'0': 'dd', '-': 'd'}, // 2-digit or unpadded day of month
'e': {'0': 'd', '-': 'd'}, // alternate, always unpadded day of month
'a': {'0': 'D', '-': 'D'}, // short weekday name
'A': {'0': 'DD', '-': 'DD'}, // full weekday name
'j': {'0': 'oo', '-': 'o'}, // 3-digit or unpadded day of the year
'W': {'0': 'ww', '-': 'w'}, // 2-digit or unpadded week of the year (Monday first)
'm': {'0': 'mm', '-': 'm'}, // 2-digit or unpadded month number
'b': {'0': 'M', '-': 'M'}, // short month name
'B': {'0': 'MM', '-': 'MM'}, // full month name
'y': {'0': 'yy', '-': 'yy'}, // 2-digit year (map unpadded to zero-padded)
'Y': {'0': 'yyyy', '-': 'yyyy'}, // 4-digit year (map unpadded to zero-padded)
'U': UNKNOWN, // Sunday-first week of the year
'w': UNKNOWN, // day of the week [0(sunday),6]
// combined format, we replace the date part with the world-calendar version
// and the %X stays there for d3 to handle with time parts
'c': {'0': 'D M d %X yyyy', '-': 'D M d %X yyyy'},
'x': {'0': 'mm/dd/yyyy', '-': 'mm/dd/yyyy'}
};
function worldCalFmt(fmt, x, calendar) {
var dateJD = Math.floor((x + 0.05) / ONEDAY) + EPOCHJD;
var cDate = getCal(calendar).fromJD(dateJD);
var i = 0;
var modifier, directive, directiveLen, directiveObj, replacementPart;
while((i = fmt.indexOf('%', i)) !== -1) {
modifier = fmt.charAt(i + 1);
if(modifier === '0' || modifier === '-' || modifier === '_') {
directiveLen = 3;
directive = fmt.charAt(i + 2);
if(modifier === '_') modifier = '-';
} else {
directive = modifier;
modifier = '0';
directiveLen = 2;
}
directiveObj = d3ToWorldCalendars[directive];
if(!directiveObj) {
i += directiveLen;
} else {
// code is recognized as a date part but world-calendars doesn't support it
if(directiveObj === UNKNOWN) replacementPart = UNKNOWN;
// format the cDate according to the translated directive
else replacementPart = cDate.formatDate(directiveObj[modifier]);
fmt = fmt.substr(0, i) + replacementPart + fmt.substr(i + directiveLen);
i += replacementPart.length;
}
}
return fmt;
}
// cache world calendars, so we don't have to reinstantiate
// during each date-time conversion
var allCals = {};
function getCal(calendar) {
var calendarObj = allCals[calendar];
if(calendarObj) return calendarObj;
calendarObj = allCals[calendar] = calendars.instance(calendar);
return calendarObj;
}
function makeAttrs(description) {
return Lib.extendFlat({}, attributes, { description: description });
}
function makeTraceAttrsDescription(coord) {
return 'Sets the calendar system to use with `' + coord + '` date data.';
}
var xAttrs = {
xcalendar: makeAttrs(makeTraceAttrsDescription('x'))
};
var xyAttrs = Lib.extendFlat({}, xAttrs, {
ycalendar: makeAttrs(makeTraceAttrsDescription('y'))
});
var xyzAttrs = Lib.extendFlat({}, xyAttrs, {
zcalendar: makeAttrs(makeTraceAttrsDescription('z'))
});
var axisAttrs = makeAttrs([
'Sets the calendar system to use for `range` and `tick0`',
'if this is a date axis. This does not set the calendar for',
'interpreting data on this axis, that\'s specified in the trace',
'or via the global `layout.calendar`'
].join(' '));
module.exports = {
moduleType: 'component',
name: 'calendars',
schema: {
traces: {
scatter: xyAttrs,
bar: xyAttrs,
box: xyAttrs,
heatmap: xyAttrs,
contour: xyAttrs,
histogram: xyAttrs,
histogram2d: xyAttrs,
histogram2dcontour: xyAttrs,
scatter3d: xyzAttrs,
surface: xyzAttrs,
mesh3d: xyzAttrs,
scattergl: xyAttrs,
ohlc: xAttrs,
candlestick: xAttrs
},
layout: {
calendar: makeAttrs([
'Sets the default calendar system to use for interpreting and',
'displaying dates throughout the plot.'
].join(' '))
},
subplots: {
xaxis: {calendar: axisAttrs},
yaxis: {calendar: axisAttrs},
scene: {
xaxis: {calendar: axisAttrs},
// TODO: it's actually redundant to include yaxis and zaxis here
// because in the scene attributes these are the same object so merging
// into one merges into them all. However, I left them in for parity with
// cartesian, where yaxis is unused until we Plotschema.get() when we
// use its presence or absence to determine whether to delete attributes
// from yaxis if they only apply to x (rangeselector/rangeslider)
yaxis: {calendar: axisAttrs},
zaxis: {calendar: axisAttrs}
},
polar: {
radialaxis: {calendar: axisAttrs}
}
},
transforms: {
filter: {
valuecalendar: makeAttrs([
'WARNING: All transforms are deprecated and may be removed from the API in next major version.',
'Sets the calendar system to use for `value`, if it is a date.'
].join(' ')),
targetcalendar: makeAttrs([
'WARNING: All transforms are deprecated and may be removed from the API in next major version.',
'Sets the calendar system to use for `target`, if it is an',
'array of dates. If `target` is a string (eg *x*) we use the',
'corresponding trace attribute (eg `xcalendar`) if it exists,',
'even if `targetcalendar` is provided.'
].join(' '))
}
}
},
layoutAttributes: attributes,
handleDefaults: handleDefaults,
handleTraceDefaults: handleTraceDefaults,
CANONICAL_SUNDAY: CANONICAL_SUNDAY,
CANONICAL_TICK: CANONICAL_TICK,
DFLTRANGE: DFLTRANGE,
getCal: getCal,
worldCalFmt: worldCalFmt
};
|
/*
artifact generator: C:\My\wizzi\v5\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js
primary source IttfDocument: c:\my\wizzi\v5\plugins\wizzi-core\src\ittf\lib\artifacts\xml\document\gen\main.js.ittf
*/
'use strict';
var util = require('util');
var md = module.exports = {};
var myname = 'xml.document.main';
md.gen = function(model, ctx, callback) {
if (model.wzElement !== 'xml') {
console.log('wizzi-core', 'artifact', 'model', model);
callback(error('Invalid model schema. Expected "xml". Received: ' + model.wzElement));
}
ctx.w('<?xml version="1.0"' + (model.encoding ? ' encoding="' + model.encoding + '"' : '') + (model.standalone ? ' standalone="' + model.standalone + '"' : '') + '>');
var i, i_items=model.elements, i_len=model.elements.length, el;
for (i=0; i<i_len; i++) {
el = model.elements[i];
md.genItem(el, ctx);
}
callback(null, ctx);
};
md.genItem = function(model, ctx) {
if (model.tag) {
ctx.write('<' + model.tag);
var i, i_items=model.attributes, i_len=model.attributes.length, item;
for (i=0; i<i_len; i++) {
item = model.attributes[i];
ctx.write(' ' + item.name + '="');
ctx.write(item.value);
ctx.write('"');
}
if ((model.elements && model.elements.length > 0) || model.text) {
ctx.write('>');
if (model.text) {
ctx.write(model.text);
}
if (model.elements && model.elements.length > 0) {
ctx.w();
ctx.indent();
var i, i_items=model.elements, i_len=model.elements.length, item;
for (i=0; i<i_len; i++) {
item = model.elements[i];
md.genItem(item, ctx);
}
ctx.deindent();
}
ctx.w('</' + model.tag + '>');
}
else {
ctx.w(' />');
}
}
else {
ctx.write(model.text);
}
};
function error(message) {
return {
__is_error: true,
source: 'wizzi-core/lib/artifacts/xml/document',
message: message
};
}
|
'use strict'
var React = require('react')
var moment = require('moment')
var copyUtils = require('copy-utils')
var copy = copyUtils.copy
var copyList = copyUtils.copyList
var asConfig = require('./utils/asConfig')
var MonthView = require('./MonthView')
var YearView = require('./YearView')
var DecadeView = require('./DecadeView')
// if (React.createFactory){
// MonthView = React.createFactory(MonthView)
// YearView = React.createFactory(YearView)
// DecadeView = React.createFactory(DecadeView)
// }
var Views = {
month : MonthView,
year : YearView,
decade: DecadeView
}
var getWeekDayNames = require('./utils/getWeekDayNames')
function emptyFn(){}
var DatePicker = React.createClass({
displayName: 'DatePicker',
propTypes: {
todayText: React.PropTypes.string,
gotoSelectedText: React.PropTypes.string,
renderFooter: React.PropTypes.func,
onChange: React.PropTypes.func,
date: React.PropTypes.any,
viewDate: React.PropTypes.any
},
getInitialState: function() {
return {
}
},
getDefaultProps: function() {
return asConfig()
},
getViewName: function() {
return this.state.view || this.props.view || 'month'
},
getViewOrder: function() {
return ['month', 'year', 'decade']
},
addViewIndex: function(amount) {
var viewName = this.getViewName()
var order = this.getViewOrder()
var index = order.indexOf(viewName)
index += amount
return index % order.length
},
getNextViewName: function() {
return this.getViewOrder()[this.addViewIndex(1)]
},
getPrevViewName: function() {
return this.getViewOrder()[this.addViewIndex(-1)]
},
getView: function() {
return Views[this.getViewName()] || Views.month
},
getViewFactory: function() {
var view = this.getView()
if (React.createFactory){
view.__factory = view.__factory || React.createFactory(view)
view = view.__factory
}
return view
},
getViewDate: function() {
return this.state.viewMoment || this.props.viewDate || this.props.date || this.now
},
render: function() {
this.now = +new Date()
var view = this.getViewFactory()
var props = asConfig(this.props)
props.viewDate = this.getViewDate()
props.renderDay = this.props.renderDay
props.onRenderDay = this.props.onRenderDay
props.onChange = this.handleChange
props.onSelect = this.handleSelect
var className = (this.props.className || '') + ' date-picker'
return (
React.createElement("div", React.__spread({className: className}, this.props),
React.createElement("div", {className: "dp-inner"},
this.renderHeader(view),
React.createElement("div", {className: "dp-body"},
React.createElement("div", {className: "dp-anim-target"},
view(props)
)
),
this.renderFooter(props)
)
)
)
},
renderFooter: function(props) {
if (this.props.hideFooter){
return
}
if (this.props.today){
console.warn('Please use "todayText" prop instead of "today"!')
}
if (this.props.gotoSelected){
console.warn('Please use "gotoSelectedText" prop instead of "gotoSelected"!')
}
var todayText = this.props.todayText || 'Today'
var gotoSelectedText = this.props.gotoSelectedText || 'Go to selected'
var footerProps = {
todayText : todayText,
gotoSelectedText : gotoSelectedText,
onTodayClick : this.gotoNow,
onGotoSelectedClick: this.gotoSelected,
date : props.date,
viewDate : props.viewDate
}
var result
if (typeof this.props.renderFooter == 'function'){
result = this.props.renderFooter(footerProps)
}
if (result !== undefined){
return result
}
return (
React.createElement("div", {className: "dp-footer"},
React.createElement("div", {className: "dp-footer-today", onClick: this.gotoNow},
todayText
),
React.createElement("div", {className: "dp-footer-selected", onClick: this.gotoSelected},
gotoSelectedText
)
)
)
},
gotoNow: function() {
this.gotoDate(+new Date())
},
gotoSelected: function() {
this.gotoDate(this.props.date || +new Date())
},
gotoDate: function(value) {
this.setState({
view: 'month',
viewMoment: moment(value)
})
},
getViewColspan: function(){
var map = {
month : 5,
year : 2,
decade: 2
}
return map[this.getViewName()]
},
renderHeader: function(view) {
var viewDate = this.getViewDate()
var headerText = this.getView().getHeaderText(viewDate)
var colspan = this.getViewColspan()
var prev = this.props.navPrev
var next = this.props.navNext
return (
React.createElement("div", {className: "dp-header"},
React.createElement("table", {className: "dp-nav-table"}, React.createElement("tbody", null,
React.createElement("tr", {className: "dp-row"},
React.createElement("td", {className: "dp-prev-nav dp-nav-cell dp-cell", onClick: this.handlePrevNav}, prev),
React.createElement("td", {className: "dp-nav-view dp-cell ", colSpan: colspan, onClick: this.handleViewChange}, headerText),
React.createElement("td", {className: "dp-next-nav dp-nav-cell dp-cell", onClick: this.handleNextNav}, next)
)
))
)
)
},
handleRenderDay: function (date) {
return (this.props.renderDay || emptyFn)(date) || []
},
handleViewChange: function() {
this.setState({
view: this.getNextViewName()
})
},
getNext: function() {
var current = this.getViewDate()
return ({
month: function() {
return moment(current).add(1, 'month')
},
year: function() {
return moment(current).add(1, 'year')
},
decade: function() {
return moment(current).add(10, 'year')
}
})[this.getViewName()]()
},
getPrev: function() {
var current = this.getViewDate()
return ({
month: function() {
return moment(current).add(-1, 'month')
},
year: function() {
return moment(current).add(-1, 'year')
},
decade: function() {
return moment(current).add(-10, 'year')
}
})[this.getViewName()]()
},
handlePrevNav: function(event) {
var viewMoment = this.getPrev()
this.setState({
viewMoment: viewMoment
})
if (typeof this.props.onNav === 'function'){
var text = viewMoment.format(this.props.dateFormat)
var view = this.getViewName()
this.props.onNav(viewMoment, text, view, -1, event)
}
},
handleNextNav: function(event) {
var viewMoment = this.getNext()
this.setState({
viewMoment: viewMoment
})
if (typeof this.props.onNav === 'function'){
var text = viewMoment.format(this.props.dateFormat)
var view = this.getViewName()
this.props.onNav(viewMoment, text, view, 1, event)
}
},
handleChange: function(date, event) {
date = moment(date)
var text = date.format(this.props.dateFormat)
;(this.props.onChange || emptyFn)(date, text, event)
},
handleSelect: function(date, event) {
var viewName = this.getViewName()
var property = ({
decade: 'year',
year : 'month'
})[viewName]
var value = date.get(property)
var viewMoment = moment(this.getViewDate()).set(property, value)
var view = this.getPrevViewName()
this.setState({
viewMoment: viewMoment,
view: view
})
if (typeof this.props.onSelect === 'function'){
var text = viewMoment.format(this.props.dateFormat)
this.props.onSelect(viewMoment, text, view, event)
}
}
})
module.exports = DatePicker |
const express = require('express');
const app = express();
const bookshelf = require('./server/Bookshelf');
const bodyParser = require('body-parser');
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const jwks = require('jwks-rsa');
const jwt_decode = require('jwt-decode');
// const cookieParser = require('cookie-parser');
const GameTypeRoutes = require('./server/routes/GameTypes');
const SquaresRoutes = require('./server/routes/Squares');
const UsersRoutes = require('./server/routes/Users');
const BoardRoutes = require('./server/routes/Board');
const BoardSquareRoutes = require('./server/routes/BoardSquare');
const User = require('./server/models/User');
const path = require('path');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS");
next();
});
var jwtCheck = jwt({
secret: jwks.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: "https://marcjohnstonuw.auth0.com/.well-known/jwks.json"
}),
audience: 'https://bingo-gen.api.com',
issuer: "https://marcjohnstonuw.auth0.com/",
algorithms: ['RS256']
});
app.use(function (req, res, next) {
if (req.headers.id) {
let decoded = jwt_decode(req.headers.id);
User.query({where: {email: decoded.email}})
.fetch()
.then((user) => {
req.headers.userID = user.id
next();
})
.catch((err) => {
next();
})
} else {
next()
}
})
//var decoded = jwt_decode(token);
// Serve static assets
console.log('__dirname', __dirname)
app.use(express.static(path.resolve(__dirname, 'build')));
// Always return the main index.html, so react-router render the route in the client
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
app.get('/callback', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use('/gameTypes', GameTypeRoutes);
app.use('/squares', jwtCheck, SquaresRoutes);
app.use('/users', jwtCheck, UsersRoutes);
app.use('/boards', jwtCheck, BoardRoutes);
app.use('/boardsquares', jwtCheck, BoardSquareRoutes);
module.exports = app;
// app.listen(8080, () => {
// console.log('Server Started on http://localhost:8080');
// console.log('Press CTRL + C to stop server');
// });
// // server/index.js
// 'use strict';
// const app = require('./server/app');
const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
}); |
function redirectToSandbox({state, services}) {
const userId = state.get('user.id');
services.router.redirect('/mainassignment/' + userId);
}
export default redirectToSandbox;
|
SceneJS_ChunkFactory.createChunkType({
type: "texture",
build : function() {
this._uTexSampler = this._uTexSampler || [];
this._uTexMatrix = this._uTexMatrix || [];
this._uTexBlendFactor = this._uTexBlendFactor || [];
var layers = this.core.layers;
if (layers) {
var layer;
var draw = this.program.draw;
for (var i = 0, len = layers.length; i < len; i++) {
layer = layers[i];
this._uTexSampler[i] = "SCENEJS_uSampler" + i;
this._uTexMatrix[i] = draw.getUniform("SCENEJS_uLayer" + i + "Matrix");
this._uTexBlendFactor[i] = draw.getUniform("SCENEJS_uLayer" + i + "BlendFactor");
}
}
},
draw : function(frameCtx) {
frameCtx.textureUnit = 0;
frameCtx.normalMapUVLayerIdx = -1;
var layers = this.core.layers;
if (layers) {
var draw = this.program.draw;
var layer;
for (var i = 0, len = layers.length; i < len; i++) {
layer = layers[i];
if (this._uTexSampler[i] && layer.texture) { // Lazy-loads
draw.bindTexture(this._uTexSampler[i], layer.texture, frameCtx.textureUnit);
frameCtx.textureUnit = (frameCtx.textureUnit + 1) % SceneJS.WEBGL_INFO.MAX_TEXTURE_UNITS;
if (layer._matrixDirty && layer.buildMatrix) {
layer.buildMatrix.call(layer);
}
if (this._uTexMatrix[i]) {
this._uTexMatrix[i].setValue(layer.matrixAsArray);
}
if (this._uTexBlendFactor[i]) {
this._uTexBlendFactor[i].setValue(layer.blendFactor);
}
if (layer.isNormalMap) {
// Remember which UV layer we're using for the normal
// map so that we can lazy-generate the tangents from the
// appropriate UV layer in the geometry chunk.
// Note that only one normal map is allowed per drawable, so there
// will be only one UV layer used for normal mapping.
frameCtx.normalMapUVLayerIdx = layer.uvLayerIdx;
}
} else {
// draw.bindTexture(this._uTexSampler[i], null, i); // Unbind
}
}
}
frameCtx.texture = this.core;
}
}); |
!function (a) {
"function" == typeof define && define.amd ? define(["jquery", "moment"], a) : a(jQuery, moment)
}(function (a, b) {
(b.defineLocale || b.lang).call(b, "ar-ma", {
months: "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),
monthsShort: "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),
weekdays: "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),
weekdaysShort: "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),
weekdaysMin: "ح_ن_ث_ر_خ_ج_س".split("_"),
longDateFormat: {
LT: "HH:mm",
LTS: "LT:ss",
L: "DD/MM/YYYY",
LL: "D MMMM YYYY",
LLL: "D MMMM YYYY LT",
LLLL: "dddd D MMMM YYYY LT"
},
calendar: {
sameDay: "[اليوم على الساعة] LT",
nextDay: "[غدا على الساعة] LT",
nextWeek: "dddd [على الساعة] LT",
lastDay: "[أمس على الساعة] LT",
lastWeek: "dddd [على الساعة] LT",
sameElse: "L"
},
relativeTime: {
future: "في %s",
past: "منذ %s",
s: "ثوان",
m: "دقيقة",
mm: "%d دقائق",
h: "ساعة",
hh: "%d ساعات",
d: "يوم",
dd: "%d أيام",
M: "شهر",
MM: "%d أشهر",
y: "سنة",
yy: "%d سنوات"
},
week: {dow: 6, doy: 12}
}), a.fullCalendar.datepickerLang("ar-ma", "ar", {
closeText: "إغلاق",
prevText: "<السابق",
nextText: "التالي>",
currentText: "اليوم",
monthNames: ["كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"],
monthNamesShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
dayNames: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"],
dayNamesShort: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"],
dayNamesMin: ["ح", "ن", "ث", "ر", "خ", "ج", "س"],
weekHeader: "أسبوع",
dateFormat: "dd/mm/yy",
firstDay: 6,
isRTL: !0,
showMonthAfterYear: !1,
yearSuffix: ""
}), a.fullCalendar.lang("ar-ma", {
buttonText: {month: "شهر", week: "أسبوع", day: "يوم", list: "أجندة"},
allDayText: "اليوم كله",
eventLimitText: "أخرى"
})
}); |
(function() {
angular.module('image-widgets', [])
.directive('imgSrc', function($window, $interval) {
return {
restrict: 'A',
scope: {
imgSrc: '@',
onImgLoad: '&'
},
link: function(scope, element, attrs) {
if (!angular.isDefined(attrs.aspectRatio)) attrs.aspectRatio = '0:0';
var ratioVals = attrs.aspectRatio.split(':');
if (ratioVals.length != 2) return;
var ratioW = parseInt(ratioVals[0]);
var ratioH = parseInt(ratioVals[1]);
if (isNaN(ratioW) || isNaN(ratioH)) return;
var pad = ((ratioH / ratioW) * 100).toFixed(2);
var img = angular.element('<img />');
// Center the image within the element container.
var center = function() {
var cw = element[0].clientWidth;
var ch = element[0].clientHeight;
var iw = img[0].naturalWidth;
var ih = img[0].naturalHeight;
var ratio = iw / ih;
var newH = cw / ratio;
var top = (ch - newH) / 2;
angular.element(img).css('top', top + 'px');
};
// Initialize the element css.
var elementCss = {
'position': 'relative',
'overflow': 'hidden'
};
// Initialize the image css.
var imgCss = {
'display': 'none',
'top': '0',
'left': '0',
'position': 'absolute',
'width': '100%',
'opacity': '0',
};
// Check if we have a valid padding value and add it to the
// element css to provide proper aspect-ratio size for the
// container.
if (!isNaN(pad)) {
elementCss['padding-top'] = pad + '%';
} else {
imgCss['position'] = 'relative';
imgCss['height'] = '100%';
}
// Set the element css.
angular.element(element).css(elementCss);
// Add CSS3 transition attributes if fade-in is defined and
// has a valid value.
if (angular.isDefined(attrs.fadeIn)) {
var fadeIn = parseFloat(attrs.fadeIn);
if (!isNaN(fadeIn)) {
fadeIn = fadeIn.toFixed(2);
imgCss['-webkit-transition'] = 'opacity ' + fadeIn + 's ease-in';
imgCss['-moz-transition'] = 'opacity ' + fadeIn + 's ease-in';
imgCss['-ms-transition'] = 'opacity ' + fadeIn + 's ease-in';
imgCss['-o-transition'] = 'opacity ' + fadeIn + 's ease-in';
imgCss['transition'] = 'opacity ' + fadeIn + 's ease-in';
}
}
// Set the image css.
img.css(imgCss);
img.attr('src', scope.imgSrc);
// Add handler for when image has finished loading.
img.on('load', function() {
// If there is a valid padding, center the image.
!isNaN(pad) && center();
// Display the image.
img.css('display', 'block');
// So that the transition animation is triggered, we
// need to separate the display attribute change from
// the opacity change.
$interval(function() {
img.css('opacity', 1);
}, 100, 1);
// Call the user defined on load function.
angular.isDefined(scope.onImgLoad) && scope.onImgLoad();
});
// Append the image to the element. This should start the
// loading of the image.
element.append(img);
// If there is an aspect-ratio no the image, make sure to
// add a handler for when the browser is resized. This will
// appropriately re-center the image within its container.
if (!isNaN(pad)) {
angular.element($window).bind('resize', function() {
center();
});
}
}
}
});
}()); |
'use strict';
var _path = require('path');var _path2 = _interopRequireDefault(_path);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
const escapePathForRegex = dir => {
if (_path2.default.sep === '\\') {
// Replace "\" with "/" so it's not escaped by escapeStrForRegex.
// replacePathSepForRegex will convert it back.
dir = dir.replace(/\\/g, '/');
}
return replacePathSepForRegex(escapeStrForRegex(dir));
}; /**
* Copyright (c) 2014, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/const escapeStrForRegex = string => string.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&');const replacePathSepForRegex = string => {if (_path2.default.sep === '\\') {return string.replace(/(\/|\\(?!\.))/g, '\\\\');}
return string;
};
module.exports = {
escapePathForRegex,
escapeStrForRegex,
replacePathSepForRegex }; |
"use strict";
/**
* The BlockPalette is the side panel on the left that holds all the Blocks. BlockPalette is a static class, since
* there is only one Palette. The BlockPalette class creates and manages a set of Categories, each of which
* controls the Blocks inside it and the CategoryBN that brings it into the foreground.
*/
function BlockPalette() {
BlockPalette.categories = []; // List of categories
BlockPalette.selectedCat = null; // category in the foreground
BlockPalette.createCatBg(); // Black bar along left side of screen
BlockPalette.createPalBg(); // Dark gray rectangle behind the CategoryBNs
BlockPalette.createCategories();
BlockPalette.selectFirstCat();
BlockPalette.visible = true;
// Stores a group featuring a trash icon that appears when Blocks are dragged over it
BlockPalette.trash = null;
if (GuiElements.paletteLayersVisible && SettingsManager.sideBarVisible.getValue() !== "true") {
// Hide the Palette if it should be hidden but isn't
GuiElements.hidePaletteLayers(true);
}
}
BlockPalette.setGraphics = function() {
// Dimensions used within a category
BlockPalette.mainVMargin = 10; // The space before the first Block in a Category
BlockPalette.mainHMargin = Button.defaultMargin; // The space between the Blocks and the left side of the screen
BlockPalette.blockMargin = 5; // The vertical spacing between Blocks
BlockPalette.sectionMargin = 10; // The additional space added between sections
BlockPalette.insideBnH = 38; // Height of buttons within a category (such as Create Variable button)
BlockPalette.insideBnW = 150; // Width of buttons within a category
// Dimensions for the region with CategoryBNs
BlockPalette.width = 253;
BlockPalette.catVMargin = Button.defaultMargin; // Margins between buttons
BlockPalette.catHMargin = Button.defaultMargin;
BlockPalette.catH = 30 * 3 + BlockPalette.catVMargin * 3; // 3 rows of BNs, 3 margins, 30 = height per BN
BlockPalette.height = GuiElements.height - TitleBar.height - BlockPalette.catH;
BlockPalette.catY = TitleBar.height;
BlockPalette.y = BlockPalette.catY + BlockPalette.catH;
BlockPalette.bg = Colors.white;
BlockPalette.catBg = Colors.white;
BlockPalette.labelFont = Font.uiFont(13);
BlockPalette.labelColor = Colors.black;
BlockPalette.trashOpacity = 0.8;
BlockPalette.trashHeight = 120;
BlockPalette.trashColor = Colors.black;
};
/**
* Called when the zoom level changes or the screen is resized to recompute dimensions
*/
BlockPalette.updateZoom = function() {
let BP = BlockPalette;
BP.setGraphics();
GuiElements.update.rect(BP.palRect, 0, BP.y, BP.width, BP.height);
GuiElements.update.rect(BP.catRect, 0, BP.catY, BP.width, BP.catH);
GuiElements.move.group(GuiElements.layers.categories, 0, TitleBar.height);
for (let i = 0; i < BlockPalette.categories.length; i++) {
BlockPalette.categories[i].updateZoom();
}
};
/**
* Creates the gray rectangle below the CategoryBNs
*/
BlockPalette.createCatBg = function() {
let BP = BlockPalette;
BP.catRect = GuiElements.draw.rect(0, BP.catY, BP.width, BP.catH, BP.catBg);
GuiElements.layers.catBg.appendChild(BP.catRect);
GuiElements.move.group(GuiElements.layers.categories, 0, TitleBar.height);
};
/**
* Creates the long black rectangle on the left of the screen
*/
BlockPalette.createPalBg = function() {
let BP = BlockPalette;
BP.palRect = GuiElements.draw.rect(0, BP.y, BP.width, BP.height, BP.bg);
GuiElements.layers.paletteBG.appendChild(BP.palRect);
};
/**
* Creates the categories listed in the BlockList
*/
BlockPalette.createCategories = function() {
const catCount = BlockList.catCount();
const numberOfRows = Math.ceil(catCount / 2);
// Automatically alternates between two columns while adding categories
const col1X = BlockPalette.catHMargin;
const col2X = BlockPalette.catHMargin + CategoryBN.hMargin + CategoryBN.width;
let firstColumn = true;
let currentY = BlockPalette.catVMargin;
let currentX = col1X;
let usedRows = 0;
for (let i = 0; i < catCount; i++) {
if (firstColumn && usedRows >= numberOfRows) {
currentX = col2X;
firstColumn = false;
currentY = BlockPalette.catVMargin;
}
const currentCat = new Category(currentX, currentY, BlockList.getCatName(i), BlockList.getCatId(i));
BlockPalette.categories.push(currentCat);
usedRows++;
currentY += CategoryBN.height + CategoryBN.vMargin;
}
};
/**
* Retrieves the category with the given id. Called when a specific category needs to be refreshed
* @param {string} id
* @return {Category}
*/
BlockPalette.getCategory = function(id) {
let i = 0;
while (BlockPalette.categories[i].id !== id) {
i++;
}
return BlockPalette.categories[i];
};
/**
* Selects the first category, making it visible on the screen
*/
BlockPalette.selectFirstCat = function() {
BlockPalette.categories[0].select();
};
/**
* Determines whether the specified point is over the Palette. Used for determining if Blocks should be deleted
* @param {number} x
* @param {number} y
* @return {boolean}
*/
BlockPalette.isStackOverPalette = function(x, y) {
const BP = BlockPalette;
if (!GuiElements.paletteLayersVisible) return false;
return CodeManager.move.pInRange(x, y, 0, BP.catY, BP.width, GuiElements.height - TitleBar.height);
};
/**
* Makes a trash can icon appear over the Palette to indicate that the Blocks being dragged will be deleted
*/
BlockPalette.showTrash = function() {
let BP = BlockPalette;
// If the trash is not visible
if (!BP.trash) {
BP.trash = GuiElements.create.group(0, 0);
let trashBg = GuiElements.draw.rect(0, BP.y, BP.width, BP.height, BP.bg);
GuiElements.update.opacity(trashBg, BP.trashOpacity);
BP.trash.appendChild(trashBg);
let trashWidth = VectorIcon.computeWidth(VectorPaths.trash, BP.trashHeight);
let imgX = BP.width / 2 - trashWidth / 2; // Center X
let imgY = BP.y + BP.height / 2 - BP.trashHeight / 2; // Center Y
let trashIcon = new VectorIcon(imgX, imgY, VectorPaths.trash, BP.trashColor, BP.trashHeight, BP.trash);
// Add to group
GuiElements.layers.trash.appendChild(BP.trash);
}
};
/**
* Removes the trash icon
*/
BlockPalette.hideTrash = function() {
let BP = BlockPalette;
if (BP.trash) {
BP.trash.remove();
BP.trash = null;
}
};
/**
* Recursively tells a specific section of a category to expand/collapse
* @param {string} id - The id of the section
* @param {boolean} collapsed - Whether the section should expand or collapse
*/
BlockPalette.setSuggestedCollapse = function(id, collapsed) {
BlockPalette.passRecursively("setSuggestedCollapse", id, collapsed);
};
/**
* Recursively tells categories that a file is now open
*/
BlockPalette.markOpen = function() {
BlockPalette.passRecursively("markOpen");
};
/**
* Recursively passes message to all children (Categories and their children) of the Palette
* @param {string} message
*/
BlockPalette.passRecursivelyDown = function(message) {
Array.prototype.unshift.call(arguments, "passRecursivelyDown");
BlockPalette.passRecursively.apply(BlockPalette, arguments);
};
/**
* Recursively passes a message to all categories
* @param {string} functionName - The function to call on each category
*/
BlockPalette.passRecursively = function(functionName) {
const args = Array.prototype.slice.call(arguments, 1);
BlockPalette.categories.forEach(function(category) {
category[functionName].apply(category, args);
});
};
/**
* Reloads all categories. Called when a new file is opened.
*/
BlockPalette.refresh = function() {
BlockPalette.categories.forEach(function(category) {
category.refreshGroup();
})
};
|
/**
* 反向代理
*/
var express = require('express');
//var proxy = require('http-proxy').createProxyServer();
var request = require('request');
var acluster = ["http://localhost:3000","http://localhost:3001"];
var aliveACluster = ["http://localhost:3000","http://localhost:3001"];;
var app = express();
setInterval(function(){
},60*1000*5);
function proxy(req,res,targets){
function next(){
var current = targets[0];
console.log(current);
request(current, function (error, response, body) {
if (!error && response.statusCode == 200) {
return res.end(body);
}else{
acluster.shift();
next();
}
})
}
next();
}
function proxyPass(config){
return function(req,res,next){
var target = config[req.hostname];
proxy(req,res,target);
}
}
app.use(proxyPass({
"a.zfpx.cn":aliveACluster,
"b.zfpx.cn":["http://localhost:4000"]
}));
app.listen(80);
//应用服务器A a.zfpx.cn
/*
var app3000 = express();
app3000.get('/',function(req,res){
res.end('3000');
});
app3000.listen(3000);
*/
var app3001 = express();
app3001.get('/',function(req,res){
res.end('3001');
});
app3001.listen(3001);
//应用服务器B b.zfpx.cn
var app4000 = express();
app4000.get('/',function(req,res){
res.end('4000');
});
app4000.listen(4000); |
export {default} from './HeaderGroup'
|
'use strict'
const autoprefixer = require('autoprefixer')
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin')
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin')
const eslintFormatter = require('react-dev-utils/eslintFormatter')
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin')
const getClientEnvironment = require('./env')
const paths = require('./paths')
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/'
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = ''
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl)
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web'
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
]
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint')
},
loader: require.resolve('eslint-loader')
}
],
include: paths.appSrc
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true
}
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1
}
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9' // React doesn't support IE8 anyway
],
flexbox: 'no-2009'
})
]
}
}
]
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.js$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]'
}
}
]
}
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
]
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false
}
}
|
import React from 'react';
class ValidateInput extends React.Component {
constructor(props) {
super(props);
this.state = {
validate: false
}
this.startValidating = this.startValidating.bind(this);
this.validate = this.validate.bind(this);
}
startValidating(e) {
if (!this.state.validate) {
e.persist();
// After first blur, start validating field on change
this.setState({
validate: true
}, () => {
this.validate(e)
})
}
}
validate(e) {
if (this.state.validate) {
this.props.validate(e);
} else {
this.props.update(e);
}
}
render() {
var error = this.props.errorMsg ?
<div className="error">{this.props.errorMsg}</div> : '';
return (
<div>
<label>
<span>{this.props.label}</span>
<input
ref='input'
type='text'
value={this.props.value}
placeholder={this.props.placeHolder}
onChange={this.validate}
onBlur={this.startValidating} />
</label>
{error}
</div>
)
}
}
ValidateInput.propTypes = {
label: React.PropTypes.string,
value: React.PropTypes.string,
placeHolder: React.PropTypes.string,
errorMsg: React.PropTypes.string
}
ValidateInput.defaultProps = {
label: '',
value: '',
placeHolder: ''
}
export default ValidateInput
|
import React, { Component, PropTypes } from "react";
import {
View,
Text,
Dimensions,
StyleSheet,
TouchableOpacity
} from "react-native";
import { withNavigation } from "@expo/ex-navigation";
import colors from "kolors";
import Collapsible from "react-native-collapsible";
import ElevatedView from "fiber-react-native-elevated-view";
import Router from "Router";
import connectDropdownAlert from "../utils/connectDropdownAlert";
import createWazeDeepLink from "../utils/createWazeDeepLink";
import { phonecall } from "react-native-communications";
import CardSublabel from "./styled/CardSublabel";
import CardLabel from "./styled/CardLabel";
import CardHeader from "./styled/CardHeader";
import CardIndicator from "./styled/CardIndicator";
import { observer, inject } from "mobx-react/native";
import { observable } from "mobx";
import _ from "lodash";
@withNavigation
@connectDropdownAlert
@inject("authStore")
@observer
export default class Carpooler extends Component {
static propTypes = {
user: PropTypes.object.isRequired,
event: PropTypes.object.isRequired,
authStore: PropTypes.object.isRequired,
pickedUpUsers: PropTypes.number,
navigator: PropTypes.object.isRequired,
navigation: PropTypes.object.isRequired,
passengers: PropTypes.array.isRequired,
refresh: PropTypes.func,
selfIsDriver: PropTypes.bool,
alertWithType: PropTypes.func.isRequired
};
@observable isCollapsed = true;
confirmAttendance = () => {
const passIndex = this.props.event.yourRide.passengers.findIndex(
i => i.userUID === this.props.user.userUID
);
global.firebaseApp
.database()
.ref("schools")
.child(this.props.event.schoolUID)
.child("events")
.child(this.props.event.uid)
.child("rides")
.child(this.props.event.yourRide.uid)
.child("passengers")
.child(this.props.event.yourRide.passengers[passIndex].passUID)
.update({ isPickedUp: !this.props.user.isPickedUp })
.then(() => {
this.props.refresh(false);
})
.catch(err => {
this.props.alertWithType("error", "Error", err.toString());
});
};
contact = () => {
phonecall(this.props.user.phoneNumber, true);
};
meetDriver = () => {
let self;
let pickupLocation;
let driver;
this.props.passengers.forEach(pass => {
if (pass.userUID === this.props.authStore.userId) {
self = pass;
}
});
global.firebaseApp
.database()
.ref("schools")
.child(self.school)
.child("pickupLocations")
.once("value")
.then(pickupLocationsSnap => {
const pickupLocations = pickupLocationsSnap.val();
_.each(pickupLocations, location => {
if (location.name === self.location) {
pickupLocation = location;
}
});
global.firebaseApp
.database()
.ref("users")
.child(this.props.event.yourRide.driver)
.once("value")
.then(driverSnap => {
driver = driverSnap.val();
this.props.navigation.getNavigator("master").push(
Router.getRoute("pickup", {
self,
driver,
pickupLocation
})
);
});
})
.catch(err => {
this.props.alertWithType("error", "Error", err.toString());
});
};
pickup = () => {
global.firebaseApp
.database()
.ref("schools")
.child(this.props.user.school)
.child("pickupLocations")
.once("value")
.then(locSnap => {
let location;
_.each(locSnap.val(), loc => {
if (loc.name === this.props.user.location) {
location = loc;
}
});
this.props.navigation.getNavigator("master").push(
Router.getRoute("pickup", {
pickupLocation: location,
rider: this.props.user,
wazeUrl: createWazeDeepLink(location.lat, location.lon)
})
);
})
.catch(err => {
this.props.alertWithType("error", "Error", err.toString());
});
};
renderDriverContent = () => // driver view if you're a rider
(
<View style={styles.collapsedContentContainer}>
<TouchableOpacity onPress={() => this.contact()}>
<View style={styles.contactDriverButton}>
<Text style={styles.buttonText}>
CONTACT
</Text>
</View>
</TouchableOpacity>
{!this.props.event.yourRide.rideStarted &&
<TouchableOpacity onPress={() => this.meetDriver()}>
<View style={styles.meetDriverButton}>
<Text style={styles.buttonText}>
MEET FOR PICKUP
</Text>
</View>
</TouchableOpacity>}
</View>
);
renderPeerPassengerContent = () => // rider view if you're a rider (or if you're a rider you shouldn't have access to other's stuff)
(
<View style={styles.collapsedContentContainer}>
<TouchableOpacity onPress={() => this.contact()}>
<View style={styles.contactDriverButton}>
<Text style={styles.buttonText}>
CONTACT
</Text>
</View>
</TouchableOpacity>
</View>
);
renderDriverPassengerContent = () => // rider view if you're a driver
(
<View style={styles.collapsedContentContainer}>
<View style={styles.twoButtonRow}>
<TouchableOpacity onPress={() => this.contact()}>
<View style={styles.leftButton}>
<Text style={styles.buttonText}>
CONTACT
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.pickup()}>
<View style={styles.rightButton}>
<Text style={styles.buttonText}>
PICKUP
</Text>
</View>
</TouchableOpacity>
</View>
<TouchableOpacity onPress={() => this.confirmAttendance()}>
<View style={styles.bottomButton}>
<Text style={styles.buttonText}>
{this.props.user.isPickedUp
? "UNCONFIRM ATTENDANCE"
: "CONFIRM ATTENDANCE"}
</Text>
</View>
</TouchableOpacity>
</View>
);
render() {
return (
this.props.user.userUID !== this.props.authStore.userId &&
<ElevatedView
onPress={() => {
this.isCollapsed = !this.isCollapsed;
}}
style={styles.cardContainer}
elevation={2}
feedbackEnabled
activeElevation={4}
>
<CardHeader>
<CardLabel>
{this.props.user.displayName.toUpperCase()}
</CardLabel>
<CardSublabel>
{this.props.user.type.toUpperCase()}
</CardSublabel>
</CardHeader>
<CardIndicator
active={
this.props.pickedUpUsers === this.props.passengers.length ||
(this.props.event.yourRide.rideStarted ||
this.props.user.isPickedUp)
}
/>
<Collapsible duration={200} collapsed={this.isCollapsed}>
{this.props.selfIsDriver &&
this.props.user.type === "rider" &&
this.renderDriverPassengerContent()}
{this.props.user.type === "rider" &&
!this.props.selfIsDriver &&
this.renderPeerPassengerContent()}
{this.props.user.type === "driver" && this.renderDriverContent()}
</Collapsible>
</ElevatedView>
);
}
}
const styles = StyleSheet.create({
cardContainer: {
flex: 1,
paddingVertical: 8,
paddingHorizontal: 16,
marginHorizontal: 8,
marginVertical: 4,
backgroundColor: "white"
},
collapsedContentContainer: {
marginTop: 16,
marginBottom: 8
},
contactDriverButton: {
justifyContent: "center",
alignItems: "center",
borderRadius: 4,
paddingVertical: 8,
backgroundColor: colors.blue
},
meetDriverButton: {
justifyContent: "center",
alignItems: "center",
borderRadius: 4,
paddingVertical: 8,
marginTop: 16,
backgroundColor: colors.hotPink
},
buttonText: {
fontFamily: "open-sans-bold",
fontSize: 18,
color: "white"
},
twoButtonRow: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
leftButton: {
marginRight: 8,
justifyContent: "center",
alignItems: "center",
borderRadius: 4,
width: Dimensions.get("window").width * 0.40,
paddingVertical: 8,
backgroundColor: colors.blue
},
rightButton: {
marginLeft: 8,
justifyContent: "center",
alignItems: "center",
borderRadius: 4,
paddingVertical: 8,
width: Dimensions.get("window").width * 0.40,
backgroundColor: colors.hotPink
},
bottomButton: {
justifyContent: "center",
alignItems: "center",
borderRadius: 4,
paddingVertical: 8,
backgroundColor: colors.neonGreen,
marginTop: 16
}
});
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M18.71 13.29 22.3 9.7c.39-.39.39-1.02 0-1.41a.9959.9959 0 0 0-1.41 0L19 10.17V4c0-.55-.45-1-1-1s-1 .45-1 1v6.17l-1.89-1.88a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l3.59 3.59c.4.39 1.03.39 1.42 0z"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M17 18H7V6h7V1H7c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2v-5h-2v2z"
}, "1")], 'InstallMobileRounded'); |
require("babel-core/register");
var app = require('./server/app');
|
const camelCase = require('camelcase');
const isPlainObject = require('is-plain-object');
const camelizeObject = (data, exceps) => {
if (Array.isArray(data)) return data.map(item => camelizeObject(item));
if (!isPlainObject(data)) return data;
return Object.keys(data).reduce((result, key) => {
const newKey = isException(key, exceps || []) ? key : camelCase(key);
if (isPlainObject(data[key])) return camelDeepObject(newKey, result, data[key], exceps);
if (Array.isArray(data[key])) return camelArray(newKey, result, data[key], exceps);
return camelPropery(newKey, result, data[key]);
}, {});
};
const isException = (key, exceps) => exceps.indexOf(key) > -1;
const camelDeepObject = (newKey, result, data, exceps) => {
const func = () => camelizeObject(data, exceps);
return applyOnResult(newKey, result, func);
};
const camelArray = (newKey, result, dataArr, exceps) => {
const func = () => dataArr.map(item => camelizeObject(item, exceps));
return applyOnResult(newKey, result, func);
};
const camelPropery = (newKey, result, data) => {
const func = () => data;
return applyOnResult(newKey, result, func);
};
const applyOnResult = (newKey, result, func) => {
const partial = {};
partial[newKey] = func();
return Object.assign({}, result, partial);
};
module.exports = camelizeObject;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.