code stringlengths 2 1.05M |
|---|
'use strict';
import _ from 'lodash';
var classNames = function(base, state) {
var css = base;
for (var c in state) {
if (c in state) {
var s = state[c];
if (_.isArray(s) ? s.length > 0 : s) {
css += ' ' + c;
}
}
}
return css;
};
var isNumeric = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
module.exports = {
classNames: classNames,
isNumeric: isNumeric,
isArray: _.isArray
};
|
import _clone from 'lodash-es/clone';
import _groupBy from 'lodash-es/groupBy';
import _reduce from 'lodash-es/reduce';
import _some from 'lodash-es/some';
import _union from 'lodash-es/union';
import { dispatch as d3_dispatch } from 'd3-dispatch';
import { osmEntity } from '../osm';
import { utilRebind } from '../util/rebind';
import {
utilQsString,
utilStringQs
} from '../util';
export function rendererFeatures(context) {
var traffic_roads = {
'motorway': true,
'motorway_link': true,
'trunk': true,
'trunk_link': true,
'primary': true,
'primary_link': true,
'secondary': true,
'secondary_link': true,
'tertiary': true,
'tertiary_link': true,
'residential': true,
'unclassified': true,
'living_street': true
};
var service_roads = {
'service': true,
'road': true,
'track': true
};
var paths = {
'path': true,
'footway': true,
'cycleway': true,
'bridleway': true,
'steps': true,
'pedestrian': true,
'corridor': true
};
var past_futures = {
'proposed': true,
'construction': true,
'abandoned': true,
'dismantled': true,
'disused': true,
'razed': true,
'demolished': true,
'obliterated': true
};
var dispatch = d3_dispatch('change', 'redraw'),
_cullFactor = 1,
_cache = {},
_features = {},
_stats = {},
_keys = [],
_hidden = [];
function update() {
if (!window.mocha) {
var q = utilStringQs(window.location.hash.substring(1));
var disabled = features.disabled();
if (disabled.length) {
q.disable_features = disabled.join(',');
} else {
delete q.disable_features;
}
window.location.replace('#' + utilQsString(q, true));
context.storage('disabled-features', disabled.join(','));
}
_hidden = features.hidden();
dispatch.call('change');
dispatch.call('redraw');
}
function defineFeature(k, filter, max) {
var isEnabled = true;
_keys.push(k);
_features[k] = {
filter: filter,
enabled: isEnabled, // whether the user wants it enabled..
count: 0,
currentMax: (max || Infinity),
defaultMax: (max || Infinity),
enable: function() { this.enabled = true; this.currentMax = this.defaultMax; },
disable: function() { this.enabled = false; this.currentMax = 0; },
hidden: function() { return !context.editable() || this.count > this.currentMax * _cullFactor; },
autoHidden: function() { return this.hidden() && this.currentMax > 0; }
};
}
defineFeature('points', function isPoint(entity, resolver, geometry) {
return geometry === 'point';
}, 200);
defineFeature('traffic_roads', function isTrafficRoad(entity) {
return traffic_roads[entity.tags.highway];
});
defineFeature('service_roads', function isServiceRoad(entity) {
return service_roads[entity.tags.highway];
});
defineFeature('paths', function isPath(entity) {
return paths[entity.tags.highway];
});
defineFeature('buildings', function isBuilding(entity) {
return (
!!entity.tags['building:part'] ||
(!!entity.tags.building && entity.tags.building !== 'no') ||
entity.tags.parking === 'multi-storey' ||
entity.tags.parking === 'sheds' ||
entity.tags.parking === 'carports' ||
entity.tags.parking === 'garage_boxes'
);
}, 250);
defineFeature('landuse', function isLanduse(entity, resolver, geometry) {
return geometry === 'area' &&
!_features.buildings.filter(entity) &&
!_features.water.filter(entity);
});
defineFeature('boundaries', function isBoundary(entity) {
return (
!!entity.tags.boundary
) && !(
traffic_roads[entity.tags.highway] ||
service_roads[entity.tags.highway] ||
paths[entity.tags.highway]
);
});
defineFeature('water', function isWater(entity) {
return (
!!entity.tags.waterway ||
entity.tags.natural === 'water' ||
entity.tags.natural === 'coastline' ||
entity.tags.natural === 'bay' ||
entity.tags.landuse === 'pond' ||
entity.tags.landuse === 'basin' ||
entity.tags.landuse === 'reservoir' ||
entity.tags.landuse === 'salt_pond'
);
});
defineFeature('rail', function isRail(entity) {
return (
!!entity.tags.railway ||
entity.tags.landuse === 'railway'
) && !(
traffic_roads[entity.tags.highway] ||
service_roads[entity.tags.highway] ||
paths[entity.tags.highway]
);
});
defineFeature('power', function isPower(entity) {
return !!entity.tags.power;
});
// contains a past/future tag, but not in active use as a road/path/cycleway/etc..
defineFeature('past_future', function isPastFuture(entity) {
if (
traffic_roads[entity.tags.highway] ||
service_roads[entity.tags.highway] ||
paths[entity.tags.highway]
) { return false; }
var strings = Object.keys(entity.tags);
for (var i = 0; i < strings.length; i++) {
var s = strings[i];
if (past_futures[s] || past_futures[entity.tags[s]]) { return true; }
}
return false;
});
// Lines or areas that don't match another feature filter.
// IMPORTANT: The 'others' feature must be the last one defined,
// so that code in getMatches can skip this test if `hasMatch = true`
defineFeature('others', function isOther(entity, resolver, geometry) {
return (geometry === 'line' || geometry === 'area');
});
function features() {}
features.features = function() {
return _features;
};
features.keys = function() {
return _keys;
};
features.enabled = function(k) {
if (!arguments.length) {
return _keys.filter(function(k) { return _features[k].enabled; });
}
return _features[k] && _features[k].enabled;
};
features.disabled = function(k) {
if (!arguments.length) {
return _keys.filter(function(k) { return !_features[k].enabled; });
}
return _features[k] && !_features[k].enabled;
};
features.hidden = function(k) {
if (!arguments.length) {
return _keys.filter(function(k) { return _features[k].hidden(); });
}
return _features[k] && _features[k].hidden();
};
features.autoHidden = function(k) {
if (!arguments.length) {
return _keys.filter(function(k) { return _features[k].autoHidden(); });
}
return _features[k] && _features[k].autoHidden();
};
features.enable = function(k) {
if (_features[k] && !_features[k].enabled) {
_features[k].enable();
update();
}
};
features.disable = function(k) {
if (_features[k] && _features[k].enabled) {
_features[k].disable();
update();
}
};
features.toggle = function(k) {
if (_features[k]) {
(function(f) { return f.enabled ? f.disable() : f.enable(); }(_features[k]));
update();
}
};
features.resetStats = function() {
for (var i = 0; i < _keys.length; i++) {
_features[_keys[i]].count = 0;
}
dispatch.call('change');
};
features.gatherStats = function(d, resolver, dimensions) {
var needsRedraw = false,
type = _groupBy(d, function(ent) { return ent.type; }),
entities = [].concat(type.relation || [], type.way || [], type.node || []),
currHidden, geometry, matches, i, j;
for (i = 0; i < _keys.length; i++) {
_features[_keys[i]].count = 0;
}
// adjust the threshold for point/building culling based on viewport size..
// a _cullFactor of 1 corresponds to a 1000x1000px viewport..
_cullFactor = dimensions[0] * dimensions[1] / 1000000;
for (i = 0; i < entities.length; i++) {
geometry = entities[i].geometry(resolver);
if (!(geometry === 'vertex' || geometry === 'relation')) {
matches = Object.keys(features.getMatches(entities[i], resolver, geometry));
for (j = 0; j < matches.length; j++) {
_features[matches[j]].count++;
}
}
}
currHidden = features.hidden();
if (currHidden !== _hidden) {
_hidden = currHidden;
needsRedraw = true;
dispatch.call('change');
}
return needsRedraw;
};
features.stats = function() {
for (var i = 0; i < _keys.length; i++) {
_stats[_keys[i]] = _features[_keys[i]].count;
}
return _stats;
};
features.clear = function(d) {
for (var i = 0; i < d.length; i++) {
features.clearEntity(d[i]);
}
};
features.clearEntity = function(entity) {
delete _cache[osmEntity.key(entity)];
};
features.reset = function() {
_cache = {};
};
features.getMatches = function(entity, resolver, geometry) {
if (geometry === 'vertex' || geometry === 'relation') return {};
var ent = osmEntity.key(entity);
if (!_cache[ent]) {
_cache[ent] = {};
}
if (!_cache[ent].matches) {
var matches = {},
hasMatch = false;
for (var i = 0; i < _keys.length; i++) {
if (_keys[i] === 'others') {
if (hasMatch) continue;
// Multipolygon members:
// If an entity...
// 1. is a way that hasn't matched other 'interesting' feature rules,
// 2. and it belongs to a single parent multipolygon relation
// ...then match whatever feature rules the parent multipolygon has matched.
// see #2548, #2887
//
// IMPORTANT:
// For this to work, getMatches must be called on relations before ways.
//
if (entity.type === 'way') {
var parents = features.getParents(entity, resolver, geometry);
if (parents.length === 1 && parents[0].isMultipolygon()) {
var pkey = osmEntity.key(parents[0]);
if (_cache[pkey] && _cache[pkey].matches) {
matches = _clone(_cache[pkey].matches);
continue;
}
}
}
}
if (_features[_keys[i]].filter(entity, resolver, geometry)) {
matches[_keys[i]] = hasMatch = true;
}
}
_cache[ent].matches = matches;
}
return _cache[ent].matches;
};
features.getParents = function(entity, resolver, geometry) {
if (geometry === 'point') return [];
var ent = osmEntity.key(entity);
if (!_cache[ent]) {
_cache[ent] = {};
}
if (!_cache[ent].parents) {
var parents = [];
if (geometry === 'vertex') {
parents = resolver.parentWays(entity);
} else { // 'line', 'area', 'relation'
parents = resolver.parentRelations(entity);
}
_cache[ent].parents = parents;
}
return _cache[ent].parents;
};
features.isHiddenFeature = function(entity, resolver, geometry) {
if (!_hidden.length) return false;
if (!entity.version) return false;
var matches = features.getMatches(entity, resolver, geometry);
for (var i = 0; i < _hidden.length; i++) {
if (matches[_hidden[i]]) return true;
}
return false;
};
features.isHiddenChild = function(entity, resolver, geometry) {
if (!_hidden.length) return false;
if (!entity.version || geometry === 'point') return false;
var parents = features.getParents(entity, resolver, geometry);
if (!parents.length) return false;
for (var i = 0; i < parents.length; i++) {
if (!features.isHidden(parents[i], resolver, parents[i].geometry(resolver))) {
return false;
}
}
return true;
};
features.hasHiddenConnections = function(entity, resolver) {
if (!_hidden.length) return false;
var childNodes, connections;
if (entity.type === 'midpoint') {
childNodes = [resolver.entity(entity.edge[0]), resolver.entity(entity.edge[1])];
connections = [];
} else {
childNodes = entity.nodes ? resolver.childNodes(entity) : [];
connections = features.getParents(entity, resolver, entity.geometry(resolver));
}
// gather ways connected to child nodes..
connections = _reduce(childNodes, function(result, e) {
return resolver.isShared(e) ? _union(result, resolver.parentWays(e)) : result;
}, connections);
return connections.length ? _some(connections, function(e) {
return features.isHidden(e, resolver, e.geometry(resolver));
}) : false;
};
features.isHidden = function(entity, resolver, geometry) {
if (!_hidden.length) return false;
if (!entity.version) return false;
var fn = (geometry === 'vertex' ? features.isHiddenChild : features.isHiddenFeature);
return fn(entity, resolver, geometry);
};
features.filter = function(d, resolver) {
if (!_hidden.length) return d;
var result = [];
for (var i = 0; i < d.length; i++) {
var entity = d[i];
if (!features.isHidden(entity, resolver, entity.geometry(resolver))) {
result.push(entity);
}
}
return result;
};
features.init = function() {
var storage = context.storage('disabled-features');
if (storage) {
var storageDisabled = storage.replace(/;/g, ',').split(',');
storageDisabled.forEach(features.disable);
}
var q = utilStringQs(window.location.hash.substring(1));
if (q.disable_features) {
var hashDisabled = q.disable_features.replace(/;/g, ',').split(',');
hashDisabled.forEach(features.disable);
}
};
return utilRebind(features, dispatch, 'on');
}
|
/**
* Created by claim on 27.12.15.
*/
/**
*
* @param config
* @param config.width - canvas width
* @param config.height - canvas height
* @param [config.font="14pt monospace"] - canvas height
* @constructor
*/
var Terminal = function (config) {
var self = this;
this.width = config.width;
this.height = config.height;
this.font = config.font || '16pt Courier';
this.terminalPrefix = "> ";
this.promptHeartbeat = 30;
this.prompt = String.fromCharCode(parseInt("25AE", 16));
this.tick = 0;
this.userInputLine = "";
this.userWritten = 0;
this.gamegine = new GAMEGINE({
canvas: 'terminal',
width: this.width,
height: this.height,
fps: 60,
ops: 60
}, this);
this.gamegine.start();
this.listener_keydown = function (event) {
event = event || window.event;
var key = event.which || event.keyCode;
if (key === 8) {
self.userWritten = 10;
self.userInputLine = self.userInputLine.substr(0, self.userInputLine.length - 1);
} else if (key === 9) {
event.preventDefault();
} else {
console.info(key);
}
};
this.listener_keypress = function (event) {
event = event || window.event;
var key = event.which || event.keyCode;
if (key !== 13) {
self.userWritten = 10;
self.userInputLine += String.fromCharCode(key);
} else {
//TODO someone pressed enter
}
};
document.addEventListener('keypress', this.listener_keypress);
document.addEventListener('keydown', this.listener_keydown);
};
Terminal.prototype.logic = function () {
this.tick += 1;
if (this.userWritten > 0) {
this.userWritten -= 1;
}
};
Terminal.prototype.render = function (context) {
var toDisplay = this.terminalPrefix + this.userInputLine;
if (this.userWritten === 0) {
if (this.tick % (2 * this.promptHeartbeat) < this.promptHeartbeat) {
toDisplay += this.prompt;
}
} else {
toDisplay += this.prompt;
}
context.clearRect(0, 0, this.width, this.height);
context.font = this.font;
context.fillStyle = "green";
context.fillText(toDisplay, 20, 30);
};
Terminal.prototype.init = function (context) {
}; |
import toVFile from 'to-vfile'
import { resolve } from 'path'
import { addChanges } from '@geut/chan-core'
import { createLogger } from '../logger.js'
import { openInEditor } from '../open-in-editor.js'
import { write } from '../vfs.js'
const actions = [
{ command: 'added', description: 'Added for new features' },
{ command: 'changed', description: 'Changed for changes in existing functionality' },
{ command: 'deprecated', description: 'Deprecated for soon-to-be removed features' },
{ command: 'removed', description: 'Removed for now removed features' },
{ command: 'fixed', description: 'Fixed for any bug fixes' },
{ command: 'security', description: 'Security in case of vulnerabilities' }
]
const builder = {
path: {
alias: 'p',
describe: 'Path of the CHANGELOG.md',
type: 'string',
default: '.'
},
group: {
alias: 'g',
describe: 'Prefix change with [<group>]. This allows to group changes on release time.',
type: 'string'
}
}
const createHandler = action => async ({ message, path, group, verbose, stdout }) => {
const { report, success, info } = createLogger({ scope: action, verbose, stdout })
try {
const file = await toVFile.read(resolve(path, 'CHANGELOG.md'))
if (!message) {
message = await openInEditor()
if (!message || message.length === 0) {
return info('Nothing to change.')
}
}
await addChanges(file, { changes: [{ action, group, value: message }] })
await write({ file, stdout })
report(file)
} catch (err) {
return report(err)
}
success('Added new changes on your changelog.')
}
export const actionCommands = [
...actions.map(({ command, description }) => ({
command: `${command} [message]`,
description,
builder,
handler: createHandler(command)
}))
]
|
var _ = require('underscore');
var moment = require('moment');
var superagent = require('superagent');
var spawn = require('child_process').spawn;
var temporal = require('temporal');
function playAlert() {
spawn('powershell.exe',['-c', '(New-Object', 'Media.SoundPlayer', '"C:\\Windows\\Media\\Alarm01.wav"', ').PlaySync()']);
}
function logOutput(msg) {
var now = moment().format('YYYY-MM-DD HH:mm:ss');
console.log(now + ' ' + msg);
}
function updateDeals(current_deals, new_deals) {
if(new_deals.seasoned.id !== current_deals.seasoned.id) {
logOutput('New Seasoned Deal -> ' + new_deals.seasoned.title);
current_deals.seasoned = new_deals.seasoned;
}
if(new_deals.fresh.id !== current_deals.fresh.id) {
logOutput('New Fresh Deal -> ' + new_deals.fresh.title);
current_deals.fresh = new_deals.fresh;
}
}
function alertForWatchList(deals, watch_list) {
var seasonedAlert = false;
var freshAlert = false;
_.each(watch_list, function(elem) {
seasonedAlert = seasonedAlert || deals.seasoned.title.toLowerCase().indexOf(elem.toLowerCase()) >= 0;
freshAlert = freshAlert || deals.fresh.title.toLowerCase().indexOf(elem.toLowerCase()) >= 0;
});
if(seasonedAlert) {
logOutput('Seasoned deal is on watch list!');
}
if(freshAlert) {
logOutput('Fresh deal is on watch list!');
}
if(seasonedAlert || freshAlert) {
playAlert();
}
}
function fetchDeals(current_deals, watch_list) {
superagent
.get('http://www.gog.com/doublesomnia/getdeals')
.set('Accept', 'application/json')
.end(function(res) {
if(res.ok) {
var new_deals = {
seasoned: res.body.oldschool,
fresh: res.body.fresh
};
updateDeals(current_deals, new_deals);
alertForWatchList(current_deals, watch_list);
} else {
if(res.text.indexOf('overcapacity.jpg') > 0) {
logOutput('Over Capacity!');
} else {
logOutput('Error! ' + res.text);
}
}
});
}
function pollDeals(watch_list) {
var watch_deals = watch_list || [];
var current_deals = {
seasoned: { id: 0 },
fresh: { id: 0 }
}
fetchDeals(current_deals, watch_deals);
temporal.loop(90000, function() {
fetchDeals(current_deals, watch_deals);
});
}
pollDeals(['wasteland','grimrock']);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Plain = void 0;
const bson_1 = require("../../bson");
const error_1 = require("../../error");
const utils_1 = require("../../utils");
const auth_provider_1 = require("./auth_provider");
class Plain extends auth_provider_1.AuthProvider {
auth(authContext, callback) {
const { connection, credentials } = authContext;
if (!credentials) {
return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'));
}
const username = credentials.username;
const password = credentials.password;
const payload = new bson_1.Binary(Buffer.from(`\x00${username}\x00${password}`));
const command = {
saslStart: 1,
mechanism: 'PLAIN',
payload: payload,
autoAuthorize: 1
};
connection.command((0, utils_1.ns)('$external.$cmd'), command, undefined, callback);
}
}
exports.Plain = Plain;
//# sourceMappingURL=plain.js.map |
// QRCODE reader Copyright 2011 Lazar Laszlo
// http://www.webqr.com
var gCtx = null;
var gCanvas = null;
var c=0;
var stype=0;
var gUM=false;
var webkit=false;
var moz=false;
var v=null;
var imghtml='<div id="qrfile"><canvas id="out-canvas" width="320" height="240"></canvas>'+
'<div id="imghelp">drag and drop a QRCode here'+
'<br>or select a file'+
'<input type="file" onchange="handleFiles(this.files)"/>'+
'</div>'+
'</div>';
var vidhtml = '<video id="v" autoplay></video>';
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
if(files.length>0)
{
handleFiles(files);
}
else
if(dt.getData('URL'))
{
qrcode.decode(dt.getData('URL'));
}
}
function handleFiles(f)
{
var o=[];
for(var i =0;i<f.length;i++)
{
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
gCtx.clearRect(0, 0, gCanvas.width, gCanvas.height);
qrcode.decode(e.target.result);
};
})(f[i]);
reader.readAsDataURL(f[i]);
}
}
function initCanvas(w,h)
{
gCanvas = document.getElementById("qr-canvas");
gCanvas.style.width = w + "px";
gCanvas.style.height = h + "px";
gCanvas.width = w;
gCanvas.height = h;
gCtx = gCanvas.getContext("2d");
gCtx.clearRect(0, 0, w, h);
}
function captureToCanvas() {
if(stype!=1)
return;
if(gUM)
{
try{
gCtx.drawImage(v,0,0);
try{
qrcode.decode();
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
}
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function read(a)
{
var html="<br>";
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
html+="<a target='_blank' href='"+a+"'>"+a+"</a><br>";
html=htmlEntities(a);
//document.getElementById("result").innerHTML=html;
//document.getElementById("employee_code").value=html;
getWebQrCode(a);//need to use in our script page with params in which we will get the qr code number...DEC-16-2015 by rafeeq
//runInScan();
//$('#acc').prop('disabled', false);
//$('#uni_code').val(html);
}
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
function success(stream) {
if(webkit)
v.src = window.webkitURL.createObjectURL(stream);
else
if(moz)
{
v.mozSrcObject = stream;
v.play();
}
else
v.src = stream;
gUM=true;
setTimeout(captureToCanvas, 500);
}
function error(error) {
gUM=false;
return;
}
function load()
{
if(isCanvasSupported() && window.File && window.FileReader)
{
initCanvas(800, 600);
qrcode.callback = read;
document.getElementById("mainbody").style.display="inline";
setwebcam();
}
else
{
document.getElementById("mainbody").style.display="inline";
document.getElementById("mainbody").innerHTML='<p id="mp1">QR code scanner for HTML5 capable browsers</p><br>'+
'<br><p id="mp2">sorry your browser is not supported</p><br><br>'+
'<p id="mp1">try <a href="http://www.mozilla.com/firefox"><img src="firefox.png"/></a> or <a href="http://chrome.google.com"><img src="chrome_logo.gif"/></a> or <a href="http://www.opera.com"><img src="Opera-logo.png"/></a></p>';
}
}
function setwebcam()
{
document.getElementById("result").innerHTML="- scanning -";
if(stype==1)
{
setTimeout(captureToCanvas, 500);
return;
}
var n=navigator;
document.getElementById("outdiv").innerHTML = vidhtml;
v=document.getElementById("v");
if(n.getUserMedia)
n.getUserMedia({video: true, audio: false}, success, error);
else
if(n.webkitGetUserMedia)
{
webkit=true;
n.webkitGetUserMedia({video: true, audio: false}, success, error);
}
else
if(n.mozGetUserMedia)
{
moz=true;
n.mozGetUserMedia({video: true, audio: false}, success, error);
}
//document.getElementById("qrimg").src="qrimg2.png";
//document.getElementById("webcamimg").src="webcam.png";
document.getElementById("qrimg").style.opacity=0.2;
document.getElementById("webcamimg").style.opacity=1.0;
stype=1;
setTimeout(captureToCanvas, 500);
}
function setimg()
{
document.getElementById("result").innerHTML="";
if(stype==2)
return;
document.getElementById("outdiv").innerHTML = imghtml;
//document.getElementById("qrimg").src="qrimg.png";
//document.getElementById("webcamimg").src="webcam2.png";
document.getElementById("qrimg").style.opacity=1.0;
document.getElementById("webcamimg").style.opacity=0.2;
var qrfile = document.getElementById("qrfile");
qrfile.addEventListener("dragenter", dragenter, false);
qrfile.addEventListener("dragover", dragover, false);
qrfile.addEventListener("drop", drop, false);
stype=2;
}
|
'use strict';
var chai = require('chai');
var expect = chai.expect;
var cycle = require('../');
var decycle = cycle.decycle;
var retrocycle = cycle.retrocycle;
var stringify = cycle.stringify;
var parse = cycle.parse;
describe('Json Cycle', function () {
var arr = [];
var prev = null;
var cnt = 100;
for (var i = 0; i < cnt; ++i) {
prev = arr[i] = {
prev: prev
};
}
arr[0].prev = arr[cnt - 1];
it('should failed with TypeError: Converting circular structure to JSON', function (done) {
expect(function () {
JSON.stringify(arr);
}).to.throw(Error);
done();
});
describe("#decycle + #JSON.stringify", function () {
it('should not failed after decycle', function (done) {
expect(function () {
JSON.stringify(decycle(arr));
}).to.not.throw(Error);
done();
});
it("should not failed with circular objects", function () {
var foo = {
prop: "dummy"
};
foo.bar = foo;
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular objects with intermediaries", function () {
var foo = {
prop: "dummy"
};
foo.bar = {
foo: foo
};
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular objects deeper", function () {
var foo = {
prop: "dummy",
bar: {
prop: "dummy"
}
};
foo.bar.self = foo.bar;
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular objects deeper with intermediaries", function () {
var foo = {
prop: "dummy",
bar: {
prop: "dummy"
}
};
foo.bar.zoo = {
self: foo.bar
};
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular objects in an array", function() {
var foo = {
prop: "dummy"
};
foo.bar = [foo, foo];
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular objects deeper in an array", function() {
var foo = {
prop: "dummy",
bar: [{
prop: "dummy"
}, {
prop: "dummy2"
}]
};
foo.bar[0].self = foo.bar[0];
foo.bar[1].self = foo.bar[1];
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular arrays", function() {
var foo = [];
foo.push(foo);
foo.push(foo);
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular arrays with intermediaries", function() {
var foo = [];
foo.push({ bar: foo });
foo.push({ bar: foo });
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular repeated objects in objects", function() {
var foo = {};
var bar = {
prop: "dummy"
};
foo.bar1 = bar;
foo.bar2 = bar;
expect(function () {
JSON.stringify(decycle(foo));
}).to.not.throw(Error);
});
it("should not failed with circular repeated objects in arrays", function() {
var foo = {
prop: "dummy"
};
var bar = [foo, foo];
expect(function () {
JSON.stringify(decycle(bar));
}).to.not.throw(Error);
});
});
describe("#stringify", function () {
it('should not failed', function (done) {
expect(function () {
stringify(arr);
}).to.not.throw(Error);
done();
});
});
describe("#parse", function () {
it('should not failed', function (done) {
var foo = {
baz: "bar",
};
expect(parse('{"baz":"bar"}')).to.deep.equal(foo);
done();
});
});
it('should be the same after retrocycling on decycled structure', function (done) {
expect(arr).to.deep.equal(retrocycle(decycle(arr)));
done();
});
it('toJSON should have been called', function() {
class Baz {
constructor() {
this.bar = 'bar';
}
toJSON() {
return this.bar;
}
}
var foo = {
baz: new Baz(),
};
expect(JSON.stringify(decycle(foo))).to.equal('{"baz":"bar"}');
});
});
|
'use strict';
angular.module('app').controller('DepositCtrl', ['$scope', '$location', '$modal', 'Deposit', function($scope, $location, $modal, Deposit) {
$scope.url = 'api/deposits.json';
$scope.openModalAddDeposit = function() {
$modal({
title: 'New deposit',
template: '/js/app/deposit/modal_add.html',
animation:'am-fade-and-scale',
placement:'center',
show: true,
scope: $scope
});
};
$scope.$on('deposit:create', function(e, deposit) {
$scope.deposits.unshift(deposit);
});
}]);
|
(function() {
/*jshint bitwise: false*/
'use strict';
angular
.module('helloJhipsterApp')
.factory('Base64', Base64);
function Base64 () {
var keyStr = 'ABCDEFGHIJKLMNOP' +
'QRSTUVWXYZabcdef' +
'ghijklmnopqrstuv' +
'wxyz0123456789+/' +
'=';
var service = {
decode : decode,
encode : encode
};
return service;
function encode (input) {
var output = '',
chr1, chr2, chr3,
enc1, enc2, enc3, enc4,
i = 0;
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
}
return output;
}
function decode (input) {
var output = '',
chr1, chr2, chr3,
enc1, enc2, enc3, enc4,
i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
while (i < input.length) {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 !== 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output = output + String.fromCharCode(chr3);
}
}
return output;
}
}
})();
|
jQuery(function($){
//------------------------------------
// Properties
//------------------------------------
//data
var scares = [
'broccoli.jpg',
'broken_ipads.jpg',
'zuchinni.jpg',
// 'Stinky Cheese',
'homework.jpg',
// 'mondays',
'braces.jpg',
// 'cooties',
'the_dentist.jpg',
// 'cool parents',
'cheek_pinches.jpg',
// 'cough syrup',
// 'bugs',
// 'paper cuts',
// 'pea soup',
// 'tests',
// 'getting clothes for your birthday',
'too_much_tickling.jpg'
// 'no tv',
// 'no ipads',
// 'no video games',
// 'no minecraft',
// 'no adventuretime',
]
//services
var socket;
var _connectionstatus;
var soundLevel = 0;
var $output;
var imageEl = $('#image');
var videoEl = $('#video');
var $player;
var player;
var $image;
var running = false;
//controllers
var actions = {
remote:{
'spike' : handleSpike,
'moduleError' : handleModuleError,
'handleSoundLevelError' : handleSoundLevelError,
'soundLevel' : handleSoundLevel
}
}
//------------------------------------
// Initialization
//------------------------------------
function init(){
initVideo();
initImage();
initOutput();
bindSocket();
bindWindow();
resize();
}
function initVideo(){
player = document.createElement('video');
$player = $(player);
$player.attr({
src: './vid/boo.m4v',
autoPlay:false,
controls:false,
loop:false
});
$player.on('ended', handleVideoEnd);
videoEl.append($player);
$player.hide();
}
function initImage(){
var image = document.createElement('img');
$image = $(image);
imageEl.append($image);
$image.attr({
src: './img/broccoli.jpg'
});
$image.addClass('tossing');
$image.hide();
}
function initOutput(){
for(var i =0 ; i<10; i++){
var span = $('<span class="output" style="-webkit-animation-delay:'+((i-10)/20)+'s">');
$(document.body).append(span);
}
$output = $(document.body).find('span');
}
//------------------------------------
// Logic
//------------------------------------
/*
* Establish Socket connection and fallbacks for errors
*/
function bindSocket(pairid){
socket = io.connect(SOCKET, {'force new connection': true, 'reconnect': false,'sync disconnect on unload': true,});
socket.on("connecting", connecting);
socket.on("connect", bindRemoteActions);
socket.on("error", connectError);
socket.on("connect_failed", connectFail);
}
function bindWindow(){
$(window).on('resize', resize);
$(window).on('keyup', function(evt){
if(evt.keyCode == 32){
handleSpacePress(evt);
//handleSpike();
}
});
}
/*
* On connection listen for events broadcast from socket
*/
function bindRemoteActions(){
draw('connected');
$output.hide();
socket.on("disconnect", disconnect);
socket.on("socket_invalid", connectError);
$.each(actions.remote, registerRemoteAction);
}
function registerRemoteAction(path, action){
socket.on(path, function(data){ action(data); });
}
//------------------------------------
// Control
//------------------------------------
/*
* Connection Management
*/
function connecting(){
draw('connecting...');
}
function disconnect(){
if(_connectionstatus != 'erred'){
_connectionstatus = 'disconnected';
draw('disconnected');
}
}
function connectError(err){
console.log(err);
_connectionstatus = 'erred';
draw('erred');
}
function connectFail(){
_connectionstatus = 'failed';
draw('failed')
}
function emit(event, data){
console.log('emit :: ' + event + " : " + data);
if(socket) socket.emit(event, data);
}
//------------------------------------
// View States
//------------------------------------
//-------------------------------------
// Render
//-------------------------------------
function draw(output){
$output.html(output);
}
function resize(){
var w = $(window).width();
var h = $(window).height();
videoEl.css({
width:w,
height:h,
});
imageEl.css({
width:w/2,
height:h
});
$image.css({
width:w/2,
height:h
});
player.videoWidth = player.width = w;
player.videoHeight = player.height = h;
}
//------------------------------
// Events
//------------------------------
function handleSpike(data){
if(!running){
var ranIndex = Math.floor((Math.random() * scares.length));
var scare = scares[ranIndex]
draw(scare.replace(/_/g, " ").replace(".jpg", ""));
$image.attr('src', 'img/'+scare);
$player.fadeIn();
$image.delay(8000).fadeIn();
$output.delay(8000).fadeIn();
player.play();
running = true;
}
}
function handleTrigger(data){
//draw('trigger' + data);
}
function handleSoundLevel(data){
soundLevel = data;
//draw('level' + data);
}
function handleSoundLevelError(err){
//draw('level error' + err);
}
function handleModuleError(err){
//draw('module error' + err);
}
function handleConnected(err){
if(err){
//draw('connect err');
}else{
listen();
}
}
function handleVideoEnd(){
$player.fadeOut();
$image.fadeOut();
$output.fadeOut();
player.pause();
player.currentTime = 0;
setTimeout(function(){
running = false;
}, 5000);
}
function handleSpacePress(evt){
socket.emit('retrain', {});
handleVideoEnd();
}
//-------------------------------------
// Startup
//-------------------------------------
init();
});
|
var sql = require('mssql')
var config = {
user: 'Nodejs',
password: '123',
server: 'frosh', // You can use 'localhost\\instance' to connect to named instance
database: 'UM',
}
function RunSP(spName, params, callback) {
var dt = new sql.Table();
dt.columns.add('Type', sql.NVarChar(50), true)
dt.columns.add('Name', sql.NVarChar(50), false)
dt.columns.add('Value', sql.NVarChar(3000), false)
dt.rows.add('', '_SpName', spName)
if (params)
Object.getOwnPropertyNames(params).forEach(function (val, idx, array) {
dt.rows.add('', val, params[val]);
});
var connection = new sql.Connection(config, function (err) {
// ... error checks
var request = new sql.Request(connection);
request.input('params', dt);
request.execute('RunSP', function (err, recordsets, returnValue) {
// ... error checks
var outlet = {}
var tableMap = recordsets[recordsets.length - 1]
for (var index = 0; index <= recordsets.length - 2; index++) {
switch (tableMap[index].TableType) {
case "D":
outlet[tableMap[index].TableName] = recordsets[index];
break;
case "E":
case "M":
outlet['Messages'] = recordsets[index];
break;
case "S":
outlet['Schema'] = recordsets[index];
break;
}
outlet.Map = tableMap;
}
callback(err, outlet)
});
});
}
module.exports = RunSP |
document.addEventListener("DOMContentLoad",typeWriter,false);
var typeWriter = function(selector,type,interval) {
var el = document.querySelectorAll(selector), // Getting elements in the DOM
i = 0,
len = el.length, // Length of element on the page
list = []; // List of elements on the page in the DOM
for(i; i < len; i++) {
list.push(el[i]); // Pushing the element in the list array
}
for(a in list) {
var all = list[a], // List of all element
text = all.innerHTML += " <span id='cursor'>|</span>", // InnerHTML of the elements
start = 0, // Start index of the text in the elements
end = 0, // End index of the text in the elements
nextText, //Animated Text
style = document.createElement("style");
document.head.appendChild(style);
if(typeof interval === "undefined") {
interval = 100;
}
if(arguments[1] === "true") {
var clear = setInterval(function() { // Animation start
newText = text.substr(start,end);
all.innerHTML = newText += " <span id='cursor'>|</span>" ;
end = end + 1; //loops through the text in the element
if(newText === text) {
clearInterval(clear); // Animation end
}
},interval);
}
return all;
}
}
typeWriter("#welcome","true",100);
|
"use babel";
import JSBeautify from "js-beautify";
import fs from "fs";
import path from "path";
import BeautifierError from "./error.js";
export default class Beautifier {
constructor() {
this.projectPath = null;
this.config = null;
}
resetConfig() {
this.config = null;
}
getConfig(projectPath) {
return new Promise((resolve, reject) => {
if(projectPath) {
let filename = path.resolve(projectPath, ".jsbeautifyrc");
fs.readFile(filename, "utf8", (err, data) => {
if(err)
reject(new BeautifierError(
".jsbeautifyrc not found",
"Beautify with default configurations",
err
));
try {
resolve(JSON.parse(data));
} catch(exception) {
reject(new BeautifierError(
"An exception occurred when parsing json configuration file " + filename,
"Beautify with default configurations",
exception
));
}
});
} else
reject(new BeautifierError(
"Wrong project path",
"No beautification",
"path is null"
));
});
}
checkConfig(projectPath) {
if(projectPath !== this.projectPath) {
console.log("atom-formatter-jsbeautify", "Beautifier->exec()", "Project folder updated: Configurations are going to be reloaded.");
this.projectPath = projectPath;
return this.getConfig(projectPath);
}
console.log("atom-formatter-jsbeautify", "Beautifier->exec()", "Same project folder.");
return new Promise((resolve, reject) => {
resolve(this.config);
});
}
js(projectPath, data) {
return this.checkConfig(projectPath).then((config) => {
if(this.config !== config)
this.config = config;
let beautifiedData = JSBeautify.js(data, config);
return new Promise((resolve, reject) => {
if(beautifiedData)
resolve(beautifiedData);
else
reject(new BeautifierError("Empty Code or An error occurred", "Attempt to beautify with default configurations"));
});
});
}
css(projectPath, data) {
return this.checkConfig(projectPath).then((config) => {
if(this.config !== config)
this.config = config;
let beautifiedData = JSBeautify.css(data, config);
return new Promise((resolve, reject) => {
if(beautifiedData)
resolve(beautifiedData);
else
reject(new BeautifierError("Empty Code or An error occurred", "Attempt to beautify with default configurations"));
});
});
}
html(projectPath, data) {
return this.checkConfig(projectPath).then((config) => {
if(this.config !== config)
this.config = config;
let beautifiedData = JSBeautify.html(data, config);
return new Promise((resolve, reject) => {
if(beautifiedData)
resolve(beautifiedData);
else
reject(new BeautifierError("Empty Code or An error occurred", "Attempt to beautify with default configurations"));
});
});
}
jsDefault(data) {
this.resetConfig();
return JSBeautify.js(data);
}
cssDefault(data) {
this.resetConfig();
return JSBeautify.css(data);
}
htmlDefault(data) {
this.resetConfig();
return JSBeautify.html(data);
}
}
|
import * as React from 'react';
function CurrencyPoundIcon(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
{...props}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 9a2 2 0 10-4 0v5a2 2 0 01-2 2h6m-6-4h4m8 0a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
);
}
export default CurrencyPoundIcon;
|
import React from 'react'
import { Link } from 'react-router-dom'
import Logo from './Logo'
import Navigations from './Navigations'
export default class Header extends React.Component {
constructor (props) {
super (props)
this.state = {
menuButtonIsActive: false,
innerWidth: window.innerWidth,
isTablet: false,
isMobile: false
}
window.scrollTo(0, 0)
}
componentDidMount() {
this.listenResizeEvent()
window.addEventListener('resize', this.listenResizeEvent)
}
componentWillUnmount () {
window.removeEventListener('resize', this.listenResizeEvent)
}
componentWillReceiveProps () {
window.scrollTo(0, 0)
}
listenResizeEvent = (event) => {
this.setState({
innerWidth: window.innerWidth
}, () => {
if (this.state.innerWidth <= 500)
this.setState({ isTablet: false, isMobile: true })
else if ((this.state.innerWidth > 500) && (this.state.innerWidth <= 902))
this.setState({ isTablet: true, isMobile: false })
else
this.setState({
menuButtonIsActive: false,
isTablet: false,
isMobile: false
})
})
}
render () {
return (
<div>
<div className='header'>
<div className='wrapper'>
<div className='logo'>
<Link to='/' >
<Logo />
</Link>
</div>
{
this.state.innerWidth > 902
? <Navigations blog={this.props.blog} inside={true}/>
: (
<div
className='menu-button'
onClick={
() => this.setState({
menuButtonIsActive: !this.state.menuButtonIsActive
}, () => {
if(this.state.menuButtonIsActive)
document.getElementsByTagName("body")[0].style.overflow = 'hidden'
else
document.getElementsByTagName("body")[0].style.overflow = 'scroll'
})
}
>
<div className='menu-text'>
{
this.state.menuButtonIsActive
? "CLOSE"
: "MENU"
}
</div>
</div>
)
}
</div>
{
this.state.menuButtonIsActive
? <div > <Navigations device={this.state.isTablet ? 'tablet-menus' : 'mobile-menus'} inside={false}/> </div>
: null
}
</div>
</div>
)
}
} |
dataCallback({
'collections': [
{
'index': 0,
'items': [
['Shrugs & Cardigans', '27', '30'],
['Sweaters', '27', '30'],
['Sets', '27', '30'],
['Shirts & Blouse', '27', '30'],
['Shorts', '27', '30'],
['Shoes', '27', '30'],
['Semiformal', '27', '30'],
['Seamless', '27', '30'],
['Special Occasion', '27', '30'],
['Socks\\/Footwear', '27', '30']
],
'title': 'Category',
'type': 'department'
},
{
'index': 1,
'items': [
['Solid Dress', 'Casual', 'c3,44'],
['Stretch Bracelet', 'Bracelets', 'c3=153'],
['Striped Top', 'Fashion Tops', 'c3=254'],
['stripe cardigan', 'Shrugs & Cardigans', 'c3=27'],
['SOLID TOP', 'Dressy Tops', 'c3=18'],
['Sweater top', 'Fashion Tops', 'c3=254'],
['SOLID TOP', 'Casual', 'c3=210'],
['SLEEVELESS TOP', 'Fashion Tops', 'c3=254'],
['SOLID TOP', 'Fashion Tops', 'c3=254'],
['STRIPED TOP', 'Casual', 'c3=210']
],
'title': 'Product in Category',
'type': 'srch_in_department'
},
{
'index': 2,
'items': [
['Skinny jeans'],
['shirt dress'],
['SWEATSHIRT'],
['striped dress'],
['sweat pants'],
['stripe CARDIGAN'],
['SunGlasses'],
['short sleeve'],
['Shopwtd'],
['shorts']
],
'title': 'Product',
'type': 'srch'
}
],
'query': ['s'],
'ver': '1.0'
}
);
|
'use strict';
/**
* @ngdoc overview
* @name trellocloneApp
* @description
* # trellocloneApp
*
* Main module of the application.
*/
angular
.module('trellocloneApp', [
'ngRoute',
'ui.sortable',
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/workitems.html',
controller: 'WorkItemCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.otherwise({
redirectTo: '/'
});
}, '$httpProvider',
function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
}
);
// .config([
// '$routeProvider',
// '$httpProvider',
// function($routeProvider, $httpProvider){
// $httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
// }
// ]); |
export default {
api_server: 'http://schedulerpre.myhopin.com/api',
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
// import { bindActionCreators } from 'redux';
import { fetchPosts } from '../actions/index';
import { Link } from 'react-router';
class PostsIndex extends Component {
componentWillMount(){
this.props.fetchPosts();
}
renderPosts(){
return this.props.posts.map((post) => {
return(
<li className="list-group-item" key={post.id}>
<Link to={"posts/" + post.id}>
<span className="pull-xs-right">{post.categories}</span>
<strong>{post.title}</strong>
</Link>
</li>
)
});
}
render(){
return(
<div>
<div className="text-xs-right">
<Link to="posts/new" className="btn btn-primary">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state){
return{
posts : state.posts.all
}
}
// function mapDispatchToProps(dispatch){
// return bindActionCreators({fetchPosts}, dispatch);
// }
// export default connect(null, mapDispatchToProps)(PostsIndex);
// export default connect(null, {fetchPosts: fetchPosts})(PostsIndex);
// export default connect(null, { fetchPosts })(PostsIndex);
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
|
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "sportsdata_nba_v3_rotoballer_premium_news"); |
var NotificationView = "";
$(function () {
var storeId = AspxCommerce.utils.GetStoreID();
var portalId = AspxCommerce.utils.GetPortalID();
var userName = AspxCommerce.utils.GetUserName();
var cultureName = AspxCommerce.utils.GetCultureName();
NotificationView = {
config: {
isPostBack: false,
async: false,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: 'json',
baseURL: ModulePath + "AspxNotificationWebService.asmx/",
method: "",
url: "",
ajaxCallMode: ""
},
ajaxCall: function (config) {
$.ajax({
type: NotificationView.config.type,
contentType: NotificationView.config.contentType,
cache: NotificationView.config.cache,
async: NotificationView.config.async,
url: NotificationView.config.url,
data: NotificationView.config.data,
dataType: NotificationView.config.dataType,
success: NotificationView.config.ajaxCallMode,
error: NotificationView.ajaxFailure
});
},
GetAllNotifications: function () {
var param = JSON2.stringify({ storeID: storeId, portalID: portalId, cultureName: cultureName });
NotificationView.config.method = "GetAllNotification";
NotificationView.config.url = this.config.baseURL + this.config.method;
NotificationView.config.data = param;
NotificationView.config.ajaxCallMode = NotificationView.BindNotificationData;
NotificationView.ajaxCall(NotificationView.config);
},
GetAllNotificationByType: function (notificationTypeID) {
var param = JSON2.stringify({ notificationTypeID: notificationTypeID, storeID: storeId, portalID: portalId, cultureName: cultureName });
NotificationView.config.method = "GetNotificationByType";
NotificationView.config.url = this.config.baseURL + this.config.method;
NotificationView.config.data = param;
NotificationView.config.ajaxCallMode = NotificationView.BindNotificationByTypeData;
NotificationView.ajaxCall(NotificationView.config);
},
UpdateNotification: function (notificationID) {
var param = JSON2.stringify({ notificationID: notificationID, storeID: storeId, portalID: portalId });
this.config.method = "UpdateNotification";
this.config.url = this.config.baseURL + this.config.method;
this.config.data = param;
this.ajaxCall(this.config);
},
BindNotificationData: function (data) {
if (data.d.length > 0) {
var htmlc = "";
nbc_notifs = 0;
var htmlo = "";
nbo_notifs = 0;
$.each(data.d, function (index, item) {
if (item.NotificationTypeID == 3) {
nbc_notifs = item.NotificationCount;
$("#customers_notif_value").attr("notifyType", item.NotificationTypeID);
}
if (item.NotificationTypeID == 1) {
nbo_notifs = item.NotificationCount;
$("#orders_notif_value").attr("notifyType", item.NotificationTypeID);
}
});
if (nbc_notifs > 0) {
$("#list_customers_notif").prev("p").hide();
$("#customers_notif_value").text(nbc_notifs);
$("#customers_notif_number_wrapper").show();
}
else {
$("#customers_notif_number_wrapper").hide();
}
if (nbo_notifs > 0) {
$("#list_orders_notif").prev("p").hide();
$("#orders_notif_value").text(nbo_notifs);
$("#orders_notif_number_wrapper").show();
}
else {
$("#orders_notif_number_wrapper").hide();
}
}
},
BindNotificationByTypeData: function (data) {
if (data.d.length > 0) {
var htmlc = "";
nbc_notifs = 0;
var htmlo = "";
nbo_notifs = 0;
$.each(data.d, function (index, item) {
if (item.NotificationTypeID == 3) {
htmlc += "<li>" + getLocale(AspxNotification, "A new Customer has been registered on your shop") + "<br />" + getLocale(AspxNotification, "Customer Name:") + "<strong><a id='lnkCustomerDetail' notifyID=" + item.NotificationID + " customerID=" + item.UserName + ">" + item.UserName + "</a></strong></li>";
}
if (item.NotificationTypeID == 1) {
htmlo += "<li>" + getLocale(AspxNotification, "A new Order has been placed on your shop") + "<br />" + getLocale(AspxNotification, "Order ID:") + "<strong>" + item.OrderID + "</strong><br /><a id='lnkOrderDetail' notifyID=" + item.NotificationID + " href=\"#" + "\">" + getLocale(AspxNotification, "See Order Detail") + "</a></li>";
}
});
if (htmlc != "") {
$("#list_customers_notif").prev("p").hide();
$("#list_customers_notif").empty().append(htmlc);
}
else {
$("#customers_notif_number_wrapper").hide();
}
if (htmlo != "") {
$("#list_orders_notif").prev("p").hide();
$("#list_orders_notif").empty().append(htmlo);
}
else {
$("#orders_notif_number_wrapper").hide();
}
}
},
init: function () {
NotificationView.GetAllNotifications();
var youEditFieldFor = "";
var hints = $('.translatable span.hint');
if (youEditFieldFor) {
hints.html(hints.html() + '<br /><span class="red">' + youEditFieldFor + '</span>');
}
var html = "";
var nb_notifs = 0;
var wrapper_id = "";
var type = new Array();
var notificationTypeID = 0;
var notificationCount = 0;
$(".notifs").on("click", function () {
$('.notifs').removeClass('open_notifs');
$(this).addClass('open_notifs');
wrapper_id = $(this).attr("id");
type = wrapper_id.split("s_notif")
notificationTypeID = $(this).children("span").children("span").attr("notifyType");
notificationCount = $(this).children("span").children("span").html();
if (!$("#" + wrapper_id + "_wrapper").is(":visible")) {
$(".notifs_wrapper").hide();
$("#" + wrapper_id + "_number_wrapper").hide();
$("#" + wrapper_id + "_wrapper").show();
} else {
$("#" + wrapper_id + "_wrapper").hide();
}
if (notificationCount > 0) {
NotificationView.GetAllNotificationByType(notificationTypeID);
}
});
$("#main").click(function () {
$(".notifs_wrapper").hide();
$('.notifs').removeClass('open_notifs');
});
$("#lnkCustomerDetail").on("click", function () {
var notificationID = $(this).attr("notifyID");
var customerID = $(this).attr("customerID");
NotificationView.UpdateNotification(notificationID);
window.location = AspxCommerce.utils.GetAspxRedirectPath() + "Admin/Users-Management.aspx?id=" + customerID + "";
});
$("#lnkShowAllCustomers").on("click", function () {
window.location = AspxCommerce.utils.GetAspxRedirectPath() + "Admin/Users-Management.aspx";
});
}
}
NotificationView.init();
}); |
/**
* @class Navy.Transition.SlideDown
*/
Navy.Class('Navy.Transition.SlideDown', Navy.Transition.Transition, {
$static: {
initAnimationStyle: false
},
_beforeView: null,
_afterView: null,
initialize: function(beforeView, afterView){
this._beforeView = beforeView;
this._afterView = afterView;
if (!this.$class.initAnimationStyle) {
this._addAnimationStyle();
this.$class.initAnimationStyle = true;
}
var height = Navy.Config.app.size.height;
afterView._setRawStyle({webkitAnimation: '0.5s', webkitTransform: 'translateY(-' + height + 'px)'});
afterView.setVisible(true);
},
_addAnimationStyle: function(){
var height = Navy.Config.app.size.height;
var animIn = '@-webkit-keyframes slide_up_in {100% {-webkit-transform: translateY(0)}}';
var animOut = '@-webkit-keyframes slide_up_out {100% {-webkit-transform: translateY(-%height%px)}}'.replace('%height%', height);
var styleElm = document.createElement('style');
styleElm.textContent = animIn + animOut;
document.head.appendChild(styleElm);
},
start: function(callback) {
if (!this._beforeView) {
this._afterView._setRawStyle({webkitTransform: 'none'});
callback && callback();
return;
}
var cb = function(){
this._beforeView.setVisible(false);
this._afterView.removeRawEventListener('webkitAnimationEnd', cb);
this._afterView._setRawStyle({webkitTransform: 'none', webkitAnimationName: 'none'});
callback && callback();
}.bind(this);
this._afterView.addRawEventListener('webkitAnimationEnd', cb);
this._afterView._setRawStyle({webkitAnimationName: 'slide_up_in'});
},
back: function(callback) {
if (!this._beforeView) {
callback && callback();
return;
}
var cb = function(){
this._afterView.removeRawEventListener('webkitAnimationEnd', cb);
callback && callback();
}.bind(this);
this._beforeView.setVisible(true);
this._afterView.addRawEventListener('webkitAnimationEnd', cb);
this._afterView._setRawStyle({webkitAnimationName: 'slide_up_out'});
}
});
|
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var pkg = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('archive:create_archive_dir', function () {
fs.mkdirSync(path.resolve(dirs.archive), '0755');
});
gulp.task('archive:zip', function (done) {
var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
var archiver = require('archiver')('zip');
var files = require('glob').sync('**/*.*', {
'cwd': dirs.dist,
'dot': true // include hidden files
});
var output = fs.createWriteStream(archiveName);
archiver.on('error', function (error) {
done();
throw error;
});
output.on('close', done);
files.forEach(function (file) {
var filePath = path.resolve(dirs.dist, file);
// `archiver.bulk` does not maintain the file
// permissions, so we need to add files individually
archiver.append(fs.createReadStream(filePath), {
'name': file,
'mode': fs.statSync(filePath)
});
});
archiver.pipe(output);
archiver.finalize();
});
gulp.task('clean', function (done) {
require('del')([
dirs.archive,
dirs.dist
], done);
});
gulp.task('copy', [
'copy:.htaccess',
'copy:index.html',
'copy:jquery',
'copy:license',
'copy:main.css',
'copy:misc',
'copy:normalize'
]);
gulp.task('copy:.htaccess', function () {
return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:index.html', function () {
return gulp.src(dirs.src + '/index.html')
.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:license', function () {
return gulp.src('LICENSE.txt')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:main.css', function () {
var banner = '/*! HTML5 Boilerplate v' + pkg.version +
' | ' + pkg.license.type + ' License' +
' | ' + pkg.homepage + ' */\n\n';
return gulp.src(dirs.src + '/css/main.css')
.pipe(plugins.header(banner))
.pipe(plugins.autoprefixer({ browsers: ['last 2 versions', 'ie >= 8', '> 1%'], cascade: false }))
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
dirs.src + '/**/*',
// Exclude the following files
// (other tasks will handle the copying of these files)
'!' + dirs.src + '/css/main.css',
'!' + dirs.src + '/index.html'
], {
// Include hidden files by default
dot: true
}).pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('lint:js', function () {
return gulp.src([
'gulpfile.js',
dirs.src + '/js/*.js',
dirs.test + '/*.js'
]).pipe(plugins.jscs())
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('archive', function (done) {
runSequence(
'build',
'archive:create_archive_dir',
'archive:zip',
done);
});
gulp.task('build', function (done) {
runSequence(
['clean', 'lint:js'],
'copy',
done);
});
gulp.task('default', ['build']);
|
import { foo as bar } from 'foo';
var foo;
class C extends D {} |
require("source-map-support").install();
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(6);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.baseId = exports.id = undefined;
exports.equals = equals;
exports.is = is;
exports.getIdChain = getIdChain;
exports.completeAssignToThis = completeAssignToThis;
exports.nameObj = nameObj;
exports.nameClass = nameClass;
var _getPrototypeChain = __webpack_require__(3);
var _getPrototypeChain2 = _interopRequireDefault(_getPrototypeChain);
var _protoExtend = __webpack_require__(8);
var _protoExtend2 = _interopRequireDefault(_protoExtend);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var id = exports.id = Symbol.for('strictduck/id');
var baseId = exports.baseId = Symbol.for('strictduck');
function equals(duckA, duckB) {
return duckA[id] && duckB[id] && duckA[id] == duckB[id];
}
function is(_ref) {
var instance = _ref.instance;
var Class = _ref.Class;
return (0, _getPrototypeChain2.default)(instance).filter(function (p) {
return equals(p, Class);
}).length > 0;
}
function getIdChain(duck) {
return (0, _getPrototypeChain2.default)(duck).map(function (p) {
return p[id];
});
}
function extendFromBase(objProto, baseProto) {
if (Object.getPrototypeOf(objProto) == null || (0, _getPrototypeChain2.default)(baseProto).indexOf(objProto) > -1) {
return baseProto;
} else {
Object.setPrototypeOf(objProto, extendFromBase(objProto.__proto__, baseProto));
return objProto;
}
}
function extendThisFromBase(base) {
if (Object.getPrototypeOf(this) != null) {
Object.setPrototypeOf(this, extendFromBase(Object.getPrototypeOf(this), Object.getPrototypeOf(base)));
} else {
Object.setPrototypeOf(this, Object.getPrototypeOf(base));
}
}
function completeAssignToThis(source) {
extendThisFromBase.bind(this)(source);
var descriptors = Object.getOwnPropertyNames(source).reduce(function (descriptors, key) {
if (key != 'constructor') descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, {});
// by default, Object.assign copies enumerable Symbols too
Object.getOwnPropertySymbols(source).forEach(function (sym) {
var descriptor = Object.getOwnPropertyDescriptor(source, sym);
if (descriptor.enumerable) {
descriptors[sym] = descriptor;
}
});
Object.defineProperties(this, descriptors);
}
function nameObj(_ref2) {
var name = _ref2.name;
var object = _ref2.object;
var dict = {};
dict[name] = object;
Object.defineProperty(dict[name], 'name', {
configurable: true, value: name
});
return dict[name];
}
function parentId(_ref3) {
var Class = _ref3.Class;
return (Class.prototype || {})[id] || baseId;
}
function extendParentSymbolFor(_ref4) {
var Class = _ref4.Class;
var name = _ref4.name;
var parentPath = Symbol.keyFor(parentId({ Class: Class }));
return Symbol.for(name ? parentPath + '.' + name : parentPath);
}
function nameClass(_ref5) {
var name = _ref5.name;
var Class = _ref5.Class;
var symbol = extendParentSymbolFor({ name: name, Class: Class });
Class[id] = symbol;
Class.prototype[id] = symbol;
return nameObj({ name: name, object: Class });
}
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Main = undefined;
exports.shouldImplement = shouldImplement;
exports.extend = extend;
var _duckface = __webpack_require__(7);
var _duckface2 = _interopRequireDefault(_duckface);
var _getPrototypeChain = __webpack_require__(3);
var _getPrototypeChain2 = _interopRequireDefault(_getPrototypeChain);
var _utils = __webpack_require__(1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function shouldImplement(_ref) {
var _ref$name = _ref.name;
var name = _ref$name === undefined ? 'strictduckInterface' : _ref$name;
var _ref$methods = _ref.methods;
var methods = _ref$methods === undefined ? [] : _ref$methods;
var face = new _duckface2.default(name, methods);
return function (instance) {
return _duckface2.default.ensureImplements(instance, face);
};
}
function firstToLowerCase(str) {
return str.substr(0, 1).toLowerCase() + str.substr(1);
}
var StrictDuck = function StrictDuck(instance) {
_classCallCheck(this, StrictDuck);
var copy = typeof instance == 'function' ? function () {} : new Object();
Object.setPrototypeOf(copy, Object.getPrototypeOf(this));
_utils.completeAssignToThis.bind(copy)(instance);
for (var _len = arguments.length, interfaces = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interfaces[_key - 1] = arguments[_key];
}
interfaces.forEach(function (i) {
return typeof i == 'function' ? i(copy) : shouldImplement(i)(copy);
});
return (0, _utils.nameObj)({
name: firstToLowerCase(Object.getPrototypeOf(this).constructor.name),
object: copy
});
};
exports.default = StrictDuck;
StrictDuck[_utils.id] = _utils.baseId;
StrictDuck.prototype[_utils.id] = _utils.baseId;
function extend(_ref2) {
var name = _ref2.name;
var _ref2$parent = _ref2.parent;
var parent = _ref2$parent === undefined ? StrictDuck : _ref2$parent;
var _ref2$interfaces = _ref2.interfaces;
var interfaces = _ref2$interfaces === undefined ? [] : _ref2$interfaces;
var _ref2$methods = _ref2.methods;
var methods = _ref2$methods === undefined ? [] : _ref2$methods;
return (0, _utils.nameClass)({
name: name || parent.name,
Class: function (_parent) {
_inherits(Class, _parent);
function Class(instance) {
var _Object$getPrototypeO;
_classCallCheck(this, Class);
for (var _len2 = arguments.length, otherInterfaces = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
otherInterfaces[_key2 - 1] = arguments[_key2];
}
return _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(Class)).call.apply(_Object$getPrototypeO, [this, instance, { name: name, methods: methods }].concat(_toConsumableArray(interfaces), otherInterfaces)));
}
return Class;
}(parent)
});
}
var Main = exports.Main = extend({ name: 'Main', methods: ['main'] });
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = require("get-prototype-chain");
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = implement;
var _strictduck2 = __webpack_require__(2);
var _strictduck3 = _interopRequireDefault(_strictduck2);
var _utils = __webpack_require__(1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function implement(_ref) {
var name = _ref.name;
var withClass = _ref.withClass;
var _ref$strictduck = _ref.strictduck;
var strictduck = _ref$strictduck === undefined ? _strictduck3.default : _ref$strictduck;
return (0, _utils.nameClass)({
name: name || withClass.name || strictduck.name,
Class: function (_strictduck) {
_inherits(Class, _strictduck);
function Class() {
_classCallCheck(this, Class);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var implementation = new (Function.prototype.bind.apply(withClass, [null].concat(args)))();
return _possibleConstructorReturn(this, Object.getPrototypeOf(Class).call(this, implementation));
}
return Class;
}(strictduck)
});
}
/***/ },
/* 5 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = implementable;
function implementable(fn, defaults) {
return function (overrides) {
return fn(Object.assign({}, defaults, overrides));
};
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.equals = exports.id = exports.utils = exports.implementable = exports.implement = exports.default = undefined;
var _strictduck = __webpack_require__(2);
Object.keys(_strictduck).forEach(function (key) {
if (key === "default") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _strictduck[key];
}
});
});
var _utils2 = __webpack_require__(1);
Object.defineProperty(exports, 'id', {
enumerable: true,
get: function get() {
return _utils2.id;
}
});
Object.defineProperty(exports, 'equals', {
enumerable: true,
get: function get() {
return _utils2.equals;
}
});
var _strictduck2 = _interopRequireDefault(_strictduck);
var _implement2 = __webpack_require__(4);
var _implement3 = _interopRequireDefault(_implement2);
var _implementable2 = __webpack_require__(5);
var _implementable3 = _interopRequireDefault(_implementable2);
var _utils = _interopRequireWildcard(_utils2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _strictduck2.default;
exports.implement = _implement3.default;
exports.implementable = _implementable3.default;
exports.utils = _utils;
/***/ },
/* 7 */
/***/ function(module, exports) {
module.exports = require("Duckface/src/duckface");
/***/ },
/* 8 */
/***/ function(module, exports) {
module.exports = require("proto-extend");
/***/ }
/******/ ]);
//# sourceMappingURL=index.js.map |
/**
* Created by paper on 2016/8/12.
*
* The gray code is a binary numeral system where two successive values differ in only one bit.
*
* Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code.
* A gray code sequence must begin with 0.
*
* For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
*
* 00 - 0
* 01 - 1
* 11 - 3
* 10 - 2
*
* Note:
* For a given n, a gray code sequence is not uniquely defined.
*
* For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
*
* For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
*/
/**
* @param {number} n
* @return {number[]}
*/
var grayCode = function(n) {
if(n===0) { return [0]; }
if(n===1) { return [0, 1]; }
if(n===2) { return [0, 1, 3, 2]; }
var r = grayCode(n-1);
var l = r.length;
var ret = [];
for(var i = l-1; i>=0; i--) {
ret.push(Math.pow(2, n-1) + r[i]);
}
ret = r.concat(ret);
return ret;
};
|
function textLesson(url) {
const name = url
fetch(url).then(function(r) {
if(!r.ok) throw new Error('Failed to load, status: ' + r.status + ' ' + r.statusText)
else return r.text()
}).then(function(text) {
const words = text.trim().split(/\s+/)
exercise = new TypeJig.Exercise(words, 0, false, 'ordered')
setExercise(name, exercise, hints, speed)
}).catch(function(error) {
changeName(error)
})
}
loadSettings()
const back = document.getElementById('back')
const again = document.getElementById('again')
const another = document.getElementById('new')
back.href = back.href.replace('text-lesson', 'form')
again.addEventListener('click', function(evt) {
evt.preventDefault()
jig.reset()
})
// Exercise isn't randomized, so there's no sense asking for another.
another.parentNode.remove()
const fields = parseQueryString(document.location.search)
const hints = initializeHints(fields.hints, fields.floating_hints)
const speed = {wpm: fields.wpm, cpm: fields.cpm}
let exercise, jig
textLesson(fields.url)
|
var gulp = require('gulp');
var kickstarter = require('../utils/kickstarter');
// Development build (watchers, live reload)
gulp.task('dev', function() {
kickstarter.emit('gulp.dev');
});
// Production build (production ready assets)
gulp.task('stage', ['install'], function () {
kickstarter.emit('gulp.stage');
}); |
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.router5Helpers = mod.exports;
}
})(this, function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.redirect = redirect;
var dotOrEnd = '(\\..+$|$)';
var dotOrStart = '(^.+\\.|^)';
function getName(route) {
return typeof route === 'string' ? route : route.name || '';
}
function test(route, regex) {
return regex.test(getName(route));
}
function normaliseSegment(name) {
return name.replace('.', '\\.');
}
function testRouteWithSegment(before, after) {
return function () {
var route = arguments[0];
function applySegment(segment) {
return test(route, new RegExp(before + normaliseSegment(segment) + after));
};
if (arguments.length === 2) {
return applySegment(arguments[1]);
}
return applySegment;
};
}
function redirect() {
var fromRouteName = arguments[0];
var redirectTo = function redirectTo(routeName, routeParams) {
return function () {
return function (toState, fromState, done) {
if (toState.name === fromRouteName) {
var finalRouteParams = typeof routeParams === 'function' ? routeParams(fromState.params) : routeParams;
var redirectState = finalRouteParams === undefined ? { name: routeName } : { name: routeName, params: finalRouteParams };
done({ redirect: redirectState });
} else {
done(null);
}
};
};
};
if (arguments.length > 1) {
return redirectTo(arguments[1], arguments[2]);
} else if (arguments.length === 1) {
return redirectTo;
} else {
throw new Error('[router5][helpers][redirect] no arguments supplied.');
}
}
var startsWithSegment = exports.startsWithSegment = testRouteWithSegment('^', dotOrEnd);
var endsWithSegment = exports.endsWithSegment = testRouteWithSegment(dotOrStart, '$');
var includesSegment = exports.includesSegment = testRouteWithSegment(dotOrStart, dotOrEnd);
}); |
import isPlainObject from 'lodash/isPlainObject';
import invariant from 'invariant';
import retrieveSinglePair from './utils/retrieveSinglePair';
import createPrefixedActionType from './utils/createPrefixedActionType';
/**
* Create a reducer and actions for toggling between an "on" and "off"
* binary state.
*
* @param {string|object} suffixDef Suffix name to use for creating the action
* type names. If an object is passed in, then it must be a single key-value
* pair where the key is `suffix` name and the value is initial state value.
* @param {string|object} onActionDef Name of action for "on" state. If an
* object is passed in, then it must be a single key-value pair where the key
* is `onActionName` and the value is the "on" state value.
* @param {string|object} offActionDef Name of action for "off" state. If an
* object is passed in, then it must be a single key-value pair where the key
* is `offActionName` and the value is the "off" state value.
*/
export default function reduxBinary(suffixDef, onActionDef, offActionDef) {
let suffix = suffixDef;
let onActionName = onActionDef;
let offActionName = offActionDef;
let onState = true;
let offState = false;
let haveCustomState = false;
if (isPlainObject(onActionDef)) {
haveCustomState = true;
[onActionName, onState] = retrieveSinglePair(onActionName);
}
if (isPlainObject(offActionName)) {
haveCustomState = true;
[offActionName, offState] = retrieveSinglePair(offActionName);
}
invariant(
onActionName !== offActionName,
'"ON" action name and "OFF" action name cannot be the same'
);
if (haveCustomState) {
invariant(
onState !== offState,
'"ON" state and "OFF" state cannot be the same'
);
}
let initialState = offState;
if (isPlainObject(suffixDef)) {
[suffix, initialState] = retrieveSinglePair(suffix);
invariant(
initialState === onState || initialState === offState,
'Initial state must match "ON" state or "OFF" state'
);
}
const onActionType = createPrefixedActionType('on', suffix);
const offActionType = createPrefixedActionType('off', suffix);
return {
actions: {
[onActionName]: () => ({ type: onActionType }),
[offActionName]: () => ({ type: offActionType }),
},
actionTypes: { ON: onActionType, OFF: offActionType },
reducer(state = initialState, action) {
switch (action.type) {
case onActionType: return onState;
case offActionType: return offState;
default: return state;
}
},
};
}
|
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$(document).ready(function(){
$('#registration-btn').click(function() {
//alert("trt");
//Pull new data from form
var firstName = $("#registration-firstname").val();
var lastName = $("#registration-lastname").val();
var email = $("#registration-email").val();
var password = $("#registration-password").val();
// var lastName = document.getElementById("registration-lastname");
// var email = document.getElementById("registration-email");
// var password = document.getElementById("registration-password");
var data = {};
data.firstName = firstName;
data.lastName = lastName;
data.email = email;
data.password = password;
//Convert form data to JSON
var send = JSON.stringify(data);
//output JSON for verification
console.log(send);
$.ajax({
//url: "http://localhost:4567/skinstore/adduser",
url: "https://radiant-waters-9673.herokuapp.com/skinstore/adduser",
type: "POST",
datatype: "json",
data: send,
error: function(xhr, error) {
alert('Error! Status = ' + xhr.status + ' Message = ' + error);
alert(send);
},
success: function(data) {
alert("User added successfully.");
alert(send);
window.location.href='https://radiant-waters-9673.herokuapp.com/index.html';
}
});//end AJAX
return false;
});//end click function
});//end ready function
|
/* */
(function(process) {
'use strict';
var ReactDOMIDOperations = require("./ReactDOMIDOperations");
var LinkedValueUtils = require("./LinkedValueUtils");
var ReactMount = require("./ReactMount");
var ReactUpdates = require("./ReactUpdates");
var assign = require("./Object.assign");
var invariant = require("fbjs/lib/invariant");
var instancesByReactID = {};
function forceUpdateIfMounted() {
if (this._rootNodeID) {
ReactDOMInput.updateWrapper(this);
}
}
var ReactDOMInput = {
getNativeProps: function(inst, props, context) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var nativeProps = assign({}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function(inst, props) {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.defaultChecked || false,
initialValue: defaultValue != null ? defaultValue : null,
onChange: _handleChange.bind(inst)
};
instancesByReactID[inst._rootNodeID] = inst;
},
unmountWrapper: function(inst) {
delete instancesByReactID[inst._rootNodeID];
},
updateWrapper: function(inst) {
var props = inst._currentElement.props;
var checked = props.checked;
if (checked != null) {
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false);
}
var value = LinkedValueUtils.getValue(props);
if (value != null) {
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactMount.getNode(this._rootNodeID);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
var otherID = ReactMount.getID(otherNode);
!otherID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined;
var otherInstance = instancesByReactID[otherID];
!otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined;
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
module.exports = ReactDOMInput;
})(require("process"));
|
var Context = require('./Context.js');
var BaseScene = require('./BaseScene.js');
var GameScene = function(game) {
BaseScene.call(this, game);
this.name = "GameScene";
};
GameScene.prototype = Object.create(BaseScene.prototype);
GameScene.prototype.constructor = GameScene;
GameScene.prototype.init = function(options) {
Context.Logger.info('Game::init ' + options);
};
GameScene.prototype.create = function() {
this.add.sprite(0, 0, 'screen-bg');
var panel = this.add.sprite(0, 0, 'panel');
this.physics.startSystem(Phaser.Physics.ARCADE);
this.fontSmall = {
font: "16px Arial",
fill: "#e4beef"
};
this.fontBig = {
font: "24px Arial",
fill: "#e4beef"
};
this.fontMessage = {
font: "24px Arial",
fill: "#e4beef",
align: "center",
stroke: "#320C3E",
strokeThickness: 4
};
this.audioStatus = true;
this.timer = 0;
this.totalTimer = 0;
this.level = 1;
this.maxLevels = 5;
this.pauseButton = this.add.button(this.game.width - 8, 8, 'img/UI/sheet01', this.managePause, this, 'button-pause');
this.pauseButton.anchor.set(1, 0);
this.pauseButton.input.useHandCursor = true;
this.audioButton = this.add.button(this.game.width - this.pauseButton.width - 8 * 2, 8, 'button-audio', this.manageAudio, this);
this.audioButton.anchor.set(1, 0);
this.audioButton.input.useHandCursor = true;
this.audioButton.animations.add('true', [0], 10, true);
this.audioButton.animations.add('false', [1], 10, true);
this.audioButton.animations.play(this.audioStatus);
this.timerText = this.game.add.text(15, 15, "Time: " + this.timer, this.fontBig);
this.levelText = this.game.add.text(120, 10, "Level: " + this.level + " / " + this.maxLevels, this.fontSmall);
this.totalTimeText = this.game.add.text(120, 30, "Total time: " + this.totalTimer, this.fontSmall);
this.hole = this.add.sprite(this.game.width * 0.5, 90, 'hole');
this.hole.inputEnabled = true;
this.hole.events.onInputDown.add(this.onTileClick.bind(this));
this.physics.arcade.enable(this.hole);
this.initLevels();
this.showLevel(1);
this.keys = this.game.input.keyboard.createCursorKeys();
this.time.events.loop(Phaser.Timer.SECOND, this.updateCounter, this);
};
GameScene.prototype.onTileClick = function() {
Context.Logger.info('onTileClick');
this.finishLevel();
};
GameScene.prototype.initLevels = function() {
this.levels = [];
this.levelData = [
[{
x: 96,
y: 224,
t: 'w'
}],
[{
x: 72,
y: 320,
t: 'w'
}, {
x: 200,
y: 320,
t: 'h'
}, {
x: 72,
y: 150,
t: 'w'
}],
[{
x: 64,
y: 352,
t: 'h'
}, {
x: 224,
y: 352,
t: 'h'
}, {
x: 0,
y: 240,
t: 'w'
}, {
x: 128,
y: 240,
t: 'w'
}, {
x: 200,
y: 52,
t: 'h'
}],
[{
x: 78,
y: 352,
t: 'h'
}, {
x: 78,
y: 320,
t: 'w'
}, {
x: 0,
y: 240,
t: 'w'
}, {
x: 192,
y: 240,
t: 'w'
}, {
x: 30,
y: 150,
t: 'w'
}, {
x: 158,
y: 150,
t: 'w'
}],
[{
x: 188,
y: 352,
t: 'h'
}, {
x: 92,
y: 320,
t: 'w'
}, {
x: 0,
y: 240,
t: 'w'
}, {
x: 128,
y: 240,
t: 'w'
}, {
x: 256,
y: 240,
t: 'h'
}, {
x: 180,
y: 52,
t: 'h'
}, {
x: 52,
y: 148,
t: 'w'
}]
];
for (var i = 0; i < this.maxLevels; i++) {
var newLevel = this.add.group();
newLevel.enableBody = true;
newLevel.physicsBodyType = Phaser.Physics.ARCADE;
for (var e = 0; e < this.levelData[i].length; e++) {
var item = this.levelData[i][e];
newLevel.create(item.x, item.y, 'element-' + item.t);
}
newLevel.setAll('body.immovable', true);
newLevel.visible = false;
this.levels.push(newLevel);
}
};
GameScene.prototype.showLevel = function(level) {
var lvl = level | this.level;
if (this.levels[lvl - 2]) {
this.levels[lvl - 2].visible = false;
}
this.levels[lvl - 1].visible = true;
};
GameScene.prototype.updateCounter = function() {
this.timer++;
this.timerText.setText("Time: " + this.timer);
this.totalTimeText.setText("Total time: " + (this.totalTimer + this.timer));
};
GameScene.prototype.managePause = function() {
this.game.paused = true;
var pausedText = this.add.text(this.game.width * 0.5, 250, "Game paused,\ntap anywhere to continue.", this.fontMessage);
pausedText.anchor.set(0.5);
this.input.onDown.add(function() {
pausedText.destroy();
this.game.paused = false;
}, this);
};
GameScene.prototype.manageAudio = function() {
this.audioStatus = !this.audioStatus;
this.audioButton.animations.play(this.audioStatus);
};
GameScene.prototype.update = function() {
};
GameScene.prototype.finishLevel = function() {
if (this.level >= this.maxLevels) {
this.totalTimer += this.timer;
alert('Congratulations, game completed!\nTotal time of play: ' + this.totalTimer + ' seconds!');
this.game.state.start('MainMenu');
} else {
this.totalTimer += this.timer;
this.timer = 0;
this.level++;
this.timerText.setText("Time: " + this.timer);
this.totalTimeText.setText("Total time: " + this.totalTimer);
this.levelText.setText("Level: " + this.level + " / " + this.maxLevels);
this.showLevel();
}
};
GameScene.prototype.render = function() {
this.game.debug.body(this.hole);
};
module.exports = GameScene;
|
version https://git-lfs.github.com/spec/v1
oid sha256:19aef7d007b5f499a4f067f35810aaa2e7548644ce82b5a634c73dae31b4ee35
size 16530
|
//
// Jala Project [http://opensvn.csie.org/traccgi/jala]
//
// Copyright 2004 ORF Online und Teletext GmbH
//
// Licensed under the Apache License, Version 2.0 (the ``License'');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an ``AS IS'' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// $Revision: 319 $
// $LastChangedBy: tobi $
// $LastChangedDate: 2008-01-08 17:44:39 +0100 (Die, 08 Jän 2008) $
// $HeadURL: http://dev.orf.at/source/jala/trunk/tests/HtmlDocument.js $
//
/**
* Declare which test methods should be run in which order
* @type Array
* @final
*/
var tests = [
"testGetAll",
"testGetLinks"
];
var source = '<html><head><title>Test</title></head><body>' +
'<h1>Hello, World!</h1>' +
'<a href="http://localhost/1">foo</a>' +
'<div><a href="http://localhost/2">bar</a></div>' +
'<a href="http://localhost/3">foobar</a>' +
'</body></html>';
/**
* Simple test of the HtmlDocument.getLinks method.
* An instance of HtmlDocument is created from a very
* simple HTML source. The result of getLinks is then
* evaluated and tested.
*/
var testGetLinks = function() {
var html = new jala.HtmlDocument(source);
var links = html.getLinks();
assertEqual(links.constructor, Array);
assertEqual(links.length, 3);
assertEqual(links[0].constructor, Object);
for (var i in links) {
assertNotUndefined(links[i].url);
assertNotUndefined(links[i].text);
}
assertEqual(links[0].url, "http://localhost/1");
assertEqual(links[0].text, "foo");
assertEqual(links[1].url, "http://localhost/2");
assertEqual(links[1].text, "bar");
assertEqual(links[2].url, "http://localhost/3");
assertEqual(links[2].text, "foobar");
return;
};
/**
* Simple test of the HtmlDocument.geAll method.
* An instance of HtmlDocument is created from a very
* simple HTML source. The result of getAll is then
* evaluated and tested.
*/
var testGetAll = function() {
var names = ["html", "head", "title", "body", "h1", "a", "div", "a", "a"];
var html = new jala.HtmlDocument(source);
var list = html.getAll("*");
for (var i in list) {
assertNotUndefined(list[i].name);
assertEqual(list[i].name, names[i]);
}
assertEqual(list[2].value, "Test");
assertEqual(list[4].value, "Hello, World!");
assertEqual(list[5].value, "foo");
assertEqual(list[7].value, "bar");
assertEqual(list[8].value, "foobar");
assertEqual(html.getAll("h1")[0].value, "Hello, World!");
return;
};
|
/* */
(function(process) {
'use strict';
function posix(path) {
return path.charAt(0) === '/';
}
;
function win32(path) {
var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
var result = splitDeviceRe.exec(path);
var device = result[1] || '';
var isUnc = !!device && device.charAt(1) !== ':';
return !!result[2] || isUnc;
}
;
module.exports = process.platform === 'win32' ? win32 : posix;
module.exports.posix = posix;
module.exports.win32 = win32;
})(require('process'));
|
/**
* @file report command
* @author Sankarsan Kampa (a.k.a k3rn31p4nic)
* @license GPL-3.0
*/
exports.exec = async (Bastion, message, args) => {
if (!args.user || !args.reason) {
return Bastion.emit('commandUsage', message, this.help);
}
let guildModel = await Bastion.database.models.guild.findOne({
attributes: [ 'reportChannel' ],
where: {
guildID: message.guild.id
}
});
if (guildModel && guildModel.dataValues.reportChannel && message.guild.channels.has(guildModel.dataValues.reportChannel)) {
let user;
if (args.user.startsWith('<@') && message.mentions.users.size) {
user = message.mentions.users.first();
}
else {
let member = message.guild.members.get(args.user);
if (member) {
user = member.user;
}
}
if (!user) {
return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'notFound', 'user'), message.channel);
}
if (message.author.id === user.id) return;
args.reason = args.reason.join(' ');
let reportChannel = message.guild.channels.get(guildModel.dataValues.reportChannel);
await reportChannel.send({
embed: {
color: Bastion.colors.ORANGE,
title: 'User Report',
fields: [
{
name: 'User',
value: user.tag,
inline: true
},
{
name: 'User ID',
value: user.id,
inline: true
},
{
name: 'Report',
value: args.reason
}
],
footer: {
text: `Reported by ${message.author.tag} / ${message.author.id}`
},
timestamp: new Date()
}
});
await message.channel.send({
embed: {
color: Bastion.colors.GREEN,
title: 'User Reported',
description: Bastion.i18n.info(message.guild.language, 'report', message.author.tag, user.tag, args.reason)
}
}).then(successMessage => {
if (message.deletable) message.delete().catch(() => {});
successMessage.delete(10000).catch(() => {});
}).catch(e => {
Bastion.log.error(e);
});
}
else {
await message.channel.send({
embed: {
color: Bastion.colors.RED,
description: Bastion.i18n.error(message.guild.language, 'noReportChannel', message.author.tag)
}
});
if (message.deletable) message.delete().catch(() => {});
}
};
exports.config = {
aliases: [],
enabled: true,
argsDefinitions: [
{ name: 'user', type: String, defaultOption: true },
{ name: 'reason', alias: 'r', type: String, multiple: true }
]
};
exports.help = {
name: 'report',
description: 'Reports a user of your Discord server to the server staffs. *Report Channel needs to be set.*',
botPermission: '',
userTextPermission: '',
userVoicePermission: '',
usage: 'report < @USER_MENTION | USER_ID > < -r REASON >',
example: [ 'report 215052539542571701 -r DM advertisement', 'report @user#0001 -r Trolling everyone' ]
};
|
/*
---
name: String
description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
requires: [Type, Array]
provides: [String]
...
*/
var core_trim = String.prototype.trim;
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.implement({
//<!ES6>
contains: function(string, index) {
return (index ? String(this).slice(index) : String(this)).indexOf(string) > -1;
},
//</!ES6>
test: function(regex, params) {
return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
},
trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function() {
String(this).trim();
} : function() {
return String(this).replace(rtrim, '');
},
clean: function() {
return String(this).replace(/\s+/g, ' ').trim();
},
camelCase: function() {
return String(this).replace(/-\D/g, function(match) {
return match.charAt(1).toUpperCase();
});
},
hyphenate: function() {
return String(this).replace(/[A-Z]/g, function(match) {
return ('-' + match.charAt(0).toLowerCase());
});
},
capitalize: function() {
return String(this).replace(/\b[a-z]/g, function(match) {
return match.toUpperCase();
});
},
escapeRegExp: function() {
return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
toInt: function(base) {
return parseInt(this, base || 10);
},
toFloat: function() {
return parseFloat(this);
},
hexToRgb: function(array) {
var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return (hex) ? hex.slice(1).hexToRgb(array) : null;
},
rgbToHex: function(array) {
var rgb = String(this).match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHex(array) : null;
},
substitute: function(object, regexp) {
return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name) {
if (match.charAt(0) == '\\') return match.slice(1);
return (object[name] != null) ? object[name] : '';
});
}
}); |
'use strict';
// Placards controller
angular.module('placards').controller('PlacardsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Compartments', 'Suppliers', 'Plantations', 'Placards', '$timeout',
function($scope, $stateParams, $location, Authentication, Compartments, Suppliers, Plantations, Placards, $timeout ) {
$scope.authentication = Authentication;
$scope.selSupplier = [];
$scope.selPlants = [];
$scope.placards = [];
$scope.addPlantation = function(plantation) {
var plantation = Plantations.get({
plantationId: plantation._id
});
$timeout(function(){
$scope.plantation = plantation;
}, 500);
};
$scope.addCompartment = function(compartment) {
var compartment = Compartments.get({
compartmentId: compartment._id
});
$timeout(function(){
$scope.compartment = compartment;
$scope.addPlacards(compartment);
}, 500);
};
$scope.addPlacards = function(compartment) {
angular.forEach(compartment.placards, function(placard){
$scope.placards.push(placard.no);
});
$scope.newP = $scope.placards.length;
};
$scope.incNewPlacard = function() {
var newVal = $scope.newP + 1;
$scope.newP += 1;
angular.forEach($scope.placards, function(item){
if (item === newVal) {
$scope.newP += 1;
}
});
};
$scope.decNewPlacard = function() {
var minValue = 1;
if ($scope.newP > minValue) {
$scope.newP -= 1;
angular.forEach($scope.placards, function(item){
if (item === $scope.newP) {
$scope.newP -= 1;
if ($scope.newP < 0 ) {
$scope.newP += 2;
}
}
});
} else if ($scope.newP === minValue) {
$scope.newP = $scope.newP;
}
};
$scope.addPlants = function(supl) {
var id = supl._id;
var values = Plantations.query();
var lengthSelPlants = $scope.selPlants.length;
if (lengthSelPlants > 0 ) {
$scope.selPlants.splice(0, lengthSelPlants);
}
$timeout(function(){
angular.forEach(values, function(value, key) {
if (value.supplier === id) {
$scope.selPlants.push(value);
}
});
}, 500);
};
$scope.loadSuppliers = function() {
$scope.suppliers = Suppliers.query();
};
// Create new Placard
$scope.create = function() {
// Create new Placard object
var placard = new Placards ({
no: $scope.newP,
supplier: $scope.supplier._id,
plantation: $scope.plantation._id,
compartment: $scope.compartment._id
});
// Redirect after save
placard.$save(function(response) {
// $location.path('placards/' + response._id);
$scope.compartment.placards.push(response._id);
var compartment = $scope.compartment;
compartment.$update(function() {
// $location.path('placards/' + placard._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Placard
$scope.remove = function( placard ) {
if ( placard ) { placard.$remove();
for (var i in $scope.placards ) {
if ($scope.placards [i] === placard ) {
$scope.placards.splice(i, 1);
}
}
} else {
$scope.placard.$remove(function() {
$location.path('placards');
});
}
};
// Update existing Placard
$scope.update = function() {
var placard = $scope.placard ;
placard.$update(function() {
$location.path('placards/' + placard._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Placards
$scope.find = function() {
$scope.placards = Placards.query();
};
// Find existing Placard
$scope.findOne = function() {
$scope.placard = Placards.get({
placardId: $stateParams.placardId
});
};
}
]); |
/**
* Problem: https://leetcode.com/problems/first-bad-version/description/
*/
/**
* Definition for isBadVersion()
*
* @param {integer} version number
* @return {boolean} whether the version is bad
* isBadVersion = function(version) {
* ...
* };
*/
/**
* @param {function} isBadVersion()
* @return {function}
*/
var solution = function(isBadVersion) {
/**
* @param {integer} n Total versions
* @return {integer} The first bad version
*/
return function(n) {
var front = 1, tail = n, mid;
while (tail > front + 1) {
mid = parseInt((front + tail) / 2);
if (isBadVersion(mid))
tail = mid;
else
front = mid;
}
return isBadVersion(front) ? front : tail;
};
};
module.exports = solution;
|
// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();
// Require keystone
var keystone = require('keystone');<% if (viewEngine == 'hbs') { %>
var handlebars = require('express-handlebars');<% } else if (viewEngine == 'swig') { %>
var swig = require('swig');<% } else if (viewEngine == 'nunjucks') { %>
var cons = require('consolidate');
var nunjucks = require('nunjucks');<% } %>
<% if (viewEngine === 'swig') { %>
// Disable swig's bulit-in template caching, express handles it
swig.setDefaults({ cache: false });
<% } if (includeGuideComments) { %>
// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.
<% } %>
keystone.init({
'name': '<%= projectName %>',
'brand': '<%= projectName %>',
<% if (preprocessor === 'sass') { %>
'sass': 'public',
<% } else if (preprocessor === 'less') { %>
'less': 'public',
<% } else { %>
'stylus': 'public',
<% } %>'static': 'public',
'favicon': 'public/favicon.ico',
'views': 'templates/views',<% if (viewEngine === 'nunjucks') { %>
'view engine': 'html',
'custom engine': cons.nunjucks,
<% } else { %>
'view engine': '<%= viewEngine %>',
<% } %><% if (viewEngine === 'hbs') { %>
'custom engine': handlebars.create({
layoutsDir: 'templates/views/layouts',
partialsDir: 'templates/views/partials',
defaultLayout: 'default',
helpers: new require('./templates/views/helpers')(),
extname: '.hbs'
}).engine,
<% } else if ( viewEngine === 'swig' ) { %>
'custom engine': swig.renderFile,
<% } %><% if (includeEmail) { %>
'emails': 'templates/emails',
<% } %>
'auto update': true,
'session': true,
'auth': true,
'user model': '<%= userModel %>'
});
<% if (includeGuideComments) { %>
// Load your project's Models
<% } %>
keystone.import('models');
<% if (includeGuideComments) { %>
// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
<% } %>
keystone.set('locals', {
_: require('underscore'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable
});
<% if (includeGuideComments) { %>
// Load your project's Routes
<% } %>
keystone.set('routes', require('./routes'));
<% if (includeEmail) { %>
<% if (includeGuideComments) { %>
// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
<% } %>
keystone.set('email locals', {
logo_src: '/images/logo-email.gif',
logo_width: 194,
logo_height: 76,
theme: {
email_bg: '#f9f9f9',
link_color: '#2697de',
buttons: {
color: '#fff',
background_color: '#2697de',
border_color: '#1a7cb7'
}
}
});
<% if (includeGuideComments) { %>
// Setup replacement rules for emails, to automate the handling of differences
// between development a production.
// Be sure to update this rule to include your site's actual domain, and add
// other rules your email templates require.
<% } %>
keystone.set('email rules', [{
find: '/images/',
replace: (keystone.get('env') == 'production') ? 'http://www.your-server.com/images/' : 'http://localhost:3000/images/'
}, {
find: '/keystone/',
replace: (keystone.get('env') == 'production') ? 'http://www.your-server.com/keystone/' : 'http://localhost:3000/keystone/'
}]);
<% if (includeGuideComments) { %>
// Load your project's email test routes
<% } %>
keystone.set('email tests', require('./routes/emails'));
<% } %><% if (includeGuideComments) { %>
// Configure the navigation bar in Keystone's Admin UI
<% } %>
keystone.set('nav', {
<% if (includeContent) { %>'contents': 'contents',
<% } if (includeBlog) { %>'posts': ['posts', 'post-categories'],
<% } if (includeGallery) { %>'galleries': 'galleries',
<% } if (includeEnquiries) { %>'enquiries': 'enquiries',
<% } %>'<%= userModelPath %>': '<%= userModelPath %>'
});
<% if (includeGuideComments) { %>
// Start Keystone to connect to your database and initialise the web server
<% } %>
keystone.start();
|
// create the table
let table = document.createElement("table");
table.border = 1;
table.width = "100%";
// create the tbody
let tbody = document.createElement("tbody");
table.appendChild(tbody);
// create the first row
let row1 = document.createElement("tr");
tbody.appendChild(row1);
let cell1_1 = document.createElement("td");
cell1_1.appendChild(document.createTextNode("Cell 1,1"));
row1.appendChild(cell1_1);
let cell2_1 = document.createElement("td");
cell2_1.appendChild(document.createTextNode("Cell 2,1"));
row1.appendChild(cell2_1);
// create the second row
let row2 = document.createElement("tr");
tbody.appendChild(row2);
let cell1_2 = document.createElement("td");
cell1_2.appendChild(document.createTextNode("Cell 1,2"));
row2.appendChild(cell1_2);
let cell2_2= document.createElement("td");
cell2_2.appendChild(document.createTextNode("Cell 2,2"));
row2.appendChild(cell2_2);
// add the table to the document body
document.body.appendChild(table);
|
import React from 'react';
import { fromJS } from 'immutable';
import { EditorState, convertFromRaw, CompositeDecorator } from 'draft-js';
import {
EXAMPLE_EDITOR_BLOCKS,
} from '../App/constants'; // eslint-disable-line
function strategyByType(type) {
return function strate(contentBlock, callback, contentState) {
return contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
if (entityKey !== null && contentState.getEntity(entityKey).getType() === type) {
return true;
}
return false;
},
callback
);
};
}
const decorator = new CompositeDecorator([
{
strategy: strategyByType('COMMENT'),
component: CommentSpan,
},
]);
function CommentSpan(props) {
return <span className="editor__comment" style={{ backgroundColor: 'yellow' }}>{props.children}</span>;
}
const initialState = fromJS({
editorState: EditorState.createWithContent(convertFromRaw(EXAMPLE_EDITOR_BLOCKS), decorator),
commentText: null,
commentIsBeingEdited: false,
});
export default function editorReducer(state = initialState, action) {
switch (action.type) {
case 'SET_EDITOR_STATE':
return state
.set('editorState', action.editorState)
.set('commentIsBeingEdited', false);
case 'SAVE_COMMENT':
return state
.set('editorState', action.editorState)
.set('commentText', null)
.set('commentIsBeingEdited', false);
case 'EDIT_COMMENT':
return state
.set('commentText', action.commentText)
.set('commentIsBeingEdited', true);
default:
return state;
}
}
|
"use strict";
const remarkFrontmatter = require("remark-frontmatter");
const remarkParse = require("remark-parse");
const unified = require("unified");
const util = require("./util");
/**
* based on [MDAST](https://github.com/syntax-tree/mdast) with following modifications:
*
* 1. restore unescaped character (Text)
* 2. merge continuous Texts
* 3. transform InlineCode#value into InlineCode#children (Text)
* 4. split Text into Sentence
*
* interface Word { value: string }
* interface Whitespace { value: string }
* interface Sentence { children: Array<Word | Whitespace> }
* interface InlineCode { children: Array<Sentence> }
*/
function parse(text /*, parsers, opts*/) {
const processor = unified()
.use(remarkParse, { footnotes: true, commonmark: true })
.use(remarkFrontmatter, ["yaml"])
.use(restoreUnescapedCharacter(text))
.use(mergeContinuousTexts)
.use(transformInlineCode(text))
.use(splitText);
return processor.runSync(processor.parse(text));
}
function map(ast, handler) {
return (function preorder(node, index, parentNode) {
const newNode = Object.assign({}, handler(node, index, parentNode));
if (newNode.children) {
newNode.children = newNode.children.map((child, index) => {
return preorder(child, index, newNode);
});
}
return newNode;
})(ast, null, null);
}
function transformInlineCode(originalText) {
return () => ast =>
map(ast, node => {
if (node.type !== "inlineCode") {
return node;
}
const rawContent = originalText.slice(
node.position.start.offset,
node.position.end.offset
);
const style = rawContent.match(/^`+/)[0];
return Object.assign({}, node, {
value: node.value.replace(/\s+/g, " "),
children: [
{
type: "text",
value: node.value,
position: {
start: {
line: node.position.start.line,
column: node.position.start.column + style.length,
offset: node.position.start.offset + style.length
},
end: {
line: node.position.end.line,
column: node.position.end.column - style.length,
offset: node.position.end.offset - style.length
}
}
}
]
});
});
}
function restoreUnescapedCharacter(originalText) {
return () => ast =>
map(ast, node => {
return node.type !== "text"
? node
: Object.assign({}, node, {
value:
node.value !== "*" &&
node.value !== "_" && // handle these two cases in printer
node.value.length === 1 &&
node.position.end.offset - node.position.start.offset > 1
? originalText.slice(
node.position.start.offset,
node.position.end.offset
)
: node.value
});
});
}
function mergeContinuousTexts() {
return ast =>
map(ast, node => {
if (!node.children) {
return node;
}
const children = node.children.reduce((current, child) => {
const lastChild = current[current.length - 1];
if (lastChild && lastChild.type === "text" && child.type === "text") {
current.splice(-1, 1, {
type: "text",
value: lastChild.value + child.value,
position: {
start: lastChild.position.start,
end: child.position.end
}
});
} else {
current.push(child);
}
return current;
}, []);
return Object.assign({}, node, { children });
});
}
function splitText() {
return ast =>
map(ast, (node, index, parentNode) => {
if (node.type !== "text") {
return node;
}
let value = node.value;
if (parentNode.type === "paragraph") {
if (index === 0) {
value = value.trimLeft();
}
if (index === parentNode.children.length - 1) {
value = value.trimRight();
}
}
return {
type: "sentence",
position: node.position,
children: util.splitText(value)
};
});
}
module.exports = parse;
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupIntl } from 'ember-intl/test-support';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { a11yAudit } from 'ember-a11y-testing/test-support';
import { DateTime } from 'luxon';
import { component } from 'ilios-common/page-objects/components/ilios-calendar-multiday-events';
module('Integration | Component | ilios calendar multiday events', function (hooks) {
setupRenderingTest(hooks);
setupIntl(hooks, 'en-us');
hooks.beforeEach(function () {
this.events = [
{
startDate: DateTime.fromISO('1984-11-11').toJSDate(),
endDate: DateTime.fromISO('1984-11-12').toJSDate(),
name: 'Cheramie is born',
location: 'Lancaster, CA',
},
{
startDate: DateTime.fromISO('1980-12-10').toJSDate(),
endDate: DateTime.fromISO('1980-12-11').toJSDate(),
name: 'Jonathan is born',
location: 'Lancaster, CA',
},
];
});
test('it renders', async function (assert) {
await render(hbs`<IliosCalendarMultidayEvents @events={{this.events}} />`);
assert.strictEqual(component.title, 'Multiday Events');
assert.strictEqual(component.events.length, 2);
await a11yAudit(this.element);
});
});
|
import React from 'react';
import ItemGrid from '../../containers/ItemGrid/ItemGrid';
import Filters from '../../containers/Filters/Filters';
// Since this component is simple and static, there's no parent container for it.
const ItemLayoutPage = () => {
return (
<main>
<h2 className="alt-header">Items</h2>
<Filters />
<ItemGrid />
</main>
);
};
export default ItemLayoutPage;
|
const _ = require(`lodash`)
const { graphql } = require(`graphql`)
const nodeTypes = require(`../build-node-types`)
const nodeConnections = require(`../build-node-connections`)
const { buildNodesSchema } = require(`../index`)
const { clearUnionTypes } = require(`../infer-graphql-type`)
const { store } = require(`../../redux`)
require(`../../db/__tests__/fixtures/ensure-loki`)()
function makeNodes() {
return [
{
id: `0`,
internal: { type: `Test` },
children: [],
index: 0,
name: `The Mad Max`,
string: `a`,
float: 1.5,
hair: 1,
date: `2006-07-22T22:39:53.000Z`,
anArray: [1, 2, 3, 4],
key: {
withEmptyArray: [],
},
anotherKey: {
withANested: {
nestedKey: `foo`,
emptyArray: [],
anotherEmptyArray: [],
},
},
frontmatter: {
date: `2006-07-22T22:39:53.000Z`,
title: `The world of dash and adventure`,
blue: 100,
},
anObjectArray: [
{ aString: `some string`, aNumber: 2, aBoolean: true },
{ aString: `some string`, aNumber: 2, anArray: [1, 2] },
],
boolean: true,
},
{
id: `1`,
internal: { type: `Test` },
children: [],
index: 1,
name: `The Mad Wax`,
string: `b`,
float: 2.5,
hair: 2,
anArray: [1, 2, 5, 4],
anotherKey: {
withANested: {
nestedKey: `foo`,
},
},
frontmatter: {
date: `2006-07-22T22:39:53.000Z`,
title: `The world of slash and adventure`,
blue: 10010,
circle: `happy`,
},
boolean: false,
data: {
tags: [
{
tag: {
document: [
{
data: {
tag: `Design System`,
},
number: 3,
},
],
},
},
],
},
},
{
id: `2`,
internal: { type: `Test` },
children: [],
index: 2,
name: `The Mad Wax`,
string: `c`,
float: 3.5,
hair: 0,
date: `2006-07-29T22:39:53.000Z`,
anotherKey: {
withANested: {
nestedKey: `bar`,
},
},
frontmatter: {
date: `2006-07-22T22:39:53.000Z`,
title: `The world of shave and adventure`,
blue: 10010,
circle: `happy`,
},
data: {
tags: [
{
tag: {
document: [
{
data: {
tag: `Gatsby`,
},
},
],
},
},
{
tag: {
document: [
{
data: {
tag: `Design System`,
},
number: 5,
},
],
},
},
],
},
},
]
}
async function queryResult(nodesData, query, { types = [] } = {}) {
store.dispatch({ type: `DELETE_CACHE` })
for (const node of nodesData) {
store.dispatch({ type: `CREATE_NODE`, payload: node })
}
clearUnionTypes()
const typesGQL = await nodeTypes.buildAll({})
const connections = nodeConnections.buildAll(_.values(typesGQL))
// Pull off just the graphql node from each type object.
const nodes = _.mapValues(typesGQL, `node`)
const schema = buildNodesSchema({ ...connections, ...nodes })
return graphql(schema, query)
}
describe(`connection input fields`, () => {
it(`returns list of distinct values in a field`, async () => {
let result = await queryResult(
makeNodes(),
`
{
allTest {
totalCount
names: distinct(field: name)
array: distinct(field: anArray)
blue: distinct(field: frontmatter___blue)
# Only one node has this field
circle: distinct(field: frontmatter___circle)
nestedField: distinct(field: anotherKey___withANested___nestedKey)
}
}
`
)
expect(result.errors).not.toBeDefined()
expect(result.data.allTest.names.length).toEqual(2)
expect(result.data.allTest.names[0]).toEqual(`The Mad Max`)
expect(result.data.allTest.array.length).toEqual(5)
expect(result.data.allTest.array[0]).toEqual(`1`)
expect(result.data.allTest.blue.length).toEqual(2)
expect(result.data.allTest.blue[0]).toEqual(`100`)
expect(result.data.allTest.circle.length).toEqual(1)
expect(result.data.allTest.circle[0]).toEqual(`happy`)
expect(result.data.allTest.nestedField.length).toEqual(2)
expect(result.data.allTest.nestedField[0]).toEqual(`bar`)
expect(result.data.allTest.nestedField[1]).toEqual(`foo`)
})
it(`handles the group connection field`, async () => {
let result = await queryResult(
makeNodes(),
` {
allTest {
blue: group(field: frontmatter___blue) {
field
fieldValue
totalCount
}
anArray: group(field: anArray) {
field
fieldValue
totalCount
}
}
}`
)
expect(result.errors).not.toBeDefined()
expect(result.data.allTest.blue).toHaveLength(2)
expect(result.data.allTest.blue[0].fieldValue).toEqual(`100`)
expect(result.data.allTest.blue[0].field).toEqual(`frontmatter.blue`)
expect(result.data.allTest.blue[0].totalCount).toEqual(1)
expect(result.data.allTest.anArray).toHaveLength(5)
expect(result.data.allTest.anArray[0].fieldValue).toEqual(`1`)
expect(result.data.allTest.anArray[0].field).toEqual(`anArray`)
expect(result.data.allTest.anArray[0].totalCount).toEqual(2)
})
it(`handles the nested group connection field`, async () => {
let result = await queryResult(
makeNodes(),
` {
allTest {
nestedKey: group(field: anotherKey___withANested___nestedKey) {
field
fieldValue
totalCount
}
}
}`
)
expect(result.errors).not.toBeDefined()
expect(result.data.allTest.nestedKey).toHaveLength(2)
expect(result.data.allTest.nestedKey[0].fieldValue).toEqual(`bar`)
expect(result.data.allTest.nestedKey[0].field).toEqual(
`anotherKey.withANested.nestedKey`
)
expect(result.data.allTest.nestedKey[0].totalCount).toEqual(1)
expect(result.data.allTest.nestedKey[1].fieldValue).toEqual(`foo`)
expect(result.data.allTest.nestedKey[1].field).toEqual(
`anotherKey.withANested.nestedKey`
)
expect(result.data.allTest.nestedKey[1].totalCount).toEqual(2)
})
it(`can query object arrays`, async () => {
let result = await queryResult(
makeNodes(),
`
{
allTest {
edges {
node {
anObjectArray {
aString
aNumber
aBoolean
}
}
}
}
}
`
)
expect(result.errors).not.toBeDefined()
expect(result).toMatchSnapshot()
})
})
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 18H9v2l3-3-3-3v2h-.5C6.02 16 4 13.98 4 11.5S6.02 7 8.5 7H12V5H8.5C4.92 5 2 7.92 2 11.5z" /></g>
, 'LowPriority');
|
var crypto = require('crypto');
module.exports = {
generateSalt: function() {
return crypto.randomBytes(128).toString('base64');
},
generateHashedPassword: function(pwd, salt) {
var hmac = crypto.createHmac('sha1', salt);
return hmac.update(pwd).digest('hex');
}
}; |
/*
* https://github.com/yuanqing/yq-js/tree/master/src/padThumbnails
*/
;(function( $ ) {
// Name
var pluginName = 'padThumbnails';
// Defaults
var defaults = {
itemContainerSelector: '.thumbnails',
itemSelector: '.thumbnail',
fillerSelector: '.filler',
breakpoints: false,
onInit: function(){},
onDestroy: function(){}
};
// Classes
var activeClass = pluginName + '-active',
showClass = pluginName + '-show';
// Plugin constructor, methods
var Plugin = function( element, options ) {
// Set element, options
var $el = $( element ),
$opt = $.extend( {}, defaults, options );
// Keep a reference to these elements
var itemContainer,
fillers;
// Initialise instance
function init() {
itemContainer = $el.find( $opt.itemContainerSelector );
fillers = $el.find( $opt.fillerSelector );
if ( typeof $opt.breakpoints !== 'object' || $opt.breakpoints.length === 0 || fillers.length === 0 ) {
return;
}
$el.addClass( activeClass );
cloneFillers();
bind();
showFillers();
$el.on( 'destroy.' + pluginName, destroy );
callback( 'onInit' );
}
// Destroy instance
function destroy() {
$.removeData( $el[0], pluginName );
$el.removeClass( activeClass );
$.each(fillers, function( i ) {
$( this ).removeClass( showClass );
});
unbind();
$el.unbind( 'destroy.' + pluginName, destroy );
$el = null;
callback( 'onDestroy' );
}
// Bind events to instance
function bind() {
$( window ).on( 'resize.' + pluginName, showFillers );
$el.on( 'change.' + pluginName, showFillers );
itemContainer.on( 'change.' + pluginName, showFillers );
}
// Unbind events from instance
function unbind() {
$( window ).off( 'resize.' + pluginName, showFillers );
$el.off( 'change.' + pluginName, showFillers );
itemContainer.off( 'change.' + pluginName, showFillers );
}
// Execute a callback
function callback( callbackName ) {
if ( typeof $opt[callbackName] == 'function' ) {
$opt[callbackName].call( $el );
}
}
// Clone fillers
function cloneFillers() {
var count = getLargestValue( $opt.breakpoints ) - 1 - fillers.length;
for ( var i=0; i<count; i++ ) {
fillers = fillers.add( fillers.eq( i ).clone().appendTo( $el ) );
}
}
// Show/hide fillers; fired on window resize
function showFillers() {
var count = countFillers();
$.each( fillers, function( i ) {
if ( i < count ) {
$( this ).addClass( showClass );
} else {
$( this ).removeClass( showClass );
}
});
}
// Returns the number of fillers to show based on window size
function countFillers() {
var count,
width = $( window ).width();
$.each( $opt.breakpoints, function( k, v ) {
if ( k <= width ) {
count = v;
}
});
var lastRow = itemContainer.find( $opt.itemSelector ).length % count;
return ( count - lastRow ) % count;
}
// Returns the largest val from an object literal of key/val pairs
function getLargestValue( obj ) {
var arr = Object.keys( obj ).map(
function( key ) {
return obj[key];
}
);
return Math.max.apply( null, arr );
}
// Initialise
init();
// Expose public methods
return {
destroy: destroy
};
};
// Plugin definition
$.fn[pluginName] = function( options ) {
if ( typeof options !== 'object' && typeof options !== 'string' ) {
options = {};
}
return this.each(function() {
var instance = $.data( this, pluginName );
if ( !instance ) {
$.data( this, pluginName, ( instance = new Plugin( this, options ) ) );
}
if ( typeof options === 'string' && typeof instance[options] === 'function' ) {
instance[options].apply( this );
}
});
};
})( jQuery );
|
/* eslint-disable no-console */
console.time('Docs generated in');
const clean = require('./docs-clean');
const copy = require('./docs-copy-files');
const template = require('./docs-template');
clean()
.then(copy)
.then(template)
.then(() => {
console.timeEnd('Docs generated in');
});
|
// Generated by SugarLisp v0.6.5
exports["awaitgen"] = function(forms) {
var macrodef = ["macro", ["result", "asynccall", "then", "error"],
["try-", ["var", ["~", "result"],
["yield", ["~", "asynccall"]]
],
["~", "then"],
["function", ["err"],
["~", "error"]
]
]
];
return this.macroexpand(forms, macrodef);
};
exports["awaitgenPrior"] = function(forms) {
var macrodef = ["macro", ["result", "asynccall", "then", "error"],
["iifegen", ["try*", ["var", ["~", "result"],
["yield", ["~", "asynccall"]]
],
["~", "then"],
["function", ["err"],
["~", "error"]
]
]]
];
return this.macroexpand(forms, macrodef);
};
exports["asyncgen"] = function(forms) {
var macrodef = ["macro", ["func", "...rest"],
[
[".", "co", "wrap"],
["function*", ["~", "rest"]]
]
];
return this.macroexpand(forms, macrodef);
};
exports["iifegen"] = function(forms) {
var macrodef = ["macro", ["iifewrapped"],
[
[
[".", "co", "wrap"],
["~", "iifewrapped"]
]
]
];
return this.macroexpand(forms, macrodef);
}; |
version https://git-lfs.github.com/spec/v1
oid sha256:aef13e0a91ba5a7189599856a7ed17e250af9e334cc5e587721895389225042d
size 2330
|
'use strict';
angular.module('projectApp')
.config(function ($stateProvider) {
$stateProvider
.state('main', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
});
}); |
'use strict';
// Load the module dependencies
var passport = require('passport');
var url = require('url');
var FacebookStrategy = require('passport-facebook').Strategy;
var config = require('../config');
var users = require('../../app/controllers/users.server.controller');
// Create the Facebook strategy configuration method
module.exports = function () {
// Use the Passport's Facebook strategy
passport.use(new FacebookStrategy({
clientID: config.facebook.clientID,
clientSecret: config.facebook.clientSecret,
callbackURL: config.facebook.callbackURL,
passReqToCallback: true
}, function (req, accessToken, refreshToken, profile, done) {
// Set the user's provider data and include tokens
var providerUserProfile;
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
providerUserProfile = {
firstName: profile.name.givenName,
lastName: profile.name.familyName,
fullName: profile.displayName,
email: profile.emails[0].value,
username: profile.username,
provider: 'facebook',
providerId: profile.id,
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}));
}; |
/**
* Get the GET variables from the url.
*/
function getUrlVars(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var currentSentenceNumber = 1;
var lang = getUrlVars()["language"];
if(lang == undefined){
var lang = userLanguage;
}
/**
* Downloads the newest poems for the poem showcase
*/
function downloadFeed () {
if (mode == "view") {
return;
}
$.ajax({
url: $("#base_url").val()+'live/?language='+lang,
success: function (data) {
if (typeof data.poems == "undefined") {
return;
}
$('#poemShowcase').html("");
$.each(data.poems,function (index,element) {
if (element.sentences == null) {
return;
}
var poem = $('<a href="'+$("#base_url").val()+'poem/'+element.identifier+'"></a>');
if (typeof element.title != "undefined") {
poem.append('<p class="header">'+element.title+'</p>');
}
var sentences = $('<div class="sentences"></div>');
$.each(element.sentences, function (sentenceIndex, sentence) {
sentences.append('<span class="sentence">'+sentence.sentence+"</span><br>");
});
poem.append(sentences);
poem.append("<em> - "+element.creator+"</em>");
poem.append("<hr>");
$('#poemShowcase').append(poem);
if ($('#poemShowcase hr').length > 1) {
$('#poemShowcase hr:last').remove();
}
});
}
});
}
$(function(){
$("#addTag").live("click",function () {
$('#addTagDialog').dialog({
maxHeigth: 20,
minWidth: 300,
maxWidth: 300,
resizable: false,
modal: true
});
});
$("#saveTagButton").live("click", function () {
if ($("#tagInput").val() != "" && $("#tag-select").find("option:contains('"+$("#tagInput").val()+"')")) {
$("#tag-select").append('<option selected>'+$("#tagInput").val()+'</option>').trigger("liszt:updated");
$("#tag-select").trigger("liszt:updated");
$("#tagInput").val("");
$('#addTagDialog').dialog("close");
}
});
if (typeof mode != undefined && mode == "view") {
$.ajax({
url : $("#base_url").val() + "collection/"+collection,
success : function (data) {
if (typeof data.poems != "undefined") {
$.each(data.poems,function (index,poem) {
var html = $("#poemTemplate").html();
var sentences = "";
html = html.replace("{title}",poem.title);
html = html.replace("{creator}",poem.creator);
var date = new Date(poem.time_created*1000);
$.each(poem.sentences,function(sentenceId,sentence) {
sentences += sentence.sentence+"<br>";
});
html = html.replace("{sentences}","<div>"+sentences+"</div>");
html = html.replace("{date}","<u>"+date.toUTCString()+"</u>");
$("#view").append(html);
});
}
$("#view").removeClass("disabledPage");
$("body").css("display","");
}
});
return;
} else {
$("#create").removeClass("disabledPage");
}
downloadFeed();
$.get(base_url+"tags").success(function (data) {
var data = $.parseJSON(data);
if ($(data.tags).length == 0) {
return;
}
$.each(data.tags,function (index,element) {
$("#tag-select").append("<option>"+element+"</option>");
if (index == $(data.tags).length) {
$("#tag-select").chosen({
no_results_text: translations.no_results_found
});
}
});
});
var questions = $('#questions');
var box = $('#title');
/**
* Refresheshs the selectboxes
*/
function refreshSelects(){
var selects = questions.find('select');
// Improve the selects with the Chose plugin
selects.chosen({
no_results_text: translations.no_results_found
});
// Listen for changes
selects.unbind('change').bind('change',function(){
// The selected option
var selected = $(this).find('option').eq(this.selectedIndex);
// Look up the data-connection attribute
var connection = selected.data('connection');
// Removing the li containers that follow (if any)
selected.closest('#questions li').nextAll().remove();
if(connection){
fetchSelect(connection);
}
});
}
var working = false;
/**
* Fetches select data from server
* @param {No idea} I don't know
*/
function fetchSelect(){
if(working){
return false;
}
working = true;
$.getJSON($("#base_url").val()+'select/'+collection+'?language='+lang,{},function(jsonData){
if (typeof jsonData.error_message != "undefined") {
var boxTitle = jsonData.error_message;
} else {
var boxTitle = jsonData.boxTitle;
}
// Add the flags
boxTitle += '<img id="flagDK" src="'+$("#base_url").val()+'assets/images/dk.png"/>\
<img id="flagGB" src="'+$("#base_url").val()+'assets/images/gb.png"/>';
// Set the title of the box
$('#title').html(boxTitle);
var selectTitle = jsonData.selectTitle;
if (typeof jsonData.selects != "undefined") {
$.each(jsonData.selects,function(arrayIndex,sentenceNumber) {
// Create options array
var options = '';
// Add a blank option
options+= '<option value=""></option>';
// Set the default text
if (sentenceNumber == "unlimited") {
var sentenceNumberText = translations.unlimited;
} else {
var sentenceNumberText = sentenceNumber;
}
var defaultText = selectTitle.replace("{number_of_syllabels}",sentenceNumberText);;
if (typeof jsonData.sentences[sentenceNumber] != "undefined") {
// Loop through sentencesj
$.each(jsonData.sentences[sentenceNumber],function(index,sentence){
options+= '<option value="' + sentence + '">' + sentence + '</option>';
});
}
// Add the select box
$('<select data-placeholder="'+defaultText+'" data-syllabels="'+sentenceNumber+'" class="sentence-select">'+ options +'</select>').appendTo(box);
$('<img src="'+base_url+'assets/images/add.png" style="margin-left:5px;" class="addIcon" id="addIcon' + currentSentenceNumber + '"></img>').appendTo(box);
currentSentenceNumber++;
});
}
refreshSelects();
working = false;
afterSelectCreation();
});
}
// Initially load the product select
fetchSelect();
/**
* When the submitButton is clicked, the saveDialog will be revealed.
*/
$('#submitButton').click(function(e) {
$('#saveDialog').dialog({
maxHeigth: 20,
minWidth: 300,
maxWidth: 300,
resizable: false,
modal: true
});
});
/**
* When enter is pressed on saveDialogName, click on saveDialogSaveButton.
*/
$('#saveDialogName').keypress(function(event) {
if ( event.which == 13 ) {
$('#saveDialogSaveButton').click();
$('#saveDialog').dialog("close");
}
});
/**
* When saveDialogSaveButton is clicked, send the data to the server.
*/
$('#saveDialogSaveButton').click(function () {
ajaxCall($("#base_url").val()+'Pusher/send_message.php', { message : "update" });
if (sendSelectValues($('#saveDialogName').val(),$('#saveDialogTitle').val()) === true) {
$("#saveDialog").dialog("close");
}
});
/**
* Sends the data(poem) to the server
*/
function sendSelectValues (name,title) {
if ($(".sentence-select option:selected").length != $(".sentence-select").length) {
showError(translations.missing_fields,translations.alert,1500);
return;
}
var object = {
"creator" : name,
"language" : userLanguage,
"sentences" : [],
"title" : title,
"tags" : []
};
$(".sentence-select").each(function(index,element) {
if ($(element).attr("data-syllabels") !== "undefined" && ($(element).attr("data-syllabels") == "unlimited" || countSyllabels($(element).val(),translation_vowels) == $(element).attr("data-syllabels"))) {
object.sentences.push({
"sentence" : $(element).val(),
"language" : userLanguage,
"syllabels" : ($(element).attr("data-syllabels") == "unlimited") ? "unlimited" : countSyllabels($(element).val(),translation_vowels)
});
}
});
var tags = $("#tag-select").val();
for (var i = 0; i < tags.length; i++) {
object.tags.push({
"tag" : tags[i].toLowerCase()
});
};
if (object.sentences.length != $(".sentence-select").length) {
showError(translations.no_sentences_match,translations.alert,1000);
return;
}
$.ajax({
url : $("#base_url").val()+"poem/save/"+collection,
type : "POST",
data : JSON.stringify(object),
error : function () {
showError(translations.an_error_occured,translations.alert,1500);
}
});
return true;
}
/**
* Adds some CSS style, based on the browser being used.
*/
function styleBrowsers() {
var deviceAgent = navigator.userAgent.toLowerCase();
var webkitFirefox = deviceAgent.match(/(webkit|firefox)/);
var webkitOpera = deviceAgent.match(/(webkit|opera)/);
if (webkitFirefox) {
// Webkit & Firefox
$('#dialogValidationIcon').addClass('dialogValidationIcon_WebkitFirefox');
}
if (webkitOpera) {
// Webkit & Opera
$('.addIcon').addClass('addIcon_WebkitOpera');
}
}
/**
* When dialogSaveButton is clicked, add the data to the selects and close the dialog box
*/
$('#dialogSaveButton').click(function () {
if (saveDialog() == true) {
$("#dialog").dialog("close");
}
});
/**
* When enter is pressed in dialogSentence, click on dialogSaveButton.
*/
$('#dialogSentence').keypress(function(event) {
if ( event.which == 13 ) {
$('#dialogSaveButton').click();
}
});
/**
* This function counts the number of syllabels
* @param {string} word The word to count in
* @param {Array} syllabelsList The list of accepted syllabels
* @return {integer}
*/
function countSyllabels (word, syllabelsList) {
var syllables = 0;
word = word.toLowerCase();
$.each(syllabelsList, function(index, element) {
syllables += (word.split(element).length - 1);
});
return syllables;
}
/**
* When a key is pressed in dialogSentence, count the number of syllables
*/
$('#dialogSentence').keyup(function(event) {
var target = event.target;
var value = target.value.toLowerCase();
var index = $('#dialogSentenceNumber').val();
var allowedSyllables;
//Needs to be rethought
if($(".sentence-select").eq(index-1).attr("data-syllabels") !== "undefined") {
allowedSyllables = $(".sentence-select").eq(index-1).attr("data-syllabels");
} else {
allowedSyllables = 5;
}
var syllables = countSyllabels(value,translation_vowels);
if(allowedSyllables == syllables || (allowedSyllables == "unlimited") && syllables > 0) {
$('#dialogValidationIcon').attr("src",base_url+"assets/images/validationOk.png");
} else {
$('#dialogValidationIcon').attr("src",base_url+"assets/images/validationError.png");
}
});
/**
* Adds the content of dialogSentence to the select box and scrolls to the top of the page.
*/
function saveDialog () {
// Ipad customizations.
$('#dialogSentence').blur();
$('html, body').animate({scrollTop:0}, 'fast');
// ---
var index = $('#dialogSentenceNumber').val();
var sentence = $('#dialogSentence').val();
if ($(".sentence-select").eq(index-1).attr("data-syllabels") == countSyllabels(sentence,translation_vowels) || $(".sentence-select").eq(index-1).attr("data-syllabels") == "unlimited") {
removeSelection(index-1);
$('<option selected value="' + sentence + '">' + sentence + '</option>').appendTo($(".sentence-select").eq(index-1));
$('<option value="' + sentence + '">' + sentence + '</option>').appendTo($('[data-syllabels="'+$(".sentence-select").eq(index-1).attr("data-syllabels")+'"]:not(:eq('+$(".sentence-select").eq(index-1)+'))'));
$('[data-syllabels="'+$(".sentence-select").eq(index-1).attr("data-syllabels")+'"]').trigger("liszt:updated");
return true;
}
}
/**
* Shows the "add your own sentence" dialog
* @param {Integer} index The jQuery index of the selected box
*/
function showAddDialog (index) {
var allowedSyllables;
//This section needs to be converted
if($(".sentence-select").eq(index-1).attr("data-syllabels") !== "undefined") {
allowedSyllables = $(".sentence-select").eq(index-1).attr("data-syllabels");
} else {
allowedSyllables = 5;
}
if (allowedSyllables == "unlimited") {
var allowedSyllablesText = translations.unlimited;
} else {
var allowedSyllablesText = allowedSyllables;
}
$('#dialogLabel').html($('#dialogLabel').attr("data-translated").replace("{number_of_syllabels}",allowedSyllablesText))
$('#dialogValidationIcon').attr("src",base_url+"assets/images/validationError.png");
$('#dialogSentenceNumber').val(index);
$('#dialogSentence').val('');
$('#dialog').dialog({
maxHeigth: 20,
minWidth: 300,
maxWidth: 300,
resizable: false,
modal: true
});
// ------- IPAD
var deviceAgent = navigator.userAgent.toLowerCase();
var iPad = deviceAgent.match(/(ipad)/);
if (iPad) {
$('#dialogSentence').removeAttr('style');
$('#dialogSentence').attr('style','width:230px;');
}
}
/**
* Removes all selections in the desired selectbox
* @param {Integer} sentenceNumber The currently used select box (1-3)
*/
function removeSelection (eq) {
$(".sentence-select").eq(eq).removeAttr('selected');
}
/**
* After the selectboxes are created, add on click functions to all of the addIcons and style the browsers.
*/
function afterSelectCreation () {
$("button").button();
$('#submitButton').show();
styleBrowsers();
$('body').fadeIn('slow');//sentence-select
$(".addIcon").live("click",function () {
showAddDialog(index($(this).prev("div").prev("select"), $(".sentence-select"))+1);
});
/**
* When the Danish flag is clicked, send the user to the Danish page
*/
$('#flagDK').click(function () {
document.location = $("#base_url").val()+'?language=danish';
});
/**
* When the English(GB) flag is clicked, send the user to the English(GB) page
*/
$('#flagGB').click(function () {
document.location = $("#base_url").val()+'?language=english';
});
};
function index (element, selector) {
for (var i = 0; i <= selector.length; i++) {
if (compare(selector.eq(i),element)) {
return i;
}
};
}
function compare (element, object) {
return ($(element).get(0) == $(object).get(0));
}
// Variables
var pusher;
var chat_channel;
// Send message function
function ajaxCall(ajax_url, ajax_data) {
$.ajax({
type : "POST",
url : ajax_url,
dataType : "json",
data: ajax_data,
async: false
});
}
// Create pusher object
pusher = new Pusher('9b245d36fea0d2611317');
// Set the channel auth endpoint
Pusher.channel_auth_endpoint = $("#base_url").val()+'Pusher/pusher_auth.php';
// Subscribe to the chat channel
chat_channel = pusher.subscribe('haiku-update-channel');
// Listen for the connected event
pusher.connection.bind('connected', function() {
// Listen for new messages
chat_channel.bind('haiku-update', function(data) {
// Call function to handle the data
setTimeout("downloadFeed()",2000);
});
});
/*
Share
*/
/*
Copyright
*/
});
|
define('app', [
'angular-package'
], function (config) {
var module = angular.module;
angular.module = function() {
var args = [].slice.call(arguments);
var app = module.apply(angular, args);
return app.config([
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide',
function($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.provider = $provide.provider;
app.value = $provide.value;
app.constant = $provide.constant;
app.decorator = $provide.decorator;
}
]);
};
var app = angular.module('ngApp',[
'oc.lazyLoad',
'ui.router',
// 'pascalprecht.translate',
'ngCookies'
]);
app.service('breadcrumb', function () {
return {
title: '',
subTitle: '',
list: []
};
})
.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
$ocLazyLoadProvider.config({
debug: true,
events: true,
modules: [
{
name: 'ui.codemirror',
module: true,
files: [
'../bower_components/angular-ui-codemirror/ui-codemirror.min.js'
]
}, {
name: 'wu.masonry',
module: true,
files: [
'../bower_components/angular-masonry/angular-masonry.js'
]
}
]
});
}])
.factory('appCookie', function() {
return function() {
token: ''
};
})
.service('config', function() {
return {
hasLogin: false,
setLogin: function(bool) {
this.hasLogin = bool;
},
username: ''
};
})
.controller('IndexController', [
'$scope', '$rootScope', '$state', '$cookieStore', 'config', 'breadcrumb',
function ($scope, $rootScope, $state, $cookieStore, config, breadcrumb)
{
var self = this;
self.hasLogin = config.hasLogin;
self.config = config;
self.parent = '';
self.subject = '';
self.toLogin = function() {
$state.go('main.auth.login', {});
};
self.logout = function() {
$cookieStore.remove('access_token');
self.toLogin();
};
self.linkto = function(link) {
$state.go(link);
};
self.breadcrumb = breadcrumb;
self.unAuthPaths = [
'main.auth.login',
'main.auth.register'
];
$rootScope.$on('$stateChangeStart',
function (event, toState, toParams, fromState, fromParams){
var name = toState.name;
var options = name.split('.');
if (options.length === 2) {
self.parent = options[1];
} else if (options.length >= 3) {
self.parent = options[1];
self.subject = options[2];
} else {
self.parent = 'dashboard';
self.subject = 'v1';
}
// Check wether login
if (self.unAuthPaths.indexOf(name) < 0) {
var token = $cookieStore.get('access_token');
self.username = $cookieStore.get('username');
if (!token || !self.username) {
event.preventDefault();
self.toLogin();
}
}
}, $scope
);
}]);
return app;
});
|
define(['marionette', 'backbone', 'modTopic', 'config', 'i18n'],
function(Marionette, Backbone, ModTopic, config) {
'use strict';
return Marionette.LayoutView.extend({
template: 'app/base/consultation/tpl/tpl-consultation.html',
className: 'consultation-page ns-full-height',
events: {
},
initialize: function(options) {
this.options = options;
this.model = window.app.user;
var topic = new ModTopic({id:options.key});
topic.fetch({async:false});
console.log(this);
/*this.userLanguage =*/
this.topic = topic;
},
serializeData: function(){
return {
topic: this.topic.attributes,
refLangue: config.refLanguage,
langue: this.model.attributes.language
};
},
animateIn: function() {
this.$el.find('#schtroudel').animate(
{opacity: 1},
500,
_.bind(this.trigger, this, 'animateIn')
);
},
// Same as above, except this time we trigger 'animateOut'
animateOut: function() {
this.$el.find('#tiles').removeClass('zoomInUp');
this.$el.animate(
{opacity: 0},
500,
_.bind(this.trigger, this, 'animateOut')
);
},
onShow: function(options) {
this.$el.i18n();
},
});
});
|
import map from 'lodash.map';
import every from 'lodash.every';
const addEntityToStoreFragment = (store, entity) => {
const { type, id, attributes, relationships } = entity;
if (!entity) {
return;
}
if (!(type in store)) {
store[type] = {};
}
store[type][id] = {
type: type,
id: id,
attributes: attributes,
relationships: relationships
};
};
const normalizeDataEntities = (storeFragment, dataEntities) => {
const entityList = Array.isArray(dataEntities) ? dataEntities : [dataEntities];
entityList.map((entity) => addEntityToStoreFragment(storeFragment, entity));
};
const normalizeIncludedEntities = (storeFragment, includedEntities) => {
map(includedEntities, (entity) => addEntityToStoreFragment(storeFragment, entity));
};
const makeEntityReferences = (data) => {
if (!data) {
return [];
}
const dataList = Array.isArray(data) ? data : [data];
return dataList.map((entity) => ({id: entity.id, type: entity.type}));
};
export const isJsonApiResponse = ({ data }) => {
const dataList = Array.isArray(data) ? data : [data];
return data && every(dataList, ref => ref.id !== undefined && ref.type !== undefined);
};
export default function parseJsonApiResponse(response) {
const { data, included, meta, links } = response;
// Create the new ref to pass to the entities reducer.
const newRequestRef = {
entities: makeEntityReferences(data),
meta,
links,
isCollection: data instanceof Array
};
// Create a store fragment map of normalized entities to pass to the entity reducer
// This will take the shape of { [type] : { [id]: ... } }
const storeFragment = {};
normalizeDataEntities(storeFragment, data);
normalizeIncludedEntities(storeFragment, included);
return {
storeFragment,
newRequestRef
};
}
|
var x = Math.floor((Math.random()*10000)+1)
//console.log( CKEDITOR.dialog )
CKEDITOR.dialog.add( 'fmDialog', function( editor ) {
return {
title: 'File Manager',
resizable: CKEDITOR.DIALOG_RESIZE_NONE,
buttons : [],
onShow : function() {
// reload the home page when every time dialog come to view. This is a workaround for ck dialog catching
var alle = document.getElementsByClassName("fmmainholder");
for(var i=0; i < alle.length; i++) {
thisalle = alle[i]
if ( isVisible(thisalle) ) {
thisalle.innerHTML = '<iframe style="width:100%;" scrolling="No" class="filemanageriframe" src="/assets/vendor/ckeditor/plugins/filemanager/filemanager.cfm"></iframe>'
}
}
},
contents: [
{
id: 'filebox',
label: 'filebox',
title: 'filebox',
elements: [
{
type: 'html',
html: '<div class="fmmainholder">Loading</div>'
}
]
}
],
};
})
function isVisible(obj)
{
if (obj == document) return true
if (!obj) return false
if (!obj.parentNode) return false
if (obj.style) {
if (obj.style.display == 'none') return false
if (obj.style.visibility == 'hidden') return false
}
if (window.getComputedStyle) {
var style = window.getComputedStyle(obj, "")
if (style.display == 'none') return false
if (style.visibility == 'hidden') return false
}
var style = obj.currentStyle
if (style) {
if (style['display'] == 'none') return false
if (style['visibility'] == 'hidden') return false
}
return isVisible(obj.parentNode)
} |
import React, { Component } from 'react'
import { SessionStore, UsersStore, RoomsStore, DrawerStore } from '../../stores'
import { Profile, Drawer, DrawerHeader } from '..'
import { getRoomProfileProps, drawerIsOpen } from '../../utils'
import { FilterList } from '../../components'
import { observer } from 'mobx-react'
let drawerId, drawerTitle, profileProps
const getItems = () => {
const { rooms } = RoomsStore
return rooms.map(e => ({ primaryText: e.title, avatar: e.avatar, data: e }))
}
const listItemProps = {
}
const onListItemClick = room => {
const isInRoom = SessionStore.isInRoom(room)
drawerTitle = room.title
profileProps = getRoomProfileProps(room,
UsersStore.users.filter(u => room.members.indexOf(u.username) >= 0))
profileProps.actions = [
{ label: isInRoom ? 'Exit' : 'Join',
backgroundColor: isInRoom ? '#B71C1C' : '#fff',
labelColor: isInRoom ? '#fff' : '#000',
onClick: () => {
if (isInRoom)
SessionStore.exit(room)
else
SessionStore.join(room)
DrawerStore.pop()
}
}
]
drawerId = DrawerStore.push()
}
const Rooms = props => {
return (
<div style={{ height: '100%' }}>
<FilterList items={getItems()} hintText="Type room name"
onListItemClick={onListItemClick}
listItemProps={listItemProps} />
{
drawerIsOpen(drawerId, DrawerStore.drawers) ?
<Drawer closing={DrawerStore.drawerClosing == drawerId}>
<DrawerHeader title={drawerTitle} close={() => DrawerStore.pop()} />
<div style={{ height: '82.439%' }}>
<Profile {...profileProps} />
</div>
</Drawer> : null
}
</div>
)
}
export default observer(Rooms) |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var assign = make_assign()
var create = make_create()
var trim = make_trim()
var Global = (typeof window !== 'undefined' ? window : global)
module.exports = {
assign: assign,
create: create,
trim: trim,
bind: bind,
slice: slice,
each: each,
map: map,
pluck: pluck,
isList: isList,
isFunction: isFunction,
isObject: isObject,
Global: Global,
}
function make_assign() {
if (Object.assign) {
return Object.assign
} else {
return function shimAssign(obj, props1, props2, etc) {
for (var i = 1; i < arguments.length; i++) {
each(Object(arguments[i]), function(val, key) {
obj[key] = val
})
}
return obj
}
}
}
function make_create() {
if (Object.create) {
return function create(obj, assignProps1, assignProps2, etc) {
var assignArgsList = slice(arguments, 1)
return assign.apply(this, [Object.create(obj)].concat(assignArgsList))
}
} else {
function F() {} // eslint-disable-line no-inner-declarations
return function create(obj, assignProps1, assignProps2, etc) {
var assignArgsList = slice(arguments, 1)
F.prototype = obj
return assign.apply(this, [new F()].concat(assignArgsList))
}
}
}
function make_trim() {
if (String.prototype.trim) {
return function trim(str) {
return String.prototype.trim.call(str)
}
} else {
return function trim(str) {
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
}
}
}
function bind(obj, fn) {
return function() {
return fn.apply(obj, Array.prototype.slice.call(arguments, 0))
}
}
function slice(arr, index) {
return Array.prototype.slice.call(arr, index || 0)
}
function each(obj, fn) {
pluck(obj, function(key, val) {
fn(key, val)
return false
})
}
function map(obj, fn) {
var res = (isList(obj) ? [] : {})
pluck(obj, function(v, k) {
res[k] = fn(v, k)
return false
})
return res
}
function pluck(obj, fn) {
if (isList(obj)) {
for (var i=0; i<obj.length; i++) {
if (fn(obj[i], i)) {
return obj[i]
}
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (fn(obj[key], key)) {
return obj[key]
}
}
}
}
}
function isList(val) {
return (val != null && typeof val != 'function' && typeof val.length == 'number')
}
function isFunction(val) {
return val && {}.toString.call(val) === '[object Function]'
}
function isObject(val) {
return val && {}.toString.call(val) === '[object Object]'
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(13)))
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
var engine = __webpack_require__(5)
var storages = __webpack_require__(6)
var plugins = [__webpack_require__(3)]
module.exports = engine.createStore(storages, plugins)
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Created by Moby on 2017/5/5.
*/
;(function () {
'use strict';
// console.info("$", $); // 测试jQuery是否加载成功
// console.info("jQuery", jQuery); // 测试jQuery是否加载成功
var store = __webpack_require__(1); // node_modules/.bin/webpack js/base.js js/base.bundle.js
$.datetimepicker.setLocale('zh');
var $form_task_add = $('.task-add'),
task_list = [],
$btn_delete,
$btn_detail,
$container_mask = $('.container-mask'),
$task_detail = $('.task-detail'),
$task_list = $('.task-list'),
$task_list_complete = $('.task-list-complete'),
$task_complete_btn = $('.task-complete-btn'),
isShowComplete = false;
init();
/**
* 新增任务条目
* @param task
* @returns {boolean}
*/
function add_task(task) {
task_list.push(task);
refresh_task_list();
return true;
}
/**
* 根据索引删除任务条目
* @param index
*/
function delete_task(index) {
if (index === undefined || !task_list[index]) return;
delete task_list[index];
refresh_task_list();
render_task_list();
}
/**
* 渲染任务列表
*/
function render_task_list() {
$task_list.html('');
$task_list_complete.html('');
for (var i = 0; i < task_list.length; i++) {
if (!task_list[i]) continue;
var $task = render_task_item(task_list[i], i);
if (task_list[i].complete) {
$task.addClass('task-complete');
$task_list_complete.append($task);
} else {
$task_list.append($task);
}
}
// 按钮绑定事件
$btn_delete = $('.inner-action.delete');
$btn_detail = $('.inner-action.detail');
$btn_delete.on('click', function () {
var $this = $(this);
var $item = $this.parent().parent();
if (!confirm('您确定删除吗?')) return;
delete_task($item.data('index'));
});
$btn_detail.on('click', function () {
var $this = $(this);
var $item = $this.parent().parent();
render_task_detail($item.data('index'));
});
$task_list.find('div[name=taskItem]').on('dblclick', function () {
var $item = $(this);
render_task_detail($item.data('index'));
});
$task_list.find('div[name=taskItem] input[type=checkbox]').on('change', function (evt) {
var $this = $(this);
var is_complete = $this.is(':checked');
var index = $this.parent().parent().data('index');
update_task_detail(index, {complete: is_complete});
render_task_list();
});
$task_list_complete.find('div[name=taskItem]').on('dblclick', function () {
var $item = $(this);
render_task_detail($item.data('index'));
});
$task_list_complete.find('div[name=taskItem] input[type=checkbox]').on('change', function (evt) {
var $this = $(this);
var is_complete = $this.is(':checked');
var index = $this.parent().parent().data('index');
update_task_detail(index, {complete: is_complete});
render_task_list();
});
}
/**
* 渲染任务列表条目
* @param data
* @param index
* @returns {*|jQuery|HTMLElement}
*/
function render_task_item(data, index) {
if (!data || !index) return;
var task_item_tpl =
'<div class="task-item" name="taskItem" data-index="' + index + '">' +
'<span><input type="checkbox" ' + (data.complete ? "checked" : "") + '></span>' +
'<span class="task-content">' + data.content + '</span>' +
'<span class="inner-action-bar">' +
'<span class="inner-action delete"> 删除 </span>' +
'<span class="inner-action detail"> 详细 </span>' +
'</span>' +
'</div>';
return $(task_item_tpl);
}
/**
* 任务数据持久化
*/
function refresh_task_list() {
store.set('task_list', task_list);
}
/**
* 初始化页面
*/
function init() {
task_list = store.get('task_list') || [];
if (task_list.length) render_task_list();
/**
* 监听事件,任务新增提交按钮
*/
$form_task_add.on('submit', function (e) {
var task_new = {}, $task_input = $(this).find('input[name=ipt_task_add]');
// 禁用默认提交
e.preventDefault();
task_new.content = $task_input.val();
// 如果为空,则返回
if (!task_new.content) return;
// 保存new task
if (add_task(task_new)) {
render_task_list();
$task_input.val('');
}
});
$task_complete_btn.on('click', function (evt) {
isShowComplete = !isShowComplete;
var $this = $(this);
$this.text((isShowComplete ? "隐藏" : "显示") + "已完成");
changeCompleteShowStatus(isShowComplete);
});
changeCompleteShowStatus(isShowComplete);
check_task_remind();
}
/**
* 渲染任务详情页面
* @param index
*/
function render_task_detail(index) {
if (index === undefined || !task_list[index]) return;
var item = task_list[index];
$container_mask.show();
$task_detail.show();
var task_detail_tpl = '<form>' +
'<div class="task-detail-item">' +
'<div class="content">' + item.content + '</div>' +
'<input type="text" name="content" value="' + item.content + '">' +
'</div>' +
'<div class="description task-detail-item">' +
'<textarea name="detail" placeholder="请输入任务详细描述信息...">' + (item.detail || '') + '</textarea>' +
'</div>' +
'<div class="remind task-detail-item">' +
'<lable>提醒时间</lable>' +
'<input class="datetime" type="text" value="' + (item.date || '') + '">' +
'</div>' +
'<div class="task-detail-item">' +
'<button type="submit">保存</button>' +
'</div>' +
'</form>';
$task_detail.html(task_detail_tpl);
$task_detail.find('div[class=content]').show();
$task_detail.find('input[name=content]').hide();
$task_detail.css({
left: ($(window).width() - $task_detail.width()) / 2,
top: ($(window).height() - $task_detail.height()) / 2 + $(document.body).scrollTop()
});
$task_detail.find('input[class=datetime]').datetimepicker();
$container_mask.on('click', function () {
$container_mask.hide();
$task_detail.hide();
});
$task_detail.find('form').on('submit', function (e) {
e.preventDefault();
item.content = $task_detail.find('input[name=content]').val();
item.detail = $task_detail.find('textarea[name=detail]').val();
item.date = $task_detail.find('input[class=datetime]').val();
update_task_detail(index, item);
});
$task_detail.find('div[class=content]').on('click', function () {
$task_detail.find('div[class=content]').hide();
$task_detail.find('input[name=content]').show();
$task_detail.find('input[name=content]').focus();
$task_detail.find('input[name=content]').select();
});
$task_detail.find('textarea').focus();
}
function update_task_detail(index, data) {
if (index === undefined || !data) return;
$.extend(task_list[index], data);
refresh_task_list();
render_task_list();
}
function changeCompleteShowStatus(isShowComplete) {
isShowComplete ? $task_list_complete.show() : $task_list_complete.hide();
}
function check_task_remind() {
var current_timestamp;
var itl = setInterval(function () {
for (var i = 0; i < task_list.length; i++) {
if (!task_list[i] || !task_list[i].date) continue;
var item = task_list[i], task_timestamp;
current_timestamp = (new Date()).getTime();
task_timestamp = (new Date(item.date)).getTime();
console.log(new Date().getHours() + ":" + new Date().getMinutes());
if (task_timestamp > current_timestamp && task_timestamp - current_timestamp <= 300000 ) { // 提前5分钟(5 * 60 * 1000ms)开始提醒
notify_task_remind(item.content);
}
}
}, 60000); // 每分钟(60 * 1000ms)检查一次任务提醒
}
function notify_task_remind(content) {
console.info(content);
}
})();
/**
* (function(){ ... })()
* 写法用途:
* 1.自调用
* 2.限定作用域
*/
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = json2Plugin
function json2Plugin() {
__webpack_require__(4)
return {}
}
/***/ }),
/* 4 */
/***/ (function(module, exports) {
// json2.js
// 2016-10-28
// Public Domain.
// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
// See http://www.JSON.org/js.html
// This code should be minified before deployment.
// See http://javascript.crockford.com/jsmin.html
// USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
// NOT CONTROL.
// This file creates a global JSON object containing two methods: stringify
// and parse. This file provides the ES5 JSON capability to ES3 systems.
// If a project might run on IE8 or earlier, then this file should be included.
// This file does nothing on ES5 systems.
// JSON.stringify(value, replacer, space)
// value any JavaScript value, usually an object or array.
// replacer an optional parameter that determines how object
// values are stringified for objects. It can be a
// function or an array of strings.
// space an optional parameter that specifies the indentation
// of nested structures. If it is omitted, the text will
// be packed without extra whitespace. If it is a number,
// it will specify the number of spaces to indent at each
// level. If it is a string (such as "\t" or " "),
// it contains the characters used to indent at each level.
// This method produces a JSON text from a JavaScript value.
// When an object value is found, if the object contains a toJSON
// method, its toJSON method will be called and the result will be
// stringified. A toJSON method does not serialize: it returns the
// value represented by the name/value pair that should be serialized,
// or undefined if nothing should be serialized. The toJSON method
// will be passed the key associated with the value, and this will be
// bound to the value.
// For example, this would serialize Dates as ISO strings.
// Date.prototype.toJSON = function (key) {
// function f(n) {
// // Format integers to have at least two digits.
// return (n < 10)
// ? "0" + n
// : n;
// }
// return this.getUTCFullYear() + "-" +
// f(this.getUTCMonth() + 1) + "-" +
// f(this.getUTCDate()) + "T" +
// f(this.getUTCHours()) + ":" +
// f(this.getUTCMinutes()) + ":" +
// f(this.getUTCSeconds()) + "Z";
// };
// You can provide an optional replacer method. It will be passed the
// key and value of each member, with this bound to the containing
// object. The value that is returned from your method will be
// serialized. If your method returns undefined, then the member will
// be excluded from the serialization.
// If the replacer parameter is an array of strings, then it will be
// used to select the members to be serialized. It filters the results
// such that only members with keys listed in the replacer array are
// stringified.
// Values that do not have JSON representations, such as undefined or
// functions, will not be serialized. Such values in objects will be
// dropped; in arrays they will be replaced with null. You can use
// a replacer function to replace those with JSON values.
// JSON.stringify(undefined) returns undefined.
// The optional space parameter produces a stringification of the
// value that is filled with line breaks and indentation to make it
// easier to read.
// If the space parameter is a non-empty string, then that string will
// be used for indentation. If the space parameter is a number, then
// the indentation will be that many spaces.
// Example:
// text = JSON.stringify(["e", {pluribus: "unum"}]);
// // text is '["e",{"pluribus":"unum"}]'
// text = JSON.stringify(["e", {pluribus: "unum"}], null, "\t");
// // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
// text = JSON.stringify([new Date()], function (key, value) {
// return this[key] instanceof Date
// ? "Date(" + this[key] + ")"
// : value;
// });
// // text is '["Date(---current time---)"]'
// JSON.parse(text, reviver)
// This method parses a JSON text to produce an object or array.
// It can throw a SyntaxError exception.
// The optional reviver parameter is a function that can filter and
// transform the results. It receives each of the keys and values,
// and its return value is used instead of the original value.
// If it returns what it received, then the structure is not modified.
// If it returns undefined then the member is deleted.
// Example:
// // Parse the text. Values that look like ISO date strings will
// // be converted to Date objects.
// myData = JSON.parse(text, function (key, value) {
// var a;
// if (typeof value === "string") {
// a =
// /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
// if (a) {
// return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
// +a[5], +a[6]));
// }
// }
// return value;
// });
// myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
// var d;
// if (typeof value === "string" &&
// value.slice(0, 5) === "Date(" &&
// value.slice(-1) === ")") {
// d = new Date(value.slice(5, -1));
// if (d) {
// return d;
// }
// }
// return value;
// });
// This is a reference implementation. You are free to copy, modify, or
// redistribute.
/*jslint
eval, for, this
*/
/*property
JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== "object") {
JSON = {};
}
(function () {
"use strict";
var rx_one = /^[\],:{}\s]*$/;
var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
var rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
function f(n) {
// Format integers to have at least two digits.
return n < 10
? "0" + n
: n;
}
function this_value() {
return this.valueOf();
}
if (typeof Date.prototype.toJSON !== "function") {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + "-" +
f(this.getUTCMonth() + 1) + "-" +
f(this.getUTCDate()) + "T" +
f(this.getUTCHours()) + ":" +
f(this.getUTCMinutes()) + ":" +
f(this.getUTCSeconds()) + "Z"
: null;
};
Boolean.prototype.toJSON = this_value;
Number.prototype.toJSON = this_value;
String.prototype.toJSON = this_value;
}
var gap;
var indent;
var meta;
var rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
rx_escapable.lastIndex = 0;
return rx_escapable.test(string)
? "\"" + string.replace(rx_escapable, function (a) {
var c = meta[a];
return typeof c === "string"
? c
: "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + "\""
: "\"" + string + "\"";
}
function str(key, holder) {
// Produce a string from holder[key].
var i; // The loop counter.
var k; // The member key.
var v; // The member value.
var length;
var mind = gap;
var partial;
var value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === "object" &&
typeof value.toJSON === "function") {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === "function") {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case "string":
return quote(value);
case "number":
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value)
? String(value)
: "null";
case "boolean":
case "null":
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce "null". The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is "object", we might be dealing with an object or an array or
// null.
case "object":
// Due to a specification blunder in ECMAScript, typeof null is "object",
// so watch out for that case.
if (!value) {
return "null";
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === "[object Array]") {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || "null";
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? "[]"
: gap
? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]"
: "[" + partial.join(",") + "]";
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === "object") {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === "string") {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (
gap
? ": "
: ":"
) + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (
gap
? ": "
: ":"
) + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? "{}"
: gap
? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}"
: "{" + partial.join(",") + "}";
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== "function") {
meta = { // table of character substitutions
"\b": "\\b",
"\t": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
"\"": "\\\"",
"\\": "\\\\"
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = "";
indent = "";
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === "number") {
for (i = 0; i < space; i += 1) {
indent += " ";
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === "string") {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== "function" &&
(typeof replacer !== "object" ||
typeof replacer.length !== "number")) {
throw new Error("JSON.stringify");
}
// Make a fake root object containing our value under the key of "".
// Return the result of stringifying the value.
return str("", {"": value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== "function") {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k;
var v;
var value = holder[key];
if (value && typeof value === "object") {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
rx_dangerous.lastIndex = 0;
if (rx_dangerous.test(text)) {
text = text.replace(rx_dangerous, function (a) {
return "\\u" +
("0000" + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with "()" and "new"
// because they can cause invocation, and "=" because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
// replace all simple value tokens with "]" characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or "]" or
// "," or ":" or "{" or "}". If that is so, then the text is safe for eval.
if (
rx_one.test(
text
.replace(rx_two, "@")
.replace(rx_three, "]")
.replace(rx_four, "")
)
) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The "{" operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval("(" + text + ")");
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return (typeof reviver === "function")
? walk({"": j}, "")
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError("JSON.parse");
};
}
}());
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var util = __webpack_require__(0)
var slice = util.slice
var pluck = util.pluck
var each = util.each
var create = util.create
var isList = util.isList
var isFunction = util.isFunction
var isObject = util.isObject
module.exports = {
createStore: createStore,
}
var storeAPI = {
version: '2.0.4',
enabled: false,
storage: null,
// addStorage adds another storage to this store. The store
// will use the first storage it receives that is enabled, so
// call addStorage in the order of preferred storage.
addStorage: function(storage) {
if (this.enabled) { return }
if (this._testStorage(storage)) {
this._storage.resolved = storage
this.enabled = true
this.storage = storage.name
}
},
// addPlugin will add a plugin to this store.
addPlugin: function(plugin) {
var self = this
// If the plugin is an array, then add all plugins in the array.
// This allows for a plugin to depend on other plugins.
if (isList(plugin)) {
each(plugin, function(plugin) {
self.addPlugin(plugin)
})
return
}
// Keep track of all plugins we've seen so far, so that we
// don't add any of them twice.
var seenPlugin = pluck(this._seenPlugins, function(seenPlugin) { return (plugin === seenPlugin) })
if (seenPlugin) {
return
}
this._seenPlugins.push(plugin)
// Check that the plugin is properly formed
if (!isFunction(plugin)) {
throw new Error('Plugins must be function values that return objects')
}
var pluginProperties = plugin.call(this)
if (!isObject(pluginProperties)) {
throw new Error('Plugins must return an object of function properties')
}
// Add the plugin function properties to this store instance.
each(pluginProperties, function(pluginFnProp, propName) {
if (!isFunction(pluginFnProp)) {
throw new Error('Bad plugin property: '+propName+' from plugin '+plugin.name+'. Plugins should only return functions.')
}
self._assignPluginFnProp(pluginFnProp, propName)
})
},
// get returns the value of the given key. If that value
// is undefined, it returns optionalDefaultValue instead.
get: function(key, optionalDefaultValue) {
var data = this._storage().read(this._namespacePrefix + key)
return this._deserialize(data, optionalDefaultValue)
},
// set will store the given value at key and returns value.
// Calling set with value === undefined is equivalent to calling remove.
set: function(key, value) {
if (value === undefined) {
return this.remove(key)
}
this._storage().write(this._namespacePrefix + key, this._serialize(value))
return value
},
// remove deletes the key and value stored at the given key.
remove: function(key) {
this._storage().remove(this._namespacePrefix + key)
},
// each will call the given callback once for each key-value pair
// in this store.
each: function(callback) {
var self = this
this._storage().each(function(val, namespacedKey) {
callback(self._deserialize(val), namespacedKey.replace(self._namespaceRegexp, ''))
})
},
// clearAll will remove all the stored key-value pairs in this store.
clearAll: function() {
this._storage().clearAll()
},
// additional functionality that can't live in plugins
// ---------------------------------------------------
// hasNamespace returns true if this store instance has the given namespace.
hasNamespace: function(namespace) {
return (this._namespacePrefix == '__storejs_'+namespace+'_')
},
// namespace clones the current store and assigns it the given namespace
namespace: function(namespace) {
if (!this._legalNamespace.test(namespace)) {
throw new Error('store.js namespaces can only have alhpanumerics + underscores and dashes')
}
// create a prefix that is very unlikely to collide with un-namespaced keys
var namespacePrefix = '__storejs_'+namespace+'_'
return create(this, {
_namespacePrefix: namespacePrefix,
_namespaceRegexp: namespacePrefix ? new RegExp('^'+namespacePrefix) : null
})
},
// createStore creates a store.js instance with the first
// functioning storage in the list of storage candidates,
// and applies the the given mixins to the instance.
createStore: function(storages, plugins) {
return createStore(storages, plugins)
},
}
function createStore(storages, plugins) {
var _privateStoreProps = {
_seenPlugins: [],
_namespacePrefix: '',
_namespaceRegexp: null,
_legalNamespace: /^[a-zA-Z0-9_\-]+$/, // alpha-numeric + underscore and dash
_storage: function() {
if (!this.enabled) {
throw new Error("store.js: No supported storage has been added! "+
"Add one (e.g store.addStorage(require('store/storages/cookieStorage')) "+
"or use a build with more built-in storages (e.g "+
"https://github.com/marcuswestin/store.js/tree/master/dist/store.legacy.min.js)")
}
return this._storage.resolved
},
_testStorage: function(storage) {
try {
var testStr = '__storejs__test__'
storage.write(testStr, testStr)
var ok = (storage.read(testStr) === testStr)
storage.remove(testStr)
return ok
} catch(e) {
return false
}
},
_assignPluginFnProp: function(pluginFnProp, propName) {
var oldFn = this[propName]
this[propName] = function pluginFn() {
var args = slice(arguments, 0)
var self = this
// super_fn calls the old function which was overwritten by
// this mixin.
function super_fn() {
if (!oldFn) { return }
each(arguments, function(arg, i) {
args[i] = arg
})
return oldFn.apply(self, args)
}
// Give mixing function access to super_fn by prefixing all mixin function
// arguments with super_fn.
var newFnArgs = [super_fn].concat(args)
return pluginFnProp.apply(self, newFnArgs)
}
},
_serialize: function(obj) {
return JSON.stringify(obj)
},
_deserialize: function(strVal, defaultVal) {
if (!strVal) { return defaultVal }
// It is possible that a raw string value has been previously stored
// in a storage without using store.js, meaning it will be a raw
// string value instead of a JSON serialized string. By defaulting
// to the raw string value in case of a JSON parse error, we allow
// for past stored values to be forwards-compatible with store.js
var val = ''
try { val = JSON.parse(strVal) }
catch(e) { val = strVal }
return (val !== undefined ? val : defaultVal)
},
}
var store = create(_privateStoreProps, storeAPI)
each(storages, function(storage) {
store.addStorage(storage)
})
each(plugins, function(plugin) {
store.addPlugin(plugin)
})
return store
}
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = {
// Listed in order of usage preference
'localStorage': __webpack_require__(8),
'oldFF-globalStorage': __webpack_require__(10),
'oldIE-userDataStorage': __webpack_require__(11),
'cookieStorage': __webpack_require__(7),
'sessionStorage': __webpack_require__(12),
'memoryStorage': __webpack_require__(9),
}
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
// cookieStorage is useful Safari private browser mode, where localStorage
// doesn't work but cookies do. This implementation is adopted from
// https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
var util = __webpack_require__(0)
var Global = util.Global
var trim = util.trim
module.exports = {
name: 'cookieStorage',
read: read,
write: write,
each: each,
remove: remove,
clearAll: clearAll,
}
var doc = Global.document
function read(key) {
if (!key || !_has(key)) { return null }
var regexpStr = "(?:^|.*;\\s*)" +
escape(key).replace(/[\-\.\+\*]/g, "\\$&") +
"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"
return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1"))
}
function each(callback) {
var cookies = doc.cookie.split(/; ?/g)
for (var i = cookies.length - 1; i >= 0; i--) {
if (!trim(cookies[i])) {
continue
}
var kvp = cookies[i].split('=')
var key = unescape(kvp[0])
var val = unescape(kvp[1])
callback(val, key)
}
}
function write(key, data) {
if(!key) { return }
doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"
}
function remove(key) {
if (!key || !_has(key)) {
return
}
doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
}
function clearAll() {
each(function(_, key) {
remove(key)
})
}
function _has(key) {
return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie)
}
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var util = __webpack_require__(0)
var Global = util.Global
module.exports = {
name: 'localStorage',
read: read,
write: write,
each: each,
remove: remove,
clearAll: clearAll,
}
function localStorage() {
return Global.localStorage
}
function read(key) {
return localStorage().getItem(key)
}
function write(key, data) {
return localStorage().setItem(key, data)
}
function each(fn) {
for (var i = localStorage().length - 1; i >= 0; i--) {
var key = localStorage().key(i)
fn(read(key), key)
}
}
function remove(key) {
return localStorage().removeItem(key)
}
function clearAll() {
return localStorage().clear()
}
/***/ }),
/* 9 */
/***/ (function(module, exports) {
// memoryStorage is a useful last fallback to ensure that the store
// is functions (meaning store.get(), store.set(), etc will all function).
// However, stored values will not persist when the browser navigates to
// a new page or reloads the current page.
module.exports = {
name: 'memoryStorage',
read: read,
write: write,
each: each,
remove: remove,
clearAll: clearAll,
}
var memoryStorage = {}
function read(key) {
return memoryStorage[key]
}
function write(key, data) {
memoryStorage[key] = data
}
function each(callback) {
for (var key in memoryStorage) {
if (memoryStorage.hasOwnProperty(key)) {
callback(memoryStorage[key], key)
}
}
}
function remove(key) {
delete memoryStorage[key]
}
function clearAll(key) {
memoryStorage = {}
}
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
// oldFF-globalStorage provides storage for Firefox
// versions 6 and 7, where no localStorage, etc
// is available.
var util = __webpack_require__(0)
var Global = util.Global
module.exports = {
name: 'oldFF-globalStorage',
read: read,
write: write,
each: each,
remove: remove,
clearAll: clearAll,
}
var globalStorage = Global.globalStorage
function read(key) {
return globalStorage[key]
}
function write(key, data) {
globalStorage[key] = data
}
function each(fn) {
for (var i = globalStorage.length - 1; i >= 0; i--) {
var key = globalStorage.key(i)
fn(globalStorage[key], key)
}
}
function remove(key) {
return globalStorage.removeItem(key)
}
function clearAll() {
each(function(key, _) {
delete globalStorage[key]
})
}
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
// oldIE-userDataStorage provides storage for Internet Explorer
// versions 6 and 7, where no localStorage, sessionStorage, etc
// is available.
var util = __webpack_require__(0)
var Global = util.Global
module.exports = {
name: 'oldIE-userDataStorage',
write: write,
read: read,
each: each,
remove: remove,
clearAll: clearAll,
}
var storageName = 'storejs'
var doc = Global.document
var _withStorageEl = _makeIEStorageElFunction()
var disable = (Global.navigator ? Global.navigator.userAgent : '').match(/ (MSIE 8|MSIE 9|MSIE 10)\./) // MSIE 9.x, MSIE 10.x
function write(unfixedKey, data) {
if (disable) { return }
var fixedKey = fixKey(unfixedKey)
_withStorageEl(function(storageEl) {
storageEl.setAttribute(fixedKey, data)
storageEl.save(storageName)
})
}
function read(unfixedKey) {
if (disable) { return }
var fixedKey = fixKey(unfixedKey)
var res = null
_withStorageEl(function(storageEl) {
res = storageEl.getAttribute(fixedKey)
})
return res
}
function each(callback) {
_withStorageEl(function(storageEl) {
var attributes = storageEl.XMLDocument.documentElement.attributes
for (var i=attributes.length-1; i>=0; i--) {
var attr = attributes[i]
callback(storageEl.getAttribute(attr.name), attr.name)
}
})
}
function remove(unfixedKey) {
var fixedKey = fixKey(unfixedKey)
_withStorageEl(function(storageEl) {
storageEl.removeAttribute(fixedKey)
storageEl.save(storageName)
})
}
function clearAll() {
_withStorageEl(function(storageEl) {
var attributes = storageEl.XMLDocument.documentElement.attributes
storageEl.load(storageName)
for (var i=attributes.length-1; i>=0; i--) {
storageEl.removeAttribute(attributes[i].name)
}
storageEl.save(storageName)
})
}
// Helpers
//////////
// In IE7, keys cannot start with a digit or contain certain chars.
// See https://github.com/marcuswestin/store.js/issues/40
// See https://github.com/marcuswestin/store.js/issues/83
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function fixKey(key) {
return key.replace(/^\d/, '___$&').replace(forbiddenCharsRegex, '___')
}
function _makeIEStorageElFunction() {
if (!doc || !doc.documentElement || !doc.documentElement.addBehavior) {
return null
}
var scriptTag = 'script',
storageOwner,
storageContainer,
storageEl
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
/* global ActiveXObject */
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<'+scriptTag+'>document.w=window</'+scriptTag+'><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storageEl = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storageEl = doc.createElement('div')
storageOwner = doc.body
}
return function(storeFunction) {
var args = [].slice.call(arguments, 0)
args.unshift(storageEl)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storageEl)
storageEl.addBehavior('#default#userData')
storageEl.load(storageName)
storeFunction.apply(this, args)
storageOwner.removeChild(storageEl)
return
}
}
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
var util = __webpack_require__(0)
var Global = util.Global
module.exports = {
name: 'sessionStorage',
read: read,
write: write,
each: each,
remove: remove,
clearAll: clearAll,
}
function sessionStorage() {
return Global.sessionStorage
}
function read(key) {
return sessionStorage().getItem(key)
}
function write(key, data) {
return sessionStorage().setItem(key, data)
}
function each(fn) {
for (var i = sessionStorage().length - 1; i >= 0; i--) {
var key = sessionStorage().key(i)
fn(read(key), key)
}
}
function remove(key) {
return sessionStorage().removeItem(key)
}
function clearAll() {
return sessionStorage().clear()
}
/***/ }),
/* 13 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ })
/******/ ]); |
/**
* User Controller
*/
var User = require('../app/db/user')
//登录
exports.login = (req, res) => {
var _user = req.body.user
var ADMIN_URL = 'http://localhost:3000/admin/'
User.findOne({username: _user.username}, (err, user) => {
if (err) {
console.log(err)
}
if (!user) {
res.send({
success: false,
errAt: 'username',
reason: '用户名不存在'
})
} else {
//如果是admin的login页面,先检查权限
if (req.get('Referer') === ADMIN_URL && user.permission < 20) {
return res.status(403).send('你不是管理员')
}
//验证密码
user.authPwd(_user.password, (err, isMatch) => {
if (err) {
console.log(err)
res.send(err)
}
if (isMatch) {
req.session.user = user
res.cookie('username', user.username)
res.send({
success: true,
data: user.username
})
} else {
res.send({
success: false,
errAt: 'password',
reason: '密码错误'
})
}
})
}
})
}
//注销
exports.logout = (req, res) => {
delete req.session.user
res.status(200).end()
}
//注册
exports.signup = (req, res) => {
var _user = req.body.user
var newUser = new User(_user)
if (!_user) {
return res.send({
success: false,
reason: '错误提交'
})
} else {
if (!_user.username) {
return res.send({
success: false,
reason: '请输入用户名'
})
}
if (!_user.password) {
return res.send({
success: false,
reason: '请输入密码'
})
}
}
User.findOne({username: _user.username}, (err, user) => {
if (err) {
console.log(err)
}
//如果user不存在
if (!user) {
newUser.save((err, newUser) => {
if (err) {
console.log(err)
}
res.send({
success:true
})
})
} else {
res.send({
success: false,
reason: '用户名已存在'
})
}
})
}
exports.read = (req, res) => {
User.find({}, (err, users) => {
if (err) console.log(err)
res.send(users)
})
}
exports.RequireAdmin = (req, res, next) => {
var _user = req.session.user
User.findOne({username: _user.username}, (err, user) => {
if (err) console.log(err)
if (!user) {
res.status(403).send({
success: false,
reason: '没有找到这个管理员'
})
console.log('没有找到这个管理员')
} else if (user.permission < 20) {
res.status(403).send({
success: false,
reason: '你无权访问这个页面'
})
console.log('你无权访问这个页面')
} else {
next()
}
})
}
exports.RequireLogin = (req, res, next) => {
if (!req.session.user) {
res.status(403).send({success: false, reason: '需要登录'})
} else {
next()
}
} |
import React from 'react';
import { Link } from 'react-router-dom';
const Navigation = ({data}) => {
const navItems = Object.keys(data.pages).map(function(key, index) {
var page = data.pages[key];
var activeCssClass = page.attributes.path === data.url ||
data.url === '/' && page.id === data.start_page.id ?
'active' :
null;
return (
<li role="presentation" className={activeCssClass} key={index}>
<Link to={key.toString()}>{page.attributes.display_name}</Link>
</li>
);
});
return (
<ul className="nav navbar-nav navbar-right">
{navItems}
<li className="hidden-xs" id="navbar-search">
<a href="#" className="show" id="open-search">
<i className="fa fa-search"></i>
</a>
<a href="#" className="hidden" id="close-search">
<i className="fa fa-times"></i>
</a>
<div className="hidden" id="navbar-search-box">
<form className="form" role="form">
<input type="text" className="form-control" placeholder="Search" />
<button className="btn btn-red btn-sm" type="button"><i className="fa fa-search"></i></button>
</form>
</div>
</li>
</ul>
);
};
export default Navigation; |
'use strict';
// eslint-disable-next-line no-unused
function isExperimentEnabled(experimentName) {
if (process.env.EMBER_CLI_ENABLE_ALL_EXPERIMENTS) {
return true;
}
let experimentEnvironmentVariable = `EMBER_CLI_${experimentName}`;
if (process.env[experimentEnvironmentVariable]) {
return true;
}
return false;
}
let experiments = {
PACKAGER: isExperimentEnabled('PACKAGER'),
MODULE_UNIFICATION: isExperimentEnabled('MODULE_UNIFICATION'),
DELAYED_TRANSPILATION: isExperimentEnabled('DELAYED_TRANSPILATION'),
};
Object.freeze(experiments);
module.exports = experiments;
|
var jsTag = angular.module('jsTag');
jsTag.controller('JSTagMainCtrl', ['$attrs', '$scope', 'InputService', 'TagsInputService', 'jsTagDefaults', function($attrs, $scope, InputService, TagsInputService, jsTagDefaults) {
// Parse user options and merge with defaults
var userOptions = {};
try {
userOptions = $scope.$eval($attrs.jsTagOptions);
} catch(e) {
console.log("jsTag Error: Invalid user options, using defaults only");
}
// Copy so we don't override original values
var options = angular.copy(jsTagDefaults);
// Use user defined options
if (userOptions !== undefined) {
userOptions.texts = angular.extend(options.texts, userOptions.texts || {});
angular.extend(options, userOptions);
}
$scope.options = options;
// Export handlers to view
$scope.tagsInputService = new TagsInputService($scope.options);
$scope.inputService = new InputService($scope.options);
// Export tagsCollection separately since it's used alot
var tagsCollection = $scope.tagsInputService.tagsCollection;
$scope.tagsCollection = tagsCollection;
// TODO: Should be inside inside tagsCollection.js
// On every change to editedTags keep isThereAnEditedTag posted
$scope.$watch('tagsCollection._editedTag', function(newValue, oldValue) {
$scope.isThereAnEditedTag = newValue !== null;
});
// TODO: Should be inside inside tagsCollection.js
// On every change to activeTags keep isThereAnActiveTag posted
$scope.$watchCollection('tagsCollection._activeTags', function(newValue, oldValue) {
$scope.isThereAnActiveTag = newValue.length > 0;
});
}]); |
var util = require('util');
var noble = require('noble');
var stream = require("stream");
var net = require("net");
////////////////////////////////////////////////////////////
function BleRawSerial(peripheral, opts, options) {
stream.Duplex.call(this, options);
this.peripheral = peripheral;
this.uuid_svc = opts.uuid_svc;
this.uuid_tx = opts.uuid_tx;
this.uuid_rx = opts.uuid_rx;
}
util.inherits(BleRawSerial, stream.Duplex);
BleRawSerial.prototype.connect = function (callback) {
var self = this;
self.peripheral.discoverServices([self.uuid_svc], function(err, services) {
if (err) throw err;
services.forEach(function(service) {
service.discoverCharacteristics([self.uuid_tx, self.uuid_rx], function(err, characteristics) {
if (err) throw err;
//console.log("CHARS:", characteristics);
self.char_tx = characteristics[0];
self.char_rx = characteristics[1];
self.char_rx.notify(true, function(err) {
if (err) throw err;
});
self.char_rx.on('read', function(data, isNotification) {
//console.log('>', data);
if (!self.push(data)) {
//self._source.readStop();
}
});
callback();
});
});
});
};
BleRawSerial.prototype._read = function (size) {
//this._source.readStart();
};
BleRawSerial.prototype._write = function (data, enc, done) {
var i = 0;
for (; i+20<data.length; i+=20) {
var ch = data.slice(i, i+20);
//console.log('<', ch);
this.char_tx.write(ch, true);
}
var ch = data.slice(i, i+20);
//console.log('<', ch);
this.char_tx.write(ch, true, done);
};
////////////////////////////////////////////////////////////
var crc = require('crc');
var commands = {
MSG_ID_SERIAL_DATA : new Buffer([0x00, 0x00]),
MSG_ID_BT_SET_ADV : new Buffer([0x05, 0x00]),
MSG_ID_BT_SET_CONN : new Buffer([0x05, 0x02]),
MSG_ID_BT_SET_LOCAL_NAME : new Buffer([0x05, 0x04]),
MSG_ID_BT_SET_PIN : new Buffer([0x05, 0x06]),
MSG_ID_BT_SET_TX_PWR : new Buffer([0x05, 0x08]),
MSG_ID_BT_GET_CONFIG : new Buffer([0x05, 0x10]),
MSG_ID_BT_ADV_ONOFF : new Buffer([0x05, 0x12]),
MSG_ID_BT_SET_SCRATCH : new Buffer([0x05, 0x14]),
MSG_ID_BT_GET_SCRATCH : new Buffer([0x05, 0x15]),
MSG_ID_BT_RESTART : new Buffer([0x05, 0x20]),
MSG_ID_GATING : new Buffer([0x05, 0x50]),
MSG_ID_BL_CMD : new Buffer([0x10, 0x00]),
MSG_ID_BL_FW_BLOCK : new Buffer([0x10, 0x01]),
MSG_ID_BL_STATUS : new Buffer([0x10, 0x02]),
MSG_ID_CC_LED_WRITE : new Buffer([0x20, 0x00]),
MSG_ID_CC_LED_WRITE_ALL : new Buffer([0x20, 0x01]),
MSG_ID_CC_LED_READ_ALL : new Buffer([0x20, 0x02]),
MSG_ID_CC_ACCEL_READ : new Buffer([0x20, 0x10]),
MSG_ID_CC_TEMP_READ : new Buffer([0x20, 0x11]),
MSG_ID_AR_SET_POWER : new Buffer([0x30, 0x00]),
MSG_ID_AR_GET_CONFIG : new Buffer([0x30, 0x06]),
MSG_ID_DB_LOOPBACK : new Buffer([0xFE, 0x00]),
MSG_ID_DB_COUNTER : new Buffer([0xFE, 0x01]),
};
function BleBeanSerial(peripheral, opts, options) {
stream.Duplex.call(this, options);
this.peripheral = peripheral;
this.uuid_svc = opts.uuid_svc;
this.uuid_rxtx = opts.uuid_rxtx;
this.count = 0;
this.gst = new Buffer(0);
}
util.inherits(BleBeanSerial, stream.Duplex);
BleBeanSerial.prototype._onRead = function(gt){
//see https://github.com/PunchThrough/bean-documentation/blob/master/serial_message_protocol.md
//Received a single GT packet
var start = (gt[0] & 0x80); //Set to 1 for the first packet of each App Message, 0 for every other packet
var messageCount = (gt[0] & 0x60); //Increments and rolls over on each new GT Message (0, 1, 2, 3, 0, ...)
var packetCount = (gt[0] & 0x1F); //Represents the number of packets remaining in the GST message
//first packet, reset data buffer
if (start) {
this.gst = new Buffer(0);
}
//TODO probably only if messageCount is in order
this.gst = Buffer.concat( [this.gst, gt.slice(1)] );
//last packet, process and emit
if(packetCount === 0){
var length = this.gst[0]; //size of thse cmd and payload
//crc only the size, cmd and payload
var crcString = crc.crc16ccitt(this.gst.slice(0,this.gst.length-2));
//messy buffer equality because we have to swap bytes and can't use string equality because tostring drops leading zeros
//console.log('CRC: ' , typeof crcString);
var crc16 = new Buffer(2);
crc16.writeUInt16BE(crcString, 0);
var valid = (crc16[0]===this.gst[this.gst.length-1] && crc16[1]===this.gst[this.gst.length-2]);
var command = ( (this.gst[2] << 8) + this.gst[3] ) & ~(0x80) ;
//this.emit('raw', this.gst.slice(2,this.gst.length-2), length, valid, command);
if(valid){
//ideally some better way to do lookup
if(command === (commands.MSG_ID_CC_ACCEL_READ[0] << 8 ) + commands.MSG_ID_CC_ACCEL_READ[1])
{
var x = (((this.gst[5] << 24) >> 16) | this.gst[4]) * 0.00391;
var y = (((this.gst[7] << 24) >> 16) | this.gst[6]) * 0.00391;
var z = (((this.gst[9] << 24) >> 16) | this.gst[8]) * 0.00391;
this.emit('accell', x.toFixed(5), y.toFixed(5), z.toFixed(5), valid);
} else if(this.gst[2] === commands.MSG_ID_SERIAL_DATA[0] && this.gst[3] === commands.MSG_ID_SERIAL_DATA[1]){
var data = this.gst.slice(4,this.gst.length-2);
if (!this.push(data)) {
//this._source.readStop();
}
} else if(command === (commands.MSG_ID_CC_TEMP_READ[0] << 8 ) + commands.MSG_ID_CC_TEMP_READ[1]){
this.emit('temp', this.gst[4], valid);
}
else{
this.emit('invalid', this.gst.slice(2,this.gst.length-2), length, valid, command);
}
}
}
};
BleBeanSerial.prototype.sendCmd = function(cmdBuffer,payloadBuffer,done) {
var sizeBuffer = new Buffer(2);
sizeBuffer.writeUInt8(cmdBuffer.length + payloadBuffer.length,0);
sizeBuffer.writeUInt8(0,1);
//GST contains sizeBuffer, cmdBuffer, and payloadBuffer
var gst = Buffer.concat([sizeBuffer,cmdBuffer,payloadBuffer]);
var crcString = crc.crc16ccitt(gst);
var crc16Buffer = new Buffer(2);
crc16Buffer.writeUInt16LE(crcString, 0);
gst = Buffer.concat([sizeBuffer,cmdBuffer,payloadBuffer,crc16Buffer]);
var gt_qty = Math.floor(gst.length/19);
if (gst.length % 19 != 0) {
gt_qty += 1;
}
var optimal_packet_size = 19;
for (var ch=0; ch<gt_qty; ch++) {
var data = gst.slice(ch*optimal_packet_size, (ch+1)*optimal_packet_size);
var gt = (this.count * 0x20); // << 5
if (ch == 0) {
gt |= 0x80;
}
gt |= gt_qty - ch - 1;
gt = Buffer.concat([new Buffer([ gt ]), data]);
//console.log('<', gt);
if (ch == gt_qty-1) {
this.char_rxtx.write(gt, true, done);
} else {
this.char_rxtx.write(gt, true);
}
}
this.count = (this.count + 1) % 4;
};
BleBeanSerial.prototype.connect = function (callback) {
var self = this;
self.peripheral.discoverServices([self.uuid_svc], function(err, services) {
if (err) throw err;
services.forEach(function(service) {
service.discoverCharacteristics([self.uuid_rxtx], function(err, characteristics) {
if (err) throw err;
//console.log("CHARS:", characteristics);
self.char_rxtx = characteristics[0];
self.char_rxtx.notify(true, function(err) {
if (err) throw err;
});
self.char_rxtx.on('read', function(data, isNotification) {
//console.log('>', data);
self._onRead(data);
});
self.unGate();
callback();
});
});
});
};
BleBeanSerial.prototype._read = function (size) {
//this._source.readStart();
};
BleBeanSerial.prototype._write = function (data, enc, done) {
var i = 0;
for (; i+64<data.length; i+=64) {
this.sendCmd(commands.MSG_ID_SERIAL_DATA, data.slice(i, i+64));
}
this.sendCmd(commands.MSG_ID_SERIAL_DATA, data.slice(i, i+64), done);
};
BleBeanSerial.prototype.unGate = function(done) {
this.sendCmd(commands.MSG_ID_GATING, new Buffer({}), done);
}
BleBeanSerial.prototype.setColor = function(color,done) {
this.sendCmd(commands.MSG_ID_CC_LED_WRITE_ALL, color, done);
};
BleBeanSerial.prototype.requestAccell = function(done) {
this.sendCmd(commands.MSG_ID_CC_ACCEL_READ, new Buffer([]), done);
};
BleBeanSerial.prototype.requestTemp = function(done) {
this.sendCmd(commands.MSG_ID_CC_TEMP_READ, new Buffer([]), done);
};
////////////////////////////////////////////////////////////
var dev_service_uuids = {
'713d0000503e4c75ba943148f18d941e': {
name : 'mbed NRF51822',
create: BleRawSerial,
options: {
uuid_svc:'713d0000503e4c75ba943148f18d941e',
uuid_tx: '713d0003503e4c75ba943148f18d941e',
uuid_rx: '713d0002503e4c75ba943148f18d941e'
}
},
'6e400001b5a3f393e0a9e50e24dcca9e': {
name : 'Nordic NRF8001 Serial',
create: BleRawSerial,
options: {
uuid_svc:'6e400001b5a3f393e0a9e50e24dcca9e',
uuid_tx: '6e400002b5a3f393e0a9e50e24dcca9e',
uuid_rx: '6e400003b5a3f393e0a9e50e24dcca9e'
}
},
'a495ff10c5b14b44b5121370f02d74de': {
name : 'LightBlue Bean',
create: BleBeanSerial,
options: {
uuid_svc: 'a495ff10c5b14b44b5121370f02d74de',
uuid_rxtx: 'a495ff11c5b14b44b5121370f02d74de'
}
}
};
//Buffer.prototype.toByteArray = function() { return Array.prototype.slice.call(this, 0); };
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
noble.startScanning(); // Object.keys(dev_service_uuids)
console.log('Scanning for BLE devices...');
} else {
noble.stopScanning();
console.log('State changed to ' + '. Scanning stopped.');
}
});
var peripherals = {};
// TODO: Multiple device connect?
noble.on('discover', function(peripheral) {
var name = peripheral.advertisement.localName;
var uuid = peripheral.uuid;
var addr = peripheral.address;
var rssi = peripheral.rssi;
console.log(util.format('Discovered %s [addr: %s, uuid: %s, rssi: %d]', name, addr, uuid, rssi));
peripheral.advertisement.serviceUuids.forEach(function(service) {
var svc = dev_service_uuids[service];
if (svc !== undefined) {
console.log("Device type:", svc.name);
peripheral.connect(function(err) {
if (err) throw err;
peripherals[uuid] = peripheral;
/*peripheral.on('rssiUpdate', function(rssi) {
console.log(name, 'rssi:', rssi);
});
setInterval(function(){
peripheral.updateRssi();
}, 2000);*/
var ble_ser = new svc.create(peripheral, svc.options);
ble_ser.connect(function(err) {
if (err) throw err;
console.log('BLE connected');
});
var tcp_conn = net.connect(8442, 'cloud.blynk.cc', function(err) {
if (err) throw err;
console.log('TCP connected');
});
peripheral.on('disconnect', function() {
console.log('BLE disconnect', uuid);
delete peripherals[uuid];
tcp_conn.end();
setTimeout(function() {
noble.startScanning();
}, 100);
});
ble_ser.on('error', function(){ console.log('BLE error'); });
tcp_conn.on('error', function(){ console.log('TCP error');});
ble_ser.on('close', function(){ console.log('BLE close'); });
tcp_conn.on('close', function(){ console.log('TCP close');});
ble_ser.pipe(tcp_conn).pipe(ble_ser);
//ble_ser.pipe(process.stdout);
});
}
});
});
// catches ctrl+c event
process.on('SIGINT', function() {
Object.keys(peripherals).forEach(function(uuid) {
console.log('Disconnecting from ' + uuid + '...');
peripherals[uuid].disconnect( function(){
console.log('disconnected');
});
});
//end process after 2 more seconds
setTimeout(function(){
process.exit();
}, 2000);
});
process.stdin.resume();//so the program will not close instantly
|
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
function reverseString(s) {
try{
console.log(s.split("").reverse().join(""));
}catch(e){
console.log(e.message);
console.log(s);
}
}
function main() {
const s = eval(readLine());
reverseString(s);
}
|
#!/usr/bin/env node
var relToAbs = require("rel-to-abs");
function convertRelToAbs(content) {
return relToAbs.convert(content, "https://azu.github.io/promises-book")
}
var data = "";
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
data += chunk
});
process.stdin.on('end', function () {
process.stdout.write(convertRelToAbs(data))
});
|
/**
* @fileoverview This service keeps and share the state of the theme.
*/
goog.provide('app.Theme');
goog.require('app.Themes');
goog.require('ngeo.Location');
goog.require('goog.asserts');
/**
* @constructor
* @param {angular.$window} $window Global Scope.
* @param {ngeo.Location} ngeoLocation ngeo Location service.
* @param {app.Themes} appThemes The themes services.
* @ngInject
*/
app.Theme = function($window, ngeoLocation, appThemes) {
/**
* @const
* @private
* @type {Object}
*/
this.piwikSiteIdLookup_ = {
'transport': 24,
'main': 24
};
/**
* @type {angular.$window}
* @private
*/
this.window_ = $window;
/**
* @type {app.Themes}
* @private
*/
this.appThemes_ = appThemes;
/**
* @type {string}
* @private
*/
this.currentTheme_ = app.Theme.DEFAULT_THEME_;
/**
* @type {ngeo.Location}
* @private
*/
this.ngeoLocation_ = ngeoLocation;
};
/**
* @param {string} themeId The id of the theme.
*/
app.Theme.prototype.setCurrentTheme = function(themeId) {
this.currentTheme_ = themeId;
var piwikSiteId = this.piwikSiteIdLookup_[this.currentTheme_];
if (!goog.isDefAndNotNull(piwikSiteId)) {
piwikSiteId = this.piwikSiteIdLookup_[app.Theme.DEFAULT_THEME_];
}
var piwik = /** @type {Piwik} */ (this.window_['_paq']);
piwik.push(['setSiteId', piwikSiteId]);
piwik.push(['setDocumentTitle', themeId]);
piwik.push(['trackPageView']);
this.setLocationPath_(this.currentTheme_);
};
/**
* @return {string} themeId The id of the theme.
*/
app.Theme.prototype.getCurrentTheme = function() {
return this.currentTheme_;
};
/**
* @return {string} themeId The id of the theme.
*/
app.Theme.prototype.getDefaultTheme = function() {
return app.Theme.DEFAULT_THEME_;
};
/**
* @param {string} themeId The theme id to set in the path of the URL.
* @private
*/
app.Theme.prototype.setLocationPath_ = function(themeId) {
var pathElements = this.ngeoLocation_.getPath().split('/');
goog.asserts.assert(pathElements.length > 1);
if (pathElements[pathElements.length - 1] === '') {
// case where the path is just "/"
pathElements.splice(pathElements.length - 1);
}
if (this.themeInUrl(pathElements)) {
pathElements[pathElements.length - 1] = themeId;
} else {
pathElements.push('theme', themeId);
}
this.ngeoLocation_.setPath(pathElements.join('/'));
};
/**
* Return true if there is a theme specified in the URL path.
* @param {Array.<string>} pathElements Array of path elements.
* @return {boolean} theme in path.
*/
app.Theme.prototype.themeInUrl = function(pathElements) {
var indexOfTheme = pathElements.indexOf('theme');
return indexOfTheme >= 0 &&
pathElements.indexOf('theme') == pathElements.length - 2;
};
/**
* @const
* @private
*/
app.Theme.DEFAULT_THEME_ = 'transport';
app.module.service('appTheme', app.Theme);
|
var $ = require('jquery');
var WindowStorage = require('../utils/window-storage');
var RelatedPopups = function() {
this.windowStorage = new WindowStorage('relatedWindows');
};
RelatedPopups.prototype = {
updateLinks: function($select) {
$select.find('~ .change-related, ~ .delete-related, ~ .add-another').each(function() {
var $link = $(this);
var hrefTemplate = $link.data('href-template');
if (hrefTemplate == undefined) {
return;
}
var value = $select.val();
if (value) {
$link.attr('href', hrefTemplate.replace('__fk__', value))
} else {
$link.removeAttr('href');
}
});
},
initLinksForRow: function($row) {
if ($row.data('related-popups-links-initialized')) {
return;
}
var self = this;
$row.find('select').each(function() {
var $select = $(this);
self.updateLinks($select);
$select.find('~ .add-related, ~ .change-related, ~ .delete-related, ~ .add-another').each(function() {
var $link = $(this);
$link.on('click', function(e) {
e.preventDefault();
var href = $link.attr('href');
if (href != undefined) {
if (href.indexOf('_popup') == -1) {
href += (href.indexOf('?') == -1) ? '?_popup=1' : '&_popup=1';
}
self.showPopup($select, href);
}
});
});
}).on('change', function() {
self.updateLinks($(this));
});
$row.find('input').each(function() {
var $input = $(this);
$input.find('~ .related-lookup').each(function() {
var $link = $(this);
$link.on('click', function(e) {
e.preventDefault();
var href = $link.attr('href');
href += (href.indexOf('?') == -1) ? '?_popup=1' : '&_popup=1';
self.showPopup($input, href);
});
});
});
$row.data('related-popups-links-initialized', true);
},
initLinks: function() {
var self = this;
$('.form-row').each(function() {
self.initLinksForRow($(this));
});
$('.inline-group').on('inline-group-row:added', function(e, $inlineItem) {
self.initLinksForRow($inlineItem.find('.form-row'));
});
},
initPopupBackButton: function() {
var self = this;
$('.related-popup-back').on('click', function(e) {
e.preventDefault();
self.closePopup();
});
},
showPopup: function($input, href) {
var $document = $(window.top.document);
var $container = $document.find('.related-popup-container');
var $loading = $container.find('.loading-indicator');
var $body = $document.find('body');
var $popup = $('<div>')
.addClass('related-popup')
.data('input', $input);
var $iframe = $('<iframe>')
.attr('src', href)
.on('load', function() {
$popup.add($document.find('.related-popup-back')).fadeIn(200, 'swing', function() {
$loading.hide();
});
});
$popup.append($iframe);
$loading.show();
$document.find('.related-popup').add($document.find('.related-popup-back')).fadeOut(200, 'swing');
$container.fadeIn(200, 'swing', function() {
$container.append($popup);
});
$body.addClass('non-scrollable');
},
closePopup: function(response) {
var previousWindow = this.windowStorage.previous();
var self = this;
(function($) {
var $document = $(window.top.document);
var $popups = $document.find('.related-popup');
var $container = $document.find('.related-popup-container');
var $popup = $popups.last();
if (response != undefined) {
self.processPopupResponse($popup, response);
}
self.windowStorage.pop();
if ($popups.length == 1) {
$container.fadeOut(200, 'swing', function() {
$document.find('.related-popup-back').hide();
$document.find('body').removeClass('non-scrollable');
$popup.remove();
});
} else if ($popups.length > 1) {
$popup.remove();
$popups.eq($popups.length - 2).show();
}
})(previousWindow ? previousWindow.jet.jQuery : $);
},
findPopupResponse: function() {
var self = this;
$('#django-admin-popup-response-constants').each(function() {
var $constants = $(this);
var response = $constants.data('popup-response');
self.closePopup(response);
});
},
processPopupResponse: function($popup, response) {
var $input = $popup.data('input');
switch (response.action) {
case 'change':
$input.find('option').each(function() {
var $option = $(this);
if ($option.val() == response.value) {
$option.html(response.obj).val(response.new_value);
}
});
$input.trigger('change').trigger('select:init');
break;
case 'delete':
$input.find('option').each(function() {
var $option = $(this);
if ($option.val() == response.value) {
$option.remove();
}
});
$input.trigger('change').trigger('select:init');
break;
default:
if ($input.is('select')) {
var $option = $('<option>')
.val(response.value)
.html(response.obj);
$input.append($option);
$option.attr('selected', true);
$input
.trigger('change')
.trigger('select:init');
} else if ($input.is('input.vManyToManyRawIdAdminField') && $input.val()) {
$input.val($input.val() + ',' + response.value);
} else if ($input.is('input')) {
$input.val(response.value);
}
break;
}
},
overrideRelatedGlobals: function() {
var self = this;
window.showRelatedObjectLookupPopup
= window.showAddAnotherPopup
= window.showRelatedObjectPopup
= function() { };
window.opener = this.windowStorage.previous();
window.dismissRelatedLookupPopup = function(win, chosenId) {
self.closePopup({
action: 'lookup',
value: chosenId
});
};
},
initDeleteRelatedCancellation: function() {
var self = this;
$('.popup.delete-confirmation .cancel-link').on('click', function(e) {
e.preventDefault();
self.closePopup();
}).removeAttr('onclick');
},
initLookupLinks: function() {
var self = this;
$("a[data-popup-opener]").click(function(e) {
e.preventDefault();
self.closePopup({
action: 'lookup',
value: $(this).data("popup-opener")
});
});
},
run: function() {
this.windowStorage.push(window);
try {
this.initLinks();
this.initPopupBackButton();
this.findPopupResponse();
this.overrideRelatedGlobals();
this.initDeleteRelatedCancellation();
this.initLookupLinks();
} catch (e) {
console.error(e, e.stack);
}
}
};
$(document).ready(function() {
new RelatedPopups().run();
});
|
ShortcodeMeta={
attributes:[
{
label:"Number of posts",
id:"posts_number",
help:"Enter number."
}
],
defaultContent:"",
shortcode:"blog_latest"
};
|
/**
* @class Base class for a game body
*/
export default class Body {
/**
* Class constructor
*
* @param {Game} game game instance
* @param {Object} size the size of the body
* @param {Object} position initial position of the body
*/
constructor(game, size, initialPosition) {
this.game = game;
this.size = size;
this.position = initialPosition;
this.speed = 0;
}
/**
* Loads necessery assets for the body
*/
load() {
}
/**
* Executed when a collision on this body is reported by the game
*/
collision() {
this.onDestroyed();
this.game.removeBody(this);
}
/**
* Updates the body properties on each screen update of the game
*/
update() {
}
/**
* draws the body on the game canvas
*/
draw() {
this.game.context.fillRect(this.position.x, this.position.y, this.size.width, this.size.height);
}
/**
* gets executed when body is destroyed by the game
*/
onDestroyed() {
}
} |
(function(jigLib){
var PlaneData=function(pos, nor){
this.position = pos.clone();
this.normal = nor.clone();
this.distance = this.position.dotProduct(this._normal);
}
PlaneData.prototype.pointPlaneDistance=function(pt){
return normal.dotProduct(pt) - distance;
}
jigLib.PlaneData=PlaneData;
})(jigLib)
|
var LolitaFramework;
(function (LolitaFramework) {
var Repeater = (function () {
function Repeater(main_selector) {
var _this = this;
this.$el = null;
this.$list = null;
this.$add_button = null;
this.$add_prev = null;
this.$remove_button = null;
this.template = null;
this.template_html = null;
this.$el = jQuery(main_selector);
this.template = atob(this.$el.find('.underscore_template').html());
this.$list = this.$el.find('.lolita-repeater-sortable');
this.$add_button = this.$el.find('.lolita-repeater-main-add');
this.$add_prev = this.$el.find('.lolita-repeater-add');
this.$remove_button = this.$el.find('.lolita-repeater-remove');
this.$add_button.one('click', function (e) { return _this.addAfter(e); });
this.$add_prev.one('click', function (e) { return _this.addPrev(e); });
this.$remove_button.one('click', function (e) { return _this.remove(e); });
jQuery(document).on('lolita-repeater-row-added', function () { return _this.recountOrder(); });
jQuery(document).on('lolita-repeater-row-removed', function () { return _this.recountOrder(); });
this.sort();
}
Repeater.prototype.sort = function () {
var me = this;
this.$list.sortable({
helper: function (e, ui) {
ui.children().each(function () {
jQuery(this).width(jQuery(this).width());
});
return ui;
},
forcePlaceholderSize: true,
placeholder: 'lolita-ui-state-highlight',
handle: '.lolita-repeater-order',
update: function () {
me.recountOrder();
}
});
};
Repeater.prototype.remove = function (e) {
if (this.$list.find('.lolita-repeater-row').length > 1) {
jQuery(e.currentTarget).closest('.lolita-repeater-row').remove();
jQuery(document).trigger('lolita-repeater-row-removed');
}
};
Repeater.prototype.recountOrder = function () {
var me = this;
this.$list.find('.lolita-repeater-row').each(function (index) {
var current_index = index + 1;
jQuery(this).find('.lolita-repeater-order span').text(current_index);
jQuery(this).find('input, textarea, select').each(function () {
jQuery(this).attr('name', me.reName(me.$el.data('name'), jQuery(this).attr('name'), current_index));
jQuery(this).attr('id', me.reID(me.$el.attr('id'), jQuery(this).attr('id'), current_index));
});
jQuery(this).find('[data-control]').each(function () {
jQuery(this).get(0).dataset['name'] = me.reName(me.$el.data('name'), jQuery(this).get(0).dataset['name'], current_index);
jQuery(this).attr('id', me.reID(me.$el.attr('id'), jQuery(this).attr('id'), current_index));
});
});
};
Repeater.prototype.reName = function (repeater_name, el_name, index) {
var result_name;
el_name = el_name.replace(repeater_name, '');
el_name = el_name.replace(/^\[[0-9]*\]/, '[' + index + ']');
result_name = repeater_name + el_name;
return repeater_name + el_name;
};
Repeater.prototype.reID = function (repeater_id, el_id, index) {
if (el_id === undefined) {
return undefined;
}
el_id = el_id.replace(repeater_id, '');
el_id = el_id.replace(/^_[0-9]*_/, '_' + index + '_');
return repeater_id + el_id;
};
Repeater.prototype.addPrev = function (e) {
e.preventDefault();
var new_row = this.getNewRow();
jQuery(e.srcElement).closest('.lolita-repeater-row').before(new_row);
jQuery(document).trigger('lolita-repeater-row-added');
};
Repeater.prototype.addAfter = function (e) {
e.preventDefault();
var new_row = this.getNewRow();
this.$list.append(new_row);
jQuery(document).trigger('lolita-repeater-row-added');
};
Repeater.prototype.getNextIndex = function () {
return this.$list.find('.lolita-repeater-row').length + 1;
};
Repeater.prototype.getNewRow = function () {
var template, next_index, $widget, parsed;
$widget = this.$el.parents('.widget');
template = this.template;
next_index = this.$list.find('.lolita-repeater-row').length + 1;
template = template.replace(/__row_index__/g, next_index);
if ($widget.length) {
parsed = this.parseWidgetId($widget.attr('id'));
template = template.replace(/__i__/g, parsed.number);
}
return template;
};
Repeater.prototype.parseWidgetId = function (widgetId) {
var matches, parsed;
parsed = {
number: null,
id_base: null
};
matches = widgetId.match(/^(.+)-(\d+)$/);
if (matches) {
parsed.id_base = matches[1];
parsed.number = parseInt(matches[2], 10);
}
else {
parsed.id_base = widgetId;
}
return parsed;
};
return Repeater;
}());
LolitaFramework.Repeater = Repeater;
})(LolitaFramework || (LolitaFramework = {}));
var LolitaFramework;
(function (LolitaFramework) {
var Repeaters = (function () {
function Repeaters() {
var _this = this;
this.repeater_selector = '.lolita-repeater-container';
this.collection = [];
this.update();
jQuery(document).on('widget-updated', function () { return _this.widgetUpdate(); });
jQuery(document).on('widget-added', function () { return _this.widgetUpdate(); });
jQuery(document).on('lolita-repeater-row-added', function () { return _this.widgetUpdate(); });
}
Repeaters.prototype.widgetUpdate = function () {
this.update();
};
Repeaters.prototype.update = function () {
var me = this;
jQuery(this.repeater_selector).each(function () {
me.collection[jQuery(this).attr('id')] = new LolitaFramework.Repeater('#' + jQuery(this).attr('id'));
});
};
return Repeaters;
}());
LolitaFramework.Repeaters = Repeaters;
window.LolitaFramework.repeaters = new Repeaters();
})(LolitaFramework || (LolitaFramework = {}));
//# sourceMappingURL=repeater.js.map |
import React, {Component, PropTypes} from 'react';
import update from 'immutability-helper';
import {TouchableWithoutFeedback,View,Dimensions,
StyleSheet, Image, Text, TouchableOpacity, ScrollView, Platform, NativeModules} from 'react-native';
import Overlay from 'react-native-overlay';
import FloatLabelTextInput from 'react-native-floating-label-text-input';
import {Button, Icon, Item, Input, Label} from 'native-base';
import AwesomeAlert from 'react-native-awesome-alerts';
import DismissKeyboard from 'react-native-dismiss-keyboard';
import SettingMenuContainer from '../settings/SettingMenuContainer';
import AppStrings from '../../localization/appStrings';
import {cleanNumericString, reorderArray} from '../../utils/helpers';
import {SOP_WHITE} from './../../styles/commonStyles';
import DeckSwiperComponent from './../../components/DeckSwiperComponent';
import HideWithKeyboard from 'react-native-hide-with-keyboard';
const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;
const DIAGRAM_2 = require('../../images/diagram-2.png');
const DIAGRAM_6 = require('../../images/diagram-6.png');
class TravelSideView extends Component {
static propTypes = {
set: PropTypes.number,
travel: PropTypes.number,
run: PropTypes.number,
loading: PropTypes.bool.isRequired,
isVisible: PropTypes.bool.isRequired,
isCalcEnabled: PropTypes.bool.isRequired,
findCardIndex: PropTypes.func.isRequired,
travelSideStateActions: PropTypes.shape({
increment: PropTypes.func.isRequired,
calculate: PropTypes.func.isRequired,
reset: PropTypes.func.isRequired,
toggleVisibility: PropTypes.func.isRequired
}).isRequired,
navigationStateActions: PropTypes.shape({
pushRoute: PropTypes.func.isRequired
}).isRequired
};
constructor(props) {
super(props);
this.state = {
setflag: false,
travelflag: false,
runflag: false,
showAlert: false,
mainDiagram: DIAGRAM_2,
cards: [],
defaultCards: []
};
}
componentWillMount() {
const that = this;
// TODO: Refactor this locale code to a HOC component wrapper
var deviceLocale = AppStrings.getInterfaceLanguage();
let langRegionLocale = 'en_US';
if (Platform.OS === 'android') {
langRegionLocale = NativeModules.I18nManager.localeIdentifier || '';
}
let languageLocale = langRegionLocale.substring(0, 2);
deviceLocale = languageLocale;
AppStrings.setLanguage(deviceLocale);
var displayedLocale = AppStrings.getLanguage();
// End Locale code
const initialCards = [
{
title: AppStrings.diagramTwoTitle,
details: AppStrings.diagramTwoDetails,
image: require('../../images/diagram-2.png')
},
{
title: AppStrings.diagramSixTitle,
details: AppStrings.formatString(AppStrings.diagramSixDetails, 'X'),
image: require('../../images/diagram-6.png')
}
];
const defaultCards = [...initialCards];
that.setState({cards: initialCards, defaultCards});
}
componentWillReceiveProps(nextProps) {
if (nextProps.travel !== this.state.travelValue && nextProps.travel) {
this.onChangeTravelValue();
}
if (nextProps.set !== this.state.setValue && nextProps.set) {
this.onChangeSetValue(nextProps.set.toString());
}
if (nextProps.run !== this.state.runValue && nextProps.run) {
this.onChangeRunValue(nextProps.run.toString());
}
}
increment = () => {
this.props.travelSideStateActions.increment();
};
toggleVisibility = () => {
DismissKeyboard();
this.props.travelSideStateActions.toggleVisibility();
};
findCardIndex = (currCardTitle) => {
let cardIndex;
cardIndex = this.state.cards.findIndex(card => card.title === currCardTitle);
cardIndex = cardIndex !== -1 ? cardIndex : 0;
return cardIndex
};
/**
* calculate if two numbers provided
*/
calculate = () => {
DismissKeyboard();
if (this.state.setValue && (this.state.runValue !== 0 && this.state.runValue))
{
if (!parseInt(this.state.setValue).isNaN && !parseInt(this.state.travelValue).isNaN && !parseInt(this.state.runValue).isNaN) {
const cardIndex = this.findCardIndex(AppStrings.diagramSixTitle);
let reOrderedCards = this.state.cards;
if (cardIndex > 0) {reOrderedCards = reorderArray(this.state.cards, 0, 1);}
this.setState({cards: reOrderedCards, setflag: true, travelflag: true, runflag: true,showAlert: false, mainDiagram: DIAGRAM_6});
this.props.travelSideStateActions.calculate(
parseFloat(cleanNumericString(this.state.setValue)),
parseFloat(this.state.travelValue),
parseFloat(cleanNumericString(this.state.runValue)));
}
} else {
this.setState({showAlert: true, travelflag: false, travelValue: ''});
}
};
reset = () => {
DismissKeyboard();
this.props.travelSideStateActions.reset();
this.setState({cards: this.state.defaultCards, setValue: '', travelValue: '', runValue: '', setflag: false, travelflag: false, runflag: false, mainDiagram: DIAGRAM_2});
};
hideAlert = () => {
this.setState({
showAlert: false
});
};
onChangeSetValue = (text) => {
this.setState({setflag: false, setValue: text});
}
onChangeTravelValue = () => {
const cardIndex = this.findCardIndex(AppStrings.diagramSixTitle);
this.setState({
cards: update(this.state.cards, {[cardIndex]: {details: {$set: AppStrings.formatString(AppStrings.diagramSixDetails, this.state.travelflag && this.props.travel
? this.props.travel.toString() : 'X')}}})
});
}
onChangeRunValue = (text) => {
this.setState({runflag: false, runValue: text});
}
render() {
return (
<TouchableWithoutFeedback onPress={ () => { DismissKeyboard(); } }>
<ScrollView style={styles.viewContainer}
ref='scrollView'
onContentSizeChange={(width,height) => this.refs.scrollView.scrollTo({y: !this.props.isVisible ? height : null})}>
{!this.props.isVisible &&
<View style={styles.imageContainer}>
<TouchableOpacity style={styles.imageOpacity} onPress={this.toggleVisibility}>
<Image
style={styles.image}
source={this.state.mainDiagram}/>
</TouchableOpacity>
<SettingMenuContainer />
</View>}
{!this.props.isVisible &&
<View style={styles.rowContainer}>
<View style={styles.rowSpacer}>
<FloatLabelTextInput
placeholder={AppStrings.runTextString}
keyboardType= 'numeric'
value={this.state.runflag && this.props.run ? this.props.run.toString() : this.state.runValue}
style={styles.textInput}
onChangeTextValue={this.onChangeRunValue}
/>
</View>
<View style={styles.rowSpacer}>
<FloatLabelTextInput
placeholder={AppStrings.setTextString}
keyboardType= 'numeric'
value={this.state.setflag && this.props.set ? this.props.set.toString() : this.state.setValue}
style={styles.textInput}
onChangeTextValue={this.onChangeSetValue}
/>
</View>
{ this.state.travelflag &&
<Label style={StyleSheet.flatten(styles.resultLabel)}>{AppStrings.travelPlaceholder}</Label>}
<Item >
<Icon active name='information-circle' />
<Input disabled
disabled style={StyleSheet.flatten(styles.resultInput)}
placeholder={AppStrings.travelPlaceholder}
value={this.state.travelflag && this.props.travel
? this.props.travel.toString() : this.state.travelValue}
/>
</Item>
</View>
}
{this.props.isVisible && (
<View
style={{
height: ScreenHeight,
width: ScreenWidth
}}
>
<Overlay isVisible={this.props.isVisible}>
<DeckSwiperComponent
onPress={this.toggleVisibility}
cards={this.state.cards}
manualSwipe={false} />
</Overlay>
</View>
)}
<AwesomeAlert
show={this.state.showAlert}
title={AppStrings.viewInputErrTitle}
message={AppStrings.viewThreeInputErrText}
messageStyle={styles.awesomeAlertText}
closeOnTouchOutside={true}
closeOnHardwareBackPress={true}
showCancelButton={false}
showConfirmButton={true}
confirmButtonStyle={styles.awesomeAlertButton}
confirmText={AppStrings.viewInputErrConfirmText}
confirmButtonColor='#DD6B55'
onConfirmPressed={() => {
this.hideAlert();
}}
/>
{ !this.props.isVisible &&
<HideWithKeyboard style={styles.buttonView}>
<Button large iconLeft primary
accessible={true}
accessibilityLabel={AppStrings.calculateBtnText}
onPress={this.calculate} >
<Icon name='calculator' style={StyleSheet.flatten(styles.iconColor)} />
<Text style={styles.buttonTextStlye}>
{AppStrings.calculateBtnText}
</Text>
</Button>
<Button medium warning
accessible={true}
accessibilityLabel={AppStrings.resetBtnText}
onPress={this.reset}
style={StyleSheet.flatten(styles.resetBtn)}>
<Icon name='trash' style={StyleSheet.flatten(styles.iconColor)}/>
</Button>
</HideWithKeyboard>
}
</ScrollView>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
viewContainer: {
// flex: 1,
width: ScreenWidth,
height: ScreenHeight,
backgroundColor: '#ecf0f1',
marginBottom: 5
},
imageContainer: {
height: ScreenHeight * 0.5,
flexDirection: 'column',
justifyContent: 'space-between',
backgroundColor: '#ecf0f1',
padding: 5,
margin: 5
},
image: {
width: ScreenWidth,
height: ScreenHeight * 0.4,
borderColor: '#888'
},
iconColor: {
color: SOP_WHITE
},
resetBtn: {
marginLeft: 4
},
resultInput: {
flex: 1,
flexDirection: 'row',
fontSize: 15,
color: 'black'
},
resultLabel: {
color: 'black',
fontSize: 15,
paddingTop: 2
},
rowContainer: {
flex: 2,
flexDirection: 'column',
justifyContent: 'space-between',
backgroundColor: '#ecf0f1',
padding: 5,
margin: 5
},
rowSpacer: {
flex: 1,
marginBottom: 5,
justifyContent: 'space-between'
},
resultMargin: {
marginTop: 5
},
awesomeAlertButton: {
minHeight: '10%'
},
awesomeAlertText: {
maxWidth: '90%',
flexWrap: 'wrap'
},
buttonTextStlye:
{
color: SOP_WHITE
},
imageOpacity: {
flex: 2.5,
minWidth: ScreenWidth,
maxWidth: ScreenWidth,
marginBottom: 5
},
textInput: {
alignSelf: 'stretch'
},
buttonView: {
flex: .5,
flexDirection: 'row',
justifyContent: 'center',
marginTop: 4,
marginBottom: 20
},
infoText: {
paddingLeft: 5
},
cancelIcon: {
color: SOP_WHITE
}
});
export default TravelSideView;
|
'use strict';
eventsApp.controller('MainMenuController',
function MainMenuController($scope, $location, authService) {
$scope.user = {};
$scope.$watch(authService.getCurrentUserName, function () {
$scope.user = authService.getCurrentUser();
});
$scope.isAuthenticated = function () {
return authService.isAuthenticated();
};
$scope.logout = function () {
authService.setCurrentUser({});
};
$scope.createEvent = function() {
console.log('Navigating to new event...');
$location.url('/newEvent', true);
};
});
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CodeZu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
var Client = require('../../../../client'), constants = Client.constants;
module.exports = Client.sub({
getFacet: Client.method({
method: constants.verbs.GET,
url: '{+tenantPod}api/commerce/catalog/admin/facets/{facetId}?validate={validate}&responseFields={responseFields}'
}),
getFacetCategoryList: Client.method({
method: constants.verbs.GET,
url: '{+tenantPod}api/commerce/catalog/admin/facets/category/{categoryId}?includeAvailable={includeAvailable}&validate={validate}&responseFields={responseFields}'
}),
addFacet: Client.method({
method: constants.verbs.POST,
url: '{+tenantPod}api/commerce/catalog/admin/facets/?responseFields={responseFields}'
}),
updateFacet: Client.method({
method: constants.verbs.PUT,
url: '{+tenantPod}api/commerce/catalog/admin/facets/{facetId}?responseFields={responseFields}'
}),
deleteFacetById: Client.method({
method: constants.verbs.DELETE,
url: '{+tenantPod}api/commerce/catalog/admin/facets/{facetId}'
})
});
|
(function() {
"use strict";
/* touchme main */
// Base function.
var root = this;
var document = this.document || {};
//native custom event or polyfill
var CustomEvent = this.CustomEvent;
if(typeof CustomEvent === 'undefined' || typeof CustomEvent === 'object'){
//https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
CustomEvent = (function(){
function CEvent( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CEvent.prototype = root.Event.prototype;
return CEvent;
}());
}
var touchme = function(args) {
//`this` will be window in browser, and will contain ontouchstart if a mobile device
var touchDevice = ('ontouchstart' in root);
//self explanatory...
var
touchStart = false,
tapNumber = 0,
tapTimer, holdTimer,
currentX, currentY,
oldX, oldY,
holdElement, isHolding,
originalX, originalY, //for elements that are being held
holdInterval, lastX, lastY, //cursor tracking while holding
initialPinch,
swipeTimeout = false,
swipeTimer,
initialEvent;
//where args is an object that can replace any of the default arguments
var defaults = {
swipePrecision: 80,
swipeThreshold: 100,
tapThreshold: 150,
pinchResolution: 15,
holdThreshold: 550,
precision: 20,
holdPrecision:200,
onlyTouch: false,
onlyTap : false,
swipeOnlyTouch: false,
nTap: false
};
//replace any object that belongs in the defaults
if(args){
for(var key in args){
if (args.hasOwnProperty(key) && defaults.hasOwnProperty(key)) {
defaults[key] = args[key];
}
}
}
var isInTapLimits = function(){
return(
currentX >= oldX-defaults.precision &&
currentX <= oldX+defaults.precision &&
currentY >= oldY-defaults.precision &&
currentY <= oldY+defaults.precision
);
};
var isInHoldLimits = function(){
return(
currentX >= oldX-defaults.holdPrecision &&
currentX <= oldX+defaults.holdPrecision &&
currentY >= oldY-defaults.holdPrecision &&
currentY <= oldY+defaults.holdPrecision
);
};
//add event (s) to a given element
var setListener = function(element, evt, callback){
var evtArr = evt.split(' ');
var i = evtArr.length;
while(i--){
//if the onlyTouch flag is set, don't add mouse events
if(defaults.onlyTouch){
if(evtArr[i].match(/mouse/)){
continue;
}
}
element.addEventListener(evtArr[i], callback, false);
}
};
//returns the node being touched/clicked
var getPointer = function(event){
if(event.targetTouches){
return event.targetTouches[0];
}else{
return event;
}
};
var isPinch = function(e){
var pinching = false;
if( e.targetTouches && e.targetTouches[0] && e.targetTouches[1]){
pinching = true;
}
return pinching;
};
var getTouchPoints = function(event){
var touchPoints = {},
touches = event.targetTouches;
for(var i = 0; i < touches.length; i++){
var keyName = "touch"+i;
touchPoints[keyName] = {
x : touches[i].clientX,
y : touches[i].clientY,
id : touches[i].identifier
};
}
return touchPoints;
};
var getMidPoint = function(points){
var x1 = points['touch0'].x,
x2 = points['touch1'].x,
y1 = points['touch0'].y,
y2 = points['touch1'].y,
midpoint;
midpoint = {
x : (x1+x2)/2,
y : (y1+y2)/2
};
return midpoint;
};
var getDistance = function(x1,x2,y1,y2){
//it's a little dense, but it's the fucking distance formula.
return Math.sqrt( Math.pow( (x2-x1) , 2) + Math.pow( (y2-y1), 2) );
};
var isPinchRes = function(firstPinch, newPinch){
var touch1Dist = getDistance( firstPinch['touch0'].x,
newPinch['touch0'].x,
firstPinch['touch0'].y,
newPinch['touch0'].y),
touch2Dist = getDistance( firstPinch['touch1'].x,
newPinch['touch1'].x,
firstPinch['touch1'].y,
newPinch['touch1'].y),
isGreater = false;
if(touch1Dist > defaults.pinchResolution || touch2Dist > defaults.pinchResolution){
isGreater = true;
}
return isGreater;
};
/*
triggerEvent()
creates a custom event, and passes any members in the data object to the event
triggers the custom event on the given element.
*/
var triggerEvent = function(element, eventName, data){
data = data || {
x: currentX,
y: currentY
};
var newEvent = new CustomEvent(
eventName,
{
bubbles: true,
cancelable:true
}
);
for(var key in data){
if(data.hasOwnProperty(key)){
newEvent[key] = data[key];
}
}
element.dispatchEvent(newEvent);
};
//if we're only dealing with touch devices, just set touch device to true to prevent mouse fallbacks
if(defaults.onlyTouch){
touchDevice = true;
}
//tap, dbltap, hold, initialPinch
setListener(document, touchDevice ? 'mousedown touchstart' : 'mousedown', function(e){
if(!initialEvent){
initialEvent = e.type
}else if(initialEvent !== e.type){
return false;
}
touchStart = true;
tapNumber += 1;
var pointer = getPointer(e);
oldX = currentX = pointer.clientX;
oldY = currentY = pointer.clientY;
//initialize tapTimer
clearTimeout(tapTimer);
tapTimer = setTimeout(function(){
if( isInTapLimits() && !touchStart ){
//dense code
// first check if it's a double tap. Anything over 2 taps considered a double tap
// then, check if ntap is enabled, if so and more than 3 taps occcured, trigger ntap.
var tapEventName = tapNumber>=2 ? 'dbltap' : 'tap';
triggerEvent(e.target, tapEventName, {
x : currentX,
y : currentY
});
initialEvent = undefined;
tapNumber = 0;
}else if( !isInTapLimits() || isHolding ){
tapNumber = 0;
}
}, defaults.tapThreshold);
clearTimeout(holdTimer);
//if the user is already holding, do not initialize another hold. as it is, this causes bugs with multiple
// touch events. However, TODO: implement a 'multiple hold' event, to allow for multiple drag-and-drop
if(!isHolding){
holdTimer = setTimeout(function(){
if( isInHoldLimits() && touchStart){
//user is within the tap region and is still after hold threshold
isHolding = true;
//set the hold interval, every 50ms update the hold elements lastXY
holdInterval = setInterval(function(){
lastX = currentX;
lastY = currentY;
},50);
//we'll reference this when the user let's go
holdElement = e;
originalX = pointer.clientX;
originalY = pointer.clientY;
triggerEvent(holdElement.target, 'hold', {
x: currentX,
y: currentY,
touches: e.touches
});
}
}, defaults.holdThreshold);
}
//here we set the initial pinch to compare distances
if(isPinch(e)){
initialPinch = getTouchPoints(e);
initialPinch['distance'] = getDistance( initialPinch['touch0'].x,
initialPinch['touch1'].x,
initialPinch['touch0'].y,
initialPinch['touch1'].y);
initialPinch['midPoint'] = getMidPoint(getTouchPoints(e));
}
//setSwipe timeout
swipeTimer = setTimeout(function(){
swipeTimeout = true;
}, defaults.swipeThreshold);
});
//track the movement / drag
// detect pinch gesture
setListener(document, touchDevice ? 'mousemove touchmove' : 'mousemove', function(e){
var pointer = getPointer(e);
currentX = pointer.clientX;
currentY = pointer.clientY;
//is the user is holding an item, it's being dragged
if(isHolding){
triggerEvent(holdElement.target, 'drag', {
x: currentX,
y: currentY
});
}
if(isPinch(e)){
/*
returns array of objects, with props: x, y, id
*/
var pinch = {};
pinch.touchPoints = getTouchPoints(e);
pinch.distance = getDistance( pinch.touchPoints['touch0'].x,
pinch.touchPoints['touch1'].x,
pinch.touchPoints['touch0'].y,
pinch.touchPoints['touch1'].y);
pinch.midPoint = getMidPoint(pinch.touchPoints);
pinch.initialPinch = initialPinch;
if( isPinchRes(pinch.initialPinch, pinch.touchPoints) ){
triggerEvent(e.target, 'pinch', pinch);
initialPinch = pinch.touchPoints;
initialPinch['distance'] = pinch.distance;
initialPinch['midPoint'] = pinch.midPoint;
}
}
});
/*
create two seperate listeners for touchend and mouseup.
the first is generic, it sets touch start to false and checks to see if the user was holding something
the second is swipe specific, to check if the default 'swipeOnlyTouch' is set
*/
setListener(document, touchDevice ? 'mouseup touchend' : 'mouseup', function(e){
touchStart = false;
if(initialPinch){
initialPinch = undefined;
triggerEvent(e.target, 'pinchrelease');
}
//if the user was holding something...
if(isHolding){
if(e.touches && e.touches.length > 0){
return false
}
isHolding = false;
clearInterval(holdInterval);
triggerEvent(holdElement.target, 'holdrelease', {
originalX: originalX,
originalY: originalY,
lastX: lastX,
lastY: lastY,
touches: e.touches
});
}
});
//swipe specific
var swipeEventName = touchDevice ? 'mouseup touchend' : 'mouseup';
swipeEventName = defaults.swipeOnlyTouch ? 'touchend' : swipeEventName;
setListener(document, swipeEventName, function(e){
touchStart = false;
var
swipeEvents = [],
deltaX = oldX - currentX,
deltaY = oldY - currentY;
//calculate radians for direction
var rads = Math.atan2((currentY-oldY), -(currentX-oldX))+Math.PI,
multiTouch = (e.touches && e.touches.length > 1);
//the user is swiping...
if(
(deltaX <= defaults.swipePrecision || deltaY <= defaults.swipePrecision)
&& multiTouch === false
&& deltaX > 0
&& deltaY > 0
){
swipeEvents.push('swipe');
}
//directional swipes
if( deltaX <= -defaults.swipePrecision ){
swipeEvents.push('swiperight');
}
if( deltaX >= defaults.swipePrecision ){
swipeEvents.push('swipeleft');
}
if( deltaY >= defaults.swipePrecision ){
swipeEvents.push('swipeup');
}
if( deltaY <= -defaults.swipePrecision ){
swipeEvents.push('swipedown');
}
var i = swipeEvents.length;
if(swipeTimeout === false){
while(i--){
triggerEvent(e.target, swipeEvents[i], {
distance:{
x: Math.abs(deltaX),
y: Math.abs(deltaY)
},
direction:{
radians: rads,
degrees: rads*(180/Math.PI)
}
});
tapNumber = 0;
}
clearTimeout(swipeTimer);
}else{
swipeTimeout = false;
clearTimeout(swipeTimer);
swipeEvents = [];
}
});
return touchDevice;
};
// Export to the root, which is probably `window`.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = touchme;
}
exports.touchme = touchme;
} else {
root.touchme = touchme;
}
// Version.
touchme.VERSION = '0.1.0';
}).call(this);
|
'use strict';
const Promise = require('bluebird');
const expect = require('chai').expect;
const sinon = require('sinon');
const AWSProvider = require('../../../src/api/aws_provider');
const AWSUtil = require('../../../src/api/aws_util');
const instance = require('../../../src/api/instance');
const health_check = require('../../../src/api/health_checks');
describe('instance create', function () {
let sandbox, mock_ec2, expected_run_args;
let region, tag, tag_key, alloc_id, assoc_id, pub_ip, instance_id;
beforeEach(function () {
region = 'us-east-1';
tag = 'tag1=val1';
tag_key = {Key: 'tag1', Value: 'val1'};
alloc_id = 'aloc123';
assoc_id = 'assoc123';
pub_ip = '999.999.999.999';
instance_id = '123';
sandbox = sinon.createSandbox();
sandbox.stub(AWSUtil, 'get_ami_id').callsFake((region, ami_name) => Promise.resolve(
ami_name
));
sandbox.stub(AWSUtil, 'get_userdata_string').callsFake((ud_files, env_vars, raw_ud_string) => Promise.resolve(
'userdata_string'
));
sandbox.stub(AWSUtil, 'get_network_interface').callsFake((region, vpc, az, eni_name, sg) => Promise.resolve(
eni_name
));
sandbox.stub(health_check, 'wait_until_status').returns(Promise.resolve(instance_id));
sandbox.stub(health_check, 'wait_for_spinup_complete').returns(Promise.resolve(instance_id));
mock_ec2 = {
runInstancesAsync: sandbox.stub().returns(
Promise.resolve({
Instances: [
{InstanceId: instance_id}
]
})
),
describeInstancesAsync: sandbox.stub().returns(
Promise.resolve({
Reservations: [
{
Instances: [
{
ImageId: 'image_id',
IamInstanceProfile: {
Arn: 'arn'
},
BlockDeviceMappings: [],
Placement: {},
KeyName: 'key_name',
Tags: [],
InstanceType: 'instance_type',
EbsOptimized: true,
NetworkInterfaces: []
}
]
}
]
})
),
createTagsAsync: sandbox.stub().returns(
Promise.resolve({})
),
waitForAsync: sandbox.stub().returns(
Promise.resolve({
Reservations: [
{
Instances: [
{
InstanceId: instance_id,
State: {
Name: 'running'
}
}
]
}
]
})
),
describeAddressesAsync: sandbox.stub().returns(
Promise.resolve({
Addresses: [{
AllocationId: alloc_id,
AssociationId: assoc_id
}]
})
),
disassociateAddressAsync: sandbox.stub().returns(
Promise.resolve()
),
associateAddressAsync: sandbox.stub().returns(
Promise.resolve()
)
};
expected_run_args = {
MaxCount: 1,
MinCount: 1,
Monitoring: {
Enabled: true
},
ImageId: 'image_id',
IamInstanceProfile: {
Name: 'iam'
},
BlockDeviceMappings: null,
KeyName: null,
InstanceType: null,
EbsOptimized: false,
NetworkInterfaces: ['fake-network-interface-id'],
UserData: new Buffer('userdata_string').toString('base64')
};
sandbox.stub(AWSProvider, 'get_ec2').returns(mock_ec2);
});
afterEach(function () {
sandbox.restore();
});
it('creates an instance with no elastic ip', function () {
return instance
.create([region], null, 'image_id', null, null, null, 'iam', null, null, null, null, ['e'], null, 'fake-network-interface-id', null, null, [], false)
.then(function (result) {
expect(mock_ec2.runInstancesAsync).to.have.been.calledWith(expected_run_args);
expect(health_check.wait_until_status).to.have.been.calledWith(region, instance_id, 'instanceExists');
expect(health_check.wait_for_spinup_complete).to.have.not.been.called;
expect(mock_ec2.describeAddressesAsync).to.have.not.been.called;
expect(mock_ec2.disassociateAddressAsync).to.have.not.been.called;
expect(mock_ec2.associateAddressAsync).to.have.not.been.called;
expect(result).eql([instance_id]);
});
});
it('creates an instance with an elastic ip when reassociate is true, and detaching and attaching succeeds', function () {
return instance
.create([region], null, 'image_id', null, null, null, 'iam', null, null, null, null, ['e'], [tag], 'fake-network-interface-id', null, null, [pub_ip], true)
.then(function (result) {
expect(mock_ec2.runInstancesAsync).to.have.been.calledWith(expected_run_args);
expect(health_check.wait_until_status).to.have.been.calledWith(region, instance_id, 'instanceExists');
expect(mock_ec2.createTagsAsync).to.be.calledWith({
Resources: [instance_id],
Tags: [tag_key]
});
expect(health_check.wait_for_spinup_complete).to.have.been.calledWith(region, instance_id);
expect(mock_ec2.describeAddressesAsync).to.have.been.calledWith({
PublicIps: [pub_ip]
});
expect(mock_ec2.disassociateAddressAsync).to.have.been.calledWith({
AssociationId: assoc_id
});
expect(mock_ec2.associateAddressAsync).to.have.been.calledWith({
AllocationId: alloc_id,
InstanceId: instance_id
});
expect(result).eql([instance_id]);
});
});
it('creates an instance without an elastic IP when reassociate is false and an EIP is already attached', function () {
return instance
.create([region], null, 'image_id', null, null, null, 'iam', null, null, null, null, ['e'], [tag], 'fake-network-interface-id', null, null, [pub_ip], false)
.then(function (result) {
expect(mock_ec2.runInstancesAsync).to.have.been.calledWith(expected_run_args);
expect(health_check.wait_until_status).to.have.been.calledWith(region, instance_id, 'instanceExists');
expect(mock_ec2.createTagsAsync).to.have.been.calledWith({
Resources: [instance_id],
Tags: [tag_key]
});
expect(health_check.wait_for_spinup_complete).to.have.not.been.called;
expect(mock_ec2.describeAddressesAsync).to.have.been.calledWith({
PublicIps: [pub_ip]
});
expect(mock_ec2.disassociateAddressAsync).to.have.not.been.called;
expect(mock_ec2.associateAddressAsync).to.have.not.been.called;
expect(result).eql([instance_id]);
});
});
it('creates an instance with an elastic ip when reassociate is true, nothing to detach, and attaching succeeds', function () {
mock_ec2.describeAddressesAsync = sandbox.stub().returns(
Promise.resolve({
Addresses: [{
AllocationId: alloc_id,
AssociationId: null
}]
})
);
return instance
.create([region], null, 'image_id', null, null, null, 'iam', null, null, null, null, ['e'], [tag], 'fake-network-interface-id', null, null, [pub_ip], false)
.then(function (result) {
expect(mock_ec2.runInstancesAsync).to.have.been.calledWith(expected_run_args);
expect(health_check.wait_until_status).to.have.been.calledWith(region, instance_id, 'instanceExists');
expect(mock_ec2.createTagsAsync).to.have.been.calledWith({
Resources: [instance_id],
Tags: [tag_key]
});
expect(health_check.wait_for_spinup_complete).to.have.not.been.called;
expect(mock_ec2.describeAddressesAsync).to.have.been.calledWith({
PublicIps: [pub_ip]
});
expect(mock_ec2.disassociateAddressAsync).to.have.not.been.called;
expect(mock_ec2.associateAddressAsync).to.have.been.calledWith({
AllocationId: alloc_id,
InstanceId: instance_id
});
expect(result).eql([instance_id]);
});
});
it('does not attach an EIP when creating tags fails due to AWS error (or other fatal error) and throws an exception', function () {
let expected_err = new Error('Something wrong');
mock_ec2.createTagsAsync = sandbox.stub().returns(
Promise.reject(expected_err)
);
return instance
.create([region], null, 'image_id', null, null, null, 'iam', ['main-ud-file'], ['us-east-1-rud'], null, null, ['e'], [tag], 'fake-network-interface-id', null, null, [pub_ip], true)
.then(function (result) {
expect(AWSUtil.get_userdata_string).to.have.been.calledWith(['us-east-1-rud','main-ud-file'], null, null);
expect(mock_ec2.runInstancesAsync).to.have.been.calledWith(expected_run_args);
expect(health_check.wait_until_status).to.have.been.calledWith(region, instance_id, 'instanceExists');
expect(mock_ec2.createTagsAsync).to.have.been.calledWith({
Resources: [instance_id],
Tags: [tag_key]
});
expect(health_check.wait_for_spinup_complete).to.have.not.been.called;
expect(mock_ec2.describeAddressesAsync).to.have.not.been.called;
expect(mock_ec2.disassociateAddressAsync).to.have.not.been.called;
expect(mock_ec2.associateAddressAsync).to.have.not.been.called;
expect(result).eql([instance_id]);
})
.catch(err => {
expect(err).to.eql(expected_err);
});
});
});
|
var fast = require('../lib'),
underscore = require('underscore'),
lodash = require('lodash'),
history = require('../test/history');
var input = [1,2,3,4,5,6,7,8,9,10];
var filter = function (item) { return (item + Math.random()) % 2; };
exports['Array::filter()'] = function () {
return input.filter(filter);
};
exports['fast.filter()'] = function () {
return fast.filter(input, filter);
};
exports['underscore.filter()'] = function () {
return underscore.filter(input, filter);
};
exports['lodash.filter()'] = function () {
return lodash.filter(input, filter);
};
|
import * as React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
const NotFoundPage = ({ data, location }) => {
const siteTitle = data.site.siteMetadata.title
return (
<Layout location={location} title={siteTitle}>
<SEO title="404: Not Found" />
<h1>404: Not Found</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</Layout>
)
}
export default NotFoundPage
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
}
`
|
app.factory('upcomingMovies', ['$http', function($http) {
return $http.jsonp('http://api.themoviedb.org/3/movie/upcoming?api_key=968cca12b1a8492036b1e1e05af57e3f&callback=JSON_CALLBACK')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
|
/*
Language: Django
Requires: xml.js
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Ilya Baryshev <baryshev@gmail.com>
*/
function(hljs) {
var FILTER = {
className: 'filter',
begin: /\|[A-Za-z]+\:?/,
keywords:
'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' +
'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' +
'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' +
'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' +
'dictsortreversed default_if_none pluralize lower join center default ' +
'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' +
'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' +
'localtime utc timezone',
contains: [
{className: 'argument', begin: /"/, end: /"/},
{className: 'argument', begin: /'/, end: /'/}
]
};
return {
aliases: ['jinja'],
case_insensitive: true,
subLanguage: 'xml', subLanguageMode: 'continuous',
contains: [
{
className: 'template_comment',
begin: /\{%\s*comment\s*%}/, end: /\{%\s*endcomment\s*%}/
},
{
className: 'template_comment',
begin: /\{#/, end: /#}/
},
{
className: 'template_tag',
begin: /\{%/, end: /%}/,
keywords:
'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' +
'endfor in ifnotequal endifnotequal widthratio extends include spaceless ' +
'endspaceless regroup by as ifequal endifequal ssi now with cycle url filter ' +
'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' +
'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' +
'plural get_current_language language get_available_languages ' +
'get_current_language_bidi get_language_info get_language_info_list localize ' +
'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone ' +
'verbatim',
contains: [FILTER]
},
{
className: 'variable',
begin: /\{\{/, end: /}}/,
contains: [FILTER]
}
]
};
}
|
$(document).ready(function () {
$("#contenedorCalendario").load(BASE_URL + "MenuAdministrativo/calendarioActual"); /*Cargo el calendario actual al momento de terminarse de cargar la pagina */
$('#flechaMesAnterior').click(function (event){
$("#contenedorCalendario").load(BASE_URL + "MenuAdministrativo/mesAnterior");
});
$('#flechaMesSiguiente').click(function (event){
$("#contenedorCalendario").load(BASE_URL + "MenuAdministrativo/mesSiguiente");
});
});
|
/**
* @fileoverview A factory for creating AST nodes
* @author Fred K. Schott
* @copyright 2014 Fred K. Schott. All rights reserved.
* @copyright 2011-2013 Ariya Hidayat <ariya.hidayat@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var astNodeTypes = require("./ast-node-types");
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
module.exports = {
/**
* Create an Array Expression ASTNode out of an array of elements
* @param {ASTNode[]} elements An array of ASTNode elements
* @returns {ASTNode} An ASTNode representing the entire array expression
*/
createArrayExpression: function (elements) {
return {
type: astNodeTypes.ArrayExpression,
elements: elements
};
},
/**
* Create an Arrow Function Expression ASTNode
* @param {ASTNode} params The function arguments
* @param {ASTNode} defaults Any default arguments
* @param {ASTNode} body The function body
* @param {ASTNode} rest The rest parameter
* @param {boolean} expression True if the arrow function is created via an expression.
* Always false for declarations, but kept here to be in sync with
* FunctionExpression objects.
* @returns {ASTNode} An ASTNode representing the entire arrow function expression
*/
createArrowFunctionExpression: function (params, defaults, body, rest, expression) {
return {
type: astNodeTypes.ArrowFunctionExpression,
id: null,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: false,
expression: expression
};
},
/**
* Create an ASTNode representation of an assignment expression
* @param {ASTNode} operator The assignment operator
* @param {ASTNode} left The left operand
* @param {ASTNode} right The right operand
* @returns {ASTNode} An ASTNode representing the entire assignment expression
*/
createAssignmentExpression: function (operator, left, right) {
return {
type: astNodeTypes.AssignmentExpression,
operator: operator,
left: left,
right: right
};
},
/**
* Create an ASTNode representation of a binary expression
* @param {ASTNode} operator The assignment operator
* @param {ASTNode} left The left operand
* @param {ASTNode} right The right operand
* @returns {ASTNode} An ASTNode representing the entire binary expression
*/
createBinaryExpression: function (operator, left, right) {
var type = (operator === "||" || operator === "&&") ? astNodeTypes.LogicalExpression :
astNodeTypes.BinaryExpression;
return {
type: type,
operator: operator,
left: left,
right: right
};
},
/**
* Create an ASTNode representation of a block statement
* @param {ASTNode} body The block statement body
* @returns {ASTNode} An ASTNode representing the entire block statement
*/
createBlockStatement: function (body) {
return {
type: astNodeTypes.BlockStatement,
body: body
};
},
/**
* Create an ASTNode representation of a break statement
* @param {ASTNode} label The break statement label
* @returns {ASTNode} An ASTNode representing the break statement
*/
createBreakStatement: function (label) {
return {
type: astNodeTypes.BreakStatement,
label: label
};
},
/**
* Create an ASTNode representation of a call expression
* @param {ASTNode} callee The function being called
* @param {ASTNode[]} args An array of ASTNodes representing the function call arguments
* @returns {ASTNode} An ASTNode representing the entire call expression
*/
createCallExpression: function (callee, args) {
return {
type: astNodeTypes.CallExpression,
callee: callee,
"arguments": args
};
},
/**
* Create an ASTNode representation of a catch clause/block
* @param {ASTNode} param Any catch clause exeption/conditional parameter information
* @param {ASTNode} body The catch block body
* @returns {ASTNode} An ASTNode representing the entire catch clause
*/
createCatchClause: function (param, body) {
return {
type: astNodeTypes.CatchClause,
param: param,
body: body
};
},
/**
* Create an ASTNode representation of a conditional expression
* @param {ASTNode} test The conditional to evaluate
* @param {ASTNode} consequent The code to be run if the test returns true
* @param {ASTNode} alternate The code to be run if the test returns false
* @returns {ASTNode} An ASTNode representing the entire conditional expression
*/
createConditionalExpression: function (test, consequent, alternate) {
return {
type: astNodeTypes.ConditionalExpression,
test: test,
consequent: consequent,
alternate: alternate
};
},
/**
* Create an ASTNode representation of a continue statement
* @param {?ASTNode} label The optional continue label (null if not set)
* @returns {ASTNode} An ASTNode representing the continue statement
*/
createContinueStatement: function (label) {
return {
type: astNodeTypes.ContinueStatement,
label: label
};
},
/**
* Create an ASTNode representation of a debugger statement
* @returns {ASTNode} An ASTNode representing the debugger statement
*/
createDebuggerStatement: function () {
return {
type: astNodeTypes.DebuggerStatement
};
},
/**
* Create an ASTNode representation of an empty statement
* @returns {ASTNode} An ASTNode representing an empty statement
*/
createEmptyStatement: function () {
return {
type: astNodeTypes.EmptyStatement
};
},
/**
* Create an ASTNode representation of an expression statement
* @param {ASTNode} expression The expression
* @returns {ASTNode} An ASTNode representing an expression statement
*/
createExpressionStatement: function (expression) {
return {
type: astNodeTypes.ExpressionStatement,
expression: expression
};
},
/**
* Create an ASTNode representation of a while statement
* @param {ASTNode} test The while conditional
* @param {ASTNode} body The while loop body
* @returns {ASTNode} An ASTNode representing a while statement
*/
createWhileStatement: function (test, body) {
return {
type: astNodeTypes.WhileStatement,
test: test,
body: body
};
},
/**
* Create an ASTNode representation of a do..while statement
* @param {ASTNode} test The do..while conditional
* @param {ASTNode} body The do..while loop body
* @returns {ASTNode} An ASTNode representing a do..while statement
*/
createDoWhileStatement: function (test, body) {
return {
type: astNodeTypes.DoWhileStatement,
body: body,
test: test
};
},
/**
* Create an ASTNode representation of a for statement
* @param {ASTNode} init The initialization expression
* @param {ASTNode} test The conditional test expression
* @param {ASTNode} update The update expression
* @param {ASTNode} body The statement body
* @returns {ASTNode} An ASTNode representing a for statement
*/
createForStatement: function (init, test, update, body) {
return {
type: astNodeTypes.ForStatement,
init: init,
test: test,
update: update,
body: body
};
},
/**
* Create an ASTNode representation of a for..in statement
* @param {ASTNode} left The left-side variable for the property name
* @param {ASTNode} right The right-side object
* @param {ASTNode} body The statement body
* @returns {ASTNode} An ASTNode representing a for..in statement
*/
createForInStatement: function (left, right, body) {
return {
type: astNodeTypes.ForInStatement,
left: left,
right: right,
body: body,
each: false
};
},
/**
* Create an ASTNode representation of a for..of statement
* @param {ASTNode} left The left-side variable for the property value
* @param {ASTNode} right The right-side object
* @param {ASTNode} body The statement body
* @returns {ASTNode} An ASTNode representing a for..of statement
*/
createForOfStatement: function (left, right, body) {
return {
type: astNodeTypes.ForOfStatement,
left: left,
right: right,
body: body
};
},
/**
* Create an ASTNode representation of a function declaration
* @param {ASTNode} id The function name
* @param {ASTNode} params The function arguments
* @param {ASTNode} defaults Any default arguments (ES6-only feature)
* @param {ASTNode} body The function body
* @param {ASTNode} rest The node representing a rest argument.
* @param {boolean} generator True if the function is a generator, false if not.
* @param {boolean} expression True if the function is created via an expression.
* Always false for declarations, but kept here to be in sync with
* FunctionExpression objects.
* @returns {ASTNode} An ASTNode representing a function declaration
*/
createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression) {
return {
type: astNodeTypes.FunctionDeclaration,
id: id,
params: params,
defaults: defaults || [],
body: body,
rest: rest || null,
generator: !!generator,
expression: !!expression
};
},
/**
* Create an ASTNode representation of a function expression
* @param {ASTNode} id The function name
* @param {ASTNode} params The function arguments
* @param {ASTNode} defaults Any default arguments (ES6-only feature)
* @param {ASTNode} body The function body
* @param {ASTNode} rest The node representing a rest argument.
* @param {boolean} generator True if the function is a generator, false if not.
* @param {boolean} expression True if the function is created via an expression.
* @returns {ASTNode} An ASTNode representing a function declaration
*/
createFunctionExpression: function (id, params, defaults, body, rest, generator, expression) {
return {
type: astNodeTypes.FunctionExpression,
id: id,
params: params,
defaults: defaults || [],
body: body,
rest: rest || null,
generator: !!generator,
expression: !!expression
};
},
/**
* Create an ASTNode representation of an identifier
* @param {ASTNode} name The identifier name
* @returns {ASTNode} An ASTNode representing an identifier
*/
createIdentifier: function (name) {
return {
type: astNodeTypes.Identifier,
name: name
};
},
/**
* Create an ASTNode representation of an if statement
* @param {ASTNode} test The if conditional expression
* @param {ASTNode} consequent The consequent if statement to run
* @param {ASTNode} alternate the "else" alternate statement
* @returns {ASTNode} An ASTNode representing an if statement
*/
createIfStatement: function (test, consequent, alternate) {
return {
type: astNodeTypes.IfStatement,
test: test,
consequent: consequent,
alternate: alternate
};
},
/**
* Create an ASTNode representation of a labeled statement
* @param {ASTNode} label The statement label
* @param {ASTNode} body The labeled statement body
* @returns {ASTNode} An ASTNode representing a labeled statement
*/
createLabeledStatement: function (label, body) {
return {
type: astNodeTypes.LabeledStatement,
label: label,
body: body
};
},
/**
* Create an ASTNode literal from the source code
* @param {ASTNode} token The ASTNode token
* @param {string} source The source code to get the literal from
* @returns {ASTNode} An ASTNode representing the new literal
*/
createLiteralFromSource: function (token, source) {
var node = {
type: astNodeTypes.Literal,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
// regular expressions have regex properties
if (token.regex) {
node.regex = token.regex;
}
return node;
},
/**
* Create an ASTNode template element
* @param {Object} value Data on the element value
* @param {string} value.raw The raw template string
* @param {string} value.cooked The processed template string
* @param {boolean} tail True if this is the final element in a template string
* @returns {ASTNode} An ASTNode representing the template string element
*/
createTemplateElement: function (value, tail) {
return {
type: astNodeTypes.TemplateElement,
value: value,
tail: tail
};
},
/**
* Create an ASTNode template literal
* @param {ASTNode[]} quasis An array of the template string elements
* @param {ASTNode[]} expressions An array of the template string expressions
* @returns {ASTNode} An ASTNode representing the template string
*/
createTemplateLiteral: function (quasis, expressions) {
return {
type: astNodeTypes.TemplateLiteral,
quasis: quasis,
expressions: expressions
};
},
/**
* Create an ASTNode representation of a spread element
* @param {ASTNode} argument The array being spread
* @returns {ASTNode} An ASTNode representing a spread element
*/
createSpreadElement: function (argument) {
return {
type: astNodeTypes.SpreadElement,
argument: argument
};
},
/**
* Create an ASTNode tagged template expression
* @param {ASTNode} tag The tag expression
* @param {ASTNode} quasi A TemplateLiteral ASTNode representing
* the template string itself.
* @returns {ASTNode} An ASTNode representing the tagged template
*/
createTaggedTemplateExpression: function (tag, quasi) {
return {
type: astNodeTypes.TaggedTemplateExpression,
tag: tag,
quasi: quasi
};
},
/**
* Create an ASTNode representation of a member expression
* @param {string} accessor The member access method (bracket or period)
* @param {ASTNode} object The object being referenced
* @param {ASTNode} property The object-property being referenced
* @returns {ASTNode} An ASTNode representing a member expression
*/
createMemberExpression: function (accessor, object, property) {
return {
type: astNodeTypes.MemberExpression,
computed: accessor === "[",
object: object,
property: property
};
},
/**
* Create an ASTNode representation of a new expression
* @param {ASTNode} callee The constructor for the new object type
* @param {ASTNode} args The arguments passed to the constructor
* @returns {ASTNode} An ASTNode representing a new expression
*/
createNewExpression: function (callee, args) {
return {
type: astNodeTypes.NewExpression,
callee: callee,
"arguments": args
};
},
/**
* Create an ASTNode representation of a new object expression
* @param {ASTNode[]} properties An array of ASTNodes that represent all object
* properties and associated values
* @returns {ASTNode} An ASTNode representing a new object expression
*/
createObjectExpression: function (properties) {
return {
type: astNodeTypes.ObjectExpression,
properties: properties
};
},
/**
* Create an ASTNode representation of a postfix expression
* @param {string} operator The postfix operator ("++", "--", etc.)
* @param {ASTNode} argument The operator argument
* @returns {ASTNode} An ASTNode representing a postfix expression
*/
createPostfixExpression: function (operator, argument) {
return {
type: astNodeTypes.UpdateExpression,
operator: operator,
argument: argument,
prefix: false
};
},
/**
* Create an ASTNode representation of an entire program
* @param {ASTNode} body The program body
* @returns {ASTNode} An ASTNode representing an entire program
*/
createProgram: function (body) {
return {
type: astNodeTypes.Program,
body: body
};
},
/**
* Create an ASTNode representation of an object property
* @param {string} kind The type of property represented ("get", "set", etc.)
* @param {ASTNode} key The property key
* @param {ASTNode} value The new property value
* @param {boolean} method True if the property is also a method (value is a function)
* @param {boolean} shorthand True if the property is shorthand
* @param {boolean} computed True if the property value has been computed
* @returns {ASTNode} An ASTNode representing an object property
*/
createProperty: function (kind, key, value, method, shorthand, computed) {
return {
type: astNodeTypes.Property,
key: key,
value: value,
kind: kind,
method: method,
shorthand: shorthand,
computed: computed
};
},
/**
* Create an ASTNode representation of a return statement
* @param {?ASTNode} argument The return argument, null if no argument is provided
* @returns {ASTNode} An ASTNode representing a return statement
*/
createReturnStatement: function (argument) {
return {
type: astNodeTypes.ReturnStatement,
argument: argument
};
},
/**
* Create an ASTNode representation of a sequence of expressions
* @param {ASTNode[]} expressions An array containing each expression, in order
* @returns {ASTNode} An ASTNode representing a sequence of expressions
*/
createSequenceExpression: function (expressions) {
return {
type: astNodeTypes.SequenceExpression,
expressions: expressions
};
},
/**
* Create an ASTNode representation of a switch case statement
* @param {ASTNode} test The case value to test against the switch value
* @param {ASTNode} consequent The consequent case statement
* @returns {ASTNode} An ASTNode representing a switch case
*/
createSwitchCase: function (test, consequent) {
return {
type: astNodeTypes.SwitchCase,
test: test,
consequent: consequent
};
},
/**
* Create an ASTNode representation of a switch statement
* @param {ASTNode} discriminant An expression to test against each case value
* @param {ASTNode[]} cases An array of switch case statements
* @returns {ASTNode} An ASTNode representing a switch statement
*/
createSwitchStatement: function (discriminant, cases) {
return {
type: astNodeTypes.SwitchStatement,
discriminant: discriminant,
cases: cases
};
},
/**
* Create an ASTNode representation of a this statement
* @returns {ASTNode} An ASTNode representing a this statement
*/
createThisExpression: function () {
return {
type: astNodeTypes.ThisExpression
};
},
/**
* Create an ASTNode representation of a throw statement
* @param {ASTNode} argument The argument to throw
* @returns {ASTNode} An ASTNode representing a throw statement
*/
createThrowStatement: function (argument) {
return {
type: astNodeTypes.ThrowStatement,
argument: argument
};
},
/**
* Create an ASTNode representation of a try statement
* @param {ASTNode} block The try block
* @param {ASTNode} guardedHandlers Any guarded catch handlers
* @param {ASTNode} handlers Any catch handlers
* @param {?ASTNode} finalizer The final code block to run after the try/catch has run
* @returns {ASTNode} An ASTNode representing a try statement
*/
createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
return {
type: astNodeTypes.TryStatement,
block: block,
guardedHandlers: guardedHandlers,
handlers: handlers,
finalizer: finalizer
};
},
/**
* Create an ASTNode representation of a unary expression
* @param {string} operator The unary operator
* @param {ASTNode} argument The unary operand
* @returns {ASTNode} An ASTNode representing a unary expression
*/
createUnaryExpression: function (operator, argument) {
if (operator === "++" || operator === "--") {
return {
type: astNodeTypes.UpdateExpression,
operator: operator,
argument: argument,
prefix: true
};
}
return {
type: astNodeTypes.UnaryExpression,
operator: operator,
argument: argument,
prefix: true
};
},
/**
* Create an ASTNode representation of a variable declaration
* @param {ASTNode[]} declarations An array of variable declarations
* @param {string} kind The kind of variable created ("var", "let", etc.)
* @returns {ASTNode} An ASTNode representing a variable declaration
*/
createVariableDeclaration: function (declarations, kind) {
return {
type: astNodeTypes.VariableDeclaration,
declarations: declarations,
kind: kind
};
},
/**
* Create an ASTNode representation of a variable declarator
* @param {ASTNode} id The variable ID
* @param {ASTNode} init The variable's initial value
* @returns {ASTNode} An ASTNode representing a variable declarator
*/
createVariableDeclarator: function (id, init) {
return {
type: astNodeTypes.VariableDeclarator,
id: id,
init: init
};
},
/**
* Create an ASTNode representation of a with statement
* @param {ASTNode} object The with statement object expression
* @param {ASTNode} body The with statement body
* @returns {ASTNode} An ASTNode representing a with statement
*/
createWithStatement: function (object, body) {
return {
type: astNodeTypes.WithStatement,
object: object,
body: body
};
},
createYieldExpression: function (argument, delegate) {
return {
type: astNodeTypes.YieldExpression,
argument: argument,
delegate: delegate
};
},
createJSXAttribute: function (name, value) {
return {
type: astNodeTypes.JSXAttribute,
name: name,
value: value || null
};
},
createJSXSpreadAttribute: function (argument) {
return {
type: astNodeTypes.JSXSpreadAttribute,
argument: argument
};
},
createJSXIdentifier: function (name) {
return {
type: astNodeTypes.JSXIdentifier,
name: name
};
},
createJSXNamespacedName: function (namespace, name) {
return {
type: astNodeTypes.JSXNamespacedName,
namespace: namespace,
name: name
};
},
createJSXMemberExpression: function (object, property) {
return {
type: astNodeTypes.JSXMemberExpression,
object: object,
property: property
};
},
createJSXElement: function (openingElement, closingElement, children) {
return {
type: astNodeTypes.JSXElement,
openingElement: openingElement,
closingElement: closingElement,
children: children
};
},
createJSXEmptyExpression: function () {
return {
type: astNodeTypes.JSXEmptyExpression
};
},
createJSXExpressionContainer: function (expression) {
return {
type: astNodeTypes.JSXExpressionContainer,
expression: expression
};
},
createJSXOpeningElement: function (name, attributes, selfClosing) {
return {
type: astNodeTypes.JSXOpeningElement,
name: name,
selfClosing: selfClosing,
attributes: attributes
};
},
createJSXClosingElement: function (name) {
return {
type: astNodeTypes.JSXClosingElement,
name: name
};
}
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose} from 'redux';
import { Router, browserHistory } from 'react-router';
import rootReducer from './reducers/index';
import routes from './routes';
import setAuthToken from './utils/setAuthToken';
import { setCurrentUser } from './actions/auth_actions';
import jwt from 'jsonwebtoken';
import thunk from 'redux-thunk';
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
)
)
if(localStorage.tfJWT) {
setAuthToken(localStorage.tfJWT);
store.dispatch(setCurrentUser(jwt.decode(localStorage.tfJWT)));
}
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('#app'));
|
import Relay from 'react-relay';
class AddUserMutation extends Relay.Mutation {
getMutation() {
return Relay.QL`
mutation { addUser }
`;
}
getVariables() {
return {
name: this.props.name,
address: this.props.address,
email: this.props.email,
age: this.props.age
};
}
getFatQuery() {
return Relay.QL`
fragment on AddUserPayload {
# userEdge,
viewer { users }
}
`;
}
getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'viewer',
parentID: this.props.viewerId,
connectionName: 'users',
edgeName: 'userEdge',
rangeBehaviors: {
'': 'append',
},
}];
}
}
export default AddUserMutation;
|
/* globals SubscribeWithScroll, InfiniteScroll, jQuery */
SubscribeWithScroll = class {
/**
* Initializes the SubscribeWithScroll
* @param {Object} options
* @return {SubscribeWithScroll}
*/
constructor(options){
check(options, {
pub: String,
limit: Match.Integer,
increment: Match.Integer,
template: Match.Optional(Blaze.TemplateInstance),
threshold: Match.OneOf(String, jQuery),
params: Match.Optional(Function),
collection: Mongo.Collection
});
this.pub = options.pub;
this.collection = options.collection;
this.limit = new ReactiveVar(options.limit);
this.hasEnded = new ReactiveVar(false);
this.increment = options.increment;
this.template = options.template || Meteor;
this.params = options.params || function(){};
this.infiniteScroll =
new InfiniteScroll(options.threshold, options.template);
this.events = $({});
return this;
}
destroy(){
this.infiniteScroll.destroy();
if(this.computation){
this.computation.stop();
}
}
onEnd(fn){
return this.events.on('end', fn);
}
run(){
this.computation = Tracker.autorun(() => {
let params = _.extend(this.params() || {}, {
limit: this.limit.get()
});
let countBefore = this.collection.find().count();
this.template.subscribe(this.pub, params, () => {
Tracker.afterFlush(() => {
const count = this.collection.find().count();
if(countBefore === count){
this.events.trigger('end');
this.hasEnded.set(true);
} else {
this.hasEnded.set(false);
}
})
});
});
this.infiniteScroll.onInfinite(() => {
this.limit.set( this.limit.get() + this.increment );
});
this.infiniteScroll.run();
}
};
|
'use strict';
var services = angular.module('haoshiyou.services', []);
services.factory('HaoshiyouService', function ($log, $cacheFactory, $http, $q) {
var CONST_SPREADSHEET_URL = "https://spreadsheets.google.com/feeds/list/1vzugrYLpgXmFODqysSx331Lhq8LpDQGJ4sQtwSMrtV4/1/public/values?alt=json&callback=JSON_CALLBACK";
var CONST_FIELD_KEYS = {
xq: "gsx$需求类别",
qssj: "gsx$预计起始日期超过这个日期本条信息失效",
qy: "gsx$区域",
ybhzcs: "gsx$邮编或者城市",
yqjg: "gsx$预期价格美元每月",
grjs: "gsx$租房需求介绍和自我介绍",
wxId: "gsx$微信号",
xb: "gsx$性别",
dhyx: "gsx$其他联系方式电话邮箱等",
fbsj: "gsx$timestamp",
ltst: "gsx$shorttermorlongterm",
entryid: "gsx$entryid"
};
var CONST_FIELDS = [
'xq', 'qssj', 'qy', 'ybhzcs', 'yqjg', 'grjs',
'wxId', 'xb', 'dhyx', 'fbsj', 'ltst'
];
var myCache = $cacheFactory('myCache');
function loadDataP() {
return $http.jsonp(CONST_SPREADSHEET_URL, { cache: true })
.then(function(data){
$log.info("loade data");
$log.info(data);
return data;
});
}
function storeData(json) {
var cacheEntries = {}; //update data;
var cacheGuids = [];
var data = json.data;
console.log(data);
data.feed.entry.forEach(function (row) {
var guid = row[CONST_FIELD_KEYS.entryid]["$t"] || "N/A";
var datum = {};
CONST_FIELDS.forEach(function (fieldName) {
datum[fieldName] = row[CONST_FIELD_KEYS[fieldName]]["$t"] || "N/A";
});
datum.guid = guid;
cacheEntries[guid] = datum;
cacheGuids.push(guid);
});
myCache.put("entries", cacheEntries);
myCache.put("guids", cacheGuids);
}
return {
post: function (guid) {
if (myCache && myCache.get("entries")) {
var cacheEntries = myCache.get("entries");
return cacheEntries[guid];
} else {
var result = {};
loadDataP()
.then(function(data) {
storeData(data);
var cacheEntries = myCache.get("entries");
angular.copy(cacheEntries[guid], result)
})
return result;
}
},
postsP: function () {
if (myCache && myCache.get("entries")) {
var cacheEntries = myCache.get("entries");
var d = $q.defer();
d.resolve(cacheEntries);
return d.promise;
} else {
return loadDataP()
.then(function(data) {
storeData(data);
var stored = myCache.get("entries");
return stored;
})
}
}
}
});
services.factory('PagedResult', function (HaoshiyouService) {
return function PagedResult (method, arg, collection_name) {
var self = this;
self.page = 0;
var collection = this[collection_name] = [];
this.loadNextPage = function () {
HaoshiyouService[method](arg, {page: self.page + 1}).then(function (data){
self.page = data.data.page;
self.pages = data.data.pages;
self.per_page = data.data.per_page;
[].push.apply(collection, data.data[collection_name])
});
return this;
}
}
});
|
corkboard.controller('corkboardController', function($scope, corkboardService, messageService, CONFIG, authService) {
var ctrl = this; //remember controller
// --- Methods ----------------------------------------------
ctrl.getCards = function() {
if(!authService.isAuthenticated()) {
return;
}
corkboardService.getCards().then( function(data) {
$scope.data.cards = data;
});
}
// ----------------------------------------------------------
$scope.openCardFormNew = function() {
$scope.data.showOverlay = "overlay-visible";
$scope.data.card = corkboardService.getCardTemplate();
};
// ----------------------------------------------------------
$scope.openCardFormEdit = function(card) {
$scope.data.showOverlay = "overlay-visible";
// Make a Copy of the chosen Card
$scope.data.card = JSON.parse(JSON.stringify(card));
// parse Dates
$scope.data.card.startdate = ($scope.data.card.startdate != null ? new Date ($scope.data.card.startdate) : null);
$scope.data.card.enddate = ($scope.data.card.enddate != null ? new Date ($scope.data.card.enddate) : null);
};
// ----------------------------------------------------------
$scope.submitCardForm = function() {
$scope.data.showOverlay = "overlay-hidden";
corkboardService.addOrEditCard($scope.data.card).then( function() {
// reset card in scope
$scope.data.card = corkboardService.getCardTemplate();
// Reload all Cards
ctrl.getCards();
});
};
// ----------------------------------------------------------
$scope.cancelCardForm = function() {
$scope.data.showOverlay = "overlay-hidden";
// reset Template
$scope.data.card = corkboardService.getCardTemplate();
};
// ----------------------------------------------------------
$scope.deleteCard = function(card) {
corkboardService.deleteCard(card).then( function() {
ctrl.getCards();
});
};
// ----------------------------------------------------------
$scope.printCard = function(divName) {
// TODO
}
// ----------------------------------------------------------
ctrl.callback = function() {
ctrl.getCards();
}
// ----------------------------------------------------------
$scope.data = {};
$scope.data.today = new Date().toISOString();
$scope.data.showOverlay = 'overlay-hidden';
$scope.data.card = corkboardService.getCardTemplate;
$scope.data.prios = CONFIG.PRIORITIES;
$scope.data.cats = CONFIG.CATEGORIES;
$scope.data.efforts = CONFIG.EFFORTS;
// ----------------------------------------------------------
ctrl.init = function() {
//register callback
authService.registerObserver(ctrl);
}
// ----------------------------------------------------------
ctrl. init();
return ctrl;
});
|
/* eslint no-magic-numbers: "off" */
const { remote, screen, ipcRenderer } = require('electron')
const h = require('hyperscript')
const csv = require('fast-csv')
const { join } = require('path')
// const { format } = require('url')
// const { createWindowMultiScreen, broadcastMsg } = require(join(process.cwd(), 'src', 'main', 'helperWindows.js'))
const signals = require(join(process.cwd(), 'config', 'signals.js'))
const stylingVars = require(join(process.cwd(), 'config', 'styling-variables.js'))
const utilsAnimation = require(join(process.cwd(), 'src', 'utils', 'utilsAnimation.js'))
const win = remote.getCurrentWindow()
// utilsWindows.createMultiScreenWindow(screen, win)
// @TODO - move to settings
const optsCsv = {
delimiter: ';'
, trim: true
, ignoreEmpty: true
}
const [
winContentSizeWidth
, winContentSizeHeight
] = win.getContentSize()
// let traceData = []
const dancePaths = new Map()
const normalizeDancePaths = (dancePathsMap) => {
// projectionWidth in meter @TODO - move to settings
const projectionWidth = 3
// projectionHeight in meter @TODO - move to settings
const projectionHeight = 1.75
const widthCoefficient = winContentSizeWidth / projectionWidth
const heightCoefficient = winContentSizeHeight / projectionHeight
let avg = 0
let numberOfElements = 0
dancePathsMap.forEach((val) => {
avg += val.reduce((carry, curr) => carry + curr[1], 0)
numberOfElements += val.length
})
avg /= numberOfElements
dancePathsMap.forEach((val) => {
val.forEach(([x, z], i, arr) => {
arr[i] = [
x * widthCoefficient + winContentSizeWidth / 2
, (z - avg) * heightCoefficient + winContentSizeHeight / 2
]
})
})
}
const canvas = h(
'canvas#animationCanvas'
, { width: winContentSizeWidth, height: winContentSizeHeight }
, 'Sorry no canvas to draw on.'
)
document.getElementById('mainAnimationContainer').appendChild(canvas)
csv
.fromPath(join(process.cwd(), 'assets', 'danceData.csv'), optsCsv)
.transform((data) => [
data[0]
, parseFloat(data[1].replace(/,/g, '.'))
, parseFloat(data[3].replace(/,/g, '.'))
, data[4]
])
.on('data', ([
dancerId
, xCoord
, zCoord
, timestamp
]) => {
if (dancePaths.has(dancerId) === false) {
dancePaths.set(dancerId, [])
}
dancePaths.get(dancerId).push([
xCoord
, zCoord
, timestamp
])
})
.on('end', () => {
normalizeDancePaths(dancePaths)
// const ctx = canvas.getContext('2d')
// make new canvas for each dancer
// like a new layer for each dancer
})
// const buildTraceCoords = () => {
// const avgDepth = traceData.reduce((carry, curr) => carry + curr[1], 0) / traceData.length
// traceData = traceData.map((val) => [
// val[0] * widthCoefficient + winContentSizeWidth / 2
// , (val[1] - avgDepth) * heightCoefficient + winContentSizeHeight / 2
// ])
// }
// csv
// // .fromPath(join(process.cwd(), 'assets', 'Testdaten Kinect Tanzen.csv'), { trim: true, ignoreEmpty: true })
// .fromPath(join(process.cwd(), 'assets', 'danceData.csv'), { delimiter: ';', trim: true, ignoreEmpty: true })
// .transform((data) => [
// // parseFloat(data[0])
// // , parseFloat(data[2])
// parseFloat(data[1].replace(/,/g, '.'))
// , parseFloat(data[3].replace(/,/g, '.'))
// ])
// .on('data', (data) => {
// traceData.push(data)
// // process.stdout(data)
// })
// .on('end', () => {
// // process.stdout('done')
// buildTraceCoords()
// const ctx = canvas.getContext('2d')
// const MyTrace = utilsAnimation.createTrace(traceData, ctx, stylingVars['animation-trace-color-default'])
// // document.getElementById('mainAnimationContainer').appendChild(canvas)
// const update = (tFrame) => {
// if (tFrame - MyTrace.lastTick > MyTrace.tickLength) {
// MyTrace.update()
// MyTrace.lastTick = tFrame
// }
// }
// const render = () => {
// ctx.clearRect(0, 0, canvas.width, canvas.height)
// MyTrace.render()
// }
// const main = (tFrame) => {
// MyTrace.rAF = window.requestAnimationFrame(main)
// update(tFrame)
// render()
// }
// const playPause = () => {
// if (MyTrace.isRunning) {
// window.cancelAnimationFrame(MyTrace.rAF)
// MyTrace.isRunning = false
// } else {
// MyTrace.isRunning = true
// MyTrace.lastTick = performance.now()
// main(performance.now())
// }
// }
// canvas.addEventListener('click', () => ipcRenderer.send('signal', 'playPause'))
// ipcRenderer.on('signal', (event, message) => {
// if (signals.get('playPause') === message) {
// playPause()
// }
// console.log(message)
// })
// })
|
// extenders
"use strict"
// Imports.
const objectifier = require("./objectifier.js")
const Stream = require("./Stream.js")
// createObjects :: [String] -> Stream [String] -> Stream (Object String a)
const createObject = (keys, source) => Stream.extend(stream => {
var values
values = Stream.extract(stream)
return values !== Stream.EOS ? objectifier.readObject(keys)(values) : Stream.EOS
}, source)
// Exports.
module.exports = {
createObject: createObject
}
|
/**
* Db schemas for accounts
* version: 0.1
*/
'use strict';
const Schema = db.Schema;
const ObjectId = Schema.ObjectId;
var accountSchema = {
id: ObjectId,
enabled: {type: Boolean, required: true, default: true},
accountKey: {type: String, required: true, unique: true, index: true},
accountName: {type: String, required: true, unique: false, index: true},
accountSecret: {type: String, required: false, unique: false, index: false},
created_at: {type: Date, default: Date.now, index: true},
updated_at: {type: Date, default: Date.now, index: true}
};
var AccountSchema = new Schema(accountSchema);
AccountSchema.path('updated_at')
.default(function(){
return new Date();
})
.set(function(v) {
return v == 'now' ? new Date() : v;
});
module.exports = db.model('Accounts', AccountSchema);
|
'use strict';
var grunt = require('grunt');
exports.i18nextract = {
default_options: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/00_fr_FR.json');
grunt.log.writeflags(actual);
var expected = grunt.file.read('test/expected/00_fr_FR.json');
grunt.log.writeflags(expected);
test.equal(actual, expected, '00 - default_options should be equal.');
test.done();
},
default_exists_i18n: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/01_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/01_fr_FR.json' );
test.equal( actual, expected, '01 - default_exists_i18n should be equal.' );
test.done();
},
default_deleted_i18n: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/02_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/02_fr_FR.json' );
test.equal(actual, expected, '02 - default_deleted_i18n should be equal.');
test.done();
},
interpolation_bracket: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/03_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/03_fr_FR.json' );
test.equal(actual, expected, '03 - interpolation_bracket should be equal.');
test.done();
},
default_language: function(test) {
test.expect(2);
var actual = grunt.file.read( 'tmp/04_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/04_fr_FR.json' );
test.equal( actual, expected, '04 - default_language fr_FR should be equal.' );
var actual = grunt.file.read( 'tmp/04_en_US.json' );
var expected = grunt.file.read( 'test/expected/04_en_US.json' );
test.equal( actual, expected, '04 - default_language en_US should be equal.' );
test.done();
},
json_extract: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/05_en_US.json' );
var expected = grunt.file.read( 'test/expected/05_en_US.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
sub_namespace: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/06_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/06_fr_FR.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
sub_namespace_default_language: function(test) {
test.expect(2);
var actual = grunt.file.read( 'tmp/07_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/07_fr_FR.json' );
test.equal( actual, expected, 'Should equal.' );
var actual = grunt.file.read( 'tmp/07_en_US.json' );
var expected = grunt.file.read( 'test/expected/07_en_US.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
sub_namespace_default_language_source: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/08_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/08_fr_FR.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
consistent_stringify: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/09_A_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/09_A_fr_FR.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
consistent_stringify_options: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/09_B_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/09_B_fr_FR.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
extra_regexs: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/10_fr_FR.json' );
var expected = grunt.file.read( 'test/expected/10_fr_FR.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
keep_translation_links: function(test) {
test.expect(1);
var actual = grunt.file.readJSON( 'test/existing/11_en_US.json' );
var expected = grunt.file.readJSON( 'test/expected/11_en_US.json' );
test.deepEqual( actual, expected, 'Should equal.' );
test.done();
},
key_as_text: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/12_en_US.json' );
var expected = grunt.file.read( 'test/expected/12_en_US.json' );
test.equal( actual, expected, 'Should equal.' );
test.done();
},
extract_to_pot: function(test) {
test.expect(1);
var actual = grunt.file.read( 'tmp/template.pot' );
var expected = grunt.file.read( 'test/expected/template.pot' );
test.equal( actual, expected, 'Should equal.' );
test.done();
}
};
|
/*
* jQuery Mobile Framework : plugin to provide a date and time picker.
* Copyright (c) JTSage
* CC 3.0 Attribution. May be relicensed without permission/notification.
* https://github.com/jtsage/jquery-mobile-datebox
*/
(function($, undefined ) {
// We can greatly reduce some operations by adding to the date object.
Date.prototype.getISO = function () { return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); };
Date.prototype.getComp = function () { return parseInt(this.getISO().replace(/-/g,''),10); }
Date.prototype.copy = function() { return this.copymod(); }
Date.prototype.copymod = function(adj,over) {
if ( typeof adj === 'undefined' ) { adj = [0,0,0,0,0,0]; }
if ( typeof over === 'undefined' ) { over = [0,0,0,0,0,0]; }
while ( adj.length < 6 ) { adj.push(0); }
while ( over.length < 6 ) { over.push(0); }
return new Date(((over[0] > 0 ) ? over[0] : this.getFullYear() + adj[0]),((over[1] > 0 ) ? over[1] : this.getMonth() + adj[1]),((over[2] > 0 ) ? over[2] : this.getDate() + adj[2]),((over[3] > 0 ) ? over[3] : this.getHours() + adj[3]),((over[4] > 0 ) ? over[4] : this.getMinutes() + adj[4]),((over[5] > 0 ) ? over[5] : this.getSeconds() + adj[5]),0);
}
Date.prototype.getEpoch = function() { return (this.getTime() - this.getMilliseconds()) / 1000; }
Date.prototype.adjust = function (type, amount) {
switch (type) {
case 'y': this.setFullYear(this.getFullYear() + amount); break;
case 'm': this.setMonth(this.getMonth() + amount); break;
case 'd': this.setDate(this.getDate() + amount); break;
case 'h': this.setHours(this.getHours() + amount); break;
case 'i': this.setMinutes(this.getMinutes() + amount); break;
case 's': this.setSeconds(this.getSeconds() + amount); break;
}
return this.getTime();
}
$.widget( "mobile.datebox", $.mobile.widget, {
options: {
// All widget options, including some internal runtime details
version: '1.0.1-2012022700', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial
theme: false,
defaultTheme: 'c',
pickPageTheme: 'b',
pickPageInputTheme: 'e',
pickPageButtonTheme: 'a',
pickPageHighButtonTheme: 'e',
pickPageOHighButtonTheme: 'e',
pickPageOAHighButtonTheme: 'e',
pickPageODHighButtonTheme: 'e',
pickPageTodayButtonTheme: 'e',
pickPageSlideButtonTheme: 'd',
pickPageFlipButtonTheme: 'b',
forceInheritTheme: false,
centerWindow: false,
calHighToday: true,
calHighPicked: true,
transition: 'pop',
noAnimation: false,
disableManualInput: false,
disabled: false,
wheelExists: false,
swipeEnabled: true,
zindex: '500',
debug: false,
clickEvent: 'vclick',
numberInputEnhance: true,
internalInputType: 'text',
resizeListener: true,
titleDialogLabel: false,
meridiemLetters: ['AM', 'PM'],
timeOutputOverride: false,
timeFormats: { '12': '%l:%M %p', '24': '%k:%M' },
durationFormat: 'DD ddd, hh:ii:ss',
timeOutput: false,
rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true },
mode: 'datebox',
calShowDays: true,
calShowOnlyMonth: false,
useDialogForceTrue: false,
useDialogForceFalse: true,
fullScreen: false,
fullScreenAlways: false,
useDialog: false,
useModal: false,
useInline: false,
useInlineBlind: false,
useClearButton: false,
collapseButtons: false,
noButtonFocusMode: false,
focusMode: false,
noButton: false,
noSetButton: false,
openCallback: false,
openCallbackArgs: [],
closeCallback: false,
closeCallbackArgs: [],
open: false,
nestedBox: false,
lastDuration: false,
fieldsOrder: false,
fieldsOrderOverride: false,
durationOrder: ['d', 'h', 'i', 's'],
defaultDateFormat: '%Y-%m-%d',
dateFormat: false,
timeFormatOverride: false,
headerFormat: false,
dateOutput: false,
minuteStep: 1,
calTodayButton: false,
calWeekMode: false,
calWeekModeFirstDay: 1,
calWeekModeHighlight: true,
calStartDay: false,
defaultPickerValue: false,
defaultDate : false, //this is deprecated and will be removed in the future versions (ok, may be not)
minYear: false,
maxYear: false,
afterToday: false,
beforeToday: false,
maxDays: false,
minDays: false,
highDays: false,
highDates: false,
highDatesAlt: false,
blackDays: false,
blackDates: false,
enableDates: false,
fixDateArrays: false,
durationSteppers: {'d': 1, 'h': 1, 'i': 1, 's': 1},
useLang: 'en',
lang: {
'en' : {
setDateButtonLabel: 'Set Date',
setTimeButtonLabel: 'Set Time',
setDurationButtonLabel: 'Set Duration',
calTodayButtonLabel: 'Jump to Today',
titleDateDialogLabel: 'Set Date',
titleTimeDialogLabel: 'Set Time',
daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'],
durationDays: ['Day', 'Days'],
timeFormat: 24,
headerFormat: '%A, %B %-d, %Y',
tooltip: 'Open Date Picker',
nextMonth: 'Next Month',
prevMonth: 'Previous Month',
dateFieldOrder: ['m', 'd', 'y'],
timeFieldOrder: ['h', 'i', 'a'],
slideFieldOrder: ['y', 'm', 'd'],
dateFormat: '%Y-%m-%d',
useArabicIndic: false,
isRTL: false,
calStartDay: 0,
clearButton: 'Clear'
}
}
},
destroy: function () {
$(this.pickPage).remove();
$.Widget.prototype.destroy.call(this);
},
_dateboxHandler: function(event, payload) {
var widget = $(this).data('datebox');
// Handle all event triggers that have an internal effect
if ( ! event.isPropagationStopped() ) {
switch (payload.method) {
case 'close':
widget.close(payload.fromCloseButton);
break;
case 'open':
widget.open();
break;
case 'set':
$(this).val(payload.value);
$(this).trigger('change');
break;
case 'doset':
if ( $.inArray(widget.options.mode, ['timebox', 'durationbox', 'timeflipbox']) > -1 ) {
$(this).trigger('datebox', {'method':'set', 'value':widget._formatTime(widget.theDate), 'date':widget.theDate});
} else {
$(this).trigger('datebox', {'method':'set', 'value':widget._formatDate(widget.theDate), 'date':widget.theDate});
}
break;
case 'dooffset':
widget._offset(payload.type, payload.amount, true);
break;
case 'dorefresh':
widget._update();
break;
case 'doreset':
widget.hardreset();
break;
case 'doclear':
$(this).val('');
break;
}
}
},
_getCoords: function(widget) {
var self = widget,
inputOffset = widget.focusedEl.offset(),
inputHigh = widget.focusedEl.outerHeight(),
inputWidth = widget.focusedEl.outerWidth(),
docWinWidth = $.mobile.activePage.width(),
docWinHighOff = $(window).scrollTop(),
docWinHigh = $(window).height(),
diaWinWidth = widget.pickerContent.innerWidth(),
diaWinHigh = widget.pickerContent.outerHeight(),
pageitem = false,
minTop = 0, // Minimum TOP measurment (absolute)
padTop = 0, // Padding for TOP measurment (fixed header)
unPadBottom = 0, // Padding for BOTTOM measurement (fixed header)
maxBottom = $(document).height(), // Max BOTTOM measurement (absolute)
coords = {
'high' : $(window).height(),
'width' : $.mobile.activePage.width(),
'fullTop' : $(window).scrollTop(),
'fullLeft': $(window).scrollLeft()
};
if ( widget.options.centerWindow ) { // If it's centered, no need for lots of checks.
coords.winTop = docWinHighOff + (( docWinHigh / 2 ) - ( diaWinHigh / 2 ) );
coords.winLeft = (( docWinWidth / 2 ) - ( diaWinWidth / 2 ) );
} else {
pageitem = $('.ui-header', $.mobile.activePage);
if ( pageitem.length > 0 ) {
if ( pageitem.is('.ui-header-fixed')) {
padTop = ( pageitem.outerHeight() + 2 );
} else {
minTop += ( pageitem.outerHeight() + 2 );
}
}
pageitem = $('.ui-footer', $.mobile.activePage);
if ( pageitem.length > 0 ) {
if ( pageitem.is('.ui-footer-fixed')) {
unPadBottom = ( pageitem.outerHeight() + 2 );
} else {
maxBottom -= ( pageitem.outerHeight() + 2 );
}
}
coords.winLeft = (inputOffset.left + ( inputWidth / 2 )) - ( diaWinWidth / 2 );
// Trap for small screens (center horizontally instead)
if ( docWinWidth < 450 ) {
coords.winLeft = (( docWinWidth / 2 ) - ( diaWinWidth / 2 ) );
}
coords.winTop = (inputOffset.top + ( inputHigh / 2)) - ( diaWinHigh / 2 );
// Not beyond bottom of page or on footer (not fixed)
if ( (coords.winTop + diaWinHigh) > maxBottom ) {
coords.winTop += ( maxBottom - ( coords.winTop + diaWinHigh ) );
}
// Not on the footer either (but only if it floats)
if ( unPadBottom > 0 && (( coords.winTop + diaWinHigh - docWinHighOff ) > (docWinHigh - unPadBottom)) ) {
coords.winTop = (( docWinHigh - unPadBottom + docWinHighOff - diaWinHigh ));
}
// Not on the header (not fixed)
if ( coords.winTop < minTop ) { coords.winTop = minTop; }
// Not on the floating header either (fixed)
if ( padTop > 0 && ( coords.winTop < ( docWinHighOff + padTop ) ) ) {
coords.winTop = docWinHighOff + padTop;
} else if ( docWinHighOff > minTop && docWinHighOff > coords.winTop ) {
// This one for non fixed scroll?
coords.winTop = docWinHighOff + 2;
}
}
return coords;
},
_fixArray: function(arr) {
var x = 0,
self = this,
exp = new RegExp('^([0-9]+)-([0-9]+)-([0-9]+)$'),
matches = null;
if ( $.isArray(arr) ) {
for ( x=0; x<arr.length; x++) {
matches = [0];
matches = exp.exec(arr[x]);
if ( matches.length === 4 ) {
arr[x] = matches[1] + '-' + self._zPad(parseInt(matches[2],10)) + '-' + self._zPad(parseInt(matches[3],10));
}
}
}
return arr;
},
_digitReplace: function(oper, direction) {
var start = 48,
end = 57,
adder = 1584,
i = null,
ch = null,
newd = '';
if ( direction === -1 ) {
start += adder;
end += adder;
adder = -1584;
}
for ( i=0; i<oper.length; i++ ) {
ch = oper.charCodeAt(i);
if ( ch >= start && ch <= end ) {
newd = newd + String.fromCharCode(ch+adder);
} else {
newd = newd + String.fromCharCode(ch);
}
}
return newd;
},
_makeDisplayIndic: function() {
var self = this,
o = this.options;
self.pickerContent.find('*').each(function() {
if ( $(this).children().length < 1 ) {
$(this).text(self._digitReplace($(this).text()));
} else if ( $(this).hasClass('ui-datebox-slideday') ) {
$(this).html(self._digitReplace($(this).html()));
}
});
self.pickerContent.find('input').each(function() {
$(this).val(self._digitReplace($(this).val()));
});
},
_zPad: function(number) {
// Pad a number with a zero, to make it 2 digits
return ( ( number < 10 ) ? "0" : "" ) + String(number);
},
_makeOrd: function (num) {
// Return an ordinal suffix (1st, 2nd, 3rd, etc)
var ending = num % 10;
if ( num > 9 && num < 21 ) { return 'th'; }
if ( ending > 3 ) { return 'th'; }
return ['th','st','nd','rd'][ending];
},
_isInt: function (s) {
// Bool, return is a number is an integer
return (s.toString().search(/^[0-9]+$/) === 0);
},
_getFirstDay: function(date) {
// Get the first DAY of the month (0-6)
return date.copymod([0],[0,0,1]).getDay();
},
_getRecDays: function(year, month, day) {
// Get the recurring Days of a week for 'year'-'month'
// (pass nulls for whatever the internal year and month are)
if ( month === null ) { month = this.theDate.getMonth()+1; }
if ( year === null ) { year = this.theDate.getFullYear(); }
var self = this,
tempDate = new Date(year, month-1, 1, 0, 0, 0, 0),
dates = [], i;
if ( tempDate.getDay() > day ) {
tempDate.setDate(8 - (tempDate.getDay() - day));
} else if ( tempDate.getDay() < day ) {
tempDate.setDate(1 + (day - tempDate.getDay()));
}
dates[0] = tempDate.getISO();
for ( i = 1; i<6; i++ ) {
tempDate.setDate(tempDate.getDate() + 7);
if ( (tempDate.getMonth()+1) === month ) {
dates[i] = tempDate.getISO();
}
}
return dates;
},
_getLastDate: function(date) {
// Get the last DATE of the month (28,29,30,31)
return 32 - date.copymod([0],[0,0,32,13]).getDate();
},
_getLastDateBefore: function(date) {
// Get the last DATE of the PREVIOUS month (28,29,30,31)
return 32 - date.copymod([0,-1],[0,0,32,13]).getDate();
},
_formatter: function(format, date) {
var self = this,
o = this.options;
// Format the output date or time (not duration)
if ( ! format.match(/%/) ) {
format = format.replace('HH', this._zPad(date.getHours()));
format = format.replace('GG', date.getHours());
format = format.replace('hh', this._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12))));
format = format.replace('gg', ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))));
format = format.replace('ii', this._zPad(date.getMinutes()));
format = format.replace('ss', this._zPad(date.getSeconds()));
format = format.replace('AA', ((date.getHours() < 12)?this.options.meridiemLetters[0].toUpperCase():this.options.meridiemLetters[1].toUpperCase()));
format = format.replace('aa', ((date.getHours() < 12)?this.options.meridiemLetters[0].toLowerCase():this.options.meridiemLetters[1].toLowerCase()));
format = format.replace('SS', this._makeOrd(date.getDate()));
format = format.replace('YYYY', date.getFullYear());
format = format.replace('mmmm', this.options.lang[this.options.useLang].monthsOfYearShort[date.getMonth()] );
format = format.replace('mmm', this.options.lang[this.options.useLang].monthsOfYear[date.getMonth()] );
format = format.replace('MM', this._zPad(date.getMonth() + 1));
format = format.replace('mm', date.getMonth() + 1);
format = format.replace('dddd', this.options.lang[this.options.useLang].daysOfWeekShort[date.getDay()] );
format = format.replace('ddd', this.options.lang[this.options.useLang].daysOfWeek[date.getDay()] );
format = format.replace('DD', this._zPad(date.getDate()));
format = format.replace('dd', date.getDate());
format = format.replace('UU', date.getEpoch());
} else {
format = format.replace(/%(0|-)*([a-z])/gi, function(match, pad, oper, offset, s) {
switch ( oper ) {
case '%': // Literal %
return '%';
case 'a': // Short Day
return o.lang[o.useLang].daysOfWeekShort[date.getDay()];
case 'A': // Full Day of week
return o.lang[o.useLang].daysOfWeek[date.getDay()];
case 'b': // Short month
return o.lang[o.useLang].monthsOfYearShort[date.getMonth()];
case 'B': // Full month
return o.lang[o.useLang].monthsOfYear[date.getMonth()];
case 'C': // Century
return date.getFullYear().toString().substr(0,2);
case 'd': // Day of month
return (( pad === '-' ) ? date.getDate() : self._zPad(date.getDate()));
case 'H': // Hour (01..23)
case 'k':
return (( pad === '-' ) ? date.getHours() : self._zPad(date.getHours()));
case 'I': // Hour (01..12)
case 'l':
return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : self._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12))));
case 'm': // Month
return (( pad === '-' ) ? date.getMonth()+1 : self._zPad(date.getMonth()+1));
case 'M': // Minutes
return (( pad === '-' ) ? date.getMinutes() : self._zPad(date.getMinutes()));
case 'p': // AM/PM (ucase)
return ((date.getHours() < 12)?o.meridiemLetters[0].toUpperCase():o.meridiemLetters[1].toUpperCase());
case 'P': // AM/PM (lcase)
return ((date.getHours() < 12)?o.meridiemLetters[0].toLowerCase():o.meridiemLetters[1].toLowerCase());
case 's': // Unix Seconds
return date.getEpoch;
case 'S': // Seconds
return (( pad === '-' ) ? date.getSeconds() : self._zPad(date.getSeconds()));
case 'w': // Day of week
return date.getDay();
case 'y': // Year (2 digit)
return date.getFullYear().toString().substr(2,2);
case 'Y': // Year (4 digit)
return date.getFullYear();
case 'o': // Ordinals
return self._makeOrd(date.getDate());
default:
return match;
}
});
}
if ( this.options.lang[this.options.useLang].useArabicIndic === true ) {
format = this._digitReplace(format);
}
return format;
},
_formatHeader: function(date) {
// Shortcut function to return headerFormat date/time format
if ( this.options.headerFormat !== false ) {
return this._formatter(this.options.headerFormat, date);
} else {
return this._formatter(this.options.lang[this.options.useLang].headerFormat, date);
}
},
_formatDate: function(date) {
// Shortcut function to return dateFormat date/time format
return this._formatter(this.options.dateOutput, date);
},
_formatTime: function(date) {
// Shortcut to return formatted time, also handles duration
var self = this,
dur_collapse = [false,false,false], adv, exp_format, i, j,
format = this.options.durationFormat,
dur_comps = [0,0,0,0];
if ( this.options.mode === 'durationbox' ) {
adv = this.options.durationFormat;
adv = adv.replace(/ddd/g, '.+?');
adv = adv.replace(/DD|ss|hh|ii/g, '([0-9Dhis]+)');
adv = new RegExp('^' + adv + '$');
exp_format = adv.exec(this.options.durationFormat);
i = self.theDate.getEpoch() - self.initDate.getEpoch(); j = i;
dur_comps[0] = parseInt( i / (60*60*24),10); i = i - (dur_comps[0]*60*60*24); // Days
dur_comps[1] = parseInt( i / (60*60),10); i = i - (dur_comps[1]*60*60); // Hours
dur_comps[2] = parseInt( i / (60),10); i = i - (dur_comps[2]*60); // Minutes
dur_comps[3] = i; // Seconds
if ( ! exp_format[0].match(/DD/) ) { dur_collapse[0] = true; dur_comps[1] = dur_comps[1] + (dur_comps[0]*24);}
if ( ! exp_format[0].match(/hh/) ) { dur_collapse[1] = true; dur_comps[2] = dur_comps[2] + (dur_comps[1]*60);}
if ( ! exp_format[0].match(/ii/) ) { dur_collapse[2] = true; dur_comps[3] = dur_comps[3] + (dur_comps[2]*60);}
format = format.replace('DD', dur_comps[0]);
format = format.replace('ddd', ((dur_comps[0] > 1)?this.options.lang[this.options.useLang].durationDays[1]:this.options.lang[this.options.useLang].durationDays[0]));
format = format.replace('hh', self._zPad(dur_comps[1]));
format = format.replace('ii', self._zPad(dur_comps[2]));
format = format.replace('ss', self._zPad(dur_comps[3]));
if ( this.options.lang[this.options.useLang].useArabicIndic === true ) {
return this._digitReplace(format);
} else {
return format;
}
} else {
return this._formatter(self.options.timeOutput, date);
}
},
_makeDate: function (str) {
// Date Parser
str = $.trim(str);
var o = this.options,
self = this,
adv = null,
exp_input = null,
exp_format = null,
exp_temp = null,
date = new Date(),
dur_collapse = [false,false,false],
found_date = [date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),0],
i;
if ( o.lang[this.options.useLang].useArabicIndic === true ) {
str = this._digitReplace(str, -1);
}
if ( o.mode === 'durationbox' ) {
adv = o.durationFormat;
adv = adv.replace(/ddd/g, '.+?');
adv = adv.replace(/DD|ss|hh|ii/g, '([0-9Dhis]+)');
adv = new RegExp('^' + adv + '$');
exp_input = adv.exec(str);
exp_format = adv.exec(o.durationFormat);
if ( exp_input === null || exp_input.length !== exp_format.length ) {
if ( typeof o.defaultPickerValue === "number" && o.defaultPickerValue > 0 ) {
return new Date((self.initDate.getEpoch() + parseInt(o.defaultPickerValue,10))*1000);
} else {
return new Date(self.initDate.getTime());
}
} else {
exp_temp = self.initDate.getEpoch();
for ( i=0; i<exp_input.length; i++ ) { //0y 1m 2d 3h 4i 5s
if ( exp_format[i].match(/^DD$/i) ) { exp_temp = exp_temp + (parseInt(exp_input[i],10)*60*60*24); }
if ( exp_format[i].match(/^hh$/i) ) { exp_temp = exp_temp + (parseInt(exp_input[i],10)*60*60); }
if ( exp_format[i].match(/^ii$/i) ) { exp_temp = exp_temp + (parseInt(exp_input[i],10)*60); }
if ( exp_format[i].match(/^ss$/i) ) { exp_temp = exp_temp + (parseInt(exp_input[i],10)); }
}
return new Date((exp_temp*1000));
}
} else {
if ( o.mode === 'timebox' || o.mode === 'timeflipbox' ) { adv = o.timeOutput; } else { adv = o.dateOutput; }
if ( adv.match(/%/) ) {
adv = adv.replace(/%(0|-)*([a-z])/gi, function(match, pad, oper, offset, s) {
switch (oper) {
case 'p':
case 'P':
case 'b':
case 'B': return '(' + match + '|' +'.+?' + ')';
case 'H':
case 'k':
case 'I':
case 'l':
case 'm':
case 'M':
case 'S':
case 'd': return '(' + match + '|' + (( pad === '-' ) ? '[0-9]{1,2}' : '[0-9]{2}') + ')';
case 's': return '(' + match + '|' +'[0-9]+' + ')';
case 'y': return '(' + match + '|' +'[0-9]{2}' + ')';
case 'Y': return '(' + match + '|' +'[0-9]{1,4}' + ')';
default: return '.+?';
}
});
adv = new RegExp('^' + adv + '$');
exp_input = adv.exec(str);
if ( o.mode === 'timebox' || o.mode === 'timeflipbox' ) {
exp_format = adv.exec(o.timeOutput); // If time, use timeOutput as expected format
} else {
exp_format = adv.exec(o.dateOutput); // If date, use dateFormat as expected format
}
if ( exp_input === null || exp_input.length !== exp_format.length ) {
if ( o.defaultPickerValue !== false ) {
if ( $.isArray(o.defaultPickerValue) && o.defaultPickerValue.length === 3 ) {
if ( o.mode === 'timebox' || o.mode === 'timeflipbox' ) {
return new Date(found_date[0], found_date[1], found_date[2], o.defaultPickerValue[0], o.defaultPickerValue[1], o.defaultPickerValue[2], 0);
}
else {
return new Date(o.defaultPickerValue[0], o.defaultPickerValue[1], o.defaultPickerValue[2], 0, 0, 0, 0);
}
}
else if ( typeof o.defaultPickerValue === "number" ) {
return new Date(o.defaultPickerValue * 1000);
}
else {
if ( o.mode === 'timebox' || o.mode === 'timeflipbox' ) {
exp_temp = o.defaultPickerValue.split(':');
if ( exp_temp.length === 3 ) {
date = new Date(found_date[0], found_date[1], found_date[2], parseInt(exp_temp[0],10),parseInt(exp_temp[1],10),parseInt(exp_temp[2],10),0);
if ( isNaN(date.getDate()) ) { date = new Date(); }
}
}
else {
exp_temp = o.defaultPickerValue.split('-');
if ( exp_temp.length === 3 ) {
date = new Date(parseInt(exp_temp[0],10),parseInt(exp_temp[1],10)-1,parseInt(exp_temp[2],10),0,0,0,0);
if ( isNaN(date.getDate()) ) { date = new Date(); }
}
}
}
}
} else {
for ( i=0; i<exp_input.length; i++ ) { //0y 1m 2d 3h 4i 5a 6epoch
if ( exp_format[i] === '%s' ) { found_date[6] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^%.*S$/) ) { found_date[5] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^%.*M$/) ) { found_date[4] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^%.*(H|k|I|l)$/) ) { found_date[3] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^%.*d$/) ) { found_date[2] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^%.*m$/) ) { found_date[1] = parseInt(exp_input[i],10)-1; }
if ( exp_format[i].match(/^%.*Y$/) ) { found_date[0] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^%.*y$/) ) {
if ( o.afterToday === true ) {
found_date[0] = parseInt('20' + exp_input[i],10);
} else {
if ( parseInt(exp_input[i],10) < 38 ) {
found_date[0] = parseInt('20' + exp_input[i],10);
} else {
found_date[0] = parseInt('19' + exp_input[i],10);
}
}
}
if ( exp_format[i].match(/^%(0|-)*(p|P)$/) ) {
if ( exp_input[i].toLowerCase().charAt(0) === 'a' && found_date[3] === 12 ) {
found_date[3] = 0;
} else if ( exp_input[i].toLowerCase().charAt(0) === 'p' && found_date[3] !== 12 ) {
found_date[3] = found_date[3] + 12;
}
}
if ( exp_format[i] === '%B' ) {
exp_temp = $.inArray(exp_input[i], o.lang[o.useLang].monthsOfYear);
if ( exp_temp > -1 ) { found_date[1] = exp_temp; }
}
if ( exp_format[i] === '%b' ) {
exp_temp = $.inArray(exp_input[i], o.lang[o.useLang].monthsOfYearShort);
if ( exp_temp > -1 ) { found_date[1] = exp_temp; }
}
}
}
if ( exp_format[0].match(/%s/) ) {
date = new Date(found_date[6] * 1000);
}
else if ( exp_format[0].match(/%(.)*(I|l|H|k|s|M)/) ) {
date = new Date(found_date[0], found_date[1], found_date[2], found_date[3], found_date[4], found_date[5], 0);
if ( found_date[0] < 100 ) { date.setFullYear(found_date[0]); }
} else {
date = new Date(found_date[0], found_date[1], found_date[2], 0, 0, 0, 0); // Normalize time for raw dates
if ( found_date[0] < 100 ) { date.setFullYear(found_date[0]); }
}
return date;
} else {
adv = adv.replace(/dddd|mmmm/g, '(.+?)');
adv = adv.replace(/ddd|SS/g, '.+?');
adv = adv.replace(/mmm/g, '(.+?)');
adv = adv.replace(/ *AA/ig, ' *(.*?)');
adv = adv.replace(/yyyy|dd|mm|gg|hh|ii/ig, '([0-9yYdDmMgGhHi]+)');
adv = adv.replace(/ss|UU/g, '([0-9sU]+)');
adv = new RegExp('^' + adv + '$');
exp_input = adv.exec(str);
if ( o.mode === 'timebox' || o.mode === 'timeflipbox' ) {
exp_format = adv.exec(o.timeOutput); // If time, use timeOutput as expected format
} else {
exp_format = adv.exec(o.dateOutput); // If date, use dateFormat as expected format
}
if ( exp_input === null || exp_input.length !== exp_format.length ) {
if ( o.defaultPickerValue !== false ) {
if ( $.isArray(o.defaultPickerValue) && o.defaultPickerValue.length === 3 ) {
if ( o.mode === 'timebox' || o.mode === 'timeflipbox' ) {
return new Date(found_date[0], found_date[1], found_date[2], o.defaultPickerValue[0], o.defaultPickerValue[1], o.defaultPickerValue[2], 0);
}
else {
return new Date(o.defaultPickerValue[0], o.defaultPickerValue[1], o.defaultPickerValue[2], 0, 0, 0, 0);
}
}
else if ( typeof o.defaultPickerValue === "number" ) {
return new Date(o.defaultPickerValue * 1000);
}
else {
if ( o.mode === 'timebox' || o.mode === 'timeflipbox' ) {
exp_temp = o.defaultPickerValue.split(':');
if ( exp_temp.length === 3 ) {
date = new Date(found_date[0], found_date[1], found_date[2], parseInt(exp_temp[0],10),parseInt(exp_temp[1],10),parseInt(exp_temp[2],10),0);
if ( isNaN(date.getDate()) ) { date = new Date(); }
}
}
else {
exp_temp = o.defaultPickerValue.split('-');
if ( exp_temp.length === 3 ) {
date = new Date(parseInt(exp_temp[0],10),parseInt(exp_temp[1],10)-1,parseInt(exp_temp[2],10),0,0,0,0);
if ( isNaN(date.getDate()) ) { date = new Date(); }
}
}
}
}
} else {
for ( i=0; i<exp_input.length; i++ ) { //0y 1m 2d 3h 4i 5a 6epoch
if ( exp_format[i].match(/^UU$/ ) ) { found_date[6] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^gg$/i) ) { found_date[3] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^hh$/i) ) { found_date[3] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^ii$/i) ) { found_date[4] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^ss$/ ) ) { found_date[5] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^dd$/i) ) { found_date[2] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^mm$/i) ) { found_date[1] = parseInt(exp_input[i],10)-1; }
if ( exp_format[i].match(/^yyyy$/i) ) { found_date[0] = parseInt(exp_input[i],10); }
if ( exp_format[i].match(/^AA$/i) ) {
if ( exp_input[i].toLowerCase().charAt(0) === 'a' && found_date[3] === 12 ) {
found_date[3] = 0;
} else if ( exp_input[i].toLowerCase().charAt(0) === 'p' && found_date[3] !== 12 ) {
found_date[3] = found_date[3] + 12;
}
}
if ( exp_format[i].match(/^mmm$/i) ) {
exp_temp = $.inArray(exp_input[i], o.lang[o.useLang].monthsOfYear);
if ( exp_temp > -1 ) { found_date[1] = exp_temp; }
}
if ( exp_format[i].match(/^mmmm$/i) ) {
exp_temp = $.inArray(exp_input[i], o.lang[o.useLang].monthsOfYearShort);
if ( exp_temp > -1 ) { found_date[1] = exp_temp; }
}
}
}
if ( exp_format[0].match(/UU/) ) {
return new Date(found_date[6] * 1000);
}
else if ( exp_format[0].match(/G|g|i|s|H|h|A/) ) {
return new Date(found_date[0], found_date[1], found_date[2], found_date[3], found_date[4], found_date[5], 0);
} else {
return new Date(found_date[0], found_date[1], found_date[2], 0, 0, 0, 0); // Normalize time for raw dates
}
}
}
},
_hoover: function(item) {
// Hover toggle class, for calendar
$(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme'));
},
_offset: function(mode, amount, update) {
// Compute a date/time offset.
// update = false to prevent controls refresh
var self = this,
o = this.options,
ok = false;
if ( typeof(update) === "undefined" ) { update = true; }
self.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount});
switch(mode) {
case 'y': ok = true; break;
case 'm':
if ( o.rolloverMode.m || ( self.theDate.getMonth() + amount < 12 && self.theDate.getMonth() + amount > -1 ) ) {
ok = true;
}
break;
case 'd':
if ( o.rolloverMode.d || (
self.theDate.getDate() + amount > 0 &&
self.theDate.getDate() + amount < (self._getLastDate(self.theDate) + 1) ) ) {
ok = true;
}
break;
case 'h':
if ( o.rolloverMode.h || (
self.theDate.getHours() + amount > -1 &&
self.theDate.getHours() + amount < 24 ) ) {
ok = true;
}
break;
case 'i':
if ( o.rolloverMode.i || (
self.theDate.getMinutes() + amount > -1 &&
self.theDate.getMinutes() + amount < 60 ) ) {
ok = true;
}
break;
case 's':
if ( o.rolloverMode.s || (
self.theDate.getSeconds() + amount > -1 &&
self.theDate.getSeconds() + amount < 60 ) ) {
ok = true;
}
break;
case 'a':
if ( self.pickerMeri.val() === o.meridiemLetters[0] ) {
self._offset('h',12,false);
} else {
self._offset('h',-12,false);
}
break;
}
if ( ok === true ) { self.theDate.adjust(mode,amount); }
if ( update === true ) { self._update(); }
},
_updateduration: function() {
// Update the duration contols when inputs are directly edited.
var self = this,
secs = self.initDate.getEpoch();
if ( !self._isInt(self.pickerDay.val()) ) { self.pickerDay.val(0); }
if ( !self._isInt(self.pickerHour.val()) ) { self.pickerHour.val(0); }
if ( !self._isInt(self.pickerMins.val()) ) { self.pickerMins.val(0); }
if ( !self._isInt(self.pickerSecs.val()) ) { self.pickerSecs.val(0); }
secs = secs + (parseInt(self.pickerDay.val(),10) * 60 * 60 * 24);
secs = secs + (parseInt(self.pickerHour.val(),10) * 60 * 60);
secs = secs + (parseInt(self.pickerMins.val(),10) * 60);
secs = secs + (parseInt(self.pickerSecs.val(),10));
self.theDate.setTime( secs * 1000 );
self._update();
},
_checkConstraints: function() {
var self = this,
testDate = null,
o = this.options;
self.dateOK = true;
if ( o.afterToday !== false ) {
testDate = new Date();
if ( self.theDate < testDate ) { self.theDate = testDate; }
}
if ( o.beforeToday !== false ) {
testDate = new Date();
if ( self.theDate > testDate ) { self.theDate = testDate; }
}
if ( o.maxDays !== false ) {
testDate = new Date();
testDate.adjust('d', o.maxDays);
if ( self.theDate > testDate ) { self.theDate = testDate; }
}
if ( o.minDays !== false ) {
testDate = new Date();
testDate.adjust('d', -1*o.minDays);
if ( self.theDate < testDate ) { self.theDate = testDate; }
}
if ( o.maxYear !== false ) {
testDate = new Date(o.maxYear, 0, 1);
testDate.adjust('d', -1);
if ( self.theDate > testDate ) { self.theDate = testDate; }
}
if ( o.minYear !== false ) {
testDate = new Date(o.minYear, 0, 1);
if ( self.theDate < testDate ) { self.theDate = testDate; }
}
if ( o.blackDates !== false ) {
if ( $.inArray(self.theDate.getISO(), o.blackDates) > -1 ) { self.dateOK = false; }
}
if ( o.blackDays !== false ) {
if ( $.inArray(self.theDate.getDay(), o.blackDays) > -1 ) { self.dateOK = false; }
}
if ( $.inArray(o.mode, ['timebox','durationbox','timeflipbox']) > -1 ) { self.dateOK = true; }
},
_orientChange: function(e) {
var self = e.data.widget,
o = e.data.widget.options,
coords = e.data.widget._getCoords(e.data.widget); // Get the coords now, since we need em.
e.stopPropagation();
if ( ! self.pickerContent.is(':visible') || o.useDialog === true ) {
return false; // Not open, or in a dialog (let jQM do it)
} else {
if ( o.fullScreen == true && ( coords.width < 400 || o.fullScreenForce === true ) ) {
self.pickerContent.css({'top': coords.fullTop, 'left': coords.fullLeft, 'height': coords.high, 'width': coords.width, 'maxWidth': coords.width });
} else {
self.pickerContent.css({'top': coords.winTop, 'left': coords.winLeft});
}
}
},
_update: function() {
// Update the display on date change
var self = this,
o = self.options,
testDate = null,
i, gridWeek, gridDay, skipThis, thisRow, y, cTheme, inheritDate, thisPRow, tmpVal, disVal,
interval = {'d': 60*60*24, 'h': 60*60, 'i': 60, 's':1},
calmode = {};
self.input.trigger('datebox', {'method':'refresh'});
/* BEGIN:DURATIONBOX */
if ( o.mode === 'durationbox' ) {
i = self.theDate.getEpoch() - self.initDate.getEpoch();
if ( i<0 ) { i = 0; self.theDate.setTime(self.initDate.getTime()); }
o.lastDuration = i; // Let the number of seconds be sort of public.
/* DAYS */
y = parseInt( i / interval.d,10);
i = i - ( y * interval.d );
self.pickerDay.val(y);
/* HOURS */
y = parseInt( i / interval.h, 10);
i = i - ( y * interval.h );
self.pickerHour.val(y);
/* MINS AND SECS */
y = parseInt( i / interval.i, 10);
i = i - ( y * interval.i);
self.pickerMins.val(y);
self.pickerSecs.val(parseInt(i,10));
}
/* END:DURATIONBOX */
/* BEGIN:TIMEBOX */
if ( o.mode === 'timebox' ) {
if ( o.minuteStep !== 1 ) {
i = self.theDate.getMinutes() % o.minuteStep;
if ( i !== 0 ) { self.theDate.adjust('m', -1*i); }
}
self.pickerMins.val(self._zPad(self.theDate.getMinutes()));
if ( o.lang[o.useLang].timeFormat === 12 || o.timeFormatOverride === 12 ) { // Handle meridiems
if ( self.theDate.getHours() > 11 ) {
self.pickerMeri.val(o.meridiemLetters[1]);
if ( self.theDate.getHours() === 12 ) {
self.pickerHour.val(12);
} else {
self.pickerHour.val(self.theDate.getHours() - 12);
}
} else {
self.pickerMeri.val(o.meridiemLetters[0]);
if ( self.theDate.getHours() === 0 ) {
self.pickerHour.val(12);
} else {
self.pickerHour.val(self.theDate.getHours());
}
}
} else {
self.pickerHour.val(self.theDate.getHours());
}
}
/* END:TIMEBOX */
/* BEGIN:FLIPBOX */
if ( o.mode === 'flipbox' || o.mode === 'timeflipbox' ) {
self._checkConstraints();
inheritDate = self._makeDate(self.input.val());
self.controlsHeader.empty().html( self._formatHeader(self.theDate) );
for ( y=0; y<o.fieldsOrder.length; y++ ) {
tmpVal = true;
switch (o.fieldsOrder[y]) {
case 'y':
thisRow = self.pickerYar.find('ul');
thisRow.empty();
for ( i=-15; i<16; i++ ) {
cTheme = ((inheritDate.getFullYear()===(self.theDate.getFullYear() + i))?o.pickPageHighButtonTheme:o.pickPageFlipButtonTheme);
if ( i === 0 ) { cTheme = o.pickPageButtonTheme; }
$("<li>", { 'class' : 'ui-body-'+cTheme, 'style':((tmpVal===true)?'margin-top: -453px':'') })
.html("<span>"+(self.theDate.getFullYear() + i)+"</span>")
.appendTo(thisRow);
tmpVal = false;
}
break;
case 'm':
thisRow = self.pickerMon.find('ul');
thisRow.empty();
for ( i=-12; i<13; i++ ) {
testDate = new Date(self.theDate.getFullYear(), self.theDate.getMonth(), 1);
testDate.adjust('m',i);
cTheme = ( inheritDate.getMonth() === testDate.getMonth() && inheritDate.getYear() === testDate.getYear() ) ? o.pickPageHighButtonTheme : o.pickPageFlipButtonTheme;
if ( i === 0 ) { cTheme = o.pickPageButtonTheme; }
$("<li>", { 'class' : 'ui-body-'+cTheme, 'style':((tmpVal===true)?'margin-top: -357px':'') })
.html("<span>"+o.lang[o.useLang].monthsOfYearShort[testDate.getMonth()]+"</span>")
.appendTo(thisRow);
tmpVal = false;
}
break;
case 'd':
thisRow = self.pickerDay.find('ul');
thisRow.empty();
for ( i=-15; i<16; i++ ) {
testDate = self.theDate.copy();
testDate.adjust('d',i);
disVal = "";
if ( ( o.blackDates !== false && $.inArray(testDate.getISO(), o.blackDates) > -1 ) ||
( o.blackDays !== false && $.inArray(testDate.getDay(), o.blackDays) > -1 ) ) {
disVal = " ui-datebox-griddate-disable";
}
cTheme = ( inheritDate.getDate() === testDate.getDate() && inheritDate.getMonth() === testDate.getMonth() && inheritDate.getYear() === testDate.getYear() ) ? o.pickPageHighButtonTheme : o.pickPageFlipButtonTheme;
if ( i === 0 ) { cTheme = o.pickPageButtonTheme; }
$("<li>", { 'class' : 'ui-body-'+cTheme+disVal, 'style':((tmpVal===true)?'margin-top: -453px':'') })
.html("<span>"+testDate.getDate()+"</span>")
.appendTo(thisRow);
tmpVal = false;
}
break;
case 'h':
thisRow = self.pickerHour.find('ul');
thisRow.empty();
for ( i=-12; i<13; i++ ) {
testDate = self.theDate.copy();
testDate.adjust('h',i);
cTheme = ( i === 0 ) ? o.pickPageButtonTheme : o.pickPageFlipButtonTheme;
$("<li>", { 'class' : 'ui-body-'+cTheme, 'style':((tmpVal===true)?'margin-top: -357px':'') })
.html("<span>"+( ( o.lang[o.useLang].timeFormat === 12 || o.timeFormatOverride === 12 ) ? ( ( testDate.getHours() === 0 ) ? '12' : ( ( testDate.getHours() < 12 ) ? testDate.getHours() : ( ( testDate.getHours() === 12 ) ? '12' : (testDate.getHours()-12) ) ) ) : testDate.getHours() )+"</span>")
.appendTo(thisRow);
tmpVal = false;
}
break;
case 'i':
thisRow = self.pickerMins.find('ul');
thisRow.empty();
for ( i=-30; i<31; i++ ) {
if ( o.minuteStep > 1 ) { self.theDate.setMinutes(self.theDate.getMinutes() - (self.theDate.getMinutes() % o.minuteStep)); }
testDate = self.theDate.copy();
testDate.adjust('i',(i*o.minuteStep));
cTheme = ( i === 0 ) ? o.pickPageButtonTheme : o.pickPageFlipButtonTheme;
$("<li>", { 'class' : 'ui-body-'+cTheme, 'style':((tmpVal===true)?'margin-top: -933px':'') })
.html("<span>"+self._zPad(testDate.getMinutes())+"</span>")
.appendTo(thisRow);
tmpVal = false;
}
break;
case 'a':
thisRow = self.pickerMeri.find('ul');
thisRow.empty();
if ( self.theDate.getHours() > 11 ) {
tmpVal = '-65';
cTheme = [o.pickPageFlipButtonTheme, o.pickPageButtonTheme];
} else {
tmpVal = '-33';
cTheme = [o.pickPageButtonTheme, o.pickPageFlipButtonTheme];
}
$("<li>").appendTo(thisRow).clone().appendTo(thisRow);
$("<li>", { 'class' : 'ui-body-'+cTheme[0], 'style':'margin-top: '+tmpVal+'px' })
.html("<span>"+o.meridiemLetters[0]+"</span>")
.appendTo(thisRow);
$("<li>", { 'class' : 'ui-body-'+cTheme[1] })
.html("<span>"+o.meridiemLetters[1]+"</span>")
.appendTo(thisRow);
$("<li>").appendTo(thisRow).clone().appendTo(thisRow);
break;
}
}
}
/* END:FLIPBOX */
/* BEGIN:SLIDEBOX */
if ( o.mode === 'slidebox' ) {
self._checkConstraints();
inheritDate = self._makeDate(self.input.val());
self.controlsHeader.empty().html( self._formatHeader(self.theDate) );
self.controlsInput.empty();
self.controlsInput.delegate('.ui-datebox-sliderow-int>div', o.clickEvent, function(e) {
e.preventDefault();
self._offset($(this).parent().jqmData('rowtype'), parseInt($(this).jqmData('offset'),10));
});
self.controlsInput.delegate('.ui-datebox-sliderow-int>div', 'vmouseover vmouseout', function() {
self._hoover(this);
});
if ( o.wheelExists ) {
self.controlsInput.delegate('.ui-datebox-sliderow-int', 'mousewheel', function(e,d) {
e.preventDefault();
self._offset($(this).jqmData('rowtype'), ((d>0)?1:-1));
});
}
if ( o.swipeEnabled ) {
self.controlsInput.delegate('.ui-datebox-sliderow-int', self.START_DRAG, function(e) {
if ( !self.dragMove ) {
self.dragMove = true;
self.dragTarget = $(this);
self.dragPos = parseInt(self.dragTarget.css('marginLeft').replace(/px/i, ''),10);
self.dragStart = self.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX;
self.dragEnd = false;
e.stopPropagation();
e.preventDefault();
}
});
}
for ( y=0; y<o.fieldsOrder.length; y++ ) {
thisPRow = $("<div>").jqmData('rowtype', o.fieldsOrder[y]);
thisRow = $("<div>", {'class': 'ui-datebox-sliderow-int'}).jqmData('rowtype',o.fieldsOrder[y]).appendTo(thisPRow);
if ( o.lang[o.useLang].isRTL === true ) { thisRow.css('direction', 'rtl'); }
switch (o.fieldsOrder[y]) {
case 'y':
thisPRow.addClass('ui-datebox-sliderow-ym');
thisRow.css('marginLeft', '-333px');
for ( i=-5; i<6; i++ ) {
cTheme = ((inheritDate.getFullYear()===(self.theDate.getFullYear() + i))?o.pickPageHighButtonTheme:o.pickPageSlideButtonTheme);
if ( i === 0 ) { cTheme = o.pickPageButtonTheme; }
$("<div>", { 'class' : 'ui-datebox-slideyear ui-corner-all ui-btn-up-'+cTheme })
.html(self.theDate.getFullYear() + i)
.jqmData('offset', i)
.jqmData('theme', cTheme)
.appendTo(thisRow);
}
break;
case 'm':
thisPRow.addClass('ui-datebox-sliderow-ym');
thisRow.css('marginLeft', '-204px');
for ( i=-6; i<7; i++ ) {
testDate = new Date(self.theDate.getFullYear(), self.theDate.getMonth(), 1);
testDate.adjust('m',i);
cTheme = ( inheritDate.getMonth() === testDate.getMonth() && inheritDate.getYear() === testDate.getYear() ) ? o.pickPageHighButtonTheme : o.pickPageSlideButtonTheme;
if ( i === 0 ) { cTheme = o.pickPageButtonTheme; }
$("<div>", { 'class' : 'ui-datebox-slidemonth ui-corner-all ui-btn-up-'+cTheme })
.jqmData('offset', i)
.jqmData('theme', cTheme)
.html(o.lang[o.useLang].monthsOfYearShort[testDate.getMonth()])
.appendTo(thisRow);
}
break;
case 'd':
thisPRow.addClass('ui-datebox-sliderow-d');
thisRow.css('marginLeft', '-386px');
for ( i=-15; i<16; i++ ) {
testDate = self.theDate.copy();
testDate.adjust('d',i);
disVal = "";
if ( ( o.blackDates !== false && $.inArray(testDate.getISO(), o.blackDates) > -1 ) ||
( o.blackDays !== false && $.inArray(testDate.getDay(), o.blackDays) > -1 ) ) {
disVal = " ui-datebox-griddate-disable";
}
cTheme = ( inheritDate.getDate() === testDate.getDate() && inheritDate.getMonth() === testDate.getMonth() && inheritDate.getYear() === testDate.getYear() ) ? o.pickPageHighButtonTheme : o.pickPageSlideButtonTheme;
if ( i === 0 ) { cTheme = o.pickPageButtonTheme; }
$("<div>", { 'class' : 'ui-datebox-slideday ui-corner-all ui-btn-up-'+cTheme+disVal })
.jqmData('offset', i)
.jqmData('theme', cTheme)
.html(testDate.getDate() + '<br /><span class="ui-datebox-slidewday">' + o.lang[o.useLang].daysOfWeekShort[testDate.getDay()] + '</span>')
.appendTo(thisRow);
}
break;
case 'h':
thisPRow.addClass('ui-datebox-sliderow-hi');
thisRow.css('marginLeft', '-284px');
for ( i=-12; i<13; i++ ) {
testDate = self.theDate.copy();
testDate.adjust('h',i);
cTheme = ( i === 0 ) ? o.pickPageButtonTheme : o.pickPageSlideButtonTheme;
$("<div>", { 'class' : 'ui-datebox-slidehour ui-corner-all ui-btn-up-'+cTheme })
.jqmData('offset', i)
.jqmData('theme', cTheme)
.html(( ( o.lang[o.useLang].timeFormat === 12 || o.timeFormatOverride === 12 ) ? ( ( testDate.getHours() === 0 ) ? '12<span class="ui-datebox-slidewday">AM</span>' : ( ( testDate.getHours() < 12 ) ? testDate.getHours() + '<span class="ui-datebox-slidewday">AM</span>' : ( ( testDate.getHours() === 12 ) ? '12<span class="ui-datebox-slidewday">PM</span>' : (testDate.getHours()-12) + '<span class="ui-datebox-slidewday">PM</span>') ) ) : testDate.getHours() ))
.appendTo(thisRow);
}
break;
case 'i':
thisPRow.addClass('ui-datebox-sliderow-hi');
thisRow.css('marginLeft', '-896px');
for ( i=-30; i<31; i++ ) {
testDate = self.theDate.copy();
testDate.adjust('i',i);
cTheme = ( i === 0 ) ? o.pickPageButtonTheme : o.pickPageSlideButtonTheme;
$("<div>", { 'class' : 'ui-datebox-slidemins ui-corner-all ui-btn-up-'+cTheme })
.jqmData('offset', i)
.jqmData('theme', cTheme)
.html(self._zPad(testDate.getMinutes()))
.appendTo(thisRow);
}
break;
}
thisPRow.appendTo(self.controlsInput);
}
}
/* END:SLIDEBOX */
/* BEGIN:DATEBOX */
if ( o.mode === 'datebox' ) {
self._checkConstraints();
self.controlsHeader.empty().html( self._formatHeader(self.theDate) );
self.pickerMon.val(self.theDate.getMonth() + 1);
self.pickerDay.val(self.theDate.getDate());
self.pickerYar.val(self.theDate.getFullYear());
if ( self.dateOK !== true ) {
self.controlsInput.find('input').addClass('ui-datebox-griddate-disable');
} else {
self.controlsInput.find('.ui-datebox-griddate-disable').removeClass('ui-datebox-griddate-disable');
}
}
/* END:DATEBOX */
/* BEGIN:CALBOX */
if ( o.mode === 'calbox' ) { // Meat and potatos - make the calendar grid.
self.controlsInput.empty().html( o.lang[o.useLang].monthsOfYear[self.theDate.getMonth()] + " " + self.theDate.getFullYear() );
self.controlsPlus.empty();
calmode = {'today': -1, 'highlightDay': -1, 'presetDay': -1, 'nexttoday': 1,
'thisDate': new Date(), 'maxDate': new Date(), 'minDate': new Date(), 'startDay': false,
'currentMonth': false, 'weekMode': 0, 'weekDays': null, 'thisTheme': o.pickPageButtonTheme };
calmode.start = self._getFirstDay(self.theDate);
calmode.end = self._getLastDate(self.theDate);
calmode.lastend = self._getLastDateBefore(self.theDate);
calmode.presetDate = self._makeDate(self.input.val());
if ( o.calStartDay !== false || typeof o.lang[o.useLang].calStartDay === "number" ) {
if ( o.calStartDay !== false ) {
calmode.start = calmode.start - o.calStartDay;
calmode.startDay = o.calStartDay;
} else {
calmode.start = calmode.start - o.lang[o.useLang].calStartDay;
calmode.startDay = o.lang[o.useLang].calStartDay;
}
if ( calmode.start < 0 ) { calmode.start = calmode.start + 7; }
}
calmode.prevtoday = calmode.lastend - (calmode.start - 1);
calmode.checkDates = ( o.enableDates === false && ( o.afterToday !== false || o.beforeToday !== false || o.notToday !== false || o.maxDays !== false || o.minDays !== false || o.blackDates !== false || o.blackDays !== false ) );
if ( calmode.thisDate.getMonth() === self.theDate.getMonth() && calmode.thisDate.getFullYear() === self.theDate.getFullYear() ) { calmode.currentMonth = true; calmode.highlightDay = calmode.thisDate.getDate(); }
if ( calmode.presetDate.getComp() === self.theDate.getComp() ) { calmode.presetDay = calmode.presetDate.getDate(); }
self.calNoPrev = false; self.calNoNext = false;
if ( o.afterToday === true &&
( calmode.currentMonth === true || ( calmode.thisDate.getMonth() >= self.theDate.getMonth() && self.theDate.getFullYear() === calmode.thisDate.getFullYear() ) ) ) {
self.calNoPrev = true; }
if ( o.beforeToday === true &&
( calmode.currentMonth === true || ( calmode.thisDate.getMonth() <= self.theDate.getMonth() && self.theDate.getFullYear() === calmode.thisDate.getFullYear() ) ) ) {
self.calNoNext = true; }
if ( o.minDays !== false ) {
calmode.minDate.adjust('d', -1*o.minDays);
if ( self.theDate.getFullYear() === calmode.minDate.getFullYear() && self.theDate.getMonth() <= calmode.minDate.getMonth() ) { self.calNoPrev = true;}
}
if ( o.maxDays !== false ) {
calmode.maxDate.adjust('d', o.maxDays);
if ( self.theDate.getFullYear() === calmode.maxDate.getFullYear() && self.theDate.getMonth() >= calmode.maxDate.getMonth() ) { self.calNoNext = true;}
}
if ( o.calShowDays ) {
if ( o.lang[o.useLang].daysOfWeekShort.length < 8 ) { o.daysOfWeekShort = o.lang[o.useLang].daysOfWeekShort.concat(o.lang[o.useLang].daysOfWeekShort); }
calmode.weekDays = $("<div>", {'class':'ui-datebox-gridrow'}).appendTo(self.controlsPlus);
if ( o.lang[o.useLang].isRTL === true ) { calmode.weekDays.css('direction', 'rtl'); }
for ( i=0; i<=6;i++ ) {
$("<div>"+o.lang[o.useLang].daysOfWeekShort[(i+calmode.startDay)%7]+"</div>").addClass('ui-datebox-griddate ui-datebox-griddate-empty ui-datebox-griddate-label').appendTo(calmode.weekDays);
}
}
if ( o.fixDateArrays === true ) {
o.blackDates = self._fixArray(o.blackDates);
o.highDates = self._fixArray(o.highDates);
o.highDatesAlt = self._fixArray(o.highDatesAlt);
o.enableDates = self._fixArray(o.enableDates);
}
for ( gridWeek=0; gridWeek<=5; gridWeek++ ) {
if ( gridWeek === 0 || ( gridWeek > 0 && (calmode.today > 0 && calmode.today <= calmode.end) ) ) {
thisRow = $("<div>", {'class': 'ui-datebox-gridrow'});
if ( o.lang[o.useLang].isRTL === true ) { thisRow.css('direction', 'rtl'); }
for ( gridDay=0; gridDay<=6; gridDay++) {
if ( gridDay === 0 ) { calmode.weekMode = ( calmode.today < 1 ) ? (calmode.prevtoday - calmode.lastend + o.calWeekModeFirstDay) : (calmode.today + o.calWeekModeFirstDay); }
if ( gridDay === calmode.start && gridWeek === 0 ) { calmode.today = 1; }
if ( calmode.today > calmode.end ) { calmode.today = -1; }
if ( calmode.today < 1 ) {
if ( o.calShowOnlyMonth ) {
$("<div>", {'class': 'ui-datebox-griddate ui-datebox-griddate-empty'}).appendTo(thisRow);
} else {
if ( o.enableDates !== false ) {
if (
( $.inArray(self.theDate.copymod([0,-1],[0,0,calmode.prevtoday]).getISO(), o.enableDates) > -1 ) ||
( $.inArray(self.theDate.copymod([0,1],[0,0,calmode.nexttoday]).getISO(), o.enableDates) > -1 ) ) {
skipThis = false;
} else { skipThis = true; }
} else {
if (
( o.afterToday !== false && gridWeek === 0 && calmode.thisDate.getMonth() >= self.theDate.getMonth()-1 && self.theDate.getFullYear() === calmode.thisDate.getFullYear() && calmode.thisDate.getDate() > calmode.prevtoday ) ||
( o.beforeToday !== false && gridWeek !== 0 && calmode.thisDate.getMonth() <= self.theDate.getMonth()+1 && self.theDate.getFullYear() === calmode.thisDate.getFullYear() && calmode.thisDate.getDate() < calmode.nexttoday ) ||
( o.blackDays !== false && $.inArray(gridDay, o.blackDays) > -1 ) ||
( o.blackDates !== false && $.inArray(self.theDate.copymod([0,-1],[0,0,calmode.prevtoday]).getISO(), o.blackDates) > -1 ) ||
( o.blackDates !== false && $.inArray(self.theDate.copymod([0,1],[0,0,calmode.nexttoday]).getISO(), o.blackDates) > -1 ) ) {
skipThis = true;
} else { skipThis = false; }
}
if ( gridWeek === 0 ) {
$("<div>"+String(calmode.prevtoday)+"</div>")
.addClass('ui-datebox-griddate ui-datebox-griddate-empty').appendTo(thisRow)
.jqmData('date', ((o.calWeekMode)?(calmode.weekMode+calmode.lastend):calmode.prevtoday))
.jqmData('enabled', (!skipThis && !self.calNoPrev))
.jqmData('month', -1);
calmode.prevtoday++;
} else {
$("<div>"+String(calmode.nexttoday)+"</div>")
.addClass('ui-datebox-griddate ui-datebox-griddate-empty').appendTo(thisRow)
.jqmData('date', ((o.calWeekMode)?calmode.weekMode:calmode.nexttoday))
.jqmData('enabled', (!skipThis && !self.calNoNext))
.jqmData('month', 1);
calmode.nexttoday++;
}
}
} else {
skipThis = false;
if ( o.enableDates ) {
if ( $.inArray(self.theDate.copymod([0],[0,0,calmode.today]).getISO(), o.enableDates) < 0 ) {
skipThis = true;
}
}
if ( calmode.checkDates ) {
if ( o.afterToday && calmode.thisDate.getComp() > (self.theDate.getComp()+calmode.today-self.theDate.getDate()) ) {
skipThis = true;
}
if ( !skipThis && o.beforeToday && calmode.thisDate.getComp() < (self.theDate.getComp()+calmode.today-self.theDate.getDate()) ) {
skipThis = true;
}
if ( !skipThis && o.notToday && calmode.today === calmode.highlightDay ) {
skipThis = true;
}
if ( !skipThis && o.maxDays !== false && calmode.maxDate.getComp() < (self.theDate.getComp()+calmode.today-self.theDate.getDate()) ) {
skipThis = true;
}
if ( !skipThis && o.minDays !== false && calmode.minDate.getComp() > (self.theDate.getComp()+calmode.today-self.theDate.getDate()) ) {
skipThis = true;
}
if ( !skipThis && ( o.blackDays !== false || o.blackDates !== false ) ) { // Blacklists
if (
( $.inArray(gridDay, o.blackDays) > -1 ) ||
( $.inArray(self.theDate.copymod([0],[0,0,calmode.today]).getISO(), o.blackDates) > -1 ) ) {
skipThis = true;
}
}
}
if ( o.calHighPicked && calmode.today === calmode.presetDay ) {
calmode.thisTheme = o.pickPageHighButtonTheme;
} else if ( o.calHighToday && calmode.today === calmode.highlightDay ) {
calmode.thisTheme = o.pickPageTodayButtonTheme;
} else if ( $.isArray(o.highDatesAlt) && ($.inArray(self.theDate.copymod([0],[0,0,calmode.today]).getISO(), o.highDatesAlt) > -1 ) ) {
calmode.thisTheme = o.pickPageOAHighButtonTheme;
} else if ( $.isArray(o.highDates) && ($.inArray(self.theDate.copymod([0],[0,0,calmode.today]).getISO(), o.highDates) > -1 ) ) {
calmode.thisTheme = o.pickPageOHighButtonTheme;
} else if ( $.isArray(o.highDays) && $.inArray(gridDay, o.highDays) > -1 ) {
calmode.thisTheme = o.pickPageODHighButtonTheme;
} else {
calmode.thisTheme = o.pickPageButtonTheme;
}
$("<div>"+String(calmode.today)+"</div>")
.addClass('ui-datebox-griddate ui-corner-all ui-btn-up-' + calmode.thisTheme + ((skipThis)?' ui-datebox-griddate-disable':''))
.jqmData('date', ((o.calWeekMode)?calmode.weekMode:calmode.today))
.jqmData('theme', calmode.thisTheme)
.jqmData('enabled', !skipThis)
.jqmData('month', 0)
.appendTo(thisRow);
calmode.today++;
}
}
}
thisRow.appendTo(self.controlsPlus);
}
self.controlsPlus.delegate('div.ui-datebox-griddate', o.clickEvent + ' vmouseover vmouseout', function(e) {
if ( e.type === o.clickEvent ) {
e.preventDefault();
if ( $(this).jqmData('enabled') ) {
if ( $(this).jqmData('month') < 0 ) {
self.theDate.adjust('m', -1);
self.theDate.setDate($(this).jqmData('date'));
} else if ( $(this).jqmData('month') > 0 ) {
self.theDate.setDate($(this).jqmData('date'));
if ( !o.calWeekMode ) { self.theDate.adjust('m',1); }
} else {
self.theDate.setDate($(this).jqmData('date'));
}
self.input.trigger('datebox', {'method':'set', 'value':self._formatDate(self.theDate), 'date':self.theDate});
self.input.trigger('datebox', {'method':'close'});
}
} else {
if ( $(this).jqmData('enabled') && typeof $(this).jqmData('theme') !== 'undefined' ) {
if ( o.calWeekMode !== false && o.calWeekModeHighlight === true ) {
$(this).parent().find('div').each(function() { self._hoover(this); });
} else { self._hoover(this); }
}
}
});
}
/* END:CALBOX */
if ( o.lang[this.options.useLang].useArabicIndic === true ) {
self._makeDisplayIndic();
}
},
_getLongOptions: function(element) {
var key, retty = {}, prefix, temp;
if ( $.mobile.ns == "" ) {
prefix = "datebox";
} else {
prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox';
}
for ( key in element.data() ) {
if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) {
temp = key.substr(prefix.length);
temp = temp.charAt(0).toLowerCase() + temp.slice(1);
retty[temp] = element.data(key);
}
}
return retty;
},
_create: function() {
// Create the widget, called automatically by widget system
// Trigger dateboxcreate
$( document ).trigger( "dateboxcreate" );
var self = this,
o = $.extend(this.options, this.element.jqmData('options')),
o = ((typeof this.element.jqmData('options') === 'undefined') ? $.extend(o, this._getLongOptions(this.element)) : o);
input = this.element,
thisTheme = ( o.theme === false && typeof($(self).jqmData('theme')) === 'undefined' ) ?
( ( typeof(input.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ?
o.defaultTheme : input.parentsUntil(':jqmData(theme)').parent().jqmData('theme') )
: o.theme,
focusedEl = input.wrap('<div class="ui-input-datebox ui-shadow-inset ui-corner-all ui-body-'+ thisTheme +'"></div>').parent(),
theDate = new Date(), // Internal date object, used for all operations
initDate = new Date(theDate.getTime()), // Initilization time - used for duration
// This is the button that is added to the original input
openbutton = $('<a href="#" class="ui-input-clear" title="'+((typeof o.lang[o.useLang].tooltip !== 'undefined')?o.lang[o.useLang].tooltip:o.lang.en.tooltip)+'">'+((typeof o.lang[o.useLang].tooltip !== 'undefined')?o.lang[o.useLang].tooltip:o.lang.en.tooltip)+'</a>')
.bind(o.clickEvent, function (e) {
e.preventDefault();
if ( !o.disabled ) { self.input.trigger('datebox', {'method': 'open'}); self.focusedEl.addClass('ui-focus'); }
setTimeout( function() { $(e.target).closest("a").removeClass($.mobile.activeBtnClass); }, 300);
})
.appendTo(focusedEl).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true})
.css({'vertical-align': 'middle', 'display': 'inline-block'}),
thisPage = input.closest('.ui-page'),
ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:'',
pickPage = $("<div data-"+ns+"role='dialog' class='ui-dialog-datebox' data-"+ns+"theme='" + ((o.forceInheritTheme === false ) ? o.pickPageTheme : thisTheme ) + "' >" +
"<div data-"+ns+"role='header' data-"+ns+"backbtn='false' data-"+ns+"theme='a'>" +
"<div class='ui-title'>PlaceHolder</div>"+
"</div>"+
"<div data-"+ns+"role='content'></div>"+
"</div>")
.appendTo( $.mobile.pageContainer )
.page().css('minHeight', '0px').css('zIndex', o.zindex).addClass(o.transition),
pickPageTitle = pickPage.find('.ui-title'),
pickPageContent = pickPage.find( ".ui-content" ),
touch = ( typeof window.ontouchstart !== 'undefined' ),
START_EVENT = touch ? 'touchstart' : 'mousedown',
MOVE_EVENT = touch ? 'touchmove' : 'mousemove',
END_EVENT = touch ? 'touchend' : 'mouseup',
dragMove = false,
dragStart = false,
dragEnd = false,
dragPos = false,
dragTarget = false,
dragThisDelta = 0;
o.theme = thisTheme;
$.extend(self, {
input: input,
focusedEl: focusedEl });
if ( o.forceInheritTheme ) {
o.pickPageTheme = thisTheme;
o.pickPageInputTheme = thisTheme;
o.pickPageButtonTheme = thisTheme;
}
if ( o.defaultPickerValue===false && o.defaultDate!==false ) {
o.defaultPickerValue = o.defaultDate;
}
if ( o.numberInputEnhance === true ) {
if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) ){
o.internalInputType = 'number';
}
}
$('label[for=\''+input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle');
/* BUILD:MODE */
if ( o.mode === "timeflipbox" ) { // No header in time flipbox.
o.lang[o.useLang].headerFormat = ' ';
}
// For focus mode, disable button, and bind click of input element and it's parent
if ( o.noButtonFocusMode || o.useInline || o.noButton ) { openbutton.hide(); }
self.focusedEl.bind(o.clickEvent, function() {
if ( !o.disabled && ( o.noButtonFocusMode || o.focusMode ) ) {
self.input.trigger('datebox', {'method': 'open'});
self.focusedEl.addClass('ui-focus');
self.input.removeClass('ui-focus');
}
});
self.input
.removeClass('ui-corner-all ui-shadow-inset')
.focus(function(){
if ( ! o.disabled ) {
self.focusedEl.addClass('ui-focus');
}
self.input.removeClass('ui-focus');
})
.blur(function(){
self.focusedEl.removeClass('ui-focus');
self.input.removeClass('ui-focus');
})
.change(function() {
self.theDate = self._makeDate(self.input.val());
self._update();
});
// Bind the master handler.
self.input.bind('datebox', self._dateboxHandler);
// Bind the close button on the DIALOG mode. (after unbinding the default)
pickPage.find( ".ui-header a").unbind('click vclick').bind(o.clickEvent, function(e) {
e.preventDefault();
e.stopImmediatePropagation();
self.input.trigger('datebox', {'method':'close', 'fromCloseButton':false});
});
$.extend(self, {
pickPage: pickPage,
thisPage: thisPage,
pickPageContent: pickPageContent,
pickPageTitle: pickPageTitle,
theDate: theDate,
initDate: initDate,
touch: touch,
START_DRAG: START_EVENT,
MOVE_DRAG: MOVE_EVENT,
END_DRAG: END_EVENT,
dragMove: dragMove,
dragStart: dragStart,
dragEnd: dragEnd,
dragPos: dragPos
});
// Check if mousewheel plugin is loaded
if ( typeof $.event.special.mousewheel !== 'undefined' ) { o.wheelExists = true; }
self._buildPage();
// drag and drop support, all ending and moving events are defined here, start events are handled in _buildPage or update
if ( o.swipeEnabled ) {
$(document).bind(self.MOVE_DRAG, function(e) {
if ( self.dragMove ) {
if ( o.mode === 'slidebox' ) {
self.dragEnd = self.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX;
self.dragTarget.css('marginLeft', (self.dragPos + self.dragEnd - self.dragStart) + 'px');
e.preventDefault();
e.stopPropagation();
return false;
} else if ( o.mode === 'flipbox' || o.mode === 'timeflipbox' ) {
self.dragEnd = self.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY;
self.dragTarget.css('marginTop', (self.dragPos + self.dragEnd - self.dragStart) + 'px');
e.preventDefault();
e.stopPropagation();
return false;
} else if ( o.mode === 'durationbox' || o.mode === 'timebox' || o.mode === 'datebox' ) {
self.dragEnd = self.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY;
if ( (self.dragEnd - self.dragStart) % 2 === 0 ) {
dragThisDelta = (self.dragEnd - self.dragStart) / -2;
if ( dragThisDelta < self.dragPos ) {
self._offset(self.dragTarget, -1*(self.dragTarget==='i'?o.minuteStep:1));
} else if ( dragThisDelta > self.dragPos ) {
self._offset(self.dragTarget, (self.dragTarget==='i'?o.minuteStep:1));
}
self.dragPos = dragThisDelta;
}
e.preventDefault();
e.stopPropagation();
return false;
}
}
});
$(document).bind(self.END_DRAG, function(e) {
if ( self.dragMove ) {
self.dragMove = false;
if ( o.mode === 'slidebox' ) {
if ( self.dragEnd !== false && Math.abs(self.dragStart - self.dragEnd) > 25 ) {
e.preventDefault();
e.stopPropagation();
switch(self.dragTarget.parent().jqmData('rowtype')) {
case 'y':
self._offset('y', parseInt(( self.dragStart - self.dragEnd ) / 84, 10));
break;
case 'm':
self._offset('m', parseInt(( self.dragStart - self.dragEnd ) / 51, 10));
break;
case 'd':
self._offset('d', parseInt(( self.dragStart - self.dragEnd ) / 32, 10));
break;
case 'h':
self._offset('h', parseInt(( self.dragStart - self.dragEnd ) / 32, 10));
break;
case 'i':
self._offset('i', parseInt(( self.dragStart - self.dragEnd ) / 32, 10));
break;
}
}
} else if ( o.mode === 'flipbox' || o.mode === 'timeflipbox' ) {
if ( self.dragEnd !== false ) {
e.preventDefault();
e.stopPropagation();
var fld = self.dragTarget.parent().parent().jqmData('field'),
amount = parseInt(( self.dragStart - self.dragEnd ) / 30,10);
self._offset(fld, amount * ( (fld === "i") ? o.minuteStep : 1 ));
}
}
self.dragStart = false;
self.dragEnd = false;
}
});
}
// Disable when done if element attribute disabled is true.
if ( self.input.is(':disabled') ) {
self.disable();
}
// Turn input readonly if requested (on by default)
if ( o.disableManualInput === true ) {
self.input.attr("readonly", true);
}
//Throw dateboxinit event
$( document ).trigger( "dateboxaftercreate" );
},
_makeElement: function(source, parts) {
var self = this,
part = false,
retty = false;
retty = source.clone();
if ( typeof parts.attr !== 'undefined' ) {
for ( part in parts.attr ) {
if ( parts.attr.hasOwnProperty(part) ) {
retty.jqmData(part, parts.attr[part]);
}
}
}
return retty;
},
_eventEnterValue: function (item) {
var self = this,
o = self.options,
newHour = false;
if ( item.val() !== '' && self._isInt(item.val()) ) {
switch(item.jqmData('field')) {
case 'm':
self.theDate.setMonth(parseInt(item.val(),10)-1); break;
case 'd':
self.theDate.setDate(parseInt(item.val(),10)); break;
case 'y':
self.theDate.setFullYear(parseInt(item.val(),10)); break;
case 'i':
self.theDate.setMinutes(parseInt(item.val(),10)); break;
case 'h':
newHour = parseInt(item.val(),10);
if ( newHour === 12 ) {
if ( ( o.lang[o.useLang].timeFormat === 12 || o.timeFormatOverride === 12 ) && self.pickerMeri.val() === o.meridiemLetters[0] ) { newHour = 0; }
}
self.theDate.setHours(newHour);
break;
}
self._update();
}
},
_buildInternals: function () {
// Build the POSSIBLY VARIABLE controls (these might change)
var self = this,
o = self.options, x, y, newHour, fld,
linkdiv =$("<div><a href='#'></a></div>"),
pickerContent = $("<div>", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden pop ui-body-'+o.pickPageTheme} ).css('zIndex', o.zindex),
templInput = $("<input type='"+o.internalInputType+"' />").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-datebox-input ui-body-'+o.pickPageInputTheme),
templInputT = $("<input type='text' />").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-datebox-input ui-body-'+o.pickPageInputTheme),
templControls = $("<div>", { "class":'ui-datebox-controls' }),
templFlip = $("<div class='ui-overlay-shadow'><ul></ul></div>"),
controlsPlus, controlsInput, controlsMinus, controlsSet, controlsHeader,
pickerHour, pickerMins, pickerMeri, pickerMon, pickerDay, pickerYar, pickerSecs;
self.calNoNext = false;
self.calNoPrev = false;
self.setButton = false;
self.clearButton = false;
self.dateOK = true;
if ( o.fieldsOrderOverride === false ) {
switch (o.mode) {
case 'timebox':
case 'timeflipbox':
o.fieldsOrder = o.lang[o.useLang].timeFieldOrder;
break;
case 'slidebox':
o.fieldsOrder = o.lang[o.useLang].slideFieldOrder;
break;
default:
o.fieldsOrder = o.lang[o.useLang].dateFieldOrder;
}
} else {
o.fieldsOrder = o.fieldsOrderOverride;
}
/* Do the Date / Time Format */
if ( o.timeOutputOverride !== false ) {
o.timeOutput = o.timeOutputOverride;
} else if ( o.timeFormatOverride === false ) {
o.timeOutput = o.timeFormats[o.lang[o.useLang].timeFormat];
} else {
o.timeOutput = o.timeFormats[o.timeFormatOverride];
}
if ( o.dateFormat !== false ) {
o.dateOutput = o.dateFormat;
} else {
if ( typeof o.lang[o.useLang].dateFormat !== 'undefined' ) {
o.dateOutput = o.lang[o.useLang].dateFormat;
} else {
o.dateOutput = o.defaultDateFormat;
}
}
self.pickerContent.empty();
/* BEGIN:DATETIME */
if ( o.mode === 'datebox' || o.mode === 'timebox' ) {
controlsHeader = $("<div class='ui-datebox-header'><h4>Uninitialized</h4></div>").appendTo(self.pickerContent).find("h4");
controlsPlus = templControls.clone().appendTo(self.pickerContent);
controlsInput = templControls.clone().appendTo(self.pickerContent);
controlsMinus = templControls.clone().appendTo(self.pickerContent);
controlsSet = templControls.clone().appendTo(self.pickerContent);
if ( o.mode === 'timebox' ) { controlsHeader.parent().empty(); } // Time mode has no header
pickerMon = self._makeElement(templInput, {'attr': {'field':'m', 'amount':1} });
pickerDay = self._makeElement(templInput, {'attr': {'field':'d', 'amount':1} });
pickerYar = self._makeElement(templInput, {'attr': {'field':'y', 'amount':1} });
pickerHour = self._makeElement(templInput, {'attr': {'field':'h', 'amount':1} });
pickerMins = self._makeElement(templInput, {'attr': {'field':'i', 'amount':1} });
pickerMeri = self._makeElement(templInputT, {'attr': {'field':'a', 'amount':o.minuteStep} });
controlsInput.delegate('input', 'keyup', function() {
self._eventEnterValue($(this));
});
if ( o.wheelExists ) { // Mousewheel operation, if plugin is loaded
controlsInput.delegate('input', 'mousewheel', function(e,d) {
e.preventDefault();
self._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount'));
});
}
for(x=0; x<=o.fieldsOrder.length; x++) { // Use fieldsOrder to decide what goes where
if (o.fieldsOrder[x] === 'y') { pickerYar.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'm') { pickerMon.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'd') { pickerDay.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'h') { pickerHour.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'i') { pickerMins.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'a' && ( o.lang[o.useLang].timeFormat === 12 || o.timeFormatOverride === 12 ) ) { pickerMeri.appendTo(controlsInput); }
}
if ( o.swipeEnabled ) { // Drag and drop support
controlsInput.delegate('input', self.START_DRAG, function(e) {
if ( !self.dragMove ) {
self.dragMove = true;
self.dragTarget = $(this).jqmData('field');
self.dragPos = 0;
self.dragStart = self.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY;
self.dragEnd = false;
e.stopPropagation();
}
});
}
if ( o.noSetButton === false ) { // Set button at bottom
self.setButton = $("<a href='#'>PlaceHolder</a>")
.appendTo(controlsSet).buttonMarkup({theme: o.pickPageTheme, icon: 'check', iconpos: 'left', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
if ( self.dateOK === true ) {
if ( o.mode === 'timebox' ) { self.input.trigger('datebox', {'method':'set', 'value':self._formatTime(self.theDate), 'date':self.theDate}); }
else { self.input.trigger('datebox', {'method':'set', 'value':self._formatDate(self.theDate), 'date':self.theDate}); }
self.input.trigger('datebox', {'method':'close'});
}
});
}
for( x=0; x<self.options.fieldsOrder.length; x++ ) { // Generate the plus and minus buttons, use fieldsOrder again
if ( o.fieldsOrder[x] !== 'a' || o.lang[o.useLang].timeFormat === 12 || o.timeFormatOverride === 12 ) {
for ( y=0; y<2; y++ ) {
linkdiv.clone()
.appendTo(((y===0)?controlsPlus:controlsMinus))
.buttonMarkup({theme: o.pickPageButtonTheme, icon: ((y===0)?'plus':'minus'), iconpos: 'bottom', corners:true, shadow:true})
.jqmData('field', o.fieldsOrder[x])
.jqmData('amount', ((o.fieldsOrder[x]==='i')?o.minuteStep:1));
}
}
}
controlsPlus.delegate('div', o.clickEvent, function(e) {
e.preventDefault();
self._offset($(this).jqmData('field'), $(this).jqmData('amount'));
});
controlsMinus.delegate('div', o.clickEvent, function(e) {
e.preventDefault();
self._offset($(this).jqmData('field'), $(this).jqmData('amount')*-1);
});
$.extend(self, {
controlsHeader: controlsHeader,
pickerDay: pickerDay,
pickerMon: pickerMon,
pickerYar: pickerYar,
pickerHour: pickerHour,
pickerMins: pickerMins,
pickerMeri: pickerMeri,
controlsInput: controlsInput
});
self.pickerContent.appendTo(self.thisPage);
}
/* END:DATETIME */
/* BEGIN:DURATIONBOX */
if ( o.mode === 'durationbox' ) {
controlsPlus = templControls.clone().removeClass('ui-datebox-controls').addClass('ui-datebox-scontrols').appendTo(self.pickerContent);
controlsInput = controlsPlus.clone().appendTo(self.pickerContent);
controlsMinus = controlsPlus.clone().appendTo(self.pickerContent);
controlsSet = templControls.clone().appendTo(self.pickerContent);
pickerDay = templInput.removeClass('ui-datebox-input');
pickerHour = pickerDay.clone();
pickerMins = pickerDay.clone();
pickerSecs = pickerDay.clone();
controlsInput.delegate('input', 'keyup', function() {
if ( $(this).val() !== '' ) { self._updateduration(); }
});
if ( o.wheelExists ) { // Mousewheel operation, if the plgin is loaded
controlsInput.delegate('input', 'mousewheel', function(e,d) {
e.preventDefault();
self._offset($(this).parent().jqmData('field'), ((d<0)?-1:1));
});
}
for ( x=0; x<o.durationOrder.length; x++ ) { // Use durationOrder to decide what goes where
switch ( o.durationOrder[x] ) {
case 'd':
$('<div>', {'class': 'ui-datebox-sinput'}).jqmData('field', 'd').append(pickerDay).appendTo(controlsInput).prepend('<label>'+o.lang[o.useLang].durationLabel[0]+'</label>');
break;
case 'h':
$('<div>', {'class': 'ui-datebox-sinput'}).jqmData('field', 'h').append(pickerHour).appendTo(controlsInput).prepend('<label>'+o.lang[o.useLang].durationLabel[1]+'</label>');
break;
case 'i':
$('<div>', {'class': 'ui-datebox-sinput'}).jqmData('field', 'i').append(pickerMins).appendTo(controlsInput).prepend('<label>'+o.lang[o.useLang].durationLabel[2]+'</label>');
break;
case 's':
$('<div>', {'class': 'ui-datebox-sinput'}).jqmData('field', 's').append(pickerSecs).appendTo(controlsInput).prepend('<label>'+o.lang[o.useLang].durationLabel[3]+'</label>');
break;
}
}
if ( o.swipeEnabled ) { // Drag and drop operation
controlsInput.delegate('input', self.START_DRAG, function(e) {
if ( !self.dragMove ) {
self.dragMove = true;
self.dragTarget = $(this).parent().jqmData('field');
self.dragPos = 0;
self.dragStart = self.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY;
self.dragEnd = false;
e.stopPropagation();
}
});
}
if ( o.noSetButton === false ) { // Bottom set button
self.setButton = $("<a href='#'>PlaceHolder</a>")
.appendTo(controlsSet).buttonMarkup({theme: o.pickPageTheme, icon: 'check', iconpos: 'left', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
self.input.trigger('datebox', {'method':'set', 'value':self._formatTime(self.theDate), 'date':self.theDate});
self.input.trigger('datebox', {'method':'close'});
});
}
for ( x=0; x<o.durationOrder.length; x++ ) {
for ( y=0; y<2; y++ ) {
linkdiv.clone()
.appendTo(((y===0)?controlsPlus:controlsMinus))
.buttonMarkup({theme: o.pickPageButtonTheme, icon: ((y===0)?'plus':'minus'), iconpos: 'bottom', corners:true, shadow:true})
.jqmData('field', o.durationOrder[x]);
}
}
controlsPlus.delegate('div', o.clickEvent, function(e) {
e.preventDefault();
self._offset($(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]);
});
controlsMinus.delegate('div', o.clickEvent, function(e) {
e.preventDefault();
self._offset($(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]*-1);
});
$.extend(self, {
pickerHour: pickerHour,
pickerMins: pickerMins,
pickerDay: pickerDay,
pickerSecs: pickerSecs
});
self.pickerContent.appendTo(self.thisPage);
}
/* END:DURATIONBOX */
/* BEGIN:SLIDEBOX */
if ( o.mode === 'slidebox' ) {
controlsHeader = $("<div class='ui-datebox-header'><h4>Uninitialized</h4></div>").appendTo(self.pickerContent).find("h4");
controlsInput = $('<div>').addClass('ui-datebox-slide').appendTo(self.pickerContent);
controlsSet = $("<div>", { "class":'ui-datebox-controls'}).appendTo(self.pickerContent);
if ( o.noSetButton === false ) { // Show set button at bottom
self.setButton = $("<a href='#'>PlaceHolder</a>")
.appendTo(controlsSet).buttonMarkup({theme: o.pickPageTheme, icon: 'check', iconpos: 'left', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
if ( self.dateOK === true ) {
self.input.trigger('datebox', {'method':'set', 'value':self._formatDate(self.theDate), 'date':self.theDate});
self.input.trigger('datebox', {'method':'close'});
}
});
}
$.extend(self, {
controlsHeader: controlsHeader,
controlsInput: controlsInput
});
self.pickerContent.appendTo(self.thisPage);
}
/* END:SLIDEBOX */
/* BEGIN:FLIPBOX */
if ( o.mode === 'flipbox' || o.mode === 'timeflipbox' ) {
controlsHeader = $("<div class='ui-datebox-header'><h4>Uninitialized</h4></div>").appendTo(self.pickerContent).find("h4");
controlsInput = $("<div>", {"class":'ui-datebox-flipcontent'}).appendTo(self.pickerContent);
controlsPlus = $("<div>", {"class":'ui-datebox-flipcenter ui-overlay-shadow'}).css('pointerEvents', 'none').appendTo(self.pickerContent);
controlsSet = templControls.clone().appendTo(self.pickerContent);
pickerDay = self._makeElement(templFlip, {'attr': {'field':'d','amount':1} });
pickerMon = self._makeElement(templFlip, {'attr': {'field':'m','amount':1} });
pickerYar = self._makeElement(templFlip, {'attr': {'field':'y','amount':1} });
pickerHour = self._makeElement(templFlip, {'attr': {'field':'h','amount':1} });
pickerMins = self._makeElement(templFlip, {'attr': {'field':'i','amount':o.minuteStep} });
pickerMeri = self._makeElement(templFlip, {'attr': {'field':'a','amount':1} });
if ( o.wheelExists ) { // Mousewheel operation, if the plugin is loaded.
controlsInput.delegate('div', 'mousewheel', function(e,d) {
e.preventDefault();
self._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount'));
});
}
for(x=0; x<=o.fieldsOrder.length; x++) { // Use fieldsOrder to decide which to show.
if (o.fieldsOrder[x] === 'y') { pickerYar.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'm') { pickerMon.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'd') { pickerDay.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'h') { pickerHour.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'i') { pickerMins.appendTo(controlsInput); }
if (o.fieldsOrder[x] === 'a' && ( o.lang[o.useLang].timeFormat === 12 || o.timeFormatOverride === 12 ) ) { pickerMeri.appendTo(controlsInput); }
}
if ( o.swipeEnabled ) { // Drag and drop support
controlsInput.delegate('ul', self.START_DRAG, function(e,f) {
if ( !self.dragMove ) {
if ( typeof f !== "undefined" ) { e = f; }
self.dragMove = true;
self.dragTarget = $(this).find('li').first();
self.dragPos = parseInt(self.dragTarget.css('marginTop').replace(/px/i, ''),10);
self.dragStart = self.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY;
self.dragEnd = false;
e.stopPropagation();
e.preventDefault();
}
});
controlsPlus.bind(self.START_DRAG, function(e) { // ONLY USED ON OLD BROWSERS & IE
if ( !self.dragMove ) {
self.dragTarget = self.touch ? e.originalEvent.changedTouches[0].pageX - $(e.currentTarget).offset().left : e.pageX - $(e.currentTarget).offset().left;
if ( o.fieldsOrder.length === 3 ) {
$(self.controlsInput.find('ul').get(parseInt(self.dragTarget / 87, 10))).trigger(self.START_DRAG, e);
} else if ( o.fieldsOrder.length === 2 ) {
$(self.controlsInput.find('ul').get(parseInt(self.dragTarget / 130, 10))).trigger(self.START_DRAG, e);
}
}
});
}
if ( o.noSetButton === false ) { // Set button at bottom
self.setButton = $("<a href='#'>PlaceHolder</a>")
.appendTo(controlsSet).buttonMarkup({theme: o.pickPageTheme, icon: 'check', iconpos: 'left', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
if ( self.dateOK === true ) {
if ( o.mode === 'timeflipbox' ) { self.input.trigger('datebox', {'method':'set', 'value':self._formatTime(self.theDate), 'date':self.theDate}); }
else { self.input.trigger('datebox', {'method':'set', 'value':self._formatDate(self.theDate), 'date':self.theDate}); }
self.input.trigger('datebox', {'method':'close'});
}
});
}
$.extend(self, {
controlsHeader: controlsHeader,
controlsInput: controlsInput,
pickerDay: pickerDay,
pickerMon: pickerMon,
pickerYar: pickerYar,
pickerHour: pickerHour,
pickerMins: pickerMins,
pickerMeri: pickerMeri
});
self.pickerContent.appendTo(self.thisPage);
}
/* END:FLIPBOX */
/* BEGIN:CALBOX */
if ( o.mode === 'calbox' ) {
controlsHeader = $("<div>", {"class": 'ui-datebox-gridheader'}).appendTo(self.pickerContent);
controlsPlus = $("<div>", {"class": 'ui-datebox-grid'}).appendTo(self.pickerContent);
controlsSet = templControls.clone().appendTo(self.pickerContent);
controlsInput = $("<div class='ui-datebox-gridlabel'><h4>Uninitialized</h4></div>").appendTo(controlsHeader).find('h4');
if ( o.swipeEnabled ) { // Calendar swipe left and right
self.pickerContent
.bind('swipeleft', function() { if ( !self.calNoNext ) { self._offset('m', 1); } })
.bind('swiperight', function() { if ( !self.calNoPrev ) { self._offset('m', -1); } });
}
if ( o.wheelExists) { // Mousewheel operations, if plugin is loaded
self.pickerContent.bind('mousewheel', function(e,d) {
e.preventDefault();
if ( d > 0 && !self.calNoNext ) {
if ( self.theDate.getDate() > 28 ) { self.theDate.setDate(1); }
self._offset('m', 1);
}
if ( d < 0 && !self.calNoPrev ) {
if ( self.theDate.getDate() > 28 ) { self.theDate.setDate(1); }
self._offset('m', -1);
}
});
}
// Previous and next month buttons, define booleans to decide if they should do anything
$("<div class='ui-datebox-gridplus"+((o.lang[o.useLang].isRTL===true)?'-rtl':'')+"'><a href='#'>"+((typeof o.lang[o.useLang].nextMonth !== 'undefined')?o.lang[o.useLang].nextMonth:o.lang.en.nextMonth)+"</a></div>")
.prependTo(controlsHeader).buttonMarkup({theme: o.pickPageButtonTheme, icon: 'plus', inline: true, iconpos: 'notext', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
if ( ! self.calNoNext ) {
if ( self.theDate.getDate() > 28 ) { self.theDate.setDate(1); }
self._offset('m',1);
}
});
$("<div class='ui-datebox-gridminus"+((o.lang[o.useLang].isRTL===true)?'-rtl':'')+"'><a href='#'>"+((typeof o.lang[o.useLang].prevMonth !== 'undefined')?o.lang[o.useLang].prevMonth:o.lang.en.prevMonth)+"</a></div>")
.prependTo(controlsHeader).buttonMarkup({theme: o.pickPageButtonTheme, icon: 'minus', inline: true, iconpos: 'notext', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
if ( ! self.calNoPrev ) {
if ( self.theDate.getDate() > 28 ) { self.theDate.setDate(1); }
self._offset('m',-1);
}
});
if ( o.calTodayButton === true ) { // Show today button at bottom
self.setButton = $("<a href='#'>PlaceHolder</a>")
.appendTo(controlsSet).buttonMarkup({theme: o.pickPageTheme, icon: 'check', iconpos: 'left', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
self.theDate = new Date();
self.theDate = new Date(self.theDate.getFullYear(), self.theDate.getMonth(), self.theDate.getDate(), 0,0,0,0);
self.input.trigger('datebox', {'method':'doset'});
});
}
$.extend(self, {
controlsInput: controlsInput,
controlsPlus: controlsPlus
});
self.pickerContent.appendTo(self.thisPage);
}
/* END:CALBOX */
if ( o.useClearButton === true ) { // Clear button at very bottom
self.clearButton = $("<a href='#'>PlaceHolder</a>")
.appendTo(controlsSet).buttonMarkup({theme: o.pickPageTheme, icon: 'delete', iconpos: 'left', corners:true, shadow:true})
.bind(o.clickEvent, function(e) {
e.preventDefault();
self.input.val('');
self.input.trigger('datebox', {'method':'clear'});
self.input.trigger('datebox', {'method':'close'});
});
}
if ( o.collapseButtons && ( self.clearButton !== false && self.setButton !== false ) ) {
controlsSet.addClass('ui-datebox-collapse');
}
},
_buttonsTitle: function () {
var self = this,
o = this.options;
// FIX THE DIALOG TITLE LABEL
if ( o.titleDialogLabel === false ) {
if ( typeof this.element.attr('title') !== 'undefined' ) {
self.pickPageTitle.html(this.element.attr('title'));
} else if ( this.focusedEl.parent().find('label').text() !== '' ) {
self.pickPageTitle.html(this.focusedEl.parent().find('label').text());
} else {
switch (o.mode) {
case "timebox":
case "timeflipbox":
self.pickPageTitle.html(o.lang[o.useLang].titleTimeDialogLabel);
break;
default:
self.pickPageTitle.html(o.lang[o.useLang].titleDateDialogLabel);
break;
}
}
} else {
self.pickPageTitle.html(o.titleDialogLabel);
}
// FIX THE CLEAR BUTTON
if ( self.clearButton !== false ) {
self.clearButton.find('.ui-btn-text').html(o.lang[o.useLang].clearButton);
}
// FIX THE SET BUTTON
if ( self.setButton !== false ) {
switch (o.mode) {
case "timebox":
case "timeflipbox":
self.setButton.find('.ui-btn-text').html(o.lang[o.useLang].setTimeButtonLabel);
break;
case "durationbox":
self.setButton.find('.ui-btn-text').html(o.lang[o.useLang].setDurationButtonLabel);
break;
case "calbox":
self.setButton.find('.ui-btn-text').html(o.lang[o.useLang].calTodayButtonLabel);
break;
default:
self.setButton.find('.ui-btn-text').html(o.lang[o.useLang].setDateButtonLabel);
break;
}
}
},
_buildPage: function () {
// Build the CONSTANT controls (these never change)
var self = this,
o = self.options,
pickerContent = $("<div>", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+o.transition+' ui-body-'+o.pickPageTheme} ).css('zIndex', o.zindex),
screen = $("<div>", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')})
.css({'z-index': o.zindex-1})
.appendTo(self.thisPage)
.bind(o.clickEvent, function(event) {
event.preventDefault();
self.input.trigger('datebox', {'method':'close'});
});
if ( o.noAnimation ) { pickerContent.removeClass(o.transition); }
$.extend(self, {
pickerContent: pickerContent,
screen: screen
});
self._buildInternals();
// If useInline mode, drop it into the document, and stop a few events from working (or just hide the trigger)
if ( o.useInline || o.useInlineBlind ) {
self.input.parent().parent().append(self.pickerContent);
if ( o.useInlineHideInput ) { self.input.parent().hide(); }
self.input.trigger('change');
self.pickerContent.removeClass('ui-datebox-hidden');
} else if ( o.centerWindow && o.useInlineHideInput ) {
self.input.parent().hide();
}
if ( o.useInline ) {
self.pickerContent.addClass('ui-datebox-inline');
self.open();
}
if ( o.useInlineBlind ) {
self.pickerContent.addClass('ui-datebox-inlineblind');
self.pickerContent.hide();
}
},
hardreset: function() {
// Public shortcut to rebuild all internals
this._buildInternals();
this.refresh();
this._buttonsTitle();
},
refresh: function() {
// Pulic shortcut to _update, with an extra hook for inline mode.
if ( this.options.useInline === true ) {
this.input.trigger('change');
}
this._update();
},
open: function() {
var self = this,
o = this.options,
coords = false, // Later, if need be
transition = o.noAnimation ? 'none' : o.transition,
callback, activePage;
// Call the open callback if provided. Additionally, if this
// returns falsy then the open of the dialog will be canceled
if ( o.openCallback !== false ) {
if ( ! $.isFunction(this.options.openCallback) ) {
if ( typeof window[o.openCallback] !== 'undefined' ) {
o.openCallback = window[o.openCallback];
} else {
o.openCallback = new Function(o.openCallback);
}
}
callback = o.openCallback.apply(self, $.merge([self.theDate],o.openCallbackArgs));
if ( callback == false ) { return false; }
}
self._buttonsTitle();
// Open the controls
if ( this.options.useInlineBlind ) { this.pickerContent.slideDown(); return false; } // Just slide if blinds mode
if ( this.options.useInline ) { return true; } // Ignore if inline
if ( this.pickPage.is(':visible') ) { return false; } // Ignore if already open
this.theDate = this._makeDate(this.input.val());
this._update();
this.input.blur(); // Grab latest value of input, in case it changed
// If the window is less than 400px wide, use the jQM dialog method unless otherwise forced
if ( ( $(document).width() > 400 && !o.useDialogForceTrue ) || o.useDialogForceFalse || o.fullScreen ) {
coords = this._getCoords(this); // Get the coords now, since we need em.
o.useDialog = false;
if ( o.nestedBox === true && o.fullScreen === false ) {
activePage = $('.ui-page-active').first();
$(activePage).append(self.pickerContent);
$(activePage).append(self.screen);
}
if ( o.fullScreenAlways === false || coords.width > 399 ) {
if ( o.useModal === true ) { // If model, fade the background screen
self.screen.fadeIn('slow');
} else { // Else just unhide it since it's transparent (with a delay to prevent insta-close)
setTimeout(function() {self.screen.removeClass('ui-datebox-hidden');}, 500);
}
}
if ( o.fullScreenAlways === true || ( o.fullScreen === true && coords.width < 400 ) ) {
self.pickerContent.addClass('in').css({'position': 'absolute', 'text-align': 'center', 'top': coords.fullTop-5, 'left': coords.fullLeft-5, 'height': coords.high, 'width': coords.width}).removeClass('ui-datebox-hidden');
} else {
self.pickerContent.addClass('ui-overlay-shadow in').css({'position': 'absolute', 'top': coords.winTop, 'left': coords.winLeft}).removeClass('ui-datebox-hidden');
$(document).bind('orientationchange.datebox', {widget:self}, function(e) { self._orientChange(e); });
if ( o.resizeListener === true ) {
$(window).bind('resize.datebox', {widget:self}, function (e) { self._orientChange(e); });
}
}
} else {
// prevent the parent page from being removed from the DOM,
self.thisPage.unbind( "pagehide.remove" );
o.useDialog = true;
self.pickPageContent.append(self.pickerContent);
self.pickerContent.css({'top': 'auto', 'left': 'auto', 'marginLeft': 'auto', 'marginRight': 'auto'}).removeClass('ui-overlay-shadow ui-datebox-hidden');
$.mobile.changePage(self.pickPage, {'transition': transition});
}
},
close: function(fromCloseButton) {
// Close the controls
var self = this,
o = this.options,
callback;
if ( o.useInlineBlind ) {
self.pickerContent.slideUp();
return false; // No More!
}
if ( o.useInline ) {
return true;
}
// Check options to see if we are closing a dialog, or removing a popup
if ( o.useDialog ) {
if (!fromCloseButton) {
$(self.pickPage).dialog('close');
}
if( !self.thisPage.jqmData("page").options.domCache ){
self.thisPage.bind( "pagehide.remove", function() {
$(self).remove();
});
}
self.pickerContent.addClass('ui-datebox-hidden').removeAttr('style').css('zIndex', self.options.zindex);
self.thisPage.append(self.pickerContent);
} else {
if ( o.useModal ) {
self.screen.fadeOut('slow');
} else {
self.screen.addClass('ui-datebox-hidden');
}
self.pickerContent.addClass('ui-datebox-hidden').removeAttr('style').css('zIndex', self.options.zindex).removeClass('in');
}
self.focusedEl.removeClass('ui-focus');
$(document).unbind('orientationchange.datebox');
if ( o.resizeListener === true ) {
$(window).unbind('resize.datebox');
}
if ( o.closeCallback !== false ) {
if ( ! $.isFunction(o.closeCallback) ) {
if ( typeof window[o.closeCallback] !== 'undefined' ) {
o.closeCallback = window[o.closeCallback];
} else {
o.closeCallback = new Function(o.closeCallback);
}
}
o.closeCallback.apply(self, $.merge([self.theDate], o.closeCallbackArgs));
}
},
disable: function(){
// Disable the element
this.element.attr("disabled",true);
this.element.parent().addClass("ui-disabled");
this.options.disabled = true;
this.element.blur();
this.input.trigger('datebox', {'method':'disable'});
},
enable: function(){
// Enable the element
this.element.attr("disabled", false);
this.element.parent().removeClass("ui-disabled");
this.options.disabled = false;
this.input.trigger('datebox', {'method':'enable'});
},
_setOption: function( key, value ) {
var noReset = ['minYear','maxYear','afterToday','beforeToday','maxDays','minDays','highDays','highDates','blackDays','blackDates','enableDates'];
$.Widget.prototype._setOption.apply( this, arguments );
if ( $.inArray(key, noReset) > -1 ) {
this.refresh();
} else {
this.hardreset();
}
}
});
// Degrade date inputs to text inputs, suppress standard UI functions.
$( document ).bind( "pagebeforecreate", function( e ) {
$( ":jqmData(role='datebox')", e.target ).each(function() {
$(this).prop('type', 'text');
});
});
// Automatically bind to data-role='datebox' items.
$( document ).bind( "pagecreate create", function( e ){
$( document ).trigger( "dateboxbeforecreate" );
$( ":jqmData(role='datebox')", e.target ).each(function() {
if ( typeof($(this).data('datebox')) === "undefined" ) {
$(this).datebox();
}
});
});
})( jQuery );
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
files: {
'css/build/dev/global.css': 'css/scss/global.scss'
}
}
},
autoprefixer: {
options: {
browsers: ['last 2 version']
},
multiple_files: {
expand: true,
flatten: true,
src: 'css/build/dev/*.css',
dest: 'css/build/prefixed/'
}
},
cssmin: {
combine: {
files: {
'css/build/production/global.css': ['css/build/prefixed/global.css']
}
}
},
imagemin: {
dynamic: {
files: [{
expand: true,
cwd: 'img/',
src: ['**/*.{png,jpg,gif}'],
dest: 'img/'
}]
}
},
watch: {
livereload: {
options: { livereload: true },
files: ['*.html', '*.php', 'js/**/*.js', 'fonts/**', 'img/**']
},
sass: {
files: 'css/scss/*.scss',
tasks: ['sass', 'autoprefixer']
},
css: {
options: { livereload: true },
files: ['css/build/prefixed/*.css']
}
}
});
// default task is for developing
grunt.registerTask('default', ['sass', 'watch']);
grunt.registerTask('dev', ['sass', 'autoprefixer', 'watch']);
grunt.registerTask('production', ['sass', 'autoprefixer', 'cssmin', 'imagemin']);
require('load-grunt-tasks')(grunt);
}; |
'use strict';
function FormulaFileController($scope, $mdDialog, $http, $routeParams, NpolarApiSecurity, fileFunnelService) {
'ngInject';
let ctrl = this;
ctrl.field = $scope.field;
ctrl.isNew = (params=$routeParams) => {
return params.id === '__new';
};
ctrl.file_uri = (options=fileFunnelService.getOptions(ctrl.field)) => {
return options.server.replace('/:id/_file', '');
};
ctrl.canUpload = (security = NpolarApiSecurity) => {
return ((false === ctrl.isNew()) && (security.isAuthorized('create', ctrl.file_uri())));
};
ctrl.canDelete = (security = NpolarApiSecurity) => {
return security.isAuthorized('delete', ctrl.file_uri());
};
$scope.files = [];
let options = fileFunnelService.getOptions($scope.field);
//console.log('field', $scope.field, fileFunnelService.getOptions(), options);
// From app-specific metadata to Hashi object
let toHashi = function(hashi_field) {
// file: metadata object as stored in the application
let file = Object.assign({},hashi_field.value);
if (typeof options.toHashi === "function") {
file = options.toHashi(file);
options.valueToFileMapper = options.toHashi;
} else if (typeof options.valueToFileMapper === "function") {
console.warn('DEPRECATED: use toHashi');
file = options.valueToFileMapper(file);
}
if (file) {
if (!file.filename || !file.url) {
throw "The hashi file mapper should be an object with keys filename, url, [file_size, icon, extras].";
}
file.extras = hashi_field.fields.filter(field => (options.fields || []).includes(field.id));
}
return file;
};
$scope.id = $routeParams.id;
$scope.field.values.forEach(value => {
let hashiFile = toHashi(value);
$scope.files.push(hashiFile);
});
$scope.isFile = function(value, index, array) {
return !!$scope.files[index];
};
ctrl.displayUploadDialog = (ev) => {
console.log('displayUploadDialog', ev);
fileFunnelService.showUpload(ev, $scope.field, options).then(files => {
files = files.filter(f => f.status >= 200 && f.status < 300);
if (files) {
files.forEach(file => {
let length = $scope.files.push(file);
file.extras = $scope.field.values[length - 1].fields.filter(field => (options.fields || []).includes(field.id));
});
}
});
};
$scope.removeFile = function(index) {
let file = $scope.field.itemRemove(index);
if (typeof options.valueToFileMapper === "function") {
file = options.valueToFileMapper(file.value);
}
$scope.files = $scope.files.filter(f => f.md5sum !== file.md5sum);
$http.delete(file.url);
};
$scope.nrFiles = function () {
return $scope.files.filter(f => !!f).length;
};
}
module.exports = FormulaFileController; |
var R = require('ramda');
var Economy = module.exports = {};
function gdpPerHourWorked(capital,labor, productivity){
return R.min([capital, labor, productivity]);
}
Economy.gdpPerCapita = function gdpPerCapita(gdp, population) {
return gdp / population;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.