text
stringlengths 2
6.14k
|
|---|
(function(){
"use strict";
/*
* Usage example:
* <div ng-init="ob = { field: 'a'}"></div>
* error: <input ng-model="error"> field: <input ng-model="ob.field">
* <div class="field-frame" label="Field:" error="{{error}}">
* <div class="view">{{ob.field}}</div>
* <div class="edit"><input ng-model="ob.field" class="form-control input-sm"></div>
* </div>
*/
angular.module('ngDataModel').directive('fieldFrame', function() {
function edit(elem) {
elem.find('div.edit').removeClass('op0').css('position', 'inherit');
elem.find('div.view').addClass('op0').css('position', 'absolute');
}
function hide(elem) {
elem.find('div.edit').addClass('op0').css('position', 'absolute');
elem.find('div.view').removeClass('op0').css('position', 'inherit');
}
return {
restrict: 'C',
scope: {
label: '@',
error: '@',
},
transclude: true,
templateUrl: 'angular_data_model/model_editors/templates/frame.html',
link: function(scope, elem) {
scope.$watch('error', function(nv) {
if(nv) elem.addClass('has-error');
else elem.removeClass('has-error');
})
if(elem.find('div.edit')[0] && elem.find('div.view')[0]) {
hide(elem);
elem.find('div.view').click(function(){
elem.find('div.edit').find('input, select').focus();
});
elem.find('div.view').dblclick(function(){
elem.find('div.edit').find('textarea').focus();
});
elem.find('div.edit').find('input, select').focus(function(){
edit(elem);
}).blur(function(){
hide(elem);
})
elem.find('div.edit').find('textarea').focus(function(){
edit(elem);
elem.find('div.view').hide();
}).blur(function(){
hide(elem);
elem.find('div.view').show();
})
};
}
}
});
})();
|
require('babel-register')
var config = require('../../config')
// http://nightwatchjs.org/gettingstarted#settings-file
module.exports = {
src_folders: ['test/e2e/specs'],
output_folder: 'test/e2e/reports',
custom_assertions_path: ['test/e2e/custom-assertions'],
selenium: {
start_process: true,
server_path: require('selenium-server').path,
host: '127.0.0.1',
port: 4444,
cli_args: {
'webdriver.chrome.driver': require('chromedriver').path
}
},
test_settings: {
default: {
selenium_port: 4444,
selenium_host: 'localhost',
silent: true,
globals: {
devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port)
}
},
chrome: {
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true
}
},
firefox: {
desiredCapabilities: {
browserName: 'firefox',
javascriptEnabled: true,
acceptSslCerts: true
}
}
}
}
|
// Karma configuration
// Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-sinon-chai',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-jquery',
'karma-chai-jquery'
],
// list of files / patterns to load in the browser
files: [
'bower/angular/angular.js',
'bower/angular-mocks/angular-mocks.js',
'dist/ng-c3-export.min.js',
'test/unit/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
function WalkontableScrollbars(instance) {
this.instance = instance;
instance.update('scrollbarWidth', Handsontable.Dom.getScrollbarWidth());
instance.update('scrollbarHeight', Handsontable.Dom.getScrollbarWidth());
this.vertical = new WalkontableVerticalScrollbarNative(instance);
this.horizontal = new WalkontableHorizontalScrollbarNative(instance);
this.corner = new WalkontableCornerScrollbarNative(instance);
if (instance.getSetting('debug')) {
this.debug = new WalkontableDebugOverlay(instance);
}
this.registerListeners();
}
WalkontableScrollbars.prototype.registerListeners = function () {
var that = this;
var oldVerticalScrollPosition
, oldHorizontalScrollPosition
, oldBoxTop
, oldBoxLeft;
function refreshAll() {
if(!that.instance.drawn) {
return;
}
if (!that.instance.wtTable.holder.parentNode) {
//Walkontable was detached from DOM, but this handler was not removed
that.destroy();
return;
}
that.vertical.windowScrollPosition = that.vertical.getScrollPosition();
that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition();
that.box = that.instance.wtTable.hider.getBoundingClientRect();
if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) {
that.vertical.onScroll();
that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles
oldVerticalScrollPosition = that.vertical.windowScrollPosition;
oldHorizontalScrollPosition = that.horizontal.windowScrollPosition;
oldBoxTop = that.box.top;
oldBoxLeft = that.box.left;
}
}
var $window = $(window);
this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) {
this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
}
if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) {
$window.on('scroll.' + this.instance.guid, refreshAll);
}
};
WalkontableScrollbars.prototype.destroy = function () {
if (this.vertical) {
this.vertical.destroy();
this.vertical.$scrollHandler.off('scroll.' + this.instance.guid);
}
if (this.horizontal) {
this.horizontal.destroy();
this.vertical.$scrollHandler.off('scroll.' + this.instance.guid);
}
$(window).off('scroll.' + this.instance.guid);
this.corner && this.corner.destroy();
this.debug && this.debug.destroy();
};
WalkontableScrollbars.prototype.refresh = function (selectionsOnly) {
this.horizontal && this.horizontal.readSettings();
this.vertical && this.vertical.readSettings();
this.horizontal && this.horizontal.refresh(selectionsOnly);
this.vertical && this.vertical.refresh(selectionsOnly);
this.corner && this.corner.refresh(selectionsOnly);
this.debug && this.debug.refresh(selectionsOnly);
};
WalkontableScrollbars.prototype.applyToDOM = function () {
this.horizontal && this.horizontal.applyToDOM();
this.vertical && this.vertical.applyToDOM();
};
|
// IndexedDB has been prefixed, so we need to get the prefixed version if the non-prefixed version
// is not available. from: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// if we don't have an object, we can't continue, obviously.
if (!indexedDB) {
console.log("You need to run this example in a browser that supports IndexedDB.");
}
function openDatabase({name, version, onopen, onerror, onupgrade}) {
let req = indexedDB.open(name, version);
req.onerror = function(evt) {
console.log("[DB] Encountered an error opening the database:" + evt.target.error);
};
req.onsuccess = function() {
let db = this.result;
db.onerror = onerror || function(dbEvent) {
console.log("[DB] Encountered a database error:" + dbEvent.target.error);
};
onopen(db);
};
req.onupgradeneeded = function(evt) {
let oldVersion = evt.oldVersion;
// Safari returns a really silly value for newly created databases.
// From https://github.com/treojs/idb-schema/blob/master/lib/index.js
onupgrade(evt.target.result, oldVersion > 4294967295 ? 0 : oldVersion);
};
}
function upgradeDatabase(db, oldVersion) {
for (let curVersion = oldVersion; curVersion < db.version; curVersion++) {
switch (curVersion) {
case 0:
console.log("First version schema");
let definitionStore = db.createObjectStore("definition", {keyPath: "wordNetRef"});
definitionStore.createIndex("lemmas", "lemmas", {unique: false, multiEntry: true});
console.log(definitionStore.indexNames);
break;
case 1:
console.log("Second version schema");
// these schemas will have keys automatically incremented
db.createObjectStore("notes", {autoIncrement: true});
db.createObjectStore("favorites", {autoIncrement: true});
break;
default:
console.log("No upgrade steps available");
}
}
}
function allDefinitionsByLemma(db) {
let IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
let range = IDBKeyRange.only("cat");
let req = db.transaction(["definition"]).objectStore("definition")
.index("lemmas").openCursor(range);
req.onerror = function (evt) {
console.log("[DB] An error occurred: " + evt.target.error);
db.close();
};
req.onsuccess = function (evt) {
let cursor = evt.target.result;
if (cursor) {
console.log(`key: ${cursor.key}, value: ${JSON.stringify(cursor.value, null, 2)}`);
cursor.continue();
} else {
console.log("No more entries.");
db.close();
}
};
}
function findADefinitionByLemma(db) {
let req = db.transaction(["definition"]).objectStore("definition")
.index("lemmas").get("cat");
req.onerror = function (evt) {
console.log("[DB] An error occurred: " + evt.target.error);
db.close();
};
req.onsuccess = function (evt) {
let definition = evt.target.result;
if (definition) {
console.log(JSON.stringify(definition, null, 2));
allDefinitionsByLemma(db);
} else {
console.log("Couldn't find entry.");
db.close();
}
};
}
function gotADatabase(db) {
// Definitions from WordNet. See LICENSE-WordNet.md in package root.
let definitions = [
{wordNetRef: "02124272", lemmas: ["cat", "true cat"], partOfSpeech: "noun", semantics: "noun.animal",
gloss: "feline mammal usually having thick soft fur and no ability to roar: domestic cats; wildcats"},
{wordNetRef: "02130460", lemmas: ["cat", "big cat"], partOfSpeech: "noun", semantics: "noun.animal",
gloss: "any of several large cats typically able to roar and living in the wild"},
{wordNetRef: "02085443", lemmas: ["aardvark", "ant bear", "anteater", "Orycteropus afer"], partOfSpeech: "noun", sematics: "noun.animal",
gloss: "nocturnal burrowing mammal of the grasslands of Africa that feeds on termites; sole extant representative of the order Tubulidentata"}
];
let transaction = db.transaction(["definition"], "readwrite");
transaction.onerror = function(evt) {
console.log("[DB] Transaction got an error: " + evt.target.error);
db.close();
};
transaction.oncomplete = function() {
console.log("[DB] All entries added.");
findADefinitionByLemma(db);
};
let definitionStore = transaction.objectStore("definition");
definitions.forEach(definition => definitionStore.put(definition));
}
let deleteReq = indexedDB.deleteDatabase("StarterDictionary");
deleteReq.onsuccess = () => {
openDatabase({name: "StarterDictionary", version: 2,
onopen: gotADatabase, onupgrade: upgradeDatabase});
};
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('helper:function-heading-id', function (hooks) {
setupRenderingTest(hooks);
test('should transform nested package to id', async function (assert) {
this.set('inputValue', '@ember/object/computed');
await render(hbs`{{function-heading-id inputValue}}`);
assert.dom(this.element).hasText('functions-computed');
});
});
|
module( "template test" );
test( "render template with data", function() {
hm.template.engineAdapter( "jsrender", {
render: function( templateId, dataSource, options ) {
return templateId.startsWith( "#" ) ?
$( templateId ).render( dataSource, options ) :
$.render[templateId]( dataSource, options );
}
} );
$.templates( "testTemplate", "{{:#data}}" );
hm.extend( {
dataSource: ["a", "b", "c"]
} );
var $view = $( "<div />" );
$view.sub( "dataSource", "init afterUpdate", "*tmpl", "testTemplate" );
equal( $view.html(), "abc",
"template converter convert data into markup" );
hm.template.engineAdapter( "jsrender" ).isTemplateLoaded = function() {
return false;
};
var defer = $.Deferred();
hm.template.load = function() {
return defer.promise();
};
hm.set( "dataSource", ["x", "y", "z"] );
equal( $view.html(), "abc",
"if isTemplateLoaded returns false, hm.loadTemplate will be used to load the template first" +
" and a promise object is return from getTemplatedContent, so handling process is pending" );
defer.resolve();
equal( $view.html(), "xyz",
"when template is loaded, template converter will continue to generate content ," +
"and the handling process continue" );
//hm.del( "dataSource" ).del( "copyOfDataSource" );
hm.debug.removeAll();
assertEmptyDb();
} );
|
/**
* @ngdoc controller
* @name EnqueteAdicionar
*
* @description
* Controladora responsável por gerenciar a tela de adiçao de enquete
*
* @requires $scope
* @requires $http
* @requires Enquete
* @requires $state
* */
enqueteControllers.controller('EnqueteAddCtrl', ['$scope', '$http', 'Enquete', '$state',
function ($scope, $http, Enquete, $state) {
$scope.checked = true;
$scope.enquete = new Enquete({
id: '',
nome: '',
ativa: 0,
created_at: '',
updated_at: ''
});
$scope.closeAlert = function (index) {
$scope.alerts.splice(index, 1);
};
$scope.submit = function () {
$scope.enquete.$save($scope.enquete, function (response, header) {
$state.go('enqueteEdit', {id: response.id, msg: '1'});
}, function (error) {
$scope.alerts = [
{
type: 'danger',
msg: '<strong>Erro!</strong> Tivemos alguns erros com a sua requisição por favor, verifique os dados.'
}
];
});
};
}
]);
|
(function(angular, CLIENT_VERSION, GITLAB_HOST, enableSignup, PROJECT_ID, PROJECT_PATH , BOARD_ROOT_PATH, BOARD_FULL_VIEW) {
'use strict';
var app = angular.module('gitlabKBApp', [
'ui.router',
'gitlabKBApp.user',
'gitlabKBApp.board',
'angular-loading-bar',
'angular-lodash',
'mm.foundation.topbar',
'angular-storage'
])
.run([
'$rootScope', '$state', '$http', 'AuthService', 'store',
function($rootScope, $state, $http, AuthService, store) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (!AuthService.authorized(toState)) {
event.preventDefault();
if (!store.get('state')) {
store.set('state', {
name: toState.name,
params: toParams
});
}
$state.go('login');
}
});
}
])
.constant('host_url', GITLAB_HOST)
.constant('version', CLIENT_VERSION)
.constant('enable_signup', enableSignup)
.constant('project_id', PROJECT_ID)
.constant('project_path', PROJECT_PATH)
.constant('board_root_path', BOARD_ROOT_PATH)
.constant('board_full_view', BOARD_FULL_VIEW)
.config(
[
'$locationProvider',
function($locationProvider) {
$locationProvider.html5Mode(true);
}
]
)
.factory("KBStore", ["store", function(store) {
return store.getNamespacedStore("kb", "localStorage", ":");
}]);
})(window.angular, window.CLIENT_VERSION, window.GITLAB_HOST, window.ENABLE_SIGNUP, window.PROJECT_ID, window.PROJECT_PATH, window.BOARD_ROOT_PATH, window.BOARD_FULL_VIEW);
|
import ajax from '@/utils/request'
class UserService {
// 登录,获取 token
login (username, password) {
return ajax({
url: '/login',
data: { username, password }
})
}
// 获取用户信息
getInfo (token) {
return ajax({
url: '/user/info',
data: { token }
})
}
/**
* 获取用户列表
*
* @param {Object} data 传参,eg: { id: 123 }
* @return {Promise}
*/
fetch (data = {}) {
return ajax({
url: '/start',
data
})
}
/**
* 获取表头
*/
getSort () {
return ajax({
url: '/sort'
})
}
// 登出
logout () {
return ajax({
url: '/logout'
})
}
}
export default new UserService()
|
/* eslint no-console: off */
const producer = require('../../src/index')().producer;
producer.connect()
.then(() => {
producer.produce('queueName', { message: 'hello world!' })
.then(console.info); // true if message has been sent, else false
});
|
let http = require('http'),
parse = require('url').parse,
join = require('path').join,
fs = require('fs');
let root = __dirname;
let server = http.createServer(( req, res )=>{
let url = parse( req.url );
let path = join( root, url.pathname );
fs.stat(path,(err,stat)=>{
if(err){
if('ENOENT'==err.code){
res.statusCode = 404;
res.end('Not Found');
}else{
res.statusCode = 500;
res.end('Internal Server Error');
}
}else{
res.setHeader('Content-Length',stat.size);
let stream = fs.createReadStream(path);
stream.pipe(res);
stream.on('error',(err)=>{
res.statusCode = 500;
res.end('Internal Server Error');
});
}
});
});
server.listen(9999);
console.log(9999);
|
import * as React from 'react';
import { createClientRender, describeConformanceV5 } from 'test/utils';
import Alert, { alertClasses as classes } from '@material-ui/core/Alert';
import Paper from '@material-ui/core/Paper';
describe('<Alert />', () => {
const render = createClientRender();
describeConformanceV5(<Alert />, () => ({
classes,
inheritComponent: Paper,
render,
refInstanceof: window.HTMLDivElement,
muiName: 'MuiAlert',
testVariantProps: { variant: 'standard', color: 'success' },
testDeepOverrides: { slotName: 'message', slotClassName: classes.message },
skip: ['componentsProp'],
}));
});
|
import { chars } from './chars'
/**
* 颠倒字符串中字符的顺序
* @module str/reverse
* @param {String} str 需要颠倒字符的顺序的字符串
* @return {String} 已颠倒字符的顺序的字符串
* @example
* str.reverse('foo bar') // 'rab oof'
* str.reverse(123.45) // '54.321'
*/
export let reverse = str => chars(str).reverse().join('')
|
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/carActions';
import Overview from '../Components/Overview';
import FullOverview from '../Components/FullOverview';
import toastr from 'toastr';
import _ from 'lodash';
class OverviewPage extends React.Component {
constructor(props, context) {
super(props, context);
this.onSave = this.onSave.bind(this);
this.updateCarState = this.updateCarState.bind(this);
this.totalCarsInfo = this.totalCarsInfo.bind(this);
this.state = {
car: Object.assign({}, this.props.car),
errors: {}
}
}
// ComponentWillReceiveProps(newProps) {
// console.log('ComponentWillReceiveProps:--->',newProps);
// if (this.props.car.id != newProps.car.id) {
// console.log('update new props:--->');
// }
// }
totalCarsInfo() {
if (!this.props || !this.props.cars || !this.props.cars.length > 0) {
return {
totalCarsSold: 0,
totalRevenue: 0,
highestModel: '-',
leastModel: '-',
highestSalesMonth: '-'
}
}
let months = ['June','July','August','September','October','November'],
totalCarsSold = 0,
totalRevenue = 0,
highestModel = 0,
leastModel = 0,
highestSalesMonth = ""
_.forOwn(this.props.cars, function (car,index) {
console.log('car in full overview :--->', car, index);
let carRevenue = 0,
carSold=0;
_.forOwn(car.sales.last6MonthSales, function (sales) {
totalCarsSold = totalCarsSold + sales;
carSold = carSold + sales;
})
_.forOwn(car.sales.last6MonthRevenue, function (revenue) {
totalRevenue = totalRevenue + revenue;
carRevenue = carRevenue + revenue;
})
if (carSold > highestModel) highestModel = index;
if (leastModel === 0)
leastModel = index;
else if(carSold < leastModel)
leastModel = index;
if (carRevenue > highestSalesMonth) highestSalesMonth = index;
})
return {
totalCarsSold :totalCarsSold,
totalRevenue :totalRevenue,
highestModel :this.props.cars[highestModel].title,
leastModel :this.props.cars[leastModel].title,
highestSalesMonth :months[highestSalesMonth]
}
}
updateCarState(event) {
const field = event.target.name;
let car = this.state.car;
car[field] = event.target.value;
return this.setState({ car: car });
}
onSave(event) {
event.preventDefault();
this.setState({ saving: true });
this.props.actions.saveCar(this.state.car)
.then(() => this.redirect())
.catch(error => {
toastr.error(error);
this.setState({ saving: false });
});
}
redirect() {
this.setState({ saving: false });
toastr.success('Car saved');
this.context.router.push('/sales-tracker');
}
render() {
console.log('overview props:--->', this.props);
const {car,cars} = this.props;
if (this.props.params.id) {
return (
<Overview car={car} cars={cars} totalCarsInfo={this.totalCarsInfo()}/>
)
} else {
return (
<FullOverview cars={cars} totalCarsInfo={this.totalCarsInfo()}/>
)
}
}
};
OverviewPage.propTypes = {
car: PropTypes.object.isRequired,
cars: PropTypes.array.isRequired,
};
OverviewPage.contextTypes = {
router: PropTypes.object
};
function getCarById(cid, cars) {
const car = cars.filter(car => car.cid == cid);
if (car) return car[0];
return null;
}
function mapStateToProps(state, ownProps) {
console.log('Overview ID:--->', state, ownProps);
let cid = ownProps.params.id;
let car = {};
if (cid && state.cars.length > 0) {
car = getCarById(cid, state.cars);
}
return {
cars: state.cars,
car: car
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(OverviewPage);
|
/* global setTimeout */
import Ember from 'ember';
import { module, moduleFor, test } from 'ember-qunit';
import { setResolverRegistry } from '../../helpers/resolver';
function setupRegistry() {
setResolverRegistry({
'component:x-foo': Ember.Component.extend(),
});
}
var callbackOrder, setupContext, teardownContext, beforeSetupContext, afterTeardownContext;
moduleFor('component:x-foo', 'TestModule callbacks', {
beforeSetup: function() {
beforeSetupContext = this;
callbackOrder = ['beforeSetup'];
setupRegistry();
},
beforeEach: function(assert) {
setupContext = this;
callbackOrder.push('setup');
return new Ember.RSVP.Promise(resolve => {
setTimeout(() => {
assert.ok(setupContext !== beforeSetupContext);
resolve();
}, 50);
});
},
afterEach: function(assert) {
teardownContext = this;
callbackOrder.push('teardown');
return new Ember.RSVP.Promise(resolve => {
setTimeout(() => {
assert.deepEqual(callbackOrder, ['beforeSetup', 'setup', 'teardown']);
assert.equal(setupContext, teardownContext);
resolve();
}, 50);
});
},
afterTeardown: function(assert) {
afterTeardownContext = this;
callbackOrder.push('afterTeardown');
assert.deepEqual(callbackOrder, ['beforeSetup', 'setup', 'teardown', 'afterTeardown']);
assert.equal(afterTeardownContext, beforeSetupContext);
assert.ok(afterTeardownContext !== teardownContext);
},
});
test('setup callbacks called in the correct order', function(assert) {
assert.expect(7);
assert.deepEqual(callbackOrder, ['beforeSetup', 'setup']);
});
moduleFor('component:x-foo', 'beforeEach/afterEach callbacks', {
before: function() {
callbackOrder = ['before'];
},
beforeSetup: function() {
setupRegistry();
beforeSetupContext = this;
callbackOrder.push('beforeSetup');
},
beforeEach: function(assert) {
setupContext = this;
callbackOrder.push('beforeEach');
assert.ok(setupContext !== beforeSetupContext);
},
afterEach: function(assert) {
teardownContext = this;
callbackOrder.push('afterEach');
assert.equal(setupContext, teardownContext);
},
after: function(assert) {
callbackOrder.push('after');
assert.deepEqual(callbackOrder, ['before', 'beforeSetup', 'beforeEach', 'afterEach', 'after']);
},
});
test('setup callbacks called in the correct order', function(assert) {
assert.expect(4);
assert.deepEqual(callbackOrder, ['before', 'beforeSetup', 'beforeEach']);
});
moduleFor('component:x-foo', {
beforeSetup: setupRegistry,
beforeEach: function() {
setupContext = this;
},
});
test('works properly without description with beforeEach', function(assert) {
assert.expect(1);
assert.equal(setupContext, this, 'beforeEach was called properly');
});
moduleFor('component:x-foo', 'test callback argument', {
beforeSetup: setupRegistry,
beforeEach: function(assert) {
assert.ok(!!assert, 'assert was passed into beforeEach');
},
afterEach: function(assert) {
assert.ok(!!assert, 'assert was passed into afterEach');
},
});
test('callback receives assert argument', function(assert) {
assert.expect(3);
assert.ok(!!assert, 'assert argument was present');
});
test('assert argument is not shared between tests', function(assert) {
assert.expect(4);
assert.ok(!!assert, 'assert argument was present');
assert.ok(true, 'dummy extra test');
});
module('Wrapper', function(hooks) {
hooks.beforeEach(setupRegistry);
moduleFor('component:x-foo', 'Some description');
test('works properly without callbacks', function(assert) {
assert.expect(1);
assert.ok(this.subject());
});
moduleFor('component:x-foo');
test('works properly without description or callbacks', function(assert) {
assert.expect(1);
assert.ok(this.subject());
});
});
|
/**
* Created by Admin on 11.12.2015.
*/
angular.module('myControllersStackedAreaChart', []).
controller('stackedAreaChartCtrl', ['$scope', 'dataService', function ($scope, dataService) {
$scope.options = {
chart: {
type: 'stackedAreaChart',
height: 450,
margin: {
top: 20,
right: 20,
bottom: 50,
left: 70
},
x: function (d) {
return d[0];
},
y: function (d) {
return d[1];
},
useVoronoi: false,
clipEdge: true,
duration: 100,
useInteractiveGuideline: true,
xAxis: {
axisLabel: "age",
//tickFormat: function (d) {
// return d3.format(',.2f')(d)
//}
"showMaxMin": false
},
yAxis: {
//tickFormat: function (d) {
// return
axisLabel: "number of persons",
enabled: true,
scaleExtent: [1, 5],
useFixedDomain: false,
useNiceScale: false,
horizontalOff: false,
verticalOff: true,
unzoomEventType: 'dblclick.zoom'
}
}
};
var graphData = [
{
key: 'male',
values: []
},
{
key: 'femail',
values: []
}
];
for (var i = 0; i < 100; i++) {
graphData[0].values[i] = [i, 0];
graphData[1].values[i] = [i, 0];
}
dataService.all(function (data) {
data.forEach(function getData(item) {
graphData[item.gender === "male" ? 0 : 1].values[item.age][1]++;
})
});
$scope.data = graphData;
}]);
|
/* eslint-env node */
'use strict';
module.exports = function(/* environment, appConfig */) {
return {
emberPerf: {
debugMode: false,
logRerenders: true,
logViewEvents: true,
injectionFactories: ['route', 'adapter']
}
};
};
|
const React = require("react");
const renderer = require("react-test-renderer");
const ReactTopBar = require("../index");
test("ReactTopBar can show topbar", () => {
let count = 0;
const topbar = {
show() {
count++;
},
hide() {}
};
let root;
renderer.act(() => {
root = renderer.create(
React.createElement(ReactTopBar, { topbar: topbar })
);
});
renderer.act(() => {
root.unmount();
});
expect(count).toBe(1);
});
test("ReactTopBar can hide topbar", () => {
let count = 0;
const topbar = {
show() {},
hide() {
count++;
}
};
let root;
renderer.act(() => {
root = renderer.create(
React.createElement(ReactTopBar, { topbar: topbar })
);
});
renderer.act(() => {
root.unmount();
});
expect(count).toBe(1);
});
test("ReactTopBar can show/hide topbar", () => {
let count = 0;
const topbar = {
show() {
count++;
},
hide() {
count++;
}
};
let root;
renderer.act(() => {
root = renderer.create(
React.createElement(ReactTopBar, { topbar: topbar })
);
});
renderer.act(() => {
root.unmount();
});
expect(count).toBe(2);
});
test("ReactTopBar can show/hide topbar even with multiples call, but once", () => {
let count = 0;
const topbar = {
show() {
count++;
},
hide() {
count++;
}
};
let root;
renderer.act(() => {
root = renderer.create(
React.createElement(ReactTopBar, { topbar: topbar })
);
});
let root2;
renderer.act(() => {
root2 = renderer.create(
React.createElement(ReactTopBar, { topbar: topbar })
);
});
renderer.act(() => {
root.unmount();
});
renderer.act(() => {
root2.unmount();
});
expect(count).toBe(2);
});
test("ReactTopBar exposes topbar config function", () => {
expect(typeof ReactTopBar.config).toBe("function");
});
|
Assembly.registerFeature('Middleware', function (
framework, frameworkPrivate, featureConfig) {
this.registerInitializationStep('Add_Middleware_Engine', function (
app, appPrivate, appConfig, proceed, terminate) {
if (!('middleware' in appConfig) ||
!(appConfig.middleware instanceof Array)) {
appConfig.middleware = [];
};
appPrivate.middlewareEngine = new MiddlewareEngine();
proceed();
});
this.registerInitializationStep('Start_Middleware_Engine', function (
app, appPrivate, appConfig, proceed, terminate) {
this.dependsOnStep('Add_Middleware_Engine');
appPrivate.middlewareEngine.start(app, appConfig.middleware);
proceed();
});
});
|
(function() {
return {
name: 'bs',
weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
months: 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'),
weekStart: 1,
weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
monthsShort: 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'),
weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
ordinal: function(n) {
return n;
},
formats: {
LT: 'H:mm',
LTS: 'H:mm:ss',
L: 'DD.MM.YYYY',
LL: 'D. MMMM YYYY',
LLL: 'D. MMMM YYYY H:mm',
LLLL: 'dddd, D. MMMM YYYY H:mm'
}
};
})();
|
var searchData=
[
['_5f_5fcm0_5fcmsis_5fversion',['__CM0_CMSIS_VERSION',['../core__cm0_8h.html#af233a7b7b2818cc6194e7a9386faccd8',1,'core_cm0.h']]],
['_5f_5fcm0_5fcmsis_5fversion_5fmain',['__CM0_CMSIS_VERSION_MAIN',['../core__cm0_8h.html#acd01bf0a654a7f15f606593aa636bc72',1,'core_cm0.h']]],
['_5f_5fcm0_5fcmsis_5fversion_5fsub',['__CM0_CMSIS_VERSION_SUB',['../core__cm0_8h.html#ab6a85b0d3b2fbcfb62003006ece175cc',1,'core_cm0.h']]],
['_5f_5fcortex_5fm',['__CORTEX_M',['../core__cm0_8h.html#a63ea62503c88acab19fcf3d5743009e3',1,'core_cm0.h']]],
['_5f_5ffpu_5fused',['__FPU_USED',['../core__cm0_8h.html#aa167d0f532a7c2b2e3a6395db2fa0776',1,'core_cm0.h']]],
['_5f_5fi',['__I',['../core__cm0_8h.html#af63697ed9952cc71e1225efe205f6cd3',1,'core_cm0.h']]],
['_5f_5fio',['__IO',['../core__cm0_8h.html#aec43007d9998a0a0e01faede4133d6be',1,'core_cm0.h']]],
['_5f_5fo',['__O',['../core__cm0_8h.html#a7e25d9380f9ef903923964322e71f2f6',1,'core_cm0.h']]]
];
|
/**
* Unit test for the frost-table component
*
* NOTE: Since it is not easy to properly set up an integration test to confirm some of the DOM
* calculations happening in frost-table, I opted to unit test these calculations, making these
* tests a little more tied to the implementation than I'd like. However, given the hoops needed to jump through to
* simulate external CSS as well as scroll and mouse events, this seemed the better option (@job13er 2016-12-13)
*/
import {expect} from 'chai'
import {unit} from 'ember-test-utils/test-support/setup-component-test'
import {afterEach, beforeEach, describe, it} from 'mocha'
import sinon from 'sinon'
import {createSelectorStub} from 'dummy/tests/helpers/selector-stub'
const test = unit('frost-table')
describe(test.label, function () {
test.setup()
let component, sandbox
beforeEach(function () {
sandbox = sinon.sandbox.create()
component = this.subject({
columns: [],
hook: 'table',
hookQualifiers: {foo: 'bar'},
items: [],
tagName: 'div'
})
})
afterEach(function () {
sandbox.restore()
})
describe('Computed Properties', function () {
describe('indexedColumns', function () {
let column1, column2, column3
beforeEach(function () {
column1 = {}
column2 = {}
column3 = {}
component.setProperties({
columns: [column1, column2, column3]
})
})
it('should have set proper index for each column', function () {
const indexedColumns = component.get('indexedColumns')
expect(indexedColumns[0].index).to.equal(0)
expect(indexedColumns[1].index).to.equal(1)
expect(indexedColumns[2].index).to.equal(2)
})
})
describe('isSelectable', function () {
describe('selection is enabled', function () {
beforeEach(function () {
component.setProperties({
onSelectionChange: function () {}
})
})
it('should have isSelectable set to true', function () {
expect(component.get('isSelectable')).to.equal(true)
})
})
describe('selection is not enabled', function () {
it('should have isSelectable set to false', function () {
expect(component.get('isSelectable')).to.equal(false)
})
})
})
})
describe('.didRender()', function () {
let tableStub
beforeEach(function () {
tableStub = createSelectorStub('css')
sandbox.stub(component, '$')
.withArgs().returns(tableStub)
sandbox.stub(component, 'alignHeaderAndBody')
component.alignHeaderAndBody.returns(100)
component.didRender()
})
it('should have called alignColumns() with correct paramaters', function () {
expect(component.alignHeaderAndBody).to.have.been.calledWithExactly('.frost-table-header', '.frost-table-body')
})
it('should have set the table min-width', function () {
expect(tableStub.css).to.have.been.calledWithExactly('min-width', '100px')
})
})
describe('onCallback', function () {
let onCallback
beforeEach(function () {
onCallback = component.get('onCallback')
})
it('should default to a function', function () {
expect(onCallback()).to.equal(undefined)
})
})
})
|
/**
Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.
If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
*/
(function() {
/**
* ## Require & Instantiate
*
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
*/
window.jasmine = jasmineRequire.core(jasmineRequire);
/**
* Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
*/
jasmineRequire.html(jasmine);
/**
* Create the Jasmine environment. This is used to run all specs in a project.
*/
var env = jasmine.getEnv();
/**
* ## The Global Interface
*
* Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged.
*/
var jasmineInterface = jasmineRequire.interface(jasmine, env);
/**
* Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`.
*/
extend(window, jasmineInterface);
/**
* ## Runner Parameters
*
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
*/
var queryString = new jasmine.QueryString({
getWindowLocation: function() { return window.location; }
});
var catchingExceptions = queryString.getParam("catch");
env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
var throwingExpectationFailures = queryString.getParam("throwFailures");
env.throwOnExpectationFailure(throwingExpectationFailures);
var random = queryString.getParam("random");
env.randomizeTests(random);
var seed = queryString.getParam("seed");
if (seed) {
env.seed(seed);
}
/**
* ## Reporters
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
*/
var htmlReporter = new jasmine.HtmlReporter({
env: env,
onRaiseExceptionsClick: function() { queryString.navigateWithNewParam("catch", !env.catchingExceptions()); },
onThrowExpectationsClick: function() { queryString.navigateWithNewParam("throwFailures", !env.throwingExpectationFailures()); },
onRandomClick: function() { queryString.navigateWithNewParam("random", !env.randomTests()); },
addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); },
getContainer: function() { return document.body; },
createElement: function() { return document.createElement.apply(document, arguments); },
createTextNode: function() { return document.createTextNode.apply(document, arguments); },
timer: new jasmine.Timer()
});
/**
* The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
*/
env.addReporter(jasmineInterface.jsApiReporter);
env.addReporter(htmlReporter);
/**
* Filter which specs will be run by matching the start of the full name against the `spec` query param.
*/
var specFilter = new jasmine.HtmlSpecFilter({
filterString: function() { return queryString.getParam("spec"); }
});
env.specFilter = function(spec) {
return specFilter.matches(spec.getFullName());
};
/**
* Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
*/
window.setTimeout = window.setTimeout;
window.setInterval = window.setInterval;
window.clearTimeout = window.clearTimeout;
window.clearInterval = window.clearInterval;
/**
* ## Execution
*
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded.
*/
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
if(window.beforeJasmineExecute){
beforeJasmineExecute(jasmineExecute);
} else {
jasmineExecute();
}
};
function jasmineExecute(){
htmlReporter.initialize();
env.execute();
}
/**
* Helper function for readability above.
*/
function extend(destination, source) {
for (var property in source) destination[property] = source[property];
return destination;
}
}());
|
var crypto = require('crypto');
exports.parse = function(d) {
var datalength = d[1] & 127;
var indexFirstMask = 2;
if (datalength == 126) {
indexFirstMask = 4;
} else if (datalength == 127) {
indexFirstMask = 10;
}
var masks = d.slice(indexFirstMask, indexFirstMask + 4);
var i = indexFirstMask + 4;
var index = 0;
var output = "";
while (i < d.length) {
output += String.fromCharCode(d[i++] ^ masks[index++ % 4]);
}
return output;
};
exports.encode = function(d) {
var bytesFormatted = [];
bytesFormatted[0] = 129;
if (d.length <= 125) {
bytesFormatted[1] = d.length;
} else if (d.length >= 126 && d.length <= 65535) {
bytesFormatted[1] = 126;
bytesFormatted[2] = (d.length >> 8) & 255;
bytesFormatted[3] = (d.length) & 255;
} else {
bytesFormatted[1] = 127;
bytesFormatted[2] = (d.length >> 56) & 255;
bytesFormatted[3] = (d.length >> 48) & 255;
bytesFormatted[4] = (d.length >> 40) & 255;
bytesFormatted[5] = (d.length >> 32) & 255;
bytesFormatted[6] = (d.length >> 24) & 255;
bytesFormatted[7] = (d.length >> 16) & 255;
bytesFormatted[8] = (d.length >> 8) & 255;
bytesFormatted[9] = (d.length) & 255;
}
for (var i = 0; i < d.length; i++) {
bytesFormatted.push(d.charCodeAt(i));
}
return bytesFormatted;
};
exports.handshake = function(d) {
var headers = d.toString().split('\r\n'),
parsedHeaders = {};
headers.forEach(function(text) {
if (text !== 'GET / HTTP/1.1' && text !== '') {
var textArray = text.split(':');
parsedHeaders[textArray[0]] = textArray[1].trim();
}
});
var swa = crypto.createHash('sha1')
.update(parsedHeaders['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
.digest('base64');
var response = 'HTTP/1.1 101 Switching Protocols\r\n';
response += 'Upgrade: websocket\r\n';
response += 'Connection: Upgrade\r\n';
response += 'Sec-WebSocket-Accept: ' + swa + '\r\n';
response += 'Sec-WebSocket-Protocol: chat\r\n';
response += '\r\n';
return response;
};
|
import React from 'react';
export default class WatsonButton extends React.Component {
render() {
return (
<div className='col-md-4'>
<img src='../../app/images/commandIcon.png' alt="Watson Command Icon"
style={{
width: '20%',
}}
/>
</div>
);
}
}
|
var shoppingControllers = angular.module('shoppingControllers', []);
var uid = 6;
shoppingControllers.factory('productFactory',function(){
var products=[
{'id':0,'list':'Lista1','checked':false,'name':'Lapte','description':'2 litri','category':'Alimentare'},
{'id':1,'list':'Lista1','checked':false,'name':'Ciocolata','description':'3 tablete','category':'Alimentare'},
{'id':2,'list':'Lista1','checked':false,'name':'Crema','description':'','category':'Nealimentare'},
{'id':3,'list':'Lista2','checked':false,'name':'Margarina','description':'','category':'Alimentare'},
{'id':4,'list':'Lista2','checked':false,'name':'Mancare pisica','description':'3 Kg','category':'Hrana Animale'},
{'id':5,'list':'Lista2','checked':false,'name':'Uscator par','description':'','category':'Electronice'}
];
var factory={};
factory.getProducts=function(){
return products;
}
return factory;
});
shoppingControllers.factory('categoriesFactory',function(){
var categories=["Alimentare", "Nealimentare","Hrana Animale","Produse Copii","Electronice"];
var factory={};
factory.getCategories=function(){
return categories;
}
return factory;
});
shoppingControllers.factory('listsFactory',function(){
var lists=['Lista1','Lista2'];
var factory={};
factory.getLists=function(){
return lists;
}
return factory;
});
shoppingControllers.controller('ProductController', function($window,$scope,productFactory,categoriesFactory,listsFactory) {
$scope.addProduct=function(){
if($scope.newProduct.name==""||$scope.newProduct.name==null){
$window.alert('Numele produsului este obligatoriu!');
}else{
if($scope.newProduct.id==null){
$scope.newProduct.checked=false;
$scope.newProduct.id=uid++;
$scope.products.push($scope.newProduct);
}else{
for(i in $scope.products){
if($scope.products[i].id==$scope.newProduct.id){
$scope.products[i]=$scope.newProduct;
};
};
};
var lista=$scope.newProduct.list;
$scope.newProduct={};
$scope.newProduct.category='Alimentare';
$scope.newProduct.list=lista;
};
};
$scope.addList=function(){
$scope.lists.push($scope.newList);
$scope.newList='';
};
$scope.editProduct=function(id){
$scope.displayAddProduct=true;
for(i in $scope.products){
if ($scope.products[i].id==id) {
$scope.newProduct=angular.copy($scope.products[i]);
};
};
};
$scope.removeProduct=function(){
i=$scope.products.length;
while(i--){
if ($scope.products[i].checked==true) {
$scope.products.splice(i, 1);
};
};
};
$scope.products = productFactory.getProducts();
$scope.categories=categoriesFactory.getCategories();
$scope.lists = listsFactory.getLists();
});
|
#include "common/mysql_helper.js"
var DESCRIPTION="This advisor scans the MySQL data directory and notifies you"
" if the GRA_*.log file exists. This file only appears if there"
" is a failure or warning in your Galera replication.";
function main()
{
var hosts = cluster::mySqlNodes();
var advisorMap = {};
for (idx = 0; idx < hosts.size(); idx++)
{
host = hosts[idx];
map = host.toMap();
gStatus = map["galera"]["galerastatus"];
var msg ="";
var advice = new CmonAdvice();
advice.setTitle("GRA Log Checker");
advice.setHost(host);
justification = "";
if (host.nodeType() != "galera")
continue;
var datadir = host.dataDir();
if (datadir == "")
continue;
var retval = host.system("find " + datadir +
" -maxdepth 1 -name 'GRA_*.log' | wc -l");
nr_files = retval["result"];
if(nr_files.toInt() == 0) {
msg = "Nothing to do. No GRA_*.log files found.";
advice.setSeverity(Ok);
justification = "Galera host does not have GRA_*.log files in the"
" MySQL data directory.";
}
else {
justification = "Found " + nr_files +
" GRA_*.log file(s) in the MySQL data directory (" + datadir +").";
advice.setSeverity(Warning);
msg = "The Galera host contains GRA_*.log files in the"
" MySQL data directory. <br/>These GRA_*.log files are"
" created whenever there is a replication failure. "
"This could be because of any failure or warning in Galera to apply a"
" certain transaction to the other nodes, e.g. replication"
" deadlocks, huge transactions, or DDL changes to the same table."
" For troubleshooting"
" purposes these transactions are then logged inside these GRA log files."
" Even if your application retries to apply the transaction on"
" failure and ultimately succeeds these files are not removed."
" <br/> See also"
" <a href='https://www.percona.com/blog/2012/12/19/"
"percona-xtradb-cluster-pxc-what-about-gra_-log-files/'"
" target='_blank'>this blog post by Percona about this topic</a>."
" <br/><br/> Galera doesn't clean up these files automatically,"
" so you can remove them once they become too old. If you wish"
" to be certain, you can examine the files and see what query"
" causing the GRA log file to be created.";
}
advice.setAdvice(msg);
advice.setJustification(justification);
advisorMap[idx]= advice;
}
return advisorMap;
}
|
/**
* Author: thegoldenmule
* Date: 9/20/14
*/
(function (global) {
'use strict';
function parseTwoDigit(digit) {
if (digit < 10) {
return '0' + digit;
}
return digit;
}
function parseThreeDigit(digit) {
if (digit < 10) {
return '00' + digit;
}
if (digit < 100) {
return '0' + digit;
}
return digit;
}
function parseTime(milliseconds) {
var minutes = Math.floor(milliseconds / 60000);
milliseconds -= minutes * 60000;
var seconds = Math.floor(milliseconds / 1000);
milliseconds -= seconds * 1000;
return parseTwoDigit(minutes) + ':' + parseTwoDigit(seconds) + ':' + parseThreeDigit(milliseconds);
}
global.TimerView = function (metronome) {
var scope = this;
this.Started = new signals.Signal();
this.Stopped = new signals.Signal();
this.Ended = new signals.Signal();
this._metronome = metronome;
$('.timer-button').click(function(event) {
var attributes = event.target.attributes;
for (var i = 0, len = attributes.length; i < len; i++) {
var name = attributes[i].name;
var value = attributes[i].value;
if (name === 'timer-value') {
var minutes = parseFloat(value);
if (0 === minutes) {
scope.stop();
} else {
scope.start(minutes);
}
break;
}
}
});
metronome.Paused.add(function() {
scope.pause();
});
metronome.Played.add(function() {
scope.resume();
});
this._startTime = null;
this._pausedTime = null;
this._totalTime = null;
this._daemon = new Daemon.safe(this, this._tick, 1);
this._daemon.pause();
this._timerBar = $('#timer-progress').progressbar();
};
global.TimerView.prototype = {
constructor: global.TimerView,
getProgress:function() {
if (null === this._startTime) {
return 0;
}
if (null === this._pausedTime) {
return (Date.now() - this._startTime) / this._totalTime;
}
return (this._pausedTime - this._startTime) / this._totalTime;
},
start:function(minutes) {
this._pausedTime = null;
this._startTime = Date.now();
this._totalTime = minutes * 60000;
this._daemon.play();
this._metronome.play();
this.Started.dispatch();
},
pause:function() {
if (null !== this._pausedTime) {
return;
}
if (null === this._startTime) {
return;
}
this._daemon.pause();
this._pausedTime = Date.now();
},
resume:function() {
if (null === this._pausedTime || null === this._startTime) {
return;
}
var duration = this._pausedTime - this._startTime;
this._pausedTime = null;
this._startTime = Date.now() - duration;
this._daemon.play();
},
stop:function() {
this._daemon.pause();
this._startTime = null;
this._pausedTime = null;
this._totalTime = null;
this._tick();
this.Stopped.dispatch();
},
_tick:function() {
if (null === this._startTime) {
this._timerBar.progressbar('value', 0);
$('#timer-label').text('00:00:000');
} else {
var timeElapsed = Date.now() - this._startTime;
if (timeElapsed > this._totalTime) {
this.stop();
this._metronome.pause();
this.Ended.dispatch();
} else {
this._timerBar.progressbar('value', timeElapsed / this._totalTime * 100);
$('#timer-label').text(parseTime(this._totalTime - timeElapsed));
}
}
}
};
})(this);
|
function createHtmlElements(){
var createArray = function(splitNumber){
var widthDimension = $("#myElement").width();
var heightDimension = $("#myElement").height();
var totalH = 0;
var totalW = 0;
var tempH,tempW;
var i = 0;
var elements = [];
while (totalH < heightDimension){
if (heightDimension-totalH<=Math.round(heightDimension/splitNumber))
tempH = heightDimension-totalH;
else{
do{
tempH = Math.round(Math.random() * Math.round(heightDimension/splitNumber));
}while(tempH<Math.round(heightDimension/splitNumber)/2 || elements[tempH]!=undefined);
}
totalW = 0;
while (totalW < widthDimension){
if (widthDimension-totalW<=Math.round(widthDimension/splitNumber))
tempW = widthDimension-totalW;
else{
do{
tempW = Math.round(Math.random() * Math.round(widthDimension/splitNumber));
}while(tempW<Math.round(widthDimension/splitNumber)/2);
}
if (elements[tempH]==undefined){
elements[tempH] = [];
i=0;
}
elements[tempH][i] = tempW;
i++;
totalW = totalW+tempW;
}
totalH = totalH+tempH;
}
return elements;
}
var animations = {};
var bx,by,img,x,y,randFound,inc;
var widthDimension = $("#myElement").width();
var heightDimension = $("#myElement").height();
var elements = createArray(5);
bx = 0;
by = 0;
x = 0;
y = 0;
inc = -1;
i = -1;
for(key in elements){
x = 0;
bx = 0;
for (key2 in elements[key]){
i++;
$("#myElement").append('<div class="smalldiv" id="BUTTERFLY-'+i+'" style="background-position:'+bx+'px '+by+'px;left:'+x+'px;top:'+y+'px;width:'+elements[key][key2]+'px;height:'+key+'px;"></div>');
var sStart,sEnd;
var sStart = Math.round(Math.random()*5);
var sEnd = 20-Math.round(Math.random()*5);
inc++;
animations[inc] = {};
animations[inc]["selector"] = "#BUTTERFLY-"+i;
animations[inc]["method"] = "animate";
animations[inc]["property"] = "top";
animations[inc]["step-start"] = sStart;
animations[inc]["step-end"] = sEnd;
randFound = false;
if (Math.round(Math.random()*1)==1){
randFound = true;
if (Math.round(Math.random()*1)==1)
animations[inc]["value-end"] = heightDimension;
else
animations[inc]["value-end"] = 0-parseInt(key);
}
else
animations[inc]["value-end"] = Math.round(Math.random()*heightDimension);
inc++;
animations[inc] = {};
animations[inc]["selector"] = "#BUTTERFLY-"+i;
animations[inc]["method"] = "animate";
animations[inc]["property"] = "left";
animations[inc]["step-start"] = sStart;
animations[inc]["step-end"] = sEnd;
if (randFound)
animations[inc]["value-end"] = Math.round(Math.random()*widthDimension);
else{
if (Math.round(Math.random()*1)==1)
animations[inc]["value-end"] = widthDimension;
else
animations[inc]["value-end"] = 0-parseInt(elements[key][key2]);
}
inc++;
animations[inc] = {};
animations[inc]["selector"] = "#BUTTERFLY-"+i;
animations[inc]["method"] = "animate";
animations[inc]["property"] = "transform";
animations[inc]["step-start"] = sStart;
animations[inc]["step-end"] = sEnd;
animations[inc]["value-start"] = "rotate(0deg) scale(1)";
animations[inc]["value-end"] = "rotate("+Math.round((Math.random()*720)-360)+"deg) scale(0)";
x = x + parseInt(elements[key][key2]);
bx = bx - parseInt(elements[key][key2]);
}
y = y + parseInt(key);
by = by - parseInt(key);
}
$("#myElement").css('background-image','none');
return animations;
}
$(window).load(function(){
var animations = createHtmlElements();
$('butterfly').isAlive('create',{
duration:500,
elements:animations,
useCSS3:true,
easing:"easeOutQuad",
enableGPU:"webkit",
elementTweaks:{'width':1026,'height':778}
});
$('#myElement').click(function(){
$('butterfly').isAlive('toggle',{duration:2000});
return false;
});
});
|
(function() {
'use strict';
angular
.module('helloJhipsterApp')
.factory('JhiConfigurationService', JhiConfigurationService);
JhiConfigurationService.$inject = ['$filter', '$http'];
function JhiConfigurationService ($filter, $http) {
var service = {
get: get,
getEnv: getEnv
};
return service;
function get () {
return $http.get('management/configprops').then(getConfigPropsComplete);
function getConfigPropsComplete (response) {
var properties = [];
angular.forEach(response.data, function (data) {
properties.push(data);
});
var orderBy = $filter('orderBy');
return orderBy(properties, 'prefix');
}
}
function getEnv () {
return $http.get('management/env').then(getEnvComplete);
function getEnvComplete (response) {
var properties = {};
angular.forEach(response.data, function (val,key) {
var vals = [];
angular.forEach(val, function (v,k) {
vals.push({ key:k, val:v });
});
properties[key] = vals;
});
return properties;
}
}
}
})();
|
'use strict';
var cclib = {};
// version
cclib.version = require('../package.json').version;
// library errors
cclib.errors = require('./errors');
//
cclib.ColorData = require('./colordata').default;
cclib.ColorSet = require('./colorset').default;
cclib.ColorTarget = require('./colortarget').default;
cclib.ColorValue = require('./colorvalue').default;
// color definitions
cclib.definitions = {};
cclib.definitions.Manager = require('./definitions/manager').default;
cclib.definitions.Interface = require('./definitions/interface').default;
cclib.definitions.Uncolored = require('./definitions/uncolored').default;
cclib.definitions.Genesis = require('./definitions/genesis').default;
cclib.definitions.EPOBC = require('./definitions/epobc').default;
// storage (data and definitions)
cclib.storage = {};
cclib.storage.data = require('./storage/data');
cclib.storage.definitions = require('./storage/definitions');
// tx
cclib.tx = {};
cclib.tx.FilledInputs = require('./tx/filledinputs').default;
cclib.tx.Composed = require('./tx/composed').default;
cclib.tx.Operational = require('./tx/operational').default;
cclib.tx.SimpleOperational = require('./tx/simpleoperational').default;
module.exports = cclib;
|
"use strict";
module.exports = function (t, a) {
var anchor;
a.throws(function () {
t({});
}, "Other");
if (typeof document !== "undefined") {
anchor = document.createElement("a");
a(t(anchor), anchor, "Anchor");
}
};
|
require('@babel/register');
const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const cleanCSS = require('gulp-clean-css');
function styles() {
return gulp
.src('src/css/styles.css')
.pipe(cleanCSS({ compatibility: '*' }))
.pipe(gulp.dest('dist'));
}
function scripts() {
return gulp
.src(['src/js/Coordinate.js', 'src/js/NQueens.js', 'src/js/Board.js', 'src/js/app.js'])
.pipe(
babel({
presets: [['@babel/preset-env']],
})
)
.pipe(concat('bundle.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
}
function sw() {
return gulp
.src('./node_modules/workbox-sw/build/workbox-sw.js')
.pipe(concat('workbox-sw.js'))
.pipe(gulp.dest('./dist'));
}
gulp.task('default', gulp.series(gulp.parallel([styles, scripts]), sw));
|
import { onChange, getState, getUrl } from './state'
let historyPushType = 'replaceState'
const { setState, setFromUrl } = onChange(() => {
history[historyPushType](getState(), '', `./${getUrl()}`)
historyPushType = 'pushState'
})
addEventListener('popstate', ({ state }) => {
if (state != null) { // State can be null on page load (Chrome < 34 and Safari) => ignore
setState(state)
}
}, false)
const { hash } = location
if (hash.length > 0) {
setFromUrl(hash.substr(1))
}
|
#!/usr/bin/env node
var rot13 = require('..')();
process.stdin.pipe(rot13).pipe(process.stdout);
|
'use strict';
// Environment variables that grunt will set when the server starts locally. Use for your api keys, secrets, etc.
// You will need to set these on the server you deploy to.
//
// This file should not be tracked by git.
module.exports = {
SESSION_SECRET: "jcrsmartadmin-secret",
FACEBOOK_ID: "app-id",
FACEBOOK_SECRET: "secret",
TWITTER_ID: "app-id",
TWITTER_SECRET: "secret",
GOOGLE_ID: "app-id",
GOOGLE_SECRET: "secret",
// Control debug level for modules using visionmedia/debug
// DEBUG: ""
};
|
var mipmap : float = -0.5;
function Start () {
renderer.material.mainTexture.mipMapBias = mipmap;
}
|
'use strict';
angular.module('mainApp.admin', [
'mainApp.admin.controllers',
'mainApp.admin.directives',
'mainApp.admin.services',
'mainApp.admin.filters'
]);
function adminStateConfig ($stateProvider) {
$stateProvider.state('login', {
url: '/login',
controller: 'LoginController',
resolve: {
user: ['authService', '$q', function (authService, $q) {
if (authService.user) {
return $q.reject({authorized: true});
};
}]
},
templateUrl: 'modules/admin/views/login.html'
}).state('admin', {
url: '/admin',
abstract: true,
controller: 'AdminController',
resolve: {
user: ['authService', '$q', function (authService, $q) {
return authService.user || $q.reject({unAuthorized: true});
}]
},
templateUrl: 'modules/admin/views/admin-home.html'
}).state('admin.newPost', {
url: '/posts/new',
controller: 'CreatePostController',
templateUrl: 'modules/admin/views/admin-new-post.html'
}).state('admin.updatePost', {
url: '/posts/:id/edit',
controller: 'UpdatePostController',
templateUrl: 'modules/admin/views/admin-update-post.html'
}).state('admin.viewAllPosts', {
url: '',
controller: 'ListPostsController',
templateUrl: 'modules/admin/views/admin-all-posts.html'
});
}
function listenStateChangeErrorEvent ($rootScope, $state, $cookieStore, authService) {
$rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
if (error.unAuthorized) {
$state.go("login");
} else if (error.authorized) {
$state.go('admin.viewAllPosts');
};
});
authService.user=$cookieStore.get('user');
}
angular.module('mainApp.admin').config(['$stateProvider', adminStateConfig]);
angular.module('mainApp.admin').run(['$rootScope', '$state', '$cookieStore', 'authService', listenStateChangeErrorEvent]);
|
/**
* Created by Moyu on 16/10/21.
*/
import React from 'react';
import { Link } from 'react-router'
import {Map} from 'immutable'
class Header extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
return !Map(this.props).equals(Map(nextProps));
}
componentWillUpdate(nextProps, nextState, nextContext) {}
componentWillReceiveProps(nextProps) {}
componentDidMount() {}
componentDidUpdate(prevProps, prevState) {}
componentWillUnmount() {}
static defaultProps = {
links: ['/posts', '/tags'],
active: 0
}
render() {
const {active, texts, links} = this.props;
return (
<header style={{position: 'relative'}} itemScope itemType="//schema.org/WPHeader" >
<ul className="tabs">
<li className={"tabs__item "+(active==0?"active":"")}>
<Link to={links[0]}>
{texts && texts[0]||'Posts'}
</Link>
</li>
<li className={"tabs__item "+(active==1?"active":"")}>
<Link to={links[1]}>
{texts && texts[1]||'Tags'}
</Link>
</li>
</ul>
{/*<div className="searchbox"><input type="text" placeholder="Search..."/></div>*/}
</header>
)
}
static contextTypes = {
router: React.PropTypes.object.isRequired
}
switchHeader(i) {
const {router} = this.context;
const {links} = this.props;
router.push(links[i-0]);
}
}
export default Header;
|
'use strict';
//Setting up route
angular.module('applicants').config(['$stateProvider',
function($stateProvider) {
// Applicants state routing
$stateProvider.
state('applicants', {
abstract: true,
url: '/applicants',
template: '<ui-view/>'
}).
state('applicants.list', {
url: '',
templateUrl: 'modules/applicants/views/list-applicants.client.view.html'
}).
state('applicants.create', {
url: '/create',
templateUrl: 'modules/applicants/views/create-applicant.client.view.html'
}).
state('applicants.view', {
url: '/:applicantId',
templateUrl: 'modules/applicants/views/view-applicant.client.view.html'
}).
state('applicants.edit', {
url: '/:applicantId/edit',
templateUrl: 'modules/applicants/views/edit-applicant.client.view.html'
});
}
]);
|
app.controller('trabalhoController', function ($scope, $http, toastr) {
$scope.Trabalho = {
id: 0,
crianca_id: '',
criancaName:'',
valor: '',
parcelas:'',
saldo: '',
observacoes: ''
};
$scope.TrabalhoAdd = {
id: 0,
crianca_id: '',
criancaName: '',
valor: '',
parcelas: '',
saldo: '',
observacoes: ''
};
$scope.Crianca = {
id: 0,
nome: ''
};
$scope.lstTrabalho = true;
$scope.addTrabalho = false;
$scope.updtTrabalho = false;
$scope.showEditarTrabalho = function () {
$scope.addTrabalho = false;
$scope.lstTrabalho = false;
$scope.updtTrabalho = true;
};
$scope.showAddTrabalho = function () {
$scope.addTrabalho = true;
$scope.lstTrabalho = false;
$scope.updtTrabalho = false;
$scope.TrabalhoAdd = {
id: 0,
crianca_id: '',
criancaName: '',
valor: '',
parcelas: '',
saldo: '',
observacoes: ''
};
};
$scope.showListTrabalho = function () {
$scope.addTrabalho = false;
$scope.lstTrabalho = true;
$scope.updtTrabalho = false;
};
$scope.inserirTrabalho = function () {
$http.post('api/createTrabalho', $scope.TrabalhoAdd)
.success(function (data) {
console.log(data);
if (!data.erro) {
toastr.success('Trabalho adicionada!', 'Sucesso');
$scope.listarTrabalhos();
$scope.showListTrabalho();
} else {
toastr.error('Erro ao inserir Trabalho', 'Erro');
}
})
.error(function (data) {
toastr.error('Erro ao inserir Trabalho', 'Erro');
console.log(data);
});
}
$scope.listaTrabalhos = {};
$scope.listarTrabalhos = function () {
$http.get('api/listarTrabalhos')
.success(function (data) {
if (data.result.length == 0) {
toastr.info('Não foram encontrados registos', 'Informação');
} else {
$scope.listaTrabalhos = data.result;
}
})
.error(function (data) {
console.log(data);
toastr.error('Erro ao localizar trabalhos', 'Erro');
});
};
$scope.editarTrabalho = function (idTrabalho) {
$http.get('api/getTrabalho/' + idTrabalho)
.success(function (data) {
console.log(data);
$scope.Trabalho = data.result;
$scope.showEditarTrabalho();
})
.error(function (data) {
toastr.error('Falha em editar Trabalho', 'Erro');
console.log(data);
});
};
$scope.excluirTrabalho = function (idTrabalho) {
$http.get('api/excluirTrabalho/' + idTrabalho)
.success(function (data) {
toastr.success('Trabalho apagada com sucesso', 'Sucesso');
$scope.listarTrabalhos();
console.log(data);
})
.error(function (data) {
toastr.error('Falha em excluir Trabalho', 'Erro');
console.log(data);
});
};
$scope.alterarTrabalho = function () {
$http.post('api/alterarTrabalho/' + $scope.Trabalho.id, $scope.Trabalho)
.success(function (data) {
if (!data.erro) {
// auterou a Trabalho
toastr.success('Dados da Trabalho atualizado com sucesso', 'Sucesso');
$scope.listarTrabalhos();
$scope.showListTrabalho();
} else {
toastr.error('Falha em alterar dados da Trabalho', 'Erro');
console.log(data);
}
})
.error(function (data) {
toastr.error('Falha em alterar dados da Trabalho', 'Erro');
console.log(data);
});
};
$scope.listaCriancas = {};
$scope.listarCriancas = function () {
$http.get('api/listarCriancas')
.success(function (data) {
if (data.result.length == 0) {
toastr.info('Não foram encontrados registos', 'Informação');
} else {
$scope.listaCriancas = data.result;
}
})
.error(function (data) {
//alert("Falha em obter usuarios");
console.log(data);
toastr.error('Erro ao localizar criancas', 'Erro');
});
};
$scope.listarCriancas();
$scope.listarTrabalhos();
})
|
var requester = require('./CssFileRequester')
exports.route = function(app) {
app.get('/cssfile/*', function(req, res) {
var filepath = req.params[0];
var cb = req.query.callback;
if (!cb) {
return res.json({
code: 500,
msg: 'no callback'
});
}
var index = req.query.index;
if (!index) {
return res.json({
code: 500,
msg: 'no index'
});
}
res.writeHead(200, {'Content-Type': 'text/javascript'});
requester.requestCSSFile(filepath, function(err, content) {
res.end(cb + '(' + JSON.stringify({
code: content,
url: filepath,
index: index
})+ ')');
})
});
app.get('/ck_detect', function(req, res) {
var cb = req.query.callback;
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(cb + '(' + JSON.stringify({
code: 200
})+ ')');
})
app.get('/help|/h', function(req, res) {
res.json({
'-----': '本服务器的主要功能介绍',
'功能列表': [
'提供远程CSS文件的下载功能,用于解决CSS跨域问题',
'架设服务器下的public资源的访问路径,未来用于官网建设'
],
'路由匹配': {
'/cssfile/[url]': '下载css文件',
'/help': '本帮助',
'/h': '本帮助'
}
})
});
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = maChoiceField;
function updateChoices(scope, choices) {
scope.choices = choices;
scope.$root.$$phase || scope.$digest();
}
function maChoiceField($compile) {
return {
scope: {
'field': '&',
'value': '=',
'entry': '=?',
'datastore': '&?',
'refresh': '&',
'choices': '&?'
},
restrict: 'E',
compile: function compile() {
return {
pre: function pre(scope, element) {
var field = scope.field();
var attributes = field.attributes();
scope.placeholder = attributes && attributes.placeholder || 'FILTER_VALUES';
scope.name = field.name();
scope.v = field.validation();
scope.$watch('value', function (newValue, oldValue) {
if (newValue !== oldValue && newValue === undefined) {
// fix for https://github.com/angular-ui/ui-select/issues/863
scope.value = null;
}
});
var refreshAttributes = '';
var itemsFilter = '| filter: {label: $select.search}';
if (field.type().indexOf('reference') === 0 && field.remoteComplete()) {
// FIXME wrong place to do that
scope.refreshDelay = field.remoteCompleteOptions().refreshDelay;
refreshAttributes = 'refresh-delay="refreshDelay" refresh="refresh({ $search: $select.search })"';
itemsFilter = '';
}
var choices = scope.choices ? scope.choices : field.choices ? field.choices() : [];
var choicesFactory = void 0;
if (typeof choices === 'function' && choices(scope.entry)) {
choicesFactory = choices;
scope.choices = choicesFactory(scope.entry);
} else {
scope.choices = choices ? choices : [];
}
var template = '\n <ui-select ng-model="$parent.value" ng-required="v.required" id="{{ name }}" name="{{ name }}">\n <ui-select-match allow-clear="{{ !v.required }}" placeholder="{{ placeholder | translate }}">{{ $select.selected.label | translate }}</ui-select-match>\n <ui-select-choices ' + refreshAttributes + ' repeat="item.value as item in choices ' + itemsFilter + ' track by $index">\n {{ item.label | translate }}\n </ui-select-choices>\n </ui-select>';
// as choices may be a function depending of another entry field, we need to watch the whole entry
scope.$watch('entry', function (newEntry, oldEntry) {
if (!choicesFactory) {
return;
}
var oldChoices = scope.choices;
scope.choices = choicesFactory(newEntry);
if (!angular.equals(scope.choices, oldChoices)) {
scope.value = null;
}
}, true);
element.html(template);
var select = element.children()[0];
for (var name in attributes) {
select.setAttribute(name, attributes[name]);
}
$compile(element.contents())(scope);
},
post: function post(scope) {
scope.$on('choices:update', function (e, data) {
updateChoices(scope, data.choices);
});
}
};
}
};
}
maChoiceField.$inject = ['$compile'];
module.exports = exports['default'];
//# sourceMappingURL=maChoiceField.js.map
|
// Depends on rsa.js and jsbn2.js
// Version 1.1: support utf-8 decoding in pkcs1unpad2
// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
function pkcs1unpad2(d,n) {
var b = d.toByteArray();
var i = 0;
while(i < b.length && b[i] == 0) ++i;
if(b.length-i != n-1 || b[i] != 2)
return null;
++i;
while(b[i] != 0)
if(++i >= b.length) return null;
var ret = "";
while(++i < b.length) {
var c = b[i] & 255;
if(c < 128) { // utf-8 decode
ret += String.fromCharCode(c);
}
else if((c > 191) && (c < 224)) {
ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63));
++i;
}
else {
ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63));
i += 2;
}
}
return ret;
}
// Set the private key fields N, e, and d from hex strings
function RSASetPrivate(N,E,D) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
this.d = parseBigInt(D,16);
}
else
alert("Invalid RSA private key");
}
// Set the private key fields N, e, d and CRT params from hex strings
function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
this.d = parseBigInt(D,16);
this.p = parseBigInt(P,16);
this.q = parseBigInt(Q,16);
this.dmp1 = parseBigInt(DP,16);
this.dmq1 = parseBigInt(DQ,16);
this.coeff = parseBigInt(C,16);
}
else
alert("Invalid RSA private key");
}
// Generate a new random private key B bits long, using public expt E
function RSAGenerate(B,E) {
var rng = new SecureRandom();
var qs = B>>1;
this.e = parseInt(E,16);
var ee = new BigInteger(E,16);
for(;;) {
for(;;) {
this.p = new BigInteger(B-qs,1,rng);
if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
}
for(;;) {
this.q = new BigInteger(qs,1,rng);
if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
}
if(this.p.compareTo(this.q) <= 0) {
var t = this.p;
this.p = this.q;
this.q = t;
}
var p1 = this.p.subtract(BigInteger.ONE);
var q1 = this.q.subtract(BigInteger.ONE);
var phi = p1.multiply(q1);
if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
this.n = this.p.multiply(this.q);
this.d = ee.modInverse(phi);
this.dmp1 = this.d.mod(p1);
this.dmq1 = this.d.mod(q1);
this.coeff = this.q.modInverse(this.p);
break;
}
}
}
// Perform raw private operation on "x": return x^d (mod n)
function RSADoPrivate(x) {
if(this.p == null || this.q == null)
return x.modPow(this.d, this.n);
// TODO: re-calculate any missing CRT params
var xp = x.mod(this.p).modPow(this.dmp1, this.p);
var xq = x.mod(this.q).modPow(this.dmq1, this.q);
while(xp.compareTo(xq) < 0)
xp = xp.add(this.p);
return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
}
// Return the PKCS#1 RSA decryption of "ctext".
// "ctext" is an even-length hex string and the output is a plain string.
function RSADecrypt(ctext) {
var c = parseBigInt(ctext, 16);
var m = this.doPrivate(c);
if(m == null) return null;
return pkcs1unpad2(m, (this.n.bitLength()+7)>>3);
}
// Return the PKCS#1 RSA decryption of "ctext".
// "ctext" is a Base64-encoded string and the output is a plain string.
function RSAB64Decrypt(ctext) {
var h = b64tohex(ctext);
if(h) return this.decrypt(h); else return null;
}
// protected
RSAKey.prototype.doPrivate = RSADoPrivate;
// public
RSAKey.prototype.setPrivate = RSASetPrivate;
RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
RSAKey.prototype.generate = RSAGenerate;
RSAKey.prototype.decrypt = RSADecrypt;
RSAKey.prototype.b64_decrypt = RSAB64Decrypt;
|
import mag from '../core/mag';
import {clone, arrayAreEqual} from './common';
import {onLCEvent} from "../core/utils/events"
const stateMap = {};
const checkExist = (name, ele, arr, stateMap, func) => {
const checkExistID = setInterval(function () {
if(mag.doc.body.contains(ele)) {
clearInterval(checkExistID);
exec(arr, stateMap, name, func)
}
}, 10);
}
const exec = (arr, stateMap, name, func) => {
let state = stateMap[name];
if (!state) {
// initial call:
const callback = typeof func == 'function' && func();
state = {
name,
func,
callback,
value: arr && arr.slice()
};
stateMap[name] = state;
const destroyer = onLCEvent('onunload', name, () => {
if (state.callback && typeof state.callback == 'function') {
state.callback();
}
delete stateMap[name];
destroyer();
});
} else if (state && !arr) {
// call on every re-render
typeof state.callback == 'function' && state.callback();
state.callback =typeof func == 'function' && func();
} else if (state && !arrayAreEqual(arr, state.value)) {
state.value = arr.slice();
typeof state.callback == 'function' && state.callback();
state.callback =typeof func == 'function' && func();
}
}
const useLayoutEffect = function(func, arr) {
const currentElement = mag._current.element;
const r = clone(mag._current);
const name = r.key || r.id;
const oprops = r.props;
const render = r;
const ele = r.element;
let state = stateMap[name];
if (!r.fake) {
//next tick
const destroy = onLCEvent('didupdate', name, (...args) => {
if(mag.doc.body.contains(args[2])) {
exec(arr, stateMap, name, func)
}else {
checkExist(name, args[2], arr, stateMap, func)
}
destroy();
})
}
};
mag.useLayoutEffect = useLayoutEffect;
export {mag, useLayoutEffect};
|
import Node from '../Node.js';
export default class FunctionDeclaration extends Node {
activate () {
if ( this.activated ) return;
this.activated = true;
const scope = this.body.scope;
this.params.forEach( param => param.run( scope ) ); // in case of assignment patterns
this.body.run();
}
addReference () {
/* noop? */
}
bind ( scope ) {
this.id.bind( scope );
this.params.forEach( param => param.bind( this.body.scope ) );
this.body.bind( scope );
}
gatherPossibleValues ( values ) {
values.add( this );
}
getName () {
return this.name;
}
hasEffects () {
return false;
}
initialise ( scope ) {
this.name = this.id.name; // may be overridden by bundle.deconflict
scope.addDeclaration( this.name, this, false, false );
this.body.createScope( scope );
this.id.initialise( scope );
this.params.forEach( param => param.initialise( this.body.scope ) );
this.body.initialise();
}
render ( code, es ) {
if ( !this.module.bundle.treeshake || this.activated ) {
super.render( code, es );
} else {
code.remove( this.leadingCommentStart || this.start, this.next || this.end );
}
}
}
|
/**
* message.test.js
* @authors luoyjx (yjk99@qq.com)
* @date 2016-07-17 00:17:30
*/
const MessageModel = require('../../models').Message
describe('test/models/message.test.js', function() {
it('message model test', function(done) {
done()
})
})
|
// Packages
import test from 'ava'
// Ours
import macros from 'babel-plugin-macros'
import jsx from 'babel-plugin-syntax-jsx'
import _transform, { transformSource as _transformSource } from './_transform'
const transform = (file, opts = {}) =>
_transform(file, {
plugins: [macros, jsx],
...opts
})
const transformSource = (src, opts = {}) =>
_transformSource(src.trim(), {
filename: './index.js',
plugins: [macros, jsx],
...opts
})
test('transpiles correctly', async t => {
const { code } = await transform('../fixtures/macro.js')
t.snapshot(code)
})
test('throws when using the default export directly', async t => {
const { message } = await t.throwsAsync(() =>
transformSource(`
import css from './src/macro'
css\`div { color: red }\`
`)
)
t.regex(message, /can't use default import directly/i)
})
test('throws when using the default export directly and it is not called css', async t => {
const { message } = await t.throwsAsync(() =>
transformSource(`
import foo from './src/macro'
foo\`div { color: red }\`
`)
)
t.regex(message, /can't use default import directly/i)
})
test('throws when using the default export directly and it is not called resolve', async t => {
const { message } = await t.throwsAsync(() =>
transformSource(`
import resolve from './src/macro'
resolve\`div { color: red }\`
`)
)
t.regex(message, /can't use default import directly/i)
})
test('throws when using an invalid method from the default export', async t => {
const { message } = await t.throwsAsync(() =>
transformSource(`
import css from './src/macro'
css.foo\`div { color: red }\`
`)
)
t.regex(message, /using an invalid tag/i)
})
test('throws when using a named import different than resolve', async t => {
const { message } = await t.throwsAsync(() =>
transformSource(`
import { foo } from './src/macro'
foo\`div { color: red }\`
`)
)
t.regex(message, /imported an invalid named import/i)
})
test('throws when using a named import as a member expression', async t => {
const { message } = await t.throwsAsync(() =>
transformSource(`
import { resolve } from './src/macro'
resolve.foo\`div { color: red }\`
`)
)
t.regex(message, /can't use named import/i)
})
test('can alias the named import', async t => {
const { code } = await transformSource(`
import { resolve as foo } from './src/macro'
foo\`div { color: red }\`
`)
t.snapshot(code)
})
test('injects JSXStyle for nested scope', async t => {
const { code } = await transformSource(`
import { resolve } from './src/macro'
function test() {
resolve\`div { color: red }\`
}
`)
t.snapshot(code)
})
|
(function() {
var app = angular.module('homeController', ['homeService', 'homeFactory']);
app.controller('HomeController', ['$scope', 'HomeService', 'HomeFactory', function($scope, HomeService, HomeFactory) {
/***************************************************************************
* Variables (includes ones from scope too)
**************************************************************************/
this.isSearching = false; // Default
this.currentTab;
$scope.searchtext;
$scope.usersSearchResults;
$scope.groupsSearchResults;
$scope.eventsSearchResults;
/***************************************************************************
* Initialize the search for users, groups, events based on keywords
* - Search Users
* - Search Groups
* - Search Events
**************************************************************************/
$scope.search = function(searchbox) {
if (searchbox.length > 0) {
this.isSearching = true;
$scope.searchtext = searchbox;
$scope.searchbox = '';
this.currentTab = 'events';
// Get Events
$scope.eventsSearchResults = HomeService.getEventSearchResults();
// Get users
$scope.usersSearchResults = HomeService.getUserSearchResults();
// Get Groups
$scope.groupsSearchResults = HomeService.getGroupSearchResults();
}
}
/***************************************************************************
* Functions that controls the view for searching or not search
**************************************************************************/
$scope.searching = function() {
if (this.isSearching == true)
return true;
else
return false;
}
$scope.stopSearching = function() {
this.isSearching = false;
}
/***************************************************************************
* Functions that controls tabs for searching
**************************************************************************/
$scope.setCurrentTab = function(category) {
this.currentTab = category;
}
$scope.getCurrentTab = function(category) {
if (this.currentTab === category)
return true;
else
return false;
}
}]);
})();
/*
user: {
firstName : String,
middleName : String,
lastName : String,
description : String,
picture: String,
email : String,
birthday : Date,
age : Number,
location : {city: String, state: String, zipcode: String},
phoneNum : Number,
googlePlus : String,
facebook : String,
linkedIn : String,
twitter : String,
volunteeredTo : [{id: String}, {id: String}, ...],
creatorOf : [{id: String}, {id: String}, ...],
organizerOf : [{id: String}, {id: String}, ...],
subscribedTo : [{id: String}, {id: String}, ...],
interests : [{type: String}, {type: String}, ...]
}
*/
/*
group: {
id : String,
name : String,
picture : String,
creationDate : String,
location : [{city: String, state: String, zipcode: String}, ...],
description : String,
googlePlusURL : String,
facebookURL : String,
linkInURL : String,
twitterURL: String,
personalWebsiteURL: String,
events: [{id: String}, {id: String}, ...],
organizers: [{id: String}, {id: String}, ...],
subscribers: [{id: String}, {id: String}, ...],
interests: [{type: String}, {type: String}, ...]
}
*/
/*
event: {
id: String,
creatorId: String,
groupId: String,
name: String,
description: String,
picture: String,
creationDate: DateTime,
startTimeDate: DateTime,
endTimeDate: DateTime,
location : {street: String, city: String, state: String, zipcode: String},
maxVolunteers: Number,
volunteers: [{id: String}, {id: String}, ...],
interests: [{type: String}, {type: String}, ...]
}
*/
|
var baseCreate = require('lodash/internal/baseCreate'),
isObject = require('lodash/lang/isObject');
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtorWrapper(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors.
// See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
module.exports = createCtorWrapper;
|
/*
* Bug testcase for a stringtable memory leak in Duktape 0.7.0, reported
* by Greg Burns.
*
* In Duktape 0.7.0 the mark-and-sweep handling of strings, specifically
* the sweeping of strings, would mark a string reachable and never clear
* the reachable flag. As a result, strings were never garbage collected
* if they had once been marked reachable. This doesn't easily show any
* symptoms when reference counting is in use (circular references are
* needed). When only mark-and-sweep is used, the problem is easy to
* reproduce.
*
* The test1() variant below works when reference counting is enabled,
* even when the bug is present. test2() uses circular references to
* cause the bug to manifest itself even with reference counting.
*
* This testcase can also be run manually with valgrind massif to see that
* the memory behavior is correct.
*/
/*---
{
"custom": true,
"slow": true
}
---*/
/*===
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
===*/
var count = 0;
var kilo = Array.prototype.join.call({ length: 1024 + 1 }, 'x');
var meg = Array.prototype.join.call({ length: 1024 + 1 }, kilo); // 1 meg prefix
function createUniqueString() {
var res = meg + (count++);
return res;
}
function test1() {
// Goes through 16G of strings
for (var i = 0; i < 16; i++) {
print(i);
for (var j = 0; j < 1024; j++) {
var ignore = createUniqueString();
Duktape.gc();
}
}
}
function test2() {
for (var i = 0; i < 16; i++) {
print(i);
for (var j = 0; j < 1024; j++) {
var obj1 = {};
var obj2 = { str: createUniqueString(), ref: obj1 };
obj1.ref = obj2; // circular reference, object contains string to collect
Duktape.gc(); // force collection once: string gets marked reachable
obj1 = undefined;
obj2 = undefined; // unreachable but not collected when refcounts enabled
Duktape.gc(); // force collection: should be collected but isn't
}
}
}
try {
test1();
} catch (e) {
print(e);
}
try {
test2();
} catch (e) {
print(e);
}
|
/**
* Delete a document
*
*/
var config = require('../lib/config')
, db = require('../lib/db')
, ObjectID = require('mongodb').ObjectID
, serialization = require('../lib/serialization')
, helpers = require('../lib/helpers')
;
module.exports = function (req, res, next) {
var collection;
if (!req.params.collection || !req.params.id) {
return res.json(404, { message: 'Wrong URL format' });
}
helpers.getIdFromStringId(req.params.collection, req.params.id, function (err, id) {
if (err) { return res.send(400, err); }
collection = db.collection(req.params.collection);
collection.remove({ _id: id }, { single: true, w:1 }, function (err) {
if (err) { return res.json(403, err); }
return res.redirect(config.baseUrl + '/' + req.params.collection + '?type=alert-success&message=The document was deleted, no turning back now!');
});
});
};
|
'use strict';
module.exports = function rrmerge() {
var array = this.openInputPortArray('IN');
var outport = this.openOutputPort('OUT');
var ip = null;
while (true) {
for (var i = 0; i < array.length; i++) {
ip = array[i].receive();
if (ip !== null) {
outport.send(ip);
}
}
if (ip === null) {
break;
}
}
};
|
nice.jsTypes = { js: { title: 'js', proto: {}, jsType: true }};
const jsHierarchy = {
js: 'primitive,object',
primitive: 'string,boolean,number,undefined,null,symbol',
object: 'function,date,regExp,array,error,arrayBuffer,dataView,map,weakMap,set,weakSet,promise',
error: 'evalError,rangeError,referenceError,syntaxError,typeError,uriError'
};
for(let i in jsHierarchy)
jsHierarchy[i].split(',').forEach(title => {
const parent = nice.jsTypes[i];
const proto = create(parent.proto);
nice.jsTypes[title] = create(parent,
{ title, proto, jsType: true, jsName: nice._capitalize(title) });
});
|
define({
"left": "बाईं ओर संरेखित करें",
"right": "दाईं ओर संरेखित करें",
"arrangement": "व्यवस्था",
"autoUpdate": "ऑटो अपडेट",
"respectCurrentMapScale": "वर्तमान मैप स्केल के सबंधी"
});
|
angular.module('starter.controllers', [])
.controller('playlistsCtrl', function ($scope, Music) {
$scope.playlists = [];
Music.getPlaylists().then(function (data) {
$scope.playlists = data;
$scope.$$phase || $scope.$digest();
})
})
.controller('playlistsDetailCtrl', function ($scope, Music, $stateParams) {
var id = $stateParams.id;
$scope.songs = [];
Music.getSongsFromPlaylist(id).then(function (data) {
$scope.songs = data;
$scope.$$phase || $scope.$digest();
})
$scope.play= function (s) {
if(s.playing){
Music.stopSong().then(function(msg){
s.playing=false;
$scope.$$phase || $scope.$digest();
alert(msg);
}).catch(function(msg){
alert(msg);
})
return
}
$scope.songs.forEach(function (obj) {
obj.playing = false;
});
s.playing=true;
Music.playSong(s.id).then(function(msg){
s.playing=false;
$scope.$$phase || $scope.$digest();
alert(msg);
}).catch(function(){
})
}
})
.controller('songsCtrl', function ($scope, Music) {
$scope.songs = [];
Music.getSongs().then(function (data) {
$scope.songs = data;
$scope.$$phase || $scope.$digest();
});
$scope.play= function (s) {
if(s.playing){
Music.stopSong().then(function(msg){
s.playing=false;
$scope.$$phase || $scope.$digest();
alert(msg);
}).catch(function(msg){
alert(msg);
})
return
}
$scope.songs.forEach(function (obj) {
obj.playing = false;
});
s.playing=true;
Music.playSong(s.id).then(function(msg){
s.playing=false;
$scope.$$phase || $scope.$digest();
alert(msg);
}).catch(function(){
})
}
})
;
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* 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.
*/
'use strict';
var _ = require('lodash');
var fs = require('fs');
var parseurl = require('parseurl');
var path = require('path');
var serveStatic = require('serve-static');
var defaultOptions = {
apiDocs: '/api-docs',
swaggerUi: '/docs'
};
var staticOptions = {};
/**
* Middleware for serving the Swagger documents via an API and Swagger UI.
*
* @param {object} swaggerObject - The Swagger object
* @param {object} [options] - The configuration options
* @param {string=/api-docs} [options.apiDocs] - The relative path to serve your Swagger documents from
* @param {string=/docs} [options.swaggerUi] - The relative path to serve Swagger UI from
* @param {string} [options.swaggerUiDir] - The filesystem path to your custom swagger-ui deployment to serve
*
* @returns the middleware function
*/
exports = module.exports = function swaggerUIMiddleware (swaggerObject, options) {
var swaggerUiPath = options.swaggerUiDir ?
path.resolve(options.swaggerUiDir) :
path.join(__dirname, '..', 'swagger-ui');
var apiDocs;
var staticMiddleware;
// Validate arguments
if (_.isUndefined(swaggerObject)) {
throw new Error('swaggerObject is required');
} else if (!_.isPlainObject(swaggerObject)) {
throw new TypeError('swaggerObject must be an object');
}
if (options.swaggerUiDir) {
if (!fs.existsSync(swaggerUiPath)) {
throw new Error('options.swaggerUiDir path does not exist: ' + swaggerUiPath);
} else if (!fs.statSync(swaggerUiPath).isDirectory()) {
throw new Error('options.swaggerUiDir path is not a directory: ' + swaggerUiPath);
}
}
staticMiddleware = serveStatic(swaggerUiPath, staticOptions);
apiDocs = JSON.stringify(swaggerObject, null, 2);
// Set the defaults
options = _.defaults(options || {}, defaultOptions);
// Sanitize values
if (options.apiDocs.charAt(options.apiDocs.length -1) === '/') {
options.apiDocs = options.apiDocs.substring(0, options.apiDocs.length - 1);
}
if (options.swaggerUi.charAt(options.swaggerUi.length -1) === '/') {
options.swaggerUi = options.swaggerUi.substring(0, options.swaggerUi.length - 1);
}
return function swaggerUI (req, res, next) {
var path = parseurl(req).pathname;
if (path === options.apiDocs || path === options.apiDocs + '/') {
res.setHeader('Swagger-API-Docs-URL', options.apiDocs);
return res.end(apiDocs);
} else if (path === options.swaggerUi || path.indexOf(options.swaggerUi + '/') === 0) {
res.setHeader('Swagger-API-Docs-URL', options.prefix+options.apiDocs);
if (path === options.swaggerUi || path === options.swaggerUi + '/') {
req.url = '/';
} else {
req.url = req.url.substring(options.swaggerUi.length);
}
return staticMiddleware(req, res, next);
}
return next();
};
};
|
var Course = require('./../models/subject-course');
var db = require('./../db-locations');
module.exports.course = function(id, cb){
var course;
db.open('school');
Course
.findOne({_id:id})
.populate('subject')
.exec(function(err, data){
db.close();
if(err){cb(err,null);return 0;}
course = data.getData();
cb(null, course);
return course;
});
};
module.exports.getCourse = function(id, cb){
var course;
db.open('school');
Course
.findOne({_id:id})
.populate('subject')
.exec(function(err, data){
db.close();
if(err){cb(err,null);return;}
course = data.getData();
cb(null, course);
return;
});
};
module.exports.fillCourseSchedule = function(schedules, cb){
db.open('school');
for(var i = 0; i < schedules.length; i++){
Course
.findOne({_id:schedules[i].course})
.populate('subject')
.exec(function(err, data){
console.log(i, err, data);
if(err){cb(err,null);return;}
//schedules[i].course = data;
});
}
db.close();
cb(null, schedules);
return;
};
|
import acorn from 'acorn';
import fs from 'fs';
/**
* This function reads a js file and transforms it into AST
*
* @author Mohamad Mohebifar
* @param file
* @param options
* @returns {Object}
*/
export function readFile(file, options) {
var ast;
if (options.sync) {
var js = fs.readFileSync(file);
ast = acorn.parse(js, options);
return ast;
} else {
fs.readFile(function (js) {
ast = acorn.parse(js, options);
if (options.callback) {
options.callback(ast);
}
});
}
}
/**
* This function reads a js string and transforms it into AST
*
* @author Mohamad Mohebifar
* @param js
* @returns {Object}
*/
export function read(js, options) {
return acorn.parse(js, options);
}
export default {
read: read,
readFile: readFile
};
|
define(['./jsonRpc-native'], (jsonRpc) => {
'use strict';
/*
* arg is:
* url - service wizard url
* timeout - request timeout
* version - service release version or tag
* auth - auth structure
* token - auth token
* username - username
* rpcContext
*/
function GenericClient(arg) {
// Establish an auth object which has properties token and user_id.
const module = arg.module;
const token = arg.token || (arg.auth ? arg.auth.token : null);
if (!arg.url) {
throw new Error('The service discovery url was not provided');
}
if (!arg.version) {
throw new Error('The service version was not provided');
}
function options() {
return {
timeout: arg.timeout,
authorization: token,
rpcContext: arg.rpcContext,
};
}
this.lookupModule = function () {
const func = 'get_service_status',
params = [
{
module_name: module,
version: arg.version || 'dev',
},
];
// NB: pass null for numRets (number of return values) so we get the
// full return structure.
return jsonRpc.request(arg.url, 'ServiceWizard', func, params, null, options());
};
this.callFunc = function (funcName, params) {
// var params = Array.prototype.slice.call(arguments);
return this.lookupModule().spread((serviceStatus) => {
return jsonRpc.request(
serviceStatus.url,
module,
funcName,
params,
null,
options()
);
});
};
}
return GenericClient;
});
|
const mongoose = require('mongoose');
const encryption = require('./../utilities/encryption');
const ObjectId = mongoose.Schema.Types.ObjectId;
let userSchema = mongoose.Schema(
{
email: {type: String, required: true, unique: true},
passwordHash: {type: String, required: true},
fullName: {type: String, required: true},
articles: {type: [ObjectId], default: []},
salt: {type: String, required: true}
}
);
userSchema.method ({
authenticate: function (password) {
let inputPasswordHash = encryption.hashPassword(password, this.salt);
let isSamePasswordHash = inputPasswordHash === this.passwordHash;
return isSamePasswordHash;
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;
|
output = [$.collection, 'find']
|
/**
* Created by yan on 16-2-23.
*/
import {applyMiddleware,createStore,compose} from 'redux';
import middleware from '../src/middleware.es6';
import {equal} from 'assert';
import {env} from 'jsdom';
import $ from 'jquery';
describe('middleware', function () {
let Deferred;
/**
* @link https://github.com/jquery/jquery/blob/2.2.1/test/promises_aplus_adapter.js
*/
before(done=> {
env("", function (error, window) {
Deferred = $(window).Deferred;
done();
});
});
it('works with resolve', function (done) {
var store = createStore((state = {}, action)=> {
switch (action.type) {
case 'AAA':
equal(action.payload, 'ok');
done();
return state;
break;
default:
return state;
}
}, applyMiddleware(middleware));
var payload = new Deferred();
store.dispatch({
type: 'AAA',
payload
});
setTimeout(()=> {
payload.resolve('ok');
});
})
it('works with reject', function (done) {
var store = createStore((state = {}, action)=> {
switch (action.type) {
case 'AAA':
equal(action.payload, 'error');
equal(action.error, true);
done();
return state;
break;
default:
return state;
}
}, applyMiddleware(middleware));
var payload = new Deferred();
store.dispatch({
type: 'AAA',
payload
});
setTimeout(()=> {
payload.reject('error');
});
})
});
|
// Regular expression that matches all symbols in the Sinhala block as per Unicode v3.2.0:
/[\u0D80-\u0DFF]/;
|
/*!
* PubTest.js
* MIT License (c) 2014
* Author: Jorge Yau <codenameyau@gmail.com>
*
* Description:
* Client-side tests with browser console.
*/
/**********************************************************
* PUBTEST CONSTRUCTOR
***********************************************************/
function PubTest(name) {
this.version = '0.1.0';
this.testing = name || 'Test';
this.cases = {
total: 0,
pass: 0,
fail: 0
};
console.time(name);
}
/**********************************************************
* PUBLIC METHODS
***********************************************************/
PubTest.prototype.results = function() {
var passColor = (this.cases.pass) ? 'color: #007A00' : 'color: #FE0000';
var failColor = (this.cases.fail) ? 'color: #FE0000' : 'color: #007A00';
console.log('%c============', failColor);
console.log('%cTest Results', failColor);
console.log('%c============', failColor);
console.log('%cTotal: %d', failColor, this.cases.total);
console.log('%cPassed: %d', passColor, this.cases.pass);
console.log('%cFailed: %d', failColor, this.cases.fail);
console.timeEnd(this.testing);
console.log('');
};
PubTest.prototype.testCase = function(callback) {
callback();
};
/**********************************************************
* VALUE ASSERTIONS
***********************************************************/
PubTest.prototype.assert = function(expr, message) {
this._addCase(expr, message);
};
PubTest.prototype.assertEqual = function(exprA, exprB, message) {
var assertion = (exprA === exprB);
this._addCase(assertion, message);
};
PubTest.prototype.assertNotEqual = function(exprA, exprB, message) {
var assertion = (exprA !== exprB);
this._addCase(assertion, message);
};
PubTest.prototype.assertTrue = function(expr, message) {
var assertion = (expr === true);
this._addCase(assertion, message);
};
PubTest.prototype.assertFalse = function(expr, message) {
var assertion = (expr === false);
this._addCase(assertion, message);
};
PubTest.prototype.assertLess = function(exprA, exprB, message) {
var assertion = (exprA < exprB);
this._addCase(assertion, message);
};
PubTest.prototype.assertLessEqual = function(exprA, exprB, message) {
var assertion = (exprA <= exprB);
this._addCase(assertion, message);
};
PubTest.prototype.assertGreater = function(exprA, exprB, message) {
var assertion = (exprA > exprB);
this._addCase(assertion, message);
};
PubTest.prototype.assertGreaterEqual = function(exprA, exprB, message) {
var assertion = (exprA >= exprB);
this._addCase(assertion, message);
};
PubTest.prototype.assertRange = function(value, min, max, message) {
var assertion = (value >= min && value <= max);
this._addCase(assertion, message);
};
PubTest.prototype.assertNotRange = function(value, min, max, message) {
var assertion = (value < min && value > max);
this._addCase(assertion, message);
};
/**********************************************************
* TYPE ASSERTIONS
***********************************************************/
PubTest.prototype.assertType = function(value, type, message) {
var assertion = (typeof value === type);
this._addCase(assertion, message);
};
PubTest.prototype.assertString = function(value, message) {
var assertion = this.assertType(value, 'string', message);
this._addCase(assertion, message);
};
PubTest.prototype.assertNumber = function(value, message) {
var assertion = this.assertType(value, 'number', message);
this._addCase(assertion, message);
};
PubTest.prototype.assertBoolean = function(value, message) {
var assertion = this.assertType(value, 'boolean', message);
this._addCase(assertion, message);
};
PubTest.prototype.assertInteger = function(value, message) {
var assertion = isNaN(value) ? false : (parseInt(value, 10) === value);
this._addCase(assertion, message);
};
PubTest.prototype.assertArray = function(value, message) {
var assertion = (value instanceof Array);
this._addCase(assertion, message);
};
/**********************************************************
* DATA ASSERTIONS
***********************************************************/
PubTest.prototype.assertArrayContains = function(array, value, message) {
var assertion = (array.indexOf(value) < 0) ? false : true;
this._addCase(assertion, message);
};
PubTest.prototype.assertNotArrayContains = function(array, value, message) {
var assertion = (array.indexOf(value) < 0) ? true : false;
this._addCase(assertion, message);
};
PubTest.prototype.assertProperty = function(object, property, message) {
var assertion = object.hasOwnProperty(property);
this._addCase(assertion, message);
};
PubTest.prototype.assertArrayEqual = function(arrayA, arrayB, message) {
if (!arrayA instanceof Array || !arrayB instanceof Array) {
return this._addCase(false, message);
}
if (arrayA.length !== arrayB.length) {
return this._addCase(false, message);
}
// Doesn't handle nested objects inside array.
for (var i=0; i<arrayA.length; i++) {
if (arrayA[i] !== arrayB[i]) {
return this._addCase(false, message);
}
}
return this._addCase(true, message);
};
/**********************************************************
* INTERNAL METHODS
***********************************************************/
PubTest.prototype._addCase = function(assertion, message) {
this.cases.total++;
message = message || 'test case ' + this.cases.total;
console.assert(assertion, message);
if (assertion) {
this._passed();
} else {
this._failed();
}
};
PubTest.prototype._passed = function() {
this.cases.pass++;
};
PubTest.prototype._failed = function() {
this.cases.fail++;
};
/**********************************************************
* ES6 MODULE EXPORT
***********************************************************/
export default PubTest;
|
import express from 'express';
import raven from 'raven';
import categories from './categories.routes';
import episodes from './episodes.routes';
import posts from './posts.routes';
import shows from './shows.routes';
import { pageNotFoundMiddleware, sentryClient, errorMiddleware } from '../components/errors';
const router = express.Router();
router.use('/categories', categories);
router.use('/episodes', episodes);
router.use('/posts', posts);
router.use('/shows', shows);
router.use(pageNotFoundMiddleware);
router.use(raven.middleware.express.errorHandler(sentryClient));
router.use(errorMiddleware);
export default router;
|
'use strict';
var assert = require('assert');
var components = require('../../components');
var logger = browser.getLogger('testLayout');
describe('layout', function () {
it('should have a link to spec', function (done) {
components.ui.page.loadBlueprints();
components.ui.layout.getSpecLink().then(function (value) {
logger.info('got spec link', value);
// the link should be 'http://_MANAGEMENT_IP_/api/spec.html#!/spec.json'
assert.equal(value, 'http://' + components.config.cloudifyUiIp + '/api/spec.html#!/spec.json');
done();
}).catch(function(e) {
done(e);
});
});
});
|
// Alternative to sorting solution
// Given
// - A dictionary file
// - An input word
// Find all words in the dictionary that are anagrams of the input word.
// Ex:
// Dictionary:
// - CAT
// - FACT
// - TAC
// - ACT
// - AT
// Word:
// - ACT
// Output:
// - ACT
// - CAT
// Given
// - A dictionary file
// - An input word
const anagram = (alist, target) => {
// construct a dictionary to measure the content and frequency of target characters
const targetSize = target.length
const targetDict = stringToDictionary(target, targetSize);
const result = [];
for (let i = 0; i < alist.length; i++) {
const compareWord = alist[i];
const compareSize = compareWord.length
// same size candidates should be further evaluated
// construct a dictionary to run comparison
if (targetSize === compareSize) {
const compareDict = stringToDictionary(compareWord, compareSize);
// content and frequency equivalency indicates an anagram
if (compareHelper(targetDict, compareDict, targetSize))
result.push(compareWord);
}
}
return result;
}
const compareHelper = (targetDict, compareDict, requiredMatches) => {
// by stripping all values that are equal across the two objects
// we can determine they are deeply equal if 0 keys remain
return Object.keys(compareDict).filter((char) => {
return compareDict[char] !== targetDict[char]
}).length === 0
}
const stringToDictionary = (str, size) => {
const dict = {};
for (let i = 0; i < size; i++) {
if (!dict[str[i]])
dict[str[i]] = 1;
else dict[str[i]]++;
}
return dict
}
console.log(anagram(['cat', 'act', 'fact', 'tac', 'at'], 'act'));
|
(function () {
'use strict';
angular
.module('ion-language', [
'ngCookies',
'pascalprecht.translate', // angular-translate
'tmh.dynamicLocale', // angular-dynamic-locale,
'angularMoment' // https://github.com/urish/angular-moment
])
.config(configLanguage)
.run(runMoment);
function runMoment(amMoment, AppConfig) {
var langvar = navigator.language || navigator.userlanguage;
var userlangvar = langvar.split('-')[0];
var language = AppConfig.preferredLocale;
var searchLang = _.some(AppConfig.locales, {
code: userlangvar
});
if (searchLang) {
language = AppConfig.locales.filter(function (item) {
return language == item.code
})[0].code;
}
amMoment.changeLocale(language);
}
function configLanguage($translatePartialLoaderProvider, $translateProvider, AppConfig, tmhDynamicLocaleProvider) {
// angular-translate configuration
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '{part}/i18n/{lang}.json'
});
$translateProvider.useSanitizeValueStrategy(null);
// Translate Config
$translateProvider.useMissingTranslationHandlerLog();
$translateProvider.useLocalStorage(); // saves selected language to localStorage
tmhDynamicLocaleProvider.localeLocationPattern('../bower_components/angular-i18n/angular-locale_{{locale}}.js');
var langvar = navigator.language || navigator.userlanguage;
var userlangvar = langvar.split('-')[0];
var language = AppConfig.preferredLocale;
var searchLang = _.some(AppConfig.locales, {
code: userlangvar
});
if (searchLang) {
language = AppConfig.locales.filter(function (item) {
return language == item.code
})[0].code;
}
$translateProvider.preferredLanguage(language);
}
})();
|
import { Match, check } from 'meteor/check';
import { API } from '../../../../api/server';
import { hasPermission } from '../../../../authorization';
import { LivechatDepartment, LivechatDepartmentAgents } from '../../../../models';
import { Livechat } from '../../../server/lib/Livechat';
import { findDepartments, findDepartmentById, findDepartmentsToAutocomplete, findDepartmentsBetweenIds } from '../../../server/api/lib/departments';
API.v1.addRoute('livechat/department', { authRequired: true }, {
get() {
const { offset, count } = this.getPaginationItems();
const { sort } = this.parseJsonQuery();
const { text } = this.queryParams;
const departments = Promise.await(findDepartments({
userId: this.userId,
text,
pagination: {
offset,
count,
sort,
},
}));
return API.v1.success(departments);
},
post() {
if (!hasPermission(this.userId, 'manage-livechat-departments')) {
return API.v1.unauthorized();
}
try {
check(this.bodyParams, {
department: Object,
agents: Match.Maybe(Array),
});
const department = Livechat.saveDepartment(null, this.bodyParams.department, this.bodyParams.agents);
if (department) {
return API.v1.success({
department,
agents: LivechatDepartmentAgents.find({ departmentId: department._id }).fetch(),
});
}
API.v1.failure();
} catch (e) {
return API.v1.failure(e);
}
},
});
API.v1.addRoute('livechat/department/:_id', { authRequired: true }, {
get() {
check(this.urlParams, {
_id: String,
});
const { department, agents } = Promise.await(findDepartmentById({
userId: this.userId,
departmentId: this.urlParams._id,
includeAgents: this.queryParams.includeAgents && this.queryParams.includeAgents === 'true',
}));
const result = { department };
if (agents) {
result.agents = agents;
}
return API.v1.success(result);
},
put() {
const permissionToSave = hasPermission(this.userId, 'manage-livechat-departments');
const permissionToAddAgents = hasPermission(this.userId, 'add-livechat-department-agents');
if (!permissionToSave && !permissionToAddAgents) {
return API.v1.unauthorized();
}
try {
check(this.urlParams, {
_id: String,
});
check(this.bodyParams, {
department: Object,
agents: Match.Maybe(Array),
});
const { _id } = this.urlParams;
const { department, agents } = this.bodyParams;
let success;
if (permissionToSave) {
success = Livechat.saveDepartment(_id, department, agents);
}
if (success && agents && permissionToAddAgents) {
success = Livechat.saveDepartmentAgents(_id, agents);
}
if (success) {
return API.v1.success({
department: LivechatDepartment.findOneById(_id),
agents: LivechatDepartmentAgents.find({ departmentId: _id }).fetch(),
});
}
return API.v1.failure();
} catch (e) {
return API.v1.failure(e);
}
},
delete() {
if (!hasPermission(this.userId, 'manage-livechat-departments')) {
return API.v1.unauthorized();
}
try {
check(this.urlParams, {
_id: String,
});
if (Livechat.removeDepartment(this.urlParams._id)) {
return API.v1.success();
}
return API.v1.failure();
} catch (e) {
return API.v1.failure(e);
}
},
});
API.v1.addRoute('livechat/department.autocomplete', { authRequired: true }, {
get() {
const { selector } = this.queryParams;
if (!selector) {
return API.v1.failure('The \'selector\' param is required');
}
return API.v1.success(Promise.await(findDepartmentsToAutocomplete({
uid: this.userId,
selector: JSON.parse(selector),
})));
},
});
API.v1.addRoute('livechat/department.listByIds', { authRequired: true }, {
get() {
const { ids } = this.queryParams;
const { fields } = this.parseJsonQuery();
if (!ids) {
return API.v1.failure('The \'ids\' param is required');
}
if (!Array.isArray(ids)) {
return API.v1.failure('The \'ids\' param must be an array');
}
return API.v1.success(Promise.await(findDepartmentsBetweenIds({
uid: this.userId,
ids,
fields,
})));
},
});
|
import React, { Component } from 'react';
import _ from 'lodash';
import { Button, ButtonToolbar, ButtonGroup, Panel } from 'react-bootstrap';
import ModalWrapper from './Modal-Wrapper';
import Ingredients from './Ingredients';
function Recipe(props) {
const { recipe } = props;
// console.log('recipe in recipe Component', recipe);
return (
<div>
<Panel header={recipe.recipeName}>
<Ingredients ingredients={recipe.ingredients} />
</Panel>
</div>
);
}
export default Recipe;
|
(function() {
var App, Views, exports,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
exports = this;
App = exports.Application || (exports.Application = {});
Views = App.Views || (App.Views = {});
Views.NotFound = (function(_super) {
__extends(NotFound, _super);
function NotFound() {
return NotFound.__super__.constructor.apply(this, arguments);
}
NotFound.prototype.el = '#not-found-page';
return NotFound;
})(Backbone.View);
_(Views.NotFound.prototype).extend(Views.Activable);
}).call(this);
|
var modRequire = require('./moduleRequire')
var cookie = modRequire('cookie', 'cookie')
module.exports = cookieMiddleware
function setCookie (res, name, value, opts) {
var serial = cookie.serialize(name, value, opts)
var header = res.getHeader('Set-Cookie')
if (typeof header === 'string') {
res.setHeader('Set-Cookie', [header, serial])
} else if (Array.isArray(header)) {
res.setHeader('Set-Cookie', header.concat([serial]))
} else {
res.setHeader('Set-Cookie', serial)
}
}
function cookieMiddleware (req, res) {
var header = req.headers.cookie
req.cookies = (typeof header === 'string') ? cookie.parse(header) : {}
res.cookie = setCookie.bind(null, res)
}
|
import {OrthographicView, COORDINATE_SYSTEM} from '@deck.gl/core';
import {ScreenGridLayer} from '@deck.gl/aggregation-layers';
import {points} from 'deck.gl-test/data';
import {WIDTH, HEIGHT} from '../constants';
export const screenSpaceData = [
[0, -100],
[0, -110],
[0, -115],
[10, -100],
[0, 100],
[0, 105],
[-100, -100],
[-100, -100],
[100, 10],
[100, 12],
[100, 100],
[110, 90]
];
export default [
{
name: 'screengrid-infoviz',
views: [new OrthographicView()],
viewState: {
left: -WIDTH / 2,
top: -HEIGHT / 2,
right: WIDTH / 2,
bottom: HEIGHT / 2
},
layers: [
new ScreenGridLayer({
id: 'screengrid-infoviz',
data: screenSpaceData,
coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,
opacity: 0.8,
getPosition: d => d,
cellSizePixels: 40,
pickable: false
})
],
goldenImage: './test/render/golden-images/screengrid-infoviz.png'
},
{
name: 'screengrid-lnglat-cpu-aggregation',
viewState: {
latitude: 37.751537058389985,
longitude: -122.42694203247012,
zoom: 11.5,
pitch: 0,
bearing: 0
},
layers: [
new ScreenGridLayer({
id: 'screengrid-lnglat-cpu-aggregation',
data: points,
opacity: 0.8,
getPosition: d => d.COORDINATES,
cellSizePixels: 40,
pickable: false,
gpuAggregation: false
})
],
goldenImage: './test/render/golden-images/screengrid-lnglat-colorRange.png'
},
{
name: 'screengrid-lnglat-colorRange',
viewState: {
latitude: 37.751537058389985,
longitude: -122.42694203247012,
zoom: 11.5,
pitch: 0,
bearing: 0
},
layers: [
new ScreenGridLayer({
id: 'screengrid-lnglat-colorRange',
data: points,
opacity: 0.8,
getPosition: d => d.COORDINATES,
cellSizePixels: 40,
pickable: false
})
],
goldenImage: './test/render/golden-images/screengrid-lnglat-colorRange.png'
}
];
|
import React from 'react';
import Article from '../article.react';
import ArticleStore from '../../stores/ArticleStore';
export default class MostRecent extends React.Component {
static get displayName() {
return 'MostRecent';
}
constructor(props) {
super(props);
this.state = {
articles: []
};
}
componentDidMount() {
ArticleStore.getList(this, 0, 1, true);
}
render() {
var mostRecent = this.state.articles.pop();
if (!(mostRecent instanceof Object)) {
return (
<div className="panel panel-default">
<div className="panel-body">
{'There seems to be nothing here.'}
</div>
</div>
);
}
return (
<Article
content={mostRecent.content}
createdAt={mostRecent.createdAt}
id={mostRecent.id}
key={mostRecent.id}
slug={mostRecent.slug}
tags={mostRecent.tags}
title={mostRecent.title}
/>
);
}
}
|
/*
node-haver-server
Haver chat server for Node.js
Copyright (c) 2011 Eric Goodwin
For license information, see LICENSE
*/
//Constants
var VERSION = 0.1;
//Libs
var net = require('net');
var Log = require('log');
var lines = require('lines');
var User = require('./user');
var Channel = require('./channel');
var Handler = require('./handler');
//Global objects
var channels = new Array();
//Logger
log = new Log(Log.DEBUG);
/* Startup */
log.info("node-haver-server v" + VERSION + " by Eric Goodwin");
var handler = Handler.createHandler(channels);
var haver_server = net.createServer(function(stream) {
log.info("New client from " + stream.remoteAddress);
var newuser = User.createUser(stream);
stream.user = newuser;
stream.setEncoding('utf8');
lines(stream);
/* Set up listeners */
stream.on("line", function(data) {
handler.handleMessage(stream.user, data);
});
stream.on("end", function() {
log.info("Client from " + stream.remoteAddress + " disconnected.");
//TODO: if unexpected quit, trigger QUIT message?
stream.user.die();
});
});
haver_server.listen(7575);
log.info("Listening on port 7575...");
|
/**
* Javascript Bindings that apply to changing of passwords
* in the admin tools
*/
(function( yourcode ) {
yourcode( window.jQuery, window, document );
} (function( $, window, document ) {
var baseURL = $("head base").attr( "href" );
$(function( ) {
$(".datatableBlock").orcaDataTableBlock({
sortCol: 1,
sortDir: "ASC",
pageLength: 100,
colTool: "manageUsersHeader",
rowTool: "manageUsersRows",
optionsCallback: function( datatable ) {
initializeClassChangeOptions( datatable );
initializeStatusChangeOptions( datatable );
initializeOptionPopups( );
}
});
});
/**
* Setup the functionality of the class change icons
*/
function initializeClassChangeOptions( datatable ) {
$(".datatableBlock").on( "click", ".classChange", function( ) {
var currentClick = $(this);
var submitSet = { };
submitSet['userID'] = $(this).attr( "data-userid" );
submitSet['direction'] = $(this).attr( "data-direction" );
submitSet['adminTool'] = "userClassChange";
//Convert to JSON
submitSet = JSON.stringify( submitSet );
$.ajax({
url: baseURL + '/scripts/adminTools.php',
type: 'POST',
data: { 'expData': submitSet},
dataType: 'json'
}).done( function( results ) {
if( results['STATUS'] == "SUCCESS" ) {
alertify.success( results['MESSAGE'] );
var cellIndex = datatable.cell( currentClick.closest( 'tr' ).find('.userClass') ).index( );
datatable.cell( cellIndex ).data( results['NEWVAL'] );
datatable.draw( false );
} else {
alertify.error( results['MESSAGE'] );
}
});
});
}
/**
* Setup the functionality of the status change icons
*/
function initializeStatusChangeOptions( datatable ) {
$(".datatableBlock").on( "click", ".statusChange", function( ) {
var currentClick = $(this);
var submitSet = { };
submitSet['userID'] = $(this).attr( "data-userid" );
submitSet['status'] = $(this).attr( "data-status" );
submitSet['adminTool'] = "userStatusChange";
//Convert to JSON
submitSet = JSON.stringify( submitSet );
$.ajax({
url: baseURL + 'scripts/adminTools.php',
type: 'POST',
data: { 'expData': submitSet},
dataType: 'json'
}).done( function( results ) {
if( results['STATUS'] == "SUCCESS" ) {
alertify.success( results['MESSAGE'] );
var cellIndex = datatable.cell( currentClick.closest( 'tr' ).find('.userStatus') ).index( );
datatable.cell( cellIndex ).data( results['NEWVAL'] );
datatable.draw( false );
} else {
alertify.error( results['MESSAGE'] );
}
});
});
}
/**
* Setup tooltips for the options in the options column
*/
function initializeOptionPopups( ) {
$("#datatableBlock").on( 'mouseover', '.popoverData', function( event ) {
var optionPopup = $(this).qtip({
overwrite: false,
content: {
text: $(this).data( "content" )
},
style: {
classes: 'qtip-bootstrap',
width: '250px'
},
position: {
my: 'bottom right',
at: 'top left'
},
show: {
event: event.type,
ready: true,
solo: true
},
hide: {
delay: 1000,
fixed: true,
event: 'mouseleave'
}
}, event);
});
}
}));
|
var searchData=
[
['us_5fticker_5fclear_5finterrupt',['us_ticker_clear_interrupt',['../group___us_ticker.html#ga373846a3122f86d7decbea5fab0590a9',1,'us_ticker_api.h']]],
['us_5fticker_5fdisable_5finterrupt',['us_ticker_disable_interrupt',['../group___us_ticker.html#ga75e46157b1bbfe4f5594e33b49ff2605',1,'us_ticker_api.h']]],
['us_5fticker_5finit',['us_ticker_init',['../group___us_ticker.html#ga829955267433ca8d04ac71f4e89c0404',1,'us_ticker_api.h']]],
['us_5fticker_5firq_5fhandler',['us_ticker_irq_handler',['../group___us_ticker.html#ga52d2b2c47d792442573e34403f9a10b1',1,'us_ticker_api.h']]],
['us_5fticker_5fread',['us_ticker_read',['../group___us_ticker.html#ga023920c1e5030a84aa39d0be1de0aa0b',1,'us_ticker_api.h']]],
['us_5fticker_5fset_5finterrupt',['us_ticker_set_interrupt',['../group___us_ticker.html#gae7b69978fcf8ce8054597c87072896ce',1,'us_ticker_api.h']]]
];
|
function ListsAssistant() {
/* this is the creator function for your scene assistant object. It will be passed all the
additional parameters (after the scene name) that were passed to pushScene. The reference
to the scene controller (this.controller) has not be established yet, so any initialization
that needs the scene controller should be done in the setup function below. */
}
ListsAssistant.prototype.setup = function() {
/* this function is for setup tasks that have to happen when the scene is first created */
/* use Mojo.View.render to render view templates and add them to the scene, if needed */
/* setup widgets here */
/* add event handlers to listen to events from widgets */
TM.helpers.setupDefaultMenu.call(this);
var shortHeader = Mojo.View.render({object: {icon: 'lists', mainText: 'Your Lists'}, template: 'partials/short-header'});
this.controller.get('divShortHeader').innerHTML = shortHeader;
TM.helpers.setupBaseLayout.call(this, 'lists');
this.listsModel = { items: [] };
this.controller.setupWidget("listWidget",
{
listTemplate: "lists/list-template",
itemTemplate: "lists/list-item",
swipeToDelete: false,
reorderable: false,
hasNoWidget: true,
fixedHeightItems: true,
renderLimit: 30,
lookahead: 20
},
this.listsModel);
this.pushListTweetsHandler = this.pushListTweets.bindAsEventListener(this);
this.controller.listen('listWidget', Mojo.Event.listTap, this.pushListTweetsHandler);
this.successfulFetchHandler = this.successfulFetch.bind(this);
Twitter.myLists({onSuccess: this.successfulFetchHandler});
this.loader = this.controller.get('divBigLoader');
};
ListsAssistant.prototype.successfulFetch = function (transport){
Mojo.Log.info('Sucessfully fetched');
this.loader.addClassName('pop');
// TM.helpers.debug(Object.clone(transport.responseJSON.lists.last()), 'My lists::::');
this.listsModel.items = this.filterLists(transport.responseJSON.lists);
Mojo.Log.info('Lists filtered');
// TM.helpers.debug(this.listsModel.items[0], 'First item');
this.controller.modelChanged(this.listsModel);
// Get lists I follow
this.listIFollowLoader = this.controller.get('divLoadingListIFollow');
this.listIFollowLoader.style.display = 'block';
this.ListIFollowFetchHandler = this.successfulListIFollowFetch.bind(this);
Twitter.listsIFollow({onSuccess: this.ListIFollowFetchHandler});
}
ListsAssistant.prototype.successfulListIFollowFetch = function (transport){
Mojo.Log.info('Attempting to add the lists that I follow');
this.listIFollowLoader.style.display = 'none';
var filteredLists = this.filterLists(transport.responseJSON.lists);
this.listsModel.items.push.apply(this.listsModel.items, filteredLists);
this.listWidget.mojo.noticeUpdatedItems(0, this.listsModel.items);
TM.helpers.showEmptyList.call(this, this.listsModel.items, 'Lists');
}
ListsAssistant.prototype.pushListTweets = function (event){
this.controller.stageController.pushScene('list-tweets', event.item.id, event.item.user.screen_name, event.item.full_name);
}
// Any processing I want to do on the list
ListsAssistant.prototype.filterLists = function (lists){
for (var i = 0; i < lists.length; i++) {
lists[i].list_name = lists[i].full_name;
}
return lists
}
ListsAssistant.prototype.handleCommand = function (event){
TM.helpers.handleCommand.bind(this, event)();
}
ListsAssistant.prototype.activate = function(event) {
/* put in event handlers here that should only be in effect when this scene is active. For
example, key handlers that are observing the document */
TM.helpers.handleActivate.call(this, event);
this.loader.addClassName('show');
};
ListsAssistant.prototype.deactivate = function(event) {
/* remove any event handlers you added in activate and do any other cleanup that should happen before
this scene is popped or another scene is pushed on top */
};
ListsAssistant.prototype.cleanup = function(event) {
/* this function should do any cleanup needed before the scene is destroyed as
a result of being popped off the scene stack */
};
|
/* eslint-disable no-unused-vars,global-require */
describe('Test the index.js', () => {
test('should import VeasyForm', () => {
const VeasyForm = require('../src/index').default;
});
});
|
var markDown = Ember.Handlebars.makeBoundHelper(function(word) {
return new Handlebars.SafeString(markdown.toHTML(word));
});
export default markDown;
|
/**
* @class dr.slider {UI Components}
* @extends dr.view
* An input component whose state is changed when the mouse is dragged.
*
* @example
*
* <slider name="hslide" y="5" width="250" height="10" value="50" bgcolor="#808080"></slider>
* Slider with a label:
*
* @example
*
* <spacedlayout spacing="8"></spacedlayout>
* <slider name="hslide" y="5" width="250" height="10" value="50" bgcolor="#808080"></slider>
* <text text="${Math.round(this.parent.hslide.value)}" y="${this.parent.hslide.y + (this.parent.hslide.height-this.height)/2}"></text>
*/
/**
* @attribute {Number} [minvalue=0]
* The minimum value of the slider
*/
/**
* @attribute {Number} [maxvalue=100]
* The maximum value of the slider
*/
/**
* @attribute {"x"/"y"} [axis=x]
* The axis to track on
*/
/**
* @attribute {Boolean} [invert=false]
* Set to true to invert the direction of the slider.
*/
/**
* @attribute {Number} [value=0]
* The current value of the slider.
*/
/**
* @attribute {String} [selectcolor="#a0a0a0"]
* The selected color of the slider.
*/
|
/**
* Created by Abyss on 15-3-10.
*
* The DD3DV is the abbreviation of Data Drive 3 Dimension View.
* It is defined as a big data visualization tool.
* It supports the most general data represent as discrete, graph and serial.
* It is based on the Webgl.
* It is a experiment project.
* It is related to WWEngine (words to world engine).
*/
var DD3DV = { REVISION: "1" };
DD3DV.ResourceBasePath = "htdocs/assets/";
|
(function () {
'use strict';
angular
.module('images')
.controller('ImagesController', ImagesController);
ImagesController.$inject = ['$scope', 'imageResolve', 'Authentication'];
function ImagesController($scope, image, Authentication) {
var vm = this;
vm.image = image;
vm.authentication = Authentication;
}
}());
|
var ToolBoxWidget = {
options: {
close: null,
open: null
},
_create: function() {
this._init_dom();
this._init_behavior();
this._init_css();
},
_init_dom: function() {
var self = this;
ales.jqui_plugins.create_close_button()
.click(function() {
self.close();
return false;
})
.appendTo(this.element);
},
_init_behavior: function() {
var self = this;
},
_init_css: function() {
this.element.find('.close_box').css(ales.jqui_plugins.std_close_btn_css);
},
close: function() {
this.element.hide();
if (this.options.close) { this.options.close(); }
},
open: function() {
this.element.show();
if (this.options.open) { this.options.open(); }
(function(self) { registerEscapeCandidate(function() { self.close() }) })(this);
},
toggle: function() {
if (this.element.is(':visible')) {
this.close();
} else {
this.open();
}
},
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments);
}
};
(function($) {
$.widget('ales.toolbox', ToolBoxWidget);
})(jQuery);
|
/* @flow */
import { assert } from 'chai';
import { createChainCreator, inspectChain, groovy } from './';
import type { ChainCreator } from './factories';
import groovySyntax from './lang/groovy';
import renderInline from './render/inline';
describe('Steps', () => {
it('should expose any step', () => {
const { out } = groovy;
const chain = out;
assert.isFunction(chain);
});
it('should expose callable steps', () => {
const { out } = groovy;
const chain = out();
assert.isFunction(chain);
});
it('should expose steps callable with arguments', () => {
const { out } = groovy;
const chain = out('firstname', 'Alice');
assert.isFunction(chain);
});
});
describe('groovy', () => {
it('should expose any object', () => {
const { g } = groovy;
const chain = g;
assert.isFunction(chain);
});
it('should expose any step', () => {
const { g } = groovy;
const chain = g.has;
assert.isFunction(chain);
});
it('should expose callable steps', () => {
const { g } = groovy;
const chain = g.has();
assert.isFunction(chain);
});
it('should expose callable steps', () => {
const { g } = groovy;
const chain = g.has('firstname', 'Alice');
assert.isFunction(chain);
});
it('should expose non-function chainable properties', function() {
const { g } = groovy;
const chain = g.has.duh.foo.baz;
assert.isFunction(chain);
});
it('should expose chainable steps', () => {
const { g } = groovy;
const chain = g.has().out();
assert.isFunction(chain);
});
it('should expose chainable-callable steps', () => {
const { g } = groovy;
const chain = g.has.out();
assert.isFunction(chain);
});
it('should expose infinitely chainable steps', () => {
const { g } = groovy;
const chain = g.has().out().in.foo.bar();
assert.isFunction(chain);
});
it('should support arguments', () => {
const { g } = groovy;
const chain = g.has('firstname', 'Alice');
assert.isFunction(chain);
});
it('should not conflict when creating multiple chains', () => {
const { g } = groovy;
const chain1 = g.has('firstname', 'Alice');
const chain2 = g.out('knows');
const repr1 = inspectChain(chain1);
const repr2 = inspectChain(chain2);
assert.isArray(repr1);
assert.deepPropertyVal(repr1, '0.name', 'g');
assert.deepPropertyVal(repr1, '1.name', 'has');
assert.deepPropertyVal(repr1, '2.params.0', 'firstname');
assert.deepPropertyVal(repr1, '2.params.1', 'Alice');
assert.isArray(repr2);
assert.deepPropertyVal(repr2, '0.name', 'g');
assert.deepPropertyVal(repr2, '1.name', 'out');
assert.deepPropertyVal(repr2, '2.params.0', 'knows');
});
});
|
/**
* Created by xue on 2017/4/14.
*/
var mongoose=require('mongoose');
var contentsSchema=require('../schemas/contents');
module.exports=mongoose.model('Content',contentsSchema);
|
var keystone = require('keystone')
exports = module.exports = function (req, res) {
var view = new keystone.View(req, res)
view.render('hotels')
}
|
module.exports = {
getAllCarts: {
map: function(doc) {
if (doc.type === "cart") {
emit(doc.name, {
_id: doc._id
});
}
}
}
}
|
function iterator(coll, root, textures) {
for (var i in coll) {
if (typeof coll[i] === 'object') {
iterator(coll[i], root + '/' + i, textures);
} else {
textures.push(root + '/' + i + coll[i]);
coll[i] = textures.length - 1;
}
}
}
var R = {
game: {
bg: '.png',
block_big: '.png',
block_small: '.png',
block_column: '.png'
},
ui: {
add: '.png',
auto: '.png',
column: '.png',
counter: '.png',
minus: '.png',
ok: '.png',
points_bg: '.png',
slide: '.png'
},
upgrade: {
archive_line_01: '.png',
archive_line_02: '.png',
arrow_level: '.png',
b_01: '.png',
b_02: '.png',
b_addcoins: '.png',
b_close: '.png',
b_close_01: '.png',
b_close_02: '.png',
b_select: '.png',
b_shop_01: '.png',
b_shop_02: '.png',
b_shop_selected: '.png',
b_unlock_01: '.png',
b_unlock_02: '.png',
b_z_achievement: '.png',
b_z_avatar: '.png',
b_z_shop: '.png',
b_z_skill: '.png',
b_z_upgrade: '.png',
bg_coins_star: '.png',
bg_level_01: '.png',
bg_level_02: '.png',
bg_start_gains_1: '.png',
bg_start_gains_2: '.png',
bg_unlock: '.png',
bg: '.png',
bg_upgrade: '.png',
bg_upgrade_coins: '.png',
coin_bg: '.png',
icon_archive_01: '.png',
icon_archive_02: '.png',
icon_boy_clothes: '.png',
icon_boy_gloves: '.png',
icon_boy_hat: '.png',
icon_boy_shoes: '.png',
icon_girl_clothes: '.png',
icon_girl_gloves: '.png',
icon_girl_hat: '.png',
icon_girl_shoes: '.png',
icon_tools_01: '.png',
icon_tools_02: '.png',
icon_tools_selected: '.png',
item_01: '.png',
item_02: '.png',
item_03: '.png',
item_04: '.png',
item_05: '.png',
item_06: '.png',
j_01: '.png',
j_02: '.png',
j_03: '.png',
j_04: '.png',
kid_boy: '.png',
kid_boy_01: '.png',
kid_boy_02: '.png',
kid_girl: '.png',
kid_girl_01: '.png',
kid_girl_02: '.png',
p_coin: '.png',
p_star: '.png',
paper_01: '.png',
paper_02: '.png',
query: '.png',
query_cp: '.png',
scroll_01: '.png',
scroll_02: '.png',
split_h: '.png',
split_v: '.png',
z_iceball: '.png',
z_magnet: '.png',
z_turbo: '.png',
z_unlock: '.png',
others: {
b_unlock_01: '.png',
b_unlock_02: '.png',
bg_unlock: '.png',
j_01: '.png',
j_02: '.png',
j_03: '.png',
j_04: '.png',
kid_boy: '.png',
kid_boy_01: '.png',
kid_boy_02: '.png',
kid_girl: '.png',
kid_girl_01: '.png',
kid_girl_02: '.png',
z_unlock: '.png'
}
},
pngnow: '.png',
test: '.png',
word: '.png'
}
var textures = [];
var root = 'images';
iterator(R, '', textures);
// managing texture frame creation
var _textures = require('glcore/textures.js');
var _frame = require('glcore/textureframe.js');
function getPath(id) {
return root + textures[id];
}
function createFrame(id) {
var path = getPath(id);
if (!path) {
console.log('createFrame image not found:' + id);
}
if (path.frame) {
return path.frame;
}
var t = _textures.createTexture2D(path);
return path.frame = new _frame(t);
}
_textures.createTexture2D('images/upgrade/b_addcoins.png');
_textures.createTexture2D('images/upgrade/b_addcoins.png');
_textures.createTexture2D('images/upgrade/b_addcoins.png');
exports.R = R;
exports.createFrame = createFrame;
|
function convertNumberToTime(number)
{
hour = Math.floor(number/100);
minutes = Math.round(number%100/100*60);
if (minutes< 10)
minutes = "0" + minutes;
time = [hour, minutes];
time = time.join(':');
return time;
}
function convertTimeToNumber(time)
{
time = time.split(":");
time[1] = Math.round(time[1]/60*100);
if(time[1] < 10)
time[1] = "0"+time[1];
time = time.join('');
time = parseInt(time,10);
return time;
}
|
(function ($) {
$(document).ready(function () {
var $icons = $(".nav-icon-wrapper");
$(".nav-icon.menu", $icons).click(function () {
$(".main-nav").toggleClass("show");
});
$(".nav-icon.edit", $icons).click(function () {
alert("Edit");
});
$(".nav-icon.save", $icons).click(function () {
confirm("Save?");
});
$(".main-wrapper").scroll(function () {
var $top = $(".top-header", this);
if ($(this).scrollTop() == 0)
$top.removeClass("glued");
else
$top.addClass("glued");
});
});
})(jQuery);
|
/*
* Copyright (c) 2015 Intel Corporation.
*
* 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.
*/
// https://github.com/w4ilun/edison-guides/tree/master/recipies/Johnny-Five%20Examples
// Plug the light sensor into the Analog port A0 on the provided
// Seeed Sensor Kit Arduino Shield
// MUST be in the analog pin slots!
var five = require("johnny-five");
var Edison = require("edison-io");
var board = new five.Board({
io: new Edison()
});
board.on("ready", function() {
var light = new five.Sensor("A1");
this.loop(2000, function() {
console.log("Light sensor value: ", light.value);
});
});
|
/**
Find the nth fibonacci number.
First 10 fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Runtime Complexity
Linear, O(n).
Memory Complexity
Constant, O(1).
*/
let get_fibonacci = function(n) {
if (n === 0 || n === 1) {
return n;
}
let n_1 = 1;
let n_2 = 0;
let res = 0;
let i = 2;
while (i <= n) {
res = n_1 + n_2;
n_2 = n_1;
n_1 = res;
i++;
}
return res;
};
/**
Runtime Complexity
Exponential, O(2n).
Memory Complexity
Linear, O(n).
*/
let get_fibonacci_rec = function(n) {
if (n === 0 || n === 1) {
return n;
}
return get_fibonacci_rec(n - 1) + get_fibonacci_rec(n - 2);
};
let fibonacci2 = n => {
if ( n === 0 || n === 1) {
return n;
}
let n1 = 0;
let n2 = 1
let res = 0;
let i = 2;
while ( i <= n ) {
res = n1 + n2;
n1 = n2;
n2 = res;
i++
}
}
|
var fs = require("fs");
var path = require("path");
var child_process = require("child_process");
/**
* @type {import('../../lib/interfaces').DockerLanguageDef}
*/
module.exports = {
setup: function (work_dir, file_content, cb, con) {
var filePath = path.resolve(work_dir, 'main.hs');
var binPath = path.resolve(work_dir, 'main');
fs.writeFileSync(filePath, file_content);
var child = child_process.spawn('ghc', ['-o', binPath, filePath], {stdio: 'pipe', cwd: path.dirname(filePath)});
child.stdout.on('data', con.log)
child.stderr.on('data', con.error)
child.on('exit', function (code, sig) {
if (code !== 0 || sig != null) {
con.log('compiler exit with code ' + code + ' and signal ' + sig);
con.exit({code: code, signal: sig});
return
}
fs.chmodSync(binPath, 0o777)
cb(binPath)
})
},
getExecuteArgs: function (file_path) {
return {
path: file_path,
args: [],
opts: {}
}
}
}
|
var u = require('../../app/util');
var SchemaPlugin = function(o){
u.extend(this, o);
if(!this.name){
throw new Error('"name" is requried and unique');
}
if(!this.prop){
throw new Error('"prop" is requried');
}
if(!this.type){
throw new Error('"type" is requried');
}
this.methodName = 'with' + this.name.charAt(0).toUpperCase() + this.name.slice(1);
};
SchemaPlugin.prototype = {
/*
* The identifier is used in builder. make sure it is unique in all plugins.
* i.e. if name is createBy and the plugin is registered,
* then withCreatedBy method will be generated in builder.
*/
name: null,
prop: null, //property name of mongoose schema. i.e. _id
type: null, //mongoose schema types. i.e. {type: String, required: true}
register: function(builderClass){
builderClass.plugins[this.prop] = this;
var plugin = this;
builderClass.prototype[this.methodName] = function(options){
this.usePlugins[plugin.prop] = options;
return this;
};
},
use: function(schema, options){
console.log('SchemaPlugin ' + this.name + ' is used');
}
};
module.exports = SchemaPlugin;
|
'use strict';
var jsc = require('jsverify');
var equals = require('./internal/equals');
var basic = jsc.sum([jsc.integer, jsc.string, jsc.bool, jsc.falsy]);
var useful = jsc.sum([basic, jsc.array(basic), jsc.dict(basic), jsc.fn(basic)]);
exports.idempotent = function(f) {
return jsc.checkForall(useful, function(x) {
return equals(f(f(x)))(f(x));
});
};
exports.involution = function(f) {
return jsc.checkForall(useful, function(x) {
return equals(f(f(x)))(x);
});
};
|
import React, { Component } from 'react'
import { inject, observer } from 'mobx-react'
import {
classNames, getDeviceBreakpoint,
getPrevDeviceBreakpoint, shallowEqual,
isEmpty
} from 'helpers'
import { image as config } from 'config'
import { imageHostname as hostname } from 'constants/urls'
import s from './Image.sass'
const mapStateToProps = ({device: {width}}) => ({
width
});
@inject(mapStateToProps) @observer
export default class Image extends Component {
isFaded = false; isMount = false;
dur = config.dur; ease = config.ease();
state = {isLoaded: false, mainImageLoaded: false};
getPrevDeviceSize = (sizes, currentDevice) => {
let prevDevice = getPrevDeviceBreakpoint(currentDevice);
if (sizes[prevDevice.name]) {
return sizes[prevDevice.name];
}
let src;
sizes.forEach(item => {
if (src) return;
prevDevice = getPrevDeviceBreakpoint(prevDevice);
if (sizes[prevDevice.name]) {
src = sizes[prevDevice.name];
}
});
return src;
};
getSrc = (sizes) => {
if (typeof sizes === 'string')
return sizes;
if (Object.keys(sizes).length <= 2) {
return sizes.src;
}
// get current device params
let currentDevice = getDeviceBreakpoint(this.props.width);
if (sizes[currentDevice.name]) {
return sizes[currentDevice.name];
}
// check other resolutions if we have.
return this.getPrevDeviceSize(sizes, currentDevice);
};
componentWillMount() {
this.isMount = true;
}
componentWillUnmount() {
this.isMount = false;
}
componentWillReceiveProps({src, preview}) {
if (preview !== preview || !shallowEqual(src, this.props.src)) {
return this.setState({isLoaded: false, mainImageLoaded: false});
}
}
componentDidUpdate() {
if (!this.isFaded && this.state.mainImageLoaded) {
this.showImage();
}
this.addEventListener();
}
componentDidMount() {
this.addEventListener();
}
addEventListener = () => {
this.image && this.image.addEventListener('load', this.onImageLoad);
}
showImage = () => {
if (!this.isMount)
return;
this.isFaded = true;
this.fadeInImage(() => {
this.isMount && this.setState({
isLoaded: true
})
})
};
fadeInImage = onComplete => {
const preview = this.preview || (this.preview = document.querySelector(`.${s.preview}`))
const image = this.image || (this.getRef(document.querySelector(`.${s.img}`)));
if (!preview || !image)
return null;
const { dur, ease } = this;
TweenMax.set(preview, {
display: 'none'
});
TweenMax.fromTo(image, dur, {
opacity: 0,
display: 'block',
}, {
opacity: 1,
ease,
onComplete
})
};
renderImage = props => (
<img {...props} src={props.src}/>
);
getPreviewRef = b => this.preview = b;
getRef = b => {
this.image = b;
if (this.props.getRef) {
this.props.getRef(b);
}
return b;
}
onImageLoad = () => {
if (this.isMount && !this.state.mainImageLoaded) {
this.isFaded = false;
this.setState({mainImageLoaded: true});
}
}
imageStyles = {display: 'none'}
getHostNameSrc = src => {
if (isEmpty(src))
return null;
if (src.indexOf('blob') === -1) {
return `${hostname}${src}`
}
return src;
}
render() {
const {
className, withLoading,
preview, src, alt, style
} = this.props;
const { getRef } = this;
const { isLoaded } = this.state;
const previewSrc =
preview || src && src.preview || withLoading;
if (!src)
return null;
if (!previewSrc) {
return this.renderImage({
src: this.getHostNameSrc(src), className, ref: getRef, alt,
style
})
}
const _src = typeof src === 'string' ? src
: src.full
? src.full : this.getSrc(src);
if (isLoaded) {
return this.renderImage({
src: this.getHostNameSrc(_src), className, ref: getRef, alt,
style
})
}
return (
<figure className={s.wrapper}>
{!isLoaded && <img className={classNames(s.preview, className)}
ref={this.getPreviewRef} style={style}
src={this.getHostNameSrc(_src)}/>}
<img className={classNames(s.img, className)}
src={this.getHostNameSrc(_src)} style={this.imageStyles} ref={getRef}
onLoad={this.onImageLoad}/>
</figure>
)
}
}
|
"use strict";
var arrays = require("./utils/arrays"),
objects = require("./utils/objects");
var PEG = {
/* PEG.js version (uses semantic versioning). */
VERSION: "0.8.0",
GrammarError: require("./grammar-error"),
parser: require("./parser"),
compiler: require("./compiler"),
/*
* Generates a parser from a specified grammar and returns it.
*
* The grammar must be a string in the format described by the metagrammar in
* the parser.pegjs file.
*
* Throws |PEG.parser.SyntaxError| if the grammar contains a syntax error or
* |PEG.GrammarError| if it contains a semantic error. Note that not all
* errors are detected during the generation and some may protrude to the
* generated parser and cause its malfunction.
*/
buildParser: function(grammar) {
function convertPasses(passes) {
var converted = {}, stage;
for (stage in passes) {
if (passes.hasOwnProperty(stage)) {
converted[stage] = objects.values(passes[stage]);
}
}
return converted;
}
var options = arguments.length > 1 ? objects.clone(arguments[1]) : {},
plugins = "plugins" in options ? options.plugins : [],
config = {
parser: this.parser,
passes: convertPasses(this.compiler.passes)
};
arrays.each(plugins, function(p) { p.use(config, options); });
return this.compiler.compile(
config.parser.parse(grammar),
config.passes,
options
);
}
};
module.exports = PEG;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.