code
stringlengths 2
1.05M
|
---|
export const UNIVERSE = "universe"
export const KIBITZ = "kibitz"
export const LEAVE ="leave"
export const ROTATE = "rotate"
export const LOGIN = "login"
export const GAME = "game"
export const REVISION = "revision"
export const PLAY = "play"
export const START = "start"
export const MOVE = "move"
export const DROP = "drop"
export const INVALID = "invalid"
export const RESIGN = "resign"
|
describe('teamform-admin-app module', function() {
beforeEach(module('teamform-admin-app'));
var $controller;
beforeAll(function() {
window.onbeforeunload = () => 'Oh no!';
});
beforeEach(inject(function(_$controller_) {
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
}));
describe('CreateEventCtrl', function() {
var controller;
beforeEach(function() {
var isEventExist = function(eventName) {
return {
'then': function() {},
};
};
var saveNewEvent = function() {};
var teamformDb = {
isEventExist: isEventExist,
saveNewEvent: saveNewEvent,
};
controller = $controller('CreateEventCtrl', {
$scope: {},
teamformDb: teamformDb,
});
});
it('should initialize with correct default values', function() {
expect(controller.eventName).toEqual('');
expect(controller.eventNameError).toEqual('');
expect(controller.eventValid).toEqual(false);
expect(controller.event.minTeamSize).toEqual(1);
expect(controller.event.maxTeamSize).toEqual(10);
});
it('change min team size correctly', function() {
controller.event.minTeamSize = 1;
controller.event.maxTeamSize = 10;
controller.changeMinTeamSize(1);
expect(controller.event.minTeamSize).toEqual(2);
controller.changeMinTeamSize(-4);
expect(controller.event.minTeamSize).toEqual(2);
controller.changeMinTeamSize(7);
expect(controller.event.minTeamSize).toEqual(9);
controller.changeMinTeamSize(2);
expect(controller.event.minTeamSize).toEqual(9);
});
it('change max team size correctly', function() {
controller.event.minTeamSize = 1;
controller.event.maxTeamSize = 10;
controller.changeMaxTeamSize(1);
expect(controller.event.maxTeamSize).toEqual(11);
controller.changeMaxTeamSize(-4);
expect(controller.event.maxTeamSize).toEqual(7);
controller.changeMaxTeamSize(-8);
expect(controller.event.maxTeamSize).toEqual(7);
});
it('check if event name exist whenever name changed', function() {
spyOn(controller, '_checkIfEventExist');
controller.onEventNameChanged();
expect(controller._checkIfEventExist).toHaveBeenCalled();
});
});
});
|
// @flow
import pg from 'pg';
import type {
ResultSet,
ResultBuilder,
QueryType,
PG_ERROR,
Client,
Row,
DoneCallback,
PoolClient,
Pool,
PGType
} from 'pg';
pg.types.setTypeParser(1184, v => v);
pg.types.setTypeParser(1184, 'text', (v: string) => v);
// $ExpectError
pg.types.setTypeParser(1184, 'binary', (v: string) => v)
pg.types.setTypeParser(1184, 'binary', (v: Buffer) => v)
// $ExpectError
pg.types.setTypeParser(1184, (v: Buffer) => v)
// There are two common ways to use node-postgres.
function test_pg() {
// 1. interact with your server via a pool of clients
function test_pool(pool: Pool) {
// 1.1 you can run queries directly against the pool
const rq: Promise<ResultSet> = pool.query('select * from table;');
// $ExpectError
const rqw: Promise<number> = pool.query('select * from table;');
const rq2: Promise<ResultSet> = pool.query('Parameterized Queries',[1],
(err, result) => {
const _err: PG_ERROR|null = err;
// $ExpectError
const _err_w: number = err;
const _result: ResultSet|void = result;
// $ExpectError
const _result_w: number = result;
});
// $ExpectError
const rq2_w: Promise<ResultSet> = pool.query('Parameterized Queries',1);
// 1.2 the pool also supports checking out a client for
// multiple operations, such as a transaction
const rc: Promise<PoolClient> = pool.connect( (err, client, done) => {
const _err: PG_ERROR|null = err;
// $ExpectError
const _err_w: number = err;
const _client: PoolClient|null = client;
// $ExpectError
const _client_w: number = client;
const _done: DoneCallback = done;
// $ExpectError
const _done_w: number = done;
});
// $ExpectError
const rc_w: number = pool.connect();
const rt: Promise<PoolClient> = pool.take( (err, client, done) => {
const _err: PG_ERROR|null = err;
// $ExpectError
const _err_w: number = err;
const _client: PoolClient|null = client;
// $ExpectError
const _client_w: number = client;
const _done: DoneCallback = done;
// $ExpectError
const _done_w: number = done;
});
// $ExpectError
const rt_w: number = pool.take();
const re: Promise<void> = pool.end( err => {
// $ExpectError
const _err_w: string = err; // ?:mixed
});
// $ExpectError
const re_w: Promise<null> = pool.end();
// Note: There is a slight different between pool.query and client.query.
// client.query return a Query, pool.query return Promise<ResultSet>
// class Query extends Promise<ResultSet>
function test_PoolClient(client: PoolClient) {
const rr: void = client.release('any msg');
const rr1: void = client.release();
// $ExpectError
const rr_w: null = client.release();
const rq: QueryType = client.query('select * from table;');
// $ExpectError
const rqw: Promise<number> = pool.query('select * from table;');
rq.on('row', (row, result) => {
const _row: Row = row;
const _result: ResultBuilder = result;
// $ExpectError
const _row_w: number = row;
// $ExpectError
const _result_w: number = result;
});
rq.on('end', (result) => {
const reselt: ResultBuilder = result;
});
rq.on('error', (err) => {
const _err: PG_ERROR = err;
// $ExpectError
const _err_w: number = err;
});
// $ExpectError
rq.on('wrong', ()=>{});
const rq2: Promise<ResultSet> = client.query('Parameterized Queries',[1],
(err, result) => {
const _err: PG_ERROR|null = err;
// $ExpectError
const _err_w: number = err;
const _result: ResultSet|void = result;
// $ExpectError
const _result_w: number = result;
});
// $ExpectError
const rq2_w: Promise<ResultSet> = client.query('Parameterized Queries',1);
}
}
// 2. instantiate a client directly.
function test_client() {
const client = new pg.Client();
client.connect((err, client) => {
const _err: PG_ERROR|null = err;
const _client: Client|void = client;
if (_client) {
const rq: QueryType = _client.query('select * from table;');
const rq2: Promise<ResultSet> = _client.query('Parameterized Queries',[1],
(err, result) => {
const _err: PG_ERROR|null = err;
// $ExpectError
const _err_w: number = err;
const _result: ResultSet|void = result;
// $ExpectError
const _result_w: number = result;
});
// $ExpectError
const rq2_w: Promise<ResultSet> = _client.query('Parameterized Queries',1);
_client.on('drain', _ => {
const a: void = _;
});
// $ExpectError
_client.on('drain',1);
_client.on('error', err => {
const _err: PG_ERROR = err;
});
// $ExpectError
_client.on('error',1);
_client.on('notification', msg => {
});
// $ExpectError
_client.on('notification',1);
_client.on('notice', msg => {
});
// $ExpectError
_client.on('notice',1);
_client.on('end', _ => {
const a: void = _;
});
// $ExpectError
_client.on('end',1);
}
});
}
}
// Simple example usage.
const pool = new pg.Pool({
user: 'testuser',
password: 'testuser',
host: 'localhost',
database: 'testdb',
max: 10,
statement_timeout: false,
idleTimeoutMillis: 1000,
connectionTimeoutMillis: 1000
});
// use pool
const promise_r = pool.query('select * from table;', ['11']);
// $ExpectError
const p:boolean = promise_r; // Promise
promise_r.then( result => {
// $ExpectError
const v:boolean = result.command; // string
// $ExpectError
const v2:boolean = result.oid; // string
// $ExpectError
const v3:boolean = result.rowCount; // string
// $ExpectError
const v4:boolean = result.rows; // Array
const rt:ResultSet = result; // the type of result
})
// directly use client
const promise_client = pool.connect();
promise_client.then( client => {
client.query('select * from table;')
.then( result => {
// $ExpectError
const v:boolean = result; // result should be typed
});
client.release('error msg'); // accept error msg
client.release(); // or without arguments
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var androidFolderOpen = exports.androidFolderOpen = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "d": "M437.334,144H256.006l-42.668-48H74.666C51.197,96,32,115.198,32,138.667v234.666C32,396.802,51.197,416,74.666,416h362.668\r\n\tC460.803,416,480,396.802,480,373.333V186.667C480,163.198,460.803,144,437.334,144z M448,373.333\r\n\tc0,5.782-4.885,10.667-10.666,10.667H74.666C68.884,384,64,379.115,64,373.333V176h373.334c5.781,0,10.666,4.885,10.666,10.667\r\n\tV373.333z" }, "children": [] }] };
|
import React from "react";
import * as ReactDom from "react-dom";
import { Router, Route } from "react-router";
import { Provider } from "react-redux";
import getMuiTheme from "material-ui/styles/getMuiTheme";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import configureStore, { configureHistory } from "./store/configureStore.js";
import Test from "./container/Test.jsx";
import injectTapEventPlugin from "react-tap-event-plugin";
injectTapEventPlugin();
let store = configureStore();
let history = configureHistory(store);
ReactDom.render(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Test}/>
</Router>
</Provider>
</MuiThemeProvider>,
document.getElementById("content")
);
|
module.exports.db = [{
code:'sol',
name:'Sol',
dimensions:[10,10],
price:50,
layout:'l',
description:'How do you imagine her?',
isCommission:false,
isSold:false
},
{
code:'eleclad',
name:'Electric Ladies',
dimensions:[10,10],
price:50,
layout:'l',
description:'',
isCommission:false,
isSold:false
},
{
code:'sissis',
name:'Sister Sister',
dimensions:[10,10],
price:50,
layout:'l',
description:'',
isCommission:false,
isSold:false
},
{
code:'twacp',
name:'This women are coloured',
dimensions:[10,10],
price:50,
layout:'p',
description:'',
isCommission:false,
isSold:false
}];
|
/* eslint no-var:0 */
var lodash = require('lodash');
module.exports = lodash.assign(require('./webpack.config.client.deploy'), {
watch: true,
});
|
setCssToHead([".",[1],"scroll-Y { height: ",[0,300],"; }\n.",[1],"scroll-view_H { white-space: nowrap; width: 100%; }\n.",[1],"scroll-view-item { height: ",[0,300],"; line-height: ",[0,300],"; text-align: center; font-size: ",[0,36],"; }\n.",[1],"scroll-view-item_H { display: inline-block; width: 100%; height: ",[0,300],"; line-height: ",[0,300],"; text-align: center; font-size: ",[0,36],"; }\n",],undefined,{path:"./pages/component/scroll-view/scroll-view.wxss"})();
document.dispatchEvent(new CustomEvent("generateFuncReady", { detail: { generateFunc: $gwx('./pages/component/scroll-view/scroll-view.wxml') } }));
|
var JumperBot = function () {
var canvas = document.getElementById('swingbot'),
bot = {},
bullet = {},
bars = [],
// Game variables
barCount = 3,
barWidth = 100,
barHeight = 15,
bulletSpeed = 15, // Higher it is, faster the bullet will be
swingSpeed = 30, // Higher it is, slower the bot will swing
ropeThickness = 2, // Higher it is, thicker will the rope be
// Do not change below this line unless you know exactly what you are doing
scorePosX = 5, // Position (x point) where score is to be displayed
scorePosY = 15, // Position (y point) where score is to be displayed
firedPointX = 0, // Exact `x` point where user clicked
firedPointY = 0, // Exact `y` point where user clicked
barHitPointX = 0, // Point on canvas where the bullet hit the bar
barHitPointY = 0, // Point on canvas where the bullet hit the bar
barHit = false, // Used to decide if the bullet hit the bar
moveBars = false, // Will decide if the bars are to be moved or not
firedPointDist = 0, // Will be cotaining the distance between the bullet hit position and player position
swingX = 0, // Next x point where the bot will be while swinging
swingY = 0, // Next y point where the bot will be while swinging
currScore = 0,
topScore = 0,
isActive = false, // If the bot is in the move. False means the game is inactive
botImg = '', // Image object containing the robot image
bulletFired = false,
swingBot = false, // Is the bot needed to swing (will happen whenever the rope will hit the bar)
relAngleX, relAngleY, relFiredPointX, relFiredPointY; // These values will be relative to the current bot position
canvas.width = 400;
canvas.height = 500;
context = canvas.getContext('2d');
context.lineWidth = ropeThickness;
/**
* Sets the bullet defaults
*/
function setBullet() {
bullet.posX = 0;
bullet.posY = 0;
bullet.height = 4;
bullet.width = 4;
}
/**
* Sets the bot defaults
*/
function setBot() {
bot.width = 24;
bot.height = 37;
bot.posX = canvas.width / 2;
bot.posY = canvas.height - bot.height - 50;
botImg = new Image();
botImg.src = "http://kamranahmed.info/img/bot.svg";
}
/**
* Generates the bars along with their positions and populates them in the bar
*/
function setBars() {
// Generate the bars positions
for (var i = 0; i < barCount; i++) {
bars.push({
posX: Math.random() * ( canvas.width / 2 ),
posY: (( canvas.height / barCount ) * i) + 20 // So to make the bars span the whole height
});
}
;
}
/**
* Sets up the variables to fire the bullet at specified position
* @param int posX X point on canvas which is to be fired at
* @param int posY Y point on canvas which is to be fired at
*/
function fireBullet(posX, posY) {
// Reset the bar hit or it will start throwing the rope
// ..instead of the bullet
barHit = false;
isActive = true;
firedPointX = posX;
firedPointY = posY;
// Get the positions relative to the current bot position
relFiredPointX = firedPointX - bot.posX;
relFiredPointY = firedPointY - bot.posY;
// Relative angles to the fire position
relAngleX = relAngleY = Math.atan2(relFiredPointY, relFiredPointX) * 57.32;
// Set the fired flag
bulletFired = true;
}
/**
* Populates the current score over top score on canvas
*/
function populateScore() {
context.fillText(currScore + '/' + topScore, scorePosX, scorePosY);
}
/**
* Draws bars upon the canvas
*/
function drawBars() {
// Draw the bars
for (var i = 0; i < barCount; i++) {
if (bars[i].posY > canvas.height) {
bars[i].posX = Math.random() * ( canvas.width / 2 );
bars[i].posY = 0
}
// If the bars are to be moved
if (moveBars) {
bars[i].posY = bars[i].posY - swingY * 4;
}
;
context.fillRect(bars[i].posX, bars[i].posY, barWidth, barHeight);
}
;
}
/**
* Draws the player on the canvas
*/
function drawPlayer() {
// context.fillRect(bot.posX, bot.posY, bot.width, bot.height);
context.drawImage(botImg, bot.posX, bot.posY);
}
/**
* Checks if the game is over or not
* @return {boolean} True if the game is over and false otherwise
*/
function isGameOver() {
return !isActive;
}
/**
* To check if the specified bar number is hit by the bullet or not
* @param {integer} barNum Bar number which is to be checked for the hit
* @return {Boolean} True if the bar is hit or false otherwise
*/
function isNthBarHit(barNum) {
return (
bullet.posX >= bars[barNum].posX &&
bullet.posX <= ( bars[barNum].posX + barWidth )
) && (
bullet.posY >= bars[barNum].posY &&
bullet.posY <= ( bars[barNum].posY + barHeight )
);
}
/**
* Handles the bullet fire. Function is to be called inside the game loop, where it sets the bullet visibility and movement is controlled
*/
function handleBulletFire() {
// If it is the first frame after bullet got fired
if (!bullet.posX && !bullet.posY) {
bullet.posX = bot.posX;
bullet.posY = bot.posY;
}
;
// Increment the bullet position so that it may move to the position
// ..towards which it is fired
bullet.posX += Math.cos(relAngleX * 0.017) * bulletSpeed;
bullet.posY -= Math.sin(relAngleY * -0.017) * bulletSpeed;
// If the bullet tries to go outside the canvas in sideways
if (( bullet.posX > canvas.width ) || ( bullet.posX < 0 )) {
// To divert the bullet in the reverse direction
relAngleX = relAngleX - relAngleY;
}
;
// To check if the bullet has hit any of the bars
for (var i = 0; i < barCount; i++) {
// If the bullet's current position overlaps with
// any of the bars
if (isNthBarHit(i)) {
// No bullet fired, it was a bar hit
bulletFired = false;
barHit = true;
// Since the bot has got a rope in his hand
// ..now swing
swingBot = true;
// Change the fired point, as this is the point where the rope will be thrown
firedPointX = bullet.posX;
firedPointY = bullet.posY;
// Reset the bullet position
bullet.posX = bullet.posY = 0;
return;
}
;
barHit = false;
}
;
// Show the bullet
context.fillRect(bullet.posX, bullet.posY, bullet.width, bullet.height);
// If the bullet goes out of the top of canvas
if (bullet.posY < 0) {
// Reset that bullet
bullet.posX = bullet.posY = 0;
bulletFired = false
}
;
}
/**
* Resets the game i.e. bars, bullet and bot positions and other required variables
*/
function resetGame() {
// Reset everything
setBars();
setBullet();
setBot();
swingX = swingY = firedPointX = firedPointY = firedPointDist = 0;
relAngleX = relAngleY = 0;
moveBars = barHit = swingBot = false;
if (currScore > topScore) {
topScore = currScore;
}
;
currScore = 0;
}
/**
* Game loop i.e. which is to be called infinitely
*/
function gameLoop() {
// Clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
populateScore();
drawPlayer();
drawBars();
if (!isGameOver()) {
// If the bullet gets fired
if (bulletFired) {
handleBulletFire();
}
;
if (moveBars) {
firedPointY = firedPointY - swingY * 4;
// Increase the score only if the bars are moving
currScore++;
}
// If the bar was hit and the fired point is not below the bot
// bot.posY > ( firedPointY + 20 ) because we want the bot to leave the rope if the hook goes lower to him
if (barHit && bot.posY > ( firedPointY + 20 )) {
context.beginPath();
// Changed the `x` a bit, so that the rope comes out of the head of the bot
context.moveTo((bot.posX + bot.width / 2), bot.posY);
context.lineTo(firedPointX, firedPointY);
context.stroke();
firedPointDist = Math.sqrt(Math.pow((bot.posX - firedPointX), 2) + Math.pow((bot.posY - firedPointY), 2));
swingX += ( firedPointX - bot.posX ) / (firedPointDist * swingSpeed);
swingY += ( firedPointY - bot.posY ) / (firedPointDist * swingSpeed);
} else {
barHit = false;
}
;
// If the bot is within the visible canvas
if (swingY > 0) {
moveBars = false;
}
;
// To simulate gravity i.e. the bot may
// get slowly pulled down
swingY += 0.01;
moveBars || (bot.posY += swingY * 4);
bot.posX += swingX;
// If the bot is about to reach the top
if (bot.posY < ( canvas.width / 2 )) {
moveBars = true;
}
;
// If the bot tries to go outside the canvas
if (bot.posX < 0 || ( bot.posX + bot.width ) > canvas.width) {
swingX = -swingX; // Swing it backward
}
;
// If the bot goes down the bottom of the canvas
if (bot.posY > canvas.height) {
isActive = false; // Bot is dead
}
;
} else {
resetGame();
}
}
/**
* Makes sure that the game is in the loop
*/
function startGame() {
window.setInterval(gameLoop, 10);
}
return {
/**
* Initializes the game
*/
init: function () {
setBars();
setBullet();
setBot();
this.bindUI();
startGame();
},
/**
* UI bindings
*/
bindUI: function () {
canvas.onclick = function (ev) {
fireBullet(ev.clientX, ev.clientY);
}
}
};
}
|
const { version } = require('../package.json');
module.exports = {
'github-link': (contractPath) => {
if (typeof contractPath !== 'string') {
throw new Error('Missing argument');
}
return `https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v${version}/contracts/${contractPath}`;
},
};
|
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.drawing.stencil.Text"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.drawing.stencil.Text"] = true;
dojo.provide("dojox.drawing.stencil.Text");
dojox.drawing.stencil.Text = dojox.drawing.util.oo.declare(
// summary:
// Creates a dojox.gfx Text (SVG or VML) based on data provided.
// description:
// There are two text classes. TextBlock extends this one and
// adds editable functionality, discovers text width etc.
// This class displays text only. There is no line wrapping.
// Multiple lines can be acheived by inserting \n linebreaks
// in the text.
//
dojox.drawing.stencil._Base,
function(options){
// summary:
// constructor.
},
{
type:"dojox.drawing.stencil.Text",
anchorType:"none",
baseRender:true,
// align: String
// Text horizontal alignment.
// Options: start, middle, end
align:"start",
//
// valign:String
// Text vertical alignment
// Options: top, middle, bottom (FIXME: bottom not supported)
valign:"top",
//
// _lineHeight: [readonly] Number
// The height of each line of text. Based on style information
// and font size.
_lineHeight:1,
/*=====
StencilData: {
// summary:
// The data used to create the dojox.gfx Text
// x: Number
// Left point x
// y: Number
// Top point y
// width: ? Number
// Optional width of Text. Not required but reccommended.
// for auto-sizing, use TextBlock
// height: ? Number
// Optional height of Text. If not provided, _lineHeight is used.
// text: String
// The string content. If not provided, may auto-delete depending on defaults.
},
StencilPoints: [
// summary:
// An Array of dojox.__StencilPoint objects that describe the Stencil
// 0: Object
// Top left point
// 1: Object
// Top right point
// 2: Object
// Bottom right point
// 3: Object
// Bottom left point
],
=====*/
typesetter: function(text){
// summary:
// Register raw text, returning typeset form.
// Uses function dojox.drawing.stencil.Text.typeset
// for typesetting, if it exists.
//
if(dojox.drawing.util.typeset){
this._rawText = text;
return dojox.drawing.util.typeset.convertLaTeX(text);
}
return text;
},
setText: function(text){
// summary:
// Setter for text.
//
// Only apply typesetting to objects that the user can modify.
// Else, it is assumed that typesetting is done elsewhere.
if(this.enabled){
text = this.typesetter(text);
}
// This only has an effect if text is null or this.created is false.
this._text = text;
this._textArray = [];
this.created && this.render(text);
},
getText: function(){
// summary:
// Getter for text.
//
return this._rawText || this._text;
},
dataToPoints: function(/*Object*/o){
//summary:
// Converts data to points.
o = o || this.data;
var w = o.width =="auto" ? 1 : o.width;
var h = o.height || this._lineHeight;
this.points = [
{x:o.x, y:o.y}, // TL
{x:o.x + w, y:o.y}, // TR
{x:o.x + w, y:o.y + h}, // BR
{x:o.x, y:o.y + h} // BL
];
return this.points;
},
pointsToData: function(/*Array*/p){
// summary:
// Converts points to data
p = p || this.points;
var s = p[0];
var e = p[2];
this.data = {
x: s.x,
y: s.y,
width: e.x-s.x,
height: e.y-s.y
};
return this.data;
},
render: function(/* String*/text){
// summary:
// Renders the 'hit' object (the shape used for an expanded
// hit area and for highlighting) and the'shape' (the actual
// display object). Text is slightly different than other
// implementations. Instead of calling render twice, it calls
// _createHilite for the 'hit'
// arguments:
// text String
// Changes text if sent. Be sure to use the setText and
// not to call this directly.
//
this.remove(this.shape, this.hit);
//console.log("text render, outline:", !this.annotation, this.renderHit, (!this.annotation && this.renderHit))
!this.annotation && this.renderHit && this._renderOutline();
if(text!=undefined){
this._text = text;
this._textArray = this._text.split("\n");
}
var d = this.pointsToData();
var h = this._lineHeight;
var x = d.x + this.style.text.pad*2;
var y = d.y + this._lineHeight - (this.textSize*.4);
if(this.valign=="middle"){
y -= h/2;
}
this.shape = this.container.createGroup();
/*console.log(" render ", this.type, this.id)
console.log(" render Y:", d.y, "textSize:", this.textSize, "LH:", this._lineHeight)
console.log(" render text:", y, " ... ", this._text, "enabled:", this.enabled);
console.log(" render text:", this.style.currentText);
*/
dojo.forEach(this._textArray, function(txt, i){
var tb = this.shape.createText({x: x, y: y+(h*i), text: unescape(txt), align: this.align})
.setFont(this.style.currentText)
.setFill(this.style.currentText.color);
this._setNodeAtts(tb);
}, this);
this._setNodeAtts(this.shape);
},
_renderOutline: function(){
// summary:
// Create the hit and highlight area
// for the Text.
//
if(this.annotation){ return; }
var d = this.pointsToData();
if(this.align=="middle"){
d.x -= d.width/2 - this.style.text.pad * 2;
}else if(this.align=="start"){
d.x += this.style.text.pad;
}else if(this.align=="end"){
d.x -= d.width - this.style.text.pad * 3;
}
if(this.valign=="middle"){
d.y -= (this._lineHeight )/2 - this.style.text.pad;
}
this.hit = this.container.createRect(d)
.setStroke(this.style.currentHit)
.setFill(this.style.currentHit.fill);
//.setFill("#ffff00");
this._setNodeAtts(this.hit);
this.hit.moveToBack();
},
makeFit: function(text, w){
var span = dojo.create('span', {innerHTML:text, id:"foo"}, document.body);
var sz = 1;
dojo.style(span, "fontSize", sz+"px");
var cnt = 30;
while(dojo.marginBox(span).w<w){
sz++;
dojo.style(span, "fontSize", sz+"px");
if(cnt--<=0) break;
}
sz--;
var box = dojo.marginBox(span);
dojo.destroy(span);
return {size:sz, box:box};
}
}
);
dojox.drawing.register({
name:"dojox.drawing.stencil.Text"
}, "stencil");
}
|
import React, { Component } from "react";
import { Button, Form, FormGroup, Input, FormText, Label, Row, Container, Col, Jumbotron, Card } from 'reactstrap';
// import Input from "./components/Input";
// import SubmitButton from "./components/SubmitButton";
// import { Container, Row, Col } from "./components/Grid";
import Appapi from '../../utils/appapi';
import "./Registration.css";
class RegistrationForm extends Component {
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
address: '',
addressTwo: '',
city: '',
state: '',
zip: '',
phone: '',
email: '',
password: '',
confirmPassword: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange = event => {
const { name, value } = event.target;
this.setState({
[name]: value
});
console.log(this.state);
};
handleSubmit(event) {
event.preventDefault();
alert('Processing new user with email: ' + this.state.firstName);
Appapi.registerUser(this.state);
}
registerUser = (data) => {
Appapi.registerUser(data)
.then(res => {
console.log(res);
// this.setState({ results: res.data.response.docs})
}).catch(err => console.log(err));
};
render() {
return (
<div className="mb20">
<Container>
<Jumbotron>
<h1>Let's get you registered</h1>
<p className="lead">Please fill out the form and we'll activate a profile, this way you can save an animal you're interested in adopting to easily find the dog or cat when you return.</p>
</Jumbotron>
<Form onSubmit={this.handleSubmit}>
<Row>
<Col>
<FormGroup>
<Label>First Name:</Label>
<Input type="text" name="firstName" value={this.state.value} onChange={this.handleChange} />
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label>Last Name:</Label>
<Input type="text" name="lastName" value={this.state.value} onChange={this.handleChange} />
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<FormGroup>
<Label>Address:</Label>
<Input type="text" name="address" value={this.state.value} onChange={this.handleChange} />
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label>Address 2:</Label>
<Input type="text" name="addressTwo"value={this.state.value} onChange={this.handleChange} />
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<FormGroup>
<Label>City:</Label>
<Input type="text" name="city" value={this.state.value}
onChange={this.handleChange} />
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label>State:</Label>
<Input type="text" name="state" value={this.state.value}
onChange={this.handleChange} />
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label>Zip:</Label>
<Input type="text" name="zip" value={this.state.value}
onChange={this.handleChange} />
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<FormGroup>
<Label>Phone:</Label>
<Input type="text" name="phone" value={this.state.value}
onChange={this.handleChange} />
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label>Email:</Label>
<Input type="text" name="email" value={this.state.value}
onChange={this.handleChange} />
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<FormGroup>
<Label>Password:</Label>
<Input type="text" name="password" value={this.state.value}
onChange={this.handleChange} />
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label>Confirm Password:</Label>
<Input type="text" name="confirmPassword" value={this.state.value}
onChange={this.handleChange} />
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<div>
<Button color="warning" type="submit" value="Submit">Submit</Button>
</div>
</Col>
</Row>
</Form>
</Container>
</div>
);
}
}
export default RegistrationForm;
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { ackExpose } from "./ack";
import { method as errorMethod } from "./error";
import { method as numberMethod } from "./number";
import { method as stringMethod } from "./string";
import { method as binaryMethod } from "./binary";
import { method as base64Method } from "./base64";
import { method as objectMethod } from "./object";
import { method as arrayMethod } from "./array";
import { method as queryObjectMethod } from "./queryObject";
import { method as weekMethod } from "./week";
import { method as monthMethod } from "./month";
import { method as yearMethod } from "./year";
import { method as dateMethod } from "./date";
import { method as timeMethod } from "./time";
import { method as methodMethod } from "./method";
var ack = (function (_super) {
__extends(ack, _super);
function ack($var) {
var _this = _super.call(this, $var) || this;
_this.error = errorMethod;
_this.number = numberMethod;
_this.string = stringMethod;
_this.binary = binaryMethod;
_this.base64 = base64Method;
_this.object = objectMethod;
_this.array = arrayMethod;
_this.queryObject = queryObjectMethod;
_this.week = weekMethod;
_this.month = monthMethod;
_this.year = yearMethod;
_this.date = dateMethod;
_this.time = timeMethod;
_this.method = methodMethod;
if (!_this)
return new ack($var);
return _this;
}
ack.prototype.ackit = function (name) {
return ack[name];
};
ack.error = errorMethod;
ack.number = numberMethod;
ack.string = stringMethod;
ack.binary = binaryMethod;
ack.base64 = base64Method;
ack.object = objectMethod;
ack.array = arrayMethod;
ack.queryObject = queryObjectMethod;
ack.week = weekMethod;
ack.month = monthMethod;
ack.year = yearMethod;
ack.date = dateMethod;
ack.time = timeMethod;
ack.method = methodMethod;
return ack;
}(ackExpose));
export { ack };
export default ack;
|
/*jslint nomen: true, vars: true, unparam: true*/
/*global angular*/
(function () {
'use strict';
angular.module('core').service('ServerMessageBroker', ['$http', 'MessagingEngineFactory', 'AppVersionService', '$rootScope',
function ($http, MessagingEngineFactory, AppVersionService, $rootScope) {
return function () {
var messageHandler = {};
var messagingEngine = MessagingEngineFactory.getEngine();
var messageEventUnBind = null;
this.sendHiMessage = function (deviceId) {
var message = {
action: "hi",
deviceId: deviceId,
appVersion: AppVersionService.getVersion()
};
return $http.post("/message", message);
};
this.publishSlideShow = function (slideShowId) {
var message = {
action: "publishSlideShow",
slideShowId: slideShowId,
appVersion: AppVersionService.getVersion()
};
return $http.post("/message", message);
};
this.onNewDeviceSaidHi = function (callback) {
messageHandler.newDeviceSaidHi = callback;
};
this.subscribe = function (callback) {
//todo: extract the subscription because it duplicates the subscription inside DeviceMessageBroker
messageEventUnBind = $rootScope.$on(messagingEngine.serverChannelMessageEvent, function (event, payload) {
var message = payload.message;
if (!messageHandler[message.action]) {
return;
}
messageHandler[message.action](message);
});
messagingEngine.subscribeToServerChannel(function () {
if (callback) {
callback();
}
});
};
this.unSubscribe = function () {
messageEventUnBind();
};
};
}]);
}());
|
/*
*
* Wijmo Library 5.20163.254
* http://wijmo.com/
*
* Copyright(c) GrapeCity, Inc. All rights reserved.
*
* Licensed under the Wijmo Commercial License.
* sales@wijmo.com
* http://wijmo.com/products/wijmo-5/license/
*
*/
"use strict";
var __extends=this && this.__extends || function(d, b)
{
function __()
{
this.constructor = d
}
for (var p in b)
b.hasOwnProperty(p) && (d[p] = b[p]);
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __)
},
wjcChartRadar=require('wijmo/wijmo.chart.radar'),
core_1=require('@angular/core'),
core_2=require('@angular/core'),
core_3=require('@angular/core'),
common_1=require('@angular/common'),
forms_1=require('@angular/forms'),
wijmo_angular2_directiveBase_1=require('wijmo/wijmo.angular2.directiveBase'),
wjFlexRadar_outputs=['initialized', 'gotFocusNg: gotFocus', 'lostFocusNg: lostFocus', 'renderingNg: rendering', 'renderedNg: rendered', 'seriesVisibilityChangedNg: seriesVisibilityChanged', 'selectionChangedNg: selectionChanged', 'selectionChangePC: selectionChange', ],
WjFlexRadar=function(_super)
{
function WjFlexRadar(elRef, injector, parentCmp)
{
_super.call(this, wijmo_angular2_directiveBase_1.WjDirectiveBehavior.getHostElement(elRef));
this.isInitialized = !1;
this.initialized = new core_1.EventEmitter(!0);
this.gotFocusNg = new core_1.EventEmitter(!1);
this.lostFocusNg = new core_1.EventEmitter(!1);
this.renderingNg = new core_1.EventEmitter(!1);
this.renderedNg = new core_1.EventEmitter(!1);
this.seriesVisibilityChangedNg = new core_1.EventEmitter(!1);
this.selectionChangedNg = new core_1.EventEmitter(!1);
this.selectionChangePC = new core_1.EventEmitter(!1);
var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp)
}
return __extends(WjFlexRadar, _super), WjFlexRadar.prototype.ngOnInit = function()
{
this._wjBehaviour.ngOnInit()
}, WjFlexRadar.prototype.ngAfterViewInit = function()
{
this._wjBehaviour.ngAfterViewInit()
}, WjFlexRadar.prototype.ngOnDestroy = function()
{
this._wjBehaviour.ngOnDestroy()
}, Object.defineProperty(WjFlexRadar.prototype, "tooltipContent", {
get: function()
{
return this.tooltip.content
}, set: function(value)
{
this.tooltip.content = value
}, enumerable: !0, configurable: !0
}), Object.defineProperty(WjFlexRadar.prototype, "labelContent", {
get: function()
{
return this.dataLabel.content
}, set: function(value)
{
this.dataLabel.content = value
}, enumerable: !0, configurable: !0
}), WjFlexRadar.meta = {
outputs: wjFlexRadar_outputs, changeEvents: {selectionChanged: ['selection']}
}, WjFlexRadar.decorators = [{
type: core_1.Component, args: [{
selector: 'wj-flex-radar', template: "<div><ng-content></ng-content></div>", inputs: ['wjModelProperty', 'isDisabled', 'binding', 'footer', 'header', 'selectionMode', 'palette', 'plotMargin', 'footerStyle', 'headerStyle', 'tooltipContent', 'itemsSource', 'bindingX', 'interpolateNulls', 'legendToggle', 'symbolSize', 'options', 'selection', 'itemFormatter', 'labelContent', 'chartType', 'startAngle', 'totalAngle', 'reversed', 'stacking', ], outputs: wjFlexRadar_outputs, providers: [{
provide: 'WjComponent', useExisting: core_2.forwardRef(function()
{
return WjFlexRadar
})
}, {
provide: forms_1.NG_VALUE_ACCESSOR, useFactory: wijmo_angular2_directiveBase_1.WjValueAccessorFactory, multi: !0, deps: ['WjComponent']
}]
}, ]
}, ], WjFlexRadar.ctorParameters = [{
type: core_2.ElementRef, decorators: [{
type: core_3.Inject, args: [core_2.ElementRef, ]
}, ]
}, {
type: core_2.Injector, decorators: [{
type: core_3.Inject, args: [core_2.Injector, ]
}, ]
}, {
type: undefined, decorators: [{
type: core_3.Inject, args: ['WjComponent', ]
}, {type: core_3.SkipSelf}, {type: core_2.Optional}, ]
}, ], WjFlexRadar
}(wjcChartRadar.FlexRadar),
wjFlexRadarAxis_outputs,
WjFlexRadarAxis,
wjFlexRadarSeries_outputs,
WjFlexRadarSeries,
moduleExports,
WjChartRadarModule;
exports.WjFlexRadar = WjFlexRadar;
wjFlexRadarAxis_outputs = ['initialized', 'rangeChangedNg: rangeChanged', ];
WjFlexRadarAxis = function(_super)
{
function WjFlexRadarAxis(elRef, injector, parentCmp)
{
_super.call(this);
this.isInitialized = !1;
this.initialized = new core_1.EventEmitter(!0);
this.wjProperty = 'axes';
this.rangeChangedNg = new core_1.EventEmitter(!1);
var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp)
}
return __extends(WjFlexRadarAxis, _super), WjFlexRadarAxis.prototype.ngOnInit = function()
{
this._wjBehaviour.ngOnInit()
}, WjFlexRadarAxis.prototype.ngAfterViewInit = function()
{
this._wjBehaviour.ngAfterViewInit()
}, WjFlexRadarAxis.prototype.ngOnDestroy = function()
{
this._wjBehaviour.ngOnDestroy()
}, WjFlexRadarAxis.meta = {outputs: wjFlexRadarAxis_outputs}, WjFlexRadarAxis.decorators = [{
type: core_1.Component, args: [{
selector: 'wj-flex-radar-axis', template: "", inputs: ['wjProperty', 'axisLine', 'format', 'labels', 'majorGrid', 'majorTickMarks', 'majorUnit', 'max', 'min', 'position', 'reversed', 'title', 'labelAngle', 'minorGrid', 'minorTickMarks', 'minorUnit', 'origin', 'logBase', 'plotArea', 'labelAlign', 'name', 'overlappingLabels', 'labelPadding', 'itemFormatter', 'itemsSource', 'binding', ], outputs: wjFlexRadarAxis_outputs, providers: [{
provide: 'WjComponent', useExisting: core_2.forwardRef(function()
{
return WjFlexRadarAxis
})
}, ]
}, ]
}, ], WjFlexRadarAxis.ctorParameters = [{
type: core_2.ElementRef, decorators: [{
type: core_3.Inject, args: [core_2.ElementRef, ]
}, ]
}, {
type: core_2.Injector, decorators: [{
type: core_3.Inject, args: [core_2.Injector, ]
}, ]
}, {
type: undefined, decorators: [{
type: core_3.Inject, args: ['WjComponent', ]
}, {type: core_3.SkipSelf}, {type: core_2.Optional}, ]
}, ], WjFlexRadarAxis
}(wjcChartRadar.FlexRadarAxis);
exports.WjFlexRadarAxis = WjFlexRadarAxis;
wjFlexRadarSeries_outputs = ['initialized', 'renderingNg: rendering', 'renderedNg: rendered', 'visibilityChangePC: visibilityChange', ];
WjFlexRadarSeries = function(_super)
{
function WjFlexRadarSeries(elRef, injector, parentCmp)
{
_super.call(this);
this.isInitialized = !1;
this.initialized = new core_1.EventEmitter(!0);
this.wjProperty = 'series';
this.renderingNg = new core_1.EventEmitter(!1);
this.renderedNg = new core_1.EventEmitter(!1);
this.visibilityChangePC = new core_1.EventEmitter(!1);
var behavior=this._wjBehaviour = wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector, parentCmp)
}
return __extends(WjFlexRadarSeries, _super), WjFlexRadarSeries.prototype.ngOnInit = function()
{
this._wjBehaviour.ngOnInit()
}, WjFlexRadarSeries.prototype.ngAfterViewInit = function()
{
this._wjBehaviour.ngAfterViewInit()
}, WjFlexRadarSeries.prototype.ngOnDestroy = function()
{
this._wjBehaviour.ngOnDestroy()
}, WjFlexRadarSeries.meta = {
outputs: wjFlexRadarSeries_outputs, changeEvents: {'chart.seriesVisibilityChanged': ['visibility']}, siblingId: 'series'
}, WjFlexRadarSeries.decorators = [{
type: core_1.Component, args: [{
selector: 'wj-flex-radar-series', template: "<div><ng-content></ng-content></div>", inputs: ['wjProperty', 'axisX', 'axisY', 'binding', 'bindingX', 'cssClass', 'name', 'style', 'altStyle', 'symbolMarker', 'symbolSize', 'symbolStyle', 'visibility', 'itemsSource', 'chartType', ], outputs: wjFlexRadarSeries_outputs, providers: [{
provide: 'WjComponent', useExisting: core_2.forwardRef(function()
{
return WjFlexRadarSeries
})
}, ]
}, ]
}, ], WjFlexRadarSeries.ctorParameters = [{
type: core_2.ElementRef, decorators: [{
type: core_3.Inject, args: [core_2.ElementRef, ]
}, ]
}, {
type: core_2.Injector, decorators: [{
type: core_3.Inject, args: [core_2.Injector, ]
}, ]
}, {
type: undefined, decorators: [{
type: core_3.Inject, args: ['WjComponent', ]
}, {type: core_3.SkipSelf}, {type: core_2.Optional}, ]
}, ], WjFlexRadarSeries
}(wjcChartRadar.FlexRadarSeries);
exports.WjFlexRadarSeries = WjFlexRadarSeries;
moduleExports = [WjFlexRadar, WjFlexRadarAxis, WjFlexRadarSeries];
WjChartRadarModule = function()
{
function WjChartRadarModule(){}
return WjChartRadarModule.decorators = [{
type: core_1.NgModule, args: [{
imports: [wijmo_angular2_directiveBase_1.WjDirectiveBaseModule, common_1.CommonModule], declarations: moduleExports.slice(), exports: moduleExports.slice()
}, ]
}, ], WjChartRadarModule.ctorParameters = [], WjChartRadarModule
}();
exports.WjChartRadarModule = WjChartRadarModule
|
'use strict';
!function (win) {
var MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
var doc = win.document;
var listen = 'attachEvent' in win ? function (element, event, callback) {
return element.attachEvent('on' + event, callback);
} : function (element, event, callback) {
return element.addEventListener(event, callback, false);
};
var id = void 0,
height = void 0,
passes = void 0,
timer = void 0;
function poll() {
return win.setTimeout(function () {
var newHeight = doc.body.scrollHeight;
if (passes++ > 60) // 15s to settle down (60 * 250msec)
return;
// Poll again and wait for height to settle down
if (height != newHeight) {
poll();
return;
}
// Height has now settled down
postHeight();
}, 250);
}
function startPoll() {
if (timer != undefined) win.clearTimeout(timer);
passes = 0;
height = doc.body.scrollHeight;
timer = poll();
}
function postHeight() {
win.parent.postMessage({ id: id, height: height }, '*');
}
listen(win, 'message', function (ev) {
if (ev.data == undefined || ev.data.id == undefined) return;
if (id == undefined) {
// first message -- initialize observers
if (MutationObserver != undefined) {
var observer = new MutationObserver(startPoll);
observer.observe(doc, {
attributes: true, subtree: true, childList: true
});
}
}
// Always setup local ID
id = ev.data.id;
// Start post height relay
startPoll();
});
}(window || undefined);
|
angular.module('futurism')
.directive('cardMagnify', function($, _, scrollToElement) {
'use strict';
return {
restrict: 'E',
replace: true,
templateUrl: 'views/card-magnify.html',
scope: {
size: '@',
magnify: '@',
useButtons: '@',
active: '@',
card: '=',
actionFn: '&'
},
link: function (scope, elem) {
scope.hovering = false;
var scrollIntoView = function() {
if(scope.hovering) {
var zoomedCard = elem.find('.card-bigger');
scrollToElement(zoomedCard);
}
};
var deZoom = function() {
if(scope.hovering) {
scope.$apply(function() {
scope.hovering = false;
$('body').off('click', deZoom);
elem.off('mouseleave', deZoom);
});
}
};
var zoom = function() {
if(!scope.hovering) {
_.delay(function() {
scope.$apply(function() {
scope.hovering = true;
_.delay(scrollIntoView, 400);
$('body').on('click', deZoom);
elem.on('mouseleave', deZoom);
});
});
}
};
elem.on('click', function() {
if(scope.active !== 'false') {
if(scope.hovering) {
deZoom();
}
else {
zoom();
}
}
});
scope.$on('$destory', function() {
$('body').off('click', deZoom);
elem.off('mouseleave', deZoom);
});
}
};
});
|
/**
* @module run-task
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("path")
const chalk = require("chalk")
const parseArgs = require("shell-quote").parse
const padEnd = require("string.prototype.padend")
const createHeader = require("./create-header")
const createPrefixTransform = require("./create-prefix-transform-stream")
const spawn = require("./spawn")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const colors = [chalk.cyan, chalk.green, chalk.magenta, chalk.yellow, chalk.red]
let colorIndex = 0
const taskNamesToColors = new Map()
/**
* Select a color from given task name.
*
* @param {string} taskName - The task name.
* @returns {function} A colorize function that provided by `chalk`
*/
function selectColor(taskName) {
let color = taskNamesToColors.get(taskName)
if (!color) {
color = colors[colorIndex]
colorIndex = (colorIndex + 1) % colors.length
taskNamesToColors.set(taskName, color)
}
return color
}
/**
* Wraps stdout/stderr with a transform stream to add the task name as prefix.
*
* @param {string} taskName - The task name.
* @param {stream.Writable} source - An output stream to be wrapped.
* @param {object} labelState - An label state for the transform stream.
* @returns {stream.Writable} `source` or the created wrapped stream.
*/
function wrapLabeling(taskName, source, labelState) {
if (source == null || !labelState.enabled) {
return source
}
const label = padEnd(taskName, labelState.width)
const color = source.isTTY ? selectColor(taskName) : (x) => x
const prefix = color(`[${label}] `)
const stream = createPrefixTransform(prefix, labelState)
stream.pipe(source)
return stream
}
/**
* Converts a given stream to an option for `child_process.spawn`.
*
* @param {stream.Readable|stream.Writable|null} stream - An original stream to convert.
* @param {process.stdin|process.stdout|process.stderr} std - A standard stream for this option.
* @returns {string|stream.Readable|stream.Writable} An option for `child_process.spawn`.
*/
function detectStreamKind(stream, std) {
return (
stream == null ? "ignore" :
// `|| !std.isTTY` is needed for the workaround of https://github.com/nodejs/node/issues/5620
stream !== std || !std.isTTY ? "pipe" :
/* else */ stream
)
}
/**
* Ensure the output of shell-quote's `parse()` is acceptable input to npm-cli.
*
* The `parse()` method of shell-quote sometimes returns special objects in its
* output array, e.g. if it thinks some elements should be globbed. But npm-cli
* only accepts strings and will throw an error otherwise.
*
* See https://github.com/substack/node-shell-quote#parsecmd-env
*
* @param {object|string} arg - Item in the output of shell-quote's `parse()`.
* @returns {string} A valid argument for npm-cli.
*/
function cleanTaskArg(arg) {
return arg.pattern || arg.op || arg
}
//------------------------------------------------------------------------------
// Interface
//------------------------------------------------------------------------------
/**
* Run a npm-script of a given name.
* The return value is a promise which has an extra method: `abort()`.
* The `abort()` kills the child process to run the npm-script.
*
* @param {string} task - A npm-script name to run.
* @param {object} options - An option object.
* @param {stream.Readable|null} options.stdin -
* A readable stream to send messages to stdin of child process.
* If this is `null`, ignores it.
* If this is `process.stdin`, inherits it.
* Otherwise, makes a pipe.
* @param {stream.Writable|null} options.stdout -
* A writable stream to receive messages from stdout of child process.
* If this is `null`, cannot send.
* If this is `process.stdout`, inherits it.
* Otherwise, makes a pipe.
* @param {stream.Writable|null} options.stderr -
* A writable stream to receive messages from stderr of child process.
* If this is `null`, cannot send.
* If this is `process.stderr`, inherits it.
* Otherwise, makes a pipe.
* @param {string[]} options.prefixOptions -
* An array of options which are inserted before the task name.
* @param {object} options.labelState - A state object for printing labels.
* @param {boolean} options.printName - The flag to print task names before running each task.
* @returns {Promise}
* A promise object which becomes fullfilled when the npm-script is completed.
* This promise object has an extra method: `abort()`.
* @private
*/
module.exports = function runTask(task, options) {
let cp = null
const promise = new Promise((resolve, reject) => {
const stdin = options.stdin
const stdout = wrapLabeling(task, options.stdout, options.labelState)
const stderr = wrapLabeling(task, options.stderr, options.labelState)
const stdinKind = detectStreamKind(stdin, process.stdin)
const stdoutKind = detectStreamKind(stdout, process.stdout)
const stderrKind = detectStreamKind(stderr, process.stderr)
const spawnOptions = { stdio: [stdinKind, stdoutKind, stderrKind] }
// Print task name.
if (options.printName && stdout != null) {
stdout.write(createHeader(
task,
options.packageInfo,
options.stdout.isTTY
))
}
// Execute.
const npmPath = options.npmPath || process.env.npm_execpath //eslint-disable-line no-process-env
const npmPathIsJs = typeof npmPath === "string" && /\.m?js/.test(path.extname(npmPath))
const execPath = (npmPathIsJs ? process.execPath : npmPath || "npm")
const isYarn = path.basename(npmPath || "npm").startsWith("yarn")
const spawnArgs = ["run"]
if (npmPathIsJs) {
spawnArgs.unshift(npmPath)
}
if (!isYarn) {
Array.prototype.push.apply(spawnArgs, options.prefixOptions)
}
else if (options.prefixOptions.indexOf("--silent") !== -1) {
spawnArgs.push("--silent")
}
Array.prototype.push.apply(spawnArgs, parseArgs(task).map(cleanTaskArg))
cp = spawn(execPath, spawnArgs, spawnOptions)
// Piping stdio.
if (stdinKind === "pipe") {
stdin.pipe(cp.stdin)
}
if (stdoutKind === "pipe") {
cp.stdout.pipe(stdout, { end: false })
}
if (stderrKind === "pipe") {
cp.stderr.pipe(stderr, { end: false })
}
// Register
cp.on("error", (err) => {
cp = null
reject(err)
})
cp.on("close", (code, signal) => {
cp = null
resolve({ task, code, signal })
})
})
promise.abort = function abort() {
if (cp != null) {
cp.kill()
cp = null
}
}
return promise
}
|
'use strict';
import React from 'react';
export default function About() {
return (
<main className="doc">
<h2>About</h2>
<p>
This app provides the capability to copy a Google Drive folder. It will
copy all contents of the folder and preserve the internal structure of
the files and folders. Optionally, you can also copy any sharing
permissions over to the new folder.
</p>
<p>
If a folder is nested within other folders of your Google Drive, it is
often convenient to make a new copy in the same location. This is the
default behavior. However, if you would rather have the copy appear at
the top level of your Google Drive, you can select to place your copy at
the Root level.
</p>
<p>
This app is licensed under the{' '}
<a href="https://opensource.org/licenses/MIT" target="_blank">
MIT License
</a>
. Feel free to reuse or distribute this code in any way you see fit. You
can find the source code on{' '}
<a href="http://www.github.com/ericyd/gdrive-copy" target="_blank">
Github
</a>
.
</p>
<p>
If you would like to run your own version of the code, please follow
deployment instructions at{' '}
<a
href="https://github.com/ericyd/gdrive-copy#deploying-app"
target="_blank"
>
https://github.com/ericyd/gdrive-copy#deploying-app
</a>
</p>
<h2>Bugs</h2>
<p>
This app is <b><i>not maintained</i></b> and any bugs are just
gonna stay there. The developer apologizes for the inconvenience.
This product does not come with any warranties or guarantees of service.
</p>
<h2>Getting started</h2>
<p>
To get started, simply select your folder and choose a new name, then
select Copy Folder!
<br />
If the folder copy get's stuck, simply use the "Resume prior folder
copy" button, then select the copy of your folder.
</p>
<h2>Privacy</h2>
<p>
Please see the{' '}
<a
href="https://github.com/ericyd/gdrive-copy/blob/master/PRIVACY_POLICY.md"
target="_blank"
>
Privacy Policy
</a>
.
</p>
<p>
This app does not store any data relating to your account or Google
Drive contents.
</p>
<h2>When issues arise...</h2>
<p>
Sometimes this app will get stuck (sorry!). To resume a folder copy that
is in-progress, but paused for whatever reason, simply select the{' '}
<b>
<i>new, incomplete copy</i>
</b>{' '}
of the folder and select "Resume copying".
</p>
</main>
);
}
|
'use strict'
const defaults = require('lodash.defaults')
const escape = require('lodash.escape')
const DefaultPosition = {
position: 0,
lineAndCharacter: {
character: 0,
line: 0,
},
}
class Formatter {
constructor(settings) {
this.settings = defaults(settings, {
severity: 'error',
})
}
formatStream(files) {
const xml = files.map(file => file.xml).join('')
return `<?xml version="1.0" encoding="utf-8"?>\n<checkstyle version="4.3">${xml}\n</checkstyle>`
}
formatFile(fileName, failures) {
const result = failures.map(failure => this.formatError(failure))
result.unshift(`\n<file name="${fileName}">`)
result.push('\n</file>')
return result.join('')
}
formatError(failure) {
const start = failure.startPosition || DefaultPosition
const line = start.lineAndCharacter.line + 1
const column = start.lineAndCharacter.character + 1
const message = escape(failure.failure)
const severity = failure.ruleSeverity || this.settings.severity
const ruleName = failure.ruleName
return `\n<error line="${line}" column="${column}" severity="${severity}" message="${message}" source="${ruleName}"/>`
}
}
module.exports = Formatter
|
$(document).ready(function(){
$("#frmAddCategory").submit(function(ev){
ev.preventDefault();
guardarCategoria();
});
function agregarCategoria(oCat){
var $detCategorias = $("#detCategorias");
var html = '<div class="row">' +
'<div class="col-xs-12 col-md-2">' + oCat.idCategoria + '</div>' +
'<div class="col-xs-12 col-md-5">' + oCat.desCategoria + '</div>' +
'<div class="col-xs-12 col-md-2"><input type="checkbox" checked="' + oCat.esActivo + '"></div>' +
'<div class="col-xs-12 col-md-3">' +
'<button onclick="editarCategoria(' + oCat._id + ', '+ oCat.idCategoria +' , '+
oCat.desCategoria +' , '+ oCat.esActivo +')" class="btn btn-trikas">' +
'<i class="fa fa-pencil"></i>' +
'</button> ' +
'<button onclick="eliminarCategoria('+ oCat._id +', this)" class="btn btn-trikas">' +
'<i class="fa fa-trash"></i>' +
'</button>' +
'</div>' +
'</div>';
$detCategorias.append(html);
}
function guardarCategoria(){
var idCategoria = $("#txtIdCategoria").val().trim();
var desCategoria = $("#txtDesCategoria").val().trim();
var esActivo = $("#chkActivo").is(":checked");
var dataIn = {
idCategoria: idCategoria,
desCategoria: desCategoria,
esActivo: esActivo,
correo: localStorage.usuarioTrikas
};
$.ajax({
type: 'POST',
url: 'http://localhost:3000/categoria',
data: dataIn,
async: false,
beforeSend: function(xhr){
if(xhr && xhr.overrideMimeType){
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function(data){
if(data){
if(typeof (data) == 'string'){
//alert("Registro inválido! " + data);
agregarMsj("msjValidacion", data, false);
}else{
//alert("Registro válido!");
agregarCategoria(data);
agregarMsj("msjValidacion", "Se ha registrado correctamente la Categoría.", true);
}
}else{
agregarMsj("msjValidacion", "Ocurrió un error al momento de guardar la Categoría.", false);
}
}
});
};
function nuevaCategoria(){
var $btnGuardarCategoria = $("#btnGuardarCategoria");
var $btnActualizarCategoria = $("#btnActualizarCategoria");
var $btnNuevaCategoria = $("#btnNuevaCategoria");
$btnGuardarCategoria.removeClass("noDisplay");
if(!$btnActualizarCategoria.hasClass("noDisplay")){
$btnActualizarCategoria.addClass("noDisplay");
}
$btnNuevaCategoria.addClass("noDisplay");
}
$("#btnNuevaCategoria").click(function(){
nuevaCategoria();
})
function actualizarCategoria(){
var id = $("#txtId").val().trim();
var idCategoria = $("#txtIdCategoria").val().trim();
var desCategoria = $("#txtDesCategoria").val().trim();
var esActivo = $("#chkActivo").is(":checked");
console.log("id: " + id);
console.log("idCategoria: " + idCategoria);
console.log("desCategoria: " + desCategoria);
console.log("esActivo: " + esActivo);
console.log("correo: " + localStorage.usuarioTrikas);
var dataIn = {
id: id,
idCategoria: idCategoria,
desCategoria: desCategoria,
esActivo: esActivo,
correo: localStorage.usuarioTrikas
};
$.ajax({
type: 'PUT',
url: 'http://localhost:3000/categoria',
data: dataIn,
async: false,
beforeSend: function(xhr){
if(xhr && xhr.overrideMimeType){
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function(data){
if(data){
if(typeof (data) == 'string'){
//alert("Registro inválido! " + data);
agregarMsj("msjValidacion", data, false);
}else{
//alert("Registro válido!");
agregarMsj("msjValidacion", "Se ha actualizado correctamente la Categoría.", true);
}
}else{
agregarMsj("msjValidacion", "Ocurrió un error al momento de actualizar la Categoría.", false);
}
}
});
}
$("#btnActualizarCategoria").click(function(){
actualizarCategoria();
})
});
function editarCategoria(id, idCategoria, desCategoria, esActivo){
$("#txtId").val(id);
$("#txtIdCategoria").val(idCategoria);
$("#txtDesCategoria").val(desCategoria);
$("#chkActivo").attr("checked", esActivo);
var $btnGuardarCategoria = $("#btnGuardarCategoria");
var $btnActualizarCategoria = $("#btnActualizarCategoria");
var $btnNuevaCategoria = $("#btnNuevaCategoria");
if(!$btnGuardarCategoria.hasClass("noDisplay")){
$btnGuardarCategoria.addClass("noDisplay");
}
$btnActualizarCategoria.removeClass("noDisplay");
$btnNuevaCategoria.removeClass("noDisplay");
}
function eliminarCategoria(id, el){
var $btnEli = $(el);
var dataIn = {
id: id
};
$.ajax({
type: 'DELETE',
url: 'http://localhost:3000/categoria',
data: dataIn,
async: false,
beforeSend: function(xhr){
if(xhr && xhr.overrideMimeType){
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function(data){
if(data){
if(typeof (data) == 'string'){
//alert("Registro inválido! " + data);
agregarMsj("msjValidacionGen", data, false);
}else{
//alert("Registro válido!");
$btnEli.parent().parent().remove();
agregarMsj("msjValidacionGen", "Se ha eliminado correctamente la Categoría.", true);
}
}else{
agregarMsj("msjValidacionGen", "Ocurrió un error al momento de eliminar la Categoría.", false);
}
}
});
}
|
// --------------------
// hints module
// --------------------
// modules
var acorn = require('acorn'),
_ = require('lodash');
// exports
/**
* Parse hints from code.
*
* @param {string} code - Code to be parsed
* @param {string} identifier - Name of hint comments
* @param {Object} [options] - Options object
* @param {boolean} [options.pos] - If true, returns hints with position info
* @returns {Object} - Hints found
*/
var hints = function(code, identifier, options) {
// conform options
options = _.extend({pos: false}, options);
// return hints
return parse(code, identifier)[options.pos ? 'hintsPos' : 'hints'];
};
var Pos = hints.Pos = function(value, start, end) {
this.value = value;
this.start = start;
this.end = end;
};
/**
* Parse hints from code and return with complete AST (abstract syntax tree)
*
* @param {string} code - Code to be parsed
* @param {string} identifier - Name of hint comments
* @returns {Object} params
* @returns {Object} params.hints - Hints object
* @returns {Object} params.hintsPos - Hints object with position info
* @returns {Object} params.tree - Complete AST of code
*/
hints.full = function(code, identifier) {
// return hints
return parse(code, identifier);
};
/**
* Parse hints from code and return with complete AST (abstract syntax tree)
*
* @param {string} code - Code to be parsed
* @param {string} identifier - Name of hint comments
* @returns {Object} params
* @returns {Object} params.hints - Hints object
* @returns {Object} params.hintsPos - Hints object with position info
* @returns {Object} params.tree - Complete AST of code
*/
function parse(code, identifier) {
// if code is an anonymous function or class statement, turn into expression to avoid acorn error
var offset = 0;
if (code.match(/^function\s*\*?\s*\(/) || code.match(/^class\s*\{/)) {
code = 'x=' + code;
offset = 2;
}
// parse code with acorn, extracting comments
var comments = [];
var tree = acorn.parse(code, {onComment: comments});
// extract hints from comments
var hints = {},
hintsPos = {};
comments.forEach(function(comment) {
// deal with single-line comments
if (comment.type == 'Line') return parseLine(comment.value, comment.start - offset, comment.end - offset + 1);
// deal with multi-line comments
comment.value.split(/[\n\r]+/).forEach(function(str) {
parseLine(str, comment.start - offset, comment.end - offset);
});
});
// adjust all positions if options.function set to adjust for offset
if (offset) adjust(tree);
// return result
return {tree: tree, hints: hints, hintsPos: hintsPos};
// parsing function
function parseLine(str, start, end) { // jshint ignore:line
// check is hint comment
var match = str.match(new RegExp('^[\\s\\*]*' + identifier + '\\s+(.+?)\\s*$'));
if (!match) return;
// get all statements
var statements = match[1].split(/[\s,]+/);
statements.forEach(function(statement) {
var parts = statement.split(':', 2),
name = parts[0],
value = (parts.length === 1 ? true : parts[1]);
_.set(hints, name, value);
_.set(hintsPos, name, new Pos(value, start, end));
});
}
// walk through AST, adjusting position of all elements by 2
function adjust(tree) {
tree.body[0] = tree.body[0].expression.right;
tree.end = tree.end - offset;
tree.body = adjustPos(tree.body);
}
function adjustPos(node) {
if (Array.isArray(node)) return node.map(adjustPos);
if (_.isObject(node)) {
node = _.mapValues(node, adjustPos);
if (node.start !== undefined) node.start -= offset;
if (node.end !== undefined) node.end -= offset;
}
return node;
}
}
module.exports = hints;
|
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
]
};
|
/**
* @fileoverview
* @enhanceable
* @public
*/
// GENERATED CODE -- DO NOT EDIT!
goog.provide('proto.tensorflow.serving.InferenceTask');
goog.require('jspb.Message');
goog.require('jspb.BinaryReader');
goog.require('jspb.BinaryWriter');
goog.require('proto.tensorflow.serving.ModelSpec');
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.tensorflow.serving.InferenceTask = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.tensorflow.serving.InferenceTask, jspb.Message);
if (goog.DEBUG && !COMPILED) {
proto.tensorflow.serving.InferenceTask.displayName = 'proto.tensorflow.serving.InferenceTask';
}
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto suitable for use in Soy templates.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.
* @param {boolean=} opt_includeInstance Whether to include the JSPB instance
* for transitional soy proto support: http://goto/soy-param-migration
* @return {!Object}
*/
proto.tensorflow.serving.InferenceTask.prototype.toObject = function(opt_includeInstance) {
return proto.tensorflow.serving.InferenceTask.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Whether to include the JSPB
* instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.tensorflow.serving.InferenceTask} msg The msg instance to transform.
* @return {!Object}
*/
proto.tensorflow.serving.InferenceTask.toObject = function(includeInstance, msg) {
var f, obj = {
modelSpec: (f = msg.getModelSpec()) && proto.tensorflow.serving.ModelSpec.toObject(includeInstance, f),
methodName: jspb.Message.getFieldWithDefault(msg, 2, "")
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.tensorflow.serving.InferenceTask}
*/
proto.tensorflow.serving.InferenceTask.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.tensorflow.serving.InferenceTask;
return proto.tensorflow.serving.InferenceTask.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.tensorflow.serving.InferenceTask} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.tensorflow.serving.InferenceTask}
*/
proto.tensorflow.serving.InferenceTask.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new proto.tensorflow.serving.ModelSpec;
reader.readMessage(value,proto.tensorflow.serving.ModelSpec.deserializeBinaryFromReader);
msg.setModelSpec(value);
break;
case 2:
var value = /** @type {string} */ (reader.readString());
msg.setMethodName(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.tensorflow.serving.InferenceTask.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.tensorflow.serving.InferenceTask.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.tensorflow.serving.InferenceTask} message
* @param {!jspb.BinaryWriter} writer
*/
proto.tensorflow.serving.InferenceTask.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getModelSpec();
if (f != null) {
writer.writeMessage(
1,
f,
proto.tensorflow.serving.ModelSpec.serializeBinaryToWriter
);
}
f = message.getMethodName();
if (f.length > 0) {
writer.writeString(
2,
f
);
}
};
/**
* optional ModelSpec model_spec = 1;
* @return {?proto.tensorflow.serving.ModelSpec}
*/
proto.tensorflow.serving.InferenceTask.prototype.getModelSpec = function() {
return /** @type{?proto.tensorflow.serving.ModelSpec} */ (
jspb.Message.getWrapperField(this, proto.tensorflow.serving.ModelSpec, 1));
};
/** @param {?proto.tensorflow.serving.ModelSpec|undefined} value */
proto.tensorflow.serving.InferenceTask.prototype.setModelSpec = function(value) {
jspb.Message.setWrapperField(this, 1, value);
};
proto.tensorflow.serving.InferenceTask.prototype.clearModelSpec = function() {
this.setModelSpec(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.tensorflow.serving.InferenceTask.prototype.hasModelSpec = function() {
return jspb.Message.getField(this, 1) != null;
};
/**
* optional string method_name = 2;
* @return {string}
*/
proto.tensorflow.serving.InferenceTask.prototype.getMethodName = function() {
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, ""));
};
/** @param {string} value */
proto.tensorflow.serving.InferenceTask.prototype.setMethodName = function(value) {
jspb.Message.setField(this, 2, value);
};
|
//<script>
(function(){
var new_campaigns = false;
bouncex.brandStyles = false;
bouncex.webfonts = false;
bouncex.gbi.stacks = false
var campaign_added = false;
for(var ca_id in new_campaigns){
if(new_campaigns.hasOwnProperty(ca_id)){
if(!bouncex.cookie.campaigns){
bouncex.cookie.campaigns = {};
}
if(!bouncex.cookie.campaigns[ca_id]){
campaign_added = true;
bouncex.cookie.campaigns[ca_id] = {lvt:bouncex.cookie.lvt, vv:0};
}
}
}
if(campaign_added){
bouncex.setBounceCookie();
}
for(var ca_id in bouncex.campaigns){
if(bouncex.campaigns.hasOwnProperty(ca_id)){//copy state vars
if(new_campaigns[ca_id]){
new_campaigns[ca_id].ap = bouncex.campaigns[ca_id].ap;
new_campaigns[ca_id].repressed = Boolean(bouncex.campaigns[ca_id].repressed);
}
if(new_campaigns[ca_id]&&
bouncex.campaigns[ca_id].ad_visible&&
new_campaigns[ca_id].html.replace(/fsa=(\d+)&|width=(\d+)&|height=(\d+)&/gi,'')==bouncex.campaigns[ca_id].html.replace(/fsa=(\d+)&|width=(\d+)&|height=(\d+)&/gi,'')){
new_campaigns[ca_id] = bouncex.campaigns[ca_id];
}else{
bouncex.destroy_ad(ca_id);
}
}
}
bouncex.campaigns = new_campaigns;
new_campaigns = {};
bouncex.debug = false;
bouncex.setBounceCookie();
if (bouncex.campaigns) {
bouncex.loadBounceCss(bouncex.initActivationFuncs);
for (var ca_id in bouncex.campaigns) {
if (bouncex.campaigns[ca_id].ad_visible && typeof bouncex.repressCampaigns === 'function') {
bouncex.repressCampaigns(ca_id);
}
}
}
bouncex.loadBrandStyles();
bouncex.loadWebfonts();
}());
|
var config = require('config');
var os = require('os');
exports.index = function(req, res) {
res.render('framework/index',{
title : 'Sashimi - Framework',
page : 'framework',
// host : getLocalAddress().ipv4[0].address/*'miura2'*/,
host : 'location.hostname',//for server with multiple ip addresses
port : (config.websocket.proxy_from_http ? 'location.port' : config.websocket.port)
});
};
var getLocalAddress = function() {
var ifacesObj = {}
ifacesObj.ipv4 = [];
ifacesObj.ipv6 = [];
var interfaces = os.networkInterfaces();
for (var dev in interfaces) {
interfaces[dev].forEach(function(details){
if (!details.internal){
switch(details.family){
case "IPv4":
ifacesObj.ipv4.push({name:dev, address:details.address});
break;
case "IPv6":
ifacesObj.ipv6.push({name:dev, address:details.address})
break;
}
}
});
}
return ifacesObj;
};
|
import BaseModel from '../BaseModel';
import app from '../../app';
import Items from '../../collections/purchase/Items';
export default class extends BaseModel {
constructor(attrs, options = {}) {
super(attrs, options);
this.shippable = options.shippable || false;
this.moderated = options.moderated || false;
}
defaults() {
return {
// if the listing is not physical, the address and shipping attributes should be blank
shipTo: '',
address: '',
city: '',
state: '',
postalCode: '',
countryCode: '',
addressNotes: '',
moderator: '',
items: new Items(),
memo: '',
alternateContactInfo: '',
};
}
get nested() {
return {
items: Items,
};
}
// this will convert and set an address from the settings
addAddress(sAddr) {
if (!sAddr) throw new Error('You must provide a valid address object.');
const company = sAddr.get('company');
const shipTo = `${sAddr.get('name')}${company ? `, ${company}` : ''}`;
const address = `${sAddr.get('addressLineOne')} ${sAddr.get('addressLineTwo')}`;
const city = sAddr.get('city');
const state = sAddr.get('state');
const postalCode = sAddr.get('postalCode');
const countryCode = sAddr.get('country');
const addressNotes = sAddr.get('addressNotes');
this.set({ shipTo, address, city, state, postalCode, countryCode, addressNotes });
}
validate(attrs) {
const errObj = this.mergeInNestedErrors({});
const addError = (fieldName, error) => {
errObj[fieldName] = errObj[fieldName] || [];
errObj[fieldName].push(error);
};
if (!attrs.items.length) {
addError('items.quantity', app.polyglot.t('orderModelErrors.noItems'));
}
if (this.shippable && !attrs.shipTo && !attrs.countryCode) {
addError('shipping', app.polyglot.t('orderModelErrors.missingAddress'));
}
if (this.moderated && !attrs.moderator && attrs.moderator !== undefined) {
addError('moderated', app.polyglot.t('orderModelErrors.needsModerator'));
}
if (!this.moderated && attrs.moderator) {
// this should only happen if there is a developer error
addError('moderated', app.polyglot.t('orderModelErrors.removeModerator'));
}
if (Object.keys(errObj).length) return errObj;
return undefined;
}
}
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define({title:"Finn min lokasjon"});
|
const THREE = require('three')
export default class Cell //class for rooms or corridors
{
constructor( _name, _center, _width, _length, _mesh )
{
this.name = _name;
this.center = _center.clone();
this.mesh = _mesh.clone();
this.cellWidth = _width; //a x axis term
this.cellLength = _length; //a z axis term
this.radius = Math.sqrt( this.cellLength*this.cellLength + this.cellWidth*this.cellWidth ) * 0.5;
//holds a plain thats deformed in the shader
this.mountain = new THREE.Mesh();
this.mountainMaterial = new THREE.ShaderMaterial();
// //slots for attaching walkways and paths
// this.slot_left = [];
// this.slot_right = [];
// this.slot_front = [];
// this.slot_back = [];
}
// emptyslots(numslots)
// {
// this.slot_left.length = 0;
// this.slot_right.length = 0;
// this.slot_front.length = 0;
// this.slot_back.length = 0;
// for(var i=0; i<numslots; i++)
// {
// this.slot_left.push(false);
// this.slot_right.push(false);
// this.slot_front.push(false);
// this.slot_back.push(false);
// }
// }
drawCell(scene)
{
this.mesh.scale.set( 1,1,1 );
this.mesh.position.set( this.center.x, this.center.y, this.center.z );
scene.add(this.mesh);
}
}
|
var path = require('path'),
RewirePlugin = require("rewire-webpack"),
webpack = require('webpack');
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'test/**/*spec.js'
],
// list of preprocessors
preprocessors: {
'test/**/*.spec.js': ['webpack']
},
webpack: {
resolve: {
root: [
path.resolve('public')
],
extensions: ['', '.js', '.html']
},
module : {
loaders: [
{ test: /\.html$/, loader: 'underscore-template-loader' }
],
postLoaders: [ {
test: /\.js$/,
exclude: /(test|node_modules|bower_components)\//,
loader: 'istanbul-instrumenter'
}]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
Backbone: 'backbone'
}),
new RewirePlugin()
]
},
webpackMiddleware: {
stats: {
colors: true
}
},
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['spec', 'coverage'],
coverageReporter: {
type : 'lcovonly',
dir : './test',
subdir : 'coverage'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
// List plugins explicitly, since autoloading karma-webpack
// won't work here
plugins: [
require("karma-jasmine"),
require("karma-coverage"),
require("karma-webpack"),
require("karma-spec-reporter"),
require("karma-phantomjs-launcher")
]
});
};
|
/*
*
* https://github.com/jkuetemeier/hexo-plugin-multilanguage
*
* Copyright (c) 2014 Jörg Kütemeier
* Licensed under the MIT license.
*/
require('./lib/helper/multi-language');
|
/**
* Panel is an element that can be in two states - opened and closed.
* Those states are controlled by a Pad or directly via methods.
*/
Smudge.Panel = function(element, direction, range)
{
this.element = element;
/**
* Direction of movement when opened
* @type {Enum ["up", "down", "left", "right"]}
*/
this.direction = direction || "up";
/**
* How far will the panel be slided when opened
* @type {Number}
*/
this.range = range || 0;
/**
* Marks the panel state
* Meant to be readonly
* @type {Boolean}
*/
this.opened = true;
/**
* The tween used for animations
* @type {Smudge.Tween}
*/
this.tween = new Smudge.Tween();
// on tween update update the panel transform
this.tween.onUpdate = this.setTransform.bind(this);
};
/**
* The minimal tween velocity (px/s)
* @type {Number}
*/
Smudge.Panel.prototype.tweenMinVelocity = 1000;
/**
* Update the value of the panel range
*
* Usually called on app layout reflow (on screen size chage for ex.)
*/
Smudge.Panel.prototype.setRange = function(range)
{
this.range = range;
};
/**
* Move the panel to the closed state
*
* You can provide velocity (px/s) to alter the animation speed
*/
Smudge.Panel.prototype.close = function(velocity)
{
this.opened = true;
velocity = Math.max(velocity || 0, this.tweenMinVelocity);
this.tween.to(0, 1000 * this.tween.currentValue / velocity);
};
/**
* Move the panel to the opened state
*
* You can provide velocity (px/s) to alter the animation speed
*/
Smudge.Panel.prototype.open = function(velocity)
{
this.opened = false;
velocity = Math.max(velocity || 0, this.tweenMinVelocity);
this.tween.to(this.range, 1000 * (this.range - this.tween.currentValue) / velocity);
};
/**
* Sets the Panel transform value based on the current offset and slide direction
*/
Smudge.Panel.prototype.setTransform = function(val)
{
var x = 0;
var y = 0;
switch (this.direction)
{
case "up": y = -val; break;
case "down": y = val; break;
case "left": x = -val; break;
case "right": x = val; break;
}
this.element.style["transform"] = "translate3d(" + x + "px, " + y + "px, 0)";
this.element.style["-webkit-transform"] = "translate3d(" + x + "px, " + y + "px, 0)";
};
/**
* Set a pad that will control panel opening
*/
Smudge.Panel.prototype.openPad = function(pad)
{
pad.on("move " + this.direction, function(e)
{
if (!this.opened)
return;
this.tween.stop();
this.setTransform(Smudge.Utils.clamp(0, this.range, e.offset));
}.bind(this));
pad.on("end " + this.direction, function(e)
{
if (!this.opened)
return;
this.tween.set(Smudge.Utils.clamp(0, this.range, e.offset));
if (e.currentVelocity > 0)
this.open(e.currentVelocity);
else
this.close(-e.currentVelocity);
}.bind(this));
};
/**
* Set a pad that will control panel closing
*/
Smudge.Panel.prototype.closePad = function(pad)
{
var direction = Smudge.Utils.opositeDirection(this.direction);
pad.on("move " + direction, function(e)
{
if (this.opened)
return;
this.tween.stop();
this.setTransform(Smudge.Utils.clamp(0, this.range, this.range - e.offset));
}.bind(this));
pad.on("end " + direction, function(e)
{
if (this.opened)
return;
this.tween.set(Smudge.Utils.clamp(0, this.range, this.range - e.offset));
if (e.currentVelocity > 0)
this.close(e.currentVelocity);
else
this.open(-e.currentVelocity);
}.bind(this));
};
|
import { createStore } from 'redux';
import reducers from '../reducers';
function reduxStore(initialState) {
const store = createStore(reducers, initialState,
window.devToolsExtension && window.devToolsExtension());
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
// We need to require for hot reloading to work properly.
const nextReducer = require('../reducers'); // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
export default reduxStore;
|
'use strict';
module.exports = {
app: {
title: 'Performance',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
'use strict';
const Command = require('../../Command.js');
const FrameEmbed = require('../../embeds/FrameEmbed.js');
const frames = require('../../resources/frames.json');
/**
* Displays the stats for a warframe
*/
class FrameStats extends Command {
/**
* Constructs a callable command
* @param {Genesis} bot The bot object
*/
constructor(bot) {
super(bot, 'warframe.misc.stats', 'frame', 'Get stats for a Warframe');
this.regex = new RegExp(`^${this.call}\\s?(.+)?`, 'i');
this.usages = [
{
description: 'Get stats for a Warframe',
parameters: ['warframe name'],
},
];
}
/**
* Run the command
* @param {Message} message Message with a command to handle, reply to,
* or perform an action based on parameters.
* @returns {string} success status
*/
async run(message) {
let frame = message.strippedContent.match(this.regex)[1];
if (frame) {
frame = frame.trim().toLowerCase();
const results = frames.filter(entry => new RegExp(entry.regex, 'ig').test(frame));
if (results.length > 0) {
this.messageManager.embed(message, new FrameEmbed(this.bot, results[0]), true, false);
return this.messageManager.statuses.SUCCESS;
}
this.messageManager.embed(message, new FrameEmbed(this.bot, undefined), true, false);
return this.messageManager.statuses.FAILURE;
}
this.messageManager.embed(message, new FrameEmbed(this.bot, undefined), true, false);
return this.messageManager.statuses.FAILURE;
}
}
module.exports = FrameStats;
|
//
import enzyme from 'enzyme'
import React from 'react'
import AdjustSpeed from '../adjust-speed'
import {mockFeed, mockModification} from '../../../utils/mock-data'
describe('Report > AdjustSpeed', () => {
it('renders correctly', () => {
const props = {
feedsById: {1: mockFeed},
modification: {...mockModification, scale: 4}
}
// mount component
const tree = enzyme.shallow(<AdjustSpeed {...props} />)
expect(tree).toMatchSnapshot()
})
})
|
/*
* Copyright (c) 2014 airbug Inc. All rights reserved.
*
* All software, both binary and source contained in this work is the exclusive property
* of airbug Inc. Modification, decompilation, disassembly, or any other means of discovering
* the source code of this software is prohibited. This work is protected under the United
* States copyright law and other international copyright treaties and conventions.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@Export('bugcall.CallResponse')
//@Require('Class')
//@Require('IObjectable')
//@Require('Obj')
//@Require('UuidGenerator')
//@Require('bugmarsh.MarshTag');
//@Require('bugmarsh.MarshPropertyTag');
//@Require('bugmeta.BugMeta')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------
var Class = bugpack.require('Class');
var IObjectable = bugpack.require('IObjectable');
var Obj = bugpack.require('Obj');
var UuidGenerator = bugpack.require('UuidGenerator');
var MarshPropertyTag = bugpack.require('bugmarsh.MarshPropertyTag');
var MarshTag = bugpack.require('bugmarsh.MarshTag');
var BugMeta = bugpack.require('bugmeta.BugMeta');
//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------
var bugmeta = BugMeta.context();
var marsh = MarshTag.marsh;
var property = MarshPropertyTag.property;
//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------
/**
* @class
* @extends {Obj}
* @implements {IObjectable}
*/
var CallResponse = Class.extend(Obj, {
_name: "bugcall.CallResponse",
//-------------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------------
/**
* @constructs
* @param {string} type
* @param {*} data
* @param {string} requestUuid
*/
_constructor: function(type, data, requestUuid) {
this._super();
//-------------------------------------------------------------------------------
// Private Properties
//-------------------------------------------------------------------------------
/**
* @private
* @type {*}
*/
this.data = data;
/**
* @private
* @type {string}
*/
this.requestUuid = requestUuid;
/**
* @private
* @type {string}
*/
this.type = type;
/**
* @private
* @type {string}
*/
this.uuid = UuidGenerator.generateUuid();
},
//-------------------------------------------------------------------------------
// Getters and Setters
//-------------------------------------------------------------------------------
/**
* @return {*}
*/
getData: function() {
return this.data;
},
/**
* @return {string}
*/
getRequestUuid: function() {
return this.requestUuid
},
/**
* @return {string}
*/
getType: function() {
return this.type;
},
/**
* @return {string}
*/
getUuid: function() {
return this.uuid;
},
//-------------------------------------------------------------------------------
// IObjectable Implementation
//-------------------------------------------------------------------------------
/**
* @return {{requestUuid: string, type: string, data: *, uuid: string}}
*/
toObject: function() {
return {
requestUuid: this.getRequestUuid(),
type: this.getType(),
data: this.getData(),
uuid: this.getUuid()
}
}
});
//-------------------------------------------------------------------------------
// Interfaces
//-------------------------------------------------------------------------------
Class.implement(CallResponse, IObjectable);
//-------------------------------------------------------------------------------
// BugMeta
//-------------------------------------------------------------------------------
bugmeta.tag(CallResponse).with(
marsh("CallResponse")
.properties([
property("data"),
property("requestUuid"),
property("type"),
property("uuid")
])
);
//-------------------------------------------------------------------------------
// Export
//-------------------------------------------------------------------------------
bugpack.export('bugcall.CallResponse', CallResponse);
});
|
const fs = require('fs');
const path = require('path');
const Product = require('../models/Product');
const Category = require('../models/Category');
module.exports.addGet = (req, res) => {
let filePath = path.normalize(
path.join(__dirname, '../views/products/add.html'));
fs.readFile(filePath, (err, data) => {
if (err) {
console.log(err);
return;
}
Category.find().then((categories) => {
let replacement = `<select class="input-field" name="category"`;
for (let category of categories) {
replacement +=
`<option value="${category._id}">${category.name}</option>`
}
replacement += '</select>';
let html = data.toString().replace('{categories}', replacement);
res.writehead(200, {
"Content-Type": "text/html"
});
res.end(html);
})
})
}
module.exports.addPost = (req, res) => {
let productObj = req.body;
productObj.image = '\\' + req.body.path;
Product.create(productObj).then((product) => {
Category.findById(product.category).then((category) => {
category.products.push(product._id);
category.save();
})
res.redirect('/');
})
}
|
'use strict';
var highScores = [];
var tbody = document.getElementById('tableBody');
if(localStorage.currentHighScore){
var dataString = localStorage.currentHighScore;
highScores = JSON.parse(dataString);
writeScoresToPage(highScores);
} else {
var newTRow = document.createElement('tr');
tbody.appendChild(newTRow);
var noNameData = document.createElement('td');
noNameData.textContent = 'No names yet!';
newTRow.appendChild(noNameData);
var noScoreData = document.createElement('td');
noScoreData.textContent = 'No scores yet!';
newTRow.appendChild(noScoreData);
}
function writeScoresToPage(array) {
if (document.getElementById('tableBody')){
for (var i = 0; i < array.length; i++) {
addToScoreBoard(array[i]);
}
}
}
function addToScoreBoard (playerObject){
var newTRow = document.createElement('tr');
tbody.appendChild(newTRow);
var playerData = document.createElement('td');
newTRow.appendChild(playerData);
playerData.textContent = playerObject.name;
var scoreData = document.createElement('td');
newTRow.appendChild(scoreData);
scoreData.textContent = playerObject.currentScore;
}
|
import BaseValidator from './base';
var PostValidator = BaseValidator.create({
properties: ['title', 'metaTitle', 'metaDescription'],
title: function (model) {
var title = model.get('title');
if (validator.empty(title)) {
model.get('errors').add('title', '必须为博文设置一个标题。');
this.invalidate();
}
if (!validator.isLength(title, 0, 150)) {
model.get('errors').add('title', 'Title cannot be longer than 150 characters.');
this.invalidate();
}
},
metaTitle: function (model) {
var metaTitle = model.get('meta_title');
if (!validator.isLength(metaTitle, 0, 150)) {
model.get('errors').add('meta_title', '优化标题不能超过 150 个字符。');
this.invalidate();
}
},
metaDescription: function (model) {
var metaDescription = model.get('meta_description');
if (!validator.isLength(metaDescription, 0, 200)) {
model.get('errors').add('meta_description', '优化描述不能超过 200 个字符。');
this.invalidate();
}
}
});
export default PostValidator;
|
var development = false;
var container;
$(document).ready(function() {
mturk_ready(function() {
mturk_blockbadworkers(boot);
});
});
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
function boot()
{
console.log("Booting...");
container = $("#container");
if (isIE())
{
container.html("<p style='width:500px;'><strong>Sorry!</strong> This application does not currently support Internet Explorer. Please upgrade to a more modern browser to complete this HIT. We recommend <a href='http://www.google.com/chrome' target='_blank'>Google Chrome</a> or <a href='http://www.getfirefox.com' target='_blank'>Mozilla Firefox</a>.</p>");
return;
}
var parameters = mturk_parameters();
if (!parameters["id"])
{
brandingscreen();
return;
}
if (!mturk_isassigned())
{
mturk_acceptfirst();
}
else
{
mturk_showstatistics();
}
mturk_disabletimer();
function dispatch(training)
{
training = training ? 1 : 0;
server_request("getjob", [parameters["id"], training], function(data) {
loadingscreen(job_import(data));
});
}
worker_isverified(function() {
console.log("Worker is verified");
dispatch(false);
}, function() {
console.log("Worker is NOT verified");
dispatch(true);
});
}
function loadingscreen(job)
{
var ls = $("<div id='loadingscreen'></div>");
ls.append("<div id='loadingscreeninstructions' class='button'>Show " +
"Instructions</div>");
ls.append("<div id='loadingscreentext'>Loading the video...</div>");
ls.append("<div id='loadingscreenslider'></div>");
if (!mturk_isassigned())
{
ls.append("<div class='loadingscreentip'><strong>Tip:</strong> You " +
"are strongly recommended to accept the task before the " +
"download completes. When you accept, you will have to restart " +
"the download.</div>");
}
ls.append("<div class='loadingscreentip'>You are welcome to work on " +
"other HITs while you wait for the download to complete. When the " +
"download finishes, we'll play a gentle musical tune to notify " +
"you.</div>");
container.html(ls);
if (!development && !mturk_isoffline())
{
ui_showinstructions(job);
}
$("#loadingscreeninstructions").button({
icons: {
primary: "ui-icon-newwin"
}
}).click(function() {
ui_showinstructions(job);
});
eventlog("preload", "Start preloading");
preloadvideo(job.start, job.stop, job.frameurl,
preloadslider($("#loadingscreenslider"), function(progress) {
if (progress == 1)
{
if (!development && !mturk_isoffline())
{
/*$("body").append('<div id="music"><embed src="magic.mp3">' +
'<noembed><bgsound src="magic.mp3"></noembed></div>');*/
window.setTimeout(function() {
$("#music").remove();
}, 2000);
}
ls.remove()
ui_build(job);
mturk_enabletimer();
eventlog("preload", "Done preloading");
}
})
);
}
function brandingscreen()
{
console.log("Loading screen");
var d = $("<div style='margin:0 auto;width:400px;background-color:#fff;padding:20px;'></div>");
d.append("<h1>Welcome to vatic</h1>");
window.location = "./login/login.html";
d.hide();
d.appendTo(container);
d.show("explode", 1000);
$("body").animate({"background-color": "#666"}, 1000);
}
|
var appModule = angular.module( "TagThisApp", [], function( $locationProvider ) {
$locationProvider.html5Mode( true );
} );
var stackExchangeAccessToken = "";
function TagThisController( $scope, $location, $http ) {
// Check if we got an access token through OAuth with the SE API.
var accessToken = $location.path().match( /\/access_token=(.+)&expires=\d+/ );
if( accessToken ) {
$scope.accessToken = stackExchangeAccessToken = accessToken[ 1 ];
console.log( "Got access token " + stackExchangeAccessToken );
$location.path( "" );
}
$scope.tag = $location.search()[ "tag" ] || $location.path().substr( 1 ) || "tag-this";
$scope.sites = {
stackoverflow : {
site : "stackoverflow",
class : "stackoverflow",
domain : "stackoverflow.com"
},
serverfault : {
site : "serverfault",
class : "serverfault",
domain : "serverfault.com"
},
superuser : {
site : "superuser",
class : "superuser",
domain : "superuser.com"
},
askubuntu : {
site : "askubuntu",
class : "askubuntu",
domain : "askubuntu.com"
},
meta : {
stackoverflow : {
site : "meta.stackoverflow",
class : "meta stackoverflow",
domain : "meta.stackoverflow.com"
},
serverfault : {
site : "meta.serverfault",
class : "meta serverfault",
domain : "meta.serverfault.com"
},
superuser : {
site : "meta.superuser",
class : "meta superuser",
domain : "meta.superuser.com"
},
askubuntu : {
site : "meta.askubuntu",
class : "meta askubuntu",
domain : "meta.askubuntu.com"
}
}
};
/**
* Update the path in the URL with the current model.
*/
$scope.updatePath = function() {
$location.path( $scope.tag );
}
}
appModule.factory( "tags", ["$q", "$timeout", "$http", function( $q, $timeout, $http ) {
// A cache for already retrieved counts.
var cache = {};
// A store for promises to retrieve counts.
var retriever = {};
function getCount( site, tag ) {
// Check if we already retrieved the count for that tag.
if( cache[site] && cache[site][tag] ) {
return cache[site][tag].promise;
}
// Store a deferred in the cache.
cache[site] = cache[site] || {};
cache[site][tag] = $q.defer();
// Cancel existing retrievals
if( retriever[site] ) {
$timeout.cancel( retriever[site] );
delete retriever[site];
}
// Construct a retriever that will run after a certain delay (to avoid sending tons of requests while typing).
var retrieverPromise = $timeout( function() {
console.log( "Retrieving " + tag + " for " + site );
var requestUri = "https://api.stackexchange.com/2.2/tags/" + encodeURIComponent( tag ) + "/info?site=" + site;
if( stackExchangeAccessToken ) {
requestUri += "&key=1dkkO89fIM9mRiK55gzqQQ((&access_token=" + stackExchangeAccessToken;
}
$http.get( requestUri )
.then( function( response ) {
if( response.status != 200 ) {
console.log( response );
cache[site][tag].reject( response );
} else {
if( response.data.items && response.data.items.length ) {
cache[site][tag].resolve( response.data.items[0].count );
} else {
cache[site][tag].resolve( 0 );
}
}
} );
}, 3000 );
// Store the retriever, so it can be cancelled if a new retrieval is queued soon.
retriever[site] = retrieverPromise;
return cache[site][tag].promise;
}
// Export
return {
getCount : getCount
};
}] );
var abstractTag = {
restrict : "E",
require : "ngModel",
scope : {
ngModel : "=",
tag : "=",
tagClass : "="
},
replace : true
};
appModule.directive( "siteTag", ["tags", function( tags ) {
var siteTag = angular.copy( abstractTag );
siteTag.template = '<span class="tag-container site-tag {{ngModel.class}}" title="{{count}}">' +
' <img class="favicon" ng-src="http://{{ngModel.domain}}/favicon.ico" width="16">' +
' <a class="tag site-tag {{ngModel.class}}" href="http://{{ngModel.domain}}/tags/{{tag}}">{{tag}}</a>' +
'</span>';
siteTag.link = function postLink( scope, element, attributes ) {
scope.$watch( "tag", function( newTag ) {
scope.count = "invalid tag";
if( !newTag ) return;
scope.count = "loading question count…";
tags.getCount( scope.ngModel.site, newTag )
.then( function( count ) {
scope.count = count + " questions with this tag";
} );
} )
};
return siteTag;
}] );
appModule.directive( "chatTag", ["tags", function( tags ) {
var chatTag = angular.copy( abstractTag );
chatTag.template = '<span class="tag-container chat-tag {{ngModel.class}}" title="{{count}}">' +
' <img class="favicon" ng-src="http://{{ngModel.domain}}/favicon.ico" width="16">' +
' <a class="tag-link chat-tag {{ngModel.class}}" href="http://{{ngModel.domain}}/tags/{{tag}}"><span class="tag chat-tag {{ngModel.class}}">{{tag}}</span></a>' +
'</span>';
chatTag.link = function postLink( scope, element, attributes ) {
scope.$watch( "tag", function( newTag ) {
scope.count = "invalid tag";
if( !newTag ) return;
scope.count = "loading question count…";
tags.getCount( scope.ngModel.site, newTag )
.then( function( count ) {
scope.count = count + " questions with this tag";
} );
} )
};
return chatTag;
}] );
|
/*! jCarousel - v0.3.1 - 2014-05-05
* http://sorgalla.com/jcarousel
* Copyright (c) 2014 Jan Sorgalla; Licensed MIT */
(function(t){"use strict";t.jcarousel.fn.scrollIntoView=function(i,s,e){var r,n=t.jCarousel.parseTarget(i),o=this.index(this._fullyvisible.first()),l=this.index(this._fullyvisible.last());if(r=n.relative?0>n.target?Math.max(0,o+n.target):l+n.target:"object"!=typeof n.target?n.target:this.index(n.target),o>r)return this.scroll(r,s,e);if(r>=o&&l>=r)return t.isFunction(e)&&e.call(this,!1),this;for(var a,h=this.items(),u=this.clipping(),c=this.vertical?"bottom":this.rtl?"left":"right",f=0;;){if(a=h.eq(r),0===a.length)break;if(f+=this.dimension(a),f>=u){var d=parseFloat(a.css("margin-"+c))||0;f-d!==u&&r++;break}if(0>=r)break;r--}return this.scroll(r,s,e)}})(jQuery);
|
/**
* @jest-environment ./__tests__/html/__jest__/WebChatEnvironment.js
*/
describe('Markdown', () => {
test('should not render URL with "javascript" scheme', () => runHTMLTest('markdown.noJavaScriptScheme.html'));
});
|
#pragma strict
var FirstForce:Vector3 = Vector3(300, 300, 0);
function Start () {
rigidbody.AddForce(FirstForce);
}
function Update () {
// ゲームオーバー判定
if(transform.position.x < 1.48)
{
Application.LoadLevel(7) ;
}
}
function OnCollisionEnter(col : Collision)
{
var count : int = 0 ;
// 削除判定
if (col.gameObject.tag == "Block")
{
col.gameObject.SendMessage("setDamage");
}
rigidbody.velocity = rigidbody.velocity.normalized * 10;
if (Mathf.Abs(rigidbody.velocity.y) < 3) {
rigidbody.velocity.y = rigidbody.velocity.y * 3;
}
if (Mathf.Abs(rigidbody.velocity.x) < 3) {
rigidbody.velocity.x = rigidbody.velocity.x * 3;
}
}
|
/** Gamepads related functionality.
*
* The object also works as an array of gamepads, thus
* PLAYGROUND.Gamepads[0] is the first one.
*
* Properties:
* - app: the main application object
* - buttons: maps numeric ids to button names
* - gamepads:
* - gamepadmoveEvent: cached event
* - gamepaddownEvent: cached event
* - gamepadupEvent: cached event
*
* Events generated by this object:
* - gamepadmove: change in position
* - gamepaddown:
* - gamepadup:
*
* Reference: http://playgroundjs.com/playground-gamepads
*/
PLAYGROUND.Gamepads = function(app) {
this.app = app;
PLAYGROUND.Events.call(this);
this.getGamepads = navigator.getGamepads || navigator.webkitGetGamepads;
this.gamepadmoveEvent = {};
this.gamepaddownEvent = {};
this.gamepadupEvent = {};
this.gamepads = {};
this.app.on("step", this.step.bind(this));
};
PLAYGROUND.Gamepads.prototype = {
buttons: {
0: "1",
1: "2",
2: "3",
3: "4",
4: "l1",
5: "r1",
6: "l2",
7: "r2",
8: "select",
9: "start",
12: "up",
13: "down",
14: "left",
15: "right"
},
zeroState: function() {
var buttons = [];
for (var i = 0; i <= 15; i++) {
buttons.push({
pressed: false,
value: 0
});
}
return {
axes: [],
buttons: buttons
};
},
createGamepad: function() {
var result = {
buttons: {},
sticks: [{
x: 0,
y: 0
}, {
x: 0,
y: 0
}]
};
for (var i = 0; i < 16; i++) {
var key = this.buttons[i];
result.buttons[key] = false;
}
return result;
},
step: function() {
if (!navigator.getGamepads) return;
var gamepads = navigator.getGamepads();
for (var i = 0; i < gamepads.length; i++) {
var current = gamepads[i];
if (!current) continue;
if (!this[i]) this[i] = this.createGamepad();
/* have to concat the current.buttons because the are read-only */
var buttons = [].concat(current.buttons);
/* hack for missing dpads */
for (var h = 12; h <= 15; h++) {
if (!buttons[h]) buttons[h] = {
pressed: false,
value: 0
};
}
var previous = this[i];
/* axes (sticks) to buttons */
if (current.axes) {
if (Math.abs(current.axes[0]) > 0.01) {
if (current.axes[0] < 0) buttons[14].pressed = true;
if (current.axes[0] > 0) buttons[15].pressed = true;
}
if (Math.abs(current.axes[1]) > 0.01) {
if (current.axes[1] < 0) buttons[12].pressed = true;
if (current.axes[1] > 0) buttons[13].pressed = true;
}
var stickChanged = false;
var stickA = false;
var stickB = false;
if (previous.sticks[0].x !== current.axes[0]) {
stickChanged = true;
stickA = true;
}
if (previous.sticks[0].y !== current.axes[1]) {
stickChanged = true;
stickA = true;
}
if (previous.sticks[1].x !== current.axes[2]) {
stickChanged = true;
stickB = true;
}
if (previous.sticks[1].y !== current.axes[3]) {
stickChanged = true;
stickB = true;
}
if (stickChanged) {
this.gamepadmoveEvent.old = [
Utils.extend({}, previous.sticks[0]),
Utils.extend({}, previous.sticks[1])
];
previous.sticks[0].x = current.axes[0];
previous.sticks[0].y = current.axes[1];
previous.sticks[1].x = current.axes[2];
previous.sticks[1].y = current.axes[3];
this.gamepadmoveEvent.sticks = previous.sticks;
if (stickA) this.gamepadmoveEvent.a = previous.sticks[0];
else this.gamepadmoveEvent.a = false;
if (stickB) this.gamepadmoveEvent.b = previous.sticks[1];
else this.gamepadmoveEvent.b = false;
this.gamepadmoveEvent.gamepad = i;
this.trigger("gamepadmove", this.gamepadmoveEvent);
}
}
/* check buttons changes */
for (var j = 0; j < buttons.length; j++) {
var key = this.buttons[j];
/* gamepad down */
if (buttons[j].pressed && !previous.buttons[key]) {
previous.buttons[key] = true;
this.gamepaddownEvent.button = this.buttons[j];
this.gamepaddownEvent.gamepad = i;
this.trigger("gamepaddown", this.gamepaddownEvent);
}
/* gamepad up */
else if (!buttons[j].pressed && previous.buttons[key]) {
previous.buttons[key] = false;
this.gamepadupEvent.button = this.buttons[j];
this.gamepadupEvent.gamepad = i;
this.trigger("gamepadup", this.gamepadupEvent);
}
}
}
}
};
PLAYGROUND.Utils.extend(PLAYGROUND.Gamepads.prototype, PLAYGROUND.Events.prototype);
|
angular.module('movieCore', ['ngResource'])
.factory('PopularMovies', function($resource) {
var token = 'teddybear'; // TBD
return $resource('popular/:movieId', { movieId: '@id' }, {
update: {
method: 'PUT',
headers: { 'authToken': token }
},
get: {
method: 'GET',
headers: { 'authToken': token }
},
query: {
method: 'GET',
headers: { 'authToken': token },
isArray: true
},
save: {
method: 'POST',
headers: { 'authToken': token }
},
remove: {
method: 'DELETE',
headers: { 'authToken': token }
}
});
});
|
(function () {
angular.module('profile', [
]);
})();
|
/**
* @Author: robin
* @Date: 2017-03-07 17:30:24
* @Email: xin.lin@qunar.com
* @Last modified by: robin
* @Last modified time: 2017-03-07 17:30:24
*/
'use strict'
var _ = require('lodash'),
swiftUtils = require('../common/swiftUtils'),
utils = require('../common/utils');
/*@Command({
"name": "swift [action] [name]",
"alias":"w",
"des":"use swift quickly",
options:[
["-h, --host [host]", "host of swift"],
["-u, --user [user]", "user of swift"],
["-p, --pass [pass]", "pass of swift"],
["-c, --container [container]", "container in swift"]
]
})*/
module.exports = {
run: function(action, name, options) {
try {
var params = swiftUtils.getConfig(options, utils.isSnapshot(name) ? 'resourceSnapshotSwift' : 'resourceSwift'),
command = { query:1, delete:1 , deleteContainer:1};
params.name = name;
if(command[action]){
this[action](params, this.exit);
}else{
throw new Error('非法swift指令操作:' + action);
}
} catch (e) {
this.exit(e);
}
},
/**
* 查询对象是否存在
* @param {Object} params [description]
* @param {Function} callback [description]
* @return {[type]} [description]
*/
query: function(params, callback) {
swiftUtils.objectExist(params, function(err, res){
if(!err){
console.info('该对象存在!!');
}
callback(err, res);
});
},
/**
* 删除对象
* @param {Object} params [description]
* @param {Function} callback [description]
*/
delete: function(params, callback){
swiftUtils.deleteObject(params, function(err, res){
if(!err){
console.info('删除对象完成!!');
}
callback(err, res);
});
},
/**
* 删除对象
* @param {Object} params [description]
* @param {Function} callback [description]
*/
deleteContainer: function(params, callback){
swiftUtils.deleteContainer(params, function(err, res){
if(!err){
console.info('删除容器完成!!');
}
callback(err, res);
});
},
/**
* 退出
* @return {[type]} [description]
*/
exit: function(err){
if(err){
console.error(err.stack || err);
process.exit(1);
} else {
process.exit(0);
}
}
}
|
const answers = [ 'Maybe.', 'Certainly not.', 'I hope so.', 'Not in your wildest dreams.', 'There is a good chance.', 'Quite likely.', 'I think so.', 'I hope not.', 'I hope so.', 'Never!', 'Fuhgeddaboudit.', 'Ahaha! Really?!?', 'Pfft.', 'Sorry, bucko.', 'Hell, yes.', 'Hell to the no.', 'The future is bleak.', 'The future is uncertain.', 'I would rather not say.', 'Who cares?', 'Possibly.', 'Never, ever, ever.', 'There is a small chance.', 'Yes!' ];
const Social = require('../base/Social.js');
class Magic8 extends Social {
constructor(client) {
super(client, {
name: 'magic8',
description: 'Answers a question, magic 8 ball style.',
usage: 'magic8 <question>?',
category: 'Miscellaneous',
extended: 'This Social will answer any question given to it in the style of a magic 8 ball.',
cost: 5,
aliases: ['8', '8ball']
});
}
async run(message, args, level) {
try {
if (!message.content.endsWith('?')) return message.reply('That does not look like a question, (hint, end your question with a `?`.)');
if (!args) return message.reply('You need to actually ask a question...');
const cost = this.cmdDis(this.help.cost, level);
const payMe = await this.cmdPay(message, message.author.id, cost, this.conf.botPerms);
if (!payMe) return;
const msg = await message.channel.send('`Thinking...`');
setTimeout( async () => {
await msg.edit(`${answers[Math.floor(Math.random() * answers.length)]}`);
}, Math.random() * (1 - 5) + 1 * 2000);
} catch (error) {
throw error;
}
}
}
module.exports = Magic8;
|
import './api/methods';
import './models';
import './publications';
|
import test from 'ava';
import sinon from 'sinon';
import ApiServer from '../../../src/server/api/server';
import ServerSettingsManager from '../../../src/server/setting/server-settings-manager';
test.beforeEach((t) => {
t.context.sandbox = sinon.sandbox.create();
t.context.sandbox.stub(ServerSettingsManager, 'getSettings');
});
test.afterEach.always((t) => {
t.context.sandbox.restore();
});
test.serial('#list is should send all server settings.', (t) => {
ServerSettingsManager.getSettings.returns(
{ dummyKey1: 'dummyValue1', dummyKey2: 'dummyValue2' }
);
const req = {};
const res = createStubResponse();
ApiServer.list(req, res);
t.true(ServerSettingsManager.getSettings.calledOnce);
t.true(res.status.calledOnce);
t.is(res.status.args[0][0], 200);
t.true(res.send.calledOnce);
t.deepEqual(res.send.args[0][0],
{ dummyKey1: 'dummyValue1', dummyKey2: 'dummyValue2' });
});
function createStubResponse() {
return {
status: sinon.stub().returnsThis(),
send: sinon.stub().returnsThis(),
};
}
|
var express = require('express');
var router = express.Router();
/* GET contact page. */
router.get('/', function(req, res) {
res.render('contact');
});
module.exports = router;
|
/*****************
Sends information to the Simulation/Stats file
*****************/
function statsController(){
console.log("Creating Stats Controller");
/* DECLARATIONS */
this.statsView = new statsView();
/* OBSERVABLE METHODS */
this.observers = [];
this.addObserver = function(observer){
this.observers.push(observer); };
this.removeObserver = function(observer){
var numObs = this.observers.length;
for (var i=0; i<numObs; i++){
if (this.observers[i] === observer){
this.observers.splice(i,1); }}};
this.notifyObservers = function(msg){
var numObs = this.observers.length;
for (var i=0; i<numObs; i++){
this.observers[i].receiveMessage(this, msg);
}};
/* INTERFACE */
this.setStats = function(stats){
this.stats = stats;
};
this.clearStats = function(){
this.stats.clearStats();
};
this.updateOrgStatsView = function(){
for (var i = 0; i < this.stats.numOrgs; i++) {
var os = this.stats.getOrgStats(i+1);
var sv = this.statsView;
sv.updateBirths(this.stats.getOrgStats(i+1).getBirths(), i+1);
sv.updateDeaths(os.getDeaths(), i+1);
sv.updateExplored(os.getExplored(), i+1);
sv.updateGenCount(this.stats.getColStats().getGens());
sv.updateAge(this.stats.getColStats().getAge());
}
};
this.updateColStatsView = function(){
var sv = this.statsView;
var s = this.stats;
this.stats.colStats.calcStats();
sv.updateAvgBirths(this.stats.colStats.getAvgBirths());
sv.updateAvgDeaths(this.stats.colStats.getAvgDeaths());
sv.updateMostBirths(this.stats.colStats.getMostBirths());
sv.updateFewestDeaths(this.stats.colStats.getFewestDeaths());
sv.updateMostBirthsOrgID(this.stats.colStats.getMostBirthsOrgID());
sv.updateFewestDeathsOrgID(this.stats.colStats.getFewestDeathsOrgID());
};
this.updateViews = function(){
this.updateColStatsView();
this.updateOrgStatsView();
};
this.toString = function(){
return "The Stats Controller";
};
}
|
var class_v_global =
[
[ "ChangeState", "class_v_global.html#a6912456eee6d25949756504b9fe439d0", null ],
[ "ClearState", "class_v_global.html#aab319618a34b8ec21cbfbdd380d1f05b", null ],
[ "Collides", "class_v_global.html#a081f153646fc33751cb3a969f4d64c34", null ],
[ "CollidesCircle", "class_v_global.html#a49687f446bc6fdbafd15ff4c034243cf", null ],
[ "CurrentState", "class_v_global.html#a93e9f40a3df5f860b8ab3f3a18763fe8", null ],
[ "Exit", "class_v_global.html#afd8d02960097f48ee7f599f63b553548", null ],
[ "GetMousePosition", "class_v_global.html#aa159bc5f7e582cb488584abd1c25d4f2", null ],
[ "IsFullscreen", "class_v_global.html#aa6373d7a5065c0a140a48efb7189213c", null ],
[ "OverlapAtPoint", "class_v_global.html#a7383a67120f6b9a44bf12474cc0aa87b", null ],
[ "OverlapCircleAtPoint", "class_v_global.html#ac33a3527b9bd7a7b300f91fbdaa6fe43", null ],
[ "Overlaps", "class_v_global.html#a86583d28e1dc6a1e9b4c40c4e91c0b3c", null ],
[ "OverlapsCircle", "class_v_global.html#acf9c112c25f28ae223941eb848635abe", null ],
[ "PopState", "class_v_global.html#a4c6047fbbeb4d5d8e180a464341099ae", null ],
[ "PushState", "class_v_global.html#a703ce11bb78975db762d8ee0c2103497", null ],
[ "SetFullscreen", "class_v_global.html#ac4ebd9f73c22ff4b84ab352dccf5a24c", null ],
[ "SetMouseCursorVisible", "class_v_global.html#a529dc70f035f320e52d85b43e0832ca2", null ],
[ "ToggleFullscreen", "class_v_global.html#aa1ee39db10d8dd9964dcb589338432a0", null ],
[ "Antialiasing", "class_v_global.html#a76ca72d91eba5052f77cb283bc6dd89a", null ],
[ "App", "class_v_global.html#a94a4ea71412120c857c1a5b17d2e6b84", null ],
[ "Async", "class_v_global.html#a23ba7fceeca72948527423d5ce69f4e0", null ],
[ "BackgroundColor", "class_v_global.html#ac8ba15751a3be1d8c1ccdca15ec6df4c", null ],
[ "Content", "class_v_global.html#a888aa3ad353c4ed5358a0f9997719cfc", null ],
[ "ContextSettings", "class_v_global.html#add32445de0ceb7ceed9630b2843e94b8", null ],
[ "DrawDebug", "class_v_global.html#a53b0f099ec895ad0b2e85e1c77029f7c", null ],
[ "FocusPause", "class_v_global.html#a75e67b8e02b98be46ac4fa04e6e31cdf", null ],
[ "FPS", "class_v_global.html#a577c23481b1a2269a25afe4f8de803ea", null ],
[ "Height", "class_v_global.html#a0f9aec392b77b2eb657f7a80b93b06d1", null ],
[ "IfChangedState", "class_v_global.html#adcd1ad622715e62685f418a4ecf942f2", null ],
[ "IfPushedState", "class_v_global.html#a24b3622966e9b6643091767292598a5b", null ],
[ "Input", "class_v_global.html#a5d309bb41e63849b880f5d6481879117", null ],
[ "Music", "class_v_global.html#aa8040bee46d63848cc5dd44a5dc9711d", null ],
[ "PostProcess", "class_v_global.html#aafb1930112c7d18f5f7d2ebdc91f3163", null ],
[ "Random", "class_v_global.html#acfb58dec5599d69296f28e94bfcca985", null ],
[ "RenderState", "class_v_global.html#a146cf907c1aa202f57a38a2f0efdc4df", null ],
[ "Sound", "class_v_global.html#a5fa2cc64f368f1e7ac5d88124b269f1b", null ],
[ "TimeScale", "class_v_global.html#ac97288e4f2f83b7eed63e9953c25f05e", null ],
[ "Title", "class_v_global.html#a66f3d86864b912775c1974e83901820f", null ],
[ "ViewportOffset", "class_v_global.html#af1e7fa30b864a179fb9de5f7c1c14a9e", null ],
[ "VSync", "class_v_global.html#ae6e033bb74c9ca7fcda71d1acb41b835", null ],
[ "Width", "class_v_global.html#a31832dc0b125265063d8fb13ff8abecb", null ],
[ "WindowHeight", "class_v_global.html#a93ac2fcffdf11b56a727573e381d030b", null ],
[ "WindowStyle", "class_v_global.html#a904ed525dc62aa6ae1de8c5f6470f7ad", null ],
[ "WindowWidth", "class_v_global.html#a221cc797649981fdf9bfe8a9c9769f08", null ],
[ "WorldBounds", "class_v_global.html#a733798b74b40e4739d8c07eba545ac43", null ]
];
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({widgetLabel:"Zoom",zoomIn:"Acercar",zoomOut:"Alejar"});
|
import React, { Component } from 'react'
import Reflux from 'Reflux'
import mui, { AppBar, Card, FlatButton, TextField, RaisedButton, CircularProgress } from 'material-ui'
import DashboardActions from '../actions/DashboardActions'
import Store from '../stores'
import { History } from 'react-router'
const Login = React.createClass({
mixins: [Reflux.connect(Store), History],
_handleUsername(e) {
this.setState({ username: e.target.value, usernameErrorText: "" })
},
_handlePassword(e) {
this.setState({ password: e.target.value, passwordErrorText: "" })
},
_handleLoginClick() {
this.setState({ isLoading: true })
DashboardActions.login(this.state.username, this.state.password)
},
_handleKeyDown(e) {
if (e.key === 'Enter' && this.state.username && this.state.password) {
this._handleLoginClick()
}
},
_validateUsername(e) {
let errorText = ""
if (!e.target.value) { errorText = "Invalid username" }
this.setState({ usernameErrorText: errorText })
},
_validatePassword(e) {
let errorText = ""
if (!e.target.value) { errorText = "Invalid password" }
this.setState({ passwordErrorText: errorText })
},
componentDidUpdate() {
if (this.state.loggedIn) {
this.history.pushState(null, '/details', null)
}
},
render() {
let view = this.state.isLoading ?
<CircularProgress
id="LoginLoader"
mode="indeterminate" /> :
<div>
<AppBar
title="Medical App"
showMenuIconButton={false} />
<Card className="loginCard">
<br />
<TextField
label="Username"
floatingLabelText="Username"
hintText="Username"
errorText={this.state.usernameErrorText}
onBlur={this._validateUsername}
onChange={this._handleUsername}
onKeyDown={this._handleKeyDown} />
<br />
<TextField
className="passwordField"
label="Password"
floatingLabelText="Password"
hintText="Password"
errorText={this.state.passwordErrorText}
type="password"
onBlur={this._validatePassword}
onChange={this._handlePassword}
onKeyDown={this._handleKeyDown} />
<br />
<RaisedButton
label="Login"
type="submit"
secondary={true}
disabled={!(this.state.username && this.state.password)}
onClick={this._handleLoginClick}
style={{
marginTop: '40px',
marginLeft: '80px'
}} />
</Card>
</div>
return (
<div className="centered">
{view}
{this.props.children}
</div>
)
}
})
export default Login
|
import angular from 'angular';
import appConfig from './app.config';
import explorerCoreModule from './explorer-core.module';
import explorerLayoutModule from './layout/explorer-layout.module';
import explorerTwoDimensionalBrushModule from
'./features/explorer-two-dimensional-brush/explorer-two-dimensional-brush.module';
export default angular
.module('app', [explorerCoreModule, explorerLayoutModule, explorerTwoDimensionalBrushModule])
.config(appConfig)
.name;
|
import { connect } from 'react-redux'
import ForgotPassword from '../components/ForgotPassword'
import { errorHandler } from 'util/common'
import axios from 'axios'
import { forgotRequest, forgotFailure, forgotSuccess } from '../modules/forgotPassword'
import APP_SETTINGS from 'config'
const mapDispatchToProps = (dispatch) => {
return {
handleForgotPassword: (user) => {
dispatch(forgotRequest())
axios.post(`${APP_SETTINGS.API_BASE}/auth/forgot-password`, user)
.then((result) => {
dispatch(forgotSuccess())
}).catch((error) => {
errorHandler(dispatch, error, forgotFailure)
})
}
}
}
const mapStateToProps = (state) => {
return {
loading: state.forgotPassword.loading,
errorMessage: state.forgotPassword.error,
emailSent: state.forgotPassword.emailSent
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ForgotPassword)
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors'),
Database = mongoose.model('Database'),
User = mongoose.model('User'),
_ = require('lodash');
/**
* Create a Database
*/
exports.create = function(req, res) {
var database = new Database(req.body);
database.user = req.user;
database.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(database);
}
});
};
/**
* Show the current Database
*/
exports.read = function(req, res) {
res.jsonp(req.database);
};
/**
* Update a Database
*/
exports.update = function(req, res) {
var database = req.database ;
database = _.extend(database , req.body);
database.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(database);
}
});
};
/**
* Delete an Database
*/
exports.delete = function(req, res) {
var database = req.database ;
database.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(database);
}
});
};
/**
* List of Databases
*/
exports.list = function(req, res) {
Database.find().sort('-created').populate('user', 'displayName').exec(function(err, databases) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
console.log(databases);
res.jsonp(databases);
}
});
};
/**
* Database middleware
*/
exports.databaseByID = function(req, res, next, id) {
Database.findById(id).populate('user', 'displayName').exec(function(err, database) {
if (err) return next(err);
if (! database) return next(new Error('Failed to load Database ' + id));
req.database = database ;
next();
});
};
/**
* Database authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if(req.user.roles.indexOf('admin') === -1) {
if (req.database.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
}
next();
};
|
var domMatch = /^[#\.a-zA-Z]/,
clsMatch = /^\$/;
Fly.def('Fly.Controller', {
singleton: true,
/**
*
*
* .class
* #id
* $className as in Fly.ns(__className__)
* $className[foo=bar]
*
*
*
* control: {
* 'something' : {
* event: 'fn'
* }
* }
*/
control: {},
construct: function () {
// var me = this;
if (this !== Fly.Controller) {
Fly.Registry.addController(this);
}
// F.each(me.control, me.assignListener, me);
}
});
|
'use strict';
var clc = require('cli-color'),
path = require('path'),
fs = require('fs-extra');
var utils = {
path: process.cwd(),
package: require(path.resolve(__dirname, '..', '..', 'package.json')),
banner: function(text) {
if (text && typeof text == 'object' && text.length) {
text = text.join('');
}
text = text ? clc.blueBright(text) : '';
if (clc.width) {
var bannerWidth = 38,
fillCharasNb = Math.floor((clc.width - bannerWidth) / 2),
margin = fillCharasNb > 0 ? new Array(Math.floor((clc.width - bannerWidth) / 2)).join(' ') : '';
var banner = [
'\n',
clc.red(margin + ' ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░') + '\n',
clc.red(margin + ' ░░ ░░') + '\n',
clc.red(margin + ' ░ ░') + '\n',
clc.red(margin + ' ░ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ░') + '\n',
clc.red(margin + ' ░ ░') + '\n',
clc.red(margin + ' ░ ') + clc.redBright('Allons-y!') + clc.red(' ░') + '\n',
clc.red(margin + ' ░ ░') + '\n',
clc.red(margin + ' ░ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ░') + '\n',
clc.red(margin + ' ░ ░') + '\n',
clc.red(margin + ' ░░ ░░') + '\n',
clc.red(margin + ' ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░') + '\n\n',
clc.red(margin + '« Webapps that come from a S.F. movie »') + '\n\n\n',
text
];
console.log([clc.reset].concat(banner).join(''));
}
},
title: function(text) {
console.log('\n');
console.log(clc.blue(new Array(clc.width).join('▀')));
console.log(clc.blueBright(' ' + text));
console.log(clc.blue(new Array(clc.width).join('▄')));
},
info: function(text) {
process.stdout.write(clc.blueBright(text));
},
warning: function(text) {
process.stdout.write(clc.yellowBright('/!\\ ' + text));
},
success: function(text) {
process.stdout.write(clc.greenBright(text));
},
log: function(text) {
process.stdout.write(clc.white(text));
},
getContent: function(source) {
return fs.readFileSync(source, 'utf-8');
},
putContent: function(text, destination) {
fs.writeFileSync(destination, text);
},
copy: function(source, destination) {
fs.copySync(source, destination);
}
};
module.exports = utils;
|
import FlowBuilder from 'ember-cli-flowbuilder/components/flow-builder';
export default FlowBuilder;
|
import {TeamService} from "../../../both/service/TeamService"
import {Utils} from "../../../client/service/Utils"
export class TaskListComponent extends BlazeComponent {
constructor() {
super();
this.taskListAdvancedSearch = new ReactiveVar(false);
this.isAfterFilterOn = new ReactiveVar(false);
this.isBeforeFilterOn = new ReactiveVar(false);
}
template() {
return "taskListComponent";
}
events() {
return [{
"keyup #search_task_name": this.filterName,
"click #advanced-search-button": this.switchAdvanced,
"click #checkbox-after-filter": this.switchAfterFilter,
"click #checkbox-before-filter": this.switchBeforeFilter,
}];
}
/**
* Switch between hiding and showing the advanced search menu
* @param event
*/
switchAdvanced(event) {
this.taskListAdvancedSearch.set(!this.isSearchAdvanced());
}
isSearchAdvanced() {
return this.taskListAdvancedSearch.get();
}
filterTeam(error, docModified, newOption) {
return _.bind(function (error, docModifier, newOption) {
var _id = newOption;
this.taskListTeamFilter.set(_id);
}, this);
}
filterResponsible(error, docModifier, newOption) {
return _.bind(function (error, docModifier, newOption) {
var _id = newOption;
this.taskListResponsibleFilter.set(_id);
}, this);
}
filterValidationStatus(error, docModifier, newOption) {
return _.bind(function (error, docModifier, validationOption) {
var queryTimeSlot = "", queryEquipment = "";
if (validationOption) {
var validationRole = validationOption.split("_")[0];
var validationStatus = validationOption.split("_")[1];
if (validationRole === RolesEnum.EQUIPMENTVALIDATION) {
queryEquipment = validationStatus;
} else if (validationRole === RolesEnum.ASSIGNMENTVALIDATION) {
queryTimeSlot = validationStatus;
} else if (validationRole === "ALL") {
//TODO
queryEquipment = validationStatus;
queryTimeSlot = validationStatus;
}
}
this.taskListTimeSlotValidationStateFilter.set(queryTimeSlot);
this.taskListEquipmentValidationStateFilter.set(queryEquipment);
}, this);
}
optionQueryTeamsWithoutAlreadyAssigned() {
return TeamService.optionQueryTeamsWithoutAlreadyAssigned();
}
optionValidationStatus() {
/*
user with at least one validation role :
for each of its validation role :
<ROLE>_TOBEVALIDATED
<ROLE>_REFUSED
user without any validation role :
ALL_OPEN
ALL_TOBEVALIDATED
ALL_REFUSED
ALL_READY
*/
var result = [];
var validationRoles = [
Meteor.roles.findOne({name: "ASSIGNMENTVALIDATION"}),
Meteor.roles.findOne({name: "EQUIPMENTVALIDATION"})
];
var userValidationRole = [];
validationRoles.forEach(validationRole => {
if (Roles.userIsInRole(Meteor.userId(), validationRole.name))
userValidationRole.push(validationRole.name);
});
if (userValidationRole.length > 0) {
validationRoles.forEach(validationRole => {
result.push({
label: RolesEnumDisplay[validationRole.name] + " " + ValidationStateDisplay.TOBEVALIDATED,
value: validationRole.name + "_" + ValidationState.TOBEVALIDATED
});
result.push({
label: RolesEnumDisplay[validationRole.name] + " " + ValidationStateDisplay.REFUSED,
value: validationRole.name + "_" + ValidationState.REFUSED
});
})
} else {
result.push({
label: ValidationStateDisplay.OPEN,
value: "ALL_" + ValidationState.OPEN
});
result.push({
label: ValidationStateDisplay.TOBEVALIDATED,
value: "ALL_" + ValidationState.TOBEVALIDATED
});
result.push({
label: ValidationStateDisplay.REFUSED,
value: "ALL_" + ValidationState.REFUSED
});
result.push({
label: ValidationStateDisplay.READY,
value: "ALL_" + ValidationState.READY
});
}
return result;
}
filterName(event) {
event.preventDefault();
var _id = $(event.target).val();
this.taskListNameFilter.set(_id);
}
switchAfterFilter(event) {
var _id = $(event.target).prop("checked");
if (_id) {
this.isAfterFilterOn.set(true);
var _date = this.$(".date-after-filter>.datetimepicker").data("DateTimePicker").date(); //get the date
this.changeDateFilter(_date, "after");
} else {
this.deleteDateFilter("after");
this.isAfterFilterOn.set(false);
}
}
isAfterFilterReadOnly() {
return !this.isAfterFilterOn.get();
}
filterAfter(newOption) {
return _.bind(function (newOption) {
var _time = new moment(newOption);
this.changeDateFilter(_time, "after");
}, this);
}
switchBeforeFilter(event) {
var _id = $(event.target).prop("checked");
if (_id) {
this.isBeforeFilterOn.set(true);
var _date = this.$(".date-before-filter>.datetimepicker").data("DateTimePicker").date(); //get the date
this.changeDateFilter(_date, "before");
} else {
this.deleteDateFilter("before");
this.isBeforeFilterOn.set(false);
}
}
isBeforeFilterReadOnly() {
return !this.isBeforeFilterOn.get();
}
filterBefore(newOption) {
return _.bind(function (newOption) {
var _time = new Date(newOption);
this.changeDateFilter(_time, "before");
}, this);
}
changeDateFilter(newDate, beforeOrAfter) {
if (this.taskDateFilter.get()["$elemMatch"]) { //if a filter is already defined
var dateQuery = this.taskDateFilter.get();
if (beforeOrAfter == "before") {
dateQuery["$elemMatch"]["end"] = {"$lte": newDate.toDate()};
} else if (beforeOrAfter == "after") {
dateQuery["$elemMatch"]["start"] = {"$gte": newDate.toDate()};
}
this.taskDateFilter.set(dateQuery);
} else {
if (beforeOrAfter == "before") {
this.taskDateFilter.set({"$elemMatch": {"end": {"$lte": newDate.toDate()}}});
} else if (beforeOrAfter == "after") {
this.taskDateFilter.set({"$elemMatch": {"start": {"$gte": newDate.toDate()}}});
}
}
}
deleteDateFilter(beforeOrAfter) {
var paramToChange, otherParam;
if (beforeOrAfter == "before") {
paramToChange = "end";
otherParam = "start";
} else if (beforeOrAfter == "after") {
paramToChange = "start";
otherParam = "end";
}
if (this.taskDateFilter.get()["$elemMatch"]) { //if a filter is defined
if (this.taskDateFilter.get()["$elemMatch"][otherParam]) { //if the other filter is active
var dateQuery = this.taskDateFilter.get();
delete dateQuery["$elemMatch"][paramToChange]; //just delete the one we don't want
this.taskDateFilter.set(dateQuery);
} else {
this.taskDateFilter.set("");
}
} else {
this.taskDateFilter.set("");
}
}
onCreated() {
this.taskListTeamFilter = new ReactiveTable.Filter("task-list-team-filter", ["teamId"]);
this.taskListResponsibleFilter = new ReactiveTable.Filter("task-list-responsible-filter", ["masterId"]);
this.taskListNameFilter = new ReactiveTable.Filter('search-task-name-filter', ['name']);
this.taskListTimeSlotValidationStateFilter = new ReactiveTable.Filter('task-timeslot-validation-state-filter', ['timeSlotValidation.currentState']);
this.taskListEquipmentValidationStateFilter = new ReactiveTable.Filter('task-equipment-validation-state-filter', ['equipmentValidation.currentState']);
this.taskDateFilter = new ReactiveTable.Filter("task-date-filter", ["timeSlots"]);
}
tasksList() {
var fields = [
{
key: 'name',
label: 'Name',
cellClass: 'col-sm-3',
headerClass: 'col-sm-3',
fnAdjustColumnSizing: true,
fn: _.bind(function (value) {
return Utils.camelize(value);
}, this)
},
// TODO add GROUP
/*{
key: 'groupId',
label: 'Group',
cellClass: 'col-sm-2',
headerClass: 'col-sm-2',
fnAdjustColumnSizing: true,
searchable: false,
fn: function (groupId, Task) {
return Groups.findOne(groupId).name;
}
},*/
{
key: 'teamId',
label: 'Team',
cellClass: 'col-sm-2',
headerClass: 'col-sm-2',
fnAdjustColumnSizing: true,
searchable: false, //TODO doesn't work (try with a teamId)
fn: function (teamId, Task) {
return Teams.findOne(teamId).name;
}
},
{
key: 'timeSlots',
label: 'Time slots count',
cellClass: 'col-sm-1 text-center',
headerClass: 'col-sm-1 text-center',
searchable: false, //TODO doesn't work (try with a teamId)
sortable: false,
fn: function (timeSlots, Task) {
return timeSlots.length;
},
fnAdjustColumnSizing: true
}
];
this.addExtraColumn(fields);
fields.push({
label: 'Actions',
cellClass: 'col-sm-2 text-center',
headerClass: 'col-sm-2 text-center',
sortable: false,
searchable: false, //TODO doesn't work (try with a teamId)
tmpl: Template.taskButtons,
fnAdjustColumnSizing: true
});
return {
collection: Tasks,
rowsPerPage: Tasks.find().fetch().length,
showFilter: false,
showRowCount: true,
fields: fields,
filters: [
'task-list-team-filter',
'task-list-responsible-filter',
'search-task-name-filter',
'task-timeslot-validation-state-filter',
'task-equipment-validation-state-filter',
'task-date-filter'
]
}
}
addExtraColumn(fields) {
if (Roles.userIsInRole(Meteor.userId(), RolesEnum.TASKWRITE))
fields.push({
label: 'Validation',
cellClass: 'col-sm-2 text-center',
headerClass: 'col-sm-2 text-center',
sortable: false,
searchable: false, //TODO doesn't work (try with a teamId)
tmpl: Template.validationStateForTaskList,
fnAdjustColumnSizing: true
});
}
}
TaskListComponent.register("TaskListComponent");
|
function foo() {}
export default foo
|
var app = (function(document) {
'use strict';
var docElem = document.documentElement,
_userAgentInit = function() {
docElem.setAttribute('data-useragent', navigator.userAgent);
},
_foundationInit = function() {
// if we see .js-randomize class, we will randomize items for Orbit slider
$('.js-randomize-items').each(function() {
// get current list
var list = $(this);
// get array of list items in current list
var listArr = list.children();
// sort array of list items in current list randomly
listArr.sort(function() {
// Get a random number between 0 and 10
var temp = parseInt(Math.random() * 10);
// Get 1 or 0, whether temp is odd or even
var isOddOrEven = temp % 2;
// Get +1 or -1, whether temp greater or smaller than 5
var isPosOrNeg = temp > 5 ? 1 : -1;
// Return -1, 0, or +1
return(isOddOrEven*isPosOrNeg);
})
// append list items to list
.appendTo(list);
});
},
_init = function() {
// Init Zurb Foundation framework
_foundationInit();
// User Agent workaround
_userAgentInit();
};
return {
init: _init
};
})(document, $);
(function() {
'use strict';
app.init();
})();
|
import React from 'react';
export default class NameOutput extends React.Component {
render() {
return (
<div>
Hello {this.props.name}!
</div>
);
}
}
|
import React from 'react';
import renderer from 'react-test-renderer';
import AppContainer from './AppContainer';
describe('<AppContainer />', () => {
test('it should match the snapshot', () => {
const component = renderer.create(<AppContainer />).toJSON();
expect(component).toMatchSnapshot();
});
});
|
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.controller('AppCtrl', ['$scope', '$timeout', function($scope, $timeout) {
// Some elements for our list
$scope.items = [{
id: 0
}, {
id: 1
}, {
id: 2
}, {
id: 3
}, {
id: 4
}];
// Edit/delete buttons display controls
$scope.display = {
showReorder: false,
showEdit: false,
showDelete: false
};
// Toggle edit/delete buttons
$scope.toggleControls = function(button) {
$scope.display.showReorder = false;
if ($scope.display.showDelete) {
if ($scope.display.showEdit) {
$scope.display.showDelete = false;
$scope.display.showEdit = false;
if (button == 'delete') {
$timeout(function() {
$scope.display.showDelete = true;
}, 300);
}
} else {
$scope.display.showDelete = false;
if (button == 'edit') {
$timeout(function() {
$scope.display.showEdit = true;
$scope.display.showDelete = true;
}, 300);
}
}
} else {
if (button == 'edit') $scope.display.showEdit = true;
$scope.display.showDelete = true;
}
};
// Edit/Delete an item
$scope.itemControls = function(item) {
if (!$scope.display.showEdit) {
// Delete an item
$scope.deleteItem(item)
} else {
// Edit item
$scope.editItem(item);
}
};
// Add a new item
$scope.addItem = function() {
$scope.items.push({
id: $scope.items[$scope.items.length - 1].id + 1
})
};
// Reorder items
$scope.moveItem = function(item, fromIndex, toIndex) {
$scope.items.splice(fromIndex, 1);
$scope.items.splice(toIndex, 0, item);
};
// Edit an item
$scope.editItem = function(item) {
alert('Edit Item ' + item.id);
};
// Share an item
$scope.shareItem = function(item) {
alert('Share Item ' + item.id);
};
// Delete an item
$scope.deleteItem = function(item) {
$scope.items.splice($scope.items.indexOf(item), 1);
}
}]);
|
var fs = require("fs");
// Synchronously reading filesystems.
//var files = fs.readdirSync('./lib');
// Async read
fs.readdir('./lib', function(err, files){
if(err){
throw err;
}
console.log(files);
})
global.console.log("readling files...");
|
/**
* Stripe Bank Account Model
*
* <%= whatIsThis %>.
*
* Refer to Stripe Documentation https://stripe.com/docs/api#bank_accounts
*/
module.exports = {
autoPK: false,
attributes: {
id: {
type: 'string', //"ba_16q4nxBw8aZ7QiYmwqM3lvdR"
primaryKey: true,
unique: true
},
object: {
type: 'string' //"bank_account"
},
last4: {
type: 'string' //"6789"
},
country: {
type: 'string' //"US"
},
currency: {
type: 'string' //"usd"
},
status: {
type: 'string' //"new"
},
fingerprint: {
type: 'string' //"4bS4RP1zGQ1IeDdc"
},
routing_number: {
type: 'string' //"110000000"
},
bank_name: {
type: 'string' //"STRIPE TEST BANK"
},
account: {
type: 'string' //"acct_15SXCKBw8aZ7QiYm"
},
default_for_currency: {
type: 'boolean' //false
},
metadata: {
type: 'json' // {}
},
customer: {
model: 'Customer'
},
//Added to Model and doesn't exists in Stripe
lastStripeEvent: {
type: 'datetime'
}
}
}
|
"use strict";
//# sourceMappingURL=ReactComponentType.js.map
|
({
mustDeps: [
{block: 'i-ajax-proxy'},
{block: 'i-promise'},
{block: 'i-state'}
]
})
|
exports.create = require('./create');
exports.change = require('./change');
exports.remove = require('./remove');
|
function PrintMessage(msg) {
var span = document.getElementById('elementName');
span.innerHTML = msg;
}
|
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const IpMessagingClient = require('twilio').IpMessagingClient;
const client = new IpMessagingClient(accountSid, authToken);
const service = client.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
service
.channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.messages.create({
body: 'MESSAGE',
})
.then(response => {
console.log(response);
})
.fail(error => {
console.log(error);
});
|
describe("jB.count", function () {
it("should be able to count Objects", function () {
var testOB = {
foo1: 1,
foo2: 2
};
expect(jB.count(testOB)).toEqual(2);
delete testOB.foo1;
expect(jB.count(testOB)).toEqual(1);
testOB.foo3 = 1;
testOB.foo4 = null;
expect(jB.count(testOB)).toEqual(3);
});
it("should be able to count Arrays", function () {
var testArr = [];
expect(jB.count(testArr)).toEqual(0);
testArr.push('fooel1');
expect(jB.count(testArr)).toEqual(1);
});
it("should be able to count Strings", function () {
var testStr = '123';
expect(jB.count(testStr)).toEqual(3);
testStr += '4';
expect(jB.count(testStr)).toEqual(4);
});
});
|
(function(){
var express = require('express');
var path = require('path');
var app = express();
var config = require('./config/server-config')(app);
var router = require('./routes/index')(app);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// error handler - move to routes?
app.use(function (err, req, res, next){
if (err.code !== 'EBADCSRFTOKEN') return next(err);
// handle CSRF token errors
res.render('warning');
})
const server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
})();
|
// import scss from './assets/sass/app.scss'
const sass = require('./assets/sass/app.sass');
const navvar = require('./assets/js/bulma.navvar.js');
const jquery = require("jquery");
const flickity = require('../node_modules/flickity/dist/flickity.pkgd.js');
const main = require('./assets/js/main.js');
console.log("Index Page");
|
Desktop = Backbone.Collection.extend({ /* -- Backbone Collection -- */});
|
var provider = {
safe_color_names: [
'preto', 'marrom', 'verde', 'roxo', 'azul', 'laranja',
'cinza', 'amarelo', 'branco','vermelho', 'violeta'
],
color_names: [
'Azul', 'Azul claro', 'Azul marinho', 'Azul celeste', 'Azul cobalto', 'Azul turquesa',
'Amarelo', 'Amarelo claro', 'Amarelo Mostarda', 'Âmbar', 'Ametista',
'Bege', 'Bordô', 'Branco', 'Branco gelo', 'Bronze', 'Caramelo',
'Carmesin', 'Caqui', 'Coral', 'Castanho', 'Cereja', 'Chocolate',
'Ciano', 'Cinza', 'Cinza claro', 'Cinza escuro', 'Cobre', 'Creme', 'Dourado',
'Esmeralda', 'Ferrugem', 'Grená', 'Índigo', 'Laranja', 'Lilás', 'Madeira',
'Magenta', 'Magenta escuro', 'Marfim', 'Marrom', 'Marrom claro', 'Oliva',
'Oliva escura', 'Prata', 'Púrpura', 'Preto', 'Rosa', 'Rosa choque', 'Roxo',
'Salmão', 'Sépia', 'Turquesa', 'Verde', 'Verde claro', 'Verde escuro', 'Verde limão',
'Vermelho', 'Vermelho escuro', 'Vermelho claro', 'Vermelhor tijolo', 'Violeta'
]
};
module.exports = provider;
|
import styled from "styled-components"
import { FONTS } from "../../../../themes/constants"
export const Container = styled.div`
text-align: right;
`
export const Label = styled.span`
font-size: 9px;
font-family: ${FONTS.sansSerif};
text-transform: uppercase;
margin: 0 0 10px 0;
opacity: 0.45;
`
export const Actions = styled.div``
export const Link = styled.a`
cursor: pointer;
text-decoration: none;
margin: 0 0 0 15px;
`
|
'use strict';
class TickCounter {
constructor(max) {
this.ticks = 0;
this.max = max;
this.countTicks();
}
countTicks() {
setImmediate(() => {
this.ticks += 1;
if (this.max > this.ticks) {
this.countTicks();
}
});
}
}
module.exports = TickCounter;
|
var Commands = require('commands');
var express = require('express');
var app = express();
(require('properties-reader')('src/properties/' + process.env.NODE_ENV + '.properties'))
.bindToExpress(app, __dirname, true);
(require('properties-reader')('src/properties/i18n.properties')).each(function (key, value) {
key = 'i18n-' + key;
app.set(key, app.locals[key] = value);
});
app.use(express.logger({
stream: require('fs').createWriteStream(app.get('access.log.path'), {flags: 'a'}),
buffer: app.get('access.log.buffering'),
format: app.get('access.log.format')
}));
if(process.env.NODE_ENV === 'development') {
app.set('version', 'dev');
app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
app.use('/dev', require('less-middleware')(app.get('static.content.dir')));
app.use('/dev', express.static(app.get('static.content.dir'), {maxAge: app.get('static.content.cache')} ));
}
else {
app.set('version', require('../../package.json').version);
}
app.set('views', require('path').join(__dirname, '../templates'));
app.set('view engine', 'mustache');
app.engine('mustache', require('hogan-middleware').__express);
app.locals.version = app.get('version');
app.locals.i18n = function (key) {
var val = app.get('i18n-' + key);
var args = arguments;
if (/\{.+\}/.test(val)) {
val = val.replace(/\{([^\}]+)\}/, function (_, key) {
return this.hasOwnProperty(key) ? this[key] : '';
}.bind(args.length === 2 && typeof args[1] === "object" ? args[1] : [].slice.call(args, 1)));
}
return val === undefined ? '' : val;
};
app.set('models', require('./models/index')(app.get('properties')));
//app.use('/user', require('./routes/user'));
//
app.get('/', function (req, res) {
res.render('comment');
});
app.all('/comments/:url', function (req, res, next) {
Comment.find({url: req.params.url}).then(function (err, comments) {
res.locals.url = req.params.url;
res.locals.comments = comments;
next();
});
});
app.get('/comments/:url', function (req, res) {
res.render('comments');
});
app.post('/comments/:url', function (req, res) {
var data = req.body;
data.url = req.param.url;
app.get('models').createComment(data).save().then(function (err, comment) {
res.locals.comments.unshift(comment);
res.locals.comment = comment;
res.render('comment-saved');
});
});
app.listen(Commands.get('port', Commands.get('port', app.get('server.port'))));
|
'use strict';
// register photos component along with its controller and template
angular.module('photos').
component('photosComponent', {
templateUrl: 'pictures/photos.template.html',
controller: ['Photos',
function PhotosController(Photos) {
var self = this;
self.photos = [];
Photos.getPhotos(function(results) {
self.photos = results;
console.log(self.photos);
})
self.name = 'PhotosController';
self.service = Photos.name;
self.msg = '';
self.uploadFile = function() {
var file = self.file;
if (!file) {
self.msg = 'please attach file';
return;
}
var check = self.checkExtension(file.name);
console.log('file is ');
console.dir(file);
var uploadUrl = "/upload";
if (check) {
Photos.uploadPhoto(file, uploadUrl, function() {
document.getElementById("file").value = "";
self.file = '';
Photos.getPhotos(function(results) {
self.photos = results;
});
});
} else {
self.msg = "only file extensions jpg, png, gif are excepted";
}
};
self.checkExtension = function(fileName) {
var extension = fileName.split(".").pop().toLowerCase();
if (extension === 'jpg' || extension === 'png' || extension === 'gif') {
return true;
}
return false;
};
}
]
})
|
//import liraries
import React, { Component } from 'react';
import { Image } from 'react-native';
// create a component
export default class TabBarItem extends Component {
render() {
let selectedImage = this.props.selectedImage ? this.props.selectedImage : this.props.normalImage
return (
<Image
source={this.props.focused
? selectedImage
: this.props.normalImage}
style={{ tintColor: this.props.tintColor, width: 25, height: 25 }}
/>
);
}
}
|
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ProfileInfo.css';
import Avatar from 'material-ui/Avatar';
import AvatarImage from './images/ed_sheeran.jpeg';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import IconButton from 'material-ui/IconButton';
import Link from '../Link';
import NewEntry from '../UI/NewEntry';
function ProfileInfo () {
return (
<div className={s.root}>
<div className={s.userArea}>
<Link to="/user_overview">
<Avatar
src={AvatarImage}
className={s.userAvatar}
/>
</Link>
<div className={s.newEntry}>
<NewEntry/>
</div>
</div>
</div>
);
}
export default withStyles(s)(ProfileInfo);
|
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({"./lang/lt":[function(require,module,exports){
module.exports = {
accepted: 'Laukas :attribute turi būti priimtas.',
active_url: 'Laukas :attribute nėra galiojantis internetinis adresas.',
after: 'Lauko :attribute reikšmė turi būti po :date datos.',
after_or_equal: 'The :attribute must be a date after or equal to :date.',
alpha: 'Laukas :attribute gali turėti tik raides.',
alpha_dash: 'Laukas :attribute gali turėti tik raides, skaičius ir brūkšnelius.',
alpha_num: 'Laukas :attribute gali turėti tik raides ir skaičius.',
attributes: {},
array: 'Laukas :attribute turi būti masyvas.',
before: 'Laukas :attribute turi būti data prieš :date.',
before_or_equal: 'The :attribute must be a date before or equal to :date.',
between: {
numeric: 'Lauko :attribute reikšmė turi būti tarp :min ir :max.',
file: 'Failo dydis lauke :attribute turi būti tarp :min ir :max kilobaitų.',
string: 'Simbolių skaičius lauke :attribute turi būti tarp :min ir :max.',
array: 'Elementų skaičius lauke :attribute turi turėti nuo :min iki :max.'
},
boolean: 'Lauko reikšmė :attribute turi būti \'taip\' arba \'ne\'.',
confirmed: 'Lauko :attribute patvirtinimas nesutampa.',
date: 'Lauko :attribute reikšmė nėra galiojanti data.',
date_format: 'Lauko :attribute reikšmė neatitinka formato :format.',
different: 'Laukų :attribute ir :other reikšmės turi skirtis.',
digits: 'Laukas :attribute turi būti sudarytas iš :digits skaitmenų.',
digits_between: 'Laukas :attribute tuti turėti nuo :min iki :max skaitmenų.',
dimensions: 'Lauke :attribute įkeltas paveiksliukas neatitinka išmatavimų reikalavimo.',
distinct: 'Laukas :attribute pasikartoja.',
email: 'Lauko :attribute reikšmė turi būti galiojantis el. pašto adresas.',
file: 'The :attribute must be a file.',
filled: 'Laukas :attribute turi būti užpildytas.',
exists: 'Pasirinkta negaliojanti :attribute reikšmė.',
gt: {
numeric: 'The :attribute must be greater than :value.',
file: 'The :attribute must be greater than :value kilobytes.',
string: 'The :attribute must be greater than :value characters.',
array: 'The :attribute must have more than :value items.'
},
gte: {
numeric: 'The :attribute must be greater than or equal :value.',
file: 'The :attribute must be greater than or equal :value kilobytes.',
string: 'The :attribute must be greater than or equal :value characters.',
array: 'The :attribute must have :value items or more.'
},
image: 'Lauko :attribute reikšmė turi būti paveikslėlis.',
in: 'Pasirinkta negaliojanti :attribute reikšmė.',
in_array: 'Laukas :attribute neegzistuoja :other lauke.',
integer: 'Lauko :attribute reikšmė turi būti sveikasis skaičius.',
ip: 'Lauko :attribute reikšmė turi būti galiojantis IP adresas.',
ipv4: 'The :attribute must be a valid IPv4 address.',
ipv6: 'The :attribute must be a valid IPv6 address.',
json: 'Lauko :attribute reikšmė turi būti JSON tekstas.',
lt: {
numeric: 'The :attribute must be less than :value.',
file: 'The :attribute must be less than :value kilobytes.',
string: 'The :attribute must be less than :value characters.',
array: 'The :attribute must have less than :value items.'
},
lte: {
numeric: 'The :attribute must be less than or equal :value.',
file: 'The :attribute must be less than or equal :value kilobytes.',
string: 'The :attribute must be less than or equal :value characters.',
array: 'The :attribute must not have more than :value items.'
},
max: {
numeric: 'Lauko :attribute reikšmė negali būti didesnė nei :max.',
file: 'Failo dydis lauke :attribute reikšmė negali būti didesnė nei :max kilobaitų.',
string: 'Simbolių kiekis lauke :attribute reikšmė negali būti didesnė nei :max simbolių.',
array: 'Elementų kiekis lauke :attribute negali turėti daugiau nei :max elementų.'
},
mimes: 'Lauko reikšmė :attribute turi būti failas vieno iš sekančių tipų: :values.',
mimetypes: 'Lauko reikšmė :attribute turi būti failas vieno iš sekančių tipų: :values.',
min: {
numeric: 'Lauko :attribute reikšmė turi būti ne mažesnė nei :min.',
file: 'Failo dydis lauke :attribute turi būti ne mažesnis nei :min kilobaitų.',
string: 'Simbolių kiekis lauke :attribute turi būti ne mažiau nei :min.',
array: 'Elementų kiekis lauke :attribute turi būti ne mažiau nei :min.'
},
not_in: 'Pasirinkta negaliojanti reikšmė :attribute.',
not_regex: 'The :attribute format is invalid.',
numeric: 'Lauko :attribute reikšmė turi būti skaičius.',
present: 'Laukas :attribute turi egzistuoti.',
regex: 'Negaliojantis lauko :attribute formatas.',
required: 'Privaloma užpildyti lauką :attribute.',
required_if: 'Privaloma užpildyti lauką :attribute kai :other yra :value.',
required_unless: 'Laukas :attribute yra privalomas, nebent :other yra tarp :values reikšmių.',
required_with: 'Privaloma užpildyti lauką :attribute kai pateikta :values.',
required_with_all: 'Privaloma užpildyti lauką :attribute kai pateikta :values.',
required_without: 'Privaloma užpildyti lauką :attribute kai nepateikta :values.',
required_without_all: 'Privaloma užpildyti lauką :attribute kai nepateikta nei viena iš reikšmių :values.',
same: 'Laukai :attribute ir :other turi sutapti.',
size: {
numeric: 'Lauko :attribute reikšmė turi būti :size.',
file: 'Failo dydis lauke :attribute turi būti :size kilobaitai.',
string: 'Simbolių skaičius lauke :attribute turi būti :size.',
array: 'Elementų kiekis lauke :attribute turi būti :size.'
},
string: 'Laukas :attribute turi būti tekstinis.',
timezone: 'Lauko :attribute reikšmė turi būti galiojanti laiko zona.',
unique: 'Tokia :attribute reikšmė jau pasirinkta.',
uploaded: 'The :attribute failed to upload.',
url: 'Negaliojantis lauko :attribute formatas.'
};
},{}]},{},[]);
|
'use strict';
/* Services */
var socialrServices = angular.module('socialr.services', ['ngResource']);
// Demonstrate how to register services
// In this case it is a simple value service.
socialrServices.value('version', '0.1');
socialrServices.factory('City', ['$resource',
function($resource) {
return $resource('data/:cityId.json', {}, {
query: {method:'GET', params:{cityId:'cities'}, isArray:true}
});
}]);
socialrServices.factory('Restaurant', ['$resource',
function($resource) {
return $resource('data/:restaurantId.json', {}, {
query: {method:'GET', params:{restaurantId:'restaurants'}, isArray:true}
});
}]);
socialrServices.factory('Rating', ['$resource',
function($resource) {
return $resource('data/:ratingId.json', {}, {
query: {method:'GET', params:{ratingId:'ratings'}, isArray:true}
});
}]);
socialrServices.factory('Review', ['$resource',
function($resource) {
return $resource('data/:reviewId.json', {}, {
query: {method:'GET', params:{reviewId:'reviews'}, isArray:false },
})
}]);
// Basic service to store app data.
socialrServices.factory('SocialrData',
function() {
return {
getRandom: function(arry) {
var pick_one = arry[Math.floor(Math.random() * arry.length)];
return pick_one;
}
};
});
|
function solve() {
return function (selector) {
var template = '<table class="items-table">' +
'<thead>' +
'<tr>' +
'<th>#</th>' +
'{{#headers}}' +
'<th>{{this}}</th>' +
'{{/headers}}' +
'</tr>' +
'</thead>' +
'<tbody>' +
'{{#items}}' +
'<tr>' +
'<td>{{@index}}</td>'+
'<td>{{col1}}</td>' +
'<td>{{col2}}</td>' +
'<td>{{col3}}</td>' +
'</tr>' +
'{{/items}}' +
'</tbody>' +
'</table>';
$(selector).html(template);
};
}
|
import React, {
Component,
PropTypes
} from 'react'
import {
AppRegistry,
StyleSheet,
View
} from 'react-native'
import NavigatorComp from './App/Components/Navigator'
AppRegistry.registerComponent('RN_HiApp', () => NavigatorComp)
|
/* */
"format cjs";
"use strict";
exports.__esModule = true;
// istanbul ignore next
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
// istanbul ignore next
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
// istanbul ignore next
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// istanbul ignore next
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _convertSourceMap = require("convert-source-map");
var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap);
var _modules = require("../modules");
var _modules2 = _interopRequireDefault(_modules);
var _optionsOptionManager = require("./options/option-manager");
var _optionsOptionManager2 = _interopRequireDefault(_optionsOptionManager);
var _pluginManager = require("./plugin-manager");
var _pluginManager2 = _interopRequireDefault(_pluginManager);
var _shebangRegex = require("shebang-regex");
var _shebangRegex2 = _interopRequireDefault(_shebangRegex);
var _traversalPath = require("../../traversal/path");
var _traversalPath2 = _interopRequireDefault(_traversalPath);
var _lodashLangIsFunction = require("lodash/lang/isFunction");
var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction);
var _sourceMap = require("source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _generation = require("../../generation");
var _generation2 = _interopRequireDefault(_generation);
var _helpersCodeFrame = require("../../helpers/code-frame");
var _helpersCodeFrame2 = _interopRequireDefault(_helpersCodeFrame);
var _lodashObjectDefaults = require("lodash/object/defaults");
var _lodashObjectDefaults2 = _interopRequireDefault(_lodashObjectDefaults);
var _lodashCollectionIncludes = require("lodash/collection/includes");
var _lodashCollectionIncludes2 = _interopRequireDefault(_lodashCollectionIncludes);
var _traversal = require("../../traversal");
var _traversal2 = _interopRequireDefault(_traversal);
var _tryResolve = require("try-resolve");
var _tryResolve2 = _interopRequireDefault(_tryResolve);
var _logger = require("./logger");
var _logger2 = _interopRequireDefault(_logger);
var _plugin = require("../plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _helpersParse = require("../../helpers/parse");
var _helpersParse2 = _interopRequireDefault(_helpersParse);
var _traversalHub = require("../../traversal/hub");
var _traversalHub2 = _interopRequireDefault(_traversalHub);
var _util = require("../../util");
var util = _interopRequireWildcard(_util);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _types = require("../../types");
/**
* [Please add a description.]
*/
var t = _interopRequireWildcard(_types);
var File = (function () {
function File(opts, pipeline) {
if (opts === undefined) opts = {};
_classCallCheck(this, File);
this.transformerDependencies = {};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.declarations = {};
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.metadata = {
modules: {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
};
this.pipeline = pipeline;
this.log = new _logger2["default"](this, opts.filename || "unknown");
this.opts = this.initOptions(opts);
this.ast = {};
this.buildTransformers();
this.hub = new _traversalHub2["default"](this);
}
/**
* [Please add a description.]
*/
/**
* [Please add a description.]
*/
File.prototype.initOptions = function initOptions(opts) {
opts = new _optionsOptionManager2["default"](this.log, this.pipeline).init(opts);
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = _path2["default"].basename(opts.filename, _path2["default"].extname(opts.filename));
opts.ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
_lodashObjectDefaults2["default"](opts, {
moduleRoot: opts.sourceRoot
});
_lodashObjectDefaults2["default"](opts, {
sourceRoot: opts.moduleRoot
});
_lodashObjectDefaults2["default"](opts, {
filenameRelative: opts.filename
});
_lodashObjectDefaults2["default"](opts, {
sourceFileName: opts.filenameRelative,
sourceMapTarget: opts.filenameRelative
});
//
if (opts.externalHelpers) {
this.set("helpersNamespace", t.identifier("babelHelpers"));
}
return opts;
};
/**
* [Please add a description.]
*/
File.prototype.isLoose = function isLoose(key) {
return _lodashCollectionIncludes2["default"](this.opts.loose, key);
};
/**
* [Please add a description.]
*/
File.prototype.buildTransformers = function buildTransformers() {
var file = this;
var transformers = this.transformers = {};
var secondaryStack = [];
var stack = [];
// build internal transformers
for (var key in this.pipeline.transformers) {
var transformer = this.pipeline.transformers[key];
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canTransform()) {
stack.push(pass);
if (transformer.metadata.secondPass) {
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
}
// init plugins!
var beforePlugins = [];
var afterPlugins = [];
var pluginManager = new _pluginManager2["default"]({
file: this,
transformers: this.transformers,
before: beforePlugins,
after: afterPlugins
});
for (var i = 0; i < file.opts.plugins.length; i++) {
pluginManager.add(file.opts.plugins[i]);
}
stack = beforePlugins.concat(stack, afterPlugins);
// build transformer stack
this.uncollapsedTransformerStack = stack = stack.concat(secondaryStack);
// build dependency graph
var _arr = stack;
// collapse stack categories
for (var _i = 0; _i < _arr.length; _i++) {
var pass = _arr[_i];var _arr2 = pass.plugin.dependencies;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var dep = _arr2[_i2];
this.transformerDependencies[dep] = pass.key;
}
}this.transformerStack = this.collapseStack(stack);
};
/**
* [Please add a description.]
*/
File.prototype.collapseStack = function collapseStack(_stack) {
var stack = [];
var ignore = [];
var _arr3 = _stack;
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var pass = _arr3[_i3];
// been merged
if (ignore.indexOf(pass) >= 0) continue;
var group = pass.plugin.metadata.group;
// can't merge
if (!pass.canTransform() || !group) {
stack.push(pass);
continue;
}
var mergeStack = [];
var _arr4 = _stack;
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var _pass = _arr4[_i4];
if (_pass.plugin.metadata.group === group) {
mergeStack.push(_pass);
ignore.push(_pass);
}
}
var visitors = [];
var _arr5 = mergeStack;
for (var _i5 = 0; _i5 < _arr5.length; _i5++) {
var _pass2 = _arr5[_i5];
visitors.push(_pass2.plugin.visitor);
}
var visitor = _traversal2["default"].visitors.merge(visitors);
var mergePlugin = new _plugin2["default"](group, { visitor: visitor });
stack.push(mergePlugin.buildPass(this));
}
return stack;
};
/**
* [Please add a description.]
*/
File.prototype.set = function set(key, val) {
return this.data[key] = val;
};
/**
* [Please add a description.]
*/
File.prototype.setDynamic = function setDynamic(key, fn) {
this.dynamicData[key] = fn;
};
/**
* [Please add a description.]
*/
File.prototype.get = function get(key) {
var data = this.data[key];
if (data) {
return data;
} else {
var dynamic = this.dynamicData[key];
if (dynamic) {
return this.set(key, dynamic());
}
}
};
/**
* [Please add a description.]
*/
File.prototype.resolveModuleSource = function resolveModuleSource(source) {
var resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
};
/**
* [Please add a description.]
*/
File.prototype.addImport = function addImport(source, name, type) {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
source = this.resolveModuleSource(source);
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);
var specifiers = [t.importDefaultSpecifier(id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
if (type) {
var modules = this.dynamicImportTypes[type] = this.dynamicImportTypes[type] || [];
modules.push(declar);
}
if (this.transformers["es6.modules"].canTransform()) {
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports, this.scope);
this.moduleFormatter.hasLocalImports = true;
} else {
this.dynamicImports.push(declar);
}
}
return id;
};
/**
* [Please add a description.]
*/
File.prototype.attachAuxiliaryComment = function attachAuxiliaryComment(node) {
var beforeComment = this.opts.auxiliaryCommentBefore;
if (beforeComment) {
node.leadingComments = node.leadingComments || [];
node.leadingComments.push({
type: "CommentLine",
value: " " + beforeComment
});
}
var afterComment = this.opts.auxiliaryCommentAfter;
if (afterComment) {
node.trailingComments = node.trailingComments || [];
node.trailingComments.push({
type: "CommentLine",
value: " " + afterComment
});
}
return node;
};
/**
* [Please add a description.]
*/
File.prototype.addHelper = function addHelper(name) {
var isSolo = _lodashCollectionIncludes2["default"](File.soloHelpers, name);
if (!isSolo && !_lodashCollectionIncludes2["default"](File.helpers, name)) {
throw new ReferenceError("Unknown helper " + name);
}
var declar = this.declarations[name];
if (declar) return declar;
this.usedHelpers[name] = true;
if (!isSolo) {
var generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) {
return generator(name);
} else if (runtime) {
var id = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, id);
}
}
var ref = util.template("helper-" + name);
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.attachAuxiliaryComment(ref);
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
this.scope.push({
id: uid,
init: ref,
unique: true
});
}
return uid;
};
File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) {
// Generate a unique name based on the string literals so we dedupe
// identical strings used in the program.
var stringIds = raw.elements.map(function (string) {
return string.value;
});
var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(",");
var declar = this.declarations[name];
if (declar) return declar;
var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
var helperId = this.addHelper(helperName);
var init = t.callExpression(helperId, [strings, raw]);
init._compact = true;
this.scope.push({
id: uid,
init: init,
_blockHoist: 1.9 // This ensures that we don't fail if not using function expression helpers
});
return uid;
};
/**
* [Please add a description.]
*/
File.prototype.errorWithNode = function errorWithNode(node, msg) {
var Error = arguments.length <= 2 || arguments[2] === undefined ? SyntaxError : arguments[2];
var err;
if (node && node.loc) {
var loc = node.loc.start;
err = new Error("Line " + loc.line + ": " + msg);
err.loc = loc;
} else {
// todo: find errors with nodes inside to at least point to something
err = new Error("There's been an error on a dynamic node. This is almost certainly an internal error. Please report it.");
}
return err;
};
/**
* [Please add a description.]
*/
File.prototype.mergeSourceMap = function mergeSourceMap(map) {
var opts = this.opts;
var inputMap = opts.inputSourceMap;
if (inputMap) {
map.sources[0] = inputMap.file;
var inputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(inputMap);
var outputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(map);
var outputMapGenerator = _sourceMap2["default"].SourceMapGenerator.fromSourceMap(outputMapConsumer);
outputMapGenerator.applySourceMap(inputMapConsumer);
var mergedMap = outputMapGenerator.toJSON();
mergedMap.sources = inputMap.sources;
mergedMap.file = inputMap.file;
return mergedMap;
}
return map;
};
/**
* [Please add a description.]
*/
File.prototype.getModuleFormatter = function getModuleFormatter(type) {
if (_lodashLangIsFunction2["default"](type) || !_modules2["default"][type]) {
this.log.deprecate("Custom module formatters are deprecated and will be removed in the next major. Please use Babel plugins instead.");
}
var ModuleFormatter = _lodashLangIsFunction2["default"](type) ? type : _modules2["default"][type];
if (!ModuleFormatter) {
var loc = _tryResolve2["default"].relative(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type));
}
return new ModuleFormatter(this);
};
/**
* [Please add a description.]
*/
File.prototype.parse = function parse(code) {
var opts = this.opts;
//
var parseOpts = {
highlightCode: opts.highlightCode,
nonStandard: opts.nonStandard,
sourceType: opts.sourceType,
filename: opts.filename,
plugins: {}
};
var features = parseOpts.features = {};
for (var key in this.transformers) {
var transformer = this.transformers[key];
features[key] = transformer.canTransform();
}
parseOpts.looseModules = this.isLoose("es6.modules");
parseOpts.strictMode = features.strict;
this.log.debug("Parse start");
var ast = _helpersParse2["default"](code, parseOpts);
this.log.debug("Parse stop");
return ast;
};
/**
* [Please add a description.]
*/
File.prototype._addAst = function _addAst(ast) {
this.path = _traversalPath2["default"].get({
hub: this.hub,
parentPath: null,
parent: ast,
container: ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
this.ast = ast;
};
/**
* [Please add a description.]
*/
File.prototype.addAst = function addAst(ast) {
this.log.debug("Start set AST");
this._addAst(ast);
this.log.debug("End set AST");
this.log.debug("Start module formatter init");
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
modFormatter.init();
}
this.log.debug("End module formatter init");
};
/**
* [Please add a description.]
*/
File.prototype.transform = function transform() {
this.call("pre");
var _arr6 = this.transformerStack;
for (var _i6 = 0; _i6 < _arr6.length; _i6++) {
var pass = _arr6[_i6];
pass.transform();
}
this.call("post");
return this.generate();
};
/**
* [Please add a description.]
*/
File.prototype.wrap = function wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return this.makeResult({ code: code, ignored: true });
} else {
return callback();
}
} catch (err) {
if (err._babel) {
throw err;
} else {
err._babel = true;
}
var message = err.message = this.opts.filename + ": " + err.message;
var loc = err.loc;
if (loc) {
err.codeFrame = _helpersCodeFrame2["default"](code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
try {
err.stack = newStack;
} catch (e) {
// `err.stack` may be a readonly property in some environments
}
}
throw err;
}
};
/**
* [Please add a description.]
*/
File.prototype.addCode = function addCode(code) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
};
/**
* [Please add a description.]
*/
File.prototype.parseCode = function parseCode() {
this.parseShebang();
var ast = this.parse(this.code);
this.addAst(ast);
};
/**
* [Please add a description.]
*/
File.prototype.shouldIgnore = function shouldIgnore() {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
};
/**
* [Please add a description.]
*/
File.prototype.call = function call(key) {
var _arr7 = this.uncollapsedTransformerStack;
for (var _i7 = 0; _i7 < _arr7.length; _i7++) {
var pass = _arr7[_i7];
var fn = pass.plugin[key];
if (fn) fn(this);
}
};
/**
* [Please add a description.]
*/
File.prototype.parseInputSourceMap = function parseInputSourceMap(code) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = _convertSourceMap2["default"].fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = _convertSourceMap2["default"].removeComments(code);
}
}
return code;
};
/**
* [Please add a description.]
*/
File.prototype.parseShebang = function parseShebang() {
var shebangMatch = _shebangRegex2["default"].exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(_shebangRegex2["default"], "");
}
};
/**
* [Please add a description.]
*/
File.prototype.makeResult = function makeResult(_ref) {
var code = _ref.code;
var _ref$map = _ref.map;
var map = _ref$map === undefined ? null : _ref$map;
var ast = _ref.ast;
var ignored = _ref.ignored;
var result = {
metadata: null,
ignored: !!ignored,
code: null,
ast: null,
map: map
};
if (this.opts.code) {
result.code = code;
}
if (this.opts.ast) {
result.ast = ast;
}
if (this.opts.metadata) {
result.metadata = this.metadata;
result.metadata.usedHelpers = Object.keys(this.usedHelpers);
}
return result;
};
/**
* [Please add a description.]
*/
File.prototype.generate = function generate() {
var opts = this.opts;
var ast = this.ast;
var result = { ast: ast };
if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start");
var _result = _generation2["default"](ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
if (this.shebang) {
// add back shebang
result.code = this.shebang + "\n" + result.code;
}
if (result.map) {
result.map = this.mergeSourceMap(result.map);
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
result.code += "\n" + _convertSourceMap2["default"].fromObject(result.map).toComment();
}
if (opts.sourceMaps === "inline") {
result.map = null;
}
return this.makeResult(result);
};
_createClass(File, null, [{
key: "helpers",
value: ["inherits", "defaults", "create-class", "create-decorated-class", "create-decorated-object", "define-decorated-property-descriptor", "tagged-template-literal", "tagged-template-literal-loose", "to-array", "to-consumable-array", "sliced-to-array", "sliced-to-array-loose", "object-without-properties", "has-own", "slice", "bind", "define-property", "async-to-generator", "interop-require-wildcard", "interop-require-default", "typeof", "extends", "get", "set", "class-call-check", "object-destructuring-empty", "temporal-undefined", "temporal-assert-defined", "self-global", "default-props", "instanceof",
// legacy
"interop-require"],
/**
* [Please add a description.]
*/
enumerable: true
}, {
key: "soloHelpers",
value: [],
enumerable: true
}]);
return File;
})();
exports["default"] = File;
module.exports = exports["default"];
|
var Helper = require("@kaoscript/runtime").Helper;
module.exports = function() {
class Foobar {
constructor() {
this.__ks_init();
this.__ks_cons(arguments);
}
__ks_init() {
}
__ks_cons(args) {
if(args.length !== 0) {
throw new SyntaxError("Wrong number of arguments");
}
}
__ks_func_foo_0(x, ...items) {
if(arguments.length < 1) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)");
}
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
let y = 42;
return Helper.concatString("[", x, ", ", items, ", ", y, "]");
}
foo() {
return Foobar.prototype.__ks_func_foo_0.apply(this, arguments);
}
}
const x = new Foobar();
console.log(x.foo(1));
console.log(x.foo(1, 2));
console.log(x.foo(1, 2, 3, 4));
};
|
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
module.exports = () => new CaseSensitivePathsPlugin();
|
// @flow
/**
* Copyright (c) 2017, Dirk-Jan Rutten
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { graphql, GraphQLObjectType, GraphQLSchema } from 'graphql'
import { GraphQLDateTime } from '../dist'
/**
* Example of the GraphQLDateTime scalar.
*/
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
now: {
type: GraphQLDateTime,
// Resolve can take a javascript Date.
resolve: (): Date => new Date()
},
instant: {
type: GraphQLDateTime,
// Resolve can take a date-time string.
resolve: (): string => '2017-01-27T21:46:33.6756Z'
},
timezone: {
type: GraphQLDateTime,
// Resolve takes a date-time string with a timezone and shifts it to UTC.
resolve: (): string => '2017-01-07T00:00:00.1+01:20'
},
unix: {
type: GraphQLDateTime,
// Resolve can take a timestamp.
resolve: (): number => 344555632.543
},
input: {
type: GraphQLDateTime,
args: {
dateTime: {
type: GraphQLDateTime
}
},
// When passed as argument the date-time string is parsed to a javascript Date.
resolve: (_, input: { dateTime: Date }): Date => input.dateTime
}
}
})
})
const query = `
query DateTimeTest($dateTime: DateTime) {
now
unix
instant
timezone
input(dateTime: $dateTime)
}
`
const variables = { dateTime: '2010-01-11T11:34:21Z' }
graphql(schema, query, null, null, variables).then(data => {
console.log('\n\nDateTime Scalar Example:\n')
console.log(JSON.stringify(data, null, 2))
})
|
// Generated by CoffeeScript 1.10.0
(function() {
var XMLProcessingInstruction, create;
create = require('lodash/create');
module.exports = XMLProcessingInstruction = (function() {
function XMLProcessingInstruction(parent, target, value) {
this.options = parent.options;
this.stringify = parent.stringify;
if (target == null) {
throw new Error("Missing instruction target");
}
this.target = this.stringify.insTarget(target);
if (value) {
this.value = this.stringify.insValue(value);
}
}
XMLProcessingInstruction.prototype.clone = function() {
return create(XMLProcessingInstruction.prototype, this);
};
XMLProcessingInstruction.prototype.toString = function(options) {
return this.options.writer.set(options).processingInstruction(this);
};
return XMLProcessingInstruction;
})();
}).call(this);
|
// создаем примесь
Ergo.alias('includes:expand-path', {
expandPath: function(path, effects) {
var path_a = path.split(':');
if(path_a.length > 1) {
var found = null;
var item_name = path_a.shift();
this.items.each(function(item) {
if(item.prop('name') == item_name)
found = item;
});
if(found) {
if(effects === false) found.$sub._no_effects = true;
found.set('expanded');
found.$sub.expandPath(path_a.join(':'));
if(effects === false) delete found.$sub._no_effects;
}
}
}
});
var w = $.ergo({
etype: 'tree',
data: tree_data,
include: 'expand-path',
nestedItem: {
$content: {
etype: 'link',
onClick: function() {
this.parent.toggle('expanded');
},
format: '#{text}'
},
binding: function(v) {
this.prop('name', v.text);
},
$sub: {
include: 'expand-path'
}
}
});
w.render('#sample');
w.expandPath('Азия:Китай', false);
w.expandPath('Европа:Германия:Мюнхен', false);
|
/* global describe, it, afterEach, after */
'use strict'
const chokidarEvEmitter = require('../server')
const fs = require('fs')
const chai = require('chai')
const expect = chai.expect
describe('chokidar-socket-emitter', function () {
let chokidarServer
this.timeout(3000)
it('should fire a change event when file changes', function (done) {
chokidarServer = chokidarEvEmitter({port: 7090, path: './test/test-folder', relativeTo: './test'})
var socket = require('socket.io-client')('http://localhost:7090')
socket.on('change', function (data) {
expect(data.path).to.equal('test-folder/labrat.txt')
expect(data.absolutePath).to.contain('test-folder/labrat.txt')
done()
})
setTimeout(() => {
fs.writeFile('./test/test-folder/labrat.txt', 'test1', (error) => {
expect(error).to.equal(null)
})
}, 300)
})
it('shoud respect baseURL in package.json if no path/relativeTo option is specified', function (done) {
chokidarServer = chokidarEvEmitter({port: 7091})
var socket = require('socket.io-client')('http://localhost:7091')
socket.on('change', function (data) {
expect(data.path).to.equal('labrat.txt')
done()
})
setTimeout(() => {
fs.writeFile('./test/nested-baseURL/labrat.txt', 'test2', (error) => {
expect(error).to.equal(null)
})
}, 300)
})
it('should expose watcher for manual event subscription', function (done) {
chokidarServer = chokidarEvEmitter({port: 7090}, done)
})
it('should respond with package.json when client emits "package.json"', function (done) {
chokidarServer = chokidarEvEmitter({port: 7090, path: './test/test-folder', relativeTo: './test'})
var socket = require('socket.io-client')('http://localhost:7090')
socket.emit('package.json', function (data) {
expect(data.name).to.equal('chokidar-socket-emitter')
done()
})
})
afterEach(function (done) {
setTimeout(() => {
chokidarServer.close(done)
}, 100)
})
after(() => {
fs.writeFileSync('./test/test-folder/labrat.txt', '')
fs.writeFileSync('./test/nested-baseURL/labrat.txt', '')
})
})
|
import { storageAvailable } from './helpers';
// DOM
const welcomeDOM = document.getElementById('js-welcome-modal');
const welcomeButtonDOM = document.getElementById('js-welcome-dismiss');
export default function () {
// Only display the welcome modal if localStorage is available,
// so that we can easily keep track of it.
if (
storageAvailable('localStorage')
&& !localStorage.getItem('launchbot__welcome')
) {
welcomeDOM.style.display = 'block';
}
// Handler: Dismiss welcome modal
//
// Set flag in localStorage, so that it doesn’t get displayed again.
welcomeButtonDOM.addEventListener('click', () => {
welcomeDOM.style.display = 'none';
localStorage.setItem('launchbot__welcome', false);
});
}
|
/**
* Module dependencies.
*/
var express = require('express')
, mongoStore = require('connect-mongo')(express)
, flash = require('connect-flash')
module.exports = function (app, config) {
app.set('showStackError', true)
// should be placed before express.static
app.use(express.compress({
filter: function (req, res) {
return /json|text|javascript|css/.test(res.getHeader('Content-Type'));
},
level: 9
}))
app.use(express.favicon())
app.use(express.static(config.root + '/public'))
// don't use logger for test env
if (process.env.NODE_ENV !== 'test') {
app.use(express.logger('dev'))
}
// set views path, template engine and default layout
app.set('views', config.root + '/app/views')
app.set('view engine', 'jade')
app.configure(function () {
// cookieParser should be above session
app.use(express.cookieParser())
// bodyParser should be above methodOverride
app.use(express.bodyParser({
keepExtensions: true,
uploadDir: './data'}))
app.use(express.methodOverride())
// express/mongo session storage
app.use(express.session({
secret: 'mysmartstreet',
store: new mongoStore({
url: config.db,
collection : 'sessions'
})
}))
// connect flash for flash messages
app.use(flash())
// routes should be at the last
app.use(app.router)
// assume "not found" in the error msgs
// is a 404. this is somewhat silly, but
// valid, you can do whatever you like, set
// properties, use instanceof etc.
app.use(function(err, req, res, next){
// treat as 404
if (~err.message.indexOf('not found')) return next()
// log it
console.error(err.stack)
// error page
res.status(500).render('500', { error: err.stack })
})
// assume 404 since no middleware responded
app.use(function(req, res, next){
res.status(404).render('404', { url: req.originalUrl, error: 'Not found' })
})
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.