text
stringlengths 2
6.14k
|
|---|
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
var fs = require('fs');
var path = require('path');
exports.up = function(db, callback) {
var filePath = path.join(__dirname + '/sqls/20160708081226-readme-in-versions-up.sql');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (err) return callback(err);
console.log('received data: ' + data);
db.runSql(data, function(err) {
if (err) return callback(err);
callback();
});
});
};
exports.down = function(db, callback) {
var filePath = path.join(__dirname + '/sqls/20160708081226-readme-in-versions-down.sql');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (err) return callback(err);
console.log('received data: ' + data);
db.runSql(data, function(err) {
if (err) return callback(err);
callback();
});
});
};
|
'use strict';
var Primus = require('primus')
, emitter = require('../')
, http = require('http').Server
, expect = require('expect.js')
, opts = { transformer: 'websockets' }
, primus
, srv;
// creates the client
function client(srv, primus, port){
var addr = srv.address();
var url = 'http://' + addr.address + ':' + (port || addr.port);
return new primus.Socket(url);
}
// creates the server
function server(srv, opts) {
return Primus(srv, opts).use('emitter', emitter);
}
describe('primus-emitter', function () {
beforeEach(function beforeEach(done) {
srv = http();
primus = server(srv, opts);
done();
});
afterEach(function afterEach(done) {
primus.end();
done();
});
it('should have required methods', function (done) {
//primus.save('testt.js');
srv.listen(function () {
primus.on('connection', function (spark) {
expect(spark.reserved).to.be.a('function');
expect(spark.send).to.be.a('function');
expect(spark.on).to.be.a('function');
done();
});
var cl = client(srv, primus);
expect(cl.reserved).to.be.a('function');
});
});
it('should emit event from server', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
spark.send('news', 'data');
});
var cl = client(srv, primus);
cl.on('news', function (data) {
expect(data).to.be('data');
done();
});
});
});
it('should emit object from server', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.send('news', msg);
});
var cl = client(srv, primus);
cl.on('news', function (data) {
expect(data).to.be.eql(msg);
done();
});
});
});
it('should support ack from server', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.send('news', msg, function (err, res) {
expect(res).to.be('received');
expect(err).to.be.eql(null);
done();
});
});
var cl = client(srv, primus);
cl.on('news', function (data, fn) {
fn(null, 'received');
});
});
});
it('should emit event from client', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
spark.on('news', function (data) {
expect(data).to.be('data');
done();
});
});
var cl = client(srv, primus);
cl.send('news', 'data');
});
});
it('should emit object from client', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.on('news', function (data) {
expect(data).to.be.eql(msg);
done();
});
});
var cl = client(srv, primus);
cl.send('news', msg);
});
});
it('should support ack from client', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.on('news', function (data, fn) {
fn(null, 'received');
});
});
var cl = client(srv, primus);
cl.send('news', msg, function (err, res) {
expect(res).to.be('received');
expect(err).to.be.eql(null);
done();
});
});
});
it('should support broadcasting from server', function (done) {
var total = 0;
srv.listen(function () {
primus.on('connection', function (spark) {
if (3 === ++total) primus.send('news', 'hi');
});
var cl1 = client(srv, primus)
, cl2 = client(srv, primus)
, cl3 = client(srv, primus);
cl1.on('news', function (msg) {
expect(msg).to.be('hi');
finish();
});
cl2.on('news', function (msg) {
expect(msg).to.be('hi');
finish();
});
cl3.on('news', function (msg) {
expect(msg).to.be('hi');
finish();
});
function finish() {
if (1 > --total) done();
}
});
});
it('should return `Primus` instance when broadcasting from server', function () {
expect(primus.send('news')).to.be.a(Primus);
srv.listen();
});
it('`Client#send` should not trigger `Spark` reserved events', function (done) {
var events = Object.keys(primus.Spark.prototype.reserved.events);
srv.listen(function () {
primus.on('connection', function (spark) {
events.forEach(function (ev) {
spark.on(ev, function (data) {
if ('not ignored' === data) {
done(new Error('should be ignored'));
}
});
});
});
});
var cl = client(srv, primus);
cl.on('open', function () {
events.forEach(function (ev) {
cl.send(ev, 'not ignored');
});
done();
});
});
it('`Spark#send` should not trigger client reserved events', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
events.forEach(function (ev) {
spark.send(ev, 'not ignored');
});
done();
});
});
var cl = client(srv, primus)
, events = Object.keys(cl.reserved.events);
events.forEach(function (ev) {
cl.on(ev, function (data) {
if ('not ignored' === data) {
done(new Error('should be ignored'));
}
});
});
});
it('should only listen to event once when binding with `once`', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
spark.once('news', function (data) {
expect(data).to.be('once');
done();
});
});
var cl = client(srv, primus);
cl.send('news', 'once');
cl.send('news', 'once');
});
});
});
|
import React from 'react';
import styled from 'styled-components';
const Emoji = ({ className, svg }) => (
<span className={className} dangerouslySetInnerHTML={{ __html: svg }} />
);
const StyledEmoji = styled(Emoji)`
display: inline-block;
width: 1.5em;
`;
export default StyledEmoji;
|
var opener = require("opener");
module.exports = {
run : function (){
opener(packageJson.docs);
}
}
|
import _curry3 from './internal/_curry3';
/**
* `o` is a curried composition function that returns a unary function.
* Like [`compose`](#compose), `o` performs right-to-left function composition.
* Unlike [`compose`](#compose), the rightmost function passed to `o` will be
* invoked with only one argument. Also, unlike [`compose`](#compose), `o` is
* limited to accepting only 2 unary functions. The name o was chosen because
* of its similarity to the mathematical composition operator ∘.
*
* @func
* @memberOf R
* @since v0.24.0
* @category Function
* @sig (b -> c) -> (a -> b) -> a -> c
* @param {Function} f
* @param {Function} g
* @return {Function}
* @see R.compose, R.pipe
* @example
*
* var classyGreeting = name => "The name's " + name.last + ", " + name.first + " " + name.last
* var yellGreeting = R.o(R.toUpper, classyGreeting);
* yellGreeting({first: 'James', last: 'Bond'}); //=> "THE NAME'S BOND, JAMES BOND"
*
* R.o(R.multiply(10), R.add(10))(-4) //=> 60
*
* @symb R.o(f, g, x) = f(g(x))
*/
var o = _curry3(function o(f, g, x) {
return f(g(x));
});
export default o;
|
/*
*--------------------------------------------------------------------
* jQuery-Plugin "lookupreferer -config.js-"
* Version: 3.0
* Copyright (c) 2018 TIS
*
* Released under the MIT License.
* http://tis2010.jp/license.txt
* -------------------------------------------------------------------
*/
jQuery.noConflict();
(function($,PLUGIN_ID){
"use strict";
var vars={
fieldtable:null,
fieldinfos:{}
};
var functions={
fieldsort:function(layout){
var codes=[];
$.each(layout,function(index,values){
switch (values.type)
{
case 'ROW':
$.each(values.fields,function(index,values){
/* exclude spacer */
if (!values.elementId) codes.push(values.code);
});
break;
case 'GROUP':
$.merge(codes,functions.fieldsort(values.layout));
break;
case 'SUBTABLE':
$.each(values.fields,function(index,values){
/* exclude spacer */
if (!values.elementId) codes.push(values.code);
});
break;
}
});
return codes;
}
};
/*---------------------------------------------------------------
initialize fields
---------------------------------------------------------------*/
kintone.api(kintone.api.url('/k/v1/app/form/layout',true),'GET',{app:kintone.app.getId()},function(resp){
var sorted=functions.fieldsort(resp.layout);
/* get fieldinfo */
kintone.api(kintone.api.url('/k/v1/app/form/fields',true),'GET',{app:kintone.app.getId()},function(resp){
var config=kintone.plugin.app.getConfig(PLUGIN_ID);
vars.fieldinfos=$.fieldparallelize(resp.properties);
$.each(sorted,function(index){
if (sorted[index] in vars.fieldinfos)
{
var fieldinfo=vars.fieldinfos[sorted[index]];
if (fieldinfo.lookup)
$('select#field').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label));
}
});
/* initialize valiable */
vars.fieldtable=$('.fields').adjustabletable({
add:'img.add',
del:'img.del'
});
var add=false;
var fields=[];
if (Object.keys(config).length!==0)
{
fields=JSON.parse(config['fields']);
for (var i=0;i<fields.length;i++)
{
if (add) vars.fieldtable.addrow();
else add=true;
$('select#field',vars.fieldtable.rows.last()).val(fields[i]);
}
}
},function(error){});
},function(error){});
/*---------------------------------------------------------------
button events
---------------------------------------------------------------*/
$('button#submit').on('click',function(e){
var row=null;
var config=[];
var fields=[];
/* check values */
for (var i=0;i<vars.fieldtable.rows.length;i++)
{
row=vars.fieldtable.rows.eq(i);
if ($('select#field',row).val().length==0) continue;
fields.push($('select#field',row).val());
}
if (fields.length==0)
{
swal('Error!','ルックアップアプリ表示フィールドは1つ以上指定して下さい。','error');
return;
}
/* setup config */
config['fields']=JSON.stringify(fields);
/* save config */
kintone.plugin.app.setConfig(config);
});
$('button#cancel').on('click',function(e){
history.back();
});
})(jQuery,kintone.$PLUGIN_ID);
|
// calculate the area of a circle based on its radius
function calcCircleArea(r) {
var area = Math.PI * Math.pow(r, 2); // area is pi times radius squared
return area;
}
console.log(calcCircleArea(35))
|
import uiRouter from 'angular-ui-router';
import ngRoute from 'angular-route';
import ContactController from './contact.controller';
import ContactResourceService from './contact-resource.service';
import ConfirmClick from '../directives/confirm-click';
export default angular.module('Contact', [
uiRouter,
ngRoute
])
.controller('contactController', ContactController)
.service('contactResourceService', ContactResourceService)
.directive('confirmClick', ConfirmClick)
.name;
|
var common = require('../common');
var assert = common.assert;
var SandboxedModule = require(common.dir.lib + '/sandboxed_module');
(function testRequire() {
var foo = SandboxedModule.load('../fixture/foo').exports;
assert.strictEqual(foo.foo, 'foo');
assert.strictEqual(foo.bar, 'bar');
})();
|
'use strict';
/* global describe it */
// core modules
var assert = require('assert');
// local modules
var makeValueFullResult = require('../../lib/consumers/makeValueFullResult.js');
var single = require('../../lib/consumers/single.js');
var Stream = require('../../lib/streams/stream.js');
describe('makeValueFullResult', function() {
it('makes value full result', function() {
var stream = Stream('x');
var consumer = makeValueFullResult(single('x'));
var parseResult = consumer.consume(stream);
assert.equal(parseResult.value.name, '"x"');
assert.equal(parseResult.value.value, 'x');
assert.equal(parseResult.value.accepted, true);
assert.equal(parseResult.value.valid, true);
assert.equal(parseResult.value.invalidations.length, 0);
assert.equal(parseResult.value.location.length, 2);
});
});
|
'use strict';
angular.module('adds').controller('QuestionController', ['$scope',
function($scope) {
// Question controller logic
// ...
}
]);
|
/* jshint esversion : 6 */
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '@mysql',
database : 'node-backend'
});
connection.connect();
// dummy function pour vérifier si la connectione à la base est bien établie
connection.query('SELECT 42 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('DATABASE SAYS => The solution is', results[0].solution);
});
const get = (clbk, id) => {
var query;
if (id) query = `SELECT id, mail, avatar, about, is_admin FROM users WHERE id = ${connection.escape(id)}`;
else query = 'SELECT id, mail, avatar, about, is_admin FROM users';
connection.query(query, (error, results, fields) => {
if (error) throw error; // en cas d'erreur, une exception est levée
clbk(results); // on passe les résultats de la requête en argument de la fonction callback
});
};
const checkMail = (clbk, mail) => {
const query = `SELECT COUNT(*) as count FROM users WHERE mail = ${connection.escape(mail)}`;
connection.query(query, (error, results, fields) => {
if (error) throw error; // en cas d'erreur, une exception est levée
clbk(results); // passe les résultats de requête en arg du callback
});
};
const register = (clbk, data) => {
checkMail(res => {
// console.log(res);
if (res[0].count > 0) { // cette adresse mail est déjà en base
return clbk({error: true, message: "mail already exists"});
}
// la base ne contient pas encore cette adresse mail, poursuivons l'insertion
let query = `INSERT INTO users (mail, password) VALUES
(${connection.escape(data.mail)}, ${connection.escape(data.password)})`;
connection.query(query, (error, results, fields) => {
if (error) throw error;
results.error = false;
results.message = "tadaa : you're now registered !!!";
clbk(results);
});
}, data.mail);
};
const remove = (clbk, id) => {
const query = `DELETE FROM users WHERE id = ${connection.escape(id)}`;
connection.query(query, (error, results, fields) => {
if (error) throw error; // en cas d'erreur, une exception est levée
results.error = false;
results.message = "user has been removed from database";
clbk(results); // on passe les résultats de la requête en argument de la fonction callback
});
};
const login = (clbk, data) => {
const q = `SELECT id, mail, avatar, about, is_admin FROM users WHERE mail = '${data.mail}' AND password = '${data.password}' GROUP BY id`;
// console.log(q);
connection.query(q, (error, results, fields) => {
if (error) throw error;
const tmp = results[0] || results;
const res = {};
if (Array.isArray(tmp) && !tmp.length) {
res.message = "Mauvais mail ou mot de passe";
} else {
res.user = tmp;
res.message = "Yay : You're now logged in !!";
}
clbk(res);
});
};
const patchAbout = (clbk, about, id) => {
const q = `UPDATE users SET about = ${connection.escape(about)} WHERE id = ${id}`;
// console.log(q);
connection.query(q, (error, results, fields) => {
if (error) throw error;
clbk(results);
});
};
const patchAvatar = (clbk, avatar, id) => {
const q = `UPDATE users SET avatar = ${connection.escape(avatar)} WHERE id = ${id}`;
// console.log(q);
connection.query(q, (error, results, fields) => {
if (error) throw error;
clbk(results);
});
};
module.exports = {
register,
get,
login,
patch: {
about: patchAbout,
avatar: patchAvatar,
},
remove: remove,
};
|
define(['plugins/router', 'durandal/app', 'services/config', 'services/datacontext', 'services/logger','knockout'], function (router, app, config, datacontext, logger,ko) {
var routes = ko.observableArray([]);
var isAdminUser = ko.observable();
var showSplash = ko.observable(false);
var vm = {
router: router,
showSplash:showSplash,
isAdminUser:isAdminUser,
routes:routes,
activate: activate,
deactivate:deactivate
};
return vm;
//called automatically by Durandal
function activate() {
return datacontext.fetchMetadata().then(function() {
return true;
}).then(function() {
return datacontext.getUserAccountDataLocal()
.then(function () {
return isAdminUser(datacontext.checkAdmin());
});
}).then(function() {
window.globalRoutes.forEach(function(r) {
routes.push(r);
});
return router.map(routes()).buildNavigationModel();
}).then(function () {
setupRouter();
return boot();
}).fail(function(e) {
return logger.log(e.message,null,null,true);
});
}
function setupRouter() {
return router.mapUnknownRoutes('dashboard/index', 'not-found');
}
function boot() {
return router.activate();
}
function deactivate() {
return true;
}
});
|
/**
* @license Highmaps JS v9.3.2 (2021-11-29)
* @module highcharts/modules/tilemap
* @requires highcharts
* @requires highcharts/modules/map
*
* Tilemap module
*
* (c) 2010-2021 Highsoft AS
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/Tilemap/TilemapSeries.js';
|
var mailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var config = require('../config');
var util = require('util');
var transport = mailer.createTransport(smtpTransport(config.mail_opts));
//域名domain没有的时留空,devMode下读取host
var SITE_ROOT_URL = 'http://' + ((config.domain && !config.devMode)?config.domain:(config.host+":"+config.port));
/**
* Send an email
* @param {Object} data 邮件对象
*/
var sendMail = function (data) {
//need_active_mail=false不发送邮件
if (!config.need_active_mail) {
return;
}
// 遍历邮件数组,发送每一封邮件,如果有发送失败的,就再压入数组,同时触发mailEvent事件
transport.sendMail(data, function (err) {
if (err) {
// 写为日志
console.log(err);
}
});
};
exports.sendMail = sendMail;
/**
* 发送激活通知邮件
* @param {String} who 接收人的邮件地址
* @param {String} token 重置用的token字符串
* @param {String} name 接收人的用户名
*/
exports.sendActiveMail = function (who, token, name) {
var from = util.format('%s <%s>', config.name, config.mail_opts.auth.user);
var to = who;
var subject = config.name + '帐号激活';
var html = '<p>您好:' + name + '</p>' +
'<p>我们收到您在' + config.name + '的注册信息,请点击下面的链接来激活帐户:</p>' +
'<a href = "' + SITE_ROOT_URL + '/active_account?key=' + token + '&name=' + name + '">激活链接</a>' +
'<p>若您没有在' + config.name + '填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' +
'<p>' + config.name + ' 谨上。</p>';
exports.sendMail({
from: from,
to: to,
subject: subject,
html: html
});
};
/**
* 发送密码重置通知邮件
* @param {String} who 接收人的邮件地址
* @param {String} token 重置用的token字符串
* @param {String} name 接收人的用户名
*/
exports.sendResetPassMail = function (who, token, name) {
var from = util.format('%s <%s>', config.name, config.mail_opts.auth.user);
var to = who;
var subject = config.name + '密码重置';
var html = '<p>您好:' + name + '</p>' +
'<p>我们收到您在' + config.name + '重置密码的请求,请在24小时内单击下面的链接来重置密码:</p>' +
'<a href="' + SITE_ROOT_URL + '/reset_pass?key=' + token + '&name=' + name + '">重置密码链接</a>' +
'<p>若您没有在' + config.name + '填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' +
'<p>' + config.name + ' 谨上。</p>';
exports.sendMail({
from: from,
to: to,
subject: subject,
html: html
});
};
|
import React from 'react';
import IconBase from 'react-icon-base';
export default class FaUserMd extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m13.1 30q0 0.6-0.5 1t-1 0.4-1-0.4-0.4-1 0.4-1 1-0.4 1 0.4 0.5 1z m22.8 1.4q0 2.7-1.6 4.2t-4.3 1.5h-19.5q-2.7 0-4.4-1.5t-1.6-4.2q0-1.6 0.1-3t0.6-3 1-3 1.8-2.3 2.7-1.4q-0.5 1.2-0.5 2.7v4.6q-1.3 0.4-2.1 1.5t-0.7 2.5q0 1.8 1.2 3t3 1.3 3.1-1.3 1.2-3q0-1.4-0.8-2.5t-2-1.5v-4.6q0-1.4 0.5-2 3 2.3 6.6 2.3t6.6-2.3q0.6 0.6 0.6 2v1.5q-2.4 0-4.1 1.6t-1.7 4.1v2q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.6t1.5 0.6 1.5-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.2 0.9-2t2-0.9 2 0.9 0.8 2v2q-0.7 0.6-0.7 1.5 0 0.9 0.6 1.6t1.5 0.6 1.6-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.5-0.8-2.9t-2.1-2.1q0-0.2 0-0.9t0-1.1 0-0.9-0.2-1.1-0.3-0.8q1.5 0.3 2.7 1.3t1.8 2.3 1.1 3 0.5 3 0.1 3z m-7.1-20q0 3.6-2.5 6.1t-6.1 2.5-6-2.5-2.6-6.1 2.6-6 6-2.5 6.1 2.5 2.5 6z"/></g>
</IconBase>
);
}
}
|
class KnormError extends Error {
constructor(...args) {
const [message] = args;
const hasMessage = typeof message === 'string';
super(hasMessage ? message : undefined);
if (!hasMessage) {
this.message = this.formatMessage(...args);
}
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error(this.message).stack;
}
}
formatMessage(message) {
return message;
}
}
export { KnormError };
|
import { AsyncStorage } from 'react-native';
import {applyMiddleware, compose, createStore} from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import client from './apolloClient';
import { initialState as configs } from '../reducers/configurations';
import rootReducer from '../reducers/index'
import {autoRehydrate, persistStore} from "redux-persist";
const isProduction = process.env.NODE_ENV !== 'development';
const isClient = typeof document !== 'undefined';
const initialState = {
configs,
};
/* Commonly used middlewares and enhancers */
/* See: http://redux.js.org/docs/advanced/Middleware.html*/
const middlewares = [thunk, client.middleware()];
const enhancers = [];
if (!isProduction && isClient) {
const loggerMiddleware = createLogger();
middlewares.push(loggerMiddleware);
if (typeof devToolsExtension === 'function') {
const devToolsExtension = window.devToolsExtension;
enhancers.push(devToolsExtension());
}
}
const composedEnhancers = compose(
applyMiddleware(...middlewares),
...enhancers
);
/* Hopefully by now you understand what a store is and how redux uses them,
* But if not, take a look at: https://github.com/reactjs/redux/blob/master/docs/api/createStore.md
* And https://egghead.io/lessons/javascript-redux-implementing-store-from-scratch
*/
const store = createStore(
rootReducer,
initialState,
composedEnhancers,
autoRehydrate(),
);
// Add the autoRehydrate middleware to your redux store
//const store_ = createStore(rootReducer, autoRehydrate());
//const createStoreWithMiddleware = applyMiddleware(...middlewares)(store);
/* See: https://github.com/reactjs/react-router-redux/issues/305 */
//export const history = syncHistoryWithStore(browserHistory, store);
/* Hot reloading of reducers. How futuristic!! */
/*if (module.hot) {
module.hot.accept('./reducers', () => {
/!*eslint-disable *!/ // Allow require
const nextRootReducer = require('./reducers').default;
/!*eslint-enable *!/
store.replaceReducer(nextRootReducer);
});
}*/
//export { store };
export default configureStore = (navReducer, onComplete) => {
let store = createStore(
rootReducer,
initialState,
composedEnhancers,
autoRehydrate(),
);
persistStore(store, { storage: AsyncStorage }, onComplete);
return store;
};
|
// @ts-check
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* @typedef {import('playwright').Page} Page
*/
const
h = include('tests/helpers');
/** @param {Page} page */
module.exports = (page) => {
beforeEach(async () => {
await page.evaluate(() => {
globalThis.removeCreatedComponents();
});
});
describe('b-checkbox simple usage', () => {
const
q = '[data-id="target"]';
it('providing of attributes', async () => {
await init({id: 'foo', name: 'bla'});
const
input = await page.$('#foo');
expect(
await input.evaluate((ctx) => [
ctx.tagName,
ctx.type,
ctx.name,
ctx.checked
])
).toEqual(['INPUT', 'checkbox', 'bla', false]);
});
it('checked checkbox', async () => {
const target = await init({checked: true, value: 'bar'});
expect(
await target.evaluate((ctx) => ctx.value)
).toBe('bar');
});
it('non-changeable checkbox', async () => {
const target = await init({changeable: false});
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.uncheck())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
});
it('checking a non-defined value (user actions)', async () => {
const target = await init();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
});
it('checking a predefined value (user actions)', async () => {
const target = await init({value: 'bar'});
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBe('bar');
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
});
it('checking a non-defined value (API)', async () => {
const target = await init();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.check())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.uncheck())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBeUndefined();
});
it('checking a predefined value (API)', async () => {
const target = await init({value: 'bar'});
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.check())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBe('bar');
expect(
await target.evaluate((ctx) => ctx.uncheck())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBe('bar');
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBeUndefined();
});
it('checkbox with a `label` prop', async () => {
const target = await init({
label: 'Foo'
});
expect(
await target.evaluate((ctx) => ctx.block.element('label').textContent.trim())
).toEqual('Foo');
const selector = await target.evaluate(
(ctx) => `.${ctx.block.element('label').className.split(' ').join('.')}`
);
await page.click(selector);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
});
async function init(attrs = {}) {
await page.evaluate((attrs) => {
const scheme = [
{
attrs: {
'data-id': 'target',
...attrs
}
}
];
globalThis.renderComponents('b-checkbox', scheme);
}, attrs);
return h.component.waitForComponent(page, q);
}
});
};
|
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import Collapse from '../Collapse';
import withStyles from '../styles/withStyles';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
marginTop: 8,
marginLeft: 12, // half icon
paddingLeft: 8 + 12, // margin + half icon
paddingRight: 8,
borderLeft: `1px solid ${
theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]
}`,
},
/* Styles applied to the root element if `last={true}` (controlled by `Step`). */
last: {
borderLeft: 'none',
},
/* Styles applied to the Transition component. */
transition: {},
});
const StepContent = React.forwardRef(function StepContent(props, ref) {
const {
active,
alternativeLabel,
children,
classes,
className,
completed,
last,
optional,
orientation,
TransitionComponent = Collapse,
transitionDuration: transitionDurationProp = 'auto',
TransitionProps,
...other
} = props;
if (process.env.NODE_ENV !== 'production') {
if (orientation !== 'vertical') {
console.error(
'Material-UI: <StepContent /> is only designed for use with the vertical stepper.',
);
}
}
let transitionDuration = transitionDurationProp;
if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {
transitionDuration = undefined;
}
return (
<div className={clsx(classes.root, { [classes.last]: last }, className)} ref={ref} {...other}>
<TransitionComponent
in={active}
className={classes.transition}
timeout={transitionDuration}
unmountOnExit
{...TransitionProps}
>
{children}
</TransitionComponent>
</div>
);
});
StepContent.propTypes = {
/**
* @ignore
* Expands the content.
*/
active: PropTypes.bool,
/**
* @ignore
* Set internally by Step when it's supplied with the alternativeLabel prop.
*/
alternativeLabel: PropTypes.bool,
/**
* Step content.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
*/
completed: PropTypes.bool,
/**
* @ignore
*/
last: PropTypes.bool,
/**
* @ignore
* Set internally by Step when it's supplied with the optional prop.
*/
optional: PropTypes.bool,
/**
* @ignore
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The component used for the transition.
*/
TransitionComponent: PropTypes.elementType,
/**
* Adjust the duration of the content expand transition.
* Passed as a prop to the transition component.
*
* Set to 'auto' to automatically calculate transition time based on height.
*/
transitionDuration: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }),
PropTypes.oneOf(['auto']),
]),
/**
* Props applied to the `Transition` element.
*/
TransitionProps: PropTypes.object,
};
export default withStyles(styles, { name: 'MuiStepContent' })(StepContent);
|
var fs = require("fs");
var http = require("http");
var fileName = __dirname + "/ipsum.txt";
var server = http.createServer(function (req, res) {
fs.exists(fileName, function(exists) {
if (exists) {
fs.stat(fileName, function(error, stats) {
if (error) {
throw error;
}
if (stats.isFile()) {
var stream = fs.createReadStream(fileName);
stream.pipe(res);
}
});
}
});
}).listen(process.env.PORT || 8000, process.env.HOST || "0.0.0.0", function() {
console.log("HTTP Server Started. Listening on " + server.address().address + " : Port " + server.address().port);
});
|
'use strict';
module.exports = function (t, a) {
a(t(), false, "Undefined");
a(t(1), false, "Primitive");
a(t({}), false, "Objectt");
a(t({
toString: function () {
return '[object Error]';
}
}), false,
"Fake error");
a(t(new Error()), true, "Error");
a(t(new EvalError()), true, "EvalError");
a(t(new RangeError()), true, "RangeError");
a(t(new ReferenceError()), true, "ReferenceError");
a(t(new SyntaxError()), true, "SyntaxError");
a(t(new TypeError()), true, "TypeError");
a(t(new URIError()), true, "URIError");
};
|
var config = require('./config'),
db;
function warn() {
console.warn('[WARN] MongoDB:', [].join.call(arguments, ' '));
}
function getDB(done) {
if (db) return done(db);
if (!config.mongoURI) return warn('No DB configured!');
require('mongodb').MongoClient.connect(config.mongoURI, function(err, _db) {
if (err) return warn('Failed to connect ->', err.message);
db = _db;
done(db);
});
}
function store(coll, data) {
data.now = new Date().toISOString();
getDB(function(db) {
db.collection(coll).insert(data, function(err) {
if (err) warn('Failed to insert to', coll, '->', err.message);
// Do nothing
});
});
}
exports.getEmailsByTo = function(to, done) {
getDB(function(db) {
db.collection(config.emailsCollection).find({to:to}).toArray(done);
});
};
exports.storeEmail = function(data) {
store(config.emailsCollection, data);
};
exports.storeError = function(data) {
store(config.errorsCollection, data);
};
|
export default class TeamScoreModel {
constructor(props) {
this.id = props.id
this.teamId = props.team_id
this.defencePoints = props.defence_points
this.attackPoints = props.attack_points
}
get totalPoints() {
return this.defencePoints + this.attackPoints
}
}
|
// Multiform extraction
|
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', '../util/data'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('../util/data'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.data);
global.attached = mod.exports;
}
})(this, function (exports, module, _utilData) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _data = _interopRequireDefault(_utilData);
module.exports = function (opts) {
return function () {
var info = (0, _data['default'])(this, 'lifecycle/' + opts.id);
if (info.attached) return;
info.attached = true;
info.detached = false;
opts.attached(this);
};
};
});
|
var Col = require('./Col')
module.exports = Col
// export { default } from './Col'
|
// ___ ____ __ __
// / _ `/ _ \\ \ /
// \_,_/ .__/_\_\
// /_/
//
// 過去は未来によって変えられる。
//
// Copyright (c) 2014 Kenan Sulayman aka apx
//
// Based on third-party code:
//
// Copyright (c) 2010 Tom Hughes-Croucher
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
var dgram = require("dgram"),
util = require("util");
var host = "localhost",
port = process.env.port || 53;
const rev = 13;
var server = dgram.createSocket("udp4");
var dnx = Object.create({
records: {},
addRecord: function (domain) {
this.records[domain] = {
in: {
a: []//,
// not implemented
}
};
var qname = this.toolchain.utils.domainToQname(domain);
return {
delegate: function (r) {
if ( typeof r.rdata === "string" ) {
r.rdata = this.toolchain.utils.ip2dec(r.rdata);
}
if ( !r["qname"] ) {
r["qname"] = qname;
}
r["zname"] = domain;
if ( !this.records[domain] )
this.records[domain] = {};
if ( !this.records[domain]["in"] )
this.records[domain]["in"] = {};
if ( !this.records[domain]["in"][r.type || "a"] )
this.records[domain]["in"][r.type || "a"] = [];
return this.records[domain]["in"][r.type || "a"].push(r), r;
}.bind(this)
};
},
server: server,
toolchain: require("./lib/toolchain")
});
server.on("message", function(msg, rinfo) {
// parse query
var q = dnx.toolchain.processRequest(msg);
// build response
var buf = dnx.toolchain.createResponse(q, dnx.records);
dnx.server.send(buf, 0, buf.length, rinfo.port, rinfo.address);
});
server.addListener("error", function(e) {
throw e;
});
var config = require("./config.json");
Object.keys(config).forEach(function (e) {
var r = dnx.addRecord(e)
config[e].forEach(function (rx) {
r.delegate(rx);
})
})
server.bind(port, host);
console.log([
" __ ",
" ___/ /__ __ __",
"/ _ / _ \\\\ \\ /",
"\\_,_/_//_/_\\_\\",
" \t",
"[dnx r" + rev + "]",
""
].join("\n"))
require("dns").resolve(host, function (err, data) {
var revlookup = data ? " (" + data.join(", ") + ")" : "";
console.log("Delegation:");
Object.keys(dnx.records).forEach(function (d) {
console.log("\t=> ", d);
Object.keys(dnx.records[d]).forEach(function (c) {
Object.keys(dnx.records[d][c]).forEach(function (r) {
console.log("\t\t" + c + ": " + r + ":");
dnx.records[d][c][r].forEach(function (rx) {
console.log("\t\t\t", rx.qname, " (" + rx["zname"] + "): ", util.inspect(rx, {depth: null}).split("{ ").join("{\n ").split("\n").join("\n\t\t\t\t").split(" }").join("\n\t\t\t }"))
})
})
});
})
process.stdout.write("\nStarted server: " + host + revlookup + ", using port " + port + ".");
});
|
'use strict'
import trumpet from 'trumpet'
import { trumpetInnerText } from './index'
import JsonStream from 'JSONStream'
// Myfox page not found is a code 200... must fix it!
const notFound200 = function () {
const parser = trumpet()
parser.select('head title', trumpetInnerText((data) => {
parser.status = 200
if (data.indexOf('Page not found') !== -1) {
parser.status = 404
const error = new Error('Page not found case returned by Myfox.')
error.status = 404
return parser.emit('error', error)
}
}))
return parser
}
// Myfox code KO is a code 200... must fix it and return error messages.
const codeKo200 = function () {
const parser = JsonStream.parse('code')
parser.on('data', (data) => {
if (data === 'KO') {
const error = new Error('Code KO returned by Myfox.')
error.status = 400
return parser.emit('error', error)
}
})
return parser
}
export { notFound200 as notFound200 }
export { codeKo200 as codeKo200 }
|
const chalk = require('chalk');
const { curry } = require('ramda');
const log = curry((color, string) => console.info(color(string)));
const good = log(chalk.green);
const info = log(chalk.cyan);
const warn = log(chalk.magenta);
const bad = log(chalk.red.bold);
module.exports = (server, port) => {
const resolve = (signal) => {
info('\n');
info(`Signal ${signal} received`);
info(`Express is shutting down on http://localhost:${port}`);
server.close();
good('\nThe server shutdown gracefully');
};
const reject = (signal, error) => {
warn('\nThe server did NOT shutdown gracefully\n');
bad(error);
};
const shutdown = (signal) => {
try {
resolve(signal);
process.exit(0);
} catch (error) {
reject(signal, error);
process.exit(-1);
}
};
const signals = ['SIGTERM', 'SIGHUP', 'SIGINT'];
signals.forEach(signal => process.on(signal, () => shutdown(signal)));
};
|
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackShellPlugin = require('webpack-shell-plugin');
const { join, resolve } = require('path');
var BUILD_DIR = resolve(__dirname, '../../priv/static');
var APP_DIR = __dirname;
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = {
entry:{
'app.bundle': [resolve(__dirname, 'js/App.jsx')],
'store.bundle': [resolve(__dirname, 'js/app/store.js')],
'dependencies.bundle': [
"react",
"react-dom",
"react-redux",
"redux-thunk",
"redux-logger",
"react-router-redux",
"react-router-dom",
"history",
"react-apollo",
"qrcode.react",
"graphql-tag",
"react-select",
"apollo-phoenix-websocket",
"jquery",
"phoenix",
"bootstrap",
]
},
output: {
path: BUILD_DIR,
publicPath: '/js',
filename: 'js/[name].js'
},
plugins: [
new WebpackShellPlugin({onBuildStart:['cp -R ../shared .']}),
new webpack.SourceMapDevToolPlugin(),
new ExtractTextPlugin('css/app.css', { allChunks: true }),
new webpack.EnvironmentPlugin({
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
DEBUG: process.env.NODE_ENV == 'development'
}),
new webpack.optimize.CommonsChunkPlugin({ name: "dependencies.bundle", filename: 'js/[name].js', minChunks: Infinity }),
// new webpack.ProvidePlugin({
// Promise: 'babel-polyfill'
// }),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
new CopyWebpackPlugin([{ from: resolve(join(__dirname, "./assets")) }], { ignore: [resolve(join(__dirname, '.gitkeep'))] })
],
resolve: {
extensions: ['.json', '.jsx', '.js']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
include: __dirname,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'react', 'stage-0'],
plugins: ['transform-decorators-legacy', 'transform-class-properties', ["resolver", { "resolveDirs": [resolve(join(__dirname, 'js'))] }]]
}
}
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
//resolve-url-loader may be chained before sass-loader if necessary
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader',
}
// { test: /\.png$/, loader: "url-loader?limit=100000" },
// { test: /\.jpg$/, loader: "file-loader" },
// { test: /\.(woff2?|svg)$/, loader: 'url?limit=10000' },
// { test: /\.(ttf|eot)$/, loader: 'file' },
// { test: /\.json$/, loader: "json-loader" }
]
}
};
module.exports = config;
|
var classNames = require('classnames');
var React = require('react/addons');
var Tappable = require('react-tappable');
var Transition = React.addons.CSSTransitionGroup;
var defaultControllerState = {
direction: 0,
fade: false,
leftArrow: false,
leftButtonDisabled: false,
leftIcon: '',
leftLabel: '',
leftAction: null,
rightArrow: false,
rightButtonDisabled: false,
rightIcon: '',
rightLabel: '',
rightAction: null,
title: ''
};
function newState (from) {
var ns = Object.assign({}, defaultControllerState);
if (from) Object.assign(ns, from);
delete ns.name; // may leak from props
return ns;
}
var NavigationBar = React.createClass({
contextTypes: {
app: React.PropTypes.object
},
propTypes: {
name: React.PropTypes.string
},
getInitialState () {
return newState(this.props);
},
componentDidMount () {
if (this.props.name) {
this.context.app.navigationBars[this.props.name] = this;
}
},
componentWillUnmount () {
if (this.props.name) {
delete this.context.app.navigationBars[this.props.name];
}
},
componentWillReceiveProps (nextProps) {
this.setState(newState(nextProps));
if (nextProps.name !== this.props.name) {
if (nextProps.name) {
this.context.app.navigationBars[nextProps.name] = this;
}
if (this.props.name) {
delete this.context.app.navigationBars[this.props.name];
}
}
},
update (state) {
state = newState(state);
// console.info('Updating NavigationBar ' + this.props.name, state);
this.setState(newState(state));
},
updateWithTransition (state, transition) {
state = newState(state);
if (transition === ('show-from-right' || 'reveal-from-left')) {
state.direction = 1;
} else if (transition === ('reveal-from-right' || 'show-from-left')) {
state.direction = -1;
} else if (transition === 'fade') {
state.fade = true;
}
// console.info('Updating NavigationBar ' + this.props.name + ' with transition ' + transition, state);
this.setState(state);
},
renderLeftButton () {
var className = classNames('NavigationBarLeftButton', {
'has-icon': this.state.leftArrow || this.state.leftIcon
});
return (
<Tappable onTap={this.state.leftAction} className={className} disabled={this.state.leftButtonDisabled} component="button">
{this.renderLeftArrow()}
{this.renderLeftIcon()}
{this.renderLeftLabel()}
</Tappable>
);
},
renderLeftArrow () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var arrow = this.state.leftArrow ? <span className="NavigationBarLeftArrow" /> : null;
return (
<Transition transitionName={transitionName}>
{arrow}
</Transition>
);
},
renderLeftIcon () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var className = classNames('NavigationBarLeftIcon', this.state.leftIcon);
var icon = this.state.leftIcon ? <span className={className} /> : null;
return (
<Transition transitionName={transitionName}>
{icon}
</Transition>
);
},
renderLeftLabel () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade) {
transitionName = 'NavigationBarTransition-Fade';
} else if (this.state.direction > 0) {
transitionName = 'NavigationBarTransition-Forwards';
} else if (this.state.direction < 0) {
transitionName = 'NavigationBarTransition-Backwards';
}
return (
<Transition transitionName={transitionName}>
<span key={Date.now()} className="NavigationBarLeftLabel">{this.state.leftLabel}</span>
</Transition>
);
},
renderTitle () {
var title = this.state.title ? <span key={Date.now()} className="NavigationBarTitle">{this.state.title}</span> : null;
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade) {
transitionName = 'NavigationBarTransition-Fade';
} else if (this.state.direction > 0) {
transitionName = 'NavigationBarTransition-Forwards';
} else if (this.state.direction < 0) {
transitionName = 'NavigationBarTransition-Backwards';
}
return (
<Transition transitionName={transitionName}>
<Tappable onTap={this.state.titleAction}>
{title}
</Tappable>
</Transition>
);
},
renderRightButton () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var button = (this.state.rightIcon || this.state.rightLabel) ? (
<Tappable key={Date.now()} onTap={this.state.rightAction} className="NavigationBarRightButton" disabled={this.state.rightButtonDisabled} component="button">
{this.renderRightLabel()}
{this.renderRightIcon()}
</Tappable>
) : null;
return (
<Transition transitionName={transitionName}>
{button}
</Transition>
);
},
renderRightIcon () {
if (!this.state.rightIcon) return null;
var className = classNames('NavigationBarRightIcon', this.state.rightIcon);
return <span className={className} />;
},
renderRightLabel () {
return this.state.rightLabel ? <span key={Date.now()} className="NavigationBarRightLabel">{this.state.rightLabel}</span> : null;
},
render () {
var className = classNames('NavigationBar', {
'has-left-arrow': this.state.leftArrow,
'has-left-icon': this.state.leftIcon,
'has-left-label': this.state.leftLabel,
'has-right-icon': this.state.rightIcon,
'has-right-label': this.state.rightLabel
});
return (
<div className={className}>
{this.renderLeftButton()}
{this.renderTitle()}
{this.renderRightButton()}
</div>
);
}
});
/*
function createController () {
var state = newState();
var listeners = [];
return {
update (ns) {
state = newState(ns);
listeners.forEach(fn => fn());
},
getState () {
return state;
},
addListener (fn) {
listeners.push(fn);
},
removeListener (fn) {
listeners = listeners.filter(i => fn !== i);
}
};
}
*/
export default NavigationBar;
|
define(['../../game', 'collectableItem', 'states/levels/LevelState'], function (game, CollectableItem, Parent) {
var map,
levelThreeFirstLayerBackground,
levelThreeSecondLayerPlatforms,
shampoosGroup,
shampoosCoordinates;
function Level3State() {
};
Level3State.prototype = new Parent();
Level3State.prototype.constructor = Level3State;
Level3State.prototype.preload = function () {
this.load.tilemap('LevelThreeMap', 'levels/LevelThreeMap.json', null, Phaser.Tilemap.TILED_JSON);
this.load.image('background', 'images/L3-CosmeticShop/wallpapers/golden-sands-beach-13840-1920x1200.jpg');
this.load.image('platforms', 'images/L3-CosmeticShop/bamboo-platform(32x32).ss.png');
this.load.image('shampoo', 'images/L3-CosmeticShop/shampoo.png');
};
Level3State.prototype.update = function () {
Parent.prototype.update.call(this, levelThreeSecondLayerPlatforms, shampoosGroup);
if (this.player.points === 410) {
this.player.level = 4;
game.state.start('level4', true, false, this.player, this.engine);
}
};
Level3State.prototype.createMap = function () {
// Load level one map
map = game.add.tilemap('LevelThreeMap');
map.addTilesetImage('background', 'background');
map.addTilesetImage('platforms', 'platforms');
levelThreeFirstLayerBackground = map.createLayer('LevelThree - background');
levelThreeFirstLayerBackground.resizeWorld();
levelThreeFirstLayerBackground.wrap = true;
levelThreeSecondLayerPlatforms = map.createLayer('LevelThree - platforms');
levelThreeSecondLayerPlatforms.resizeWorld();
levelThreeSecondLayerPlatforms.wrap = true;
// Set collision between player and platforms
map.setCollisionByExclusion([0], true, levelThreeSecondLayerPlatforms);
showLevelPrehistory();
};
Level3State.prototype.initializePlayer = function () {
//Place player graphics at the map
this.player.placeAtMap(50, 120);
Parent.prototype.initializePlayer.call(this);
};
Level3State.prototype.initializeCollectableItems = function () {
//Create shampoos
shampoosGroup = this.add.group();
shampoosGroup.enableBody = true;
shampoosCoordinates = [
{x: 50, y: 420},
{x: 185, y: 65},
{x: 215, y: 65},
{x: 195, y: 350},
{x: 315, y: 320},
{x: 350, y: 450},
{x: 510, y: 160},
{x: 415, y: 65},
{x: 595, y: 320},
{x: 700, y: 64},
{x: 670, y: 450},
{x: 990, y: 350},
{x: 1020, y: 350},
{x: 900, y: 65},
{x: 940, y: 65},
{x: 980, y: 65},
{x: 1130, y: 255},
{x: 1275, y: 195},
{x: 1400, y: 290},
{x: 1370, y: 290}
];
for (var i = 0; i < shampoosCoordinates.length; i += 1) {
var currentShampoo = shampoosCoordinates[i];
var x = currentShampoo.x;
var y = currentShampoo.y;
new CollectableItem(x, y, shampoosGroup, 'shampoo');
}
};
function showLevelPrehistory() {
var body = document.getElementsByTagName('body')[0],
div = document.createElement('div'),
span,
spanText,
divPrehistory,
spanInDivPrehistory,
spanInDivPrehistoryText,
continueGameButton,
continueGameButtonText,
playButton;
div.id = 'prehistory-main-background';
span = document.createElement('span');
span.id = 'current-level';
spanText = document.createTextNode('Level 3');
span.textContent = spanText.textContent;
divPrehistory = document.createElement('div');
divPrehistory.id = 'divPrehistory';
divPrehistory.style.backgroundImage = "url('images/Prehistory/paper-roll.png')";
spanInDivPrehistory = document.createElement('span');
spanInDivPrehistory.id = 'prehistory-span-text';
spanInDivPrehistoryText = document.createTextNode('Enough with these silly games – StarCraft, MarCraft...! Let’s do ' +
'something for the girls! We need to create a cosmetics shop! Wait a minute! A cosmetics shop! ' +
'What the hell!?!?!Yeah, that right! Everyone can learn S# only a few are those who can master the OOP that goes with it. ' +
'Saddy Kopper is one of them. But in that crazy girl dimension (somewhere in Waka waka eh eh) the young Kopper must ' +
'create a cosmestics shop. In order to complete this task, he needs to collect all shampoos. If the Amazons are merciful ' +
'(they will be - Saddy is very charming), they will reveal the secret of mastering OOP.');
spanInDivPrehistory.textContent = spanInDivPrehistoryText.textContent;
divPrehistory.appendChild(spanInDivPrehistory);
continueGameButton = document.createElement('button');
continueGameButton.className = 'hvr-border-fade';
continueGameButton.id = 'continue';
continueGameButtonText = document.createTextNode('Continue');
continueGameButton.textContent = continueGameButtonText.textContent;
div.appendChild(span);
div.appendChild(divPrehistory);
div.appendChild(continueGameButton);
div.style.backgroundImage = "url('images/Game Over - messages background/L3-beach.jpg')";
body.appendChild(div);
playButton = document.getElementById('continue');
playButton.onclick = function () {
div.removeChild(span);
div.removeChild(divPrehistory);
div.removeChild(continueGameButton);
body.removeChild(div);
};
}
return Level3State;
});
|
function goMain(){
window.location.href = 'main.html';
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:8d51e43626611f90ffa2bf855ceaf2c501b01a5a083681b6a9426092bd85651f
size 3788
|
var assert = require('assert');
var wdQuery = require('../index.js');
describe('wd-query', function () {
describe('injected browser executing a Google Search', function () {
var browser, $;
before(function(){
browser = this.browser;
$ = wdQuery(browser);
});
it('performs as expected', function (done) {
browser.get('http://google.com')
.then(function () {
return $('input[name=q]').val('webdriver');
})
.then(function () {
return $('input[name=q]').val();
})
.then(function (val) {
return assert.equal(val, 'webdriver');
})
.then(function(){
return $('body').isDisplayed();
})
.then(function(isDisplayed){
assert.ok(isDisplayed);
done();
});
});
});
});
|
/* eslint no-var: [0] */
var path = require('path'),
assign = require('object-assign'),
pick = require('lodash.pick');
var browserWindowDefaults = {
width: 600,
height: 600
};
var webPreferencesDefaults = {
nodeIntegration: false,
javascript: true,
webSecurity: false
};
module.exports = function(browserWindowSettings) {
var browserWindowOpts,
webPreferences;
browserWindowOpts = pick(browserWindowSettings || {}, [
'width',
'height',
'x',
'y',
'useContentSize',
'webPreferences'
]);
browserWindowOpts = assign({}, browserWindowDefaults, browserWindowOpts, {
show: false
});
webPreferences = pick(browserWindowOpts.webPreferences || {}, [
'nodeIntegration',
'partition',
'zoomFactor',
'javascript',
'webSecurity',
'allowDisplayingInsecureContent',
'allowRunningInsecureContent',
'images',
'java',
'webgl',
'webaudio',
'plugins',
'experimentalFeatures',
'experimentalCanvasFeatures',
'overlayScrollbars',
'overlayFullscreenVideo',
'sharedWorker',
'directWrite'
]);
browserWindowOpts.webPreferences = assign({}, webPreferencesDefaults, webPreferences, {
preload: path.join(__dirname, 'preload.js')
});
return browserWindowOpts;
};
|
function load_servers(addr)
{
//ajax
$.get(addr,function(json,status){
// same as loadServers(addr)
serversElement = document.getElementById("servers-list");
var innerHtmls = "";
for (var obj in json) {
innerHtmls = innerHtmls +
" <li><a href=\"server.html?id="+json[obj].id+"\">"+
json[obj].displayName+"</a></li>"
}
console.log(json);
serversElement.innerHTML=innerHtmls;
//add to ServersPage
$.each(json,function(idx, obj) {
if(obj.id == window.servername)
{
$("#displayName").text(obj.displayName);
}
});
});
}
function load_hoststatus()
{
$("#id").text(window.servername);
console.log(window.hosts);
//ajax
$.get("/data/host-status.json",function(data,status){
window.hosts_status = data;
$.each(data, function(idx,obj) {
if(obj.id == window.servername)
{
$("#address").text(obj.address);
$("#ip").text(obj.ip);
$("#link").attr("href","http://"+obj.address);
$("#status").text(obj.status);
$("#delay").text(obj.delay);
switch(obj.status)
{
case "online": $(".panel-default").addClass("panel-success");break;
case "offline": $(".panel-default").addClass("panel-danger");break;
case "unknown": $(".panel-default").addClass("panel-warning");break;
}
datestr = /Date\((\d+)\)/.exec(obj.time.value)[1];
$("#time").text(new Date(parseInt(datestr)));
}
})
});
}
$(document).ready(function() {
load_servers("../../servers.json");
load_hoststatus();
});
|
/**
* Test case for knListItemArrowIcon.
* Runs with mocha.
*/
"use strict";
const knListItemArrowIcon = require('../lib/kn_list_item_arrow_icon.js'),
assert = require('assert');
describe('kn-list-item-arrow-icon', () => {
before((done) => {
done();
});
after((done) => {
done();
});
it('Kn list item arrow icon', (done) => {
done();
});
});
|
/*global $:true, Backbone:true, _:true, App:true */
/*jshint browser:true */
/*jshint strict:false */
App.Models.Controller = Backbone.Model.extend({
defaults: {
socket: false
},
initialize: function(opts) {
}
});
|
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
const documents = {
indexList: []
};
const elements = {
indexInput: null,
indexTable: null
};
function isCorrect(index) {
return index.length === 6;
}
function addIndex(index) {
documents.indexList.push(index);
elements.indexTable.append('<tr><td>' + index + '</td></tr>');
}
function sendToPrint() {
const toPush = '';
if (documents.indexList.length % 6 !== 0) {
while (documents.indexList.length % 6 !== 0) {
documents.indexList.push(toPush);
}
}
nw.Window.open('modules/f20-print/html/print.html', { 'show': false }, (win) => {
win.maximize();
// data is the list
win.window.data = documents.indexList;
});
}
function initModule() {
elements.indexInput = $('#indexInput');
elements.indexInput.mask('999999');
elements.indexTable = $('#indexTable');
$('#addIndexButton').button().click((event) => {
const index = elements.indexInput.val();
if (isCorrect(index)) {
addIndex(index);
} else {
alert(global.strings.f20_print.badFormat);
}
elements.indexInput.focus();
});
$('#printIndexesButton').button().click((event) => {
sendToPrint();
});
}
|
export {default} from 'ember-frost-demo-components/components/frost-file-node/component'
|
import { getEvent, eventMap } from '../../src/module/moveRow/event';
import { EMPTY_TPL_KEY } from '../../src/common/constants';
describe('drag', () => {
describe('getEvent', () => {
let events = null;
beforeEach(() => {
});
afterEach(() => {
events = null;
});
it('基础验证', () => {
expect(getEvent).toBeDefined();
expect(getEvent.length).toBe(1);
});
it('执行验证', () => {
events = getEvent('test');
expect(events.start.events).toBe('mousedown.gmLineDrag');
expect(events.start.target).toBe('test');
expect(events.start.selector).toBe(`tr:not([${EMPTY_TPL_KEY}])`);
expect(events.doing.events).toBe('mousemove.gmLineDrag');
expect(events.doing.target).toBe('body');
expect(events.doing.selector).toBeUndefined();
expect(events.abort.events).toBe('mouseup.gmLineDrag');
expect(events.abort.target).toBe('body');
expect(events.abort.selector).toBeUndefined();
});
});
describe('eventMap', () => {
it('基础验证', () => {
expect(eventMap).toEqual({});
});
});
});
|
output = function() {
navigator.camera.getPicture(function(imageData) {
cb({ imageData: $.create(imageData) });
}, function(err) {
cb({ error: $.create(err) });
}, {
quality: $.quality,
sourceType: Camera.PictureSourceType[$.sourceType],
allowEdit: $.allowEdit,
encodingType: Camera.EncodingType[$.encodingType],
targetWidth: $.targetWidth,
targetHeight: $.targetHeight
});
};
|
'use strict'
const execa = require('execa')
const chalk = require('chalk')
const figures = require('figures')
const ora = require('ora')
module.exports = function fetchRemote(flags) {
// git fetch
let args = ['fetch']
// fetch with prune?
if (!flags.skipPrune) {
// git fetch -p
args.push('-p')
}
let spin = ora(chalk.dim('Fetching remote')).start()
return execa('git', args).then(() => {
spin.stop()
console.log(
chalk.green(figures.tick) +
chalk.dim(' Fetched remote')
)
})
}
|
const { massiveHide } = require('../coreFunctions');
const header = {
init: () => {
constructor();
setupLogo();
},
};
const constructor = () => {
headerContainer = body.find('#header');
const breadcrumbContainer = body.find('.bread-container')
const hideElements = [
headerContainer.find('#station-logo'),
headerContainer.find('#header-menu'),
headerContainer.find('#header-actions-ul'),
headerContainer.find('#header-facebook-like'),
];
massiveHide(hideElements);
headerContainer.addClass('mo-header-container');
breadcrumbContainer.addClass('mo-breadcrumb-container');
}
const setupLogo = () => {
const logoContainer = `
<a href="/vale-tudo_f_57" class="mo-logo-container">
<div class="mo-logo-image sprite-vtMini"></div>
<div class="mo-logo-text">VT Mobile</div>
</a>
<div class="mo-login-container">
<a href="https://acesso.uol.com.br/login.html?skin=forum-jogos&dest=REDIR|mlocal.forum.jogos.uol.com.br" class="mo-login-button fa fa-user fa-2x"></a>
</div>
`;
headerContainer.append(logoContainer);
}
module.exports = header;
|
"use strict";
const btc = require("./coins/btc.js");
module.exports = {
"BTC": btc,
"coins":["BTC"]
};
|
"use strict";
module.exports = {
test_page: "tests/index.html?hidepassed",
disable_watching: true,
launch_in_ci: ["Chrome"],
launch_in_dev: [],
browser_start_timeout: 120,
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? "--no-sandbox" : null,
"--headless",
"--disable-dev-shm-usage",
"--disable-software-rasterizer",
"--mute-audio",
"--remote-debugging-port=0",
"--window-size=1440,900",
].filter(Boolean),
},
},
};
|
const greeting = (name) => {
const element = document.querySelector('.js-greeting');
if (element) {
element.innerHTML = name;
}
};
export default greeting;
|
define(function(require,exports, module) {
var $ = require('jquery');
var React = require('react');
var Backbone = require('backbone');
var MyTable = require('./components/table/Table');
var ReactApp={
getJsonData:function(data){
alert('收集数据!'+data);
},
getInstance:function(model,options){
var modelData = new Backbone.Model(model);
React.render(React.createElement(MyTable, {data: modelData, onGetJsonData: this.getJsonData}), $('#example')[0]);
}
};
return ReactApp;
});
|
import Backend from 'i18next-xhr-backend';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.plugin('aurelia-i18n', (i18n) => {
i18n.i18next.use(Backend);
return i18n.setup({
backend: {
loadPath: './locales/{{lng}}/{{ns}}.json',
},
lng : 'en',
fallbackLng : 'en'
});
});
}
|
import React, { Component } from 'react';
import Hawk from '../src/';
// For your app, import Hawk like so
// import Hawk from 'hawk-graph';
export default class App extends Component {
state = {
nodes: [
{
nid: 1,
type: 'Users',
x: 200,
y: 100,
fields: {
in: [
{ name: 'user_id' },
{ name: 'role_id' },
],
out: [{ name: 'out' }]
}
},
{
nid: 2,
type: 'Photos',
x: 800,
y: 100,
fields: {
in: [
{ name: 'user_id' },
{ name: 'photo' },
],
out: [{ name: 'out' }]
}
},
{
nid: 3,
type: 'Role',
x: 400,
y: 500,
fields: {
in: [
{ name: 'user_id' },
{ name: 'role' },
],
out: [{ name: 'out' }]
}
}
],
connections: [
{ from_node: 1, from: 'out', to_node: 2, to: 'user_id' },
{ from_node: 2, from: 'out', to_node: 3, to: 'user_id' },
]
}
onNewConnector(fromNode, fromPin, toNode, toPin) {
let connections = [
...this.state.connections,
{
from_node: fromNode,
from: fromPin,
to_node: toNode,
to: toPin
}
];
this.setState({ connections: connections });
}
onRemoveConnector(connector) {
let connections = [...this.state.connections];
connections = connections.filter(connection => {
return connection != connector;
});
this.setState({ connections: connections });
}
onNodeMove(nid, pos) {
console.log('end move : ' + nid, pos);
}
onNodeStartMove(nid) {
console.log('start move : ' + nid);
}
handleNodeSelect(nid) {
console.log('node selected : ' + nid);
}
handleNodeDeselect(nid) {
console.log('node deselected : ' + nid);
}
render() {
return (
<Hawk
data={this.state}
onNodeMove={(nid, pos) => this.onNodeMove(nid, pos)}
onNodeStartMove={nid => this.onNodeStartMove(nid)}
onNewConnector={(n1, o, n2, i) => this.onNewConnector(n1, o, n2, i)}
onRemoveConnector={connector => this.onRemoveConnector(connector)}
onNodeSelect={nid => {
this.handleNodeSelect(nid);
}}
onNodeDeselect={nid => {
this.handleNodeDeselect(nid);
}}
/>
);
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { TextAmount, TextInfo } from '../../Atoms/Text';
import theme from '../../../theme';
import styles from './styles';
const { color } = theme;
const Balance = ({ balance, sendMessage }) => (
<View style={styles.containerBalance}>
<View style={styles.containerSubBalance}>
<View style={styles.containerAvailable}>
<TextInfo value="Disponible" />
<View style={styles.amount}>
<TextAmount value={`$${balance.wallet.toLocaleString()}`} />
</View>
</View>
<View style={styles.containerGoals}>
<TextInfo value="Metas" />
<View style={styles.amount}>
<TextAmount value={`$${balance.goals.toLocaleString()}`} />
</View>
</View>
</View>
<View style={styles.line} />
<View style={styles.containerTotal}>
<View style={styles.containerSubTotal}>
<TouchableOpacity
onPress={() => sendMessage({ type: 'APPLICATION', value: 'WELCOME' })}
>
<View style={styles.buttom}>
<Icon name="minus" color={color.pink} size={24} />
</View>
</TouchableOpacity>
<View style={styles.containerSubTotalData}>
<View style={styles.bigAmount}>
<TextAmount value={`$${balance.total.toLocaleString()}`} big />
</View>
<TextInfo value="Total" />
</View>
<TouchableOpacity
onPress={() => sendMessage({ type: 'APPLICATION', value: 'WELCOME' })}
>
<View style={styles.buttom}>
<Icon name="plus" color={color.pink} size={24} />
</View>
</TouchableOpacity>
</View>
</View>
</View>
);
Balance.propTypes = {
balance: PropTypes.shape({}).isRequired,
sendMessage: PropTypes.func.isRequired,
};
export default Balance;
|
!function(){"use strict"}();
//# sourceMappingURL=app.js.map
|
import PageObject from '../../tests/page-object';
const {
value,
//customHelper,
collection,
clickable
} = PageObject;
export default function aupacTypeahead(selector/*, options*/) {
return {
search(search) {
$(selector).val(search).trigger('input');
},
suggestions : collection({
scope: '', //Reset to global scope
itemScope: '.tt-suggestion',
item: {
select: clickable()
}
}),
value : value(selector),
isDisabled: function() {
return $(selector).prop('disabled');
},
isEnabled: function() {
return ! $(selector).prop('disabled');
}
};
}
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.push = push;
exports.unshift = unshift;
exports.pop = pop;
exports.shift = shift;
exports.sort = sort;
exports.reverse = reverse;
exports.removeAt = removeAt;
exports.setKey = setKey;
exports.setAt = setAt;
exports.assign = assign;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); }
var _objectAssign = require('object-assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _debug = require('debug');
var _debug2 = _interopRequireDefault(_debug);
var debug = (0, _debug2['default'])('idempotent');
/**
* Returns a copy of the `arr` array, with the specified `element` appended to
* the highest index of the array.
*
* @param {Array[Anything]} arr
* @param {Anything} element
* @return {Array[Anything]}
*/
function push(arr, element) {
return arr.concat([element]);
}
/**
* Returns a copy of the `arr` array, with the specified `element` prepended to
* the 0th index of the array.
*
* @param {Array[Anything]} arr
* @param {Anything} element
* @return {Array[Anything]}
*/
function unshift(arr, element) {
return [element].concat(arr);
}
/**
* Returns a copy of the `arr` array, with the element at the highest index
* removed.
*
* @param {Array[Anything]} arr
* @return {Array[Anything]}
*/
function pop(arr) {
return arr.slice(0, arr.length - 1);
}
/**
* Returns a copy of the `arr` array, with the element at the 0th index removed.
*
* @param {Array[Anything]} arr
* @return {Array[Anything]}
*/
function shift(arr) {
return arr.slice(1, arr.length);
}
/**
* Returns a copy of the `arr` array, with all the elements sorted. Optionally,
* you can supply a function that
*
* @param {Array[Anything]} arr
* @param {Function : (Anything, Anything) -> Number}
* @return {Array[Anything]}
*/
function sort(arr, sorter) {
var copy = arr.slice();
if (sorter) {
return copy.sort(sorter);
}
return copy.sort();
}
/**
* Returns a copy of the `arr` array, with all the elements placed in reverse
* from the original array.
*
* @param {Array[Anything]} arr
* @return {Array[Anything]}
*/
function reverse(arr) {
return arr.slice().reverse();
}
/**
* Returns a copy of the `arr` array, with the element at the specified index
* removed.
*
* @param {Array[Anything]} arr
* @param {Integer} index
*/
function removeAt(arr, index) {
if (isNaN(index) || index < 0 || index % 1 !== 0) {
debug('Was given a non-integer value ' + index);
return arr.slice();
}
return arr.slice(0, index).concat(arr.slice(index + 1, arr.length));
}
/**
* Returns a copy of the `obj` object, with the element associated with the
* specified `key` replaced with the `value`.
*
* @param {Object} obj
* @param {Anything} key
* @param {Anything} value
* @return {Object}
*/
function setKey(obj, key, value) {
return assign(obj, _defineProperty({}, key, value));
}
/**
* Returns a copy of the `arr` array, with element at the specified `index`
* replaced with the `value`.
*
* @param {Array[Anything]} arr
* @param {Number} index
* @param {Array[Anything]} value
*/
function setAt(arr, index, value) {
if (arr.length <= index) {
return arr.concat(Array(index - arr.length)).concat([value]);
}
return arr.slice(0, index).concat([value]).concat(arr.slice(index + 1, arr.length));
}
/**
* Assigns all properties from the source objects, to the specified destination
* object.
*
* @param {Object} destination
* @param {Object} source in sources
* @return {Object}
*/
function assign(destination) {
for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
sources[_key - 1] = arguments[_key];
}
return _objectAssign2['default'].apply(undefined, [{}, destination].concat(sources));
}
|
define(["Tone/core/Tone", "Tone/effect/StereoXFeedbackEffect", "Tone/signal/Signal", "Tone/core/Delay"],
function(Tone){
"use strict";
/**
* @class Tone.PingPongDelay is a feedback delay effect where the echo is heard
* first in one channel and next in the opposite channel. In a stereo
* system these are the right and left channels.
* PingPongDelay in more simplified terms is two Tone.FeedbackDelays
* with independent delay values. Each delay is routed to one channel
* (left or right), and the channel triggered second will always
* trigger at the same interval after the first.
*
* @constructor
* @extends {Tone.StereoXFeedbackEffect}
* @param {Time|Object} [delayTime] The delayTime between consecutive echos.
* @param {NormalRange=} feedback The amount of the effected signal which
* is fed back through the delay.
* @example
* var pingPong = new Tone.PingPongDelay("4n", 0.2).toMaster();
* var drum = new Tone.DrumSynth().connect(pingPong);
* drum.triggerAttackRelease("C4", "32n");
*/
Tone.PingPongDelay = function(){
var options = this.optionsObject(arguments, ["delayTime", "feedback"], Tone.PingPongDelay.defaults);
Tone.StereoXFeedbackEffect.call(this, options);
/**
* the delay node on the left side
* @type {Tone.Delay}
* @private
*/
this._leftDelay = new Tone.Delay(0, options.maxDelayTime);
/**
* the delay node on the right side
* @type {Tone.Delay}
* @private
*/
this._rightDelay = new Tone.Delay(0, options.maxDelayTime);
/**
* the predelay on the right side
* @type {Tone.Delay}
* @private
*/
this._rightPreDelay = new Tone.Delay(0, options.maxDelayTime);
/**
* the delay time signal
* @type {Time}
* @signal
*/
this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time);
//connect it up
this.effectSendL.chain(this._leftDelay, this.effectReturnL);
this.effectSendR.chain(this._rightPreDelay, this._rightDelay, this.effectReturnR);
this.delayTime.fan(this._leftDelay.delayTime, this._rightDelay.delayTime, this._rightPreDelay.delayTime);
//rearranged the feedback to be after the rightPreDelay
this._feedbackLR.disconnect();
this._feedbackLR.connect(this._rightDelay);
this._readOnly(["delayTime"]);
};
Tone.extend(Tone.PingPongDelay, Tone.StereoXFeedbackEffect);
/**
* @static
* @type {Object}
*/
Tone.PingPongDelay.defaults = {
"delayTime" : 0.25,
"maxDelayTime" : 1
};
/**
* Clean up.
* @returns {Tone.PingPongDelay} this
*/
Tone.PingPongDelay.prototype.dispose = function(){
Tone.StereoXFeedbackEffect.prototype.dispose.call(this);
this._leftDelay.dispose();
this._leftDelay = null;
this._rightDelay.dispose();
this._rightDelay = null;
this._rightPreDelay.dispose();
this._rightPreDelay = null;
this._writable(["delayTime"]);
this.delayTime.dispose();
this.delayTime = null;
return this;
};
return Tone.PingPongDelay;
});
|
/* */
module.exports = function(hljs) {
return {
contains: [
{
begin: /[^\u2401\u0001]+/,
end: /[\u2401\u0001]/,
excludeEnd: true,
returnBegin: true,
returnEnd: false,
contains: [
{
begin: /([^\u2401\u0001=]+)/,
end: /=([^\u2401\u0001=]+)/,
returnEnd: true,
returnBegin: false,
className: 'attribute'
},
{
begin: /=/,
end: /([\u2401\u0001])/,
excludeEnd: true,
excludeBegin: true,
className: 'string'
}]
}],
case_insensitive: true
};
};
|
class A extends B {
X() {
return super[1];
}
}
|
(function ($, window, document, undefined)
{
var defaults = {
};
//var fr = new FileReader();
//var img = new Image();
var canvas;
var URL = window.webkitURL || window.URL;
function Plugin(element, options)
{
this.w = $(document);
this.el = $(element);
this.options = $.extend({}, defaults, options);
this.init(element);
}
Plugin.prototype = {
// инициализация плагина
init: function (params) {
var list = $(params),
thiss = this;
this.start(params);
},
start: function (params)
{
var thiss = this;
$(document).on("input", ".natura", function (e) {
var cont = $(this).closest(".grup");
var item = $(this).closest(".dd-item");
var result = cont.find(".result");
if (result.length){
if (item.find(">label input:checked").length){
result.val(thiss.get_translit($(this).val()));
}
}
});
console.log("start");
},
get_translit: function (str) {
var entoru = [[['а'], ['a']],
[['б'], ['b']],
[['в'], ['v']],
[['г'], ['g']],
[['д'], ['d']],
[['е'], ['e']],
[['ё'], ['yo']],
[['ж'], ['zh']],
[['з'], ['z']],
[['и'], ['i']],
[['й'], ['j']],
[['к'], ['k']],
[['л'], ['l']],
[['м'], ['m']],
[['н'], ['n']],
[['о'], ['o']],
[['п'], ['p']],
[['р'], ['r']],
[['с'], ['s']],
[['т'], ['t']],
[['у'], ['u']],
[['ф'], ['f']],
[['х'], ['h']],
[['ц'], ['c']],
[['ч'], ['ch']],
[['ш'], ['sh']],
[['щ'], ['shch']],
[['ъ'], ['']],
[['ы'], ['y']],
[['ь'], ['']],
[['э'], ['e']],
[['ю'], ['yu']],
[['я'], ['ya']],
[['і'], ['i']],
[['ї'], ['i']],
[['є'], ['e']],
[['А'], ['A']],
[['Б'], ['B']],
[['В'], ['V']],
[['Г'], ['G']],
[['Д'], ['D']],
[['Е'], ['E']],
[['Ё'], ['Yo']],
[['Ж'], ['Zh']],
[['З'], ['Z']],
[['И'], ['I']],
[['Й'], ['J']],
[['К'], ['K']],
[['Л'], ['L']],
[['М'], ['M']],
[['Н'], ['N']],
[['О'], ['O']],
[['П'], ['P']],
[['Р'], ['R']],
[['С'], ['S']],
[['Т'], ['T']],
[['У'], ['U']],
[['Ф'], ['F']],
[['Х'], ['H']],
[['Ц'], ['C']],
[['Ч'], ['Ch']],
[['Ш'], ['Sh']],
[['Щ'], ['Shch']],
[['Ъ'], ['']],
[['Ы'], ['Y']],
[['Ь'], ['']],
[['Э'], ['E']],
[['Ю'], ['Yu']],
[['Я'], ['Ya']],
[[' '], ['-']],
[['І'], ['I']],
[['Ї'], ['I']],
[['Є'], ['E']]];
var nameVal = trim(str);
var trans = new String();
for (i = 0; i < entoru.length; i++) {
var regex = new RegExp(entoru[i][0][0], "g");
nameVal = nameVal.replace(regex, entoru[i][1][0]);
}
return nameVal.toLowerCase();
}//,resetFile
};
$.fn.transfer = function (params)
{
var lists = this,
retval = this;
lists.each(function ()
{
var plugin = $(this).data("transfer");
if (!plugin) {
$(this).data("transfer", new Plugin(this, params));
$(this).data("transfer-id", new Date().getTime());
} else {
if (typeof params === 'string' && typeof plugin[params] === 'function') {
retval = plugin[params]();
}
}
});
return retval || lists;
}
;
})(window.jQuery || window.Zepto, window, document);
|
/**
* @author mrdoob / http://mrdoob.com/
*/
export var Config = function ( name ) {
var storage = {
'autosave': true,
'theme': 'css/light.css',
'project/renderer': 'WebGLRenderer',
'project/renderer/antialias': true,
'project/renderer/gammaInput': false,
'project/renderer/gammaOutput': false,
'project/renderer/shadows': true,
'project/editable': false,
'project/vr': false,
'settings/history': false,
'ui/sidebar/animation/collapsed': true,
'ui/sidebar/script/collapsed': true
};
if ( window.localStorage[ name ] === undefined ) {
window.localStorage[ name ] = JSON.stringify( storage );
} else {
var data = JSON.parse( window.localStorage[ name ] );
for ( var key in data ) {
storage[ key ] = data[ key ];
}
}
return {
getKey: function ( key ) {
return storage[ key ];
},
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l; i += 2 ) {
storage[ arguments[ i ] ] = arguments[ i + 1 ];
}
window.localStorage[ name ] = JSON.stringify( storage );
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' );
},
clear: function () {
delete window.localStorage[ name ];
}
};
};
|
let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function timer(seconds) {
// clean any existing timers
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
// check if we should stop it
if(secondsLeft < 0) {
clearInterval(countdown);
return;
}
// display it
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
const minutes = Math.floor(seconds / 60);
const reminderSeconds = seconds % 60;
const display = `${minutes}:${reminderSeconds < 10 ? '0' : ''}${reminderSeconds}`;
timerDisplay.textContent = display;
document.title = display;
}
function displayEndTime(timestamp) {
const end = new Date(timestamp);
const hour = end.getHours();
// const adjustedHour = hour > 12 ? hour - 12 : hour;
const minutes = end.getMinutes();
endTime.textContent = `Be Back At ${hour}:${minutes < 10 ? '0' : ''}${minutes}`;
// endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes}`;
}
function startTimer() {
const seconds = parseInt(this.dataset.time);
timer(seconds);
}
buttons.forEach(button => button.addEventListener('click', startTimer));
document.customForm.addEventListener('submit', function(e) {
e.preventDefault();
const mins = this.minutes.value;
console.log(mins);
timer(mins * 60);
this.reset();
});
|
var path = require('path')
var configVars = require('./configVars.js')
var karmaConfig = {
basePath: './',
frameworks: ['jasmine-jquery', 'jasmine'],
port: 9876,
colors: true,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: 1,
files: [
'./' + configVars['unitTests']['entryFile']
],
reporters: [
'spec',
'coverage'
],
specReporter: {
maxLogLines: 2,
suppressErrorSummary: false,
suppressFailed: false,
suppressPassed: false,
suppressSkipped: false
},
coverageReporter: {
includeAllSources: true,
reporters: [
{
type: 'lcov',
subdir: '../' + configVars['unitTests']['coverageOutputPath']
},
{
type: 'text-summary'
}
]
},
preprocessors: {},
webpack: {
devtool: 'inline-source-map',
babel: {
presets: ['es2015'],
plugins: ['transform-object-assign'],
cacheDirectory: true
},
isparta: {
embedSource: true,
noAutoWrap: true,
babel: {
presets: ['es2015'],
plugins: [
'transform-object-assign',
'transform-es2015-modules-umd'
]
}
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'babel'
},
{
test: /^(.(?!\.spec))*\.js$/,
include: path.resolve('./' + configVars['js']['srcPath']),
loader: 'isparta'
}
]
},
externals: [
{}
],
cache: true
}
}
karmaConfig.preprocessors['./' + configVars['unitTests']['entryFile']] = ['webpack', 'sourcemap']
module.exports = function (config) {
karmaConfig.logLevel = config.LOG_ERROR
config.set(karmaConfig)
}
|
var credentialUtil = require('../../lib/creds');
var fs = require('fs');
var path = require('path');
var test = require('tape');
var SSH_CONFIG_FILE = path.join(__dirname, '..', 'ssh_config.txt');
var GAURAV_SSH_CONFIG_FILE = path.join(__dirname, '..', 'gaurav_ssh_config.txt');
var REMTAIL_JSON_FILE = path.join(__dirname, '..', 'remtail.json');
var PRIVATE_KEY_FILE = path.join(__dirname, '..', 'privateKey.txt');
var SSH_CONFIG_CONTENTS = fs.readFileSync(SSH_CONFIG_FILE, 'UTF-8');
var GAURAV_SSH_CONFIG_CONTENTS = fs.readFileSync(GAURAV_SSH_CONFIG_FILE, 'UTF-8');
var REMTAIL_JSON_CONTENTS = fs.readFileSync(REMTAIL_JSON_FILE, 'UTF-8');
var PRIVATE_KEY_CONTENTS = fs.readFileSync(PRIVATE_KEY_FILE, 'UTF-8');
var SSH_CONFIG = credentialUtil.parseSshConfig(SSH_CONFIG_CONTENTS);
var REMTAIL_JSON = JSON.parse(REMTAIL_JSON_CONTENTS);
test('ssh config parsing', function(t) {
var expectedSshConfig = [
{
Host: 'trillworks',
HostName: 'trillworks.com',
User: 'nickc'
}, {
Host: 'globcong',
HostName: 'globcong.com',
User: 'maurice',
IdentityFile: 'test/privateKey.txt'
}
];
var sshConfig = credentialUtil.parseSshConfig(SSH_CONFIG_CONTENTS);
t.deepEquals(sshConfig, expectedSshConfig);
t.end();
});
test('basic ssh credentials map', function(t) {
var expectedCredentialsMap = {
'trillworks.com': {
user: 'nickc'
},
'globcong.com': {
user: 'maurice',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var credentialsMap = credentialUtil.buildSshConfigCredentialsMap({}, SSH_CONFIG);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
test('basic remtail credentials map', function (t) {
var expectedCredentialsMap = {
'trillworks.com': {
port: 22,
user: 'bigtex',
password: 'hunter2'
},
'globcong.com': {
user: 'peter',
password: 'blah'
},
"yahoo.com": {
user: 'ganley',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var credentialsMap = credentialUtil.addFileCredentials({}, REMTAIL_JSON);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
test('merging credentials maps', function(t) {
var expectedCredentialsMap = {
'trillworks.com': {
port: 22,
user: 'bigtex',
password: 'hunter2'
},
'globcong.com': {
user: 'peter',
password: 'blah',
privateKey: PRIVATE_KEY_CONTENTS
},
"yahoo.com": {
user: 'ganley',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var credentialsMap = {};
credentialUtil.buildSshConfigCredentialsMap(credentialsMap, SSH_CONFIG);
credentialUtil.addFileCredentials(credentialsMap, REMTAIL_JSON);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
test('gaurav ssh config with ForwardAgent entry', function(t) {
var expectedCredentialsMap = {
'ggmathur.ausoff.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-user1.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-user2.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-svc1.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-svc2.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var gauravSshConfig = credentialUtil.parseSshConfig(GAURAV_SSH_CONFIG_CONTENTS);
var credentialsMap = credentialUtil.buildSshConfigCredentialsMap({}, gauravSshConfig);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
|
var _ember = require('ember');
_ember['default'].debug('this will NOT be removed');
warn('this will NOT be removed');
info('this will NOT be removed');
console.log(message);
|
var test = require('tape')
var Rectangle = require('../src/Rectangle.js')
var Square = require('../src/Square.js')
test('Square constructor', function (t) {
t.plan(3)
t.equal(typeof Square, 'function', 'should be a function')
var squ = new Square(7)
t.equal(squ.width, 7, 'should set square width')
t.equal(squ.height, 7, 'should set square height')
})
test('Square::area', function (t) {
t.plan(2)
var squ = new Square(7)
t.equal(typeof squ.area, 'function', 'should be a function')
t.equal(squ.area, Rectangle.prototype.area, 'should be inherited from Rectangle')
})
test('Square::description', function (t) {
t.plan(2)
var squ = new Square(7)
t.equal(typeof squ.description, 'function', 'should be a function')
t.equal(squ.description(), 'Square of side 7 and area 49.', 'should return square\'s description')
})
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('service:alert-box', 'Unit | Service | alert box', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let service = this.subject();
assert.ok(service);
});
|
import hoistNonReactStatics from 'hoist-non-react-statics';
import React, { Component } from 'react';
export default function fetchData(callback) {
return (WrappedComponent) => {
class FetchData extends Component {
render() {
return <WrappedComponent {...this.props} />;
}
}
FetchData.fetchData = callback;
return hoistNonReactStatics(FetchData, WrappedComponent);
};
}
export function fetchAllData(components, getState, dispatch) {
return Promise.all(
components.filter((component) => component && component.fetchData)
.map((component) => component.fetchData)
.map(fetchData => fetchData(getState, dispatch))
);
};
|
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule monitorCodeUse
*/
"use strict";
var invariant = require("./invariant");
/**
* Provides open-source compatible instrumentation for monitoring certain API
* uses before we're ready to issue a warning or refactor. It accepts an event
* name which may only contain the characters [a-z0-9_] and an optional data
* object with further information.
*/
function monitorCodeUse(eventName, data) {
(require('./React').__DEV__ === true ? invariant(
eventName && !/[^a-z0-9_]/.test(eventName),
'You must provide an eventName using only the characters [a-z0-9_]'
) : invariant(eventName && !/[^a-z0-9_]/.test(eventName)));
}
module.exports = monitorCodeUse;
|
/*! @license Firebase v4.5.0
Build: rev-f49c8b5
Terms: https://firebase.google.com/terms/ */
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.OperationSource = exports.OperationType = undefined;
var _assert = require("../../../utils/assert");
/**
*
* @enum
*/
var OperationType = exports.OperationType = undefined; /**
* Copyright 2017 Google 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.
*/
(function (OperationType) {
OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
OperationType[OperationType["MERGE"] = 1] = "MERGE";
OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
})(OperationType || (exports.OperationType = OperationType = {}));
/**
* @param {boolean} fromUser
* @param {boolean} fromServer
* @param {?string} queryId
* @param {boolean} tagged
* @constructor
*/
var OperationSource = /** @class */function () {
function OperationSource(fromUser, fromServer, queryId, tagged) {
this.fromUser = fromUser;
this.fromServer = fromServer;
this.queryId = queryId;
this.tagged = tagged;
(0, _assert.assert)(!tagged || fromServer, 'Tagged queries must be from server.');
}
/**
* @const
* @type {!OperationSource}
*/
OperationSource.User = new OperationSource(
/*fromUser=*/true, false, null,
/*tagged=*/false);
/**
* @const
* @type {!OperationSource}
*/
OperationSource.Server = new OperationSource(false,
/*fromServer=*/true, null,
/*tagged=*/false);
/**
* @param {string} queryId
* @return {!OperationSource}
*/
OperationSource.forServerTaggedQuery = function (queryId) {
return new OperationSource(false,
/*fromServer=*/true, queryId,
/*tagged=*/true);
};
return OperationSource;
}();
exports.OperationSource = OperationSource;
//# sourceMappingURL=Operation.js.map
|
/*
* This file is part of the Spludo Framework.
* Copyright (c) 2009-2010 DracoBlue, http://dracoblue.net/
*
* Licensed under the terms of MIT License. For the full copyright and license
* information, please see the LICENSE file in the root folder.
*/
/**
* @class The manager for all registered data_mappers.
*
* @extends Logging
*/
DataMapperManager = function() {
this.data_mappers = {};
};
extend(true, DataMapperManager.prototype, Logging.prototype);
DataMapperManager.prototype.logging_prefix = 'DataMapperManager';
DataMapperManager.prototype.addDataMapper = function(name, data_mapper) {
this.trace("addDataMapper", arguments);
this.data_mappers[name] = data_mapper;
};
DataMapperManager.prototype.getDataMapper = function(name) {
if (this.data_mappers[name]) {
return this.data_mappers[name];
}
throw new Error("DataMapper for name " + name + " not found!");
};
DataMapperManager.prototype.shutdown = function() {
this.trace("shutdown", arguments);
for (var name in this.data_mappers) {
/*
* Check wether this data_mapper has a shutdown method.
*/
if (typeof this.data_mappers[name].shutdown === "function") {
try {
this.data_mappers[name].shutdown();
} catch (e) {
this.warn("Exception when trying to shutdown data_mapper " + name);
this.warn(e);
}
}
}
};
|
var gulp = require('gulp'),
mocha = require('gulp-spawn-mocha');
gulp.task('test', function(){
return gulp.src('test/*.js').pipe(mocha());
});
gulp.task('default', ['test']);
|
exports.list = require('./list')
exports.game = require('./game')
|
'use strict';
const { thinscriptWasm } = require('/usr/lib/wasm');
module.exports = (args, env, cb) => {
try {
env.stdio.write(thinscriptWasm.helloWorld());
cb(0);
} catch(e) {
env.stdio.writeError(e);
cb(1);
}
}
|
import pidcrypt from 'pidcrypt'
import {
path,
pipe,
type,
equals
} from 'rambda'
import {
toByteArray,
decodeBase64,
encodeBase64,
convertFromHex
} from 'pidcrypt/pidcrypt_util'
import 'pidcrypt/asn1'
import 'pidcrypt/rsa'
import createError from './error'
const { RSA, ASN1 } = pidcrypt
const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
export const isFunction = pipe(type, equals('Function'))
export const isUndefined = pipe(type, equals('Undefined'))
export function publicEncrypt(key, value) {
const asn = ASN1.decode(toByteArray(decodeBase64(key)))
const rsa = new RSA()
rsa.setPublicKeyFromASN(asn.toHexTree())
return encodeBase64(convertFromHex(rsa.encrypt(value)))
}
export function get(inputObject, inputPath, defaultValue) {
const inputValue = path(inputPath, inputObject)
return isUndefined(inputValue) ? defaultValue : inputValue
}
export function getOption(key, options, defaults) {
return get(options, key, path(key, defaults))
}
export function transformResponse(response) {
return path('data', response)
}
export function transformError(error) {
throw createError(error)
}
export function uniqueId(length = 15, chars = CHARS) {
let i, result = ''
for (i = length; i > 0; --i) {
result += chars[Math.floor(Math.random() * chars.length)]
}
return result
}
|
import * as React from "react";
import PropTypes from "prop-types";
import { withWrapper } from "../Icon";
const Vector = React.forwardRef(({ size, color, ...props }, ref) => (
<svg
width={size}
height={size}
viewBox="2 2 20 20"
xmlns="http://www.w3.org/2000/svg"
ref={ref}
aria-hidden={!props["aria-label"]}
{...props}
>
<path
d="m13.414 12 2.829-2.828a1 1 0 0 0-1.415-1.415L12 10.586 9.172 7.757a1 1 0 0 0-1.415 1.415L10.586 12l-2.829 2.828a1 1 0 0 0 1.415 1.415L12 13.414l2.828 2.829a1 1 0 0 0 1.415-1.415L13.414 12Z"
fill={color}
fillRule="evenodd"
/>
</svg>
));
Vector.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
"aria-label": PropTypes.string,
};
Vector.defaultProps = {
color: "currentColor",
size: "1em",
};
const SmCross = withWrapper(Vector);
SmCross.groupName = "Actions";
export default SmCross;
|
import angular from 'angular';
import {loginComponent} from './login.component';
const loginConfig = ($stateProvider) => {
'use strict';
$stateProvider
.state('app.login', {
url: '/login',
layout: 'mainMenu',
component: 'login'
});
};
loginConfig.$inject = ['$stateProvider'];
const login = angular.module('login', [])
.config(loginConfig)
.component('login', loginComponent);
export {login};
|
var log4js = require("log4js"),
log = log4js.getLogger("megapis-worker"),
request = require("request"),
cheerio = require("cheerio"),
_ = require("lodash"),
async = require("async"),
util = require("util");
var MegapisWorker = require("megapis-worker").MegapisWorker;
function PrimeBooksWorker(config) {
PrimeBooksWorker.super_.call(this, config);
}
util.inherits(PrimeBooksWorker, MegapisWorker);
exports.createWorker = function(config) {
return new PrimeBooksWorker(config);
};
PrimeBooksWorker.prototype.getConfigKeys = function() {
return ["urls", "output"];
};
PrimeBooksWorker.prototype.run = function(callback) {
var self = this;
async.waterfall([
function getExclude(next) {
if (self.config.exclude) {
self.get(self.config.exclude, function(err, values) {
log.debug("found "+values.length+" ASINs to exclude");
next(null, values);
});
} else {
next(null, []);
}
},
function getBooks(exclude, next) {
var byUrl = {};
async.forEach(self.config.urls, function(url, forEachCallback) {
request(url, function(err, response, body) {
if (err) throw err;
var $ = cheerio.load(body);
// get books
$(".s-result-item").each(function() {
var asin = $(this).attr("data-asin");
var item = $(this).find(".s-access-detail-page");
var title = $(item).attr("title");
var author = $(this).find(".a-row .a-row a").eq(2).text();
var url = $(item).attr("href");
//log.debug("exclude "+url+"="+_.includes(exclude, url));
if (!_.includes(exclude, asin)) {
byUrl[url] = {
asin: asin,
title: title,
author: author,
url: url
};
}
});
forEachCallback();
});
}, function(err) {
next(err, byUrl);
});
},
function getDetails(byUrl, next) {
var books = [];
var i = 0;
var total= _.keys(byUrl).length;
log.info("found "+total+" books");
async.forEach(_.keys(byUrl), function(url, forEachCallback) {
// get synopsis from detail page link
request(url, function(err, response, body) {
if (err) throw err;
var $ = cheerio.load(body);
var book = byUrl[url];
book.url = $("link[rel='canonical']").attr("href");
book.description = $("#bookDescription_feature_div noscript").text().trim();
if (book.description.length > 500) {
book.description = book.description.substring(0, 500)+"...";
}
var tag = $("meta[name='title']").attr("content");
tag = tag.replace("Amazon.com: ", "");
tag = tag.replace(": Kindle Store", "");
book.tag = tag;
book.source = self.config.id;
// TODO: author?
books.push(book);
i++;
if (i%10 === 0) {
log.debug("loaded "+i+"/"+total+" book pages");
}
forEachCallback();
});
}, function(err) {
next(err, books);
});
}
], function(err, books) {
self.save(books, callback);
});
};
|
exports.ADD_ITEM_TO_IMPORT_LIST = function(state, contentNode) {
state.itemsToImport.push(contentNode);
};
exports.REMOVE_ITEM_FROM_IMPORT_LIST = function(state, contentNodeId) {
state.itemsToImport = state.itemsToImport.filter(function(node) {
return node.id !== contentNodeId;
});
};
exports.UPDATE_IMPORT_SIZE = function(state, newSize) {
state.importSizeInBytes = newSize;
};
exports.UPDATE_CHANNELS = function(state, channels) {
state.channels = channels;
};
exports.UPDATE_IMPORT_STATUS = function(state, status) {
state.importStatus = status;
};
exports.UPDATE_PAGE_STATE = function(state, payload) {
state.pageState = {
pageType: payload.pageType,
data: payload.data || {},
};
};
exports.RESET_IMPORT_STATE = function(state) {
Object.assign(state, {
itemsToImport: [],
importStatus: null,
importSizeInBytes: 0,
});
};
exports.UPDATE_CHANNELS_ARE_LOADING = function(state, isLoading) {
state.channelsAreLoading = isLoading;
};
|
var TutorialStudyLayer = cc.Layer.extend({
label : null,
array : [
//"안녕하세요!\n뉴로스터디를 이용해주셔서 감사합니다!\n\n뉴로스터디는 뇌파를 이용한 영어 학습 도구입니다.\n\n뇌파 헤드셋을 통하여 집중력을 측정하고 이에 대한 피드백을 전달하여 사용자가 자연스럽게 집중 상태를 유지하도록 도와줍니다.\n\n이를 통하여 하루 30분 정도의 시간 투자만으로도 놀라울 정도의 학습 효과를 보장합니다.",
"본격적인 학습에 앞서 뉴로스터디의 뇌파 스터디 시스템에 대해 소개해드리겠습니다.\n\n뇌파 스터디는 뇌파 ",
"본격적인 학습에 앞서 뉴로 워밍업 프로그램을 소개합니다.\n\n뉴로 워밍업은 학습에 앞서서 집중력과 관련이 높은 세타파를 학습에 적합한 형태로 유도하는 프로그램입니다.\n\n시각 효과와 시냇물 소리를 통하여 사용자의 세타파를 다량 발생하도록 유도하여 집중 상태로 학습에 임할 수 있도록 도와줍니다",
],
index : 0,
cur : 0,
nextEnabled : false,
clickMenu : null,
ctor:function () {
this._super();
var size = cc.winSize;
var backgroundLayer = new cc.LayerColor();
backgroundLayer.setColor(cc.color(0,0,0));
backgroundLayer.opacity = 230;
this.addChild(backgroundLayer);
var pageView = new ccui.PageView();
pageView.setTouchEnabled(true);
pageView.setContentSize(cc.size(size.width, size.height));
pageView.x = (size.width - pageView.width) / 2;
pageView.y = (size.height - pageView.height) / 2;
this.addChild(pageView);
this.clickMenu = new SimpleMenu(res.forward_white_png, res.forward_white_png, res.forward_white_png, function(sender) {
this.touchEvent();
}, this);
this.clickMenu.attr({
x : size.width - 128,
y : 128,
opacity : 0
});
this.addChild(this.clickMenu);
this.clickMenu.runAction(new cc.RepeatForever(
new cc.Sequence(
new cc.ScaleTo(0.3, 1),
new cc.ScaleTo(0.3, 1.03)
)
));
this.label = new cc.LabelTTF("", "Arial", 50, cc.size(size.width * 0.8, size.height * 0.7), cc.TEXT_ALIGNMENT_LEFT, cc.VERTICAL_TEXT_ALIGNMENT_TOP);
this.label.attr({
x : size.width / 2,
y : size.height / 2
});
this.addChild(this.label);
this.schedule(function() {
if(this.cur < this.array[this.index].length) {
this.label.string += this.array[this.index][this.cur];
this.cur++;
}
else {
this.clickMenu.runAction(new cc.FadeIn(0.1));
this.nextEnabled = true;
}
}, 0.05);
},
touchEvent:function (event) {
if(this.nextEnabled) {
this.clickMenu.runAction(new cc.FadeOut(0.1));
if(this.index < this.array.length - 1) {
this.nextEnabled = false;
this.index++;
this.cur = 0;
this.label.string = "";
}
else {
this.removeFromParent();
cc.sys.localStorage.setItem("warmup-tutorial", "true");
}
}
}
});
|
const React = require('react')
const {Cursor} = require('./prop_types')
class Chat extends React.Component {
onSubmit = (e) => {
e.preventDefault()
const input = this.refs.input.getDOMNode()
const message = input.value
input.value = ''
// push the new message onto the array in ultrawave
if (message.length > 0) {
this.props.messages.push({sender: this.props.name, text: message})
}
}
render() {
// get the messages array object out from our cursor
const messages = this.props.messages.get()
const name = this.props.name
// make sure messages stay scrolled to the bottom
setTimeout(() => {this.refs.messages.getDOMNode().scrollTop = Infinity})
return <section className='chat flex flex-column flex-none bg-darken-1'>
<div
className='flex flex-column flex-auto scroll py2'
ref='messages'
>
{
messages.map(({sender, text}, i) =>
<div
key={i}
className={
'py1 px2 flex-none' +
((sender === name) ? ' bg-white' : '') +
((sender === null) ? ' gray' : '')
}
>
{
sender ?
<span className='bold'>{sender}: </span>
:
null
}
{text}
</div>
)
}
</div>
<form className='flex p2 flex-none' onSubmit={this.onSubmit}>
<input
type='text'
className='field-light border-white flex-auto rounded-left'
ref='input'
placeholder='Message'
/>
<button
type='submit'
className='button rounded-right white regular bg-aqua x-group-item'
>
Send
</button>
</form>
</section>
}
}
Chat.propTypes = {
name: React.PropTypes.string.isRequired,
messages: Cursor.isRequired,
}
module.exports = Chat
|
import Enum from '../../lib/Enum';
export default new Enum([
'init',
'initSuccess',
'fetch',
'fetchSuccess',
'fetchError',
'fSync',
'fSyncSuccess',
'fSyncError',
'iSync',
'iSyncSuccess',
'iSyncError',
'reset',
'resetSuccess',
'clearToken',
], 'callLogActionTypes');
|
//For submit articles
tinymce.init({
selector: '#content',
directionality:'ltr',
language:'zh_CN',
height:400,
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'save table contextmenu directionality emoticons template paste textcolor',
'codesample',
],
toolbar: 'insertfile undo redo | \
styleselect | \
bold italic | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | \
link image | \
print preview media fullpage | \
forecolor backcolor emoticons |\
codesample fontsizeselect fullscreen',
fontsize_formats: '10pt 12pt 14pt 18pt 24pt 36pt',
nonbreaking_force_tab: true
});
//For add plugin
tinymce.init({
selector: '#pluginContent',
directionality:'ltr',
language:'zh_CN',
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'save table contextmenu directionality emoticons template paste textcolor',
'codesample',
],
});
|
import componentsModule from '../index';
describe('tl-people-you-may-know component', () => {
'use strict';
var $rootScope, $compile, elm, scope, $httpBackend, $timeout;
beforeEach(window.module(componentsModule.name));
beforeEach(inject(($injector) => {
$rootScope = $injector.get('$rootScope');
$compile = $injector.get('$compile');
$httpBackend = $injector.get('$httpBackend');
$timeout = $injector.get('$timeout');
scope = $rootScope.$new();
$httpBackend.expectJSONP(/http:\/\/www.filltext.com\/\?callback=JSON_CALLBACK&rows=2&fname=\{firstName}&lname=\{lastName}/).respond([
{fname: 'Chris', lname: 'Bond'},
{fname: 'Mike', lname: 'Bond'}
]);
}));
function renderComponent() {
elm = angular.element('<tl-people-you-may-know></tl-people-you-may-know>');
$compile(elm)(scope);
scope.$digest();
return elm;
}
it('should be able to load users suggested as friends', () => {
let component = renderComponent();
let controller = component.controller('tlPeopleYouMayKnow');
$httpBackend.flush();
$timeout.flush();
expect(controller.suggestedPeople.length).toEqual(2);
});
it('should be able to have loading state when fetching data', () => {
let component = renderComponent();
expect(component.find('.segment').hasClass('loading')).toEqual(true);
$httpBackend.flush();
$timeout.flush();
expect(component.find('.segment').hasClass('loading')).toEqual(false);
});
it('should be able to display full user name', () => {
let component = renderComponent();
$httpBackend.flush();
$timeout.flush();
expect(component.find('.content:eq(1)').text().trim()).toEqual('Chris Bond')
});
it('should be able to add user as a friend', () => {
spyOn($rootScope, '$broadcast');
let component = renderComponent();
let controller = component.controller('tlPeopleYouMayKnow');
$httpBackend.flush();
$timeout.flush();
expect(controller.suggestedPeople.length).toEqual(2);
let userToAdd = controller.suggestedPeople[0];
controller.addUser(userToAdd);
expect($rootScope.$broadcast).toHaveBeenCalledWith('add-suggested-user', userToAdd);
expect(controller.suggestedPeople.length).toEqual(1);
});
it('should be able to skip user as a friend', () => {
let component = renderComponent();
let controller = component.controller('tlPeopleYouMayKnow');
$httpBackend.flush();
$timeout.flush();
expect(controller.suggestedPeople.length).toEqual(2);
controller.skipUser(controller.suggestedPeople[0]);
expect(controller.suggestedPeople.length).toEqual(1);
});
it('should be hidden when there are no suggested users', () => {
let component = renderComponent();
let controller = component.controller('tlPeopleYouMayKnow');
$httpBackend.flush();
$timeout.flush();
expect(component.find('.segment').hasClass('ng-hide')).toEqual(false);
controller.skipUser(controller.suggestedPeople[0]);
controller.skipUser(controller.suggestedPeople[0]);
scope.$apply();
expect(component.find('.segment').hasClass('ng-hide')).toEqual(true);
});
});
|
import Loader from '../../src/loader';
describe('loader', function () {
let loader, configRan;
beforeAll(() => {
window.pmAnimatedBannersConfig = () => {
configRan = true;
};
loader = new Loader();
});
it('should call pmAnimatedBannersConfig', () => {
expect(configRan).toEqual(true);
});
});
|
(function() {
'use strict';
angular
.module('app')
.filter('sample', sample);
function sample() {
return sampleFilter;
////////////////
function sampleFilter(params) {
return params;
}
}
})();
|
Ext.define('Signout.controller.Home', {
extend: 'Ext.app.Controller',
refs:[{
ref: 'infoform',
selector: 'homecard > * > form'
}],
models:['SliInfo'],
stores:['SliInfos'],
init: function(){
var id = tokobj.ssid;
var me = this;
this.control({
'homecard > * > form': {
render: function(){me.loadSliInfoForm(id)}
}
});
},
loadSliInfoForm: function(id){
var me = this;
this.getSliInfosStore().load({
url: '/ncssm/resources/slis/'+id,
method: 'GET',
callback: function(record){
me.getInfoform().getForm().loadRecord(record[0]);
}
});
}
});
|
'use strict';
module.exports = {
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/pw',
facebook: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: 'CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
}
};
|
// ==UserScript==
// @include http://reference.bahai.org/en/t/*
// ==/UserScript==
/*globals WritingsMap, SpecialWritingsMap, MissingWritingsMap*/
var WritingsMap = {
// 'b/ESW': "Epistle to the Son of the Wolf",
'b/GDM': "Gems of Divine Mysteries", // "Gems of Divine Mysteries (Javáhiru’l-Asrár)"
'b/GWB': "Gleanings from the Writings of Bahá'u'lláh", // "Gleanings From the Writings of Bahá'u'lláh"
'b/HW': "Hidden Words", // "The Hidden Words of Bahá'u'lláh"
'b/KA': "Kitáb-i-Aqdas", // "The Kitáb-i-Aqdas"
'b/KI': "Kitáb-i-Íqán", // "The Kitáb-i-Íqán"
'b/PM': "Prayers and Meditations", // "Prayers and Meditations by Bahá'u'lláh"
'b/PB': "Proclamation of Bahá'u'lláh", // "Proclamation of Bahá’u’lláh"
'b/SVFV': "Seven Valleys and the Four Valleys", // "The Seven Valleys and the Four Valleys"
'b/SLH': "Summons of the Lord of Hosts", // "The Summons of the Lord of Hosts"
'b/TU': "Tabernacle of Unity", // "The Tabernacle of Unity"
// 'b/TB': "Tablets of Bahá’u’lláh Revealed After the Kitáb-i-Aqdas", // "Tablets of Bahá’u’lláh Revealed After the Kitáb-i-Aqdas"
'tb/SWB': "Selections from the Writings of the Báb", // "Selections From the Writings of the Báb"
'ab/ABL': "`Abdu'l-Bahá in London", // '': "‘Abdu’l-Bahá in London"
'c/BWF': "Bahá'í World Faith", // "Bahá’í World Faith—Selected Writings of Bahá’u’lláh and ‘Abdu’l-Bahá (‘Abdu’l-Bahá’s Section Only)"
// 'c/FWU': "Foundations of World Unity",
// 'ab/MF': "Memorials of the Faithful",
// 'ab/PT': "Paris Talks",
'ab/PUP': "Promulgation of Universal Peace", // "The Promulgation of Universal Peace"
'ab/SDC': "Secret of Divine Civilization", // "The Secret of Divine Civilization"
'ab/SAB': "Selections from the Writings of 'Abdu'l-Bahá", // "Selections from the Writings of ‘Abdu’l-Bahá"
// 'ab/SAQ': "Some Answered Questions",
// 'ab/TAF': "Tablet to August Forel",
'ab/TAB': "Tablets of 'Abdu'l-Bahá", // "Tablets of ‘Abdu’l-Bahá"
// 'ab/TDP': "Tablets of the Divine Plan",
'ab/TN': "Traveler's Narrative", // "A Traveler's Narrative"
'ab/WT': "Will and Testament of 'Abdu'l-Bahá", // "The Will and Testament of ‘Abdu’l-Bahá"
'se/ADJ': "Advent of Divine Justice", // "The Advent of Divine Justice"
'se/ARO': "Arohanui", // "Arohanui: Letters to New Zealand"
// 'se/BA': "Bahá'í Administration",
// 'se/CF': "Citadel of Faith",
// 'se/DND': "Dawn of a New Day",
// 'se/DG': "Directives from the Guardian",
// 'se/GPB': "God Passes By",
'se/HE': "High Endeavours", // "High Endeavours: Messages to Alaska"
// 'se/LANZ': "Letters from the Guardian to Australia and New Zealand",
'se/LDG1': "Light of Divine Guidance (vol1)", // "The Light of Divine Guidance (Volume I)"
'se/LDG2': "Light of Divine Guidance (vol2)", // "The Light of Divine Guidance (Volume II)"
// 'se/MA': "Messages to America",
'se/MC': "Messages to Canada",
'se/MBW': "Messages to the Bahá'í World", // "Messages to the Bahá'í World: 1950-1957"
'se/PDC': "Promised Day is Come", // "The Promised Day is Come"
'se/UD': "Unfolding Destiny",
'se/WOB': "World Order of Bahá'u'lláh", // "The World Order of Bahá'u'lláh"
'uhj/PWP': "Promise of World Peace", // "The Promise of World Peace"
// 'bic/COL': "Century of Light",
// 'bic/OCF': "One Common Faith",
'bic/PRH': "Prosperity of Humankind",
'bic/SB': "Bahá'u'lláh (statement)",
'c/BP': "Bahá'í Prayers", // "Bahá'í Prayers: A selection of prayers revealed by Bahá'u'lláh, the Báb, and ‘Abdu’l-Baha.",
'c/BE': "Bahá'í Education", // "Compilation on Bahá'í Education",
'c/CP': "Peace (compilation)", // "Compilation on Peace"
'c/SCH': "Scholarship (compilation)", // "Compilation on Scholarship"
'c/CW': "Women (compilation)", // "Compilation on Women"
'c/HC': "Huqúqu'lláh—The Right of God", // "Huqúqu’lláh—The Right of God"
// 'c/JWTA': "Japan Will Turn Ablaze!",
'je/BNE': "Bahá'u'lláh and the New Era",
'bwc/BK': "Bahíyyih Khánum (compilation)",
'nz/DB': "Dawn-Breakers" // , // "The Dawn Breakers"
},
// Indicates missing for Baha'u'llah, the Bab,
SpecialWritingsMap = {
Bahai9 : {},
Bahaipedia: {'b/GWB': 'Gleanings from the Writings of Bahá’u’lláh', 'ab/ABL': '‘Abdu’l-Bahá in London'},
Wikipedia: {'ab/WT': 'Will_and_Testament_of_`Abdu\'l-Bahá',
'se/BA': 'Bahá\'í_Administration_(book)', 'se/DND': 'Dawn of a New Day (book)',
'se/LDG1': 'Light of Divine Guidance', 'se/LDG2': 'Light of Divine Guidance',
'uhj/PWP': 'The Promise of World Peace',
'bwc/BK': 'Bahíyyih Khánum (book)',
'nz/DB': 'The Dawn-Breakers'
},
Bahaiworks: {'b/GWB': 'Gleanings from the Writings of Bahá’u’lláh', 'ab/ABL': '‘Abdu’l-Bahá in London',
'nz/DB': 'The Dawn-Breakers'
}
},
MissingWritingsMap = {
Bahai9: ['bic/SB'],
Bahaipedia: ['b/PM', 'b/PB', 'b/SVFV',
'ab/ABL', 'c/BWF', 'ab/MF', 'ab/TAB', 'ab/TN',
'se/ARO', 'se/CF', 'se/DND', 'se/DG', 'se/HE', 'se/LANZ', 'se/LDG1', 'se/LDG2', 'se/MA', 'se/MC', 'se/MBW', 'se/PDC', 'se/UD',
'uhj/PWP', 'bic/COL', 'bic/OCF', 'bic/PRH', 'bic/SB', 'c/BP', 'c/BE', 'c/CP', 'c/SCH', 'c/CW', 'c/HC', 'c/JWTA', 'bwc/BK'
],
Wikipedia: ['b/PM', 'b/PB', 'b/SVFV',
'ab/ABL', 'ab/MF', 'ab/PUP', 'ab/SAB', 'ab/TAF', 'ab/TAB', 'ab/TN',
'se/ARO', 'se/CF', 'se/DND', 'se/DG', 'se/HE', 'se/LANZ', 'se/LDG1', 'se/LDG2', 'se/MA', 'se/MC', 'se/MBW', 'se/UD',
'bic/COL', 'bic/OCF', 'bic/PRH', 'bic/SB', 'c/BP', 'c/BE', 'c/CP', 'c/SCH', 'c/CW', 'c/HC', 'c/JWTA', 'bwc/BK'
],
Bahaiworks: ['b/PB',
'ab/ABL', 'c/BWF', 'ab/MF', 'ab/PT', 'ab/MF', 'ab/SAB', 'ab/TAF', 'ab/TAB', 'ab/TDP', 'ab/TN', 'ab/WT',
'se/ARO', 'se/BA', 'se/CF', 'se/DND', 'se/DG', 'se/GPB', 'se/HE',
'se/LANZ', 'se/LDG1', 'se/LDG2', 'se/MA', 'se/MC', 'se/MBW', 'se/PDC', 'se/UD', 'se/WOB',
'uhj/PWP', 'bic/COL', 'bic/OCF', 'bic/PRH', 'bic/SB', 'c/BP', 'c/BE', 'c/CP', 'c/SCH', 'c/CW', 'c/HC', 'c/JWTA', 'je/BNE', 'bwc/BK'
]
};
|
describe('ModeloConsultaDeTs', function() {
var ModeloConsultaDeTs;
beforeEach(module('ApiConsumator'))
beforeEach(inject(function($injector) {
ModeloConsultaDeTs = $injector.get('ModeloConsultaDeTs')
}))
describe('criação', function() {
it('deve ter as propriedades default preenchidas corretamente', function() {
var _m = new ModeloConsultaDeTs();
expect(_m.Ttype).toBe('')
expect(_m.Ttext).toBe('')
})
it('deve ter as propriedades default sobrescritas corretamente', function() {
var _objPassado = {
Ttype: '1',
Ttext: '999',
outraInfo: true
}
var _m = new ModeloConsultaDeTs(_objPassado);
expect(_m.Ttype).toBe(_objPassado.Ttype)
expect(_m.Ttext).toBe(_objPassado.Ttext)
expect(_m.outraInfo).toBe(_objPassado.outraInfo)
})
})
describe('typePreenchido', function() {
it('deve retornar false, porque a instância é vazia - sem type', function() {
var _m = new ModeloConsultaDeTs();
expect(_m.typePreenchido()).toBe(false)
})
it('deve retornar false, porque a instância é vazia - type é string vazia', function() {
var _m = new ModeloConsultaDeTs({Ttype: ''});
expect(_m.typePreenchido()).toBe(false)
})
it('deve retornar false, porque a instância é vazia - com type preenchido', function() {
var _m = new ModeloConsultaDeTs({Ttype: 'yo!'});
expect(_m.typePreenchido()).toBe(true)
})
})
describe('textPreenchido', function() {
it('deve retornar false, porque a instância é vazia - sem type', function() {
var _m = new ModeloConsultaDeTs();
expect(_m.textPreenchido()).toBe(false)
})
it('deve retornar false, porque a instância é vazia - type é string vazia', function() {
var _m = new ModeloConsultaDeTs({Ttext: ''});
expect(_m.textPreenchido()).toBe(false)
})
it('deve retornar false, porque a instância é vazia - com type preenchido', function() {
var _m = new ModeloConsultaDeTs({Ttext: 'yo!'});
expect(_m.textPreenchido()).toBe(true)
})
})
describe('estaValido', function() {
it('deve retornar false, porque o método typePreenchido recebeu false', function() {
var _m = new ModeloConsultaDeTs();
expect(_m.estaValido()).toBe(false)
})
it('deve retornar false, porque o método textPreenchido recebeu false', function() {
var _m = new ModeloConsultaDeTs();
expect(_m.estaValido()).toBe(false)
})
it('deve retornar true, pois ambos os métodos typePreenchido e textPreenchido retornaram true', function() {
var _m = new ModeloConsultaDeTs({Ttype: 'yo!', Ttext: 'yo2!'});
expect(_m.estaValido()).toBe(true)
})
})
})
|
var express = require('express');
var router = express.Router();
// use session auth to secure the angular app files
router.use('/', function (req, res, next) { // request will be intercepted
console.log("token is " + req.session.token)
if (req.path !== '/login' && !req.session.token) {
return res.redirect('/login?returnUrl=' + encodeURIComponent('/app' + req.path));
}
next();
});
// make JWT token available to angular app
router.get('/token', function (req, res) {
res.send(req.session.token);
});
// serve angular app files from the '/app' route
router.use('/', express.static('app'));
module.exports = router;
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
coffee: {
compile:{
files: {
'app/js/quote.js' : 'app/coffee/quote.coffee',
'app/js/util.js' : 'app/coffee/util.coffee',
}
}
},
<<<<<<< HEAD
=======
copy: {
main: {
expand: true,
cwd: 'bower_components/',
src: '**/*.js',
dest: 'app/js/vendor'
},
},
>>>>>>> ba20389... popup directive refined a lot.
watch: {
grunt: { files: ['Gruntfile.js'] },
coffee: {
files: 'app/coffee/**/*.coffee',
tasks: ['coffee'],
options: {
livereload: true,
}
},
markup: {
files: ['*.php', '**/*.php'],
options: {
livereload: true,
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-coffee');
<<<<<<< HEAD
=======
grunt.loadNpmTasks('grunt-contrib-copy');
>>>>>>> ba20389... popup directive refined a lot.
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('build', ['coffee', 'copy']);
grunt.registerTask('default', ['watch']);
//grunt.registerTask('default', ['copy', 'uglify', 'concat', 'watch']);
}
|
/**
* @external {Project} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Project
*/
/**
* @external {Schema} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Schema
*/
/**
* @external {Column} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Column
*/
/**
* @external {Changes} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Changes
*/
/**
* @external {Change} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Change
*/
/**
* @external {DataInfo} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-DataInfo
*/
/**
* @external {Item} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Item
*/
/**
* @external {ValidationResult} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ValidationResult
*/
/**
* @external {ProjectCreateChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ProjectCreateChange
*/
/**
* @external {ProjectTagChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ProjectTagChange
*/
/**
* @external {SchemaCreateChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-SchemaCreateChange
*/
/**
* @external {SchemaRemoveChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-SchemaRemoveChange
*/
/**
* @external {SchemaRenameChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-SchemaRenameChange
*/
/**
* @external {ColumnCreateChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnCreateChange
*/
/**
* @external {ColumnRemoveChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnRemoveChange
*/
/**
* @external {ColumnRenameChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnRenameChange
*/
/**
* @external {ColumnTypechangeChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnTypechangeChange
*/
"use strict";
|
jQuery.sap.registerModulePath("oui5lib", "webapp");
var oui5lib = {};
oui5lib.namespace = function(string) {
var object = this;
var levels = string.split(".");
for (var i = 0, l = levels.length; i < l; i++) {
if (typeof object[levels[i]] === "undefined") {
object[levels[i]] = {};
}
object = object[levels[i]];
}
return object;
};
const xhr = new XMLHttpRequest();
xhr.open("GET", "oui5lib.json", false);
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 0) {
try {
const configData = JSON.parse(xhr.responseText);
oui5lib.config = configData;
} catch (e) {
throw new Error("Not valid JSON");
}
}
}
};
xhr.send();
|
'use strict';
moduloPrioridad.controller('PrioridadPListController', ['$scope', '$routeParams', '$location', 'serverService', 'prioridadService', '$uibModal',
function ($scope, $routeParams, $location, serverService, prioridadService, $uibModal) {
$scope.fields = prioridadService.getFields();
$scope.obtitle = prioridadService.getObTitle();
$scope.icon = prioridadService.getIcon();
$scope.ob = prioridadService.getTitle();
$scope.title = "Listado de " + $scope.obtitle;
$scope.op = "plist";
$scope.numpage = serverService.checkDefault(1, $routeParams.page);
$scope.rpp = serverService.checkDefault(10, $routeParams.rpp);
$scope.neighbourhood = serverService.getGlobalNeighbourhood();
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.filtervalue = "";
$scope.filterParams = serverService.checkNull($routeParams.filter)
$scope.orderParams = serverService.checkNull($routeParams.order)
$scope.sfilterParams = serverService.checkNull($routeParams.sfilter)
$scope.filterExpression = serverService.getFilterExpression($routeParams.filter, $routeParams.sfilter);
$scope.status = null;
$scope.debugging = serverService.debugging();
$scope.url = $scope.ob + '/' + $scope.op;
function getDataFromServer() {
serverService.promise_getCount($scope.ob, $scope.filterExpression).then(function (response) {
if (response.status == 200) {
$scope.registers = response.data.message;
$scope.pages = serverService.calculatePages($scope.rpp, $scope.registers);
if ($scope.numpage > $scope.pages) {
$scope.numpage = $scope.pages;
}
return serverService.promise_getPage($scope.ob, $scope.rpp, $scope.numpage, $scope.filterExpression, $routeParams.order);
} else {
$scope.status = "Error en la recepción de datos del servidor1";
}
}).then(function (response) {
if (response.status == 200) {
$scope.page = response.data.message;
$scope.status = "";
} else {
$scope.status = "Error en la recepción de datos del servidor2";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor3";
});
}
$scope.pop = function (id, foreignObjectName, foreignContollerName, foreignViewName) {
var modalInstance = $uibModal.open({
templateUrl: 'js/' + foreignObjectName + '/' + foreignViewName + '.html',
controller: foreignContollerName,
size: 'lg',
resolve: {
id: function () {
return id;
}
}
}).result.then(function (modalResult) {
if (modalResult) {
getDataFromServer();
}
});
};
getDataFromServer();
}]);
|
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _assert = _interopRequireDefault(require("assert"));
var t = _interopRequireWildcard(require("@babel/types"));
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)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ImportBuilder = function () {
function ImportBuilder(importedSource, scope, file) {
this._statements = [];
this._resultName = null;
this._scope = null;
this._file = null;
this._scope = scope;
this._file = file;
this._importedSource = importedSource;
}
var _proto = ImportBuilder.prototype;
_proto.done = function done() {
return {
statements: this._statements,
resultName: this._resultName
};
};
_proto.import = function _import() {
this._statements.push(t.importDeclaration([], t.stringLiteral(this._importedSource)));
return this;
};
_proto.require = function require() {
this._statements.push(t.expressionStatement(t.callExpression(t.identifier("require"), [t.stringLiteral(this._importedSource)])));
return this;
};
_proto.namespace = function namespace(name) {
if (name === void 0) {
name = "namespace";
}
name = this._scope.generateUidIdentifier(name);
var statement = this._statements[this._statements.length - 1];
(0, _assert.default)(statement.type === "ImportDeclaration");
(0, _assert.default)(statement.specifiers.length === 0);
statement.specifiers = [t.importNamespaceSpecifier(name)];
this._resultName = t.cloneNode(name);
return this;
};
_proto.default = function _default(name) {
name = this._scope.generateUidIdentifier(name);
var statement = this._statements[this._statements.length - 1];
(0, _assert.default)(statement.type === "ImportDeclaration");
(0, _assert.default)(statement.specifiers.length === 0);
statement.specifiers = [t.importDefaultSpecifier(name)];
this._resultName = t.cloneNode(name);
return this;
};
_proto.named = function named(name, importName) {
if (importName === "default") return this.default(name);
name = this._scope.generateUidIdentifier(name);
var statement = this._statements[this._statements.length - 1];
(0, _assert.default)(statement.type === "ImportDeclaration");
(0, _assert.default)(statement.specifiers.length === 0);
statement.specifiers = [t.importSpecifier(name, t.identifier(importName))];
this._resultName = t.cloneNode(name);
return this;
};
_proto.var = function _var(name) {
name = this._scope.generateUidIdentifier(name);
var statement = this._statements[this._statements.length - 1];
if (statement.type !== "ExpressionStatement") {
(0, _assert.default)(this._resultName);
statement = t.expressionStatement(this._resultName);
this._statements.push(statement);
}
this._statements[this._statements.length - 1] = t.variableDeclaration("var", [t.variableDeclarator(name, statement.expression)]);
this._resultName = t.cloneNode(name);
return this;
};
_proto.defaultInterop = function defaultInterop() {
return this._interop(this._file.addHelper("interopRequireDefault"));
};
_proto.wildcardInterop = function wildcardInterop() {
return this._interop(this._file.addHelper("interopRequireWildcard"));
};
_proto._interop = function _interop(callee) {
var statement = this._statements[this._statements.length - 1];
if (statement.type === "ExpressionStatement") {
statement.expression = t.callExpression(callee, [statement.expression]);
} else if (statement.type === "VariableDeclaration") {
(0, _assert.default)(statement.declarations.length === 1);
statement.declarations[0].init = t.callExpression(callee, [statement.declarations[0].init]);
} else {
_assert.default.fail("Unexpected type.");
}
return this;
};
_proto.prop = function prop(name) {
var statement = this._statements[this._statements.length - 1];
if (statement.type === "ExpressionStatement") {
statement.expression = t.memberExpression(statement.expression, t.identifier(name));
} else if (statement.type === "VariableDeclaration") {
(0, _assert.default)(statement.declarations.length === 1);
statement.declarations[0].init = t.memberExpression(statement.declarations[0].init, t.identifier(name));
} else {
_assert.default.fail("Unexpected type:" + statement.type);
}
return this;
};
_proto.read = function read(name) {
this._resultName = t.memberExpression(this._resultName, t.identifier(name));
};
return ImportBuilder;
}();
exports.default = ImportBuilder;
|
'use strict'
const server = require('./lib/server')
const base = require('../webpack.config')
module.exports = function(env) {
let config = base(env)
// Setup the webpack dev server to include our API endpoints
config.devServer.before = server
return config
}
|
app.controller('GroupListCtlr', [
'$scope',
'$http',
'ToastFactory',
function($scope, $http, toast) {
$scope.pageSize = 20;
$scope.currentPage = 0;
$scope.getGroups = function() {
$http.get('/api/management/groups')
.success(function(data, status, headers, config) {
if (data.success) $scope.groups = data.result;
else toast.error(data.error);
})
.error(function(data, status, headers, config) {
toast.error(data);
})
;
};
$scope.delete = function(group) {
swal({
title: 'Confirm group deletion',
text: 'You are about to delete group \"' + group + '\". Continue?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Confirm',
closeOnConfirm: true
}, function(){
toast.show('Deleting group \"' + group + '\" ...');
$http.delete('/api/management/groups/' + group)
.success(function(data, status, headers, config) {
if (data.success) {
toast.success('Group \"' + group + '\" deleted successfully!');
$scope.getGroups();
} else toast.error(data.error);
})
.error(function(data, status, headers, config) {
toast.error(data);
})
;
});
};
}
]);
|
export default {
cancel: 'Cancelar',
reply: 'Responder',
onMyWay: 'Estou a caminho',
customMessage: 'Mensagem personalizada',
callMeBackIn: 'Ligue de novo em',
willCallYouBackIn: 'Você pode ligar de novo em',
min: 'min.',
hours: 'horas',
days: 'dias',
};
// @key: @#@"cancel"@#@ @source: @#@"Cancel"@#@
// @key: @#@"reply"@#@ @source: @#@"Reply"@#@
// @key: @#@"onMyWay"@#@ @source: @#@"On my way"@#@
// @key: @#@"customMessage"@#@ @source: @#@"Custom Message"@#@
// @key: @#@"callMeBackIn"@#@ @source: @#@"Call me back in"@#@
// @key: @#@"willCallYouBackIn"@#@ @source: @#@"Will call you back in"@#@
// @key: @#@"min"@#@ @source: @#@"min."@#@
// @key: @#@"hours"@#@ @source: @#@"hours"@#@
// @key: @#@"days"@#@ @source: @#@"days"@#@
|
'use strict';
var cocktail = require('cocktail');
var senchaCmd = require('./cmd/sencha');
var listCmd = require('./cmd/list');
var useCmd = require('./cmd/use');
var versionCmd = require('./cmd/version');
var noOpCmd = require('./cmd/noop.js');
//TODO: Review this, maybe using nopts
var CMD_OPTIONS = {
'noop' : [noOpCmd],
'use' : [useCmd],
'list' : [listCmd],
'version' : [versionCmd]
};
cocktail.mix({
'@exports': module,
'@as': 'class',
'@static': {
create: function (args) {
var Module = this,
pargs = args.slice(2),
talents = Module._cmdByArgs(pargs),
cli;
cli = new Module(pargs);
cocktail.mix(cli, {'@talents': talents});
return cli;
},
_cmdByArgs: function (pargs) {
var first = pargs && pargs[0],
options = CMD_OPTIONS;
return options[first] || [senchaCmd];
}
},
'@properties': {
args: undefined
},
constructor: function (args) {
this.setArgs(args);
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.