text
stringlengths 2
6.14k
|
|---|
const webdriver = require('selenium-webdriver');
const setupDriver = (browser) => {
const driver = new webdriver
.Builder()
.usingServer('http://localhost:9515/')
.withCapabilities({
browserName: browser,
})
.build();
return driver;
};
module.exports = { setupDriver };
|
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
function random(min, max) {
min = min || 0;
max = max || 1;
var result;
if(min === 0 && max === 1) {
result = Math.random();
} else {
result = Math.floor((Math.random() * max) + min);
}
return result;
}
grunt.registerMultiTask('random', 'Your task description goes here.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({min:0,max:1});
grunt.log.writeln('Random: ' + random(options.min, options.max));
});
};
|
'use strict';
angular
.module('facebookMe', [
])
;
|
var base64url = require('urlsafe-base64')
, After = require('json-list-response').After
, inherits = require('util').inherits
module.exports = DateAfter
function DateAfter(value, options) {
After.call(this, value, options)
this.skip = 0
this.value = 0
if (value) {
value = base64url.decode(value)
if (value.length === 9) {
this.value = value.readDoubleBE(0)
this.skip = value.readUInt8(8)
}
}
}
inherits(DateAfter, After)
DateAfter.prototype.add = function (row) {
var value = row[this.key]
if (!value) return
if (+this.value === +value) {
this.skip++
} else {
this.skip = 0
this.value = value
}
}
DateAfter.prototype.toString = function () {
if (!this.value) return ''
var buf = new Buffer(9)
buf.writeDoubleBE(+this.value || 0, 0)
buf.writeUInt8(this.skip, 8)
return base64url.encode(buf)
}
DateAfter.prototype.mongoSorting = function (list, sorting) {
var obj = {}
obj[sorting.key] = {}
obj[sorting.key][sorting.descending ? '$lte' : '$gte'] = new Date(this.value)
list.selector.$and.push(obj)
list.cursor.skip(this.skip + 1)
}
|
export goCommand from './goCommand'
export goReducer from './goReducer'
export parseBestmove from './parseBestmove'
export parseId from './parseId'
export parseInfo from './parseInfo'
export parseOption from './parseOption'
export initReducer from './initReducer'
|
exports.translate = function(tag) {
return this.import("riot").compile(tag);
};
|
en.resources.define("audio",{
name: "Engine",
src: "./audio/ship_engine.ogg",
}, function(content, callback){
var sound = client.audio.createSound();
sound.load(content.src, function(sound){
content.sound = sound;
callback(content.type, content);
});
}, function(content){
return content.sound;
});
|
var express = require("express");
var Pusher = require("pusher");
var bodyParser = require("body-parser");
var env = require("node-env-file");
var app = express();
app.use(bodyParser.urlencoded());
try {
env(__dirname + "/.env");
} catch (_error) {
error = _error;
console.log(error);
}
var pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET
});
app.use('/', express["static"]('dist'));
app.post("/pusher/auth", function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var auth = pusher.authenticate(socketId, channel);
res.send(auth);
});
var port = process.env.PORT || 5000;
app.listen(port);
|
var app = angular.module("ethics-app");
// User create controller
app.controller("userCreateController", function($scope, $rootScope, $routeParams, $filter, $translate, $location, config, $window, $authenticationService, $userService, $universityService, $instituteService) {
/*************************************************
FUNCTIONS
*************************************************/
/**
* [redirect description]
* @param {[type]} path [description]
* @return {[type]} [description]
*/
$scope.redirect = function(path){
$location.url(path);
};
/**
* [description]
* @param {[type]} former_status [description]
* @return {[type]} [description]
*/
$scope.getGroupName = function(former_status){
if(former_status){
return $filter('translate')('FORMER_INSTITUTES');
} else {
return $filter('translate')('INSTITUTES');
}
};
/**
* [send description]
* @return {[type]} [description]
*/
$scope.send = function(){
// Validate input
if($scope.createUserForm.$invalid) {
// Update UI
$scope.createUserForm.email_address.$pristine = false;
$scope.createUserForm.title.$pristine = false;
$scope.createUserForm.first_name.$pristine = false;
$scope.createUserForm.last_name.$pristine = false;
$scope.createUserForm.institute_id.$pristine = false;
$scope.createUserForm.blocked.$pristine = false;
} else {
$scope.$parent.loading = { status: true, message: $filter('translate')('CREATING_NEW_USER') };
// Create new user
$userService.create($scope.new_user)
.then(function onSuccess(response) {
var user = response.data;
// Redirect
$scope.redirect("/users/" + user.user_id);
})
.catch(function onError(response) {
$window.alert(response.data);
});
}
};
/**
* [description]
* @param {[type]} related_data [description]
* @return {[type]} [description]
*/
$scope.load = function(related_data){
// Check which kind of related data needs to be requested
switch (related_data) {
case 'universities': {
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_UNIVERSITIES') };
// Load universities
$universityService.list({
orderby: 'name.asc',
limit: null,
offset: null
})
.then(function onSuccess(response) {
$scope.universities = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
break;
}
case 'institutes': {
if($scope.university_id){
if($scope.university_id !== null){
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_INSTITUTES') };
// Load related institutes
$instituteService.listByUniversity($scope.university_id, {
orderby: 'name.asc',
limit: null,
offset: null,
former: false
})
.then(function onSuccess(response) {
$scope.institutes = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
break;
}
}
};
/*************************************************
INIT
*************************************************/
$scope.new_user = $userService.init();
$scope.authenticated_member = $authenticationService.get();
// Load universities
$scope.load('universities');
// Set default value by member
$scope.university_id = $scope.authenticated_member.university_id;
// Load related institutes
$scope.load('institutes');
// Set default value by member
$scope.new_user.institute_id = $scope.authenticated_member.institute_id;
});
|
#!/usr/bin/env node
var child_process = require('child_process');
var argv = require('yargs')
.boolean(['readability', 'open'])
.argv;
var pdfdify = require('../lib');
var srcUrl = argv._[0];
console.log("Convertering: '"+srcUrl+"'");
pdfdify.convert({
title:argv.title|| srcUrl,
readability:argv.readability,
srcUrl:srcUrl
},function (err, pdfFile) {
if (err) {
throw err;
}
console.log("Created: '"+pdfFile+"'");
if(argv.open) {
child_process.exec('open "'+pdfFile+'"');
}
});
|
import { createTest } from 'tests/test-utils'
import moment from 'moment'
import { EventTypes, Disciplines } from 'client/calendar/events/types'
import _ from 'lodash'
import ncnca2017 from '../2017-ncnca-events'
import usac2017 from '../2017-usac-events'
const events = _.concat(
// does not inlcude older events that do not comply with this requirements
ncnca2017,
usac2017
)
//TODO: make this tests event centric or test-case centric?
const test = createTest('Common events tests')
const parseDate = date => moment(date, 'MMMM DD YYYY')
const getKeyByValue = (obj, value) => Object.keys(obj).filter(key => obj[key] === value)
const getFirstKeyByValue = (obj, value) => getKeyByValue(obj, value)[0]
test('Event must have short id as part of long id and separately as "_shortId" property', t => {
events.forEach((event, i) => {
const eventId = event.id
const shortIdFromId = eventId.match(/[a-zA-Z0-9_$]+$/gm)[0] //matches part after last '-'
t.equal(event._shortId, shortIdFromId,
`#${event.name} "${event._shortId}" => "${shortIdFromId}"`)
})
t.end()
})
test('Event must have unique id across all events', t => {
const eventsById = _.groupBy(events, 'id')
_.map(eventsById, (value, key) => {
if (value.length !== 1) {
t.fail(`There are "${value.length}" events with id: "${key}", id must be unique.`)
}
})
t.end()
})
test('Event must have _shortId that only contains predefined characters', t => {
events.forEach((event, i) => {
const matches = event._shortId.match(/[a-zA-Z0-9_$]+$/gm) //matches part after last '-'
if (matches && matches.length === 1) {
t.pass(`#${event._shortId} for event "${event.name}"`)
} else {
t.fail(`Problematic _shortId: "#${event._shortId}" for event "${event.name}"`)
}
})
t.end()
})
test('Event must have id starting from "evt-"', t => {
events.forEach((event, i) => {
t.ok(event.id.startsWith(('evt-')),
`${event.name}`)
})
t.end()
})
test('Event must have date in a format "MMMM DD YYYY"', t => {
events.forEach((event, i) => {
const date = moment(event.date, 'MMMM DD YYYY')
t.ok(date.isValid(),
`${event.name}`)
})
t.end()
})
test('Event with USAC permit should have permit starting from events year', t => {
events
.filter(x => x.usacPermit)
.forEach((event, i) => {
const date = parseDate(event.date)
t.ok(event.usacPermit.startsWith(date.year() + '-'), `${event.name}`)
})
t.end()
})
test('Event with promoters', t => {
events.forEach((event, i) => {
t.comment(`${event.name}`)
if (event.promoters) {
t.ok(Array.isArray(event.promoters), 'promoters should be an array')
if (event.promoters.length >= 1) {
t.ok(event.promoters.every(x => x.id),
'each promoter should have an id')
t.ok(event.promoters.every(x => x.id && x.id.startsWith('prm-')),
'each promoter\'s id should start from "prm-"')
}
}
})
t.end()
})
test('Each Event must have at least city and state set in Location', t => {
events.forEach((event, i) => {
t.comment(`${event.name}`)
t.ok(event.location, 'has location set')
t.ok(event.location.city, 'has city set')
t.ok(event.location.state, 'has state set')
})
t.end()
})
test('Each Event must have Type and Discipline set to one of the pre-defined ones', t => {
const allDisciplines = _.values(Disciplines)
const getEventTypesForDiscipline = discipline => {
const disciplineKey = getFirstKeyByValue(Disciplines, discipline)
return _.values(EventTypes[disciplineKey])
}
events.forEach((event, i) => {
t.comment(`${event.id}`)
t.ok(allDisciplines.includes(event.discipline),
'should have discipline equal to one of the pre-defined ones')
t.ok(getEventTypesForDiscipline(event.discipline).includes(event.type),
'should have type set to one that corresponds to event\'s discipline'
+ `, current one is set to: "${event.type}" which is not part of "${event.discipline}" discipline`)
})
t.end()
})
test('Event that is moved, when have "movedToEventId" should point to existing event', t => {
const eventsById = _.keyBy(events, 'id')
events
.filter(x => x.movedToEventId)
.forEach((event, i) => {
t.comment(`${event.name}`)
const movedToEvent = eventsById[event.movedToEventId]
t.ok(movedToEvent, 'moved to event id should point to existing event')
t.comment(`Provided evnet id: ${event.movedToEventId}`)
t.ok(event.movedToEventId !== event.id, 'moved to event id should point to a different event')
t.comment(`Provided evnet id: ${event.movedToEventId}`)
t.ok(parseDate(movedToEvent.date) > parseDate(event.date),
'moved to event should be later than the event it is moved from')
})
t.end()
})
|
/**
* Global Variable Configuration
* (sails.config.globals)
*
* Configure which global variables which will be exposed
* automatically by Sails.
*
* For more information on configuration, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.globals.html
*/
module.exports.globals = {
/****************************************************************************
* *
* Expose the lodash installed in Sails core as a global variable. If this *
* is disabled, like any other node module you can always run npm install *
* lodash --save, then var _ = require('lodash') at the top of any file. *
* *
****************************************************************************/
// _: true,
/****************************************************************************
* *
* Expose the async installed in Sails core as a global variable. If this is *
* disabled, like any other node module you can always run npm install async *
* --save, then var async = require('async') at the top of any file. *
* *
****************************************************************************/
// async: true,
/****************************************************************************
* *
* Expose the sails instance representing your app. If this is disabled, you *
* can still get access via req._sails. *
* *
****************************************************************************/
// sails: true,
/****************************************************************************
* *
* Expose each of your app's services as global variables (using their *
* "globalId"). E.g. a service defined in api/models/NaturalLanguage.js *
* would have a globalId of NaturalLanguage by default. If this is disabled, *
* you can still access your services via sails.services.* *
* *
****************************************************************************/
// services: true,
/****************************************************************************
* *
* Expose each of your app's models as global variables (using their *
* "globalId"). E.g. a model defined in api/models/User.js would have a *
* globalId of User by default. If this is disabled, you can still access *
* your models via sails.models.*. *
* *
****************************************************************************/
// models: true
};
|
this.NesDb = this.NesDb || {};
NesDb[ '9F3DE783494F7FF30679A17B0C5B912834121095' ] = {
"$": {
"name": "Nekketsu Kouha Kunio-kun",
"altname": "熱血硬派くにおくん",
"class": "Licensed",
"catalog": "TJC-KN",
"publisher": "Technos",
"developer": "Technos",
"region": "Japan",
"players": "2",
"date": "1987-04-17"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-06-24"
},
"board": [
{
"$": {
"type": "HVC-UNROM",
"pcb": "HVC-UNROM-02",
"mapper": "2"
},
"prg": [
{
"$": {
"name": "TJC-KN-0 PRG",
"size": "128k",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095"
}
}
],
"vram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "74xx161"
}
},
{
"$": {
"type": "74xx32"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
]
};
|
/**
* Interaction for the tags module
*
* @author Tijs Verkoyen <tijs@sumocoders.be>
*/
jsBackend.tags =
{
// init, something like a constructor
init: function()
{
$dataGridTag = $('.jsDataGrid td.tag');
if($dataGridTag.length > 0) $dataGridTag.inlineTextEdit({ params: { fork: { action: 'edit' } }, tooltip: jsBackend.locale.msg('ClickToEdit') });
}
};
$(jsBackend.tags.init);
|
/* global WebFont */
(function () {
'use strict';
function FontLoaderFactory () {
return {
setFonts : function () {
WebFont.load({
custom: {
families: [ 'FontAwesome','Ubuntu','Oxygen','Open Sans' ],
urls: [ '/fonts/base.css']
}
});
}
};
}
angular.module('app.core.fontloader', [])
.factory('FontLoader',FontLoaderFactory);
})();
|
module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function handler (err, req, res, next) {
debug('Error page because of ' + err.message)
var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.errorHandler) {
return ldp.errorHandler(err, req, res, next)
}
// If noErrorPages is set,
// then use built-in express default error handler
if (ldp.noErrorPages) {
return res
.status(err.status)
.send(err.message + '\n' || '')
}
// Check if error page exists
var errorPage = ldp.errorPages + err.status.toString() + '.html'
fs.readFile(errorPage, 'utf8', function (readErr, text) {
if (readErr) {
return res
.status(err.status)
.send(err.message || '')
}
res.status(err.status)
res.header('Content-Type', 'text/html')
res.send(text)
})
}
|
module.exports = function () {
var modules = [];
var creeps = Game.creeps;
var spawn = Game.spawns.Spawn1;
var score = spawn ? spawn.room.survivalInfo.score : 0;
var minions = {
total: 0,
build: 0,
carry: 0,
harvest: 0,
guard: 0,
medic: 0,
runner: 0
};
if (score == 0 || spawn.spawning != null) return; // no action when already spawning
for (var i in creeps) {
var creep = creeps[i];
minions.total++;
minions[creep.memory.module]++;
}
var getTough = function (amount) {
var modules = [];
amount += Math.round(score / 250);
for (var i = 0; i < amount; i++) {
modules.push(TOUGH);
}
return modules;
};
var spawnCreep = function (modules, memory) {
var creep = spawn.createCreep(modules, undefined, memory);
if (typeof creep != 'number') {
console.log('created ' + memory.module, modules);
}
return creep;
};
if (minions.harvest < 2) {
spawnCreep([WORK, WORK, WORK, CARRY, MOVE], {module: 'harvest'});
}
else if (minions.carry < 2) {
spawnCreep([CARRY, MOVE, MOVE], {module: 'carry'});
}
else if (score > 1000 && minions.runner < 1 || score > 2000 && minions.runner < 2) {
spawnCreep([CARRY, MOVE, MOVE, CARRY, MOVE], {module: 'runner'});
}
else if (minions.medic < minions.guard / 2) {
modules = [];
modules.push(HEAL, HEAL, HEAL, HEAL, MOVE);
spawnCreep(modules, {module: 'medic'});
}
else if (minions.harvest > 0 && ((score < 1100 && minions.guard < 6) || (score > 1100 && score < 2100 && minions.guard < 12) || score > 2100)) {
modules = getTough(0);
modules.push(RANGED_ATTACK, RANGED_ATTACK, RANGED_ATTACK, MOVE, MOVE);
spawnCreep(modules, {module: 'guard'});
}
};
|
import hotkeys from "hotkeys-js";
export default class HotkeyHandler {
constructor(hotkeyRegistry) {
this.hotkeyRegistry = hotkeyRegistry;
hotkeys("*", { keyup: true, keydown: false }, event => {
event.preventDefault();
this.hotkeyRegistry.resetLastPressedKeyCodes();
return false;
});
hotkeys("*", { keyup: false, keydown: true }, event => {
event.preventDefault();
const pressed = hotkeys.getPressedKeyCodes();
this.hotkeyRegistry.onKeyPressed(pressed);
return false;
});
}
dispose() {
hotkeys.deleteScope("all");
}
}
|
$(function(){
BrowserDetect.init();
$('.minifyme').on("navminified", function() {
// $('td.expand,th.expand').toggle();
});
// Activate all popovers (if NOT mobile)
if ( !BrowserDetect.isMobile() ) {
$('[data-toggle="popover"]').popover();
}
});
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
function ensureHeightOfSidebar() {
$('#left-panel').css('height',$('#main').height());
}
BrowserDetect =
// From http://stackoverflow.com/questions/13478303/correct-way-to-use-modernizr-to-detect-ie
{
init: function ()
{
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
isMobile: function ()
{
if (navigator.userAgent.search(/(Android|Touch|iPhone|iPad)/) == -1) {
return false;
} else {
return true;
}
},
searchString: function (data)
{
for (var i=0 ; i < data.length ; i++)
{
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) != -1)
{
return data[i].identity;
}
}
},
searchVersion: function (dataString)
{
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser:
[
{ string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
{ string: navigator.userAgent, subString: "MSIE", identity: "Explorer" },
{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
{ string: navigator.userAgent, subString: "Safari", identity: "Safari" },
{ string: navigator.userAgent, subString: "Opera", identity: "Opera" }
]
};
|
// (The MIT License)
//
// Copyright Michał Czapracki, budleigh.salterton@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
/**
* @fileoverview
* @author Michał Czapracki
*
* An extended config example
*
* Try invoking this file like:
* node simple --config=./myvars
* or
* node examples/simple --config=./examples/myvars --no-all-fixes-global --all-fixes-heap --quiet=
*/
var path = require('path');
var flatconfig = require('flatconfig'),
args = flatconfig.parseArgs(process.argv.slice(2));
if (!args['config']) {
console.log('Usage: ' + process.argv.slice(0, 2).join(' ')
+ ' --config=path/to/config');
process.exit(1);
}
var cfgpath = args['config'][0];
delete args['config'];
var config = flatconfig.load(__dirname + '/cfg.js',
path.resolve(process.cwd(), cfgpath),
args),
flat = flatconfig.flatten(config);
if (!config.quiet) {
console.log('The configuration resolved to: ');
for (var k in flat) {
console.log(' ', k, '=', JSON.stringify(flat[k]));
}
console.log('');
console.log('The resulting JSON is: ');
}
console.log(JSON.stringify(config));
|
'use strict';
(function() {
// ProductAppliers Controller Spec
describe('ProductAppliersController', function() {
// Initialize global variables
var ProductAppliersController,
scope,
$httpBackend,
$stateParams,
$location;
// 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, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the ProductAppliers controller.
ProductAppliersController = $controller('ProductAppliersController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one productApplier object fetched from XHR', inject(function(ProductAppliers) {
// Create sample productApplier using the ProductAppliers service
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productAppliers array that includes the new productApplier
var sampleProductAppliers = [sampleProductApplier];
// Set GET response
$httpBackend.expectGET('productAppliers').respond(sampleProductAppliers);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.productAppliers).toEqualData(sampleProductAppliers);
}));
it('$scope.findOne() should create an array with one productApplier object fetched from XHR using a productApplierId URL parameter', inject(function(ProductAppliers) {
// Define a sample productApplier object
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Set the URL parameter
$stateParams.productApplierId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/productAppliers\/([0-9a-fA-F]{24})$/).respond(sampleProductApplier);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.productApplier).toEqualData(sampleProductApplier);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(ProductAppliers) {
// Create a sample productApplier object
var sampleProductApplierPostData = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productApplier response
var sampleProductApplierResponse = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Fixture mock form input values
scope.title = 'An ProductApplier about MEAN';
scope.content = 'MEAN rocks!';
// Set POST response
$httpBackend.expectPOST('productAppliers', sampleProductApplierPostData).respond(sampleProductApplierResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// Test URL redirection after the productApplier was created
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierResponse._id);
}));
it('$scope.update() should update a valid productApplier', inject(function(ProductAppliers) {
// Define a sample productApplier put data
var sampleProductApplierPutData = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN Rocks!'
});
// Mock productApplier in scope
scope.productApplier = sampleProductApplierPutData;
// Set PUT response
$httpBackend.expectPUT(/productAppliers\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid productApplierId and remove the productApplier from the scope', inject(function(ProductAppliers) {
// Create new productApplier object
var sampleProductApplier = new ProductAppliers({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new productAppliers array and include the productApplier
scope.productAppliers = [sampleProductApplier];
// Set expected DELETE response
$httpBackend.expectDELETE(/productAppliers\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleProductApplier);
$httpBackend.flush();
// Test array after successful delete
expect(scope.productAppliers.length).toBe(0);
}));
});
}());
|
/* global expect */
describe('outputFormat', () => {
describe('when given a format', () => {
it('decides the output that will be used for serializing errors', () => {
expect(
function () {
const clonedExpect = expect.clone().outputFormat('html');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
htmlMessage:
'<div style="font-family: monospace; white-space: nowrap">' +
'<div><span style="color: red; font-weight: bold">expected</span> <span style="color: #0086b3">42</span> <span style="color: red; font-weight: bold">to equal</span> <span style="color: #0086b3">24</span></div>' +
'</div>',
}
);
expect(
function () {
const clonedExpect = expect.clone().outputFormat('ansi');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
message:
'\n\x1b[31m\x1b[1mexpected\x1b[22m\x1b[39m 42 \x1b[31m\x1b[1mto equal\x1b[22m\x1b[39m 24\n',
}
);
});
});
});
|
'use strict';
const fs = require('fs');
const remote = require('electron').remote;
const mainProcess = remote.require('./main');
module.exports = {
template: `
<v-list dense class="pt-0">
<v-list-tile to="recent-projects" :router="true">
<v-list-tile-action>
<v-icon>list</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="recent-projects">Recent projects</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="existingProject">
<v-list-tile-action>
<v-icon>folder_open</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-project">Add existing project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="create-project" :router="true">
<v-list-tile-action>
<v-icon>create_new_folder</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="create-project">Create new project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="globalProject" v-if="globalComposerFileExists">
<v-list-tile-action>
<v-icon>public</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="global-composer">Global composer</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="settings" :router="true">
<v-list-tile-action>
<v-icon>settings</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-settings">Settings</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
</v-list>
`,
computed: {
globalComposerFileExists() {
return fs.existsSync(remote.app.getPath('home') + '/.composer');
}
},
methods: {
existingProject: () => {
mainProcess.openDirectory();
},
globalProject: () => {
mainProcess.openProject(remote.app.getPath('home') + '/.composer');
},
}
}
|
var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url"),
filesys = require("fs");
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path,function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else{
filesys.readFile(full_path, "binary", function(err, file) {
if(err) {
response.writeHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
}
else{
response.writeHeader(200);
response.write(file, "binary");
response.end();
}
});
}
});
}).listen(8080);
sys.puts("Server Running on 8080");
|
var path = require('path');
var fs = require('fs');
var Writer = require('broccoli-writer');
var Handlebars = require('handlebars');
var walkSync = require('walk-sync');
var RSVP = require('rsvp');
var helpers = require('broccoli-kitchen-sink-helpers');
var mkdirp = require('mkdirp');
var Promise = RSVP.Promise;
var EXTENSIONS_REGEX = new RegExp('.(hbs|handlebars)');
var HandlebarsWriter = function (inputTree, files, options) {
if (!(this instanceof HandlebarsWriter)) {
return new HandlebarsWriter(inputTree, files, options);
}
this.inputTree = inputTree;
this.files = files;
this.options = options || {};
this.context = this.options.context || {};
this.destFile = this.options.destFile || function (filename) {
return filename.replace(/(hbs|handlebars)$/, 'html');
};
this.handlebars = this.options.handlebars || Handlebars;
this.loadPartials();
this.loadHelpers();
};
HandlebarsWriter.prototype = Object.create(Writer.prototype);
HandlebarsWriter.prototype.constructor = HandlebarsWriter;
HandlebarsWriter.prototype.loadHelpers = function () {
var helpers = this.options.helpers;
if (!helpers) return;
if ('function' === typeof helpers) helpers = helpers();
if ('object' !== typeof helpers) {
throw Error('options.helpers must be an object or a function that returns an object');
}
this.handlebars.registerHelper(helpers);
};
HandlebarsWriter.prototype.loadPartials = function () {
var partials = this.options.partials;
var partialsPath;
var partialFiles;
if (!partials) return;
if ('string' !== typeof partials) {
throw Error('options.partials must be a string');
}
partialsPath = path.join(process.cwd(), partials);
partialFiles = walkSync(partialsPath).filter(EXTENSIONS_REGEX.test.bind(EXTENSIONS_REGEX));
partialFiles.forEach(function (file) {
var key = file.replace(partialsPath, '').replace(EXTENSIONS_REGEX, '');
var filePath = path.join(partialsPath, file);
this.handlebars.registerPartial(key, fs.readFileSync(filePath).toString());
}, this);
};
HandlebarsWriter.prototype.write = function (readTree, destDir) {
var self = this;
this.loadPartials();
this.loadHelpers();
return readTree(this.inputTree).then(function (sourceDir) {
var targetFiles = helpers.multiGlob(self.files, {cwd: sourceDir});
return RSVP.all(targetFiles.map(function (targetFile) {
function write (output) {
var destFilepath = path.join(destDir, self.destFile(targetFile));
mkdirp.sync(path.dirname(destFilepath));
var str = fs.readFileSync(path.join(sourceDir, targetFile)).toString();
var template = self.handlebars.compile(str);
fs.writeFileSync(destFilepath, template(output));
}
var output = ('function' !== typeof self.context) ? self.context : self.context(targetFile);
return Promise.resolve(output).then(write);
}));
});
};
module.exports = HandlebarsWriter;
|
import './index.css';
import React, {Component} from 'react';
import { postToggleDevice } from '../ajax';
export default class SocketDevice extends Component {
constructor() {
super();
this.state = {clicked: false, device: {}};
this.clicked = this.clicked.bind(this);
}
componentWillMount() {
var device = this.props.device;
if (device.enabled) {
this.setState({clicked: true});
}
this.setState({device: device});
}
clicked() {
var nextState = !this.state.clicked;
var id = this.state.device.id;
if (this.props.valueControl) {
this.props.valueControl(id, 'enabled', nextState);
this.setState({clicked: nextState});
} else {
this.toggle(id);
}
}
toggle() {
var id = this.state.device.id;
postToggleDevice(id, function (device) {
this.setState({clicked: device.enabled, device: device});
}.bind(this));
}
render() {
var name = this.state.device.name;
var classes = 'icon-tinted' + (this.state.clicked ? ' active' : '');
return (<div className="m-t-1">
<h4>
<a className={classes} onClick={this.clicked}><i className="fa fa-plug fa-lg"/></a> {name}
</h4>
</div>);
}
}
SocketDevice.propTypes = {
device: React.PropTypes.object.isRequired,
valueControl: React.PropTypes.func.isRequired
};
|
require( ['build/index'] );
|
/*
* Copyright (c) 2016 airbug Inc. http://airbug.com
*
* bugcore may be freely distributed under the MIT license.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@TestFile
//@Require('Class')
//@Require('Map')
//@Require('ObservableMap')
//@Require('PutChange')
//@Require('TypeUtil')
//@Require('bugdouble.BugDouble')
//@Require('bugmeta.BugMeta')
//@Require('bugunit.TestTag')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------
var Class = bugpack.require('Class');
var Map = bugpack.require('Map');
var ObservableMap = bugpack.require('ObservableMap');
var PutChange = bugpack.require('PutChange');
var TypeUtil = bugpack.require('TypeUtil');
var BugDouble = bugpack.require('bugdouble.BugDouble');
var BugMeta = bugpack.require('bugmeta.BugMeta');
var TestTag = bugpack.require('bugunit.TestTag');
//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------
var bugmeta = BugMeta.context();
var spyOnObject = BugDouble.spyOnObject;
var test = TestTag.test;
//-------------------------------------------------------------------------------
// Declare Tests
//-------------------------------------------------------------------------------
/**
* This tests...
* 1) Instantiating a ObservableMap class with no parameters
*/
var observableMapInstantiationTest = {
// Setup Test
//-------------------------------------------------------------------------------
setup: function() {
this.testObservableMap = new ObservableMap();
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
test.assertTrue(Class.doesExtend(this.testObservableMap.getObserved(), Map),
"Assert ObservableMap.observed defaults to a Map")
}
};
bugmeta.tag(observableMapInstantiationTest).with(
test().name("ObservableMap - instantiation test")
);
/**
* This tests...
* 1) Instantiating a ObservableMap class with parameters
*/
var observableMapInstantiationWithParametersTest = {
// Setup Test
//-------------------------------------------------------------------------------
setup: function() {
this.testKey = "testKey";
this.testValue = "testValue";
this.testMap = new Map();
this.testMap.put(this.testKey, this.testValue);
this.testObservableMap = new ObservableMap(this.testMap);
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
test.assertTrue(Class.doesExtend(this.testObservableMap.getObserved(), Map),
"Assert ObservableMap.observed was set to a Map");
test.assertEqual(this.testObservableMap.getObserved().get(this.testKey), this.testValue,
"Assert ObservableMap.observed was set correctly");
}
};
bugmeta.tag(observableMapInstantiationWithParametersTest).with(
test().name("ObservableMap - instantiation with parameters test")
);
});
|
const app = require('../server');
const readline = require('readline');
const {
User,
Role,
RoleMapping,
} = app.models;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
Role.findOne({ where: { name: 'admin' } })
.then((role) => {
if (!role) {
console.log('No admin role found. Create fixtures first.');
process.exit();
}
const admin = {};
const fields = ['username', 'password'];
let field = fields.shift();
console.log(`${field}: `);
rl.on('line', (line) => {
admin[field] = line;
field = fields.shift();
if (!field) {
process.stdout.write('Creating the user... ');
User.create(admin)
.then(user =>
RoleMapping.create({
UserId: user.id,
RoleId: role.id,
})
)
.then(() => {
console.log('Done!\n');
process.exit(0);
})
.catch((err) => {
console.error(err);
process.exit(1);
});
return;
}
process.stdout.write(`${field}: \n`);
});
});
|
var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.addColumn("troop_type", "production_cost", "int", callback);
};
exports.down = function(db, callback) {
};
|
if(Bar.app("Início")) throw "Barra já existe!";
/*/LOADING BAR
$.get("http://hosts.medorc.org/xn--stio-vpa/json/bar.Home.json"),
function(data){
//if(Bar.app(data.name)) throw "Barra já existe!";
$('#header').bar({
toolbox: data,
callback: function(bar){
//(auto) load requested addon
(function(startHash){
if(startHash && startHash != '#!Home' && startHash != '#!Início'){
// gets bar addon (or loads addon script) before callback
Bar.getBar(Bar.urls(startHash), function(error, addon){
// error getting addon
if(error) throw error + " error getting addon " + startHash + " @bar.Home";
// route to addon (select addon tab)
Frontgate.router.route(addon.href);
//console.log('Bar.route', bar, route);
});
}
})(Remote.attr("requestHash"));
// mostrar item IE apenas se o utilizador for "daniel"
if(Situs.attr().user == "daniel") $("#isec-ei").show();
Situs.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}
});
});
/*/
//AUTO LOADING BAR
Bar.load('#header', function(bar, data){
Frontgate.router.on("#Home", function(hash){
location.hash = "Início";
});
// mostrar item IE apenas se o utilizador for "daniel"
if(Frontgate.attr().user == "daniel") $("#isec-ei").show();
Frontgate.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}, FILE);//*/
//------------------------------------------------------------------
// BUG:
// when addon items are not hash banged (#!ToolboxItem)
// the tab is added to the navigator but the toolbox is not selected
//------------------------------------------------------------------
|
// app.js
/*jslint node: true */
'use strict';
var compression = require('compression');
var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var hbs = require('hbs'); // Handlebars templating engine
var configDB = require('./config/database.js'); // Load our db configuration
mongoose.connect(configDB.url); // Connect to our db.
require('./config/passport')(passport); // Configure passport authentication
var app = express();
// Set up express app
app.use(compression({
threshold: 512
}));
app.set('json spaces', 0);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.errorHandler());
app.use(express.methodOverride());
app.use(express.cookieParser('flyingfish'));
app.use(express.session());
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
require('./routes')(app, passport); // Load our routes and pass in our app and passport
app.listen(process.env.PORT || 3000);
|
!function($) {
$(document).on("keydown", 'input[data-type="numeric"]', function (e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
}(window.jQuery || window.ender);
|
import Chip from '../../components/Chip'
import { vueTest } from '../utils'
describe('Chip', () => {
let vm
before((done) => {
vm = vueTest(Chip)
vm.$nextTick(done)
})
it('renders with text', () => {
const el = vm.$('#chip')
el.should.contain.text('Basic chip')
el.should.not.have.class('mdl-chip--contact')
el.should.not.have.class('mdl-chip--deletable')
})
it('renders with close button', () => {
const el = vm.$('#delete')
el.should.contain.text('Deletable chip')
el.should.not.have.class('mdl-chip--contact')
el.should.have.class('mdl-chip--deletable')
const action = vm.$('#delete .mdl-chip__action')
action.should.exist
action.should.have.text('cancel')
})
it('has custom icon', (done) => {
const action = vm.$('#delete .mdl-chip__action')
action.should.have.text('cancel')
vm.deleteIcon = 'star'
vm.nextTick()
.then(() => {
action.should.have.text('star')
})
.then(done, done)
})
it('emits close event', (done) => {
vm.deleted.should.be.false
const action = vm.$('#delete .mdl-chip__action')
action.click()
vm.nextTick()
.then(() => {
vm.deleted.should.be.true
vm.deleted = false
return vm.nextTick()
})
.then(done, done)
})
it('renders text inside circle', (done) => {
vm.$('#contact').should.have.class('mdl-chip--contact')
const el = vm.$('#contact .mdl-chip__contact')
el.should.contain.text(vm.contact)
el.should.not.have.class('mdl-chip--deletable')
vm.contact = 'A'
vm.nextTick()
.then(() => {
el.should.have.text('A')
})
.then(done, done)
})
it('renders image inside circle', () => {
vm.$('#image').should.have.class('mdl-chip--contact')
const el = vm.$('#image .mdl-chip__contact')
el.should.have.attr('src', 'https://getmdl.io/templates/dashboard/images/user.jpg')
el.should.not.have.class('mdl-chip--deletable')
})
})
|
import { hashHistory } from 'react-router'
import { auth } from 'lib/firebase'
export const redirect = path => hashHistory.push(path)
export const signInWithGoogle = () => {
const provider = new auth.GoogleAuthProvider()
provider.addScope('https://www.googleapis.com/auth/userinfo.profile')
return auth().signInWithPopup(provider)
}
export const signInWithFacebook = () => {
const provider = new auth.FacebookAuthProvider()
return auth().signInWithPopup(provider)
}
export const signOut = () => {
return auth().signOut()
}
export const getCurrentUser = () => {
return Promise.resolve(auth().currentUser)
}
|
var request = require('supertest');
var should = require('should');
var express = require('express');
var expressRouter = require('../index.js');
var mockPath = 'mock.js';
describe('register routes', function(){
var app;
before(function(){
app = express();
expressRouter.sync(app, mockPath);
});
it('should have register: GET /api/collection', function(done){
request(app)
.get('/api/collection')
.expect(200)
.expect('OK', done);
});
it('should have register: GET /api/entity/:id', function(done){
request(app)
.get('/api/entity/1')
.expect(200)
.expect('OK', done);
});
it('should have register: POST /api/test', function(done){
request(app)
.post('/api/test')
.expect(201)
.expect('Created', done);
});
});
|
/* eslint no-console: warn */
const _ = require('lodash');
const { processScore } = require('../helpers/game.js');
const getRandomQuiz = require('../../app/helpers/quizRandomizer.js');
module.exports = function socketHandler(io) {
const players = [];
const game = io.of('/game');
game.on('connect', function (socket) {
socket.join('gameRoom');
console.log('connected !!');
console.log('socket ID', socket.id);
console.log('players', players);
socket.on('score update', broadcastScore.bind(null, socket));
socket.on('spectator join', sendPlayers.bind(null, socket, players));
socket.on('player join', handleGame.bind(null, socket));
socket.on('player input', broadcastPlayerCode.bind(null, socket));
});
game.on('disconnect', (socket) => {
console.log('disconnected', socket.id);
});
const handleGame = (socket, player ) => {
console.log('handling game', player);
addPlayer(players, player);
sendPlayers(socket, players);
// if all players ready
if (players.length >= 2) {
// send randomCodeQuizURL
game.emit('quiz url', getRandomQuiz());
}
};
const broadcastScore = (socket, { id, score, passCount, failCount }) => {
console.log('broadcasting score');
socket.to('gameRoom').emit('score update', { id, score: processScore(score), passCount, failCount });
};
const broadcastPlayerCode = (socket, { id, randomCode, code }) => {
socket.to('gameRoom').emit('player input', { id, randomCode, code });
};
const sendPlayers = (socket, players) => {
console.log('sending players');
socket.to('gameRoom').emit('player join', { players });
};
};
function addPlayer(players, newPlayer) {
// !_.some(players, player => _.includes(player, newPlayer.id)) && players.push(newPlayer);
players[newPlayer.id - 1] = newPlayer;
}
|
'use strict';
import Component from './component';
import VolumeAttachment from './volume-attachment';
import Port from './port';
import {isString} from './util';
const Server = function (properties) {
if (!(this instanceof Server)) {
return new Server(properties);
}
Component.call(this, {
ports: [],
...properties
});
};
Server.prototype = Object.create(Component.prototype);
Server.prototype.constructor = Server;
Server.prototype.getDependencies = function () {
return [
...this.dependencies,
...this.properties.ports
]
};
Server.prototype.attachVolume = function (volume, mountPoint) {
const attachment = new VolumeAttachment({
id: `${isString(volume) ? volume : volume.properties.id}-attachment`,
server: this,
volume,
mountPoint
});
this.dependencies.push(attachment);
return this;
};
Server.prototype.attachPort = function (port) {
this.properties.ports.push(port);
return this;
};
Server.prototype.getSchema = function () {
return {
zone: {
type: String
},
name: {
type: String
},
image: {
type: String,
required: true
},
flavor: {
type: String,
required: true
},
keyPair: {
type: String
},
ports: {
type: Array,
items: [String, Port]
}
};
};
Server.prototype.getResources = function () {
const {
id, zone, name, flavor,
keyPair, image, ports
} = this.properties;
const networks = ports.map(port => ({
port: Component.resolve(port)
}));
const properties = {
flavor,
image
};
Object.assign(
properties,
name ? {name} : {},
zone ? {zone} : {},
keyPair ? {key_name: keyPair} : {},
networks.length ? {networks} : {}
);
return {
[id]: {
type: 'OS::Nova::Server',
properties
}
};
};
export default Server;
|
define([
'./src/vertebrae'
], function(Vertebrae) {
return Vertebrae;
});
|
import Ember from 'ember';
import StatefulMixin from './mixins/stateful';
export default Ember.Object.extend(StatefulMixin);
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Animated,
Easing,
View,
} from 'react-native';
const INDETERMINATE_WIDTH_FACTOR = 0.3;
const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR);
export default class ProgressBar extends Component {
static propTypes = {
animated: PropTypes.bool,
borderColor: PropTypes.string,
borderRadius: PropTypes.number,
borderWidth: PropTypes.number,
children: PropTypes.node,
color: PropTypes.string,
height: PropTypes.number,
indeterminate: PropTypes.bool,
progress: PropTypes.number,
style: View.propTypes.style,
unfilledColor: PropTypes.string,
width: PropTypes.number,
};
static defaultProps = {
animated: true,
borderRadius: 4,
borderWidth: 1,
color: 'rgba(0, 122, 255, 1)',
height: 6,
indeterminate: false,
progress: 0,
width: 150,
};
constructor(props) {
super(props);
const progress = Math.min(Math.max(props.progress, 0), 1);
this.state = {
progress: new Animated.Value(props.indeterminate ? INDETERMINATE_WIDTH_FACTOR : progress),
animationValue: new Animated.Value(BAR_WIDTH_ZERO_POSITION),
};
}
componentDidMount() {
if (this.props.indeterminate) {
this.animate();
}
}
componentWillReceiveProps(props) {
if (props.indeterminate !== this.props.indeterminate) {
if (props.indeterminate) {
this.animate();
} else {
Animated.spring(this.state.animationValue, {
toValue: BAR_WIDTH_ZERO_POSITION,
}).start();
}
}
if (
props.indeterminate !== this.props.indeterminate ||
props.progress !== this.props.progress
) {
const progress = (props.indeterminate
? INDETERMINATE_WIDTH_FACTOR
: Math.min(Math.max(props.progress, 0), 1)
);
if (props.animated) {
Animated.spring(this.state.progress, {
toValue: progress,
bounciness: 0,
}).start();
} else {
this.state.progress.setValue(progress);
}
}
}
animate() {
this.state.animationValue.setValue(0);
Animated.timing(this.state.animationValue, {
toValue: 1,
duration: 1000,
easing: Easing.linear,
isInteraction: false,
}).start((endState) => {
if (endState.finished) {
this.animate();
}
});
}
render() {
const {
borderColor,
borderRadius,
borderWidth,
children,
color,
height,
style,
unfilledColor,
width,
...restProps
} = this.props;
const innerWidth = width - (borderWidth * 2);
const containerStyle = {
width,
borderWidth,
borderColor: borderColor || color,
borderRadius,
overflow: 'hidden',
backgroundColor: unfilledColor,
};
const progressStyle = {
backgroundColor: color,
height,
width: innerWidth,
transform: [{
translateX: this.state.animationValue.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth * -INDETERMINATE_WIDTH_FACTOR, innerWidth],
}),
}, {
translateX: this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth / -2, 0],
}),
}, {
scaleX: this.state.progress,
}],
};
return (
<View style={[containerStyle, style]} {...restProps}>
<Animated.View style={progressStyle} />
{children}
</View>
);
}
}
|
import './accounts-config.js';
import './i18n.js';
import './routes.js';
import '../../ui/iso3d/phaser-plugin-isometric.min.js';
|
const basicJson = require('./basic.json')
export const jsonExport = {
basicJson
}
|
describe("OCombo:", function () {
var wtest, $p;
beforeEach(function () {
wtest = frames[0];
$p = wtest.$p;
});
it("Конствуктор должен возвращать объект типа OCombo", function () {
expect(typeof $p).toBe("object");
});
});
|
import { exec } from "child_process"
import test from "tape"
import cliBin from "./utils/cliBin"
test("--watch error if no input files", (t) => {
exec(
`${ cliBin }/testBin --watch`,
(err, stdout, stderr) => {
t.ok(
err,
"should return an error when <input> or <output> are missing when " +
"`--watch` option passed"
)
t.ok(
stderr.includes("--watch requires"),
"should show an explanation when <input> or <output> are missing when" +
" `--watch` option passed"
)
t.end()
}
)
})
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['de_LU@euro'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N",
"country_name": "Luxemburg",
"country_post": null,
"country_ab2": "LU",
"country_ab3": "LUX",
"country_num": 442,
"country_car": "L",
"country_isbn": null,
"lang_name": "Deutsch",
"lang_ab": "de",
"lang_term": "deu",
"lang_lib": "ger"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1jJyY]",
"noexpr": "^[-0nN]",
"yesstr": "ja",
"nostr": "nein"
},
"LC_MONETARY": {
"currency_symbol": "\u20ac",
"mon_decimal_point": ",",
"mon_thousands_sep": ".",
"mon_grouping": [
3,
3
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 1,
"p_sep_by_space": 1,
"n_cs_precedes": 1,
"n_sep_by_space": 1,
"p_sign_posn": 4,
"n_sign_posn": 4,
"int_curr_symbol": "EUR ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%d%t%g%t%m%t%f",
"name_gen": null,
"name_mr": null,
"name_mrs": null,
"name_miss": null,
"name_ms": null
},
"LC_NUMERIC": {
"decimal_point": ",",
"thousands_sep": ".",
"grouping": [
3,
3
]
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": "+%c %a %l",
"tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "352"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"So",
"Mo",
"Di",
"Mi",
"Do",
"Fr",
"Sa"
],
"day": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"week": [
7,
19971130,
4
],
"abmon": [
"Jan",
"Feb",
"M\u00e4r",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez"
],
"mon": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"d_t_fmt": "%a %d %b %Y %T %Z",
"d_fmt": "%Y-%m-%d",
"t_fmt": "%T",
"am_pm": [
"",
""
],
"t_fmt_ampm": "",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": 2,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
|
// TODO: Add tests
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from '../credentials.json';
import init from '../init';
import { upsert } from '../../lib/util';
function passportInit() {
// serialize user into the session
init();
passport.use(new GoogleStrategy(
authConfig.google,
(accessToken, refreshToken, profile, done) => {
const params = {
email: profile.emails[0].value,
external_auth_type: 'google',
};
const data = {
first_name: profile.name.givenName,
last_name: profile.name.familyName,
email: profile.emails.length && profile.emails[0].value,
photo_url: profile.photos.length && profile.photos[0].value,
external_auth_type: 'google',
external_auth_id: profile.id,
};
upsert('/users', params, data)
.then(resp => done(null, resp))
.catch(err => done(err));
},
));
}
passportInit();
export default passport;
|
var React = require('react');
var _ = require('underscore');
var List = React.createClass({
render: function() {
var listItems = [];
_.each(this.props.value, function(data, index) {
listItems.push(<li>{JSON.stringify(data)}</li>);
});
return (
<div>
<strong>{this.props.title}:</strong>
<ol>{listItems}</ol>
</div>
);
}
});
module.exports = List;
|
var Helper = require("@kaoscript/runtime").Helper;
module.exports = function() {
var path = require("path");
require("../require/require.string.ks")(Helper.cast(path.join(__dirname, "foobar.txt"), "String", false, null, "String"));
};
|
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}]);
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) {
$scope.phone = data;
$scope.mainImageUrl = data.images[0];
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}]);
|
var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
});
elixir(function(mix) {
mix.scriptsIn('resources/assets/js/');
});
|
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/views/Home.vue';
import Sms from '@/views/SMS.vue';
import Services from '@/views/Services.vue';
import Settings from '@/views/Settings.vue';
import Wlan from '@/views/settings/wlan.vue';
import DialUp from '@/views/settings/dialup.vue';
import AppSettings from '@/views/AppSettings.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
redirect: { name: 'home' },
},
{
path: '/home',
name: 'home',
component: Home,
},
{
path: '/sms',
name: 'sms',
component: Sms,
},
{
path: '/statistics',
name: 'statistics',
},
{
path: '/services',
name: 'services',
component: Services,
},
{
path: '/settings',
name: 'settings',
component: Settings,
redirect: { name: 'settings/wlan' },
children: [
{
path: 'wlan',
name: 'settings/wlan',
component: Wlan,
label: 'WLAN',
},
{
path: 'dialup',
name: 'settings/dialup',
component: DialUp,
label: 'Dial-up',
},
],
},
{
path: '/app-settings',
name: 'appSettings',
component: AppSettings,
},
],
});
|
import React, {PropTypes, Component} from 'react';
import { NavGroup } from 'react-photonkit'
/*class NavGroup extends Component {
static propTypes = {
children: PropTypes.any
}
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<nav className="nav-group">
{this.props.children}
</nav>
);
}
}*/
export default NavGroup
|
var model = require('model');
var adapter = require('./..').adapter;
var Issue = function () {
this.adapter = adapter;
this.property('assignees','string');
this.property('htmlUrl','string');
this.property('number','number');
this.property('state','string');
this.property('title','string');
this.property('body','string');
this.property('user','object');
this.property('labels','object');
this.property('assignee','object');
this.property('milestone','object');
this.property('comments','number');
this.property('pullRequest','object');
this.property('closedAt','date');
this.property('createdAt','date');
this.property('updatedAt','date');
this.property('trckrState','string');
this.property('trckrLastReview','date');
this.property('trckrPingback','string'); // ping me back in a specific future
};
model.register('Issue', Issue);
|
"use strict";
const RandomStrategy = require("../../../src/strategies/random");
const { extendExpect } = require("../utils");
extendExpect(expect);
describe("Test RandomStrategy", () => {
it("test with empty opts", () => {
const strategy = new RandomStrategy();
const list = [
{ a: "hello" },
{ b: "world" },
];
expect(strategy.select(list)).toBeAnyOf(list);
expect(strategy.select(list)).toBeAnyOf(list);
expect(strategy.select(list)).toBeAnyOf(list);
});
});
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
$scope.alerts = [
{
icon: 'glyphicon-user',
colour: 'btn-success',
total: '20,408',
description: 'TOTAL CUSTOMERS'
},
{
icon: 'glyphicon-calendar',
colour: 'btn-primary',
total: '8,382',
description: 'UPCOMING EVENTS'
},
{
icon: 'glyphicon-edit',
colour: 'btn-success',
total: '527',
description: 'NEW CUSTOMERS IN 24H'
},
{
icon: 'glyphicon-record',
colour: 'btn-info',
total: '85,000',
description: 'EMAILS SENT'
},
{
icon: 'glyphicon-eye-open',
colour: 'btn-warning',
total: '268',
description: 'FOLLOW UPS REQUIRED'
},
{
icon: 'glyphicon-flag',
colour: 'btn-danger',
total: '348',
description: 'REFERRALS TO MODERATE'
}
];
}
]);
|
var Vector = function(values) {
// An N-Dimensional vector.
//
// Args:
// values: A list of values for each dimension of the vector.
var self = this;
self.values = values;
self.hash = function() {
// Generate a hash of the vector.
//
// Returns:
// A hash of the vector.
var r = '';
var i;
for (i = 0; i < self.values.length; i++) {
r += String(self.values[i]) + ','
}
return '[' + r + ']';
};
self.copy = function() {
// Get a duplicate vector.
return (new Vector(self.values.slice()));
};
self.divide = function(c) {
// Divide the vector by a constant.
//
// Args:
// c: A constant.
//
// Returns:
// A new vector with each value divided by c.
return self.multiply(1 / c);
};
self.multiply = function(c) {
// Multiply the vector by a constant.
//
// Args:
// c: A constant.
//
// Returns:
// A new vector with each value multiplied by c.
var copy = self.copy();
var i;
for (i = 0; i < self.values.length; i++) {
copy.values[i] *= c;
}
return copy;
};
self.add = function(other) {
// Add another vector to self.
//
// Args:
// other: Another vector.
//
// Returns:
// The resultant vector.
var values = [];
var i;
if (self.dimension() != other.dimension()) {
var msg = "Cannot add two vectors of different dimensionality.";
log(loglevel.error, msg);
throw (new Error(msg));
}
for (i = 0; i < self.values.length; i++) {
values.push(self.values[i] + other.values[i]);
}
return (new Vector(values));
};
self.subtract = function(other) {
// Subtract another vector from self.
//
// Args:
// other: Another vector.
//
// Returns:
// The resultant vector from other to self.
var values = [];
var i;
if (self.dimension() != other.dimension()) {
var msg = "Cannot subtract two vectors of different dimensionality.";
log(loglevel.error, msg);
throw (new Error(msg));
}
for (i = 0; i < self.values.length; i++) {
values.push(self.values[i] - other.values[i]);
}
return (new Vector(values));
};
self.dimension = function() {
// Get the dimension of the vector.
return self.values.length;
};
self.magnitude = function() {
// Get the magnitude of this vector.
var s = 0;
var i;
var dimension = self.dimension();
for (i = 0; i < self.values.length; i++) {
s += Math.pow(self.values[i], dimension)
}
return Math.pow(s, 1 / dimension);
};
self.unit = function() {
// Get a unit vector in the direction of this vector.
return self.divide(self.magnitude());
};
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = fn;
var _includes = require('utilise/includes');
var _includes2 = _interopRequireDefault(_includes);
var _client = require('utilise/client');
var _client2 = _interopRequireDefault(_client);
var _all = require('utilise/all');
var _all2 = _interopRequireDefault(_all);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// register custom element prototype (render is automatic)
function fn(ripple) {
return function (res) {
if (!customs || !customEl(res) || registered(res)) return (0, _all2.default)(res.name + ':not([inert])\n ,[is="' + res.name + '"]:not([inert])').map(ripple.draw);
var proto = Object.create(HTMLElement.prototype),
opts = { prototype: proto };
proto.attachedCallback = ripple.draw;
document.registerElement(res.name, opts);
};
}
var registered = function registered(res) {
return document.createElement(res.name).attachedCallback;
};
var customs = _client2.default && !!document.registerElement,
customEl = function customEl(d) {
return (0, _includes2.default)('-')(d.name);
};
|
'use strict';
/* jshint -W098 */
angular.module('mean.rules').controller('RulesController', ['$scope', '$stateParams', '$location', '$http','Global', 'Rules', 'MeanUser','Circles','Groups',
function($scope, $stateParams, $location, $http, Global, Rules, MeanUser,Circles,Groups) {
$scope.global = Global;
$scope.rules = {};
$scope.rule = {};
$scope.groups={};
$scope.sortType = 'name'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchFish = ''; // set the default search/filter term
$scope.hasAuthorization = function(rule) {
if (!rule || !rule.user) return false;
return MeanUser.isAdmin || rule.user._id === MeanUser.user._id;
};
$scope.popup1 = {
opened: false
};
$scope.testdataerror=false;
$scope.popup2 = {
opened: false
};
$scope.testdataresult='';
$scope.openpicker1 = function() {
$scope.popup1.opened = true;
};
$scope.openpicker2 = function() {
$scope.popup2.opened = true;
};
$scope.availableCircles = [];
Circles.mine(function(acl) {
$scope.availableCircles = acl.allowed;
$scope.allDescendants = acl.descendants;
});
$scope.showDescendants = function(permission) {
var temp = $('.ui-select-container .btn-primary').text().split(' ');
temp.shift(); //remove close icon
var selected = temp.join(' ');
$scope.descendants = $scope.allDescendants[selected];
};
$scope.selectPermission = function() {
$scope.descendants = [];
};
$scope.create = function(isValid) {
if (isValid) {
// $scope.article.permissions.push('test test');
var rule = new Rules($scope.rule);
rule.$save(function(response) {
$location.path('rules/' + response._id);
});
$scope.rules = {};
} else {
$scope.submitted = true;
}
};
$scope.remove = function(rule) {
if (rule) {
rule.$remove(function(response) {
for (var i in $scope.rules) {
if ($scope.rules[i] === rule) {
$scope.rules.splice(i, 1);
}
}
$location.path('rules');
});
} else {
$scope.rules.$remove(function(response) {
$location.path('rules');
});
}
};
$scope.update = function(isValid) {
if (isValid) {
var rule = $scope.rule;
if (!rule.updated) {
rule.updated = [];
}
rule.updated.push(new Date().getTime());
rule.$update(function() {
$location.path('rules/' + rule._id);
});
} else {
$scope.submitted = true;
}
};
$scope.findGroups = function() {
Groups.query(function(groups) {
$scope.groups = groups;
});
};
$scope.find = function() {
Rules.query(function(rules) {
$scope.rules = rules;
});
};
$scope.findOne = function() {
Rules.get({
ruleId: $stateParams.ruleId
}, function(rule) {
$scope.rule = rule;
});
};
$scope.documentupdate = function(testdata) {
$scope.testdataerror=false;
try{
testdata = JSON.parse(testdata);
} catch (ex) {
$scope.testdataerror=true;
}
}
$scope.cmdtestdata = function (testdata,execIf,execThen,execElse) {
var td={};
$scope.testdataerror=false;
try{
td = JSON.parse(testdata);
} catch (ex) {
$scope.testdataerror=true;
return;
}
$scope.testdataresult = '';
$http({
method: 'PUT',
url: '/api/rulesprocessor/testdata' ,
headers: {
'Content-Type': 'application/json'
},
data: {
"document": td,
"execIf":execIf,
"execThen":execThen,
"execElse":execElse
}
}).then(function successCallback(response) {
if (response.data === undefined) {
$scope.testdataresult = '';
} else {
$scope.testdataresult = '' +
'IF() evaluated to: ' + response.data.resExecIf.var0 +
'\nThen() evaluated to: ' + JSON.stringify(response.data.resExecThen) +
'\nElse() evaluated to: ' + JSON.stringify(response.data.resExecElse);
}
}, function errorCallback(response) {
$scope.testdataresult = 'Error: (HTTP ' + response.status + ') ' + response.data.error;
});
}
}
]);
|
var utilities = (function(window, $){
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function topHalfRoundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + width, y);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function bottomHalfRoundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height);
ctx.lineTo(x, y + height);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
return {
drawRoundRect: roundRect,
drawTopHalfRoundRect: topHalfRoundRect,
drawBottomHalfRoundRect: bottomHalfRoundRect
}
})(window, $);
|
var c = require("./config").twitter;
var Twit = require('twit');
//console.log(c);
console.log(c.apiKey);
console.log(c.apiSecret);
console.log(c.accessToken);
console.log(c.accessTokenSecret);
var T = new Twit({
consumer_key: c.apiKey,
consumer_secret: c.apiSecret,
access_token: c.accessToken,
access_token_secret: c.accessTokenSecret
});
/*
T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
console.log(err);
})
*/
//console.log(T);
//
// tweet 'hello world!'
//
T.get('search/tweets', { q: 'banana since:2011-11-11', count: 100 }, function(err, data, res) {
console.log(data);
//console.log(err);
//console.log(res);
});
|
// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from './utils/asyncInjectors';
const errorLoading = (err) => {
console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};
const loadModule = (cb) => (componentModule) => {
cb(null, componentModule.default);
};
export default function createRoutes(store) {
// create reusable async injectors using getAsyncInjectors factory
const { injectReducer, injectSagas } = getAsyncInjectors(store);
return [
{
path: '/',
name: 'home',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/HomePage/reducer'),
import('containers/HomePage/sagas'),
import('containers/HomePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('home', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/features',
name: 'features',
getComponent(nextState, cb) {
import('containers/FeaturePage')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/login',
name: 'login',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/LoginPage/reducer'),
import('containers/LoginPage/sagas'),
import('containers/LoginPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('loginPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/signup',
name: 'signup',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/SignupPage/reducer'),
import('containers/SignupPage/sagas'),
import('containers/SignupPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('signupPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/restorepassword',
name: 'restorepassword',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/PasswordRestorePage/reducer'),
import('containers/PasswordRestorePage/sagas'),
import('containers/PasswordRestorePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('passwordRestorePage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/trackingpage',
name: 'trackingpage',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/TrackingPage/reducer'),
import('containers/TrackingPage/sagas'),
import('containers/TrackingPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('trackingPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/userprofile',
name: 'userprofilepage',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/UserProfilePage/reducer'),
import('containers/UserProfilePage/sagas'),
import('containers/UserProfilePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('userProfilePage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '*',
name: 'notfound',
getComponent(nextState, cb) {
import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
];
}
|
/**
* Fac.js
* (c) 2017 Owen Luke
* https://github.com/tasjs/fac
* Released under the MIT License.
*/
var copy = require('./copy');
var chain = require('./chain');
var super_ = require('./super');
var core = {
new: function(options){
typeof options === 'string' && (options = {name: options});
var obj = chain.create(this, options);
obj.protoName = this.name;
obj.model = this;
obj.super = super_;
chain.init(obj.parent, options, obj);
return obj;
},
extends: function(proto, p1){
var obj = chain.create(this, {});
var options = proto;
if (typeof p1 !== 'undefined') {
var args = Array.prototype.slice.call(arguments);
for (var i = 0, len = args.length - 1; i < len; i ++) {
options = args[i];
copy.do(obj, options);
}
options = args[i];
}
copy.do(obj, options);
obj.protoName = options.name;
obj.super = super_;
typeof options.default === 'function' && options.default.call(obj, options);
return obj;
},
ext: function(options){
copy.do(this, options);
return this;
},
spawn: function(options) {
typeof options === 'string' && (options = {name: options});
var obj = Object.create(this);
copy.do(obj, options);
chain.init(this, options, obj);
return obj;
},
isChildOf: function(obj){
return chain.isChildOf(obj, this);
},
isParentOf: function(obj){
return chain.isParentOf(obj, this);
},
isAncestorOf: function(obj){
return chain.isAncestorOf(obj, this);
},
isDescendantOf: function(obj){
return chain.isDescendantOf(obj, this);
},
isModelOf: function(obj){
return this === obj.model;
},
isCopyOf: function(obj){
return this.model === obj;
}
};
module.exports = core;
|
const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser')
// const formidable = require('formidable');
// const createTorrent = require('create-torrent');
// const WebTorrent = require('webtorrent');
const socketController = require('./socketController');
// max # of sockets to keep open
const socketLimit = 1;
// takes in Node Server instance and returns Express Router
module.exports = function nileServer(server) {
// Pass server instance to use socket controller
const socket = new socketController(server, socketLimit);
// create nile.js mini-app through express Router
const nileServer = express.Router();
// endpoint for receiving magnet URI from Broadcaster
nileServer.post('/magnet', (req, res, next) => {
socket.emitNewMagnet(req.body.magnetURI);
res.sendStatus(200);
});
return nileServer;
}
|
const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'eval',
output: {
path: path.join(__dirname, '/public'),
publicPath: '/public/',
filename: 'bundle.js'
},
devServer: {
publicPath: '/public/',
historyApiFallback: true
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modlues/
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
include: path.resolve(__dirname, 'js'),
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
]
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!autoprefixer-loader!sass-loader'
},
{
test: /\.otf$/,
loader: 'file-loader?name=fonts/[name].[ext]'
}
]
}
}
|
import SqSortableList from 'sq-ember-inputs/components/sq-sortable-list';
export default SqSortableList;
|
(function() {
"use strict";
angular.module('common.dragdrop', [])
.factory('DragDropHandler', [function() {
return {
dragObject: undefined,
addObject: function(object, objects, to) {
objects.splice(to, 0, object);
},
moveObject: function(objects, from, to) {
objects.splice(to, 0, objects.splice(from, 1)[0]);
}
};
}])
.directive('draggable', ['DragDropHandler', function(DragDropHandler) {
return {
scope: {
draggable: '='
},
link: function(scope, element, attrs){
element.draggable({
connectToSortable: attrs.draggableTarget,
helper: "clone",
revert: "invalid",
start: function() {
DragDropHandler.dragObject = scope.draggable;
},
stop: function() {
DragDropHandler.dragObject = undefined;
}
});
element.disableSelection();
}
};
}])
.directive('droppable', ['DragDropHandler', function(DragDropHandler) {
return {
scope: {
droppable: '=',
ngMove: '&',
ngCreate: '&'
},
link: function(scope, element, attrs){
element.sortable({
connectWith: ['.draggable','.sortable'],
});
element.disableSelection();
element.on("sortdeactivate", function(event, ui) {
var from = (angular.element(ui.item).scope()) ? angular.element(ui.item).scope().$index : undefined;
var to = element.children().index(ui.item);
var list = element.attr('id');
if (to >= 0 ){
scope.$apply(function(){
if (from >= 0) {
//item is coming from a sortable
if (!ui.sender || ui.sender[0] === element[0]) {
//item is coming from this sortable
DragDropHandler.moveObject(scope.droppable, from, to);
} else {
//item is coming from another sortable
scope.ngMove({
from: from,
to: to,
fromList: ui.sender.attr('id'),
toList: list
});
ui.item.remove();
}
} else {
//item is coming from a draggable
scope.ngCreate({
object: DragDropHandler.dragObject,
to: to,
list: list
});
ui.item.remove();
}
});
}
});
}
};
}])
;})();
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _functionalCurry = require('../functional/curry');
var lt = (0, _functionalCurry.curry)(function (a, b) {
return a < b;
});
exports.lt = lt;
|
/**
* Blog-api.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
}
};
|
/**
* Palindromic Substrings
*
* Given a string, your task is to count how many palindromic substrings in this string.
*
* The substrings with different start indexes or end indexes are counted as different substrings even they consist of
* same characters.
*
* Example 1:
*
* Input: "abc"
* Output: 3
* Explanation: Three palindromic strings: "a", "b", "c".
*
* Example 2:
*
* Input: "aaa"
* Output: 6
* Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
*
* Note:
* The input string length won't exceed 1000.
*/
/**
* @param {string} s
* @return {number}
*/
const countSubstrings = s => {
const extendPalindrome = (s, left, right) => {
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++;
left--;
right++;
}
};
if (!s || s.length === 0) {
return 0;
}
let count = 0;
for (let i = 0; i < s.length; i++) {
// i is the mid point
extendPalindrome(s, i, i); // odd length;
extendPalindrome(s, i, i + 1); // even length
}
return count;
};
export { countSubstrings };
|
jest.unmock('../../src/filtering/filter');
import React from 'react';
import {shallow} from 'enzyme';
import {Filter} from '../../src/filtering/filter';
describe('Filter', () => {
it('has empty filtering text by default', () => {
// when
const filter = shallow(
<Filter/>
);
// then
expect(filter.props().value).toEqual('');
});
it('changes provided filtering text', () => {
// given
const state = {
textToUse : 'abc'
};
const filter = shallow(
<Filter filteringText={state.textToUse}
onFilteringTextChange={text => state.textToUse = text}/>
);
// when
filter.simulate('change', { target : { value : 'def' } });
expect(state.textToUse).toEqual('def');
});
});
|
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import {
killApp,
findPort,
launchApp,
nextStart,
nextBuild,
fetchViaHTTP,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import cheerio from 'cheerio'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../')
const gip404Err = /`pages\/404` can not have getInitialProps\/getServerSideProps/
let appPort
let app
describe('404 Page Support with _app', () => {
describe('production mode', () => {
afterAll(() => killApp(app))
it('should build successfully', async () => {
const { code, stderr, stdout } = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
expect(code).toBe(0)
expect(stderr).not.toMatch(gip404Err)
expect(stdout).not.toMatch(gip404Err)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
it('should not output static 404 if _app has getInitialProps', async () => {
const browser = await webdriver(appPort, '/404')
const isAutoExported = await browser.eval('__NEXT_DATA__.autoExport')
expect(isAutoExported).toBe(null)
})
it('specify to use the 404 page still in the routes-manifest', async () => {
const manifest = await fs.readJSON(
join(appDir, '.next/routes-manifest.json')
)
expect(manifest.pages404).toBe(true)
})
it('should still use 404 page', async () => {
const res = await fetchViaHTTP(appPort, '/abc')
expect(res.status).toBe(404)
const $ = cheerio.load(await res.text())
expect($('#404-title').text()).toBe('Hi There')
})
})
describe('dev mode', () => {
let stderr = ''
let stdout = ''
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg
},
onStdout(msg) {
stdout += msg
},
})
})
afterAll(() => killApp(app))
it('should not show pages/404 GIP error if _app has GIP', async () => {
const res = await fetchViaHTTP(appPort, '/abc')
expect(res.status).toBe(404)
const $ = cheerio.load(await res.text())
expect($('#404-title').text()).toBe('Hi There')
expect(stderr).not.toMatch(gip404Err)
expect(stdout).not.toMatch(gip404Err)
})
})
})
|
'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), mockResponse(), done);
deferred.resolve();
});
it('Should return 201 created', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
responseSpy.args[0][0].should.equal(201);
done();
}
deferred.resolve();
});
it('Should return an id property with the scenario id', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
const body = responseSpy.args[0][1];
body.should.deep.equal({id: idsGeneratorStub()});
done();
}
deferred.resolve();
});
it('Should store the scenario data and id', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const bookId = 'abc1234';
const mockedRequest = mockRequest(bookId);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockedRequest, mockResponse(), checkResponse);
deferred.resolve();
function checkResponse() {
persistEpisodeInStorage.calledOnce.should.equal(true);
persistEpisodeInStorage.args[0][0].should.equal(bookId);
persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body));
done();
}
});
afterEach(() => {
mockery.deregisterAll();
mockery.disable();
});
});
function getCreateEpisodeMiddleware(idsMock, persistEpisodeInStorage) {
mockery.registerMock('../idsGenerator/generateId.js', idsMock);
mockery.registerMock('./persistEpisodeInStorage.js', persistEpisodeInStorage);
mockery.enable({
useCleanCache: true,
warnOnReplace: false,
warnOnUnregistered: false
});
return require('../../src/episodes/createEpisode.js');
}
function mockResponse() {
return { json: () => {} };
}
function mockRequest(bookId) {
return {
context: {
bookId: bookId
},
body: {
a: 1,
b: 2
}
};
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M4 17h6v2H4zm13-6H4v2h13.25c1.1 0 2 .9 2 2s-.9 2-2 2H15v-2l-3 3 3 3v-2h2c2.21 0 4-1.79 4-4s-1.79-4-4-4zM4 5h16v2H4z" />
, 'WrapTextTwoTone');
|
import React from 'react';
import {shallow} from 'enzyme';
import {BareCheckSuiteView} from '../../lib/views/check-suite-view';
import CheckRunView from '../../lib/views/check-run-view';
import checkSuiteQuery from '../../lib/views/__generated__/checkSuiteView_checkSuite.graphql';
import {checkSuiteBuilder} from '../builder/graphql/timeline';
describe('CheckSuiteView', function() {
function buildApp(override = {}) {
const props = {
checkSuite: checkSuiteBuilder(checkSuiteQuery).build(),
checkRuns: [],
switchToIssueish: () => {},
...override,
};
return <BareCheckSuiteView {...props} />;
}
it('renders the summarized suite information', function() {
const checkSuite = checkSuiteBuilder(checkSuiteQuery)
.app(a => a.name('app'))
.status('COMPLETED')
.conclusion('SUCCESS')
.build();
const wrapper = shallow(buildApp({checkSuite}));
const icon = wrapper.find('Octicon');
assert.strictEqual(icon.prop('icon'), 'check');
assert.isTrue(icon.hasClass('github-PrStatuses--success'));
assert.strictEqual(wrapper.find('.github-PrStatuses-list-item-context strong').text(), 'app');
});
it('omits app information when the app is no longer present', function() {
const checkSuite = checkSuiteBuilder(checkSuiteQuery)
.nullApp()
.build();
const wrapper = shallow(buildApp({checkSuite}));
assert.isTrue(wrapper.exists('Octicon'));
assert.isFalse(wrapper.exists('.github-PrStatuses-list-item-context'));
});
it('renders a CheckRun for each run within the suite', function() {
const checkRuns = [{id: 0}, {id: 1}, {id: 2}];
const wrapper = shallow(buildApp({checkRuns}));
assert.deepEqual(wrapper.find(CheckRunView).map(v => v.prop('checkRun')), checkRuns);
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var minus = exports.minus = { "viewBox": "0 0 20 20", "children": [{ "name": "path", "attribs": { "d": "M16,10c0,0.553-0.048,1-0.601,1H4.601C4.049,11,4,10.553,4,10c0-0.553,0.049-1,0.601-1h10.799C15.952,9,16,9.447,16,10z" } }] };
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var Utilities_1 = require("../../Utilities");
var stylesImport = require("./Check.scss");
var styles = stylesImport;
var Check = (function (_super) {
__extends(Check, _super);
function Check() {
return _super !== null && _super.apply(this, arguments) || this;
}
Check.prototype.shouldComponentUpdate = function (newProps) {
return this.props.isChecked !== newProps.isChecked || this.props.checked !== newProps.checked;
};
Check.prototype.render = function () {
var _a = this.props, isChecked = _a.isChecked, checked = _a.checked;
isChecked = isChecked || checked;
return (React.createElement("div", { className: Utilities_1.css('ms-Check', styles.root, (_b = {},
_b['is-checked ' + styles.rootIsChecked] = isChecked,
_b)) },
React.createElement("div", { className: Utilities_1.css('ms-Icon ms-Check-background', styles.background) }),
React.createElement("i", { className: Utilities_1.css('ms-Check-check ms-Icon ms-Icon--CheckMark', styles.check) })));
var _b;
};
return Check;
}(Utilities_1.BaseComponent));
Check.defaultProps = {
isChecked: false
};
exports.Check = Check;
//# sourceMappingURL=Check.js.map
|
var Buffer = require('buffer').Buffer,
Jpeg = require('jpeg').Jpeg;
function randomColorComponent() {
return Math.floor(Math.random() * 256);
}
/**
* Creates a random image
*/
module.exports = function(width, height, callback) {
var buffer = new Buffer(width * height * 3);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
var pixelStart = x * width * 3 + y * 3;
buffer[pixelStart + 0] = randomColorComponent();
buffer[pixelStart + 1] = randomColorComponent();
buffer[pixelStart + 2] = randomColorComponent();
}
}
var image = new Jpeg(buffer, width, height);
image.encode(function(result) {
callback(null, result);
});
};
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import themed from '@rentpath/react-themed'
import clsx from 'clsx'
import isEqual from 'lodash/isEqual'
import { randomId } from '@rentpath/react-ui-utils'
import SubmitButton from './SubmitButton'
import Header from './Header'
import {
Form,
Field,
Name,
Message,
Email,
Phone,
RadioGroup,
OptInNewsLetter,
TermsOfService,
} from '../Form'
const FIELD_MAPPING = {
header: Header,
name: Name,
message: Message,
email: Email,
phone: Phone,
tos: TermsOfService,
submit: SubmitButton,
opt_in_newsletter: OptInNewsLetter,
terms_of_service: TermsOfService,
}
const FIELDS = [
{ name: 'header' },
{ name: 'message' },
{ name: 'name' },
{ name: 'email' },
{ name: 'phone' },
{ name: 'submit' },
{ name: 'opt_in_newsletter' },
{ name: 'terms_of_service' },
]
@themed(/^(LeadForm|Field)/)
export default class LeadForm extends Component {
static propTypes = {
theme: PropTypes.object,
className: PropTypes.string,
fields: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
field: PropTypes.oneOfType([
PropTypes.func,
PropTypes.node,
]),
}),
),
children: PropTypes.node,
}
static defaultProps = {
theme: {},
fields: FIELDS,
}
constructor(props) {
super(props)
this.generateRandomId()
}
componentWillReceiveProps() {
this.generateRandomId()
}
shouldComponentUpdate(nextProps) {
return !isEqual(this.props.fields, nextProps.fields)
}
get fields() {
const { fields } = this.props
return fields.map(fieldComposition => {
const {
field,
className,
...props
} = fieldComposition
const name = props.name
const FormField = field || FIELD_MAPPING[name] || this.fallbackField(props.type)
return (
<FormField
data-tid={`lead-form-${name}`}
key={`${this.id}-${name}`}
{...props}
/>
)
})
}
generateRandomId() {
this.id = randomId('leadform')
}
fallbackField(type) {
return type === 'radiogroup' ? RadioGroup : Field
}
render() {
const {
className,
theme,
fields,
children,
...props
} = this.props
return (
<Form
className={clsx(
theme.LeadForm,
className,
)}
{...props}
>
{this.fields}
{children}
</Form>
)
}
}
|
export * from './user';
export * from './template';
|
var gulp = require("gulp"),
del = require("del"),
ts = require("gulp-typescript"),
tsProject = ts.createProject("tsconfig.json")
typedoc = require("gulp-typedoc");
var compileTS = function () {
return tsProject.src()
.pipe(tsProject())
.js.pipe(gulp.dest("app"));
};
gulp.task("doc", function() {
return gulp
.src(["src/**/*.ts"])
.pipe(typedoc({
module: "commonjs",
target: "es5",
out: "docs/",
name: "My project title"
}))
;
});
gulp.task("ts", compileTS);
gulp.task("cleanup", function() {
return del([__dirname + "/app"]);
});
gulp.task("default", ["cleanup", "ts"], function () {
compileTS();
gulp.watch("src/**/*.ts", ["ts"]);
});
|
/* global describe, it, beforeEach */
'use strict';
process.env.NODE_ENV = 'test';
var sharedModule = require('../lib/module-shared');
var instance1;
var instance2;
var should = require('should');
var stubs = {};
describe('Private Module Tests', function () {
beforeEach(function (done) {
for (var stub in stubs) {
try {
stubs[stub].restore();
}
catch (err) {}
}
done();
});
describe('Initializing', function () {
describe('when creating a new instance of the module', function () {
it('should not have an error', function (done) {
var x = sharedModule({
mocking: true
});
x.should.have.property('initializeModule');
should.not.exist(x.initialized);
done();
});
});
});
describe('Function Calls', function () {
describe('when calling "initializeModule"', function () {
it('should not have an error', function (done) {
var x = sharedModule({
mocking: {}
});
x.should.have.property('initializeModule');
should.not.exist(x.initialized);
x.initializeModule(x);
should.exist(x.initialized);
done();
});
});
describe('when creating more than one instance', function () {
describe('and the module is already initialized', function () {
it('the new instance should return the first created instance', function (done) {
instance1 = sharedModule({
mocking: true
});
instance2 = sharedModule({
mocking: true
});
should.exist(instance1.initialized);
instance1.initialized.should.equal(true);
done();
});
});
describe('if we add .name = "instance1" to the first instance', function () {
it('"instance2" should have a name', function (done) {
delete instance1.name;
delete instance2.name;
instance1.name = 'instance1';
instance1.name.should.equal('instance1');
instance2.name.should.equal('instance1');
done();
});
});
describe('if we add .name = "instance2" to the second instance', function () {
it('"instance1" should have a name', function (done) {
delete instance1.name;
delete instance2.name;
instance2.name = 'instance2';
instance2.name.should.equal('instance2');
instance1.name.should.equal('instance2');
done();
});
});
describe('if we add .name to both instances and they are different names', function () {
it('they should still have the same names', function (done) {
delete instance1.name;
delete instance2.name;
instance1.name = 'instance1';
instance1.name.should.equal('instance1');
instance2.name.should.equal('instance1');
instance2.name = 'instance2';
instance1.name.should.equal('instance2');
instance2.name.should.equal('instance2');
instance1.name.should.equal(instance2.name);
instance2.name.should.equal(instance1.name);
done();
});
});
});
});
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './layout.js';
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(<Layout />, document.getElementById('main'));
});
|
$.fn.onEnterKey =
function( closure ) {
$(this).keypress(
function( event ) {
var code = event.keyCode ? event.keyCode : event.which;
if (code == 13) {
closure();
return false;
}
} );
}
String.prototype.trunc = String.prototype.trunc ||
function(n){
return this.length>n ? this.substr(0,n-1)+'…' : this;
};
|
/**
* Pipedrive API v1
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
/**
* The UpdateFileRequest model module.
* @module model/UpdateFileRequest
* @version 1.0.0
*/
class UpdateFileRequest {
/**
* Constructs a new <code>UpdateFileRequest</code>.
* @alias module:model/UpdateFileRequest
*/
constructor() {
UpdateFileRequest.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>UpdateFileRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/UpdateFileRequest} obj Optional instance to populate.
* @return {module:model/UpdateFileRequest} The populated <code>UpdateFileRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new UpdateFileRequest();
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
delete data['name'];
}
if (data.hasOwnProperty('description')) {
obj['description'] = ApiClient.convertToType(data['description'], 'String');
delete data['description'];
}
if (Object.keys(data).length > 0) {
obj['extra'] = data;
}
}
return obj;
}
}
/**
* Visible name of the file
* @member {String} name
*/
UpdateFileRequest.prototype['name'] = undefined;
/**
* Description of the file
* @member {String} description
*/
UpdateFileRequest.prototype['description'] = undefined;
export default UpdateFileRequest;
|
export default class ContestType {
constructor(options) {
let _id = null;
let _name = null;
let _berryFlavor = null;
let _color = null;
Object.defineProperty(this, 'id', {
enumarable: true,
get() {
return _id;
}
});
Object.defineProperty(this, 'name', {
enumarable: true,
get() {
return _name;
}
});
Object.defineProperty(this, 'berryFlavor', {
enumerable: true,
get() {
return _berryFlavor;
}
});
Object.defineProperty(this, 'color', {
enumerable: true,
get() {
return _color;
}
});
_id = parseInt(options.id) || null;
_name = options.name || "No name";
_berryFlavor = options.berryFlavor || "No flavor";
_color = options.color || "No color";
Object.seal(this);
}
}
|
// Looking at closures
// http://stackoverflow.com/q/111102/137001
$(document).ready(function() {
closureTest();
function closureTest() {
//console.log
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:0f088644576fe6fee42bb3ce7f1d056f5db1079bf284c312f2acb895c5510851
size 11112
|
// # Ghost Configuration
// Setup your Ghost install for various environments
var path = require('path'),
config;
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
url: 'http://objectiveclem.local',
// Example mail config
// Visit http://docs.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'objective-clem.azurewebsites.net',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.PORT
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
}
},
// ### Travis
// Automated testing run through Github
travis: {
url: 'http://127.0.0.1:2368',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-travis.db')
}
},
server: {
host: '127.0.0.1',
port: '2368'
}
}
};
// Export config
module.exports = config;
|
import { FETCH_AUTHOR, UPDATE_AUTHOR } from 'shared/constants/actions';
const INITIAL_STATE = {
author: {},
errorMessage: ''
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_AUTHOR.SUCCESS:
// author -> { id, email, name, image, description, introduction }
return { author: action.payload.author, errorMessage: '' };
case UPDATE_AUTHOR.SUCCESS:
return { ...state, author: {}, errorMessage: '' };
case UPDATE_AUTHOR.FAILURE:
return { ...state, errorMessage: action.payload.errorMessage };
default:
return state;
}
}
|
'use strict'
// Load requirements
const slack = require('slack')
const path = require('path')
// Load utilities
const i18n = require('../locale')
const logger = require('../log')
// Data directory
const dataDir = path.join(__dirname, '../../../data/')
// User tracking and handling
module.exports = {
// User flags to avoid, edit these depending on your privileges
flags: [
// 'is_admin',
// 'is_owner',
// 'is_primary_owner',
// 'is_restricted',
'is_ultra_restricted',
'is_bot'
],
// Load the user blacklist
blacklist: require(path.join(dataDir, 'blacklist')),
// Contains the list of tracked users
users: {},
// Check if id or username is on the blacklist
blacklisted: function (user) {
return this.blacklist.some((handle) => {
return handle === user.id || handle === user.name
})
},
// Check if a user is restricted
restricted: function (user) {
return this.flags.some((flag) => {
return user[flag] === true
})
},
// Add a user to the track list
add: function (user, ignore) {
// DEBUG
logger.verbose(i18n.t('users.add.added'), user.name)
// Add to object for tracking
this.users[user.id] = {
id: user.id,
name: user.name,
real_name: user.real_name,
short_name: (user.real_name || '').split(' ')[0],
emoji: (user.profile.status_emoji || '').replace(/:/g, ''),
text: user.profile.status_text || '',
ignore: ignore || false
}
},
// Load the available users
load: function () {
return new Promise((resolve, reject) => {
// Get the list from the slack API
slack.users.list({token: process.env.SLACK_TOKEN}, (err, data) => {
// Check for errors
if (err !== null) {
return reject(new Error(i18n.t('users.load.errors.slack', err.message)))
}
// Check for a response
if (data.ok !== true) {
return reject(new Error(i18n.t('users.load.errors.invalid')))
}
// Loop members and add them to ze list
data.members.forEach((user) => {
if (!this.restricted(user)) this.add(user)
})
// resolve the promise with data
return resolve(this.users)
})
})
}
}
|
Rickshaw.namespace('Rickshaw.Graph.Axis.Y.Scaled');
Rickshaw.Graph.Axis.Y.Scaled = Rickshaw.Class.create( Rickshaw.Graph.Axis.Y, {
initialize: function($super, args) {
if (typeof(args.scale) === 'undefined') {
throw new Error('Scaled requires scale');
}
this.scale = args.scale;
if (typeof(args.grid) === 'undefined') {
this.grid = true;
} else {
this.grid = args.grid;
}
$super(args);
},
_drawAxis: function($super, scale) {
// Adjust scale's domain to compensate for adjustments to the
// renderer's domain (e.g. padding).
var domain = this.scale.domain();
var renderDomain = this.graph.renderer.domain().y;
var extents = [
Math.min.apply(Math, domain),
Math.max.apply(Math, domain)];
// A mapping from the ideal render domain [0, 1] to the extent
// of the original scale's domain. This is used to calculate
// the extents of the adjusted domain.
var extentMap = d3.scaleLinear().domain([0, 1]).range(extents);
var adjExtents = [
extentMap(renderDomain[0]),
extentMap(renderDomain[1])];
// A mapping from the original domain to the adjusted domain.
var adjustment = d3.scaleLinear().domain(extents).range(adjExtents);
// Make a copy of the custom scale, apply the adjusted domain, and
// copy the range to match the graph's scale.
var adjustedScale = this.scale.copy()
.domain(domain.map(adjustment))
.range(scale.range());
return $super(adjustedScale);
},
_drawGrid: function($super, axis) {
if (this.grid) {
// only draw the axis if the grid option is true
$super(axis);
}
}
} );
|
define([
"knockout",
// mappoint needs to be here first for addEventListener
"../modules/mappoint",
], function (ko) {
// create result object
var result = {
cityname : ko.observable(''),
citydata : ko.observableArray([])
};
// subscribe to custom event
window.addEventListener("getTitle", getWikipedia, false);
// use for jsonp call to wikipedia
var city ='',
// oldValue
oldValue = '';
// call function
function getWikipedia (e) {
// listen to custom event
city = e.detail.title;
// store data object
var data = '';
// if city equals old value do nothing
if (city === oldValue) {
// do something when element is clicked twice
console.log("you have allready clicked this " + city + " marker");
}
// if city contains new value
else {
// check if city is in LocalStorage
if (localStorage[city]) {
// get localstorage item and store it
data = JSON.parse(localStorage[city]);
// populate observables
result.citydata([data]);
result.cityname(city);
}
else {
// if no localstorage, sent request
sentJSONPRequest(city);
}
// set city to old value
oldValue = city;
}
}
// found jsonp solution for wikipedia after trying it many times with xmlhttprequest and cors
function jsonp(url, callback) {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
// create callback and delete it
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
// add script
var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
// simple error handling (works in firefox and chrome)
window.onerror = function (errorMsg, url, lineNumber) {
alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber);
};
document.body.appendChild(script);
}
// set api url
var sentJSONPRequest = function (city) {
// set url for jsonp request
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=' + city + '&format=json&callback=?';
// call jsonp request
jsonp(url, function(data) {
// fill result with wikipedia object
result.citydata([data[1]]);
// use change in city for observable
result.cityname(data[0]);
// if localstorage support
if (window.localStorage) {
// store city object with data array
localStorage[data[0]] = JSON.stringify(data[1]);
}
});
};
return result;
});
|
import path from 'path';
import os from 'os';
import { assert, test } from 'yeoman-generator';
describe('sails-rest-api:logger', () => {
describe('Should properly scaffold default configuration', () => {
before(done => test.run(path.join(__dirname, '../../src/logger')).on('end', done));
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /timestamp: true/);
});
});
describe('Should properly scaffold bunyan configuration', () => {
before(done => {
test
.run(path.join(__dirname, '../../src/logger'))
.withArguments(['bunyan'])
.on('end', done)
});
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /bunyan:/);
});
});
describe('Should properly scaffold Sails default configuration', () => {
before(done => {
test
.run(path.join(__dirname, '../../src/logger'))
.withArguments(['default'])
.on('end', done)
});
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /level: 'verbose'/);
});
});
describe('Should properly scaffold winston configuration', () => {
before(done => {
test
.run(path.join(__dirname, '../../src/logger'))
.withArguments(['winston'])
.on('end', done)
});
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /timestamp: true/);
});
});
});
|
angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/'
function cmd(){
return _.cloneDeep( command );
}
function sendRequest( data ){
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
}
XBMC.sendText = function( text ){
var data = cmd();
data.params = { method: "Player.SendText", item: { text: text, done: true } };
return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
data.method = "Input.Left";
break;
case 'right':
data.method = "Input.right";
break;
case 'up':
data.method = "Input.Up";
break;
case 'down':
data.method = "Input.Down";
break;
case 'select':
data.method = "Input.Select";
break;
case 'info':
data.method = "Input.Info";
break;
case 'context':
data.method = "Input.ContextMenu";
break;
}
return sendRequest( data );
}
XBMC.sendToPlayer = function( link ){
var data = cmd();
data.params = { method: "Player.Open", item: { file: link } };
return sendRequest( data );
}
})
|
import Ember from "ember";
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';
import { authenticateSession } from 'code-corps-ember/tests/helpers/ember-simple-auth';
import indexPage from '../pages/index';
let application;
module('Acceptance: Logout', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test("Logging out", function(assert) {
assert.expect(2);
let user = server.create('user');
authenticateSession(application, { user_id: user.id });
indexPage.visit();
andThen(function() {
assert.equal(indexPage.navMenu.userMenu.logOut.text, "Log out", "Page contains logout link");
indexPage.navMenu.userMenu.logOut.click();
});
andThen(function() {
assert.equal(indexPage.navMenu.logIn.text, "Sign in", "Page contains login link");
});
});
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
Cu.import("resource://gre/modules/Services.jsm");
const TEST_DATA = "ftp://ftp.mozqa.com/";
var setupModule = function(aModule) {
aModule.controller = mozmill.getBrowserController();
}
var testNavigateFTP = function () {
// opens the mozilla.org ftp page then navigates through a couple levels.
controller.open(TEST_DATA);
controller.waitForPageLoad();
var dataLink = new elementslib.Link(controller.tabs.activeTab, 'data');
controller.click(dataLink);
controller.waitForPageLoad();
var up = new elementslib.Selector(controller.tabs.activeTab, '.up');
controller.click(up);
controller.waitForPageLoad();
controller.waitForElement(dataLink);
}
|
var data = {videos-content: {}}
|
(function ($) {
// Navigation scrolls
$('.navbar-nav li a').bind('click', function (event) {
$('.navbar-nav li').removeClass('active');
$(this).closest('li').addClass('active');
var $anchor = $(this);
var nav = $($anchor.attr('href'));
if (nav.length) {
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
}
});
// About section scroll
$(".overlay-detail a").on('click', function (event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function () {
window.location.hash = hash;
});
});
//jQuery to collapse the navbar on scroll
$(window).scroll(function () {
if ($(".navbar-default").offset().top > 40) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
$('.navbar-collapse').on('show.bs.collapse', function () {
$(".navbar-fixed-top").addClass("top-nav-collapse-shadow");
})
$('.navbar-collapse').on('hide.bs.collapse', function () {
$(".navbar-fixed-top").removeClass("top-nav-collapse-shadow");
})
})(jQuery);
|
import util from 'util'
import mongoose from 'mongoose'
import seedData from '../seedData'
const debug = require('debug')('api:server:db')
mongoose.Promise = require('bluebird')
const host = process.env.MONGO_HOST || 'localhost'
const database = process.env.MONGO_DATABASE || 'admin'
const port = process.env.MONGO_PORT || 27017
const url = `mongodb://${host}:${port}/${database}`
const configureMongo = () => {
debug(`connecting to ${url}...`)
mongoose.connect(url).then(
() => seedData(),
err => {
debug(`unable to connect to database: ${err}`)
setTimeout(configureMongo, 5000)
}
)
if (process.env.MONGO_DEBUG) {
mongoose.set('debug', (collectionName, method, query, doc) => {
debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
});
}
}
export default configureMongo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.