code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
import expect from 'expect';
import createStore from './createStore';
describe('createStore()', () => {
let store;
beforeEach(() => {
store = createStore();
});
it('should write data and return its key when write() is called', () => {
const hash = store.write({ hello: 'world' });
expect(hash).toBe(store.keys()[0]);
});
it('should return data when read() is called with a valid key', () => {
const hash = store.write({ hello: 'world' });
expect(store.read(hash)).toEqual({ hello: 'world' });
});
it('should throw an error when read() is called with an invalid key', () => {
store.write({ hello: 'world' });
expect(() => store.read('wrong')).toThrow(/Entry wrong not found/);
});
it('should return all keys when keys() is called', () => {
const hash1 = store.write({ hello: 'world' });
const hash2 = store.write({ hello2: 'world2' });
expect(store.keys()).toEqual([
hash1,
hash2,
]);
});
it('should return all store content when toJSON() is called', () => {
const hash1 = store.write({ hello: 'world' });
const hash2 = store.write({ hello2: 'world2' });
expect(store.toJSON()).toEqual({
[hash1]: {
hello: 'world',
},
[hash2]: {
hello2: 'world2',
},
});
});
it('should init the store if a snapshot is given', () => {
const localStore = createStore({
ae3: {
hello: 'world',
},
});
expect(localStore.read('ae3')).toEqual({
hello: 'world',
});
});
it('should write data with the given hash if provided', () => {
const hash = store.write({ hello: 'world' }, 'forcedHash');
expect(hash).toBe('forcedHash');
expect(store.keys()[0]).toBe('forcedHash');
expect(store.read('forcedHash')).toEqual({ hello: 'world' });
});
it('should notify any subscriber when something is written into the store', () => {
const subscriber1 = expect.createSpy();
store.subscribe(subscriber1);
const subscriber2 = expect.createSpy();
store.subscribe(subscriber2);
const hash = store.write({ hello: 'world' });
expect(subscriber1).toHaveBeenCalledWith(hash);
expect(subscriber2).toHaveBeenCalledWith(hash);
store.unsubscribe(subscriber1);
const hash2 = store.write({ hello: 'earth' });
expect(subscriber1.calls.length).toBe(1);
expect(subscriber2).toHaveBeenCalledWith(hash2);
expect(subscriber2.calls.length).toBe(2);
});
});
| RobinBressan/json-git | src/createStoreSpec.js | JavaScript | mit | 2,726 |
var xml = require('xmlbuilder');
var fs = require('fs');
/**
* Function is used to create plis file which is required for downloading ios app.
* @param {string} name app name
* @param {string} path path to application
* @param {string} title title for alert
* @param {Function} callback function which will be called when plist file is created
*/
function creatPlist(name, path, title, callback){
var d = xml.create('plist', {'version':'1.0'})
.ele('dict')
.ele('key','items').up()
.ele('array')
.ele('dict')
.ele('key','assets').up()
.ele('array')
.ele('dict')
.ele('key','kind').up()
.ele('string','software-package').up()
.ele('key','url').up()
.ele('string',path).up()
.up()
.up()
.ele('key','metadata').up()
.ele('dict')
.ele('key','bundle-identifier').up()
.ele('string', name).up()
.ele('key', 'kind').up()
.ele('string','software').up()
.ele('key','title').up()
.ele('string', title)
.up()
.up()
.up()
.up()
.up()
.end({ pretty: true});
//generate unique file path:) use this for now.
var filePath = './processing/file' + new Date().getMilliseconds() + '.plist';
fs.writeFile(filePath, d, function(err){
callback(err,filePath);
});
console.log(xml);
}
//--------------EXPORTS---------------//
exports.creatPlist = creatPlist;
| dimko1/ohmystore | server/utils/utils.xml.js | JavaScript | mit | 1,412 |
'use strict';
define([],
function($) {
var Util = class {
static charToLineCh(string, char) {
var stringUpToChar = string.substr(0, char);
var lines = stringUpToChar.split("\n");
return {
line: lines.length - 1,
ch: lines[lines.length - 1].length
};
}
};
return Util;
}); | pixelmaid/DynamicBrushes | javascript/app/Util.js | JavaScript | mit | 319 |
function initBtnStartAlgo(){
$('#btn_startDispatch').bind('click', function(event) {
event.preventDefault();
initAlgo();
createResultPanel("div_resultPanel");
doRound();
printRound("resultRegion");
printResultPersonal("resultPersonal");
createDownloadableContent();
});
}
// 初始化變數、將 html 清空
function initAlgo(){
// 有時會發生役男進來後,才臨時驗退的情形,我們會在其分數欄位填入 "NA" ,在算平均成績時不把他算進去
// 注意這裡只是預設值,當程式執行時,此預設值會被算出的值取代
// Fixed: 2014, Dec, 11
var not_here_student = 0;
students = new Array();
avgScore = 0.0;
for(x in regionDatas){
regionDatas[x].queue = new Array();
regionDatas[x].resultArray = new Array();
}
for(var i=1;i<=TOTAL_STUDENT;i++){
var student = new Student();
student.id = i;
student.score = $('#score'+i).val();
student.home = $('#wishList'+i+'_0').val();
student.wish1 = $('#wishList'+i+'_1').val();
student.result = NO_REGION_RESULT;
student.homeFirst = $('#homeFirst'+i).is(':checked');
// Add to lists
students[i-1] = student;
// 處理臨時被驗退的
if($('#score'+i).val()==="NA"){
students[i-1].result = "NA"; // 要給予跟 NO_REGION_RESULT 不一樣的值
not_here_student++;
continue;
}
// parserInt() used to cause lost of digits. Fixed: 2014, Oct 29
avgScore += parseFloat(student.score);
}
avgScore = avgScore/(TOTAL_STUDENT-not_here_student);
var size = Math.pow(10, 2);
avgScore = Math.round(avgScore * size) / size;
}
// 畫出 平均分數、Round1、Round2、Round3、分發結果(依個人)的那個 nav-tabs
function createResultPanel(printToDivID){
var str = '<div class="panel panel-info">';
str += '<div class="panel-heading">';
str += '<h3 class="panel-title">第 ' + WHAT_T + ' 梯 預排結果 ( 平均分數:'+avgScore+' )</h3>';
str += '</div>';
str += '<div class="panel-body" id="div_dispatchResult">';
str += '<ul class="nav nav-tabs">';
str += '<li class="active"><a href="#resultRegion" data-toggle="tab">地區</a></li>';
str += '<li><a href="#resultPersonal" data-toggle="tab">個人</a></li>';
// color block 色塊
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeHome + ';"></canvas> 家因</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type1 + ';"></canvas> 高均+戶籍</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type2 + ';"></canvas> 高均+非戶籍</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type3 + ';"></canvas> 低均+戶籍地</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type4 + ';"></canvas> 低均+非戶籍</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeKicked + ';"></canvas> 被擠掉</li>';
str += '</ul>';
str += '<div id="resultTabContent" class="tab-content">';
str += ' <div class="tab-pane fade active in" id="resultRegion"></div>';
str += ' <div class="tab-pane fade" id="resultPersonal"></div>';
str += '</div>';
str += '</div>';
str += '<div class="panel-fotter">';
str += ' <div class="btn-group btn-group-justified">';
str += ' <a href="" class="btn btn-primary" id="btn_downloadTXT">下載程式可讀取的格式(.txt)</a>';
str += ' <a href="" class="btn btn-info" id="btn_downloadCSVRegion">給輔導組(照地區.csv)</a>';
str += ' <a href="" class="btn btn-success" id="btn_downloadCSVPersonnel">給輔導組(照個人.csv)</a>';
str += ' </div>';
str += '</div>';
str += '</div>';
$("#"+printToDivID).html(str);
}
// 將 分發規則 用演算法實作
function doRound(){
// 可以清空 queue,因為我們可以直接從 student.result 的內容來找出還沒被分發的學生,送進下一 round
for(var i=0;i<regionDatas.length;i++){
regionDatas[i].queue = new Array();
}
// Step 1: 將學生加入其第N志願的 queue (N depend on round)
var regionDatasLength = regionDatas.length;
for(var k=0;k<TOTAL_STUDENT;k++){
// 如果學生已經分發到某的地點,就不須再分發,可跳過直接看下個學生。
if(students[k].result != NO_REGION_RESULT){
continue;
}
// TODO: 這邊改用 key hash 應該會漂亮、效能也更好
for(var i=0;i<regionDatasLength;i++){
if(students[k].wish1 == regionDatas[i].name){
regionDatas[i].queue.push(students[k]);
}
}
}
// Step 2: 將每個單位的 queue 裡面的學生互相比較,取出最適合此單位的學生放入此單位的 resultArray
for(var i=0;i<regionDatasLength;i++){
var region = regionDatas[i];
// 此單位名額已經滿,跳過
if(region.resultArray.length == region.available){
continue;
}
// 要去的人數 小於等於 開放的名額,每個人都錄取
else if(region.queue.length <= region.available){
// 其實可以不用排序,但是排序之後印出來比較好看
region.queue.sort(function(a, b){return a.score-b.score});
popItemFromQueueAndPushToResultArray(region, region.queue.length);
}
// 要去的人數 大於 開放的名額,依照 分發規則 找出最適合此單位的學生放入此單位的 resultArray
else{
// 不管是中央還是地方,都要比較成績,所以先依照成績排序
region.queue.sort(function(a, b){return a.score-b.score});
// 依照成績排序後是"由小到大",亦即 [30分, 40分, 60分, 90分, 100分]
// 考慮到之後的 Array.pop() 是 pop 出"最後一個"物件,這樣排列比較方便之後的處理
cruelFunction(i, region);
}
}
}
// This function is so cruel that I cannot even look at it.
function cruelFunction(regionID, region){
if(regionID<=3){
// 中央只有比成績,不考慮戶籍地,因此可直接依成績排序找出錄取的學生
popItemFromQueueAndPushToResultArray(region, region.available);
}else{
// 地方單位在依照成績排序後,再把 "過均標" 且 "符合戶籍地" 的往前排
// 剛剛已經過成績順序了,現在要分別對“過均標”跟“沒過均標”的做戶籍地優先的排序
region.queue.sort(function(a, b){
if((a.score >= avgScore && b.score >= avgScore) || (a.score < avgScore && b.score < avgScore)){
if(a.home == region.homeName && b.home != region.homeName){
return 1;
}else if(b.home == region.homeName && a.home != region.homeName){
return -1;
}
}
return 0;
});
// 接下來,把家因的抓出來,要優先分發,所以丟到 queue 最後面。(等等 pop()時會變成最前面 )
region.queue.sort(function(a, b){
if(a.homeFirst==true){
return 1;
}
return 0;
});
// 排完後再依照順序找出錄取的學生
popItemFromQueueAndPushToResultArray(region, region.available);
}
}
// 從 region 的排序過後的 queue 裡面,抓出 numberOfItems 個學生,丟進 resultArray 裡面
function popItemFromQueueAndPushToResultArray(region, numberOfItems){
for(var k=0;k<numberOfItems;k++){
region.resultArray.push(region.queue.pop());
}
assignStudentToRegion(region.homeName, region.resultArray);
}
// 將已經被分配到某地區的學生的 result attribute 指定為該地區。(resultArray[] 的 items 為學生,擁有 result )
function assignStudentToRegion(regionName, resultArray){
var length = resultArray.length;
for(var i=0;i<length;i++){
resultArray[i].result = regionName;
}
}
| johnyluyte/EPA-SMS-Dispatcher | js/algo.js | JavaScript | mit | 7,887 |
'use strict';
angular.module('articles').controller('ChangeHeaderImageController', ['$scope', '$timeout', '$stateParams', '$window', 'Authentication', 'FileUploader', 'Articles',
function ($scope, $timeout, $stateParams, $window, Authentication, FileUploader, Articles) {
$scope.user = Authentication.user;
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
$scope.imageURL = $scope.article.headerMedia || null;
// Create file uploader instance
$scope.uploader = new FileUploader({
url: 'api/articles/' + $stateParams.articleId + '/headerimage',
alias: 'newHeaderImage'
});
// Set file uploader image filter
$scope.uploader.filters.push({
name: 'imageFilter',
fn: function (item, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});
// Called after the user selected a new picture file
$scope.uploader.onAfterAddingFile = function (fileItem) {
if ($window.FileReader) {
var fileReader = new FileReader();
fileReader.readAsDataURL(fileItem._file);
fileReader.onload = function (fileReaderEvent) {
$timeout(function () {
$scope.imageURL = fileReaderEvent.target.result;
}, 0);
};
}
};
// Called after the article has been assigned a new header image
$scope.uploader.onSuccessItem = function (fileItem, response, status, headers) {
// Show success message
$scope.success = true;
// Populate user object
$scope.user = Authentication.user = response;
// Clear upload buttons
$scope.cancelUpload();
};
// Called after the user has failed to upload a new picture
$scope.uploader.onErrorItem = function (fileItem, response, status, headers) {
// Clear upload buttons
$scope.cancelUpload();
// Show error message
$scope.error = response.message;
};
// Change article header image
$scope.uploadHeaderImage = function () {
console.log($scope);
// Clear messages
$scope.success = $scope.error = null;
// Start upload
$scope.uploader.uploadAll();
};
// Cancel the upload process
$scope.cancelUpload = function () {
$scope.uploader.clearQueue();
//$scope.imageURL = $scope.article.profileImageURL;
};
}
]);
| davidsbelt/bacca-app | modules/articles/client/controllers/change-header-image.client.controller.js | JavaScript | mit | 2,451 |
/** @jsx h */
import h from '../../../helpers/h'
import { Mark } from '../../../..'
export default function(change) {
change.addMark(
Mark.create({
type: 'bold',
data: { thing: 'value' },
})
)
}
export const input = (
<value>
<document>
<paragraph>
<anchor />w<focus />ord
</paragraph>
</document>
</value>
)
export const output = (
<value>
<document>
<paragraph>
<anchor />
<b thing="value">w</b>
<focus />ord
</paragraph>
</document>
</value>
)
| ashutoshrishi/slate | packages/slate/test/changes/at-current-range/add-mark/with-mark-object.js | JavaScript | mit | 556 |
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var Parameter = require("../src/Parameter");
var OT = require("./FRP");
var glow = require("./glow");
__export(require("./types"));
var DEBUG = false;
/**
* Each frame an animation is provided a CanvasTick. The tick exposes access to the local animation time, the
* time delta between the previous frame (dt) and the drawing context. Animators typically use the drawing context
* directly, and pass the clock onto any time varying parameters.
*/
var CanvasTick = (function (_super) {
__extends(CanvasTick, _super);
function CanvasTick(clock, dt, ctx, events, previous) {
_super.call(this, clock, dt, previous);
this.clock = clock;
this.dt = dt;
this.ctx = ctx;
this.events = events;
this.previous = previous;
}
CanvasTick.prototype.copy = function () {
return new CanvasTick(this.clock, this.dt, this.ctx, this.events, this.previous);
};
CanvasTick.prototype.save = function () {
var cp = _super.prototype.save.call(this);
cp.ctx.save();
return cp;
};
CanvasTick.prototype.restore = function () {
var cp = _super.prototype.restore.call(this);
cp.ctx.restore();
return cp;
};
return CanvasTick;
})(OT.BaseTick);
exports.CanvasTick = CanvasTick;
var Animation = (function (_super) {
__extends(Animation, _super);
function Animation(attach) {
_super.call(this, attach);
this.attach = attach;
}
/**
* subclasses should override this to create another animation of the same type
* @param attach
*/
Animation.prototype.create = function (attach) {
if (attach === void 0) { attach = function (nop) { return nop; }; }
return new Animation(attach);
};
/**
* Affect this with an effect to create combined animation.
* Debug messages are inserted around the effect (e.g. a mutation to the canvas).
* You can expose time varying or constant parameters to the inner effect using the optional params.
*/
Animation.prototype.loggedAffect = function (label, effectBuilder, param1, param2, param3, param4, param5, param6, param7, param8) {
if (DEBUG)
console.log(label + ": build");
return this.affect(function () {
if (DEBUG)
console.log(label + ": attach");
var effect = effectBuilder();
return function (tick, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {
if (DEBUG) {
var elements = [];
if (arg1)
elements.push(arg1 + "");
if (arg2)
elements.push(arg2 + "");
if (arg3)
elements.push(arg3 + "");
if (arg4)
elements.push(arg4 + "");
if (arg5)
elements.push(arg5 + "");
if (arg6)
elements.push(arg6 + "");
if (arg7)
elements.push(arg7 + "");
if (arg8)
elements.push(arg8 + "");
console.log(label + ": tick (" + elements.join(",") + ")");
}
effect(tick, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
};
}, (param1 ? Parameter.from(param1) : undefined), (param2 ? Parameter.from(param2) : undefined), (param3 ? Parameter.from(param3) : undefined), (param4 ? Parameter.from(param4) : undefined), (param5 ? Parameter.from(param5) : undefined), (param6 ? Parameter.from(param6) : undefined), (param7 ? Parameter.from(param7) : undefined), (param8 ? Parameter.from(param8) : undefined));
};
Animation.prototype.velocity = function (velocity) {
if (DEBUG)
console.log("velocity: build");
return this.affect(function () {
if (DEBUG)
console.log("velocity: attach");
var pos = [0.0, 0.0];
return function (tick, velocity) {
if (DEBUG)
console.log("velocity: tick", velocity, pos);
tick.ctx.transform(1, 0, 0, 1, pos[0], pos[1]);
pos[0] += velocity[0] * tick.dt;
pos[1] += velocity[1] * tick.dt;
};
}, Parameter.from(velocity));
};
Animation.prototype.tween_linear = function (from, to, time) {
return this.affect(function () {
var t = 0;
if (DEBUG)
console.log("tween: init");
return function (tick, from, to, time) {
t = t + tick.dt;
if (t > time)
t = time;
var x = from[0] + (to[0] - from[0]) * t / time;
var y = from[1] + (to[1] - from[1]) * t / time;
if (DEBUG)
console.log("tween: tick", x, y, t);
tick.ctx.transform(1, 0, 0, 1, x, y);
};
}, Parameter.from(from), Parameter.from(to), Parameter.from(time));
};
Animation.prototype.glow = function (decay) {
if (decay === void 0) { decay = 0.1; }
return glow.glow(this, decay);
};
// Canvas API
/**
* Dynamic chainable wrapper for strokeStyle in the canvas API.
*/
Animation.prototype.strokeStyle = function (color) {
return this.loggedAffect("strokeStyle", function () { return function (tick, color) {
return tick.ctx.strokeStyle = color;
}; }, color);
};
/**
* Dynamic chainable wrapper for fillStyle in the canvas API.
*/
Animation.prototype.fillStyle = function (color) {
return this.loggedAffect("fillStyle", function () { return function (tick, color) {
return tick.ctx.fillStyle = color;
}; }, color);
};
/**
* Dynamic chainable wrapper for shadowColor in the canvas API.
*/
Animation.prototype.shadowColor = function (color) {
return this.loggedAffect("shadowColor", function () { return function (tick, color) {
return tick.ctx.shadowColor = color;
}; }, color);
};
/**
* Dynamic chainable wrapper for shadowBlur in the canvas API.
*/
Animation.prototype.shadowBlur = function (level) {
return this.loggedAffect("shadowBlur", function () { return function (tick, level) {
return tick.ctx.shadowBlur = level;
}; }, level);
};
/**
* Dynamic chainable wrapper for shadowOffsetX and shadowOffsetY in the canvas API.
*/
Animation.prototype.shadowOffset = function (xy) {
return this.loggedAffect("shadowOffset", function () { return function (tick, xy) {
tick.ctx.shadowOffsetX = xy[0];
tick.ctx.shadowOffsetY = xy[1];
}; }, xy);
};
/**
* Dynamic chainable wrapper for lineCap in the canvas API.
*/
Animation.prototype.lineCap = function (style) {
return this.loggedAffect("lineCap", function () { return function (tick, arg) {
return tick.ctx.lineCap = arg;
}; }, style);
};
/**
* Dynamic chainable wrapper for lineJoin in the canvas API.
*/
Animation.prototype.lineJoin = function (style) {
return this.loggedAffect("lineJoin", function () { return function (tick, arg) {
return tick.ctx.lineJoin = arg;
}; }, style);
};
/**
* Dynamic chainable wrapper for lineWidth in the canvas API.
*/
Animation.prototype.lineWidth = function (width) {
return this.loggedAffect("lineWidth", function () { return function (tick, arg) {
return tick.ctx.lineWidth = arg;
}; }, width);
};
/**
* Dynamic chainable wrapper for miterLimit in the canvas API.
*/
Animation.prototype.miterLimit = function (limit) {
return this.loggedAffect("miterLimit", function () { return function (tick, arg) {
return tick.ctx.miterLimit = arg;
}; }, limit);
};
/**
* Dynamic chainable wrapper for rect in the canvas API.
*/
Animation.prototype.rect = function (xy, width_height) {
return this.loggedAffect("rect", function () { return function (tick, xy, width_height) {
return tick.ctx.rect(xy[0], xy[1], width_height[0], width_height[1]);
}; }, xy, width_height);
};
/**
* Dynamic chainable wrapper for fillRect in the canvas API.
*/
Animation.prototype.fillRect = function (xy, width_height) {
return this.loggedAffect("fillRect", function () { return function (tick, xy, width_height) {
return tick.ctx.fillRect(xy[0], xy[1], width_height[0], width_height[1]);
}; }, xy, width_height);
};
/**
* Dynamic chainable wrapper for strokeRect in the canvas API.
*/
Animation.prototype.strokeRect = function (xy, width_height) {
return this.loggedAffect("strokeRect", function () { return function (tick, xy, width_height) {
return tick.ctx.strokeRect(xy[0], xy[1], width_height[0], width_height[1]);
}; }, xy, width_height);
};
/**
* Dynamic chainable wrapper for clearRect in the canvas API.
*/
Animation.prototype.clearRect = function (xy, width_height) {
return this.loggedAffect("clearRect", function () { return function (tick, xy, width_height) {
return tick.ctx.clearRect(xy[0], xy[1], width_height[0], width_height[1]);
}; }, xy, width_height);
};
/**
* Encloses the inner animation with a beginpath() and endpath() from the canvas API.
*
* This returns a path object which events can be subscribed to
*/
Animation.prototype.withinPath = function (inner) {
return this.pipe(new PathAnimation(function (upstream) {
if (DEBUG)
console.log("withinPath: attach");
var beginPathBeforeInner = upstream.tapOnNext(function (tick) { return tick.ctx.beginPath(); });
return inner.attach(beginPathBeforeInner).tapOnNext(function (tick) { return tick.ctx.closePath(); });
}));
};
/**
* Dynamic chainable wrapper for fill in the canvas API.
*/
Animation.prototype.closePath = function () {
return this.loggedAffect("closePath", function () { return function (tick) {
return tick.ctx.closePath();
}; });
};
/**
* Dynamic chainable wrapper for fill in the canvas API.
*/
Animation.prototype.beginPath = function () {
return this.loggedAffect("beginPath", function () { return function (tick) {
return tick.ctx.beginPath();
}; });
};
/**
* Dynamic chainable wrapper for fill in the canvas API.
*/
Animation.prototype.fill = function () {
return this.loggedAffect("fill", function () { return function (tick) {
return tick.ctx.fill();
}; });
};
/**
* Dynamic chainable wrapper for stroke in the canvas API.
*/
Animation.prototype.stroke = function () {
return this.loggedAffect("stroke", function () { return function (tick) {
return tick.ctx.stroke();
}; });
};
/**
* Dynamic chainable wrapper for moveTo in the canvas API.
*/
Animation.prototype.moveTo = function (xy) {
return this.loggedAffect("moveTo", function () { return function (tick, xy) {
return tick.ctx.moveTo(xy[0], xy[1]);
}; }, xy);
};
/**
* Dynamic chainable wrapper for lineTo in the canvas API.
*/
Animation.prototype.lineTo = function (xy) {
return this.loggedAffect("lineTo", function () { return function (tick, xy) {
return tick.ctx.lineTo(xy[0], xy[1]);
}; }, xy);
};
/**
* Dynamic chainable wrapper for clip in the canvas API.
*/
Animation.prototype.clip = function () {
return this.loggedAffect("clip", function () { return function (tick) {
return tick.ctx.clip();
}; });
};
/**
* Dynamic chainable wrapper for quadraticCurveTo in the canvas API. Use with withinPath.
*/
Animation.prototype.quadraticCurveTo = function (control, end) {
return this.loggedAffect("quadraticCurveTo", function () { return function (tick, arg1, arg2) {
return tick.ctx.quadraticCurveTo(arg1[0], arg1[1], arg2[0], arg2[1]);
}; }, control, end);
};
/**
* Dynamic chainable wrapper for bezierCurveTo in the canvas API. Use with withinPath.
*/
Animation.prototype.bezierCurveTo = function (control1, control2, end) {
return this.loggedAffect("bezierCurveTo", function () { return function (tick, arg1, arg2, arg3) {
return tick.ctx.bezierCurveTo(arg1[0], arg1[1], arg2[0], arg2[1], arg3[0], arg3[1]);
}; }, control1, control2, end);
};
/**
* Dynamic chainable wrapper for arc in the canvas API. Use with withinPath.
*/
Animation.prototype.arcTo = function (tangent1, tangent2, radius) {
return this.loggedAffect("arcTo", function () { return function (tick, arg1, arg2, arg3) {
return tick.ctx.arcTo(arg1[0], arg1[1], arg2[0], arg2[1], arg3);
}; }, tangent1, tangent2, radius);
};
/**
* Dynamic chainable wrapper for scale in the canvas API.
*/
Animation.prototype.scale = function (xy) {
return this.loggedAffect("scale", function () { return function (tick, xy) {
return tick.ctx.scale(xy[0], xy[1]);
}; }, xy);
};
/**
* Dynamic chainable wrapper for rotate in the canvas API.
*/
Animation.prototype.rotate = function (clockwiseRadians) {
return this.loggedAffect("rotate", function () { return function (tick, arg) {
return tick.ctx.rotate(arg);
}; }, clockwiseRadians);
};
/**
* Dynamic chainable wrapper for translate in the canvas API.
*/
Animation.prototype.translate = function (xy) {
return this.loggedAffect("translate", function () { return function (tick, xy) {
tick.ctx.translate(xy[0], xy[1]);
}; }, xy);
};
/**
* Dynamic chainable wrapper for translate in the canvas API.
* [ a c e
* b d f
* 0 0 1 ]
*/
Animation.prototype.transform = function (a, b, c, d, e, f) {
return this.loggedAffect("transform", function () { return function (tick, arg1, arg2, arg3, arg4, arg5, arg6) {
return tick.ctx.transform(arg1, arg2, arg3, arg4, arg5, arg6);
}; }, a, b, c, d, e, f);
};
/**
* Dynamic chainable wrapper for setTransform in the canvas API.
*/
Animation.prototype.setTransform = function (a, b, c, d, e, f) {
return this.loggedAffect("setTransform", function () { return function (tick, arg1, arg2, arg3, arg4, arg5, arg6) {
return tick.ctx.setTransform(arg1, arg2, arg3, arg4, arg5, arg6);
}; }, a, b, c, d, e, f);
};
/**
* Dynamic chainable wrapper for font in the canvas API.
*/
Animation.prototype.font = function (style) {
return this.loggedAffect("font", function () { return function (tick, arg) {
return tick.ctx.font = arg;
}; }, style);
};
/**
* Dynamic chainable wrapper for textAlign in the canvas API.
*/
Animation.prototype.textAlign = function (style) {
return this.loggedAffect("textAlign", function () { return function (tick, arg) {
return tick.ctx.textAlign = arg;
}; }, style);
};
/**
* Dynamic chainable wrapper for textBaseline in the canvas API.
*/
Animation.prototype.textBaseline = function (style) {
return this.loggedAffect("textBaseline", function () { return function (tick, arg) {
return tick.ctx.textBaseline = arg;
}; }, style);
};
/**
* Dynamic chainable wrapper for textBaseline in the canvas API.
*/
Animation.prototype.fillText = function (text, xy, maxWidth) {
if (maxWidth) {
return this.loggedAffect("fillText", function () { return function (tick, text, xy, maxWidth) {
return tick.ctx.fillText(text, xy[0], xy[1], maxWidth);
}; }, text, xy, maxWidth);
}
else {
return this.loggedAffect("fillText", function () { return function (tick, text, xy, maxWidth) {
return tick.ctx.fillText(text, xy[0], xy[1]);
}; }, text, xy);
}
};
/**
* Dynamic chainable wrapper for drawImage in the canvas API.
*/
Animation.prototype.drawImage = function (img, xy) {
return this.loggedAffect("drawImage", function () { return function (tick, img, xy) {
return tick.ctx.drawImage(img, xy[0], xy[1]);
}; }, img, xy);
};
/**
* * Dynamic chainable wrapper for globalCompositeOperation in the canvas API.
*/
Animation.prototype.globalCompositeOperation = function (operation) {
return this.loggedAffect("globalCompositeOperation", function () { return function (tick, arg) {
return tick.ctx.globalCompositeOperation = arg;
}; }, operation);
};
Animation.prototype.arc = function (center, radius, radStartAngle, radEndAngle, counterclockwise) {
if (counterclockwise === void 0) { counterclockwise = false; }
return this.loggedAffect("arc", function () { return function (tick, arg1, arg2, arg3, arg4, counterclockwise) {
return tick.ctx.arc(arg1[0], arg1[1], arg2, arg3, arg4, counterclockwise);
}; }, center, radius, radStartAngle, radEndAngle, counterclockwise);
};
return Animation;
})(OT.SignalPipe);
exports.Animation = Animation;
function create(attach) {
if (attach === void 0) { attach = function (x) { return x; }; }
return new Animation(attach);
}
exports.create = create;
var PathAnimation = (function (_super) {
__extends(PathAnimation, _super);
function PathAnimation() {
_super.apply(this, arguments);
}
return PathAnimation;
})(Animation);
exports.PathAnimation = PathAnimation;
function save(width, height, path) {
var GIFEncoder = require('gifencoder');
var fs = require('fs');
var encoder = new GIFEncoder(width, height);
encoder.createReadStream()
.pipe(encoder.createWriteStream({ repeat: 10000, delay: 100, quality: 1 }))
.pipe(fs.createWriteStream(path));
encoder.start();
return new Animation(function (upstream) {
return upstream.tap(function (tick) {
if (DEBUG)
console.log("save: wrote frame");
encoder.addFrame(tick.ctx);
}, function () { console.error("save: not saved", path); }, function () { console.log("save: saved", path); encoder.finish(); });
});
}
exports.save = save;
| tomlarkworthy/animaxe | dist/src/CanvasAnimation.js | JavaScript | mit | 19,265 |
import { h } from 'preact';
import JustNotSorry from '../src/components/JustNotSorry.js';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-preact-pure';
configure({ adapter: new Adapter() });
describe('JustNotSorry', () => {
const justNotSorry = mount(<JustNotSorry />);
let editableDiv1;
let editableDiv2;
let editableDiv3;
let wrapper;
let instance;
const mutationObserverMock = jest.fn(function MutationObserver(callback) {
this.observe = jest.fn();
this.disconnect = jest.fn();
this.trigger = (mockedMutationList) => {
callback(mockedMutationList, this);
};
});
document.createRange = jest.fn(() => ({
setStart: jest.fn(),
setEnd: jest.fn(),
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
startContainer: 'test',
getClientRects: jest.fn(() => [{}]),
}));
global.MutationObserver = mutationObserverMock;
function generateEditableDiv(id, innerHtml) {
return mount(
<div id={id} contentEditable={'true'}>
{innerHtml ? innerHtml : ''}
</div>
);
}
beforeAll(() => {
editableDiv1 = generateEditableDiv('div-1');
editableDiv2 = generateEditableDiv('div-2', 'test just test');
editableDiv3 = generateEditableDiv('div-3', 'test justify test');
});
describe('#addObserver', () => {
it('adds an observer that listens for structural changes to the content editable div', () => {
// remount JNS to trigger constructor functions
justNotSorry.unmount();
justNotSorry.mount();
const instance = justNotSorry.instance();
const spy = jest.spyOn(instance, 'addObserver');
const node = mount(
<div
id={'div-focus'}
contentEditable={'true'}
onFocus={instance.addObserver.bind(instance)}
></div>
);
node.simulate('focus');
// There should be the document observer and the observer specifically for the target div
const observerInstances = mutationObserverMock.mock.instances;
const observerInstance = observerInstances[observerInstances.length - 1];
expect(observerInstances.length).toBe(2);
expect(spy).toHaveBeenCalledTimes(1);
expect(observerInstance.observe).toHaveBeenCalledWith(node.getDOMNode(), {
attributes: false,
characterData: false,
childList: true,
subtree: true,
});
node.unmount();
});
it('starts checking for warnings', () => {
const instance = justNotSorry.instance();
const spy = jest.spyOn(instance, 'checkForWarnings');
const node = mount(
<div
id={'div-focus'}
contentEditable={'true'}
onFocus={instance.addObserver.bind(instance)}
></div>
);
node.simulate('focus');
expect(spy).toHaveBeenCalled();
node.unmount();
});
it('adds warnings to the content editable div', () => {
const instance = justNotSorry.instance();
const spy = jest.spyOn(instance, 'addWarnings');
const node = mount(
<div
id={'div-focus'}
contentEditable={'true'}
onFocus={instance.addObserver.bind(instance)}
></div>
);
node.simulate('focus');
expect(spy).toHaveBeenCalledWith(node.getDOMNode().parentNode);
node.unmount();
});
});
describe('#removeObserver', () => {
it('removes any existing warnings', () => {
const instance = justNotSorry.instance();
const spy = jest.spyOn(instance, 'removeObserver');
const node = mount(
<div
id={'div-focus'}
contentEditable={'true'}
onFocus={instance.addObserver.bind(instance)}
onBlur={instance.removeObserver.bind(instance)}
>
just not sorry
</div>
);
node.simulate('focus');
expect(justNotSorry.state('warnings').length).toEqual(2);
// remount the node
node.mount();
node.simulate('blur');
expect(spy).toHaveBeenCalledTimes(1);
expect(justNotSorry.state('warnings').length).toEqual(0);
node.unmount();
});
it('no longer checks for warnings on input events', () => {
justNotSorry.unmount();
justNotSorry.mount();
const instance = justNotSorry.instance();
const node = mount(
<div
id={'div-remove'}
contentEditable={'true'}
onFocus={instance.addObserver.bind(instance)}
onBlur={instance.removeObserver.bind(instance)}
></div>
);
node.simulate('focus');
node.simulate('blur');
const spy = jest.spyOn(instance, 'checkForWarnings');
node.simulate('input');
expect(spy).not.toHaveBeenCalled();
node.unmount();
});
it('disconnects the observer', () => {
const instance = justNotSorry.instance();
const spy = jest.spyOn(instance, 'removeObserver');
const node = mount(
<div
id={'div-disconnect'}
contentEditable={'true'}
onFocus={instance.addObserver.bind(instance)}
onBlur={instance.removeObserver.bind(instance)}
></div>
);
node.simulate('focus');
node.simulate('blur');
// There should be the document observer and the observer specifically for the target div
const observerInstances = mutationObserverMock.mock.instances;
const observerInstance = observerInstances[observerInstances.length - 1];
expect(spy).toHaveBeenCalled();
expect(observerInstance.disconnect).toHaveBeenCalled();
node.unmount();
});
});
describe('#addWarning', () => {
beforeEach(() => {
wrapper = mount(<JustNotSorry />);
instance = wrapper.instance();
});
it('adds a warning for a single keyword', () => {
const node = editableDiv2.getDOMNode();
instance.addWarning(node, 'just', 'warning message');
expect(wrapper.state('warnings').length).toEqual(1);
expect(wrapper.state('warnings')[0]).toEqual(
expect.objectContaining({
keyword: 'just',
message: 'warning message',
parentNode: node,
})
);
});
it('does not add warnings for partial matches', () => {
const node = editableDiv3.getDOMNode();
instance.addWarning(node, 'just', 'warning message');
expect(wrapper.state('warnings').length).toEqual(0);
expect(wrapper.state('warnings')).toEqual([]);
});
it('matches case insensitive', () => {
const node = generateEditableDiv('div-case', 'jUsT kidding').getDOMNode();
instance.addWarning(node, 'just', 'warning message');
expect(wrapper.state('warnings').length).toEqual(1);
expect(wrapper.state('warnings')[0]).toEqual(
expect.objectContaining({
keyword: 'just',
message: 'warning message',
parentNode: node,
})
);
});
it('catches keywords with punctuation', () => {
const node = generateEditableDiv(
'div-punctuation',
'just. test'
).getDOMNode();
instance.addWarning(node, 'just', 'warning message');
expect(wrapper.state('warnings').length).toEqual(1);
expect(wrapper.state('warnings')[0]).toEqual(
expect.objectContaining({
keyword: 'just',
message: 'warning message',
parentNode: node,
})
);
});
it('matches phrases', () => {
const node = generateEditableDiv(
'div-phrase',
'my cat is so sorry because of you'
).getDOMNode();
instance.addWarning(node, 'so sorry', 'warning message');
expect(wrapper.state('warnings').length).toEqual(1);
expect(wrapper.state('warnings')[0]).toEqual(
expect.objectContaining({
keyword: 'so sorry',
message: 'warning message',
parentNode: node,
})
);
});
it('does not add warnings for tooltip matches', () => {
document.createRange = jest.fn(() => ({
setStart: jest.fn(),
setEnd: jest.fn(),
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
startContainer:
"The word 'very' does not communicate enough information. Find a stronger, more meaningful adverb, or omit it completely. --Andrea Ayres",
getClientRects: jest.fn(() => [{}]),
}));
const node = editableDiv3.getDOMNode();
instance.addWarning(node, 'very', 'warning message');
expect(wrapper.state('warnings').length).toEqual(0);
expect(wrapper.state('warnings')).toEqual([]);
});
});
describe('#addWarnings', () => {
beforeEach(() => {
wrapper = mount(<JustNotSorry />);
instance = wrapper.instance();
});
it('does nothing when given an empty string', () => {
const node = editableDiv1.getDOMNode();
instance.addWarnings(node);
expect(wrapper.state('warnings').length).toEqual(0);
expect(wrapper.state('warnings')).toEqual([]);
});
it('adds warnings to all keywords', () => {
const node = generateEditableDiv(
'div-keywords',
'I am just so sorry. Yes, just.'
).getDOMNode();
instance.addWarnings(node);
expect(wrapper.state('warnings').length).toEqual(3);
});
});
describe('#checkForWarnings', () => {
const instance = justNotSorry.instance();
const spy = jest.spyOn(instance, 'checkForWarnings');
const node = mount(
<div onInput={instance.checkForWarnings}>just not sorry</div>
);
it('updates warnings each time input is triggered', () => {
node.simulate('input');
node.simulate('input');
node.simulate('input');
expect(spy).toHaveBeenCalledTimes(3);
node.unmount();
});
});
});
| cyrusinnovation/just-not-sorry | spec/JustNotSorrySpec.test.js | JavaScript | mit | 9,846 |
import { Category } from '../../../stories/storiesHierarchy';
export const storySettings = {
category: Category.COMPONENTS,
storyName: 'ColorPicker',
dataHook: 'storybook-colorpicker',
};
| wix/wix-style-react | packages/wix-style-react/src/ColorPicker/test/storySettings.js | JavaScript | mit | 195 |
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaihttp = require('chai-http');
chai.use(chaihttp);
var expect = chai.expect;
require(__dirname + '/../app.js');
describe('the error handler function', function() {
it('should return a status of 500', function(done) {
chai.request('localhost:3000')
.get('/products/fish')
.end(function(err, res) {
expect(res).to.have.status(500);
expect(JSON.stringify(res.body)).to.eql('{"msg":"ERROR!!"}');
done();
});
});
});
| ryanheathers/seattle-composting | test/error_handler_test.js | JavaScript | mit | 531 |
// "node scripts/create-package-app-test.js && node packages/app-test/synchronize.js && node packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js && lerna bootstrap",
'use strict';
require('./create-package-app-test.js');
require('../packages/app-test/synchronize.js');
require('../packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js');
const fs = require('fs-extra');
const path = require('path');
const execSync = require('child_process').execSync;
try {
//begin----加上packages/app-test
const lernaJson = require('../lerna.json');
const packagesFolderName = 'packages/app-test';
if (lernaJson.packages.indexOf(packagesFolderName) === -1) {
//可能中途ctr+c,导致包名没被删除
lernaJson.packages.push(packagesFolderName);
}
fs.writeFileSync(
path.resolve(__dirname, '../lerna.json'),
JSON.stringify(lernaJson, null, 2)
);
//end----加上packages/app-test
execSync('npm run lerna-bootstrap', { stdio: 'inherit' });
//begin----移除packages/app-test,发布的时候不会发布这个的,只是用来测试
if (lernaJson.packages.indexOf(packagesFolderName) !== -1) {
lernaJson.packages.splice(
lernaJson.packages.indexOf(packagesFolderName),
1
);
}
fs.writeFileSync(
path.resolve(__dirname, '../lerna.json'),
JSON.stringify(lernaJson, null, 2)
);
//end----移除packages/app-test,发布的时候不会发布这个的,只是用来测试
} catch (e) {
console.log(e);
}
| dog-days/create-react-boilerplate-app | scripts/bootstrap.js | JavaScript | mit | 1,512 |
'use strict';
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var eat = require('eat');
var userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true,
trim: true
},
username: {
type: String,
required: true,
unique: true,
trim: true
},
biography: {
type: String
},
location: {
type: String
},
auth: {
basic: {
username: String,
password: String
}
}
});
userSchema.methods.hashPassword = function(password) {
var hash = this.auth.basic.password = bcrypt.hashSync(password, 8);
return hash;
};
userSchema.methods.checkPassword = function(password) {
return bcrypt.compareSync(password, this.auth.basic.password);
};
userSchema.methods.generateToken = function(callback) {
var id = this._id;
eat.encode({id: id}, process.env.APP_SECRET, callback);
};
module.exports = mongoose.model('User', userSchema);
| mskalandunas/parcel | models/user.js | JavaScript | mit | 997 |
version https://git-lfs.github.com/spec/v1
oid sha256:bf2580cc3dbb5c69564e5338a736b949ba7f1c7d567f37e58589d9f573c7abbb
size 481
| yogeshsaroya/new-cdnjs | ajax/libs/highlight.js/8.4/languages/step21.min.js | JavaScript | mit | 128 |
version https://git-lfs.github.com/spec/v1
oid sha256:e7cf7648766782e7940410a3abb8126a98b94e57bd61bfc7c1523679e8ce7ed6
size 26807
| yogeshsaroya/new-cdnjs | ajax/libs/string.js/1.9.1/string.js | JavaScript | mit | 130 |
const UrlPathValidator = require('../../../services/validators/url-path-validator')
const referenceIdHelper = require('../../helpers/reference-id-helper')
const BenefitOwner = require('../../../services/domain/benefit-owner')
const ValidationError = require('../../../services/errors/validation-error')
const insertBenefitOwner = require('../../../services/data/insert-benefit-owner')
const SessionHandler = require('../../../services/validators/session-handler')
module.exports = function (router) {
router.get('/apply/:claimType/new-eligibility/benefit-owner', function (req, res) {
UrlPathValidator(req.params)
const isValidSession = SessionHandler.validateSession(req.session, req.url)
if (!isValidSession) {
return res.redirect(SessionHandler.getErrorPath(req.session, req.url))
}
return res.render('apply/new-eligibility/benefit-owner', {
claimType: req.session.claimType,
dob: req.session.dobEncoded,
relationship: req.session.relationship,
benefit: req.session.benefit,
referenceId: req.session.referenceId
})
})
router.post('/apply/:claimType/new-eligibility/benefit-owner', function (req, res, next) {
UrlPathValidator(req.params)
const isValidSession = SessionHandler.validateSession(req.session, req.url)
if (!isValidSession) {
return res.redirect(SessionHandler.getErrorPath(req.session, req.url))
}
const benefitOwnerBody = req.body
try {
const benefitOwner = new BenefitOwner(
req.body.FirstName,
req.body.LastName,
req.body['dob-day'],
req.body['dob-month'],
req.body['dob-year'],
req.body.NationalInsuranceNumber)
const referenceAndEligibilityId = referenceIdHelper.extractReferenceId(req.session.referenceId)
return insertBenefitOwner(referenceAndEligibilityId.reference, referenceAndEligibilityId.id, benefitOwner)
.then(function () {
return res.redirect(`/apply/${req.params.claimType}/new-eligibility/about-you`)
})
.catch(function (error) {
next(error)
})
} catch (error) {
if (error instanceof ValidationError) {
return renderValidationError(req, res, benefitOwnerBody, error.validationErrors, false)
} else {
throw error
}
}
})
}
function renderValidationError (req, res, benefitOwnerBody, validationErrors, isDuplicateClaim) {
return res.status(400).render('apply/new-eligibility/benefit-owner', {
errors: validationErrors,
isDuplicateClaim: isDuplicateClaim,
claimType: req.session.claimType,
dob: req.session.dobEncoded,
relationship: req.session.relationship,
benefit: req.session.benefit,
referenceId: req.session.referenceId,
benefitOwner: benefitOwnerBody
})
}
| ministryofjustice/apvs-external-web | app/routes/apply/new-eligibility/benefit-owner.js | JavaScript | mit | 2,796 |
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('memo-card', 'Integration | Component | memo card', {
integration: true
});
test('it renders', function(assert) {
assert.expect(2);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{memo-card}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#memo-card}}
template block text
{{/memo-card}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
| kush-team/pisku-afda | tests/integration/components/memo-card-test.js | JavaScript | mit | 661 |
module.exports = function (grunt) {
grunt.initConfig({
less: {
test: {
src: 'test/test.less',
dest: 'test/test.css'
}
}
})
grunt.loadNpmTasks('grunt-contrib-less')
grunt.registerTask('default', ['less'])
} | xsm-ue/xsm-page | Gruntfile.js | JavaScript | mit | 230 |
(function () {
'use strict';
// Setting up route
angular
.module('app.users')
.run(appRun);
// appRun.$inject = ['$stateProvider'];
/* @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [
{
state: 'profile',
config: {
url: '/settings/profile',
controller: 'SettingsController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
}
},
{
state: 'password',
config: {
url: '/settings/password',
controller: 'SettingsController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/settings/change-password.client.view.html'
}
},
{
state: 'accounts',
config: {
url: '/settings/accounts',
controller: 'SettingsController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/settings/social-accounts.client.view.html'
}
},
{
state: 'signup',
config: {
url: '/signup',
controller: 'AuthenticationController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/authentication/signup.client.view.html'
}
},
{
state: 'signin',
config: {
url: '/signin',
controller: 'AuthenticationController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/authentication/signin.client.view.html'
}
},
{
state: 'forgot',
config: {
url: '/password/forgot',
controller: 'PasswordController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/password/forgot-password.client.view.html'
}
},
{
state: 'reset-invalid',
config: {
url: '/password/reset/invalid',
controller: 'PasswordController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html'
}
},
{
state: 'reset-success',
config: {
url: '/password/reset/success',
controller: 'PasswordController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/password/reset-password-success.client.view.html'
}
},
{
state: 'reset',
config: {
url: '/password/reset/:token',
controller: 'PasswordController',
controllerAs: 'vm',
templateUrl: 'modules/users/views/password/reset-password.client.view.html'
}
}
];
}
})(); | fr101ed/mean | public/modules/users/config/users.client.routes.js | JavaScript | mit | 2,628 |
'use strict';
const {app} = require('electron');
const appName = app.getName();
module.exports = {
label: appName,
submenu: [{
label: 'About ' + appName,
role: 'about',
params: {
version: '1.0.0'
}
}, {
type: 'separator'
}, {
label: 'Preferences',
event: 'prefer',
params: 'optional params'
}, {
type: 'separator'
}, {
label: 'Hide ' + appName,
accelerator: 'Command+H',
role: 'hide'
}, {
label: 'Hide Others',
accelerator: 'Command+Shift+H',
role: 'hideothers'
}, {
label: 'Show All',
role: 'unhide'
}, {
type: 'separator'
}, {
label: 'Quit',
accelerator: 'Command+Q',
click: () => app.quit()
}]
};
| ragingwind/electron-menu-loader | demo/menu/darwin.js | JavaScript | mit | 659 |
(function($) {
"use strict";
/**
* Main controller class for jaoselect input
* @param {Object} settings for widget
* @param {JQuery} model initial <select> element, we hide it and use like a "model" layer
*/
var JaoSelect = function(settings, model) {
// Delete previously created element if exists
model.next('.jao_select').remove();
// Create and cache DOM blocks
this.model = model.hide();
this.block = $.fn.jaoselect.htmlBuilder.render(settings, model);
this.header = this.block.find('.jao_header');
this.list = this.block.find('.jao_options');
this.options = this.block.find('.jao_options input.jao_option');
this.placeholder = this.block.find('.jao_value');
this.settings = settings;
this.block.data('jaoselect', this);
// Event handlers
this.header.click($.proxy(function() {this.toggleList();}, this));
this.options.click($.proxy(function() {this.onOptionClick();}, this));
this.model.change($.proxy(function() {this.onModelChange();}, this));
this.onModelChange();
return this;
};
JaoSelect.prototype = {
/* ---------------- Controllers ----------------- */
/**
* Callback for option click
*/
onOptionClick: function() {
if (!this.settings.multiple && this.settings.dropdown) {
this.hideList();
}
this.updateModel();
},
/**
* Update model input element and init UI changes
*/
updateModel: function() {
this.model.val(this.getValueFromView());
this.model.trigger('change');
},
/**
* Change view due to model value
*/
onModelChange: function() {
this.updateList();
this.updateHeader();
},
/**
* Get/set value of input
* @param value if not undefined, set this value for input element
*/
value: function(value) {
// Get values
if (!arguments.length) {
return this.getValue();
} else {
this.setValue(value);
}
},
/**
* Get jaoselect value
* @return {Array}
*/
getValue: function() {
return this.model.val();
},
/**
* Set jaoselect value
* @param value value to be set
*/
setValue: function(value) {
this.model.val(value);
this.model.trigger('change');
},
/**
* get list of values of checked options
*/
getValueFromView: function() {
var value = [];
this.options.filter(':checked').each(function() {
value.push(this.value);
});
return value;
},
/**
* get list of values with attributes
*/
getValueWithData: function() {
var values = [];
this.options.filter(':checked').parent().each(function() {
values.push($.extend({}, $(this).data()));
});
return values;
},
/* -------------------------- View ----------------- */
toggleList: function() { this.list.toggle(); },
openList: function() { this.list.show(); },
hideList: function() { this.list.hide(); },
/**
* Update list view: set correct checks and classes for checked labels
*/
updateList: function() {
var i, value = this.getValue();
value = $.isArray(value) ? value : [value];
this.options.removeAttr('checked');
for (i=0; i<value.length; i++) {
this.options.filter('[value="' + value[i] + '"]').attr('checked', 'checked');
}
this.list.find('>label').removeClass('selected');
this.list.find('>label:has(input:checked)').addClass('selected');
},
/**
* Update combobox header: get selected items and view them in header depending on their quantity
*/
updateHeader: function() {
var values = this.getValueWithData(), html;
switch (values.length) {
case 0:
html = this.settings.template.placeholder.call(this);
break;
case 1:
html = this.settings.template.singleValue.call(this, values[0]);
break;
default:
html = this.settings.template.multipleValue.call(this, values);
}
this.placeholder.html(html);
}
};
/**
* Plugin function; get defaults, merge them with real <select> settings and user settings
* @param s {Object} custom settings
*/
$.fn.jaoselect = function (s) {
// Initialize each multiselect
return this.each(function () {
var $this = $(this),
settings = $.extend(true, {}, $.fn.jaoselect.defaults, {
// Settings specific to dom element
width: this.style.width || $this.width() + 'px',
height: $this.height(),
multiple: !!$this.attr('multiple'),
name: $this.attr('name') || $.fn.jaoselect.index++
}, s);
// If multiple, model must support multiple selection
if (settings.multiple) {
$this.attr('multiple', 'multiple');
}
new JaoSelect(settings, $this);
});
};
$.fn.jaoselect.index = 0; // Index for naming different selectors if DOM name doesn't provided
/**
* Templates for combobox header
* This is set of functions which can be called from JaoSelect object within its scope.
* They return some html (depending on currently selected values), which is set to header when
* combobox value changes.
*/
$.fn.jaoselect.template = {
/**
* @return placeholder html
*/
placeholder: function() {
return '<span class="jao_placeholder">' + this.settings.placeholder + '</span>';
},
/**
* @param value {Object} single value
* @return html for first value
*/
singleValue: function(value) {
var html = '';
if (value.image) {
html += '<img src="' + value.image + '"> ';
}
html += '<span>' + value.title + '</span>';
return html;
},
/**
* @param values {Array}
* @return html for all values, comma-separated
*/
multipleValue: function(values) {
var i, html = [];
for (i=0; i<values.length; i++) {
html.push(this.settings.template.singleValue.call(this, values[i]));
}
return html.join(', ');
},
/**
* @param values {Array}
* @return html for quantity of selected items and overall options
*/
selectedCount: function(values) {
return 'Selected ' + values.length + ' of ' + this.options.size();
}
};
/**
* Default settings
*/
$.fn.jaoselect.defaults = {
maxDropdownHeight: 400,
dropdown: true,
placeholder: ' ',
template: {
placeholder: $.fn.jaoselect.template.placeholder,
singleValue: $.fn.jaoselect.template.singleValue,
multipleValue: $.fn.jaoselect.template.selectedCount
}
};
/**
* Helper for rendering html code
*/
$.fn.jaoselect.htmlBuilder = {
/**
* Render whole jaoselect widget
* @param settings {Object} settings for widget
* @param model {JQuery} initial <select> element
*/
render: function (settings, model) {
this.settings = settings;
this.model = model;
var classNames = [
'jao_select',
this.model.attr('class'),
(this.settings.multiple) ? 'multiple':'single',
(this.settings.dropdown) ? 'dropdown':'list'
];
this.block = $(
'<div class="' + classNames.join(' ') + '">' +
'<div class="jao_header">' +
'<div class="jao_arrow"></div>' +
'<div class="jao_value"></div>' +
'</div>' +
this.renderOptionsList() +
'</div>'
);
// Sometimes model selector is in hidden or invisible block,
// so we cannot adjust jaoselect in that place and must attach it to body,
// then reattach in its place
this.block.appendTo('body');
this.adjustStyle();
$('body').detach('.jaoselect');
this.block.insertAfter(this.model);
return this.block;
},
/**
* render html for the selector options
*/
renderOptionsList: function() {
var self = this,
html = '';
this.model.find('option').each(function() {
html += self.renderOption($(this));
});
return '<div class="jao_options">' + html + '</div>';
},
/**
* render html for a single option
* @param option {JQuery}
*/
renderOption: function(option) {
var attr = {
type: this.settings.multiple? 'checkbox' : 'radio',
value: option.val(),
name: 'jaoselect_' + this.settings.name,
disabled: option.attr('disabled') ? 'disabled' : '',
'class': 'jao_option'
},
labelAttr = $.extend({
'data-title': option.text(),
'data-cls': option.attr('class') || '',
'data-value': option.val(),
'class': option.attr('disabled') ? 'disabled' : ''
}, this.dataToAttributes(option));
return '<label ' + this.renderAttributes(labelAttr) + '>' +
'<input ' + this.renderAttributes(attr) + ' />' + this.renderLabel(option) +
'</label>';
},
/**
* Render label for one option
* @param option {JQuery}
*/
renderLabel: function(option) {
var className = option.attr('class') ? 'class="' + option.attr('class') + '"' : '',
image = option.data('image') ? '<img src="' + option.data('image') + '" /> ' : '';
return image + '<span ' + className + '>' + option.text() + '</span>';
},
/**
* Adjust width and height of header and dropdown list due to settings
*/
adjustStyle: function() {
this.block.css({
width: this.settings.width
});
if (this.settings.dropdown) {
this.adjustDropdownStyle();
} else {
this.adjustListStyle();
}
},
/**
* Adjust dropdown combobox header and options list
*/
adjustDropdownStyle: function() {
var header = this.block.find('div.jao_header'),
options = this.block.find('div.jao_options'),
optionsHeight = Math.min(options.innerHeight(), this.settings.maxDropdownHeight);
// optionsWidth = Math.max(header.innerWidth(), options.width());
options.css({
width: '100%', //this.settings.width, //optionsWidth + 'px',
height: optionsHeight + 'px'
});
},
/**
* Adjust options list for non-dropdown selector
*/
adjustListStyle: function() {
var options = this.block.find('div.jao_options');
options.css('height', this.settings.height + 'px');
},
/**
* Get html for given html attributes
* @param attr {Object} list of attributes and their values
*/
renderAttributes: function(attr) {
var key, html = [];
for (key in attr) {
if (attr[key]) {
html.push(key + '="' + attr[key] + '"');
}
}
return html.join(' ');
},
/**
* Get all data- attributes from source jQuery object
* source {JQuery} source element
*/
dataToAttributes: function(source) {
var data = source.data(), result = {}, key;
for (key in data) {
result['data-' + key] = data[key];
}
return result;
}
};
/**
* Document click handler, it is responsible for closing
* jaoselect dropdown list when user click somewhere else in the page
*/
$(document).bind('click.jaoselect', function(e) {
$('.jao_select.dropdown').each(function() {
// For some reasons initial select element fires "click" event when
// clicking on jaoselect, so we exclude it
if ($(this).data('jaoselect').model[0] == e.target)
return;
if (!$.contains(this, e.target)) {
$(this).data('jaoselect').hideList();
}
});
});
})(jQuery); | PieceOfMeat/jaoselect | src/jquery.jaoselect.js | JavaScript | mit | 10,820 |
// Get all of our fake login data
//var login = require('../login.json');
exports.view = function(req, res){
var goalname =req.params.goalname;
res.render('add-milestone', {'time' : req.cookies.startTime, 'goalname': goalname});
};
exports.timePost = function(req,res){
var startTime = req.params.startTime;
res.cookie('time', startTime, { maxAge: 900000 });
}
| w0nche0l/milestone | routes/add-milestone.js | JavaScript | mit | 369 |
Template.index.onCreated( () => {
let template = Template.instance();
template.autorun(()=> {
template.subscribe('wishList');
});
});
Template.index.helpers({
contentReady() {
return Template.instance().subscriptionsReady();
},
wishItems() {
return Wish.find().fetch();
}
});
| lnwKodeDotCom/WeWish | client/templates/authenticated/index.js | JavaScript | mit | 307 |
jQuery(document).ready(function($){$(".slide8").remove();}); | kwhaler/thenewarkansans | menace/rw_common/themes/couture/scripts/banner/slide_7.js | JavaScript | mit | 61 |
var throttle = require( "../throttle" );
// Fire callback at end of detection period
var func = throttle(function() {
// Do stuff here
console.log( "throttled" );
}, 200 );
func(); | ProperJS/throttle | test/test.js | JavaScript | mit | 195 |
version https://git-lfs.github.com/spec/v1
oid sha256:e1af4eb3952e50a1690c1d45f20c988b688e49f11938afc9f62e5384f71aaebb
size 7470
| yogeshsaroya/new-cdnjs | ajax/libs/fpsmeter/0.3.0/fpsmeter.min.js | JavaScript | mit | 129 |
version https://git-lfs.github.com/spec/v1
oid sha256:ef8207110cddbc9ab9a056d5d654bd6d8615dca91bbba5f04af60bfa0a82e780
size 408546
| yogeshsaroya/new-cdnjs | ajax/libs/jsPlumb/1.4.1/mootools.jsPlumb-1.4.1-all.js | JavaScript | mit | 131 |
const jwt = require("jwt-simple");
const co = require('co');
const config = require('../config');
const dbX = require('../db');
const coForEach = require('co-foreach');
module.exports = (io) => {
const collectionVersionsNS = io.of('/collectionVersions');
collectionVersionsNS.use((socket, next) => {
let token = socket.handshake.query.token;
// let isReconnect = socket.handshake.query.isReconnect;
// console.log('isReconnect:', isReconnect);
let decoded = null;
try {
decoded = jwt.decode(token, config.jwtSecret);
} catch(error) {
switch (error) {
case 'Signature verification failed':
return next(new Error('authentication error: the jwt has been falsified'));
case 'Token expired':
return next(new Error('authentication error: the jwt has been expired'));
}
}
console.log('decoded:', decoded);
return next();
})
//
collectionVersionsNS.on('connection', (socket) => {
// const roomId = socket.client.id;
console.log(`${new Date()}: ${socket.client.id} connected to socket /collectionVersions`);
socket.on('clientCollectionVersions', (data) => {
const versionsClient = data['versions'];
co(function*() {
const db = yield dbX.dbPromise;
const versionsLatest = yield db.collection('versions').find({}).toArray();
const clientCollectionUpdates = {};
// console.log('versionsClient', versionsClient);
versionsClient.reduce((acc, curr) => {
switch (true) {
case curr['collection'] === 'gd': // prices is called gd at client
const pricesVersionLatest = versionsLatest.find(v => v['collection'] === 'prices');
if (curr['version'] !== pricesVersionLatest['version']) {
acc['gd'] = {version: pricesVersionLatest['version']};
}
break;
default:
const versionLatest = versionsLatest.find(v => {
return v['collection'] === curr['collection'];
});
if (curr['version'] !== versionLatest['version']) {
acc[curr['collection']] = {version: versionLatest['version']};
}
}
return acc;
}, clientCollectionUpdates);
const hasUpdates = Object.keys(clientCollectionUpdates).length;
if (hasUpdates) {
const collectionsToUpdate = Object.keys(clientCollectionUpdates);
// types, titles, staffs
yield coForEach(Object.keys(clientCollectionUpdates), function*(k) {
console.log('adding to clientCollectionUpdates:', k);
switch (k) {
case 'gd':
clientCollectionUpdates[k]['data'] = JSON.stringify(yield db.collection('prices').find({}, {
createdAt: 0, createdBy: 0, modifiedAt: 0, modifiedBy: 0
}).toArray());
break;
default:
// need two stringifies, otherwise, error at heroku without details
clientCollectionUpdates[k]['data'] = [{a: 1}];
// clientCollectionUpdates[k]['data'] = JSON.stringify(JSON.stringify(yield db.collection(k).find({}).toArray()));
}
});
socket.emit('collectionUpdate', clientCollectionUpdates);
} else {
socket.send({message: 'all collections up-to-date'});
}
}).catch(error => {
console.log(error.stack);
socket.emit('error', {
error: error.stack
})
})
})
// after connection, client sends collectionVersions, then server compares
// each time a collection is updated, update its version in the 'versions' collection
})
} | rxjs-space/lyback | sockets/collection-versions.js | JavaScript | mit | 3,763 |
var gulp = require('gulp');
var setup = require('web3-common-build-setup');
var DEPS_FOLDER = setup.depsFolder;
// Build tools
var _ = require(DEPS_FOLDER + 'lodash');
var insert = require(DEPS_FOLDER + 'gulp-insert');
var del = require(DEPS_FOLDER + 'del');
var plugins = {};
plugins.sass = require(DEPS_FOLDER + 'gulp-sass');
plugins.tsc = require(DEPS_FOLDER + 'gulp-tsc');
plugins.ngHtml2js = require(DEPS_FOLDER + 'gulp-ng-html2js');
plugins.concat = require(DEPS_FOLDER + 'gulp-concat');
// Customize build configuration
var CONFIG = setup.buildConfig;
CONFIG.FOLDER.APP = _.constant("./src/app/web3-demo/");
CONFIG.PARTIALS.MAIN = function() {
return [
"./src/app/web3-demo/view/content.html"
];
};
var tmpLibs = CONFIG.SRC.JS.LIBS();
tmpLibs.push('./bower_components/angular-mocks/angular-mocks.js');
tmpLibs.push('./bower_components/jquery/dist/jquery.js');
tmpLibs.push('./bower_components/bootstrap/dist/js/bootstrap.min.js');
CONFIG.SRC.JS.LIBS = function() { return tmpLibs; };
CONFIG.DEV.NG_MODULE_DEPS = function() { return ['httpBackendMock']; };
var deployDir = "./dist";
// Initialize gulp
var gulpInstance = setup.initGulp(gulp, CONFIG);
gulpInstance.task('dist', ['tscompile:templates', 'tscompile:app', 'resources']);
gulpInstance.task('deploy', ['dist'], function() {
gulp.src([
CONFIG.DIST.FOLDER() + "app.js",
CONFIG.DIST.FOLDER() + "templates.js",
CONFIG.DIST.FOLDER() + "app.js.map",
])
.pipe(gulp.dest(deployDir));
});
gulp.task("tscompile:templates", function (cb) {
var camelCaseModuleName = CONFIG.DYNAMIC_META.MODULE_NAME().replace(/-([a-z])/g, function(g) {
return g[1].toUpperCase();
});
gulp.src(CONFIG.SRC.ANGULAR_HTMLS())
.pipe(plugins.ngHtml2js({
moduleName: camelCaseModuleName + "Templatecache",
prefix: "/"
}))
.pipe(plugins.concat(CONFIG.DIST.JS.FILES.TEMPLATES()))
.pipe(insert.wrap(requireJSTemplatesPrefix, requireJSSuffix))
.pipe(gulp.dest(CONFIG.DIST.FOLDER()))
.on('error', cb);
cb();
});
gulpInstance.task('tscompile:app', ['prod:init-app'], function(cb) {
// Exclude bootstrap.ts when compiling distributables since
// Camunda's tasklist app takes care of bootrapping angular
var srcFiles = [CONFIG.FOLDER.SRC() + "**/*.ts",
//"!" + CONFIG.FOLDER.SRC() + "**/*Interceptor.ts",
//"!" + CONFIG.FOLDER.SRC() + "**/bootstrap.ts",
"!" + CONFIG.SRC.TS.GLOBAL_TS_UNIT_TEST_FILES()];
gulp.src(srcFiles.concat(CONFIG.SRC.TS.TS_DEFINITIONS()))
.pipe(plugins.tsc(
{
allowBool: true,
out: CONFIG.DIST.JS.FILES.APP(),
sourcemap: true,
sourceRoot: "/",
target: "ES5"
}))
.pipe(insert.wrap(requireJSAppPrefix, requireJSSuffix))
.pipe(gulp.dest(CONFIG.DIST.FOLDER()))
.on('error', cb);
cb();
});
gulpInstance.task('sass', function (cb) {
gulp.src("./sass/main.scss")
.pipe(plugins.sass({
precision: 8,
errLogToConsole: true
}))
.pipe(gulp.dest("./target/css"))
.on('error', cb);
cb();
});
gulpInstance.task('watchSass', function (cb) {
gulp.watch(['sass/**/*.scss'], ['sass']);
});
| toefel/web3-demo | gulpfile.js | JavaScript | mit | 3,495 |
angular.module('africaXpress')
.controller('ShopController', function($scope, Item){
$scope.allItems;
$scope.getAll = function () {
Item.getAll().success(function(data){
$scope.allItems = data
});
};
$scope.getAll();
}); | ctodmia/africaexpress | client/controllers/shopcontroller.js | JavaScript | mit | 244 |
var REGEX = require('REGEX'),
MAX_SINGLE_TAG_LENGTH = 30,
create = require('DIV/create');
var parseString = function(parentTagName, htmlStr) {
var parent = create(parentTagName);
parent.innerHTML = htmlStr;
return parent;
};
var parseSingleTag = function(htmlStr) {
if (htmlStr.length > MAX_SINGLE_TAG_LENGTH) { return null; }
var singleTagMatch = REGEX.singleTagMatch(htmlStr);
return singleTagMatch ? [create(singleTagMatch[1])] : null;
};
module.exports = function(htmlStr) {
var singleTag = parseSingleTag(htmlStr);
if (singleTag) { return singleTag; }
var parentTagName = REGEX.getParentTagName(htmlStr),
parent = parseString(parentTagName, htmlStr);
var child,
idx = parent.children.length,
arr = Array(idx);
while (idx--) {
child = parent.children[idx];
parent.removeChild(child);
arr[idx] = child;
}
parent = null;
return arr.reverse();
};
| JosephClay/d-js | src/parser.js | JavaScript | mit | 975 |
import { module, test } from "qunit";
import argvInjector from "inject-loader?nwjs/App!nwjs/argv";
module( "nwjs/argv" );
test( "Default values", assert => {
const argv = argvInjector({
"nwjs/App": {
argv: []
}
});
assert.propEqual(
argv.argv,
{
"_": [],
"tray": false,
"hide": false,
"hidden": false,
"max": false,
"maximize": false,
"maximized": false,
"min": false,
"minimize": false,
"minimized": false,
"reset-window": false,
"versioncheck": true,
"version-check": true,
"logfile": true,
"loglevel": "",
"l": "",
"goto": "",
"launch": ""
},
"Has the correct parameters"
);
assert.deepEqual(
Object.keys( argv ).sort(),
[
"argv",
"parseCommand",
"ARG_GOTO",
"ARG_LAUNCH",
"ARG_LOGFILE",
"ARG_LOGLEVEL",
"ARG_MAX",
"ARG_MIN",
"ARG_RESET_WINDOW",
"ARG_TRAY",
"ARG_VERSIONCHECK"
].sort(),
"Exports the correct constants"
);
});
test( "Custom parameters", assert => {
const { argv } = argvInjector({
"nwjs/App": {
argv: [
// boolean without values
"--tray",
"--max",
"--min",
"--reset-window",
// boolean with "no-" prefix
"--no-versioncheck",
// boolean with value
"--logfile=false",
// string
"--loglevel",
"debug",
"--goto",
"foo",
"--launch",
"bar",
"positional"
]
}
});
assert.propEqual(
argv,
{
"_": [ "positional" ],
"tray": true,
"hide": true,
"hidden": true,
"max": true,
"maximize": true,
"maximized": true,
"min": true,
"minimize": true,
"minimized": true,
"reset-window": true,
"versioncheck": false,
"version-check": false,
"logfile": false,
"loglevel": "debug",
"l": "debug",
"goto": "foo",
"launch": "bar"
},
"Has the correct parameters"
);
});
test( "Aliases", assert => {
const { argv } = argvInjector({
"nwjs/App": {
argv: [
"--hide",
"--maximize",
"--minimize",
"--no-version-check",
"-l",
"debug"
]
}
});
assert.propEqual(
argv,
{
"_": [],
"tray": true,
"hide": true,
"hidden": true,
"max": true,
"maximize": true,
"maximized": true,
"min": true,
"minimize": true,
"minimized": true,
"reset-window": false,
"versioncheck": false,
"version-check": false,
"logfile": true,
"loglevel": "debug",
"l": "debug",
"goto": "",
"launch": ""
},
"Has the correct parameters"
);
});
test( "Parse command", assert => {
const { parseCommand } = argvInjector({
"nwjs/App": {
argv: [],
manifest: {
"chromium-args": "--foo --bar"
}
}
});
assert.propEqual(
// this is unfortunately how NW.js passes through the command line string from second
// application starts: parameters with leading dashes get moved to the beginning
parseCommand([
"/path/to/executable",
"--goto",
"--unrecognized-parameter-name",
"--foo",
"--bar",
"--user-data-dir=baz",
"--no-sandbox",
"--no-zygote",
"--flag-switches-begin",
"--flag-switches-end",
"foo"
].join( " " ) ),
{
"_": [],
"tray": false,
"hide": false,
"hidden": false,
"max": false,
"maximize": false,
"maximized": false,
"min": false,
"minimize": false,
"minimized": false,
"reset-window": false,
"versioncheck": true,
"version-check": true,
"logfile": true,
"loglevel": "",
"l": "",
"goto": "foo",
"launch": ""
},
"Correctly parses parameters"
);
});
| bastimeyer/livestreamer-twitch-gui | src/test/tests/nwjs/argv.js | JavaScript | mit | 3,497 |
module.exports.default = undefined;
| webpack/webpack-cli | test/build/config/undefined-default/webpack.config.js | JavaScript | mit | 36 |
var tpl = [
'<div id="{uuid}" class="datepicker ui-d-n">',
' <div class="datepicker__mask"></div>',
' <div class="datepicker__main">',
' <div class="datepicker__header">',
' <div class="datepicker__time-toggle"></div>',
' <div class="datepicker__time-selector-list">',
' <div class="datepicker__time-selector-item">',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-prev" id="_j_year_prev"><</a>',
' <a href="javascript:;" class="datepicker__time-selector-text" id="_j_year_text">{year}年</a>',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-next" id="_j_year_next">></a>',
' </div>',
' <div class="datepicker__time-selector-item">',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-prev" id="_j_month_prev"><</a>',
' <a href="javascript:;" class="datepicker__time-selector-text" id="_j_month_text">{month}月</a>',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-next" id="_j_month_next" >></a>',
' </div>',
' </div>',
' </div>',
' <div class="datepicker__panel">',
' <ul class="datepicker__week-list">',
' <li class="datepicker__week-item">日</li>',
' <li class="datepicker__week-item">一</li>',
' <li class="datepicker__week-item">二</li>',
' <li class="datepicker__week-item">三</li>',
' <li class="datepicker__week-item">四</li>',
' <li class="datepicker__week-item">五</li>',
' <li class="datepicker__week-item">六</li>',
' </ul>',
' <div class="datepicker__day-wrap">',
' <ul class="datepicker__day-list datepicker__day-list-curr">',
' {all_days}',
' </ul>',
' </div>',
' </div>',
' ',
' <div class="datepicker__footer">',
' <div class="datepicker__btn" id="_j_confirm_btn">确定</div>',
' <div class="datepicker__btn" id="_j_cancel_btn">取消</div>',
' </div>',
' </div>',
'</div>'
].join("");
module.exports = tpl;
| yuanzm/simple-date-picker | lib/datepicker_tpl.js | JavaScript | mit | 2,048 |
/**
* Created by Administrator on 2015/2/3.
*/
var Task = require('../models/task') ;
//add task
exports.addTask = function(req,res){
var title = req.body.title,
content = req.body.content,
date = req.body.date,
duration = req.body.duration,
done = req.body.done,
frequency = req.body.frequency ;
Task.addTask(title,content,date,duration,frequency,done,function(task){
res.json({'status':1,'task':task}) ;
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//update task
exports.updateTask = function(req,res){
var id = req.params.task_id,
title = req.body.title,
content = req.body.content,
date = req.body.date,
duration = req.body.duration,
frequency = req.body.frequency,
done = req.body.done;
Task.updateTask(id,title,content,date,duration,frequency,done,function(task){
res.json({'status':1,'task':task}) ;
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//get all tasks
exports.getAllTasks = function(req,res){
Task.findAll(function(tasks){
console.log(tasks.length) ;
res.json({'status':1,'tasks':tasks}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//get task by id
exports.getTaskById = function(req,res){
var id = req.params.task_id ;
Task.findById(id,function(task){
res.json({'status':1,'task':task}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
//delete task by id
exports.deleteTask = function(req,res){
var id = req.params.task_id ;
Task.delete(id,function(task){
res.json({'status':1,'task':task}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
} ;
/*
Task.addTask(title,content,date,duration,frequency,
function(task){
var task_id = task.objectId,
startDate = task.date,
duration = task.duration,
frequency = task.frequency,
date;
//add task records
for(var i = 1 ; i <= duration ; i ++){
//when reach the frequency , continue to next day
if(i % (frequency + 1) === 0)
continue ;
//take current date into consideration,so i must reduce 1
date = dateToInt(afterSomeDays(startDate,i-1)) ;
TaskRecord.addTaskRecord(task_id,date,0,null,
function(obect,error){
//if error happened , remove all records related to task
TaskRecord.deleteTaskRecordByTaskId(task_id) ;
res.json({'status':0,'message':error}) ;
}) ;
}
//return new records and task
TaskRecord.findByTaskId(task.objectId,function(records){
res.json({'status':1,'task':task,'records':records}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
*/
/*
Task.updateTask(id,title,content,date,duration,frequency,
function(task){
//update task records
if(reset){
//update task records by resetting all done record
//delete the old records by task id
TaskRecord.deleteTaskRecordByTaskId(id,function(){
//add new task records after delete old task records
var task_id = task.objectId,
startDate = task.date,
duration = task.duration,
frequency = task.frequency,
intDate;
for(var i = 1 ; i <= duration ; i ++){
//when reach the frequency , continue to next day
if(i % (frequency + 1) === 0)
continue ;
//take current date into consideration,so i must reduce 1
intDate = dateToInt(afterSomeDays(startDate,i-1)) ;
TaskRecord.addTaskRecord(task_id,intDate,0,null,
function(object,error){
//if error happened , remove all records related to task
TaskRecord.deleteTaskRecordByTaskId(task_id) ;
res.json({'status':0,'message':error}) ;
}) ;
}
//return new records and task
TaskRecord.findByTaskId(task.objectId,function(records){
res.json({'status':1,'task':task,'records':records}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}else{
//update task records by overriding the old record
var task_id = task.objectId,
startDate = task.date,
duration = task.duration,
frequency = task.frequency,
intDate;
for(var i = 1 ; i <= duration ; i ++){
//when reach the frequency , delete the exist record
if(i % (frequency + 1) === 0){
intDate = dateToInt(afterSomeDays(startDate,i-1)) ;
TaskRecord.findByTaskIdAndDate(task_id,intDate,function(records){
//exist a record,so delete the exist record
if(records.length !== 0)
records[0].destroy() ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}else{
//take current date into consideration,so i must reduce 1
intDate = dateToInt(afterSomeDays(startDate,i-1)) ;
//not exist a record so add new record
TaskRecord.findByTaskIdAndDate(task_id,intDate,function(records){
if(records.length === 0){
TaskRecord.addTaskRecord(task_id,intDate,0) ;
}
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}
}
//return new records and task
TaskRecord.findByTaskId(task.objectId,function(records){
res.json({'status':1,'task':task,'records':records}) ;
},function(error){
res.json({'status':0,'message':error}) ;
}) ;
}
},function(object,error){
res.json({'status':0,'message':error}) ;
}) ;
*/ | lakb248/CouplesWallet | controllers/taskController.js | JavaScript | mit | 6,193 |
(function () {
'use strict';
angular
.module('password', [
'ngMaterial',
/*@@DIST-TEMPLATE-CACHE*/
'ngRoute',
'password.analytics',
'password.title',
'password.nav',
'password.welcome',
'password.forgot',
'password.recovery',
'password.change',
'password.profile',
'password.mfa',
'password.reset',
'password.help',
'password.logo'
]);
})();
| silinternational/idp-pw-ui | app/password.module.js | JavaScript | mit | 513 |
const greetings = {
morning: ['God morgon!', 'Kaffe?', 'Ha en bra dag!', 'Hoppas du får en bra dag!', 'Sovit gott?'],
afternoon: ['Ganska fin du!', 'Trevlig eftermiddag!', 'Eftermiddags kaffe?', 'Glömde väl inte att fika?'],
evening: ['Trevlig kväll!', 'Ser bra ut!', 'Myskväll?!'],
};
module.exports = {
getMessage: function(callback) {
const d = new Date();
var hour = d.getHours();
if (hour >= 5 && hour < 12) {
return greetings.morning[Math.floor(Math.random() * greetings.morning.length)];
} else if (hour >= 12 && hour < 18) {
return greetings.afternoon[Math.floor(Math.random() * greetings.afternoon.length)];
} else if (hour >= 18 || (hour >= 0 && hour < 5)) {
return greetings.evening[Math.floor(Math.random() * greetings.evening.length)];
} else {
return 'Something wrong, hour is: ' + hour;
}
},
};
| jakkra/SmartMirror | util/messages.js | JavaScript | mit | 879 |
import auth from '../auth';
import clone from 'clone';
import storage from './storage';
async function addBlockOrItem(dbConn, token, codeObj, props, type) {
let user = await auth.getUser(token);
console.log(`Adding new ${type} for user ${user.login}`);
let add;
let newType = {
code: codeObj,
name: props.name,
icon: 'code',
owner: user.login
};
if(type == 'item') {
add = storage.addItemType;
newType.crosshairIcon = props.crosshairIcon;
newType.adjacentActive = props.adjacentActive;
} else {
add = storage.addBlockType;
newType.material = props.material;
}
await add(dbConn, newType);
return newType;
}
async function updateBlockOrItemCode(dbConn, token, id, codeObj, type) {
let user = await auth.getUser(token);
console.log(`Updating ${type} ${id} for user ${user.login}`);
let get, add, update;
if(type == 'item') {
get = storage.getItemType;
add = storage.addItemType;
update = storage.updateItemType;
} else {
get = storage.getBlockType;
add = storage.addBlockType;
update = storage.updateBlockType;
}
let original = await get(dbConn, id);
if(original.owner != user.login) {
throw new Error(`${type} ${id} belongs to ${original.owner} - ${user.login} doesn't have access.`);
}
let updated = clone(original);
updated.code = codeObj;
delete updated.newerVersion;
await add(dbConn, updated);
original.newerVersion = updated.id;
await update(dbConn, original);
return updated;
}
export default {
async getToolbar(dbConn, token) {
let user = await auth.getUser(token);
return await storage.getToolbar(dbConn, user.login);
},
async setToolbarItem(dbConn, token, position, type, id) {
let user = await auth.getUser(token);
await storage.updateToolbarItem(dbConn, user.login, position, {type, id});
},
async removeToolbarItem(dbConn, token, position) {
let user = await auth.getUser(token);
await storage.updateToolbarItem(dbConn, user.login, position, null);
},
async getAll(dbConn) {
let itemTypes = await storage.getAllItemTypes(dbConn);
let blockTypes = await storage.getAllBlockTypes(dbConn);
return {
itemTypes,
blockTypes
};
},
async getItemTypes(dbConn, token, ids) {
return await storage.getItemTypes(dbConn, ids);
},
async getBlockTypes(dbConn, token, ids) {
return await storage.getBlockTypes(dbConn, ids);
},
async updateBlockCode(dbConn, token, id, codeObj) {
return await updateBlockOrItemCode(dbConn, token, id, codeObj, 'block');
},
async updateItemCode(dbConn, token, id, codeObj) {
return await updateBlockOrItemCode(dbConn, token, id, codeObj, 'item');
},
async addBlockType(dbConn, token, codeObj, props) {
return await addBlockOrItem(dbConn, token, codeObj, props, 'block');
},
async addItemType(dbConn, token, codeObj, props) {
return await addBlockOrItem(dbConn, token, codeObj, props, 'item');
}
};
| UnboundVR/metavrse-server | src/inventory/controller.js | JavaScript | mit | 2,973 |
import { globalShortcut } from 'electron'
import playbackControls from '../actions/playbackControls'
function initGlobalShortcuts () {
globalShortcut.register('MediaNextTrack', playbackControls.clickNextSong)
globalShortcut.register('MediaPreviousTrack', playbackControls.clickPreviousSong)
globalShortcut.register('MediaStop', playbackControls.clickPlayPause)
globalShortcut.register('MediaPlayPause', playbackControls.clickPlayPause)
}
export default initGlobalShortcuts
| ashokfernandez/kiste | src/shortcuts/initGlobalShortcuts.js | JavaScript | mit | 483 |
/**
* @package EntegreJS
* @subpackage Widgets
* @subpackage fontawesome
* @author James Linden <[email protected]>
* @copyright 2016 James Linden
* @license MIT
*/
E.widget.fontawesome = class extends E.factory.node {
constructor( icon ) {
super( 'i' );
this.attr( 'class', `fa fa-${icon.toString().toLowerCase()}` );
}
static css() {
return 'https:/' + '/maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css';
}
size( size ) {
if( !E.empty( size ) ) {
var sizes = [ 'lg', '2x', '3x', '4x', '5x' ];
size = size.toString().toLowerCase();
if( sizes.includes( size ) ) {
this.attr( 'class', `fa-${size}` );
}
}
return this;
}
fixedwidth() {
this.attr( 'class', 'fa-fw' );
return this;
}
border() {
this.attr( 'class', 'fa-border' );
return this;
}
rotate( angle ) {
angle = parseInt( angle );
if( angle >= 0 && angle <= 360 ) {
this.attr( 'class', `fa-rotate-${angle}` );
}
return this;
}
flip( dir ) {
if( !E.empty( dir ) ) {
switch( dir.toString().toLowerCase() ) {
case 'h':
case 'horz':
dir = 'horizontal';
break;
case 'v':
case 'vert':
dir = 'vertical';
break;
}
if( dir in [ 'horizontal', 'vertical' ] ) {
this.attr( 'class', `fa-flip-${dir}` );
}
}
return this;
}
};
| entegreio/entegre-js | src/widget/fontawesome.js | JavaScript | mit | 1,327 |
require("kaoscript/register");
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
var Shape = require("../export/export.class.default.ks")().Shape;
function foobar() {
if(arguments.length === 1 && Type.isString(arguments[0])) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isString(x)) {
throw new TypeError("'x' is not of type 'String'");
}
return x;
}
else if(arguments.length === 1) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isClassInstance(x, Shape)) {
throw new TypeError("'x' is not of type 'Shape'");
}
return x;
}
else {
throw new SyntaxError("Wrong number of arguments");
}
};
return {
foobar: foobar
};
}; | kaoscript/kaoscript | test/fixtures/compile/export/export.filter.func.import.js | JavaScript | mit | 914 |
/**
* Node class
* @param {object} value
* @constructor
*/
class Node {
constructor(value) {
this._data = value;
}
value() {
return this._data;
}
}
export default Node;
| jvalen/dstruct-algorithms-examples-js | src/Node/Node.js | JavaScript | mit | 190 |
var AllDrinks =
[{"drinkName": "Alexander",
"recipe": "Shake all ingredients with ice and strain contents into a cocktail glass. Sprinkle nutmeg on top and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Gin_Alexander_%284371721753%29.jpg/220px-Gin_Alexander_%284371721753%29.jpg",
"alcohol": ["Brandy","Liqueur",],
"ingredients": ["1 oz cognac","1 oz white crème de cacao","1 oz light cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 8, "wWarm": 7, "wHot": 5},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue":{"sSpr": 7, "sSum": 4, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 2, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Americano",
"recipe": "Pour the Campari and vermouth over ice into glass, add a splash of soda water and garnish with half orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Americano_cocktail_at_Nightwood_Restaurant.jpg/220px-Americano_cocktail_at_Nightwood_Restaurant.jpg",
"alcohol": ["Vermouth","Liqueur",], "ingredients": ["1 oz Campari","1 oz red vermouth","A splash of soda water",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 2, "sSum": 7, "sFal": 8, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 6, "wSleep": 7}
}
},
{"drinkName": "Aperol Spritz",
"recipe": "Add 3 parts prosecco, 2 parts Aperol and top up with soda water, garnish with a slice of orange and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Aperol_Spritz_2014a.jpg/220px-Aperol_Spritz_2014a.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3 parts Prosecco","2 parts Aperol","1 part Soda Water",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 5, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 5}
}
},
{"drinkName": "Appletini",
"recipe": "Mix in a shaker, then pour into a chilled glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/28/Appletini.jpg/220px-Appletini.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (3 parts) Vodka","½ oz (1 part) Apple schnapps / Calvados","½ oz (1 part) Cointreau",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 3, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Aviation",
"recipe": "Add all ingredients into cocktail shaker filled with ice. Shake well and strain into cocktail glass. Garnish with a cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Aviation_Cocktail.jpg/220px-Aviation_Cocktail.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1½ oz gin","½ oz lemon juice","½ oz maraschino liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 4, "tNt": 7, "wSleep": 5}}},
{"drinkName": "B-52",
"recipe": "Layer ingredients into a shot glass. Serve with a stirrer.",
"image": "https://upload.wikimedia.org/wikipedia/commons/3/3a/Cocktail_B52.jpg",
"alcohol": ["Liqueur","Brandy",],
"ingredients": ["¾ oz Kahlúa","¾ oz Baileys Irish Cream","¾ oz Grand Marnier",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 6, "wWarm": 7, "wHot": 5},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 3, "dFS": 6},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 7, "wSleep": 6}
}
},
{"drinkName": "Bellini",
"recipe": "Pour peach purée into chilled flute, add sparkling wine. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Bellini_Cipriani%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg/220px-Bellini_Cipriani%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3½ oz (2 parts) Prosecco","2 oz (1 part) fresh peach purée",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 2, "sSum": 5, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Bijou",
"recipe": "Stir in mixing glass with ice and strain",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Bijou_Cocktail.jpg/220px-Bijou_Cocktail.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["1 part gin","1 part green Chartreuse","1 part sweet vermouth","Dash orange bitters",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 4, "wHot": 5},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 3, "sSum": 5, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 4, "dFS": 5},
"timeValue": {"tMrn": 0, "tAft": 3, "tNt": 5, "wSleep": 0}
}
},
{"drinkName": "Black Russian",
"recipe": "Pour the ingredients into an old fashioned glass filled with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Blackrussian.jpg/220px-Blackrussian.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["2 oz (5 parts) Vodka","¾ oz (2 parts) Coffee liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 3, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Black Velvet",
"recipe": "fill a tall champagne flute, halfway with chilled sparkling wine and float stout beer on top of the wine",
"image": "https://upload.wikimedia.org/wikipedia/en/thumb/f/f4/Black_Velvet_Cocktail_Layered.jpg/220px-Black_Velvet_Cocktail_Layered.jpg",
"alcohol": ["Champagne","Wine",],
"ingredients": ["Beer","Sparkling wine",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 5, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Bloody Mary",
"recipe": "Add dashes of Worcestershire Sauce, Tabasco, salt and pepper into highball glass, then pour all ingredients into highball with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Bloody_Mary.jpg/220px-Bloody_Mary.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (3 parts) Vodka","3 oz (6 parts) Tomato juice","½ oz (1 part) Lemon juice","2 to 3 dashes of Worcestershire Sauce","Tabasco","Celery salt","Pepper",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 7, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 4, "pSome": 9},
"seasonValue":{"sSpr": 6, "sSum": 5, "sFal": 8, "sWin": 10},
"dayValue": {"dMTRS": 8, "dW": 8, "dFS": 10},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Blue Hawaii",
"recipe": "Combine all ingredients with ice, stir or shake, then pour into a hurricane glass with the ice. Garnish with pineapple or orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Bluehawaiian.jpg/220px-Bluehawaiian.jpg",
"alcohol": ["Vodka","Rum","Liqueur",],
"ingredients": ["3/4 oz light rum","3/4 oz vodka","1/2 oz Curaçao","3 oz pineapple juice","1 oz Sweet and Sour",],
"drinkRating": {
"weatherValue": {"wCold": 0, "wMod": 3, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 2, "sSum": 6, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 6, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Blue Lagoon",
"recipe": "pour vodka and blue curacao in a shaker with ice, shake well & strain into ice filled highball glass, top with lemonade, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Blue_Lagoon_at_the_Mandarin_Oriental%2C_Washington_DC.jpg/220px-Blue_Lagoon_at_the_Mandarin_Oriental%2C_Washington_DC.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka","1 oz Blue Curacao","3½ oz Lemonade","1 orange slice.","Ice cubes",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Bramble",
"recipe": "Fill glass with crushed ice. Build gin, lemon juice and simple syrup over. Stir, and then pour blackberry liqueur over in a circular fashion to create marbling effect. Garnish with two blackberries and lemon slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Bramble_Cocktail1.jpg/220px-Bramble_Cocktail1.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1½ oz gin","½ oz lemon juice","½ oz simple syrup","½ oz Creme de Mure(blackberry liqueur)",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 8, "wSleep": 3}
}
},
{"drinkName": "Brandy Alexander",
"recipe": "Shake and strain into a chilled cocktail glass. Sprinkle with fresh ground nutmeg.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Brandy_alexander.jpg/220px-Brandy_alexander.jpg",
"alcohol": ["Brandy",],
"ingredients": ["1 oz (1 part) Cognac","1 oz (1 part) Crème de cacao (brown)","1 oz (1 part) Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Bronx",
"recipe": "Pour into cocktail shaker all ingredients with ice cubes, shake well. Strain in chilled cocktail or martini glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Bronx_%28cocktail%29.jpg/220px-Bronx_%28cocktail%29.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["1 oz (6 parts) Gin","½ oz (3 parts) Sweet Red Vermouth","½ oz (2 parts) Dry Vermouth","½ oz (3 parts) Orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Bucks Fizz",
"recipe": "* Pour the orange juice into glass and top up Champagne. Stir gently, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Buck%27s_Fizz_on_Christmas_Morning_%288491638980%29.jpg/220px-Buck%27s_Fizz_on_Christmas_Morning_%288491638980%29.jpg",
"alcohol": ["Champagne",],
"ingredients": ["2 oz (1 part) orange juice","3½ oz (2 parts) Champagne",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 4, "tAft": 6, "tNt": 7, "wSleep": 5}
}
},
{"drinkName": "Casesar",
"recipe": "Worcestershire Sauce, Sriracha or lime Cholula, lemon juice, olive juice, salt and pepper. Rim with celery salt, fill pint glass with ice - add ingredients - shake passionately & garnish. ",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Caesar_Cocktail.JPG/220px-Caesar_Cocktail.JPG",
"alcohol": ["Vodka",],
"ingredients": ["3 parts Vodka","9 Clamato juice", "Cap of Lemon juice", "2 to 3 dashes of Worcestershire Sauce", "Sriracha", "Celery salt", "Pepper",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 7, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 4, "pSome": 9},
"seasonValue":{"sSpr": 6, "sSum": 5, "sFal": 8, "sWin": 10},
"dayValue": {"dMTRS": 9, "dW": 9, "dFS": 10},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Caipirinha",
"recipe": "Place lime and sugar into old fashioned glass and muddle (mash the two ingredients together using a muddler or a wooden spoon). Fill the glass with crushed ice and add the Cachaça.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/15-09-26-RalfR-WLC-0048.jpg/220px-15-09-26-RalfR-WLC-0048.jpg",
"alcohol": [],
"ingredients": ["2 oz cachaça","Half a lime cut into 4 wedges","2 teaspoons sugar",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 6, "wSleep": 2}
}
},
{"drinkName": "Cape Codder",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Cape_Codder%2C_Tommy_Doyles_Irish_Pub%2C_Hyannis_MA.jpg/220px-Cape_Codder%2C_Tommy_Doyles_Irish_Pub%2C_Hyannis_MA.jpg",
"alcohol": ["Vodka",],
"ingredients": ["Vodka","Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 5},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "Chimayó Cocktail",
"recipe": "Pour the tequila and unfiltered apple cider into glass over ice. Add the lemon juice and creme de cassis and stir. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Chimayo_Cocktail_at_Rancho_de_Chimayo%2C_Chimayo_NM.jpg/220px-Chimayo_Cocktail_at_Rancho_de_Chimayo%2C_Chimayo_NM.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1½ oz Tequila","1 oz apple cider","1/4 oz lemon juice","1/4 oz creme de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 7, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Clover Club Cocktail",
"recipe": "Dry shake ingredients to emulsify, add ice, shake and served straight up.",
"image": "https://upload.wikimedia.org/wikipedia/en/thumb/9/99/Cloverclub.jpg/220px-Cloverclub.jpg",
"alcohol": ["Gin",],
"ingredients": ["1½ oz Gin","½ oz Lemon Juice","½ oz Raspberry Syrup","1 Egg White",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 7, "dFS": 10},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Colombia",
"recipe": "Shake the vodka and citrus juices in a mixer, then strain into the glass. Slide the grenadine down one side of the glass, where it will sink to the bottom. Slide the curacao down the other side, to lie between the vodka and grenadine.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Columbia-cocktail.jpg/220px-Columbia-cocktail.jpg",
"alcohol": ["Vodka","Liqueur","Brandy",],
"ingredients": ["2 parts vodka or brandy","1 part blue Curaçao","1 part grenadine","1 part lemon juice","6 parts orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 9, "sFal": 7, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 6, "wSleep": 4}
}
},
{"drinkName": "Cosmopolitan",
"recipe": "Add all ingredients into cocktail shaker filled with ice. Shake well and double strain into large cocktail glass. Garnish with lime wheel.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Cosmopolitan_%285076906532%29.jpg/220px-Cosmopolitan_%285076906532%29.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka Citron","½ oz Cointreau","½ oz Fresh lime juice","1 oz Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 5, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 9, "sFal": 8, "sWin": 4},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "Cuba Libre",
"recipe": "Build all ingredients in a Collins glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/15-09-26-RalfR-WLC-0056.jpg/220px-15-09-26-RalfR-WLC-0056.jpg",
"alcohol": ["Rum",],
"ingredients": ["1¾ oz Cola","2 oz Light rum","½ oz Fresh lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Dark N Stormy",
"recipe": "In a highball glass filled with ice add 2 oz dark rum and top with ginger beer. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Dark_n_Stormy.jpg/220px-Dark_n_Stormy.jpg",
"alcohol": ["Rum",],
"ingredients": ["2 oz dark rum","3½ oz Ginger beer",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 2, "pSome": 8},
"seasonValue":{"sSpr": 5, "sSum": 7, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "El Presidente",
"recipe": "stir well with ice, then strain into glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/El_Presidente_Cocktail.jpg/220px-El_Presidente_Cocktail.jpg",
"alcohol": ["Rum","Liqueur","Vermouth",],
"ingredients": ["Two parts rum","One part curaçao","One part dry vermouth","Dash grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 5},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Espresso Martini",
"recipe": "Pour ingredients into shaker filled with ice, shake vigorously, and strain into chilled martini glass",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Espresso-martini.jpg/220px-Espresso-martini.jpg",
"alcohol": ["Vodka",],
"ingredients": ["2 oz Vodka","½ oz Kahlua","Sugar syrup","1 shot strong Espresso",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 7, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 8, "tAft": 7, "tNt": 5, "wSleep": 1}
}
},
{"drinkName": "Fizzy Apple Cocktail",
"recipe": "Combine all three ingredients into a chilled glass and serve with ice and garnish.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Cup02.jpg/220px-Cup02.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1 shot Apple Vodka","1/2 cup Apple Juice","1/2 cup Lemonade",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Flaming Doctor Pepper",
"recipe": "Layer the two spirits in the shot glass, with the high-proof liquor on top. Light the shot and allow it to burn; then extinguish it by dropping it into the beer glass. Drink immediately.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Flaming_dr_pepper_%28101492893%29.jpg/220px-Flaming_dr_pepper_%28101492893%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 pint (~13 parts) beer","3 parts Amaretto","1 part high-proof liquor",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 1},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 3, "dFS": 7},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Flaming Volcano",
"recipe": "Combine all ingredients with 2 scoops of crushed ice in a blender, blend briefly, then pour into the volcano bowl. Pour some rum into the central crater of the volcano bowl and light it.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Flaming_Volcano.jpg/220px-Flaming_Volcano.jpg",
"alcohol": ["Rum","Brandy",],
"ingredients": ["1 oz light rum","1 oz brandy","1 oz overproof rum (e.g. Bacardi 151)","4 oz orange juice","2 oz lemon juice","2 oz almond flavored syrup",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 3},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "French 75",
"recipe": "Combine gin, syrup, and lemon juice in a cocktail shaker filled with ice. Shake vigorously and strain into an iced champagne glass. Top up with Champagne. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/French_75.jpg/220px-French_75.jpg",
"alcohol": ["Champagne","Gin",],
"ingredients": ["1 oz gin","2 dashes simple syrup","½ oz lemon juice","2 oz Champagne",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 6},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Gibson",
"recipe": "*Stir well in a shaker with ice, then strain into a chilled martini glass. Garnish and serve",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Gibson_cocktail.jpg/220px-Gibson_cocktail.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["2 oz gin","½ oz dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Gimlet",
"recipe": "Mix and serve. Garnish with a slice of lime",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Gimlet_cocktail.jpg/220px-Gimlet_cocktail.jpg",
"alcohol": ["Gin","Vodka",],
"ingredients": ["Five parts gin","One part simple syrup","One part sweetened lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 7, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Gin & Tonic",
"recipe": "In a glass filled with ice cubes, add gin and tonic.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/Gin_and_Tonic_with_ingredients.jpg/220px-Gin_and_Tonic_with_ingredients.jpg",
"alcohol": ["Gin",],
"ingredients": ["Gin", "Tonic"],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 6, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 9, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 9, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 8, "dW": 10, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 7, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Godfather",
"recipe": "Pour all ingredients directly into old fashioned glass filled with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Godfather_cocktail.jpg/220px-Godfather_cocktail.jpg",
"alcohol": ["Whiskey","Liqueur",],
"ingredients": ["1 oz scotch whisky","1 oz Disaronno",],
"drinkRating": {
"weatherValue": {"wCold": 9, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 6, "pSome": 8},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 8, "sWin": 9},
"dayValue": {"dMTRS": 7, "dW": 8, "dFS": 4},
"timeValue": {"tMrn": 8, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Golden Dream",
"recipe": "Shake with cracked ice. Strain into glass and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Godlen-Dream_Mixed_Drink_Cocktail_%282360538105%29.jpg/220px-Godlen-Dream_Mixed_Drink_Cocktail_%282360538105%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["¾ oz (2 parts) Galliano","¾ oz (2 parts) Triple Sec","¾ oz (2 parts) Fresh orange juice","½ oz (1 part) Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 7, "wWarm": 7, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 8, "sFal": 5, "sWin": 5},
"dayValue": {"dMTRS": 5, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 10, "tAft": 9, "tNt": 5, "wSleep": 0}
}
},
{"drinkName": "Grasshopper",
"recipe": "Pour ingredients into a cocktail shaker with ice. Shake briskly and then strain into a chilled cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Grasshopper_cocktail.jpg/220px-Grasshopper_cocktail.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 oz Crème de menthe (green)","1 oz Crème de cacao (white)","1 oz Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 8},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 7, "sWin": 5},
"dayValue": {"dMTRS": 5, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Greyhound",
"recipe": "Mix gin and juice, pour over ice in Old Fashioned glass",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Greyhound_Cocktail.jpg/220px-Greyhound_Cocktail.jpg",
"alcohol": ["Gin",],
"ingredients": ["2 oz (1 parts) Gin","7 oz (4 parts) Grapefruit juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 5, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 8, "sSum": 8, "sFal": 8, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 6, "dFS": 6},
"timeValue": {"tMrn": 8, "tAft": 4, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Harvey Wallbanger",
"recipe": "Stir the vodka and orange juice with ice in the glass, then float the Galliano on top. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Harvey_Wallbanger.jpg/220px-Harvey_Wallbanger.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["1½ oz (3 parts) Vodka","½ oz (1 part) Galliano","3 oz (6 parts) fresh orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 7, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 5, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 9, "tAft": 8, "tNt": 6, "wSleep": 0}
}
},
{"drinkName": "Horses Neck",
"recipe": "Pour brandy and ginger ale directly into highball glass with ice cubes. Stir gently. Garnish with lemon zest. If desired, add dashes of Angostura Bitter.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Horse%27s_Neck_cocktail.jpg/220px-Horse%27s_Neck_cocktail.jpg",
"alcohol": ["Brandy",],
"ingredients": ["1½ oz (1 part) Brandy","1¾ oz (3 parts) Ginger ale","Dash of Angostura bitter",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 7, "sFal": 9, "sWin": 9},
"dayValue": {"dMTRS": 7, "dW": 6, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Huckleberry Hound",
"recipe": "Shake ingredients with ice, then pour into the glass and serve over ice - garnish with Montana Huckleberries",
"image": "http://www.trbimg.com/img-538660e1/turbine/ctn-liquor-cabinet-maggie-mcflys-20140528-001/1050/1050x591",
"alcohol": ["Vodka",],
"ingredients": ["2 oz. 44 North Huckleberry Vodka", "1 oz. Huckleberry syrup", "Lemonade or Limeade"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 9, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 4},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 8, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 6, "tNt": 9, "wSleep": 0}
}
},
{"drinkName": "Hurricane",
"recipe": "Shake ingredients with ice, then pour into the glass and serve over ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Hurricane_cocktail.jpg/220px-Hurricane_cocktail.jpg",
"alcohol": ["Rum",],
"ingredients": ["One part dark rum","One part white rum","Half part over proofed rum","Passion fruit syrup","Lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 1, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Irish Car Bomb",
"recipe": "The whiskey is floated on top of the Irish cream in a shot glass, and the shot glass is then dropped into the stout",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/Irish_Car_Bomb.jpg/220px-Irish_Car_Bomb.jpg",
"alcohol": ["Whiskey","Liqueur",],
"ingredients": ["1/2 oz whiskey","1/2 oz Irish cream liqueur","1/2 pint stout",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 5, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 6},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 1, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 0, "tAft": 4, "tNt": 9, "wSleep": 6}
}
},
{"drinkName": "Irish Coffee",
"recipe": "Heat the coffee, whiskey and sugar; do not boil. Pour into glass and top with cream; serve hot.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Irish_coffee_glass.jpg/220px-Irish_coffee_glass.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz (2 parts) Irish whiskey","3 oz (4 parts) hot coffee","1 oz (1½ parts) fresh cream","1tsp brown sugar",],
"drinkRating": {
"weatherValue": {"wCold": 10, "wMod": 8, "wWarm": 2, "wHot": 1},
"precipValue": {"pNone": 3, "pSome": 9},
"seasonValue":{"sSpr": 5, "sSum": 5, "sFal": 8, "sWin": 9},
"dayValue": {"dMTRS": 8, "dW": 5, "dFS": 6},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 2, "wSleep": 2}
}
},
{"drinkName": "Jack Rose",
"recipe": "Traditionally shaken into a chilled glass, garnished, and served straight up.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/15-09-26-RalfR-WLC-0259.jpg/220px-15-09-26-RalfR-WLC-0259.jpg",
"alcohol": ["Brandy",],
"ingredients": ["2 parts applejack","1 part lemon or lime juice","1/2 part grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 4, "wWarm": 5, "wHot": 5},
"precipValue": {"pNone": 4, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 4, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 6, "dW": 4, "dFS": 4},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 6, "wSleep": 0}
}
},
{"drinkName": "Japanese Slipper",
"recipe": "Shake together in a mixer with ice. Strain into glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Japanese_slipper.jpg/220px-Japanese_slipper.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 oz (1 part) Midori","1 oz (1 part) cointreau","1 oz (1 part) lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 3, "wWarm": 5, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 3, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 6, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 8, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Kalimotxo",
"recipe": "Stir together over plenty of ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Porr%C3%B3n_1.jpg/220px-Porr%C3%B3n_1.jpg",
"alcohol": ["Wine",],
"ingredients": ["One part red wine","One part cola",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 7, "wWarm": 7, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 9},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 8, "sWin": 7},
"dayValue": {"dMTRS": 9, "dW": 10, "dFS": 4},
"timeValue": {"tMrn": 1, "tAft": 7, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Kamikaze",
"recipe": "Shake all ingredients together with ice. Strain into glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Kamikaze.jpg/220px-Kamikaze.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["1 oz vodka","1 oz triple sec","1 oz lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 5, "wHot": 5},
"precipValue": {"pNone": 6, "pSome": 6},
"seasonValue":{"sSpr": 4, "sSum": 6, "sFal": 4, "sWin": 6},
"dayValue": {"dMTRS": 0, "dW": 4, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 6, "tNt": 7, "wSleep": 0}
}
},
{"drinkName": "Kentucky Corpse Reviver",
"recipe": "Shake ingredients together with ice, and strain into a glass. Garnish with mint sprig.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8f/Glass02.jpg/50px-Glass02.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1 part Bourbon","1 part Lillet Blanc","1 part Lemon Juice","1 part Cointreau",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 3, "pSome": 9},
"seasonValue":{"sSpr": 10, "sSum": 8, "sFal": 3, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Kir",
"recipe": "Add the crème de cassis to the bottom of the glass, then top up with wine.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Kir_cocktail.jpg/220px-Kir_cocktail.jpg",
"alcohol": ["Wine",],
"ingredients": ["3 oz (9 parts) white wine","½ oz (1 part) crème de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 8},
"seasonValue":{"sSpr": 8, "sSum": 7, "sFal": 4, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 5, "tAft": 5, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Kir Royal",
"recipe": "*Add the crème de cassis to the bottom of the glass, then top up champagne.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Kir_Royal.jpg/220px-Kir_Royal.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3 oz champagne","½ oz crème de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 6, "wHot": 6},
"precipValue": {"pNone": 5, "pSome": 8},
"seasonValue":{"sSpr": 5, "sSum": 5, "sFal": 7, "sWin": 8},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 10, "tAft": 7, "tNt": 2, "wSleep": 0}
}
},
{"drinkName": "Long Island Iced Tea",
"recipe": "Add all ingredients into highball glass filled with ice. Stir gently. Garnish with lemon spiral. Serve with straw.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Long_Island_Iced_Teas.jpg/220px-Long_Island_Iced_Teas.jpg",
"alcohol": ["Gin","Tequila","Vodka","Rum","Liqueur",],
"ingredients": ["½ oz Tequila","½ oz Vodka","½ oz White rum","½ oz Triple sec","½ oz Gin","¾ oz Lemon juice","1 oz Gomme Syrup","1 dash of Cola",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue":{"sSpr": 4, "sSum": 9, "sFal": 8, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 10},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 0}
}
},
{"drinkName": "Lynchburg Lemonade",
"recipe": "Shake first 3 ingredients with ice and strain into ice-filled glass. Top with the lemonade or lemon-lime. Add ice and stir. Garnish with lemon slices and cherries.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Lynchburg_Lemonade%2C_Grindhouse_Killer_Burgers%2C_Atlanta_GA.jpg/220px-Lynchburg_Lemonade%2C_Grindhouse_Killer_Burgers%2C_Atlanta_GA.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1¼ oz Tennessee whiskey", "¾ oz Triple sec", "2 oz Sour mix", "lemon-lime", "lemon slice", "cherries" ],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 2, "wWarm": 5, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 7},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 1, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Mai Tai",
"recipe": "Shake all ingredients with ice. Strain into glass. Garnish and serve with straw.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/Mai_Tai.jpg/220px-Mai_Tai.jpg",
"alcohol": ["Rum","Liqueur",],
"ingredients": ["1½ oz white rum","¾ oz dark rum","½ oz orange curaçao","½ oz Orgeat syrup","½ oz fresh lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 10, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 0}
}
},
{"drinkName": "Manhattan",
"recipe": "Stirred over ice, strained into a chilled glass, garnished, and served up.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/Manhattan_Cocktail2.jpg/220px-Manhattan_Cocktail2.jpg",
"alcohol": ["Whiskey","Vermouth",],
"ingredients": ["2 oz rye","¾ oz Sweet red vermouth","Dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 8, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 9},
"seasonValue":{"sSpr": 7, "sSum": 4, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 7, "dW": 8, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Margarita",
"recipe": "Rub the rim of the glass with the lime slice to make the salt stick. Shake the other ingredients with ice, then carefully pour into the glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/MargaritaReal.jpg/220px-MargaritaReal.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1 oz (7 parts) tequila","¾ oz (4 parts) Cointreau","½ oz (3 parts) lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 8, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue":{"sSpr": 8, "sSum": 10, "sFal": 3, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 7, "tNt": 9, "wSleep": 1}
}
},
{"drinkName": "Martini",
"recipe": "Straight: Pour all ingredients into mixing glass with ice cubes. Stir well. Strain in chilled martini cocktail glass. Squeeze oil from lemon peel onto the drink, or garnish with olive.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/15-09-26-RalfR-WLC-0084.jpg/220px-15-09-26-RalfR-WLC-0084.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["2 oz (6 parts) gin","½ oz (1 parts) dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 7, "wWarm": 8, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 8},
"seasonValue":{"sSpr": 4, "sSum": 6, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 2, "dW": 8, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Mimosa",
"recipe": "Ensure both ingredients are well chilled, then mix into the glass. Serve cold.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Pool-side_Mimosas_at_The_Standard_Hotel.jpg/220px-Pool-side_Mimosas_at_The_Standard_Hotel.jpg",
"alcohol": ["Champagne",],
"ingredients": ["7 oz champagne","2 oz orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 5, "sWin": 4},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 9, "tAft": 4, "tNt": 3, "wSleep": 0}
}
},
{"drinkName": "Mint Julep",
"recipe": "In a highball glass gently muddle the mint, sugar and water. Fill the glass with cracked ice, add Bourbon and stir well until the glass is well frosted. Garnish with a mint sprig.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Mint_Julep_im_Silberbecher.jpg/220px-Mint_Julep_im_Silberbecher.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["2 oz Bourbon whiskey","4 mint leaves","1 teaspoon powdered sugar","2 teaspoons water", "mint sprig"],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 10, "pSome": 2},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 3, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 3, "wSleep": 1}
}
},
{"drinkName": "Monkey Gland",
"recipe": "Shake well over ice cubes in a shaker, strain into a chilled cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Monkey_Gland_%2811677703163%29.jpg/220px-Monkey_Gland_%2811677703163%29.jpg",
"alcohol": ["Gin",],
"ingredients": ["2 oz gin","1 oz orange juice","2 drops absinthe","2 drops grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 9, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 3},
"seasonValue":{"sSpr": 8, "sSum": 6, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 4, "tAft": 6, "tNt": 5, "wSleep": 3}
}
},
{"drinkName": "Moscow Mule",
"recipe": "Combine vodka and ginger beer in a highball glass filled with ice. Add lime juice. Stir gently. Garnish with a lime slice and sprig of mint on the brim of the copper mug.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Moscow_Mule.jpg/220px-Moscow_Mule.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (9 parts) vodka","¼ oz (1 part) lime juice","1¾ oz (24 parts) ginger beer","lime slice", "sprig of mint"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 9, "wSleep": 4}
}
},
{"drinkName": "Negroni",
"recipe": "Stir into glass over ice, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Negroni_served_in_Vancouver_BC.jpg/220px-Negroni_served_in_Vancouver_BC.jpg",
"alcohol": ["Gin","Vermouth","Liqueur",],
"ingredients": ["1 oz gin","1 oz sweet red vermouth","1 oz campari",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 6, "wSleep": 3}
}
},
{"drinkName": "Nikolaschka",
"recipe": "Pour cognac into brandy snifter, place lemon disk across the top of the glass and top with sugar and coffee.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Cocktail_-_Nikolaschka.jpg/220px-Cocktail_-_Nikolaschka.jpg",
"alcohol": ["Brandy",],
"ingredients": ["Cognac","Coffee powder","Powdered sugar","Lemon disk, peeled",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue": {"sSpr": 7, "sSum": 4, "sFal": 8, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 9, "tAft": 6, "tNt": 5, "wSleep": 1}
}
},
{"drinkName": "Old Fashioned",
"recipe": "Place sugar cube in old fashioned glass and saturate with bitters, add a dash of plain water. Muddle until dissolved. Fill the glass with ice cubes and add whiskey. Garnish with orange twist, and a cocktail cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Whiskey_Old_Fashioned1.jpg/220px-Whiskey_Old_Fashioned1.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz Bourbon or Rye whiskey","2 dashes Angostura bitters","1 sugar cube","Few dashes plain water","orange twist", "cocktail cherry"],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 9, "wWarm": 5, "wHot": 4},
"precipValue": {"pNone": 4, "pSome": 7},
"seasonValue": {"sSpr": 4, "sSum": 5, "sFal": 8, "sWin": 7},
"dayValue": {"dMTRS": 9, "dW": 7, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 9, "wSleep": 8}
}
},
{"drinkName": "Orgasm",
"recipe": "Build all ingredients over ice in an old fashioned glass or shot glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Orgasm_%28cocktail%29.jpg/220px-Orgasm_%28cocktail%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["3/4 oz. Amaretto","3/4 oz. Kahlúa","3/4 oz. Baileys Irish Cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 8, "pSome": 2},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 6, "wSleep": 3}
}
},
{"drinkName": "Paradise",
"recipe": "Shake together over ice. Strain into cocktail glass and serve chilled.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Paradise_cocktail.jpg/220px-Paradise_cocktail.jpg",
"alcohol": ["Gin","Brandy",],
"ingredients": ["1 oz (7 parts) gin","¾ oz (4 parts) apricot brandy","½ oz (3 parts) orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue": {"sSpr": 7, "sSum": 8, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 6, "tAft": 7, "tNt": 4, "wSleep": 3}
}
},
{"drinkName": "Piña Colada",
"recipe": "Mix with crushed ice in blender until smooth. Pour into chilled glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Pi%C3%B1a_Colada.jpg/220px-Pi%C3%B1a_Colada.jpg",
"alcohol": ["Rum",],
"ingredients": ["1 oz (one part) white rum","1 oz (one part) coconut milk","3 oz (3 parts) pineapple juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 8, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 1},
"seasonValue": {"sSpr": 8, "sSum": 10, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 8, "tAft": 9, "tNt": 4, "wSleep": 1}
}
},
{"drinkName": "Pink Lady",
"recipe": "Shake ingredients very well with ice and strain into cocktail glass. Garnish with a cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Pink_Lady_with_a_twist_of_lime%2C_in_a_cocktail_glass.jpg/220px-Pink_Lady_with_a_twist_of_lime%2C_in_a_cocktail_glass.jpg",
"alcohol": ["Gin",],
"ingredients": ["1.5 oz. gin","4 dashes grenadine","1 egg white","cherry"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 8, "wHot": 5},
"precipValue": {"pNone": 3, "pSome": 5},
"seasonValue": {"sSpr": 8, "sSum": 7, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 3, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Planters Punch",
"recipe": "Pour all ingredients, except the bitters, into shaker filled with ice. Shake well. Pour into large glass, filled with ice. Add Angostura bitters, on top. Garnish with cocktail cherry and pineapple.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Planters_Punch_2.jpg/220px-Planters_Punch_2.jpg",
"alcohol": ["Rum",],
"ingredients": ["1½ oz Dark rum","1 oz Fresh orange juice","1 oz Fresh pineapple juice","¾ oz Fresh lemon juice","½ oz Grenadine syrup","½ oz Sugar syrup","3 or 4 dashes Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 5, "wHot": 9},
"precipValue": {"pNone": 9, "pSome": 1},
"seasonValue": {"sSpr": 9, "sSum": 8, "sFal": 3, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 6, "tAft": 9, "tNt": 5, "wSleep": 3}
}
},
{"drinkName": "Porto Flip",
"recipe": "Shake ingredients together in a mixer with ice. Strain into glass, garnish and serve",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Porto_Flip.jpg/220px-Porto_Flip.jpg",
"alcohol": ["Wine","Brandy",],
"ingredients": ["½ oz (3 parts) brandy","1½ oz (8 parts) port","½ oz (2 parts) egg yolk",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 9, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 3, "pSome": 7},
"seasonValue": {"sSpr": 5, "sSum": 4, "sFal": 9, "sWin": 8},
"dayValue": {"dMTRS": 3, "dW": 9, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 7, "tNt": 9, "wSleep": 6}
}
},
{"drinkName": "Rickey",
"recipe": "Combine spirit, lime and shell in a highball or wine glass. Add ice, stir and then add sparkling mineral water.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Gin_Rickey.jpg/220px-Gin_Rickey.jpg",
"alcohol": ["Gin","Whiskey",],
"ingredients": ["2oz bourbon, rye whiskey, or gin","Half of a lime","Sparkling mineral water",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 7, "wWarm": 6, "wHot": 3},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Rob Roy",
"recipe": "Stirred over ice, strained into a chilled glass, garnished, and served straight up, or mixed in rocks glass, filled with ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/15-09-26-RalfR-WLC-0266.jpg/220px-15-09-26-RalfR-WLC-0266.jpg",
"alcohol": ["Whiskey","Vermouth",],
"ingredients": ["1½ oz Scotch whisky","¾ oz Sweet vermouth","Dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 9, "wWarm": 5, "wHot": 2},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue": {"sSpr": 5, "sSum": 3, "sFal": 9, "sWin": 8},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 7, "wSleep": 8}
}
},
{"drinkName": "Rose",
"recipe": "Shake together in a cocktail shaker, then strain into chilled glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/Rose_%28cocktail%29.jpg/220px-Rose_%28cocktail%29.jpg",
"alcohol": ["Vermouth","Brandy"],
"ingredients": ["1½ oz (2 parts) dry vermouth","¾ oz (1 parts) Kirsch","3 Dashes Strawberry syrup",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 9, "wWarm": 5, "wHot": 2},
"precipValue": {"pNone": 1, "pSome": 7},
"seasonValue": {"sSpr": 5, "sSum": 3, "sFal": 7, "sWin": 8},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Rusty Nail",
"recipe": "Pour all ingredients directly into old-fashioned glass filled with ice. Stir gently. Garnish with a lemon twist. Serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Rusty_Nail_at_Sparta_Restaurant%2C_Bedford_MA.jpg/220px-Rusty_Nail_at_Sparta_Restaurant%2C_Bedford_MA.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["7.2 oz Scotch Whisky","¾ oz Drambuie",],
"drinkRating": {
"weatherValue": {"wCold": 9, "wMod": 6, "wWarm": 3, "wHot": 1},
"precipValue": {"pNone": 2, "pSome": 7},
"seasonValue": {"sSpr": 2, "sSum": 1, "sFal": 6, "sWin": 8},
"dayValue": {"dMTRS": 4, "dW": 7, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 6, "wSleep": 8}
}
},
{"drinkName": "Sake Bomb",
"recipe": "The shot of sake is dropped into the beer, causing it to fizz violently. The drink should then be consumed immediately.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/71/Sake_bomb_-_man_pounds_table_with_fist.jpg/220px-Sake_bomb_-_man_pounds_table_with_fist.jpg",
"alcohol": ["Wine",],
"ingredients": ["1 pint (~16 parts) beer","1 shot (1.5 parts) sake",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 6, "pSome": 3},
"seasonValue": {"sSpr": 6, "sSum": 7, "sFal": 8, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 1}
}
},
{"drinkName": "Salty Dog",
"recipe": "Shake gin and grapefruit juice in cocktail shaker. Strain into a salt-rimmed highball glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Salty_Dog.jpg/220px-Salty_Dog.jpg",
"alcohol": ["Gin","Vodka",],
"ingredients": ["1½ oz gin or vodka","3½ oz grapefruit juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 2, "pSome": 8},
"seasonValue": {"sSpr": 5, "sSum": 5, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 4},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 5, "wSleep": 6}
}
},
{"drinkName": "Screwdriver",
"recipe": "Mix in a highball glass with ice. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Screwdriver%2C_Birmingham-Shuttlesworth_International_Airport%2C_Birmingham_AL.jpg/220px-Screwdriver%2C_Birmingham-Shuttlesworth_International_Airport%2C_Birmingham_AL.jpg",
"alcohol": ["Vodka",],
"ingredients": ["2 oz (1 part) vodka","3½ oz (2 parts) orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 5, "pSome": 4},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 6, "sWin": 5},
"dayValue": {"dMTRS": 9, "dW": 5, "dFS": 3},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 3, "wSleep": 5}
}
},
{"drinkName": "Sea Breeze",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Cocktail_with_vodka.jpg/220px-Cocktail_with_vodka.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka","1¾ oz Cranberry juice","1 oz Grapefruit juice","lime wedge"],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 9, "pSome": 3},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 4, "wSleep": 3}
}
},
{"drinkName": "Sex on the Beach",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Sex_On_The_Beach.jpg/220px-Sex_On_The_Beach.jpg",
"alcohol": ["Vodka", "Liqueur",],
"ingredients": ["1½ oz Vodka","¾ oz Peach schnapps","1½ oz Orange juice","1½ oz Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 5, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue": {"sSpr": 6, "sSum": 10, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 10},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 3, "wSleep": 2}
}
},
{"drinkName": "Sidecar",
"recipe": "Pour all ingredients into cocktail shaker filled with ice. Shake well and strain into cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Sidecar-cocktail.jpg/220px-Sidecar-cocktail.jpg",
"alcohol": ["Brandy",],
"ingredients": ["2 oz cognac","¾ oz triple sec","¾ oz lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 9, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 3, "pSome": 8},
"seasonValue": {"sSpr": 9, "sSum": 6, "sFal": 5, "sWin": 7},
"dayValue": {"dMTRS": 3, "dW": 4, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 8}
}
},
{"drinkName": "Singapore Sling",
"recipe": "Pour all ingredients into cocktail shaker filled with ice cubes. Shake well. Strain into highball glass. Garnish with pineapple and cocktail cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Singapore_Sling.jpg/220px-Singapore_Sling.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1 oz Gin","½ oz Cherry Liqueur","¼ oz Cointreau","¼ oz DOM Bénédictine","½ oz Grenadine","1¾ oz Pineapple juice","½ oz Fresh lime juice","1 dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 2},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 2, "wSleep": 1}
}
},
{"drinkName": "Slippery Nipple",
"recipe": "Pour the Baileys into a shot glass, then pour the Sambuca on top so that the two liquids do not mix.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Slippery_Nipple.jpg/220px-Slippery_Nipple.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["(1 part) Sambuca","(1 part) Baileys Irish Cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 8, "wHot": 4},
"precipValue": {"pNone": 5, "pSome": 5},
"seasonValue": {"sSpr": 6, "sSum": 7, "sFal": 2, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 4, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Springbokkie",
"recipe": "The Crème de menthe is poured into the shot glass and the Amarula is carefully layered on top.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/74/Amarula_Springbokkie_shooter.jpg/220px-Amarula_Springbokkie_shooter.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["½ oz (1 part) Amarula","1 oz (3 parts) Crème de menthe",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 9, "wHot": 7},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 6},
"timeValue": {"tMrn": 7, "tAft": 9, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Tequila & Tonic",
"recipe": "In a glass filled with ice cubes, add tequila and tonic.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Tequila_%26_Tonic.jpg/220px-Tequila_%26_Tonic.jpg",
"alcohol": ["Tequila",],
"ingredients": ["Tequila","Tonic"],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 8, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 5, "wSleep": 8}
}
},
{"drinkName": "Tequila Sunrise",
"recipe": "Pour the tequila and orange juice into glass over ice. Add the grenadine, which will sink to the bottom. Do not stir. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Tequila_Sunrise_garnished_with_orange_and_cherry_-_Evan_Swigart.jpg/220px-Tequila_Sunrise_garnished_with_orange_and_cherry_-_Evan_Swigart.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1½ oz (3 parts) Tequila","3 oz (6 parts) Orange juice","½ oz (1 part) Grenadine syrup",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 9, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 3, "dFS": 6},
"timeValue": {"tMrn": 10, "tAft": 3, "tNt": 2, "wSleep": 1}
}
},
{"drinkName": "The Last Word",
"recipe": "Shake with ice and strain into a cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/The_Last_Word_cocktail_raised.jpg/220px-The_Last_Word_cocktail_raised.jpg",
"alcohol": ["Liqueur","Gin",],
"ingredients": ["One part gin","One part lime juice","One part green Chartreuse","One part maraschino liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 6, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 3, "pSome": 7},
"seasonValue": {"sSpr": 4, "sSum": 3, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 7, "dW": 4, "dFS": 3},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 5, "wSleep": 6}
}
},
{"drinkName": "Tinto de Verano",
"recipe": "Mix and serve well chilled.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Tinto_de_verano.jpg/220px-Tinto_de_verano.jpg",
"alcohol": ["Wine",],
"ingredients": ["One part red wine","One part Sprite and water(or Gaseosa)",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 8, "wHot": 6},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue": {"sSpr": 7, "sSum": 8, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 9, "tNt": 6, "wSleep": 1}
}
},
{"drinkName": "Tom Collins",
"recipe": "Mix the gin, lemon juice and sugar syrup in a tall glass with ice, top up with soda water, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Tom_Collins_in_Copenhagen.jpg/220px-Tom_Collins_in_Copenhagen.jpg",
"alcohol": ["Gin",],
"ingredients": ["1½ oz (3 parts) Old Tom Gin","1 oz (2 parts) lemon juice","½ oz (1 part) sugar syrup","2 oz (4 parts) carbonated water",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 5, "wWarm": 8, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 3},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 5, "tAft": 9, "tNt": 6, "wSleep": 2}
}
},
{"drinkName": "Vesper",
"recipe": "Shake over ice until well chilled, then strain into a deep goblet and garnish with a thin slice of lemon peel.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/01/Vesper_Martini_%28corrected%29.jpg/220px-Vesper_Martini_%28corrected%29.jpg",
"alcohol": ["Gin","Vodka", "Wine"],
"ingredients": ["2 oz gin","½ oz vodka","¼ oz Lillet Blonde(wine)",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 8, "wWarm": 4, "wHot": 2},
"precipValue": {"pNone": 2, "pSome": 9},
"seasonValue": {"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 9},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Vodka Martini",
"recipe": "Straight: Pour all ingredients into mixing glass with ice cubes. Shake well. Strain in chilled martini cocktail glass. Squeeze oil from lemon peel onto the drink, or garnish with olive.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Vodka_Martini%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg/220px-Vodka_Martini%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg",
"alcohol": ["Vermouth","Vodka",],
"ingredients": ["2 oz (6 parts) vodka","½ oz (1 parts) dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 10, "wWarm": 4, "wHot": 3},
"precipValue": {"pNone": 4, "pSome": 8},
"seasonValue": {"sSpr": 3, "sSum": 5, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 4, "tNt": 10, "wSleep": 9}
}
},
{"drinkName": "Whiskey Sour",
"recipe": "Shake with ice. Strain into chilled glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Whiskey_Sour.jpg/220px-Whiskey_Sour.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz (3 parts) Bourbon whiskey","1 oz (2 parts) fresh lemon juice","½ oz (1 part) Gomme syrup","dash egg white (optional)",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 6, "wWarm": 6, "wHot": 5},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 4, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "White Russian",
"recipe": "Pour coffee liqueur and vodka into an Old Fashioned glass filled with ice. Float fresh cream on top and stir slowly.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/White-Russian.jpg/220px-White-Russian.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["2 oz (5 parts) Vodka","¾ oz (2 parts) Coffee liqueur","1 oz (3 parts) fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 3},
"seasonValue": {"sSpr": 7, "sSum": 7, "sFal": 9, "sWin": 3},
"dayValue": {"dMTRS": 7, "dW": 10, "dFS": 4},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Zombie",
"recipe": "Mix ingredients other than the 151 in a shaker with ice. Pour into glass and top with the high-proof rum.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Zombiecocktail.jpg/220px-Zombiecocktail.jpg",
"alcohol": ["Brandy","Rum",],
"ingredients": ["1 part white rum","1 part golden rum","1 part dark rum","1 part apricot brandy","1 part pineapple juice","½ part 151-proof rum","1 part lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 7, "wHot": 10},
"precipValue": {"pNone": 8, "pSome": 1},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 1, "dW": 4, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 10, "tNt": 6, "wSleep": 1}
}
}]
module.exports = AllDrinks; | srs1212/drinkSync | AllDrinks.js | JavaScript | mit | 69,466 |
;(function(){
'use strict';
angular.module('TTT')
.config(function($routeProvider){
$routeProvider
.when('/emu',{
templateUrl: 'views/emu.html',
controller: 'emuController',
controllerAs: 'emu'
});
});
})();
| beck410/GJ_Timetravel | app/js/config/emu.config.js | JavaScript | mit | 247 |
(function (window) {
'use strict';
var applicationModuleName = 'mean';
var service = {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: ['ngResource', 'ngAnimate', 'ngMessages', 'ui.router', 'angularFileUpload', 'ngMaterial'],
registerModule: registerModule
};
window.ApplicationConfiguration = service;
// Add a new vertical module
function registerModule(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
}
}(window));
| tennosys/autoworks | modules/core/client/app/config.js | JavaScript | mit | 674 |
(function (require) {
var test = require('test'),
asyncTest = require('asyncTest'),
start = require('start'),
module = require('module'),
ok = require('ok'),
expect = require('expect'),
$ = require('$'),
document = require('document'),
raises = require('raises'),
rnd = '?' + Math.random(),
ENV_NAME = require('worker_some_global_var') ? 'Worker' : require('node_some_global_var') ? 'Node' : 'DOM';
function getComputedStyle(element, rule) {
if(document.defaultView && document.defaultView.getComputedStyle){
return document.defaultView.getComputedStyle(element, "").getPropertyValue(rule);
}
rule = rule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
return element.currentStyle[rule];
}
module('LMD loader @ ' + ENV_NAME);
asyncTest("require.js()", function () {
expect(6);
require.js('./modules/loader/non_lmd_module.js' + rnd, function (script_tag) {
ok(typeof script_tag === "object" &&
script_tag.nodeName.toUpperCase() === "SCRIPT", "should return script tag on success");
ok(require('some_function')() === true, "we can grab content of the loaded script");
ok(require('./modules/loader/non_lmd_module.js' + rnd) === script_tag, "should cache script tag on success");
// some external
require.js('http://yandex.ru/jquery.js' + rnd, function (script_tag) {
ok(typeof script_tag === "undefined", "should return undefined on error in 3 seconds");
ok(typeof require('http://yandex.ru/jquery.js' + rnd) === "undefined", "should not cache errorous modules");
require.js('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.js() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
});
asyncTest("require.js() JSON callback and chain calls", function () {
expect(2);
var id = require('setTimeout')(function () {
ok(false, 'JSONP call fails');
start();
}, 3000);
require('window').someJsonHandler = function (result) {
ok(result.ok, 'JSON called');
require('window').someJsonHandler = null;
require('clearTimeout')(id);
start();
};
var requireReturned = require.js('./modules/loader/non_lmd_module.jsonp.js' + rnd);
ok(typeof requireReturned === "function", "require.js() must return require");
});
asyncTest("require.js() race calls", function () {
expect(1);
var result;
var check_result = function (scriptTag) {
if (typeof result === "undefined") {
result = scriptTag;
} else {
ok(result === scriptTag, "Must perform one call. Results must be the same");
start();
}
};
require.js('./modules/loader_race/non_lmd_module.js' + rnd, check_result);
require.js('./modules/loader_race/non_lmd_module.js' + rnd, check_result);
});
asyncTest("require.js() shortcut", function () {
expect(5);
require.js('sk_js_js', function (script_tag) {
ok(typeof script_tag === "object" &&
script_tag.nodeName.toUpperCase() === "SCRIPT", "should return script tag on success");
ok(require('sk_js_js') === script_tag, "require should return the same result");
require.js('sk_js_js', function (script_tag2) {
ok(script_tag2 === script_tag, 'should load once');
ok(require('sk_js_js') === require('/modules/shortcuts/js.js'), "should be defined using path-to-module");
ok(typeof require('shortcuts_js') === "function", 'Should create a global function shortcuts_js as in module function');
start();
})
});
});
// -- CSS
asyncTest("require.css()", function () {
expect(4);
require.css('./modules/loader/some_css.css' + rnd, function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(getComputedStyle(document.getElementById('qunit-fixture'), 'visibility') === "hidden", "css should be applied");
ok(require('./modules/loader/some_css.css' + rnd) === link_tag, "should cache link tag on success");
require.css('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.css() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
asyncTest("require.css() CSS loader without callback", function () {
expect(1);
var requireReturned = require
.css('./modules/loader/some_css_callbackless.css' + rnd)
.css('./modules/loader/some_css_callbackless.css' + rnd + 1);
ok(typeof requireReturned === "function", "require.css() must return require");
start();
});
asyncTest("require.css() race calls", function () {
expect(1);
var result;
var check_result = function (linkTag) {
if (typeof result === "undefined") {
result = linkTag;
} else {
ok(result === linkTag, "Must perform one call. Results must be the same");
start();
}
};
require.css('./modules/loader_race/some_css.css' + rnd, check_result);
require.css('./modules/loader_race/some_css.css' + rnd, check_result);
});
asyncTest("require.css() shortcut", function () {
expect(4);
require.css('sk_css_css', function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(require('sk_css_css') === link_tag, "require should return the same result");
require.css('sk_css_css', function (link_tag2) {
ok(link_tag2 === link_tag, 'should load once');
ok(require('sk_css_css') === require('/modules/shortcuts/css.css'), "should be defined using path-to-module");
start();
})
});
});
asyncTest("require.css() cross origin", function () {
expect(2);
require.css('sk_css_xdomain', function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(getComputedStyle(document.body, 'min-width') === "960px", "css should be applied");
start();
});
});
// -- image
asyncTest("require.image()", function () {
expect(5);
require.image('./modules/loader/image.gif' + rnd, function (img_tag) {
ok(typeof img_tag === "object" &&
img_tag.nodeName.toUpperCase() === "IMG", "should return img tag on success");
ok(require('./modules/loader/image.gif' + rnd) === img_tag, "should cache img tag on success");
require.image('./modules/loader/image_404.gif' + rnd, function (img_tag) {
ok(typeof img_tag === "undefined", "should return undefined on error in 3 seconds");
ok(typeof require('./modules/loader/image_404.gif' + rnd) === "undefined", "should not cache errorous modules");
require.image('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.image() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
});
asyncTest("require.image() image loader without callback", function () {
expect(1);
var requireReturned = require
.image('./modules/loader/image_callbackless.gif' + rnd)
.image('./modules/loader/image_callbackless.gif' + rnd + 1);
ok(typeof requireReturned === "function", "require.image() must return require");
start();
});
asyncTest("require.image() race calls", function () {
expect(1);
var result;
var check_result = function (linkTag) {
if (typeof result === "undefined") {
result = linkTag;
} else {
ok(result === linkTag, "Must perform one call. Results must be the same");
start();
}
};
require.image('./modules/loader_race/image.gif' + rnd, check_result);
require.image('./modules/loader_race/image.gif' + rnd, check_result);
});
asyncTest("require.image() shortcut", function () {
expect(4);
require.image('sk_image_image', function (img_tag) {
ok(typeof img_tag === "object" &&
img_tag.nodeName.toUpperCase() === "IMG", "should return img tag on success");
ok(require('sk_image_image') === img_tag, "require should return the same result");
require.image('sk_image_image', function (img_tag2) {
ok(img_tag2 === img_tag, 'should load once');
ok(require('sk_image_image') === require('/modules/shortcuts/image.gif'), "should be defined using path-to-module");
start();
})
});
});
}) | pierrec/js-xxhash | node_modules/lmd/test/qunit/modules/test_case/testcase_lmd_loader/testcase_lmd_loader.js | JavaScript | mit | 10,330 |
/*
The main entry point for the client side of the app
*/
// Create the main app object
this.App = {};
// Create the needed collections on the client side
this.Surprises = new Meteor.Collection("surprises");
// Subscribe to the publishes in server/collections
Meteor.subscribe('surprises');
// Start the app
Meteor.startup(function() {
$(function() {
App.routes = new Routes();
});
});
| angelwong/giftedfromus | client/js/main.js | JavaScript | mit | 405 |
// Copyright (c) 2016, Frappe Technologies and contributors
// For license information, please see license.txt
frappe.ui.form.on('Address Template', {
refresh: function(frm) {
if(frm.is_new() && !frm.doc.template) {
// set default template via js so that it is translated
frappe.call({
method: 'frappe.geo.doctype.address_template.address_template.get_default_address_template',
callback: function(r) {
frm.set_value('template', r.message);
}
});
}
}
});
| rohitwaghchaure/frappe | frappe/geo/doctype/address_template/address_template.js | JavaScript | mit | 488 |
/**
* A debounce method that has a sliding window, there's a minimum and maximum wait time
**/
module.exports = function (cb, min, max, settings) {
var ctx, args, next, limit, timeout;
if (!settings) {
settings = {};
}
function fire() {
limit = null;
cb.apply(settings.context || ctx, args);
}
function run() {
var now = Date.now();
if (now >= limit || now >= next) {
fire();
} else {
timeout = setTimeout(run, Math.min(limit, next) - now);
}
}
let fn = function windowed() {
var now = Date.now();
ctx = this;
args = arguments;
next = now + min;
if (!limit) {
limit = now + max;
timeout = setTimeout(run, min);
}
};
fn.clear = function () {
clearTimeout(timeout);
timeout = null;
limit = null;
};
fn.flush = function () {
fire();
fn.clear();
};
fn.shift = function (diff) {
limit += diff;
};
fn.active = function () {
return !!limit;
};
return fn;
};
| b-heilman/bmoor | src/flow/window.js | JavaScript | mit | 935 |
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
mocha = require('gulp-mocha'),
cover = require('gulp-coverage'),
jscs = require('gulp-jscs');
gulp.task('default', ['jscs', 'lint', 'test'], function () {
});
gulp.task('lint', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default', {verbose: true}));
});
gulp.task('test', ['jscs', 'lint'], function () {
return gulp.src('./test', {read: false})
.pipe(cover.instrument({
pattern: ['*lib/*.js'],
debugDirectory: 'debug'
}))
.pipe(mocha({reporter: 'nyan'}))
.pipe(cover.gather())
.pipe(cover.format())
.pipe(gulp.dest('reports'));
});
gulp.task('jscs', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jscs());
});
| olavhaugen/telldus-live-promise | gulpfile.js | JavaScript | mit | 875 |
if (typeof window !== 'undefined') {
var less = require('npm:less/lib/less-browser/index')(window, window.less || {})
var head = document.getElementsByTagName('head')[0];
// get all injected style tags in the page
var styles = document.getElementsByTagName('style');
var styleIds = [];
for (var i = 0; i < styles.length; i++) {
if (!styles[i].hasAttribute("data-href")) continue;
styleIds.push(styles[i].getAttribute("data-href"));
}
var loadStyle = function (url) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = request.responseText;
var options = window.less || {};
options.filename = url;
options.rootpath = url.replace(/[^\/]*$/, '');
//render it using less
less.render(data, options).then(function (data) {
//inject it into the head as a style tag
var style = document.createElement('style');
style.textContent = '\r\n' + data.css;
style.setAttribute('type', 'text/css');
//store original type in the data-type attribute
style.setAttribute('data-type', 'text/less');
//store the url in the data-href attribute
style.setAttribute('data-href', url);
head.appendChild(style);
resolve('');
});
} else {
// We reached our target server, but it returned an error
reject()
}
};
request.onerror = function (e) {
reject(e)
};
request.send();
});
}
exports.fetch = function (load) {
// don't reload styles loaded in the head
for (var i = 0; i < styleIds.length; i++)
if (load.address == styleIds[i])
return '';
return loadStyle(load.address);
}
}
else {
exports.translate = function (load) {
// setting format = 'defined' means we're managing our own output
load.metadata.format = 'defined';
};
exports.bundle = function (loads, opts) {
var loader = this;
if (loader.buildCSS === false)
return '';
return loader.import('./less-builder', {name: module.id}).then(function (builder) {
return builder.call(loader, loads, opts);
});
}
}
| Aaike/jspm-less-plugin | less.js | JavaScript | mit | 2,820 |
(function () {
"use strict";
angular.module("myApp.components.notifications")
.factory("KudosNotificationService", KudosNotificationService);
KudosNotificationService.$inject = [
"Transaction"
];
function KudosNotificationService(transactionBackend) {
var service = {
getNewTransactions: getNewTransactions,
setLastTransaction: setLastSeenTransaction
};
return service;
function getNewTransactions() {
return transactionBackend.getNewTransactions()
}
function setLastSeenTransaction(timestamp) {
return transactionBackend.setLastSeenTransactionTimestamp(timestamp)
}
}
})(); | open-kudos/open-kudos-intern-web | src/app/components/kudos-notifications-transaction/kudos-notification-transaction.service.js | JavaScript | mit | 722 |
/**
(function(){
window.saveUser();
saveBlog();
var util_v1 = new window.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
})();
**/
/**
(function(w){
w.saveUser();
saveBlog();
var util_v1 = new w.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
})(window);
*/
/**
$(function(w){
w.saveUser();
saveBlog();
var util_v1 = new w.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
}(window));
*/
//最保险的方式
$(function(){
window.saveUser();
saveBlog();
var util_v1 = new window.util_v1();
util_v1.ajax();
test1();
test2();
test3();
test4();
});
//note: 当在$(function(){window.test=fn;});赋值到window时,只能在$(function(){})中调用到window.test!
//ques:
/**Q1
$(function(){
window.test = function(){
alert('test');
};
});
// ok
$(function(){
test();
});
// fail
$(function(w){
w.test();
}(window));
// fail
(function(){
test();
})();
*/
| rainbowCN/soul | javascript/research/JS 10 Share/Javascript技术研究第1讲《JS代码的组织》/app2.js | JavaScript | mit | 1,127 |
Template.login.events({
'submit form': function(){
event.preventDefault();
var email = event.target.email.value;
var password = event.target.password.value;
//error handling
Meteor.loginWithPassword(email, password, function(error){
if (error) {
alert(error.reason);
} else{
Router.go('/');
};
});
}
}); | quanbinn/healthygeek | client/templates/login.js | JavaScript | mit | 336 |
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// Flags: --expose_externalize_string
'use strict';
const common = require('../common');
const assert = require('assert');
const path = require('path');
const fs = require('fs');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const fn = path.join(tmpdir.path, 'write.txt');
const fn2 = path.join(tmpdir.path, 'write2.txt');
const fn3 = path.join(tmpdir.path, 'write3.txt');
const expected = 'ümlaut.';
const constants = fs.constants;
/* eslint-disable no-undef */
common.allowGlobals(externalizeString, isOneByteString, x);
{
const expected = 'ümlaut eins'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'latin1');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'latin1'));
}
{
const expected = 'ümlaut zwei'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
{
const expected = '中文 1'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'ucs2');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'ucs2'));
}
{
const expected = '中文 2'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
/* eslint-enable no-undef */
fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn, 'utf8');
fs.unlinkSync(fn);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
const args = constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC;
fs.open(fn2, args, 0o644, common.mustCall((err, fd) => {
assert.ifError(err);
const done = common.mustCall((err, written) => {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn2, 'utf8');
fs.unlinkSync(fn2);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
fs.open(fn3, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
});
fs.write(fd, expected, done);
}));
[false, 'test', {}, [], null, undefined].forEach((i) => {
common.expectsError(
() => fs.write(i, common.mustNotCall()),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
common.expectsError(
() => fs.writeSync(i),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
});
| MTASZTAKI/ApertusVR | plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-fs-write.js | JavaScript | mit | 4,815 |
/**
* @generated-from ./$execute.test.js
* This file is autogenerated from a template. Please do not edit it directly.
* To rebuild it from its template use the command
* > npm run generate
* More information can be found in CONTRIBUTING.md
*/
/* eslint-disable no-unused-vars */
import { asyncExecute } from '../..'
describe('asyncExecute', () => {
it('executes forever', async () => {
const iter = asyncExecute(() => 1)
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
})
it('can be passed additional arguments', async () => {
const iter = asyncExecute((a, b) => a + b + 1, 4, 6)
expect((await iter.next())).toEqual({
value: 11,
done: false
})
expect((await iter.next())).toEqual({
value: 11,
done: false
})
expect((await iter.next())).toEqual({
value: 11,
done: false
})
})
it('executes forever (with promise value)', async () => {
const iter = asyncExecute(() => Promise.resolve(1))
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
expect((await iter.next())).toEqual({
value: 1,
done: false
})
})
})
| sithmel/iter-tools | src/__tests__/async-execute.test.js | JavaScript | mit | 1,434 |
var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attribute ? ' media="' + attribute + '" ' : '';
return '<style' + attribute + '>\n' + String(contents) + '\n</style>';
},
filter: function(el) {
return el.attr('rel') === 'stylesheet' && isLocal(el.attr('href'));
},
getSrc: function(el) {
return el.attr('href');
}
},
js: {
tag: 'script',
template: function(contents) {
return '<script type="text/javascript">\n' + String(contents) + '\n</script>';
},
filter: function(el) {
return isLocal(el.attr('src'));
},
getSrc: function(el) {
return el.attr('src');
}
},
img: {
tag: 'img',
template: function(contents, el) {
el.attr('src', 'data:image/unknown;base64,' + contents.toString('base64'));
return cheerio.html(el);
},
filter: function(el) {
var src = el.attr('src');
return !/\.svg$/.test(src);
},
getSrc: function(el) {
return el.attr('src');
}
},
svg: {
tag: 'img',
template: function(contents) {
return String(contents);
},
filter: function(el) {
var src = el.attr('src');
return /\.svg$/.test(src) && isLocal(src);
},
getSrc: function(el) {
return el.attr('src');
}
}
};
function noop() {
return through.obj(function(file, enc, cb) {
this.push(file);
cb();
});
}
function after(n, cb) {
var i = 0;
return function() {
i++;
if(i === n) cb.apply(this, arguments);
};
}
function isLocal(href) {
return href && href.slice(0, 2) !== '//' && ! url.parse(href).hostname;
}
function replace(el, tmpl) {
return through.obj(function(file, enc, cb) {
el.replaceWith(tmpl(file.contents, el));
this.push(file);
cb();
});
}
function inject($, process, base, cb, opts, relative, ignoredFiles) {
var items = [];
$(opts.tag).each(function(idx, el) {
el = $(el);
if(opts.filter(el)) {
items.push(el);
}
});
if(items.length) {
var done = after(items.length, cb);
items.forEach(function(el) {
var src = opts.getSrc(el) || '';
var file = path.join(src[0] === '/' ? base : relative, src);
if (fs.existsSync(file) && ignoredFiles.indexOf(src) === -1) {
gulp.src(file)
.pipe(process || noop())
.pipe(replace(el, opts.template))
.pipe(through.obj(function(file, enc, cb) {
cb();
}, done));
} else {
done();
}
});
} else {
cb();
}
}
module.exports = function(opts) {
opts = opts || {};
opts.base = opts.base || '';
opts.ignore = opts.ignore || [];
opts.disabledTypes = opts.disabledTypes || [];
return through.obj(function(file, enc, cb) {
var self = this;
var $ = cheerio.load(String(file.contents), {decodeEntities: false});
var typeKeys = Object.getOwnPropertyNames(typeMap);
var done = after(typeKeys.length, function() {
file.contents = new Buffer($.html());
self.push(file);
cb();
});
typeKeys.forEach(function(type) {
if (opts.disabledTypes.indexOf(type) === -1) {
inject($, opts[type], opts.base, done, typeMap[type], path.dirname(file.path), opts.ignore);
} else {
done();
}
});
});
};
| jonnyscholes/gulp-inline | index.js | JavaScript | mit | 3,543 |
'use strict';
angular.module('app.directives')
.directive('questionBlock',function() {
return {
restrict: 'E',
scope: {
question:'='
},
templateUrl:'/directives/questions/question-block.html'
};
});
| pwithers/agrippa | public/js/directives/question-block.js | JavaScript | mit | 244 |
'use strict';
var _ = require('lodash');
var utils = require('../utils');
var d3 = require('d3');
var sunCalc = require('suncalc');
var geocoder = require('geocoder');
var Path = require('svg-path-generator');
var margin = {
top: 20,
right: 0,
bottom: 20,
left: 0
};
var dayOfYear = function(d) {
var j1 = new Date(d);
j1.setMonth(0, 0);
return Math.round((d - j1) / 8.64e7) - 1;
};
/*
* View controller
*/
function Viz($el) {
if (!(this instanceof Viz)) {
return new Viz($el);
}
this.$el = $el;
var $tooltip = $('#tooltip');
// do some cool vizualization here
var width = $el.width() - margin.left - margin.right;
var height = (Math.min(width * 0.6, $(document).height() - $el.offset().top - 180)) - margin.top - margin.bottom;
var today = new Date();
var start = new Date(today.getFullYear(), 0, 1, 12, 0, 0, 0, 0);
var end = new Date(today.getFullYear(), 11, 31, 12, 0, 0, 0, 0);
var dateX = d3.time.scale().domain([start, end]).range([0, width]);
this.x = d3.scale.linear()
.domain([0, 365])
.range([0, width]);
this.y = d3.scale.linear()
.domain([0, 24])
.range([0, height]);
var inverseX = d3.scale.linear()
.range([0, 365])
.domain([0, width]);
var xAxis = d3.svg.axis()
.scale(dateX);
var svg = d3.select($el[0])
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.classed('container', true)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var self = this;
var hideTimeout;
svg.on('mousemove', function() {
if(!self.times.length) {
return;
}
var coordinates = d3.mouse(this);
var x = coordinates[0];
var i = inverseX(x);
i = Math.floor(i);
self.svg.selectAll('g.day').classed('hover', function(d, idx) {
return idx === i;
});
var format = d3.time.format('%B %e');
$tooltip.find('.date').text(format(self.dates[i]));
var sunset = new Date(self.times[i].sunset);
var sunrise = new Date(self.times[i].sunrise);
format = d3.time.format('%I:%M %p');
console.log(format(sunrise));
console.log(format(sunset));
$tooltip.find('.sunrise').text(format(sunrise));
$tooltip.find('.sunset').text(format(sunset));
var offset = self.$el.offset();
var top = offset.top;
top += self.y(sunrise.getHours() + sunrise.getMinutes() / 60);
var left = self.x(i) + offset.left;
left -= $tooltip.width() / 2;
top -= $tooltip.height() - 15;
$tooltip.css('top', top).css('left', left).show();
clearTimeout(hideTimeout);
}).on('mouseout', function(){
hideTimeout = setTimeout(function() {
$tooltip.fadeOut();
self.svg.selectAll('g.day').classed('hover', false);
}, 750);
});
d3.select($tooltip[0]).on('mouseenter', function() {
clearTimeout(hideTimeout);
});
this.svg = svg;
svg.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
var max = 0;
for (var d = start, i=0; d < end; d.setDate(d.getDate() + 1), i++) {
this._drawDay(i);
if(i > max) {
max = i;
}
}
var avgGroup = this.svg.append('g').classed('average', true);
avgGroup
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(12))
.horizontalLineTo(self.x(max))
.end();
})
.classed('sunrise', true);
avgGroup
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(12))
.horizontalLineTo(self.x(max))
.end();
})
.classed('sunset', true);
avgGroup
.append('text')
.attr('x', self.x(50))
.attr('y', self.y(12))
.style('opacity', 0)
.classed('sunrise', true);
avgGroup
.append('text')
.attr('x', self.x(250))
.attr('y', self.y(12))
.style('opacity', 0)
.classed('sunset', true);
this.svg
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(today.getHours() + today.getMinutes() / 60))
.horizontalLineTo(self.x(max))
.end();
})
.classed('now', true);
}
Viz.prototype.updatePlace = function(placeName) {
var self = this;
if(placeName.trim() === '') {
return;
}
var times = [];
var dates = [];
geocoder.geocode(placeName, function(err, res) {
if(err) {
return console.log(err);
}
if(!res.results.length) {
return $('.place-name-container').text('Could not find ' + placeName + '!');
}
$('.place-name-container').text(res.results[0].formatted_address);
var location = res.results[0].geometry.location;
var today = new Date();
var start = new Date(today.getFullYear(), 0, 1, 12, 0, 0, 0, 0);
var end = new Date(today.getFullYear()+1, 0, 1, 12, 0, 0, 0, 0);
for (var d = start, i=0; d < end; d.setDate(d.getDate() + 1), i++) {
var time = sunCalc.getTimes(d, location.lat, location.lng);
var isToday = false;
if(d.getDate() === today.getDate() && d.getMonth() === today.getMonth()) {
console.log('Today!');
console.log(d);
isToday = true;
}
self._updateToday(time);
self._updateLine(i, time, isToday);
times.push(time);
dates.push(new Date(d));
}
self._updateAverages(times);
});
this.times = times;
this.dates = dates;
};
Viz.prototype._updateToday = function(times) {
};
Viz.prototype._updateAverages = function(times) {
var avgSunrise = 0, avgSunset = 0;
_.each(times, function(time, i) {
var sunrise = new Date(time.sunrise);
var sunset = new Date(time.sunset);
if(sunset.getDate() !== sunrise.getDate()) {
if(dayOfYear(sunrise) !== i) {
avgSunrise -= 24;
} else {
avgSunset += 24;
}
}
avgSunset += sunset.getHours() + sunset.getMinutes() / 60;
avgSunrise += sunrise.getHours() + sunrise.getMinutes() / 60;
});
avgSunset /= times.length;
avgSunrise /= times.length;
avgSunrise = (avgSunrise + 24) % 24;
avgSunset = (avgSunset + 24) % 24;
var avg = this.svg.select('g.average');
var self = this;
avg.select('path.sunrise')
.transition()
.delay(150)
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(avgSunrise))
.horizontalLineTo(self.x(times.length))
.end();
});
avg.select('path.sunset')
.transition()
.delay(150)
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(avgSunset))
.horizontalLineTo(self.x(times.length))
.end();
});
var format = d3.time.format('%I:%M %p');
var getTimeZone = function() {
return /\((.*)\)/.exec(new Date().toString())[1];
};
var formatHour = function(n) {
var d = new Date();
var hour = Math.floor(n);
var minutes = n - Math.floor(n);
minutes = Math.round(minutes * 60);
d.setHours(hour);
d.setMinutes(minutes);
return format(d) + ' (' + getTimeZone() + ')';
};
avg.select('text.sunrise')
.transition()
.delay(150)
.duration(1500)
.style('opacity', 1)
.attr('y', function() {
if(avgSunrise < 4) {
return self.y(avgSunrise) + 20;
}
return self.y(avgSunrise) - 7;
})
.text(function() {
return 'Average Sunrise: ' + formatHour(avgSunrise);
});
avg.select('text.sunset')
.transition()
.delay(150)
.duration(1500)
.style('opacity', 1).attr('y', function() {
if(avgSunset < 4) {
return self.y(avgSunset) + 20;
}
return self.y(avgSunset) - 7;
})
.text(function() {
return 'Average Sunset: ' + formatHour(avgSunset);
});
};
Viz.prototype._updateLine = function(i, times, today) {
var sunrise = new Date(times.sunrise);
var sunset = new Date(times.sunset);
today = today || false;
var self = this;
var group = this.svg.selectAll('g.day').filter(function(d, idx) {
return i === idx;
});
var start = self.y(sunrise.getHours() + sunrise.getMinutes() / 60);
var end = self.y(sunset.getHours() + sunset.getMinutes() / 60);
if(start < end) {
group
.select('path.day')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), start)
.verticalLineTo(end)
.end();
});
group
.select('path.day-wrap')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), self.y(24))
.verticalLineTo(self.y(24))
.end();
})
.style('stroke-width', 0);
} else {
group
.select('path.day')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), 0)
.verticalLineTo(end)
.end();
});
group
.select('path.day-wrap')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), start)
.verticalLineTo(self.y(24))
.end();
})
.style('stroke-width', (today) ? 2 : 0.5);
}
}
Viz.prototype._drawDay = function(i) {
var today = dayOfYear(new Date()) === i;
var self = this;
var group = this.svg.append('g').classed('day', true);
group
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(i + 0.5), self.y(11.9))
.verticalLineTo(self.y(12.1))
.end();
})
// .style('stroke-width', self.x(i+1) - self.x(i) - .5)
.style('stroke-width', function() {
if(today) {
return 2;
}
return 0.5;
})
.classed('day', true)
.classed('today', today);
group
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(i + 0.5), self.y(24))
.verticalLineTo(self.y(24))
.end();
})
.classed('day-wrap', true)
.classed('today', today);
};
Viz.prototype.destroy = function() {
// destroy d3 object
};
module.exports = Viz;
| mathisonian/sunrise | src/js/viz/viz.js | JavaScript | mit | 11,928 |
// All symbols in the `Runic` script as per Unicode v10.0.0:
[
'\u16A0',
'\u16A1',
'\u16A2',
'\u16A3',
'\u16A4',
'\u16A5',
'\u16A6',
'\u16A7',
'\u16A8',
'\u16A9',
'\u16AA',
'\u16AB',
'\u16AC',
'\u16AD',
'\u16AE',
'\u16AF',
'\u16B0',
'\u16B1',
'\u16B2',
'\u16B3',
'\u16B4',
'\u16B5',
'\u16B6',
'\u16B7',
'\u16B8',
'\u16B9',
'\u16BA',
'\u16BB',
'\u16BC',
'\u16BD',
'\u16BE',
'\u16BF',
'\u16C0',
'\u16C1',
'\u16C2',
'\u16C3',
'\u16C4',
'\u16C5',
'\u16C6',
'\u16C7',
'\u16C8',
'\u16C9',
'\u16CA',
'\u16CB',
'\u16CC',
'\u16CD',
'\u16CE',
'\u16CF',
'\u16D0',
'\u16D1',
'\u16D2',
'\u16D3',
'\u16D4',
'\u16D5',
'\u16D6',
'\u16D7',
'\u16D8',
'\u16D9',
'\u16DA',
'\u16DB',
'\u16DC',
'\u16DD',
'\u16DE',
'\u16DF',
'\u16E0',
'\u16E1',
'\u16E2',
'\u16E3',
'\u16E4',
'\u16E5',
'\u16E6',
'\u16E7',
'\u16E8',
'\u16E9',
'\u16EA',
'\u16EE',
'\u16EF',
'\u16F0',
'\u16F1',
'\u16F2',
'\u16F3',
'\u16F4',
'\u16F5',
'\u16F6',
'\u16F7',
'\u16F8'
]; | mathiasbynens/unicode-data | 10.0.0/scripts/Runic-symbols.js | JavaScript | mit | 1,010 |
/**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _storage = {};
function getPath(options) {
if(options.prefix) {
return path.join(_defaultDir, options.prefix, options.fileName);
}
return path.join(_defaultDir, options.fileName);
}
function ensureDirectoryExists(dir) {
if (!fs.existsSync(dir)){
mkdirp.sync(dir);
}
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(path.join(_defaultDir, prefix));
}
ensureDirectoryExists(_defaultDir);
const Storage = {};
Storage.set = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
_storage[file] = options.value;
fs.writeFile(file, options.value, callback);
};
Storage.get = function(options, callback) {
const file = getPath(options);
if(file in _storage) {
callback(null, _storage[file]);
return;
}
fs.readFile(file, callback);
};
Storage.append = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
if(!(file in _storage)) {
_storage[file] = [];
}
_storage[file].push(options.value);
fs.appendFile(file, options.value, callback);
};
Storage.delete = function(options, callback) {
const file = getPath(options);
delete _storage[file];
fs.unlink(file, callback);
};
module.exports = Storage;
| scholtzm/punk | src/utils/storage.js | JavaScript | mit | 1,642 |
'use strict';
/* global $: true */
/* global animation: true */
/* global boidWeights: true */
//Slider for selecting initial number of boids
//---------------------------------------------
$('#numBoidsSlider').slider({
min: 0,
max: 400,
step: 10,
value: animation.numBoids
});
$('#numBoidsVal').text(animation.numBoids);
$('#numBoidsSlider').on('slide', function (slideEvt) {
$('#numBoidsVal').text(slideEvt.value);
animation.numBoids = slideEvt.value;
});
//Sliders for weights
//--------------------
$('#slider1').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.separation
});
$('#slider1val').text(boidWeights.separation);
$('#slider1').on('slide', function (slideEvt) {
$('#slider1val').text(slideEvt.value);
boidWeights.separation = slideEvt.value;
});
$('#slider2').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.alginment
});
$('#slider2').on('slide', function (slideEvt) {
$('#slider2val').text(boidWeights.alginment);
$('#slider2val').text(slideEvt.value);
boidWeights.alginment = slideEvt.value;
});
$('#slider3').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.cohesion
});
$('#slider3val').text(boidWeights.cohesion);
$('#slider3').on('slide', function (slideEvt) {
$('#slider3val').text(slideEvt.value);
boidWeights.cohesion = slideEvt.value;
});
$('#slider4').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.obstacle
});
$('#slider4val').text(boidWeights.obstacle);
$('#slider4').on('slide', function (slideEvt) {
$('#slider4val').text(slideEvt.value);
boidWeights.obstacle = slideEvt.value;
});
$('#slider5').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.predators
});
$('#slider5val').text(boidWeights.predators);
$('#slider5').on('slide', function (slideEvt) {
$('#slider5val').text(slideEvt.value);
boidWeights.predators = slideEvt.value;
});
| johhat/boids | ui-components/ui.js | JavaScript | mit | 1,967 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'iframe', 'ko', {
border: '프레임 테두리 표시',
noUrl: '아이프레임 주소(URL)를 입력해주세요.',
scrolling: '스크롤바 사용',
title: '아이프레임 속성',
toolbar: '아이프레임'
} );
| otto-torino/gino | ckeditor/plugins/iframe/lang/ko.js | JavaScript | mit | 424 |
/**
* Hydro configuration
*
* @param {Hydro} hydro
*/
module.exports = function(hydro) {
hydro.set({
suite: 'equals',
timeout: 500,
plugins: [
require('hydro-chai'),
require('hydro-bdd')
],
chai: {
chai: require('chai'),
styles: ['should'],
stack: true
}
})
}
| jkroso/equals | test/hydro.conf.js | JavaScript | mit | 324 |
module.exports = function(params) {
params = params || {};
_.extend(this, params);
this.validate = params.validate || function() {
return true;
};
} | chrisharrington/traque | app/models/base.js | JavaScript | mit | 177 |
class DataControl {
constructor() {
this.appData
updateData()
}
updateData() {
this.appData = fetcherama()
}
fetcherama() {
lib.fetch(`http://localhost:8080/api/class/getNearbyClasses/${coor.long}/${coor.lat}`, opt, data => {
if (data.success === true) {
return data.classes
}
})
}
}
export default DataControl
| andrewgremlich/presence-keeper | pk_static_files_server/app/js/util/DataControl.js | JavaScript | mit | 369 |
/* */
"format cjs";
(function(e){if("function"==typeof bootstrap)bootstrap("csv2geojson",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeCsv2geojson=e}else"undefined"!=typeof window?window.csv2geojson=e():global.csv2geojson=e()})(function(){var define,ses,bootstrap,module,exports;
return (function(e,t,n){function r(n,i){if(!t[n]){if(!e[n]){var s=typeof require=="function"&&require;if(!i&&s)return s(n,!0);throw new Error("Cannot find module '"+n+"'")}var o=t[n]={exports:{}};e[n][0](function(t){var i=e[n][1][t];return r(i?i:t)},o,o.exports)}return t[n].exports}for(var i=0;i<n.length;i++)r(n[i]);return r})({1:[function(require,module,exports){
function csv(text) {
var header;
return csv_parseRows(text, function(row, i) {
if (i) {
var o = {}, j = -1, m = header.length;
while (++j < m) o[header[j]] = row[j];
return o;
} else {
header = row;
return null;
}
});
function csv_parseRows (text, f) {
var EOL = {}, // sentinel value for end-of-line
EOF = {}, // sentinel value for end-of-file
rows = [], // output rows
re = /\r\n|[,\r\n]/g, // field separator regex
n = 0, // the current line number
t, // the current token
eol; // is the current token followed by EOL?
re.lastIndex = 0; // work-around bug in FF 3.6
/** @private Returns the next token. */
function token() {
if (re.lastIndex >= text.length) return EOF; // special case: end of file
if (eol) { eol = false; return EOL; } // special case: end of line
// special case: quotes
var j = re.lastIndex;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < text.length) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
i++;
}
}
re.lastIndex = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) re.lastIndex++;
} else if (c === 10) {
eol = true;
}
return text.substring(j + 1, i).replace(/""/g, "\"");
}
// common case
var m = re.exec(text);
if (m) {
eol = m[0].charCodeAt(0) !== 44;
return text.substring(j, m.index);
}
re.lastIndex = text.length;
return text.substring(j);
}
while ((t = token()) !== EOF) {
var a = [];
while ((t !== EOL) && (t !== EOF)) {
a.push(t);
t = token();
}
if (f && !(a = f(a, n++))) continue;
rows.push(a);
}
return rows;
}
}
function csv2geojson(x, lonfield, latfield) {
var features = [],
featurecollection = {
type: 'FeatureCollection',
features: features
};
var parsed = csv(x);
if (!parsed.length) return featurecollection;
latfield = latfield || '';
lonfield = lonfield || '';
for (var f in parsed[0]) {
if (!latfield && f.match(/^Lat/i)) latfield = f;
if (!lonfield && f.match(/^Lon/i)) lonfield = f;
}
if (!latfield || !lonfield) {
var fields = [];
for (var k in parsed[0]) fields.push(k);
return fields;
}
for (var i = 0; i < parsed.length; i++) {
if (parsed[i][lonfield] !== undefined &&
parsed[i][lonfield] !== undefined) {
features.push({
type: 'Feature',
properties: parsed[i],
geometry: {
type: 'Point',
coordinates: [
parseFloat(parsed[i][lonfield]),
parseFloat(parsed[i][latfield])]
}
});
}
}
return featurecollection;
}
function toline(gj) {
var features = gj.features;
var line = {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: []
}
};
for (var i = 0; i < features.length; i++) {
line.geometry.coordinates.push(features[i].geometry.coordinates);
}
line.properties = features[0].properties;
return {
type: 'FeatureSet',
features: [line]
};
}
function topolygon(gj) {
var features = gj.features;
var poly = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[]]
}
};
for (var i = 0; i < features.length; i++) {
poly.geometry.coordinates[0].push(features[i].geometry.coordinates);
}
poly.properties = features[0].properties;
return {
type: 'FeatureSet',
features: [poly]
};
}
module.exports = {
csv: csv,
toline: toline,
topolygon: topolygon,
csv2geojson: csv2geojson
};
},{}]},{},[1])(1)
});
;
| thomjoy/turftest | src/jspm_packages/npm/[email protected]/docs/assets/csv2geojson.js | JavaScript | mit | 5,283 |
var module = angular.module('mtg', ['ngRoute', 'timer']);
DEBUG = true;
module.controller('main', function($scope, $filter) {
$scope.matches = [];
$scope.players = [{}, {}];
var orderBy = $filter('orderBy');
$scope.importFromStorage = function() {
console.log("Importing from local storage");
tourney = JSON.parse(localStorage.tourney);
console.log(tourney);
$scope.title = tourney.title;
$scope.players = tourney.players;
$scope.matches = tourney.matches;
// ugly way of rebind players to respective matches.
for(var m = 0; m < $scope.matches.length; m++)
{
for(var i = 0; i < $scope.players.length; i++) {
if($scope.matches[m].players[0].id == $scope.players[i].id)
$scope.matches[m].players[0] = $scope.players[i];
if($scope.matches[m].players[1].id == $scope.players[i].id)
$scope.matches[m].players[1] = $scope.players[i];
}
}
$scope.inited = true;
$scope.updatePlayerRanks();
};
$scope.exportToStorage = function() {
localStorage.tourney = JSON.stringify({
players: $scope.players,
matches: $scope.matches,
title: $scope.title,
inited: $scope.inited,
});
console.log("Exported to storage");
};
$scope.initPlayers = function() {
for(var p = 0; p < $scope.players.length; p++) {
$scope.players[p].won =
$scope.players[p].lost =
$scope.players[p].draw = 0;
$scope.players[p].rank = 1;
$scope.players[p].id = p;
}
};
$scope.updatePlayerRanks = function() {
$scope.players = orderBy($scope.players, ['-won','-draw']);
prev = $scope.players[0];
prev.rank = 1;
for(var i = 1; i < $scope.players.length; i++) {
curr = $scope.players[i];
if(curr.won == prev.won && curr.draw == prev.draw) // Not counting losses here.
{
curr.rank = prev.rank;
} else {
curr.rank = prev.rank + 1;
prev = curr;
}
}
console.log($scope.players);
};
$scope.createMatches = function() {
$scope.matches = [];
index = 0;
for(var p = 0; p < $scope.players.length; p++) {
var player1 = $scope.players[p];
for(var p2 = p+1; p2 < $scope.players.length; p2++) {
var player2 = $scope.players[p2];
var match = {
players: [player1, player2],
scores: [0, 0],
status: 'queued',
index: -1
}
$scope.matches.push(match);
}
}
// Semi-Random ordering of the matches.
// Should be so that min n-1 players have a match in the first
// round. This problem could be reduced to finding a Hamilton path...
indexes = [];
for(var i = 0; i < $scope.matches.length; i++)
indexes.push(i);
// Random shuffle. This could probably be improved in terms of efficiency.
matches_without_index = [];
while(indexes.length > 0) {
pick = Math.floor(Math.random() * indexes.length);
ind = indexes[pick];
matches_without_index.push(ind);
indexes.splice(pick, 1);
}
console.log(matches_without_index);
picked_players = [];
for(var i = 0; i < $scope.matches.length;) {
var m = 0;
for(; m < $scope.matches.length; m++) {
var match = $scope.matches[matches_without_index[m]]; // accessing the random order.
if(match.index > -1)
continue; // already visited.
if(picked_players.indexOf(match.players[0]) > -1 || picked_players.indexOf(match.players[1]) > -1)
continue; // at least one of the players already has a matchup this round.
match.index = i++;
picked_players.push(match.players[0]);
picked_players.push(match.players[1]);
break;
}
if(m == $scope.matches.length) {
picked_players = []; // new round.
}
}
$scope.matchesLeft = $scope.matches.length;
};
$scope.init = function() {
console.log("Init was called");
$scope.inited = true;
$scope.initPlayers();
$scope.createMatches();
$scope.exportToStorage();
};
$scope.matchEvaluator = function(a) {
statusorder = ['playing','queued','ended']
letters = ['a','b','c'];
return letters[statusorder.indexOf(a.status)] + a.index;
};
$scope.getMatchesLeft = function() {
var count = 0;
for(var i = 0; i < $scope.matches.length; i++)
if($scope.matches[i].status != 'ended')
count++;
return count;
};
$scope.reorderMatches = function() {
$scope.matches = orderBy($scope.matches, $scope.matchEvaluator, false);
$scope.exportToStorage();
};
$scope.startMatch = function(match) {
match.status = 'playing';
match.endtime = new Date().getTime() + 45*60*1000; // todo flytta till setting.
$scope.reorderMatches();
};
$scope.editMatch = function(match) {
match.status = 'playing';
if(match.scores[0] == match.scores[1])
{
match.players[0].draw -= 1;
match.players[1].draw -= 1;
} else if(match.scores[0] > match.scores[1]) {
match.players[0].won -= 1;
match.players[1].lost -= 1;
} else {
match.players[1].won -= 1;
match.players[0].lost -= 1;
}
$scope.updatePlayerRanks();
$scope.reorderMatches();
};
$scope.endMatch = function(match) {
match.status = 'ended';
if(match.scores[0] == match.scores[1])
{
match.players[0].draw += 1;
match.players[1].draw += 1;
} else if(match.scores[0] > match.scores[1]) {
match.players[0].won += 1;
match.players[1].lost += 1;
} else {
match.players[1].won += 1;
match.players[0].lost += 1;
}
$scope.reorderMatches();
$scope.updatePlayerRanks();
};
$scope.reset = function() {
$scope.matches = [];
$scope.players = [{}, {}];
$scope.inited = false;
if(DEBUG) {
$scope.players = [{name:'Herp'}, {name:'Derp'}, {name:'Merp'}];
}
$scope.exportToStorage();
};
if (localStorage.tourney) {
$scope.importFromStorage();
}
});
| Tethik/mtg | mtg.js | JavaScript | mit | 5,687 |
// Demo component
// this is only example component
// you can find tests in __test__ folder
import React from 'react';
import Button from './components/Button'
class TeamCatfish extends React.Component {
render() {
return (
<div className="team-catfish">
<p>TC</p>
</div>
)
}
};
module.exports = {
TeamCatfish,
...Button
} | anthonykulis/npm-test | src/index.js | JavaScript | mit | 399 |
var LOTUS = Symbol.for('lotus');
var lotus = global[LOTUS];
if (!lotus) {
var lotusPath = process.env.LOTUS_PATH;
// Try using the local version.
if (lotusPath) {
lotusPath += '/lotus-require';
if (__dirname === lotusPath) {
// We are already using the local version.
}
else if (require('fs').existsSync(lotusPath)) {
lotus = require(lotusPath);
}
}
// Default to using the installed remote version.
if (!lotus) {
lotus = require('./js/index');
}
global[LOTUS] = lotus;
}
module.exports = lotus;
| aleclarson/lotus-require | index.js | JavaScript | mit | 554 |
import { compose, combineReducers, createStore } from 'redux';
import { devTools } from 'redux-devtools';
import twist from './reducers/twist';
import form from './reducers/form';
const twister = combineReducers({
twist,
form
});
const finalCreateStore = compose(devTools())(createStore);
export default finalCreateStore(twister);
| mvader/reactmad-redux-example | src/store.js | JavaScript | mit | 338 |
'use strict';
describe('Controller: HomeCtrl', function () {
it('should make a unit test ...', function () {
});
});
| topheman/cycle-infos | test/spec/controllers/home.js | JavaScript | mit | 123 |
const
pObj=pico.export('pico/obj'),
fb=require('api/fbJSON'),
rdTrip=require('redis/trip')
return {
setup(context,cb){
cb()
},
addPickup(user,action,evt,name,next){
const text=pObj.dotchain(evt,['message','text'])
if(!text) return next(null,`fb/ask${action[action.length-1]}`)
const a=action.pop()
switch(a){
case 'TripFirstPickup':
switch(text.toLowerCase()){
case 'done': return next(null,`fb/ask${a}`)
default:
action.push('-',text)
this.set(name,'TripPickup')
break
}
break
case 'TripPickup':
switch(text.toLowerCase()){
case 'done':
action.push('+:pickup',null)
this.set(name,'TripFirstDropoff')
break
default:
action.push('-',text)
this.set(name,'TripPickup')
break
}
break
default: return next(null,`fb/ask${a}`)
}
next()
},
addDropoff(user,action,evt,name,next){
const text=pObj.dotchain(evt,['message','text'])
if(!text) return next(null,`fb/ask${action[action.length-1]}`)
const a=action.pop()
switch(a){
case 'TripFirstDropoff':
switch(text.toLowerCase()){
case 'done': return next(null,`fb/ask${a}`)
default:
action.push('-',text)
this.set(name,'TripDropoff')
break
}
break
case 'TripDropoff':
switch(text.toLowerCase()){
case 'done':
action.push('+:dropoff',null)
this.set(name,'TripSeat')
break
default:
action.push('-',text)
this.set(name,'TripDropoff')
break
}
break
default: return next(null,`fb/ask${a}`)
}
next()
},
done(user,cmd,msg,next){
console.log('addTrp.done',user,cmd)
rdTrip.set(user,cmd,(err)=>{
if (err) Object.assign(msg, fb.message(user,fb.text(`An error has encountered when adding your trip: ${err}.\ntype help for more action`)))
else Object.assign(msg, fb.message(user,fb.text(`New trip on ${fb.toDateTime(user,cmd.date)} has been added.\ntype help for more action`)))
next()
})
}
}
| ldarren/mysg | api/addTrip.js | JavaScript | mit | 1,913 |
"use strict";
var testCase = require('nodeunit').testCase,
path = require('path'),
fs = require('fs'),
avconv;
function read(stream, callback) {
var output = [],
err = [];
stream.on('data', function(data) {
output.push(data);
});
stream.on('error', function(data) {
err.push(data);
});
stream.once('end', function(exitCode, signal) {
callback(exitCode, signal, output, err);
});
}
module.exports = testCase({
'TC 1: stability tests': testCase({
'loading avconv function (require)': function(t) {
t.expect(1);
avconv = require('../avconv.js');
t.ok(avconv, 'avconv is loaded.');
t.done();
},
'run without parameters (null) 1': function(t) {
t.expect(4);
var stream = avconv(null);
read(stream, function(exitCode, signal, output, err) {
t.strictEqual(exitCode, 1, 'avconv did nothing');
t.notEqual(output.length, 0, 'output is not empty');
t.strictEqual(err.length, 0, 'err is empty');
t.strictEqual(signal, null, 'Signal is null');
t.done();
});
},
'run with empty array ([])': function(t) {
t.expect(3);
var stream = avconv([]);
read(stream, function(exitCode, signal, output, err) {
t.strictEqual(exitCode, 1, 'avconv did nothing');
t.notEqual(output.length, 0, 'output is not empty');
t.strictEqual(err.length, 0, 'err is empty');
t.done();
});
},
'run with invalid string parameter (fdsfdsfsdf)': function(t) {
t.expect(1);
t.throws(
function() {
avconv('fdsfdsfsdf');
},
TypeError,
'a type error must be thrown here'
);
t.done();
},
'run with invalid array parameters ([fdsfdsfsdf])': function(t) {
t.expect(3);
var stream = avconv(['fdsfdsfsdf']);
read(stream, function(exitCode, signal, output, err) {
t.strictEqual(exitCode, 1, 'avconv did nothing');
t.notEqual(output.length, 0, 'stdout is not empty and contains a warning about the wrong parameter');
t.strictEqual(err.length, 0, 'stderr is still empty');
t.done();
});
}
}),
'TC 2: real tests': testCase({
'loading help (--help)': function(t) {
t.expect(3);
var stream = avconv(['--help']);
read(stream, function(exitCode, signal, output, err) {
t.strictEqual(exitCode, 0, 'avconv returned help');
t.notEqual(output.length, 0, 'stdout contains help');
t.strictEqual(err.length, 0, 'stderr is still empty');
t.done();
});
}
}),
'TC 3: do a conversion': testCase({
setUp: function(callback) {
this.exampleDir = path.join(__dirname, 'example');
var source = path.join(this.exampleDir, 'pokemon_card.webm');
try {
fs.unlinkSync(source);
} catch (exc) {
// ignore if it does not exist
}
callback();
},
'convert pokemon flv to webm': function(t) {
var params = [
'-i', path.join(this.exampleDir, 'pokemon_card.flv'),
'-c:v', 'libvpx',
'-deadline', 'realtime',
'-y', path.join(this.exampleDir, 'pokemon_card.webm')
];
var errors = '',
datas = '',
previousProgress = 0;
var stream = avconv(params);
stream.on('data', function(data) {
datas += data;
});
stream.on('progress', function(progress) {
t.ok(progress > previousProgress, 'Progress has been made');
t.ok(progress <= 1, 'Progress is never over 100%');
previousProgress = progress;
});
stream.on('meta', function(meta) {
t.strictEqual(meta.video.track, '0.0', 'Video track number is correct');
t.strictEqual(meta.video.codec, 'h264 (Main)', 'Video codec is correct');
t.strictEqual(meta.video.format, 'yuv420p', 'Video format is correct');
t.strictEqual(meta.video.width, 320, 'Video width is correct');
t.strictEqual(meta.video.height, 240, 'Video height is correct');
});
stream.on('error', function(data) {
errors += data;
});
stream.once('end', function(exitCode, signal) {
t.strictEqual(exitCode, 0, 'Video has been successfully generated');
t.strictEqual(errors, '', 'No errors occured at all');
t.strictEqual(signal, null, 'Signal is null');
t.ok(datas.length > 0, 'There is data');
t.done();
});
},
'convert and kill in the middle': function(t) {
var params = [
'-i', path.join(this.exampleDir, 'pokemon_card.flv'),
'-c:v', 'libvpx',
'-deadline', 'realtime',
'-y', path.join(this.exampleDir, 'pokemon_card.webm')
];
var errors = '';
var stream = avconv(params);
stream.on('error', function(data) {
errors += data;
});
stream.once('end', function(exitCode, signal) {
t.strictEqual(exitCode, null, 'There is no exit code when killed');
t.strictEqual(errors, '', 'No errors occured at all');
t.strictEqual(signal, 'SIGTERM', 'Signal is SIGTERM');
t.done();
});
setTimeout(function() {
stream.kill();
}, 10);
}
})
});
| olivererxleben/hipsterbility | serverside/node_modules/avconv/tests/basics.js | JavaScript | mit | 6,328 |
Clazz.declarePackage ("J.renderspecial");
Clazz.load (["J.render.ShapeRenderer"], "J.renderspecial.PolyhedraRenderer", ["JU.P3i", "JM.Atom", "JU.C"], function () {
c$ = Clazz.decorateAsClass (function () {
this.drawEdges = 0;
this.isAll = false;
this.frontOnly = false;
this.screens = null;
this.vibs = false;
Clazz.instantialize (this, arguments);
}, J.renderspecial, "PolyhedraRenderer", J.render.ShapeRenderer);
Clazz.overrideMethod (c$, "render",
function () {
var polyhedra = this.shape;
var polyhedrons = polyhedra.polyhedrons;
this.drawEdges = polyhedra.drawEdges;
this.g3d.addRenderer (1073742182);
this.vibs = (this.ms.vibrations != null && this.tm.vibrationOn);
var needTranslucent = false;
for (var i = polyhedra.polyhedronCount; --i >= 0; ) if (polyhedrons[i].isValid && this.render1 (polyhedrons[i])) needTranslucent = true;
return needTranslucent;
});
Clazz.defineMethod (c$, "render1",
function (p) {
if (p.visibilityFlags == 0) return false;
var colixes = (this.shape).colixes;
var iAtom = p.centralAtom.i;
var colix = (colixes == null || iAtom >= colixes.length ? 0 : colixes[iAtom]);
colix = JU.C.getColixInherited (colix, p.centralAtom.colixAtom);
var needTranslucent = false;
if (JU.C.renderPass2 (colix)) {
needTranslucent = true;
} else if (!this.g3d.setC (colix)) {
return false;
}var vertices = p.vertices;
var planes;
if (this.screens == null || this.screens.length < vertices.length) {
this.screens = new Array (vertices.length);
for (var i = vertices.length; --i >= 0; ) this.screens[i] = new JU.P3i ();
}planes = p.planes;
for (var i = vertices.length; --i >= 0; ) {
var atom = (Clazz.instanceOf (vertices[i], JM.Atom) ? vertices[i] : null);
if (atom == null) {
this.tm.transformPtScr (vertices[i], this.screens[i]);
} else if (!atom.isVisible (this.myVisibilityFlag)) {
this.screens[i].setT (this.vibs && atom.hasVibration () ? this.tm.transformPtVib (atom, this.ms.vibrations[atom.i]) : this.tm.transformPt (atom));
} else {
this.screens[i].set (atom.sX, atom.sY, atom.sZ);
}}
this.isAll = (this.drawEdges == 1);
this.frontOnly = (this.drawEdges == 2);
if (!needTranslucent || this.g3d.setC (colix)) for (var i = 0, j = 0; j < planes.length; ) this.fillFace (p.normixes[i++], this.screens[planes[j++]], this.screens[planes[j++]], this.screens[planes[j++]]);
if (p.colixEdge != 0) colix = p.colixEdge;
if (this.g3d.setC (JU.C.getColixTranslucent3 (colix, false, 0))) for (var i = 0, j = 0; j < planes.length; ) this.drawFace (p.normixes[i++], this.screens[planes[j++]], this.screens[planes[j++]], this.screens[planes[j++]]);
return needTranslucent;
}, "J.shapespecial.Polyhedron");
Clazz.defineMethod (c$, "drawFace",
function (normix, A, B, C) {
if (this.isAll || this.frontOnly && this.vwr.gdata.isDirectedTowardsCamera (normix)) {
this.drawCylinderTriangle (A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z);
}}, "~N,JU.P3i,JU.P3i,JU.P3i");
Clazz.defineMethod (c$, "drawCylinderTriangle",
function (xA, yA, zA, xB, yB, zB, xC, yC, zC) {
var d = (this.g3d.isAntialiased () ? 6 : 3);
this.g3d.fillCylinderScreen (3, d, xA, yA, zA, xB, yB, zB);
this.g3d.fillCylinderScreen (3, d, xB, yB, zB, xC, yC, zC);
this.g3d.fillCylinderScreen (3, d, xA, yA, zA, xC, yC, zC);
}, "~N,~N,~N,~N,~N,~N,~N,~N,~N");
Clazz.defineMethod (c$, "fillFace",
function (normix, A, B, C) {
this.g3d.fillTriangleTwoSided (normix, A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z);
}, "~N,JU.P3i,JU.P3i,JU.P3i");
});
| rishiloyola/jsmol-models | jsmol/j2s/J/renderspecial/PolyhedraRenderer.js | JavaScript | mit | 3,499 |
var buttons = function(req, res, next) {
var request = require('request');
var cheerio = require('cheerio');
var Case = require('case');
// var url = "http://clas.asu.edu";
var url = req.body.page;
var parsedResults = [];
//testing url argument site buttons casing
request(url, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
$('.btn').each(function(i, element){
var text = $(this).text().trim();
var casing = Case.of($(this).text().trim());
if ( (casing == "sentence") || (casing == "header") ){
var passfail = "PASS";
} else {
var passfail = "FAIL";
}
var testResults = {
text: text,
casing: casing,
passfail: passfail
};
parsedResults.push(testResults);
});
req.pf = parsedResults;
next();
};
});
};
module.exports = buttons;
| gabemartinez/clastestsuite | tests/buttons.js | JavaScript | mit | 975 |
var taxi = require('..');
var chromedriver = require('chromedriver');
var fs = require('fs');
var user = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;
var sauceLabsUrl = "http://" + user + ":" + accessKey + "@ondemand.saucelabs.com/wd/hub";
var tests = [
{ url:'http://localhost:9515/', capabilities: { browserName:'chrome' }, beforeFn: function () { chromedriver.start(); }, afterFn: function () { chromedriver.stop() } },
{ url:'http://localhost:9517/', capabilities: { browserName:'phantomjs', browserVersion:'1.9.8' } },
{ url:'http://localhost:4444/wd/hub', capabilities: { browserName:'firefox' } },
{ url:'http://makingshaking.corp.ne1.yahoo.com:4444', capabilities: { browserName:'phantomjs', browserVersion: '2.0.0 dev' } },
{ url:sauceLabsUrl, capabilities: { browserName:'chrome', version:'41.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'firefox', version:'37.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'11.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'10.0', platform:'Windows 8' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'9.0', platform:'Windows 7' } },
{ url:sauceLabsUrl, capabilities: { browserName:'safari', version:'5.1', platform:'Windows 7' } },
{ url:sauceLabsUrl, capabilities: { browserName:'safari', version:'8.0', platform:'OS X 10.10' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPad Simulator', "device-orientation":'portrait' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPad Simulator', "device-orientation":'landscape' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPhone Simulator', "device-orientation":'portrait' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPhone Simulator', "device-orientation":'landscape' } }
];
tests.forEach(function (test) {
// Do we need to run something before the test-run?
if (test.beforeFn) {
test.beforeFn();
}
try {
var driver = taxi(test.url, test.capabilities, {mode: taxi.Driver.MODE_SYNC, debug: true, httpDebug: true});
var browser = driver.browser();
var activeWindow = browser.activeWindow();
// Navigate to Yahoo
activeWindow.navigator().setUrl('http://www.yahoo.com');
var browserId = (driver.deviceName() != '' ? driver.deviceName() : driver.browserName()) + " " + driver.deviceOrientation() + " " + driver.browserVersion() + " " + driver.platform();
// Write screenshot to a file
fs.writeFileSync(__dirname + '/' + browserId.trim() + '.png', activeWindow.documentScreenshot({
eachFn: function (index) {
// Remove the header when the second screenshot is reached.
// The header keeps following the scrolling position.
// So, we want to turn it off here.
if (index >= 1 && document.getElementById('masthead')) {
document.getElementById('masthead').style.display = 'none';
}
},
completeFn: function () {
// When it has a "masthead", then display it again
if (document.getElementById('masthead')) {
document.getElementById('masthead').style.display = '';
}
},
// Here is a list of areas that should be blocked-out
blockOuts: [
// Block-out all text-boxes
'input',
// Custom block-out at static location with custom color
{x:60, y: 50, width: 200, height: 200, color:{red:255,green:0,blue:128}}
]
// The element cannot be found in mobile browsers since they have a different layout
//, activeWindow.getElement('.footer-section')]
}));
} catch (err) {
console.error(err.stack);
} finally {
driver.dispose();
// Do we need to run something after the test-run?
if (test.afterFn) {
test.afterFn();
}
}
});
| preceptorjs/taxi | examples/stitching.js | JavaScript | mit | 4,049 |
/**
* @author Chine
*/
function switchTheme(theme) {
$.cookie('blog_theme', theme, { expires: 30 });
location.href = location.href;
}
| harveyqing/Qingblog | Qingblog/public/static/dopetrope/js/theme.js | JavaScript | mit | 142 |
var mtd = require('mt-downloader');
var fs = require('fs');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Download = function() {
EventEmitter.call(this);
this._reset();
this.url = '';
this.filePath = '';
this.options = {};
this.meta = {};
this._retryOptions = {
_nbRetries: 0,
maxRetries: 5,
retryInterval: 5000
};
};
util.inherits(Download, EventEmitter);
Download.prototype._reset = function(first_argument) {
this.status = 0; // -3 = destroyed, -2 = stopped, -1 = error, 0 = not started, 1 = started (downloading), 2 = error, retrying, 3 = finished
this.error = '';
this.stats = {
time: {
start: 0,
end: 0
},
total: {
size: 0,
downloaded: 0,
completed: 0
},
past: {
downloaded: 0
},
present: {
downloaded: 0,
time: 0,
speed: 0
},
future: {
remaining: 0,
eta: 0
},
threadStatus: {
idle: 0,
open: 0,
closed: 0,
failed: 0
}
};
};
Download.prototype.setUrl = function(url) {
this.url = url;
return this;
};
Download.prototype.setFilePath = function(filePath) {
this.filePath = filePath;
return this;
};
Download.prototype.setOptions = function(options) {
if(!options || options == {}) {
return this.options = {};
}
// The "options" object will be directly passed to mt-downloader, so we need to conform to his format
//To set the total number of download threads
this.options.count = options.threadsCount || options.count || 2;
//HTTP method
this.options.method = options.method || 'GET';
//HTTP port
this.options.port = options.port || 80;
//If no data is received the download times out. It is measured in seconds.
this.options.timeout = options.timeout/1000 || 5;
//Control the part of file that needs to be downloaded.
this.options.range = options.range || '0-100';
// Support customized header fields
this.options.headers = options.headers || {};
return this;
};
Download.prototype.setRetryOptions = function(options) {
this._retryOptions.maxRetries = options.maxRetries || 5;
this._retryOptions.retryInterval = options.retryInterval || 2000;
return this;
};
Download.prototype.setMeta = function(meta) {
this.meta = meta;
return this;
};
Download.prototype.setStatus = function(status) {
this.status = status;
return this;
};
Download.prototype.setError = function(error) {
this.error = error;
return this;
};
Download.prototype._computeDownloaded = function() {
if(!this.meta.threads) { return 0; }
var downloaded = 0;
this.meta.threads.forEach(function(thread) {
downloaded += thread.position - thread.start;
});
return downloaded;
};
// Should be called on start, set the start timestamp (in seconds)
Download.prototype._computeStartTime = function() {
this.stats.time.start = Math.floor(Date.now() / 1000);
};
// Should be called on end, set the end timestamp (in seconds)
Download.prototype._computeEndTime = function() {
this.stats.time.end = Math.floor(Date.now() / 1000);
};
// Should be called on start, count size already downloaded (eg. resumed download)
Download.prototype._computePastDownloaded = function() {
this.stats.past.downloaded = this._computeDownloaded();
};
// Should be called on start compute total size
Download.prototype._computeTotalSize = function() {
var threads = this.meta.threads;
if(!threads) { return 0; }
this.stats.total.size = threads[threads.length-1].end - threads[0].start;
};
Download.prototype._computeStats = function() {
this._computeTotalSize();
this._computeTotalDownloaded();
this._computePresentDownloaded();
this._computeTotalCompleted();
this._computeFutureRemaining();
// Only compute those stats when downloading
if(this.status == 1) {
this._computePresentTime();
this._computePresentSpeed();
this._computeFutureEta();
this._computeThreadStatus();
}
};
Download.prototype._computePresentTime = function() {
this.stats.present.time = Math.floor(Date.now() / 1000) - this.stats.time.start;
};
Download.prototype._computeTotalDownloaded = function() {
this.stats.total.downloaded = this._computeDownloaded();
};
Download.prototype._computePresentDownloaded = function() {
this.stats.present.downloaded = this.stats.total.downloaded - this.stats.past.downloaded;
};
Download.prototype._computeTotalCompleted = function() {
this.stats.total.completed = Math.floor((this.stats.total.downloaded) * 1000 / this.stats.total.size) / 10;
};
Download.prototype._computeFutureRemaining = function() {
this.stats.future.remaining = this.stats.total.size - this.stats.total.downloaded;
};
Download.prototype._computePresentSpeed = function() {
this.stats.present.speed = this.stats.present.downloaded / this.stats.present.time;
};
Download.prototype._computeFutureEta = function() {
this.stats.future.eta = this.stats.future.remaining / this.stats.present.speed;
};
Download.prototype._computeThreadStatus = function() {
var self = this;
this.stats.threadStatus = {
idle: 0,
open: 0,
closed: 0,
failed: 0
};
this.meta.threads.forEach(function(thread) {
self.stats.threadStatus[thread.connection]++;
});
};
Download.prototype.getStats = function() {
if(!this.meta.threads) {
return this.stats;
}
this._computeStats();
return this.stats;
};
Download.prototype._destroyThreads = function() {
if(this.meta.threads) {
this.meta.threads.forEach(function(i){
if(i.destroy) {
i.destroy();
}
});
}
};
Download.prototype.stop = function() {
this.setStatus(-2);
this._destroyThreads();
this.emit('stopped', this);
};
Download.prototype.destroy = function() {
var self = this;
this._destroyThreads();
this.setStatus(-3);
var filePath = this.filePath;
var tmpFilePath = filePath;
if (!filePath.match(/\.mtd$/)) {
tmpFilePath += '.mtd';
} else {
filePath = filePath.replace(new RegExp('(.mtd)*$', 'g'), '');
}
fs.unlink(filePath, function() {
fs.unlink(tmpFilePath, function() {
self.emit('destroyed', this);
});
});
};
Download.prototype.start = function() {
var self = this;
self._reset();
self._retryOptions._nbRetries = 0;
this.options.onStart = function(meta) {
self.setStatus(1);
self.setMeta(meta);
self.setUrl(meta.url);
self._computeStartTime();
self._computePastDownloaded();
self._computeTotalSize();
self.emit('start', self);
};
this.options.onEnd = function(err, result) {
// If stopped or destroyed, do nothing
if(self.status == -2 || self.status == -3) {
return;
}
// If we encountered an error and it's not an "Invalid file path" error, we try to resume download "maxRetries" times
if(err && (''+err).indexOf('Invalid file path') == -1 && self._retryOptions._nbRetries < self._retryOptions.maxRetries) {
self.setStatus(2);
self._retryOptions._nbRetries++;
setTimeout(function() {
self.resume();
self.emit('retry', self);
}, self._retryOptions.retryInterval);
// "Invalid file path" or maxRetries reached, emit error
} else if(err) {
self._computeEndTime();
self.setError(err);
self.setStatus(-1);
self.emit('error', self);
// No error, download ended successfully
} else {
self._computeEndTime();
self.setStatus(3);
self.emit('end', self);
}
};
this._downloader = new mtd(this.filePath, this.url, this.options);
this._downloader.start();
return this;
};
Download.prototype.resume = function() {
this._reset();
var filePath = this.filePath;
if (!filePath.match(/\.mtd$/)) {
filePath += '.mtd';
}
this._downloader = new mtd(filePath, null, this.options);
this._downloader.start();
return this;
};
// For backward compatibility, will be removed in next releases
Download.prototype.restart = util.deprecate(function() {
return this.resume();
}, 'Download `restart()` is deprecated, please use `resume()` instead.');
module.exports = Download; | leeroybrun/node-mt-files-downloader | lib/Download.js | JavaScript | mit | 8,675 |
import * as utils from '../../utils/utils'
import * as math from '../../math/math'
import QR from '../../math/qr'
import LMOptimizer from '../../math/lm'
import {ConstantWrapper, EqualsTo} from './constraints'
import {dog_leg} from '../../math/optim'
/** @constructor */
function Param(id, value, readOnly) {
this.reset(value);
}
Param.prototype.reset = function(value) {
this.set(value);
this.j = -1;
};
Param.prototype.set = function(value) {
this.value = value;
};
Param.prototype.get = function() {
return this.value;
};
Param.prototype.nop = function() {};
/** @constructor */
function System(constraints) {
this.constraints = constraints;
this.params = [];
for (var ci = 0; ci < constraints.length; ++ci) {
var c = constraints[ci];
for (var pi = 0; pi < c.params.length; ++pi) {
var p = c.params[pi];
if (p.j == -1) {
p.j = this.params.length;
this.params.push(p);
}
}
}
}
System.prototype.makeJacobian = function() {
var jacobi = [];
var i;
var j;
for (i=0; i < this.constraints.length; i++) {
jacobi[i] = [];
for (j=0; j < this.params.length; j++) {
jacobi[i][j] = 0;
}
}
for (i=0; i < this.constraints.length; i++) {
var c = this.constraints[i];
var cParams = c.params;
var grad = [];
utils.fillArray(grad, 0, cParams.length, 0);
c.gradient(grad);
for (var p = 0; p < cParams.length; p++) {
var param = cParams[p];
j = param.j;
jacobi[i][j] = grad[p];
}
}
return jacobi;
};
System.prototype.fillJacobian = function(jacobi) {
for (var i=0; i < this.constraints.length; i++) {
var c = this.constraints[i];
var cParams = c.params;
var grad = [];
utils.fillArray(grad, 0, cParams.length, 0);
c.gradient(grad);
for (var p = 0; p < cParams.length; p++) {
var param = cParams[p];
var j = param.j;
jacobi[i][j] = grad[p];
}
}
return jacobi;
};
System.prototype.calcResidual = function(r) {
var i=0;
var err = 0.;
for (i=0; i < this.constraints.length; i++) {
var c = this.constraints[i];
r[i] = c.error();
err += r[i]*r[i];
}
err *= 0.5;
return err;
};
System.prototype.calcGrad_ = function(out) {
var i;
for (i = 0; i < out.length || i < this.params.length; ++i) {
out[i][0] = 0;
}
for (i=0; i < this.constraints.length; i++) {
var c = this.constraints[i];
var cParams = c.params;
var grad = [];
utils.fillArray(grad, 0, cParams.length, 0);
c.gradient(grad);
for (var p = 0; p < cParams.length; p++) {
var param = cParams[p];
var j = param.j;
out[j][0] += this.constraints[i].error() * grad[p]; // (10.4)
}
}
};
System.prototype.calcGrad = function(out) {
var i;
for (i = 0; i < out.length || i < this.params.length; ++i) {
out[i] = 0;
}
for (i=0; i < this.constraints.length; i++) {
var c = this.constraints[i];
var cParams = c.params;
var grad = [];
utils.fillArray(grad, 0, cParams.length, 0);
for (var p = 0; p < cParams.length; p++) {
var param = cParams[p];
var j = param.j;
out[j] += this.constraints[i].error() * grad[p]; // (10.4)
}
}
};
System.prototype.fillParams = function(out) {
for (var p = 0; p < this.params.length; p++) {
out[p] = this.params[p].get();
}
};
System.prototype.getParams = function() {
var out = [];
this.fillParams(out);
return out;
};
System.prototype.setParams = function(point) {
for (var p = 0; p < this.params.length; p++) {
this.params[p].set(point[p]);
}
};
System.prototype.error = function() {
var error = 0;
for (var i=0; i < this.constraints.length; i++) {
error += Math.abs(this.constraints[i].error());
}
return error;
};
System.prototype.errorSquare = function() {
var error = 0;
for (var i=0; i < this.constraints.length; i++) {
var t = this.constraints[i].error();
error += t * t;
}
return error * 0.5;
};
System.prototype.getValues = function() {
var values = [];
for (var i=0; i < this.constraints.length; i++) {
values[i] = this.constraints[i].error();
}
return values;
};
var wrapAux = function(constrs, locked) {
var i, lockedSet = {};
for (i = 0; i < locked.length; i++) {
lockedSet[locked[i].j] = true;
}
for (i = 0; i < constrs.length; i++) {
var c = constrs[i];
var mask = [];
var needWrap = false;
for (var j = 0; j < c.params.length; j++) {
var param = c.params[j];
mask[j] = lockedSet[param.j] === true;
needWrap = needWrap || mask[j];
}
if (needWrap) {
var wrapper = new ConstantWrapper(c, mask);
constrs[i] = wrapper;
}
}
};
var lock2Equals2 = function(constrs, locked) {
var _locked = [];
for (var i = 0; i < locked.length; ++i) {
_locked.push(new EqualsTo([locked[i]], locked[i].get()));
}
return _locked;
};
var diagnose = function(sys) {
if (sys.constraints.length == 0 || sys.params.length == 0) {
return {
conflict : false,
dof : 0
}
}
var jacobian = sys.makeJacobian();
var qr = new QR(jacobian);
return {
conflict : sys.constraints.length > qr.rank,
dof : sys.params.length - qr.rank
}
};
var prepare = function(constrs, locked, aux, alg) {
var simpleMode = true;
if (!simpleMode) {
var lockingConstrs = lock2Equals2(constrs, locked);
Array.prototype.push.apply( constrs, lockingConstrs );
}
var sys = new System(constrs);
wrapAux(constrs, aux);
var model = function(point) {
sys.setParams(point);
return sys.getValues();
};
var jacobian = function(point) {
sys.setParams(point);
return sys.makeJacobian();
};
var nullResult = {
evalCount : 0,
error : 0,
returnCode : 1
};
function solve(rough, alg) {
//if (simpleMode) return nullResult;
if (constrs.length == 0) return nullResult;
if (sys.params.length == 0) return nullResult;
switch (alg) {
case 2:
return solve_lm(sys, model, jacobian, rough);
case 1:
default:
return dog_leg(sys, rough);
}
}
var systemSolver = {
diagnose : function() {return diagnose(sys)},
error : function() {return sys.error()},
solveSystem : solve,
system : sys,
updateLock : function(values) {
for (var i = 0; i < values.length; ++i) {
if (simpleMode) {
locked[i].set(values[i]);
} else {
lockingConstrs[i].value = values[i];
}
}
}
};
return systemSolver;
};
var solve_lm = function(sys, model, jacobian, rough) {
var opt = new LMOptimizer(sys.getParams(), math.vec(sys.constraints.length), model, jacobian);
opt.evalMaximalCount = 100 * sys.params.length;
var eps = rough ? 0.001 : 0.00000001;
opt.init0(eps, eps, eps);
var returnCode = 1;
try {
var res = opt.doOptimize();
} catch (e) {
returnCode = 2;
}
sys.setParams(res[0]);
return {
evalCount : opt.evalCount,
error : sys.error(),
returnCode : returnCode
};
};
export {Param, prepare} | Autodrop3d/autodrop3dServer | public/webcad/app/sketcher/constr/solver.js | JavaScript | mit | 7,075 |
(function() {
function Base(props) {
this.id = Ambient.getID();
$.extend(this, props || {});
}
Base.extend = function(methods) {
if (typeof methods === "function") {
methods = methods();
}
methods = (methods || {});
var self = this;
var Controller = function() {
self.apply(this, arguments);
};
Controller.prototype = Object.create(self.prototype);
Controller.prototype.constructor = Controller;
for (var key in methods) {
Controller.prototype[key] = methods[key];
}
Controller.extend = Base.extend.bind(Controller);
return Controller;
};
window.Ambient.Controller = Base;
})();
| lewie9021/ambient-js | src/Controller.js | JavaScript | mit | 870 |
import React from 'react'
import { Router, Route, hashHistory, browserHistory, IndexRoute } from 'react-router'
import MainContainer from '../components/MainContainer'
import Login from '../components/hello/Login'
import Register from '../components/hello/Register'
import Index from '../components/index/Index'
import HelloWorld from '../components/hello/HelloWorld'
import Header from '../components/common/Header'
import Xiexie from '../components/write/Write'
import ArticleDetail from '../components/index/ArticleDetail'
class Root extends React.Component {
render() {
return (
<Router history={browserHistory}>
<Route path="/" component={Header}>
<IndexRoute component={Index}/>
<Route path="/xiexie" component={Xiexie}/>
<Route path="/articleDetail" component={ArticleDetail}/>
</Route>
</Router>
)
}
}
export default Root | weifengsmile/xiexie | client/src/containers/Root.js | JavaScript | mit | 931 |
var READONLY = false
// How much labor you generate per minute
var LABORGENRATE = 2;
if (READONLY){
// This is just for setting up a display-only example of this app
Characters = new Meteor.Collection(null)
Timers = new Meteor.Collection(null)
} else {
Characters = new Meteor.Collection("characters");
Timers = new Meteor.Collection("timers");
}
DayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;1
}
return str;
}
function formattime(hour, minutes) {
if (hour >= 12) {
ampm = 'pm'
} else {
ampm = 'am'
}
hour = hour % 12;
if (hour == 0) {
hour = 12;
}
return hour+":"+pad(minutes,2)+ampm;
}
function parsetimerlength(timerstring) {
var totaltime = 0;
// Find days
var re = /(\d+) ?(?:days|day|d)/g;
var matches = re.exec(timerstring);
if(matches) {
totaltime += (Number(matches[1]) * 86400);
}
// Find hours
var re = /(\d+) ?(?:hours|hour|h|hr|hrs)/g;
var matches = re.exec(timerstring);
if(matches) {
totaltime += (Number(matches[1]) * 3600);
}
// Find minutes
var re = /(\d+) ?(?:minutes|minute|min|m)/g;
var matches = re.exec(timerstring);
if(matches) {
totaltime += (Number(matches[1]) * 60);
}
// Find seconds
var re = /(\d+) ?(?:seconds|second|secs|sec|s)/g;
var matches = re.exec(timerstring);
if(matches) {
totaltime += Number(matches[1]);
}
return totaltime;
}
function maxtime(now, max) {
return Date.now() + (max - now) * 1000 * 60 / LABORGENRATE;
}
if (Meteor.isClient) {
var highestMaxLabor = function () {
var highestchar = Characters.findOne({owner: Session.get('sessionid')}, {sort: {labormax: -1}})
if (highestchar)
return highestchar.labormax;
else
return 1000;
};
Session.set('sessionid', location.search);
// When editing a character name, ID of the character
Session.set('editing_charactername', null);
// When editing current labor, ID of the character
Session.set('editing_characterlabor', null);
// When editing current labormax, ID of the character
Session.set('editing_characterlabormax', null);
/* New version
Deps.autorun(function () {
Meteor.subscribe("characters");
});
*/
Meteor.autosubscribe(function () {
Meteor.subscribe('characters', {owner: Session.get('sessionid')});
Meteor.subscribe('timers', {owner: Session.get('sessionid')});
});
if (READONLY) {
// Super duper quickl and dirty hack for creating a read-only version of the app to show as an example from GitHub
newchar = Characters.insert({name: 'OverloadUT', labor: 4000, labormax: 4320, labortimestamp: Date.now(), maxtime: maxtime(4320, 4000), owner: Session.get('sessionid')});
newchar = Characters.insert({name: 'DiscoC', labor: 2400, labormax: 1650, labortimestamp: Date.now(), maxtime: maxtime(1650, 2400), owner: Session.get('sessionid')});
newchar = Characters.insert({name: 'RoughRaptors', labor: 1250, labormax: 5000, labortimestamp: Date.now(), maxtime: maxtime(5000, 1250), owner: Session.get('sessionid')});
var length = 3600
var percent = 0.75
Timers.insert({name: 'Strawberries', starttime: Date.now() - percent * length * 1000, timerlength: length, owner: Session.get('sessionid'), endtime: Date.now() + (1-percent) * length * 1000});
var length = 3600 * 72
var percent = 0.10
Timers.insert({name: 'Pine trees', starttime: Date.now() - percent * length * 1000, timerlength: length, owner: Session.get('sessionid'), endtime: Date.now() + (1-percent) * length * 1000});
var length = 3600 * 18
var percent = 0.90
Timers.insert({name: 'Cows', starttime: Date.now() - percent * length * 1000, timerlength: length, owner: Session.get('sessionid'), endtime: Date.now() + (1-percent) * length * 1000});
var length = 3600 * 24 * 7
var percent = 0.5
Timers.insert({name: 'Pay Taxes', starttime: Date.now() - percent * length * 1000, timerlength: length, owner: Session.get('sessionid'), endtime: Date.now() + (1-percent) * length * 1000});
var length = 3600 * 7
var percent = 1.5
Timers.insert({name: 'Goats', starttime: Date.now() - percent * length * 1000, timerlength: length, owner: Session.get('sessionid'), endtime: Date.now() + (1-percent) * length * 1000});
}
//{//////// Helpers for in-place editing //////////
// Returns an event map that handles the "escape" and "return" keys and
// "blur" events on a text input (given by selector) and interprets them
// as "ok" or "cancel".
var okCancelEvents = function (selector, callbacks) {
var ok = callbacks.ok || function () {};
var cancel = callbacks.cancel || function () {};
var events = {};
events['keyup '+selector+', keydown '+selector+', focusout '+selector] =
function (evt) {
if (evt.type === "keydown" && evt.which === 27) {
// escape = cancel
cancel.call(this, evt);
} else if (evt.type === "keyup" && evt.which === 13 ||
evt.type === "focusout") {
// blur/return/enter = ok/submit if non-empty
var value = String(evt.target.value || "");
if (value)
ok.call(this, value, evt);
else
cancel.call(this, evt);
}
};
return events;
};
var activateInput = function (input) {
input.focus();
input.select();
};
//} END IN-PLACE EDITING HELPERS
//{///////// NEED SESSION PAGE ///////////
Template.needsession.events({
'click input.sessionnamesubmit' : function () {
window.location = Meteor.absoluteUrl('?' + $("#sessionname").val())
}
});
//} END NEED SESSION PAGE
//{//////////// MAIN TEMPLATE //////////////
Template.main.need_session = function () {
return Session.get('sessionid') == "" || Session.get('sessionid') == "?undefined" || Session.get('sessionid') == "?";
};
Template.main.is_readonly = function () {
return READONLY;
};
Template.main.show_timers = function() {
//TODO: Make a way for the user to pick which modules are visible
return true;
}
//} END MAIN TEMPLATE
//{//////////// TIMERS LIST ///////////////////
// When editing timer name, ID of the timer
Session.set('editing_timername', null);
// When editing timer length, ID of the timer
Session.set('editing_timertimeleft', null);
// Preference to hide seconds from timers
Session.setDefault('pref_show_seconds', false);
var timersTimerDep = new Deps.Dependency;
var timersTimerUpdate = function () {
timersTimerDep.changed();
};
Meteor.setInterval(timersTimerUpdate, 1000);
Template.timers.timers = function () {
return Timers.find({owner: Session.get('sessionid')}, {sort: {endtime: 1}});
};
Template.timers.events({
'click a.add' : function () {
var newtimer = Timers.insert({name: 'Timer', starttime: Date.now(), timerlength: 3600, owner: Session.get('sessionid'), endtime: Date.now() + 3600 * 1000});
Session.set('editing_timername', newtimer);
Meteor.flush(); // force DOM redraw, so we can focus the edit field
activateInput($("#timer-name-input"));
},
'click th.timeleft' : function () {
Session.set('pref_show_seconds', !Session.get('pref_show_seconds'));
}
});
//} END TIMERS LIST
//{////////// EACH TIMER //////////////
Template.timer.displaytimeleft = function() {
return this.timerlength;
};
Template.timer.timerdone = function() {
return (this.endtime <= Date.now())
};
var format_time_left = function(totalsecondsleft) {
var daysleft = Math.floor(totalsecondsleft / 60 / 60 / 24);
var hoursleft = Math.floor(totalsecondsleft / 60 / 60 % 24);
var minutesleft = Math.floor(totalsecondsleft / 60 % 60);
var secondsleft = Math.floor(totalsecondsleft % 60);
var timestring = '';
if(totalsecondsleft > 86400) {
timestring += daysleft + 'd ';
}
if(totalsecondsleft > 3600) {
timestring += hoursleft + 'h ';
}
if(totalsecondsleft > 60) {
timestring += minutesleft + 'm ';
}
if (Session.get('pref_show_seconds')) {
timestring += secondsleft + 's';
}
return timestring;
}
Template.timer.timeleft = function() {
timersTimerDep.depend();
var totalsecondsleft = Math.abs((this.timerlength*1000 - (Date.now() - this.starttime)) / 1000);
return format_time_left(totalsecondsleft);
}
Template.timer.timeleftinput = function() {
if(this.endtime <= Date.now()) {
// Timer finished, so show the original timer length
return format_time_left(this.timerlength);
} else {
// Timer not finished, so show the current time left
var totalsecondsleft = Math.abs((this.timerlength*1000 - (Date.now() - this.starttime)) / 1000);
return format_time_left(totalsecondsleft);
}
}
Template.timer.endtimestring = function() {
timersTimerDep.depend();
var date = new Date(this.endtime);
var hour = date.getHours();
var minutes = date.getMinutes();
var day = date.getDay();
var hoursleft = Math.floor(Math.abs((this.endtime - Date.now()) / 1000 / 60 / 60))
var minutesleft = Math.floor(Math.abs((this.endtime - Date.now()) / 1000 / 60 % 60))
return DayStrings[day] + ' ' + formattime(hour,minutes);
}
Template.timer.percentage = function() {
timersTimerDep.depend();
var end = this.starttime + this.timerlength * 1000;
var now = Date.now();
return Math.min(100,Math.floor((now - this.starttime) / (end - this.starttime) * 100));
}
Template.timer.events({
'click a.remove' : function () {
Timers.remove({_id: this._id});
},
'click div.name': function (evt, tmpl) { // start editing list name
Session.set('editing_timername', this._id);
Meteor.flush(); // force DOM redraw, so we can focus the edit field
activateInput(tmpl.find("#timer-name-input"));
},
'click div.timeleft': function (evt, tmpl) { // start editing list name
Session.set('editing_timertimeleft', this._id);
Meteor.flush(); // force DOM redraw, so we can focus the edit field
activateInput(tmpl.find("#timer-timeleft-input"));
}
});
Template.timer.events(okCancelEvents(
'#timer-name-input', {
ok: function (value) {
Timers.update(this._id, {$set: {name: value}});
Session.set('editing_timername', null);
},
cancel: function () {
Session.set('editing_timername', null);
}
}
));
Template.timer.events(okCancelEvents(
'#timer-timeleft-input', {
ok: function (value) {
var timerlength = parsetimerlength(value);
Timers.update(this._id, {$set: {timerlength: timerlength, starttime: Date.now(), endtime: Date.now() + timerlength * 1000}});
Session.set('editing_timertimeleft', null);
},
cancel: function () {
Session.set('editing_timertimeleft', null);
}
}
));
Template.timer.editingname = function () {
return Session.equals('editing_timername', this._id);
};
Template.timer.editingtimeleft = function () {
return Session.equals('editing_timertimeleft', this._id);
};
//} END EACH TIMER
//{///////// CHARACTERS LIST //////////
// Preference to hide seconds from timers
Session.setDefault('pref_scale_maxlabor', true);
Session.setDefault('pref_sort_maxtime', false);
Template.characters.characters = function () {
if(Session.get('pref_sort_maxtime')) {
return Characters.find({owner: Session.get('sessionid')}, {sort: {maxtime: 1}});
} else {
return Characters.find({owner: Session.get('sessionid')}, {});
}
};
Template.characters.events({
'click a.add' : function () {
var newmaxtime = Date.now() + (this.labormax - this.labor) * 1000 * 60 / LABORGENRATE;
var newchar = Characters.insert({name: 'NewCharacter', labor: 50, labormax: 1000, labortimestamp: Date.now(), maxtime: newmaxtime, owner: Session.get('sessionid')});
Session.set('editing_charactername', newchar);
Meteor.flush(); // force DOM redraw, so we can focus the edit field
activateInput($("#character-name-input"));
},
'click th.labor' : function () {
Session.set('pref_scale_maxlabor', !Session.get('pref_scale_maxlabor'))
},
'click th.maxtime' : function () {
Session.set('pref_sort_maxtime', !Session.get('pref_sort_maxtime'))
}
});
//}
//{///////// EACH CHARACTER ///////////
var timerDep = new Deps.Dependency;
var timerUpdate = function () {
timerDep.changed();
};
Meteor.setInterval(timerUpdate, 60000 / LABORGENRATE);
Template.character.currentlabor = function() {
timerDep.depend();
var currentlabor = Math.floor((Date.now() - this.labortimestamp) / 1000 / 60 * LABORGENRATE) + this.labor;
return currentlabor;
};
Template.character.currentlaborcapped = function() {
timerDep.depend();
return Math.min(this.labormax,Math.floor((Date.now() - this.labortimestamp) / 1000 / 60 * LABORGENRATE) + this.labor);
};
// Returns the percentage of max labor, in integer format (50 for 50%)
Template.character.percentage = function() {
timerDep.depend();
var currentlabor = Math.floor((Date.now() - this.labortimestamp) / 1000 / 60 * LABORGENRATE) + this.labor;
return Math.min(100,Math.floor(currentlabor / this.labormax * 100))
};
// Returns the percentage of this character's max labor compared to,
// the character with the MOST max labor. Integer format (50 for 50%)
Template.character.percentagemax = function() {
if(Session.get('pref_scale_maxlabor')) {
return Math.min(100,Math.floor(this.labormax / highestMaxLabor() * 100))
} else {
return 100;
}
};
Template.character.laborcapped = function() {
timerDep.depend();
var currentlabor = Math.floor((Date.now() - this.labortimestamp) / 1000 / 60 * LABORGENRATE) + this.labor;
return (currentlabor >= this.labormax);
}
Template.character.laborwaste = function() {
timerDep.depend();
var currentlabor = Math.floor((Date.now() - this.labortimestamp) / 1000 / 60 * LABORGENRATE) + this.labor;
return Math.max(0,currentlabor - this.labormax);
}
Template.character.maxtimestring = function() {
var maxtimestamp = this.labortimestamp + (this.labormax - this.labor) * 1000 * 60 / LABORGENRATE;
var date = new Date(maxtimestamp);
var hour = date.getHours();
var minutes = date.getMinutes();
var day = date.getDay();
var hoursleft = Math.floor(Math.abs((maxtimestamp - Date.now()) / 1000 / 60 / 60))
var minutesleft = Math.floor(Math.abs((maxtimestamp - Date.now()) / 1000 / 60 % 60))
return DayStrings[day] + " " + formattime(hour,minutes)+" ("+hoursleft+"h "+minutesleft+"m)";
};
Template.character.events({
'click a.remove' : function () {
Characters.remove({_id: this._id});
},
'click div.name': function (evt, tmpl) { // start editing list name
Session.set('editing_charactername', this._id);
Meteor.flush(); // force DOM redraw, so we can focus the edit field
activateInput(tmpl.find("#character-name-input"));
},
'click div.labor': function (evt, tmpl) { // start editing list name
Session.set('editing_characterlabor', this._id);
Meteor.flush(); // force DOM redraw, so we can focus the edit field
activateInput(tmpl.find("#character-labor-input"));
},
'click div.labormax': function (evt, tmpl) { // start editing list name
Session.set('editing_characterlabormax', this._id);
Meteor.flush(); // force DOM redraw, so we can focus the edit field
activateInput(tmpl.find("#character-labormax-input"));
}
});
Template.character.events(okCancelEvents(
'#character-name-input', {
ok: function (value) {
Characters.update(this._id, {$set: {name: value}});
Session.set('editing_charactername', null);
},
cancel: function () {
Session.set('editing_charactername', null);
}
}
));
Template.character.events(okCancelEvents(
'#character-labor-input', {
ok: function (value) {
var newmaxtime = Date.now() + (this.labormax - Number(value)) * 1000 * 60 / LABORGENRATE;
Characters.update(this._id, {$set: {labor: Number(value), labortimestamp: Date.now(), maxtime: newmaxtime}});
Session.set('editing_characterlabor', null);
},
cancel: function () {
Session.set('editing_characterlabor', null);
}
}
));
Template.character.events(okCancelEvents(
'#character-labormax-input', {
ok: function (value) {
var newmaxtime = Date.now() + (Number(value) - this.labor) * 1000 * 60 / LABORGENRATE;
Characters.update(this._id, {$set: {labormax: Number(value), maxtime: newmaxtime}});
Session.set('editing_characterlabormax', null);
},
cancel: function () {
Session.set('editing_characterlabormax', null);
}
}
));
Template.character.editingname = function () {
return Session.equals('editing_charactername', this._id);
};
Template.character.editinglabor = function () {
return Session.equals('editing_characterlabor', this._id);
};
Template.character.editinglabormax = function () {
return Session.equals('editing_characterlabormax', this._id);
};
//} END EACH CHARACTER
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
// Upgrade database from earlier version
Timers.find({}, {}).fetch().forEach(function(timer) {
if (timer.endtime == null) {
console.log('Updating timer ' + timer._id);
Timers.update(timer._id, {$set: {endtime: timer.starttime + timer.timerlength * 1000}});
}
});
// Upgrade database from earlier version
Characters.find({}, {}).fetch().forEach(function(character) {
if (character.maxtime == null) {
console.log('Updating character ' + character._id);
var newmaxtime = character.labortimestamp + (character.labormax - character.labor) * 1000 * 60 / LABORGENRATE;
Characters.update(character._id, {$set: {maxtime: newmaxtime}});
}
});
});
} | OverloadUT/LaborTracker | LaborTracker.js | JavaScript | mit | 18,428 |
var gulp = require('gulp');
var blocksConfig = require('../config').geniblocksRsrc;
var gvConfig = require('../config').geniverseRsrc;
// Copy files directly simple
exports.geniblocksRsrc = function geniblocksRsrc() {
return gulp.src(blocksConfig.src)
.pipe(gulp.dest(blocksConfig.dest));
};
exports.geniverseRsrc = function geniverseRsrc() {
gulp.src(gvConfig.index)
.pipe(gulp.dest(gvConfig.destIndex));
return gulp.src(gvConfig.src)
.pipe(gulp.dest(gvConfig.dest));
};
| concord-consortium/geniblocks | gulp/tasks/geniblocks-rsrc-task.js | JavaScript | mit | 522 |
import express from 'express'
import adminOnly from 'desktop/lib/admin_only'
import { buildServerApp } from 'reaction/Router'
import { routes } from './routes'
import { renderLayout } from '@artsy/stitch'
import { Meta } from './components/Meta'
const app = (module.exports = express())
app.get('/isomorphic-relay-example*', adminOnly, async (req, res, next) => {
try {
const { ServerApp, redirect, status } = await buildServerApp({
routes,
url: req.url,
})
if (redirect) {
res.redirect(302, redirect.url)
return
}
const layout = await renderLayout({
basePath: __dirname,
layout: '../../components/main_layout/templates/react_index.jade',
config: {
styledComponents: true,
},
blocks: {
head: Meta,
body: ServerApp,
},
locals: {
...res.locals,
assetPackage: 'relay',
styledComponents: true,
},
})
res.status(status).send(layout)
} catch (error) {
console.log(error)
next(error)
}
})
| kanaabe/force | src/desktop/apps/isomorphic-relay-example/server.js | JavaScript | mit | 1,049 |
var view = require("ui/core/view");
var proxy = require("ui/core/proxy");
var dependencyObservable = require("ui/core/dependency-observable");
var color = require("color");
var bindable = require("ui/core/bindable");
var types;
function ensureTypes() {
if (!types) {
types = require("utils/types");
}
}
var knownCollections;
(function (knownCollections) {
knownCollections.items = "items";
})(knownCollections = exports.knownCollections || (exports.knownCollections = {}));
var SegmentedBarItem = (function (_super) {
__extends(SegmentedBarItem, _super);
function SegmentedBarItem() {
_super.apply(this, arguments);
this._title = "";
}
Object.defineProperty(SegmentedBarItem.prototype, "title", {
get: function () {
return this._title;
},
set: function (value) {
if (this._title !== value) {
this._title = value;
this._update();
}
},
enumerable: true,
configurable: true
});
SegmentedBarItem.prototype._update = function () {
};
return SegmentedBarItem;
}(bindable.Bindable));
exports.SegmentedBarItem = SegmentedBarItem;
var SegmentedBar = (function (_super) {
__extends(SegmentedBar, _super);
function SegmentedBar() {
_super.apply(this, arguments);
}
SegmentedBar.prototype._addArrayFromBuilder = function (name, value) {
if (name === "items") {
this._setValue(SegmentedBar.itemsProperty, value);
}
};
SegmentedBar.prototype._adjustSelectedIndex = function (items) {
if (this.items) {
if (this.items.length > 0) {
ensureTypes();
if (types.isUndefined(this.selectedIndex) || (this.selectedIndex > this.items.length - 1)) {
this._setValue(SegmentedBar.selectedIndexProperty, 0);
}
}
else {
this._setValue(SegmentedBar.selectedIndexProperty, undefined);
}
}
else {
this._setValue(SegmentedBar.selectedIndexProperty, undefined);
}
};
Object.defineProperty(SegmentedBar.prototype, "selectedIndex", {
get: function () {
return this._getValue(SegmentedBar.selectedIndexProperty);
},
set: function (value) {
this._setValue(SegmentedBar.selectedIndexProperty, value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SegmentedBar.prototype, "items", {
get: function () {
return this._getValue(SegmentedBar.itemsProperty);
},
set: function (value) {
this._setValue(SegmentedBar.itemsProperty, value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SegmentedBar.prototype, "selectedBackgroundColor", {
get: function () {
return this._getValue(SegmentedBar.selectedBackgroundColorProperty);
},
set: function (value) {
this._setValue(SegmentedBar.selectedBackgroundColorProperty, value instanceof color.Color ? value : new color.Color(value));
},
enumerable: true,
configurable: true
});
SegmentedBar.prototype._onBindingContextChanged = function (oldValue, newValue) {
_super.prototype._onBindingContextChanged.call(this, oldValue, newValue);
if (this.items && this.items.length > 0) {
var i = 0;
var length = this.items.length;
for (; i < length; i++) {
this.items[i].bindingContext = newValue;
}
}
};
SegmentedBar.selectedBackgroundColorProperty = new dependencyObservable.Property("selectedBackgroundColor", "SegmentedBar", new proxy.PropertyMetadata(undefined));
SegmentedBar.selectedIndexProperty = new dependencyObservable.Property("selectedIndex", "SegmentedBar", new proxy.PropertyMetadata(undefined));
SegmentedBar.itemsProperty = new dependencyObservable.Property("items", "SegmentedBar", new proxy.PropertyMetadata(undefined));
SegmentedBar.selectedIndexChangedEvent = "selectedIndexChanged";
return SegmentedBar;
}(view.View));
exports.SegmentedBar = SegmentedBar;
| danik121/HAN-MAD-DT-NATIVESCRIPT | node_modules/tns-core-modules/ui/segmented-bar/segmented-bar-common.js | JavaScript | mit | 4,284 |
'use strict';
module.exports = ({ app, controllers, authentication }) => {
const controller = controllers.auth;
const authRoute = '/api/auth';
app.post(authRoute + '/register', controller.register);
app.post(authRoute + '/login', controller.loginLocal);
app.get(authRoute + '/logout', controller.logout);
// app.get(authRoute + '//getLoggedUser', authController.getLoggedUser);
} | Team3OfAKind/course-project-back-end | server/routers/auth-router.js | JavaScript | mit | 405 |
'use strict';
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Redirect to home view when route not found
$urlRouterProvider.otherwise('/');
// Home state routing
$stateProvider.
state('home', {
url: '/',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('presupuesto',{
url: '/presupuesto',
templateUrl: 'modules/productos/views/productos.pedido.client.view.html'
});
}
]); | LuisPe/norisk | public/modules/core/config/core.client.routes.js | JavaScript | mit | 514 |
var m2pong = require('./m2pong');
Player = function(connection, name, nr){
this.connection = connection;
this.name = name;
this.nr = nr;
this.x = 0;
this.y = 0;
this.height = 0;
this.width = 0;
this.score = 0;
this.move = function(x, y){
this.x = x;
this.y = y;
m2pong.sendToDisplays('movePlayer', {
nr: this.nr,
x: this.x,
y: this.y
});
};
this.setScore = function(score){
this.score = score;
m2pong.sendToDisplays('setScore', {
nr: this.nr,
score: score
});
};
};
exports.Player = Player;
| sabl0r/m2pong | server/player.js | JavaScript | mit | 547 |
var _ = require("underscore");
var os = require("os");
var path = require("path");
var assert = require("assert");
// All of these functions are attached to files.js for the tool;
// they live here because we need them in boot.js as well to avoid duplicating
// a lot of the code.
//
// Note that this file does NOT contain any of the "perform I/O maybe
// synchronously" functions from files.js; this is intentional, because we want
// to make it very hard to accidentally use fs.*Sync functions in the app server
// after bootup (since they block all concurrency!)
var files = module.exports;
var toPosixPath = function (p, partialPath) {
// Sometimes, you can have a path like \Users\IEUser on windows, and this
// actually means you want C:\Users\IEUser
if (p[0] === "\\" && (! partialPath)) {
p = process.env.SystemDrive + p;
}
p = p.replace(/\\/g, '/');
if (p[1] === ':' && ! partialPath) {
// transform "C:/bla/bla" to "/c/bla/bla"
p = '/' + p[0] + p.slice(2);
}
return p;
};
var toDosPath = function (p, partialPath) {
if (p[0] === '/' && ! partialPath) {
if (! /^\/[A-Za-z](\/|$)/.test(p))
throw new Error("Surprising path: " + p);
// transform a previously windows path back
// "/C/something" to "c:/something"
p = p[1] + ":" + p.slice(2);
}
p = p.replace(/\//g, '\\');
return p;
};
var convertToOSPath = function (standardPath, partialPath) {
if (process.platform === "win32") {
return toDosPath(standardPath, partialPath);
}
return standardPath;
};
var convertToStandardPath = function (osPath, partialPath) {
if (process.platform === "win32") {
return toPosixPath(osPath, partialPath);
}
return osPath;
}
var convertToOSLineEndings = function (fileContents) {
return fileContents.replace(/\n/g, os.EOL);
};
var convertToStandardLineEndings = function (fileContents) {
// Convert all kinds of end-of-line chars to linuxy "\n".
return fileContents.replace(new RegExp("\r\n", "g"), "\n")
.replace(new RegExp("\r", "g"), "\n");
};
// Return the Unicode Normalization Form of the passed in path string, using
// "Normalization Form Canonical Composition"
const unicodeNormalizePath = (path) => {
return (path) ? path.normalize('NFC') : path;
};
// wrappings for path functions that always run as they were on unix (using
// forward slashes)
var wrapPathFunction = function (name, partialPaths) {
var f = path[name];
assert.strictEqual(typeof f, "function");
return function (/* args */) {
if (process.platform === 'win32') {
var args = _.toArray(arguments);
args = _.map(args, function (p, i) {
// if partialPaths is turned on (for path.join mostly)
// forget about conversion of absolute paths for Windows
return toDosPath(p, partialPaths);
});
var result = f.apply(path, args);
if (typeof result === "string") {
result = toPosixPath(result, partialPaths);
}
return result;
}
return f.apply(path, arguments);
};
};
files.pathJoin = wrapPathFunction("join", true);
files.pathNormalize = wrapPathFunction("normalize");
files.pathRelative = wrapPathFunction("relative");
files.pathResolve = wrapPathFunction("resolve");
files.pathDirname = wrapPathFunction("dirname");
files.pathBasename = wrapPathFunction("basename");
files.pathExtname = wrapPathFunction("extname");
// The path.isAbsolute function is implemented in Node v4.
files.pathIsAbsolute = wrapPathFunction("isAbsolute");
files.pathSep = '/';
files.pathDelimiter = ':';
files.pathOsDelimiter = path.delimiter;
files.convertToStandardPath = convertToStandardPath;
files.convertToOSPath = convertToOSPath;
files.convertToWindowsPath = toDosPath;
files.convertToPosixPath = toPosixPath;
files.convertToStandardLineEndings = convertToStandardLineEndings;
files.convertToOSLineEndings = convertToOSLineEndings;
files.unicodeNormalizePath = unicodeNormalizePath;
| mjmasn/meteor | tools/static-assets/server/mini-files.js | JavaScript | mit | 3,947 |
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user'),
userUsername: DS.attr('string'),
emailNotifications: DS.attr('boolean')
});
| jbingham94/innovation-week-project | example_app/static/example_app/app/models/user-profile.js | JavaScript | mit | 179 |
'use strict';
// Tasks controller
angular.module('tasks').controller('TasksController', ['$scope', '$stateParams', '$location', 'Authentication', 'Tasks',
function($scope, $stateParams, $location, Authentication, Tasks) {
$scope.authentication = Authentication;
$scope.bases = [
{name: 'Squat', lift: 'squat'},
{name: 'Deadlift', lift: 'deadlift'},
{name: 'Bench Press', lift: 'benchPress'},
{name: 'Clean and Jerk', lift: 'cleanJerk'},
{name: 'Snatch', lift: 'snatch'},
{name: 'Front Squat', lift: 'frontSquat'}
];
// Create new Task
$scope.create = function() {
// Create new Task object
var task = new Tasks ({
name: this.name,
description: this.description,
reps: this.reps,
sets: this.sets,
weights: this.weights,
baseLift: this.baseLift
});
// Redirect after save
task.$save(function(response) {
$location.path('workoutplans/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Task
$scope.remove = function(task) {
if ( task ) {
task.$remove();
for (var i in $scope.tasks) {
if ($scope.tasks [i] === task) {
$scope.tasks.splice(i, 1);
}
}
} else {
$scope.task.$remove(function() {
$location.path('tasks');
});
}
};
// Update existing Task
$scope.update = function() {
var task = $scope.task;
task.$update(function() {
$location.path('tasks/' + task._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Tasks
$scope.find = function() {
$scope.tasks = Tasks.query();
};
// Find existing Task
$scope.findOne = function() {
$scope.task = Tasks.get({
taskId: $stateParams.taskId
});
};
}
]); | kyleaziz/lptrack | public/modules/tasks/controllers/tasks.client.controller.js | JavaScript | mit | 1,862 |
angular
.module('eventApp', [
'ngResource',
'ui.bootstrap',
'ui.select',
'ui.bootstrap.datetimepicker',
'global',
'messagingApp',
'datasetApp'
])
.constant('HEK_URL', 'http://www.lmsal.com/hek/her')
.constant('HEK_QUERY_PARAMS', {
'cosec': 2, // ask for json
'cmd': 'search', // search command
'type': 'column',
'event_coordsys': 'helioprojective', //always specify wide coordinates, otherwise does not work
'x1': '-5000',
'x2': '5000',
'y1': '-5000',
'y2': '5000',
'return': 'event_type,event_starttime,event_endtime,kb_archivid,gs_thumburl,frm_name,frm_identifier', // limit the returned fields
'result_limit': 10, // limit the number of results
'event_type': '**', // override to only select some event types
'event_starttime': new Date(Date.UTC(1975, 9, 1)).toISOString(), // The first HEK event is in september 1975
'event_endtime': new Date().toISOString()
})
.constant('HEK_GET_PARAMS', {
'cosec': 2, // ask for json
'cmd': 'export-voevent' // search command
})
.constant('EVENT_TYPES', {
AR : 'Active Region',
CE : 'CME',
CD : 'Coronal Dimming',
CH : 'Coronal Hole',
CW : 'Coronal Wave',
FI : 'Filament',
FE : 'Filament Eruption',
FA : 'Filament Activation',
FL : 'Flare',
C_FL : 'Flare (C1+)',
M_FL : 'Flare (M1+)',
X_FL : 'Flare (X1+)',
LP : 'Loop',
OS : 'Oscillation',
SS : 'Sunspot',
EF : 'Emerging Flux',
CJ : 'Coronal Jet',
PG : 'Plage',
OT : 'Other',
NR : 'Nothing Reported',
SG : 'Sigmoid',
SP : 'Spray Surge',
CR : 'Coronal Rain',
CC : 'Coronal Cavity',
ER : 'Eruption',
TO : 'Topological Object'
}); | bmampaey/SVO | event/module.js | JavaScript | mit | 1,566 |
'use strict';
module.exports = {
db: 'mongodb://localhost/qaapp-dev',
//db: 'mongodb://nodejitsu:[email protected]:10001/nodejitsudb3924701379',
mongoose: {
debug: true
},
app: {
name: 'AskOn'
},
facebook: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: 'DEFAULT_CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
github: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: 'DEFAULT_API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <[email protected]>
mailer: {
service: 'SERVICE_PROVIDER', // Gmail, SMTP
auth: {
user: 'EMAIL_ID',
pass: 'PASSWORD'
}
}
};
| Chien19861128/qa-app | config/env/development.js | JavaScript | mit | 1,201 |
module.exports = function ( grunt ) {
grunt.initConfig( {
pkg: grunt.file.readJSON( 'package.json' ),
banner: '/*!\n' +
'* <%= pkg.name %> v<%= pkg.version %> - <%= pkg.description %>\n' +
'* Copyright (c) <%= grunt.template.today(\'yyyy\') %> <%= pkg.author %>. All rights reserved.\n' +
'* Licensed under <%= pkg.license %> License.\n' +
'*/',
connect: {
docs: {
options: {
protocol: 'http',
port: 8080,
hostname: 'localhost',
livereload: true,
base: {
path: 'docs/',
options: {
index: 'index.htm'
}
},
open: 'http://localhost:8080/index.htm'
}
}
},
sass: {
docs: {
options: {
style: 'expanded'
},
files: {
'dist/autoc.css': 'src/sass/autoc.scss',
'docs/css/layout.css': 'sass/layout.scss'
}
}
},
csslint: {
docs: {
options: {
'bulletproof-font-face': false,
'order-alphabetical': false,
'box-model': false,
'vendor-prefix': false,
'known-properties': false
},
src: [
'dist/autoc.css',
'docs/css/layout.css'
]
}
},
cssmin: {
dist: {
files: {
'dist/autoc.min.css': [
'dist/autoc.css'
]
}
},
docs: {
files: {
'docs/css/layout.min.css': [
'node_modules/normalize.css/normalize.css',
'docs/css/layout.css',
'dist/autoc.css'
]
}
}
},
jshint: {
src: {
options: {
jshintrc: '.jshintrc'
},
src: [
'src/**/*.js'
],
filter: 'isFile'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
docs: {
files: {
'docs/js/autoc.min.js': [
'src/autoc.js'
]
}
},
dist: {
files: {
'dist/autoc.min.js': [
'src/autoc.js'
]
}
}
},
copy: {
docs: {
files: [
{
'docs/js/jquery.js': 'node_modules/jquery/dist/jquery.js'
}
]
},
dist: {
files: [
{
'dist/autoc.js': 'src/autoc.js'
}
]
}
},
pug: {
docs: {
options: {
pretty: true,
data: {
debug: true
}
},
files: {
// create api home page
'docs/index.htm': 'pug/api/index.pug'
}
}
},
watch: {
css: {
files: [
'sass/**/**.scss'
],
tasks: [
'sass',
'csslint',
'cssmin'
]
},
js: {
files: [
'src/**/*.js'
],
tasks: [
'jshint:src',
'uglify',
'copy:docs'
]
},
pug: {
files: [
'pug/**/**.pug'
],
tasks: [
'pug:docs'
]
},
docs: {
files: [
'docs/**/**.html',
'docs/**/**.js',
'docs/**/**.css'
],
options: {
livereload: true
}
}
}
} );
grunt.loadNpmTasks( 'grunt-contrib-connect' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-sass' );
grunt.loadNpmTasks( 'grunt-contrib-csslint' );
grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-pug' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.registerTask( 'html', [ 'pug' ] );
grunt.registerTask( 'http', [
'connect:docs',
'watch'
] );
grunt.registerTask( 'hint', [ 'jshint:src' ] );
grunt.registerTask( 'scripts', [
'jshint',
'uglify',
'copy'
] );
grunt.registerTask( 'styles', [
'sass',
'csslint',
'cssmin'
] );
grunt.registerTask( 'default', [
'connect:docs',
'sass',
'csslint',
'cssmin',
'jshint:src',
'uglify',
'copy',
'pug',
'watch'
] );
}; | yaohaixiao/AutocJS | Gruntfile.js | JavaScript | mit | 5,753 |
/*
setInterval(function() {
console.log(document.activeElement);
}, 1000);
*/
/*
* Notes regarding app state/modes, activeElements, focusing etc.
* ==============================================================
*
* 1) There is always exactly one item selected. All executed commands
* operate on this item.
*
* 2) The app distinguishes three modes with respect to focus:
* 2a) One of the UI panes has focus (inputs, buttons, selects).
* Keyboard shortcuts are disabled.
* 2b) Current item is being edited. It is contentEditable and focused.
* Blurring ends the edit mode.
* 2c) ELSE the Clipboard is focused (its invisible textarea)
*
* In 2a, we try to lose focus as soon as possible
* (after clicking, after changing select's value), switching to 2c.
*
* 3) Editing mode (2b) can be ended by multiple ways:
* 3a) By calling current.stopEditing();
* this shall be followed by some resolution.
* 3b) By executing MM.Command.{Finish,Cancel};
* these call 3a internally.
* 3c) By blurring the item itself (by selecting another);
* this calls MM.Command.Finish (3b).
* 3b) By blurring the currentElement;
* this calls MM.Command.Finish (3b).
*
*/
MM.App = {
keyboard: null,
current: null,
editing: false,
history: [],
historyIndex: 0,
portSize: [0, 0],
map: null,
ui: null,
io: null,
help: null,
_port: null,
_throbber: null,
_drag: {
pos: [0, 0],
item: null,
ghost: null
},
_fontSize: 100,
action: function(action) {
if (this.historyIndex < this.history.length) { /* remove undoed actions */
this.history.splice(this.historyIndex, this.history.length-this.historyIndex);
}
this.history.push(action);
this.historyIndex++;
action.perform();
return this;
},
setMap: function(map) {
if (this.map) { this.map.hide(); }
this.history = [];
this.historyIndex = 0;
this.map = map;
this.map.show(this._port);
},
select: function(item) {
if (this.current && this.current != item) { this.current.deselect(); }
this.current = item;
this.current.select();
},
adjustFontSize: function(diff) {
this._fontSize = Math.max(30, this._fontSize + 10*diff);
this._port.style.fontSize = this._fontSize + "%";
this.map.update();
this.map.ensureItemVisibility(this.current);
},
handleMessage: function(message, publisher) {
switch (message) {
case "ui-change":
this._syncPort();
break;
case "item-change":
if (publisher.isRoot() && publisher.getMap() == this.map) {
document.title = this.map.getName() + " :: 启示工作室";
}
break;
}
},
handleEvent: function(e) {
switch (e.type) {
case "resize":
this._syncPort();
break;
case "beforeunload":
e.preventDefault();
return "";
break;
}
},
setThrobber: function(visible) {
this._throbber.classList[visible ? "add" : "remove"]("visible");
},
init: function() {
this._port = document.querySelector("#port");
this._throbber = document.querySelector("#throbber");
this.ui = new MM.UI();
this.io = new MM.UI.IO();
this.help = new MM.UI.Help();
MM.Tip.init();
MM.Keyboard.init();
MM.Menu.init(this._port);
MM.Mouse.init(this._port);
MM.Clipboard.init();
window.addEventListener("resize", this);
window.addEventListener("beforeunload", this);
MM.subscribe("ui-change", this);
MM.subscribe("item-change", this);
this._syncPort();
this.setMap(new MM.Map());
},
_syncPort: function() {
this.portSize = [window.innerWidth - this.ui.getWidth(), window.innerHeight];
this._port.style.width = this.portSize[0] + "px";
this._port.style.height = this.portSize[1] + "px";
this._throbber.style.right = (20 + this.ui.getWidth())+ "px";
if (this.map) { this.map.ensureItemVisibility(this.current); }
}
}
| sysuzhang/my-mind | src/app.js | JavaScript | mit | 3,807 |
'use strict';
// Setting up route
angular.module('publications').config(['$stateProvider',
function ($stateProvider) {
// publications state routing
$stateProvider
.state('publications', {
abstract: true,
url: '/publications',
template: '<ui-view/>'
})
.state('publications.list', {
url: '',
templateUrl: 'modules/publications/client/views/list-publications.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.search', {
url: '/search',
templateUrl: 'modules/publications/client/views/pagination-publications.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.create', {
url: '/create',
templateUrl: 'modules/publications/client/views/create-publication.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.view', {
url: '/:publicationId',
templateUrl: 'modules/publications/client/views/view-publication.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.edit', {
url: '/:publicationId/edit',
templateUrl: 'modules/publications/client/views/edit-publication.client.view.html',
data: {
roles: ['user', 'admin']
}
});
}
]);
| hibernator11/Galatea | modules/publications/client/config/publications.client.routes.js | JavaScript | mit | 1,447 |
define(function() {
var ctor = function () {
};
//Note: This module exports a function. That means that you, the developer, can create multiple instances.
//This pattern is also recognized by Durandal so that it can create instances on demand.
//If you wish to create a singleton, you should export an object instead of a function.
return ctor;
}); | monmamo/Website | app/Misc/home.js | JavaScript | mit | 375 |
// Generated on 2014-07-03 using
// generator-webapp 0.5.0-rc.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
jstest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
sass: {
files: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['sass:server', 'autoprefixer']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
open: true,
livereload: 35729,
// Change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
test: {
options: {
open: false,
port: 9001,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
dist: {
options: {
base: '<%= config.dist %>',
livereload: false
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
// Mocha testing framework configuration options
mocha: {
all: {
options: {
run: true,
urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html']
}
}
},
// Compiles Sass to CSS and generates necessary files if requested
sass: {
options: {
sourcemap: true,
loadPath: 'bower_components'
},
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
},
server: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
}
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the HTML file
wiredep: {
app: {
ignorePath: new RegExp('^<%= config.app %>/|../'),
src: ['<%= config.app %>/index.html'],
},
sass: {
src: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /(\.\.\/){1,2}bower_components\//
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: ['<%= config.dist %>', '<%= config.dist %>/images']
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},
// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*',
'fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: 'bower_components/Leaflet.awesome-markers/dist/images/',
src: ['**'],
dest: '<%= config.dist %>/styles/images'
}, {
expand: true,
cwd: 'bower_components/font-awesome/fonts/',
src: ['**'],
dest: '<%= config.dist %>/fonts'
}
]
},
styles: {
expand: true,
dot: true,
cwd: '<%= config.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Generates a custom Modernizr build that includes only the tests you
// reference in your app
modernizr: {
dist: {
devFile: 'bower_components/modernizr/modernizr.js',
outputFile: '<%= config.dist %>/scripts/vendor/modernizr.js',
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'!<%= config.dist %>/scripts/vendor/*'
]
},
uglify: true
}
},
// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'sass:server',
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'sass',
'copy:styles',
'imagemin',
'svgmin'
]
}
});
grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
if (grunt.option('allow-remote')) {
grunt.config.set('connect.options.hostname', '0.0.0.0');
}
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});
grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'autoprefixer'
]);
}
grunt.task.run([
'connect:test',
'mocha'
]);
});
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'cssmin',
'uglify',
'copy:dist',
'modernizr',
'rev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
//'test',
'build'
]);
};
| openchattanooga/chattanooga-bike-parking-locator | Gruntfile.js | JavaScript | mit | 10,821 |
import should from 'should';
import Schema from '../../src/schema';
const SIMPEL_OBJECT = {
type: 'object',
properties: {
name: { type: 'string' }
}
};
describe('Schema', () => {
describe('#getType', () => {
it('should return string type for child', () => {
const schema = new Schema(SIMPEL_OBJECT);
schema.getType('name').should.equal('string');
});
});
describe('#isObject', () => {
it('should return true with no path', () => {
const schema = new Schema(SIMPEL_OBJECT);
const r = schema.isObject();
r.should.equal(true);
});
it('should return false with name path', () => {
const schema = new Schema(SIMPEL_OBJECT);
const r = schema.isObject('name');
r.should.equal(false);
});
});
describe('#getProperties', () => {
it('should return array with length same as properties', () => {
const schema = new Schema(SIMPEL_OBJECT);
const r = schema.getProperties();
Object.keys(r).length.should.equal(1);
});
});
});
| surikaterna/formr | test/schema/schema.js | JavaScript | mit | 1,034 |
import { key, PLAY, PAUSE, MUTE, UNMUTE, UPDATE_VOLUME, UPDATE_TIME, SET_SONG, SET_TIME, updateTime } from './actions'
import { store } from '../store'
let audio = new Audio()
audio.addEventListener('timeupdate', event => store.dispatch(updateTime(event)))
const initialState = {
isPlaying: false,
muted: false,
volume: audio.volume,
src: '',
currentTime: '',
duration: 0.0,
completed: 0.0
}
export const selectors = {
audio: state => state[key].audio
}
export default function reducer (state = initialState, { type, payload }) {
switch (type) {
case PLAY:
{
audio.play()
return { ...state, isPlaying: !state.isPlaying }
}
case PAUSE:
{
audio.pause()
return { ...state, isPlaying: !state.isPlaying }
}
case MUTE:
{
audio.muted = true
return { ...state, muted: true }
}
case UNMUTE:
{
audio.muted = false
return { ...state, muted: false }
}
case UPDATE_TIME:
{
const { currentTime, duration, completed } = payload
return { ...state, currentTime, duration, completed }
}
case UPDATE_VOLUME:
{
audio.volume = payload
return { ...state, volume: payload }
}
case SET_TIME:
{
const newCurrentTime = state.currentTime * parseFloat(payload) / 100
audio.currentTime = newCurrentTime
return { ...state, currentTime: newCurrentTime }
}
case SET_SONG:
{
audio.src = payload
return { ...state, src: payload }
}
default:
return state
}
}
| shempignon/podcast-api | app/Resources/js/player/reducer.js | JavaScript | mit | 1,630 |
Subsets and Splits