text
stringlengths 2
6.14k
|
|---|
var toInteger = require('./toInteger');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @specs
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => logs 'done saving!' after the two async saves have completed
*/
function after(n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
module.exports = after;
|
$.widget( "alexandra.panelSlider", {
options: {
currentView: null, // The panel currently in focus
panels:[] // All panels added to the navigation system
},
//The constructor of the panelSLide widget
_create: function() {
var tempThis=this;
this.element.addClass("panelSlider");
this.options.currentView=this.options.panels[0];
$.each(this.options.panels, function(i, val){
$("#"+val).hide();
tempThis._checkLinks(val);
});
$("#"+this.options.currentView).show();
},
_checkLinks: function(val){
var tempThis=this;
$("#"+val+" a").click(function (event) {
event.preventDefault();
event.stopPropagation();
var url = $(this).attr('href');
var urlRegex = '/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/';
var res = url.match(urlRegex);
if(res==null){
var newView=$.inArray(url,tempThis.options.panels);
if(newView>-1){
var curView=$.inArray(tempThis.options.currentView,tempThis.options.panels);
console.log("new: "+newView+", current: "+curView);
if(newView>curView)
tempThis.slide(url,false);
else if(newView<curView)
tempThis.slide(url,true);
return;
}
}
window.location = url;
});
},
//It's possible to add a panel in runtime
addPanel: function(panel) {
this.options.panels.push(panel);
$("#"+panel).hide();
this._checkLinks(panel);
},
//A panel can be removed runtime
removePanel: function(panel){
for(var i=0;i<this.options.panels.length;i++){
if(this.options.panels[i]==panel){
if(panel==this.options.currentView){
$("#"+panel).hide();
this.options.currentView= i-1<0 ? this.options.panels[1] : this.options.panels[i-1];
$("#"+this.options.currentView).show();
}
this.options.panels.splice(i, 1);
break;
}
}
},
//The function that actually does all the sliding
//If the goingBack variable is true the sliding will happen from left to right, and vice versa
slide: function(panelToShow, goingBack){
/*
Making sure that only registered objects can act as panels.
Might be a little to rough to make such a hard return statement.
*/
if($.inArray(panelToShow,this.options.panels)<0)
return "Not a registered panel";
var tempThis=this;
var tempCurrentView=this.options.currentView;
/*
Temporary absolute positioned div for doing sliding of dfferent panels on same line.
This is the wrapper for the panel to slide off the screen
*/
var currentPanel=$("<div/>",{
css:{
"position":"absolute",
"top":0,
"left":0,
"width":"100%"
}
});
//Needed for keeping padding and margin while transition happens
var innerWrapper=$("<div/>");
this.element.append(currentPanel);
currentPanel.append(innerWrapper);
innerWrapper.append($("#"+this.options.currentView));
innerWrapper.hide("slide",{direction: goingBack ? "right" : "left"}, function(){
$("#"+tempCurrentView).hide();
tempThis.element.append($("#"+tempCurrentView));
currentPanel.remove();
});
/*
Temporary absolute positioned div for doing sliding of dfferent panels on same line.
This is the wrapper for the panel to slide onto the screen
*/
var newPanel=$("<div/>",{
css:{
"position":"absolute",
"top":0,
"left":0,
"width":"100%"
}
});
//Needed for keeping padding and margin while transition happens
var innerWrapper2=$("<div/>");
innerWrapper2.hide();
this.element.append(newPanel);
newPanel.append(innerWrapper2);
innerWrapper2.append($("#"+panelToShow));
$("#"+panelToShow).show();
innerWrapper2.show("slide",{direction: goingBack ? "left" : "right"},function(){
tempThis.element.append($("#"+panelToShow));
newPanel.remove();
});
this.options.currentView=panelToShow;
}
});
|
(function() {
'use strict';
function movieDetail(movieDetailService) {
return {
restrict: 'EA',
replace: true,
templateUrl: './src/app/movieDetail/template.html',
scope: {},
controllerAs: 'vm',
bindToController: true,
/*jshint unused:false*/
controller: function($log, $stateParams) {
var vm = this;
movieDetailService.getMovie().then(function(response){
vm.movie = response.data;
vm.movie.vote = (vm.movie.vote_average*10);
vm.movie.genres_name = [];
vm.movie.production_companies_name = [];
vm.movie.production_countries_name = [];
for (var i = 0; i <= vm.movie.genres.length-1; i++) {
vm.movie.genres_name.push(vm.movie.genres[i].name);
vm.movie.genres_name.sort();
}
for (var i = 0; i <= vm.movie.production_companies.length-1; i++) {
vm.movie.production_companies_name.push(vm.movie.production_companies[i].name);
vm.movie.production_companies_name.sort();
}
for (var i = 0; i <= vm.movie.production_countries.length-1; i++) {
vm.movie.production_countries_name.push(vm.movie.production_countries[i].name);
vm.movie.production_countries_name.sort();
}
});
},
link: function(scope, elm, attrs) {
}
};
}
angular.module('movieDetailDirective', ['services.movieDetail'])
.directive('movieDetail', movieDetail);
})();
|
/* See license.txt for terms of usage */
require.def("domplate/toolTip", [
"domplate/domplate",
"core/lib",
"core/trace"
],
function(Domplate, Lib, Trace) { with (Domplate) {
// ************************************************************************************************
// Globals
var mouseEvents = "mousemove mouseover mousedown click mouseout";
var currentToolTip = null;
// ************************************************************************************************
// Tooltip
function ToolTip()
{
this.element = null;
}
ToolTip.prototype = domplate(
{
tag:
DIV({"class": "toolTip"},
DIV()
),
show: function(target, options)
{
if (currentToolTip)
currentToolTip.hide();
this.target = target;
this.addListeners();
// Render the tooltip.
var body = Lib.getBody(document);
this.element = this.tag.append({options: options}, body, this);
// Compute coordinates and show.
var box = Lib.getElementBox(this.target);
this.element.style.top = box.top + box.height + "px";
this.element.style.left = box.left + box.width + "px";
this.element.style.display = "block";
currentToolTip = this;
return this.element;
},
hide: function()
{
if (!this.element)
return;
this.removeListeners();
// Remove UI
this.element.parentNode.removeChild(this.element);
currentToolTip = this.element = null;
},
addListeners: function()
{
this.onMouseEvent = Lib.bind(this.onMouseEvent, this);
// Register listeners for all mouse events.
$(document).bind(mouseEvents, this.onMouseEvent, true);
},
removeListeners: function()
{
// Remove listeners for mouse events.
$(document).unbind(mouseEvents, this.onMouseEvent, this, true);
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Listeners
onMouseEvent: function(event)
{
var e = Lib.fixEvent(event);
// If the mouse is hovering within the tooltip pass the event further to it.
var ancestor = Lib.getAncestorByClass(e.target, "toolTip");
if (ancestor)
return;
var x = event.clientX, y = event.clientY;
var box = Lib.getElementBox(this.element);
if (event.type != "click" && event.type != "mousedown")
box = Lib.inflateRect(box, 10, 10);
// If the mouse is hovering within near neighbourhood, ignore it.
if (Lib.pointInRect(box, x, y))
{
Lib.cancelEvent(e);
return;
}
// If the mouse is hovering over the target, ignore it too.
if (Lib.isAncestor(e.target, this.target))
{
Lib.cancelEvent(e);
return;
}
// The mouse is hovering far away, let's destroy the the tooltip.
this.hide();
Lib.cancelEvent(e);
}
});
// ************************************************************************************************
return ToolTip;
// **********************************************************************************************//
}});
|
import robot from 'robotjs'
import sleep from 'sleep'
import orifice from './fc8_orifice_map.json'
var fs = require('fs')
/*//set speed
robot.setKeyboardDelay(150)
robot.setMouseDelay(100)*/
let type = [
"Orifice",
"Venturi",
"Nozzle",
"Fixed Geometry",
"V-Cone",
"Segmental Meters",
"Linear Meters"
]
exports.startFC8 = function(){
robot.keyTap('command')
robot.typeString('FC8')
sleep.msleep(500)
robot.keyTap('enter')
sleep.msleep(500)
}
exports.selectType = function(request){
robot.keyTap('tab')
let i = 0
for(i=0; i<type.indexOf(request); i++){
robot.keyTap('down')
}
robot.keyTap('tab')
robot.keyTap('enter')
}
exports.autoCompileGas = function(){
let i = 0
for(i=0; i<9; i++){
robot.keyTap('tab')
}
robot.keyTap('enter')
for(i=0; i<7; i++){
robot.keyTap('tab')
}
robot.keyTap('enter')
robot.keyTap('enter')
robot.keyTap('tab')
robot.keyTap('tab')
robot.keyTap('enter')
robot.keyTap('enter')
}
exports.calculation = function(object) {
//select dp flow size
let i = 0
if(object.method == "dp"){
robot.keyTap('enter')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.dp.percMaxFlow)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.dp.maxFlow)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.dp.normalFlow)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.pipeDiameter)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.borePrimaryElement)
robot.keyTap('tab')
robot.keyTap('enter')
} else if (object.method == "flow"){
robot.keyTap('tab')
robot.keyTap('enter')
robot.keyTap('tab')
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.flow.differentialPressure)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.pipeDiameter)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.borePrimaryElement)
robot.keyTap('tab')
robot.keyTap('tab')
robot.keyTap('enter')
} else if (object.method == "size"){
robot.keyTap('tab')
robot.keyTap('tab')
robot.keyTap('enter')
robot.keyTap('tab')
robot.keyTap('tab')
/*for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.size.percMaxFlow)*/
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.size.maxFlow)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.size.normalFlow)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.size.differential)
robot.keyTap('tab')
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(object.base.pipeDiameter)
robot.keyTap('tab')
robot.keyTap('tab')
robot.keyTap('enter')
}
if(object.checkVentDrainHole!="off"){
/*
robot.keyTap('tab')
robot.keyTap('tab')
let ind = orifice.FlangeTaps.VentDrainHole.indexOf(object.ventDrainHole)
let indStd = orifice.FlangeTaps.VentDrainHole.indexOf('No Vent/Drain Hole')
if(ind<indStd){
for (i=0; i<indStd-ind; i++){
robot.keyTap('up')
}
} else {
for (i=0; i<ind-indStd; i++){
robot.keyTap('down')
}
}*/
if(object.ventDrainHole=="FC8"){
robot.keyTap('enter')
} else if (object.ventDrainHole=="userdefined"){
robot.keyTap('tab')
robot.keyTap('tab')
for(i=0;i<17;i++){
robot.keyTap('down')
}
robot.typeString(object.userDefinedDiameters)
robot.keyTap('tab')
robot.keyTap('enter')
robot.keyTap('tab')
robot.keyTap('enter')
}
for(i=0; i<2; i++){
robot.keyTap('tab', 'shift')
}
}
}
exports.printPDF = function(fileName, customer, tag){
let i=0
robot.keyTap('enter')
for(i=0; i<7; i++){
robot.keyTap('tab')
}
for(i=0; i<10; i++){
robot.keyTap('delete')
}
robot.typeString(customer)
robot.keyTap('tab')
robot.keyTap('tab')
robot.typeString(tag)
for(i=0; i<15; i++){
robot.keyTap('tab')
}
robot.keyTap('enter')
sleep.msleep(500)
robot.typeString(fileName)
robot.keyTap('enter')
sleep.msleep(500)
}
exports.existFile = function (fileName, errors) {
fs.exists('../Documents/'+fileName, function(exists) {
if(!exists){
errors.push(fileName)
console.log(fileName, "ha presentato un errore")
console.log(errors)
}
});
}
|
/**
* Simple re-export of frost-detail-tabs-more-tabs in the app namespace
*/
export {default} from 'ember-frost-tabs/components/frost-detail-tabs-more-tabs'
|
'use strict';
/**
* Module dependencies
*/
var citiesPolicy = require('../policies/cities.server.policy'),
cities = require('../controllers/cities.server.controller');
module.exports = function (app) {
// City collection routes
app.route('/api/cities').all(citiesPolicy.isAllowed)
.get(cities.list)
.post(cities.create);
// Single city routes
app.route('/api/cities/:cityId').all(citiesPolicy.isAllowed)
.get(cities.read)
.put(cities.update)
.delete(cities.delete);
// Finish by binding the city middleware
app.param('cityId', cities.cityByID);
};
|
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery", "../jquery.validate"], factory );
} else if (typeof exports === "object") {
factory(require("jquery"));
} else {
factory( jQuery );
}
}(function( $ ) {
/*
* Translated default messages for the jQuery validation plugin.
* Locale: ET (Estonian; eesti, eesti keel)
*/
$.extend($.validator.messages, {
required: "See väli peab olema täidetud.",
maxlength: $.validator.format("Palun sisestage vähem kui {0} tähemärki."),
minlength: $.validator.format("Palun sisestage vähemalt {0} tähemärki."),
rangelength: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1} tähemärki."),
email: "Palun sisestage korrektne e-maili aadress.",
url: "Palun sisestage korrektne URL.",
date: "Palun sisestage korrektne kuupäev.",
dateISO: "Palun sisestage korrektne kuupäev (YYYY-MM-DD).",
number: "Palun sisestage korrektne number.",
digits: "Palun sisestage ainult numbreid.",
equalTo: "Palun sisestage sama väärtus uuesti.",
range: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1}."),
max: $.validator.format("Palun sisestage väärtus, mis on väiksem või võrdne arvuga {0}."),
min: $.validator.format("Palun sisestage väärtus, mis on suurem või võrdne arvuga {0}."),
creditcard: "Palun sisestage korrektne krediitkaardi number."
});
}));
|
import {
TASK_STATUS_ACTIVE,
TASK_STATUS_COMPLETED
} from 'modules/task/constants';
export class RouterService {
constructor($state, $stateParams) {
this.state = $state;
this.params = $stateParams;
}
isActiveTasks() {
return this.state.is('app.tasks', {filter: TASK_STATUS_ACTIVE});
}
isCompletedTasks() {
return this.state.is('app.tasks', {filter: TASK_STATUS_COMPLETED});
}
isTasks() {
return this.state.is('app.tasks', {filter: ''});
}
toActiveTasks() {
return this.state.go('app.tasks', {filter: TASK_STATUS_ACTIVE});
}
toCompletedTasks() {
return this.state.go('app.tasks', {filter: TASK_STATUS_COMPLETED});
}
toTasks() {
return this.state.go('app.tasks');
}
}
|
module.exports = {
description: 'deconflict entry points with the same name in different directories',
command:
'rollup --input main.js --input sub/main.js --format esm --dir _actual --experimentalCodeSplitting'
};
|
/**
* xDo app client
*
* Auther: vs4vijay@gmail.com
*/
var app = angular.module('app', ['ngResource']);
app.controller('AppCtrl', ['$scope', function($scope) {
// Parent controller for all the Ctrls
$scope.appModel = {}
}]);
// Can define config block here or use ngRoute
|
/**
* @module creatine.transitions
**/
(function() {
"use strict";
/**
* A transition effect to scroll the new scene.
*
* ## Usage example
*
* var game = new tine.Game(null, {
* create: function() {
* var transition = new tine.transitions.Scroll(tine.TOP, null, 1000);
* game.replace(new MyScene(), transition);
* }
* });
*
* @class Scroll
* @constructor
* @param {Constant} [direction=creatine.LEFT] The direction.
* @param {Function} [ease=createjs.Ease.linear] An easing function from
* `createjs.Ease` (provided by TweenJS).
* @param {Number} [time=400] The transition time in milliseconds.
**/
var Scroll = function(direction, ease, time) {
/**
* Direction of the effect.
* @property direction
* @type {Constant}
**/
this.direction = direction || creatine.LEFT;
/**
* An Easing function from createjs.Ease.
* @property ease
* @type {Function}
**/
this.ease = ease || createjs.Ease.linear;
/**
* The transition time in milliseconds.
* @property time
* @type {Number}
**/
this.time = time || 400;
}
var p = Scroll.prototype;
/**
* Initialize the transition (called by the director).
* @method start
* @param {Director} director The Director instance.
* @param {Scene} outScene The active scene.
* @param {Scene} inScene The incoming scene.
* @param {Function} callback The callback function called when the
* transition is done.
* @protected
**/
p.start = function(director, outScene, inScene, callback) {
this.director = director;
this.outScene = outScene;
this.inScene = inScene;
this.callback = callback;
var w = director.stage.canvas.width;
var h = director.stage.canvas.height;
var dir = this.direction;
this.targetX = 0;
this.targetY = 0;
inScene.x = 0;
inScene.y = 0;
switch (this.direction) {
case creatine.LEFT:
inScene.x = w;
this.targetX = -w;
break;
case creatine.RIGHT:
inScene.x = -w;
this.targetX = w;
break;
case creatine.TOP:
inScene.y = h;
this.targetY = -h;
break;
case creatine.BOTTOM:
inScene.y = -h;
this.targetY = h;
break;
}
var self = this;
createjs.Tween.get(inScene, {override:true})
.to({x:0, y:0}, this.time, this.ease)
.call(function() { self.complete(); })
createjs.Tween.get(outScene, {override:true})
.to({x:this.targetX, y:this.targetY}, this.time, this.ease)
}
/**
* Finalize the transition (called by the director).
* @method complete
* @protected
**/
p.complete = function() {
createjs.Tween.removeTweens(this.inScene);
createjs.Tween.removeTweens(this.outScene);
this.inScene.x = 0;
this.inScene.x = 0;
this.outScene.x = 0;
this.outScene.y = 0;
this.callback();
}
creatine.transitions.Scroll = Scroll;
}());
|
function Test() {
a = 1;
console.log(a);
try {
console.log(b);
} catch (e) {
console.log("null");
}
}
console.log("Test1");
Test();
a = 2;
b = 3;
console.log("Test2");
Test();
Test.a = 4;
Test.b = 4;
console.log("Test3");
Test();
console.log("Test4");
console.log(Test.a);
console.log(Test.b);
|
// All code points in the `Sc` category as per Unicode v6.3.0:
[
0x24,
0xA2,
0xA3,
0xA4,
0xA5,
0x58F,
0x60B,
0x9F2,
0x9F3,
0x9FB,
0xAF1,
0xBF9,
0xE3F,
0x17DB,
0x20A0,
0x20A1,
0x20A2,
0x20A3,
0x20A4,
0x20A5,
0x20A6,
0x20A7,
0x20A8,
0x20A9,
0x20AA,
0x20AB,
0x20AC,
0x20AD,
0x20AE,
0x20AF,
0x20B0,
0x20B1,
0x20B2,
0x20B3,
0x20B4,
0x20B5,
0x20B6,
0x20B7,
0x20B8,
0x20B9,
0x20BA,
0xA838,
0xFDFC,
0xFE69,
0xFF04,
0xFFE0,
0xFFE1,
0xFFE5,
0xFFE6
];
|
var should = require('should'),
supertest = require('supertest'),
testUtils = require('../../../utils/index'),
localUtils = require('./utils'),
config = require('../../../../server/config/index'),
ghost = testUtils.startGhost,
request;
describe('Slug API', function () {
var accesstoken = '', ghostServer;
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
})
.then(function () {
return localUtils.doAuth(request);
})
.then(function (token) {
accesstoken = token;
});
});
it('should be able to get a post slug', function (done) {
request.get(localUtils.API.getApiQuery('slugs/post/a post title/'))
.set('Authorization', 'Bearer ' + accesstoken)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
var jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.slugs);
jsonResponse.slugs.should.have.length(1);
localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug');
jsonResponse.slugs[0].slug.should.equal('a-post-title');
done();
});
});
it('should be able to get a tag slug', function (done) {
request.get(localUtils.API.getApiQuery('slugs/post/atag/'))
.set('Authorization', 'Bearer ' + accesstoken)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
var jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.slugs);
jsonResponse.slugs.should.have.length(1);
localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug');
jsonResponse.slugs[0].slug.should.equal('atag');
done();
});
});
it('should be able to get a user slug', function (done) {
request.get(localUtils.API.getApiQuery('slugs/user/user name/'))
.set('Authorization', 'Bearer ' + accesstoken)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
var jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.slugs);
jsonResponse.slugs.should.have.length(1);
localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug');
jsonResponse.slugs[0].slug.should.equal('user-name');
done();
});
});
it('should be able to get an app slug', function (done) {
request.get(localUtils.API.getApiQuery('slugs/app/cool app/'))
.set('Authorization', 'Bearer ' + accesstoken)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
var jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.slugs);
jsonResponse.slugs.should.have.length(1);
localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug');
jsonResponse.slugs[0].slug.should.equal('cool-app');
done();
});
});
it('should not be able to get a slug for an unknown type', function (done) {
request.get(localUtils.API.getApiQuery('slugs/unknown/who knows/'))
.set('Authorization', 'Bearer ' + accesstoken)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(400)
.end(function (err, res) {
if (err) {
return done(err);
}
var jsonResponse = res.body;
should.exist(jsonResponse.errors);
done();
});
});
});
|
/*
* Favorites
* Favorites landing page
*/
import React, { Component } from 'react'
import NavBar from '../NavBar.react'
export default class Favorites extends Component {
render() {
return (
<div>
<div className="p2 overflow-scroll mt4 mb4">
<div className="center mb3">
<button className="btn bg-purple-3 white regular py1 px3">Import from Spotify</button>
</div>
<div className="h6 caps white">Your favorites</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Let's Dance</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Lazarus</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Let's Dance</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Lazarus</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Let's Dance</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Lazarus</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Let's Dance</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
<div className="border-bottom border-muted py2 mrn2 relative">
<div className="white h4 mb1">Lazarus</div>
<div className="white muted h6 semibold">David Bowie</div>
<span className="white absolute right-0 h2 mr3" style={{top: '23px'}}>
<span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span>
›
</span>
</div>
</div>
<NavBar activeTab="favorites"/>
</div>
)
}
}
|
function generateList(people, template){
var i,
result = '',
len = people.length;
result += '<ul>';
for(i = 0; i < len; i += 1){
result += '<li>';
result += template;
result = result.replace('-{name}-', people[i]['name']);
result = result.replace('-{age}-', people[i]['age']);
result += '</li>';
}
result += '</ul>';
return result;
}
var people = [
{ name: 'Pehso', age: 20},
{ name: 'Gosho', age: 30},
{ name: 'Stamat', age: 25}
];
var template = document.getElementById('list-item').innerHTML;
document.getElementById('list-item').innerHTML = generateList(people, template);
|
const admin = require('firebase-admin');
const DATABASE_URL = process.env.DATABASE_URL || 'https://dailyjack-8a930.firebaseio.com';
// const DATABASE_URL = 'https://dailyjack-d2fa0.firebaseio.com';
const jackDB = (config = {}) => {
const app = admin.initializeApp({
credential: admin.credential.cert({
projectId: config.projectId,
clientEmail: config.clientEmail,
privateKey: config.privateKey,
}),
databaseURL: DATABASE_URL,
});
const db = admin.database();
const jacksRef = db.ref('jacks');
const totalJacksRef = db.ref('totalJacks');
const usersRef = db.ref('users');
const insert = jack => (
jacksRef
.child(jack.id)
.set({
id: jack.id,
title: jack.title,
contents: jack.contents || [],
author: jack.author || null,
createdTime: Date.now(),
isLimited: Boolean(jack.isLimited),
isSpecial: Boolean(jack.isSpecial),
})
.then(() => (
totalJacksRef.transaction(total => (total || 0) + 1)
))
);
const filter = (jacks = [], filterOptions = {}) => jacks.filter(
jack => (!filterOptions.shouldExcludeLimited || !jack.isLimited)
&& (!filterOptions.shouldExcludeSpecial || !jack.isSpecial)
);
const all = (filterOptions = {}) => (
jacksRef.once('value')
.then(snapshot => snapshot.val())
.then(jacks => (jacks || []).filter(Boolean))
.then(jacks => filter(jacks, filterOptions))
);
const get = id => (
jacksRef.child(id)
.once('value')
.then(snapshot => snapshot.val())
);
const random = (filterOptions = {}) => (
all(filterOptions)
.then(jacks => jacks[Math.floor(Math.random() * jacks.length)])
);
const upvote = (id, user) => (
jacksRef.child(id)
.child('ratedUsers')
.child(user)
.set(true)
);
const downvote = (id, user) => (
jacksRef.child(id)
.child('ratedUsers')
.remove(user)
);
const togglevote = (id, user) => (
jacksRef.child(id)
.child('ratedUsers')
.child(user)
.transaction(rate => (rate ? null : true))
);
const getRate = id => (
jacksRef.child(id)
.child('ratedUsers')
.once('value')
.then(snapshot => snapshot.val())
.then(rate => Object.keys(rate || {})
.filter(Boolean)
.length
)
);
const setUser = user => (
usersRef.child(user.name)
.set(user)
);
const updateUser = user => (
usersRef.child(user.name)
.update(user)
);
const getUser = userName => (
usersRef.child(userName)
.once('value')
.then(snapshot => snapshot.val())
);
const exit = () => {
db.goOffline();
app.delete();
};
return {
all,
get,
random,
insert,
exit,
upvote,
downvote,
togglevote,
getRate,
setUser,
updateUser,
getUser,
};
};
module.exports = {
default: jackDB,
};
|
//TODO : socket.ioコネクション処理を1.0推奨の非同期方式にする
describe('serverクラスのテスト', function() {
var SERVER_PORT = process.env.PORT || 3000;
var SERVER_URL = 'http://localhost:'+SERVER_PORT;
var assert = require('chai').assert;
var io = require('socket.io-client');
var server = require('../../../server/server.js');
var http = require('http');
var dbMock = require('./../testData/dbMock.js')();
var app;
var testServer;
var option = {
'forceNew' : true
};
beforeEach(function() {
app = http.createServer().listen(SERVER_PORT);
testServer = server({
httpServer : app,
dao : dbMock
});
});
afterEach(function() {
app.close();
});
describe('退室系テスト',function(){
it('入室後に退室する',function(done){
var client = io(SERVER_URL, option);
client.on('connect',doAuth);
function doAuth() {
client.emit('auth',{
userId : 'test001@gmail.com'
});
client.once('successAuth',enterRoom);
}
function enterRoom() {
client.emit('enterRoom',{
roomId : 0
});
client.on('succesEnterRoom',leaveRoom);
}
function leaveRoom() {
client.emit('leaveRoom');
client.on('successLeaveRoom',done);
}
});
});
});
|
// eslint-disable-next-line import/prefer-default-export
export const serializePlaylist = model => ({
_id: model.id,
name: model.name,
author: model.author,
createdAt: model.createdAt,
description: model.description,
shared: model.shared,
nsfw: model.nsfw,
size: model.media.length,
});
|
class NotFoundError extends Error {
constructor(message) {
super();
if (Error.hasOwnProperty('captureStackTrace')) {
Error.captureStackTrace(this, this.constructor);
} else {
Object.defineProperty(this, 'stack', { value : (new Error()).stack });
}
Object.defineProperty(this, 'message', { value : message });
}
get name() {
return this.constructor.name;
}
}
export default { NotFoundError }
|
"use strict";
/* global describe it before */
const { assert } = require("chai");
const Database = require("./lib/database");
const testcases = (env) => {
describe("Basic operations", () => {
before(async () => {
await Database.start();
});
it("should list zero objects", async () => {
const list = await env.client.list("thing");
assert.isArray(list);
assert.equal(list.length, 0);
});
it("should create one object", async () => {
const thing = await env.client.create("thing", {
_id: "1",
thingy: "Hello"
});
assert.equal(thing.type, "scom.thing");
assert.equal(thing.thingy, "Hello");
});
it("should list one object", async () => {
const list = await env.client.list("thing");
assert.isArray(list);
assert.equal(list.length, 1);
});
it("should update one object", async () => {
const thing = await env.client.update("thing", "1", {
thingy: "World"
});
assert.equal(thing.type, "scom.thing");
assert.equal(thing.thingy, "World");
});
it("should delete one object", async () => {
const thing = await env.client.remove("thing", "1");
assert.equal(thing.type, "scom.thing");
assert.equal(thing.thingy, "World");
});
it("should list zero objects", async () => {
const list = await env.client.list("thing");
assert.isArray(list);
assert.equal(list.length, 0);
});
});
describe("Action operations", () => {
before(async () => {
await Database.start();
});
it("should create an object and tag it", async () => {
await env.client.create("thing", {
_id: "1",
thingy: "Hello"
});
const thing2 = await env.client.tag("thing", "1", {
tag: [ "tag1", "tag2" ]
});
assert.equal(thing2.type, "scom.thing");
assert.equal(thing2.thingy, "Hello");
assert.deepEqual(thing2.tags, [ "tag1", "tag2" ]);
});
it("should get error with invalid action", async () => {
try {
await env.client.stuff("thing", "1", { 1: 0 });
assert(false, "Should have thrown");
} catch (error) {
assert.equal(error.status, 400);
}
});
});
describe("Getter operations", () => {
before(async () => {
await Database.start();
});
it("should create an object and get something on it", async () => {
await env.client.create("thing", {
_id: "1",
thingy: "Hello"
});
const value = await env.client.thingy("thing", "1");
assert.equal(value, "Hello");
});
it("should get error with invalid getter", async () => {
try {
await env.client.stuff("thing", "1");
assert(false, "Should have thrown");
} catch (error) {
assert.equal(error.status, 400);
}
});
});
};
module.exports = testcases;
|
export const state = () => ({
visits:[]
})
export const mutations = {
ADD_VISIT (state,path) {
state.visits.push({
path,
date:new Date().toJSON()
})
}
}
|
import React, { PropTypes } from 'react';
const ProductList = (props) => {
const pl = props.productList;
const products = Object.keys(pl);
return (<ul>
{products.map(key => <li key={key}><a href={`#/product/${key}`} >{pl[key].name}</a></li>)}
</ul>);
};
ProductList.propTypes = {
productList: PropTypes.object.isRequired
};
export default ProductList;
|
//Variables
var chrome_points = 0;
//Functions
function test_chromepoints() {
chrome_points = chrome_points + 1;
}
//HTML Updates
window.setInterval(function(){
document.getElementById("chrome_points").innerHTML = chrome_points;
}, 1000);
|
ace.define("ace/snippets/sqlserver", ["require", "exports", "module"], function(require, exports, module) {
"use strict";
exports.snippetText = "# ISNULL\n\
snippet isnull\n\
ISNULL(${1:check_expression}, ${2:replacement_value})\n\
# FORMAT\n\
snippet format\n\
FORMAT(${1:value}, ${2:format})\n\
# CAST\n\
snippet cast\n\
CAST(${1:expression} AS ${2:data_type})\n\
# CONVERT\n\
snippet convert\n\
CONVERT(${1:data_type}, ${2:expression})\n\
# DATEPART\n\
snippet datepart\n\
DATEPART(${1:datepart}, ${2:date})\n\
# DATEDIFF\n\
snippet datediff\n\
DATEDIFF(${1:datepart}, ${2:startdate}, ${3:enddate})\n\
# DATEADD\n\
snippet dateadd\n\
DATEADD(${1:datepart}, ${2:number}, ${3:date})\n\
# DATEFROMPARTS \n\
snippet datefromparts\n\
DATEFROMPARTS(${1:year}, ${2:month}, ${3:day})\n\
# OBJECT_DEFINITION\n\
snippet objectdef\n\
SELECT OBJECT_DEFINITION(OBJECT_ID('${1:sys.server_permissions /*object name*/}'))\n\
# STUFF XML\n\
snippet stuffxml\n\
STUFF((SELECT ', ' + ${1:ColumnName}\n\
FROM ${2:TableName}\n\
WHERE ${3:WhereClause}\n\
FOR XML PATH('')), 1, 1, '') AS ${4:Alias}\n\
${5:/*https://msdn.microsoft.com/en-us/library/ms188043.aspx*/}\n\
# Create Procedure\n\
snippet createproc\n\
-- =============================================\n\
-- Author: ${1:Author}\n\
-- Create date: ${2:Date}\n\
-- Description: ${3:Description}\n\
-- =============================================\n\
CREATE PROCEDURE ${4:Procedure_Name}\n\
${5:/*Add the parameters for the stored procedure here*/}\n\
AS\n\
BEGIN\n\
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.\n\
SET NOCOUNT ON;\n\
\n\
${6:/*Add the T-SQL statements to compute the return value here*/}\n\
\n\
END\n\
GO\n\
# Create Scalar Function\n\
snippet createfn\n\
-- =============================================\n\
-- Author: ${1:Author}\n\
-- Create date: ${2:Date}\n\
-- Description: ${3:Description}\n\
-- =============================================\n\
CREATE FUNCTION ${4:Scalar_Function_Name}\n\
-- Add the parameters for the function here\n\
RETURNS ${5:Function_Data_Type}\n\
AS\n\
BEGIN\n\
DECLARE @Result ${5:Function_Data_Type}\n\
\n\
${6:/*Add the T-SQL statements to compute the return value here*/}\n\
\n\
END\n\
GO";
exports.scope = "sqlserver";
});
(function() {
ace.require(["ace/snippets/sqlserver"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
/**
* Module dependencies
*/
var Server = require('annex-ws-node').Server;
var http = require('http');
var stack = require('connect-stack');
var pns = require('pack-n-stack');
module.exports = function createServer(opts) {
var server = http.createServer();
server.stack = [];
server.handle = stack(server.stack);
server.use = function(fn) {
fn.handle = fn;
server.stack.push(fn);
return server;
};
var routes = server.routes = {};
var hasPushedRouter = false;
server.register =
server.fn = function(modName, fnName, cb) {
var mod = routes[modName] = routes[modName] || {};
var fn = mod[fnName] = mod[fnName] || [];
fn.push(cb);
server.emit('register:call', modName, fnName);
if (hasPushedRouter) return server;
server.use(router);
hasPushedRouter = true;
return server;
};
function router(req, res, next) {
var mod = routes[req.module];
if (!mod) return next();
var fn = mod[req.method];
if (!fn) return next();
// TODO support next('route')
fn[0](req, res, next);
}
var wss = new Server({server: server, marshal: opts.marshal});
wss.listen(function(req, res) {
// TODO do a domain here
server.handle(req, res, function(err) {
if (!res._sent) {
err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented');
if (err) console.error(err.stack || err.message);
}
});
});
return server;
}
|
(function () {
'use strict';
/* Controllers */
var pollsControllers = angular.module('pollsControllers', []);
var author = 'Patrick Nicholls';
pollsControllers.controller('PollListCtrl', ['$scope', '$http',
function ($scope, $http) {
var resource = "/~pjn59/365/polls/index.php/services/polls";
$scope.polls = undefined;
$scope.author = author;
$http.get(resource)
.success(function(data){
$scope.polls = data;
})
.error(function(){
console.log("Couldn't get data");
});
}]);
pollsControllers.controller('PollDetailCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$scope.pollId = $routeParams.pollId;
$scope.title = undefined;
$scope.quesiton = undefined;
$scope.choice = undefined;
var base_url = "/~pjn59/365/polls/index.php/services/";
$http.get(base_url + "polls/" + $scope.pollId)
.success(function(data){
console.log(data);
var choices = [];
for (var i = 0; i < data.choices.length; i++) {
choices[i] = {
'choice': data.choices[i],
'votes' : parseInt(data.votes[i])
};
}
$scope.choices = choices;
$scope.question = data.question;
$scope.title = data.title;
console.log($scope.choices);
})
.error(function(){
console.log("Couldn't get data");
});
$scope.vote = function() {
//Increment database through PHP somehow
$scope.choices[$scope.choice-1].votes += 1;
$http.post(base_url + "votes/" + $scope.pollId + "/" + $scope.choice)
.success(function(data){
console.log("Vote succeeded")
})
.error(function(){
console.log("Vote unsuccessful");
});
};
$scope.reset = function() {
for (var i = 0; i < $scope.choices.length; i++) {
$scope.choices[i].votes = 0;
}
$http.delete(base_url + "votes/" + $scope.pollId)
.success(function(data){
console.log("Reset succeeded")
})
.error(function(){
console.log("Reset unsuccessful");
});
}
}]);
pollsControllers.controller('AboutCtrl', ['$scope',
function ($scope) {
$scope.author = author;
}]);
}())
|
// Generated by CoffeeScript 1.7.1
(function() {
var ERROR, IGNORE, WARN;
ERROR = 'error';
WARN = 'warn';
IGNORE = 'ignore';
module.exports = {
coffeescript_error: {
level: ERROR,
message: ''
}
};
}).call(this);
|
/**
* Run the APP
*/
app.run();
|
/*
* slush-ml-3t
* https://github.com/edmacabebe/slush-ml-3t
*
* Copyright (c) 2017, edmacabebe
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = require('gulp-rename'),
_ = require('underscore.string'),
inquirer = require('inquirer'),
path = require('path');
function format(string) {
var username = string.toLowerCase();
return username.replace(/\s/g, '');
}
var defaults = (function () {
var workingDirName = path.basename(process.cwd()),
homeDir, osUserName, configFile, user;
if (process.platform === 'win32') {
homeDir = process.env.USERPROFILE;
osUserName = process.env.USERNAME || path.basename(homeDir).toLowerCase();
}
else {
homeDir = process.env.HOME || process.env.HOMEPATH;
osUserName = homeDir && homeDir.split('/').pop() || 'root';
}
configFile = path.join(homeDir, '.gitconfig');
user = {};
if (require('fs').existsSync(configFile)) {
user = require('iniparser').parseSync(configFile).user;
}
return {
appName: workingDirName,
userName: osUserName || format(user.name || ''),
authorName: user.name || '',
authorEmail: user.email || ''
};
})();
gulp.task('default', function (done) {
var prompts = [{
name: 'appName',
message: 'What is the name of your project?',
default: defaults.appName
}, {
name: 'appDescription',
message: 'What is the description?'
}, {
name: 'appVersion',
message: 'What is the version of your project?',
default: '0.1.0'
}, {
name: 'authorName',
message: 'What is the author name?',
default: defaults.authorName
}, {
name: 'authorEmail',
message: 'What is the author email?',
default: defaults.authorEmail
}, {
name: 'userName',
message: 'What is the github username?',
default: defaults.userName
}, {
type: 'confirm',
name: 'moveon',
message: 'Continue?'
}];
//Ask
inquirer.prompt(prompts,
function (answers) {
if (!answers.moveon) {
return done();
}
answers.appNameSlug = _.slugify(answers.appName);
gulp.src(__dirname + '/templates/**')
.pipe(template(answers))
.pipe(rename(function (file) {
if (file.basename[0] === '_') {
file.basename = '.' + file.basename.slice(1);
}
}))
.pipe(conflict('./'))
.pipe(gulp.dest('./'))
.pipe(install())
.on('end', function () {
done();
});
});
});
|
angular.module('streama').controller('adminVideosCtrl', ['$scope', 'apiService', 'modalService', '$state', function ($scope, apiService, modalService, $state) {
$scope.loading = true;
apiService.genericVideo.list().then(function (response) {
$scope.videos = response.data;
$scope.loading = false;
});
$scope.openGenericVideoModal = function () {
modalService.genericVideoModal(null, function (data) {
$state.go('admin.video', {videoId: data.id});
});
};
$scope.addFromSuggested = function (movie, redirect) {
var tempMovie = angular.copy(movie);
var apiId = tempMovie.id;
delete tempMovie.id;
tempMovie.apiId = apiId;
apiService.movie.save(tempMovie).then(function (response) {
if(redirect){
$state.go('admin.movie', {movieId: response.data.id});
}else{
$scope.movies.push(response.data);
}
});
};
$scope.alreadyAdded = function (movie) {
console.log('%c movie', 'color: deeppink; font-weight: bold; text-shadow: 0 0 5px deeppink;', movie);
return movie.id && _.find($scope.movies, {apiId: movie.id.toString()});
};
}]);
|
var cookie = require('../index');
chai.should();
describe('cookie monster', function() {
it('sets a cookie', function (){
cookie.setItem('cookieKey', 'cookieVal');
document.cookie.should.contain('cookieKey=cookieVal');
});
it('gets a cookie', function (){
document.cookie = 'dumby=mcdumberson;';
cookie.getItem('dumby').should.equal('mcdumberson');
});
it('sets and gets cookie with `=` in value', function (){
cookie.setItem('key', 'val=ue');
cookie.getItem('key').should.equal('val=ue');
});
it('removes a cookie', function (){
document.cookie = 'dumby=mcdumberson;';
document.cookie.should.contain('dumby=mcdumberson');
cookie.removeItem('dumby');
document.cookie.should.not.contain('dumby=mcdumberson');
});
it('sets 30 cookies and clears all of them', function (){
for (var i = 0; i++; i < 30){ cookie.setItem('key' + i, 'value' + i); }
for (var i = 0; i++; i < 30){ cookie.getItem('key' + i).should.equal('value' + i); }
cookie.clear();
document.cookie.should.equal('');
});
});
|
/**
*
* Store transaction
*
* Programmer By Emay Komarudin.
* 2013
*
* Description Store transaction
*
*
**/
var data_gen = generate_transaction_list(30);
Ext.define('App.store.transaction.sListTrx',{
extend : 'Ext.data.Store',
// groupField: 'trx_no',
// model : 'App.model.transaction.mOrders',
fields : ['trx_no','user_name','status','count_orders','count_items','order_no'],
data : data_gen
});
|
'use strict'
const { Message: MessageModel } = require('../model')
module.exports = exports = {
sendAtMessage: (masterId, authorId, topicId, replyId) => {
return exports.sendMessage('at', masterId, authorId, topicId, replyId)
},
sendReplyMessage: (masterId, authorId, topicId, replyId) => {
return exports.sendMessage('reply', masterId, authorId, topicId, replyId)
},
sendMessage: (type, masterId, authorId, topicId, replyId) => {
return new MessageModel({
type: type,
master_id: masterId,
author_id: authorId,
topic_id: topicId,
reply_id: replyId
}).save()
}
}
|
export { default as Toolbar } from './Toolbar';
export { default as ToolbarSection } from './ToolbarSection';
export { default as ToolbarTitle } from './ToolbarTitle';
export { default as ToolbarRow } from './ToolbarRow';
export { default as ToolbarIcon } from './ToolbarIcon';
|
var SanctuaryApp = angular.module('SanctuaryApp', [
'ngRoute',
'SanctuaryControllers'
]);
SanctuaryApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/youtubelist', {
templateUrl: 'partials/youtubelist.html',
controller: 'YoutubeListController'
})
.otherwise({
redirectTo: '/youtubelist'
});
}]);
|
'use strict';
require('angular/angular');
angular.module('<%= name %>Module', [])
.directive('<%= name %>', [
function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'src/<%= name %>/<%= name %>.tpl.html',
scope: {},
link: function(scope, element, attrs) {
scope.directiveTitle = 'dummy';
}
};
}
]);
|
import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
import InfinityRoute from "../../../../mixins/infinity-route";
export default Ember.Route.extend(InfinityRoute, AuthenticatedRouteMixin, {
_listName: 'model',
model: function() {
return this.infinityModel("report", { perPage: 10, startingPage: 1});
},
actions: {
remove: function(model) {
if(confirm('Are you sure?')) {
model.destroyRecord();
}
},
search: function () {
this.set('_listName', 'model.content');
var filter = { perPage: 10, startingPage: 1};
this.get('controller').set('model', this.infinityModel("report", filter))
}
}
});
|
/**
* @file theme loader
*
* @desc 向每个.vue文件中注入样式相关的变量,不需要手动import
* @author echaoo(1299529160@qq.com)
*/
/* eslint-disable fecs-no-require, fecs-prefer-destructure */
'use strict';
const theme = require('../../config/theme');
const loaderUtils = require('loader-utils');
const STYLE_TAG_REG = /(\<style.*?lang="styl(?:us)?".*?\>)([\S\s]*?)(\<\/style\>)/g;
// 定义在vuetify中默认的两组stylus hash:主题色和material相关
let defaultVuetifyVariables = {
themeColor: {
primary: '$blue.darken-2',
accent: '$blue.accent-2',
secondary: '$grey.darken-3',
info: '$blue.base',
warning: '$amber.base',
error: '$red.accent-2',
success: '$green.base'
},
materialDesign: {
'bg-color': '#fff',
'fg-color': '#000',
'text-color': '#000',
'primary-text-percent': .87,
'secondary-text-percent': .54,
'disabledORhints-text-percent': .38,
'divider-percent': .12,
'active-icon-percent': .54,
'inactive-icon-percent': .38
}
};
// 使用用户定义在config/theme.js中的变量覆盖默认值
let themeColor = Object.assign(
{},
defaultVuetifyVariables.themeColor,
theme.theme.themeColor
);
// 最终输出的stylus hash(themeColor部分)
let themeColorTemplate = `
$theme := {
primary: ${themeColor.primary}
accent: ${themeColor.accent}
secondary: ${themeColor.secondary}
info: ${themeColor.info}
warning: ${themeColor.warning}
error: ${themeColor.error}
success: ${themeColor.success}
}
`;
let materialDesign = Object.assign(
{},
defaultVuetifyVariables.materialDesign,
theme.theme.materialDesign
);
let materialDesignTemplate = `
$material-custom := {
bg-color: ${materialDesign['bg-color']}
fg-color: ${materialDesign['fg-color']}
text-color: ${materialDesign['text-color']}
primary-text-percent: ${materialDesign['primary-text-percent']}
secondary-text-percent: ${materialDesign['secondary-text-percent']}
disabledORhints-text-percent: ${materialDesign['disabledORhints-text-percent']}
divider-percent: ${materialDesign['divider-percent']}
active-icon-percent: ${materialDesign['active-icon-percent']}
inactive-icon-percent: ${materialDesign['inactive-icon-percent']}
}
$material-theme := $material-custom
`;
// 引入项目变量和vuetify中使用的颜色变量
let importVariablesTemplate = `
@import '~@/assets/styles/variables';
@import '~vuetify/src/stylus/settings/_colors';
`;
let injectedTemplate = importVariablesTemplate
+ themeColorTemplate + materialDesignTemplate;
module.exports = function (source) {
this.cacheable();
let options = loaderUtils.getOptions(this);
if (options && options.injectInVueFile) {
// 向每一个.vue文件的<style>块中注入
return source.replace(STYLE_TAG_REG, `$1${injectedTemplate}$2$3`);
}
return injectedTemplate + source;
};
|
/*
* Kendo UI v2014.2.1008 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["ms-BN"] = {
name: "ms-BN",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["($n)","$n"],
decimals: 0,
",": ".",
".": ",",
groupSize: [3],
symbol: "$"
}
},
calendars: {
standard: {
days: {
names: ["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"],
namesAbbr: ["Ahad","Isnin","Sel","Rabu","Khamis","Jumaat","Sabtu"],
namesShort: ["A","I","S","R","K","J","S"]
},
months: {
names: ["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember",""],
namesAbbr: ["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogos","Sept","Okt","Nov","Dis",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy H:mm:ss",
g: "dd/MM/yyyy H:mm",
G: "dd/MM/yyyy H:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
"use strict";
var m = require("mithril"),
assign = require("lodash.assign"),
id = require("./lib/id"),
hide = require("./lib/hide"),
label = require("./lib/label"),
css = require("./textarea.css");
module.exports = {
controller : function(options) {
var ctrl = this;
ctrl.id = id(options);
ctrl.text = options.data || "";
ctrl.resize = function(opt, value) {
opt.update(opt.path, value);
ctrl.text = value;
};
},
view : function(ctrl, options) {
var field = options.field,
hidden = hide(options);
if(hidden) {
return hidden;
}
return m("div", { class : options.class },
label(ctrl, options),
m("div", { class : css.expander },
m("pre", { class : css.shadow }, m("span", ctrl.text), m("br")),
m("textarea", assign({
// attrs
id : ctrl.id,
class : css.textarea,
required : field.required ? "required" : null,
// events
oninput : m.withAttr("value", ctrl.resize.bind(null, options))
},
field.attrs || {}
), options.data || "")
)
);
}
};
|
(function() {
"use strict";
angular
.module('app.users', [
'app.core'
]);
})();
|
var Plugin = require('./baseplugin'),
request = require('request-promise');
class Spotify extends Plugin {
init() {
this.httpRegex = /(?:https?:\/\/)?open\.spotify\.com\/(album|track|user\/[^\/]+\/playlist)\/([a-zA-Z0-9]+)/;
this.uriRegex = /^spotify:(album|track|user:[^:]+:playlist):([a-zA-Z0-9]+)$/;
}
canHandle(url) {
return this.httpRegex.test(url) || this.uriRegex.test(url);
}
run(url) {
var options = {
url: `https://embed.spotify.com/oembed/?url=${url}`,
headers: {'User-Agent': 'request'}
};
return request.get(options)
.then(body => JSON.parse(body).html)
.then(html => ({ type: 'spotify', html: html }));
}
}
module.exports = Spotify;
|
'use strict';
const fs = require('fs'),
_ = require('lodash');
let config = require('./_default');
const ENV_NAME = process.env.NODE_ENV || process.env.ENV;
const ENVIRONMENT_FILE = `${__dirname}/_${ENV_NAME}.js`;
// Merge with ENV file if exits.
if (fs.existsSync(ENVIRONMENT_FILE)) {
const env = require(ENVIRONMENT_FILE);
config = _.mergeWith(config, env);
}
module.exports = config;
|
import now from './now.js';
/**
* This function transforms stored pixel values into a canvas image data buffer
* by using a LUT.
*
* @param {Image} image A Cornerstone Image Object
* @param {Array} lut Lookup table array
* @param {Uint8ClampedArray} canvasImageDataData canvasImageData.data buffer filled with white pixels
*
* @returns {void}
*/
export default function (image, lut, canvasImageDataData) {
let start = now();
const pixelData = image.getPixelData();
image.stats.lastGetPixelDataTime = now() - start;
const numPixels = pixelData.length;
const minPixelValue = image.minPixelValue;
let canvasImageDataIndex = 0;
let storedPixelDataIndex = 0;
let pixelValue;
// NOTE: As of Nov 2014, most javascript engines have lower performance when indexing negative indexes.
// We have a special code path for this case that improves performance. Thanks to @jpambrun for this enhancement
// Added two paths (Int16Array, Uint16Array) to avoid polymorphic deoptimization in chrome.
start = now();
if (pixelData instanceof Int16Array) {
if (minPixelValue < 0) {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++] + (-minPixelValue)];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
} else {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++]];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
}
} else if (pixelData instanceof Uint16Array) {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++]];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
} else if (minPixelValue < 0) {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++] + (-minPixelValue)];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
} else {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++]];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
}
image.stats.lastStoredPixelDataToCanvasImageDataTime = now() - start;
}
|
module.exports = function() {
function CreditsCommand() {
return {
name: 'credits',
params: '[none]',
execute: function(data, sandbox) {
var msg = '\nCREDITS:\n';
msg += 'Hack Bot\n';
msg += 'version: v1\n';
msg += 'created by: R.M.C. (hacktastic)\n\n\n';
sandbox.sendChannelMessage(msg);
}
};
}
return new CreditsCommand();
};
|
'use strict';
const Bluebird = require('bluebird');
const Book = require('./helpers/book');
const Counter = require('../lib/counter');
const Genre = require('./helpers/genre');
const Redis = require('./helpers/redis');
describe('counter', () => {
describe('count', () => {
it('returns the count for a model without a filter function', () => {
const request = {};
return Counter.count(Genre, request)
.then((count) => {
expect(count).to.eql(3);
});
});
it('returns the count for a model with a filter function', () => {
const request = { query: { filter: { year: 1984 } }, auth: { credentials: {} } };
return Counter.count(Book, request)
.then((count) => {
expect(count).to.eql(2);
});
});
it('saves the count to redis under the given key with a ttl when a redis client is given', () => {
const key = 'key';
const ttl = () => 10;
const request = { query: { filter: { year: 1984 } }, auth: { credentials: {} } };
return Counter.count(Book, request, Redis, key, ttl)
.then(() => {
return Bluebird.all([
Redis.getAsync(key),
Redis.ttlAsync(key)
]);
})
.spread((cachedCount, cachedTtl) => {
expect(cachedCount).to.eql('2');
expect(cachedTtl).to.eql(10);
});
});
});
});
|
// Dependencies
let builder = require('focus').component.builder;
let React = require('react');
let checkIsNotNull = require('focus').util.object.checkIsNotNull;
let type = require('focus').component.types;
let find = require('lodash/collection/find');
// Mixins
let translationMixin = require('../../common/i18n').mixin;
let infiniteScrollMixin = require('../mixin/infinite-scroll').mixin;
let referenceMixin = require('../../common/mixin/reference-property');
// Components
let Button = require('../../common/button/action').component;
let listMixin = {
/**
* Display name.
*/
displayName: 'selection-list',
/**
* Mixin dependancies.
*/
mixins: [translationMixin, infiniteScrollMixin, referenceMixin],
/**
* Default properties for the list.
* @returns {{isSelection: boolean}} the default properties
*/
getDefaultProps: function getListDefaultProps(){
return {
data: [],
isSelection: true,
selectionStatus: 'partial',
selectionData: [],
isLoading: false,
operationList: [],
idField: 'id'
};
},
/**
* list property validation.
* @type {Object}
*/
propTypes: {
data: type('array'),
idField: type('string'),
isLoading: type('bool'),
isSelection: type('bool'),
lineComponent: type('func', true),
loader: type('func'),
onLineClick: type('func'),
onSelection: type('func'),
operationList: type('array'),
selectionData: type('array'),
selectionStatus: type('string')
},
/**
* called before component mount
*/
componentWillMount() {
checkIsNotNull('lineComponent', this.props.lineComponent);
},
/**
* Return selected items in the list.
* @return {Array} selected items
*/
getSelectedItems() {
let selected = [];
for(let i = 1; i < this.props.data.length + 1; i++){
let lineName = 'line' + i;
let lineValue = this.refs[lineName].getValue();
if(lineValue.isSelected){
selected.push(lineValue.item);
}
}
return selected;
},
/**
* Render lines of the list.
* @returns {*} DOM for lines
*/
_renderLines() {
let lineCount = 1;
let {data, lineComponent, selectionStatus, idField, isSelection, selectionData, onSelection, onLineClick, operationList} = this.props;
return data.map((line) => {
let isSelected;
let selection = find(selectionData, {[idField]: line[idField]});
if (selection) {
isSelected = selection.isSelected;
} else {
switch(selectionStatus){
case 'none':
isSelected = false;
break;
case 'selected':
isSelected = true;
break;
case 'partial':
isSelected = undefined;
break;
default:
isSelected = false;
}
}
return React.createElement(lineComponent, {
key: line[idField],
data: line,
ref: `line${lineCount++}`,
isSelection: isSelection,
isSelected: isSelected,
onSelection: onSelection,
onLineClick: onLineClick,
operationList: operationList,
reference: this._getReference()
});
});
},
_renderLoading() {
if(this.props.isLoading){
if(this.props.loader){
return this.props.loader();
}
return (
<li className='sl-loading'>{this.i18n('list.loading')} ...</li>
);
}
},
_renderManualFetch() {
if(this.props.isManualFetch && this.props.hasMoreData){
let style = {className: 'primary'};
return (
<li className='sl-button'>
<Button
handleOnClick={this.handleShowMore}
label='list.button.showMore'
style={style}
type='button'
/>
</li>
);
}
},
/**
* Render the list.
* @returns {XML} DOM of the component
*/
render() {
return (
<ul data-focus='selection-list'>
{this._renderLines()}
{this._renderLoading()}
{this._renderManualFetch()}
</ul>
);
}
};
module.exports = builder(listMixin);
|
import { createAction } from 'redux-actions';
import axios from '../../../utils/APIHelper';
export const CATEGORY_FORM_UPDATE = 'CATEGORY_FORM_UPDATE';
export const CATEGORY_FORM_RESET = 'CATEGORY_FORM_RESET';
export const categoryFormUpdate = createAction(CATEGORY_FORM_UPDATE);
export const categoryFormReset = createAction(CATEGORY_FORM_RESET);
export function requestCreateCategory(attrs) {
return (dispatch) => {
dispatch(categoryFormUpdate());
return axios.post('/api/categories', { category: attrs })
.then(response => {
dispatch(categoryFormReset());
return response.data.category;
}, e => dispatch(categoryFormUpdate(e)));
};
}
|
'use strict';
/**
* Module dependencies
*/
var forumsPolicy = require('../policies/forums.server.policy'),
forums = require('../controllers/forums.server.controller');
module.exports = function (app) {
// Forums collection routes
app.route('/api/forums').all(forumsPolicy.isAllowed)
.get(forums.list)
.post(forums.create);
// Single forum routes
app.route('/api/forums/:forumId').all(forumsPolicy.isAllowed)
.get(forums.read)
.put(forums.update)
.delete(forums.delete);
// Finish by binding the forum middleware
app.param('forumId', forums.forumByID);
};
|
/* global $,kendo,PouchDB */
var testHelper = testHelper || {};
//Returns event spy {events:array, dispose:function, reset:function}.
//events[i] is {e:*}.
testHelper.spyKendoEvent = function (instance, eventName) {
'use strict';
var handler = function (e) {
var copy = $.extend(true, {}, e);
result.events.push({ e: copy });
},
dispose = function () {
instance.unbind(eventName, handler);
this.reset();
},
reset = function () {
result.events = [];
},
result = {
events: [],
dispose: dispose,
reset: reset
};
instance.bind(eventName, handler);
return result;
};
//Returns promise that resolves when change event occurs on PouchDB specified number of times.
testHelper.waitForDbChanges = function (db, numberOfChanges) {
var counter = 0,
deferred = new $.Deferred(),
handler = function () {
counter++;
if (counter === numberOfChanges) {
changes.removeListener("change", handler);
deferred.resolve();
}
},
changes = db.changes({
since: 'now',
live: true
});
changes.on("change", handler);
return deferred.promise();
};
testHelper.addArrayToDataSource = function (dataSource, rows) {
$.each(rows, function (_, row) {
dataSource.add(row);
});
};
|
const EventEmitter = require('events');
class MomentumEventEmitter extends EventEmitter {}
module.exports = MomentumEventEmitter;
|
module.exports = function(grunt) {
var commonTasks = ['jscs', 'jshint', 'concat', 'uglify'];
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jscs: {
src: ['Gruntfile.js', 'src/*.js', 'test/utils-test.js', 'test/basicTimerSpec', 'test/timedFuncSpec.js']
},
jshint: {
all: ['Gruntfile.js', 'src/*.js', 'test/utils-test.js', 'test/basicTimerSpec', 'test/timedFuncSpec.js']
},
concat: {
options: {
banner: [
'/*! <%= pkg.name %> <%= pkg.version %> <%=grunt.template.today("yyyy-mm-dd")%>*/\n',
'(function($) {\n'
].join(''),
footer: '} (jQuery));'
},
dist: {
src: [
'src/constants.js',
'src/utils.js',
'src/Timer.js',
'src/index.js'
],
dest: 'dist/timer.jquery.js'
}
},
uglify: {
dist: {
src: 'dist/timer.jquery.js',
dest: 'dist/timer.jquery.min.js'
}
},
watch: {
scripts: {
files: ['src/*.js'],
tasks: commonTasks,
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', commonTasks);
};
|
module.exports = (req, res, next) => {
const _registration = req.requestParams.registration
const match = {
_registration: _registration
}
return global.models.getAll(
global.db.registrations.RegistrationDebaters,
match,
global.utils.populate.registrationDebaters,
res
)
}
|
'use strict'
const pkg = require('../package')
module.exports = {
port: 4000,
title: 'slotlist.info - ArmA 3 mission and slotlist management',
publicPath: '/',
}
|
export default from './navigation.component';
|
(function(){
'use strict';
angular
.module('app')
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('edit-profile', {
url:'/edit-profile/:id',
templateUrl: 'edit-profile-state/edit-profile.view.html',
controller: 'EditProfileController',
controllerAs: 'vm',
permissions: {
only: 'isAuthorized'
}
})
}])
})();
|
'use strict';
angular.module('<%= name %>')
.service('<%= serviceName %>', function ($q, $http) {
// A private cache key.
var cache = {};
// Update broadcast name.
var broadcastUpdateEventName = '<%= serviceName %>Change';
/**
* Return the promise with the collection, from cache or the server.
*
* @returns {*}
*/
this.get = function() {
if (cache) {
return $q.when(cache.data);
}
return getDataFromBackend();
};
/**
* Return promise with the collection from the server.
*
* @returns {$q.promise}
*/
function getDataFromBackend() {
var deferred = $q.defer();
var url = '';
$http({
method: 'GET',
url: url,
params: params,
transformResponse: prepareDataForLeafletMarkers
}).success(function(response) {
setCache(response);
deferred.resolve(response);
});
return deferred.promise;
}
/**
* Save cache, and broadcast an event, because data changed.
*
* @param data
* Object with the data to cache.
*/
var setCache = function(data) {
// Cache data by company ID.
cache = {
data: data,
timestamp: new Date()
};
// Clear cache in 60 seconds.
$timeout(function() {
if (cache.data && cache.data[cacheId]) {
cache.data[cacheId] = null;
}
}, 60000);
// Broadcast a change event.
$rootScope.$broadcast(broadcastUpdateEventName);
};
/**
* Convert the response to a collection.
*
* @param response
* The response from the $http.
*
* @returns {*}
* The Collection requested.
*/
function prepareDataForLeafletMarkers(response) {
var collection;
// Convert response serialized to an object.
collection = angular.fromJson(reponse).data;
return collection;
}
});
|
'use strict';
angular.module('myApp.contact', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contact', {
templateUrl: 'app/view/contact.html',
controller: 'contactCtrl'
});
}])
.controller('contactCtrl',['$scope','$http', function($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'http://localhost:8000/contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.';
$scope.result='bg-danger';
}
};
var myCenter=new google.maps.LatLng(42.656021, -71.330044);
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("map"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"203 University avenue Lowell, MA, 01854"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.addDomListener(window, 'load');
}]);
|
'use strict';
angular.module('f1feeder.version.version-directive', [])
.directive('appVersion', ['version', function(version) {
return function(scope, elm, attrs) {
elm.text(version);
};
}]);
|
'use strict';
/**
* Module Dependencies
*/
var gulp = require('gulp');
var sass = require('gulp-sass');
var app = require('./app.js');
/**
* Config
*/
var PUBLIC = __dirname + '/public';
var ASSETS = PUBLIC + '/assets';
/**
* Compiling
*/
gulp.task('sass', function(){
gulp.src(ASSETS + '/styles/sass/app.scss')
.pipe(sass())
.pipe(gulp.dest(ASSETS + '/styles/css'));
});
// lol
gulp.task('piss', ['sass'], function() {
app.init();
});
// Default
gulp.task('default', ['piss']);
|
import {waitFor} from './wait-for'
const isRemoved = result => !result || (Array.isArray(result) && !result.length)
// Check if the element is not present.
// As the name implies, waitForElementToBeRemoved should check `present` --> `removed`
function initialCheck(elements) {
if (isRemoved(elements)) {
throw new Error(
'The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.',
)
}
}
async function waitForElementToBeRemoved(callback, options) {
// created here so we get a nice stacktrace
const timeoutError = new Error('Timed out in waitForElementToBeRemoved.')
if (typeof callback !== 'function') {
initialCheck(callback)
const elements = Array.isArray(callback) ? callback : [callback]
const getRemainingElements = elements.map(element => {
let parent = element.parentElement
if (parent === null) return () => null
while (parent.parentElement) parent = parent.parentElement
return () => (parent.contains(element) ? element : null)
})
callback = () => getRemainingElements.map(c => c()).filter(Boolean)
}
initialCheck(callback())
return waitFor(() => {
let result
try {
result = callback()
} catch (error) {
if (error.name === 'TestingLibraryElementError') {
return undefined
}
throw error
}
if (!isRemoved(result)) {
throw timeoutError
}
return undefined
}, options)
}
export {waitForElementToBeRemoved}
/*
eslint
require-await: "off"
*/
|
// @flow
import React, { Component, PropTypes } from "react"
import { connect } from "react-redux"
import TextField from 'material-ui/TextField'
import { CreateAuctionButton } from "../../molecules/"
import * as AuctionActions from "../../../actions/auction"
import { Button } from "../../atoms/"
import styles from "./styles.css"
export class CreateAuctionBox extends Component {
constructor(props) {
super(props)
this.state = {
name: "",
minimum: "",
message: "",
image: "",
auctionMsg: props.auctionMsg,
}
}
change = (event) => {
if ("id" in event.target && "value" in event.target) {
console.log(event.target.id)
console.log(event.target.value)
this.setState({ [event.target.id]: event.target.value })
}
}
data = () => {
const { name, minimum, message, image } = this.state
const base = { name : name, minimum : minimum, message : message, image : image }
if (firebase.auth().currentUser) {
return Object.assign({}, base, { usrID : firebase.auth().currentUser.uid })
}
return base
}
action = () => {
const { name, minimum, message, image } = this.state
if (name && minimum && message && image && minimum > 0) {
const { dispatch } = this.props
console.log(this.data())
dispatch(AuctionActions.queryCreateAuction(JSON.stringify(this.data())))
}
}
componentWillReceiveProps(nextProps) {
if(JSON.stringify(this.state.auctionMsg) !== JSON.stringify(nextProps.auctionMsg))
{
this.setState({ auctionMsg: nextProps.auctionMsg })
}
}
render() {
const { auctionMsg } = this.state
return (
<div className={ styles.root }>
<h3>Create Bid</h3>
<div>Status: <span style={{ color : (auctionMsg.status.toLowerCase() !== 'success' ? "red" : "green") }}>{ auctionMsg.status }</span></div>
<TextField id="name" value={ this.state.name } floatingLabelText="Domain" onChange={this.change}/><br />
<TextField id="minimum" type="number" value={ this.state.minimum } floatingLabelText="Minimum" onChange={this.change}/><br />
<TextField id="message" value={ this.state.message } floatingLabelText="Message" onChange={this.change}/><br />
<TextField id="image" value={ this.state.image } floatingLabelText="Image" style={{ "marginBottom" : "1em"}} onChange={this.change}/><br />
<Button onClick={ this.action }>
Create Auction
</Button>
</div>
)
}
}
CreateAuctionBox.propTypes = {
auctionMsg: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
}
function mapStateToProps(state) {
const { auctionMsg } = state.auction
return {
auctionMsg,
}
}
export default connect(mapStateToProps)(CreateAuctionBox)
|
"use strict";
var expect = require('chai').expect
, protolib = require(__dirname + '/../')
;
describe('protolib', function() {
describe('clone', function() {
it('should create a clone of the given object', function() {
var object = {
name: 'Philip'
, hello: function() { return 'Hello, my name is ' + this.name; }
, date: new Date()
, arr: [1, {foo: 'bar'}]
};
var clone_object = protolib.clone(object);
expect(clone_object).to.have.property('name', 'Philip');
expect(clone_object.hello()).to.equal('Hello, my name is Philip');
expect(clone_object.date.getMonth()).to.equal(new Date().getMonth());
expect(clone_object).to.have.deep.property('arr[0]', 1);
expect(clone_object).to.have.deep.property('arr[1].foo', 'bar');
});
it('should throw an error if input is not an object or array', function() {
expect(protolib.clone).to.throw('Cannot clone!');
});
});
describe('inherit', function() {
it('should set the prototype of an object to the given value', function() {
var proto = {foo: 'bar'};
var object = protolib.inherit(proto);
expect(object).to.have.property('foo', 'bar');
proto.foo = 'baz';
expect(object).to.have.property('foo', 'baz');
});
});
describe('mixin', function() {
it('should add the prototype properties to the given object', function() {
var proto = {type: 'list', values: [1, 2, 3]};
var object = {readonly: true};
protolib.mixin(object, proto);
expect(object).to.have.property('readonly', true);
expect(object).to.have.property('type', 'list');
expect(object).to.have.deep.property('values[0]', 1);
expect(object).to.have.deep.property('values[1]', 2);
expect(object).to.have.deep.property('values[2]', 3);
});
it('should overwrite any existing properties with duplicate names', function() {
var proto = {type: 'list', values: [1, 2, 3]};
var object = {type: 'none'};
protolib.mixin(object, proto);
expect(object).to.have.property('type', 'list');
expect(object).to.have.deep.property('values[0]', 1);
expect(object).to.have.deep.property('values[1]', 2);
expect(object).to.have.deep.property('values[2]', 3);
});
});
});
|
console.log('load version 2.0.0');
|
/// <reference path="Xrm.js" />
var EntityLogicalName = "uomschedule";
var Form_a793fa7c_8b63_43f0_b4bc_73f75a68935a_Properties = {
description: "description",
name: "name"
};
var Form_a793fa7c_8b63_43f0_b4bc_73f75a68935a_Controls = {
description: "description",
name: "name"
};
var pageData = {
"Event": "none",
"SaveMode": 1,
"EventSource": null,
"AuthenticationHeader": "",
"CurrentTheme": "Default",
"OrgLcid": 1033,
"OrgUniqueName": "",
"QueryStringParameters": {
"_gridType": "1056",
"etc": "1056",
"id": "",
"pagemode": "iframe",
"preloadcache": "1344548892170",
"rskey": "141637534"
},
"ServerUrl": "",
"UserId": "",
"UserLcid": 1033,
"UserRoles": [""],
"isOutlookClient": false,
"isOutlookOnline": true,
"DataXml": "",
"EntityName": "uomschedule",
"Id": "",
"IsDirty": false,
"CurrentControl": "",
"CurrentForm": null,
"Forms": [],
"FormType": 2,
"ViewPortHeight": 558,
"ViewPortWidth": 1231,
"Attributes": [{
"Name": "description",
"Value": "",
"Type": "memo",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 2000,
"Controls": [{
"Name": "description"
}]
},
{
"Name": "name",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 200,
"Controls": [{
"Name": "name"
}]
}],
"AttributesLength": 2,
"Controls": [{
"Name": "description",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Description",
"Attribute": "description"
},
{
"Name": "name",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Name",
"Attribute": "name"
}],
"ControlsLength": 2,
"Navigation": [],
"Tabs": [{
"Label": "General",
"Name": "general",
"DisplayState": "expanded",
"Visible": true,
"Sections": [{
"Label": "UOM Schedule Information",
"Name": "uom schedule information",
"Visible": true,
"Controls": [{
"Name": "name"
},
{
"Name": "description"
}]
}]
}]
};
var Xrm = new _xrm(pageData);
|
// To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const Twilio = require('twilio').Twilio;
const client = new Twilio(accountSid, authToken);
const service = client.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
service
.syncLists('MyFirstList')
.syncListItems(0)
.update({
data: {
number: '001',
attack: '49',
name: 'Bulbasaur',
},
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'newpage', 'af', {
toolbar: 'Nuwe bladsy'
} );
|
'use strict'
const Twitter = require('twitter')
const twitterOpts = require('./auth.json')
const client = new Twitter(twitterOpts)
const twttr = require('./twttr/')
twttr.getTrendingTopics(client).then((tt) => {
tt.forEach((topic, idx) => {
twttr.searchTopic(client, topic).then((tweets) => {
let statuses = twttr.transformTweets(tweets)
console.log(statuses)
// insights: word count, graphos etc.
})
})
})
|
{
babelHelpers.inheritsLoose(Test, _Foo);
function Test() {
return _Foo.apply(this, arguments) || this;
}
return Test;
}
|
import Aquaman from './components/Aquaman.jsx'; // eslint-disable-line no-unused-vars
import '../styles/appStyles.scss';
|
const Hapi = require('hapi');
const Request = require('request');
const port = process.env.PORT || 8080;
const server = new Hapi.Server();
const cephalopods = 'http://api.gbif.org/v1/species/136';
server.connection({
port: port,
host: '0.0.0.0'
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
Request(cephalopods, function (err, response, body) {
return reply(body);
});
}
});
server.start(function () {
console.log('Server started on ' + port);
});
|
const {env, browsers} = require('config');
const isProd = env === 'production';
module.exports = {
// parser: 'sugarss',
plugins: {
'postcss-preset-env': browsers,
'cssnano': isProd ? {} : false,
}
};
|
$(document).ready(function() {
SVGUpInstance.init('inforamaui',
{"icons": {
"logo":{"url":"images/inforama-icon.svg"},
"downarrow":{"url":"images/down-arrow.svg"},
"usericon":{"url":"images/user-icon.svg"}
},
"classes":{
"mainstyle":{
"svgdefault":{"fillcolor":"#AA8833"},
"svghover":{"fillcolor":"#8CC63E"},
"cssdefault":{"opacity":"0.3", "width":"40px", "height":"40px", "transition":"all 0.5s"},
"csshover":{"opacity":"1", "width":"50px", "height":"50px"}
}
}}
);
});
|
import _ from 'lodash' // eslint-disable-line
export default function loadInitialState(req) {
const user = req.user
const state = {
auth: {},
}
if (user) {
state.auth = {
user: {id: user.id},
}
if (req.session.accessToken) {
state.auth.accessToken = req.session.accessToken.token
}
}
if (req.csrfToken) {
state.auth.csrf = req.csrfToken()
}
// Immutable.fromJS has a bug with objects flagged as anonymous in node 6
// https://github.com/facebook/immutable-js/issues/1001
return JSON.parse(JSON.stringify(state))
// callback(null, state)
}
|
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import pluralize from 'common/utils/pluralize';
import search from './actions';
import { selectSearchResultIds, selectIsSearching, selectIsSearchComplete } from './selectors';
import Element from 'common/components/Element';
import H3 from 'common/components/H3';
import Button from 'common/components/Button';
import VocabList from 'common/components/VocabList';
import { blue, orange } from 'common/styles/colors';
SearchResults.propTypes = {
ids: PropTypes.arrayOf(PropTypes.number),
isSearching: PropTypes.bool,
isSearchComplete: PropTypes.bool,
onReset: PropTypes.func.isRequired,
};
SearchResults.defaultProps = {
ids: [],
isSearching: false,
isSearchComplete: false,
};
export function SearchResults({ ids, isSearching, isSearchComplete, onReset }) {
const tooBroad = ids.length >= 50;
const amount = `${ids.length}${tooBroad ? '+' : ''}`;
const wordsFoundText = `${amount} ${pluralize('word', ids.length)} found${
tooBroad ? '. Try refining your search keywords.' : ''
}`;
return (
(isSearching || isSearchComplete) && (
<Fragment>
<Element flexRow flexCenter>
<H3>{(isSearching && 'Searching...') || wordsFoundText}</H3>
{isSearchComplete && (
<Button bgColor={orange[5]} colorHover={orange[5]} onClick={onReset}>
Clear Results
</Button>
)}
</Element>
<VocabList ids={ids} bgColor={blue[5]} showSecondary showFuri />
</Fragment>
)
);
}
const mapStateToProps = (state, props) => ({
ids: selectSearchResultIds(state, props),
isSearching: selectIsSearching(state, props),
isSearchComplete: selectIsSearchComplete(state, props),
});
const mapDispatchToProps = {
onReset: search.clear,
};
export default connect(mapStateToProps, mapDispatchToProps)(SearchResults);
|
import { toTitleCase } from 'utils';
export default values => {
let newValues = { ...values };
// Add a sourceType if no source (i.e. not scraped) and no sourceType
if (!newValues['source'] && !newValues['sourceType']) {
newValues['sourceType'] = 'user';
}
switch (newValues['sourceType']) {
case 'user':
newValues = {
...newValues,
url: undefined,
page: undefined,
book: undefined,
};
break;
case 'website':
newValues = { ...newValues, page: undefined, book: undefined };
break;
case 'book':
newValues = { ...newValues, url: undefined };
break;
default:
break;
}
if (Array.isArray(values['ingredients'])) {
newValues = {
...newValues,
ingredients: values['ingredients'].map(ingredient => ({
...ingredient,
text: ingredient.text.trim(),
})),
};
}
return {
public: true,
...newValues,
title: toTitleCase(values['title']),
};
};
|
pinion.backend.renderer.CommentRenderer = (function($) {
var constr;
// public API -- constructor
constr = function(settings, backend) {
var _this = this,
data = settings.data;
this.$element = $("<div class='pinion-backend-renderer-CommentRenderer'></div>");
// TEXTWRAPPER
var $textWrapper = $("<div class='pinion-textWrapper'></div>")
.appendTo(this.$element);
// INFOS
$("<div class='pinion-comment-info'></div>")
// USER
.append("<div class='pinion-name'><span class='pinion-backend-icon-user'></span><span class='pinion-username'>"+data.name+"</span></div>")
// TIME
.append("<div class='pinion-time'><span class='pinion-backend-icon-clock'></span><span class='pinion-time-text'>"+data.created+"</span></div>")
.append("<div class='pinion-mail'><span class='pinion-backend-icon-mail'></span><a href='mailto:"+data.email+"' class='pinion-mail-adress'>"+data.email+"</a></div>")
.appendTo(this.$element);
// COMMENT
$("<div class='pinion-commentWrapper'><div class='pinion-comment-text'>"+data.text+"</div></div>")
.appendTo(this.$element);
var $activate = $("<div class='pinion-activate'><div class='pinion-icon'></div><div class='pinion-text'>"+pinion.translate("activate comment")+"</div></div>")
.click(function() {
if(_this.$element.hasClass("pinion-activated")) {
_this.setClean();
} else {
_this.setDirty();
}
_this.$element.toggleClass("pinion-activated")
});
// RENDERER BAR
var bar = [];
if(pinion.hasPermission("comment", "approve comment")) {
bar.push($activate);
}
if(pinion.hasPermission("comment", "delete comment")) {
bar.push(pinion.data.Delete.call(this, data, function() {
_this.info.deleted = true;
_this.fadeOut(300, function() {
_this.setDirty();
});
}));
}
if(!pinion.isEmpty(bar)) {
pinion.data.Bar.call(this, bar);
}
// INFO
pinion.data.Info.call(this, ["Time"], data);
// group events
settings.groupEvents = true;
}
// public API -- prototype
constr.prototype = {
constructor: pinion.backend.renderer.CommentRenderer,
init: function() {
this.info.id = this.settings.data.id;
},
reset: function() {
this.$element.removeClass("pinion-activated");
}
}
return constr;
}(jQuery));
|
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.lang.functional.scan"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.lang.functional.scan"] = true;
dojo.provide("dojox.lang.functional.scan");
dojo.require("dojox.lang.functional.lambda");
// This module adds high-level functions and related constructs:
// - "scan" family of functions
// Notes:
// - missing high-level functions are provided with the compatible API:
// scanl, scanl1, scanr, scanr1
// Defined methods:
// - take any valid lambda argument as the functional argument
// - operate on dense arrays
// - take a string as the array argument
// - take an iterator objects as the array argument (only scanl, and scanl1)
(function(){
var d = dojo, df = dojox.lang.functional, empty = {};
d.mixin(df, {
// classic reduce-class functions
scanl: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from left
// to right using a seed value as a starting point; returns an array
// of values produced by foldl() at that point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var t, n, i;
if(d.isArray(a)){
// array
t = new Array((n = a.length) + 1);
t[0] = z;
for(i = 0; i < n; z = f.call(o, z, a[i], i, a), t[++i] = z);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
t = [z];
for(i = 0; a.hasNext(); t.push(z = f.call(o, z, a.next(), i++, a)));
}else{
// object/dictionary
t = [z];
for(i in a){
if(!(i in empty)){
t.push(z = f.call(o, z, a[i], i, a));
}
}
}
return t; // Array
},
scanl1: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from left
// to right; returns an array of values produced by foldl1() at that
// point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var t, n, z, first = true;
if(d.isArray(a)){
// array
t = new Array(n = a.length);
t[0] = z = a[0];
for(var i = 1; i < n; t[i] = z = f.call(o, z, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
if(a.hasNext()){
t = [z = a.next()];
for(var i = 1; a.hasNext(); t.push(z = f.call(o, z, a.next(), i++, a)));
}
}else{
// object/dictionary
for(var i in a){
if(!(i in empty)){
if(first){
t = [z = a[i]];
first = false;
}else{
t.push(z = f.call(o, z, a[i], i, a));
}
}
}
}
return t; // Array
},
scanr: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from right
// to left using a seed value as a starting point; returns an array
// of values produced by foldr() at that point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var n = a.length, t = new Array(n + 1), i = n;
t[n] = z;
for(; i > 0; --i, z = f.call(o, z, a[i], i, a), t[i] = z);
return t; // Array
},
scanr1: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from right
// to left; returns an array of values produced by foldr1() at that
// point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var n = a.length, t = new Array(n), z = a[n - 1], i = n - 1;
t[i] = z;
for(; i > 0; --i, z = f.call(o, z, a[i], i, a), t[i] = z);
return t; // Array
}
});
})();
}
|
'use strict';
/* jasmine specs for directives go here */
describe('directives', function () {
beforeEach(module('myApp.directives'));
describe('app-version', function () {
it('should print current version', function () {
module(function ($provide) {
$provide.value('version', 'TEST_VER');
});
inject(function ($compile, $rootScope) {
var element = $compile('<span app-version></span>')($rootScope);
expect(element.text()).toEqual('TEST_VER');
});
});
});
describe('Button directive', function(){
var $compile, $rootScope;
beforeEach(inject(function (_$rootScope_, _$compile_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('should have "btn" class to the button element', function(){
var element = $compile('<button></button>')($rootScope);
expect(element.hasClass('btn')).toBeTruthy();
})
});
describe('Pagination directive', function () {
var element, $scope, lis;
beforeEach(inject(function ($compile, $rootScope) {
$scope = $rootScope;
$scope.numPage = 5;
$scope.currentPage = 2;
element = $compile('<pagination num-pages="numPages" current-page="currentPage"></pagination>')($scope);
$scope.$digest();
lis = function () {
return element.find('li');
};
}));
it('has the number of the page as text in each page item', function () {
for (var i = 0;i < $scope.numPage; i++) {
expect(lis.eq(i).text()).toEqual('' + i);
}
});
});
});
|
const https = require('https')
const cookie = require('cookie');
var exports = module.exports = {}
exports.getResponseHeaders = function(httpOptions, formData) {
if (formData) {
httpOptions.headers = formData.getHeaders()
}
return new Promise((resolve, reject) => {
const request = https.request(httpOptions, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', () => {});
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(response.headers));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
request.end()
})
}
exports.getCookies = function(headers) {
cookies = {}
headers['set-cookie'].forEach((element) => {
cookies = Object.assign(cookies, cookie.parse(element))
})
return cookies
}
|
'use strict';
/**
* Developed by Engagement Lab, 2019
* ==============
* Route to retrieve data by url
* @class api
* @author Johnny Richardson
*
* ==========
*/
const keystone = global.keystone,
mongoose = require('mongoose'),
Bluebird = require('bluebird');
mongoose.Promise = require('bluebird');
let list = keystone.list('Story').model;
var getAdjacent = (results, res, lang) => {
let fields = 'key photo.public_id ';
if (lang === 'en')
fields += 'name';
else if (lang === 'tm')
fields += 'nameTm';
else if (lang === 'hi')
fields += 'nameHi';
// Get one next/prev person from selected person's sortorder
let nextPerson = list.findOne({
sortOrder: {
$gt: results.jsonData.sortOrder
}
}, fields).limit(1);
let prevPerson = list.findOne({
sortOrder: {
$lt: results.jsonData.sortOrder
}
}, fields).sort({
sortOrder: -1
}).limit(1);
// Poplulate next/prev and output response
Bluebird.props({
next: nextPerson,
prev: prevPerson
}).then(nextPrevResults => {
let output = Object.assign(nextPrevResults, {
person: results.jsonData
});
return res.status(200).json({
status: 200,
data: output
});
}).catch(err => {
console.log(err);
});
};
var buildData = (storyId, res, lang) => {
let data = null;
let fields = 'key photo.public_id ';
if (lang === 'en')
fields += 'name subtitle';
else if (lang === 'tm')
fields += 'nameTm subtitleTm';
else if (lang === 'hi')
fields += 'nameHi subtitleHi';
if (storyId) {
let subFields = ' description.html ';
if (lang === 'tm')
subFields = ' descriptionTm.html ';
else if (lang === 'hi')
subFields = ' descriptionHi.html ';
data = list.findOne({
key: storyId
}, fields + subFields + 'sortOrder -_id');
} else
data = list.find({}, fields + ' -_id').sort([
['sortOrder', 'descending']
]);
Bluebird.props({
jsonData: data
})
.then(results => {
// When retrieving one story, also get next/prev ones
if (storyId)
getAdjacent(results, res, lang);
else {
return res.status(200).json({
status: 200,
data: results.jsonData
});
}
}).catch(err => {
console.log(err);
})
}
/*
* Get data
*/
exports.get = function (req, res) {
let id = null;
if (req.query.id)
id = req.query.id;
let lang = null;
if (req.params.lang)
lang = req.params.lang;
return buildData(id, res, lang);
}
|
import React from 'react';
import Sortable from '../../src/';
import DemoItem from '../components/DemoItem';
export default class Dynamic extends React.Component {
constructor() {
super();
this.state = {
arr: [998, 225, 13]
};
}
handleSort(sortedArray) {
this.setState({
arr: sortedArray
});
}
handleAddElement() {
this.setState({
arr: this.state.arr.concat(Math.round(Math.random() * 1000))
});
}
handleRemoveElement(index) {
const newArr = this.state.arr.slice();
newArr.splice(index, 1);
this.setState({
arr: newArr
});
}
render() {
function renderItem(num, index) {
return (
<DemoItem key={num} className="dynamic-item" sortData={num}>
{num}
<span className="delete"
onClick={this.handleRemoveElement.bind(this, index)}
>×</span>
</DemoItem>
);
}
return (
<div className="demo-container">
<h4 className="demo-title">
Dynamically adding/removing children
<a href="https://github.com/jasonslyvia/react-anything-sortable/tree/master/demo/pages/dynamic.js" target="_blank">source</a>
</h4>
<div className="dynamic-demo">
<button onClick={::this.handleAddElement}>Add 1 element</button>
<Sortable onSort={::this.handleSort} dynamic>
{this.state.arr.map(renderItem, this)}
</Sortable>
</div>
</div>
);
}
}
|
"use strict";
var userUtils = require("../../lib/user-utils.js");
module.exports = function(core, config, store) {
core.on("setstate", function(changes) {
var future = store.with(changes),
userId = future.get("user"),
roomId = future.get("nav", "room"),
mode = future.get("nav", "mode"),
cta = future.get("app", "cta"),
role = future.get("entities", roomId + "_" + userId, "role"),
roomObj = future.getRoom(roomId);
changes.app = changes.app || {};
if (roomObj === "missing") {
changes.app.cta = null;
} else if (userId && !userUtils.isGuest(userId) && ((/(visitor|none)/).test(role) || !role) && (/(chat|room)/).test(mode) &&
!(roomObj && roomObj.guides && roomObj.guides.authorizer && roomObj.guides.authorizer.openRoom === false)) {
changes.app.cta = "follow";
} else if (cta === "follow") {
changes.app.cta = null;
}
}, 400);
};
|
export * from './achievement';
export * from './auth';
export * from './chatlinks';
export * from './forum';
export * from './help';
export * from './emotes';
export * from './rank';
export * from './test';
|
////////////////////////////////////////////////////////////////////
//
// GENERATED CLASS
//
// DO NOT EDIT
//
// See sequelize-auto-ts for edits
//
////////////////////////////////////////////////////////////////////
var Sequelize = require('sequelize');
exports.initialized = false;
exports.SEQUELIZE;
/*__each__ tables */ exports.__tableName__;
/*__each__ tables */ exports.__tableNameCamel__;
/*__ignore__*/ var __defineFieldType__;
/*__ignore__*/ var __primaryTableName__;
/*__ignore__*/ var __foreignTableName__;
/*__ignore__*/ var __firstTableName__;
/*__ignore__*/ var __secondTableName__;
/*__ignore__*/ var __associationNameQuoted__;
function initialize(database, username, password, options) {
if (exports.initialized) {
return;
}
exports.SEQUELIZE = new Sequelize(database, username, password, options);
/*__startEach__ tables */
exports.__tableName__ = exports.__tableNameCamel__ = exports.SEQUELIZE.define('__tableNameSingular__', {
/*__each__ realDbFields, */ '__fieldName__': __defineFieldType__
}, {
timestamps: false,
classMethods: {
get__tableNameSingular__: function (__tableNameSingularCamel__) {
var where = {};
var id = parseInt(__tableNameSingularCamel__);
if (isNaN(id)) {
/*__each__ realDbFields */ if (__tableNameSingularCamel__['__fieldName__'] !== undefined) {
where['__fieldName__'] = __tableNameSingularCamel__['__fieldName__'];
}
}
else {
where['__idFieldName__'] = id;
}
return exports.__tableName__.find({ where: where });
}
}
});
/*__endEach__*/
/*__startEach__ references */
__primaryTableName__.hasMany(__foreignTableName__, { foreignKey: '__foreignKey__' });
__foreignTableName__.belongsTo(__primaryTableName__, { as: __associationNameQuoted__, foreignKey: '__foreignKey__' });
/*__endEach__*/
/*__startEach__ xrefs */
__firstTableName__.hasMany(__secondTableName__, { through: '__xrefTableName__' });
__secondTableName__.hasMany(__firstTableName__, { through: '__xrefTableName__' });
/*__endEach__*/
return exports;
}
exports.initialize = initialize;
//# sourceMappingURL=sequelize-models.js.map
|
import Vue from 'vue';
import Electron from 'vue-electron';
import Resource from 'vue-resource';
import Router from 'vue-router';
import KeenUI from 'keen-ui';
import 'keen-ui/dist/keen-ui.css';
import App from './App';
import routes from './routes';
Vue.use(Electron);
Vue.use(Resource);
Vue.use(Router);
Vue.use(KeenUI);
Vue.config.debug = true;
const router = new Router({
scrollBehavior: () => ({ y: 0 }),
routes,
});
/* eslint-disable no-new */
new Vue({
router,
...App,
}).$mount('#app');
|
'use strict'
import Tea from './modules/tea.core.js'
global.app = () => {
return Tea;
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:b7405262706997cffc865837cffd6bd9eb92a8f12c3da71795815fb2da9be9f6
size 2483
|
var Imap = require('imap'),
MailParser = require('mailparser').MailParser,
moment = require('moment')
util = require('util'),
events = require('events');
var SimpleImap = function(options) {
this.options = options;
this.imap = null;
this.start = function() {
if (this.imap === null) {
this.imap = new Imap(this.options);
var selfImap = this.imap,
self = this;
selfImap.on('ready', function() {
self.emit('ready');
selfImap.openBox(self.options.mailbox, false, function() {
self.emit('open');
});
});
selfImap.on('mail', function(num) {
selfImap.search(['UNSEEN'], function(err, result) {
if (result.length) {
var f = selfImap.fetch(result, {
markSeen: true,
struct: true,
bodies: ''
});
f.on('message', function(msg, seqNo) {
msg.on('body', function(stream, info) {
var buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
stream.on('end', function() {
var mailParser = new MailParser();
mailParser.on('end', function(mailObject) {
self.emit('mail', {
from: mailObject.from,
subject: mailObject.subject,
text: mailObject.text,
html: mailObject.html,
date: moment(mailObject.date).format('YYYY-MM-DD HH:mm:ss')
});
});
mailParser.write(buffer);
mailParser.end();
});
});
});
}
});
});
selfImap.on('end', function() {
self.emit('end');
});
selfImap.on('error', function(err) {
self.emit('error', err);
});
selfImap.on('close', function(hadError) {
self.emit('close', hadError);
});
}
this.imap.connect();
}
this.stop = function() {
this.imap.destroy();
}
this.restart = function() {
this.stop();
if (arguments.length >= 1)
this.options = arguments[0];
this.start();
}
this.getImap = function() {
return this.imap;
}
};
util.inherits(SimpleImap, events.EventEmitter);
module.exports = SimpleImap
|
/**
* Connections
*
* `Connections` are like "saved settings" for your adapters. What's the difference between
* a connection and an adapter, you might ask? An adapter (e.g. `sails-mysql`) is generic--
* it needs some additional information to work (e.g. your database host, password, user, etc.)
* A `connection` is that additional information.
*
* Each model must have a `connection` property (a string) which is references the name of one
* of these connections. If it doesn't, the default `connection` configured in `config/models.js`
* will be applied. Of course, a connection can (and usually is) shared by multiple models.
* .
* Note: If you're using version control, you should put your passwords/api keys
* in `config/local.js`, environment variables, or use another strategy.
* (this is to prevent you inadvertently sensitive credentials up to your repository.)
*
* For more information on configuration, check out:
* http://links.sailsjs.org/docs/config/connections
*/
module.exports.connections = {
// Local disk storage for DEVELOPMENT ONLY
//
// Installed by default.
//
localDiskDb: {
adapter: 'sails-disk'
},
// MySQL is the world's most popular relational database.
// http://en.wikipedia.org/wiki/MySQL
//
// Run:
// npm install sails-mysql
//
someMysqlServer: {
adapter: 'sails-mysql',
host: 'YOUR_MYSQL_SERVER_HOSTNAME_OR_IP_ADDRESS',
user: 'YOUR_MYSQL_USER',
password: 'YOUR_MYSQL_PASSWORD',
database: 'YOUR_MYSQL_DB'
},
// MongoDB is the leading NoSQL database.
// http://en.wikipedia.org/wiki/MongoDB
//
// Run:
// npm install sails-mongo
//
mongodb: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
user: '',
password: '',
database: 'nhop'
},
// PostgreSQL is another officially supported relational database.
// http://en.wikipedia.org/wiki/PostgreSQL
//
// Run:
// npm install sails-postgresql
//
somePostgresqlServer: {
adapter: 'sails-postgresql',
host: 'YOUR_POSTGRES_SERVER_HOSTNAME_OR_IP_ADDRESS',
user: 'YOUR_POSTGRES_USER',
password: 'YOUR_POSTGRES_PASSWORD',
database: 'YOUR_POSTGRES_DB'
}
// More adapters:
// https://github.com/balderdashy/sails
};
|
'use strict';
var Axes = require('../../plots/cartesian/axes');
module.exports = function formatLabels(cdi, trace, fullLayout) {
var labels = {};
var mockGd = {_fullLayout: fullLayout};
var xa = Axes.getFromTrace(mockGd, trace, 'x');
var ya = Axes.getFromTrace(mockGd, trace, 'y');
labels.xLabel = Axes.tickText(xa, xa.c2l(cdi.x), true).text;
labels.yLabel = Axes.tickText(ya, ya.c2l(cdi.y), true).text;
return labels;
};
|
var app = angular.module('AtWork', [
'atwork.system',
'atwork.users',
'atwork.posts',
'atwork.streams',
'atwork.chats',
'atwork.activities',
'atwork.notifications',
'atwork.settings',
'ngMaterial']);
app.controller('AppCtrl', [
'$scope',
'$route',
'$rootScope',
'$mdSidenav',
'$mdBottomSheet',
'$location',
'$timeout',
'appLocation',
'appAuth',
'appWebSocket',
'appSettings',
'appSettingsValid',
'appToast',
function($scope, $route, $rootScope, $mdSidenav, $mdBottomSheet, $location, $timeout, appLocation, appAuth, appWebSocket, appSettings, appSettingsValid, appToast) {
$scope.barTitle = '';
$scope.search = '';
$scope.toggleSidenav = function(menuId) {
$mdSidenav(menuId).toggle();
};
$scope.updateLoginStatus = function() {
$scope.isLoggedIn = appAuth.isLoggedIn();
$scope.user = appAuth.getUser();
};
$scope.goHome = function() {
appLocation.url('/');
};
$scope.showUserActions = function($event) {
$mdBottomSheet.show({
templateUrl: '/modules/users/views/user-list.html',
controller: 'UserSheet',
targetEvent: $event
}).then(function(clickedItem) {
$scope.alert = clickedItem.name + ' clicked!';
});
};
var initiateSettings = function(cb) {
appSettings.fetch(function(settings) {
$rootScope.systemSettings = settings;
if (cb) {
cb();
}
});
};
/**
* Scroll the view to top on route change
*/
$scope.$on('$routeChangeSuccess', function() {
angular.element('*[md-scroll-y]').animate({scrollTop: 0}, 300);
$mdSidenav('left').close();
});
$scope.$on('loggedIn', function() {
$scope.updateLoginStatus();
$scope.barTitle = '';
$scope.$broadcast('updateNotifications');
appWebSocket.conn.emit('online', {token: appAuth.getToken()});
appAuth.refreshUser(function(user) {
$scope.user = user;
});
/**
* Fetch settings and get the app ready
*/
initiateSettings(function() {
$scope.$on('$routeChangeStart', function (event, toState) {
var valid = appSettingsValid();
if (!valid) {
appToast('Please complete the setup first.');
}
});
$scope.appReady = true;
$scope.barTitle = $rootScope.systemSettings.tagline;
$timeout(appSettingsValid);
});
});
$scope.$on('loggedOut', function() {
$scope.updateLoginStatus();
appWebSocket.conn.emit('logout', {token: appAuth.getToken()});
});
appWebSocket.conn.on('connect', function() {
if (appAuth.isLoggedIn()) {
appWebSocket.conn.emit('online', {token: appAuth.getToken()});
}
});
$scope.updateLoginStatus();
$timeout(function() {
if (!appAuth.isLoggedIn()) {
if (window.location.href.indexOf('/activate/') == -1 && window.location.href.indexOf('/changePassword/') == -1) {
appLocation.url('/login');
}
initiateSettings();
$scope.appReady = true;
} else {
$scope.barTitle = '';
$scope.$broadcast('loggedIn');
}
});
}
]);
|
version https://git-lfs.github.com/spec/v1
oid sha256:ad911cfe35ed2702a6023f24dac7e20b7b1d64e5583cd53411e87b5c10fa0c35
size 16080
|
function render(node){
console.log(node);
};
export default render;
|
(function ($, _, Backbone, models) {
"use strict";
models.Widget = Backbone.Model.extend({
defaults: {
"name" : "Undefined name",
"range" : '30-minutes',
"update_interval": '10'
},
url: function() {
var tmp = "/api/dashboards/" + this.get("dashboard_id") + "/widgets";
if (this.isNew()) {
return tmp;
} else {
return tmp + "/" + this.get("id");
}
},
targetsString: function() {
return (this.get("targets") || "").split(';');
}
});
})($, _, Backbone, app.models);
|
XO.View.define({
pid:'home',
vid:'page2',
version:'20131209',
cssHost:'body',
init:function(){
XO.warn('View inited:'+this.id);
}
});
|
module.exports = function (app) {
var colaboradorCtrl = app.controllers.colaborador;
app.get('/colaborador', colaboradorCtrl.index);
app.post('/buscar_colaborador', colaboradorCtrl.find);
app.get('/buscar_colaborador_id/:id', colaboradorCtrl.buscarId);
app.post('/editar_colaborador/:id', colaboradorCtrl.update);
app.get('/remover_colaborador/:id', colaboradorCtrl.remove);
app.post('/cadastrar_colaborador', colaboradorCtrl.insert);
}
|
import arrayToObject from './array-to-object'
describe('array to object', () => {
it('takes an array of object and returns an object', () => {
expect(arrayToObject([
{
name: 'A', age: 30, food: 'pizza'
}, {
name: 'B', age: 40, food: 'pasta'
}
], 'name')).toEqual({
A: { age: 30, food: 'pizza' },
B: { age: 40, food: 'pasta' }
})
})
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.