text
stringlengths 2
6.14k
|
|---|
version https://git-lfs.github.com/spec/v1
oid sha256:2be307387611bb321bf57f38be0d4f981704cb3b07deb7e8ee71928624c6ec00
size 42186
|
'use strict';
global.expect = require('chai').expect;
global.clientOptions = {
'transports': ['websocket'],
'forceNew': true
};
|
/* jshint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
module.exports = {
name: 'ember-cli-f7',
included: function(app) {
this._super.included(app);
app.import('vendor/css/ember-cli-f7.css');
var bowerDirectory = app.bowerDirectory;
var imagesPath = bowerDirectory + '/framework7/dist/img';
var imgFiles = fs.readdirSync(path.join(imagesPath));
var config = app.project.config(process.env.EMBER_ENV || 'development')['framework7'];
if (!config) {
config = {
theme: 'ios'
};
}
if (!config.theme) {
config.theme = 'ios';
}
app.import({
development: bowerDirectory + '/framework7/dist/css/framework7.' + config.theme + '.css',
production: bowerDirectory + '/framework7/dist/css/framework7.' + config.theme + '.min.css'
});
app.import({
development: bowerDirectory + '/framework7/dist/css/framework7.' + config.theme + '.colors.css',
production: bowerDirectory + '/framework7/dist/css/framework7.' + config.theme + '.colors.min.css'
});
app.import({
development: bowerDirectory + '/framework7/dist/js/framework7.js',
production: bowerDirectory + '/framework7/dist/js/framework7.min.js',
});
app.import({
development: bowerDirectory + '/framework7/dist/js/framework7.js.map',
production: bowerDirectory + '/framework7/dist/js/framework7.min.js.map',
destDir: 'assets'
});
imgFiles.forEach(function(file) {
app.import(path.join(imagesPath, file), {
destDir: '/img'
});
});
},
isDevelopingAddon: function() {
return true;
}
};
|
'use strict';
var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var mkdirp = require('mkdirp');
var path = require('path');
function makeProjectName (name) {
name = _.kebabCase(name);
return name;
}
module.exports = Generator.extend({
constructor: function () {
Generator.apply(this, arguments)
this.option('test', {
type: Boolean,
desc: 'test',
defaults: false
})
this.storedConfig = this.config.getAll()
},
initializing: function () {
// this.log('initializing');
this.props = {};
},
prompting: function () {
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the superior ' + chalk.red('generator-nodejs-bin') + ' generator!'
));
var prompts = [
{
type: String,
name: 'name',
message: 'your project name',
default: makeProjectName(path.basename(process.cwd())),
filter: makeProjectName
},
{
type: 'input',
name: 'username',
message: 'What\'s your Github username',
store: true,
default: this.storedConfig.username
}
];
return this.prompt(prompts).then(function (props) {
// To access props later use this.props.someAnswer;
this.props = props;
}.bind(this));
},
configuring: function () {
// this.log('configuring');
this.config.save();
},
default() {
if (path.basename(this.destinationPath()) !== this.props.name) {
this.log(
'Your project must be inside a folder named ' + this.props.name + '\n' +
'I\'ll automatically create this folder.'
);
mkdirp(this.props.name);
this.destinationRoot(this.destinationPath(this.props.name));
}
},
writing: function () {
this._copy('bin', 'bin');
this._copy('src', 'src');
this._copy('test', 'test');
this._copy('.gitignore', '.gitignore');
this._copy('.npmignore', '.npmignore');
this._copy('README.md', 'README.md');
this._copyTpl('_package.json', 'package.json');
},
_copy: function (from, to) {
this.fs.copy(this.templatePath(from), this.destinationPath(to))
},
_copyTpl: function (from, to) {
this.fs.copyTpl(this.templatePath(from), this.destinationPath(to), this)
},
install: function () {
this.installDependencies({bower: false});
},
conflicts: function () {
// this.log('conflicts');
},
end: function () {
// this.log('end');
}
});
|
'use strict';
describe('Main', function () {
var Formatter = require('../../../src/scripts/formatter.js');
it('should parse some json', function () {
var obj = Formatter.parse('{"name":"John"}');
expect(obj).toEqual({name: "John"});
});
it('should parse some javascript object', function () {
var obj = Formatter.parse('{name:"John"}');
expect(obj).toEqual({name: "John"});
});
it('should stringify some object', function () {
var str = Formatter.stringify({name: "John"});
expect(str).toEqual('{\n "name": "John"\n}');
});
it('should stringify some object with an array', function () {
var str = Formatter.stringify({name: "John", numbers: [1, 3, 5]});
expect(str).toEqual('{\n "name": "John",\n "numbers": [1, 3, 5]\n}');
});
it('should stringify some object with an array', function () {
var str = Formatter.stringify({name: "John", numbers: [1, 3, 5]});
expect(str).toEqual('{\n "name": "John",\n "numbers": [1, 3, 5]\n}');
});
it('should recursively stringify some object', function () {
var str = Formatter.stringify({name: "John", numbers: [1, 3, 5], obj: {key: "value"}});
expect(str).toEqual([
'{',
' "name": "John",',
' "numbers": [1, 3, 5],',
' "obj": {',
' "key": "value"',
' }',
'}'].join("\n"));
});
it('should recursively stringify some object with options', function () {
var str = Formatter.stringify(
{
name: "John",
numbers: [1, 3, 5],
obj: {
key: "value"
}
}, {
spacesPerTab: 2,
quote: "'",
quoteAroundKeys : false
}
);
expect(str).toEqual([
'{',
' name: \'John\',',
' numbers: [1, 3, 5],',
' obj: {',
' key: \'value\'',
' }',
'}'].join("\n"));
});
// todo: escape quotes
// todo: support keys with dashes
});
|
/* eslint react/no-multi-comp: 0 */
/* eslint react/display-name: 0 */
import React, {PropTypes} from 'react';
import BbCodeParser from 'services/bbCodes/BbCodeParser';
import BaseSpan from 'Atoms/BbCode_BaseSpan';
import Code from 'Atoms/BbCode_Code';
import Color from 'Atoms/BbCode_Color';
import Email from 'Atoms/BbCode_Email';
import Image from 'Atoms/BbCode_Image';
import Link from 'Atoms/BbCode_Link';
import ListItem from 'Atoms/BbCode_ListItem';
import NewLine from 'Atoms/BbCode_NewLine';
import OffTopic from 'Atoms/BbCode_OffTopic';
import OrderedList from 'Atoms/BbCode_OrderedList';
import Paragraph from 'Atoms/BbCode_Paragraph';
import Quote from 'Atoms/BbCode_Quote';
import Root from 'Atoms/BbCode_Root';
import TextLine from 'Atoms/BbCode_TextLine';
import Think from 'Atoms/BbCode_Think';
import UnorderedList from 'Atoms/BbCode_UnorderedList';
import StringHelper from 'services/helpers/StringHelper';
import styles from './index.scss';
const bbCodesMap = {
'b': (children) =>
<BaseSpan key={Math.random()} className={styles.bold}>{children}</BaseSpan>,
'i': (children) =>
<BaseSpan key={Math.random()} className={styles.italic}>{children}</BaseSpan>,
'u': (children) =>
<BaseSpan key={Math.random()} className={styles.underline}>{children}</BaseSpan>,
's': (children) =>
<BaseSpan key={Math.random()} className={styles.lineThrough}>{children}</BaseSpan>,
'offtopic': (children) =>
<OffTopic key={Math.random()}>{children}</OffTopic>,
'think': (children) =>
<Think key={Math.random()}>{children}</Think>,
'color': (children, options) =>
<Color key={Math.random()} options={options}>{children}</Color>,
'center': (children) =>
<BaseSpan key={Math.random()} className={`${styles.position} ${styles.center}`}>{children}</BaseSpan>,
'left': (children) =>
<BaseSpan key={Math.random()} className={`${styles.position} ${styles.left}`}>{children}</BaseSpan>,
'right': (children) =>
<BaseSpan key={Math.random()} className={`${styles.position} ${styles.right}`}>{children}</BaseSpan>,
'size': (children, options) =>{
let fontSizeByDefault = 16;
if(options <= 150 && options > 0){
return (
<BaseSpan key={Math.random()} className='' styleObject={{fontSize: `${options/fontSizeByDefault}rem`}}>
{children}
</BaseSpan>
);
} else {
return (
<BaseSpan key={Math.random()} className='' styleObject={{fontSize: '1rem'}}>
{children}
</BaseSpan>
);
}
},
'code': (children, options) =>{
let key = Math.random();
return <Code key={key} id={key} options={options}>{children}</Code>;
},
//spoiler
'quote': (children, options) =>
<Quote key={Math.random()} options={options}>{children}</Quote>,
'email': (children) =>{
let result= [];
let addBreak = children.length > 1;
for(let child of children)
{
if (typeof(child.props['children']) === 'string' && StringHelper.stringIsEmail(child.props['children'])){
let email = child.props['children'];
result.push(<Email key={Math.random()} email={email} addBreak={addBreak}>{email}</Email>);
} else {
continue;
}
}
return result;
},
'url': (children, options) =>{
let result= [];
if(typeof(options) === 'string' && StringHelper.stringIsLink(options)){
let url = options;
result.push(<Link key={Math.random()} url={url}>{children}</Link>);
}
else{
let addBreak = children.length > 1;
for(let child of children)
{
if (typeof(child.props['children']) === 'string' && StringHelper.stringIsLink(child.props['children'])){
let url = child.props['children'];
result.push(<Link key={Math.random()} url={url} addBreak={addBreak}>{url}</Link>);
} else {
continue;
}
}
}
return result;
},
'img': (children) =>{
let result= [];
let addBreak = children.length > 1;
for(let child of children)
{
if (typeof(child.props['children']) === 'string' && StringHelper.stringIsLink(child.props['children'])){
let url = child.props['children'];
result.push(<Image key={Math.random()} url={url} addBreak={addBreak}/>);
} else {
continue;
}
}
return result;
},
'ol': (children) =>
<OrderedList key={Math.random()}>{children}</OrderedList>,
'ul': (children) =>
<UnorderedList key={Math.random()}>{children}</UnorderedList>,
'li': (children) =>
<ListItem key={Math.random()}>{children}</ListItem>,
//media
'p': (children) =>
<Paragraph key={Math.random()}>{children}</Paragraph>,
'br': () =>
<NewLine key={Math.random()}/>,
'textline': (children) =>
<TextLine key={Math.random()}>{children}</TextLine>,
'root': (children) =>
<Root key={Math.random()}>{children}</Root>
};
const bbCodesMapNames = Object.getOwnPropertyNames(bbCodesMap);
class BbCodePresenter extends React.Component {
static propTypes = {
text: PropTypes.string.isRequired
};
state = {
parsedTree: BbCodeParser.getParsedTree(this.props.text)
}
getComponentByTagName = (tagName) => {
return bbCodesMap[tagName.toLowerCase()];
}
mapTreeToComponent = () => {
let parsedTree = this.state.parsedTree;
let mappedTree;
if(parsedTree.type === 'root' && parsedTree.children.length > 0){
mappedTree = this.mapNodeToComponent(parsedTree);
}
return mappedTree;
}
mapNodeToComponent = (node) => {
let Component = this.getComponentByTagName(node.type);
let result;
if(Component){
if(node.children.length > 0) {
let children = [];
for(let child of node.children){
children.push(this.mapNodeToComponent(child));
}
result = Component(children, node.options);
}
else {
result = Component(node.content, node.options);
}
}
return result;
}
render(){
return this.mapTreeToComponent();
}
}
export default BbCodePresenter;
export {bbCodesMapNames};
|
var fast = require('../lib');
var input = [1,2,3,4,5,6,7,8,9,10];
exports['Array::indexOf()'] = function () {
return input.indexOf(9);
};
exports['fast.indexOf()'] = function () {
return fast.indexOf(input, 9);
};
|
'use strict';
module.exports = (Sequelize, sequelize) => {
return sequelize.define('jacked_car', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
JC_JACKDATE:{
type:Sequelize.DATEONLY,
},
JC_REPORT_DATE:{
type:Sequelize.DATEONLY,
defaultValue: Sequelize.NOW
},
JC_ADDITIONAL: {
type:Sequelize.CHAR(100),
},
JC_FOUND:{
type:Sequelize.BOOLEAN,
defaultValue: false,
allowNull: false
},
JC_FOUND_DATE:{
type:Sequelize.CHAR(20),
},
DRIVER_RULES_DATE:{
type:Sequelize.DATEONLY,
},
DRIVER_CATEGORY:{
type:Sequelize.CHAR(1),
}
});
};
|
import Vue from 'vue';
import mountComponent from 'helpers/vue_mount_component_helper';
import closedComponent from '~/vue_merge_request_widget/components/states/mr_widget_closed.vue';
describe('MRWidgetClosed', () => {
let vm;
beforeEach(() => {
const Component = Vue.extend(closedComponent);
vm = mountComponent(Component, {
mr: {
metrics: {
mergedBy: {},
closedBy: {
name: 'Administrator',
username: 'root',
webUrl: 'http://localhost:3000/root',
avatarUrl:
'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
},
mergedAt: 'Jan 24, 2018 1:02pm GMT+0000',
closedAt: 'Jan 24, 2018 1:02pm GMT+0000',
readableMergedAt: '',
readableClosedAt: 'less than a minute ago',
},
targetBranchPath: '/twitter/flight/commits/so_long_jquery',
targetBranch: 'so_long_jquery',
},
});
});
afterEach(() => {
vm.$destroy();
});
it('renders warning icon', () => {
expect(vm.$el.querySelector('.js-ci-status-icon-warning')).not.toBeNull();
});
it('renders closed by information with author and time', () => {
expect(
vm.$el
.querySelector('.js-mr-widget-author')
.textContent.trim()
.replace(/\s\s+/g, ' '),
).toContain('Closed by Administrator less than a minute ago');
});
it('links to the user that closed the MR', () => {
expect(vm.$el.querySelector('.author-link').getAttribute('href')).toEqual(
'http://localhost:3000/root',
);
});
it('renders information about the changes not being merged', () => {
expect(
vm.$el
.querySelector('.mr-info-list')
.textContent.trim()
.replace(/\s\s+/g, ' '),
).toContain('The changes were not merged into so_long_jquery');
});
it('renders link for target branch', () => {
expect(vm.$el.querySelector('.label-branch').getAttribute('href')).toEqual(
'/twitter/flight/commits/so_long_jquery',
);
});
});
|
/**
* Created by mac on 15-6-6.
*/
|
import chai from 'chai';
import {mergeTo,
isUndef} from '../src/util/index';
import Van from '../src/instance/Van';
var assert = chai.assert;
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal(-1, [1,2,3].indexOf(4));
});
});
});
// 测试Util
describe('Util', function() {
describe('#mergeTo()', function(){
it('合并后的对象拥有两个对象的属性', function() {
let obj1 = {name: 'name'};
let obj2 = {age: 10};
let obj3 = mergeTo(obj1, obj2);
assert.equal(10, obj3.age);
assert.equal('name', obj3.name);
});
});
describe('#isUndef()', function(){
it('undefined与null均返回true', function() {
let flag1 = isUndef(undefined);
let flag2 = isUndef(null);
assert.equal(true, flag1);
assert.equal(true, flag2);
});
});
});
describe('Instance', function() {
describe('#mergeTo()', function(){
it('合并后的对象拥有两个对象的属性', function() {
let obj1 = {name: 'name'};
let obj2 = {age: 10};
let obj3 = mergeTo(obj1, obj2);
assert.equal(10, obj3.age);
assert.equal('name', obj3.name);
});
});
});
|
/**
* @jsx React.DOM
*/
'use strict';
/* Controllers */
var dpiControllers = angular.module('dpiControllers', []);
dpiControllers.controller('dpiCtrl', ['$scope',
function($scope) {
//$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
|
import axios from 'axios';
export function getQuestions() {
return axios
.get("https://nameless-sands-91761.herokuapp.com/api/forums")
.then(response => response.data)
.catch(error => {
throw (error)
});
}
export function getQuestion(forumId) {
return axios
.get(`https://nameless-sands-91761.herokuapp.com/api/forums/${forumId}`)
.then(response => response.data)
.catch(error => {
throw (error)
});
}
export function postQuestion(model) {
return axios
.post("https://nameless-sands-91761.herokuapp.com/api/forums", model)
.then(response => response.data)
.catch(error => {
throw (error)
});
}
export function getAnswers(forumId) {
return axios
.get(`https://nameless-sands-91761.herokuapp.com/api/forums/${forumId}/answers`)
.then(response => response.data)
.catch(error => {
throw (error)
});
}
export function postAnswers(forumId, model) {
return axios
.post(`https://nameless-sands-91761.herokuapp.com/api/forums/${forumId}/answers`, model)
.then(response => response.data)
.catch(error => {
throw (error)
});
}
export function postReply(forumId, model) {
return axios
.post(`https://nameless-sands-91761.herokuapp.com/api/forums/${forumId}/answers`, model)
.then(response => response.data)
.catch(error => {
throw (error)
});
}
|
(function($) {
var urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
$.fn.psdomgallery = function(options) {
//var galleries = [];
galleries = [];
var _options = options;
var init = function($this) {
galleries = [];
$this.each(function(i, gallery) {
galleries.push({
id: i,
items: [],
maincaption: galleryCaption(gallery)
});
// $(gallery).find('a.js-gallerystart').data('gallery-id', i + 1);
// $(gallery).find('a.js-gallerystart').data('photo-id', 0);
$(gallery).find('figure a').each(function(k, link) {
var $link = $(link),
size = $link.data('size').split('x');
if (size.length != 2) {
throw SyntaxError("Missing data-size attribute.");
}
$link.data('gallery-id', i + 1);
$link.data('photo-id', k );
var gurl = $(gallery).data('galleryurl')?$(gallery).data('galleryurl'):window.location.href.match(/^[^\#\?]+/)[0];
var item = {
src: link.href,
msrc: link.children[0].getAttribute('src'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10),
attachmentURL: gurl + '#/&gid=1&pid=' + (k+1),
el: link,
title: '<h3>'+link.getAttribute('title')+'</h3><ul class="card__related">'+ $(link).parents('.card').find('.card__related').html()+'</ul>'+$(link).parents('.card').find('.card__leiras').html()
}
galleries[i].items.push(item);
});
$(gallery).on('click', 'figure a', function(e) {
e.preventDefault();
var gid = $(this).data('gallery-id'),
pid = $(this).data('photo-id');
startGallery(gid, pid);
});
});
}
var galleryCaption = function(gallery) {
var $gtitle = $(gallery).data('gallerytitle'),
$gdate = $(gallery).data('gallerydate'),
$gphotographer = $(gallery).data('galleryphotographer');
var niceHead = '<header class="niceHeader"><h1 class="niceHeader-mainText"><span>' + $gtitle + '</span></h1><time class="niceHeader-subText">' + $gdate + '</time><div class="niceHeader-disclaimer">Fotó: ' + $gphotographer + '</div></header>';
return niceHead;
};
var parseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if (hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if (!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if (pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if (params.gid) {
params.gid = parseInt(params.gid, 10);
}
if (!params.hasOwnProperty('pid')) {
return params;
}
params.pid = parseInt(params.pid, 10);
return params;
};
var openGallery = function(gid, pid) {
var pswpElement = document.querySelectorAll('.pswp')[0],
items = galleries[gid - 1].items,
fixcaption = galleries[gid - 1].maincaption
options = {
barsSize: {top:44, bottom:'66'},
bgOpacity: 1,
shareButtons: [
{id:'urltest', label:'Sima link teszt', url: '{{url}}'},
{id:'facebook', label:'Megosztás Facebookon', url:'https://www.facebook.com/dialog/share?app_id=646072898740588&href={{url}}&picture={{image_url}}'},
{id:'pinterest', label:'Pin it', url:'http://www.pinterest.com/pin/create/button/?url={{url}}&media={{image_url}}&description={{text}}'},
{id:'download', label:'Kép letöltése', url:'{{raw_image_url}}', download:true}
],
getPageURLForShare: function( /* shareButtonData */ ) {
return items[urlParam('pid') - 1].attachmentURL;
},
// Function builds caption markup
// addCaptionHTMLFn: function(item, captionEl, isFake) {
// captionEl.children[0].innerHTML = fixcaption;
// return true;
// },
index: pid,
galleryUID: gid,
getThumbBoundsFn: function(index) {
var thumbnail = items[index].el.children[0],
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {
x: rect.left,
y: rect.top + pageYScroll,
w: rect.width
};
}
};
$.extend(options, _options);
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
// gallery.listen('destroy', function() {
// $('.pswp').remove();
// });
}
//load ui + open gallery. root html lang attr must be set
var startGallery = function(gid, pid) {
$('.banner').removeClass('ison');
openGallery(gid,pid);
return true;
}
// initialize
init(this);
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = parseHash();
if (hashData.pid > 0 && hashData.gid > 0) {
if ($('.js-gallery').length) {
startGallery(hashData.gid, hashData.pid);
}
}
return this;
};
}(jQuery));
|
/* globals angular */
angular.module('wizardApp.spells', ['wizardApp.socketIO'])
.directive('spells', function() {
return {
restrict: 'E',
replace: true,
scope: {
spells: '='
},
templateUrl: './components/spells/spells.html',
controller: 'SpellsCtrl'
};
})
.controller('SpellsCtrl', ['$scope', '$timeout', 'socketIO', SpellsCtrl]);
function SpellsCtrl($scope, $timeout, socketIO) {
$scope.castSpell = function(spell) {
console.log('"' + spell + '"' + ' spell has been cast');
switch (spell) {
case 'Recover':
break;
case 'Defend':
break;
case 'Perry':
break;
case 'Repost':
break;
case 'Attack':
var attackId = new Date().getTime();
socketIO.socket.emit(socketIO.E.ATTACK_PU, {attackId: attackId});
// var power = Math.floor(Math.random() * 10);
// var crit = Math.floor(Math.random() * 11 + 1 );
// $timeout(function() {
// console.log('2-SECOND TIMEOUT COMPLETE');
// socket.emit(ATTACK, {attackId: attackId, power: power, crit: (crit > 8), time: new Date().getTime()});
// }, 2000);
break;
}
};
}
|
/* eslint-disable import/no-extraneous-dependencies, func-names */
/* global describe, it */
import { expect } from 'chai';
import { Subject } from 'rxjs/Subject';
import { filter as filter$ } from 'rxjs/operators/filter';
import { map as map$ } from 'rxjs/operators/map';
import combineEpics from './combineEpics';
import ActionsObservable from './ActionsObservable';
describe('frint-store › combineEpics', function () {
it('triggers epics correct response', function () {
const pingEpic = function (action$) {
return action$
.pipe(
filter$(action => action.type === 'PING'),
map$(() => ({ type: 'PONG' }))
);
};
const rootEpic = combineEpics(pingEpic);
const subject$ = new Subject();
const actions$ = new ActionsObservable(subject$);
const result$ = rootEpic(actions$);
const emittedActions = [];
const subscription = result$.subscribe((emittedAction) => {
emittedActions.push(emittedAction);
});
subject$.next({ type: 'PING' });
expect(emittedActions).to.deep.equal([
{ type: 'PONG' }
]);
subscription.unsubscribe();
});
});
|
import { ComponentTreeCache, VTree, Transaction } from './util/types';
import globalThis from './util/global';
import onceEnded from './once-ended';
import componentWillUnmount from './lifecycle/component-will-unmount';
import renderComponent from './render-component';
const { assign } = Object;
/**
* @param {VTree} oldTree
* @param {VTree} newTree
*
* @returns {VTree | null}
*/
function render(oldTree, newTree) {
let oldComponentTree = null;
// When there is an oldTree and it has childNodes, attempt to look up first
// by the top-level element, or by the first element.
if (oldTree && oldTree.childNodes) {
// First try and lookup the old tree as a component.
oldComponentTree = ComponentTreeCache.get(oldTree);
// If that fails, try looking up it's first child.
if (!oldComponentTree) {
oldComponentTree = ComponentTreeCache.get(oldTree.childNodes[0]);
}
}
// If there is no old component, or if the components do not match, then we
// are rendering a brand new component.
if (!oldComponentTree || oldComponentTree.rawNodeName !== newTree.rawNodeName) {
return renderComponent(newTree);
}
// Otherwise re-use the existing component if the constructors are the same.
if (oldComponentTree) {
// Update the incoming props/attrs.
assign(oldComponentTree.attributes, newTree.attributes);
return renderComponent(oldComponentTree);
}
return oldTree;
}
/**
* @param {VTree} vTree
*/
const releaseHook = vTree => componentWillUnmount(vTree);
/**
* @param {VTree} vTree
*/
const createTreeHook = vTree => {
const { customElements } = globalThis;
const Constructor = customElements && customElements.get(vTree.nodeName);
if (typeof vTree.rawNodeName === 'function' || Constructor) {
vTree.attributes.children = vTree.attributes.children || vTree.childNodes;
}
};
/**
* @param {VTree} vTree
*/
const createNodeHook = vTree => {
// Only look up elements with a dash in the name.
if (!vTree.nodeName.includes('-')) return;
// Convert this to globalThis
const { customElements } = globalThis;
const Constructor = customElements && customElements.get(vTree.nodeName);
if (Constructor) {
return new Constructor(vTree.attributes);
}
};
/**
* @param {VTree} oldTree
* @param {VTree} newTree
*/
const syncTreeHook = (oldTree, newTree) => {
// Render components during synchronization.
if (
// When child is a Component
typeof newTree.rawNodeName === 'function' &&
// If there is an oldTree and it's not the existing component, trigger a
// render.
(oldTree && oldTree.rawNodeName ? oldTree.rawNodeName !== newTree.rawNodeName : false)
) {
return render(oldTree, newTree);
}
if (!newTree.childNodes) {
return oldTree;
}
// Loop through childNodes seeking out components to render.
for (let i = 0; i < newTree.childNodes.length; i++) {
const newChildTree = newTree.childNodes[i];
if (typeof newChildTree.rawNodeName === 'function') {
const oldChildTree = oldTree.childNodes && oldTree.childNodes[i];
const renderTree = render(oldChildTree, newChildTree);
// If nothing was rendered, return the oldTree.
if (!renderTree) {
return oldTree;
}
// Inject the rendered tree into the position.
if (renderTree) {
newTree.childNodes[i] = renderTree;
// If the rendered tree is a fragment, splice in the children, as this
// is simply a container for the nodes.
if (renderTree.nodeType === 11) {
// If a function was returned, re-run the inspection over this
// element.
if (typeof renderTree.rawNodeName === 'function') {
i = i - 1;
}
// Replace the fragment with the rendered elements. This reduces and
// flattens the fragments into their respective nodes. If there are
// none, then they are removed from the DOM and nothing is rendered.
else {
newTree.childNodes.splice(i, 1, ...renderTree.childNodes);
}
}
}
}
}
};
export default () => assign(
(/** @type {Transaction} */transaction) => transaction.onceEnded(onceEnded),
{
displayName: 'componentTask',
syncTreeHook,
createNodeHook,
createTreeHook,
releaseHook,
},
);
|
"use strict";
var HaProxy = require("@quilt/haproxy").Haproxy;
var Mongo = require("@quilt/mongo");
var Node = require("@quilt/nodejs");
var Inf = require("./inf.js");
var count = 4;
var mongo = new Mongo(count);
var app = new Node({
nWorker: count,
repo: "https://github.com/quilt/node-todo.git",
env: {
PORT: "80",
MONGO_URI: mongo.uri("mean-example")
}
});
var haproxy = new HaProxy(count, app.services());
mongo.connect(mongo.port, app);
app.connect(mongo.port, mongo);
haproxy.public();
var inf = Inf.New(4);
inf.deploy(app);
inf.deploy(mongo);
inf.deploy(haproxy);
|
var mgkey = require("./apikeys").mailgun.secretKey;
var Mailgun = new (require("mailgun").Mailgun)(mgkey);
var MailComposer = require("mailcomposer").MailComposer;
module.exports.validateEmail = function(email) {
/* Validate email address
* @email: An email address to check
*/
//res.status(500).send({ error: "email invalid" });
return true;
};
module.exports.sendEmail = function (sender, recipients, subject, fhtml, callback) {
/* Wrapper for Mailgun.sendText function
* @sender: Set sender field
* @recipients: Set recipients field
* @subject: Set subject field
* @fhtml: Set html field
* @callback(err): Handle response (err is undefined if successful)
*/
var mailcomposer = new MailComposer({
"keepBcc": true,
"forceEmbeddedImages": true
});
mailcomposer.setMessageOption({
from: sender,
to: recipients,
html: fhtml
});
mailcomposer.buildMessage(function(err, messageSource) {
/* sendRaw(sender, recipients, rawBody, [servername], [callback(err)])
* @sender - Sender of the message; this should be a full email address
* (e.g. example@example.com)
* @recipients - A string (example@example.com) or array of strings
* (['a@example.com', 'b@example.com']) of recipients;
* these can be email addresses or HTTP URLs.
* @rawBody - MIME message to send
* @servername - The name of the Mailgun server. If you only have one
* server on your Mailgun account, this can be omitted.
* Otherwise, it should be set to the server you want to send from.
* @callback - Callback to be fired when the email is done being sent.
* This should take a single parameter, err, that will be set to
* the status code of the API HTTP response code if the email
* failed to send; on success, err will be undefined.
*/
console.log(err || messageSource);
//Mailgun.sendText(sender, recipients, subject, html, callback);
Mailgun.sendRaw(sender, recipients, messageSource, callback);
});
};
|
/**
* Created by edagarli on 16/4/12.
* https://github.com/edagarli
*/
'use strict';
var React = require('react-native');
var {
AsyncStorage,
Image,
StyleSheet,
Text,
View,
} = React;
var Drawer = require('react-native-drawer');
var ThemesList = require('./ThemesList');
var DRAWER_REF = 'drawer';
var MainScreen = React.createClass({
getInitialState: function() {
return ({
theme: null,
});
},
onSelectTheme: function(theme) {
this.refs[DRAWER_REF].close();
this.setState({theme: theme});
},
onRefresh: function() {
this.onSelectTheme(this.state.theme);
},
render: function() {
var drawer = <ThemesList onSelectItem={this.onSelectTheme} />;
return (
<Drawer
ref={DRAWER_REF}
openDrawerOffset={100}
panCloseMask={1}
content={drawer} >
</Drawer>
);
}
});
module.exports = MainScreen;
|
console.log('init animachine')
var sourceUrl = window.ANIMACHINE_SOURCE_URL || 'https://rawgit.com/animachine/animachine/browser-dist/animachine.js'
loadjscssfile('js', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.5/TweenMax.min.js')
loadjscssfile('js', sourceUrl)
loadjscssfile('css', '//fonts.googleapis.com/css?family=Open+Sans:400,700,600,300&subset=latin,latin-ext')
loadjscssfile('css', '//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css')
function loadjscssfile(filetype, filename){
var fileref
if (filetype=='js'){ //if filename is a external JavaScript file
fileref=document.createElement('script')
fileref.setAttribute('type','text/javascript')
fileref.setAttribute('src', filename)
}
else if (filetype=='css'){ //if filename is an external CSS file
fileref=document.createElement('link')
fileref.setAttribute('rel', 'stylesheet')
fileref.setAttribute('type', 'text/css')
fileref.setAttribute('href', filename)
}
document.head.appendChild(fileref)
}
|
/* */
module.exports = function(hljs) {
var Q_KEYWORDS = {
keyword:
'do while select delete by update from',
constant:
'0b 1b',
built_in:
'neg not null string reciprocal floor ceiling signum mod xbar xlog and or each scan over prior mmu lsq inv md5 ltime gtime count first var dev med cov cor all any rand sums prds mins maxs fills deltas ratios avgs differ prev next rank reverse iasc idesc asc desc msum mcount mavg mdev xrank mmin mmax xprev rotate distinct group where flip type key til get value attr cut set upsert raze union inter except cross sv vs sublist enlist read0 read1 hopen hclose hdel hsym hcount peach system ltrim rtrim trim lower upper ssr view tables views cols xcols keys xkey xcol xasc xdesc fkeys meta lj aj aj0 ij pj asof uj ww wj wj1 fby xgroup ungroup ej save load rsave rload show csv parse eval min max avg wavg wsum sin cos tan sum',
typename:
'`float `double int `timestamp `timespan `datetime `time `boolean `symbol `char `byte `short `long `real `month `date `minute `second `guid'
};
return {
aliases:['k', 'kdb'],
keywords: Q_KEYWORDS,
lexemes: /\b(`?)[A-Za-z0-9_]+\b/,
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE
]
};
};
|
/**
* Created by haden on 1/6/2017.
*/
module.exports = {
dev: {
options: {
mangle: false, //keep original var/function/etc names for debugging in browser
paths: ["_assets/js/src/"],
compress: {
sequences: false
}
},
files: {
'_assets/js/build.min.js': ['_assets/js/src/*.js']
}
},
// Uncomment and modify to suite production needs
//production: {
// options: {
// mangle: true, // further minify files
// paths: ["_assets/js/src/"],
// compress: {
// sequences: false
// }
// },
// files: {
// '_assets/js/src/build.min.js': ['_assets/js/src/*.js']
// }
//}
};
|
// Box requirements
var PlayerBox = require('./box/player_box');
var EnemyBox = require('./box/enemy_box');
var ExplodeBox = require('./box/explode_box');
var PowerBox = require('./box/power_box');
var BoxManager = require('./box/box_manager')
// Background and Hud
var Background = require('./background');
var Hud = require('./hud');
//
var Controller = require('./controller');
var Display = require('./display');
var Interaction = require('./interaction');
var config = require('./config');
/**
* A class for managing the game.
*/
var Engine = function(socket){
this.socket = socket;
this.total_score = 0;
this.level_score = 0;
this.level = 0;
this.lives = config.box.player.lives;
this.max_level = config.numberOfLevels;
};
/**
*
*/
Engine.prototype.init = function(contexts){
this.interaction = new Interaction();
this.display = new Display(config, contexts);
this.display.init();
this.background = new Background(config);
this.hud = new Hud(config);
// Set up the controller to pass to the player
var controller = new Controller();
window.onkeydown = function (event) { controller.keyDown(event); };
window.onkeyup = function (event) { controller.keyUp(event); };
this.boxManager = new BoxManager(config, controller);
this.boxManager.init();
};
/**
*
*/
Engine.prototype.run = function(){
var self = this;
// loop
function loop(){
self.update();
self.draw();
// Check if game is over and clearInterval if so
if (self.lives === 0 || self.level === config.numberOfLevels) {
self.endGame();
clearInterval(gameLoop);
}
}
var gameLoop = setInterval(loop, 1000 / config.fps);
};
/**
*
*/
Engine.prototype.update = function(){
// update all
this.background.update();
this.hud.update();
this.boxManager.update(this.level);
this.boxManager.enemyHit()
this.lives = config.box.player.lives - this.boxManager.enemiesHit;
this.level = Math.floor(this.boxManager.enemiesDodged / 100);
this.score = this.boxManager.enemiesDodged;
};
/**
*
*/
Engine.prototype.draw = function(){
// draw
this.display.drawGame({
background: this.background,
hud: this.hud,
player: this.boxManager.playerBox,
enemies: this.boxManager.enemyBoxes,
explosions: this.boxManager.explodeBoxes,
powerboxes: []
});
this.display.drawHud({
score: this.score,
level: this.level,
lives: this.lives
});
};
/**
*
*/
Engine.prototype.endGame = function(){
this.display.end(this.score, this.level);
var gameDetails = {};
gameDetails.playerName = $("#name").val();
gameDetails.level = this.level;
gameDetails.score = this.score;
// Emit event with game details object to add to highscores
this.socket.emit('score', gameDetails);
};
module.exports = Engine;
|
// @flow
import type {FilterConfigId, FilterType} from '../BasicTypes';
export default class FilterConfig {
filterType: FilterType;
id: FilterConfigId | null;
enabled: boolean;
description: string;
constructor(filterType: FilterType) {
this.filterType = filterType;
this.id = null;
this.enabled = true;
this.description = '';
}
}
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('route:sessions/create', 'Unit | Route | sessions/create', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function(assert) {
var route = this.subject();
assert.ok(route);
});
|
'use strict';
var fs = require('fs-extra');
var dir = '/src/lib';
fs.ensureDir(dir, function (err) {
console.log(err); // => null
// dir has now been created, including the directory it is to be placed in
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9zY2FmZm9sZC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLElBQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxVQUFVLENBQUMsQ0FBQzs7QUFFL0IsSUFBTSxHQUFHLEdBQUcsVUFBVSxDQUFDO0FBQ3ZCLEVBQUUsQ0FBQyxTQUFTLENBQUMsR0FBRyxFQUFFLFVBQVMsR0FBRyxFQUFFO0FBQzVCLFdBQU8sQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLENBQUM7O0NBRXBCLENBQUMsQ0FBQyIsImZpbGUiOiJzY2FmZm9sZC5qcyIsInNvdXJjZXNDb250ZW50IjpbImNvbnN0IGZzID0gcmVxdWlyZSgnZnMtZXh0cmEnKTtcblxuY29uc3QgZGlyID0gJy9zcmMvbGliJztcbmZzLmVuc3VyZURpcihkaXIsIGZ1bmN0aW9uKGVycikge1xuICAgIGNvbnNvbGUubG9nKGVycik7IC8vID0+IG51bGxcbi8vIGRpciBoYXMgbm93IGJlZW4gY3JlYXRlZCwgaW5jbHVkaW5nIHRoZSBkaXJlY3RvcnkgaXQgaXMgdG8gYmUgcGxhY2VkIGluXG59KTtcbiJdfQ==
|
window.Mobike = {
"site": "http://www.mobike.com",
"0": "mobike",
"1": "mobike lite"
}
|
import React from 'react';
import {Route, IndexRoute} from 'react-router';
import {requireAuthentication} from '../components/Auth'
import {
App,
NotFound,
RoomDetail,
AddRoom,
UserInfo,
Rooms,
OrderPage,
LoginView,
RegistView,
NotActiveView,
ActiveView,
Loading,
UserList,
ResetPassword,
DepartmentsView
} from '../components';
export default (
<Route path='/' component={App}>
<IndexRoute component={Rooms}></IndexRoute>
<Route path='/rooms' component={Rooms}></Route>
<Route path='/rooms/:id' component={RoomDetail}></Route>
<Route path='/addroom' component={AddRoom}></Route>
<Route path='/userslist' component={requireAuthentication(UserList)}></Route>
<Route path="/departments" component={DepartmentsView}/>
<Route path='/users/:id' component={UserInfo}></Route>
<Route path='/order/:id' component={requireAuthentication(OrderPage)}></Route>
<Route path="/login" component={LoginView}/>
<Route path="/regist" component={RegistView}/>
<Route path="/notactive" component={NotActiveView}/>
<Route path="/active" component={ActiveView}/>
<Route path='/notfound' component={NotFound}/>
<Route path='/loading' component={Loading}/>
<Route path='/resetpassword' component={ResetPassword}/>
<Route path='*' component={NotFound}/>
</Route>
)
|
'use strict'
const co = require('co')
const cli = require('heroku-cli-util')
const pg = require('@heroku-cli/plugin-pg-v5')
function * run (context, heroku) {
const db = yield pg.fetcher(heroku).database(context.app, context.args.database)
const query = `
SELECT
relname AS name,
n_live_tup AS estimated_count
FROM
pg_stat_user_tables
ORDER BY
n_live_tup DESC;
`
const output = yield pg.psql.exec(db, query)
process.stdout.write(output)
}
const cmd = {
topic: 'pg',
description: 'show all tables and the number of rows in each ordered by number of rows descending',
needsApp: true,
needsAuth: true,
args: [{ name: 'database', optional: true }],
run: cli.command({ preauth: true }, co.wrap(run))
}
module.exports = [
Object.assign({ command: 'records-rank' }, cmd),
Object.assign({ command: 'records_rank', hidden: true }, cmd)
]
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var router_1 = require("@angular/router");
var ProductDetailGuard = (function () {
function ProductDetailGuard(_router) {
this._router = _router;
}
ProductDetailGuard.prototype.canActivate = function (route) {
var id = +route.url[1].path;
if (isNaN(id) || id < 1) {
alert('Invalid product Id');
// start a new navigation to redirect to list page
this._router.navigate(['/products']);
// abort current navigation
return false;
}
;
return true;
};
return ProductDetailGuard;
}());
ProductDetailGuard = __decorate([
core_1.Injectable(),
__metadata("design:paramtypes", [router_1.Router])
], ProductDetailGuard);
exports.ProductDetailGuard = ProductDetailGuard;
//# sourceMappingURL=product-guard.service.js.map
|
Ext.define('SlateAdmin.controller.courses.Profile', {
extend: 'Ext.app.Controller',
// controller config
views: [
'courses.sections.details.Profile'
],
stores: [
'Terms@Slate.store',
'Locations@Slate.store',
'courses.Schedules'
],
refs: {
profilePanel: {
selector: 'courses-sections-details-profile',
autoCreate: true,
xtype: 'courses-sections-details-profile'
},
profileForm: 'courses-sections-details-profile form',
cancelBtn: 'courses-sections-details-profile button[action=cancel]',
saveBtn: 'courses-sections-details-profile button[action=save]',
courseField: 'courses-sections-details-profile field[name=CourseID]',
codeField: 'courses-sections-details-profile field[name=Code]',
titleField: 'courses-sections-details-profile field[name=Title]'
},
control: {
'courses-sections-manager': {
selectedsectionchange: 'onSelectedSectionChange'
},
'courses-sections-manager #detailTabs': {
beforerender: 'onBeforeTabsRender'
},
'courses-sections-details-profile': {
sectionloaded: 'onSectionLoaded'
},
'courses-sections-details-profile form': {
dirtychange: 'syncButtons',
validitychange: 'syncButtons'
},
'courses-sections-details-profile button[action=cancel]': {
click: 'onCancelButtonClick'
},
'courses-sections-details-profile button[action=save]': {
click: 'onSaveButtonClick'
},
'courses-sections-details-profile combobox[name=CourseID]': {
select: 'onCourseSelect'
}
},
// event handlers
onSelectedSectionChange: function(manager, section) {
var me = this;
// switch to the profile tab and focus first field if this is a phantom
if (section && section.phantom) {
manager.detailTabs.setActiveTab(me.getProfilePanel());
Ext.defer(function() {
me.getProfileForm().down('field[readOnly=false][disabled=false]').focus();
}, 100);
}
},
onBeforeTabsRender: function(detailTabs) {
detailTabs.add(this.getProfilePanel());
},
onSectionLoaded: function(profilePanel, section) {
var me = this;
me.getCodeField().setDisabled(!section.phantom);
profilePanel.setLoading('Loading lists…');
Ext.StoreMgr.requireLoaded(['Terms', 'Locations', 'courses.Schedules'], function() {
me.getProfileForm().loadRecord(section);
me.syncEmptyText();
profilePanel.setLoading(false);
});
},
onCancelButtonClick: function() {
this.getProfileForm().getForm().reset();
},
onSaveButtonClick: function() {
var me = this,
profileForm = me.getProfileForm(),
form = profileForm.getForm(),
section = form.getRecord();
profileForm.setLoading('Saving…');
form.updateRecord(section);
section.save({
success: function(record) {
profileForm.loadRecord(record);
profileForm.setLoading(false);
},
failure: function(record, operation) {
var rawData = record.getProxy().getReader().rawData,
failed,
validationErrors;
if (rawData && (failed = rawData.failed) && failed[0] && (validationErrors = failed[0].validationErrors)) {
Ext.Object.each(validationErrors, function(fieldName, error) {
var field = profileForm.getForm().findField(fieldName);
if (field) {
profileForm.getForm().findField(fieldName).markInvalid(error);
}
});
validationErrors = 'You\'ve tried to make invalid changes, please check the highlighted field(s) for details';
}
Ext.Msg.alert('Not saved', validationErrors);
profileForm.setLoading(false);
}
});
},
onCourseSelect: function() {
this.syncEmptyText();
},
// internal methods
syncEmptyText: function() {
var me = this,
courseField = me.getCourseField(),
codeField = me.getCodeField(),
titleField = me.getTitleField(),
courseId = courseField.getValue(),
course = courseId && courseField.findRecordByValue(courseId);
codeField.setEmptyText(course ? (course.get('Code') + '-000') : 'ABCD-000');
titleField.setEmptyText(course ? course.get('Title') : 'Algebra 1');
},
syncButtons: function() {
var me = this,
profileForm = me.getProfileForm(),
valid = profileForm.isValid(),
dirty = profileForm.isDirty();
me.getCancelBtn().setDisabled(!dirty);
me.getSaveBtn().setDisabled(!dirty || !valid);
}
});
|
game.PlayScreen = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function() {
// reset the score
game.data.score = 0;
me.levelDirector.loadLevel("level01");
this.resetPlayer(0, 420);
var gameTimerManager = me.pool.pull("GameTimerManager", 0, 0, {});
me.game.world.addChild(gameTimerManager, 0);
var heroDeathManager = me.pool.pull("HeroDeathManager", 0, 0, {});
me.game.world.addChild(heroDeathManager, 0);
var experienceManager = me.pool.pull("ExperienceManager", 0, 0, {});
me.game.world.addChild(experienceManager, 0);
var spendGold = me.pool.pull("SpendGold", 0, 0, {});
me.game.world.addChild(spendGold, 0);
me.input.bindKey(me.input.KEY.E, "buy");
me.input.bindKey(me.input.KEY.R, "skill-1");
me.input.bindKey(me.input.KEY.T, "skill-2");
me.input.bindKey(me.input.KEY.Y, "skill-3");
me.input.bindKey(me.input.KEY.RIGHT, "right");
me.input.bindKey(me.input.KEY.LEFT, 'left');
me.input.bindKey(me.input.KEY.UP, 'jump');
me.input.bindKey(me.input.KEY.SPACE, "attack");
me.input.bindKey(me.input.KEY.D, "right");
me.input.bindKey(me.input.KEY.A, 'left');
me.input.bindKey(me.input.KEY.W, 'jump');
// add our HUD to the game world
this.HUD = new game.HUD.Container();
me.game.world.addChild(this.HUD);
},
/**
* action to perform when leaving this screen (state change)
*/
onDestroyEvent: function() {
// remove the HUD from the game world
me.game.world.removeChild(this.HUD);
},
resetPlayer: function(x, y){
game.data.player = me.pool.pull("player", x, y, {});
me.game.world.addChild(game.data.player, 5);
}
});
|
/**
* Module dependencies
*/
var showcase = require('shoelace-ui-showcase');
var app = module.exports = showcase({
defaultTheme: 'octanner/theme-vision',
logo: 'http://i.imgur.com/834AbOg.png'
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:eb6f428dbcb778d6524e5412cf812f9ec1f172db21aad03813c71790ee2897b1
size 583
|
const { BrokerOptionsError } = require("../../../../src/errors");
const Discoverers = require("../../../../src/registry/discoverers");
describe("Test Discoverers resolver", () => {
it("should resolve default Local discoverer", () => {
const discoverer = Discoverers.resolve();
expect(discoverer).toBeInstanceOf(Discoverers.Local);
});
it("should resolve Local reporter from string", () => {
const discoverer = Discoverers.resolve("Local");
expect(discoverer).toBeInstanceOf(Discoverers.Local);
});
it("should resolve Local discoverer from obj", () => {
const options = { heartbeatInterval: 8 };
const discoverer = Discoverers.resolve({ type: "Local", options });
expect(discoverer).toBeInstanceOf(Discoverers.Local);
expect(discoverer.opts).toEqual(expect.objectContaining({ heartbeatInterval: 8 }));
});
it("should resolve Local discoverer from instance", () => {
const instance = new Discoverers.Local();
const discoverer = Discoverers.resolve(instance);
expect(discoverer).toBe(instance);
});
it("should resolve Etcd3 reporter from string", () => {
const discoverer = Discoverers.resolve("Etcd3");
expect(discoverer).toBeInstanceOf(Discoverers.Etcd3);
});
it("should resolve Etcd3 reporter from connection string", () => {
const discoverer = Discoverers.resolve("etcd3://server:2345");
expect(discoverer).toBeInstanceOf(Discoverers.Etcd3);
expect(discoverer.opts.etcd).toEqual({ hosts: "server:2345" });
});
it("should resolve Etcd3 discoverer from obj", () => {
const options = { heartbeatInterval: 8 };
const discoverer = Discoverers.resolve({ type: "Etcd3", options });
expect(discoverer).toBeInstanceOf(Discoverers.Etcd3);
expect(discoverer.opts).toEqual(expect.objectContaining({ heartbeatInterval: 8 }));
});
it("should resolve Etcd3 discoverer from instance", () => {
const instance = new Discoverers.Etcd3();
const discoverer = Discoverers.resolve(instance);
expect(discoverer).toBe(instance);
});
it("should resolve Redis reporter from string", () => {
const discoverer = Discoverers.resolve("Redis");
expect(discoverer).toBeInstanceOf(Discoverers.Redis);
});
it("should resolve Redis reporter from connection string", () => {
const discoverer = Discoverers.resolve("redis://redis-server:6379");
expect(discoverer).toBeInstanceOf(Discoverers.Redis);
expect(discoverer.opts.redis).toEqual("redis://redis-server:6379");
});
it("should resolve Redis discoverer from obj", () => {
const options = { heartbeatInterval: 8 };
const discoverer = Discoverers.resolve({ type: "Redis", options });
expect(discoverer).toBeInstanceOf(Discoverers.Redis);
expect(discoverer.opts).toEqual(expect.objectContaining({ heartbeatInterval: 8 }));
});
it("should resolve Redis discoverer from instance", () => {
const instance = new Discoverers.Redis();
const discoverer = Discoverers.resolve(instance);
expect(discoverer).toBe(instance);
});
it("should throw error if not found by name", () => {
expect(() => Discoverers.resolve("xyz")).toThrowError(BrokerOptionsError);
expect(() => Discoverers.resolve({ type: "xyz" })).toThrowError(BrokerOptionsError);
});
});
describe("Test Discoverer register", () => {
class MyCustom {}
it("should throw error if type if not correct", () => {
expect(() => {
Discoverers.resolve("MyCustom");
}).toThrowError(BrokerOptionsError);
});
it("should register new type", () => {
Discoverers.register("MyCustom", MyCustom);
expect(Discoverers.MyCustom).toBe(MyCustom);
});
it("should find the new type", () => {
const discoverer = Discoverers.resolve("MyCustom");
expect(discoverer).toBeInstanceOf(MyCustom);
});
});
|
class Desktop {
constructor (Graphics, moduleList) {
this.g = Graphics;
this.mL = moduleList;
// Constants (not technically)
this.portSize = 15;
// Display
this.cX = 0;
this.cY = 0;
this.sXY = 1;
// Mouse
this.mX = 0;
this.mY = 0;
// Modules
this.selectedModule = undefined;
this.selectedInput = -1;
this.selectedOutput = -1;
this.caplocks = false;
}
scaleUp (e) {
if ( this.sXY >= 3) return;
this.cX -= ~~this.mouseMapX(e.clientX);
this.cY -= ~~this.mouseMapY(e.clientY);
this.sXY = ~~(this.sXY + 1);
}
scaleDown (e) {
if ( this.sXY == 1 ) return;
this.cX += ~~this.mouseMapX(e.clientX);
this.cY += ~~this.mouseMapY(e.clientY);
this.sXY = ~~(this.sXY - 1);
}
mouseMapX (x) {
return (x - this.cX)/this.sXY;
}
mouseMapY (y) {
return (y - this.cY)/this.sXY;
}
isOnModule (x, y) {
x = this.mouseMapX(x);
y = this.mouseMapY(y);
var _m = undefined;
this.mL.some(m => x > m.x - this.portSize && x < m.x + m.width + this.portSize && y > m.y && y < m.y + m.height && (_m = m));
return _m;
}
isOnInput (m, x, y) {
if (!m) return -1;
x = this.mouseMapX(x);
y = this.mouseMapY(y);
return ( x < m.x && y < m.y + m.numberOfInputs * this.portSize )? ~~((y - m.y)/this.portSize) : -1;
}
isOnOutput (m, x, y) {
if (!m) return -1;
x = this.mouseMapX(x);
y = this.mouseMapY(y);
return ( x > m.x + m.width && y < m.y + m.numberOfOutputs * this.portSize )? ~~((y - m.y)/this.portSize) : -1;
}
eMouseDown (e, listener) {
const x = e.clientX, y = e.clientY;
const m = this.isOnModule(x, y);
if (m) {
this.selectedModule = m;
this.selectedOutput = this.isOnOutput(m, x, y);
if(this.selectedOutput !== -1) return;
if (e.shiftKey || this.caplocks) {
listener.turnOn("eModuleShiftDrag");
this.selectedModule.eMouseDown(this.mouseMapX(x) - this.selectedModule.x, this.mouseMapY(y) - this.selectedModule.y);
} else {
listener.turnOn("eModuleDrag");
}
} else {
listener.turnOn("eDrag");
}
}
eMouseUp (e, listener) {
const x = e.clientX, y = e.clientY;
const m = this.isOnModule(x, y);
let i = -1;
if (m && (i = this.isOnInput(m, x, y)) !== -1)
if(this.selectedOutput !== -1) {
if( m.inputs[i] && m.inputs[i].index == this.selectedOutput ) m.unsetInput(i);
this.selectedModule.connect(m, i, this.selectedOutput);
}
this.selectedOutput = this.selectedInput = -1;
listener.turnOff("eModuleShiftDrag");
listener.turnOff("eModuleDrag");
listener.turnOff("eDrag");
}
eDrag (e) {
this.cX += e.movementX;
this.cY += e.movementY;
}
eMouseMove (e) {
this.mX = this.mouseMapX(e.clientX);
this.mY = this.mouseMapY(e.clientY);
}
eModuleDrag (e) {
this.selectedModule.x += e.movementX / this.sXY;
this.selectedModule.y += e.movementY / this.sXY;
}
eModuleShiftDrag(e) {
let x = this.mouseMapX(e.clientX ) - this.selectedModule.x;
let y = this.mouseMapY(e.clientY ) - this.selectedModule.y;
this.selectedModule.eDrag(e, x, y);
}
eKeyDown (e) {
if (e.key == "CapsLock")
this.caplocks = !this.caplocks;
}
render () {
const g = this.g;
const portSize = this.portSize;
g.setColor(1);
if (this.caplocks)
g.text(5, 5, "CAPLOCKS ON");
g.context.save();
g.context.translate(this.cX, this.cY);
g.context.scale(this.sXY, this.sXY);
if (this.selectedOutput !== -1) {
const m = this.selectedModule;
g.context.fillStyle = "#fff";
g.line(
m.x + m.width + portSize,
m.y + portSize/2 + this.selectedOutput * portSize,
this.mX,
this.mY
);
}
for ( let i = 0; i < this.mL.length; i++ ) {
const m = this.mL[i];
// Draw current module
//g.context.fillStyle = g.context.strokeStyle = `hsl(${m.color}, 100%, ${(m == this.selectedModule)? 65 : 85}%)`;
g.setColor(m.color);
if (this.selectedModule == m)
g.box(m.x, m.y + m.height, m.width, 1);
g.box(m.x, m.y, m.width, m.height);
// Draw inputs & outputs
for (let j=0; j < m.numberOfInputs ; j++)
g.box(m.x - portSize, m.y + j * portSize, portSize, portSize);
for (let j=0; j < m.numberOfOutputs; j++)
g.box(m.x + m.width, m.y + j * portSize, portSize, portSize);
// Draw connections
for (let j=0; j < m.inputs.length; j++) {
// Skip empty ports
if (!m.inputs[j]) continue;
const sourceModule = m.inputs[j].module;
g.line(
m.x - portSize,
m.y + portSize/2 + portSize * j,
sourceModule.x + sourceModule.width + portSize,
sourceModule.y + portSize/2 + portSize * m.inputs[j].index
);
}
// Module local rendering
g.context.save();
g.context.translate(~~m.x, ~~m.y);
m.interface(g, { portSize: portSize } );
g.context.restore();
}
g.context.restore();
}
}
|
module.exports = {
displayName: 'positioning',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/testing/test-setup.ts'],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
astTransformers: {
before: [
'jest-preset-angular/build/InlineFilesTransformer',
'jest-preset-angular/build/StripStylesTransformer',
],
},
},
},
coverageDirectory: '../../coverage/src/positioning',
snapshotSerializers: [
'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
'jest-preset-angular/build/AngularSnapshotSerializer.js',
'jest-preset-angular/build/HTMLCommentSerializer.js',
],
};
|
import {browserHistory} from 'react-router'
import types from '../constants/actionTypes'
import utils from '../../shared/utils'
function replaceOrder(order) {
return {
type: types.REPLACE_ORDER,
order
}
}
function getOrder(id) {
return (dispatch, getState) => {
utils.ajax({
url: '/api/order/getOrder',
type: 'get',
data: {
id
}
}).then(res => {
dispatch(replaceOrder(res.entry))
browserHistory.push('/orderDetail')
})
}
}
function cancelOrder(id) {
return (dispatch, getState) => {
utils.ajax({
url: '/api/order/cancelOrder',
data: {
id
}
}).then(res => {
browserHistory.goBack()
})
}
}
function receiveOrder(id) {
return (dispatch, getState) => {
utils.ajax({
url: '/api/order/receiveOrder',
data: {
id
}
}).then(res => {
browserHistory.goBack()
})
}
}
function refundOrder(id) {
return (dispatch, getState) => {
utils.ajax({
url: '/api/order/refundOrder',
data: {
id
}
}).then(res => {
browserHistory.goBack()
})
}
}
function getOrderWithoutRedirect() {
return (dispatch, getState) => {
utils.ajax({
url: '/api/order/getOrder',
type: 'get',
data: {
id: getState().order.id
}
}).then(res => {
dispatch(replaceOrder(res.entry))
})
}
}
export default {
replaceOrder,
getOrder,
getOrderWithoutRedirect,
cancelOrder,
refundOrder,
receiveOrder
}
|
/**
* Copyright 2014 GetHuman LLC
* Author: Masaya Ando
* Date Created: 6/11/2014
*
* Test runner for base.transformer.js
*/
var name = 'transformers/base.transformer';
var taste = require('taste');
var transformer = taste.target(name);
var _ = require('lodash');
var annotationHelper = taste.target('annotation.helper');
var utensils = taste.target('utensils');
var path = require('path');
describe('Unit Test for ' + name, function () {
var transformDir = path.join(__dirname, '../../fixtures/templates');
describe('loadUIPart()', function () {
it('should load a UI part with a parent', function () {
var filePath = '/app/foo/pages/something.page.js';
var commonPath = '/app/common/pages/something.page.js';
var obj = {parent: 'other', foo: 'choo', two: 'moo', three: 'me'};
var pancakes = {
requireModule: function (moduleName) {
if (moduleName === commonPath) {
return {
parent: 'other',
foo: 'choo',
two: 'moo'
};
}
else {
return {
'abstract': true,
two: 'loo',
three: 'me'
};
}
},
getRootDir: function () {
return '';
},
cook: function () {
return obj;
}
};
var context = {pancakes: pancakes};
var expected = obj;
var actual = transformer.loadUIPart.call(context, 'foo', filePath);
actual.should.deep.equal(expected);
});
});
describe('getAppName()', function () {
it('should extract an app name from a path', function () {
var filePath = '/blah/app/foo/pages/something.page.js';
var expected = 'foo';
var actual = transformer.getAppName(filePath);
actual.should.equal(expected);
});
});
describe('getAppModuleName()', function () {
it('should get an app module name', function () {
var prefix = 'gh';
var appName = 'foo';
var context = {getCamelCase: utensils.getCamelCase};
var expected = 'ghFooApp';
var actual = transformer.getAppModuleName.call(context, prefix, appName);
actual.should.equal(expected);
});
});
describe('setTemplate()', function () {
it('should set a dot template', function () {
var context = {};
transformer.setTemplate.call(context, transformDir, 'test.params');
taste.should.exist(context.template);
});
});
describe('getParamInfo()', function () {
it('should convert a list of params and return an object with converted values', function () {
var params = ['foo', 'bar', 'boo', 'donut'];
var alias = {
donut: 'munchkins'
};
var expected = {
converted: ['foo', 'bar', 'boo', 'munchkins'],
list: ['foo', 'bar', 'boo', 'donut'],
ngrefs: []
};
var actual = transformer.getParamInfo(params, alias);
actual.should.deep.equal(expected);
});
});
describe('getFilteredParamInfo()', function () {
it('should return param info', function () {
var flapjack = function (one, three, four, $scope) {
// @module({ "client": { "one": "two" } })
$scope.blah = one + three + four;
};
var context = _.extend({getParamInfo: transformer.getParamInfo}, annotationHelper);
var expected = {
converted: ['two', 'three', 'four'],
list: ['one', 'three', 'four'],
ngrefs: []
};
var actual = transformer.getFilteredParamInfo.call(context, flapjack, null);
taste.should.exist(actual);
actual.should.deep.equal(expected);
});
});
describe('getModuleBody()', function () {
it('should return the entire string if it cant find a opening/closing curly in the string', function () {
var flapjack = 'FooBarBooRamenMunchkinDonutWorldCup';
var expected = 'FooBarBooRamenMunchkinDonutWorldCup';
var actual = transformer.getModuleBody(flapjack);
actual.should.equal(expected);
});
it('should extract everything inside the curly brackets of a module without function declaration', function () {
var flapjack = 'Everything inside of the curly brackets {GetHuman is frickin awesome} will be extracted';
var expected = 'GetHuman is frickin awesome';
var actual = transformer.getModuleBody(flapjack);
actual.should.equal(expected);
});
it('should replace new line character with a new line + tab character', function () {
var flapjack = 'function getHuman() {\nvar latePenalty = munchkin(25 Count)}';
var expected = '\n\tvar latePenalty = munchkin(25 Count)';
var actual = transformer.getModuleBody(flapjack);
actual.should.equal(expected);
});
});
});
|
'use strict';
/* Services */
myApp.factory('mockDetailService', function($http, $q) {
return {
getData : function() {
var defer=$q.defer();
$http({method: 'GET', url: 'data/mockData.json'}).success(function(data) {
defer.resolve(data);
});
return defer.promise;
}
}
});
|
/*
* Wegas
* http://wegas.albasim.ch
*
* Copyright (c) 2013 School of Business and Engineering Vaud, Comem
* Licensed under the MIT License
*/
/**
* @fileoverview
* @author Cyril Junod
*/
YUI.add('wegas-menu', function(Y) {
'use strict';
var WegasMenu,
CONTENT_BOX = "contentBox",
tooltipTrigger = "wegas-tooltip-trigger";
WegasMenu = Y.Base.create("wegas-menu", Y.Widget, [], {
BOUNDING_TEMPLATE: "<div></div>",
CONTENT_TEMPLATE: null,
nodeInstances: null,
eventInstances: null,
clickHandler: null,
initializer: function() {
this.nodeInstances = [];
this.eventInstances = [];
this.publish("itemClick", {
emitFacade: true,
bubbles: true
});
},
syncUI: function() {
this.buildMenu(this.get("items"), this.get(CONTENT_BOX));
},
bindUI: function() {
this.clickHandler = this.get(CONTENT_BOX).delegate('click', function(e) {// Listen for click events on the table
e.stopImmediatePropagation();
this.fire("itemClick", {
data: e.currentTarget.item.data,
params: this.get("params")
});
}, 'li', this);
if (this.get("eventTarget")) {
this.addTarget(this.get("eventTarget"));
}
},
destructor: function() {
this.clickHandler.detach();
for (var n in this.nodeInstances) {
this.nodeInstances[n].destroy();
}
},
buildMenu: function(items, node) {
var listItem, item, content = Y.Node.create("<ul></ul>");
for (var n in this.nodeInstances) {
this.nodeInstances[n].destroy();
}
node.empty();
for (var i in items) {
item = items[i];
listItem = this.itemCreator(item);
if (item.items) {
this.buildMenu(item.items, listItem);
}
content.append(listItem);
this.nodeInstances.push(listItem);
}
node.append(content);
},
itemCreator: function(item) {
//TODO: Tooltip
var node = Y.Node.create("<li><div>" + (item.cssClass ? "<span class='menu-icon " + item.cssClass + "'></span>" : "") + "<span>" + (item.label ? item.label : "") + "</span></div></li>"),
divNode = node.one("div");
node.item = item;
node.addClass(this.getClassName("itemlist", this.get("horizontal") ? "horizontal" : "vertical"));
if (item.tooltip) {
divNode.addClass(tooltipTrigger);
divNode.setAttribute("title", item.tooltip);
}
return node;
}
}, {
NAME: "wegas-menu",
CSS_PREFIX: "wegas-menu",
ATTRS: {
eventTarget: {
value: null
},
items: {
validator: Y.Lang.isArray
},
horizontal: {
value: false
},
params: {// Given input params returned with the click event, a reference for instance
value: null
}
}
});
Y.namespace('Wegas').WegasMenu = WegasMenu;
});
|
'use strict'
const generateDeployment = (overrides = {}) => ({
id: 'Deployments-123',
comments: 'Test deployment from node script',
created: '2017-01-01T00:00:00+0000',
environmentId: 'Environments-123',
forcePackageDownload: false,
forcePackageRedeployment: false,
formValues: {},
lastModifiedBy: 'email@acme.com',
lastModifiedOn: '2017-01-01T00:00:00+0000',
links: {},
name: 'Deploy to DEV-SERVER',
projectId: 'Projects-123',
queueTime: null,
releaseId: 'Releases-123',
skipActions: [],
specificMachineIds: [],
taskId: 'ServerTasks-123',
useGuidedFailure: false,
...overrides
})
module.exports = { generateDeployment }
|
'use strict';
var Promise = require('bluebird');
var errors = require('./errors');
/**
* Get folder from the cordova file system
* @param {Object} fs Instance of the cordova file system
* @param {String} path Path to the folder to be fetched by cordova
* @param {Object} options Options for the cordova File API
* @return {Promise}
*/
function getFolder(fs, path, options) {
return new Promise(function (resolve, reject) {
fs.getDirectory(path, options, resolve, function (err) {
return reject(errors.create(errors.GET_FOLDER, 'Error when getting folder at path ' + path + ' Error: ' + JSON.stringify(err)));
});
});
}
module.exports = getFolder;
|
/*global html,isHostMethod,getEventTarget */
/*
For browsers that can capture
*/
var delegateBlurListener;
if(html && isHostMethod(html, 'addEventListener')){
delegateBlurListener = function(el, fn, fnDelegate) {
var listener = function(e) {
var currentTarget = fnDelegate(el, getEventTarget(e));
if(currentTarget) {
fn.call(currentTarget, e, currentTarget, el);
}
};
el.addEventListener('blur', listener, true);
return listener;
};
}
|
(function() {
var hasRetinafyableSrc, isAlreadyRetinafied, isRetinaDisplay, retinaImageSrc, swapToRetinaImg;
isRetinaDisplay = function() {
var mediaQuery;
mediaQuery = ['(-webkit-min-device-pixel-ratio: 1.5)', '(min--moz-device-pixel-ratio: 1.5)', '(-o-min-device-pixel-ratio: 3/2)', '(min-resolution: 1.5dppx)'].join(',');
return window.devicePixelRatio > 1 || (window.matchMedia && window.matchMedia(mediaQuery).matches);
};
hasRetinafyableSrc = function($element) {
return $element.attr('src') || /url\(/.test($element.css('background-image'));
};
isAlreadyRetinafied = function($element, settings) {
var imageSrc;
imageSrc = $element.attr('src') || $element.css('background-url');
return new RegExp("(.+)(" + settings.retina_suffix + "\\.\\w{3,4})").test(imageSrc);
};
retinaImageSrc = function($element, settings) {
var imageSrc, rawBackground;
if ($element.attr('src')) {
imageSrc = $element.attr("src");
} else {
rawBackground = $element.css("background-image").replace(/(.+)(\.\w{3,4})$/, "$1" + settings.retina_suffix + "$2");
imageSrc = rawBackground.substring(4, rawBackground.length - 1).replace(/"/g, '');
}
return imageSrc.replace(/(.+)(\.\w{3,4})/, "$1" + settings.retina_suffix + "$2");
};
swapToRetinaImg = function($element, settings) {
if ($element.attr('src')) {
return $element.attr("src", retinaImageSrc($element, settings));
} else {
return $element.css("background-image", "url(" + (retinaImageSrc($element, settings)) + ")");
}
};
$.fn.retinaify = function(options) {
var settings;
settings = $.extend({
retina_suffix: '@2x'
}, options);
if (isRetinaDisplay()) {
this.each(function() {
var $element;
$element = $(this);
if (hasRetinafyableSrc($element) && !isAlreadyRetinafied($element, settings)) {
return $('<img>').attr("src", retinaImageSrc($element, settings)).load(function() {
return swapToRetinaImg($element, settings);
});
}
});
}
return this;
};
}).call(this);
|
module.exports = (basePath, authorize) => {
const req = require('../util/req')(authorize);
const util = require('../util/util');
const campaigns = require('./campaigns.js')(basePath, authorize);
/**
* Get all Campaign Scripts
*
* http://docs.oracle.com/cloud/latest/marketingcs_gs/OMCGF/op-sites-%7Bsite-id%7D-%7Bconfiguration%7D-campaigns-%7Bcampaign-id%7D-scripts-get.html
*
* Possible options:
* -----------------
* `siteId` (optional if `siteName` provided) - ID of the site to be fetched
* `siteName` (optional if `siteId` provided) - name of the site to be fetched
* `campaignId` (optional if `campaignName` provided) - ID of the campaign to be fetched
* `campaignName` (optional if `campaignId` provided) - name of the campaign to be fetched
*
* Get all Scripts of the given Campaigns;
* `siteId` has priority over the `siteName`.
*
* @param {Object} options
* @return {Promise}
*/
const get = (options = {}) => {
var {siteId, siteName, campaignId, campaignName} = options;
if (!siteId && !siteName) {
return Promise.reject({ error: '`siteId` or `siteName` must be provided!' });
}
if (!campaignId && !campaignName) {
return Promise.reject({ error: '`campaignId` or `campaignName` must be provided!' });
}
return campaigns.get({siteId, siteName})
.then(campaigns => {
var campaign = !campaignId ?
util.getByName(campaigns, campaignName) :
util.getById(campaigns, campaignId);
var promise = req.get(
`${basePath}/sites/${campaign.siteId}/sandbox/campaigns/${campaign.id}/scripts`,
{campaignId: campaign.id});
return promise;
});
};
/**
* Create Campaign Script
*
* http://docs.oracle.com/cloud/latest/marketingcs_gs/OMCGF/op-sites-%7Bsite-id%7D-%7Bconfiguration%7D-campaigns-%7Bcampaign-id%7D-scripts-post.html
*
* Possible options:
* -----------------
* `siteId` (optional if `siteName` provided) - ID of the site to be fetched
* `siteName` (optional if `siteId` provided) - name of the site to be fetched
* `campaignId` (optional if `campaignName` provided) - ID of the campaign to be fetched
* `campaignName` (optional if `campaignId` provided) - name of the campaign to be fetched
*
* `name` (required) - campaign name
* `content` (required) - campaign script content
* `description` (optional) - campaign description
*
* Create new Element for the given campaign;
* `siteId` has priority over the `siteName`.
* `campaignId` has priority over the `campaignName`.
*
* @param {Object} options
* @return {Promise}
*/
const create = (options = {}) => {
var {siteId, siteName, campaignId, campaignName, name, description, content} = options;
var data = { name, description, content };
if (!siteId && !siteName) {
return Promise.reject({ error: '`siteId` or `siteName` must be provided!' });
}
if (!campaignId && !campaignName) {
return Promise.reject({ error: '`campaignId` or `campaignName` must be provided!' });
}
if (!data.name) {
return Promise.reject({ error: '`name` must be provided!' });
}
if (!data.content) {
return Promise.reject({ error: '`content` must be provided!' });
}
return campaigns.get({siteId, siteName})
.then(campaigns => {
var campaign = !campaignId ?
util.getByName(campaigns, campaignName) :
util.getById(campaigns, campaignId);
var promise = req.post(
`${basePath}/sites/${campaign.siteId}/sandbox/campaigns/${campaign.id}/scripts`,
data
);
return promise;
});
};
/**
* Update Campaign Script by ID/Name
*
* http://docs.oracle.com/cloud/latest/marketingcs_gs/OMCGF/op-sites-%7Bsite-id%7D-sandbox-campaigns-%7Bcampaign-id%7D-scripts-%7Bscript-id%7D-put.html
*
* Possible options:
* -----------------
* `siteId` (optional if `siteName` provided) - ID of the site to be fetched
* `siteName` (optional if `siteId` provided) - name of the site to be fetched
* `campaignId` (optional if `campaignName` provided) - ID of the campaign to be fetched
* `campaignName` (optional if `campaignId` provided) - name of the campaign to be fetched
*
* `name` - campaign name
* `description` - campaign description
* `content` - campaign description
*
* Update Campaign Script for the given campaign;
* `siteId` has priority over the `siteName`.
* `campaignId` has priority over the `campaignName`.
*
* @param {Object} options
* @return {Promise}
*/
const update = (options = {}) => {
var {siteId, siteName, campaignId, campaignName, scriptId, scriptName, name, description, type, isPrimary} = options;
var data = util.getUpdatedData(options);
if (!siteId && !siteName) {
return Promise.reject({ error: '`siteId` or `siteName` must be provided!' });
}
if (!campaignId && !campaignName) {
return Promise.reject({ error: '`campaignId` or `campaignName` must be provided!' });
}
if (!scriptId && !scriptName) {
return Promise.reject({ error: '`scriptId` must be provided!' });
}
return campaigns.get({siteId, siteName})
.then(campaigns => {
var campaign = !campaignId ?
util.getByName(campaigns, campaignName) :
util.getById(campaigns, campaignId);
if (!scriptId) {
return get({siteId: campaign.siteId, campaignId: campaign.id})
.then(scripts => {
var script = util.getByName(scripts, scriptName);
return req.put(
`${basePath}/sites/${campaign.siteId}/sandbox/campaigns/${campaign.id}/scripts/${script.id}`,
data
);
});
} else {
return req.put(
`${basePath}/sites/${campaign.siteId}/sandbox/campaigns/${campaign.id}/scripts/${scriptId}`,
data
);
}
});
};
return {
get,
create,
update
}
}
|
/*jslint browser: true */
(function() {
"use strict";
var originalTitle = document.title,
originalURL = document.location.href.replace(document.location.search, "") + "?name=",
qShareURL = document.querySelector("section a");
/**
* Generate a sharing URL.
* @param {String} name The person's name.
*/
function makeShareLink(name) {
qShareURL.innerHTML = originalURL + decodeURIComponent(name);
qShareURL.href = originalURL + encodeURIComponent(name);
}
/**
* Update the page title with the person's name.
* @param {String} name The person's name.
*/
function updatePageTitle(name) {
document.title = `${decodeURIComponent(name)} ${originalTitle}`;
}
// Initial setup of the share link
qShareURL.innerHTML = originalURL;
qShareURL.href = originalURL;
// Update everything on keypress
document.querySelector("header input").addEventListener("input", function() {
updatePageTitle(this.value);
makeShareLink(this.value);
});
window.onload = function() {
var qs = window.location.search;
// No query string was given
if (!/^\?name=.+?$/.test(qs)) {
return false;
}
// Get just the name and update all displays
var name = qs.split("=")[1];
updatePageTitle(name);
makeShareLink(name);
document.querySelector("header input").value = decodeURIComponent(name);
// Test for HTML5 audio compatibility, preferring MP3 audio
// Taken from http://diveintohtml5.info/everything.html#audio-mp3
var _a = document.createElement("audio");
var audioFile = (!!(_a.canPlayType && _a.canPlayType("audio/mpeg;").replace(/no/, ""))) ?
"audio/congratulations.mp3" : "audio/congratulations.ogg";
var congrats = new Audio(audioFile);
congrats.load();
congrats.play();
};
}());
|
Lava.define(
'Lava.system.DataView',
/**
* Holds a subset of values from {@link Lava.system.Enumerable}, preserving item UIDs.
* Can remove, filter and sort existing values, but can't be used to add new values.
*
* @lends Lava.system.DataView#
* @extends Lava.system.CollectionAbstract#
*/
{
Extends: 'Lava.system.CollectionAbstract',
/**
* To tell other classes that this is instance of Enumerable
* @type {boolean}
* @const
*/
isDataView: true,
/**
* The existing collection, which provides data for this instance
* @type {Lava.system.CollectionAbstract}
*/
_data_source: null,
/**
* Create DataView instance
* @param {Lava.system.CollectionAbstract} data_source
*/
init: function(data_source) {
this.guid = Lava.guid++;
data_source && this.refreshFromDataSource(data_source);
},
/**
* Refresh the DataView from it's Enumerable
*/
refresh: function() {
this._data_names = this._data_source.getNames();
this._data_values = this._data_source.getValues();
this._data_uids = this._data_source.getUIDs();
this._count = this._data_uids.length;
this._fire('collection_changed');
},
/**
* Set new `_data_source`
* @param {Lava.system.CollectionAbstract} data_source
*/
setDataSource: function(data_source) {
if (Lava.schema.DEBUG && !data_source.isCollection) Lava.t("Wrong argument supplied for DataView constructor");
this._data_source = data_source;
},
/**
* Set `_data_source` and refresh from it
* @param {Lava.system.CollectionAbstract} data_source
*/
refreshFromDataSource: function (data_source) {
this.setDataSource(data_source);
this.refresh();
},
/**
* Get `_data_source`
* @returns {Lava.system.CollectionAbstract}
*/
getDataSource: function() {
return this._data_source;
}
});
|
(function () {
'use strict';
describe('Magicitems List Controller Tests', function () {
// Initialize global variables
var MagicitemsListController,
$scope,
$httpBackend,
$state,
Authentication,
MagicitemsService,
mockMagicitem;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _MagicitemsService_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
$state = _$state_;
Authentication = _Authentication_;
MagicitemsService = _MagicitemsService_;
// create mock article
mockMagicitem = new MagicitemsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Magicitem Name'
});
// Mock logged in user
Authentication.user = {
roles: ['user']
};
// Initialize the Magicitems List controller.
MagicitemsListController = $controller('MagicitemsListController as vm', {
$scope: $scope
});
// Spy on state go
spyOn($state, 'go');
}));
describe('Instantiate', function () {
var mockMagicitemList;
beforeEach(function () {
mockMagicitemList = [mockMagicitem, mockMagicitem];
});
it('should send a GET request and return all Magicitems', inject(function (MagicitemsService) {
// Set POST response
$httpBackend.expectGET('api/magicitems').respond(mockMagicitemList);
$httpBackend.flush();
// Test form inputs are reset
expect($scope.vm.magicitems.length).toEqual(2);
expect($scope.vm.magicitems[0]).toEqual(mockMagicitem);
expect($scope.vm.magicitems[1]).toEqual(mockMagicitem);
}));
});
});
}());
|
module.exports = function() {
return '$011@M@7AN';
}
|
var crypto = require ('crypto');
var async = require ('async');
var mongodb = require ('mongodb');
var mailgun = require ('mailgun-js');
var Action = require ('substation').Action;
var infosex = require ('infosex');
var uid = infosex.uid.craft;
var session = infosex.session.craft;
var UsernameCollection, ConfirmationCollection, Mailer;
module.exports = new Action ({
hideSchema: true,
bodySchema: {
properties: {
email: {
type: 'string',
format: 'email'
},
username: {
type: 'string',
minLength: 3,
maxLength: 32
},
password: {
minLength: 8,
maxLength: 128
},
confirm: {
minLength: 8,
maxLength: 128
},
homepage: {
invalid: true
},
wasps: {
type: 'string',
equals: 'on'
}
},
required: [ 'email', 'username', 'password', 'confirm', 'wasps' ]
},
setup: function (station, config, callback) {
UsernameCollection = station.UsernameCollection;
ConfirmationCollection = station.ConfirmationCollection;
Mailer = mailgun ({
apiKey: station.config.mailgunKey,
domain: station.config.mailgunDomain
});
callback();
}
}, function (station, agent, request, reply) {
if (agent.isLoggedIn) {
reply.content ({ error:"you are already logged in" });
return reply.done (403);
}
var passHash; // calculated synchronously after the call to system random begins
var userID, confirmID;
async.parallel ([
function (callback) {
console.log ('getting uid');
uid (function (newID) {
userID = newID;
callback();
});
},
function (callback) {
console.log ('getting confirm id');
session (function (newID) {
confirmID = newID;
callback();
});
}
], function(){
console.log ('updating username');
var now = (new Date()).getTime();
UsernameCollection.findAndModify ({
name: request.body.username,
email: request.body.email,
pass: passHash
}, { name:1 }, {
$setOnInsert: {
_id: userID,
confirm: confirmID
},
$push: {
sent: { $each:[ now ], $slice:-4 }
}
}, {
upsert: true
}, function (err, oldRecord) {
console.log ('old username', err, oldRecord);
if (err)
return reply.done (502);
var useThisTarget = oldRecord ? oldRecord._id : userID;
// new username created - we can wait for email confirmation to create the User record
ConfirmationCollection.insert ({ _id:confirmID, target:useThisTarget }, function (err) {
console.log ('new confirmation', err);
if (err)
return reply.done (502);
// respond early
reply.done (200);
// send the email
Mailer.messages().send ({
from: "no-reply@sublayer.io",
to: request.body.email,
subject: "Confirm Email Address",
text: "Somebody (hopefully you) registered this email address as a user"
+ " account at sublayer.io. If it was you, confirm that you control this inbox"
+ " by clicking this link (or pasting it into a browser):"
+ " http://sublayer.io/confirm/"
+ confirmID
}, function (err, body) {
if (err)
station.logger.error (
{ err:err, email:request.body.email },
'mail sending error'
);
else
station.logger.info ({ email:request.body.email }, 'sent confirmation email');
});
});
});
});
var hasher = crypto.createHash ('sha256');
hasher.update (request.body.password);
hasher.update ('sublayer.io');
hasher.update (request.body.username);
passHash = hasher.digest ('base64');
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:c13684399f6bccf03e8549978a02ae41368b1f0ff57b48152e953f54a734e5dc
size 683
|
window.onload = function () {
|
module.exports = class VertexSocketDataError extends Error {
constructor(message, from) {
super(message);
this.name = this.constructor.name;
this.from = from;
}
};
|
// @flow
export const TOAST_MAKE = 'TOAST_MAKE';
export const TOAST_SHOW = 'TOAST_SHOW';
export const TOAST_DISMISS = 'TOAST_DISMISS';
type ToastProps = {
action?: (event: Event) => void, // onClick handler
actionLabel?: React$Element<*>,
dismissable?: boolean,
autodismiss?: boolean,
};
export const makeToast = (payload: ToastProps) => ({
type: TOAST_MAKE,
payload,
});
export const showToasts = () => ({ type: TOAST_SHOW });
|
{
expect(request.url).toBe("/foo");
expect(request.method).toBe("POST");
done();
}
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v1c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-1h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm-1 14H4c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h16c.55 0 1 .45 1 1v10c0 .55-.45 1-1 1zm-5.52-5.13l-3.98 2.28c-.67.38-1.5-.11-1.5-.87V8.72c0-.77.83-1.25 1.5-.87l3.98 2.28c.67.39.67 1.35 0 1.74z"
}), 'OndemandVideoRounded');
|
'use strict';
/**
* @ngdoc function
* @name austinFiberApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the austinFiberApp
*/
angular.module('austinFiberApp')
.controller('MainCtrl', function($scope, $http) {
$scope.apartments = [];
$scope.aptPromise = $http({
url: '/ajax/apartments',
method: 'GET'
}).success(function(data) {
$scope.apartments = _.map(data.apartments, function(apt) {
var a = {
id: apt.id,
name: apt['Building Name'],
address: apt['Building Address'],
date: moment.unix(apt.added_on).format("dddd, MMMM Do"),
added_on: apt.added_on
};
if (apt['Property Website'].length > 0) {
var url = apt['Property Website'];
a.site = (url.indexOf('http://') == 0 || url.indexOf('https://') == 0) ? url : 'http://' + url;
} else {
a.site = 'http://www.google.com/search?q=' + apt['Building Name'];
}
return a;
});
$scope.last_update = moment.unix(data.last_update).format("dddd, MMMM Do, LT");
});
});
|
define(["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
});
//# sourceMappingURL=Layer.Props.js.map
|
import uniqueRandomArray from 'unique-random-array';
const warcraftNames = require('./warcraft-names.json');
const mainExport = {
all: warcraftNames,
random: uniqueRandomArray(warcraftNames),
};
export default mainExport;
module.exports = mainExport; // for CommonJS compatibility
|
var baseClamp = require('./_baseClamp'),
toInteger = require('./toInteger'),
toString = require('./toString');
/**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to search.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search from.
* @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
* @specs
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = toString(string);
target = typeof target == 'string' ? target : (target + '');
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
position -= target.length;
return position >= 0 && string.indexOf(target, position) == position;
}
module.exports = endsWith;
|
import hi, { five } from './two';
console.log( five );
hi();
|
/* eslint-disable no-param-reassign */
import store from './store';
import { getDog } from './actions';
/*
* Function: render
* Description: Renders the given state to the given HTML DOM node
*/
const render = (mount, state) => {
if (state.pending) {
mount.innerHTML = 'Loading...';
} else if (state.data) {
mount.innerHTML = `<img src=${state.data.message} />`;
}
};
/*
* Function: initializes
* Description: Renders the initial state of the example
*/
const initialize = () => {
const mount = document.querySelector('#mount');
// Load the post when button is clicked
const button = document.querySelector('#load');
button.addEventListener('click', () => store.dispatch(getDog()));
render(mount, {});
store.subscribe(() => render(mount, store.getState()));
};
initialize();
|
/**
* https://github.com/facebook/react-native/blob/master/Libraries/ReactIOS/requireNativeComponent.js
*/
import React from 'react'; /* eslint no-unused-vars:0 */
import createReactClass from 'create-react-class';
function requireNativeComponent(viewName, componentInterface, extraConfig) {
return createReactClass({
displayName: viewName,
render() {
return null;
},
});
}
module.exports = requireNativeComponent;
|
module.exports = function(f$bec4494a) {
// --- fest prolog ---
var v$bec4494a$templates = {};
// --- end of fest prolog ---
return function(json) {
return f$bec4494a('#root', {}, [f$bec4494a('div', {}, [f$bec4494a('fest:attributes', {}, [])]), f$bec4494a('div', {}, [f$bec4494a('fest:attributes', {}, [(function() {
var v$bec4494a$1 = [];
if (true) {
v$bec4494a$1.push();
} else {
v$bec4494a$1.push();
}
return v$bec4494a$1;
}()), (function() {
var v$bec4494a$2 = [];
if (false) {
v$bec4494a$2.push();
} else {
v$bec4494a$2.push();
}
return v$bec4494a$2;
}())])])]);
};;
};
|
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var react = require('gulp-react');
var plumber = require('gulp-plumber');
var concat = require('gulp-concat');
var runSequence = require('gulp-run-sequence');
gulp.task('default', function(cb){
runSequence(
'compile-jsx',
'browserify',
cb);
})
gulp.task('compile-jsx', function(){
return gulp.src([
'./react/**/*.jsx'
])
.pipe(plumber())
.pipe(react({ addPragma: false }))
.pipe(gulp.dest('./build/'));
});
gulp.task('browserify', function(){
return gulp.src(['./build/index.js'])
.pipe(plumber())
.pipe(browserify({
insertGlobals: true,
debug: false
}))
.pipe(concat('index.js'))
.pipe(gulp.dest('./'));
});
|
'use strict';
var DelimiterParser = require('./parser-delimiter');
var inherits = require('inherits');
function ReadlineParser(options) {
if (!(this instanceof ReadlineParser)) {
return new ReadlineParser(options);
}
options = options || {};
if (options.delimiter === undefined) {
options.delimiter = new Buffer('\n', 'utf8');
}
DelimiterParser.call(this, options);
var encoding = options.encoding || 'utf8';
this.delimiter = new Buffer(options.delimiter, encoding);
this.setEncoding(encoding);
}
inherits(ReadlineParser, DelimiterParser);
module.exports = ReadlineParser;
|
module.exports = function(key, threshold, dataSources, rename){
var dataSource = dataSources.get(key);
var newName = rename ? rename : key + "Heaviside";
var newSource = dataSource.map(function(val){
if(val >= threshold){
return 1;
}
return 0;
});
dataSources.get("creationMap").set(newName, key, [key, threshold], "heaviside");
dataSources.set(newName, newSource);
}
module.exports.initialize = function(dataSources){
dataSources.get("translations").set("heaviside", module.exports);
}
|
// generated by Neptune Namespaces v4.x.x
// file: tests/Art.Engine/Core/Layout/index.js
(module.exports = require('./namespace'))
.addModules({
CommentInspiredLayout: require('./CommentInspiredLayout'),
TextElement: require('./TextElement')
});
require('./Flex');
require('./Flow');
require('./Functional');
|
define(function(require) {
'use strict';
var ng = require('angular');
require('angular-route');
/**
* Home Module
*
* ### Overview
*
* This is a long-form description of the home module. Here, things such as the available controllers, directives,
* routes, services, filters and so forth should be documented. Generally speaking, these kinds of modules should
* only include controllers, templates and routes. Specialized directives are also okay, although it's usually
* better to write directives that are reusable, rather than highly specialized ones. Those reusable directives
* belong as root level modules in the 'app/modules' directory, rather than under the main module.
*
* Services are also okay, but exposing them to other modules can be tricky, especially if it requires two modules
* to depend on each other. Since services are typically meant to share state between components (they are
* singletons after all) it's best to give special care to their design, and extrapolate them into a services
* sub-module or stand-alone module. In doing so, services can be readily shared between modules so long as
* developers take care and understand the consequences that the coupling can create.
*
* @name app.home
* @requires 'angular-route'
*/
var homeModule = ng.module('app.home', [
'ngRoute'
]);
/**
* @requires HomeControllerTemplate.html
*/
var homeControllerTemplate = require('text!./HomeControllerTemplate.html');
var mapControllerTemplate = require('text!../../map/MapTemplate.html');
/**
* Home module configuration
*
* ### Routes
*
* The home module utilizes the following routes:
*
* - '/'
* - Controller: HomeController.js
* - Template: HomeControllerTemplate.html
*
*/
homeModule.config(function($routeProvider) {
$routeProvider
.when('/streams', {
template: homeControllerTemplate,
controller: 'HomeController'
})
.when('/streams/:streamId', {
template: homeControllerTemplate,
controller: 'HomeController'
})
.otherwise({
redirectTo: '/streams'
});
});
return homeModule;
});
|
Game.Menu = function (game) {
this.music = null
this.playButton = null
}
Game.Menu.prototype = {
init: function (problem_set) {
this.problem_set = problem_set
},
create: function () {
title = this.game.add.text(this.game.world.centerX,75,'Add it up!',{font:'80px Arial', fill:'#FFFFFF', align:'center'})
title.anchor.x = 0.5
button = this.add.button(this.game.world.centerX, 175, 'lightning', function () {this.state.start('Instructions', true, false, this.problem_set);}, this);
button.scale.setTo(0.5,0.5)
button.anchor.x = 0.5
},
}
|
'use strict';
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var debug = require('gulp-debug');
var rename = require('gulp-rename');
var stripDebug = require('gulp-strip-debug');
var gutil = require('gulp-util');
var clean = require('gulp-clean');
var runSequence = require('run-sequence');
var gutil = require('gulp-util');
var through = require('through2');
var replace = require('gulp-replace');
var tap = require('gulp-tap');
var bump = require('gulp-bump');
var shell = require('gulp-shell');
var karma = require('karma').server;
var connect = require('gulp-connect');
var gulpProtractor = require("gulp-protractor").protractor;
var angularJsdoc = require('angular-jsdoc');
var bumpVersion = function(type) {
type = type || 'patch';
var version = '';
gulp.src(['./bower.json', './package.json'])
.pipe(bump({type: type}))
.pipe(gulp.dest('./'))
.pipe(tap(function(file, t) {
version = JSON.parse(file.contents.toString()).version;
})).on('end', function() {
var color = gutil.colors;
gulp.src('')
.pipe(shell([
'git commit --all --message "Version ' + version + '"',
(type != 'patch' ? 'git tag --annotate "v' + version + '" --message "Version ' + version + '"' : 'true')
], {ignoreErrors: false}))
.pipe(tap(function() {
gutil.log(color.green("Version bumped to ") + color.yellow(version) + color.green(", don't forget to push!"));
}));
});
};
gulp.task('clean', function() {
return gulp.src('build')
.pipe(clean({force: true}));
});
gulp.task('build-js', function() {
return gulp.src([
'app.js',
'services/*.js',
'directives/*.js'
])
.pipe(concat('ng-map.debug.js'))
.pipe(gulp.dest('build/scripts'))
.pipe(stripDebug())
.pipe(concat('ng-map.js'))
.pipe(gulp.dest('build/scripts'))
.pipe(uglify())
.pipe(rename('ng-map.min.js'))
.pipe(gulp.dest('build/scripts'))
.on('error', gutil.log);
});
gulp.task('docs', function() {
angularJsdoc(['directives', 'services'], {destination: 'build/docs'});
});
gulp.task('bump', function() { bumpVersion('patch'); });
gulp.task('bump:patch', function() { bumpVersion('patch'); });
gulp.task('bump:minor', function() { bumpVersion('minor'); });
gulp.task('bump:major', function() { bumpVersion('major'); });
gulp.task('build', function(callback) {
runSequence('clean', 'build-js', 'test', 'docs', callback);
});
gulp.task('test', function (done) {
karma.start({
configFile: __dirname + '/config/karma.conf.js',
singleRun: true
}, done);
});
gulp.task('testapp-server', function() {
connect.server({
root: __dirname + '/testapp',
port: 8888
});
});
gulp.task('test-e2e', ['testapp-server'], function() {
gulp.src([__dirname + "/spec/e2e/*_spec.js"])
.pipe(gulpProtractor({
configFile: __dirname + "/config/protractor.conf.js",
args: [
'--baseUrl', 'http://localhost:8888'
]
}))
.on('error', function(e) {
console.log([
'------------------------------------------------------------------------------------',
'For first-time user, we need to update webdrivers',
'$ node_modules/gulp-protractor/node_modules/protractor/bin/webdriver-manager update',
'------------------------------------------------------------------------------------'
].join('\n'));
throw e;
})
.on('end', function() { // when process exits:
connect.serverClose();
});
});
|
import Redact from "../lib/Redact";
import { expect, sinon, TestUtils } from "./NexmoTestUtils";
describe("Redact", function() {
beforeEach(function() {
this.httpClientStub = TestUtils.getHttpClient();
sinon.stub(this.httpClientStub, "request");
this.redact = new Redact(TestUtils.getCredentials(), {
api: this.httpClientStub
});
});
afterEach(function() {
this.httpClientStub.request.restore();
});
describe("#transaction", function() {
it("should work with no optional fields", function() {
return expect(this.redact)
.method("transaction")
.withParams("ABC123", "voice")
.to.post.withJsonBody({ id: "ABC123", product: "voice" })
.to.url(`${Redact.PATH}/transaction`);
});
it("should pass through optional fields", function() {
return expect(this.redact)
.method("transaction")
.withParams("ABC123", "voice", { type: "outbound" })
.to.post.withJsonBody({
id: "ABC123",
product: "voice",
type: "outbound"
})
.to.url(`${Redact.PATH}/transaction`);
});
});
});
|
#!/usr/bin/env node
var gulp = require('gulp'),
path = require('path'),
gulpfilePath = path.resolve(process.cwd(), process.argv[2] || 'gulpfile.js');
require(gulpfilePath);
console.log('digraph GulpTasks {');
for (var name in gulp.tasks) {
for (var i = 0; i < gulp.tasks[name].dep.length; i++) {
console.log(' "' + name + '" -> "' + gulp.tasks[name].dep[i] + '";');
}
}
console.log('}');
|
/* eslint-disable no-undef */
export const IS_BROWSER = (typeof window !== 'undefined' && window !== null) ||
(process.env.TEST_BROWSER != null);
/* eslint-enable no-undef */
export const LEVEL_NUM_TO_STR = {
10: 'TRACE',
20: 'DEBUG',
30: 'INFO',
40: 'WARN',
50: 'ERROR',
60: 'FATAL',
};
export const LEVEL_STR_TO_NUM = {
TRACE: 10,
DEBUG: 20,
INFO: 30,
WARN: 40,
ERROR: 50,
FATAL: 60,
};
// WebSockets
export const WS_NAMESPACE = '/STORYBOARD';
// Filters
export const FILTER_KEY = 'STORYBOARD';
export const DEFAULT_FILTER = '*:DEBUG';
|
'use strict';
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Redirect to home view when route not found
$urlRouterProvider.otherwise('/');
// Home state routing
$stateProvider.
state('home', {
url: '/',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('sucesso', {
url: '/sucesso',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('roupas', {
url: '/roupas',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('eletronicos', {
url: '/eletronicos',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('top', {
url: '/top',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('admin', {
url: '/admin',
templateUrl: 'modules/landingpages/views/list-landingpages.client.view.html'
})
;
}
]);
|
process.env.NODE_ENV = 'test';
process.setMaxListeners(process.env.MAX_LISTENERS || 0);
require('sugar');
require('colors');
module.exports.chai = require('chai');
module.exports.chai.Assertion.includeStack = true;
module.exports.chai.use(require('chai-http'));
module.exports.async = require('async');
module.exports.debug = console.log;
// module.exports.longjohn = require('longjohn');
// module.exports.longjohn.async_trace_limit = 3;
// REVIEW: http://chaijs.com/plugins
module.exports.flag = function(value, default_value) {
if (typeof value === 'undefined') {
return (default_value === undefined) ? false : default_value;
} else {
return (/^1|true$/i).test('' + value); // ...to avoid the boolean/truthy ghetto.
}
};
module.exports.API = function() {
var app = function(req, res) {
res.writeHeader(200, {
'content-type': 'application/json',
'x-powered-by': 'connect'
});
res.end(JSON.stringify({hello: "world"}));
};
var api = require('connect')();
api.use(require('../').apply(this, arguments));
api.use(app);
return api;
};
|
'use strict';
var fs = require('fs');
var http = require('http');
var jwt = require('jsonwebtoken');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var _ = require('underscore');
var configParameter =require('./config.js');
var nodemailer = require('nodemailer');
var my_ejs = require('ejs');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'bacalhau',
password : '123456',
database : 'datahub'
});
var query_username = 'baca';
var new_user = {
name:'Isa',
lastname:'bacalhau',
username:'joaomarcusbacalhau@hotmail.com',
password:'123456',
application:'default'
};
pool.getConnection(function(err, connection) {
// Use the connection
if (err) throw err;
console.log('GET 1');
connection.query("SELECT * FROM Usuario WHERE uname=?",query_username ,function (error, results, fields)
{
if (error) throw error;
if(_.isEmpty(results))
{
console.log('Not Found!');
}
else
{
console.log('The result is: ', results);
}
});
connection.release();
// Handle error after the release.
if (err) throw err;
// Don't use the connection here, it has been returned to the pool.
});
console.log('Connection 2');
pool.getConnection(function(err, connection) {
// Use the connection
if (err) throw err;
console.log('GET 2');
connection.query("SELECT * FROM Usuario WHERE uname=?",query_username ,function (error, results, fields)
{
if (error) throw error;
if(_.isEmpty(results))
{
console.log('Not Found!');
}
else
{
console.log('The result is: ', results);
}
});
connection.release();
// Handle error after the release.
if (err) throw err;
// Don't use the connection here, it has been returned to the pool.
});
console.log('Connection 3');
pool.getConnection(function(err, connection) {
// Use the connection
if (err) throw err;
console.log('GET 3');
connection.query("SELECT * FROM Usuario WHERE uname=?",query_username ,function (error, results, fields)
{
if (error) throw error;
if(_.isEmpty(results))
{
console.log('Not Found!');
}
else
{
console.log('The result is: ', results);
}
});
connection.release();
// Handle error after the release.
if (err) throw err;
// Don't use the connection here, it has been returned to the pool.
});
console.log('Connection 4');
pool.getConnection(function(err, connection) {
// Use the connection
if (err) throw err;
console.log('GET 4');
connection.query("SELECT * FROM Usuario WHERE uname=?",query_username ,function (error, results, fields)
{
if (error) throw error;
if(_.isEmpty(results))
{
console.log('Not Found!');
}
else
{
console.log('The result is: ', results);
}
});
connection.release();
// Handle error after the release.
if (err) throw err;
// Don't use the connection here, it has been returned to the pool.
});
/*
pool.end(function (err) {
// all connections in the pool have ended
});
*/
|
define(function (require) {
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('util/backbone-helper');
var Hbs = require('handlebars');
var Mn = require('backbone.marionette');
var Q = require('q');
var Radio = require('backbone.radio');
var userChannel = Radio.channel('user');
var courseChannel = Radio.channel('course');
var pageChannel = Radio.channel('page');
var ModalHelpers = require('util/modal-helpers');
var template = require('text!ctemplates/headerStudentDropdownView.hbs');
var AddNewStudentView = require('app/addNewStudent');
var ModifyStudentView = require('app/modifyStudent');
var SelectStudentView = require('course/view/select-student-view');
var DeleteStudentView = require('course/view/delete-student-view');
var GroupStudentsView = require('course/view/group-students-view');
return Mn.ItemView.extend({
tagName: 'li',
template: Hbs.compile(template),
ui: {
newStudent: ".newStudent",
modifyStudent: ".modifyStudent",
deleteStudent: ".deleteStudent",
groupStudents: ".groupStudents",
mockData: ".mockData"
},
events: {
"click @ui.newStudent": "showNewStudent",
"click @ui.modifyStudent": "showModifyStudent",
"click @ui.deleteStudent": "showDeleteStudent",
"click @ui.groupStudents": "showGroupStudents",
"click @ui.mockData": "createMockGradeData"
},
initialize: function (options) {
this.model = courseChannel.request('current:course');
ModalHelpers.call(this);
},
showNewStudent: function (domEvent) {
//courseChannel.command('showAllCourses');
userChannel.request('user').then(function (user) {
var modalRegion = pageChannel.request('modalRegion');
modalRegion.show(new AddNewStudentView);
})
},
showModifyStudent: function (domEvent) {
//courseChannel.command('showUserCourses');
//userChannel.request('user').then(function(user) {
// var modalRegion = pageChannel.request('modalRegion');
// modalRegion.show(new ModifyStudentView);
//
//
//})
userChannel.request('user').then(function (user) {
courseChannel.request('select:student').then(function (selectedStudent) {
var modalRegion = pageChannel.request('modalRegion');
modalRegion.show(new ModifyStudentView({
'student': selectedStudent
}));
}).done()
})
},
showDeleteStudent: function (domEvent) {
userChannel.request('user').then(function (user) {
courseChannel.request('select:student').then(function (selectedStudent) {
var modalRegion = pageChannel.request('modalRegion');
modalRegion.show(new DeleteStudentView({
'student': selectedStudent
}));
}).done();
})
},
showGroupStudents: function (domEvent) {
//courseChannel.command('showUserCourses');
userChannel.request('user').then(function (user) {
var modalRegion = pageChannel.request('modalRegion');
modalRegion.show(new GroupStudentsView());
})
},
createMockGradeData: function () {
console.log('creating mock grade data...')
var students = this.model.students;
var assignments = this.model.assignments;
students.each(function (student) {
assignments.each(function (a) {
var rawScore = Math.round(70 + Math.random() * 30);
student.setGrade(a.id, rawScore);
})
})
}
});
});
|
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const assert = require("assert")
const EOL = require("os").EOL
const createSplitStream = require("../").createSplitStream
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
describe("split function", () => {
const patterns = [
[
"Hello",
[["Hel", "lo"], ["Hell", "o"], ["Hello"]], // x2.0; by 3, 4, 5
[["Hel", "lo"], ["Hell", "o"], ["Hello"]], // x1.5; by 3, 4, 5
],
[
"アイウエオ",
[["ア", "イ", "ウ", "エ", "オ"], ["アイ", "ウエ", "オ"], ["アイ", "ウエ", "オ"]],
[["アイ", "ウエ", "オ"], ["アイ", "ウエ", "オ"], ["アイウ", "エオ"]],
],
[
"アイウエオ",
[["アイウ", "エオ"], ["アイウエ", "オ"], ["アイウエオ"]],
[["アイウ", "エオ"], ["アイウエ", "オ"], ["アイウエオ"]],
],
[
"Hello, 世界",
[["Hel", "lo,", " 世", "界"], ["Hell", "o, ", "世界"], ["Hello", ", 世", "界"]],
[["Hel", "lo,", " 世", "界"], ["Hell", "o, ", "世界"], ["Hello", ", 世界"]],
],
[
"ひとつ、ふたつ。",
[["ひ", "と", "つ、", "ふ", "た", "つ。"], ["ひと", "つ、", "ふた", "つ。"], ["ひと", "つ、ふ", "たつ。"]],
[["ひと", "つ、", "ふた", "つ。"], ["ひと", "つ、ふ", "たつ。"], ["ひとつ", "、ふた", "つ。"]],
],
]
for (let i = 0; i < patterns[0][1].length; ++i) {
it(`should return ${
JSON.stringify([].concat.apply([], patterns.map(x => x[1][i])))
} if "${
patterns.map(x => x[0]).join("\\n")
}" was given with max ${3 + i} and ww 2.`, (next) => {
const stream = createSplitStream(3 + i)
const expected = [].concat.apply([], patterns.map(x => x[1][i]))
let j = 0
stream.on("data", (line) => {
assert(line === `${expected[j++]}${EOL}`)
})
stream.on("end", () => {
assert(j === expected.length)
next()
})
const text = patterns.map(x => x[0]).join("\n")
const middle = text.length / 2 | 0
stream.write(text.slice(0, middle))
stream.write(text.slice(middle))
stream.end()
})
}
for (let i = 0; i < patterns[0][2].length; ++i) {
it(`should return ${
JSON.stringify([].concat.apply([], patterns.map(x => x[2][i])))
} if "${
patterns.map(x => x[0]).join("\\n")
}" was given with max ${3 + i} and ww 1.5.`, (next) => {
const stream = createSplitStream(3 + i, 1.5)
const expected = [].concat.apply([], patterns.map(x => x[2][i]))
let j = 0
stream.on("data", (line) => {
assert(line === `${expected[j++]}${EOL}`)
})
stream.on("end", () => {
assert(j === expected.length)
next()
})
const text = patterns.map(x => x[0]).join("\n")
const middle = text.length / 2 | 0
stream.write(text.slice(0, middle))
stream.write(text.slice(middle))
stream.end()
})
}
})
|
//= Emmeline: Pure and Simple Javascript.
//> Tom Harding | thedigitalnatives.co.uk
import test from 'tape'
import { all } from '../../list'
test ('List.All', t => {
function isOdd () {
return this % 2 === 1
}
function * pass () {
yield 9
yield 7
yield 5
}
function * fail () {
yield 1
yield 3
yield 4
t.fail ('Short-circuiting')
}
t.ok
( [] :: all (isOdd)
, 'Empty list'
)
t.ok
( [1, 3, 5] :: all (isOdd)
, 'List pass'
)
t.notOk
( [2, 4, 6] :: all (isOdd)
, 'List failure'
)
t.notOk
( fail () :: all (isOdd)
, 'Generator failure'
)
t.ok
( pass () :: all (isOdd)
, 'Generator pass'
)
t.end ()
})
|
const { is, as } = require('describe-type');
const { env, flag } = require('../@/config');
const defaultFormats = ['iife', 'umd', 'amd', 'cjs'];
const target = (name, outputPath, format) => ({
sourcemap: env.MINIFY,
file: `${outputPath}.${format}${env.MINIFY ? '.min' : ''}.js`,
banner: env.SIGN ? flag : '',
indent: env.INDENT,
format,
name,
});
exports.parseFormats = ({ formats }) => {
formats = is.string(formats) ? [formats] : formats;
formats = as(Array, formats, defaultFormats);
return formats;
};
exports.hasFormat = (file, format) => {
const formats = exports.parseFormats(file);
return formats.indexOf(format) !== -1;
};
exports.parseOutput = ({ module, output, formats }) => {
formats = exports.parseFormats({ formats });
return formats.map(format => target(module, output, format));
};
|
import borrowsReducer from '../../src/reducers/borrowsReducer';
import * as actionTypes from '../../src/actions/types';
import {
borrows1,
} from '../__mocks__/testData';
describe('borrow reducer', () => {
it('should return the initial state', () => {
expect(borrowsReducer({}, {})).toEqual({});
});
it('should handle SET_BORROWED_BOOKS and save to store', () => {
expect(
borrowsReducer(
{ borrows: [] },
{ type: actionTypes.SET_BORROWED_BOOKS, borrowedBooks: borrows1 }
)
).toEqual({ borrows: borrows1 });
});
});
|
// facebook app settings - fb.js
module.exports = {
'appID' : process.env.fbAppId,
'appSecret' : process.env.fbAppSecret,
'callbackUrl' : 'https://churntrack.herokuapp.com:5000/login/facebook/callback'
}
|
var httpServer = require('./httpserver');
/**
* Listen for HTTP requests using a cluster of HTTP servers.
*
* This phase creates a cluster of HTTP servers and listens for requests on the
* given address and port, defaulting to 0.0.0.0:3000.
*
* This phase is typically one of the final phases in the boot sequence.
* Initializers should be run and routes should be drawn prior to this phase,
* ensuring that the application is fully prepared to handle requests.
*
* Examples:
*
* app.phase(locomotive.boot.httpServerCluster(8080));
*
* app.phase(locomotive.boot.httpServerCluster(8080, '127.0.0.1'));
*
* app.phase(locomotive.boot.httpServerCluster(8080, '127.0.0.1', { size: 8 }));
*
* @param {Number} port
* @param {String} address
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function(port, address, options) {
var os = require('os')
, http = require('http')
, cluster = require('cluster')
, debug = require('debug')('locomotive');
if (typeof address == 'object') {
options = address;
address = undefined;
} else if (typeof port == 'object') {
options = port;
address = undefined;
port = undefined;
}
options = options || {};
var size = options.size || os.cpus().length;
return function httpServerCluster(done) {
port = port || options.port || this.get('port') || 3000;
address = address || options.address || this.get('address') || '0.0.0.0';
if (cluster.isMaster) {
console.info('Creating HTTP server cluster with %d workers', size);
for (var i = 0; i < size; ++i) {
debug('spawning worker process %d', (i + 1));
cluster.fork();
}
cluster.on('fork', function(worker) {
debug('worker %s spawned', worker.id);
});
cluster.on('online', function(worker) {
debug('worker %s online', worker.id);
});
cluster.on('listening', function(worker, addr) {
debug('worker %s listening on %s:%d', worker.id, addr.address, addr.port);
});
cluster.on('disconnect', function(worker) {
debug('worker %s disconnected', worker.id);
});
cluster.on('exit', function(worker, code, signal) {
debug('worker %s died (%s)', worker.id, signal || code);
if (!worker.suicide) {
debug('restarting worker');
cluster.fork();
}
});
} else {
http.createServer(this.express).listen(port, address, function() {
var addr = this.address();
console.info('HTTP server listening on %s:%d', addr.address, addr.port);
return done();
});
}
};
};
|
ScalaJS.is.scala_collection_generic_Sorted = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_generic_Sorted)))
});
ScalaJS.as.scala_collection_generic_Sorted = (function(obj) {
if ((ScalaJS.is.scala_collection_generic_Sorted(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.collection.generic.Sorted")
}
});
ScalaJS.isArrayOf.scala_collection_generic_Sorted = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_generic_Sorted)))
});
ScalaJS.asArrayOf.scala_collection_generic_Sorted = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_collection_generic_Sorted(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.collection.generic.Sorted;", depth)
}
});
ScalaJS.data.scala_collection_generic_Sorted = new ScalaJS.ClassTypeData({
scala_collection_generic_Sorted: 0
}, true, "scala.collection.generic.Sorted", undefined, {
scala_collection_generic_Sorted: 1,
java_lang_Object: 1
});
//@ sourceMappingURL=Sorted.js.map
|
// Influnced by polymer project.
'use strict';
var util = require('util');
module.exports = function(href, onload, onerror) {
var link = document.createElement('link');
link.rel = 'import';
link.href = href;
if (onload && util.isFunction(onload)) {
link.onload = onload.bind(this);
}
if (onerror && util.isFunction(onerror)) {
link.onerror = onerror.bind(this);
}
document.head.appendChild(link);
return link;
};
|
const mongoose = require( 'mongoose' );
const Schema = mongoose.Schema;
const schema = new Schema({
drinkAgain: {
type: String,
enum: ['no', 'occasionally', 'yes'],
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
reviewer: {
type: String,
required: true
},
beerId: {
type: Schema.Types.ObjectId,
ref: 'Beer',
required: true
},
brewery: {
type: String,
required: true
},
beerName: {
type: String,
required: true
},
comments: {
type: String
}
});
module.exports = mongoose.model('Review', schema);
|
import ls from 'local-storage';
import defaultScript from './defaultScript.js.raw';
const scripts = [];
export const validEventNames = {
CLICK: 'onClick',
HOVER: 'onHover',
HOVER_END: 'onHoverEnd'
};
async function buildObj(code) {
let Ctor = (await window.jspmSystem.module(code)).default;
return new Ctor();
}
export function getDefaultCode(scriptIndex) {
return defaultScript.replace('%SCRIPT_INDEX%', scriptIndex);
}
export function getCode(scriptIndex) {
const registeredScript = scripts[scriptIndex];
return (registeredScript && registeredScript.code) || getDefaultCode(scriptIndex);
}
export function hasCode(scriptIndex) {
return !!scripts[scriptIndex];
}
export async function loadFromLocalStorage() {
const storedScripts = ls('scripts') || [getDefaultCode(0)];
for (let i = 0; i < storedScripts.length; i++) {
const script = storedScripts[i];
if (!script) {
continue;
}
await registerScript(i, script);
}
}
export function handleEvent(index, eventName, payload) {
const script = scripts[index];
if (!script) {
return;
}
const handler = script.obj[eventName];
if (!handler) {
return;
}
const boundHandler = handler.bind(script.obj);
const {obj, e} = payload;
boundHandler(obj, e);
}
export async function registerScript(index, code) {
try {
const obj = await buildObj(code);
scripts[index] = {
code,
obj
};
ls('scripts', scripts.map(script => script.code));
} catch (err) {
alert(err);
}
}
export function getItemText(index) {
const script = scripts[index];
if (!script) {
return '';
}
const {obj} = script;
return obj.text;
}
|
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
// Load all gulp plugins automatically
// and attach them to the `plugins` object
var plugins = require('gulp-load-plugins')();
// Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var runSequence = require('run-sequence');
var pkg = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('archive:create_archive_dir', function () {
fs.mkdirSync(path.resolve(dirs.archive), '0755');
});
gulp.task('archive:zip', function (done) {
var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
var archiver = require('archiver')('zip');
var files = require('glob').sync('**/*.*', {
'cwd': dirs.dist,
'dot': true // include hidden files
});
var output = fs.createWriteStream(archiveName);
archiver.on('error', function (error) {
done();
throw error;
});
output.on('close', done);
files.forEach(function (file) {
var filePath = path.resolve(dirs.dist, file);
// `archiver.bulk` does not maintain the file
// permissions, so we need to add files individually
archiver.append(fs.createReadStream(filePath), {
'name': file,
'mode': fs.statSync(filePath).mode
});
});
archiver.pipe(output);
archiver.finalize();
});
gulp.task('javascript', function () {
// set up the browserify instance on a task basis
var b = browserify({
entries: './src/js/main.js',
debug: true
});
return b.bundle()
.pipe(source('build.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js/'))
.pipe(gulp.dest('./src/js/'));
});
gulp.task('clean', function (done) {
require('del')([
dirs.archive,
dirs.dist
]).then(function () {
done();
});
});
gulp.task('copy', [
'copy:.htaccess',
'copy:index.html',
'copy:jquery',
'copy:license',
'copy:main.css',
'copy:misc',
'copy:normalize'
]);
gulp.task('copy:.htaccess', function () {
return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:index.html', function () {
return gulp.src(dirs.src + '/index.html')
.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:license', function () {
return gulp.src('LICENSE.txt')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:main.css', function () {
var banner = '/*! HTML5 Boilerplate v' + pkg.version +
' | ' + pkg.license.type + ' License' +
' | ' + pkg.homepage + ' */\n\n';
return gulp.src(dirs.src + '/css/main.css')
.pipe(plugins.header(banner))
.pipe(plugins.autoprefixer({
browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
cascade: false
}))
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
dirs.src + '/**/*',
// Exclude the following files
// (other tasks will handle the copying of these files)
'!' + dirs.src + '/css/main.css',
'!' + dirs.src + '/index.html'
], {
// Include hidden files by default
dot: false
}).pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('lint:js', function () {
return gulp.src([
'gulpfile.js',
dirs.src + '/js/*.js',
dirs.test + '/*.js'
]).pipe(plugins.jscs())
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('archive', function (done) {
runSequence(
'build',
'archive:create_archive_dir',
'archive:zip',
done);
});
gulp.task('build', function (done) {
runSequence(
['clean', 'lint:js', 'javascript'],
'copy',
done);
});
gulp.task('default', ['build']);
|
var SVGPathElement = {};
var SVGPathSeg = {};
var SVGRectElement = {};
var SVGPolygonElement = {};
var SVGSVGElement = {};
var JSM = {};
|
import View from "../modules/view";
import Menu from "../components/menu/menu";
import Profile from "../components/profileForm/profile";
export default class ProfileView extends View {
constructor(options = {}) {
super(options);
this._el = document.querySelector('.js-profile');
this.show();
}
init(options = {}) {
let menu = new Menu();
menu._updateHtml();
let profile= new Profile();
profile._updateHtml();
}
}
|
require("jquery")
require("font-awesome-webpack")
require('bootstrap-loader')
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Notifications from 'vue-notification'
import App from './App'
import router from './router'
import store from './store'
import commonMixin from './mixins/common.js'
import chartMixin from './mixins/chart.js'
import statTable from './components/misc/stat-table.vue'
Vue.mixin(commonMixin)
Vue.mixin(chartMixin)
Vue.use(Notifications)
Vue.component('stat-table', statTable)
import Chart from 'chart.js'
Chart.defaults.global.responsive = true
Chart.defaults.global.maintainAspectRatio = false
Chart.defaults.global.animation = false
Chart.defaults.global.elements.line.backgroundColor = "rgba(0,0,0,0)"
Chart.defaults.global.elements.line.fill = false
Chart.defaults.global.elements.line.borderWidth = 1
Chart.defaults.global.elements.point.radius = 0
//Chart.defaults.global.tooltips = { "mode": false, "intersect": false }
Chart.defaults.global.title.display = false
Chart.defaults.global.title.display = false
Chart.defaults.global.defaultFontColor = '#000'
Chart.defaults.global.defaultFontSize = 12
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
|
'use strict';
var angular = require('angular');
angular.module('odca.static_api', [
require('angular-resource')
])
.factory('static_api', function ($resource, settings) {
'ngInject';
return {
candidate: api_group('/candidate/:candidate_id', {
supporting: {
method: 'get',
url: '/supporting'
},
opposing: {
method: 'get',
url: '/opposing'
}
}),
committee: api_group('/committee/:filer_id', {
contributions: {
method: 'get',
url: '/contributions',
isArray: true
}
}),
locality: api_group('/locality/:locality_id', {
get: {
method: 'get',
transformResponse: arrayFirst
}, // Workaround for backend returning an array here
current_ballot: {
method: 'get',
url: '/current_ballot'
}
}),
referendum: api_group('/referendum/:referendum_id', {
supporting: {
method: 'get',
url: '/supporting'
},
opposing: {
method: 'get',
url: '/opposing'
}
}),
stats: api_group('/stats', {})
};
function api_group(base_url, actions, defaultParams) {
var absolute_url = settings.DISCLOSURE_STATIC_BACKEND + base_url;
defaultParams = defaultParams || {};
var resourceActions = {};
Object.keys(actions).forEach(function (actionName) {
var action = actions[actionName];
resourceActions[actionName] = angular.extend({
cache: true
}, action, {
url: absolute_url + (action.url || '')
});
});
return $resource(absolute_url, defaultParams, resourceActions);
}
function arrayFirst(data) {
return angular.fromJson(data)[0];
}
});
module.exports = 'odca.static_api';
|
module.exports = function(a, b) {
return a * b;
};
|
'use strict';
export default function isToday (date, options = {}) {
const {convert = false, scope = new Date()} = options;
if(typeof convert !== 'boolean') {
throw new TypeError('Expected convert option to be a Boolean got ' + typeof convert);
}
if(convert === true) {
date = new Date(date);
}
if (isNaN(Date.parse(date))) {
throw new TypeError('Expected first parameter to be a Date got ' + typeof date);
}
return date.toDateString() === scope.toDateString();
};
|
require( 'babel-polyfill' )
global.Utils = require('./utils.es6.js').default
global.SnapshotService = require('./services/SnapshotService.es6.js').default
global.Dashboard = require('./components/Dashboard.jsx').default
global.SimpleLineChart = require('./components/SimpleLineChart.jsx').default
global.StackedAreaChart = require('./components/StackedAreaChart.jsx').default
|
'use strict';
var Board = require('./game/board')
, Grid = require('./client/grid')
, wsconfig = require('../wsconfig.json')
, stat = require('./game/stat');
var Socket = require('simple-websocket')
, rainbow = require('color-rainbow')
, thus = require('thus')
, colorNamer = require('color-namer')
, declared = require('declared')
, humane = require('humane-js').create({ timeout: 500 })
, uniq = require('uniq');
var EventEmitter = require('events').EventEmitter;
var showMyColor = function (color) {
document.getElementById('mycolor').style.display = 'block';
thus(document.getElementById('mycolor-icon'), function () {
var hex = color.hexString();
this.textContent = color.keyword() || colorNamer(hex, 'html')[0].name;
this.style.color = hex;
});
};
var win = function () {
humane.log('You win!', { timeout: 0 });
};
var lose = function () {
humane.log('You lost.', { timeout: 0 });
};
var inactiveCounter = (function () {
var bar = document.getElementById('inactive-bar');
var counter = document.getElementById('inactive-counter');
var value = 0;
var timer;
return {
start: function () {
bar.style.visibility = 'visible';
counter.textContent = value = 0;
timer = setInterval(function () {
counter.textContent = ++value;
}, 1000);
},
stop: function () {
clearInterval(timer);
bar.style.visibility = 'hidden';
}
};
}());
var Game = function (server) {
return new EventEmitter().
on('wait', function () {
humane.log('Waiting for the opponent…', { timeout: 0 });
}).
on('start', function (message) {
var game = this;
game.player = message.player;
game.opponent = message.opponent;
game.board = Board(message.numColors, message.board);
game.playerColor = game.board.colorAt(game.player);
game.opponentColor = game.board.colorAt(game.opponent);
var canvas = document.getElementById('grid');
var palette = rainbow.create(game.board.numColors);
game.grid = Grid(game.board, canvas, palette);
var validateMove = function (region) {
var instantWin = region == game.board.regionAt(game.opponent);
var unreachable = !game.board.border(game.player).some(function (pos) {
return game.board.regionAt(pos) == region;
});
var invalidMove = instantWin || unreachable;
if (invalidMove) {
humane.log('Invalid move!');
}
return !invalidMove;
};
var checkResult = function () {
var overlord = stat.overlord(game.board);
if (overlord.size * 2 < game.board.size) {
return;
}
if (overlord.color == game.playerColor) {
win();
}
else if (overlord.color == game.opponentColor) {
lose();
}
};
game.grid.on('click', function (i, j, owner) {
owner = declared(owner, game.player);
var ownerColor = game.board.colorAt(owner);
var targetRegion = game.board.regions[i][j];
var targetColor = game.board.colors[i][j];
if (owner == game.player) {
if (!validateMove(targetRegion)) {
return;
}
server.send(JSON.stringify({
code: 'move',
i: i,
j: j
}));
}
// Select regions adjacent to the owner's region.
var regions = uniq(game.board.border(owner).filter(function (cell) {
return game.board.colorAt(cell) == targetColor;
}).map(game.board.regionAt.bind(game.board)));
regions.forEach(function (region) {
region.forEach(function (pos) {
this.fill(pos.i, pos.j, ownerColor);
}, this);
}, this);
game.board.recomputeRegions();
if (owner == game.player) {
game.grid.disable();
inactiveCounter.start();
}
else {
inactiveCounter.stop();
game.grid.enable();
}
checkResult();
});
showMyColor(palette[game.playerColor]);
humane.remove();
humane.log('Let the carnage begin!', { timeout: 1500 });
}).
on('move', function (message) {
// Opponent clicked some cell.
this.grid.emit('click', message.i, message.j, this.opponent);
});
};
/**
* Start the game client.
*
* @arg {string} wshost - Back-end WebSocket server host.
* @arg {number} wsport - Back-end WebSocket server port.
*/
var start = function (wshost, wsport) {
var server = new Socket('ws://' + wshost + ':' + wsport);
var game = Game(server);
server.on('message', function (message) {
game.emit(message.code, message);
});
};
start(wsconfig.host, wsconfig.port);
|
'use strict';
/**
* @ngdoc overview
* @name frontendApp
* @description
* # frontendApp
*
* Main module of the application.
*/
angular
.module('frontendApp', [
'constantsApp',
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'satellizer',
'route-segment',
'view-segment',
'restangular',
'ui.bootstrap'
])
.config(function ($locationProvider, $authProvider, $routeSegmentProvider,
RestangularProvider, API_ROOT, GOOGLE_API_CLIENT_ID) {
// push state settings
$locationProvider.html5Mode(true);
// restangular settings
RestangularProvider.setBaseUrl(API_ROOT);
RestangularProvider.setRequestSuffix('/');
// satellizer settings
$authProvider.tokenType = 'JWT';
$authProvider.google({
clientId: GOOGLE_API_CLIENT_ID,
url: API_ROOT + '/login/social/jwt_user/',
scope: [
'email'
],
redirectUri: window.location.origin + '/'
});
// routes
$routeSegmentProvider
.when('/', 'main')
.when('/bank_accounts/', 'main.bank_accounts_list')
.when('/bank_accounts/:id/', 'main.bank_accounts_list.create_edit')
.segment('main', {
templateUrl: 'views/main.html'
})
.within()
.segment('bank_accounts_list', {
default: true,
templateUrl: 'views/bank_accounts/list.html'
})
.within()
.segment('create_edit', {
controller: 'BankAccountsCreateEditCtrl',
dependencies: ['id']
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.