text
stringlengths 2
6.14k
|
|---|
import React from 'react';
import Link from 'gatsby-link';
import '../css/tags.css';
export default function Tags({ list = [] }) {
return (
<div className="tag-list">
{list.map(tag =>
<Link className="tag" to={`/tags/${tag}`}>
{tag}
</Link>
)}
</div>
);
}
|
var webpack = require('webpack'),
webpackConfig = require('./webpack.config.base'),
DefinePlugin = require('webpack/lib/DefinePlugin'),
SourceMapDevToolPlugin = require('webpack/lib/SourceMapDevToolPlugin'),
env = require('../environment/dev.env');
webpackConfig.module.rules = [{
test: /\.ts$/,
exclude: /node_modules/,
loader: 'awesome-typescript-loader',
query: {
compilerOptions: {
inlineSourceMap: true,
sourceMap: false
}
}
},
{
test: /\.html$/,
loader: 'raw-loader',
exclude: ['./src/index.html']
},
{
test: /\.scss$/,
use: [{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(jpg|png|gif|eot|svg|ttf|woff|woff2)$/,
loader: 'url-loader?limit=8192'
}
];
webpackConfig.plugins = [...webpackConfig.plugins,
new SourceMapDevToolPlugin({
filename: null, // if no value is provided the sourcemap is inlined
test: /\.(ts|js)($|\?)/i
}),
new DefinePlugin({
'process.env': env
})
];
webpackConfig.devtool = 'inline-source-map';
module.exports = webpackConfig;
|
'use strict';
import React from 'react';
const Page = ({children}) => (
<div className="page-component container">
<div className="page-box">
{children}
</div>
</div>
);
export default Page;
|
/*
*
* @author Benoit Vinay
*
* ben@benoitvinay.com
* http://www.benoitvinay.com
*
*/
//////////////////////////////////////////////////////////////////////////////////////////
// Sound Object
//
// use in loader.sound.js
//////////////////////////////////////////////////////////////////////////////////////////
function SoundObject(url, tag) {
var _this = this;
var _tag = tag;
var _valid = (_tag.canPlayType ? true : false); // check if the tag is valid (i.e.: Safari on Windows)
var _playTimeout = undefined;
var _loopInterval = undefined;
var _duration = (_valid ? (_tag.duration * 1000) : -1);
var _playing = false;
this.url = url;
// play
var _play = function(time) {
_this.stop();
try {
_tag.currentTime = time || 0;
_tag.play();
}
catch(e) {
_error(e);
}
_playing = true;
}
this.play = function(time, complete) {
_play.apply(_this, [time]);
try {
_tag.loop = false;
}
catch(e) {
_error(e);
}
if(complete) {
_playTimeout = setTimeout(function() {
clearTimeout(_playTimeout);
complete.apply(_this);
}, _duration);
}
}
// loop
this.loop = function(time, complete) {
_play.apply(_this, [time]);
try {
_tag.loop = true;
}
catch(e) {
_error(e);
}
_loopInterval = setInterval(function() {
if(complete) {
complete.apply(_this);
}
}, _duration);
}
// stop
this.stop = function() {
_playing = false;
if(_playTimeout) {
clearTimeout(_playTimeout);
}
if(_loopInterval) {
clearInterval(_loopInterval);
}
try {
_tag.pause();
}
catch(e) {
_error(e);
}
}
// volume
this.mute = function(value) {
try {
_tag.muted = value;
}
catch(e) {
_error(e);
}
}
// error
var _error = function(e) {
Console.log("SoundObject.error:", e.message);
}
// valid
if(!_valid) {
_play = function(time) {};
this.play = function(time, complete) {};
this.loop = function(time, complete) {};
this.stop = function() {};
this.mute = function(value) {};
_error({ message: this.url + " is not valid." });
}
// if valid
// we add the tag to the holder
else {
if($("#audios-holder").length == 0) {
$("body").prepend("<div id='audios-holder'></div>");
}
$("#audios-holder").append(_tag);
_tag = document.getElementById(url);
}
}
|
// app/models/tools.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ToolsSchema = new Schema({
name: String,
tooltype: String,
weight: Number,
damagedflag: Boolean,
serialnumber: String
});
module.exports = mongoose.model('Tools', ToolsSchema);
|
module.exports = parse
/**
* expected argument lengths
* @type {Object}
*/
var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0}
/**
* segment pattern
* @type {RegExp}
*/
var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig
/**
* parse an svg path data string. Generates an Array
* of commands where each command is an Array of the
* form `[command, arg1, arg2, ...]`
*
* @param {String} path
* @return {Array}
*/
function parse(path) {
var data = []
path.replace(segment, function(_, command, args){
var type = command.toLowerCase()
args = parseValues(args)
// overloaded moveTo
if (type == 'm' && args.length > 2) {
data.push([command].concat(args.splice(0, 2)))
type = 'l'
command = command == 'm' ? 'l' : 'L'
}
while (true) {
if (args.length == length[type]) {
args.unshift(command)
return data.push(args)
}
if (args.length < length[type]) throw new Error('malformed path data')
data.push([command].concat(args.splice(0, length[type])))
}
})
return data
}
var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig
function parseValues(args) {
var numbers = args.match(number)
return numbers ? numbers.map(Number) : []
}
|
/* global module, require */
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
banner: '/*!\n * <%= pkg.name %> - <%= pkg.description %>\n' +
' * Copyright (c) 2010 <%= pkg.author.name %> <<%= pkg.author.email %>>\n' +
' * Licensed <%= pkg.license %>-style.\n */\n',
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true
},
dist: {
src: [
'src/js/Moovie.js',
'src/js/Moovie.registerPlugin.js',
'src/js/Moovie.Support.js',
'src/js/Moovie.Util.js',
'src/js/Moovie.toHTMLTrackElement.js',
'src/js/Moovie.Ui.js',
'src/js/Moovie.Ui.Panel.js',
'src/js/Moovie.MediaEvents.js',
'src/js/Moovie.Playlist.js'
],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
src: '<%= concat.dist.dest %>',
dest: 'dist/<%= pkg.name %>.min.js'
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
karmafile: {
src: 'karma.conf.js'
},
all: {
src: [
//'src/js/*.js',
'test/specs/*.js'
]
}
},
karma: {
unit: {
configFile: '<%= jshint.karmafile.src %>',
browsers: ['Firefox']
},
watch: {
configFile: '<%= jshint.karmafile.src %>',
browsers: ['Firefox'],
background: true,
singleRun: false,
reporters: ['mocha', 'coverage']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
karmafile: {
files: '<%= jshint.karmafile.src %>',
tasks: ['jshint:karmafile']
},
all: {
files: '<%= jshint.all.src %>',
tasks: ['jshint:all', 'karma:watch:run']
}
},
bump: {
options: {
files: ['package.json', 'bower.json'],
updateConfigs: ['pkg'],
commit: true,
commitMessage: 'Release v%VERSION%',
commitFiles: ['-a'],
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: true,
pushTo: 'origin',
gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
globalReplace: false,
prereleaseName: false,
regExp: false
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['test', 'build']);
grunt.registerTask('test', ['jshint', 'karma:unit']);
grunt.registerTask('start', ['karma:watch:start', 'watch']);
grunt.registerTask('build', ['concat', 'uglify']);
grunt.registerTask('release', function (target) {
target = 'bump-only:' + (target || 'patch');
grunt.task.run(['default', target, 'bump-commit']);
});
};
|
jui.define("chart.brush.map.selector", [ "util.base" ], function(_) {
/**
* @class chart.brush.over
* @extends chart.brush.core
*/
var MapSelectorBrush = function(chart, axis, brush) {
var g = null,
activePath = null;
this.drawBefore = function() {
g = chart.svg.group();
}
this.draw = function() {
var originFill = null;
this.on("map.mouseover", function(obj, e) {
if(activePath == obj.path) return;
originFill = obj.path.styles.fill || obj.path.attributes.fill;
obj.path.css({
fill: chart.theme("mapSelectorHoverColor")
});
});
this.on("map.mouseout", function(obj, e) {
if(activePath == obj.path) return;
obj.path.css({
fill: originFill
});
});
if(brush.activeEvent != null) {
this.on(brush.activeEvent, function(obj, e) {
activePath = obj.path;
axis.map.each(function(i, obj) {
obj.path.css({
fill: originFill
});
});
obj.path.css({
fill: chart.theme("mapSelectorActiveColor")
});
});
}
if(brush.active.length > 0) {
activePath = [];
axis.map.each(function(i, obj) {
if(_.inArray(axis.getValue(obj.data, "id"), brush.active) != -1) {
activePath.push(obj.path);
obj.path.css({
fill: chart.theme("mapSelectorActiveColor")
});
}
});
}
return g;
}
}
MapSelectorBrush.setup = function() {
return {
active: [],
activeEvent: null
}
}
return MapSelectorBrush;
}, "chart.brush.map.core");
|
import React, {Component} from 'react';
// require('./style.scss');
export default class WorkDetails extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
document.title = "Profile | Work Details";
}
render() {
return (
<div>WorkDetailsWorkDetailsWorkDetailsWorkDetailsWorkDetailsWorkDetails</div>
);
}
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Chart = require('../../../models/Chart');
var _Chart2 = _interopRequireDefault(_Chart);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = async function (ctx) {
await ctx.checkAbility('admin');
//abilities
let id = ctx.query.id || ctx.error(404);
// $Flow findById
let chart = await _Chart2.default.findById(id);
if (!chart) ctx.error(404);
if (chart.abilities) {
for (let ability of chart.abilities) {
// $Flow ability Object string
await ctx.checkAbility(ability);
}
}
ctx.body = await chart.getData(ctx);
};
|
'use strict';
/**
* Import plugins
*/
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
runSequence = require('run-sequence'),
argv = require('yargs').argv,
del = require('del');
/**
* Build vendors dependencies
*/
gulp.task('vendors', function() {
/**
* CSS VENDORS
*/
gulp.src([
'bower_components/font-awesome/css/font-awesome.min.css',
'bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css',
'bower_components/bootstrap-chosen/bootstrap-chosen.less'
])
.pipe($.concat('vendors.css'))
.pipe($.minifyCss())
.pipe(gulp.dest('web/assets/css'));
/**
* JS VENDORS
* (with jQuery and Bootstrap dependencies first)
*/
gulp.src([
'bower_components/jquery/dist/jquery.js',
'bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/affix.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/alert.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/button.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/carousel.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/collapse.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/dropdown.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/modal.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tooltip.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/popover.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/scrollspy.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tab.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/transition.js'
])
.pipe($.concat('vendors.min.js'))
.pipe($.uglify())
.pipe(gulp.dest('web/assets/js'));
/**
* FONTS SOURCES
* Important to add the bootstrap fonts to avoid issues with the fonts include path
*/
gulp.src([
'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
'bower_components/font-awesome/fonts/*'
])
.pipe(gulp.dest('web/assets/fonts'));
/**
* POLYFILLS SOURCES
* Various polyfills required for old IE
*/
gulp.src([
'bower_components/html5shiv/dist/html5shiv.js',
'bower_components/respond/dest/respond.src.js'
])
.pipe($.concat('polyfills.min.js'))
.pipe($.uglify())
.pipe(gulp.dest('web/assets/js'));
/**
* POLYFILLS SOURCES
* Various polyfills required for old IE
*/
gulp.src([
'bower_components/bootstrap-chosen/chosen-sprite.png',
'bower_components/bootstrap-chosen/chosen-sprite@2x.png'
])
.pipe(gulp.dest('web/assets/css'));
});
/**
* Build styles from SCSS files
* With error reporting on compiling (so that there's no crash)
*/
gulp.task('styles', function() {
if (!argv.production) {
console.log('[styles] Processing styles for dev env. No minifying here, for sourcemaps!')
} else {
console.log('[styles] Processing styles for production env.');
}
return $.rubySass('sass/main.scss', {sourcemap: !argv.production})
.on('error', $.notify.onError(function (error) {
console.log('Error', error.message);
if (!argv.production) {
return 'Message to the notifier: ' + error.message;
}
}))
.pipe($.autoprefixer({
browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1']
}))
.pipe($.if(!argv.production, $.sourcemaps.write()))
.pipe($.if(argv.production, $.minifyCss()))
.pipe(gulp.dest('web/assets/css'));
});
/**
* Build JS
* With error reporting on compiling (so that there's no crash)
* And jshint check to highlight errors as we go.
*/
gulp.task('scripts', function() {
return gulp.src('js/**/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.concat('main.js'))
.pipe(gulp.dest('web/assets/js'))
.pipe($.rename({ suffix: '.min' }))
.pipe($.uglify())
.pipe(gulp.dest('web/assets/js'));
});
/**
* Clean output directories
*/
gulp.task('clean', del.bind(null, ['web/assets']));
/**
* Serve
*/
gulp.task('serve', ['styles', 'scripts'], function () {
gulp.watch(['sass/**/*.scss'], function() {
runSequence('styles');
});
gulp.watch(['js/**/*.js'], function() {
runSequence('scripts');
});
});
/**
* Task to build assets on production server
*/
gulp.task('build', ['clean'], function() {
argv.production = true;
runSequence('vendors', 'styles', 'scripts');
});
/**
* Default task
*/
gulp.task('default', ['clean'], function(cb) {
runSequence('vendors', 'styles', 'scripts', cb);
});
|
export { default } from 'ember-fhir/serializers/appointment-response';
|
import random from '../../randomGenerator'
import sendCommand from './commandHelper'
const getTextDocumentData = (textDocumentData) => {
if ('k' in textDocumentData) {
return textDocumentData.k
} else {
return [
{
s: textDocumentData
}
]
}
}
const processText = (textData, layerId) => {
const textDocumentData = getTextDocumentData(textData.d)
const sourceTextIdId = random(10);
sendCommand('assignIdToProp', ['Source Text', sourceTextIdId, layerId]);
if (textDocumentData.length === 1) {
const textDocumentValue = textDocumentData[0].s
sendCommand('setTextDocumentValue',
[
layerId,
encodeURIComponent(textDocumentValue.t),
textDocumentValue.s,
encodeURIComponent(textDocumentValue.f),
textDocumentValue.fc,
textDocumentValue.tr,
textDocumentValue.j,
textDocumentValue.ls || 0,
]
);
} else {
textDocumentData.forEach(textDocument => {
const textDocumentValue = textDocument.s
sendCommand('setTextDocumentValueAtTime',
[
layerId,
textDocument.t,
encodeURIComponent(textDocumentValue.t),
textDocumentValue.s,
encodeURIComponent(textDocumentValue.f),
textDocumentValue.fc,
textDocumentValue.tr,
textDocumentValue.j,
textDocumentValue.ls || 0,
]
);
})
}
}
export default processText
|
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
var onReady = function() {
$('table.table a#ping').on('click', function(event) {
var recruiterId = $(this).closest('tr.recruiter-id').attr('id').split('-')[1];
console.debug('clicked', recruiterId, $(this), event);
});
// Source: http://stackoverflow.com/q/30019692/1093087
// initialize bloodhound engine
var searchSelector = 'div.search.recruiters input.typeahead';
var bloodhound = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
// sends ajax request to remote url where %QUERY is user input
remote: '/recruiters/typeahead/%QUERY',
limit: 50
});
bloodhound.initialize();
// initialize typeahead widget and hook it up to bloodhound engine
// #typeahead is just a text input
$(searchSelector).typeahead(null, {
displayKey: 'email',
source: bloodhound.ttAdapter()
});
// this is the event that is fired when a user clicks on a suggestion
$(searchSelector).bind('typeahead:selected', function(event, datum, name) {
//console.debug('Suggestion clicked:', event, datum, name);
window.location.href = '/recruiters/' + datum.id;
});
// Modal for blacklist button
$('div#blacklist-modal').on('show.bs.modal', function(e) {
var color = $(e.relatedTarget).hasClass('graylist') ? 'gray' : 'black';
$('div#blacklist-modal input#color').val(color);
})
$('div#blacklist-modal form').on('submit', function(e) {
$('div#blacklist-modal').modal('hide');
})
};
$(document).ready(onReady);
$(document).on('page:load', onReady);
|
var searchData=
[
['bool1',['bool1',['../a00743.html#gaddcd7aa2e30e61af5b38660613d3979e',1,'glm']]],
['bool1x1',['bool1x1',['../a00743.html#ga7f895c936f0c29c8729afbbf22806090',1,'glm']]],
['bool2',['bool2',['../a00743.html#gaa09ab65ec9c3c54305ff502e2b1fe6d9',1,'glm']]],
['bool2x2',['bool2x2',['../a00743.html#gadb3703955e513632f98ba12fe051ba3e',1,'glm']]],
['bool2x3',['bool2x3',['../a00743.html#ga9ae6ee155d0f90cb1ae5b6c4546738a0',1,'glm']]],
['bool2x4',['bool2x4',['../a00743.html#ga4d7fa65be8e8e4ad6d920b45c44e471f',1,'glm']]],
['bool3',['bool3',['../a00743.html#ga99629f818737f342204071ef8296b2ed',1,'glm']]],
['bool3x2',['bool3x2',['../a00743.html#gac7d7311f7e0fa8b6163d96dab033a755',1,'glm']]],
['bool3x3',['bool3x3',['../a00743.html#ga6c97b99aac3e302053ffb58aace9033c',1,'glm']]],
['bool3x4',['bool3x4',['../a00743.html#gae7d6b679463d37d6c527d478fb470fdf',1,'glm']]],
['bool4',['bool4',['../a00743.html#ga13c3200b82708f73faac6d7f09ec91a3',1,'glm']]],
['bool4x2',['bool4x2',['../a00743.html#ga9ed830f52408b2f83c085063a3eaf1d0',1,'glm']]],
['bool4x3',['bool4x3',['../a00743.html#gad0f5dc7f22c2065b1b06d57f1c0658fe',1,'glm']]],
['bool4x4',['bool4x4',['../a00743.html#ga7d2a7d13986602ae2896bfaa394235d4',1,'glm']]],
['bvec1',['bvec1',['../a00695.html#ga067af382616d93f8e850baae5154cdcc',1,'glm']]],
['bvec2',['bvec2',['../a00710.html#ga0b6123e03653cc1bbe366fc55238a934',1,'glm']]],
['bvec3',['bvec3',['../a00710.html#ga197151b72dfaf289daf98b361760ffe7',1,'glm']]],
['bvec4',['bvec4',['../a00710.html#ga9f7b9712373ff4342d9114619b55f5e3',1,'glm']]],
['byte',['byte',['../a00782.html#ga3005cb0d839d546c616becfa6602c607',1,'glm']]]
];
|
/**
* res : successCallback
* rej : failCallback
*/
const promise = new Promise((res, rej) => {
setTimeout(() => {
const name = "alice";
res(name);
}, 1000);
});
promise.then((name) => {
console.log('안녕하세요, ' + name + '님');
});
|
const readline = require('readline');
const constants = require('./constants.js');
const authenticate = require('./functions/authenticate.js');
const getMetadata = require('./functions/getMetadata.js');
const downloadRemote = require('./functions/downloadRemote.js');
const error = require('./functions/error.js');
const checkbox = require('./functions/checkbox.js');
const checkNewVersion = require('./functions/checkNewVersion.js');
const findInProject = require('./functions/findInProject.js');
/**
* Link a remote Google Apps Script project to the current folder
*
* @param {String} identifier - Identifier of the remote project to link to the current folder.
* @returns {void}
*/
module.exports = async (identifier) => {
let auth;
try {
const checkedVersion = await checkNewVersion();
process.stdout.write('Linking to this folder...');
auth = await authenticate([]);
const projectRoot = await findInProject('.', constants.META_DIR);
if (projectRoot.found && projectRoot.folder !== '.') {
throw {
message: `You seem to be linking a project inside another project. Cowardly chose not to do that.\n` +
`If you are sure you are not in another project you can execute 'gas unlink' to unlink the remote project.\n`,
print: true,
};
}
const metadata = await getMetadata(auth, identifier);
readline.clearLine(process.stdout);
readline.cursorTo(process.stdout, 0);
process.stdout.write(`Linking '${metadata.name}' to this folder...`);
const downloaded = await downloadRemote(auth, metadata.projectId, '.', 'link');
checkbox.display('green');
process.exit(0);
} catch (err) {
checkbox.display('red');
await error.log(err, auth);
process.exit(1);
}
};
|
import { RECORD_DATA_TABLE_STATE_UPDATE, RESET_RECORD_DATA_TABLE_STATE } from './actions'
import { recordDataTableDefaultState, updateRecordDataTableState, updateRecordLockState } from './state'
import { ACTIVE_SURVEY_FETCHED } from 'actions/activeSurvey'
import { RECORD_LOCKED, RECORD_UNLOCKED } from '../actions'
export default function recordDataTable(state = recordDataTableDefaultState, action) {
const { type, ...otherProps } = action
switch (type) {
case RECORD_DATA_TABLE_STATE_UPDATE:
return updateRecordDataTableState(state, { ...otherProps })
case ACTIVE_SURVEY_FETCHED:
case RESET_RECORD_DATA_TABLE_STATE:
return { ...recordDataTableDefaultState }
case RECORD_LOCKED:
return updateRecordLockState(state, action.recordId, action.lockedBy)
case RECORD_UNLOCKED:
return updateRecordLockState(state, action.recordId, null)
default:
return state
}
}
|
/*globals Foo:true $foo:true */
var obj, moduleOpts = {
setup: function() {
obj = {
foo: {
bar: {
baz: { biff: 'BIFF' }
}
}
};
Foo = {
bar: {
baz: { biff: 'FooBiff' }
}
};
$foo = {
bar: {
baz: { biff: '$FOOBIFF' }
}
};
},
teardown: function() {
obj = null;
Foo = null;
$foo = null;
}
};
module('Ember.get with path', moduleOpts);
// ..........................................................
// LOCAL PATHS
//
test('[obj, foo] -> obj.foo', function() {
deepEqual(Ember.get(obj, 'foo'), obj.foo);
});
test('[obj, foo.bar] -> obj.foo.bar', function() {
deepEqual(Ember.get(obj, 'foo.bar'), obj.foo.bar);
});
test('[obj, this.foo] -> obj.foo', function() {
deepEqual(Ember.get(obj, 'this.foo'), obj.foo);
});
test('[obj, this.foo.bar] -> obj.foo.bar', function() {
deepEqual(Ember.get(obj, 'this.foo.bar'), obj.foo.bar);
});
test('[obj, this.Foo.bar] -> (null)', function() {
deepEqual(Ember.get(obj, 'this.Foo.bar'), undefined);
});
// ..........................................................
// NO TARGET
//
test('[null, Foo] -> Foo', function() {
deepEqual(Ember.get('Foo'), Foo);
});
test('[null, Foo.bar] -> Foo.bar', function() {
deepEqual(Ember.get('Foo.bar'), Foo.bar);
});
|
exports.register = (server, options, next) => {
let routes = [
{
method: 'GET',
path: '/{param*}',
handler: { directory: {
path: './web', listing: false, index: true
} }
}, {
method: 'GET',
path: '/client.bundle.js',
handler: (request, reply) => {
reply.file('./web/build/client.bundle.js');
}
}, {
method: 'GET',
path: '/client.bundle.js.map',
handler: (request, reply) => {
reply.file('./web/build/client.bundle.js.map');
}
}, {
method: 'GET',
path: '/main.css',
handler: (request, reply) => {
reply.file('./web/build/main.css');
}
}, {
method: 'GET',
path: '/main.css.map',
handler: (request, reply) => {
reply.file('./web/build/main.css.map');
}
}
];
server.route(routes);
next();
};
exports.register.attributes = { name: 'web' };
|
///**
//* Forgot Component Spec Test
//*/
//
//
//'use strict';
//
//var React = require('react');
//var ForgotComponent = React.createFactory(require('../../../../client/scripts/components/account/forgot.jsx'));
//
//describe('Forgot Component', function() {
//
// var ReactTestUtils;
// var reactRender;
//
// beforeEach(function() {
// ReactTestUtils = require('react/addons').addons.TestUtils;
// reactRender = ReactTestUtils.renderIntoDocument;
// this.forgotComponent = new ForgotComponent();
// });
//
// it('provides the "Forgot Component" instance', function() {
// // Expect it to exist
// expect(this.forgotComponent).toBeDefined();
// });
//
//});
|
version https://git-lfs.github.com/spec/v1
oid sha256:3174031dbf1b5143f26c5323bd5b2f0e6845efabf494ae2ed9641bbb2c186e85
size 1053
|
//
// XYO Build
//
// Copyright (c) 2014 Grigore Stefan, <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// The MIT License (MIT) <http://opensource.org/licenses/MIT>
//
function Solution() {
.name_="";
.project_= {};
.option_= {};
.dependencyOption_= {};
.projectBasePath_=null;
.projectBasePathStack_=[];
.projectBasePathStackIndex_=0;
.projectBasePathStack_[.projectBasePathStackIndex_]=null;
.solutionPath_=Shell.getcwd();
.name=function(name) {
.name_=name;
};
.project=function(name,type,proc) {
var typeX;
typeX=Platform.projectTypeX(type);
.project_[name+"."+typeX]=new Project();
.project_[name+"."+typeX].name(name);
.project_[name+"."+typeX].type(type);
.project_[name+"."+typeX].basePath_=.projectBasePath_;
var restorePath_=null;
if(.projectBasePath_) {
restorePath_=Shell.getcwd();
Shell.chdir(.projectBasePath_);
};
proc.apply(.project_[name+"."+typeX]);
if(restorePath_) {
Shell.chdir(restorePath_);
};
};
.option=function(category,name,value) {
if(Script.isNil(.option_[category])) {
.option_[category]= {};
};
.option_[category][name]=value;
};
.dependencyOption=function(category,name,value) {
if(Script.isNil(.dependencyOption_[category])) {
.dependencyOption_[category]= {};
};
.dependencyOption_[category][name]=value;
};
.pushProjectPath_=function(path) {
.projectBasePathStackIndex_++;
if(Script.isNil(.projectBasePath_)) {
.projectBasePath_=path;
} else {
.projectBasePath_+="/"+path;
};
.projectBasePathStack_[.projectBasePathStackIndex_]=.projectBasePath_;
};
.popProjectPath_=function() {
.projectBasePathStackIndex_--;
.projectBasePath_=.projectBasePathStack_[.projectBasePathStackIndex_];
};
.projectFromPath=function(path,name) {
.pushProjectPath_(path);
if(Script.isNil(name)) {
name="project.xyo-build.js";
};
Script.include.call(this,path+"/"+name);
.popProjectPath_();
};
.withPath=function(path,proc) {
.pushProjectPath_(path);
proc.apply(this);
.popProjectPath_();
};
};
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Row } from 'react-bootstrap';
import KeyBinding from 'react-keybinding-component';
import Header from './Header/Header.react';
import Footer from './Footer/Footer.react';
import Toasts from './Toasts/Toasts.react';
import lib from '../lib';
class Museeks extends Component {
static propTypes = {
state: React.PropTypes.object,
playToggle: React.PropTypes.func,
children: React.PropTypes.object,
}
constructor(props) {
super(props);
}
render() {
const state = this.props.state;
const trackPlayingId = state.player.currentTrack && state.player.currentTrack._id ? state.player.currentTrack._id : null;
const tracks = state.tracks[state.tracks.tracksCursor].sub.map((trackId) => state.tracks.library.data[trackId]);
const library = state.tracks[state.tracks.tracksCursor].all.map((trackId) => state.tracks.library.data[trackId]);
return (
<div className='main'>
<KeyBinding onKey={ this.onKey } preventInputConflict />
<Header />
<div className='main-content'>
<Row className='content'>
{ React.cloneElement(
this.props.children, {
app: this,
config: state.config,
columns: state.tracks.columns,
playStatus: state.player.playStatus,
network: state.network,
queue: state.queue,
tracks,
library,
playlists: state.playlists,
refreshingLibrary: state.library.refreshingLibrary,
refreshProgress: state.refreshProgress,
trackPlayingId
})
}
</Row>
</div>
<Footer
network={ state.network }
tracks={ tracks }
refreshingLibrary={ state.library.refreshingLibrary }
/>
<Toasts toasts={ state.toasts } />
</div>
);
}
onKey = (e) => {
switch (e.keyCode) {
case 32:
e.preventDefault();
e.stopPropagation();
this.props.playToggle();
break;
}
}
}
const stateToProps = (state) => ({ state });
const dispatchToProps = {
playToggle: lib.actions.player.playToggle
};
export default connect(stateToProps, dispatchToProps)(Museeks);
|
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs',
'ang2-phaser': 'node_modules/ang2-phaser'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
'ang2-phaser': { defaultExtension: 'js' }
};
var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade',
];
// Individual files (~300 requests):
function packIndex(pkgName) {
packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
}
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPackageNames.forEach(setPackageConfig);
// No umd for router yet
packages['@angular/router'] = { main: 'index.js', defaultExtension: 'js' };
var config = {
map: map,
packages: packages
};
System.config(config);
})(this);
|
import varianceOf from "./variance-of";
export default function standardDeviationOf(array, callback) {
let variance = varianceOf(array, callback);
return variance ? Math.sqrt(variance) : false;
}
|
function animate() {
tail = tabCube.pop();
tail.position.x = tabCube[0].position.x;
tail.position.y = tabCube[0].position.y;
tail.position.z = tabCube[0].position.z;
if(direction[0] == 1) {
if(tabCube[0].position.x == (largeur*9)) {
tail.position.x = -(largeur*10);
} else {
tail.position.x += largeur;
}
}
if(direction[1] == 1) {
if(tabCube[0].position.y == (largeur*9)) {
tail.position.y = -(largeur*10);
} else {
tail.position.y += largeur;
}
}
if(direction[2] == 1) {
if(tabCube[0].position.z == (largeur*9)) {
tail.position.z = -(largeur*10);
} else {
tail.position.z += largeur;
}
}
if(direction[0] == -1) {
if(tabCube[0].position.x == -(largeur*10)) {
tail.position.x = (largeur*9);
} else {
tail.position.x -= largeur;
}
}
if(direction[1] == -1) {
if(tabCube[0].position.y == -(largeur*10)) {
tail.position.y = (largeur*9);
} else {
tail.position.y -= largeur;
}
}
if(direction[2] == -1) {
if(tabCube[0].position.z == -(largeur*10)) {
tail.position.z = (largeur*9);
} else {
tail.position.z -= largeur;
}
}
tabCube.unshift(tail);
if(snakeConfondBonbon()) {
ajoutCubeEnQueue(tail);
positionAleatoireBonbon();
document.getElementById("score").innerHTML++;
} else if(teteConfondSnake(tail)) {
if(confirm("Partie terminée! Recommencer?")) {
location.reload();
} else {
clearInterval(timer);
}
}
renderer.render(scene, camera);
}
function allouerDirection(e) {
/**
* KEYCODE
*
* gauche 37
* haut 38
* droite 39
* bas 40
* W 87
* Z 90
**/
if(e.keyCode == 37) {
if(direction[0] != 1) {
direction = new Array(0,0,0);
direction[0] = -1;
}
}
if(e.keyCode == 38) {
if(direction[1] != -1) {
direction = new Array(0,0,0);
direction[1] = 1;
}
}
if(e.keyCode == 39) {
if(direction[0] != -1) {
direction = new Array(0,0,0);
direction[0] = 1;
}
}
if(e.keyCode == 40) {
if(direction[1] != 1) {
direction = new Array(0,0,0);
direction[1] = -1;
}
}
if(e.keyCode == 87) {
if(direction[2] != -1) {
direction = new Array(0,0,0);
direction[2] = 1;
}
}
if(e.keyCode == 90) {
if(direction[2] != 1) {
direction = new Array(0,0,0);
direction[2] = -1;
}
}
}
function snakeConfondBonbon() {
if(tail.position.x == bonbon.position.x && tail.position.y == bonbon.position.y && tail.position.z == bonbon.position.z) {
return true;
} else {
return false;
}
}
function teteConfondSnake(head) {
for(i = 1; i < tabCube.length; i++) {
if(head.position.x == tabCube[i].position.x && head.position.y == tabCube[i].position.y && head.position.z == tabCube[i].position.z) {
return true;
}
}
return false;
}
function ajoutCubeEnQueue(tail) {
var l = tabCube.length;
tabCube.push(new THREE.Mesh(new THREE.CubeGeometry(largeur, largeur, largeur), new THREE.MeshNormalMaterial({color: 0x0000ff, wireframe: false})) );
tabCube[l].position.x = tail.position.x;
tabCube[l].position.y = tail.position.y;
tabCube[l].position.z = tail.position.z;
scene.add(tabCube[l]);
}
function aleatoire() {
var pos;
if(Math.random() > 0.5) {
pos = Math.floor(Math.random()*10)*largeur;
} else {
pos = -Math.ceil(Math.random()*10)*largeur;
}
return pos;
}
function positionAleatoireBonbon() {
var posX = aleatoire();
var posY = aleatoire();
var posZ = aleatoire();
for(i = 0; i < tabCube.length; i++) {
if(posX == tabCube[i].position.x && posY == tabCube[i].position.y && posZ == tabCube[i].position.z) {
positionAleatoireBonbon();
}
}
bonbon.position.x = posX;
bonbon.position.y = posY;
bonbon.position.z = posZ;
}
|
// --------------------
// toposort extended
// Tests
// --------------------
// modules
var chai = require('chai'),
expect = chai.expect,
toposort = require('../lib/');
// init
chai.config.includeStack = true;
// tests
/* jshint expr: true */
/* global describe, it */
describe('toposort', function() {
it('sorts strings', function() {
var sorted = toposort([
['Ingredient', 'Shop'],
['Food', 'Ingredient']
]);
expect(sorted).to.deep.equal(['Food', 'Ingredient', 'Shop']);
});
it('sorts objects', function() {
var sorted = toposort([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ]
]);
expect(sorted).to.deep.equal([ { table: 'Food' }, { table: 'Ingredient' }, { table: 'Shop' } ]);
});
it('throws error on cyclic dependency', function() {
expect(function() {
toposort([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ],
[ { table: 'Shop' }, { table: 'Food' } ]
]);
}).to.throw(toposort.Error, 'Cyclic dependency: {"table":"Food"}');
});
});
describe('toposort.dependents', function() {
it('sorts strings', function() {
var sorted = toposort.dependents([
['Ingredient', 'Shop'],
['Food', 'Ingredient']
]);
expect(sorted).to.deep.equal(['Food', 'Ingredient']);
});
it('sorts objects', function() {
var sorted = toposort.dependents([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ]
]);
expect(sorted).to.deep.equal([ { table: 'Food' }, { table: 'Ingredient' } ]);
});
it('throws error on cyclic dependency', function() {
expect(function() {
toposort.dependents([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ],
[ { table: 'Shop' }, { table: 'Food' } ]
]);
}).to.throw(toposort.Error, 'Cyclic dependency: {"table":"Food"}');
});
});
|
import 'bootstrap';
import '../../src/scss/index.scss';
import profile from '../../src/img/portrait-medium.jpg';
const img = document.getElementById('profile');
if (img) {
img.src = profile;
}
|
import React, {
Component,
View,
StyleSheet,
Text,
TouchableHighlight,
PropTypes,
NativeModules,
DeviceEventEmitter
} from 'react-native';
import { login, logout, getCredentials, liEvents} from './util';
import styles from './theme/style';
const Icon = require('react-native-vector-icons/FontAwesome');
export default class LILoginMock extends Component {
constructor(props) {
super(props);
this.willUnmountSoon = false;
this.state = {
credentials: null,
subscriptions: []
};
}
handleLogin() {
login(this.props.appDetails).then((data) => {
if (!this.willUnmountSoon) this.setState({ credentials : data });
}).catch((err) => {
if (!this.willUnmountSoon) this.setState({ credentials : null });
})
}
handleLogout() {
logout().then((data) => {
if (!this.willUnmountSoon) this.setState({ credentials : null });
}).catch((err) => {
console.warn(err);
})
}
onPress() {
this.state.credentials
? this.handleLogout()
: this.handleLogin();
this.props.onPress && this.props.onPress();
}
invokeHandler(eventType, eventData) {
const eventHandler = this.props["on" + eventType];
if (typeof eventHandler === 'function') eventHandler(eventData);
}
componentWillMount() {
this.willUnmountSoon = false;
const subscriptions = this.state.subscriptions;
Object.keys(liEvents).forEach((eventType) => {
let sub = DeviceEventEmitter.addListener( liEvents[eventType], this.invokeHandler.bind(this, eventType) );
subscriptions.push(sub);
});
// Add listeners to state
this.setState({ subscriptions : subscriptions });
}
unSubscribeEvents(subscription) {
subscription.remove();
}
componentWillUnmount() {
this.willUnmountSoon = true;
this.state.subscriptions.forEach(this.unSubscribeEvents);
}
componentDidMount() {
getCredentials().then((data)=>{
this.setState({ credentials : data });
}).catch((err) =>{
this.setState({ credentials : null });
console.log('Request failed: ', err);
});
}
prepareStyle() {
const { style ={} } = this.props;
const LILMText = style.LILMText || styles.LILMText;
const LILMTextLoggedIn = style.LILMTextLoggedIn || styles.LILMTextLoggedIn;
const LILMTextLoggedOut = style.LILMTextLoggedOut || styles.LILMTextLoggedOut;
return {
LILMButton: style.LILMButton || styles.LILMButton,
LILMButtonContent: style.LILMButtonContent || styles.LILMButtonContent,
LILMIconWrap: style.LILMIconWrap || styles.LILMIconWrap,
LILMIcon: style.LILMIcon || styles.LILMIcon,
LILMTextWrap: style.LILMTextWrap || styles.LILMTextWrap,
LILMText: [LILMText, this.state.credentials ? LILMTextLoggedIn : LILMTextLoggedOut],
}
}
render() {
const { loginText = "Log in with Linkedin", logoutText = "Log out"} = this.props;
const text = this.state.credentials ? logoutText : loginText;
const { LILMButton, LILMButtonContent, LILMIconWrap, LILMIcon, LILMTextWrap, LILMText} = this.prepareStyle();
return (
<TouchableHighlight style={ LILMButton } onPress={this.onPress.bind(this)}>
<View style={LILMButtonContent}>
<View style={ LILMIconWrap }>
<Icon name="linkedin" style={ LILMIcon }/>
</View>
<View style={ LILMTextWrap }>
<Text style={ LILMText } numberOfLines={1}>{text}</Text>
</View>
<View style={ LILMIconWrap }></View>
</View>
</TouchableHighlight>
);
}
}
/**
*
* appDetails: {
* redirectUrl, // optional
* clientId, // client id
* clientSecret, // client secret
* state, // some unique string that is hard to guess
* scopes // an array of permissions / scores your app will request access to.
* }
*
*/
LILoginMock.propTypes = {
styleOverride: PropTypes.object,
appDetails: PropTypes.object,
loginText: PropTypes.string,
logoutText: PropTypes.string,
onPress: PropTypes.func,
onLogin: PropTypes.func,
onLoginError: PropTypes.func,
onRequestSucess: PropTypes.func,
onRequestError: PropTypes.func
};
|
(function(){
'use strict';
angular
.module('users')
.controller('EmailChangeCtrl', ['$rootScope', '$scope', '$state', '$location', '$translate', 'restFulService', 'config', 'errorService', function($rootScope, $scope, $state, $location, $translate, restFulService, config, errorService){
$scope.show = {
message: false
};
// Si falta alguno de los 3 parametros
if ($state.params.token === '' || $state.params.tokenId === '' || $state.params.userId === '')
$location.path('error');
// Se valida que el token exista en la DB
restFulService.get('emailChange/validate/' + $state.params.token +'/'+ $state.params.tokenId +'/'+ $state.params.userId)
.then(function(response){
$scope.email = response.email;
$rootScope.user.email = response.email;
$scope.show.message = true;
})
.catch(function(err){
$location.path('error/' + err.status);
});
}]);
}());
|
import Vue from 'vue'
import * as types from './mutation-types'
export default {
[types.PUT] (state, { key, value }) {
Vue.set(state, key, value)
},
[types.REMOVE] (state, { key }) {
Vue.delete(state, key)
},
[types.SYNC] (state, { records }) {
// Delete existing keys - Cognito datastore is the source of truth
for (const key in state) {
Vue.delete(state, key)
}
// Assign keys from Cognito datastore
for (const record of records) {
if (!record.value) continue
Vue.set(state, record.key, record.value)
}
}
}
|
'use strict';
describe('Service: scenarioFactory', function () {
// load the service's module
beforeEach(module('testerApp'));
// instantiate service
var scenarioFactory;
beforeEach(inject(function (_scenarioFactory_) {
scenarioFactory = _scenarioFactory_;
}));
it('should do something', function () {
expect(!!scenarioFactory).toBe(true);
});
});
|
const _ = require('lodash');
module.exports = () => (hook) => {
const sequelize = hook.app.get('sequelize');
const eventId = hook.result.id;
const quotasToAdd = hook.data.quota.map(quota => _.merge(quota, { eventId }));
const quotaModel = hook.app.get('models').quota;
return sequelize.transaction(t => {
return quotaModel.destroy({
where: { eventId }
}, { transaction: t }).then(() => {
return quotaModel.bulkCreate(quotasToAdd, { updateOnDuplicate: true }, { transaction: t })
.then(() => {
return quotaModel.findAll({
where: {
eventId,
deletedAt: null
},
order: [
['sortId', 'ASC'],
],
include: [{
attributes: ['firstName', 'lastName', 'email', 'createdAt'],
model: sequelize.models.signup,
required: false
}]
}, { transaction: t });
});
});
}).then((quota) => {
hook.result.dataValues.quota = quota;
return hook;
}).catch((error => {
throw new Error('Quota update failed:', error);
}));
};
|
'use strict';
/**
* @ngdoc function
* @name teamDjApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the teamDjApp
*/
angular.module('teamDjApp')
.controller('AboutCtrl', function ($rootScope) {
$rootScope.activetab = 'about';
});
|
module("Unit - Party",{
setup: function(){
var mod = this;
Ember.run(this,function(){
var appController = App.__container__.lookup("controller:application") ;
mod.appC = appController ;
mod.store = appController.store ;
resetTests(mod.store).then(function(){
mod.baseParty = mod.store.createRecord('party',{
name: 'baseparty',
size: 2,
phone_number: '3125551212',
time_taken: '2013-11-05T20:15:15'
}) ;
}) ;
}) ;
wait() ;
},
teardown: function(){
destroy(this.store, this.appC) ;
return wait() ;
}
}) ;
asyncTest("party.notified", 2, function() {
var party = this.baseParty;
equal(false, party.get('notified'), "initially, party.notified should be false") ;
Ember.run(function(){
party.set('time_notified', '2013-11-05T20:35:15') ;
equal(true, party.get('notified'), "after setting time_notified, party.notified should be true") ;
start() ;
});
});
asyncTest("party.seated", 2, function() {
var party = this.baseParty;
equal(false, party.get('seated'), "initially, party.seated should be false") ;
Ember.run(function(){
party.set('time_seated', '2013-11-05T20:35:15') ;
equal(true, party.get('seated'), "after setting time_seated, party.seated should be true") ;
start() ;
});
});
asyncTest("party.waiting depends on party.time_seated", 3, function() {
var party = this.baseParty;
equal(true, party.get('waiting'), "initially, party.waiting should be true") ;
Ember.run(function(){
party.set('time_seated', '2013-11-05T20:35:15') ;
equal(false, party.get('waiting'), "after setting time_seated, party.waiting should be false") ;
party.set('time_seated', null) ;
equal(true, party.get('waiting'), "after setting time_seated to null, party.waiting should be true") ;
start() ;
});
});
asyncTest("party.waiting depends on party.time_cancelled", function() {
var party = this.baseParty;
equal(party.get('waiting'), true, "initially, party.waiting should be true") ;
Ember.run(function(){
party.set('time_cancelled', '2013-11-05T20:35:15') ;
equal(party.get('waiting'), false, "after setting time_cancelled, party.waiting should be false") ;
party.set('time_cancelled', null) ;
equal(party.get('waiting'), true, "after setting time_cancelled to null, party.waiting should be true") ;
start() ;
});
});
asyncTest("party.waiting depends on party.time_cancelled and party.time_seated", function() {
var party = this.baseParty;
equal(party.get('waiting'), true, "initially, party.waiting should be true") ;
Ember.run(function(){
party.set('time_seated', '2013-11-05T20:35:15') ;
equal(party.get('waiting'), false, "after setting time_seated, party.waiting should be false") ;
party.set('time_cancelled', '2013-11-05T20:40:15') ;
equal(party.get('waiting'), false, "after setting time_cancelled, party.waiting should still be false") ;
party.set('time_cancelled', null) ;
equal(party.get('waiting'), false, "after setting time_cancelled to null, party.waiting should still be false") ;
party.set('time_seated', null) ;
equal(party.get('waiting'), true, "after setting time_seated and time_cancelled to null, party.waiting should be true") ;
start() ;
});
});
asyncTest("party.countdown should count down seconds", function(){
var party = this.baseParty ;
var now = moment() ;
Ember.run(function(){
party.set('time_notified',now.subtract('minute',1).format("YYYY-MM-DDTHH:mm:ss")) ;
var rem = Math.round(party.get('countdown')/1000) ;
ok(Math.abs(rem-(4*60)) <= 1, "countdown should equal 4 min give or take a second") ;
start() ;
});
}) ;
asyncTest("party.countdown should count up if negative", function(){
var party = this.baseParty ;
Ember.run(function(){
var now = moment() ;
party.set('time_notified',now.subtract('minute',7).format("YYYY-MM-DDTHH:mm:ss")) ;
var rem = Math.round(party.get('countdown')/1000) ;
ok(Math.abs(rem-(2*60)) <= 1, "countup should equal 2 min give or take a second") ;
});
Ember.run(function(){
var now = moment() ;
party.set('time_notified',now.subtract('minute',9).format("YYYY-MM-DDTHH:mm:ss")) ;
var rem = Math.round(party.get('countdown')/1000) ;
ok(Math.abs(rem-(4*60)) <= 1, "countup should equal 4 min give or take a second") ;
start() ;
});
}) ;
asyncTest("party.overdue", function(){
var party = this.baseParty ;
var now = moment() ;
equal(party.get('overdue'), false, "Party should not be initially overdue") ;
Ember.run(function(){
party.set('time_notified',now.subtract('minute',3).format("YYYY-MM-DDTHH:mm:ss")) ;
equal(party.get('overdue'), false, "Party should not be overdue at 3 min") ;
});
Ember.run(function(){
party.set('time_notified',now.subtract('minute',7).format("YYYY-MM-DDTHH:mm:ss")) ;
equal(party.get('overdue'), true, "Party should be overdue at 7 min") ;
start() ;
});
}) ;
|
/** @jsx jsx */
import { Editor } from 'slate'
import { jsx } from '../../..'
export const run = editor => {
Editor.delete(editor, { reverse: true })
}
export const input = (
<editor>
<block>Hello</block>
<block>
<block>
<cursor />
world!
</block>
</block>
</editor>
)
export const output = (
<editor>
<block>
Hello
<cursor />
world!
</block>
</editor>
)
|
/*******************************************************************************
* bars coming out from a circle
*/
function VizRadialBars(variant) {
this.dampen = true;
this.hasVariants = true;
this.variants = [[false], [true]];
this.vary(variant);
}
VizRadialBars.prototype.resize = function() {}
VizRadialBars.prototype.vary = function(variant) {
this.variant = variant;
this.fade = this.variants[variant][0];
}
VizRadialBars.prototype.draw = function(spectrum) {
ctx.save();
ctx.clearRect(0, 0, cv.width, cv.height)
ctx.translate(cv.width / 2, cv.height / 2);
ctx.rotate(allRotate);
for (var i = 0; i < bandCount; i++) {
ctx.rotate(rotateAmount);
var hue = Math.floor(360.0 / bandCount * i);
if (this.fade) {
var brightness = constrain(Math.floor(spectrum[i] / 1.5), 25, 99);
ctx.fillStyle = bigColorMap[hue * 100 + brightness];
ctx.fillRect(-bandWidth / 2, centerRadius, bandWidth,
Math.max(2, spectrum[i] * heightMultiplier));
} else {
var avg = 0;
avg = (spectrum[i] + lastVolumes[i]) / 2;
ctx.fillStyle = bigColorMap[hue * 100 + 50];
ctx.fillRect(-bandWidth / 2, centerRadius + avg, bandWidth, 2);
ctx.fillStyle = bigColorMap[hue * 100 + 99];
ctx.fillRect(-bandWidth / 2, centerRadius, bandWidth,
spectrum[i] * heightMultiplier);
}
}
allRotate += 0.002;
ctx.restore();
}
|
// line comment
// line comment with prefix space
/**
* block comment
*/
function test () {
var a = 'ok'
var error
}
|
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { isBlank } from '@ember/utils';
export default Route.extend({
/**
Service that get current project contexts.
@property currentProjectContext
@type {Class}
@default service()
*/
currentProjectContext: service('fd-current-project-context'),
/**
List exist subsystems.
@property subsystems
@type Array
*/
subsystems: undefined,
/**
A hook you can implement to convert the URL into the model for this route.
[More info](http://emberjs.com/api/classes/Ember.Route.html#method_model).
@method model
*/
model: function() {
const subsystems = this.get('subsystems');
const stage = this.get('currentProjectContext').getCurrentStage();
const adapter = this.get('store').adapterFor('application');
const data = { 'project': stage, 'moduleSettingTypes': subsystems };
return adapter.callAction('GetCurrentModuleSettings', data, null, { withCredentials: true }).then((subsystemsSettings) => {
let currentSubsystemsSettings = JSON.parse(subsystemsSettings.value);
let updateSubsystemsSettings = {};
for (let prop in currentSubsystemsSettings) {
let value = currentSubsystemsSettings[prop];
let newValue = !isBlank(value) ? JSON.parse(value) : {};
updateSubsystemsSettings[prop] = newValue;
}
return updateSubsystemsSettings;
});
},
init() {
this._super(...arguments);
this.set('subsystems', ['GisSubsystemSettings'/*, 'SecuritySubsystemSettings', 'AuditSubsystemSettings'*/]);
},
/**
A hook you can use to setup the controller for the current route.
[More info](https://www.emberjs.com/api/ember/release/classes/Route/methods/setupController?anchor=setupController).
@method setupController
@param {<a href="https://emberjs.com/api/ember/release/classes/Controller">Controller</a>} controller
*/
setupController(controller) {
this._super(...arguments);
controller.set('routeName', this.get('routeName'));
}
});
|
var searchData=
[
['incomelinks',['incomeLinks',['../classDAGraphNode.html#abdf9c01751f27d2294ce2bd00f197778',1,'DAGraphNode']]]
];
|
import layout from '../templates/components/input-for';
import FormControl from './form-control';
import Ember from 'ember';
const {
get,
set,
isPresent,
computed
} = Ember;
export default FormControl.extend({
layout,
classNameBindings: ['hasValue'],
init() {
this._super(...arguments);
let field = get(this, 'field');
this.hasValue = computed(`data.${field}`, 'placeholder', () => {
if (isPresent(get(this, 'placeholder'))) {
return true;
}
return isPresent(get(this, `data.${field}`));
});
},
didReceiveAttrs() {
this._super(...arguments);
if (!get(this, 'type')) {
set(this, 'type', 'text');
}
}
});
|
"use strict";
(function () {
var app = angular.module("storeProducts", []);
app.directive("productTitle", function () {
return {
restrict: "A",
templateUrl: "product-title.html"
}
});
app.directive("productDescription", function () {
return {
restrict: "E",
templateUrl: "product-description.html"
}
});
app.directive("productSpecs", function () {
return {
restrict: "E",
templateUrl: "product-specs.html"
}
});
app.directive("productReviews", function () {
return {
restrict: "E",
templateUrl: "product-reviews.html"
}
});
app.directive("productReviewsForm", function () {
return {
restrict: "E",
templateUrl: "product-reviews-form.html"
}
});
app.directive("productPanels", function () {
return {
restrict: "E",
templateUrl: "product-panels.html",
controller: function () {
this.tab = 1;
this.setTab = function (setTab) {
this.tab = setTab;
};
this.isSet = function (setValue) {
return this.tab === setValue;
};
this.setActive = function (activeValue) {
return this.tab === activeValue;
};
},
controllerAs: "navTab"
}
});
app.directive("productGallery", function () {
return {
restrict: "E",
templateUrl: "product-gallery.html",
controller: function () {
this.currentImage = 0;
this.setCurrent = function (currentValue) {
this.currentImage = currentValue || 0;
};
this.toggleCurrent = function (toggleValue) {
if (this.currentImage === toggleValue) {
return false;
}
this.currentImage = toggleValue || 0;
};
this.setActive = function (activeValue) {
return this.currentImage === activeValue;
};
},
controllerAs: "gallery"
}
});
app.directive("productButton", function () {
return {
restrict: "E",
templateUrl: "product-button.html"
};
});
})();
|
var diff = require('../');
var left = {
left: 'yes',
right: 'no',
};
var right = {
left: {
toString: true,
},
right: 'no',
};
console.log(diff(left, right)); // eslint-disable-line no-console
|
/*
* This file is part of the hyyan/woo-poly-integration plugin.
* (c) Hyyan Abo Fakher <tiribthea4hyyan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
(function ($, document, HYYAN_WPI_VARIABLES) {
/**
* Construct variables
*
* @param {jQuery} $
* @param {document} document
* @param {object} data
*
* @returns {Variables}
*/
var Variables = function ($, document, data) {
this.$ = $;
this.document = document;
this.data = data;
this._dialog = this._createDialog();
};
Variables.prototype = {
/** Constructor */
constructor: Variables,
init: function () {
var self = this;
$('#post_lang_choice').change(function () {
self.shouldAlert();
});
$('#product-type').change(function () {
self.shouldAlert();
});
}
/**
* Check if we should alert the user
*
* @returns {Boolean}
*/
, shouldAlert: function () {
var type = this.getCurrentProduct();
var lang = this.getCurrentLanguage();
if (type === 'variable' && lang !== this.data['defaultLang']) {
this._dialog.dialog('open');
/* Disable Saving */
this._changeSaveBoxState(true);
return true;
}
this._changeSaveBoxState(false);
return false;
}
/**
* Get current product language
*
* @returns {String}
*/
, getCurrentLanguage: function () {
return this.$('#post_lang_choice').val();
}
/**
* Get current product type
*
* @returns {string}
*/
, getCurrentProduct: function () {
return this.$('#product-type').val();
}
/**
* Change the state of save box from disable to enable and vs
*
* @param {boolean} enable
*/
, _changeSaveBoxState: function (enable) {
this.$('#submitdiv *').attr('disabled', enable);
}
/**
* Create dialog
*
* @returns {objet}
*/
, _createDialog: function () {
/* This variable */
var self = this;
/* Fix the z-index */
this.$('<style>.ui-dialog { z-index: 1000 !important ;}</style>')
.appendTo($('head'));
/* Create dialog */
var dialog = this.$("<div id='woo-poly-variables-dialog'/>")
.html('<p>' + self.data['content'] + '</p>')
.attr('title', self.data['title'])
.appendTo("body");
dialog.dialog({
dialogClass: "wp-dialog",
autoOpen: false,
modal: true,
width: 400,
height: 250,
position: {
my: "center",
at: "center"
},
buttons: [
{
text: 'Got It',
click: function () {
$(this).dialog('close');
}
}
]
});
return dialog;
}
};
// bootstrap
$(document).ready(function ($) {
new Variables($, document, HYYAN_WPI_VARIABLES).init();
});
})(jQuery, document, HYYAN_WPI_VARIABLES);
|
ml.module('three.extras.objects.ImmediateRenderObject')
.requires('three.Three',
'three.core.Object3D')
.defines(function(){
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ImmediateRenderObject = function ( ) {
THREE.Object3D.call( this );
this.render = function ( renderCallback ) { };
};
THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
});
|
const initialState = {
types: [],
running: [],
performatives: []
}
const reduce = (state = initialState, action) => {
switch (action.type) {
case 'ADD_TYPES':
return {
...state,
types: [...state.types, ...action.types]
};
case 'ADD_RUNNING':
return {
...state,
running: [...state.running, ...action.runningAgents]
};
case 'UPDATE_TYPES':
return {
...state,
types: action.types
};
case 'UPDATE_RUNNING':
return {
...state,
running: action.running
};
case 'START_AGENT':
return {
...state,
running: [...state.running, action.agent]
};
case 'STOP_AGENT':
const running = state.running.filter(agent => agent.id.name !== action.name);
return {
...state,
running
};
case 'SET_PERFORMATIVES':
return {
...state,
performatives: action.performatives
}
default:
return state;
}
};
export default reduce;
|
module.exports = require('material-ui/Dialog');
|
// Generated by CoffeeScript 1.10.0
var EsyFile;
EsyFile = (function() {
function EsyFile() {}
EsyFile.prototype["delete"] = function(filepath) {
var file;
if (File(filepath)) {
file = File(filepath);
}
return file.remove();
};
EsyFile.prototype.append = function(filepath, content) {
var file;
file = File(filepath);
file.open("a");
file.write(content);
file.close();
return file;
};
EsyFile.prototype.buildExtendScript = function(filepath, destinations) {
var content, destination, i, len, read, results;
content = this.read(filepath);
content = content.replace("debug = true", "debug = false");
read = (function(_this) {
return function(str, p1) {
return _this.read((_this.path(filepath)) + "/" + p1);
};
})(this);
content = content.replace(/#include \"(.*)\";/g, read);
if (typeof destinations === "string") {
destinations = [destinations];
}
results = [];
for (i = 0, len = destinations.length; i < len; i++) {
destination = destinations[i];
results.push(this.create("" + (destination.toString()), content));
}
return results;
};
EsyFile.prototype.create = function(filepath, content, overwrite) {
var file;
if (content == null) {
content = "";
}
if (overwrite == null) {
overwrite = true;
}
if (overwrite) {
this["delete"](filepath);
}
file = File(filepath);
file.open("w");
file.write(content);
file.close();
return file;
};
EsyFile.prototype.exists = function(filepath) {
var file;
file = File(filepath);
if (file.created) {
return file;
} else {
return false;
}
};
EsyFile.prototype.read = function(filepath) {
var content, file;
file = File(filepath);
file.open("r");
content = file.read();
file.close();
return content;
};
EsyFile.prototype.folderName = function(filepath) {
var folderName;
folderName = this.filename(filepath);
return folderName;
};
EsyFile.prototype.fileName = function(filepath) {
var filename;
filename = filepath.substr(filepath.lastIndexOf('/') + 1);
return filename;
};
EsyFile.prototype.path = function(filepath) {
var filename;
filename = filepath.substr(0, filepath.lastIndexOf('/'));
return filename;
};
return EsyFile;
})();
|
'use strict';
module.exports = {
'+': 'Pass',
'-': 'Fail',
'~': 'SoftFail',
'?': 'Neutral'
};
|
'use strict';
// Test specific configuration
// ===========================
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://localhost/conversionrobot-test'
}
};
|
window.ProseMirror = require("prosemirror/dist/edit").ProseMirror
require("prosemirror/dist/menu/menubar") // Load menubar module
require( "prosemirror/dist/markdown/to_markdown" )
require( "prosemirror/dist/markdown/from_markdown" )
window.ProseMirrorUtils = {};
window.ProseMirrorUtils.defaultschema = require( "prosemirror/dist/model/defaultschema")
window.ProseMirrorUtils.schema = require( "prosemirror/dist/model/schema")
window.ProseMirrorUtils.commandSet = require( "prosemirror/dist/edit/command").CommandSet
window.ProseMirrorUtils.menu = require ( "prosemirror/dist/menu/menu" )
|
const SHADERS = require('../chunks/index.js')
module.exports = /* glsl */ `
precision highp float;
${SHADERS.math.PI}
${SHADERS.sky}
${SHADERS.rgbm}
${SHADERS.gamma}
${SHADERS.encodeDecode}
uniform vec3 uSunPosition;
varying vec2 vTexCoord0;
uniform bool uRGBM;
void main() {
//Texture coordinates to Normal is Based on
//http://gl.ict.usc.edu/Data/HighResProbes/
// u=[0,2], v=[0,1],
// theta=pi*(u-1), phi=pi*v
// (Dx,Dy,Dz) = (sin(phi)*sin(theta), cos(phi), -sin(phi)*cos(theta)).
float u = vTexCoord0.x;
float v = 1.0 - vTexCoord0.y; // uv's a Y flipped in WebGL
float theta = PI * (u * 2.0 - 1.0);
float phi = PI * v;
float x = sin(phi) * sin(theta);
float y = cos(phi);
float z = -sin(phi) * cos(theta);
vec3 N = vec3(x, y, z);
vec3 color = sky(uSunPosition, N);
if (uRGBM) {
gl_FragColor = encodeRGBM(color);
} else {
gl_FragColor.rgb = color;
gl_FragColor.a = 1.0;
}
}
`
|
import estap from '../../lib';
const test = estap();
estap.disableAutorun();
test('should pass', t => {
t.pass();
});
|
import { connect } from 'react-redux'
import SignUpForm from '../components/SignUpForm'
import { signUpUser } from '../actions/SignUpFormActions'
const mapStateToProps = (state, ownProps) => {
return {}
}
const mapDispatchToProps = (dispatch) => {
return {
onSignUpFormSubmit: (name) => {
event.preventDefault();
dispatch(signUpUser(name))
}
}
}
const SignUpFormContainer = connect(
mapStateToProps,
mapDispatchToProps
)(SignUpForm)
export default SignUpFormContainer
|
Ember.TEMPLATES["unit-controllers"] = Ember.Handlebars.compile(
'<div class="unit-controllers">{{render "rendered" someModel className="asd"}}</div>'
);
//--------------------------------------------------------------------------
module("templates - controllers - full environment", {
setup: function() {
var container = new Ember.Container();
container.register("template:rendered", Ember.Handlebars.compile("controller stub"), {instantiate: false});
container.register("view:rendered", Ember.View);
container.register("controller:rendered", Ember.Controller);
var view = Ember.View.create({
controller: Ember.Controller.create({
container: container
}),
template: Ember.TEMPLATES["unit-controllers"]
});
Ember.run(function() {
view.appendTo("#qunit-fixture");
});
}
});
test("template renders correctly", function() {
equal(Ember.$("#qunit-fixture .unit-controllers").text(), "controller stub");
});
module("templates - controllers - stubbing helper", {
setup: function() {
sinon.stub(Ember.Handlebars.helpers, 'render').returns(new Handlebars.SafeString("controller stub"));
var view = Ember.View.create({
template: Ember.TEMPLATES["unit-controllers"]
});
Ember.run(function() {
view.appendTo("#qunit-fixture");
});
}
});
test("template renders correctly", function() {
equal(Ember.$("#qunit-fixture .unit-controllers").text(), "controller stub");
});
|
'use babel'
import util from 'util'
import { exec } from 'child_process'
import applescript from 'applescript'
import { Errors } from './constants'
const runscript = (file) => new Promise((resolve, reject) => {
applescript.execFile(file, (error, result) => {
if (error) { reject(error) }
try {
if (result) {
resolve(JSON.parse(result))
} else {
reject(new Error(Errors.NO_DATA))
}
} catch (e) {
reject(new Error(Errors.JSON_PARSE_ERROR))
}
});
})
const getState = () => runscript(`${__dirname}/scripts/getState.applescript`)
const getTrack = () => runscript(`${__dirname}/scripts/getTrack.applescript`)
export default {
getState,
getTrack
}
|
/*!
* CanJS - 2.2.5
* http://canjs.com/
* Copyright (c) 2015 Bitovi
* Wed, 22 Apr 2015 15:03:29 GMT
* Licensed MIT
*/
/*can@2.2.5#view/elements*/
var can = require('../util/util.js');
require('./view.js');
var doc = typeof document !== 'undefined' ? document : null;
var selectsCommentNodes = doc && function () {
return can.$(document.createComment('~')).length === 1;
}();
var elements = {
tagToContentPropMap: {
option: doc && 'textContent' in document.createElement('option') ? 'textContent' : 'innerText',
textarea: 'value'
},
attrMap: can.attr.map,
attrReg: /([^\s=]+)[\s]*=[\s]*/,
defaultValue: can.attr.defaultValue,
tagMap: {
'': 'span',
colgroup: 'col',
table: 'tbody',
tr: 'td',
ol: 'li',
ul: 'li',
tbody: 'tr',
thead: 'tr',
tfoot: 'tr',
select: 'option',
optgroup: 'option'
},
reverseTagMap: {
col: 'colgroup',
tr: 'tbody',
option: 'select',
td: 'tr',
th: 'tr',
li: 'ul'
},
getParentNode: function (el, defaultParentNode) {
return defaultParentNode && el.parentNode.nodeType === 11 ? defaultParentNode : el.parentNode;
},
setAttr: can.attr.set,
getAttr: can.attr.get,
removeAttr: can.attr.remove,
contentText: function (text) {
if (typeof text === 'string') {
return text;
}
if (!text && text !== 0) {
return '';
}
return '' + text;
},
after: function (oldElements, newFrag) {
var last = oldElements[oldElements.length - 1];
if (last.nextSibling) {
can.insertBefore(last.parentNode, newFrag, last.nextSibling);
} else {
can.appendChild(last.parentNode, newFrag);
}
},
replace: function (oldElements, newFrag) {
elements.after(oldElements, newFrag);
if (can.remove(can.$(oldElements)).length < oldElements.length && !selectsCommentNodes) {
can.each(oldElements, function (el) {
if (el.nodeType === 8) {
el.parentNode.removeChild(el);
}
});
}
}
};
can.view.elements = elements;
module.exports = elements;
|
import Resolver from 'ember/resolver';
var CustomResolver = Resolver.extend({
moduleNameLookupPatterns: Ember.computed(function() {
var defaults = this._super();
return defaults.concat([
this.podBasedComponentsInResource
]);
}),
podBasedComponentsInResource: function(parsedName) {
var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix;
if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) {
var nameWithoutComponent = parsedName.fullNameWithoutType.replace(/components\//, '');
var slash = nameWithoutComponent.lastIndexOf('/');
if (slash > 0) {
podPrefix = podPrefix + "/" + nameWithoutComponent.substr(0, slash);
parsedName.fullNameWithoutType = nameWithoutComponent.substr(slash + 1);
return this.podBasedLookupWithPrefix(podPrefix, parsedName);
}
}
},
podBasedComponentsInSubdir: function(parsedName) {
var podPrefix = this.namespace.modulePrefix; // this.namespace.podModulePrefix || this.namespace.modulePrefix
podPrefix = podPrefix + '/components';
if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) {
return this.podBasedLookupWithPrefix(podPrefix, parsedName);
}
}
});
export default CustomResolver
|
import Element from '../../../shared/Element';
import Elements from '../../../shared/Elements';
import link from '../../../shared/link';
import { isNormalElement } from '../../../shared/helper';
export function createElements(elements, parent) {
elements.forEach(
element => appendElement(element, parent)
);
return parent;
}
export function appendElement(element, parent) {
parent.appendChild(createElement(element, parent));
}
export function createElement(element) {
const {props, tag, children} = element;
let node;
if (Element.isInstance(element)) {
node = document.createElement(tag);
createElements(children, node); // children
if (isNormalElement(element)) { // only link normal nodes
link(node, element);
}
setProps(node, {
tag, type: props.type , props
}); // props
} else if (Elements.isInstance(element)) {
const node = document.createDocumentFragment(); // package
createElements(element, node);
} else {
node = document.createTextNode(element);
}
return node;
}
const acceptValue = (tag) => ['input', 'textarea', 'option', 'select', 'progress'].includes(tag);
const mustUseProp = (tag, type, attr) => (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
);
export function setProps(node, {tag, type, props}) {
Object.keys(props).forEach((name) => {
if (mustUseProp(tag, type, name)) {
node[name] = props[name];
} else {
node.setAttribute(name, props[name]);
}
});
}
export function setStyle(node, styles) {
Object.assign(node.style, styles);
}
|
(function () {
'use strict';
angular
.module('mainApp', []);
})();
|
const Rebase = require('../../../src/rebase');
const React = require('react');
const ReactDOM = require('react-dom');
const firebase = require('firebase');
require('firebase/firestore');
var dummyCollection = require('../../fixtures/dummyCollection');
var firebaseConfig = require('../../fixtures/config');
describe('get()', function() {
var base;
var testApp;
var collectionPath = 'testCollection';
var collectionRef;
var app;
function seedCollection() {
const docs = dummyCollection.map((doc, index) => {
const docRef = collectionRef.doc(`doc-${index + 1}`);
return docRef.set(doc);
});
return Promise.all(docs);
}
beforeAll(() => {
testApp = firebase.initializeApp(firebaseConfig, 'DB_CHECK');
collectionRef = testApp.firestore().collection(collectionPath);
var mountNode = document.createElement('div');
mountNode.setAttribute('id', 'mount');
document.body.appendChild(mountNode);
});
afterAll(done => {
var mountNode = document.getElementById('mount');
mountNode.parentNode.removeChild(mountNode);
testApp.delete().then(done);
});
beforeEach(done => {
app = firebase.initializeApp(firebaseConfig);
var db = firebase.firestore(app);
base = Rebase.createClass(db);
seedCollection().then(done);
});
afterEach(done => {
ReactDOM.unmountComponentAtNode(document.body);
Promise.all([
collectionRef.get().then(docs => {
const deleteOps = [];
docs.forEach(doc => {
deleteOps.push(doc.ref.delete());
});
return Promise.all(deleteOps);
}),
app.delete()
])
.then(done)
.catch(err => done.fail(err));
});
it('get() validates endpoint', done => {
try {
base.get('').then(() => {
done.fail('error should thrown');
});
} catch (err) {
expect(err).not.toBeNull(err);
done();
}
});
describe('Async tests', function() {
it('get() resolves with data from a collection', done => {
base
.get(collectionPath)
.then(data => {
expect(data.length).toEqual(5);
done();
})
.catch(err => done.fail(err));
});
it('get() resolves with data from a collection query', done => {
base
.get(`${collectionPath}`, {
query: ref =>
ref
.where('id', '<', 5)
.where('id', '>', 2)
.orderBy('id')
})
.then(data => {
expect(data.length).toEqual(2);
expect(data[0].name).toEqual('Document 3');
expect(data[1].name).toEqual('Document 4');
done();
})
.catch(err => done.fail(err));
});
it('get() rejects if collection query returns no results', done => {
base
.get(`${collectionPath}`, {
query: ref => ref.where('id', '>', 5).orderBy('id')
})
.then(data => {
done.fail('query should reject');
})
.catch(err => {
expect(err.message).toEqual('No Result');
done();
});
});
it('get() rejects if document does not exist', done => {
base
.get(`${collectionPath}/nodoc`)
.then(data => {
done.fail('query should reject');
})
.catch(err => {
expect(err.message).toEqual('No Result');
done();
});
});
it('get() resolves with a document', done => {
base
.get(`${collectionPath}/doc-1`)
.then(data => {
expect(data.name).toEqual(dummyCollection[0].name);
done();
})
.catch(err => done.fail(err));
});
it('get() accepts a document reference', done => {
const docRef = app
.firestore()
.collection('testCollection')
.doc('doc-1');
base
.get(docRef)
.then(data => {
expect(data.name).toEqual(dummyCollection[0].name);
done();
})
.catch(err => done.fail(err));
});
it('get() accepts a collection reference', done => {
const testRef = app.firestore().collection('testCollection');
base
.get(testRef)
.then(data => {
expect(data[0].name).toEqual(dummyCollection[0].name);
done();
})
.catch(err => done.fail(err));
});
it('get() rejects Promise when read fails or is denied', done => {
base
.get('/readFail')
.then(() => {
done.fail('Promise should reject');
})
.catch(err => {
expect(err.code).toContain('permission-denied');
done();
});
});
});
});
|
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://127.0.0.1:3000', // WebpackDevServer host and port
'webpack/hot/only-dev-server',
'./src/js/index.js' // Your appʼs entry point
],
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/static/'
},
module: {
loaders: [
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'},
{ test: /\.js?$/, loaders: ['react-hot', 'babel'], include: [path.join(__dirname, 'src/js')]}
]
},
resolve: {
root: [path.resolve(__dirname)],
extensions: ['', '.js', '.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
|
import { expect } from 'chai';
import request from '../src/reqwest-fetch';
/* eslint func-names: 0 */
/* eslint prefer-arrow-callback: 0 */
describe('reqwest-fetch', function () {
it('should accept json response', function () {
this.timeout(10000);
const test = request({ url: 'https://o.hahoo.cn/test.json' })
.then(function (res) {
expect(res.body).to.eql({ foo: 'bar' });
});
return test;
});
});
|
var db = require('../models');
function index(req, res) {
db.User.find({}, function(err, allUsers) {
//TODO: handle the errors.
// TODO: Send this array as a json object
res.json(allUsers);
});
}
function create(req, res) {
// TODO: Consider creating an obect literal then passing in that object rather than just the req.body
db.User.create(req.body, function(err, user) {
if (err) {
console.log('error', err);
}
// remove console logs from production
console.log(user);
res.json(user);
});
}
function destroy(req, res) {
db.User.findOneAndRemove({
_id: req.params.userId
}, function(err, foundUser) {
//TODO: Handle ERR
res.json(foundUser);
});
}
function update(req, res) {
// remove console logs from production
console.log('Updating user', req.body);
var updateUser = {
userName: req.body.userName,
email: req.body.email,
passwordDigest: req.body.passwordDigest,
}
db.User.findOneAndUpdate({_id: req.params.userId}, updateUser, function(err, foundUser) {
if (err) {console.log('usersController.update.error', err);}
res.json(foundUser);
});
}
module.exports = {
index: index,
create: create,
destroy: destroy,
update: update
};
|
angular.module('VoltronApp.services', []).
factory('voltronAPIservice', function($http)
{
var voltronAPI = {};
function createRequest(requestType, data) {
return {type: "request", request: requestType, data: data}
}
voltronAPI.request = function(request) {
return $http({
method: 'POST',
url: '/api/request',
data: request
});
}
voltronAPI.disassemble_format = function(data) {
res = voltronAPI.request(createRequest('disassemble', {address: address, count: count}))
return $http({
method: 'POST',
url: '/api/request',
data: createRequest('format_disasm', {disassembly: res.data.disassembly})
});
}
voltronAPI.disassemble = function(address, count) {
return voltronAPI.request(createRequest('disassemble', {address: address, count: count}))
}
voltronAPI.command = function(command) {
return voltronAPI.request(createRequest('command', {command: command}))
}
voltronAPI.targets = function() {
return voltronAPI.request(createRequest('targets', {}))
}
voltronAPI.memory = function(address, length) {
return voltronAPI.request(createRequest('memory', {address: address, length: length}))
}
voltronAPI.registers = function() {
return voltronAPI.request(createRequest('registers', {}))
}
voltronAPI.stack = function(length) {
return voltronAPI.request(createRequest('stack', {length: length}))
}
voltronAPI.state = function() {
return voltronAPI.request(createRequest('state', {}))
}
voltronAPI.version = function() {
return voltronAPI.request(createRequest('version', {}))
}
return voltronAPI;
});
|
define("#base/0.9.2/attrs-debug", ["./util"], function(require, exports) {
// Attrs
// -----------------
// Thanks to:
// - http://documentcloud.github.com/backbone/#Model
// - http://yuilibrary.com/yui/docs/api/classes/AttributeCore.html
// - https://github.com/berzniz/backbone.getters.setters
var Util = require('./util');
// 负责 attributes 的初始化
// attributes 是与实例相关的状态信息,可读可写,发生变化时,会自动触发相关事件
exports.initAttrs = function(config) {
// Keep existed attrs.
if (!this.hasOwnProperty('attrs')) {
this.attrs = {};
}
var attrs = this.attrs;
// Only merge all inherited attributes once.
if (!attrs.__defaults) {
attrs.__defaults = Util.getInherited(this, 'attrs', normalize);
Util.merge(attrs, attrs.__defaults);
}
var options = { silent: true };
for (var key in attrs) {
// only merge recognized attributes, and delete it from config
// after merged.
if (config && config.hasOwnProperty(key)) {
this.set(key, config[key], options);
delete config[key];
}
// automatically register `_onChangeX` method as
// 'change:x' handler.
var eventKey = getChangeEventKey(key);
if (this[eventKey]) {
this.on('change:' + key, this[eventKey]);
}
}
};
// Get the value of an attribute.
exports.get = function(key) {
var attr = this.attrs[key] || {};
var val = attr.value;
return attr.getter ? attr.getter.call(this, val, key) : val;
};
// Set a hash of model attributes on the object, firing `"change"` unless
// you choose to silence it.
exports.set = function(key, val, options) {
var attrs = {};
// set("key", val, options)
if (Util.isString(key)) {
attrs[key] = val;
}
// set({ "key": val, "key2": val2 }, options)
else {
attrs = key;
options = val;
}
options || (options = {});
var now = this.attrs;
var silent = options.silent;
for (key in attrs) {
var attr = now[key] || ( now[key] = {} );
val = attrs[key];
// invoke validator
if (attr.validator) {
var ex = attr.validator.call(this, val, key);
if (ex !== true) {
if (options.error) {
options.error.call(this, ex);
}
continue;
}
}
// invoke setter
if (attr.setter) {
val = attr.setter.call(this, val, key);
}
// set finally
var prev = this.get(key);
if (Util.isPlainObject(prev) && Util.isPlainObject(val)) {
val = Util.merge(Util.merge({}, prev), val);
}
now[key].value = val;
// invoke change event
if (!silent && this.trigger && prev !== val) {
this.trigger('change:' + key, val, prev, key);
}
}
};
// Helpers
// -------
var ATTR_SPECIAL_KEYS = ['value', 'getter', 'setter', 'validator'];
// normalize `attrs` to
//
// {
// value: 'xx',
// getter: fn,
// setter: fn,
// validator: fn
// }
//
function normalize(attrs) {
// clone it
attrs = Util.merge({}, attrs);
for (var key in attrs) {
var attr = attrs[key];
if (Util.isPlainObject(attr) &&
hasOwnProperties(attr, ATTR_SPECIAL_KEYS)) {
continue;
}
attrs[key] = {
value: attr
};
}
return attrs;
}
function hasOwnProperties(object, properties) {
for (var i = 0, len = properties.length; i < len; i++) {
if (object.hasOwnProperty(properties[i])) {
return true;
}
}
return false;
}
function getChangeEventKey(key) {
return '_onChange' + key.charAt(0).toUpperCase() + key.substring(1);
}
});
|
var MNote = (function() {
function MNote(label) {
if (label == '' || label == null) {
label = 'Note';
}
var uiElement = document.createElement('span');
$(uiElement).addClass('MNote').css({
'transform' : MNumber.random(-8, 8)
}).html(label);
return uiElement;
};
return MNote;
})();
|
class msvidctl_msvidaudiorendererdevices_1 {
constructor() {
// IMSVidAudioRenderer Item (Variant) {get}
this.Parameterized = undefined;
// int Count () {get}
this.Count = undefined;
}
// void Add (IMSVidAudioRenderer)
Add(IMSVidAudioRenderer) {
}
// void Remove (Variant)
Remove(Variant) {
}
}
module.exports = msvidctl_msvidaudiorendererdevices_1;
|
/**
* Created by Administrator on 2015/1/6.
*/
var grunt = require("grunt");
var htmlConverter = require("../tasks/lib/text").init(grunt);
describe("Test JSON Converter",function(){
it("should convert JSON to cmd module",function(){
var code = JSON.stringify({test:"test",value:1,number:2.2});
var e = 'define("test",[],"{\\\"test\\\":\\\"test\\\",\\\"value\\\":1,\\\"number\\\":2.2}");';
expect(htmlConverter.html2js(code,"test")).toEqual(e);
});
it("should convert JSON file to cmd module",function(){
var src = "test/fixture/no-modifier.json";
var dest = "test/tmp/no-modifier.json";
var output = htmlConverter.htmlConverter({
src : src,
dest : dest
},{});
expect(grunt.file.read(dest+".js")).toEqual(grunt.file.read("test/expect/no-modifier.json.js"));
})
});
|
/*global jQuery:true*/
(function($, window){
"use strict";
function MaxlengthInput( el ){
var self = this;
this.el = el;
this.$el = $(el);
// prevent double init
if( this.$el.data( "MaxlengthInput" ) ){
return;
}
this.$el.data( "MaxlengthInput", this);
this.maxlength = this.$el.attr("maxlength");
this.$el
.bind("keydown", function(event){
// prevent extra text entry based on the maxlength
self.onKeydown(event);
})
.bind("paste", function(event){
// prevent extra characters in the form element from pastes
self.onPaste(event);
});
}
MaxlengthInput.allowedKeys = [
9, // Tab
27, // Escape
8, // Backspace
39, // ArrowRight
37, // ArrowLeft
38, // ArrowUp
40 // ArrowDown
];
MaxlengthInput.returnRegex = /\r\n|\n/g;
// TODO shared behavior with NumericInput
MaxlengthInput.prototype.isKeyAllowed = function( event ) {
var isAllowed = false, key = event.keyCode;
// indexOf not supported everywhere for arrays
$.each(MaxlengthInput.allowedKeys, function(i, e){
if( e === key ) {
isAllowed = true;
}
});
return event.altKey || event.ctrlKey || event.metaKey || isAllowed;
};
MaxlengthInput.prototype.onKeydown = function( event ){
var self = this;
if( this.isKeyAllowed( event ) ){
return;
}
// if any character would put us at the
if(this.valueLength() >= this.maxlength){
event.preventDefault();
return;
}
// if the user hits return and that would put the length above
// the max, prevent the return character addition
if(event.keyCode == 13 && this.valueLength() + 2 > this.maxlength){
event.preventDefault();
return;
}
setTimeout(function(){
self.alterValue();
});
};
MaxlengthInput.prototype.alterValue = function(){
var newValue = this.el
.value
.replace(MaxlengthInput.returnRegex, "\r\n")
.slice(0, this.maxlength);
return this.el.value = newValue;
};
MaxlengthInput.prototype.onPaste = function( e ){
var self = this;
// force the text to look right after the paste has applied
setTimeout(function(){
self.alterValue();
});
};
MaxlengthInput.prototype.valueLength = function(check){
return (check || this.el.value)
.replace(MaxlengthInput.returnRegex, "__")
.length;
};
window.MaxlengthInput = MaxlengthInput;
}(jQuery, this));
|
version https://git-lfs.github.com/spec/v1
oid sha256:3027fc57c3d0f37949a71c0e7f6cecae9198b13aa8ac666d1a752323b776547f
size 97712
|
var myWindow = {
screenX: window.screenX,
screenY: window.screenY,
location: window.location.pathname,
screenW: window.screen.width,
screenZ: window.screen.height,
render: function() {
var ele = document.getElementById("location");
ele.value = this.location;
ele = document.getElementById("sx");
ele.value = this.screenX;
ele = document.getElementById("sy");
ele.value = this.screenY;
ele = document.getElementById("sw");
ele.value = this.screenW;
ele = document.getElementById("sz");
ele.value = this.screenZ;
}
};
myWindow.render();
|
import { module, test } from 'qunit';
import { setupApplicationTest } from 'travis/tests/helpers/setup-application-test';
import jobPage from 'travis/tests/pages/job';
import topPage from 'travis/tests/pages/top';
import signInUser from 'travis/tests/helpers/sign-in-user';
import { enableFeature } from 'ember-feature-flags/test-support';
import { percySnapshot } from 'ember-percy';
import { setupMirage } from 'ember-cli-mirage/test-support';
module('Acceptance | jobs/debug', function (hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
test('debugging job', async function (assert) {
enableFeature('debugBuilds');
const currentUser = this.server.create('user', { confirmed_at: Date.now() });
this.server.create('allowance', {subscription_type: 1});
this.server.create('user', {login: 'travis-ci'});
this.server.create('allowance', {subscription_type: 1});
signInUser(currentUser);
let repo = this.server.create('repository', { slug: 'travis-ci/travis-web', private: true, owner: { login: 'travis-ci', id: 1 } });
let branch = this.server.create('branch', { name: 'acceptance-tests' });
let gitUser = this.server.create('git-user', { name: 'Mr T' });
let commit = this.server.create('commit', { author: gitUser, committer: gitUser, branch: 'acceptance-tests', message: 'This is a message', branch_is_default: true });
let build = this.server.create('build', { repository: repo, state: 'failed', commit, branch });
let job = this.server.create('job', { number: '1234.1', repository: repo, state: 'failed', commit, build });
commit.job = job;
job.save();
commit.save();
this.server.create('log', { id: job.id });
const requestBodies = [];
this.server.post(`/job/${job.id}/debug`, function (schema, request) {
const parsedRequestBody = JSON.parse(request.requestBody);
requestBodies.push(parsedRequestBody);
});
await jobPage
.visit()
.debugJob();
assert.deepEqual(requestBodies.pop(), { quiet: true });
assert.equal(topPage.flashMessage.text, 'The job was successfully restarted in debug mode but make sure to watch the log for a host to connect to.');
percySnapshot(assert);
});
});
|
var net = require('net');
var HOST = '128.197.50.236';
var PORT = 55000;
var n=1;
var client = new net.Socket();
var RollingSpider = new require('rolling-spider');
var quad = new RollingSpider({
logger: console.log
});
var flying = false;
var inFlip = false;
var land = false;
var count=0;
var prevControls;
quad.connect(function(err) {
if (err) console.log(err);
quad.setup(function(err) {
if (err) console.log(err);
quad.flatTrim();
quad.startPing();
quad.flatTrim();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
// client.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
if (data == 3 && flying == false){
quad.flatTrim();
quad.takeoff();
console.log('takeoff');
flying = true;
count=0;
}
else if (data == 2 && flying==true && count<3){
count=count+1;
}
else if (data == 2 && flying== true && count >= 3){
quad.land();
flying = false;
console.log('landing');
count=0;
}
else if (data == 6 && flying== true && inFlip == false){
inFlip = true;
quad.frontFlip(flipDone);
console.log('frontflip');
count=0;
}
else if (data == 11 && flying== true && inFlip == false){
inFlip = true;
quad.backFlip(flipDone);
console.log('backflip');
count=0;
}
else quad.hover();
// Close the client socket completely
//client.destroy();
});
});
});
function flipDone() {
inFlip = false;
}
// Add a 'clos joystick.on('data', function(buf) {
/* var controls = parseControls(buf);
if (!prevControls)
prevControls = controls;
if (prevControls.buttons[0] === 0 && controls.buttons[0] === 1) {
if (flying) {
quad.land();
flying = false;
} else {
quad.flatTrim();
quad.takeoff();
flying = true;
}
}
if (prevControls.view === 8 && controls.view !== 8)
switch (controls.view) {
case 0:
inFlip = true;
quad.frontFlip(flipDone);
break;
case 2:
inFlip = true;
quad.rightFlip(flipDone);
break;
case 4:
inFlip = true;
quad.backFlip(flipDone);
break;
case 6:
inFlip = true;
quad.leftFlip(flipDone);
break;
}
prevControls = controls;
if (flying && !inFlip) {
if (controls.buttons[1]) {
quad.driveStepsRemaining = 1;
quad.speeds = {
yaw: 100 * (controls.yaw - 128) / 128,
pitch: -100 * (controls.pitch - 512) / 512,
roll: 100 * (controls.roll - 512) / 512,
altitude: 100 * (controls.throttle - 128) / 128
}
} else quad.hover();
}
// console.log(JSON.stringify(controls));
});
joystick.on('error', function() {
quad.land();
});
});
});
function flipDone() {
inFlip = false;
}
function parseControls(buf) {
var ch = buf.toString('hex').match(/.{1,2}/g).map(function(c) {
return parseInt(c, 16);
});
return {
roll: ((ch[1] & 0x03) << 8) + ch[0],
pitch: ((ch[2] & 0x0f) << 6) + ((ch[1] & 0xfc) >> 2),
yaw: ch[3],
view: (ch[2] & 0xf0) >> 4,
throttle: -ch[5] + 255,
buttons: [
(ch[4] & 0x01) >> 0, (ch[4] & 0x02) >> 1, (ch[4] & 0x04) >> 2, (ch[4] & 0x08) >> 3, (ch[4] & 0x10) >> 4, (ch[4] & 0x20) >> 5, (ch[4] & 0x40) >> 6, (ch[4] & 0x80) >> 7, (ch[6] & 0x01) >> 0, (ch[6] & 0x02) >> 1, (ch[6] & 0x04) >> 2, (ch[6] & 0x08) >> 3
]
}
}e' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
*/
//var hid = require('node-hid');
// console.log(hid.devices());
// Logitech Extreme 3D Pro's vendorID and productID: 1133:49685 (i.e. 046d:c215)
//var joystick = new hid.HID(1133, 49685);
// console.log(joystick);
|
import React from 'react';
import classes from 'classnames';
import Feed from 'src/components/Feed';
import equip from './equip';
const Content = ({ isFetching, posts, postCount, lastUpdated }) => (
<div>
{isFetching && posts.length === 0 &&
<h2>Loading...</h2>
}
{!isFetching && posts.length === 0 &&
<h2>Empty.</h2>
}
{postCount > 0 &&
<div>
{lastUpdated &&
<sub className={classes('pa3', 'top-075', 'grey-text')}>
Last updated at {new Date(lastUpdated).toLocaleTimeString()}
</sub>
}
<Feed style={{ opacity: isFetching ? 0.5 : 1 }} />
</div>
}
</div>
);
export default equip(Content);
|
import path from 'path'
import webpack from 'webpack'
import UglifyJsPlugin from 'uglifyjs-webpack-plugin'
const config = {
mode: process.env.NODE_ENV,
entry: [
'./src/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: process.env.NODE_ENV === 'production' ? 'threesixty.min.js' : 'threesixty.js',
library: 'threesixty',
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
}),
],
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
ie8: false,
warnings: false,
},
})
]
},
}
export default config
|
var express = require('express');
var router = express.Router();
// use auth_token cookie to secure the angular /app files
//TODO this needs to be reworked since someone could spoof
//a legitimate cookie named auth_token. Need to actually verify
//the cookie
router.use('/', function (req, res, next) {
if (!req.cookies.auth_token) {
return res.redirect('/login?returnUrl=' + encodeURIComponent('/app' + req.path));
}
next();
});
// serve angular app files from the '/app' route
router.use('/', express.static('app'));
module.exports = router;
|
var mongoose = require("../../database/");
var UserSchema = mongoose.Schema({
username: String,
password: String,
lastLoginTime: Date,
createTime: Date,
userType: String, // admin,normal
projectList: [
{
_id: Object,
name: String
}
]
});
module.exports = UserSchema;
|
define(['angular'], function(angular) {
'use strict';
return angular.module('biomsef.filter', [ ]);
});
|
/**
* Controller module.
* This is the unique master controller, with tiny controllers for each view.
* Our project is not large scaled, so our controllers can all stay together
* happily like a family.
* @module shell
*/
'use strict';
var helpers = require('./helpers');
var model = require('./model');
// var page = require('page');
var pubSub = require('pubsub-js');
var notie = require('notie');
/* Views */
var views = {};
views.peopleList = require('./views/people-list');
views.chat = require('./views/chat');
views.account = require('./views/account');
var configMap = {
};
var isTesting = true;
var _testing = function() {
// model.people.login('Alfred');
};
///////////////////////////
// VIEWS EVENTS HANDLERS //
///////////////////////////
/* ACCOUNT */
var _onSignClick = function() {
var currentUser = model.people.getCurrentUser();
if(currentUser.getIsAnon()) {
notie.input('Please sign-in with a nickname: ', 'Sign-in', 'Cancel', 'text', 'Nickname', function(userName) {
if( (userName.length < 3) || (userName.length > 12) ) {
notie.alert(3, 'Sorry, username must be between 3 and 12 characters');
} else {
model.people.login(userName);
document.qs('.account .sign').textContent = '... Processing ...';
}
});
} else {
model.people.logout();
}
return false;
};
/* PEOPLE LIST */
var onSetChatee = function(personId) {
model.chat.setChatee(personId);
};
/* CHAT */
var onSubmitMsg = function(msgText) {
if(!model.chat.getChatee()) {
return;
}
model.chat.sendMsg(msgText);
};
////////////////////////////////////
// RENDERING VIEWS WHEN USER LOGS IN //
////////////////////////////////////
var onLogin = function() {
//people-list
views.peopleList.init();
views.peopleList.bind('setChatee', onSetChatee);
//chat
views.chat.init();
views.chat.bind('submitMsg', onSubmitMsg);
};
/**
* PUBLIC FUNCTIONS
*/
var configModule = function(inputMap) {
helpers.configMap(inputMap, configMap);
};
var init = function() {
//Account
views.account.init();
views.account.bind('onSignClick', _onSignClick);
//People list
//When user is logged in
pubSub.subscribe('login', onLogin);
if(isTesting) {
_testing();
}
};
module.exports = {
/** configures the module configMap */
configModule: configModule,
/** init shell module */
init: init
};
|
'use strict';
const chalk = require('chalk');
const inquirer = require('inquirer');
const labels = require('./labels');
module.exports = {
multipleWordsInput: (input) => {
// node index.js add Super Mario World returns Super Mario World
return input.splice(3).join(' ');
},
calculateGames: (games) => {
return console.log(chalk.cyan(games.length) + ` ${labels.log.gamesInCollection}`);
},
gameAdded: (game) => {
return console.log(chalk.yellow(chalk.bold(game) + ` ${labels.log.insertedIntoCollection}`));
},
gameRemoved: (game) => {
return console.log(chalk.yellow(chalk.bold(game) + ` ${labels.log.removedFromCollection}`));
},
console: (type, message, style) => {
if (type === 'log') {
console.log(
style ? chalk[style](chalk.dim(message)) : chalk.dim(message)
);
}
if (type === 'warning') {
console.log(
style ? chalk[style](chalk.yellow(message)) : chalk.yellow(message)
);
}
if (type === 'success') {
console.log(
style ? chalk[style](chalk.green(message)) : chalk.green(message)
);
}
if (type === 'error') {
console.log(
style ? chalk[style](chalk.red(message)) : chalk.red(message)
);
}
},
dialog: async (dialogType, dialogMessage, dialogName, dialogChoices, dialogPageSize, dialogNoSelectionMessage) => {
return await inquirer.prompt([{
type: dialogType,
message: dialogMessage,
name: dialogName,
choices: dialogChoices,
pageSize: dialogPageSize,
validate: (answer) => {
if (answer.length < 1) {
return dialogNoSelectionMessage;
}
return true;
}
}]);
},
getMatchedGame: (gameFromDB, gamesFromAPI) => {
for (const item of gamesFromAPI) {
if (gameFromDB.title === item.title && gameFromDB.platform === item.platform) {
module.exports.console('success', `${item.title} | ${item.platform}`);
return item;
}
}
module.exports.console('error', `${gameFromDB.title} | ${gameFromDB.platform}`);
return null;
}
};
|
var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.length == 0) {
throw "Error: please, provide your userkey as first parameter!";
}
var userKey = argv[0];
function registerMachine(callback) {
var data = {
'UserKey': userKey,
'ComputerName': os.hostname(),
'OS': os.type() + ' ' + os.release()
};
sendPOST(data, '/machine', callback);
}
function sendHealthcheck(hc, callback) {
sendPOST(hc, '/', callback);
}
function sendPOST(postData, path, callback) {
var data = JSON.stringify(postData);
var options = getOpts(config.get('api.url'), 'POST', path, data);
var req = http.request(options, function (res) {
var resData = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
resData += chunk;
});
res.on('end', function () {
callback(res.statusCode != 200 ? res.statusCode : null, resData);
});
});
req.on('error', function (err) {
callback(err);
});
req.write(data);
req.end();
}
function getOpts(apiUrl, method, path, data) {
var options = url.parse(apiUrl + '/v'+config.get('api.v')+path);
options.method = method;
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
return options;
}
attempt(
{
retries: 5,
interval: 3000
},
function() {
registerMachine(this);
},
function(err, res) {
if (err) {
logger.error(err);
throw err;
}
logger.debug(res);
var machineContainer = JSON.parse(res);
(function gatherHealthCheck(timeout) {
logger.debug('Getting healthcheck...')
healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) {
if (err) throw err;
logger.debug('Healthcheck: ' + JSON.stringify(res));
logger.debug('Sending data to API...');
sendHealthcheck(res, function (err, data) {
if (err) {
logger.error(err);
}
else {
var json = JSON.parse(data);
logger.debug('Got response: ' + data);
var newInterval = json.Interval * 1000;
if (newInterval != timeout) {
logger.debug('Changing data collection interval: ');
timeout = newInterval;
}
}
});
});
setTimeout(function () {
gatherHealthCheck(timeout);
}, timeout);
})(machineContainer.Settings.Interval * 1000);
});
|
// change these variables
var data_source_name = "";
// end changes
if(a=="view"){
(function (u,c,p,a,r,q) {
if (!utag.ut) utag.ut = {};
r = function (w, x, y, z) {
// read cookie
x = w + "=";
y = document.cookie.split(';');
for (var i = 0; i < y.length; i++) {
z = y[i];
while (z.charAt(0) == ' ')
z = z.substring(1, z.length);
if (z.indexOf(x) == 0)
return z.substring(x.length, z.length);
}
return "";
};
q = function (x, y, z) {
// set cookie
if (typeof z == "number") z = new Date(z);
document.cookie = x + "=" + y + ";path=/;domain=" + utag.cfg.domain + ";expires=" + (z?z.toGMTString():"");
//b["cp."+x] = y; // add cookie to udo
};
utag.ut.hppv = function (w,x,y,z,r,q,c) {
if (!utag.ut.getPPVid)
return;
c = "utag_ppv";
r = function (w, x, y, z) {
// read cookie
x = w + "=";
y = document.cookie.split(';');
for (var i = 0; i < y.length; i++) {
z = y[i];
while (z.charAt(0) == ' ')
z = z.substring(1, z.length);
if (z.indexOf(x) == 0)
return z.substring(x.length, z.length);
}
return "";
};
q = function (x, y, z) {
// set cookie
if (typeof z == "number")
z = new Date(z);
document.cookie = x + "=" + y + ";path=/;domain=" + utag.cfg.domain + ";expires=" + (z?z.toGMTString():"");
//b["cp."+x] = y; // add cookie to udo
};
w = Math.max(
Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
Math.max(document.body.clientHeight, document.documentElement.clientHeight)
),
x = (window.pageYOffset || (document.documentElement.scrollTop || document.body.scrollTop))
+(window.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight));
y = Math.min(Math.round(x / w * 100), 100);
z = (r(c).indexOf(',') > -1) ? r(c).split(',', 4) : [];
q(c, ((y > 0) ? (((z.length > 0) ? (z[0]) : escape(utag.ut.getPPVid)) + ',' + ((y > ((z.length > 1) ? parseInt(z[1]) : (0))) ? y : ((z.length > 1) ? parseInt(z[1]) : (0))) + ',' + ((z.length > 2) ? parseInt(z[2]) : (y)) + ',' + ((x > ((z.length > 3) ? parseInt(z[3]) : (0))) ? x : ((z.length > 3) ? parseInt(z[3]) : (0)))) : ''));
};
c = "utag_ppv";
p = p ? p : '-';
a = (r(c).indexOf(',') > -1) ? r(c).split(',', 4) : [];
if (a.length < 4) {
for (i=3; i>0; i--) {
a[i] = (i < a.length) ? (a[i - 1]) : ('');
}
a[0] = '';
}
a[0] = unescape(a[0]);
q(c, escape(p));
if (!utag.ut.getPPVid) {
utag.ut.getPPVid = (p) ? (p) : document.location.href;
q(c, escape(utag.ut.getPPVid));
if (window.addEventListener) {
window.addEventListener('load', utag.ut.hppv, false);
window.addEventListener('scroll', utag.ut.hppv, false);
window.addEventListener('resize', utag.ut.hppv, false);
} else if (window.attachEvent) {
window.attachEvent('onload', utag.ut.hppv);
window.attachEvent('onscroll', utag.ut.hppv);
window.attachEvent('onresize', utag.ut.hppv);
}
}
b[u] = (p != '-') ? (a) : (a[1]);
})(data_source_name);
}
|
const watson = require('watson-developer-cloud');
const API_KEY = '1b72f2aaaf9d29cd93d4805592c8991c828f9169'; // Put API key here
// Connect to Watson Alchemy Language service
if (API_KEY) {
var alchemy = watson.alchemy_language({
api_key: API_KEY
});
} else {
console.error('Could not connect to Alchemy API - No API key');
}
/**
* Uses the Watson Alchemy API to generate a tag-cloud for target.
* target should be an object with one of the properties html, url or text.
*/
module.exports = target => new Promise((resolve, reject) => {
if (!target || !(target.html || target.url || target.text)) {
reject('Could not invoke Alchemy API - No target');
}
if (!alchemy) {
reject('No Alchemy connection');
}
// Refer to the following link for more information:
// http://www.ibm.com/watson/developercloud/alchemy-language/api/v1/?node#entities
var parameters = Object.assign({
structuredEntities: 0,
emotion: 1
}, target);
// Make API call
alchemy.entities(parameters, function (err, res) {
if (!err && res && Array.isArray(res.entities)) {
resolve(res.entities);
}
reject(err || 'No results');
});
})
|
const webpack = require('webpack')
const express = require('express')
const path = require('path')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackConfig = require('../build/webpack.config.js')
const config = require('../project.config.js')
const compiler = webpack(webpackConfig)
const server = express()
// Add conditional based on ENV
server.use(
webpackDevMiddleware(
compiler, {
stats: {
colors: true,
modules: false,
chunks: false,
},
resolve: {
modules: [
'node_modules',
path.resolve(config.src)
]
}
}
)
)
server.use(require('webpack-hot-middleware')(compiler))
server.listen(config.port, () => {
console.log(`Server running on port ${config.port}`)
})
module.exports = server
|
import Expr from './Expr'
export default class ColorByWavelengthExpr extends Expr {
constructor(value, $loc) {
super('colorByWavelength', $loc)
this.value = value
}
_evaluateInternal(e) {
return e.evalColorByWavelength(this)
}
}
|
import React, { Component, PropTypes } from 'react';
/*** Third Party Components ***/
import Dialog from 'react-toolbox/lib/dialog';
import { Button, IconButton } from 'react-toolbox/lib/button';
import Icon from 'react-fa';
import style from './style.scss';
class NavButton extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
handleOpen = () => {
this.setState({
open: true
});
};
handleClose = () => {
this.setState({
open: false
});
};
render() {
return (
<div className={`${style.root} ${this.props.className}`} >
<IconButton
className={style.navBars}
neutral={false}
onClick={this.handleOpen}>
<Icon
name={this.state.open ? 'times-circle-o' : 'bars'} />
</IconButton>
<Dialog
active={this.state.open}
onOverlayClick={this.handleClose}
className={style.dialog} >
<Button
flat
label="What is this?"
target="_blank"
neutral={false}
className={style.link} />
<Button
flat
label="Why?"
target="_blank"
neutral={false}
className={style.link} />
<Button
flat
label="Contact"
target="_blank"
neutral={false}
className={style.link} />
</Dialog>
</div>
);
}
}
export default NavButton;
|
import clone from "clone";
const initialState = {
busy: false
};
export default function(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case "BUSY": {
const newState = clone(state);
newState.busy = payload;
const stateCopy = { ...state };
return newState;
}
}
return state;
}
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
/**
* Connect Mongodb
*/
mongoose.connect('mongodb://localhost/speedyfx');
/**
* Schemas
*/
var UserSchema = new Schema({
uid: { type: String, required: true, trim: true, index: { unique: true, dropDups: true} },
pwd: { type: String, required: true, select: false },
nick: { type: String, required: true, trim: true },
email: { type: String, required: true, trim: true },
gender: { type: String, enum: ['male', 'female'] },
image: String,
status: String,
address: String,
phone: String
});
var ContactSchema = new Schema({
uid: { type: String, required: true, index: true },
cid: { type: String, required: true, index: true },
alias: { type: String, 'default': '' },
black: { type: Boolean, required: true, 'default': false }
});
var MessageSchema = new Schema({
uid: { type: String, required: true, index: true },
mid: { type: String, required: true, index: true },
msg: { type: String, required: true },
time: { type: String, required: true, 'default': Date.now }
});
/**
* Models
*/
var User = module.exports.User = mongoose.model('user', UserSchema);
var Contact = module.exports.Contact = mongoose.model('contact', ContactSchema);
var Message = module.exports.Message = mongoose.model('message', MessageSchema);
/**
* Create query condition expression
*/
module.exports.Q = function Q(fields, params) {
var r = {};
for (var i in fields) {
// required condition
if (fields[i]) {
if (params[i] === undefined) return null;
else r[i] = params[i];
}
// optional condition
else {
if (params[i] != undefined)
r[i] = params[i];
}
}
return r;
};
/**
* Create selection filter expression
*/
module.exports.F = function F(def, params) {
if (params.filter)
return params.filter.replace(/,/g, ' ');
else return def;
};
/**
* Create update setter expression
*/
module.exports.S = function S(fields, params) {
var r = {};
for (var i in fields) {
// required fields
if (fields[i]) {
if (params[i] === undefined) return null;
else r[i] = params[i];
}
// optional fields
else {
if (params[i] != undefined)
r[i] = params[i];
}
}
return { $set: r };
};
/**
* Extract field from query result and make array
*/
module.exports.asArray = function asArray(doc, field) {
var r = [];
doc.forEach(function (obj, index, array) {
if (obj[field] != undefined) r.push(obj[field]);
});
return r;
};
module.exports.toArray = function toArray(doc) {
var r = [];
doc.forEach(function (obj, index, array) {
r.push(obj.toObject());
});
return r;
};
|
import 'rxjs/add/operator/combineLatest';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/skip';
import 'rxjs/add/operator/withLatestFrom';
import 'rxjs/add/operator/concat';
import 'rxjs/add/operator/share';
export default function(...observables) {
return source => {
const published = source.share();
return published
.combineLatest(...observables)
.take(1)
.concat(published.skip(1).withLatestFrom(...observables));
};
}
|
(function ($, window) {
$.fn.twitterify = function (options) {
return this.each(function () {
new window.twitterify.Twitterifier(this, options)
.init()
.load();
});
};
}(jQuery, window));
|
'use strict';
/**
* Module dependencies
*/
var flipflopsPolicy = require('../policies/flipflops.server.policy'),
flipflops = require('../controllers/flipflops.server.controller');
module.exports = function(app) {
// Flipflops Routes
app.route('/api/flipflops').all(flipflopsPolicy.isAllowed)
.get(flipflops.list)
.post(flipflops.create);
app.route('/api/flipflops/:flipflopId').all(flipflopsPolicy.isAllowed)
.get(flipflops.read)
.put(flipflops.update)
.delete(flipflops.delete);
app.route('/api/topic').all(flipflopsPolicy.isAllowed)
.get(flipflops.fetchTopic);
app.route('/api/topic/:topicId').all(flipflopsPolicy.isAllowed)
.put(flipflops.updateTopic);
app.route('/api/upload').all(flipflopsPolicy.isAllowed)
.post(flipflops.upload);
app.route('/api/judge').all(flipflopsPolicy.isAllowed)
.get(flipflops.judge);
app.route('/api/judge/:flipflopId').all(flipflopsPolicy.isAllowed)
.put(flipflops.update);
// Finish by binding the Flipflop middleware
app.param('flipflopId', flipflops.flipflopByID);
app.param('topicId', flipflops.topicByID);
};
|
(function (angular) {
"use strict";
angular
.module("Cerberus.TemplateEditor")
.controller("Cerberus.TemplateEditor.Controller.ComponentEditor.Navigation.Link", function () { });
})(window.angular);
|
'use strict'
import React, { PropTypes } from 'react';
import { Button } from 'antd';
import { Link } from 'react-router';
import * as actions from '../action/note'
class Notes_item extends React.Component{
onDeleteNote (event) {
event.preventDefault()
this.props.onDeleteNote(this.props.note._id)
}
render() {
let date = this.props.note.date;
let postDate = 'posted @' + date;
let deleteChoice
if (this.props.note.isLogin) {
deleteChoice = (
<span className="deleteNote" onClick={ this.onDeleteNote.bind(this) }> 删除 </span>
)
}
return (
<div>
<div className="notes_item" >
<h4><Link to={ '/note/' + this.props.note._id }>{ this.props.note.title }</Link></h4>
<p>{ this.props.note.content.substr(0,50) + '...' }</p>
<span className="tag">
<span>{ '作者:' + this.props.note.author } </span>
<span className="tag-left">{ postDate }</span>
<span className="tag-right">浏览({ this.props.note.pv || 0 }){' '}留言({ this.props.note.commentCnt || 0})</span>
{ deleteChoice }
</span>
</div>
</div>
);
}
}
export default Notes_item;
|
Package.describe({
summary: "Sentinel role based authorization."
});
Package.on_use(function (api) {
var both = ['client', 'server'];
api.use(['coffeescript', 'underscore', 'accounts-base'], both);
api.add_files('sentinel.litcoffee', both);
api.export && api.export('Sentinel');
});
|
/*
*
* ToolPage reducer
*
*/
import { fromJS } from 'immutable';
import {
DEFAULT_ACTION,
REAL_WORLD_EXAMPLE,
CONTRIBUTED_BY,
LEARN_MORE,
SET_CHOSEN_SECTION,
RESET_TOOL_STATE,
SET_EXPAND_ALL
} from './constants';
const initialState = fromJS({
expandAll: false,
chosenSection: REAL_WORLD_EXAMPLE,
});
function toolPageReducer(state = initialState, action) {
switch (action.type) {
case DEFAULT_ACTION:
return state;
case RESET_TOOL_STATE:
return initialState;
case SET_CHOSEN_SECTION:
return state.set('chosenSection', action.chosenSection);
case SET_EXPAND_ALL:
return state.set('expandAll', action.isExpandAll);
default:
return state;
}
}
export default toolPageReducer;
|
'use strict';
const DateRange = require('../../../api/lib/DateRange');
const moment = require('moment');
describe('DateRange', () => {
describe('constructor', () => {
it('should assign properties correctly', () => {
var from = new Date();
var to = new Date();
var result = new DateRange(from, to);
expect(result).to.have.property('from', from);
expect(result).to.have.property('to', to);
});
});
describe('contains', () => {
it('should return true if the date falls within the date range', () => {
var date = new Date();
var from = moment(date).subtract(1, 'second').toDate();
var to = moment(date).add(1, 'second').toDate();
var dateRange = new DateRange(from, to);
expect(dateRange.contains(date)).to.equal(true);
expect(dateRange.contains(from)).to.equal(true);
expect(dateRange.contains(to)).to.equal(true);
});
it('should return false if the date falls outside the date range', () => {
var date = new Date();
var from = moment(date).subtract(1, 'second').toDate();
var to = moment(date).add(1, 'second').toDate();
var dateRange = new DateRange(from, to);
expect(dateRange.contains(moment(from).subtract(1, 'second').toDate())).to.equal(false);
expect(dateRange.contains(moment(to).add(1, 'second').toDate())).to.equal(false);
});
});
describe('widen', () => {
it('should return a DateRange from the earliest point, to the latest point of n DateRanges', () => {
const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02'));
const r2 = new DateRange(new Date('2016/01/03'), new Date('2016/01/04'));
const r3 = new DateRange(new Date('2016/01/05'), new Date('2016/01/06'));
const result = DateRange.widen(r3,r2,r1);
expect(result.from).to.equal(r1.from);
expect(result.to).to.equal(r3.to);
});
it('should return the same result regardless of argument order', () => {
const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02'));
const r2 = new DateRange(new Date('2016/01/03'), new Date('2016/01/04'));
const r3 = new DateRange(new Date('2016/01/05'), new Date('2016/01/06'));
const result = DateRange.widen(r3,r2,r1);
const result2 = DateRange.widen(r1,r3,r2);
expect(result.from).to.equal(result2.from);
expect(result.to).to.equal(result2.to);
});
it('should work with overlapping ranges', () => {
const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02'));
const r2 = new DateRange(new Date('2015/12/03'), new Date('2016/01/02'));
const r3 = new DateRange(new Date('2016/01/01'), new Date('2016/02/06'));
const result = DateRange.widen(r3,r2,r1);
expect(result.from).to.equal(r2.from);
expect(result.to).to.equal(r3.to);
});
});
});
|
//This snippet is a sample of using a JavaScript client library to access a public API
//require the https module to enable a connection to the https protocol URL of the public API
let http = require('http');
let key = require('./modules/auth.js');
let _key = key;
let location = 'Lagos';
//Use the GET method to send a request to the API which will pass the response to the callback
const request = http.get('http://api.apixu.com/v1/current.json?key='+_key+'&q='+location, function(response){
let weatherData = "";
//console.log(response.statusCode);
//Call a data event that will be used to retrieve the data sent from the API in JSON format to the callback
response.on("data", function(data){
weatherData += data;
if (response.statusCode === 200) {
try{
weatherInfo = JSON.parse(weatherData);
console.log(weatherInfo);
}catch(e){
console.log("We encountered error while processing your request");
}
}else {
console.log("There was an error in your request! Try again later");
}
}).on("error", function(e){
console.error("The API is unavailable");
});
});
request.end();
//check for weather current condition text (current.condition.text)
//weather locaation
|
taskName = "Problem3.DeepCopy";
function Main(bufferElement) {
function createDeepCopy(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
var copy = obj.constructor();
for (var prop in obj) {
copy[prop] = createDeepCopy(obj[prop]);
}
return copy;
}
var person = {
firstName: 'Pesho',
lastName: 'Peshov',
marks: {
C1: 6,
C2: 6,
COOP: 5,
HTML: 4,
CSS: 6
}
},
copy = createDeepCopy(person);
person.marks.COOP = 4;
WriteLine('Person COOP: ' + person.marks.COOP);
WriteLine('Copy COOP' + copy.marks.COOP);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.