text
stringlengths 2
6.14k
|
|---|
import 'ui/stringify/editors/color.less';
import _ from 'lodash';
import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format';
import colorTemplate from 'ui/stringify/editors/color.html';
export default function ColorFormatProvider(Private) {
const FieldFormat = Private(IndexPatternsFieldFormatProvider);
const convertTemplate = _.template('<span style="<%- style %>"><%- val %></span>');
const DEFAULT_COLOR = {
range: `${Number.NEGATIVE_INFINITY}:${Number.POSITIVE_INFINITY}`,
text: '#000000',
background: '#ffffff'
};
_.class(_Color).inherits(FieldFormat);
function _Color(params) {
_Color.Super.call(this, params);
}
_Color.id = 'color';
_Color.title = 'Color';
_Color.fieldType = [
'number'
];
_Color.editor = {
template: colorTemplate,
controller($scope) {
$scope.addColor = function () {
$scope.editor.formatParams.colors.push(_.cloneDeep(DEFAULT_COLOR));
};
$scope.removeColor = function (index) {
$scope.editor.formatParams.colors.splice(index, 1);
};
}
};
_Color.paramDefaults = {
colors: [_.cloneDeep(DEFAULT_COLOR)]
};
_Color.prototype._convert = {
html(val) {
const color = _.findLast(this.param('colors'), ({ range }) => {
if (!range) return;
const [start, end] = range.split(':');
return val >= Number(start) && val <= Number(end);
});
if (!color) return _.asPrettyString(val);
let style = '';
if (color.text) style += `color: ${color.text};`;
if (color.background) style += `background-color: ${color.background};`;
return convertTemplate({ val, style });
}
};
return _Color;
};
|
#!/usr/bin/node
// 09-timer.js
//var count = 0;
var timer;
console.log('start...');
timer = setInterval(loop, 500);
timer.unref();
function loop() {
//count++;
console.log('i will loop forever! times:', Date.now());
/*
if(count === 10) {
global.clearInterval(timer);
console.log('enough! good bye!');
}
*/
}
setTimeout(function() {
console.log('Game over!');
}, 5000);
|
/*global app*/
var log = require('bows')('session-users');
var Users = require('client/js/models/users');
var UserView = require('client/js/views/users/view');
var UsersArea = require('client/js/views/users/area');
var config = require('client/js/helpers/clientconfig');
module.exports = UsersArea.extend({
initialize: function() {
var self = this;
var SessionUsers = Users.extend({
url: config.cannonUrl + '/tickets/'+self.model.id+'/users',
});
self.model.usersDetails = new SessionUsers();
self.model.on('change:users', function() {
self.fetchCollection();
});
self.fetchCollection();
},
render: function () {
this.renderWithTemplate();
this.renderCollection(this.model.usersDetails, UserView, this.queryByHook('users-list'));
},
fetchCollection: function () {
var self = this;
self.model.usersDetails.fetch({ success: function() {
log('Got session users', self.model.usersDetails.serialize());
self.render();
}});
}
});
|
'use strict';
/**
* An asynchronous bootstrap function that runs before
* your application gets started.
*
* This gives you an opportunity to set up your data model,
* run jobs, or perform some special logic.
*/
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
module.exports = async cb => {
// set plugin store
const pluginStore = strapi.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'upload'
});
strapi.plugins.upload.config.providers = [];
const loadProviders = (basePath, cb) => {
fs.readdir(path.join(basePath, 'node_modules'), async (err, node_modules) => {
// get all upload provider
const uploads = _.filter(node_modules, (node_module) => {
// DEPRECATED strapi-upload-* will be remove in next version
return _.startsWith(node_module, 'strapi-provider-upload') || _.startsWith(node_module, 'strapi-upload');
});
// mount all providers to get configs
_.forEach(uploads, (node_module) => {
strapi.plugins.upload.config.providers.push(
require(path.join(`${basePath}/node_modules/${node_module}`))
);
});
try {
// if provider config not exit set one by default
const config = await pluginStore.get({key: 'provider'});
if (!config) {
const provider = _.find(strapi.plugins.upload.config.providers, {provider: 'local'});
const value = _.assign({}, provider, {
enabled: true,
// by default limit size to 1 GB
sizeLimit: 1000000
});
await pluginStore.set({key: 'provider', value});
}
} catch (err) {
strapi.log.error(`Can't load ${config.provider} upload provider.`);
strapi.log.warn(`Please install strapi-provider-upload-${config.provider} --save in ${path.join(strapi.config.appPath, 'plugins', 'upload')} folder.`);
strapi.stop();
}
cb();
});
};
// Load providers from the plugins' node_modules.
loadProviders(path.join(strapi.config.appPath, 'plugins', 'upload'), () => {
// Load providers from the root node_modules.
loadProviders(path.join(strapi.config.appPath), cb);
});
};
|
/*
* @lc app=leetcode.cn id=1025 lang=javascript
*
* [1025] 除数博弈
*/
// @lc code=start
/**
* @param {number} N
* @return {boolean}
*/
var divisorGame = function (N) {
return N % 2 == 0;
};
// @lc code=end
|
import NextImage from 'next/image'
import src from '../../public/test.jpg'
export default function Image() {
return <NextImage src={src} />
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Contributor(s):
*
*
*
* ***** END LICENSE BLOCK ***** */
define(["require","exports","module","../lib/oop","./text","./prolog_highlight_rules","./folding/cstyle"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("./prolog_highlight_rules").PrologHighlightRules,o=e("./folding/cstyle").FoldMode,u=function(){this.HighlightRules=s,this.foldingRules=new o};r.inherits(u,i),function(){this.lineCommentStart="%",this.blockComment={start:"/*",end:"*/"},this.$id="ace/mode/prolog"}.call(u.prototype),t.Mode=u});
|
/*
===============================================================================================
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com
===============================================================================================
*/
/**
* Animate position of widget
*/
core.Class("unify.fx.Opacity", {
include: [unify.fx.core.Base],
construct : function(widget) {
unify.fx.core.Base.call(this, widget);
},
members : {
__mod : null,
__anim : null,
__resetPoint: null,
_setup : function() {
var to = this.getValue();
var from = this.__resetPoint = parseFloat(this._widget.getStyle("opacity")) || 1;
this.__mod = from;
this.__anim = to - from
},
_reset : function(value) {
this._widget.setStyle({
opacity: value||"1"
});
},
_getResetValue : function() {
return this.__resetPoint;
},
_render : function(percent, now, render) {
if (!render) {
return;
}
var mod = this.__mod;
var anim = this.__anim;
this._widget.setStyle({
opacity: (mod + anim * percent)
});
}
}
});
|
/**
* "Language Key" : {
* "languageDirection": "rtl or ltr" // for example english is left to right but arabic is right to left
* "servicesUrl": // where we pull the services data from. This can be a local (ex. js/a.json) or an external url (ex. http://my-website/a.json)
* "languageName": // The language as it will be displayed to the user.
* "languageCode": // The two letter code that is used internally, i.e. 'EN', 'AR', 'KU'
* "amani": true or false // whether this source is from amani. If it is, we convert their json schema into ours otherwise we expect it will be our format
* "logo": // URL to logo image.
* }
*/
var services = angular.module('services');
services.factory('DefaultSettings', [function () {
return {
version: 'v0.21.0',
defaultLanguage: "EN",
mapTileAPI: null,
includePolygons: false,
defaultLogo: "images/logo.png",
feedbackEndpoint: false,
analyticsId: false,
languages: {},
fields: {
allowFeedback: false
},
clusterColors: {
// Text color inside cluster markers.
text: 'rgba(0, 0, 0, 1)',
// Outer circle color for clusters of 10 or less.
small: 'rgba(181, 226, 140, 0.6)',
// Inner circle color for clusters of 10 or less.
smallInner: 'rgba(110, 204, 57, 0.6)',
// Outer circle color for clusters of 10 to 100.
medium: 'rgba(241, 211, 87, 0.6)',
// Inner circle color for clusters of 10 to 100.
mediumInner: 'rgba(240, 194, 12, 0.6)',
// Outer circle color for clusters of 100 or more.
large: 'rgba(253, 156, 115, 0.6)',
// Inner circle color for clusters of 100 or more.
largeInner: 'rgba(241, 128, 23, 0.6)',
},
search: {
shouldSort: false,
tokenize: true,
matchAllTokens: true,
threshold: 0.1,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 2,
keys: [
{
name: 'id',
weight: 0.9
},
{
name: 'region',
weight: 0.7
},
'organization.name',
'nationality',
'intakeCriteria',
'accessibility',
'coverage',
'availability',
'referralMethod',
'referralNextSteps',
'feedbackMechanism',
'feedbackDelay',
'complaintsMechanism',
'hotlinePhone',
'publicAddress',
'additionalDetails',
'comments'
],
id: 'id'
}
};
}
]);
|
// controls the loading dots and bar
angular.module('homepageApp').controller('LoadingCtrl', LoadingCtrl);
LoadingCtrl.$inject = ['$scope', '$rootScope', 'uiCalendarConfig', '$timeout'];
function LoadingCtrl($scope, $rootScope) {
// using the angular loading bar rootscope broadcast to know when all HTTP requests are finished
$rootScope.$on('cfpLoadingBar:completed', function() {
// broadcast that everything has loaded
$scope.loaded = true;
$scope.$broadcast('loaded');
});
}
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.angular_translate_extract = {
setUp: function(done) {
// setup here if necessary
done();
},
default_options: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/default_options');
var expected = grunt.file.read('test/expected/default_options');
test.equal(actual, expected, 'should extract texts correctly.');
test.done();
},
custom_interpolation: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/custom_interpolation');
var expected = grunt.file.read('test/expected/custom_interpolation');
test.equal(actual, expected, 'should handle custom interpolation delimiters correctly.');
test.done();
},
custom_regex: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/custom_regex');
var expected = grunt.file.read('test/expected/custom_regex');
test.equal(actual, expected, 'should handle custom regex correctly.');
test.done();
},
no_source_file_output: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/no_source_file_output');
var expected = grunt.file.read('test/expected/no_source_file_output');
test.equal(actual, expected, 'should extract texts without source file info.');
test.done();
},
no_source_file_line_output: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/no_source_file_line_output');
var expected = grunt.file.read('test/expected/no_source_file_line_output');
test.equal(actual, expected, 'should extract texts correctly.');
test.done();
},
};
|
//@flow
import React, { Component } from 'react'
import './DataForm.css'
type Props = {}
type State = {
value: string,
}
class DataForm extends Component<Props, State> {
state = {
value: '',
}
handleChange = (ev: SyntheticEvent<HTMLInputElement>) => {
this.setState({ value: ev.currentTarget.value })
}
handleSubmit = (ev: SyntheticEvent<HTMLButtonElement>) => {
alert(this.state.value)
ev.preventDefault()
}
render() {
return (
<form className="DataForm" onSubmit={this.handleSubmit}>
<input
type="text"
name="url"
value={this.state.value}
placeholder="Paste the link to a .csv file or Google Spreadsheet"
onChange={this.handleChange}
/>
<button type="submit">
Go
</button>
</form>
)
}
}
export default DataForm
|
import { Badge } from 'antd';
export default Badge;
|
$(document).ready(function() {
//questions
var questions = [{
'questionNum': 1,
'question': 'When was the first mobile phone, Motorola Dyna TAC 8000X manufactured?',
'answer': ['1981', '1983', '1995', '1991'],
'correctAnswer': '1983',
}, {
'questionNum': 2,
'question': 'Dr. Morton Cooper supposedly made the first "modern mobile phone" call on a New York City street in 1973. For which Illinois company was Cooper working at the time?',
'answer': ['Motorola', 'Nokia', 'Samsung', 'Sony'],
'correctAnswer': 'Motorola'
}, {
'questionNum': 3,
'question': "The first 'smart-phones' were designed in the early 1990s. What is the definition of a 'smart-phone'?",
'answer': ['A device which does not have personal digital assistance capability', 'A device which allows users to install and run applications of their choice.',
'A device which does not have a ringtone', 'Any 2G type of cellular device'
],
'correctAnswer': "A device which allows users to install and run applications of their choice."
}, {
'questionNum': 4,
'question': "Which Mobile Operating System has the world's largest user base?",
'answer': ["Apple's IOS", "Microsoft's Windows Mobile", "Research in Motion's BB10", "Google's Android OS"],
'correctAnswer': "Google's Android OS"
}]
var right = 0;
var wrong = 0;
/* EVENTS */
/* button click */
$('#start').on('click', function() {
startGame();
countdown();
$('.js-check').on('click', function() {
var answerChosen = ($(this).attr('data-name'));
var correct = (questions[this.name].correctAnswer);
if (answerChosen === correct) {
alert("Correct!!");
right++;
// alert(right);
} else {
alert("try again");
wrong++;
// alert(wrong);
}
});
})
/* FUNCTIONS */
function startGame() {
var questionString = '';
for (var i = 0; i < questions.length; i++) {
var answerString = '';
questionString = '<label class="question">' + questions[i].question + '</label>';
for (var a = 0; a < questions[i].answer.length; a++) {
answerString +=
'<label class="radio answer">' +
'<input class="answer js-check" type="radio" name="' + i +
'" data-name="' + questions[i].answer[a] +
'">' + questions[i].answer[a] +
'</input>' +
'</label>';
}
$('#questions').append('<label class="question">' + questionString +
'<div class="answer">' + answerString + '</div>' + '</label>');
}
}
// Timer
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function countdown() {
var oneMinutes = 60 * 1,
// $('#time').append('<div class="timer">' + oneMinutes + '</div>');
display = document.querySelector("#time");
startTimer(oneMinutes, display);
};
});
|
var sinon = require('sinon');
var assert = require('assert');
var Listen = require('listen-js');
describe('Device Manager', function (){
it('isMobile() should return false if nav user agent is empty string', function (){
var userAgentMock = '';
var eventManagerCreateTargetStub = sinon.stub(Listen, 'createTarget');
var eventManagerDestroyTargetStub = sinon.stub(Listen, 'destroyTarget');
var device = require('./../src/device-manager');
var getUserAgentStub = sinon.stub(device, 'getUserAgent').returns(userAgentMock);
assert.equal(device.isMobile(), false);
device.destroy();
eventManagerCreateTargetStub.restore();
eventManagerDestroyTargetStub.restore();
getUserAgentStub.restore();
});
it('Chrome for Android should return true for isMobile() and when passing "android" to isOS()', function (){
var userAgentMock = 'Mozilla/5.0 (Linux; Android 4.0.4; ' +
'Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) ' +
'Chrome/18.0.1025.133 Mobile Safari/535.19';
var eventManagerCreateTargetStub = sinon.stub(Listen, 'createTarget');
var eventManagerDestroyTargetStub = sinon.stub(Listen, 'destroyTarget');
var device = require('./../src/device-manager');
var getUserAgentStub = sinon.stub(device, 'getUserAgent').returns(userAgentMock);
assert.equal(device.isMobile(), true, 'isMobile() returns true');
assert.equal(device.isBrowser('chrome'), true, 'isBrowser() returns true');
assert.equal(device.isOS('android'), true, 'isOS() returns true');
device.destroy();
eventManagerCreateTargetStub.restore();
eventManagerDestroyTargetStub.restore();
getUserAgentStub.restore();
});
it('isBrowser("safari") should return false, even when useragent string contains the word "safari" like in Mac\'s Chrome', function (){
var chromeUserAgentMock = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) " +
"AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/42.0.2311.90 Safari/537.36";
var eventManagerCreateTargetStub = sinon.stub(Listen, 'createTarget');
var eventManagerDestroyTargetStub = sinon.stub(Listen, 'destroyTarget');
var device = require('./../src/device-manager');
var getUserAgentStub = sinon.stub(device, 'getUserAgent').returns(chromeUserAgentMock);
assert.equal(device.isBrowser('safari'), false);
device.destroy();
eventManagerCreateTargetStub.restore();
eventManagerDestroyTargetStub.restore();
getUserAgentStub.restore();
});
it('isBrowser() should return true if nothing is passed to it', function (){
var userAgentMock = '';
var eventManagerCreateTargetStub = sinon.stub(Listen, 'createTarget');
var eventManagerDestroyTargetStub = sinon.stub(Listen, 'destroyTarget');
var device = require('./../src/device-manager');
var getUserAgentStub = sinon.stub(device, 'getUserAgent').returns(userAgentMock);
assert.equal(device.isBrowser(), true);
device.destroy();
eventManagerCreateTargetStub.restore();
eventManagerDestroyTargetStub.restore();
getUserAgentStub.restore();
});
});
|
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const response = new MessagingResponse();
const message = response.message();
message.body('Store Location: 123 Easy St.');
message.media('https://demo.twilio.com/owl.png');
console.log(response.toString());
|
/* Copyright (c) 2015 Giffo. All rights reserved.*/
var fs = require("fs");
var path = require("path");
var sep = path.sep;
//author ~ giffo, dated: 10/10/2013
/**
* just load the files, parse the data and then use a simple binary search to fetch the country
*/
var GeoIP = module.exports = (function(dir) {
if(!dir)
dir = __dirname;
// read from file sync
var countryNames = {}; // use code to return country
var world = [];
var region = {};
// reads file and returns an array of string lines
function readFile(fname) {
var filename = path.resolve(dir, fname);
if(!fs.existsSync(filename)) {
console.log("your precious file does not exist: "+filename);
console.error(filename + " was not found, it is dearly needed my friend.\nExiting.");
process.exit(1);
return;
}
var filedata = fs.readFileSync(filename).toString("utf8");
return filedata.split("\n");
}
(function loadFiles(dir) {
var line, i, len;
var lines = readFile("geoip.dat");
// lines.length-1 is because the last split is nothingness
for(i=0, len = lines.length-1;i<len;i++) {
line = lines[i].split(",");
world.push(new IPBlock(line[0],line[1],line[2].trim()));
}
lines = "";
path.resolve()
lines = readFile("geoip-countries.dat");
for(i=0, len = lines.length-1;i<len;i++) {
line = lines[i].split(",");
countryNames[line[0]] = line[1];
}
lines = "";
lines = readFile("geoip-region.dat");
for(i=0, len = lines.length-1;i<len;i++) {
line = lines[i].split(",");
region[line[0]] = line[1];
}
})(dir);
function ipValue(ip) {
var n = ip.split(".");
//if(n.length !==4) {return 0;}
return (16777216*+n[0])+(65536*+n[1])+(256*+n[2])+(parseInt(n[3],10));
}
function bsearch(ipAddrValue, to, from) {
var pivot = ~~((from-to)/2)+to;
var current = world[pivot];
if(ipAddrValue < current.fromValue) {
return bsearch(ipAddrValue, to, pivot);
} else if(ipAddrValue > current.fromValue + current.range) {
return bsearch(ipAddrValue, pivot, from);
}
return current.code; // if its not less than nor greater than, we have found our match
}
return {
country:function(ip) {
var c = bsearch(ipValue(ip),0,world.length);
return c?countryNames[c]:"unknownland";
},
region:function(ip) {
var c = bsearch(ipValue(ip),0,world.length);
return c?region[c]:"somewhere";
}
}
})()
// this is how the ip's are stored
function IPBlock(fromVal, range, countryCode) {
this.fromValue = +fromVal;
this.range = +range;
this.code = countryCode;//.toLowerCase();
}
|
module.exports = Dependency1;
function Dependency1() {
}
Dependency1.prototype.testMethod = function (callback) {
setTimeout(function () {
callback(null, 'success');
}, 2000);
};
|
$("document").ready(function() {
var location = window.location.href.split("?id=");
var api_base = "http://192.168.160.39/api/Movies/";
var viewMovies = new function(){
var self = this;
var movieID = location[1];
self.movie = ko.observableArray();
getMovie = function () {
var final_link = api_base + movieID;
console.log(final_link);
$.getJSON(final_link, function(data) {
if (data[0].poster == '/images/noposter.png') {
data[0].poster = './images/noposter.png';
};
if (data[0].title_year == null){
data[0].title_year = "";
}
data[0].movie_facebook_likes = data[0].movie_facebook_likes + " <i class='fa fa-thumbs-o-up' aria-hidden='true'></i>"
/*for (var i = 0; i < data[0].movie_actors.length; i++){
var link = "http://192.168.160.39/api/Actors/" + data[0].movie_actors[i].actorID;
var pot = i;
console.log(link);
$.getJSON(link, function(data2) {
if (data2[0].photo == '/images/nophoto.png') {
data2[0].photo = './images/nophoto.png';
};
data[0].movie_actors[pot].photo = data2[0].photo;
console.log(data[0].movie_actors[pot].photo);
})
}*/
console.log(data);
self.movie(data);
})
}
getMovie();
}
ko.applyBindings(viewMovies);
});
|
(function(angular, autobahn, console){
var services = angular.module('ngWAMP', []);
services.factory('wamp', function($q) {
var globalDeferred;
function WampClient() {
this.connections = {};
}
WampClient.prototype = {
_newConnection: function(serverUrl) {
var conn = new autobahn.Connection({
url: serverUrl,
realm: 'realm1'
});
return conn;
},
_open: function(connection) {
var deferred = $q.defer();
if(connection.isOpen) {
console.log('Connection to WAMP router ['
+ connection.transport.info.url + '] is already open');
deferred.resolve(connection.session);
} else {
connection.onopen = function(session) {
console.log('Connected to WAMP router ['
+ connection.transport.info.url + "]");
deferred.resolve(session);
};
connection.onclose = function(reason, details) {
console.log('Connection to WAMP router ['
+ connection.transport.info.url
+ '] has been closed. Reason: ' + reason);
};
connection.open();
}
return deferred.promise;
}
};
WampClient.prototype.subscribe = function(streamUri, callback) {
var deferred = $q.defer();
var uri = parseUri(streamUri);
var serverUri = uri.protocol + '://' + uri.host;
serverUri += (uri.port? ':' + uri.port : '') + uri.path;
if(!this.connections.hasOwnProperty(serverUri)) {
this.connections[serverUri] = this._newConnection(serverUri);
}
var connection = this.connections[serverUri];
/**
* The connect should not be called while the previous one
* has not finished yet.
*/
var thisArg = this;
if(!globalDeferred) {
globalDeferred = $q.defer();
}
globalDeferred = $q.when(globalDeferred)
.then(function() {
return thisArg._open(connection);
})
.then(function(session) {
session.subscribe(uri.queryKey['topic'], callback)
.then(function(subscription) {
console.log('Subscribed to [' + streamUri + '] stream');
deferred.resolve(subscription);
}, function(error) {
console.log('Failed to subscribe to [' + streamUri
+ ']. Error: ' + error);
});
}, function() {
deferred.reject();
});
return deferred.promise;
};
return new WampClient();
});
})(window.angular, window.autobahn, window.console);
|
module.exports = [{
def:'Spacer',
name:'Spacer',
loadID:3,
relations:{
li:[{
other:'Faction_9',
goodwill:-100,
hostile:true
},{
other:'Faction_4',
goodwill:-80
},{
other:'Faction_0',
goodwill:0
}]
},
tacticalMemory:{
traps:{
li:[{
loc:'(233, 0, 360)',
tick:23900962
}]
}
}
},{
def:'PlayerColony',
loadID:9,
relations:{
li:[{
other:'Faction_3',
goodwill:-100,
hostile:true
},{
other:'Faction_4',
goodwill:-80
},{
other:'Faction_0',
goodwill:0
}]
}
},{
def:'FooClan',
loadID:4,
relations:{
li:[{
other:'Faction_3',
goodwill:-80
},{
other:'Faction_9',
goodwill:-80
},{
other:'Faction_0',
goodwill:0
}]
}
},{
def:'BarClan',
relations:{
li:[{
other:'Faction_3',
goodwill:-80
},{
other:'Faction_9',
goodwill:-80
},{
other:'Faction_4',
goodwill:0
}]
}
}];
|
// Description:
// This kata is designed to test your ability to extend the functionality of built-in ruby classes. In this case, we want you to extend the built-in Array class with the following methods: square(), cube(), average(), sum(), even() and odd().
// Explanation:
// square() must return a copy of the array, containing all values squared, the original array must not be changed
// cube() must return a copy of the array, containing all values cubed, the original array must not be changed
// average() must return the average of all array values, average() on an empty array must return NaN
// sum() must return the sum of all array values
// even() must return an array of all even numbers, the original array must not be changed
// odd() must return an array of all odd numbers, the original array must not be changed
// Examples:
// var numbers = [1, 2, 3, 4, 5];
// numbers.square(); // must return [1, 4, 9, 16, 25]
// numbers.cube(); // must return [1, 8, 27, 64, 125]
// numbers.average(); // must return 3
// numbers.sum(); // must return 15
// numbers.even(); // must return [2, 4]
// numbers.odd(); // must return [1, 3, 5]
// mine
Array.prototype.square = function(){
return this.map(x=>Math.pow(x,2))
}
Array.prototype.cube = function(){
return this.map(x=>Math.pow(x,3))
}
Array.prototype.sum = function(){
return this.reduce((x,y)=>x+y,0)
}
Array.prototype.average = function(){
return (this.sum()/this.length)
}
Array.prototype.even = function(){
return this.filter(x=> x%2 == 0?x:'');
}
Array.prototype.odd = function(){
return this.filter(x=> x%2 == 1?x:'');
}
// top vote solution
Array.prototype.square = function () { return this.map(function(n) { return n*n; }); }
Array.prototype.cube = function () { return this.map(function(n) { return n*n*n; }); }
Array.prototype.average = function () { return this.sum() / this.length; }
Array.prototype.sum = function () { return this.reduce(function(a, b) { return a + b; }, 0); }
Array.prototype.even = function () { return this.filter(function(item) { return 0 == item % 2; }); }
Array.prototype.odd = function () { return this.filter(function(item) { return 0 != item % 2; }); }
|
require('module-alias/register');
var generators = require('yeoman-generator');
var _ = require('lodash');
var mkdirp = require('mkdirp');
var ifNotDatabase = require('/utils/if-not-database');
var writeScript = require('/utils/write-script');
var sharedInput = require('/utils/shared-input');
var wipeableGenerator = require('/utils/wipeable-generator');
module.exports = wipeableGenerator.extend({
constructor: function() {
generators.Base.apply(this, arguments);
this.argument('sequencename', { type: String, required: false });
this.props = {};
ifNotDatabase(this, 'sequence');
if (this.sequencename !== undefined) {
this.sequencename = _.snakeCase(this.sequencename);
}
},
prompting: function() {
if (!this.options.wipe) {
var that = this;
return this.prompt([
sharedInput.entityName('sequence', this.sequencename),
sharedInput.useSchema('sequence'),
sharedInput.schemaName,
{
type: 'input',
name: 'increment',
message: 'Enter the increment step for the sequence:',
validate: function(input) {
return (!isNaN(input) && Math.ceil(input) === input)
|| 'Step must be an integer number.';
},
default: 1
},
{
type: 'input',
name: 'min',
message: 'Enter the sequence\'s minimum value or leave empty for no minimum:',
default: function(response) {
return response.increment;
}
},
{
type: 'input',
name: 'max',
message: 'Enter the sequence\'s maximum value or leave empty for no maximum:'
},
{
type: 'confirm',
name: 'owned',
message: 'Is this sequence owned by a table column?',
default: false
},
{
type: 'input',
name: 'table',
message: 'Enter the name of the column (schema.table.column):',
when: function(response) { return response.owned; }
}
]).then(function(props) {
that.props = props;
});
}
},
writing: function() {
if (this.options.wipe) {
this._wipe(this.sequencename, 'sequences');
} else {
writeScript(this, {
databaseName: this.props.dbname,
entityCollection: 'sequences',
useSchema: this.props.useschema,
schemaName: this.props.schemaname,
entityName: this.props.sequencename,
scriptType: 'sql',
templateName: 'create_sequence'
});
}
}
});
|
const Addon_Id = "treeview";
const item = GetAddonElement(Addon_Id);
Sync.TreeView = {
strName: "Tree",
List: item.getAttribute("List"),
nPos: 0,
WM: TWM_APP++,
Depth: GetNum(item.getAttribute("Depth")),
Collapse: GetNum(item.getAttribute("Collapse")),
Exec: function (Ctrl, pt) {
const FV = GetFolderView(Ctrl, pt);
if (FV) {
FV.Focus();
const TV = FV.TreeView;
if (TV) {
TV.Visible = !TV.Visible;
if (TV.Visible) {
if (!TV.Width) {
TV.Width = 200;
}
Sync.TreeView.Expand(FV);
}
}
}
return S_OK;
},
Expand: function (Ctrl) {
if (Sync.TreeView.List && Ctrl.FolderItem) {
var TV = Ctrl.TreeView;
if (TV) {
if (Sync.TreeView.Collapse) {
const hwnd = TV.hwndTree;
let hItem = api.SendMessage(hwnd, TVM_GETNEXTITEM, 9, null);
let Now = TV.SelectedItem;
let New = Ctrl.FolderItem;
let nUp = Sync.TreeView.Depth ? 0 : 1;
while (api.ILGetCount(New) > api.ILGetCount(Now)) {
New = api.ILRemoveLastID(New);
}
while (api.ILGetCount(Now) > api.ILGetCount(New)) {
Now = api.ILRemoveLastID(Now);
++nUp;
}
while (!api.ILIsEqual(Now, New) && api.ILGetCount(Now) > 1) {
New = api.ILRemoveLastID(New);
Now = api.ILRemoveLastID(Now);
++nUp;
}
while (--nUp > 0) {
hItem = api.SendMessage(hwnd, TVM_GETNEXTITEM, 3, hItem);
}
do {
api.PostMessage(hwnd, TVM_EXPAND, 0x8001, hItem);
} while (hItem = api.SendMessage(hwnd, TVM_GETNEXTITEM, 1, hItem));
}
TV.Expand(Ctrl.FolderItem, Sync.TreeView.Depth);
}
}
},
Refresh: function (Ctrl, pt) {
var FV = GetFolderView(Ctrl, pt);
FV.TreeView.Refresh();
Sync.TreeView.Expand(FV);
}
};
if (GetNum(item.getAttribute("Refresh"))) {
AddEvent("Refresh", Sync.TreeView.Refresh);
} else {
SetKeyExec("Tree", "$3f,Ctrl+R", function (Ctrl, pt) {
Sync.TreeView.Refresh(Ctrl, pt);
return S_OK;
}, "Func", true);
}
if (Sync.TreeView.List) {
AddEvent("ChangeView", Sync.TreeView.Expand);
}
//Menu
if (item.getAttribute("MenuExec")) {
Sync.TreeView.nPos = api.LowPart(item.getAttribute("MenuPos"));
Sync.TreeView.strName = item.getAttribute("MenuName") || Sync.TreeView.strName;
AddEvent(item.getAttribute("Menu"), function (Ctrl, hMenu, nPos) {
api.InsertMenu(hMenu, Sync.TreeView.nPos, MF_BYPOSITION | MF_STRING, ++nPos, GetText(Sync.TreeView.strName));
ExtraMenuCommand[nPos] = Sync.TreeView.Exec;
return nPos;
});
}
//Key
if (item.getAttribute("KeyExec")) {
SetKeyExec(item.getAttribute("KeyOn"), item.getAttribute("Key"), Sync.TreeView.Exec, "Func");
}
//Mouse
if (item.getAttribute("MouseExec")) {
SetGestureExec(item.getAttribute("MouseOn"), item.getAttribute("Mouse"), Sync.TreeView.Exec, "Func");
}
if (Sync.TreeView.List) {
SetGestureExec("Tree", "1", function (Ctrl, pt) {
const Item = Ctrl.HitTest(pt);
if (Item) {
const FV = Ctrl.FolderView;
if (!api.ILIsEqual(FV.FolderItem, Item) && Item.IsFolder) {
setTimeout(function () {
FV.Navigate(Item, GetNavigateFlags(FV));
}, 99);
}
}
return S_OK;
}, "Func", true);
}
SetGestureExec("Tree", "11", function (Ctrl, pt) {
const Item = Ctrl.HitTest(pt);
if (Item) {
const FV = Ctrl.FolderView;
if (!api.ILIsEqual(FV.FolderItem, Item)) {
setTimeout(function () {
FolderMenu.Invoke(Item, void 0, FV);
}, 99);
}
}
return S_OK;
}, "Func", true);
SetGestureExec("Tree", "3", function (Ctrl, pt) {
const Item = Ctrl.SelectedItem;
if (Item) {
setTimeout(function () {
Ctrl.FolderView.Navigate(Item, SBSP_NEWBROWSER);
}, 99);
}
return S_OK;
}, "Func", true);
//Tab
SetKeyExec("Tree", "$f", function (Ctrl, pt) {
const FV = GetFolderView(Ctrl, pt);
FV.focus();
return S_OK;
}, "Func", true);
//Enter
SetKeyExec("Tree", "$1c", function (Ctrl, pt) {
const FV = GetFolderView(Ctrl, pt);
FV.Navigate(Ctrl.SelectedItem, GetNavigateFlags(FV));
return S_OK;
}, "Func", true);
AddTypeEx("Add-ons", "Tree", Sync.TreeView.Exec);
if (WINVER >= 0x600) {
AddEvent("AppMessage", function (Ctrl, hwnd, msg, wParam, lParam) {
if (msg == Sync.TreeView.WM) {
const pidls = {};
const hLock = api.SHChangeNotification_Lock(wParam, lParam, pidls);
if (hLock) {
api.SHChangeNotification_Unlock(hLock);
const cFV = te.Ctrls(CTRL_FV);
for (let i in cFV) {
cFV[i].TreeView.Notify(pidls.lEvent, pidls[0], pidls[1], wParam, lParam);
}
}
return S_OK;
}
});
AddEvent("Finalize", function () {
api.SHChangeNotifyDeregister(Sync.TreeView.uRegisterId);
});
Sync.TreeView.uRegisterId = api.SHChangeNotifyRegister(te.hwnd, SHCNRF_InterruptLevel | SHCNRF_NewDelivery, SHCNE_MKDIR | SHCNE_MEDIAINSERTED | SHCNE_DRIVEADD | SHCNE_NETSHARE | SHCNE_DRIVEREMOVED | SHCNE_MEDIAREMOVED | SHCNE_NETUNSHARE | SHCNE_RENAMEFOLDER | SHCNE_RMDIR | SHCNE_SERVERDISCONNECT | SHCNE_UPDATEDIR, Sync.TreeView.WM, ssfDESKTOP, true);
}
|
/**
* @ignore
* TabBar for KISSY.
* @author yiminghe@gmail.com
*/
var Toolbar = require('toolbar');
var util = require('util');
/**
* tab bar container for tab tabs.xclass: 'tabs-bar'.
* @class KISSY.Tabs.Bar
* @extends KISSY.Toolbar
*/
var TabBar = Toolbar.extend({
beforeCreateDom: function (renderData) {
renderData.elAttrs.role = 'tablist';
},
bindUI: function () {
var self = this;
self.on('afterSelectedChange', function (e) {
if (e.newVal && e.target.isTabsTab) {
self.set('selectedTab', e.target);
}
});
},
syncUI: function () {
var self = this,
children = self.get('children');
util.each(children, function (c) {
if (c.get('selected')) {
self.setInternal('selectedTab', c);
return false;
}
return undefined;
});
},
handleKeyDownInternal: function (e) {
var self = this;
var current = self.get('selectedTab');
var next = self.getNextItemByKeyDown(e, current);
if (typeof next === 'boolean') {
return next;
} else {
next.set('selected', true);
return true;
}
},
_onSetSelectedTab: function (v, e) {
var prev;
if (v) {
if (e && (prev = e.prevVal)) {
prev.set('selected', false);
}
v.set('selected', true);
}
},
_onSetHighlightedItem: function (v, e) {
var self = this;
self.callSuper(v, e);
if (self.get('changeType') === 'mouse') {
self._onSetSelectedTab.apply(self, arguments);
}
}
}, {
ATTRS: {
selectedTab: {
},
changeType: {
value: 'click'
},
defaultChildCfg: {
valueFn: function () {
return {
xclass: 'tabs-tab'
};
}
}
},
xclass: 'tabs-bar'
});
/**
* tabs change type
* @enum {String} KISSY.Tabs.ChangeType
*/
TabBar.ChangeType = {
/**
* click
*/
CLICK: 'click',
/**
* mouse
*/
MOUSE: 'mouse'
};
module.exports = TabBar;
|
/*
Eventually by HTML5 UP
html5up.net | @n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/
(function() {
"use strict";
// Methods/polyfills.
// classList | (c) @remy | github.com/remy/polyfills | rem.mit-license.org
!function(){function t(t){this.el=t;for(var n=t.className.replace(/^\s+|\s+$/g,"").split(/\s+/),i=0;i<n.length;i++)e.call(this,n[i])}function n(t,n,i){Object.defineProperty?Object.defineProperty(t,n,{get:i}):t.__defineGetter__(n,i)}if(!("undefined"==typeof window.Element||"classList"in document.documentElement)){var i=Array.prototype,e=i.push,s=i.splice,o=i.join;t.prototype={add:function(t){this.contains(t)||(e.call(this,t),this.el.className=this.toString())},contains:function(t){return-1!=this.el.className.indexOf(t)},item:function(t){return this[t]||null},remove:function(t){if(this.contains(t)){for(var n=0;n<this.length&&this[n]!=t;n++);s.call(this,n,1),this.el.className=this.toString()}},toString:function(){return o.call(this," ")},toggle:function(t){return this.contains(t)?this.remove(t):this.add(t),this.contains(t)}},window.DOMTokenList=t,n(Element.prototype,"classList",function(){return new t(this)})}}();
// canUse
window.canUse=function(p){if(!window._canUse)window._canUse=document.createElement("div");var e=window._canUse.style,up=p.charAt(0).toUpperCase()+p.slice(1);return p in e||"Moz"+up in e||"Webkit"+up in e||"O"+up in e||"ms"+up in e};
// window.addEventListener
(function(){if("addEventListener"in window)return;window.addEventListener=function(type,f){window.attachEvent("on"+type,f)}})();
// Vars.
var $body = document.querySelector('body');
// Disable animations/transitions until everything's loaded.
$body.classList.add('is-loading');
window.addEventListener('load', function() {
window.setTimeout(function() {
$body.classList.remove('is-loading');
}, 100);
});
})();
|
import React, { PropTypes } from 'react'
import '../../styles/core.scss'
import GlobalMenu from 'components/GlobalMenu/GlobalMenu'
// Note: Stateless/function components *will not* hot reload!
// react-transform *only* works on component classes.
//
// Since layouts rarely change, they are a good place to
// leverage React's new Stateless Functions:
// https://facebook.github.io/react/docs/reusable-components.html#stateless-functions
//
// CoreLayout is a pure function of its props, so we can
// define it with a plain javascript function...
function CoreLayout ({ children }) {
return (
<div className='page-container'>
<GlobalMenu />
<div className='view-container'>
{children}
</div>
</div>
)
}
CoreLayout.propTypes = {
children: PropTypes.element
}
export default CoreLayout
|
import { extend } from 'lodash-es'
import cheerio from 'cheerio'
import serialize from 'dom-serializer'
var $ = null
function _createElement(data) {
var options = {}
if (data.root && data.root.options) {
options = data.root.options
}
return extend({
attribs: {},
children: [],
parent: null,
root: null,
options: options,
next: null,
prev: null
}, data)
}
if (!$) {
if (cheerio.prototype) {
cheerio.prototype.prop = cheerio.prototype.attr
cheerio.prototype.removeProp = cheerio.prototype.removeAttr
cheerio.prototype.on = function() {}
cheerio.prototype.off = function() {}
$ = cheerio.load('', {decodeEntities: false})
$._createElement = function(tagName, root) {
return _createElement({
type: "tag",
name: tagName,
root: root
})
}
/*
we need to be able to create native text nodes efficiently
this code is taken from:
https://github.com/cheeriojs/cheerio/blob/106e42a04e38f0d2c7c096d693be2f725c89dc85/lib/api/manipulation.js#L366
*/
$._createTextNode = function(text, root) {
return _createElement({
type: 'text',
data: text,
root: root
})
}
var parseMarkup = function(str, options) {
var parsed = $.load(str, options)
var root = parsed.root()[0]
if (!root.options) {
root.options = options
}
return root.children.slice()
}
$.parseHTML = function(str) {
return parseMarkup(str, { xmlMode: false })
}
$.parseXML = function(str) {
return parseMarkup(str, { xmlMode: true })
}
$._serialize = function(el) {
var opts = el.options || (el.root && el.root.options)
return serialize(el, opts)
}
}
}
export default $
|
exports.TYPE_WARNING = 1;
exports.TYPE_ERROR = 2;
exports.ERRORS = {
BASIC_VALIDATION_ERROR: 1000,
MISSING_ACL: 1100
};
exports.InputError = function (errorType, errorCode) {
if (typeof errorType !== 'number') {
throw "errorType has to be an integer";
}
if (typeof errorCode !== 'number' && typeof errorCode !== 'string') {
throw "errorCode must be an integer or string";
}
this.errorType = errorType;
this.errorCode = errorCode;
};
exports.InputErrorCollection = function (errors) {
var messages = errors ? errors : [];
this.hasError = function (errorCode) {
for(key in messages) {
if(
(errorCode && messages[key].errorCode === errorCode)
|| messages[key].errorType === exports.TYPE_ERROR
) {
return true;
}
}
return false;
};
this.add = function(inputError) {
messages.push(inputError);
};
};
|
import React, {PropTypes} from 'react';
export default class InfiniteScroll extends React.Component {
static propTypes = {
bufferPx: PropTypes.number,
callback: PropTypes.func,
autoFirstLoad: PropTypes.bool,
style: PropTypes.object
};
static defaultProps = {
bufferPx: 40,
autoFirstLoad: false,
style: {}
};
constructor() {
super();
this.dom = null;
this.timer = null;
}
componentDidMount() {
if (!this.dom) {
return false;
}
this.dom.addEventListener('scroll', (e) => {
if (this.checkScrollBottom()) {
this.throttle(this.props.callback);
}
});
if (this.props.autoFirstLoad) {
this.props.callback();
}
}
componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) {
if (!this.checkBottom()) {
this.throttle(this.props.callback);
}
}
}
throttle(func, time = 150) {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
if (typeof func === 'function') {
func();
}
}, time);
}
checkScrollBottom() {
if (!this.dom) {
return false;
}
if (this.dom.scrollTop === 0) {
return true;
}
return this.dom.scrollTop + this.dom.clientHeight + this.props.bufferPx >= this.dom.scrollHeight;
}
checkBottom() {
if (!this.dom) {
return true;
}
if (!this.dom.lastChild) {
return false;
}
return this.dom.lastChild.offsetTop + this.props.bufferPx >= this.dom.scrollTop + this.dom.clientHeight;
}
componentWillUnmount() {
this.dom.removeEndEventListener('scroll');
}
render() {
return (
<div ref={(ref) => this.dom = ref}
style={this.props.style}
>
{this.props.children}
</div>
)
}
}
|
/**
* Created by lindem on 12/4/13.
*/
module.exports = function (grunt) {
"use strict";
grunt.initConfig({
ts: {
// use to override the default options, See: http://gruntjs.com/configuring-tasks#options
// these are the default options to the typescript compiler for grunt-ts:
// see `tsc --help` for a list of supported options.
options: {
compile: true, // perform compilation. [true (default) | false]
comments: false, // same as !removeComments. [true | false (default)]
target: 'es5', // target javascript language. [es3 (default) | es5]
module: 'commonjs', // target javascript module style. [amd (default) | commonjs]
sourceMap: true, // generate a source map for every output js file. [true (default) | false]
sourceRoot: '', // where to locate TypeScript files. [(default) '' == source ts location]
mapRoot: '', // where to locate .map.js files. [(default) '' == generated js location.]
declaration: false // generate a declaration .d.ts file for every output js file. [true | false (default)]
},
// a particular target
cjsbuild: {
src: ["src/FirstContract.ts"], // The source typescript files, http://gruntjs.com/configuring-tasks#files
//outDir: 'commonjs', // If specified, generate an out.js file which is the merged js file
outDir: 'commonjs',
//watch: 'src', // If specified, watches this directory for changes, and re-runs the current target
// use to override the grunt-ts project options above for this target
options: {
module: 'commonjs'
}
},
amdbuild: {
src: ["src/FirstContract.ts"],
outDir: 'amd',
options: {
module: "amd",
sourceMap: false
}
},
plainjsbuild: {
src: ["src/fc-script.ts"],
options: {
module: "commonjs"
}
}
},
clean: {
commonjs: ["commonjs"],
amd: ["amd"],
plainjs: ["plainjs"]
},
mochaTest: {
test: {
options: {
reporter: "spec",
ui: "tdd"
},
src: ["tests/*js"]
}
},
browserify: {
browsersuite: {
files: {
"browser/build.js": ["browser/alltests.js"]
}
},
plainjsbuild: {
files: {
"plainjs/firstcontract.js": ["commonjs/FirstContract.js"]
}
}
},
mocha_phantomjs: {
browsersuite: ["browser/*.html"]
},
gitpush: {
"github": {
options: {
remote: "github",
branch: "master"
}
},
"tixn": {
options: {
remote: "origin",
branch: "master"
}
}
}
});
grunt.loadNpmTasks("grunt-ts");
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-phantomjs");
grunt.loadNpmTasks("grunt-browserify");
grunt.loadNpmTasks("grunt-git");
grunt.registerTask("browsersuite", [
"browserify:browsersuite",
"mocha_phantomjs:browsersuite"
]);
grunt.registerTask("gitpush", ["gitpush:tixn", "gitpush:github"]);
grunt.registerTask("test", ["mochaTest"]);
grunt.registerTask("default", [
"clean:commonjs",
"clean:amd",
"clean:plainjs",
"ts:cjsbuild",
"ts:amdbuild",
// plain javascript is built with browserify.
"ts:plainjsbuild",
"browserify:plainjsbuild",
"mochaTest"]);
};
|
define('views/modifyView', ['text!views/templates/modify.html'], function(template) {
"use strict";
return Backbone.View.extend({
tagName: 'div',
className: 'modalDialog visible',
error: '',
initialize: function(){
},
events: {
'click #closeBtn': 'onClose'
},
setError: function(error) {
this.error = error;
},
render: function() {
this.$el.html(template);
this.$('.modifyok').i18n();
if(this.error === 'noright') {
this.$('.titleModify').text(i18n.t('noright.title'));
this.$('.detailsModify').text(i18n.t('noright.subtitle'));
}
else if(this.error === 'badpassword') {
this.$('.titleModify').text(i18n.t('badpassword.title'));
this.$('.detailsModify').text(i18n.t('badpassword.subtitle'));
}
return this;
},
close: function() {
this.remove();
this.undelegateEvents();
this.unbind();
this.off();
},
onClose: function(e) {
e.preventDefault();
e.stopPropagation();
Backbone.Mediator.publish('modifyok-close', this.model);
},
});
});
|
(function(){
'use strict';
var garage = require('./garage');
var util = require('util');
var events = require('events');
function GarageMonitor(){
this.interval = setInterval(function(){
garage.isOpen(function(err, open){
this.emit('update', open);
}.bind(this));
}.bind(this), 30000);
this.on('update', function(open){
if(open !== this.open){
this.open = open;
this.emit('change', this.open);
}
}.bind(this));
}
util.inherits(GarageMonitor, events.EventEmitter);
module.exports = exports = new GarageMonitor();
})();
|
me.CustomImageLayer = me.ImageLayer.extend({
init: function(x, y, name, width, height, image, z, ratio) {
this._super(me.ImageLayer, "init", [name, width, height, image, z, ratio]);
this.x = x;
this.y = y;
},
draw: function(renderer, rect) {
var context = renderer.getContext();
context.save();
context.translate(this.x, this.y);
//context.beginPath();
//context.rect(0, 0, this.x, this.y);
//context.clip();
this._super(me.ImageLayer, "draw", [renderer, rect]);
context.restore();
}
});
|
var level2_menu = {
preload: function() {
},
create: function() {
game.input.onTap.add(this.start, this);
var style = { font: "30px Arial", fill: "#ffffff" };
// Adding a text centered on the screen
var text = this.game.add.text(game.world.centerX, game.world.centerY - 50, "Top Hatty Bird", style);
text.anchor.setTo(0.5, 0.5);
var text1 = this.game.add.text(game.world.centerX, game.world.centerY - 20, "approaches a room...", style);
text1.anchor.setTo(0.5, 0.5);
var text2 = this.game.add.text(game.world.centerX, game.world.centerY + 50, "Badass..", style);
text2.anchor.setTo(0.5, 0.5);
},
start: function() {
this.game.state.start('level2');
}
};
|
export function isUndefined(value) {
return typeof value === "undefined";
}
export function isString(value) {
return typeof value === "string";
}
export function isEmptyObject(value) {
return !Object.keys(value).length;
}
export function isObject(value) {
return value instanceof Object;
}
//# sourceMappingURL=utils.js.map
|
/*
* regexp-inverse
* https://github.com/dploeger/regexp-inverse
*
* Copyright (c) 2016 Dennis Ploeger
* Licensed under the MIT license.
*/
'use strict';
function RegExpInverse(pattern, flags) {
this.regExp = new RegExp(pattern, flags);
}
RegExpInverse.prototype.exec = function (text) {
var matches = this.regExp.exec(text);
if (matches) {
return null;
} else {
return [text];
}
};
RegExpInverse.prototype.compile = function (pattern, flags) {
this.regExp.compile(pattern, flags);
};
RegExpInverse.prototype.test = function (text) {
return !this.regExp.test(text);
};
RegExpInverse.prototype.toString = function () {
return this.regExp.toString();
};
module.exports = RegExpInverse;
|
import Parser from "../parser";
import { types as tt } from "../tokenizer/types";
const pp = Parser.prototype;
export default function(parser) {
if (parser.__tryExpressionPluginInstalled) return;
parser.__tryExpressionPluginInstalled = true;
// c/p parseTryStatement
pp.parseTry = function(node, isExpression) {
this.next();
let indentLevel, isBrace = true;
if (this.hasPlugin("lightscript")) {
indentLevel = this.state.indentLevel;
isBrace = this.match(tt.braceL);
if (!isBrace) this.pushBlockState("try", indentLevel);
}
node.handler = null;
node.guardedHandlers = [];
this.parseTryBlock(node, isBrace, isExpression);
// coalescing `try` can't have catch or finally
if (node.coalesce) {
if (this.match(tt._catch) || this.match(tt._finally)) {
this.unexpected(null, "Cannot use `catch` or `finally` with error-coalescing `try`");
}
} else {
this.parseCatchBlock(node, indentLevel, isBrace);
if (!isExpression) {
this.parseFinallyBlock(node, indentLevel, isBrace);
} else {
if (this.match(tt._finally)) {
this.unexpected(null, "Finalizers are illegal with `try` expressions." +
" Use a `try` statement instead.");
}
}
}
if (!node.coalesce && !node.handler && !node.finalizer) {
this.raise(node.start, "Missing catch or finally clause");
}
if (this.hasPlugin("lightscript") && !isBrace) this.popBlockState();
return this.finishNode(node, isExpression ? "TryExpression" : "TryStatement");
};
pp.parseTryBlock = function(node, isBrace) {
if (!isBrace && !this.match(tt.colon)) {
// Allow `try (Expr)` for error coalescence
node.block = this.parseExpression();
node.coalesce = true;
} else {
node.block = this.parseBlock();
}
};
pp.parseCatchBlock = function(node, tryIndentLevel, isBrace) {
const shouldParseCatch = this.match(tt._catch) && (
!this.hasPlugin("lightscript") ||
tryIndentLevel <= this.state.indentLevel ||
(isBrace && !this.matchBlockState("try", this.state.indentLevel))
);
if (shouldParseCatch) {
const clause = this.startNode();
this.next();
clause.param = null;
if (!this.match(tt.colon) && !this.match(tt.braceL)) {
this.parseCatchClauseParam(clause);
}
if (this.hasPlugin("lightscript")) {
this.expectParenFreeBlockStart(clause);
if (!this.match(tt.colon) && !this.match(tt.braceL)) {
this.unexpected(null, "Expected a block.");
}
}
clause.body = this.parseBlock();
node.handler = this.finishNode(clause, "CatchClause");
}
};
pp.parseCatchClauseParam = function(clause) {
if (this.hasPlugin("lightscript")) {
if (this.eat(tt.parenL)) {
this.addExtra(clause, "hasParens", true);
}
} else {
this.expect(tt.parenL);
}
clause.param = this.parseBindingAtom();
this.checkLVal(clause.param, true, Object.create(null), "catch clause");
if (!this.hasPlugin("lightscript")) {
this.expect(tt.parenR);
}
};
pp.parseFinallyBlock = function(node, tryIndentLevel, isBrace) {
if (this.hasPlugin("lightscript")) {
const shouldParseFinally = this.match(tt._finally) && (
tryIndentLevel <= this.state.indentLevel ||
(isBrace && !this.matchBlockState("try", this.state.indentLevel))
);
if (shouldParseFinally) {
this.next();
if (!this.match(tt.colon) && !this.match(tt.braceL)) {
this.unexpected(null, "Expected a block.");
}
node.finalizer = this.parseBlock();
} else {
node.finalizer = null;
}
} else {
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
}
};
}
|
//@flow
const API_URL = "https://api.dribbble.com/v1/",
ACCESS_TOKEN = "8d9bd601f9461955b330d88c44f2930257364de98cddc2064d93cdcb300cb91d";
function fetchData(URL) {
return fetch(URL, {
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN
}
}).then((response) => response.json())
}
export function getShotsByType(type: string, pageNumber: ?number): ?Object {
var URL = API_URL + "shots/?list=" + type;
if (pageNumber) {
URL += "&per_page=10&page=" + pageNumber;
}
return fetchData(URL);
}
export function getResources(url: ?string): ?Object {
return fetchData(url);
}
|
//Products.html
function addProduct(index) {
var elems = $(".product" + index+"");
var productName = elems[0].innerHTML;
var orderProducts = $("strong.orderName");
var exist = false;
for (var i=0;i<orderProducts.length && !exist;i++){
if(productName===orderProducts[i].innerHTML){
exist=true;
var amount = parseInt($("span.amount:eq("+i+")").text()) + 1;
$("span.amount:eq("+i+")").text(amount);
$("input[name=amounts]:eq("+i+")").val(amount);
}
}
if(!exist){
var id = $(elems[0]).parent().find("input[type='hidden']").val();
var row = $("<tr></tr>");
row.html('<td><span class="glyphicon glyphicon-remove" aria-hidden="true" onclick="removeProduct(this);"></span></td>'
+'<td><span class="amount">1</span><input name=amounts type="hidden" value="1"/></td>'
+'<td><input name=products type="hidden" value="'+id+'"/><span>x</span></td>'
+'<td><span class="product"><strong class="orderName">'+productName+'</strong></span></td>'
+'<td><span class="price">'+elems[1].innerHTML+'</span> <span class="glyphicon glyphicon-euro"></span></td>');
row.insertBefore($("#totalRow"));
}
calculateTotal();
}
function calculateTotal(){
var amounts = $("span.amount");
var prices = $("span.price");
var total = 0;
for(var i=0; i<amounts.length;i++){
total = total + amounts[i].innerHTML * prices[i].innerHTML;
}
$("#totalID").text(total);
$("input[name='total']").val(total);
}
function removeProduct(elem){
var index = $(elem).parent().parent().index();
var amount = parseInt($("span.amount:eq("+index+")").text());
amount--;
if(amount<1){
$("#order tr:eq("+index+")").remove();
}else{
$("span.amount:eq("+index+")").text(amount);
}
calculateTotal();
}
//Form.html
function changeForm(){
var userType = $("input[name='userType']:checked").val();
if(userType==="person"){
$(".surname").show();
$(".categorias").hide();
$(".image").hide();
}else{
$(".surname").hide();
$(".categorias").show();
$(".image").show();
}
}
//listRequest.html
function deliver(elem){
var index = $(elem).parent().parent().index();
$("input[name='delivered']")[index].value=true;
var spanDel = $($("span.delivered")[index]);
spanDel.html("<strong> Entregado </strong>");
spanDel.removeClass("text-warning");
spanDel.addClass("text-primary");
elem.remove();
}
//editProducts.html
function deleteProdRest(elem){
var index = $(elem).parent().parent().parent().index();
$("#edit tr:eq("+(index+1)+")").remove();
}
function addProdRest(){
var nomProd=$('#nombreItem').val();
var precio=$('#precioItem').val();
var descripcion=$('#descripcionItem').val();
var row=$('<tr></tr>');
$('table#edit').append(row);
row.html('<td><div><button type="button" class="btn btn-danger btn-number btn-sm" data-type="minus" data-field="quant[2]" onclick="deleteProdRest(this);"><span class="glyphicon glyphicon-remove"></span></button> '
+'<button type="button" class="btn btn-warning btn-number btn-sm hidden" data-type="plus" data-field="quant[2]" onclick="editProdRest(this);"><span class="glyphicon glyphicon-pencil"></span> </button></div></td>'
+'<td><span class="product"><strong>'+nomProd+'</strong></span>'
+'<input name="nomProd" type="hidden" value="'+nomProd+'"/></td>'
+'<td><span class="product">'+precio+'<span class="glyphicon glyphicon-euro"></span></span>'
+'<input name="price" type="hidden" value="'+precio+'"/></td>'
+'<td><span class="product">'+ descripcion+'</span>'
+'<input name="description" type="hidden" value="'+descripcion+'"/></td>');
$('#nombreItem').val('');
$('#precioItem').val('');
$('#descripcionItem').val('');
}
function editProdRest(elem){
var index = $(elem).parent().parent().parent().index();
}
//restaurant
function getTenRestaurants(){
$("#spinner").show();
$("#btnLoad").hide();
$.ajax({
url:"/restaurant/?page="+page+"&size=10",
success:addTenRestaurants
});
}
function addTenRestaurants(result){
var content = result["content"];
for(var i=0;i<content.length;i++){
$("#restaurantList").append('<li class="list-group-item itemListaRest"><a href="/products/'+content[i].id+'">'
+'<img src="data:image/jpg;base64,'+content[i].image+'" width="150 px" height="150 px"></a>'
+'<h5 class="nombre-rest"><a href="/products/'+content[i].id+'">'+ content[i].name +'</a></h5>'
+'<p class="direccion">'+ content[i].address +' <br>'+ content[i].phone +', ' + content[i].email
+'</p></li>');
}
$("#spinner").hide();
page++;
if(!result["last"]){
$("#btnLoad").show();
}
}
//Request
function examineProducts(id){
$("input[name='selectedRequest']").val(id);
$("form#products").submit();
}
|
'use strict';
angular.module('copayApp.controllers').controller('preferencesUnitController',
function($rootScope, $scope, configService, go) {
var config = configService.getSync();
this.unitName = config.wallet.settings.unitName;
this.unitOpts = [
// TODO : add Satoshis to bitcore-wallet-client formatAmount()
// {
// name: 'Satoshis (100,000,000 satoshis = 1BTC)',
// shortName: 'SAT',
// value: 1,
// decimals: 0,
// code: 'sat',
// },
// {
// name: 'bits (1,000,000 bits = 1BTC)',
// shortName: 'bits',
// value: 100,
// decimals: 2,
// code: 'bit',
// }
// TODO : add mBTC to bitcore-wallet-client formatAmount()
// ,{
// name: 'mBTC (1,000 mBTC = 1BTC)',
// shortName: 'mBTC',
// value: 100000,
// decimals: 5,
// code: 'mbtc',
// }
{
name: 'CREDIT',
shortName: 'CREDIT',
value: 100000000,
decimals: 6,
code: 'CREDIT',
}
];
this.save = function(newUnit) {
var opts = {
wallet: {
settings: {
unitName: newUnit.shortName,
unitToSatoshi: newUnit.value,
unitDecimals: newUnit.decimals,
unitCode: newUnit.code,
}
}
};
this.unitName = newUnit.shortName;
configService.set(opts, function(err) {
if (err) console.log(err);
$scope.$emit('Local/UnitSettingUpdated');
});
};
});
|
// LinkJS
// ======
// pfraze 2012
function noop() {}
var Link = {};
|
/**
* Created by invader on 06.07.16.
*/
import React from 'react'
import s from './benefits.pcss'
import {Grid, Row, Col} from 'react-flexgrid'
import FaDesktop from 'react-icons/lib/fa/desktop'
import FaPaperPlane from 'react-icons/lib/fa/paper-plane'
import FaAnchor from 'react-icons/lib/fa/anchor'
import FaCogs from 'react-icons/lib/fa/cogs'
import FaGG from 'react-icons/lib/fa/gg'
import FaCode from 'react-icons/lib/fa/code'
export default class Benefits extends React.Component {
render() {
return <div className={s.benefits}>
<Grid>
<Row>
<Col md={8} mdOffset={2}>
<div className={s.head}>
<h2 className={s.title}>Benefits of this App</h2>
<p className={s.subtitle}>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</Col>
<Col md={4} sm={6}>
<div className={s.benefit}>
<div className={s.icon}><i><FaDesktop/></i></div>
<h4 className={s.title}>CROSS PLATFORM SUPPORT</h4>
<p className={s.subtitle}>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</Col>
<Col md={4} sm={6}>
<div className={s.benefit}>
<div className={s.icon}><i><FaPaperPlane/></i></div>
<h4 className={s.title}>CROSS PLATFORM SUPPORT</h4>
<p className={s.subtitle}>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</Col>
<Col md={4} sm={6}>
<div className={s.benefit}>
<div className={s.icon}><i><FaAnchor/></i></div>
<h4 className={s.title}>CROSS PLATFORM SUPPORT</h4>
<p className={s.subtitle}>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</Col>
<Col md={4} sm={6}>
<div className={s.benefit}>
<div className={s.icon}><i><FaCogs/></i></div>
<h4 className={s.title}>CROSS PLATFORM SUPPORT</h4>
<p className={s.subtitle}>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</Col>
<Col md={4} sm={6}>
<div className={s.benefit}>
<div className={s.icon}><i><FaGG/></i></div>
<h4 className={s.title}>CROSS PLATFORM SUPPORT</h4>
<p className={s.subtitle}>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</Col>
<Col md={4} sm={6}>
<div className={s.benefit}>
<div className={s.icon}><i><FaCode/></i></div>
<h4 className={s.title}>CROSS PLATFORM SUPPORT</h4>
<p className={s.subtitle}>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</Col>
</Row>
</Grid>
</div>
}
}
|
/*
HTML Import plugin
Adapted from systemjs/plugin-css
https://github.com/systemjs/plugin-css
*/
if (typeof window !== 'undefined') {
System.import('webcomponentsjs/webcomponents-lite.min');
exports.build = false;
exports.fetch = function(load) {
return importHref(load);
};
exports.instantiate = function(load) {
return load.metadata.link.import;
};
} else {
exports.fetch = function(load) {
load.metadata.build = false;
load.metadata.format = 'defined';
return '';
};
exports.instantiate = function() {};
exports.bundle = function(loads, opts) {
return '';
};
}
var waitSeconds = 100;
var head = (typeof document !== 'undefined') ? document.getElementsByTagName('head')[0] : null;
function errCallback(err) {
setTimeout(function() { throw err; });
}
// from https://github.com/ModuleLoader/es6-module-loader/issues/95#issuecomment-98705035
function processScript(script) {
var source = script.innerHTML.substr(1);
return System.module(source).catch(errCallback);
}
function processDocument(e) {
var Q = [];
// process modules in this document
var scripts = e.querySelectorAll('script[type="module"]');
for (var i = 0; i < scripts.length; i++) {
Q.push(processScript(scripts[i]));
}
// process imports (not yet working as expected)
var links = e.querySelectorAll('link[rel="import"]');
for (var j = 0; j < links.length; j++) {
Q.push(processDocument(links[j].import));
}
return Promise.all(Q);
}
function importHref(load) {
return new Promise(function(resolve, reject) {
var timeout = setTimeout(function() {
reject('Unable to load HTML');
}, waitSeconds * 1000);
var _callback = function(error) {
clearTimeout(timeout);
link.onload = link.onerror = function() {};
setTimeout(function() {
if (error)
reject(error);
else
resolve('');
}, 7);
};
var link = load.metadata.link = document.createElement('link');
link.rel = 'import';
link.href = load.address;
link.onload = function() {
processDocument(link.import).then(function() {
_callback();
});
};
link.onerror = function(event) {
_callback(event.error);
};
head.appendChild(link);
});
}
|
global.ArrayUtility = (function() {
"use strict";
function remove(array, element) {
let index = array.indexOf(element);
(index >= 0) ? array.splice(index, 1) : array;
}
function addAll(target, array) {
each(array, function(item) { target.push(item); });
}
return {
remove: remove,
addAll: addAll,
};
})();
|
var formidable = require('formidable'),
http = require('http'),
sys = require('sys');
http.createServer(function(req, res) {
if(req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(error, fields, files) {
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('received upload:\n\n');
});
return;
}
// show file upload form
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<form action="/upload" enctype="multiplart/form-data" ' +
'method="post' +
'<input type="text" name="title"><br>' +
'<input type="file" name="upload" multiple="multiple"><br>' +
'<input type="submit" value="Upload"' +
'</form>'
);
}).listen(8888);
|
Ext.define('EmergencePullTool.view.Main', {
extend: 'Ext.container.Container',
xtype: 'app-mainview',
requires: [
'Ext.layout.container.Border',
'EmergencePullTool.view.ChangesGrid',
'EmergencePullTool.view.DiffPanel'
],
layout: {
type: 'border'
},
items: [{
xtype: 'app-changesgrid',
region: 'center'
}, {
xtype: 'app-diffpanel',
title: 'Select change to view differences',
region: 'south',
height: '40%',
collapsible: true,
split: true,
html: 'diff goes here'
}]
});
|
(function(MainService) {
MainService.module
.factory('RegistrationService', function($http) {
return {
register: function(registrationId) {
$http({
headers: {
'Content-Type': 'application/json'
},
url: MainService.httpUrl + 'register',
method: "POST",
data: {
id: registrationId
}
});
}
}
});
})(MainService);
|
'use strict';
import parser from '../../index';
import tape from 'tape';
import util from 'util';
export let parse = (input, transform) => {
return parser(transform).process(input).result;
};
export let test = (spec, input, callback) => {
var tree;
let result = parse(input, (selectors) => {tree = selectors});
if (callback) {
tape(`${spec} (tree)`, (t) => {
let debug = util.inspect(tree, false, null);
callback.call(this, t, tree, debug);
});
}
tape(`${spec} (toString)`, (t) => {
t.plan(1);
t.equal(result, input);
});
};
export let throws = (spec, input) => {
tape(`${spec} (throws)`, (t) => {
t.plan(1);
t.throws(() => {
return parser().process(input).result;
});
});
};
|
(function(globals){
"use strict";
globals._ = globals._ || {};
var __ = globals._;
var display = function() {
var found = __.dom.display("404-id");
if (!!found) {
__.footer.displayChildFooter();
}
};
var hide = function() {
__.dom.hide("404-id");
};
var initialized = false;
var initialize = function() {
if (!!initialized) {
return ;
}
__.dom.setHrefOfScreen('404-back-id', 'home');
initialized = true;
};
__.screens = __.screens || [];
__.screens.push({
id: 'pageNotFound',
routeUrl: ['404'],
initialize: initialize,
display: display,
hide: hide
});
} (this));
|
angular.module('feedback', [])
.directive('feedbackcount', function(FeedbackService) {
return {
restrict: 'A'
, link: function(scope, element, attrs) {
FeedbackService.get_feedback_count();
var feedback = FeedbackService.feedback;
var type = $(element).attr("show");
if(feedback) {
if(type == 'msg') {
if(feedback.msg) {
$(element).html("<sup class='count'>" + feedback.msg + "</sup>");
}
}
if(type == 'msg_ap') {
if(feedback.msg_ap) {
$(element).html("<sup class='count'>" + feedback.msg_ap + "</sup>");
}
}
if(type == 'msg_topbar') {
if(feedback.msg) {
var link = "<a href='/inbox/all' id='click-topbar'>You have <sup class='count-topbar'>" + feedback.msg + "</sup> new feedback!</a>"
$(element).html(link);
$("#click-topbar").bind("click", function(e) {
FeedbackService.set_inbox_as_read("msg");
e.preventDefault();
})
}
}
} else {
$(element).html("");
}
}
}
})
.directive('inboxclick', function(FeedbackService) {
return {
restrict: 'A'
, link: function(scope, element, attrs) {
$(element).click(function(e) {
var type = $(this).attr('show');
FeedbackService.set_inbox_as_read(type);
e.preventDefault();
});
}
}
})
|
/**
* p5.js example of HackforPlay
* (c) teramotodaiki 2016
* MIT License
*/
// See ---- http://p5js.org
var p5 = require('https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.3/p5.min.js');
new p5();
pixelDensity(1);
Hack.view = canvas;
resizeCanvas(720, 400);
module.exports = function (tileSize) {
w = tileSize;
// Calculate columns and rows
columns = floor(width/w);
rows = floor(height/w);
// Wacky way to make a 2D array is JS
board = new Array(columns);
for (var i = 0; i < columns; i++) {
board[i] = new Array(rows);
}
// Going to use multiple 2D arrays and swap them
next = new Array(columns);
for (i = 0; i < columns; i++) {
next[i] = new Array(rows);
}
window.draw = draw;
window.mousePressed = mousePressed;
init();
};
/**
* Game of Life
* https://p5js.org/examples/examples/Simulate_Game_of_Life.php
* p5.js was created by Lauren McCarthy and is developed by a community of collaborators,
* with support from the Processing Foundation and NYU ITP. © Info.
*/
var w;
var columns;
var rows;
var board;
var next;
w = 20;
// Calculate columns and rows
columns = floor(width/w);
rows = floor(height/w);
// Wacky way to make a 2D array is JS
board = new Array(columns);
for (var i = 0; i < columns; i++) {
board[i] = new Array(rows);
}
// Going to use multiple 2D arrays and swap them
next = new Array(columns);
for (i = 0; i < columns; i++) {
next[i] = new Array(rows);
}
init();
function draw() {
background(255);
generate();
for ( var i = 0; i < columns;i++) {
for ( var j = 0; j < rows;j++) {
if ((board[i][j] == 1)) fill(0);
else fill(255);
stroke(0);
rect(i*w, j*w, w-1, w-1);
}
}
}
// reset board when mouse is pressed
function mousePressed() {
init();
}
// Fill board randomly
function init() {
for (var i = 0; i < columns; i++) {
for (var j = 0; j < rows; j++) {
// Lining the edges with 0s
if (i == 0 || j == 0 || i == columns-1 || j == rows-1) board[i][j] = 0;
// Filling the rest randomly
else board[i][j] = floor(random(2));
next[i][j] = 0;
}
}
}
// The process of creating the new generation
function generate() {
// Loop through every spot in our 2D array and check spots neighbors
for (var x = 1; x < columns - 1; x++) {
for (var y = 1; y < rows - 1; y++) {
// Add up all the states in a 3x3 surrounding grid
var neighbors = 0;
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
neighbors += board[x+i][y+j];
}
}
// A little trick to subtract the current cell's state since
// we added it in the above loop
neighbors -= board[x][y];
// Rules of Life
if ((board[x][y] == 1) && (neighbors < 2)) next[x][y] = 0; // Loneliness
else if ((board[x][y] == 1) && (neighbors > 3)) next[x][y] = 0; // Overpopulation
else if ((board[x][y] == 0) && (neighbors == 3)) next[x][y] = 1; // Reproduction
else next[x][y] = board[x][y]; // Stasis
}
}
// Swap!
var temp = board;
board = next;
next = temp;
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M3 3h8v8H3zm0 10h8v8H3zM13 3h8v8h-8zm0 10h8v8h-8z" />
, 'GridViewSharp');
|
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
var babel = require('gulp-babel');
var del = require('del');
var isparta = require('isparta');
// Initialize the babel transpiler so ES2015 files gets compiled
// when they're loaded
require('babel-core/register');
gulp.task('static', function () {
return gulp.src(['**/*.js', '!template/**/*.js', '!test/output/**/*.js', '!test/functional/expected/**/*.js'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('nsp', function (cb) {
nsp({package: path.resolve('package.json')}, cb);
});
gulp.task('pre-test', function () {
return gulp.src('lib/**/*.js')
.pipe(excludeGitignore())
.pipe(istanbul({
includeUntested: true,
instrumenter: isparta.Instrumenter
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function (cb) {
var mochaErr;
gulp.src(['test/*functional/*.js', 'test/*functional/directive/*.js'])
.pipe(plumber())
.pipe(mocha({reporter: 'spec'}))
.on('error', function (err) {
console.log(err);
mochaErr = err;
})
.pipe(istanbul.writeReports())
.on('end', function () {
cb(mochaErr);
});
});
gulp.task('watch', function () {
gulp.watch(['lib/**/*.js', 'test/**'], ['babel']);
});
gulp.task('coveralls', ['test'], function () {
if (!process.env.CI) {
return;
}
return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
.pipe(coveralls());
});
gulp.task('babel', function () {
return gulp.src('lib/**/*.js')
.pipe(babel())
.pipe(gulp.dest('dist'));
});
gulp.task('clean', function () {
return del('dist');
});
gulp.task('prepublish', ['nsp', 'babel']);
gulp.task('default', ['test', 'static']);
|
/* globals describe, it */
const assert = require('assert');
const App = require('../src/app');
describe('App', function () {
it('exists', function () {
assert.equal(typeof App, 'function');
});
});
|
window.onload = function fixActiveX ()
{
if(navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf('Opera') == -1)
{
var changeElements = new Array(3);
changeElements[0] = "applet";
changeElements[1] = "embed";
changeElements[2] = "object";
//mooooooo!
offScreenBuffer = document.createElement("div");
for (i = 0; i < changeElements.length; i++)
{
thisTypeElements = document.getElementsByTagName(changeElements[i]);
elementsLength = thisTypeElements.length;
for (j = 0; j < elementsLength; j++ )
{
totalString = "";
eatMe(thisTypeElements[j]);
newContainer = document.createElement("div");
oldElement = thisTypeElements[j];
newContainer.innerHTML = totalString;
oldElement.parentNode.insertBefore(newContainer,oldElement);
offScreenBuffer.appendChild(oldElement);
}
}
clearBuffer = window.setInterval("biteMe()", 500);
}
}
function biteMe()
{
while(offScreenBuffer.hasChildNodes()) { offScreenBuffer.removeChild(offScreenBuffer.firstChild); }
window.clearInterval(clearBuffer);
}
function eatMe(thisElement)
{
if(thisElement.childNodes.length>0)
{
totalString = "<"+thisElement.nodeName;
parentAttributesLength = thisElement.attributes.length;
for (k=0; k<parentAttributesLength; k++)
{
if(thisElement.attributes[k].nodeValue != null && thisElement.attributes[k].nodeValue != "")
totalString += " "+ thisElement.attributes[k].nodeName +" = "+ thisElement.attributes[k].nodeValue;
}
totalString += ">";
parentLength = thisElement.childNodes.length;
for(k=0; k<parentLength; k++)
{
eatMe(thisElement.childNodes[k]);
}
totalString += "</"+thisElement.nodeName+">";
}
else processElement(thisElement);
}
function processElement(thisElement)
{
subElementString = "<"+thisElement.nodeName;
attributesLength = thisElement.attributes.length;
for (l=0; l<attributesLength; l++)
{
if(thisElement.attributes[l].nodeValue != null && thisElement.attributes[l].nodeValue != "")
subElementString += " "+ thisElement.attributes[l].nodeName +" = "+ thisElement.attributes[l].nodeValue;
}
subElementString += "></"+thisElement.nodeName+">";
totalString += subElementString;
}
|
/**
*
* @author : Mei XinLin
* @version : 1.0
*/
'use strict';
import gulp from 'gulp';
import runSequence from 'run-sequence';
import gutilsModule from 'gulp-load-utils';
const config = require(process.cwd() + '/config');
const gutils = gutilsModule(['colors', 'env', 'log']);
gulp.task('default', ()=> {
/*
* 用于获取输入的环境信息,并声明出来。(默认环境为development)
* Run `gulp --production`
*/
var type = gutils.env.production ? 'production' : 'development';
if (type == 'development') {
runSequence('clean', ['build:style', 'build:html', 'assets', 'lib', 'build:js'], 'dist', 'complete');
} else if (type == 'production') {
runSequence(['clean', 'unitTest'], ['build:js--production', 'build:style--production', 'min:img', 'move:nls', 'move:lib'], 'build:html--production', 'dist', 'complete');
} else {
gutils.log(gutils.colors.green('////////////////////////////////////'));
gutils.log(gutils.colors.green('/// ///'));
gutils.log(gutils.colors.green('/// unknown development type ///'));
gutils.log(gutils.colors.green('/// ///'));
gutils.log(gutils.colors.green('////////////////////////////////////'));
}
});
|
var ws = require('websocket-stream')
var stream = ws('ws://localhost:8099')
stream.end('hello\n')
|
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { loadAbout } from 'redux/about/actions';
import { getAbout } from 'redux/about/selectors';
import fetchData from 'lib/fetchData';
/* eslint-disable react/prefer-stateless-function */
@fetchData((state, dispatch) => dispatch(loadAbout()))
@connect(state => ({ about: getAbout(state) }))
export default class About extends React.Component {
static propTypes = {
about: PropTypes.any.isRequired,
};
render() {
return (
<div className="about" dangerouslySetInnerHTML={{ __html: this.props.about }} />
);
}
}
|
const toolingPresetReact = require('../')
test('main', () => {
expect(typeof toolingPresetReact).toBe('function')
})
|
/*global describe, before, it */
'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
describe('yui-library generator', function () {
var OUT_DIR = path.join(__dirname, 'output');
var APP_DIR = path.join(__dirname, '../app');
var MOD_DIR = path.join(__dirname, '../module');
describe('project', function () {
describe('defaults', function () {
before(function (done) {
yeoman.test
.run(APP_DIR)
.inDir(OUT_DIR)
.on('end', done);
});
it('creates expected files', function () {
yeoman.assert.file([
'BUILD.md',
'README.md',
'Gruntfile.js',
'bower.json',
'package.json',
'.editorconfig',
'.gitignore',
'.jshintrc',
'.yeti.json'
]);
});
it('properly templatizes Gruntfile.js', function () {
yeoman.assert.noFileContent('Gruntfile.js', (/<%%=/));
});
it('matches expected Gruntfile.js output', function () {
var defaultGruntfile = fs.readFileSync(path.join(__dirname, 'fixtures/project/gruntfile-default.js'));
yeoman.assert.fileContent('Gruntfile.js', new RegExp(escapeRegExp(defaultGruntfile), 'm'));
});
});
});
describe('css module', function () {
before(function (done) {
yeoman.test
.run(MOD_DIR)
.inDir(OUT_DIR)
.withPrompts({
moduleName: 'foo',
moduleTitle: 'Foo',
moduleType: 'css'
})
.on('end', done);
});
it('creates expected files', function () {
yeoman.assert.file([
'build.json',
'docs/component.json',
'docs/index.mustache',
'HISTORY.md',
'css/foo.css',
'meta/foo.json',
'README.md'
]);
});
});
describe('js module', function () {
before(function (done) {
yeoman.test
.run(MOD_DIR)
.inDir(OUT_DIR)
.withPrompts({
moduleName: 'bar',
moduleTitle: 'Bar',
moduleType: 'js'
})
.on('end', done);
});
it('creates expected files', function () {
yeoman.assert.file([
'build.json',
'docs/component.json',
'docs/index.mustache',
'HISTORY.md',
'js/bar.js',
'meta/bar.json',
'README.md',
'tests/unit/assets/bar-test.js',
'tests/unit/bar.html'
]);
});
});
describe('widget module', function () {
before(function (done) {
yeoman.test
.run(MOD_DIR)
.inDir(OUT_DIR)
.withPrompts({
moduleName: 'qux',
moduleTitle: 'Qux',
moduleType: 'widget'
})
.on('end', done);
});
it('creates expected files', function () {
yeoman.assert.file([
'assets/qux/qux-core.css',
'assets/qux/skins/night/qux-skin.css',
'assets/qux/skins/sam/qux-skin.css',
'build.json',
'docs/component.json',
'docs/index.mustache',
'HISTORY.md',
'js/qux.js',
'meta/qux.json',
'README.md',
'tests/unit/assets/qux-test.js',
'tests/unit/qux.html'
]);
});
});
describe('imported module', function () {
before(function (done) {
yeoman.test
.run(MOD_DIR)
.inDir(OUT_DIR)
.withOptions({
'file': path.join(__dirname, 'fixtures/module/existing.js')
})
.withPrompts({
moduleName: 'existing',
moduleTitle: 'Existing',
moduleType: 'js'
})
.on('end', done);
});
it('creates expected files', function () {
yeoman.assert.file([
'build.json',
'docs/component.json',
'docs/index.mustache',
'HISTORY.md',
'js/existing.js',
'meta/existing.json',
'README.md',
'tests/unit/assets/existing-test.js',
'tests/unit/existing.html'
]);
});
it('matches expected JS output', function () {
var existingCode = fs.readFileSync(path.join(__dirname, 'fixtures/module/existing-code.js'));
yeoman.assert.fileContent('js/existing.js', new RegExp(escapeRegExp(existingCode), 'm'));
});
it('matches expected JSON output', function () {
var existingMeta = fs.readFileSync(path.join(__dirname, 'fixtures/module/existing-meta.json'));
yeoman.assert.fileContent('meta/existing.json', new RegExp(escapeRegExp(existingMeta), 'm'));
});
});
});
// escape a string for use in RegExp constructor
// http://stackoverflow.com/a/3561711/5707
function escapeRegExp(s) {
return String(s).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
|
var searchData=
[
['rt_5fcontroltype',['RT_ControlType',['../thermistor__lab_2src_2main_8c.html#union_r_t___control_type',1,'']]],
['rt_5fcontroltype_2ebits',['RT_ControlType.Bits',['../thermistor__lab_2src_2main_8c.html#struct_r_t___control_type_8_bits',1,'']]]
];
|
var R = require('../source/index.js');
var eq = require('./shared/eq.js');
describe('dec', function() {
it('decrements its argument', function() {
eq(R.dec(-1), -2);
eq(R.dec(0), -1);
eq(R.dec(1), 0);
eq(R.dec(12.34), 11.34);
eq(R.dec(-Infinity), -Infinity);
eq(R.dec(Infinity), Infinity);
});
});
|
/*jshint unused:false */
function NodeController( $scope ){
this.initialize= function () {
$scope.calculateImagePosition();
};
$scope.calculateImagePosition = function(){
var depth = $scope.node.depth;
var width = $scope.treeWidth[depth];
if( width === undefined ) { width = 1; }
else { width++; }
//console.log( "depth:" + depth + " width:" + width );
$scope.cx = width * 40;
$scope.cy = 30 + depth * 40;
$scope.r = 14;
$scope.x = $scope.cx - 15;
$scope.y = $scope.cy + 2;
$scope.lineColor = '#FF0000';
//$scope.test = 1;
console.log( $scope.cx );
$scope.treeWidth[depth] = width;
};
this.initialize();
}
|
import React from 'react'
import { Table } from 'shengnian-ui-react'
const TableExampleDisabled = () => (
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Status</Table.HeaderCell>
<Table.HeaderCell>Notes</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row disabled>
<Table.Cell>Jamie</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>Requires call</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>John</Table.Cell>
<Table.Cell>Selected</Table.Cell>
<Table.Cell>None</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>Requires call</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell disabled>Jill</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>None</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
)
export default TableExampleDisabled
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Evmit = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*!
* Dependencies
*/
var slice = require('sliced')
/*!
* Exports
*/
module.exports = Evmit
/**
* Initialize `Evmit`.
*
* @constructor
*/
function Evmit() {}
/**
* Get an event or all events.
*
* @param {String} name
* @return {Array|Object}
*/
Evmit.prototype.listeners = function(name) {
var events = this.events || (this.events = {})
return name ? events[name] : events
}
/**
* Subscribe to an event.
*
* @param {String} name
* @param {Function} fn
* @return {this}
*/
Evmit.prototype.on = function(name, fn) {
var events = this.listeners()
if (!events[name]) events[name] = []
events[name].push(fn)
return this
}
/**
* Unsubscribe from an event or all events.
*
* @param {String} name
* @param {Function} fn
* @return {this}
*/
Evmit.prototype.off = function(name, fn) {
var events = this.listeners()
if (!name) delete this.events
if (events[name] && fn) {
events[name].splice(events[name].indexOf(fn), 1)
if (events[name].length === 0) delete events[name]
return this
}
if (events[name]) delete events[name]
return this
}
/**
* Subscribe to an event only once.
*
* @param {String} name
* @param {Function} fn
* @return {this}
*/
Evmit.prototype.once = function(name, fn) {
this.on(name, function done() {
this.off(name, done)
fn.apply(arguments)
}.bind(this))
return this
}
/**
* Trigger an event.
*
* @param {String} name
* @return {this}
*/
Evmit.prototype.emit = function(name) {
var events = this.listeners()
var params = slice(arguments, 1)
if (events[name]) {
events[name].forEach(function(fn) {
fn.apply(fn, params)
})
}
return this
}
},{"sliced":2}],2:[function(require,module,exports){
/**
* An Array.prototype.slice.call(arguments) alternative
*
* @param {Object} args something with a length
* @param {Number} slice
* @param {Number} sliceEnd
* @api public
*/
module.exports = function (args, slice, sliceEnd) {
var ret = [];
var len = args.length;
if (0 === len) return ret;
var start = slice < 0
? Math.max(0, slice + len)
: slice || 0;
if (sliceEnd !== undefined) {
len = sliceEnd < 0
? sliceEnd + len
: sliceEnd
}
while (len-- > start) {
ret[len - start] = args[len];
}
return ret;
}
},{}]},{},[1])(1)
});
|
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const routes = require('./routes/index');
const othello = require('./routes/othello');
const bluebird = require('bluebird')
const app = express();
global.redis = require("redis");
let redis_config = process.env.rediscloud_5e8ad;
if (redis_config) {
redis_config = JSON.parse(redis_config);
global.client = global.redis.createClient(redis_config.port,
redis_config.hostname, {auth_pass: redis_config.password});
} else {
bluebird.promisifyAll(global.redis.RedisClient.prototype);
bluebird.promisifyAll(global.redis.Multi.prototype);
global.client = global.redis.createClient();
}
global.client.on("error", function (err) {
console.log("Error " + err);
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/othello', othello);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
import React, { Component } from 'react';
import InfoSection from '../components/InfoSection';
import InfoSectionToggle from '../components/InfoSectionToggle';
class SearchContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
error: '',
showContent: true,
content: `The field below accepts search criteria for those on Odecee bench. Try searching by technologies like: 'node', or 'javascript' and you will see a list of candidates with those skill sets.`
};
}
onPressError() {
this.setState({
error: ''
});
}
onPressInfo() {
this.setState({
showContent: !this.state.showContent
});
}
renderError() {
if(this.state.error) {
return (
<li>
<div className="error">
<span className="message">{this.state.error}</span>
<span className="error-icon" onClick={this.onPressError.bind(this)}>
<i className="fa fa-times-circle"></i>
</span>
</div>
</li>
)
}
}
renderInfoSection() {
return (
<InfoSection
revealContent={this.state.showContent}
content={this.state.content}
title={'Add Skill'}
/>
);
}
render() {
return (
<div>
{this.renderInfoSection()}
<section>
<InfoSectionToggle onPressInfo={this.onPressInfo.bind(this)} />
<ul className="input-list style-4 clearfix">
{this.renderError()}
<li>
<label className="search" htmlFor="search">Search: </label>
<input
type="text"
style={{width: '100%'}}
placeholder="Search"
ref="email"
id="search"
/>
</li>
</ul>
</section>
</div>
)
}
}
export default SearchContainer;
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Ticket = new Schema({
date: Date,
seat: Number,
customer:Object
});
module.exports = mongoose.model('Ticket', Ticket);
|
define([
'thruster/graphics/color',
'thruster/graphics/surface'
], function(
Color,
Surface
){
/**
* @namespace
* @memberof thruster
*/
var graphics = {
Color: Color,
Surface: Surface
};
return graphics;
});
|
/*
* Globalize Culture mn
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function (window, undefined) {
var Globalize;
if (typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined") {
// Assume CommonJS
Globalize = require("globalize");
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo("mn", "default", {
name: "mn",
englishName: "Mongolian",
nativeName: "Монгол хэл",
language: "mn",
numberFormat: {
",": " ",
".": ",",
percent: {
",": " ",
".": ","
},
currency: {
pattern: ["-n$", "n$"],
",": " ",
".": ",",
symbol: "₮"
}
},
calendars: {
standard: {
"/": ".",
firstDay: 1,
days: {
names: ["Ням", "Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба"],
namesAbbr: ["Ня", "Да", "Мя", "Лх", "Пү", "Ба", "Бя"],
namesShort: ["Ня", "Да", "Мя", "Лх", "Пү", "Ба", "Бя"]
},
months: {
names: ["1 дүгээр сар", "2 дугаар сар", "3 дугаар сар", "4 дүгээр сар", "5 дугаар сар", "6 дугаар сар", "7 дугаар сар", "8 дугаар сар", "9 дүгээр сар", "10 дугаар сар", "11 дүгээр сар", "12 дугаар сар", ""],
namesAbbr: ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", ""]
},
monthsGenitive: {
names: ["1 дүгээр сарын", "2 дугаар сарын", "3 дугаар сарын", "4 дүгээр сарын", "5 дугаар сарын", "6 дугаар сарын", "7 дугаар сарын", "8 дугаар сарын", "9 дүгээр сарын", "10 дугаар сарын", "11 дүгээр сарын", "12 дугаар сарын", ""],
namesAbbr: ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", ""]
},
AM: null,
PM: null,
patterns: {
d: "yy.MM.dd",
D: "yyyy 'оны' MMMM d",
t: "H:mm",
T: "H:mm:ss",
f: "yyyy 'оны' MMMM d H:mm",
F: "yyyy 'оны' MMMM d H:mm:ss",
M: "d MMMM",
Y: "yyyy 'он' MMMM"
}
}
}
});
}(this));
|
var db = require('../db.js')
var Promise = require('bluebird')
var General = require('../lib/general.js');
var Contacts = module.exports = General.access('contacts');
module.exports.retrieveByName = function(string){
if (string.length < 4){
return db.select('contacts.name','contacts.phone_number','companies.name AS company_name').from('contacts').where('contacts.name', 'ILIKE', '%'+string+'%').limit('3').join('companies', function() {
this.on('companies.id', '=', 'contacts.company_id')})
} else {
return db.select('contacts.*','companies.name AS company_name').from('contacts').whereRaw('? % contacts.name', string).limit('3').join('companies', function() {
this.on('companies.id', '=', 'contacts.company_id')})
}
}
|
import Ember from 'ember';
import EditorAPI from 'ghost-admin/mixins/ed-editor-api';
import EditorShortcuts from 'ghost-admin/mixins/ed-editor-shortcuts';
import EditorScroll from 'ghost-admin/mixins/ed-editor-scroll';
import {invokeAction} from 'ember-invoke-action';
const {TextArea, run} = Ember;
export default TextArea.extend(EditorAPI, EditorShortcuts, EditorScroll, {
focus: false,
/**
* Tell the controller about focusIn events, will trigger an autosave on a new document
*/
focusIn() {
this.sendAction('onFocusIn');
},
/**
* Sets the focus of the textarea if needed
*/
setFocus() {
if (this.get('focus')) {
this.$().val(this.$().val()).focus();
}
},
/**
* Sets up properties at render time
*/
didInsertElement() {
this._super(...arguments);
this.setFocus();
invokeAction(this, 'setEditor', this);
run.scheduleOnce('afterRender', this, this.afterRenderEvent);
},
afterRenderEvent() {
if (this.get('focus') && this.get('focusCursorAtEnd')) {
this.setSelection('end');
}
},
actions: {
toggleCopyHTMLModal(generatedHTML) {
invokeAction(this, 'toggleCopyHTMLModal', generatedHTML);
}
}
});
|
import React, {PropTypes} from 'react';
import CourseListRow from './CourseListRow';
const CourseList = ({courses}) => {
return(
<table className="table">
<thead>
<tr>
<th> </th>
<th>Title</th>
<th>Author</th>
<th>Categoty</th>
<th>Length</th>
</tr>
</thead>
<tbody>
{courses.map(course =>
<CourseListRow key={course.id} course={course} />
)}
</tbody>
</table>
);
};
CourseList.propTypes = {
courses: PropTypes.array.isRequired
};
export default CourseList;
|
import { expect } from 'chai';
import * as constants from 'client/constants/contact';
import * as actions from 'client/actions/form';
describe('form actions', () => {
it('tests nameChange action with incorrect name', () => {
const value = 'na';
const name = {
value,
valid: false,
touched: true
};
const expectedAction = {
type: constants.NAME_CHANGE,
name
};
expect(actions.nameChange(value)).to.eql(expectedAction);
});
it('tests nameChange action correct name', () => {
const value = 'name';
const name = {
value,
valid: true,
touched: true
};
const expectedAction = {
type: constants.NAME_CHANGE,
name
};
expect(actions.nameChange(value)).to.eql(expectedAction);
});
it('tests phoneChange action with incorrect phone number', () => {
const value = '123';
const phone = {
value,
valid: false,
touched: true
};
const expectedAction = {
type: constants.PHONE_CHANGE,
phone
};
expect(actions.phoneChange(value)).to.eql(expectedAction);
});
it('tests phoneChange action with correct phone number', () => {
const value = '123456';
const phone = {
value,
valid: true,
touched: true
};
const expectedAction = {
type: constants.PHONE_CHANGE,
phone
};
expect(actions.phoneChange(value)).to.eql(expectedAction);
});
});
|
export default {
UPDATE_MATCH: '@@found/UPDATE_MATCH',
RESOLVE_MATCH: '@@found/RESOLVE_MATCH',
};
|
$(document).ready(function() {
$.localScroll();
});
|
import React from 'react';
import ReactDOM from 'react-dom'
class FilterInfo extends React.Component {
render() {
return (
<div className="filterInfo">
We found <span>{this.props.itemNum}</span> item!
</div>
)
}
}
export default FilterInfo;
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
Text,
TouchableOpacity,
Button
} from 'react-native';
import MenuSide from './App/MenuSide'
import LogArea from './App/LogArea'
import { Pages, ControlsPage, FixesPage, MainPage, AccessibilityPage, WebViewPage } from './App/ContentSide'
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter')
import * as Animatable from 'react-native-animatable'
import GenericModal from "./App/Modals/GenericModal";
const LOG_INIT_MESSAGE = 'Playground v 0.3'
class Playground extends Component {
constructor(props) {
super(props)
this.state = {
displayPage: Pages.MAIN,
log: LOG_INIT_MESSAGE,
isModalOpen: false
}
}
switchContent = (page) => {
if (page === 'CLEAR_LOG') {
this.setState(previousState => ({
log: LOG_INIT_MESSAGE
})
)
return
}
this.setState(previousState => ({
displayPage: page,
log: `${previousState.log}\n${new Date().toISOString()}: Page changed to ${page}`
}))
}
renderContent = () => {
const { displayPage } = this.state
return (
<View style={styles.clientArea}>
{displayPage === Pages.MAIN && <MainPage/>}
{displayPage === Pages.CONTROLS && <ControlsPage logger={this.log} />}
{displayPage === Pages.FIXES && <FixesPage logger={this.log} />}
{displayPage === Pages.ACCESSIBILITY && <AccessibilityPage isFocusable={this.state.isModalOpen === false} logger={this.log} />}
{displayPage === Pages.WEBVIEW && <WebViewPage isFocusable={this.state.isModalOpen === false} logger={this.log} />}
</View>
)
}
log = (message) => {
this.setState(previousState => (
{ log: `${previousState.log}\n${new Date().toISOString()}: ${message}` }
))
}
modalButtonClickHandler = (isOpen) => {
this.setState({isModalOpen: isOpen})
}
componentWillMount() {
RCTDeviceEventEmitter.addListener('logMessageCreated', (evt) => { this.log(`${evt.messageSender}: ${evt.message}`) })
}
render() {
return (
<View isFocusable={this.state.isModalOpen === false} style={styles.container}>
<Animatable.View isFocusable={this.state.isModalOpen === false} style={styles.content} ref='content' animation='fadeInUp' duration={800} easing='ease-in'>
<View isFocusable={this.state.isModalOpen === false} style={styles.content}>
<MenuSide isFocusable={this.state.isModalOpen === false} logger={this.log} menuClick={this.switchContent} />
{this.renderContent()}
</View>
</Animatable.View>
<LogArea content={this.state.log} />
<View style={{backgroundColor: 'gray', alignItems: 'center', justifyContent: 'center'}} isFocusable={this.state.isModalOpen === false}>
<TouchableOpacity onPress={() => this.modalButtonClickHandler(true)}>
<Text>Show Modal</Text>
</TouchableOpacity>
</View>
<GenericModal isOpen={this.state.isModalOpen} close={() => this.modalButtonClickHandler(false)} />
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
},
content: {
flex: 1,
flexGrow: 2,
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'stretch',
minHeight: 200
},
clientArea: {
flexGrow: 2,
}
});
AppRegistry.registerComponent('Playground.Net46', () => Playground);
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('swapcase', 'helper:swapcase', {
integration: true
});
test('It formats the input text with `swapcase` format', function(assert) {
assert.expect(2);
this.set('input', 'this Is some TEXT');
this.render(hbs`{{swapcase input}}`);
assert.equal(this.$().text().trim(), 'THIS iS SOME text');
this.set('input', 'this Was some TEXT');
assert.equal(this.$().text().trim(), 'THIS wAS SOME text');
});
|
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('ngBrxApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
import {
cssWordIsVariable,
optionsHaveIgnored,
report,
ruleMessages,
validateOptions,
} from "../../utils"
export const ruleName = "declaration-block-no-duplicate-properties"
export const messages = ruleMessages(ruleName, {
rejected: p => `Unexpected duplicate property "${p}"`,
})
export default function (on, options) {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, { actual: on }, {
actual: options,
possible: {
ignore: ["consecutive-duplicates"],
},
optional: true,
})
if (!validOptions) { return }
// In order to accommodate nested blocks (postcss-nested),
// we need to run a shallow loop (instead of eachDecl() or eachRule(),
// which loop recursively) and allow each nested block to accumulate
// its own list of properties -- so that a property in a nested rule
// does not conflict with the same property in the parent rule
root.each(node => {
if (node.type === "rule" || node.type === "atrule") {
checkRulesInNode(node)
}
})
function checkRulesInNode(node) {
const decls = []
node.each(child => {
if (child.nodes && child.nodes.length) {
checkRulesInNode(child)
}
if (child.type !== "decl") { return }
const prop = child.prop
if (cssWordIsVariable(prop)) { return }
// Ignore the src property as commonly duplicated in at-fontface
if (prop === "src") { return }
const indexDuplicate = decls.indexOf(prop)
if (indexDuplicate !== -1) {
if (
optionsHaveIgnored(options, "consecutive-duplicates")
&& indexDuplicate === decls.length - 1
) {
return
}
report({
message: messages.rejected(prop),
node: child,
result,
ruleName,
})
}
decls.push(prop)
})
}
}
}
|
import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.scss';
import Header from '../Header';
import Footer from '../Footer';
import Daytime from '../../models/daytime';
class App extends Component {
static propTypes = {
context: PropTypes.shape({
insertCss: PropTypes.func,
onSetTitle: PropTypes.func,
onSetMeta: PropTypes.func,
onPageNotFound: PropTypes.func,
}),
children: PropTypes.element.isRequired,
error: PropTypes.object,
};
static childContextTypes = {
insertCss: PropTypes.func.isRequired,
onSetTitle: PropTypes.func.isRequired,
onSetMeta: PropTypes.func.isRequired,
onPageNotFound: PropTypes.func.isRequired,
};
getChildContext() {
const context = this.props.context;
return {
insertCss: context.insertCss || emptyFunction,
onSetTitle: context.onSetTitle || emptyFunction,
onSetMeta: context.onSetMeta || emptyFunction,
onPageNotFound: context.onPageNotFound || emptyFunction,
};
}
componentWillMount() {
this.removeCss = this.props.context.insertCss(s);
}
componentWillUnmount() {
this.removeCss();
}
render() {
const className = Daytime.isNight() ? s.containerNight : s.containerDay;
return !this.props.error ? (
<div className={className}>
<div className={s.container}>
<Header />
<main className={s.pageMain}>
{this.props.children}
</main>
<Footer />
</div>
</div>
) : this.props.children;
}
}
export default App;
|
var $table = $('.table');
var $fixedColumn = $table.clone().insertBefore($table).addClass('fixed-column');
$fixedColumn.find('th:not(:first-child),td:not(:first-child)').remove();
$fixedColumn.find('tr').each(function (i, elem) {
$(this).height($table.find('tr:eq(' + i + ')').height());
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DecoratorParamsController = void 0;
const tslib_1 = require("tslib");
const route_1 = require("@appolo/route");
const manager_1 = require("../manager/manager");
const userMiddleware_1 = require("../middleware/userMiddleware");
const inject_1 = require("@appolo/inject");
let DecoratorParamsController = class DecoratorParamsController extends route_1.StaticController {
constructor(manager) {
super();
this.name = manager.name;
}
//@inject() manager: any;
test(req, res, route, aaa, env) {
this.sendOk(res, { model: env.test, name: this.name, user: req.user });
}
};
tslib_1.__decorate([
route_1.get("/test/decorator/param/:name/:name2"),
route_1.abstract({ middleware: [userMiddleware_1.UserMiddleware] }),
tslib_1.__param(4, inject_1.inject()),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [Object, Object, Object, Object, Object]),
tslib_1.__metadata("design:returntype", void 0)
], DecoratorParamsController.prototype, "test", null);
DecoratorParamsController = tslib_1.__decorate([
route_1.controller(),
inject_1.singleton(),
inject_1.lazy(),
tslib_1.__param(0, inject_1.inject()),
tslib_1.__metadata("design:paramtypes", [manager_1.Manager])
], DecoratorParamsController);
exports.DecoratorParamsController = DecoratorParamsController;
//# sourceMappingURL=decoratorParamsController.js.map
|
beforeEach(() => {
const gmfModule = angular.module('gmf');
gmfModule.constant('angularLocaleScript', 'http://fake');
module('gmf', ($provide) => {
$provide.value('gmfTreeUrl', 'http://fake/gmf/themes');
$provide.value('gmfShortenerCreateUrl', 'http://fake/gmf/short/create');
$provide.value('authenticationBaseUrl', 'https://fake/gmf/authentication');
$provide.value('gmfRasterUrl', 'https://fake/gmf/raster');
$provide.value('gmfContextualdatacontentTemplateUrl', 'contextualdata.html');
$provide.value('defaultTheme', 'Demo');
});
});
|
/**
* This is the startup script for a basic Postvox interchange server.
*
* An interchange server is a data-hosting server for one or more Postvox
* streams, which are identified by a URL like "vox://<source>". It's like a
* network-accessible database of messages and user metadata.
*
* Start it like so:
*
* $ npm run vox-server --port 9001
*
* Set the DEBUG environment variable to see debug logging:
*
* $ DEBUG='vox:*' npm run vox-server --port 9001
*/
var argv = require('./argv');
var hubclient = require('vox-common/hubclient');
var interchangedb = require('./interchangedb');
var interchangeserver = require('./interchangeserver');
var mkdirp = require('mkdirp');
var path = require('path');
if (!argv.dbDir) {
console.error('Must specify --dbDir');
process.exit(1);
}
mkdirp.sync(argv.dbDir, 0700);
var dbConfig = {
dbFile: path.join(argv.dbDir, 'metadata.db'),
streamDbDir: path.join(argv.dbDir, 'messages.leveldb')
};
process.on('unhandledRejection', function(err, promise) {
console.error('Unhandled error', err, err.stack);
process.exit(1);
});
return interchangedb.openDb(dbConfig)
.then(function(db) {
var hubClient = hubclient.HubClient(argv.hubUrl, db);
return interchangeserver.CreateInterchangeServer(
argv.port,
argv.metricsPort,
hubClient,
db);
})
.catch(function(err) {
console.error('FATAL ERROR', err, err ? err.stack : '');
process.exit(1);
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:e932813a72f5b25e41020dcd05cda2ffc04743196a9dc3d16eb5d2ff4f1900bf
size 1536
|
version https://git-lfs.github.com/spec/v1
oid sha256:032ce2000da04ad5dc4c1e5d13ede6873568a099dbf775d39afe21aecf82dab6
size 101984
|
import React, { Component } from 'react';
import OnClickOutside from 'react-onclickoutside';
import './SimplePopover.scss';
const TOOLTIP_MARGIN = 10;
const getPopoverOnBottomStyle = (position, popoverWidth) => ({
position: 'absolute',
top: `${position.bottom + TOOLTIP_MARGIN}px`,
left: `${(position.left + (position.width / 2)) - (popoverWidth / 2)}px`,
});
const getPopoverOnBottomLeftStyle = (position, popoverWidth) => ({
position: 'absolute',
top: `${position.bottom + TOOLTIP_MARGIN}px`,
left: `${(position.left - popoverWidth) + position.width}px`,
});
const getPopoverOnRightStyle = (position, popoverWidth, popoverHeight) => ({
position: 'absolute',
top: `${position.bottom - (popoverHeight / 2)}px`,
left: `${position.right + TOOLTIP_MARGIN}px`,
});
@OnClickOutside
export default class SimplePopover extends Component {
constructor(props) {
super(props);
this.state = {
el: null,
};
}
handleRef = (e) => {
if (!this.state.el) {
this.setState({ el: e });
}
};
// Will be triggered by OnClickOutside HoC
handleClickOutside() {
this.props.removePopover();
}
render() {
const { pos, className, title, content, appearOn } = this.props;
const popoverWidth = this.state.el ? this.state.el.clientWidth : 0;
const popoverHeight = this.state.el ? this.state.el.clientHeight : 0;
let style;
if (appearOn === 'right') {
style = getPopoverOnRightStyle(pos, popoverWidth, popoverHeight);
} else if (appearOn === 'bottom-left') {
style = getPopoverOnBottomLeftStyle(pos, popoverWidth);
} else if(appearOn === 'bottom') {
style = getPopoverOnBottomStyle(pos, popoverWidth);
}
return (
<div className={className} style={style} ref={this.handleRef}>
<p className={`${className}--title`}>{title}</p>
{content}
</div>
);
}
}
|
/**
* @author Vincent
* @description can also use node-fs fetch..
*/
'use strict';
var _=require('../lib/underscore.js');
function Template(options){
var opts=options||{};
this.tmpl_name=opts.tmplName;
this.tmpl_data=opts.tmplData;
}
Template.prototype.getHtml=function() {
var tmpl_name=this.tmpl_name,tmpl_data=this.tmpl_data;
var tmpl_string=this.tmpl_name;
if ( ! this.tmpl_cache ) {
this.tmpl_cache = {};
}
if ( ! this.tmpl_cache[tmpl_name] ) {
//var tmpl_dir = './templates';
//var tmpl_url = tmpl_dir + '/' + tmpl_name + '.html';
//tmpl_string=require(tmpl_dir);
this.tmpl_cache[tmpl_name] = _.template(tmpl_string);
}
return this.tmpl_cache[tmpl_name](tmpl_data);
}
module.exports=Template;
|
/**
* This script automatically creates a default Admin user when an
* empty database is used for the first time. You can use this
* technique to insert data into any List you have defined.
*
* Alternatively, you can export a custom function for the update:
* module.exports = function(done) { ... }
*/
/*
exports.create = {
User: [
{
'name.first': 'Admin',
'name.last': 'User',
email: 'user@keystonejs.com',
password: 'admin',
isAdmin: true
}
]
};
*/
/*
// This is the long-hand version of the functionality above:
var keystone = require('keystone');
var async = require('async');
var User = keystone.list('User');
var admins = [
{ email: 'user@keystonejs.com', password: 'admin', name: { first: 'Admin', last: 'User' } }
];
function createAdmin (admin, done) {
var newAdmin = new User.model(admin);
newAdmin.isAdmin = true;
newAdmin.save(function (err) {
if (err) {
console.error('Error adding admin ' + admin.email + ' to the database:');
console.error(err);
} else {
console.log('Added admin ' + admin.email + ' to the database.');
}
done(err);
});
}
exports = module.exports = function (done) {
async.forEach(admins, createAdmin, done);
};
*/
|
/*!
* js-file-browser
* Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file.
*
* With components from: Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.test.session.addTest( 'ArrayReader', {
name: 'readRecords',
setUp: function() {
this.reader = new Ext.data.ArrayReader({
idIndex: 1,
fields: [
{name: 'floater', type: 'float'},
{name: 'id'},
{name: 'totalProp', type: 'integer'},
{name: 'bool', type: 'boolean'},
{name: 'msg'}
]
});
this.data1 = [
[ 1.23, 1, 6, true, 'hello' ]
];
this.rec1 = this.reader.readRecords(this.data1);
},
test_tearDown: function() {
delete this.reader;
delete this.data1;
delete this.rec1;
},
test_TotalRecords: function() {
Y.Assert.areSame(this.rec1.totalRecords, 1);
},
test_Records: function() {
Y.Assert.areSame(this.rec1.records[0].data.floater, this.data1[0][0]);
Y.Assert.areSame(this.rec1.records[0].data.id, this.data1[0][1]);
Y.Assert.areSame(this.rec1.records[0].data.totalProp, this.data1[0][2]);
Y.Assert.areSame(this.rec1.records[0].data.bool, this.data1[0][3]);
Y.Assert.areSame(this.rec1.records[0].data.msg, this.data1[0][4]);
}
});
|
var model = require( "../../model.js" );
module.exports = function( host ) {
return {
name: "board",
actions: {
self: {
include: [ "id", "title" ],
method: "get",
url: "/:id",
embed: {
lanes: {
resource: "lane",
render: "self",
actions: [ "self", "cards" ]
}
},
handle: function( envelope ) {
envelope.hyped( model.board1 ).status( 200 ).render();
}
},
cards: {
method: "get",
url: "/:id/card",
render: { resource: "card", action: "self" },
handle: function( envelope ) {
return _.reduce( model.board1.lanes, function( acc, lane ) {
return acc.concat( lane.cards );
}, [] );
}
}
},
versions: {
2: {
self: {
include: [ "id", "title", "description" ]
}
}
}
};
};
|
/*!
* uaDetector
*
* @author Van Zheng (zgbjili2009@126.com)
* @copyright Copyright (c) Van Zheng.
* @license This uaDetector is licensed under the MIT licenses.
* @version Version 0.8.0
*
*/
(function(root) {
var ua = window.navigator.userAgent.toLowerCase(),
matches,
browser = 'unknown',
version = '0',
device = 'unknown',
os = 'unknown',
engine = 'unknown',
uaDetector;
// Browser info
// Opera ua contains `chrome`, `safari` keywords
if (ua.indexOf('opera') > -1 || ua.indexOf('opr') > -1) {
browser = 'opera';
matches = /(opera|opr)\/([\d\.]+)/.exec(ua);
version = matches ? matches[2] : '0';
}
// Chrome ua contains `chrome`, `safari` keywords
else if (ua.indexOf('chrome') > -1) {
browser = 'chrome';
matches = /chrome\/([\d\.]+)/.exec(ua);
version = matches ? matches[1] : '0';
} else if (ua.indexOf('safari') > -1) {
browser = 'safari';
matches = /version\/([\d\.]+)/.exec(ua);
version = matches ? matches[1] : '0';
} else if (ua.indexOf('firefox') > -1) {
browser = 'firefox';
matches = /firefox\/([\d\.]+)/.exec(ua);
version = matches ? matches[1] : '0';
} else if (ua.indexOf('msie') > -1 || ua.indexOf('trident') > -1) {
browser = 'msie';
matches = /(msie|rv:?)\s?([\d\.]+)/.exec(ua);
version = matches ? matches[2] : '0';
}
// platform info
if (ua.indexOf('iphone') > -1 || ua.indexOf('ipad') > -1 || ua.indexOf('ipod') > -1) {
device = 'mobile';
os = 'ios';
} else if (ua.indexOf('android') > -1) {
device = 'mobile';
os = 'android';
} else if (ua.indexOf('windows phone') > -1) {
device = 'mobile';
os = 'windows';
} else if (ua.indexOf('blackberry') > -1) {
device = 'mobile';
os = 'blackberry';
} else if (ua.indexOf('symbian') > -1) {
device = 'mobile';
os = 'symbian';
} else if (ua.indexOf('windows') > -1) {
device = 'desktop';
os = 'windows';
} else if (ua.indexOf('macintosh') > -1) {
device = 'macintosh';
os = 'macintosh';
} else if (ua.indexOf('linux') > -1) {
device = 'desktop';
os = 'linux';
}
// Rendering engine
if (ua.indexOf('webkit') > -1) {
engine = 'webkit';
} else if (ua.indexOf('trident') > -1) {
engine = 'trident';
} else if (ua.indexOf('presto') > -1) {
engine = 'presto';
} else if (ua.indexOf('khtml') > -1) {
engine = 'khtml';
} else if (ua.indexOf('gecko') > -1) {
engine = 'gecko';
} else {
engine = 'unknown';
}
uaDetector = {
browser: browser,
version: version,
device: device,
os: os,
engine: engine
}
root.uaDetector = uaDetector;
})(window);
|
var test = require("tape"), routes = require("../uru/routes"), _ = require("lodash");
test("api should comprise: navigate, router, resolve, reverse", function(t){
"use strict";
var total = 0, keys = {navigate:1, router:1, resolve:1, reverse:1};
_.each(routes, function(value, key){
if(_.isFunction(value)){
total++;
t.ok(key in keys, key + " should be present module");
}
});
t.equal(4, total, "only 4 functions should be present");
t.end();
});
test("simple route", function (t) {
"use strict";
function callback(){}
var router = routes.router("", "name", callback);
t.notOk(routes.resolve("name"), "router should be unavailable before starting");
router.start();
t.ok(routes.resolve("name") === callback, "router should be available after starting");
router.stop();
t.notOk(routes.resolve("name"), "router should be unavailable after stopping");
t.end();
});
test("router.reverse forms url for a name", function(t){
"use strict";
function callback(){}
var router = routes.router("", "name", callback);
t.notOk(routes.reverse("name"), "router should be unavailable before starting");
router.start();
t.ok(routes.reverse("name") === "", "router should be available after starting");
router.stop();
t.notOk(routes.reverse("name"), "router should be unavailable after stopping");
t.end();
});
test("flat routes", function(t){
"use strict";
function callback(){}
var router = routes.router("/some/count:int/tail:*/", "name", callback);
router.start();
t.equal(routes.reverse("name", {0:45, tail:"randomness/is/lethal"}), "/some/45/randomness/is/lethal/");
t.equal(routes.resolve("name"), callback);
t.equal(routes.resolve("/some/45/randomness/is/lethal/"), callback);
t.end();
});
test("nested routes", function(t){
"use strict";
function callback1(){}
function callback3(){}
var router = routes.router("node/", "node", [
["node1/", "node1", callback1],
["node2/", "node2", [
["node3/:int/", "node3", callback3]
]]
]);
router.start();
t.equal(routes.resolve("node:node1"), callback1);
t.equal(routes.resolve("node:node2:node3"), callback3);
t.equal(routes.resolve("node/node2/node3/90/"), callback3);
t.end();
});
|
module.exports = function(grunt) {
grunt.initConfig({
// https://github.com/ck86/main-bower-files#usage-with-grunt
bower: {
dev: {
dest: 'components/bower',
options: {
checkExistence: true,
debugging: true
}
}
},
sass: {
dev: {
options: {
// https://github.com/gruntjs/grunt-contrib-sass#style
style: 'compressed', // nested, compact, compressed, expanded
// https://github.com/gruntjs/grunt-contrib-sass#linenumbers
lineNumbers: true,
sourcemap: 'none'
},
files: {
'components/scss/style.css': 'components/scss/style.scss' // 'destination': 'source'
}
},
dist: {
options: {
style: 'compressed',
lineNumbers: false,
sourcemap: 'none'
},
files: {
'components/scss/style.css': 'components/scss/style.scss' // 'destination': 'source'
}
}
},
concat: {
css: {
options: {
stripBanners: true,
banner:
'/******************************************************************************' + String.fromCharCode(13) +
'Theme Name: My Damn Wordpress Boilerplate' + String.fromCharCode(13) +
'Theme URI: http://30.jonathanbell.ca' + String.fromCharCode(13) +
'Description: It\'s just my damn Wordpress boilerplate.' + String.fromCharCode(13) +
'Author: Jonathan Bell' + String.fromCharCode(13) +
'Author URI: http://30.jonathanbell.ca' + String.fromCharCode(13) +
'Version: 0.1' + String.fromCharCode(13) +
'Tags: fluid-layout, responsive-layout, light, two-columns, right-sidebar, featured-images, rtl-language-support' + String.fromCharCode(13) +
'License: WTFPL' + String.fromCharCode(13) +
'License URI: http://sam.zoy.org/wtfpl/' + String.fromCharCode(13) +
'Are You Serious? Yes.' + String.fromCharCode(13) +
'******************************************************************************/' + String.fromCharCode(13) + String.fromCharCode(13) +
'/* these are here to make the theme check happy */' + String.fromCharCode(13) +
'.sticky {}' + String.fromCharCode(13) +
'.gallery-caption {}' + String.fromCharCode(13) +
'.bypostauthor {}' + String.fromCharCode(13) + String.fromCharCode(13)
},
src: [
'components/bower/*.css',
'components/css/**/*.css',
'components/scss/*.css'
],
dest: 'style.css'
},
js: {
src: [
// http://gruntjs.com/configuring-tasks#globbing-patterns
'components/bower/*.js', '!components/bower/jquery.js', // exclude jquery as WP includes it
'components/js/*.js'
],
options: {
separator: '\n\n//-------------------------------------------------\n'
},
dest: 'main.dev.js'
}
},
// minify JS
uglify: {
dist: {
src: 'main.dev.js',
dest: 'main.min.js'
}
},
// https://www.npmjs.com/package/grunt-contrib-watch#options-spawn
watch: {
options: {
spawn: false
},
scripts: {
files: [
'components/js/*.js',
'components/scss/**/*.scss'
],
tasks: [
// 'bower', // copy main bower files into project
'sass:dev', // compile sass
'concat', // concat any css from bower with the output from sass. place result in 'style.css'. concat js from bower with main js and place in 'main.dev.js'
'uglify' // minify the main js file
]
}
}
}); // grunt.initConfig
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('main-bower-files');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.registerTask('default', [
'bower', // copy main bower files into project
'sass:dev', // compile sass
'concat', // concat any css from bower with the output from sass. place result in 'style.css'. concat js from bower with main js and place in 'main.dev.js'
'uglify' // minify the main js file
]);
grunt.registerTask('prod', [
'bower', // copy main bower files into project
'sass:dist', // compile sass
'concat', // concat any css from bower with the output from sass. place result in 'style.css'. concat js from bower with main js and place in 'main.dev.js'
'uglify' // minify the main js file
]);
}; // wrapper function
|
/* eslint-disable import/prefer-default-export */
import visibleItems from './visible-items';
export default {
visibleItems,
};
|
/**
* Copyright (c) 2015 Guyon Roche
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var events = require("events");
var utils = require("./utils");
// =============================================================================
// AutoDrain - kind of /dev/null
var AutoDrain = module.exports = function() {
};
utils.inherits(AutoDrain, events.EventEmitter, {
write: function(chunk) {
this.emit('data', chunk);
},
end: function() {
this.emit('end');
}
});
|
/**
* Since we moved our documentation to our website repo, we want to point to the
* website from the docs in this repo
*
* This script write the link to the website in every READMEs.
*/
const { join } = require("path");
const { readdirSync, writeFileSync } = require("fs");
const cwd = process.cwd();
const packageDir = join(cwd, "packages");
const packages = readdirSync(packageDir);
const getWebsiteLink = n => `https://babeljs.io/docs/en/next/${n}.html`;
const getPackageJson = pkg => require(join(packageDir, pkg, "package.json"));
const getIssueLabelLink = l =>
`https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22${encodeURIComponent(
l
)}%22+is%3Aopen`;
const labels = {
"babel-preset-flow": getIssueLabelLink("area: flow"),
"babel-preset-node": getIssueLabelLink("area: node"),
"babel-preset-react": getIssueLabelLink("area: react"),
"babel-preset-typescript": getIssueLabelLink("area: typescript"),
"babel-parser": getIssueLabelLink("pkg: babylon"),
"babel-cli": getIssueLabelLink("pkg: cli"),
"babel-core": getIssueLabelLink("pkg: core"),
"babel-generator": getIssueLabelLink("pkg: generator"),
"babel-polyfill": getIssueLabelLink("pkg: polyfill"),
"babel-preset-env": getIssueLabelLink("pkg: preset-env"),
"babel-register": getIssueLabelLink("pkg: register"),
"babel-template": getIssueLabelLink("pkg: template"),
"babel-traverse": getIssueLabelLink("pkg: traverse"),
"babel-types": getIssueLabelLink("pkg: types"),
"babel-standalone": getIssueLabelLink("pkg: standalone"),
};
const generateReadme = ({ websiteLink, issuesLink, name, description }) =>
`# ${name}
> ${description}
See our website [${name}](${websiteLink}) for more information${
issuesLink
? ` or the [issues](${issuesLink}) associated with this package`
: ""
}.
## Install
Using npm:
\`\`\`sh
npm install --save-dev ${name}
\`\`\`
or using yarn:
\`\`\`sh
yarn add ${name} --dev
\`\`\`
`;
packages
.filter(x => x !== "README.md") // ignore root readme
.filter(x => x.indexOf("babel-preset-stage-") === -1) // ignore stages
.forEach(id => {
const { name, description } = getPackageJson(id);
const readmePath = join(packageDir, id, "README.md");
// generate
const websiteLink = getWebsiteLink(id);
const issuesLink = labels[id];
const readme = generateReadme({
websiteLink,
issuesLink,
name,
description,
});
// write
writeFileSync(readmePath, readme);
console.log("OK", id);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.