text
stringlengths 2
6.14k
|
|---|
var HTTP = require("q-io/http");
HTTP.read('http://localhost:1337')
.then(JSON.parse)
.then(function(response) {
console.log(response);
})
.done();
|
(function () {
// The default state core singleton for {@link SceneJS.View} nodes
var defaultCore = {
type:"view",
stateId:SceneJS._baseStateId++,
scissorTestEnabled:false
};
var coreStack = [];
var stackLen = 0;
SceneJS_events.addListener(
SceneJS_events.SCENE_COMPILING,
function (params) {
params.engine.display.view = defaultCore;
stackLen = 0;
});
/**
* @class Scene graph node which configures view parameters such as depth range, scissor test and viewport
* @extends SceneJS.Node
* void depthRange(floatzNear, floatzFar)
zNear: Clamped to the range 0 to 1 Must be <= zFar
zFar: Clamped to the range 0 to 1.
void scissor(int x, int y, long width, long height)
void viewport(int x, int y, long width, long height)
*/
SceneJS.View = SceneJS_NodeFactory.createNodeType("view");
SceneJS.View.prototype._init = function (params) {
if (params.scissorTestEnabled != undefined) {
this.setScissorTestEnabled(params.scissorTestEnabled);
} else if (this._core.useCount == 1) { // This node defines the core
this.setScissorTestEnabled(false);
}
};
/**
* Enable or disables scissor test.
*
* When enabled, the scissor test will discards fragments that are outside the scissor box.
*
* Scissor test is initially disabled.
*
* @param scissorTestEnabled Specifies whether scissor test is enabled or not
* @return {*}
*/
SceneJS.View.prototype.setScissorTestEnabled = function (scissorTestEnabled) {
if (this._core.scissorTestEnabled != scissorTestEnabled) {
this._core.scissorTestEnabled = scissorTestEnabled;
this._engine.display.imageDirty = true;
}
return this;
};
/**
* Get whether or not scissor test is enabled.
* Initial value will be false.
*
* @return Boolean
*/
SceneJS.View.prototype.getScissorTestEnabled = function () {
return this._core.scissorTestEnabled;
};
SceneJS.View.prototype._compile = function (ctx) {
this._engine.display.view = coreStack[stackLen++] = this._core;
this._compileNodes(ctx);
this._engine.display.view = (--stackLen > 0) ? coreStack[stackLen - 1] : defaultCore;
};
})();
|
"use strict";
define(['dou', 'build/ComponentRegistry'],
function (dou, ComponentRegistry) {
describe('ComponentRegistry', function () {
var componentRegistry;
var specs = [ {
type: 'A',
name: 'Component A',
description: 'description for Component A',
defaults: {
attr1: '1',
attr2: 'A',
attr3: 100
},
shape_factory: dou.define({
}),
handle_factory: dou.define({
}),
toolbox_image: 'toolbox_small.png'
}, {
type: 'B',
name: 'Component B',
description: 'description for Component B',
defaults: {
attr1: '2',
attr2: 'B',
attr3: 200
},
shape_factory: dou.define({
}),
handle_factory: dou.define({
}),
toolbox_image: 'toolbox_small.png'
} ];
beforeEach(function() {
componentRegistry = new ComponentRegistry();
specs.forEach(function(spec) {
componentRegistry.register(spec);
});
});
afterEach(function() {
componentRegistry.dispose()
});
describe('register', function() {
it('should ', function () {
componentRegistry.register({
type: 'C',
name: 'Component C',
description: 'description for Component C',
defaults: {
attr1: '3',
attr2: 'C',
attr3: 300
},
shape_factory: dou.define({
}),
handle_factory: dou.define({
}),
toolbox_image: 'toolbox_small.png'
});
var specs = componentRegistry.list();
Object.keys(specs).length.should.equal(3);
});
});
describe('list', function() {
it('should return list of registered component specs.', function () {
var specs = componentRegistry.list();
var inst = new ComponentRegistry();
specs.length.should.equal(2);
});
});
describe('get', function() {
it('should get component spec by type of spec as a key', function () {
var spec = componentRegistry.get('B');
spec.name.should.equal('Component B');
spec.defaults.attr2.should.equal('B');
});
it('should not be able to change attributes of regietered spec.', function () {
var spec = componentRegistry.get('B');
var origin = spec.name;
spec.name = origin + ' Changed';
var spec = componentRegistry.get('B');
spec.name.should.equal(origin);
});
});
});
});
|
'use strict';
var git = require('../')
console.log('git.short() => ' + git.short());
// 75bf4ee
console.log('git.long() => ' + git.long());
// 75bf4eea9aa1a7fd6505d0d0aa43105feafa92ef
console.log('git.branch() => ' + git.branch());
// master
// console.log('git.tag() => ', git.tag());
// console.log('git.log() => ', git.log());
console.log('git.message() => ' + git.message());
// initial commit
|
import { message } from 'antd'
import { changePasswordAction } from '../request/password'
export const changePassword = (data, cb) => (dispatch, getState) => {
dispatch(changePasswordAction(data)).then(action => {
action.data.body.opResult == '1' ?
message.success('密码修改成功!') :
message.error('密码修改失败,请重试!')
if (cb) cb()
})
}
|
// https://github.com/jgthms/bulma/issues/238 thanks!
document.getElementById("nav-toggle").addEventListener("click", toggleNav);
function toggleNav() {
var nav = document.getElementById("nav-menu");
var className = nav.getAttribute("class");
if(className == "nav-right nav-menu") {
nav.className = "nav-right nav-menu is-active";
} else {
nav.className = "nav-right nav-menu";
}
}
// for the random quote in the header
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "/quotes.txt", true);
txtFile.onreadystatechange = function () {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) {
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n");
randLine = lines[Math.floor((Math.random() * lines.length) + 1)];
document.getElementById('quote').innerHTML = randLine ||
"Intelligence is the ability to adapt to change."; // fallback quote
}
}
};
txtFile.send(null);
document.getElementById("search-text").addEventListener("keydown", function(e) {
// search
if (e.keyCode == 13) { searchHandler(); }
}, false);
function searchHandler() {
var searchInput = document.getElementById('search-text');
var text = searchInput.value;
// add site:example.com in the placeholder
window.location.href = "https://www.google.com/search?q=site:wangxin1248.github.io " + text;
}
|
var gulp = require('gulp'),
watch = require('gulp-watch'),
run = require('gulp-run'),
sourcemaps = require('gulp-sourcemaps'),
rename = require('gulp-rename'),
mochify = require('mochify'),
to5 = require('gulp-6to5');
gulp.task('6to5', function() {
return gulp.src('**/*.es6')
.pipe(sourcemaps.init())
.pipe(to5({
experimental: true,
loose: 'all'
}))
.pipe(sourcemaps.write())
.pipe(rename({
extname: '.js'
}))
.pipe(gulp.dest('./'));
});
gulp.task('test', ['6to5'], function() {
mochify('./test.js', {
reporter: 'tap'
}).bundle();
});
gulp.task('default', ['test'], function() {
gulp.watch('**/*.es6', ['test']);
});
|
/**
Data comes from a docker inspect command output
*/
function Container(data)
{
for (d in data) {
this[d] = data[d];
}
}
Container.prototype.name = function()
{
return this.Name.ltrim('/');
}
Container.prototype.shortName = function()
{
return this.name();
}
Container.prototype.shortId = function()
{
return this.Id.substr(0, 12);
}
Container.prototype.links = function()
{
if (this.HostConfig == undefined || this.HostConfig.Links == undefined) {
return [];
}
return this.HostConfig.Links.reduce(function (arr, str) {
var name = str.split(':')[0];
if (arr.indexOf(name) < 0) {
arr.push(name);
}
return arr;
}, []);
}
Container.prototype.linksShortNames = function()
{
if (this.HostConfig == undefined || this.HostConfig.Links == undefined) {
return {};
}
return this.HostConfig.Links.reduce(function (arr, str) {
var parts = str.split(':');
var name = parts[0];
var sname = parts.last().split('/').last();
if (!(name in arr) || sname.length < arr[name].length) {
arr[name] = sname;
}
return arr;
}, {});
}
Container.prototype.stringPorts = function()
{
if (this.NetworkSettings == undefined || this.NetworkSettings.Ports == undefined) {
return []
}
var ports = []
for (ph in this.NetworkSettings.Ports) {
var list = this.NetworkSettings.Ports[ph]
ports = ports.concat(list.map(function(o) {
return o.HostIp+':'+o.HostPort+'->'+ph
}))
}
return ports
}
module.exports = Container;
|
/* globals mocha, chai */
import {jml, glue, nbsp, $, $$, body} from '../src/jml.js';
mocha.setup('bdd');
mocha.globals(['jml', 'glue', 'nbsp']);
window.jml = jml;
window.glue = glue;
window.nbsp = nbsp;
window.$ = $;
window.$$ = $$;
window.body = body;
window.assert = chai.assert;
window.expect = chai.expect;
|
let webpack = require('webpack');
let path = require( 'path');
const AssetsPlugin = require('assets-webpack-plugin');
let projectRoot = process.cwd();
let assetsPath = path.join(projectRoot, "public", "build");
let publicPath = `/build/`;
let host = "0.0.0.0";
let config = {
devServer: {
inline: true,
host,
port: 3100,
hot: true,
disableHostCheck: true,
contentBase: assetsPath,
watchOptions: {
poll: true
}
},
cache: false,
// devtool: 'cheap-module-eval-source-map',
devtool: 'eval',
mode: "development",
context: process.cwd(),
entry: {
bundle: [
path.resolve(projectRoot, './webpack/util/polyfills.js'),
path.resolve(projectRoot, './src/client/index.js'),
]
},
target: 'web',
output: {
path: assetsPath, // Note: Physical files are only output by the production build task `npm run build`.
publicPath: publicPath,
pathinfo: false,
filename: 'bundle/[name].js',
chunkFilename: 'bundle/chunk-[name].js',
hotUpdateChunkFilename: '[hash].hot-update.js', // use for AssetsPlugin to filter out hot updates
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'process.env.BROWSER': true,
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.DllReferencePlugin({
context: path.join(projectRoot, "src" , "client"),
manifest: require("../dll/commons-manifest.json")
}),
new AssetsPlugin({
fullPath: true,
path: path.join(projectRoot, './dev')
})
],
module: {
noParse: /ffmpeg/,
rules: [
{
test: /\.s[ac]ss$/i,
include: [
path.resolve(projectRoot, './src/shared/'),
path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/stylesheets/'),
],
use: [
"style-loader",
"css-loader?url=false",
"sass-loader",
],
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
loader: "url-loader" ,
options: {
limit: 10000,
mimetype: 'application/font-woff',
name: 'fonts/[name].[ext]'
},
include: [
path.resolve(projectRoot, './src/shared/fonts/') ,
path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/fonts/') ,
path.resolve(projectRoot, './node_modules/font-awesome/fonts/') ,
],
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
loader: "file-loader" ,
options: {
name: 'fonts/[name].[ext]'
},
include: [
path.resolve(projectRoot, './src/shared/fonts/') ,
path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/fonts/') ,
path.resolve(projectRoot, './node_modules/font-awesome/fonts/') ,
],
},
{
test: /(\.jsx)|(\.js)$/i,
exclude: [/node_modules/, /ffmpeg/],
include: [
path.join(projectRoot, "src" , "client"),
path.join(projectRoot, "src" , "shared")
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
"@babel/preset-react",
[
"@babel/preset-env",
{
"modules": false,
"debug": true,
"loose": true,
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 2 ChromeAndroid versions",
"last 2 Edge versions",
"last 2 Firefox versions",
"last 2 FirefoxAndroid versions",
"last 2 iOS versions",
"last 2 Opera versions",
"last 2 Safari versions",
"ie >= 11"
]
},
}
],
],
plugins: [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-proposal-class-properties",
],
},
}
],
},
]
},
resolveLoader: {
modules: [
"node_modules"
],
},
resolve: {
modules: [
"node_modules"
],
unsafeCache : true,
},
profile: true
}
module.exports = config;
|
import * as types from '../../mutation-types'
import lazyLoader from './lazyLoader'
const state = {
items: [
{
name: 'Home',
path: '/',
meta: {
label: ['主頁面'],
link: 'Home.vue',
icon: ['fas', 'home'],
permission: 99
},
components: lazyLoader('Home')
},
{
name: 'Server Status',
path: '/status',
meta: {
label: ['伺服器'],
link: 'Server.vue',
icon: ['fas', 'server'],
permission: 99
},
components: lazyLoader('Server')
},
{
name: 'Files',
path: '/files',
meta: {
label: ['檔案庫'],
link: 'File.vue',
icon: ['fas', 'database'],
permission: 0
},
components: lazyLoader('File')
},
{
name: 'Monit',
path: '/monit',
meta: {
label: ['監視器'],
link: 'Monit.vue',
icon: ['fas', 'video'],
permission: 1
},
components: lazyLoader('Monit')
},
{
name: 'Todo List',
path: '/todos',
meta: {
label: ['待辦事項'],
link: 'Todos.vue',
icon: ['fas', 'calendar-check'],
permission: 2
},
components: lazyLoader('Todos')
},
{
name: 'Post',
path: '/post',
meta: {
label: ['新增文章'],
link: 'Post.vue',
icon: ['fas', 'file'],
permission: 3
},
components: lazyLoader('Post/Add')
},
{
name: 'Post List',
path: '/post-list',
meta: {
label: ['文章列表'],
link: 'Post.vue',
icon: ['fas', 'list-alt'],
permission: 3
},
components: lazyLoader('Post/List')
},
{
name: 'News',
path: '/news',
meta: {
label: ['新增新聞'],
link: 'News.vue',
icon: ['fas', 'plus'],
permission: 2
},
components: lazyLoader('News/Add')
},
{
name: 'News List',
path: '/news-list',
meta: {
label: ['新聞列表'],
link: 'News.vue',
icon: ['fas', 'newspaper'],
permission: 2
},
components: lazyLoader('News/List')
}
]
}
const mutations = {
[types.EXPAND_MENU] (state, menuItem) {
if (menuItem.index > -1) {
if (state.items[menuItem.index] && state.items[menuItem.index].meta) {
state.items[menuItem.index].meta.expanded = menuItem.expanded
}
} else if (menuItem.item && 'expanded' in menuItem.item.meta) {
menuItem.item.meta.expanded = menuItem.expanded
}
}
}
export default {
state,
mutations
}
|
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports LevelRowColumnUrlBuilder
* @version $Id: LevelRowColumnUrlBuilder.js 2643 2015-01-09 20:37:58Z tgaskins $
*/
define([
'../error/ArgumentError',
'../util/Logger',
'../util/WWUtil'
],
function (ArgumentError,
Logger,
WWUtil) {
"use strict";
/**
* Constructs a URL builder for level/row/column tiles.
* @alias LevelRowColumnUrlBuilder
* @constructor
* @classdesc Provides a factory to create URLs for level/row/column tile REST requests.
* <p>
* URLs are formed by appending the specified server address with the specified path and appending
* a path of the form <em>/level/row/row_column.image-format</em>, where image-format is the corresponding
* suffix to the image mime type specified when a URL is requested. For example, if the specified server
* address is <em>http://worldwindserver.net/webworldwind</em> and the specified path-to-data is
* <em>../data/Earth/BMNG256</em>, and the requested tile's level, row and column are 0, 5 and 9 respectively,
* and the image format is <em>image/jpeg</em>, the composed URL is
* <em>http://worldwindserver.net/webworldwind/../data/Earth/BMNG256/0/5/5_9.jpg.
*
* @param {String} serverAddress The server address. May be null, in which case the address is assumed to be
* the current location (see <code>window.location</code>) minus the last path component.
* @param {String} pathToData The path to the dataset on the server. May be null or empty to indicate that
* the data is directly relative to the specified server address.
*
*/
var LevelRowColumnUrlBuilder = function (serverAddress, pathToData) {
/**
* The server address.
* @type {String}
*/
this.serverAddress = serverAddress;
if (!serverAddress || serverAddress.length === 0) {
this.serverAddress = WWUtil.currentUrlSansFilePart();
}
/**
* The server-side path to the dataset.
* @type {String}
*/
this.pathToData = pathToData;
};
/**
* Creates the URL string for a WMS Get Map request.
* @param {Tile} tile The tile for which to create the URL.
* @param {String} imageFormat The image format to request.
* @throws {ArgumentError} If the specified tile or image format are null or undefined.
*/
LevelRowColumnUrlBuilder.prototype.urlForTile = function (tile, imageFormat) {
if (!tile) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile", "missingTile"));
}
if (!imageFormat) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile",
"The image format is null or undefined."));
}
var sb = this.serverAddress;
if (this.pathToData) {
sb = sb + "/" + this.pathToData;
}
sb = sb + "/" + tile.level.levelNumber.toString();
sb = sb + "/" + tile.row.toString();
sb = sb + "/" + tile.row.toString() + "_" + tile.column.toString();
sb = sb + "." + WWUtil.suffixForMimeType(imageFormat);
sb = sb.replace(" ", "%20");
return sb;
};
return LevelRowColumnUrlBuilder;
});
|
module.exports = {
entry: './test/unit/specs/index.js',
output: {
path: './test/unit',
filename: 'specs.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /test|node_modules\/dist/,
loader: 'babel-loader'
}
]
}
}
|
define(function(require, exports, module){
'use strict';
var layers = require('cqwrap/layers');
var BaseLayer = layers.BaseLayer, BgLayer = layers.BgLayer;
var BaseScene = cc.Scene.extend({
ctor:function() {
this._super();
this.init.apply(this, arguments);
cc.associateWithNative( this, cc.Scene );
}
});
function loadFrames(cache, frames, callback){
callback(frames);
if(frames.length <= 0){
return;
}
cache.addSpriteFrames(frames[0][0], frames[0][1]);
setTimeout(function(){
loadFrames(cache, frames.slice(1), callback);
}, 100);
}
var LoadingLayer = BaseLayer.extend({
init: function(frameCaches){
this._super();
var self = this;
setTimeout(function(){
var cache = cc.SpriteFrameCache.getInstance();
loadFrames(cache, frameCaches, function(frames){
self.getParent().onProgressChange(1 - frames.length / frameCaches.length);
if(frames.length <= 0){
setTimeout(function(){
self.getParent().onLoaded();
}, 200);
}
});
}, 100);
if(this.setKeypadEnabled){
this.setKeypadEnabled(true);
}
},
backClicked: function(){
this.getParent().backClicked();
}
});
var LoadingScene = BaseScene.extend({
init: function(resFrames){
this._super();
var loadingLayer = new LoadingLayer(resFrames);
this.addChild(loadingLayer);
},
onProgressChange: function(){
//Overload by subclass
},
onLoaded: function(){
//Overload by subclass
},
backClicked: function(){
director.end();
}
});
module.exports = {
BaseScene: BaseScene,
LoadingScene: LoadingScene
};
});
|
'use strict';
var React = require('React');
var createReactClass = require('create-react-class');
var Component = createReactClass({
displayName: 'Component',
render() {
return <div />;
},
});
|
import Ember from 'ember';
import layout from '../templates/container';
import UnlessDestroyedMixin from '../mixins/unless-destroyed';
const { RSVP, Component, Logger:logger } = Ember;
const AsyncActionContainer = Component.extend(UnlessDestroyedMixin, {
layout,
inFlight: false,
result: null,
actions: {
invoke() {
if (!this.attrs.hasOwnProperty('asyncAction')) {
logger.warn('No async-container attribute found for action');
return;
}
this.set('inFlight', true);
this.set('result', null);
return RSVP
.cast(this.attrs.asyncAction(...arguments))
.then(this.unlessDestroyed(function(result) {
this.set('result', result);
return result;
}))
.finally(this.unlessDestroyed(function() {
this.set('inFlight', false);
}));
}
}
});
AsyncActionContainer.reopenClass({
positionalParams: ['asyncAction']
});
export default AsyncActionContainer;
|
/*jslint nomen:true*/
/*global define*/
define([
'backgrid',
'orodatagrid/js/datagrid/formatter/cell-formatter'
], function (Backgrid, CellFormatter) {
'use strict';
var StringCell;
/**
* String column cell. Added missing behaviour.
*
* @export oro/datagrid/cell/string-cell
* @class oro.datagrid.cell.StringCell
* @extends Backgrid.StringCell
*/
StringCell = Backgrid.StringCell.extend({
/**
@property {(Backgrid.CellFormatter|Object|string)}
*/
formatter: new CellFormatter(),
/**
* @inheritDoc
*/
enterEditMode: function (e) {
if (this.column.get("editable")) {
e.stopPropagation();
}
return StringCell.__super__.enterEditMode.apply(this, arguments);
}
});
return StringCell;
});
|
var conectaN_8cpp =
[
[ "main", "conectaN_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4", null ]
];
|
console.log("Hello space !");
|
'use strict';
const
Input = require('./input'),
Level = require('./level'),
StartScreen = require('./start-screen'),
LevelEnding = require('./level-ending'),
GameEnding = require('./game-ending'),
Sound = require('./sound'),
FpsCounter = require('./fps-counter');
const
config = require('./config'),
stats = require('./stats'),
eventBus = require('./event-bus');
Window.meow = () => {
eventBus.fire({ name: 'event.level.end'});
};
class Game {
constructor(stage, renderer) {
this._stage = stage;
this._renderer = renderer;
this._input = new Input();
this._startScreen = new StartScreen(stage, this._input);
this._levelEnding = new LevelEnding(stage, renderer, this._input);
this._gameEnding = new GameEnding(stage);
this._sound = new Sound(this._stage);
this._fpsCounter = new FpsCounter(this._stage, this._input);
this._level = null;
this._levelNumber = 0;
this._mazeOrder = [];
this._lastStep = Date.now();
this._state = 'initialized';
}
start() {
document.body.appendChild(this._renderer.view);
this._input.start();
stats.start();
this._sound.start();
this._fpsCounter.start();
this._fillMazeOrder();
eventBus.register('event.startscreen.end', () => {
this._switchState('level-starting');
});
eventBus.register('event.level.end', () => {
this._switchState('level-ending');
});
eventBus.register('event.level.ending.readyfornext', () => {
this._switchState('level-starting');
});
eventBus.register('event.level.ending.lastlevel', () => {
this._switchState('game-ending');
});
this._switchState('startscreen-active');
}
/**
* Not sure if this will ever be called.
*/
stop() {
this._level.stop();
stats.stop();
this._sound.stop();
this._fpsCounter.stop();
}
draw() {
this._renderer.render(this._stage);
this._fpsCounter.stepRender();
}
step() {
let elapsed = this._calculateElapsed();
switch (this._state) {
case 'initialized':
break;
case 'startscreen-active':
this._startScreen.step(elapsed);
break;
case 'level-starting':
this._level.step(elapsed);
if (this._level.checkForEndLevelCondition()) {
eventBus.fire({ name: 'event.level.end' });
}
break;
case 'level-ending':
this._levelEnding.step(elapsed);
break;
case 'game-ending':
this._gameEnding.step(elapsed);
break;
}
this._sound.step(elapsed);
this._fpsCounter.step(elapsed);
this._resortStageChildren();
}
_fillMazeOrder() {
for (let num = 0; num < config.mazes.length; num++) {
this._mazeOrder.push(num);
}
shuffleArray(this._mazeOrder);
}
_switchState(state) {
this._state = state;
switch (state) {
case 'initialized':
// Do nothing
break;
case 'startscreen-active':
this._startScreen.start();
break;
case 'level-starting':
// TODO: Determine if that was the final level
let currentLevel = this._level;
if (currentLevel !== null && currentLevel !== undefined) {
this._levelNumber = currentLevel.number + 1;
} else {
this._levelNumber = 0;
}
this._level = new Level(
this._levelNumber,
this._input,
this._stage,
this._levelEnding,
this._mazeOrder[this._levelNumber]
);
this._level.start();
break;
case 'level-ending':
this._levelEnding.start(this._levelNumber);
this._level.stop();
break;
case 'game-ending':
this._gameEnding.start();
break;
}
}
_calculateElapsed() {
let elapsed = Date.now() - this._lastStep;
if (elapsed > 1000) {
elapsed = 1000; // enforce speed limit
}
this._lastStep = Date.now();
return elapsed;
}
/**
* Re-sort the stage children to their z-order, if any.
* @private
*/
_resortStageChildren() {
this._stage.children.sort((a, b) => {
if (a.z === undefined || a.z === null) {
return -1;
} else if (b.z === undefined || b.z === null) {
return 1;
} else {
return b.z - a.z;
}
});
}
}
module.exports = Game;
/**
* Fischer-Yates Algorithm
* http://stackoverflow.com/a/6274398/738081
*/
function shuffleArray(arr) {
var counter = arr.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = arr[counter];
arr[counter] = arr[index];
arr[index] = temp;
}
return arr;
}
|
export { default } from 'ember-fhir/models/encounter-class-history';
|
/*
Generates a deck of cards. You can swap cards between the "main" deck and other decks (which can represent players, dealers etc)
Sebastian Lenton 2013
*/
"use strict";
//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];
var deckCardOffset = 2;
function Card( suit, value, index ) {
this.index = index;
this.suit = suit;
this.value = value;
this.flipped = false;
this.getCardString = function( offset ) {
return '<div id="card' + this.index + '" style="top:-' + ( offset * deckCardOffset ) + 'px;" class="card ' + this.suit + '"><p>' + this.value + '</p></div>';
};
this.identify = function() {
return this.suit + ' ' + this.value + ' ' + this.index;
}
}
function Deck( name ) {
this.cards = [];
this.name = name;
this.generate = function() {
var counter = 0;
for( var j = 0; j < suits.length; j++ ) {
for( var i = 0; i < cardValues.length; i++ ) {
this.cards.push( new Card( suits[ j ], cardValues[ i ], counter ) );
//console.log( this.cards[ this.howMany( true ) ].identify() );
}
}
};
this.shuffle = function() {
this.cards = shuffle( this.cards );
};
this.howMany = function( countFromZero ) {
var length = this.cards.length;
if( countFromZero ) {
return length - 1;
} else {
return length;
}
};
this.passCards = function( deck, amount ) { //this could be more efficient
if( !amount ) {
amount = 1;
}
for( var i = 0; i < amount; i++ ) {
var cardToPass = this.cards.pop();
deck.cards.push( cardToPass );
}
}
this.renderAll = function() {
var deckString = '';
for( var j = 0; j < this.cards.length; j++ ) {
deckString += this.cards[ j ].getCardString( j );
}
deckString = '<div id="deck' + this.name + '" class="deck">' + deckString + '</div>';
$( 'body' ).append( deckString );
}
}
var deck = new Deck( 'DefaultDeck' );
var startDeck = new Deck( 'StartDeck' );
var eggDeck = new Deck( 'EggDeck' );
deck.generate();
deck.passCards( eggDeck, 20 );
//deck.passCards( startDeck ); //need to stop too large amounts throwing errors
deck.renderAll();
startDeck.renderAll();
eggDeck.renderAll();
$( '.card' ).click( function() {
console.log( 'clicked;' );
$( this ).toggleClass( 'flipped' );
} )
/*********************
HELPERS
*********************/
function shuffle(array) {
var counter = array.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter--) | 0;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
|
/* -----------------------------------------------------------------------------------------------
* BuddyTok Application
* ----------------------------------------------------------------------------------------------*/
/* global jQuery, _, OT, Backbone, log, alert */
/* global LocalUser, BuddyList, InvitationList, UserInfoView, ConnectModalView, BuddyListView */
/* global InvitationListView, ChatView */
// Declare dependencies and prevent leaking into global scope
(function(
exports, doc, // Environment
$, _, OT, Backbone, log, // External libraries
LocalUser, // Application modules
BuddyList,
InvitationList,
UserInfoView,
ConnectModalView,
BuddyListView,
InvitationListView,
ChatView,
undefined
) {
var App = exports.App = {
// Models
presenceSession: null,
me: null,
buddyList: null,
invitationList: null,
// Views
userInfoView: null,
connectModalView: null,
buddyListView: null,
invitationListView: null,
chatView: null,
initialize: function() {
// Presence session initialization
App.once('presenceSessionReady', App.presenceSessionReady, this);
App.retrievePresenceConfig();
// Model initialization
App.me = new LocalUser({}, { dispatcher: App });
App.buddyList = new BuddyList([], { dispatcher: App });
App.invitationList = new InvitationList([], { dispatcher: App });
// View initialization
App.connectModalView = new ConnectModalView({
model: App.me,
el: $('#connect-modal'),
dispatcher: App
});
App.userInfoView = new UserInfoView({ model: App.me });
App.buddyListView = new BuddyListView({
collection: App.buddyList,
dispatcher: App
});
App.invitationListView = new InvitationListView({ collection: App.invitationList });
App.chatView = new ChatView({
dispatcher: App,
localUser: App.me
});
$(doc).ready(App.domReady);
},
retrievePresenceConfig: function() {
$.get('/presence')
.done(function(presenceConfig) {
log.info('App: presenceSessionReady');
App.presenceSession = OT.initSession(presenceConfig.apiKey, presenceConfig.sessionId);
App.trigger('presenceSessionReady', App.presenceSession);
})
.fail(function(jqXHR, responseText, errorThrown) {
log.error('App: presenceSessionReady failed', errorThrown);
alert('Could not retreive the presence configuration. Please try again later');
});
},
domReady: function() {
log.info('App: domReady');
// NOTE: App.connectModalView is already in the DOM and does not need to be rendered
App.connectModalView.show();
App.userInfoView.render().$el.appendTo('.navbar-right');
App.buddyListView.render().$el.appendTo('.sidebar-left');
App.invitationListView.render().$el.appendTo('.row-top');
App.chatView.render().$el.appendTo('.content-right');
},
};
_.extend(App, Backbone.Events);
App.initialize();
}(window, window.document, jQuery, _, OT, Backbone, log, LocalUser, BuddyList, InvitationList,
UserInfoView, ConnectModalView, BuddyListView, InvitationListView, ChatView));
|
'use strict';
/* global angular */
(function() {
var register = angular.module('register');
register.controller('RegisterController', function($rootScope, $scope, $state, sessionFactory) {
$scope.stateName = 'register';
$scope.name = '';
$scope.email = '';
$scope.password = '';
$scope.loading = false;
$scope.registerAndLogin = function() {
if (!$scope.form.$valid) {
return;
}
$scope.loading = false;
var user = { };
user.name = $scope.name;
user.email = $scope.email;
user.password = $scope.password;
sessionFactory.registerAndLogin(user)
.then(function() {
$scope.loading = false;
$state.go('app-root.list');
});
};
});
})();
|
const removeMigratorDir = require('./removeMigratorDir');
module.exports = ({migrator}) => {
return Promise.resolve()
.then(() => migrator.disconnect())
.then(() => removeMigratorDir(migrator))
.then(() => migrator);
};
|
'use strict'
module.exports = function () {
this.When(/^preencher as características do produto$/, {timeout: 60 * 1000}, function (callback) {
})
this.When(/^selecionar alguma categoria$/, {timeout: 60 * 1000}, function (callback) {
})
this.Then(/^devo visualizar o campo de foto do produto$/, {timeout: 60 * 1000}, function (callback) {
})
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:b0478c6949985585d1cbadad447cd75680baa15e4f0fab56943993d2f24afe67
size 4569
|
/*!
Grape JavaScript game engine
(c) 2012-<%= grunt.template.today('yyyy') %> Zoltan Mihalyi.
https://github.com/zoltan-mihalyi/grape/blob/master/MIT-LICENSE.txt
*/
|
/*!
* heap.js - example.js
* Author: dead_horse <dead_horse@qq.com>
*/
/**
* Module dependencies.
*/
var heaps = require('./');
var bHeap = heaps.binaryHeap(function (a, b) {
return a.value - b.value;
});
for (var i = 0; i < 10; i++) {
bHeap.push({
value: Math.random()
});
}
var result = [];
while(!bHeap.empty()) {
result.push(bHeap.pop());
}
console.log('%j', result);
|
var pkg = require('../package.json'); //Application Settings
var fs = require('fs');
var db;
var collection; //Twitter Collection
var summaryLength = 2;
var summary = {}; //Tweets by country, total tweets, total smiley face matches
summary.name="World Text";
var countries;
//Heat map coloring
//Provide a range minimum and maximum along with the target value
//Returns a CSS ready RGB value
var rgb = function(heats, value) {
var index = Math.floor(heats.length/9);
var colors = ['rgb(247,244,249)','rgb(231,225,239)','rgb(212,185,218)',
'rgb(201,148,199)','rgb(223,101,176)','rgb(231,41,138)',
'rgb(206,18,86)','rgb(152,0,67)','rgb(103,0,31)'];
if( value < heats[index]){
return colors[0];
}else if ( value <= heats[index*2]){
return colors[1];
}else if ( value <= heats[index*3]){
return colors[2];
}else if ( value <= heats[index*4]){
return colors[3];
}else if ( value <= heats[index*5]){
return colors[4];
}else if ( value <= heats[index*6]){
return colors[5];
}else if ( value <= heats[index*7]){
return colors[6];
}else if ( value <= heats[index*8]){
return colors[7];
}else{
return colors[8];
}
};
var createSummary = function() {
console.log("Starting createSummary");
collection.distinct("properties.country", function(err, docs) {
if (err) {
console.error("Error - distinct countries: " + err.message);
} else {
countries = docs;
summaryLength += (countries.length * 2);
for (var x = 0; x < countries.length; x++) {
countries[x] = countries[x].replace(/\./g,'_');
countrySum(countries[x]);
}
}
wrapIt();
});
};
var countrySum = function(country) {
summary[country] = {};
collection.count({
"properties.country": country
}, {}, function(err, count) {
if (err) {
console.error("Error - summary[" + country + "].total: " + err.message);
} else {
summary[country].total = count;
}
wrapIt();
});
//Regular expression matching for the following smiley faces:
//:) :D :-D ;) :-) :P :p :-P :-p =) ;-) =D =] :] =P :-D ^_^ (^^) (: (8 (;
collection.count({
"properties.country": country,
$or:[
{"properties.text":{$regex:/\:\)/}},
{"properties.text":{$regex:/\:D/}},
{"properties.text":{$regex:/\:\-D/}},
{"properties.text":{$regex:/\(\^\^\)/}},
{"properties.text":{$regex:/\;\)/}},
{"properties.text":{$regex:/\:\-\)/}},
{"properties.text":{$regex:/\:p/}},
{"properties.text":{$regex:/\=\)/}},
{"properties.text":{$regex:/\=D/}},
{"properties.text":{$regex:/\=\]/}},
{"properties.text":{$regex:/\:\]/}},
{"properties.text":{$regex:/\:\-D/}},
{"properties.text":{$regex:/\^\_\^/}},
{"properties.text":{$regex:/\(\:/}},
{"properties.text":{$regex:/\(8/}},
{"properties.text":{$regex:/\(\;/}},
{"properties.text":{$regex:/\:\-P/}},
{"properties.text":{$regex:/\:\-p/}},
{"properties.text":{$regex:/\:p/}},
{'properties.text':/😄|😃|😀|😊|☺|😉|😍|😘|😚|😗|😙|😜|😝|😛|😁|😇|😏|👮|👷|👶|👦|👧|👨|👩|👴|👵|👱|👼|👸|😺|😸|👹|👽|💩/}
]
}, {}, function(err, count) {
if (err) {
console.error("Error - summary[" + country + "].textMatch: " + err.message);
} else {
summary[country].textMatch = count;
}
wrapIt();
});
};
var countryCode = function() {
console.log("Starting countryCode");
var heats = [];
for (var x = 0; x < countries.length; x++) {
summary[countries[x]].percent = summary[countries[x]].textMatch / summary[countries[x]].total;
heats.push(summary[countries[x]].percent);
}
heats.sort(function(a,b){return a-b;});
console.log("Creating HeatMap");
for (var x = 0; x < countries.length; x++) {
if (summary[countries[x]].total) {
summary[countries[x]].heat = rgb(heats, summary[countries[x]].percent);
}
};
wrapIt();
};
var wrapIt = function() {
summaryLength -= 1;
if (summaryLength == 1) {
//DB queries done
countryCode();
} else if (summaryLength == 0) {
console.log('Saving World Text Summary');
db.collection('summary').update({"name": "World Text"}, summary, {upsert: true, w:1, safe:true},function(err) { if(err) { console.error(err.message); } db.close(); });
}
};
var dbLoaded = function(err, database) {
if (err) {
console.error(err.message);
}
db = database;
collection = db.collection('twitter');
console.log("Database Connected");
createSummary();
};
require('mongodb').MongoClient.connect(pkg.config.db_url, dbLoaded);
|
const util = require('../util/httpUtil.js')
function createTask (name, content, creatorId, memberId, progressId, file, ddl) {
return util.httpPost(util.baseURL + 'task', {
name: name,
content: content,
creatorId: creatorId,
memberIds: memberIds,
progressId: progressId,
file: file,
ddl: ddl
})
}
function deleteTask (projectId, taskId, userId) {
return util.httpDel(util.baseURL + 'task', {projectId: projectId, taskId: taskId, userId: userId})
}
function getTaskList (projectId, userId) {
return util.httpGet(util.baseURL + 'task/list?projectId=” + = projectId “&userId=“ + userId')
}
function updateInfo (taskId, executorId, userId) {
return util.httpPut(util.baseURL + 'task/item', {
taskId: taskId,
executorId: executorId,
userId: userId
})
}
function getInfo (projectId, taskId) {
return util.httpGet(util.baseURL + 'task/item?projectId=” + = projectId “&taskId” += taskId')
}
function updateState (taskId, userId) {
return util.httpPut(util.baseURL + 'task/state', {
taskId: taskId,
userId: userId
})
}
function createSubTask (subtaskContent, taskId, userId) {
return util.httpPost(util.baseURL + 'subtask', {
subtaskContent: subtaskContent,
taskId: taskId,
userId: userId
})
}
function deleteSubTask (subtaskId, userId) {
return util.httpDel(util.baseURL + 'subtask', {subtaskId: subtaskId, userId: userId})
}
function getSubtaskList (subtaskId) {
return util.httpGet(util.baseURL + 'subtask/list/?subtaskId=” += subtaskId')
}
function updateSubtaskInfo (subtaskId, subtaskExecutorId) {
return util.httpPut(util.baseURL + 'subtask', {
subtaskId: subtaskId,
subtaskExecutorId: subtaskExecutorId
})
}
function updateSubtaskState (subtaskId, userId) {
return util.httpPut(util.baseURL + 'subtask/state', {
subtaskId: subtaskId,
userId: userId
})
}
function addMember (taskId, participatorIds) {
return util.httpDel(util.baseURL + 'task/participator', {
taskId: taskId,
participatorIds: participatorIds
})
}
function deleteMember (taskId, participatorIds) {
return util.httpDel(util.baseURL + 'task/participator', {
taskId: taskId,
participatorIds: participatorIds
})
}
function getMemberList (taskId) {
return util.httpGet(util.httpGet + 'task/participator/list?taskId=“ + taskId')
}
module.exports = {
createTask,
deleteTask,
getTaskList,
updateInfo,
getInfo,
updateState,
createSubTask,
deleteSubTask,
getSubtaskList,
updateSubtaskInfo,
updateSubtaskState,
addMember,
deleteMember,
getMemberList
}
|
import { h, Component } from 'preact';
import './style.css';
export default class Imprint extends Component {
render() {
return (
<div className="c-imprint b-content">
<h1>Imprint</h1>
<p>
Name
<br />
Address
<br />
Country
<br />
contact@example.com
</p>
</div>
);
}
}
|
var Notify = require('../')
var tape = require('tape')
var pull = require('pull-stream')
tape('simple', function (t) {
var notify = Notify()
var r = Math.random()
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
t.end()
})
)
t.equal(notify(r), r)
notify.end()
})
tape('end', function (t) {
var notify = Notify()
var r = Math.random()
var n = 3
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
t.equal(notify(r), r)
notify.end()
})
|
/*!
* wyre: the new way to do websockets
* Copyright(c) 2015 Jordan S Davidson <thatoneemail@gmail.com>
* MIT Licensed
*/
var port = 22345;
exports = module.exports = function() {
return port++;
}
|
$(document).ready(function () {
$(".courses").each(function () {
var courseClass = ['course-blue', 'course-red', 'course-green', 'course-peach', 'course-darck-green', 'course-darck-blue', 'course-purple', 'course-orange'];
var rand = courseClass[Math.floor(Math.random() * courseClass.length)];
$(this).addClass(rand);
});
});
|
export default _normalizeLink;
/**
This method normalizes a link to an "links object". If the passed link is
already an object it's returned without any modifications.
See http://jsonapi.org/format/#document-links for more information.
@method _normalizeLink
@private
@param {String} link
@return {Object|null}
@for DS
*/
function _normalizeLink(link) {
switch (typeof link) {
case 'object':
return link;
case 'string':
return { href: link };
}
return null;
}
|
import React, { Component, PropTypes } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
export default class Home extends Component {
static propTypes = {
onNavigate: PropTypes.func.isRequired
};
toCounter = () => {
const { onNavigate } = this.props;
onNavigate({
type: 'push',
key: 'counter'
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native Boilerplate!
</Text>
<TouchableOpacity onPress={this.toCounter}>
<Text style={styles.instructions}>Navigate to Counter</Text>
</TouchableOpacity>
</View>
);
}
}
|
// A '.tsx' file enables JSX support in the TypeScript compiler,
// for more information see the following page on the TypeScript wiki:
// https://github.com/Microsoft/TypeScript/wiki/JSX
/// ../typings/es6-promise/es6-promise.d.ts
var Adal = require('./adal.js');
// very important!!! if you put these locally then multiple versions of react get loaded and cause random errors
var React = require('react');
var ReactDOM = require('react-dom');
var Office365_Adal = (function () {
function Office365_Adal() {
}
Office365_Adal.launchWebAuth = function () {
// redirectUri: 'ms-app://S-1-15-2-362237037-3722746685-439561638-2597901564-3613092599-1873846187-518014421'
/* GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
response_type=code&
client_id=32613fc5-e7ac-4894-ac94-fbc39c9f3e4a&
redirect_uri=https:%2f%2foauthplay.azurewebsites.net%2f&
scope=openid+offline_access+https:%2f%2foutlook.office.com%2fmail.read+https:%2f%2foutlook.office.com%2fcalendars.read+https:%2f%2foutlook.office.com%2fcontacts.read&state=f561be3f-e050-4251-bf32-9ae73fc7a6ce&
prompt=login HTTP/1.1
*/
var urlToGo = '';
var displayCallback = function (url) {
urlToGo = url;
};
var config = {
tenant: 'trewin.onmicrosoft.com',
clientId: 'fd79b0e0-38b3-42e7-97fd-2f42d47beb6f',
cacheLocation: 'localStorage',
instance: 'https://login.windows.net/',
resource: 'https://outlook.office365.com',
endpoints: {
'https://outlook.office.com/api/v1.0/me/folders/inbox/messages': 'https://outlook.office.com'
}
};
var authContext = new Adal.inject(config);
// always logout for now
authContext.logOut();
Office365_Adal.getUser(authContext).then(function (token) {
console.log(token);
authContext.acquireToken(config.resource, function (error, token) {
if (error || !token) {
console.log(error);
return;
}
});
});
};
Office365_Adal.getUser = function (authContext) {
var dummyAuthPage = 'default.html';
return new Promise(function (resolve, reject) {
// If the user is cached, resolve the promise immediately.
//var user = authContext.getCachedUser();
//if (user) {
// resolve(user);
// return;
//}
// The user was not cached. Open a popup window which
// performs the OAuth login process, then signals
// the result.
authContext.config.redirectUri = window.location.href;
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
var user = authContext.getCachedUser();
if (user) {
resolve(user);
return;
}
else {
authContext.login();
}
});
};
return Office365_Adal;
})();
module.exports = Office365_Adal;
//// var officeURL = 'https://login.microsoftonline.com/trewin.onmicrosoft.com/oauth2/authorize?response_type=code&client_id=';
////var windowsLoginURL = 'https://login.microsoftonline.com/448cfd31-021b-4a3c-beb9-26d8ba169252/oauth2/v2.0/authorize?response_type=code&client_id=';
//var windowsLoginURL = "https://login.windows.net/Common/oauth2/authorize?response_type=code&client_id=";
//var clientID = 'fd79b0e0-38b3-42e7-97fd-2f42d47beb6f';
//var callbackURL = 'http://localhost:3030/oauth2Callback';
//// var callbackURL = 'ms-app://S-1-15-2-362237037-3722746685-439561638-2597901564-3613092599-1873846187-518014421';
//// var scope = 'https://outlook.office.com/Mail.Read';
//// var resource = "00000002-0000-0000-c000-000000000000";
//var resource = "https://outlook.office365.com";
//# sourceMappingURL=Office365_Adal.js.map
|
// API
// ===
module.exports.api = function(server<% if(mongo){ %>, schema<% } %>) {
// Sample Rest Call
server.get('/hello', function(req, res){
res.send('<h1>Hello World!</h1>');
});
}
|
/**
* angular-strap
* @version v2.1.7 - 2015-10-19
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes (olivier@mg-crea.com)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
"use strict";angular.module("mgcrea.ngStrap.alert").run(["$templateCache",function(t){t.put("alert/alert.tpl.html",'<div class="alert" ng-class="[type ? \'alert-\' + type : null]"><button type="button" class="close" ng-if="dismissable" ng-click="$hide()">×</button> <strong ng-bind="title"></strong> <span ng-bind-html="content"></span></div>')}]);
|
module.exports = {
dir: ""
}
|
const td = require("testdouble");
const proxyquire = require("proxyquire");
const expect = require("chai").expect;
describe("configurationRepository.spec.js", () => {
const cwd = "/home/pawel/workspace/logweb";
const configurationData = {any: "configuration value"};
let configurationRepository;
let fsMock;
let processCwdMock;
let argvSliceMock;
beforeEach(() => {
fsMock = {
readFileSync: td.function(),
writeFile: td.function(),
"@noCallThru": true
};
processCwdMock = td.replace(process, "cwd");
argvSliceMock = td.replace(process.argv, "slice");
td.when(processCwdMock()).thenReturn(cwd);
configurationRepository = proxyquire("./configurationRepository", {fs: fsMock});
});
afterEach(() => {
td.reset();
});
describe("argv configuration", () => {
const configFile = "config/custom-config.json";
beforeEach(() => {
td.when(argvSliceMock(2)).thenReturn([configFile]);
});
it("should load configuration from command argv", () => {
// given
td.when(fsMock.readFileSync(`${cwd}/${configFile}`, "utf8")).thenReturn(JSON.stringify(configurationData));
// expect
expect(configurationRepository.loadConfiguration()).to.eql(configurationData);
});
it("should save configuration file to argv parameter", done => {
// given
td.when(
fsMock.writeFile(
`${cwd}/${configFile}`,
JSON.stringify(configurationData, null, 2),
"utf8"),
{ignoreExtraArgs: true}
).thenCallback(null);
// when
configurationRepository
.saveConfiguration(configurationData)
.then(() => done());
});
});
describe("default configuration location", () => {
beforeEach(() => {
td.when(argvSliceMock(2)).thenReturn([]);
});
it("should load configuration from file named logweb.json in current working directory", () => {
// given
td.when(fsMock.readFileSync(`${cwd}/logweb.json`, "utf8")).thenReturn(JSON.stringify(configurationData));
// expect
expect(configurationRepository.loadConfiguration()).to.eql(configurationData);
});
it("should save configuration to file named logweb.json in current working directory", done => {
// given
td.when(
fsMock.writeFile(
`${cwd}/logweb.json`,
JSON.stringify(configurationData, null, 2),
"utf8"),
{ignoreExtraArgs: true}
).thenCallback(null);
// when
configurationRepository
.saveConfiguration(configurationData)
.then(() => done());
});
});
});
|
EmberApp.ModalDialogComponent = Ember.Component.extend({
actions: {
close: function() {
return this.sendAction('close');
},
save: function(){
return this.sendAction('close', 'save');
}
}
});
|
{
String.fromCodePoint(Infinity);
}
|
'use strict';
function f1(a, b) {
console.log('f1(' + a + ', ' + b + ')');
}
f1(2, 3);
f1.call(null, 2, 3);
f1(...[2, 3]);
f1.apply(null, [2, 3]);
|
var Intersection;
(function (Intersection) {
class Result {
constructor(success, distance, point) {
this.success = success;
this.distance = distance;
this.point = point;
}
}
Result.FAILED = new Result(false, 1000000);
Intersection.Result = Result;
class Point {
constructor(hp, normal, material, object) {
this.hp = hp;
this.normal = normal;
this.material = material;
this.object = object;
}
}
Intersection.Point = Point;
})(Intersection = exports.Intersection || (exports.Intersection = {}));
//# sourceMappingURL=scene-object.js.map
|
var
fs = require("fs"),
path = require("path"),
url = require("url"),
images = require("images"),
ab_getPath = require("./abc-util-getPath").getPath,
ab_extend = require("./abc-util-extend").extend,
ab_checkMime = require("./abc-util-checkMime").checkMime,
ab_getType = require("./abc-util-getType").getType,
ab_model = require("./abc-opt"),
ab_optOptions = ab_model.opt_options,
ab_optTask = ab_model.opt_task,
ab_optPreOpt = ab_model.opt_preOpt;
var
preOpt2IdPreOpt;
/**
* 修改预处理参数("{$now}" -> "{xxx@$now}")修改
* 如果不存在于 ab_optPreOpt 中,则不作处理
*
* @param {string} srcStr : [] 源字符串
* @param {string|number} idname : [] id 名
*
* @return {string} : [] 处理完的字符串
*/
exports.preOpt2IdPreOpt = preOpt2IdPreOpt = function(srcStr, idName) {
return srcStr.replace(/\{\$[^{}]+\}/g, function(str) {
var
__name = str
.replace(/^\{\s*/, '')
.replace(/\s*\}$/, ''),
__isSupport = __name in ab_optPreOpt,
__newStr = __isSupport ? "{" + idName + "@" + __name + "}" : str;
return __newStr;
});
};
/**
* 生成单个完整的任务对象
*
* @param {object} taskOpt : [] 从文本转换成的基本对象(结构与 ab_optOptions 一致)
* @param {object} baseOpt : [ {} ] 公共参数对象(结构与 ab_optTask 一致)
*
* @return {object} : [] 处理完的 task 参数对象
*/
exports.createTask = function(taskOpt, baseOpt) {
// 退出 -> 参数类型错误
if (ab_getType(taskOpt) !== "object") {
throw "ERROR: createTask: 第一个参数必须为对象(第二个参数选填)<- " + taskOpt;
}
var
_taskOpt = ab_extend({}, ab_optTask, taskOpt),
_baseOpt = baseOpt || {},
_baseOpt = ab_extend({}, ab_optOptions, baseOpt),
_fold = _taskOpt.fold,
_files = [], // 指定文件夹中的文件列表
_re_fName = /[^\/\\]+?$/, // 路径中,最末的文件名
_re_lastSep = /[\\\/]+?$/,
_now = new Date();; // 去除完文件名后的最末的 "/" 或 "\"
var __func_add0;
_func_add0 = function(num) {
return (num < 10 ? "0" : "") + num;
};
// (内部变量)id、时间
_taskOpt._dateRaw
= _now.getTime();
_taskOpt._dateNow
= ""
+ _now.getFullYear()
+ _func_add0(_now.getMonth() + 1)
+ _func_add0(_now.getDate())
+ _func_add0(_now.getHours())
+ _func_add0(_now.getMinutes())
+ _func_add0(_now.getSeconds());
_taskOpt._id
= _taskOpt._dateRaw
+ Math.random()
.toString(16)
.replace(/^0\./, "");
// img 和 css 的路径值中的预处理变量进行处理(如 "{$now}" -> "{nnn:$now}")
_taskOpt.img = preOpt2IdPreOpt(_taskOpt.img, _taskOpt._id);
_taskOpt.css = preOpt2IdPreOpt(_taskOpt.css, _taskOpt._id);
var
_imgUrl = url.parse(_taskOpt.img),
_imgSearch = _imgUrl.search || "",
_cssUrl = url.parse(_taskOpt.css),
_cssSearch = _cssUrl.search || "";
// 解码 search 部分
_taskOpt._imgSearch = decodeURIComponent(_imgSearch);
_taskOpt._cssSearch = decodeURIComponent(_cssSearch);
// 去除 search 部分
_taskOpt.img = _taskOpt.img.replace(/\?[^?]+$/, "");
_taskOpt.css = _taskOpt.css.replace(/\?[^?]+$/, "");
// 提取目录部分
_taskOpt.imgFold = _taskOpt.img.replace(_re_fName, '').replace(_re_lastSep, '');
_taskOpt.cssFold = _taskOpt.css.replace(_re_fName, '').replace(_re_lastSep, '');
// 退出 <- 仅支持 png 或 jpg 输出
if ( !_taskOpt.img.match(/\.(png|jpg)$/i) ) {
throw "WARM: createTask: 仅支持 png 或 jpg 输出 <- " + _taskOpt.img;
}
// 退出 <- 目录不存在
if (ab_getPath(_fold).status !== 1) {
throw "ERROR: createTask: 目录不存在或为外链 <- " + _fold;
}
_files = fs.readdirSync(_fold);
// 退出 <- 指定文件夹不存在图片文件
if (!_files || _files.length === 0) {
throw "ERROR: createTask: 指定文件夹不存在图片文件 <- " + _fold;
}
// 读取图片,并进行相关操作
for (var i = 0, len = _files.length; i < len; i++) {
var __checkVal = _files[i].match(/\.(jpg|png|gif)$/i);
// 不添加到操作列表中 <- 文件后缀不为 jpg/png/gif
if (!__checkVal) {
continue;
}
var __imgPath = path.join(_fold, _files[i]);
// 不添加到操作列表中 <- 文件后缀与其文件 mime 类型不匹配
// (总处理时间增加大约 50ms)
if (!ab_checkMime(__imgPath, __checkVal[0].replace(/^\./, ""))) {
continue;
}
var
__img = images(__imgPath);
__imgW = __img.width(),
__imgH = __img.height(),
__name = _files[i]
.replace(/\.(jpg|png|gif)$/i, ''), // 去掉后缀(.jpg | .png | .gif)的文件名
__cssOptStr = (/#/.test(__name)) ?
__name.replace(/^[^#]*?#/, '') :
'' ,
__cName = __name
.replace(__cssOptStr, '')
.replace(/^\d+[\s]*/g,'')
.replace("#",'')
.replace(/[ ]+/g, '_');
// 不添加到操作列表中 <- 文件名前缀为 #
if (/^#/.test(__name)) {
continue;
}
_taskOpt.filename.push(__name);
_taskOpt.cssname.push(__cName);
_taskOpt.cssOptStr.push(__cssOptStr);
_taskOpt.images.push(__img);
_taskOpt.imagesPath.push(__imgPath);
_taskOpt.widths.push(__imgW);
_taskOpt.heights.push(__imgH);
_taskOpt.maxWidth = (__imgW > _taskOpt.maxWidth) ? __imgW : _taskOpt.maxWidth;
_taskOpt.maxHeight = (__imgH > _taskOpt.maxHeight) ? __imgH : _taskOpt.maxHeight;
_taskOpt.totalWidth += __imgW;
_taskOpt.totalHeight += __imgH;
// 子类操作参数继承基类操作参数
_taskOpt.opt = ab_extend({}, _baseOpt, _taskOpt.opt);
}
return _taskOpt;
};
|
angular.module('ira.gobiernosLocales', ['ira.core']).config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('gobiernosLocales', {
abstract: true,
url: '/gobiernosLocales',
template: '<ui-view/>'
});
}]);
|
version https://git-lfs.github.com/spec/v1
oid sha256:2c3b21c8a49c14ad439fc2110acb23f5c059f92e96b26b09dbe8761d4b912e09
size 21510
|
'use strict';
module.exports = {
id: 0x6E,
type: 'MONEYN',
name: 'MoneyN',
dataLengthLength: 1
};
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.6-4-531-11
description: >
Object.defineProperty will update [[Get]] and [[Set]] attributes
of named accessor property 'P' successfully when [[Configurable]]
attribute is true, 'A' is an Array object (8.12.9 step 11)
includes: [propertyHelper.js]
---*/
var obj = [];
obj.verifySetFunction = "data";
Object.defineProperty(obj, "prop", {
get: function () {
return obj.verifySetFunction;
},
set: function (value) {
obj.verifySetFunction = value;
},
configurable: true
});
obj.verifySetFunction1 = "data1";
var getFunc = function () {
return obj.verifySetFunction1;
};
var setFunc = function (value) {
obj.verifySetFunction1 = value;
};
Object.defineProperty(obj, "prop", {
get: getFunc,
set: setFunc
});
verifyEqualTo(obj, "prop", getFunc());
verifyWritable(obj, "prop", "verifySetFunction1");
verifyNotEnumerable(obj, "prop");
verifyConfigurable(obj, "prop");
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema ({
patchId: {
type: Schema.Types.ObjectId,
ref: 'Patch'
},
sequence: {
type: Array,
required: [true, 'Sequence array required.']
},
tempo: {
type: Number,
default: 120
}
// key: {
// type: String,
// default: 'C'
// }
});
module.exports = mongoose.model('Sequence', schema);
|
"use strict";
//# sourceMappingURL=cli.js.map
|
function scoreS(p1, px, p2, e1, ex, e2) {
var checksum1 = p1 + px + p2;
var checksum2 = e1 + ex + e2;
if (checksum1 > 0 && checksum2 > 0) {
p1 = p1 / checksum1;
px = px / checksum1;
p2 = p2 / checksum1;
e1 = e1 / checksum2;
ex = ex / checksum2;
e2 = e2 / checksum2;
return 100 - 50 * ((e1 - p1) * (e1 - p1) + (ex - px) * (ex - px) + (e2 - p2) * (e2 - p2));
} else return 0;
}
//funzione di score T con ass. prob. (p1,px,p2) e risultato di verità (e1,ex,e2)
function scoreT(p1, px, p2, e1, ex, e2) {
var checksum1 = p1 + px + p2;
var checksum2 = e1 + ex + e2;
if (checksum1 > 0 && checksum2 > 0) {
p1 = p1 / checksum1;
px = px / checksum1;
p2 = p2 / checksum1;
e1 = e1 / checksum2;
ex = ex / checksum2;
e2 = e2 / checksum2;
var v1 = e1 - p1,
v2 = v1 + ex - px;
return 100 - 50 * (v1 * v1 + v2 * v2);
} else return 0;
}
function calcola_classifica_scoreS(array_giocatori, array_risultati) {
var ret = [];
var c, d, iniz_giocatori = 0,
score_non_valido = 0;
var temp = [],
temp2 = [],
tt = 0;
var min_score, lista_score_mancanti = [];
for (var week in array_risultati) {
for (var partita in array_risultati[week]) {
c = 0;
d = 0;
lista_score_mancanti = [];
min_score = 100;
for (var giocatore in array_giocatori) {
if (iniz_giocatori == 0) {
temp[c] = array_giocatori[giocatore]["name"];
temp2[c] = 0;
}
var p = [];
if (array_giocatori[giocatore]["bets"] && array_giocatori[giocatore]["bets"][week] && array_giocatori[giocatore]["bets"][week][partita]) {
p = array_giocatori[giocatore]["bets"][week][partita];
if (!isNaN(p[0]) && !isNaN(p[2]) && !isNaN(p[1])) {
var e = [];
p = array_giocatori[giocatore]["bets"][week][partita];
e = array_risultati[week][partita];
tt = scoreS(p[0] / 100, p[1] / 100, p[2] / 100, e[0], e[1], e[2]);
if (tt <= min_score) {
min_score = tt;
}
temp2[c] += tt;
} else
score_non_valido = 1;
} else
score_non_valido = 1;
if (score_non_valido == 1) {
lista_score_mancanti[d] = c;
d++;
score_non_valido = 0;
}
c++;
}
if (d > 0)
for (var i = 0; i < d; i++)
temp2[lista_score_mancanti[i]] += min_score;
iniz_giocatori = 1;
}
}
return toArray(temp, temp2, c);
}
//score tipo T
function calcola_classifica_scoreT(array_giocatori, array_risultati) {
var ret = [];
var c, d, iniz_giocatori = 0,
score_non_valido = 0;
var temp = [],
temp2 = [],
tt = 0;
var min_score, lista_score_mancanti = [];
for (var week in array_risultati) {
for (var partita in array_risultati[week]) {
c = 0;
d = 0;
lista_score_mancanti = [];
min_score = 100;
for (var giocatore in array_giocatori) {
if (iniz_giocatori == 0) {
temp[c] = array_giocatori[giocatore]["name"];
temp2[c] = 0;
}
var p = [];
if (array_giocatori[giocatore]["bets"] && array_giocatori[giocatore]["bets"][week] && array_giocatori[giocatore]["bets"][week][partita]) {
p = array_giocatori[giocatore]["bets"][week][partita];
if (!isNaN(p[0]) && !isNaN(p[2]) && !isNaN(p[1])) {
var e = [];
p = array_giocatori[giocatore]["bets"][week][partita];
e = array_risultati[week][partita];
tt = scoreT(p[0] / 100, p[1] / 100, p[2] / 100, e[0], e[1], e[2]);
if (tt <= min_score) {
min_score = tt;
}
temp2[c] += tt;
} else
score_non_valido = 1;
} else
score_non_valido = 1;
if (score_non_valido == 1) {
lista_score_mancanti[d] = c;
d++;
score_non_valido = 0;
}
c++;
}
if (d > 0)
for (var i = 0; i < d; i++)
temp2[lista_score_mancanti[i]] += min_score;
iniz_giocatori = 1;
}
}
return toArray(temp, temp2, c);
}
function toArray(origin, origin2, count) {
var ret = [];
for (var i = 0; i < count; i++)
ret.push({
name: origin[i],
score: parseFloat(origin2[i].toFixed(2))
});
return ret.sort(function(a, b) {
return a.score < b.score;
});
}
exports.calcola_classifica_scoreS = calcola_classifica_scoreS;
exports.calcola_classifica_scoreT = calcola_classifica_scoreT;
|
export const addTestCase = function() {
return {
type: 'EDITOR/VARIABLE_ADD_CASE'
};
};
export const setProperty = function(index, name, value) {
return {
type: 'EDITOR/VARIABLE_SET_PROPERTY',
payload: {
index,
name,
value
}
};
};
export const addVariable = function(index) {
return {
type: 'EDITOR/VARIABLE_ADD_VARIABLE',
payload: {
index
}
};
};
export const setVariable = function(checkIndex, index, name, value, type) {
return {
type: 'EDITOR/VARIABLE_SET_VARIABLE',
payload: {
checkIndex,
index,
name,
value,
type
}
};
};
export default {
addTestCase,
addVariable,
setProperty,
setVariable,
};
|
'use strict';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
doneFilters: false
};
}
componentDidUpdate() {
if (this.props.filters && !this.state.doneFilters) {
$('.button-collapse').sideNav();
this.setState({ doneFilters: true });
}
}
render() {
var buttonClasses = 'button-collapse';
var filters = null;
if (!this.props.filters) {
buttonClasses += ' hidden';
} else {
filters = React.createElement(Filters, this.props);
}
return React.createElement(
'nav',
{ className: 'red', role: 'navigation' },
React.createElement(
'div',
{ className: 'nav-wrapper container' },
React.createElement(
'a',
{ id: 'logo-container', href: '#', className: 'brand-logo' },
'ExQuery'
),
React.createElement(
'div',
{ id: 'slide-out', className: 'side-nav' },
filters
),
React.createElement(
'a',
{
href: '#',
'data-activates': 'slide-out',
className: buttonClasses },
React.createElement('i', { className: 'mdi-navigation-menu' })
)
)
);
}
}
|
// Routes everything '/helper' related.
exports.index = function(app) {
app.get('/datasets', function(req, res) {
res.render('misc/error', {
'info': 'Work in Progress'
});
});
}
|
define(['components/home-page/home'], function(homePage) {
var HomePageViewModel = homePage.viewModel;
var instance;
describe('Home page view model', function() {
beforeEach(function() {
spyOn(HomePageViewModel.prototype, 'loadYelpPlaces').and.callThrough();
instance = new HomePageViewModel();
});
it('should call loadYelpPlaces', function() {
expect(instance.loadYelpPlaces).toHaveBeenCalled();
});
it('filterOptions array should eqal ["all"]', function() {
expect(instance.filterOptions()).toEqual(['all']);
});
});
});
|
import { vec2, vec3, vec4, quat, mat4 } from 'gl-matrix';
import toNDC from '../../util/toNDC';
export default class RotateMode {
constructor(entity, ndc, alignAxis = null) {
this.entity = entity;
this.startQuat = quat.create();
this.mouseHeld = true;
this.ndc = ndc;
this.angle = 0;
this.lastAngle = 0;
this.align = alignAxis != null;
this.alignAxis = alignAxis || [1, 1, 1];
this.alignGlobal = false;
}
enter(manager) {
this.manager = manager;
this.engine = manager.engine;
this.renderer = manager.renderer;
this.engine.actions.renderer.effect.add('axis');
this.setEffect();
let matrixSys = this.engine.systems.matrix;
let mat = matrixSys.get(this.entity);
mat4.getRotation(this.startQuat, mat);
quat.normalize(this.startQuat, this.startQuat);
this.camera = this.engine.systems.renderer.viewportList[0].camera;
let perspPos = vec4.fromValues(0, 0, 0, 1);
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.matrix.get(this.entity));
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.cameraMatrix.getProjectionView(this.camera));
let aspect = this.engine.systems.cameraMatrix.getCurrentAspect(this.camera);
vec4.scale(perspPos, perspPos, 1 / perspPos[3]);
vec2.subtract(perspPos, this.ndc, perspPos);
this.lastAngle = Math.atan2(perspPos[1], perspPos[0] * aspect);
}
exit() {
// Remove axis effect
this.engine.actions.renderer.effect.remove('axis');
}
setEffect() {
this.renderer.effects.axis.direction = this.align ? this.alignAxis : null;
this.renderer.effects.axis.color = this.align && this.alignAxis.concat([1]);
}
setRotation() {
let tmpQuat = quat.create();
let axis = this.alignAxis;
let modifier = 1;
// Shoot a ray from camera to model
let matrixSys = this.engine.systems.matrix;
let cameraPos = matrixSys.getPosition(this.camera);
let entityPos = matrixSys.getPosition(this.entity);
let cameraRay = vec3.create();
vec3.subtract(cameraRay, cameraPos, entityPos);
vec3.normalize(cameraRay, cameraRay);
if (!this.align) {
axis = cameraRay;
} else {
// Compare align axis and camera axis
let cos = vec3.dot(axis, cameraRay);
if (cos < 0) modifier = -1;
}
// Convert it to local space (if any)
let parentMat = matrixSys.getParent(this.entity);
let parentQuat = quat.create();
mat4.getRotation(parentQuat, parentMat);
quat.normalize(parentQuat, parentQuat);
quat.conjugate(parentQuat, parentQuat);
quat.setAxisAngle(tmpQuat, axis, this.angle * modifier);
quat.multiply(tmpQuat, parentQuat, tmpQuat);
quat.multiply(tmpQuat, tmpQuat, this.startQuat);
this.engine.actions.external.execute('transform.setRotation',
this.entity, tmpQuat);
}
mousemove(e) {
let ndc = toNDC(e.clientX, e.clientY, this.renderer);
this.ndc = ndc;
// Get angle :S
let perspPos = vec4.fromValues(0, 0, 0, 1);
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.matrix.get(this.entity));
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.cameraMatrix.getProjectionView(this.camera));
vec4.scale(perspPos, perspPos, 1 / perspPos[3]);
let aspect = this.engine.systems.cameraMatrix.getCurrentAspect(this.camera);
vec2.subtract(perspPos, this.ndc, perspPos);
let angle = Math.atan2(perspPos[1], perspPos[0] * aspect);
let diff = angle - this.lastAngle;
if (diff > Math.PI) diff -= Math.PI * 2;
if (diff < -Math.PI) diff += Math.PI * 2;
this.angle += diff;
this.lastAngle = angle;
this.setRotation();
}
mouseup(e) {
if (e.buttons === 0) this.manager.pop();
}
keydown(e) {
if (e.keyCode === 27) {
this.engine.actions.external.execute('transform.setRotation',
this.entity, this.startQuat, true);
this.manager.pop();
} else if (e.keyCode === 67) {
this.align = false;
this.alignAxis = [1, 1, 1];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 88) {
this.align = true;
this.alignAxis = [1, 0, 0];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 89) {
this.align = true;
this.alignAxis = [0, 1, 0];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 90) {
this.align = true;
this.alignAxis = [0, 0, 1];
this.setRotation();
this.setEffect();
}
}
}
|
import Relay from 'react-relay/classic';
class FindPublicTeamRoute extends Relay.Route {
static queries = {
team: () => Relay.QL`query FindPublicTeam { find_public_team(slug: $teamSlug) }`,
};
static paramDefinitions = {
teamSlug: { required: true },
};
static routeName = 'FindPublicTeamRoute';
}
export default FindPublicTeamRoute;
|
'use strict';
describe('Authentication Identity Specification', function()
{
var _authIdentity;
var _httpBackend;
var _identity = {
key1: 'value1',
key2: 'value2',
key3: {
subKey1: 'subValue1',
subKey2: 'subValue2'
}
};
var _authRequests;
beforeEach(angular.mock.module('dgAuth'));
beforeEach(function()
{
inject(function($injector)
{
_authIdentity = $injector.get('authIdentity');
_authRequests = $injector.get('authRequests');
_httpBackend = $injector.get('$httpBackend');
var http = $injector.get('$http');
spyOn(_authRequests, 'getPromise').andCallFake(function()
{
return http.post('/fake');
});
_httpBackend.whenPOST('/fake').respond(function()
{
return [201, '', ''];
});
});
});
afterEach(function()
{
_httpBackend.verifyNoOutstandingExpectation();
_httpBackend.verifyNoOutstandingRequest();
});
describe('tests access methods', function()
{
it('should get null values', function()
{
expect(_authIdentity.has()).toBeFalsy();
expect(_authIdentity.get()).toBeNull();
expect(_authIdentity.get('some_key')).toBeNull();
});
it('should set the values and gets them', function()
{
_authIdentity.set(null, _identity);
expect(_authIdentity.has()).toBeTruthy();
expect(_authIdentity.get('key1')).toEqual(_identity.key1);
expect(_authIdentity.get('key2')).toEqual(_identity.key2);
expect(_authIdentity.get('key3')).toEqual(_identity.key3);
expect(_authIdentity.get('fake')).toBeNull();
expect(_authIdentity.get()).toEqual(_identity);
});
it('should set one value and gets it', function()
{
_authIdentity.set('key', 'value');
expect(_authIdentity.has()).toBeTruthy();
expect(_authIdentity.get('key')).toEqual('value');
_authIdentity.set(null, _identity);
expect(_authIdentity.get()).toEqual(_identity);
expect(_authIdentity.get('key')).toBeNull();
});
it('should clear the identity', function()
{
_authIdentity.set(null, _identity);
expect(_authIdentity.has()).toBeTruthy();
_authIdentity.clear();
expect(_authIdentity.has()).toBeFalsy();
expect(_authIdentity.get()).toBeNull();
});
});
});
|
angular.module('keyringLogin', ['auth'])
.component('keyringLogin', {
templateUrl : 'users/login',
controllerAs: 'login',
controller: ['$scope', '$http', '$location', '$httpParamSerializerJQLike', 'auth', function($scope, $http, $location, $httpParamSerializerJQLike, auth) {
this.username = '';
this.password = '';
this.submit = function(e, url) {
var url = e.target.action;
e.preventDefault();
e.stopPropagation();
$http({
method: 'POST',
url: url,
data: $httpParamSerializerJQLike({
username: this.username,
password: this.password
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
auth.setToken(data.token);
$location.path('/');
}).error(function(e) {
this.error = e;
}.bind(this));
return false;
};
}]
})
|
var ffi = require('ffi'),
ref = require('ref'),
RefArray = require('ref-array'),
Struct = require('ref-struct'),
Union = require('ref-union'),
_library = require('./');
loadDependentSymbols();
_library._preload['the_dependent'] = [function () {
_library.the_dependent = _library.dependent;
}];
_library.my_enum = {
five: 555,
VAR_THREE: 24,
VAR_TWO: 23,
VAR_FOUR: 25,
VAR_ONE: -1
};
_library._preload['my_function'] = [function () {
_library.my_function = ['double', ['int32', 'int', ref.refType('uint'), 'float']];
_library._functions['my_function'] = _library.my_function;
}];
_library._preload['my_other_function'] = ['pointer', function () {
_library.my_other_function = [ref.refType('double'), [ref.refType('int32'), ref.refType('int'), ref.refType(ref.refType('uint')), ref.refType('float')]];
_library._functions['my_other_function'] = _library.my_other_function;
}];
_library.nothing = Struct({});
_library.nothing.size = 1;
_library._preload['nothing'] = [function () {
_library.nothing.size = 0;
_library.nothing.defineProperty("__ignore", 'char');
}];
_library._preload['nill'] = [function () {
_library.nill = _library.nothing;
}];
_library._preload['zilch'] = ['nill', function () {
_library.zilch = _library.nill;
}];
_library.something = Struct({});
_library.something.size = 1;
_library._preload['something'] = ['nothing', 'nothing', 'dependent', 'dependent', function () {
_library.something.size = 0;
_library.something.defineProperty("field", 'int');
_library.something.defineProperty("another", 'int32');
_library.something.defineProperty("firstfield", _library.__RefArray('int', 4));
_library.something.defineProperty("message", ref.refType('char'));
_library.something.defineProperty("nillo", _library.nothing);
_library.something.defineProperty("dependent", _library.dependent);
}];
_library.flying_struct = Struct({});
_library.flying_struct.size = 1;
_library._preload['flying_struct'] = ['something', 'something', 'flying_struct', function () {
_library.flying_struct.size = 0;
_library.flying_struct.defineProperty("identity", 'longlong');
_library.flying_struct.defineProperty("object", _library.something);
_library.flying_struct.defineProperty("recursive_pointer", ref.refType(_library.flying_struct));
}];
_library._preload['invasion_force'] = [function () {
_library.invasion_force = _library.__RefArray(_library.flying_struct, 64);
}];
_library.variant1 = Union({});
_library.variant1.size = 1;
_library._preload['variant1'] = ['flying_struct', 'flying_struct', 'something', 'something', 'zilch', 'nothing', function () {
_library.variant1.size = 0;
_library.variant1.defineProperty("val1", _library.flying_struct);
_library.variant1.defineProperty("val2", _library.something);
_library.variant1.defineProperty("val3", _library.zilch);
}];
_library.variant2 = Union({});
_library.variant2.size = 1;
_library._preload['variant2'] = ['variant1', 'variant1', 'stat', 'stat', function () {
_library.variant2.size = 0;
_library.variant2.defineProperty("v1", _library.variant1);
_library.variant2.defineProperty("v2", _library.__RefArray('int', 5));
_library.variant2.defineProperty("str", (function () {
var temp = Struct({});
temp.defineProperty("text", ref.refType('char'));
temp.defineProperty("length", 'ulong');
return temp;
})());
_library.variant2.defineProperty("gs", _library.stat);
}];
_library._preload['my_function_pointer'] = ['void (int, int *, struct flying_struct *)', function () {
_library.my_function_pointer = ffi.Function('void', ['int', ref.refType('int'), ref.refType(_library.flying_struct)]);
}];
_library._preload['my_other_function_pointer'] = ['unsigned int (long double, long double, long long)', function () {
_library.my_other_function_pointer = ffi.Function('uint', ['double', 'double', 'longlong']);
}];
_library._preload['my_undefined_struct_typedef'] = [function () {
_library.my_undefined_struct_typedef = 'void';
}];
_library._preload['my_struct_function'] = ['variant1', function () {
_library.my_struct_function = ['void', [ref.refType(_library.variant1)]];
_library._functions['my_struct_function'] = _library.my_struct_function;
}];
_library.my_unused_struct = Struct({});
_library.my_unused_struct.size = 1;
_library._preload['my_unused_struct'] = [function () {
_library.my_unused_struct.size = 0;
_library.my_unused_struct.defineProperty("a", 'int');
}];
function loadDependentSymbols() {
require('./used.js');
}
|
/**
* Created by ZhiyuanSun on 16/9/22.
*/
import React, {Component} from 'react';
import EventSelectionItemImage from './event-selection-item-image';
export default class EventSelectionItem extends Component{
static defaultProps = {
showImage: false,
lazyLoading: false
};
constructor(props){
super(props);
this.state = {
showImage: false
}
}
componentWillMount(){
}
componentWillUpdate(){
}
componentDidMount(){
}
render(){
let {item, lazyLoading} = this.props;
return (
<li>
<a href={item.url}>
<EventSelectionItemImage {...this.props} img={item.img}></EventSelectionItemImage>
<p>{item.description}</p>
</a>
</li>
);
}
}
|
new (require('front.js').Front)().init().start();
|
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var RestMethod;
return {
setters: [],
execute: function () {
(function (RestMethod) {
RestMethod[RestMethod["POST"] = 0] = "POST";
RestMethod[RestMethod["GET"] = 1] = "GET";
RestMethod[RestMethod["PUT"] = 2] = "PUT";
RestMethod[RestMethod["DELETE"] = 3] = "DELETE";
})(RestMethod || (RestMethod = {}));
exports_1("RestMethod", RestMethod);
}
};
});
//# sourceMappingURL=type-rest-method.js.map
|
(function () {
"use strict";
// ReSharper disable once UndeclaredGlobalVariableUsing
angular
.module("umbraco.resources")
.filter("ujetAsGroup", ujetAsGroupFilter);
function ujetAsGroupFilter() {
return function (object) {
object.label = object.name;
return object;
};
};
})();
|
const { expect } = require('chai');
const nock = require('nock');
const timekeeper = require('timekeeper');
const jose2 = require('jose2');
const { Issuer } = require('../../lib');
const fail = () => {
throw new Error('expected promise to be rejected');
};
describe('Validating Self-Issued OP responses', () => {
afterEach(timekeeper.reset);
afterEach(nock.cleanAll);
before(function () {
const issuer = new Issuer({
authorization_endpoint: 'openid:',
issuer: 'https://self-issued.me',
scopes_supported: ['openid', 'profile', 'email', 'address', 'phone'],
response_types_supported: ['id_token'],
subject_types_supported: ['pairwise'],
id_token_signing_alg_values_supported: ['RS256'],
request_object_signing_alg_values_supported: ['none', 'RS256'],
registration_endpoint: 'https://self-issued.me/registration/1.0/',
});
const client = new issuer.Client({
client_id: 'https://rp.example.com/cb',
response_types: ['id_token'],
token_endpoint_auth_method: 'none',
id_token_signed_response_alg: 'ES256',
});
Object.assign(this, { issuer, client });
});
const idToken = (claims = {}) => {
const jwk = jose2.JWK.generateSync('EC');
return jose2.JWT.sign(
{
sub_jwk: jwk.toJWK(),
sub: jwk.thumbprint,
...claims,
},
jwk,
{ expiresIn: '2h', issuer: 'https://self-issued.me', audience: 'https://rp.example.com/cb' },
);
};
describe('consuming an ID Token response', () => {
it('consumes a self-issued response', function () {
const { client } = this;
return client.callback(undefined, { id_token: idToken() });
});
it('expects sub_jwk to be in the ID Token claims', function () {
const { client } = this;
return client
.callback(undefined, { id_token: idToken({ sub_jwk: undefined }) })
.then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('missing required JWT property sub_jwk');
expect(err).to.have.property('jwt');
});
});
it('expects sub_jwk to be a public JWK', function () {
const { client } = this;
return client
.callback(undefined, { id_token: idToken({ sub_jwk: 'foobar' }) })
.then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('failed to use sub_jwk claim as an asymmetric JSON Web Key');
expect(err).to.have.property('jwt');
});
});
it('expects sub to be the thumbprint of the sub_jwk', function () {
const { client } = this;
return client.callback(undefined, { id_token: idToken({ sub: 'foo' }) }).then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('failed to match the subject with sub_jwk');
expect(err).to.have.property('jwt');
});
});
});
});
|
/**
* at test
* @authors yanjixiong
* @date 2016-10-11 11:02:10
*/
const should = require('should')
const at = require('../../common/at')
describe('test/common/at.test.js', function() {
describe('fetchUsers()', function() {
it('should return a names array', function(done) {
const names = at.fetchUsers('@foo @bar')
names.should.be.Array
done()
})
})
describe('linkUsers()', function() {
it('should return text contains `/u/` path ', function(done) {
const result = at.linkUsers('@foo @bar')
result.should.containEql('/u/')
done()
})
})
})
|
global.add = function(){
return 20;
}
|
'use strict';
/*
1. Переместите 0 в конец массива, остальные числа должны остаться
неизменными
.сoncat();
example:
[1,false,2,0,3,null,0,4,0,25] => [1, false, 2, 3, null, 4, 25, 0, 0, 0]
[ 'a', 0, 0, 'b', null, 'c', 'd', 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9 ] => ["a","b",null,"c","d",1,false,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0]
[ 0, 1, null, 2, false, 1, 0 ] => [1,null,2,false,1,0,0]
*/
let arr1 = [1, false, 2, 0, 3, null, 0, 4, 0, 25];
arr1 = [ 'a', 0, 0, 'b', null, 'c', 'd', 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9 ];
function moveZeroToEnd(arr){
let lookingFor = 0;
let zeroArray = [];
for (let i = 0; i < arr.length;){
if (arr[i] === lookingFor){
arr.splice(i, 1);
zeroArray.push(lookingFor);
continue;
}
i++;
}
return arr.concat(zeroArray);
}
console.log(moveZeroToEnd(arr1));
/*
2. Верните сумму двух найменьших чисел в массиве
[10,20,30,1,31,11,10] => 11
[-1,0,25] => -1
[-4,-10,25,10] => -14
[0,200,10,25,15] => 10
*/
function orderNumbers(a, b){// WTF????
return a - b;
}
function minimalNumber(arr){
let a = arr.sort(orderNumbers);//Вот эту МАГИЮ Я РЕАЛЬНО НЕ ВКУРИЛ КАК ЭТО РАБОТЕТ???
return a.shift() + a.shift();
}
console.log(minimalNumber([10,20,30,1,31,11,10]));
/*
3. Напишите функцию которая меняет местами имя и фамилию
nameShuffler('john McClane'); => "McClane john"
nameShuffler('Arnold Schwarzenegger'); => "Schwarzenegger Arnold"
nameShuffler('James Bond'); => "Bond James"
*/
function nameShuffler(name){
return name.split(' ').reverse().join(' ');
}
console.log(nameShuffler('john McClane'));
console.log(nameShuffler('Arnold Schwarzenegger'));
console.log(nameShuffler('James Bond'));
/*
// !
4. Напишите функцию которая принимает массив с именами и возвращает массив
в котором каждая буква становится заглавной
capMe(['jo', 'nelson', 'jurie']) // returns ['Jo', 'Nelson', 'Jurie']
capMe(['KARLY', 'DANIEL', 'KELSEY']) // returns ['Karly', 'Daniel', 'Kelsey']
*/
function capMe(arr){
for (var i = 0; i < arr.length; i++){
arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1).toLowerCase();
}
return arr;
}
console.log(capMe(['KARLY', 'DANIEL', 'KELSEY']));
console.log(capMe(['jo', 'nelson', 'jurie']));
//@SUPER
/*
1. Найдите число отсутствующее в заданной последовательности
example:
[1,3,5,9] => 7
[0,8,16,32] => 24
[4, 6, 8, 10] => 2 // число сначала
[0,16,24,32] => 8
*/
function steps(arr){
let maxStep = 0;
let index = 0;
if (arr[0] !== 0){
arr.unshift(0); // для коректного поиска с 0;
}
for (let i = 0; i + 1 < arr.length; i++){
if (maxStep < (arr[i + 1] - arr[i])){
maxStep = (arr[i + 1] - arr[i]);
index = i;
}
}
return arr[index] + maxStep/2;
}
function random(arr) {
console.log(arr);
console.log('Пропущеное число: ' + steps(arr));
}
random([1, 3, 5, 9]);
random([0, 8, 16, 32]);
random([4, 6, 8, 10]);
random([0, 16, 24, 32]);
/*
2. Напишите функция которая преобразовывает/открывает скобки всех
вложенных внутри массивов
Необходимо реализовать рекурсивный фызов функции.
Функция должна открывать любое количество внутренних массивов
example:
[[1,2],[3,[4]],5, 10] => [1,2,3,4,5,10]
[25,10,[10,[15]]] => [25,10,10,15]
*/
function openBraces(arr, arrNoBraces = []) {
for (let i = 0; i < arr.length; i++){
if (Array.isArray(arr[i])){
openBraces(arr[i], arrNoBraces);
}
else{
arrNoBraces.push(arr[i]);
}
}
return arrNoBraces;
}
console.log(openBraces ([[1,2],[3,[4]],5, 10]));
console.log(openBraces ([25,10,[10,[15]]]));
|
var searchData=
[
['thread_2eh',['thread.h',['../sys_2thread_8h.html',1,'(Global Namespace)'],['../lv2_2thread_8h.html',1,'(Global Namespace)']]],
['tty_2eh',['tty.h',['../tty_8h.html',1,'']]]
];
|
/*
* grunt-pip
* https://github.com/davidshrader/grunt-pip
*
* Copyright (c) 2014 david.shrader
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
'use strict';
//var exec = require('exec');
var exec = require('child_process').exec;
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('pip', 'Grunt plug-in to install Python packages via PIP.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
vritualenv: 'venv',
verbose: false
});
var args = []
args.push(options.vritualenv);
if (options.verbose) {
args.push('-v');
}
grunt.log.writeln(args);
var done = this.async();
grunt.util.spawn({
cmd: 'virtualenv',
args: args
}, function(error, result, code) {
grunt.log.writeln(result);
done(error);
});
// grunt.util.spawn({
// cmd: ['ls'],
// args: ['-l']
// }, function(error, result, code) {
// grunt.log.writeln('hey there');
// grunt.log.writeln(error);
// grunt.log.writeln(code);
// done();
// });
// check to see if virtualenv command is available
// if (options.vritualenv !== 'venv') {
// grunt.fatal('\'virtualenv\' command not found');
// }
// exec('ls', function (error, stdout, stderr) {
// grunt.log.writeln('hey there');
// console.log('stdout: ' + stdout);
// console.log('stderr: ' + stderr);
// if (error !== null) {
// console.log('exec error: ' + error);
// };
// });
// exec(['ls', '-l'], function(err, out, code) {
// if (err instanceof Error)
// throw err;
// process.stderr.write(err);
// process.stdout.write(out);
// process.exit(code);
// });
// var cmd = 'virtualenv ' + options.virtualenv + '\n';
// cmd += 'python benjamint.py';
// exec(cmd, function(err, stdout) {
// if (err instanceof Error)
// throw err;
// process.stderr.write(err);
// process.stdout.write(out);
// process.exit(code);
// // grunt.log.write(stdout);
// });
// var vritualenv = options.virtualenv;
// grunt.log.writeln(vritualenv);
// var verbose = options.verbose;
// grunt.log.writeln(verbose);
// var modules = options.modules;
// grunt.log.writeln(modules);
});
};
|
'use strict';
const writeFile = require('../index');
const chai = require('chai');
const expect = chai.expect;
const rimraf = require('rimraf');
const root = process.cwd();
const fs = require('fs');
const broccoli = require('broccoli');
let builder;
chai.Assertion.addMethod('sameStatAs', function(otherStat) {
this.assert(
this._obj.mode === otherStat.mode,
'expected mode ' + this._obj.mode + ' to be same as ' + otherStat.mode,
'expected mode ' + this._obj.mode + ' to not the same as ' + otherStat.mode
);
this.assert(
this._obj.size === otherStat.size,
'expected size ' + this._obj.size + ' to be same as ' + otherStat.size,
'expected size ' + this._obj.size + ' to not the same as ' + otherStat.size
);
this.assert(
this._obj.mtime.getTime() === otherStat.mtime.getTime(),
'expected mtime ' + this._obj.mtime.getTime() + ' to be same as ' + otherStat.mtime.getTime(),
'expected mtime ' + this._obj.mtime.getTime() + ' to not the same as ' + otherStat.mtime.getTime()
);
});
describe('broccoli-file-creator', function() {
afterEach(function() {
if (builder) {
builder.cleanup();
}
});
function read(path) {
return fs.readFileSync(path, 'UTF8');
}
it('creates the file specified', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/something.js', content);
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/something.js')).to.eql(content);
});
});
it('creates the file specified in a non-existent directory', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/somewhere/something.js', content);
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/somewhere/something.js')).to.eql(content);
});
});
it('if the content is a function, that functions return value or fulfillment value is used', function() {
const CONTENT = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('the-file.txt', () => Promise.resolve(CONTENT));
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/the-file.txt')).to.eql(CONTENT);
});
});
it('correctly caches', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/something.js', content);
builder = new broccoli.Builder(tree);
var stat;
return builder.build().then(result => {
stat = fs.lstatSync(result.directory + '/something.js');
return builder.build();
}).then(result => {
var newStat = fs.lstatSync(result.directory + '/something.js');
expect(newStat).to.be.sameStatAs(stat);
});
});
});
|
/**
* 邮件通知
*/
const config = require('../config').email
const nodemailer = require('nodemailer')
let smtpTransport = null
module.exports = {
send(tip, title, message) {
if (!smtpTransport) {
smtpTransport = nodemailer.createTransport({
pool:true,
service:config.service,
auth:{
user:config.from,
pass:config.pass
}
})
}
console.log(`sending email to ${config.to}:${title} ${message}`)
if (config.filter.indexOf(tip.level) > -1) {
console.log('email filterd')
return
}
smtpTransport.sendMail({
from:config.from,
to:config.to,
subject:message,
html:title
}, (e, res) => e ? console.error('send email failed:' + e) : console.log('send email success.'))
}
}
|
// Creates a hot reloading development environment
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const DashboardPlugin = require('webpack-dashboard/plugin');
const config = require('./config/webpack.config.development');
const app = express();
const compiler = webpack(config);
// Apply CLI dashboard for your webpack dev server
compiler.apply(new DashboardPlugin());
const host = process.env.HOST || 'localhost';
const port = process.env.PORT || 3000;
function log() {
arguments[0] = '\nWebpack: ' + arguments[0];
console.log.apply(console, arguments);
}
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: "/",
stats: {
colors: true
},
historyApiFallback: true
}));
app.use(webpackHotMiddleware(compiler));
app.get('/css/*', (req, res) => {
res.sendFile(path.join(__dirname, './src/app.html'),{
headers:{
"Content-Type":"text/css"
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './src/app.html'));
});
app.listen(port, host, (err) => {
if (err) {
log(err);
return;
}
const exec = require('child_process').exec;
exec("cd src && electron main.dev.js", (err, stdout, stderr) => {
if (err) {
log(err);
return;
}
log("Electron Started");
});
log(' App is listening at http://%s:%s', host, port);
});
|
/****************************************/
/* Level One - Concatenation Exercises */
/****************************************/
/*
Return a string that will add a "Hello" string in front of the name
ie:
sayHello("Jesse") => Hello Jesse
sayHello("Mat") => Hello Mat
*/
function sayHello(name) {
}
/*
Create a full name using the first and last parameters and store into a variable
Then return a string that will add a "Hello" string in front of the full name
ie:
sayHelloAdv("Jesse", "Wang") => Hello Jesse Wang
sayHelloAdv("Alex", "Pelan") => Hello Alex Pelan
*/
function sayHelloAdv(first, last) {
}
/*
Return a string that will display how many points a player made
ie:
playerStats("Steph Curry", 32") => Steph Curry made 32 points
playerStats("Meghan", 12) => Meghan made 12 points
*/
function playerStats(player, points) {
}
/*
Return a number that will be the total score in points made
ie:
calculateScore(1, 0) => 2
calculateScore(0, 1) => 3
calculateScore(8, 6) => 34
*/
function calculateScore(twoPointersMade, threePointersMade) {
}
/*
Calculates the totalScore a player has made
Then return a string that will display the total score a player made
ie:
playerStatsAdv("Steph Curry", 6, 7) => "Steph Curry made 33 points"
playerStatsAdv("Meghan", 4, 2) => "Meghan made 14 points"
*/
function playerStatsAdv(player, twoPointersMade, threePointersMade) {
}
|
var net = require('net');
var client = net.connect(4444, '192.168.99.100');
client.setEncoding('utf8');
setInterval(function() {
console.log("sending...")
var msg = Math.floor(Math.random()*10000);
client.write('send mytopic 123 bajs'+msg+'\n');
}, 250)
client.on('data', function(data) {
console.log('data was', data)
})
|
const _evaluate = function(stateData) {
if(stateData.fireKey)
return "Yellow"
};
module.exports = function(Anystate) {
Anystate.prototype._evaluate = _evaluate
}
|
#!/usr/bin/env node
var fs = require("fs");
var path = require("path");
var optimist = require("optimist");
var argv = optimist.argv;
var to_center = [-119.95388, 37.913055];
var FILE_IN = path.resolve(argv._[0]);
var FILE_OUT = path.resolve(argv._[1]);
var geojson = JSON.parse(fs.readFileSync(FILE_IN));
var get_center = function(pg){
var b = [pg[0][0],pg[0][0],pg[0][1],pg[0][1]];
pg.forEach(function(p){
if (b[0] < p[0]) b[0] = p[0];
if (b[1] > p[0]) b[1] = p[0];
if (b[2] < p[1]) b[2] = p[1];
if (b[3] > p[1]) b[3] = p[1];
});
return [((b[0]+b[1])/2),((b[2]+b[3])/2)];
};
var from_center = null;
var move_shape = function(coords) {
var xScale = Math.cos(from_center[1]*3.14159/180)/Math.cos(to_center[1]*3.14159/180);
var dy = from_center[1]-to_center[1];
coords.forEach(function(v,k){
coords[k] = [
(v[0]-from_center[0])*xScale+to_center[0],
v[1]-dy
]
});
return coords;
}
switch (geojson["features"][0]["geometry"]["type"]) {
case "Polygon":
var from_center = get_center(geojson["features"][0]["geometry"]["coordinates"][0]);
geojson["features"][0]["geometry"]["coordinates"][0] = move_shape(geojson["features"][0]["geometry"]["coordinates"][0]);
break;
case "MultiPolygon":
var centers = [];
geojson["features"][0]["geometry"]["coordinates"].forEach(function(v){
centers.push(get_center(v[0]));
});
var from_center = get_center(centers);
geojson["features"][0]["geometry"]["coordinates"].forEach(function(v,k){
geojson["features"][0]["geometry"]["coordinates"][k][0] = move_shape(v[0])
});
break;
}
fs.writeFileSync(FILE_OUT, JSON.stringify(geojson,null,'\t'));
|
angular.module("soundipic.model", [
])
.service("model", function() {
var imageSrc,
imageData;
function srcToData(src) {
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, width, height);
return context.getImageData(0, 0, width, height);
}
function dataToSrc(data) {
var canvas = document.createElement("canvas"),
context = canvas.getContext("2d");
context.putImageData(data, 0, 0);
return canvas.toDataURL("image/jpg");
}
function getImageData() {
if (!imageSrc) {
return null;
}
}
return {
imageSrc: function(src) {
if (src) {
imageSrc = src;
imageData = srcToData(src);
}
return imageSrc;
},
imageData: function(data) {
if (data) {
imageData = data;
imageSrc = dataToSrc(data);
}
return imageData;
}
};
})
;
|
version https://git-lfs.github.com/spec/v1
oid sha256:5a4b87becf4d55857fc2346606917d9c17ea96ba34d8cda9efdd44b97576c0f7
size 2824
|
/*global define*/
define({
"_widgetLabel": "Netoli manęs",
"searchHeaderText": "Ieškoti adreso arba rasti žemėlapyje",
"invalidSearchLayerMsg": "Netinkamai sukonfigūruota sluoksnių paieška",
"bufferSliderText": "Rezultatus pateikti ${BufferDistance} ${BufferUnit}",
"bufferTextboxLabel": "Rezultatus pateikti diapazone (${BufferUnit})",
"invalidBufferDistance": "Įvesta buferio atstumo reikšmė yra netinkama.",
"bufferSliderValueString": "Nurodykite atstumą, didesnį nei 0",
"unableToCreateBuffer": "Rezultatų nerasta",
"selectLocationToolTip": "Nustatyti vietą",
"noFeatureFoundText": "Nieko nerasta ",
"unableToFetchResults": "Nepavyko rasti rezultatų sluoksnyje (-iuose):",
"informationTabTitle": "Informacija",
"directionTabTitle": "Maršrutai",
"failedToGenerateRouteMsg": "Nepavyko sugeneruoti maršruto.",
"geometryServicesNotFound": "Geometrijos paslauga negalima.",
"allPopupsDisabledMsg": "Nesukonfigūruoti iškylantys langai, rezultatų pateikti negalima.",
"worldGeocoderName": "Adresas",
"searchLocationTitle": "Ieškota vieta",
"unknownAttachmentExt": "FAILAS",
"proximityButtonTooltip": "Paieška šalia",
"approximateDistanceTitle": "Apytikslis atstumas: ${DistanceToLocation}",
"toggleTip": "Spustelėkite, norėdami parodyti/paslėpti filtravimo nustatymus",
"filterTitle": "Pasirinkti taikytinus filtrus",
"clearFilterButton": "Išvalyti visus filtrus",
"bufferDistanceLabel": "Buferio atstumas",
"units": {
"miles": {
"displayText": "Mylios",
"acronym": "mi."
},
"kilometers": {
"displayText": "Kilometrai",
"acronym": "km"
},
"feet": {
"displayText": "Pėdos",
"acronym": "pėdos"
},
"meters": {
"displayText": "Metrai",
"acronym": "m"
}
}
});
|
(function() {
'use strict';
angular
.module('socialprofileApp')
.provider('AlertService', AlertService);
function AlertService () {
this.toast = false;
/*jshint validthis: true */
this.$get = getService;
this.showAsToast = function(isToast) {
this.toast = isToast;
};
getService.$inject = ['$timeout', '$sce', '$translate'];
function getService ($timeout, $sce,$translate) {
var toast = this.toast,
alertId = 0, // unique id for each alert. Starts from 0.
alerts = [],
timeout = 5000; // default timeout
return {
factory: factory,
isToast: isToast,
add: addAlert,
closeAlert: closeAlert,
closeAlertByIndex: closeAlertByIndex,
clear: clear,
get: get,
success: success,
error: error,
info: info,
warning : warning
};
function isToast() {
return toast;
}
function clear() {
alerts = [];
}
function get() {
return alerts;
}
function success(msg, params, position) {
return this.add({
type: 'success',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function error(msg, params, position) {
return this.add({
type: 'danger',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function warning(msg, params, position) {
return this.add({
type: 'warning',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function info(msg, params, position) {
return this.add({
type: 'info',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function factory(alertOptions) {
var alert = {
type: alertOptions.type,
msg: $sce.trustAsHtml(alertOptions.msg),
id: alertOptions.alertId,
timeout: alertOptions.timeout,
toast: alertOptions.toast,
position: alertOptions.position ? alertOptions.position : 'top right',
scoped: alertOptions.scoped,
close: function (alerts) {
return closeAlert(this.id, alerts);
}
};
if(!alert.scoped) {
alerts.push(alert);
}
return alert;
}
function addAlert(alertOptions, extAlerts) {
alertOptions.alertId = alertId++;
alertOptions.msg = $translate.instant(alertOptions.msg, alertOptions.params);
var that = this;
var alert = this.factory(alertOptions);
if (alertOptions.timeout && alertOptions.timeout > 0) {
$timeout(function () {
that.closeAlert(alertOptions.alertId, extAlerts);
}, alertOptions.timeout);
}
return alert;
}
function closeAlert(id, extAlerts) {
var thisAlerts = extAlerts ? extAlerts : alerts;
return closeAlertByIndex(thisAlerts.map(function(e) { return e.id; }).indexOf(id), thisAlerts);
}
function closeAlertByIndex(index, thisAlerts) {
return thisAlerts.splice(index, 1);
}
}
}
})();
|
jest
.dontMock('../resolvers')
.dontMock('../queries')
import { fromJS } from 'immutable'
describe('resolvers', () => {
let resolvers
beforeEach(() => {
resolvers = require('../resolvers')
})
it('retrieves a value', () => {
const {value} = resolvers
const mockVal = 'testing-wow'
expect(value(mockVal)).toBe(mockVal)
})
it('constructs a proper get query', () => {
const {get, value} = resolvers
expect(get('testing')).toEqual({
testing: value,
})
})
it('constructs a valid getIn query', () => {
const {getIn, value} = resolvers
expect(getIn('one', 'two', 'three')).toEqual({
one: {
two: {
three: value,
},
},
})
})
it('constructs a valid index query', () => {
const {index} = resolvers
const indexResolver = index(['users'])
const mockCache = fromJS({
users: {
'123': {
name: 'one',
friends: {
'456': true,
'789': true,
},
},
'456': { name: 'two' },
'789': { name: 'three' },
},
})
const mockState = { firebase: mockCache }
const value = mockCache.getIn(['users', '123', 'friends'])
expect(
indexResolver.subscriptions(value)
).toEqual([
['users', '456'],
['users', '789'],
])
expect(
indexResolver.values(value, mockState, {}).toJS()
).toEqual({
'456': { name: 'two' },
'789': { name: 'three' },
})
})
})
|
import React from 'react'
import { renderRoutes } from 'react-router-config'
import { Header } from '../containers/Header'
const App = ({ route }) => (
<div>
<Header
title="reSolve Styled-Components Example"
name="Styled-Components Example"
favicon="/favicon.png"
css={['/bootstrap.min.css']}
/>
{renderRoutes(route.routes)}
</div>
)
export default App
|
$(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").append(generateDivSlot(nbSlots));
})
$(document).on('click', '.remove-slot', function(){
var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] + "</option>";
})
str += " </select>";
if(nbSlots > 1){
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
}
str += "<br />";
str += "</div>";
return str;
}
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
|
const { Router } = require('director');
const ReactDOM = require('react-dom');
const { computed, observable } = require('../../core');
const React = require('../../react');
const { Todo, todos } = require('./model');
const { StatsView } = require('./StatsView');
const { TodoView } = require('./TodoView');
const { cat } = require('../../cat');
class AppView extends React.Component {
constructor() {
super();
this.newTodoTitle = observable("");
this.todoFilter = observable("all");
this.todoFiltered = computed(() => todos[this.todoFilter.$].$);
this.footerStyle = computed(() => {
let result = {};
if (todos.all.$.length === 0)
result.display = "none";
return result;
});
this.allComplete = computed({
read: () => !todos.active.$.length,
write: (v) => {
todos.all.$.forEach(todo => {
todo.completed.$ = Boolean(v);
});
},
});
}
componentDidMount() {
let router = Router({
'/': () => {
this.todoFilter.$ = "all";
},
'/active': () => {
this.todoFilter.$ = "active";
},
'/completed': () => {
this.todoFilter.$ = "completed";
},
});
router.init('/');
}
render() {
return <div>
<section className="todoAppView">
<header className="header">
<h1>todos</h1>
<input className="new-todo"
placeholder="What needs to be done?"
autoFocus
value={ this.newTodoTitle }
onKeyPress={ this.createOnEnter.bind(this) }
/>
</header>
<section className="main">
<input className="toggle-all"
id="toggle-all"
type="checkbox"
checked={ this.allComplete }/>
<label htmlFor="toggle-all">Mark all as complete</label>
<ul className="todo-list">
{this.todoFiltered.$.map(todo => <TodoView key={todo.id.$} todo={todo} />)}
</ul>
</section>
<footer className="footer" style={this.footerStyle}>
<StatsView todoFilter={ this.todoFilter }/>
</footer>
</section>
</div>;
}
createOnEnter(event) {
if (event.key === "Enter" && this.newTodoTitle.$.trim().length) {
todos.add(new Todo(this.newTodoTitle.$));
this.newTodoTitle.$ = "";
}
}
}
cat(__filename).providesEach({
AppView,
});
ReactDOM.render(
<AppView/>,
document.getElementById("main")
);
module.exports = {
AppView,
}
|
(function () {
'use strict';
angular
.module('buildings')
.controller('BuildingsController', BuildingsController);
BuildingsController.$inject = ['$scope', '$state', 'projectResolve', '$window', 'Authentication'];
function BuildingsController ($scope, $state, project, $window, Authentication) {
var vm = this;
// initialization objects
vm.project = project;
vm.project.isNewBuilding = false;
vm.project.removeBuilding = false;
vm.project.isUpdateBuilding = false;
vm.building = {};
// functionality
vm.save = save;
vm.remove = remove;
vm.edit = edit;
// initialization variables
vm.parentName = $state.params.projectName;
vm.index = $state.params.index ? $state.params.index : 0;
// implementation
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.buildingForm');
return false;
}
if (vm.project._id) {
vm.project.addBuilding = vm.building;
vm.project.isNewBuilding = true;
vm.project.$update(successCallBack, errorCallBack);
} else {
// throw error , can't exist building without project
}
}
function successCallBack(res) {
$state.go('projects.view', {
projectId: res._id
});
}
function successCallBackUpdateBuilding(res) {
$state.go('buildings.view', {
projectId: res._id,
buildingId: res.buildings[vm.index]._id
});
}
function errorCallBack(res) {
vm.error = res.data + ' ' + res.statusText;
}
function remove(index) {
if ($window.confirm('Are you sure you want to remove building ')) {
vm.project.removeBuilding = true;
vm.project.index = index;
vm.project.$update(successCallBack, errorCallBack);
}
}
function edit(isValid) {
vm.project.isUpdateBuilding = true;
vm.project.index = vm.index;
vm.project.$update(successCallBackUpdateBuilding, errorCallBack);
}
}
}());
|
export { default } from 'ember-flexberry-gis/components/layer-treenode-contents/base';
|
var path = require('path')
var webpack = require('webpack')
const config = {
entry: path.join(__dirname, './src/index.js'),
output: {
filename: 'ajax-manager.js',
library: 'ajaxManager',
libraryTarget: 'umd',
path: path.join(__dirname, './dist')
},
module: {
rules: [
{
test: /\.js$/,
use: [
{ loader: 'babel-loader' }
]
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
})
]
}
module.exports = config
|
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('../alasql.js');
};
if(false) {
describe('Test 16b', function() {
it('Grouping', function(done){
alasql('create database test16;use test16');
alasql.tables.students = new alasql.Table({data: [
{studentid:58,studentname:'Sarah Patrik',courseid:1, startdate: new Date(2014,0,10), amt:10, schoolid:1},
{studentid:102,studentname:'John Stewart', courseid:2, startdate: new Date(2014,0,20), amt:20, schoolid:1},
{studentid:103,studentname:'Joan Blackmore', courseid:2, startdate: new Date(2014,0,20), amt:20, schoolid:1},
{studentid:104,studentname:'Anna Wooden', courseid:4, startdate: new Date(2014,0,15), amt:30, schoolid:2},
{studentid:150,studentname:'Astrid Carlson', courseid:7, startdate: new Date(2014,0,15), amt:30, schoolid:1},
]});
alasql.tables.courses = new alasql.Table({data:[
{courseid:1, coursename: 'first', schoolid:1},
{courseid:2, coursename: 'second', schoolid:1},
{courseid:3, coursename: 'third', schoolid:2},
{courseid:4, coursename: 'fourth', schoolid:2},
{courseid:5, coursename: 'fifth', schoolid:2}
]});
alasql.tables.schools = new alasql.Table({data:[
{schoolid:1, schoolname: 'Northern School', regionid:'north'},
{schoolid:2, schoolname: 'Southern School', regionid:'south'},
{schoolid:3, schoolname: 'Eastern School', regionid:'east'},
{schoolid:4, schoolname: 'Western School', regionid:'west'},
]});
var res = alasql.exec('SELECT * '+
' FROM students '+
' LEFT JOIN courses ON students.courseid = courses.courseid AND students.schoolid = courses.schoolid'+
' LEFT JOIN schools ON students.schoolid = schools.schoolid '+
' GROUP BY schoolid, courseid, studentname '+
' ORDER BY studentname DESC' );
console.log(res);
assert.equal(5, res.length);
assert.equal(1, res[0].courseid);
assert.equal(2, res[1].courseid);
assert.equal(2, res[2].courseid);
assert.equal(7, res[3].courseid);
assert.equal(4, res[4].courseid);
alasql('drop database test16');
done();
});
});
}
|
/*Problem 2. Divisible by 7 and 5
Write a boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 in the same time.
Examples:
n Divided by 7 and 5?
3 false
0 true
5 false
7 false
35 true
140 true*/
var number = 35,
devidedBySevenandFive = true;
if (number % 7 == 0 && number % 5 == 0) {
console.log(devidedBySevenandFive)
}
else {
console.log(!devidedBySevenandFive)
}
|
/* global describe, expect, it */
const fishNames = require('../src/index');
const allFish = fishNames.all;
describe('fish names', function() {
describe('all', function() {
it('should return an object containing all 200 fish names', function() {
expect(Object.keys(allFish).length).toEqual(200);
});
});
describe('random', function() {
it('should return a random fish', function() {
expect(Object.keys(allFish).map(fish => allFish[fish])).toContain(
fishNames.random()
);
});
it('should return an array of random fish names if passed a number as a param', function() {
const threeRandomFish = fishNames.random(3);
expect(threeRandomFish.length).toBe(3);
});
});
describe('male/female fish', function() {
const allMaleFish = Object.keys(fishNames.allMaleFish).map(
fish => fishNames.allMaleFish[fish]
);
const allFemaleFish = Object.keys(fishNames.allFemaleFish).map(
fish => fishNames.allFemaleFish[fish]
);
it('should ONLY contain names of male fish', function() {
expect(allMaleFish).not.toEqual(expect.arrayContaining(allFemaleFish));
});
it('should ONLY contain names of female fish', function() {
expect(allFemaleFish).not.toEqual(expect.arrayContaining(allMaleFish));
});
});
});
|
import produce from 'immer';
import homeReducer, { initialState } from '../reducer';
import {
loadGalleries,
galleriesLoadingSuccess,
galleriesLoadingError,
} from '../actions';
/* eslint-disable default-case, no-param-reassign */
describe('homeReducer', () => {
let state;
beforeEach(() => {
state = initialState;
});
test('should return the initial state', () => {
const expectedResult = state;
expect(homeReducer(undefined, {})).toEqual(expectedResult);
});
test('should handle the loadGalleries action correctly', () => {
const expectedResult = produce(state, draft => {
draft.galleryLoadings = true;
});
expect(homeReducer(state, loadGalleries())).toEqual(expectedResult);
});
test('should handle the galleriesLoadingSuccess action correctly', () => {
const fixture = {
entries: [{ name: 'demo', path_lower: '/public/galleries/demo' }],
};
const expectedResult = produce(state, draft => {
draft.galleryLoadings = false;
draft.contents = fixture.entries;
});
expect(homeReducer(state, galleriesLoadingSuccess(fixture))).toEqual(
expectedResult,
);
});
test('should handle the galleriesLoadingError action correctly', () => {
const fixture = { type: 'ReferenceError' };
const expectedResult = produce(state, draft => {
draft.galleryErrors = fixture;
draft.host = 'cdn';
});
expect(homeReducer(state, galleriesLoadingError(fixture, 'cdn'))).toEqual(
expectedResult,
);
});
});
|
var x;
var y;
var d;
var speedX;
var speedY;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 255, 255);
d = 100;
x = random(d, width-d);
y = random(d, height-d);
speedX = random(5, 15);
speedY = random(5, 15);
}
function draw() {
background(0, 255, 255);
ellipse(x, y, d, d);
x = x + speedX;
y = y + speedY;
//d = d + 1;
if(y > height - d/2) {
speedY = -1 * abs(speedY);
fill(random(255), random(255), random(255))
}
if(y < d/2) {
speedY = abs(speedY);
}
if(x > width - d/2) {
speedX = -1 * abs(speedX);
}
if(x < d/2) {
speedX = abs(speedX);
}
}
|
/* eslint-disable no-console,func-names,react/no-multi-comp */
const React = require('react');
const ReactDOM = require('react-dom');
const Table = require('table-v7');
require('table-v7/assets/index.less');
const columns = [
{ title: '表头1', dataIndex: 'a', key: 'a', width: 100, fixed: 'left' },
{ title: '表头2', dataIndex: 'b', key: 'b', width: 100, fixed: 'left' },
{ title: '表头3', dataIndex: 'c', key: 'c' },
{ title: '表头4', dataIndex: 'b', key: 'd' },
{ title: '表头5', dataIndex: 'b', key: 'e' },
{ title: '表头6', dataIndex: 'b', key: 'f' },
{ title: '表头7', dataIndex: 'b', key: 'g' },
{ title: '表头8', dataIndex: 'b', key: 'h' },
{ title: '表头9', dataIndex: 'b', key: 'i' },
{ title: '表头10', dataIndex: 'b', key: 'j' },
{ title: '表头11', dataIndex: 'b', key: 'k' },
{ title: '表头12', dataIndex: 'b', key: 'l', width: 100, fixed: 'right' },
];
const data = [
{ a: '123', b: 'xxxxxxxx', d: 3, key: '1' },
{ a: 'cdd', b: 'edd12221', d: 3, key: '2' },
{ a: '133', c: 'edd12221', d: 2, key: '3' },
{ a: '133', c: 'edd12221', d: 2, key: '4' },
{ a: '133', c: 'edd12221', d: 2, key: '5' },
{ a: '133', c: 'edd12221', d: 2, key: '6' },
{ a: '133', c: 'edd12221', d: 2, key: '7' },
{ a: '133', c: 'edd12221', d: 2, key: '8' },
{ a: '133', c: 'edd12221', d: 2, key: '9' },
];
ReactDOM.render(
<div style={{ width: 800 }}>
<h2>Fixed columns</h2>
<Table
columns={columns}
expandedRowRender={record => record.title}
expandIconAsCell
scroll={{ x: 1200 }}
data={data}
/>
</div>
, document.getElementById('__react-content'));
|
import Ember from 'ember';
const {
Route
} = Ember;
export default Route.extend({
model(params) {
return this.get('store').findRecord('item', params.id);
}
});
|
app.service('UserService', function (FIREBASE_URL, $firebase) {
var connectedUsersRef = new Firebase(FIREBASE_URL + 'whiteBoard/connectedUsers');
this.userRef = null;
this.setCurrentUser = function(user) {
this.userRef = connectedUsersRef.push(user);
this.userRef.onDisconnect().remove();
};
this.getConnectedUsersRef = function() {
return $firebase(connectedUsersRef);
};
this.getCurrentUserKey = function() {
return this.userRef.name();
};
});
|
const server = require('./server')
const port = process.env.PORT || 3000
server.listen(port, () => {
console.log('Listening on port %s', port)
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.