code
stringlengths 2
1.05M
|
|---|
try {
return cache()
} catch (ex) {
try {
return server()
} catch (ex) {
return 'default'
}
}
|
global.Thousand = 1000; //For readability of number literals in code
global.tryRequire = (path, silent = false) => {
let mod;
try{
mod = require(path);
} catch(e) {
if( e.message && e.message.indexOf('Unknown module') > -1 ){
if(!silent) Logger.error(`Module "${path}" not found!`);
} else if(mod == null) {
Logger.error(`Error loading module "${path}"!<br/>${e.stack || e.toString()}`);
}
mod = null;
}
return mod;
};
global.C = {
USERNAME: 'Lucky777777',
SIGN_TEXT: 'A little mutation?',
OWNED_ROOM: 'owned room',
EXTERNAL_ROOM: 'external room',
HIGH_WAY: 'high way',
CENTER_ROOM: 'center room',
KEEPER_ROOM: 'keeper room',
STATE: {
IDLE_CREEPS: 'idleCreeps'
},
/*
========================================
harvest energy from source and haul it
========================================
source ----------> container/ground --------> storage
harvester hauler
----------------------> spawns/extensions
hauler(if no storage)
----------------------> keeper
hauler(if no storage)
----------------------> controllerContainer
hauler(if no storage)
link --------> spawns/extensions
filler
--------> StructureController
upgrader
========================================
if storage present, do this pattern
========================================
storage --------> structures
builder
--------> spawns/extensions ------------> Creeps
filler spawnCreep
--------> towers -------------> RoomObjects
keeper towerAction
--------> controllerContainer/upgrader ---------> StructureController
keeper upgrader
========================================
if no storage, fall back to this pattern
========================================
controllerContainer ----------> structures
builder
so keeper redistribute energy from storage or self to towers/upgraders(its container if present)
*/
//=== Base role ===
WORKER: 'worker',
HARVESTER: 'harvester',
HAULER: 'hauler',
UPGRADER: 'upgrader',
BUILDER: 'builder',
WALLMAINTAINER: 'wallmaintainer',
FILLER: 'filler',
KEEPER: 'keeper',
MINER: 'miner',
//=== Defense role ===
GUARDIAN: 'guardian', //honour rampart and fight invaders
//=== Special role ===
RECYCLER: 'recycler', //drive creep to put resources into storage and let spawn recycle self
//=== Multiroom role ===
SCOUT: 'scout', //travel between rooms and provide vision of the room it stayed
RESERVER: 'reserver', //go to target room and reserve controller in that room
REMOTE_WORKER: 'Rworker', //go to target room, get energy and haul it back
REMOTE_HARVESTER: 'Rharvester', //go to target room and be a miner in that room
REMOTE_HAULER: 'Rhauler', //travel and haul energy between rooms
CLAIMER: 'claimer', //go to target room and claim controller in that room
PIONEER: 'pioneer', //go to target room, build a spawn and upgrade controller until RCL 3
};
global.cli = require('util_cli');
const DefaultConfig = require('config_default');
const OverrideConfig = tryRequire('config_override', true) || {};
global.Config = _.defaultsDeep(OverrideConfig, DefaultConfig);
global.RoleObj = require('role_obj');
global.ActionObj = require('action_obj');
global.SetupObj = require('setup_obj');
global.ColorMapper = ['NONE',
'COLOR_RED', 'COLOR_PURPLE', 'COLOR_BLUE', 'COLOR_CYAN',
'COLOR_GREEN', 'COLOR_YELLOW', 'COLOR_ORANGE', 'COLOR_BROWN',
'COLOR_GREY', 'COLOR_WHITE'];
//WHITE for top level task
//GREY for low level task
//BROWN for special use
//YELLOW for anchor
//RED for combat task
global.FlagUtil = {
//=========Anchor=========
bunkerAnchor: {
color: COLOR_YELLOW,
secondaryColor: COLOR_WHITE
},
//=========Top level=========
// base is a combination of spawning, mining, building and upgrading
base: {
color: COLOR_WHITE,
secondaryColor: COLOR_WHITE,
},
// outpost is a combination of spawning, mining
// once this task is finished, it will be convert to a base task
outpost: {
color: COLOR_WHITE,
secondaryColor: COLOR_GREY,
},
remoteMining: {
color: COLOR_WHITE,
secondaryColor: COLOR_BROWN,
},
//=========Low level=========
working: {
color: COLOR_GREY,
secondaryColor: COLOR_WHITE,
parent: 'base',
},
spawning: {
color: COLOR_GREY,
secondaryColor: COLOR_GREY,
parent: 'base',
},
mining: {
color: COLOR_GREY,
secondaryColor: COLOR_BROWN,
parent: 'base',
},
building: {
color: COLOR_GREY,
secondaryColor: COLOR_ORANGE,
parent: 'base',
},
upgrading: {
color: COLOR_GREY,
secondaryColor: COLOR_YELLOW,
parent: 'base',
},
defending: {
color: COLOR_ORANGE,
secondaryColor: COLOR_GREEN,
parent: 'base',
},
//=============================
// create this, set its memory and convert it to useful task flag
empty: {
color: COLOR_BROWN,
secondaryColor: COLOR_WHITE,
},
//Depreated not used!
dismantle: {
color: COLOR_RED,
secondaryColor: COLOR_RED,
},
guard: {
color: COLOR_BLUE,
secondaryColor: COLOR_BLUE,
},
};
(function() {
function makeExamineFunc(constant) {
return o => {
//Check parent
const parent= constant.parent;
if(parent) {
const parentFlag = FlagUtil[parent];
if(parentFlag) {
return o.color===parentFlag.color && o.secondaryColor===parentFlag.secondaryColor;
} else {
Logger.warning('Undefined parentFlag!');
}
}
return o.color==constant.color && o.secondaryColor==constant.secondaryColor;
};
};
function makeDescribeFunc(constant) {
return () => [ColorMapper[constant.color], ColorMapper[constant.secondaryColor]];
};
_.forEach(FlagUtil, o => {
o.examine = makeExamineFunc(o);
o.describe = makeDescribeFunc(o);
});
})();
global.Action = {
Harvest: require('action_harvest'),
Mine: require('action_mine'),
Fill: require('action_fill'),
Idle: require('action_idle'),
Upgrade: require('action_upgrade'),
Build: require('action_build'),
FromContainer: require('action_fromContainer'),
FromTombstone: require('action_fromTombstone'),
FromStorage: require('action_fromStorage'),
FromTerminal: require('action_fromTerminal'),
FromLink: require('action_fromLink'),
Put: require('action_put'),
Help: require('action_help'),
PutToStorage: require('action_putToStorage'),
PutForUpgrade: require('action_putForUpgrade'),
PutToLink: require('action_putToLink'),
PutToTerminal: require('action_putToTerminal'),
PutToKeeper: require('action_putToKeeper'),
Fuel: require('action_fuel'),
Guard: require('action_guard'),
Pickup: require('action_pickup'),
Drop: require('action_drop'),
Maintain: require('action_maintain'),
Fortify: require('action_fortify'),
Repair: require('action_repair'),
Recycle: require('action_recycle'),
Dismantle: require('action_dismantle'),
Invade: require('action_invade'),
Travel: require('action_travel'),
Back: require('action_back'),
Reserve: require('action_reserve'),
Heal: require('action_heal'),
Claim: require('action_claim'),
Sign: require('action_sign'),
Renew: require('action_renew'),
};
global.Setup = {
[C.WORKER]: require('setup_worker'),
[C.HARVESTER]: require('setup_harvester'),
[C.MINER]: require('setup_miner'),
[C.UPGRADER]: require('setup_upgrader'),
[C.BUILDER]: require('setup_builder'),
[C.WALLMAINTAINER]: require('setup_wallmaintainer'),
[C.HAULER]: require('setup_hauler'),
[C.GUARDIAN]: require('setup_guardian'),
[C.FILLER]: require('setup_filler'),
[C.KEEPER]: require('setup_keeper'),
[C.SCOUT]: require('setup_scout'),
[C.REMOTE_WORKER]: require('setup_remoteWorker'),
[C.REMOTE_HARVESTER]: require('setup_remoteHarvester'),
[C.REMOTE_HAULER]: require('setup_remoteHauler'),
[C.RESERVER]: require('setup_reserver'),
[C.CLAIMER]: require('setup_claimer'),
[C.PIONEER]: require('setup_pioneer'),
};
global.Role = {
[C.WORKER]: require('role_worker'),
[C.HARVESTER]: require('role_harvester'),
[C.MINER]: require('role_miner'),
[C.UPGRADER]: require('role_upgrader'),
[C.BUILDER]: require('role_builder'),
[C.WALLMAINTAINER]: require('role_wallmaintainer'),
[C.HAULER]: require('role_hauler'),
[C.GUARDIAN]: require('role_guardian'),
[C.RECYCLER]: require('role_recycler'),
[C.FILLER]: require('role_filler'),
[C.KEEPER]: require('role_keeper'),
[C.SCOUT]: require('role_scout'),
[C.REMOTE_WORKER]: require('role_remoteWorker'),
[C.REMOTE_HARVESTER]: require('role_remoteHarvester'),
[C.REMOTE_HAULER]: require('role_remoteHauler'),
[C.RESERVER]: require('role_reserver'),
[C.CLAIMER]: require('role_claimer'),
[C.PIONEER]: require('role_pioneer'),
};
global.Util = {
Logger: require('util_logger'),
Defense: require('util_defense'),
Mark: require('util_mark'),
SourceMark: require('util_sourcemark'),
Smalltask: require('util_smalltask'),
Stat: require('util_stat'),
Helper: require('util_helper'),
Movement: require('util_movement'),
Observer: require('util_observer'),
};
//Shorthand
global.Logger = Util.Logger;
global.State= {};
|
import _ from 'underscore';
export class SelectionResolver {
constructor(gridView) {
this.gridView = gridView;
}
updateItems() {
return this.patch({});
}
selectRow() {
throw new Error('Not Supported');
}
deselectRow() {
throw new Error('Not Supported');
}
selectAll() {
throw new Error('Not Supported');
}
deselectAll() {
throw new Error('Not Supported');
}
patch(options) {
const selectionCur = this.gridView.get('selection');
const selection = _.isFunction(options) ? options(selectionCur) : options;
return _.defaults(selection, selectionCur);
}
}
|
/*eslint no-underscore-dangle:0*/
'use strict';
/*!
* Module dependencies
*/
var AWS, DOC; // loaded JIT with settings
var util = require('util');
var Connector = require('loopback-connector').Connector;
var async = require('async');
var MAX_BATCH_SIZE = 25;
// Load parse library with custom operators for DynamoDB
var parse = require('jsep');
var binaries = ["BETWEEN","AND","IN","OR","="];
var unaries = ["SET", "REMOVE", "ADD", "NOT"];
binaries.forEach(function(b) { parse.addBinaryOp(b,10); });
unaries.forEach(function(u) { parse.addUnaryOp(u,10); });
var uuid = require('node-uuid');
var debug = false;
try {
debug = require('debug')('dynamo');
} catch(err) {
//we have installed this package somewhere else and devDependencies are not installed.
}
/**
* The constructor for the DynamoDB connector
* @param {Object} client The DOC.DynamoDB client object
* @param {Object} dataSource The data source instance
* @constructor
*/
function DynamoDB(client, dataSource) {
Connector.call(this, 'dynamodb', dataSource.settings);
this.client = client;
this.dataSource = dataSource;
}
util.inherits(DynamoDB, Connector);
/**
* Test connection to DynamoDB
* @param {Function} [cb] The callback function
*
* @callback cb
* @param {Error} err The error object
* @param {Client} client The DynamoDB DOC object
*/
DynamoDB.prototype.connect = function(cb) {
var self = this;
if (self.client) {
process.nextTick(function () {
if (cb) {
cb(null, self.client);
}
});
} else {
if (cb) {
cb(null, self.client);
}
}
};
/**
* Get types associated with the connector
* @returns {String[]} The types for the connector
*/
DynamoDB.prototype.getTypes = function() {
return ['db', 'nosql'];
};
/**
* Get the default data type for ID
* @returns {Function} The default type for ID
*/
DynamoDB.prototype.getDefaultIdType = function() {
return String;
};
/**
* Create a new model instance for the given data
* @param {String} model The model name
* @param {Object} entity The primary model entity
* @param {Object} document The document data to be created
* @param {Object} properties The defined dcoument properties
* @param {String} projection The path from the primary entity root to the document
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.createDocument = function (model, entity, document, properties, projection, cb) {
var me = this;
var ppath = parameterizePath(projection);
var params = {
Key: me.getPrimaryKeyValues(model, entity),
TableName: me.tableName(model),
UpdateExpression: "SET " + ppath.path + " = :document",
ExpressionAttributeValues: { ":document": document },
ExpressionAttributeNames: ppath.ExpressionAttributeNames,
ReturnValues: "ALL_NEW"
};
me.client.updateItem(params, function(err, data) {
if(err) {
debug.enabled && debug(err,params);
cb(err);
}
else cb(null, data.Attributes);
});
}
/**
* Create a new model instance for the given data
* @param {String} model The model name
* @param {Object} entity The primary model entity
* @param {Object} document The document data to be updated
* @param {Object} properties The defined dcoument properties
* @param {String} projection The path from the primary entity root to the document
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.updateDocument = function (model, entity, document, projection, cb) {
var me = this;
var expressions = me.computeExpression(model, document, projection);
var params = {
Key: me.getPrimaryKeyValues(model, entity),
TableName: me.tableName(model),
ReturnValues: "ALL_NEW"
};
for(var exp in expressions)
params[exp] = expressions[exp];
me.client.updateItem(params, function(err, data) {
if(err) {
debug.enabled && debug(err,params);
cb(err);
}
else cb(null, data.Attributes);
});
}
/**
* Create a new model instance for the given data
* @param {String} model The model name
* @param {Object} entity The primary model entity
* @param {String} projection The path from the primary entity root to the document
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.locateDocument = function(model, entity, projection, cb) {
var me = this;
var ppath = parameterizePath(projection);
var params = {
Key: me.getPrimaryKeyValues(model, entity),
TableName: me.tableName(model),
ProjectionExpression: ppath.path,
ExpressionAttributeNames: ppath.ExpressionAttributeNames
};
me.client.getItem(params, function(err, data) {
if(err) {
debug.enabled && debug(err,params);
cb(err);
}
else cb(null, data.Item);
});
}
/**
* Create a new model instance for the given data
* @param {String} model The model name
* @param {Object} entity The primary model entity
* @param {String} projection The path from the primary entity root to the document
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.listDocuments = function(model, entity, projection, cb) {
var me = this;
var ppath = parameterizePath(projection);
var params = {
Key: me.getPrimaryKeyValues(model, entity),
TableName: me.tableName(model),
ProjectionExpression: ppath.path,
ExpressionAttributeNames: ppath.ExpressionAttributeNames
};
me.client.getItem(params, function(err, data) {
if(err) {
debug.enabled && debug(err,params);
cb(err);
}
else cb(null, data.Item);
});
}
/**
* Create a new model instance for the given data
* @param {String} model The model name
* @param {Object} entity The primary model entity
* @param {String} projection The path from the primary entity root to the document
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.delDocument = function(model, entity, projection, cb) {
var me = this;
var ppath = parameterizePath(projection);
var params = {
Key: me.getPrimaryKeyValues(model, entity),
TableName: me.tableName(model),
UpdateExpression: "REMOVE " + ppath.path,
ExpressionAttributeNames: ppath.ExpressionAttributeNames
};
me.client.updateItem(params, function(err, data) {
if(err) {
debug.enabled && debug(err,params);
cb(err);
}
else cb(null, data.Item);
});
}
/**
* Create a new model instance for the given data
* @param {String} model The model name
* @param {Object} data The model data
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.create = function (model, data, cb) {
/* Note: We need to create the table name beforehand since
the table generation will take a few seconds; Or we need to
use the wait API call until the table is created to
proceed to insert records into the table
*/
debug && debug("Create " + model + ".");
debug && debug(data);
var primaryKeys = this.getPrimaryKeyProperties(model),
hashKeyProperty = this.idKey(model),
itemToPut
primaryKeys.forEach(function (primaryKey) {
if (data[primaryKey.key] === undefined) {
if (primaryKey.type === 'S') {
data[primaryKey.key] = uuid.v1();
} else if (primaryKey.type === 'N') {
//Try time since epoch to set it automatically.
data[primaryKey.key] = new Date() / 1;
}
} else if(primaryKey.type === 'N') {
data[primaryKey.key] = Number(data[primaryKey.key]);
}
});
debug && debug("Data after id auto-generated:");
debug && debug(data);
//The dynamo doc library does not like undefined values.
var sanitizedData = this.sanitizeData(data);
itemToPut = sanitizedData;
var params = {
TableName: this.tableName(model),
Item: itemToPut
};
debug && debug("Data after sanitation");
debug && debug(params);
this.client.putItem(params, function(err, data) {
if(err) {
debug.enabled && debug(err,params);
cb(err);
} else {
debug && debug("Put response:");
debug && debug(data);
debug("Create " + model + " success.",itemToPut);
cb(null, itemToPut[hashKeyProperty]);
}
});
};
DynamoDB.prototype.idKey = function (model) {
var primaryKeys = this.getPrimaryKeyProperties(model),
hashKey;
primaryKeys.forEach(function (key) {
if (key.isHash) {
hashKey = key.key;
}
});
return hashKey;
};
DynamoDB.prototype.sanitizeData = function (data, allowUndefined) {
var self = this;
if (data) {
Object.keys(data).forEach(function (key) {
if(!allowUndefined && data[key] === undefined) {
data[key] = null;
}
else if (data[key] === "")
data[key] = null
else if (data[key] instanceof Date) {
data[key] = data[key] / 1;
} else if (util.isArray(data[key])) {
data[key] = data[key].map(function (value) {
var subKey = self.sanitizeData({data:value});
return subKey.data;
});
} else if (typeof data[key] === "object") {
data[key] = self.sanitizeData(data[key]);
}
});
}
return data;
};
/**
* Save the model instance for the given data
* @param {String} model The model name
* @param {Object} data The model data
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.save = function(model, data, cb) {
debug && debug("Save " + model + ".");
debug && debug(data);
this.updateAttributes(model, null, data, cb);
};
/**
* Check if a model instance exists by id
* @param {String} model The model name
* @param {*} id The id value
* @param {Function} [cb] The callback function
*
*/
DynamoDB.prototype.exists = function (model, id, cb) {
debug && debug("Exists " + model + " id: " + id);
id = this.convertId(model, id);
var idWhere = this.getIdWhere(model, id);
this.client.getItem({
TableName: this.tableName(model),
Key: idWhere
}, function (err, data) {
if (err) {
debug.enabled && debug(err,params);
cb(err);
} else {
if(Object.keys(data).length === 0) cb(null, false);
else cb(null, true);
}
});
};
/**
* Find a model instance by id
* @param {String} model The model name
* @param {*} id The id value
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.find = function find(model, id, cb) {
debug && debug("Find single " + model + " id: " + id);
var idWhere = this.getIdWhere(model, id),
self = this,
findParams = {
TableName: this.tableName(model),
Key: idWhere
};
debug && debug(findParams);
this.client.getItem(findParams, function (err, data) {
if (err) {
debug.enabled && debug(err,params);
cb(err);
} else {
self.castDatePropertiesBackToDate(model, data.Item);
cb(null, data.Item);
}
});
};
/**
* Delete a model instance by id
* @param {String} model The model name
* @param {*} id The id value
* @param [cb] The callback function
*/
DynamoDB.prototype.destroy = function destroy(model, id, cb) {
var me = this;
var params = {
TableName: me.tableName(model),
Key: me.getPrimaryKeyValues(model, {id: id})
};
if(id != null)
for(var field in params.Key)
params.Key[field] = this.convertId(model, id);
me.client.deleteItem(params, function(err,data) {
if (err) {
debug.enabled && debug(err,params);
cb(err);
}
else cb(null, data);
});
};
/**
* Retrieve all model IDs.
*
* @param {String} model The model name
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.scanIds = function scanIds(model, callback) {
var me = this;
debug && debug("Getting all " + model + " ids.");
var ids = [];
me.getPrimaryKeyProperties(model).forEach(function(pkp) {
ids.push(pkp.key);
});
var scanParams = {
TableName: me.tableName(model),
ProjectionExpression: ids.join(", ")
};
var items = [], scans = 0;
function scan() {
me.client.scan(scanParams, function(err, data) {
scans++;
if(err) {
callback(err);
debug.enabled && debug("Scan failed:",err);
}
else {
debug.enabled && debug(scans + " scans completed, " + data.Items.length + " items scanned, " + items.length + " items total");
items = items.concat(data.Items);
if(data.LastEvaluatedKey) {
scanParams.ExclusiveStartKey = data.LastEvaluatedKey;
scan();
} else {
callback(null, items);
}
}
});
}
scan();
};
/**
* Find matching model instances by the filter
*
* @param {String} model The model name
* @param {Object} filter The filter
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.all = function all(model, filter, cb) {
debug && debug("Getting all " + model);
debug && debug(filter);
filter = this.convertFilter(model, filter);
/**
* Ideally we would support the full filter syntax for loopback.
* Initially, just going to support the fields.
*** Note -- Object syntax seems to be the only thing supported at this layers
* fields Object, Array, or String
Specify fields to include in or exclude from the response.
See Fields filter.
(*** Note -- NOT SUPPORTED RIGHT NOW
* include String, Object, or Array
Include results from related models, for relations such as belongsTo and hasMany.
See Include filter.)
* limit Number
Limit the number of instances to return.
See Limit filter.
*** Note, order will only work if a range key has been specified properly.
So if this is part of the filter, it's assuming the table was setup to allow
it to be used. Keys: RangeKeyCondition, ScanIndexForward
This will only work if the order property is the range key in the same index
this is being used to query in the "where" object.
* order String
Specify sort order: ascending or descending.
See Order filter.
*** DynamoDB keys LastEvaluatedKey and ExclusiveStartKey as progressive queries are made until limit and skip are met.
* skip (offset) Number
Skip the specified number of instances.
See Skip filter.
*** Note, where will only work in a performant fashion if the primary key, a LocalSecondaryIndex or a GlobalSecondaryIndex
contains all the keys in the where clause. Otherwise, the whole table is scanned. Additionally, the more complex query
notation defined in /loopback-datasource-juggler/lib/dao.js ~line 620 in the documentation for the find
method is NOT fully supported.
Each property in the where clause might have a special "inc" key, which is an array of acceptable values.
* where Object
Specify search criteria; similar to a WHERE clause in SQL.
See Where filter.
**/
//Because dynamodb only returns 1 MB at a time, we might need to query multiple times to populate this array.
var items = [],
conditions = [],
queryParams = {},
properties = filter.where ? Object.keys(filter.where) : null,
findOperation = properties ? "query" : "scan",
whereIsIndexed = true,
me = this;
if (properties) {
properties.forEach(function (property) {
if (!me.isInPrimaryIndex(property)) {
whereIsIndexed = false;
}
});
}
//We have to use scan if the where clause is not indexed.
if (!whereIsIndexed) {
findOperation = "scan";
}
if (!cb) {
cb = filter;
}
queryParams.TableName = this.tableName(model);
if (properties) {
if (findOperation === 'query' && !me.whereCanBeQueried(filter.where)) {
findOperation = "scan";
}
me.addWhereObjectToConditions(queryParams, findOperation, filter.where);
}
if (filter.order && findOperation === "query") {
var order = filter.order.split(' ');
if (order[1] === 'ASC') {
queryParams.ScanIndexForward = true;
} else {
queryParams.ScanIndexForward = false;
}
}
if (filter.fields) {
var fieldsToInclude = [];
if (util.isArray(filter.fields)) {
fieldsToInclude = filter.fields;
} else {
Object.keys(filter.fields).forEach(function (key) {
if (filter.fields[key]) {
fieldsToInclude.push(key);
}
});
}
queryParams.AttributesToGet = fieldsToInclude;
}
if (findOperation === "scan" && !queryParams.AttributesToGet) {
queryParams.Select = 'ALL_ATTRIBUTES';
}
function runQuery(params, cb) {
if (filter.limit) {
var max = filter.skip ? filter.limit + filter.skip : filter.limit;
if (items.length >= max) {
cb(null);
}
}
debug && debug(params);
me.client[findOperation](params, function (err, data) {
if (err) {
debug.enabled && debug(err,params);
cb(err);
return;
}
if (data.Items) {
items = items.concat(data.Items);
}
//If there is more data to read then read it.
if (data.LastEvaluatedKey) {
params.ExclusiveStartKey = data.LastEvaluatedKey;
runQuery(params, cb);
return;
}
cb();
});
}
runQuery(queryParams, function (err) {
if (err) {
debug && debug("Error doing query");
debug && debug(err,queryParams);
cb(err);
return;
}
//At many items as we can find that are near the limit. It may be more items than the limit
//Trim to match the query.
if (filter.limit) {
var maxNumberOfItems = filter.limit,
start = filter.skip ? filter.skip : 0;
if (items.length >= maxNumberOfItems) {
items = items.slice(start, Math.min(maxNumberOfItems + start, items.length));
}
}
process.nextTick(function () {
items.forEach(function (item) {
me.castDatePropertiesBackToDate(model, item);
});
debug && debug("Retrieved :");
debug && debug(items);
if (filter && filter.include) {
me._models[model].model.include(items, filter.include, cb);
} else {
cb(err, items);
}
});
});
};
DynamoDB.prototype.runAll = function (model, where, cb) {
//If no criteria is provided, refuse to perform the costly scan/delete operation.
if (!where) {
this.all(model, cb);
} else {
this.all(
model,
{
"where": where
},
cb
);
}
};
DynamoDB.prototype.batches = function(model, where, cb) {
this.runAll(model, where, function(err, data) {
if(err) return cb(err);
var batches = [];
while(data.length) {
batches.push(data.splice(0, MAX_BATCH_SIZE));
}
cb(null, batches);
});
};
/**
* Delete all instances for the given model
* @param {String} model The model name
* @param {Object} [where] The filter for where
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.destroyAll = function destroyAll(model, where, cb) {
debug && debug("Destroying all " + model);
if (!cb) {
cb = where;
where = null;
}
var table = this.tableName(model);
var me = this;
var handleDestroy = function(items, cb) {
if(!items || !items.length) return cb();
var batchParams = {
RequestItems: {},
ReturnConsumedCapacity: 'NONE',
ReturnItemCollectionMetrics: 'NONE'
},
primaryKeyProperties = me.getPrimaryKeyProperties(model);
batchParams.RequestItems[table] = [];
items.forEach(function (item) {
var deleteRequest = {
DeleteRequest: { Key: {} }
};
primaryKeyProperties.forEach(function (key) {
deleteRequest.DeleteRequest.Key[key.key] = item[key.key];
});
batchParams.RequestItems[table].push(deleteRequest);
});
me.client.batchWriteItem(batchParams, cb);
};
this.batches(model, where, function(err, batches) {
if(err) {
debug.enabled && debug(err);
if(cb) cb(err);
return;
}
async.map(batches, handleDestroy, function(err, results) {
if(err) {
debug.enabled && debug(err);
if(cb) cb(err);
return;
}
cb(null, results);
});
});
};
/**
* Count the number of instances for the given model
*
* @param {String} model The model name
* @param {Function} [cb] The callback function
* @param {Object} filter The filter for where
*
*/
DynamoDB.prototype.count = function count(model, cb, where) {
debug && debug("Performing count on: ");
debug && debug(model);
var properties = where ? Object.keys(where) : [],
conditions = [],
me = this;
this.all(model, {where: where}, function (err, items) {
if (items) {
cb(err, items.length);
} else {
cb(err, null);
}
});
};
DynamoDB.prototype.baseUpdate = function baseUpdate(model, id, data, condition, cb) {
var me = this;
data = me.sanitizeData(data, true);
var expressions = me.computeExpression(model, data);
debug.enabled && debug("expressions:",expressions);
if(!expressions) return cb();
var updateParams = {
TableName: me.tableName(model),
Key: me.getPrimaryKeyValues(model, data),
ReturnValues: "ALL_NEW"
};
for(var exp in expressions)
updateParams[exp] = expressions[exp];
if(condition) {
var conditionParams = me.parameterizeExpressions(condition);
updateParams = me.copyParameters(conditionParams, updateParams);
// copy updated condition
updateParams.ConditionExpression = conditionParams.expressions[0];
}
if(id != null)
for(var field in updateParams.Key)
updateParams.Key[field] = this.convertId(model, id);
debug.enabled && debug(updateParams);
me.client.updateItem(updateParams, function(err,data) {
if(err) {
debug.enabled && debug(updateParams,err);
cb(err);
}
else cb(null, data.Attributes);
});
};
/**
* Update properties for the model instance data
*
* Updates in loopback are implicit merges, so first get the object, then merge it.
*
* @param {String} model The model name
* @param {Object} data The model data
* @param {Function} [cb] The callback function
*
*
* Must have an id -- seems to get called by update and update All in other connectors
*/
DynamoDB.prototype.updateAttributes = function updateAttributes(model, id, data, cb) {
this.baseUpdate(model, id, data, null, cb);
};
/**
* Update all matching instances
* @param {String} model The model name
* @param {Object} entity The entity to be updated
* @callback {Function} cb Callback function
*/
DynamoDB.prototype.updateSingle = function (model, entity, cb) {
debug && debug("UpdateSingle on:");
debug && debug(model);
debug && debug(entity);
this.updateAttributes(model, null, entity, cb);
};
DynamoDB.prototype.updateConditionally = function(model, entity, condition, cb) {
this.baseUpdate(model, null, entity, condition, cb);
};
/**
* Update all matching instances
* @param {String} model The model name
* @param {Object} where The search criteria
* @param {Object} data The property/value pairs to be updated
* @callback {Function} cb Callback function
*/
DynamoDB.prototype.update =
DynamoDB.prototype.updateAll = function (model, where, data, cb) {
var me = this;
debug && debug("Update/UpdateAll on:");
debug && debug(model);
debug && debug(where);
debug && debug(data);
this.runAll(model, where, function (err, items) {
async.each(items, function (item, done) {
for(var field in data)
item[field] = data[field];
me.updateAttributes(model, null, item, done);
}, cb);
});
};
/**
* Clean a Table Name
* @param {String} model Model to select table name from
* @returns String
* @type String
*/
DynamoDB.prototype.tableSanitized = function(model) {
model = model.replace(/[^a-zA-Z0-9_\-\.]/, '');
if (model.length < 3) {
var i = model.length;
while (i < 3) {
model += '_';
i++;
}
} else if (model.length > 255) {
model = model.substring(0, 255);
}
return model;
};
/**
* Perform automigrate for the given models.
*
* @param {String[]} [models] A model name or an array of model names. If not present, apply to all models
* @param {Function} [cb] The callback function
*/
DynamoDB.prototype.automigrate = function (models, cb) {
debug && debug('Performing automigrate on:');
debug && debug(models);
var self = this;
if (self.client && self.dataSource) {
if (self.debug) {
debug('automigrate');
}
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
}
// First arg is a model name
if ('string' === typeof models) {
models = [models];
}
models = models || Object.keys(self._models);
async.each(models, function (model, modelCallback) {
if (self.debug) {
debug('drop ')
}
if (self.dataSource.definitions[model]) {
self.client.deleteTable({
TableName: self.tableName(model)
}, function (err, data) {
var attributeKeys = {},
//Initialize indexes based on special model properties. they don't exist, just do id.
primaryIndex = self.dataSource.definitions[model].settings.primaryIndex || {hashKey: {key: self.idKey(model), type: 'S'}},
globalSecondaryIndices = self.dataSource.definitions[model].settings.indices,
tableParams = {
KeySchema: [{
AttributeName: primaryIndex.hashKey.key,
KeyType: 'HASH'
}],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
if (primaryIndex.rangeKey) {
tableParams.KeySchema.push({
AttributeName: primaryIndex.rangeKey.key,
KeyType: 'RANGE'
});
}
attributeKeys[primaryIndex.hashKey.key] = primaryIndex.hashKey;
if (primaryIndex.rangeKey) {
attributeKeys[primaryIndex.rangeKey.key] = primaryIndex.rangeKey;
}
if (globalSecondaryIndices) {
tableParams.GlobalSecondaryIndexes = [];
globalSecondaryIndexes.forEach(function (index) {
tableParams.GlobalSecondaryIndexes.push({
IndexName: 'UserEmail',
KeySchema: [{
AttributeName: index.hashKey.key,
KeyType: 'HASH'
}, {
AttributeName: index.rangeKey.key,
KeyType: 'RANGE'
}],
Projection: {
ProjectionType: 'ALL'
},
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
});
attributeKeys[index.hashKey.key] = index.hashKey;
if (attributeKeys.rangeKey) {
attributeKeys[index.rangeKey.key] = index.rangeKey;
}
});
}
tableParams.AttributeDefinitions = [];
Object.keys(attributeKeys).forEach(function (key) {
tableParams.AttributeDefinitions.push({
AttributeType: attributeKeys[key].type,
AttributeName: attributeKeys[key].key
});
});
tableParams.TableName = self.tableName(model);
self.client.createTable(tableParams, function (err) {
if (err) {
modelCallback(err);
} else {
modelCallback(null);
}
});
});
} else {
modelCallback();
}
}, function (err) {
debug.enabled && debug(err);
cb(err);
});
} else {
cb();
}
};
DynamoDB.prototype.disconnect = function () {
};
DynamoDB.prototype.ping = function (cb) {
debug && debug("Pinging for a list of tables");
this.client.listTables({}, function(err, data) {
debug && debug(data);
if (err) {
debug.enabled && debug(err);
cb(err); // an error occurred
} else{
cb(err, data); // successful response
}
});
};
/**
* @private
* @param {String} model The name of the model
*
* @returns {String[]} Any model properties that are in the primary key of the dynamo db table. If the model did
* not define the primary key keys, then we assume 'id'.
*/
DynamoDB.prototype.getPrimaryKeyProperties = function (model) {
var primaryKeyProperties = [];
if (this.dataSource.definitions[model] &&
this.dataSource.definitions[model].settings.primaryIndex) {
var primaryKeyDefinition = this.dataSource.definitions[model].settings.primaryIndex;
primaryKeyDefinition.hashKey.isHash = true;
primaryKeyProperties.push(primaryKeyDefinition.hashKey);
if (primaryKeyDefinition.rangeKey) {
primaryKeyDefinition.rangeKey.isRange = true;
primaryKeyProperties.push(primaryKeyDefinition.rangeKey);
}
} else {
primaryKeyProperties.push({
key: this.dataSource.definitions[model].idColumnName() || 'id',
type: 'S',
isHash: true
});
}
return primaryKeyProperties;
};
DynamoDB.prototype.getPrimaryKeyValues = function(model, data) {
var me = this;
var primaryKeyValues = {};
var primaryKeyProperties = this.getPrimaryKeyProperties(model);
primaryKeyProperties.forEach(function (property) {
primaryKeyValues[property.key] = me.convertId(model, data[property.key], property);
});
return primaryKeyValues;
}
DynamoDB.prototype.castDatePropertiesBackToDate = function (model, data) {
var modelDefinition = this.dataSource.definitions[model],
properties = modelDefinition.properties,
property;
Object.keys(properties).forEach(function (key) {
property = properties[key];
if (property && property.type === Date && data && data[key]) {
data[key] = new Date(data[key]);
}
});
};
/**
*
* @private
*/
DynamoDB.prototype.isInPrimaryIndex = function (key, model) {
if (this.dataSource.definitions[model] &&
this.dataSource.definitions[model].settings.primaryIndex) {
var primaryKeyDefinition = this.dataSource.definitions[model].settings.primaryIndex;
return key === primaryKeyDefinition.rangeKey.key || key === primaryKeyDefinition.hashKey.key;
} else {
return key === 'id';
}
};
/**
*
* @private
*
* More information on where operations:
* http://docs.strongloop.com/display/public/LB/Where+filter#Wherefilter-Operators
*
* Here we are checking to see if this where clause requests an operator that does not work for DynamoDB
* querying. This lets us know we have to scan instead.
*
*/
DynamoDB.prototype.whereCanBeQueried = function (whereObject) {
var properties = Object.keys(whereObject),
whereIsQueriable = true;
properties.forEach(function (conditionKey) {
var whereValue = whereObject[conditionKey],
hasNonQueryableAttributes = false;
//The where definition is a complex and not just an equivalancy operation.
if (Object.prototype.toString.call(whereValue) == "[object Object]") {
hasNonQueryableAttributes = !!whereValue.inq ||
!!whereValue.and ||
!!whereValue.or ||
!!whereValue.gt ||
!!whereValue.gte ||
!!whereValue.lt ||
!!whereValue.lte ||
!!whereValue.between ||
!!whereValue.nin ||
!!whereValue.near ||
!!whereValue.neq ||
!!whereValue.like ||
!!whereValue.nlike;
if (hasNonQueryableAttributes) {
whereIsQueriable = false;
}
}
});
return whereIsQueriable;
};
/**
* @private
*/
DynamoDB.prototype.addWhereObjectToConditions = function (params, findOperation, whereObject, operator) {
var properties = Object.keys(whereObject),
me = this;
//For each property in the where condition, decide what to add to the query or scan operation.
properties.forEach(function (conditionKey) {
var whereValue = whereObject[conditionKey];
if (conditionKey === "and") {
whereValue.forEach(function (whereClause) {
me.addWhereObjectToConditions(params, findOperation, whereClause, 'AND');
});
} else if (conditionKey === "or") {
whereValue.forEach(function (whereClause) {
me.addWhereObjectToConditions(params, findOperation, whereClause, 'OR');
});
} else {
me.addConditionToParam(params, findOperation, conditionKey, whereValue, operator || "AND");
}
});
};
/**
* @private
*
*/
DynamoDB.prototype.getIdWhere = function (model, id) {
var idWhere = {};
idWhere[this.idKey(model)] = this.convertId(model, id);
return idWhere;
};
DynamoDB.prototype.convertId = function convertId(model, id, property) {
if(!property) {
var properties = this.getPrimaryKeyProperties(model);
property = properties[0];
if(!property.isHash) property = properties[1];
}
if(property.type == "S") id = String(id);
else if (property.type == "N") id = Number(id);
return id;
}
DynamoDB.prototype.convertFilter = function convertFilter(model, filter) {
var properties = this.getPrimaryKeyProperties(model);
properties.forEach(function(p) {
if(filter.where) {
if(filter.where[p.key]) {
if(filter.where[p.key].inq) return;
filter.where[p.key] = this.convertId(model, filter.where[p.key], p);
}
} else if(filter[p.key]) filter[p.key] = this.convertId(model, filter[p.key]);
}.bind(this));
return filter;
}
// TODO: wrap this functionality in with the main .all implementation
DynamoDB.prototype.range = function (model, id, start, end, callback) {
var properties = this.getPrimaryKeyProperties(model);
var hash = properties[0], range = properties[1];
if(!hash.isHash) hash = properties[1], range = properties[0];
id = this.convertId(model, id, hash);
var params = {
TableName: this.tableName(model),
Select: "ALL_ATTRIBUTES"
};
params.KeyConditions = [
this.client.Condition(hash.key, "EQ", id),
this.client.Condition(range.key, "BETWEEN", start, end)
];
this.client.query(params, function(err, data) {
if(err) callback(err);
else callback(null, data.Items);
});
};
/**
* @private
*
* @param {Object} params The params to the query or scan DynamoDB operation.
* @param {String} operation "scan" or "query"
* @param {String} key The key in the where clause, either a property of the model, or a logical operator.
* @param {Object|String|Number|String[]|Number[]} Whatever the value is in the logical operation.
*
*/
DynamoDB.prototype.addConditionToParam = function (params, operation, key, conditionValue, operator) {
if (key === "and") {
throw new Error("And operator not currently supported");
}
if (key === "or") {
throw new Error("Or operator not currently supported");
}
var attributeShorthand = "#" + key;
//If it is a scan, we have to add expression attributes.
if (operation === "scan") {
params.ExpressionAttributeNames = params.ExpressionAttributeNames || {};
params.ExpressionAttributeValues = params.ExpressionAttributeValues || {};
var expressionAttributeName = {};
params.ExpressionAttributeNames[attributeShorthand] = key;
}
function getExpressionValueToken(value) {
if (!util.isArray(value)) {
var token = value ? ":" + value.toString().replace(/[^a-zA-Z0-9]/g, "") : ":" + value;
if (value === "*") {
token = ":specialStarParamKey";
}
if (!params.ExpressionAttributeValues[token]) {
if (value instanceof Date) {
params.ExpressionAttributeValues[token] = value / 1;
} else {
params.ExpressionAttributeValues[token] = value;
}
}
return token;
} else {
var tokens = [];
value.forEach(function (subValue) {
tokens.push(getExpressionValueToken(subValue));
});
return tokens.join(',');
}
}
//The where definition is a complex and not just an equivalancy operation.
if (Object.prototype.toString.call(conditionValue) == "[object Object]") {
var operators = Object.keys(conditionValue);
if (!params.FilterExpression) {
params.FilterExpression = "";
}
operators.forEach(function (keyValue) {
if (params.FilterExpression !== "") {
params.FilterExpression += " " + operator + " ";
}
//We are already into a scan situation because queries can't support any of this.
switch (keyValue) {
case 'inq':
params.FilterExpression += "(#" + key + " IN (" + getExpressionValueToken(conditionValue.inq) + ")" + ")";
break;
case 'gt':
params.FilterExpression += "(#" + key + " > " + getExpressionValueToken(conditionValue.gt) + ")";
break;
case 'gte':
params.FilterExpression += "(#" + key + " >= " + getExpressionValueToken(conditionValue.gte) + ")";
break;
case 'lt':
params.FilterExpression += "(#" + key + " < " + getExpressionValueToken(conditionValue.lt) + ")";
break;
case 'lte':
params.FilterExpression += "(#" + key + " <= " + getExpressionValueToken(conditionValue.lte) + ")";
break;
case 'between':
params.FilterExpression += "(#" + key + " BETWEEN " + getExpressionValueToken(conditionValue.between[0]) + " AND " + getExpressionValueToken(conditionValue.between[1]) + ")";
break;
case 'nin':
params.FilterExpression += "NOT " + "(#" + key + " IN (" + getExpressionValueToken(conditionValue.nin) + "))"
break;
case 'near':
throw new Error('near is not supported');
break;
case 'neq':
params.FilterExpression += "(#" + key + " <> " + getExpressionValueToken(conditionValue.neq) + ")";
break;
case 'like':
params.FilterExpression += "(contains(#" + key + "," + getExpressionValueToken(conditionValue.like) + "))";
break;
case 'nlike':
params.FilterExpression += "(NOT contains(#" + key + "," + getExpressionValueToken(conditionValue.nlike) + "))";
break;
case 'or':
case 'and':
throw new Error('and and or conditions are not supported');
}
});
} else {
//Simple case -- do equivalency in query/scan notation.
if (operation === 'query') {
params.KeyConditions = params.KeyConditions || [];
params.KeyConditions.push(this.client.Condition(key, "EQ", conditionValue));
} else {
if (!params.FilterExpression) {
params.FilterExpression = "";
} else {
params.FilterExpression += " " + operator + " ";
}
params.FilterExpression += "#" + key + " = " + getExpressionValueToken(conditionValue);
}
}
};
function parameterizePath(path) {
var pieces = path.split(".");
var ean = {}; //ExpressionAttributeNames
var parameters = [];
for(var i = 0; i < pieces.length; i++) {
var param = "#" + pieces[i];
ean[param] = pieces[i];
parameters.push(param);
}
var ppath = parameters.join(".");
return {ExpressionAttributeNames:ean, path: ppath};
}
DynamoDB.prototype.computeExpression = function computeExpression(model, object, projection) {
var uvalues = {};
var unames = {};
var updates = [], removes = [];
var keyFields = {};
var hasNames = false;
this.getPrimaryKeyProperties(model).forEach(function(p) { keyFields[p.key] = true; });
for(var field in object) {
if(field in keyFields) continue;
var value = object[field];
var path = field;
if(projection) path = projection + "." + path;
var param = parameterizePath(path);
if(value === undefined) {
removes.push(param.path);
} else {
var update = param.path + " = :" + field;
updates.push(update);
uvalues[":" + field] = value;
}
for(var name in param.ExpressionAttributeNames) {
unames[name] = param.ExpressionAttributeNames[name];
hasNames = true;
}
}
var uexp = "";
if(updates.length)
uexp += "SET " + updates.join(', ') + " ";
if(removes.length)
uexp += "REMOVE " + removes.join(', ') + " ";
if(!updates.length && !removes.length) return null;
var params = {
UpdateExpression: uexp
};
if(updates.length > 0)
params.ExpressionAttributeValues = uvalues;
if(hasNames)
params.ExpressionAttributeNames = unames;
return params;
}
function findTerminals(tree, lambda) {
switch(tree.type) {
case "Compound":
tree.body.forEach(function(child) { findTerminals(child, lambda); });
break;
case "BinaryExpression":
findTerminals(tree.left, lambda);
findTerminals(tree.right, lambda);
break;
case "MemberExpression":
findTerminals(tree.object, lambda);
findTerminals(tree.property, lambda);
break;
case "UnaryExpression":
findTerminals(tree.argument, lambda);
break;
case "CallExpression":
tree.arguments.forEach(function(child) { findTerminals(child, lambda); });
break;
case "Identifier":
case "Literal":
lambda(tree);
break;
};
}
DynamoDB.prototype.copyParameters = function copyParameters(source, destination) {
// copy names
if(!destination.ExpressionAttributeNames && source.ExpressionAttributeNames)
destination.ExpressionAttributeNames = {};
for(var field in source.ExpressionAttributeNames)
destination.ExpressionAttributeNames[field] = source.ExpressionAttributeNames[field];
// copy values
if(!destination.ExpressionAttributeValues && source.ExpressionAttributeValues)
destination.ExpressionAttributeValues = {};
for(var field in source.ExpressionAttributeValues)
destination.ExpressionAttributeValues[field] = source.ExpressionAttributeValues[field];
["UpdateExpression", "ConditionExpression", "TableName", "Key", "ReturnValues"].forEach(function(f) {
if(source[f]) destination[f] = source[f];
});
return destination;
}
DynamoDB.prototype.parameterizeExpressions = function parameterizeExpressions() {
var expressions = [];
for(var i = 0; i < arguments.length; i++)
if(arguments[i] != null)
expressions.push(arguments[i]);
var values = {}, names = {};
var vcount = 0, ncount = 0;
expressions.forEach(function(expression) {
var tree = parse(expression);
findTerminals(tree, function(item) {
if(item.type == "Literal") {
var replacement = ":val" + vcount++;
values[replacement] = item.value;
vcount++;
} else if(item.type == "Identifier") {
var replacement = "#" + item.name;
names[replacement] = item.name;
ncount++;
}
});
});
expressions.forEach(function(expression, i) {
for(var r in names) {
var rname = names[r];
var re = new RegExp("\\b" + rname + "\\b", "g");
expression = expression.replace(re, r);
}
for(var r in values) {
var rvalue = values[r];
var re;
if(typeof rvalue == 'string') {
re = new RegExp("['\"]?\\b" + rvalue + "\\b['\"]?", "g");
} else {
re = new RegExp("\\b" + rvalue + "\\b", "g");
}
expression = expression.replace(re, r);
}
expressions[i] = expression;
});
var parameterizations = { expressions : expressions };
if(ncount)
parameterizations.ExpressionAttributeNames = names;
if(vcount)
parameterizations.ExpressionAttributeValues = values;
return parameterizations;
};
function merge(base, update) {
if (!base) {
return update;
}
// We cannot use Object.keys(update) if the update is an instance of the model
// class as the properties are defined at the ModelClass.prototype level
for(var key in update) {
var val = update[key];
if(typeof val === 'function') {
continue; // Skip methods
}
base[key] = val;
}
return base;
}
DynamoDB.prototype.tableName = function (model) {
var name = this.getDataSource(model).tableName(model);
var dbName = this.dbName;
if (typeof dbName === 'function') {
name = dbName(name);
}
return name;
};
/**
* Initialize the DynamoDB connector for the given data source
* @param {DataSource} dataSource The data source instance
* @param {Function} [cb] The callback function
*/
exports.initialize = function initializeDataSource(dataSource, cb) {
var settings = dataSource.settings || {};
debug && debug('Initializing dynamo');
// prepare for loading AWS SDK
if (settings.region) {
process.env.AWS_REGION = settings.region;
}
if (settings.credentials === 'shared') {
if (settings.profile) {
process.env.AWS_PROFILE = settings.profile;
}
}
AWS = require('aws-sdk');
DOC = require('dynamodb-doc');
if (!AWS) {
return;
}
var dbConfig = {
region: process.env.AWS_REGION,
apiVersion: settings.dynamoApiVersion
};
if (settings.credentials === 'file') {
AWS.config.loadFromPath(settings.credfile);
//allowing in memory credentials against original repository creator's wishes
} else if (settings.credentials === 'memory') {
dbConfig.credentials = settings.inMemoryCredentials;
}
AWS.config.apiVersions = {
dynamodb: 'latest'
};
if (settings.endpoint) {
dbConfig.endpoint = new AWS.Endpoint(settings.endpoint);
}
var db = new AWS.DynamoDB(dbConfig),
client = new DOC.DynamoDB(db);
debug && debug(settings);
dataSource.connector = new DynamoDB(client, dataSource);
dataSource.connector.dataSource = dataSource;
if (debug) {
debug && debug("Tables present at initialization:");
dataSource.connector.ping(function () {});
}
if (cb) {
dataSource.connector.connect(cb);
}
};
|
import React from 'react';
import { FormattedRelative, FormattedMessage } from 'react-intl';
import moment from 'moment';
export default function HelloWorld() {
return (
<h1 className="hw-headline">
<span>
<FormattedMessage
id="app.helloWorld.greeting"
description="Greeting to welcome the user to the app"
defaultMessage="Hello, {name}! Last Action: {date}"
values={{
name: <i>World</i>,
date: (
<FormattedRelative
value={moment().add(7, 'days')}
options={{ style: 'numeric', units: 'second' }}
/>
)
}}
/>
</span>
</h1>
);
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/builtin/extends"));
var _react = _interopRequireDefault(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _withProps = _interopRequireDefault(require("recompose/withProps"));
var _List = _interopRequireDefault(require("@material-ui/core/List"));
var _BaseMediaList = _interopRequireDefault(require("../../../components/MediaList/BaseMediaList"));
var _Row = _interopRequireDefault(require("./Row"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var HistoryList = (0, _withProps.default)({
className: 'RoomHistory-list',
listComponent: _react.default.forwardRef(function (props, _ref) {
return _react.default.createElement(_List.default, (0, _extends2.default)({}, props, {
ref: function ref(list) {
return _ref(list && _reactDom.default.findDOMNode(list));
} // eslint-disable-line react/no-find-dom-node
}));
}),
rowComponent: _Row.default
})(_BaseMediaList.default);
var _default = HistoryList;
exports.default = _default;
//# sourceMappingURL=HistoryList.js.map
|
module.exports = {
config: {
type: 'radar',
data: {
labels: [0, 1, 2, 3, 4, 5],
datasets: [
{
// option in dataset
data: [0, 5, 10, null, -10, -5],
pointBorderColor: '#ff0000'
},
{
// option in element (fallback)
data: [4, -5, -10, null, 10, 5]
}
]
},
options: {
legend: false,
title: false,
elements: {
line: {
fill: false
},
point: {
borderColor: '#00ff00',
borderWidth: 5,
radius: 10
}
},
scale: {
display: false,
min: -15
}
}
},
options: {
canvas: {
height: 512,
width: 512
}
}
};
|
'use strict';
module.exports = {
SERVER_ERROR: 500,
BAD_GATEWAY: 502,
BAD_PARAMS: 400,
NOT_FOUND: 404,
TEMPORARY_REDIRECT: 301,
PERMANENT_REDIRECT: 302,
NOT_AUTHORIZED: 403
};
|
var getChildren = exports.getChildren = function(elem){
return elem.children;
};
var getParent = exports.getParent = function(elem){
return elem.parent;
};
exports.getSiblings = function(elem){
var parent = getParent(elem);
return parent ? getChildren(parent) : [elem];
};
exports.getAttributeValue = function(elem, name){
return elem.attribs && elem.attribs[name];
};
exports.hasAttrib = function(elem, name){
return !!elem.attribs && hasOwnProperty.call(elem.attribs, name);
};
exports.getName = function(elem){
return elem.name;
};
|
/**
* Paint House
*
* There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of
* painting each house with a certain color is different. You have to paint all the houses such that no two adjacent
* houses have the same color.
*
* The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0]
* is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so
* on...
*
* Find the minimum cost to paint all houses.
*
* Note:
* All costs are positive integers.
*
* Example:
*
* Input: [[17,2,17],[16,16,5],[14,3,19]]
* Output: 10
* Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
* Minimum cost: 2 + 5 + 3 = 10.
*/
/**
* @param {number[][]} costs
* @return {number}
*/
const minCost = costs => {
if (!costs || costs.length === 0) {
return 0;
}
const n = costs.length; // n houses
// costs[i]]j] represents the minimum cost of painting house i with color j
for (let i = 1; i < n; i++) {
costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]);
costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]);
costs[i][2] += Math.min(costs[i - 1][1], costs[i - 1][0]);
}
return Math.min(Math.min(costs[n - 1][0], costs[n - 1][1]), costs[n - 1][2]);
};
export { minCost };
|
/*
* grunt-init-web
* http://github.com/Safareli/grunt-init-web
*
* Copyright (c) 2014 "Safareli" Irakli Safareli
* Licensed under the MIT license.
*/
'use strict';
// Basic template description.
exports.description = 'Create a web development skeleton, with cofeescript, stylus, jade and livereload';
// Template-specific notes to be displayed before question prompts.
// exports.notes = '';
// Template-specific notes to be displayed after question prompts.
exports.after = 'You should now install project dependencies with _npm ' +
'install_. After that, you may execute project tasks with _grunt_. For ' +
'more information about installing and configuring Grunt, please see ' +
'the Getting Started guide:' +
'\n\n' +
'http://gruntjs.com/getting-started';
// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';
// The actual init template.
exports.template = function(grunt, init, done) {
init.process({type: 'node'}, [
// Prompt for these values.
init.prompt('name'),
init.prompt('description'),
init.prompt('version'),
init.prompt('repository'),
init.prompt('homepage'),
init.prompt('bugs'),
init.prompt('licenses', 'MIT'),
init.prompt('author_name'),
init.prompt('author_email'),
init.prompt('author_url'),
init.prompt('node_version', '>= 0.8.0'),
init.prompt('source_dir', 'source'),
init.prompt('build_dir', 'build'),
init.prompt('scripts_dir', 'scripts'),
init.prompt('styles_dir', 'styles'),
init.prompt('livereload_port', '4000'),
init.prompt('server_port', '3000'),
init.prompt('server_hostname', '0.0.0.0')
], function(err, props) {
props.devDependencies = {
"nib": "~1.0.2",
"jade": "~1.3.0",
"grunt": "~0.4.4",
"stylus": "~0.42.3",
"grunt-newer": "~0.7.0",
"grunt-coffeelint": "0.0.8",
"load-grunt-tasks": "~0.2.1",
"grunt-contrib-jade": "~0.11.0",
"grunt-contrib-watch": "~0.6.1",
"grunt-contrib-stylus": "~0.13.2",
"grunt-contrib-connect": "~0.7.1",
"grunt-contrib-coffee": "~0.10.1",
"grunt-contrib-uglify": "~0.3.2",
"grunt-contrib-clean": "~0.5.0"
};
props.keywords = [];
props.__scripts_dir = props.source_dir + '/' + props.scripts_dir;
props.__styles_dir = props.source_dir + '/' + props.styles_dir;
// Files to copy (and process).
var files = init.filesToCopy(props);
// Add properly-named license files.
init.addLicenseFiles(files, props.licenses);
// Actually copy (and process) files.
init.copyAndProcess(files, props);
// Generate package.json file.
init.writePackageJSON('package.json', props);
// All done!
done();
});
};
|
/* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
* Copyright (c) 2010 Mr.doob, rhyolight, bebraw
*/
var DEBUG = true;
var BRUSHES = ["sketchy", "shaded", "chrome", "blur", "fur", "longfur", "web",
"simple", "squares", "ribbon", "circles", "grid", "stringy", "curvy",
"eraser"];
var MODIFIERS = ["array", "group", "horizontalmirror", "verticalmirror",
"radialmirror"];
var PROJECTORS = ["horizontal", "vertical", "target", "radial", "parallel",
"settarget", "cycletarget"];
var PANELS = ["brushes", "canvas", "modifiers", "playback", "palette"];
var COLOR = 'black';
var AMOUNTOFCOLORROWS = 5;
var AMOUNTOFCOLORCOLUMNS = 8;
// palette options
var PALETTECORNERS = {
'topleft': 'black',
'topright': 'gray',
'bottomleft': 'gray',
'bottomright': 'white',
}
// background options
var BACKGROUNDCOLOR = 'darkgray';
// stroke filtering options
var FILTERDISTANCE = 500;
var FILTERLENGTH = 3;
var SHOWPREVIEWIMAGES = false;
var PREVIEWFONTSIZE = '90px';
var PREVIEWBACKGROUNDCOLOR = 'white';
// projection options
var PROJECTIONOVERLAYCOLOR = 'limegreen';
var PROJECTIONOVERLAYALPHA = 0.5;
var PROJECTIONTARGETRADIUS = 10;
var AMOUNTOFTARGETS = 3;
var DISABLEDTARGETCOLOR = 'red';
// hotkeys
var HOTKEYS = {
'projection': {
'horizontal': '1',
'vertical': '2',
'target': '3',
'parallel': '4',
'radial': '5',
'settarget': '6',
'cycletarget': '7'
},
'palette': {
'up': 'i',
'down': 'k',
'left': 'j',
'right': 'l'
},
'brushes': {
'size': {
'toggle': 'q',
'decrease': 'w',
'increase': 'e',
'decreaseJitter': 'r',
'increaseJitter': 't'
},
'opacity': {
'toggle': 'a',
'decrease': 's',
'increase': 'd',
'decreaseJitter': 'f',
'increaseJitter': 'g'
},
'location': {
'decreaseJitter': 'v',
'increaseJitter': 'b'
}
}
};
|
//
// TDigest:
//
// approximate distribution percentiles from a stream of reals
//
var RBTree = require('bintrees').RBTree;
function TDigest(delta, K, CX) {
// allocate a TDigest structure.
//
// delta is the compression factor, the max fraction of mass that
// can be owned by one centroid (bigger, up to 1.0, means more
// compression). delta=false switches off TDigest behavior and treats
// the distribution as discrete, with no merging and exact values
// reported.
//
// K is a size threshold that triggers recompression as the TDigest
// grows during input. (Set it to 0 to disable automatic recompression)
//
// CX specifies how often to update cached cumulative totals used
// for quantile estimation during ingest (see cumulate()). Set to
// 0 to use exact quantiles for each new point.
//
this.discrete = (delta === false);
this.delta = delta || 0.01;
this.K = (K === undefined) ? 25 : K;
this.CX = (CX === undefined) ? 1.1 : CX;
this.centroids = new RBTree(compare_centroid_means);
this.nreset = 0;
this.reset();
}
TDigest.prototype.reset = function() {
// prepare to digest new points.
//
this.centroids.clear();
this.n = 0;
this.nreset += 1;
this.last_cumulate = 0;
};
TDigest.prototype.size = function() {
return this.centroids.size;
};
TDigest.prototype.toArray = function(everything) {
// return {mean,n} of centroids as an array ordered by mean.
//
var result = [];
if (everything) {
this._cumulate(true); // be sure cumns are exact
this.centroids.each(function(c) { result.push(c); });
} else {
this.centroids.each(function(c) { result.push({mean:c.mean, n:c.n}); });
}
return result;
};
TDigest.prototype.summary = function() {
var approx = (this.discrete) ? "exact " : "approximating ";
var s = [approx + this.n + " samples using " + this.size() + " centroids",
"min = "+this.percentile(0),
"Q1 = "+this.percentile(0.25),
"Q2 = "+this.percentile(0.5),
"Q3 = "+this.percentile(0.75),
"max = "+this.percentile(1.0)];
return s.join('\n');
};
function compare_centroid_means(a, b) {
// order two centroids by mean.
//
if (a === null) {
// XXX super-narrow workaround for https://github.com/vadimg/js_bintrees/pull/14
return NaN;
}
return (a.mean > b.mean) ? 1 : (a.mean < b.mean) ? -1 : 0;
}
function compare_centroid_mean_cumns(a, b) {
// order two centroids by mean_cumn.
//
if (a === null) {
// XXX super-narrow workaround for https://github.com/vadimg/js_bintrees/pull/14
return NaN;
}
return (a.mean_cumn - b.mean_cumn);
}
TDigest.prototype.push = function(x, n) {
// incorporate value or array of values x, having count n into the
// TDigest. n defaults to 1.
//
n = n || 1;
x = Array.isArray(x) ? x : [x];
for (var i = 0 ; i < x.length ; i++) {
this._digest(x[i], n);
}
};
TDigest.prototype.push_centroid = function(c) {
// incorporate centroid or array of centroids c
//
c = Array.isArray(c) ? c : [c];
for (var i = 0 ; i < c.length ; i++) {
this._digest(c[i].mean, c[i].n);
}
};
TDigest.prototype._cumulate = function(exact) {
// update cumulative counts for each centroid
//
// exact: falsey means only cumulate after sufficient
// growth. During ingest, these counts are used as quantile
// estimates, and they work well even when somewhat out of
// date. (this is a departure from the publication, you may set CX
// to 0 to disable).
//
if (this.n === this.last_cumulate ||
!exact && this.CX && this.CX > (this.n / this.last_cumulate)) {
return;
}
var cumn = 0;
var self = this;
this.centroids.each(function(c) {
c.mean_cumn = cumn + c.n / 2; // half of n at the mean
cumn = c.cumn = cumn + c.n;
});
this.n = this.last_cumulate = cumn;
};
TDigest.prototype.find_nearest = function(x) {
// find the centroid closest to x. The assumption of
// unique means and a unique nearest centroid departs from the
// paper, see _digest() below
//
if (this.size() === 0) {
return null;
}
var iter = this.centroids.lowerBound({mean:x}); // x <= iter || iter==null
var c = (iter.data() === null) ? iter.prev() : iter.data();
if (c.mean === x || this.discrete) {
return c; // c is either x or a neighbor (discrete: no distance func)
}
var prev = iter.prev();
if (prev && Math.abs(prev.mean - x) < Math.abs(c.mean - x)) {
return prev;
} else {
return c;
}
};
TDigest.prototype._new_centroid = function(x, n, cumn) {
// create and insert a new centroid into the digest (don't update
// cumulatives).
//
var c = {mean:x, n:n, cumn:cumn};
this.centroids.insert(c);
this.n += n;
return c;
};
TDigest.prototype._addweight = function(nearest, x, n) {
// add weight at location x to nearest centroid. adding x to
// nearest will not shift its relative position in the tree and
// require reinsertion.
//
if (x !== nearest.mean) {
nearest.mean += n * (x - nearest.mean) / (nearest.n + n);
}
nearest.cumn += n;
nearest.mean_cumn += n / 2;
nearest.n += n;
this.n += n;
};
TDigest.prototype._digest = function(x, n) {
// incorporate value x, having count n into the TDigest.
//
var min = this.centroids.min();
var max = this.centroids.max();
var nearest = this.find_nearest(x);
if (nearest && nearest.mean === x) {
// accumulate exact matches into the centroid without
// limit. this is a departure from the paper, made so
// centroids remain unique and code can be simple.
this._addweight(nearest, x, n);
} else if (nearest === min) {
this._new_centroid(x, n, 0); // new point around min boundary
} else if (nearest === max ) {
this._new_centroid(x, n, this.n); // new point around max boundary
} else if (this.discrete) {
this._new_centroid(x, n, nearest.cumn); // never merge
} else {
// conider a merge based on nearest centroid's capacity. if
// there's not room for all of n, don't bother merging any of
// it into nearest, as we'll have to make a new centroid
// anyway for the remainder (departure from the paper).
var p = nearest.mean_cumn / this.n;
var max_n = Math.floor(4 * this.n * this.delta * p * (1 - p));
if (max_n - nearest.n >= n) {
this._addweight(nearest, x, n);
} else {
this._new_centroid(x, n, nearest.cumn);
}
}
this._cumulate(false);
if (!this.discrete && this.K && this.size() > this.K / this.delta) {
// re-process the centroids and hope for some compression.
this.compress();
}
};
TDigest.prototype.bound_mean = function(x) {
// find centroids lower and upper such that lower.mean < x <
// upper.mean or lower.mean === x === upper.mean. Don't call
// this for x out of bounds.
//
var iter = this.centroids.upperBound({mean:x}); // x < iter
var lower = iter.prev(); // lower <= x
var upper = (lower.mean === x) ? lower : iter.next();
return [lower, upper];
};
TDigest.prototype.p_rank = function(x_or_xlist) {
// return approximate percentile-ranks (0..1) for data value x.
// or list of x. calculated according to
// https://en.wikipedia.org/wiki/Percentile_rank
//
// (Note that in continuous mode, boundary sample values will
// report half their centroid weight inward from 0/1 as the
// percentile-rank. X values outside the observed range return
// 0/1)
//
// this triggers cumulate() if cumn's are out of date.
//
var xs = Array.isArray(x_or_xlist) ? x_or_xlist : [x_or_xlist];
var ps = xs.map(this._p_rank, this);
return Array.isArray(x_or_xlist) ? ps : ps[0];
};
TDigest.prototype._p_rank = function(x) {
if (this.size() === 0) {
return undefined;
} else if (x < this.centroids.min().mean) {
return 0.0;
} else if (x > this.centroids.max().mean) {
return 1.0;
}
// find centroids that bracket x and interpolate x's cumn from
// their cumn's.
this._cumulate(true); // be sure cumns are exact
var bound = this.bound_mean(x);
var lower = bound[0], upper = bound[1];
var mean_cumn = lower.mean_cumn;
if (!this.discrete && lower !== upper) {
mean_cumn += (x - lower.mean) * (upper.mean_cumn - lower.mean_cumn) / (upper.mean - lower.mean);
}
return mean_cumn / this.n;
};
TDigest.prototype.bound_mean_cumn = function(cumn) {
// find centroids lower and upper such that lower.mean_cumn < x <
// upper.mean_cumn or lower.mean_cumn === x === upper.mean_cumn. Don't call
// this for cumn out of bounds.
//
// XXX because mean and mean_cumn give rise to the same sort order
// (up to identical means), use the mean rbtree for our search.
this.centroids._comparator = compare_centroid_mean_cumns;
var iter = this.centroids.upperBound({mean_cumn:cumn}); // cumn < iter
this.centroids._comparator = compare_centroid_means;
var lower = iter.prev(); // lower <= cumn
var upper = (lower && lower.mean_cumn === cumn) ? lower : iter.next();
return [lower, upper];
};
TDigest.prototype.percentile = function(p_or_plist) {
// for percentage p (0..1), or for each p in a list of ps, return
// the smallest data value q at which at least p percent of the
// observations <= q.
//
// for discrete distributions, this selects q using the Nearest
// Rank Method
// (https://en.wikipedia.org/wiki/Percentile#The_Nearest_Rank_method)
// (in scipy, same as percentile(...., interpolation='higher')
//
// for continuous distributions, interpolates data values between
// count-weighted bracketing means.
//
// this triggers cumulate() if cumn's are out of date.
//
var ps = Array.isArray(p_or_plist) ? p_or_plist : [p_or_plist];
var qs = ps.map(this._percentile, this);
return Array.isArray(p_or_plist) ? qs : qs[0];
};
TDigest.prototype._percentile = function(p) {
if (this.size() === 0) {
return undefined;
}
this._cumulate(true); // be sure cumns are exact
var min = this.centroids.min();
var max = this.centroids.max();
var h = this.n * p;
var bound = this.bound_mean_cumn(h);
var lower = bound[0], upper = bound[1];
if (upper === lower || lower === null || upper === null) {
return (lower || upper).mean;
} else if (!this.discrete) {
return lower.mean + (h - lower.mean_cumn) * (upper.mean - lower.mean) / (upper.mean_cumn - lower.mean_cumn);
} else if (h === lower.mean_cumn) {
return lower.mean;
} else {
return upper.mean;
}
};
function pop_random(choices) {
// remove and return an item randomly chosen from the array of choices
// (mutates choices)
//
var idx = Math.floor(Math.random() * choices.length);
return choices.splice(idx, 1)[0];
}
TDigest.prototype.compress = function() {
// TDigests experience worst case compression (none) when input
// increases monotonically. Improve on any bad luck by
// reconsuming digest centroids as if they were weighted points
// while shuffling their order (and hope for the best).
//
if (this.compressing) {
return;
}
var points = this.toArray();
this.reset();
this.compressing = true;
while (points.length > 0) {
this.push_centroid(pop_random(points));
}
this._cumulate(true);
this.compressing = false;
};
function Digest(config) {
// allocate a distribution digest structure. This is an extension
// of a TDigest structure that starts in exact histogram (discrete)
// mode, and automatically switches to TDigest mode for large
// samples that appear to be from a continuous distribution.
//
this.config = config || {};
this.mode = this.config.mode || 'auto'; // disc, cont, auto
TDigest.call(this, this.mode === 'cont' ? config.delta : false);
this.digest_ratio = this.config.ratio || 0.9;
this.digest_thresh = this.config.thresh || 1000;
this.n_unique = 0;
}
Digest.prototype = Object.create(TDigest.prototype);
Digest.prototype.constructor = Digest;
Digest.prototype.push = function(x_or_xlist) {
TDigest.prototype.push.call(this, x_or_xlist);
this.check_continuous();
};
Digest.prototype._new_centroid = function(x, n, cumn) {
this.n_unique += 1;
TDigest.prototype._new_centroid.call(this, x, n, cumn);
};
Digest.prototype._addweight = function(nearest, x, n) {
if (nearest.n === 1) {
this.n_unique -= 1;
}
TDigest.prototype._addweight.call(this, nearest, x, n);
};
Digest.prototype.check_continuous = function() {
// while in 'auto' mode, if there are many unique elements, assume
// they are from a continuous distribution and switch to 'cont'
// mode (tdigest behavior). Return true on transition from
// disctete to continuous.
if (this.mode !== 'auto' || this.size() < this.digest_thresh) {
return false;
}
if (this.n_unique / this.size() > this.digest_ratio) {
this.mode = 'cont';
this.discrete = false;
this.delta = this.config.delta || 0.01;
this.compress();
return true;
}
return false;
};
module.exports = {
'TDigest': TDigest,
'Digest': Digest
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:8632d5b2bdb30b871a57e622df9b805a3649f022646ca3e1633ba4cf4d08f5fe
size 17011
|
/*
* ajax.js by Meiguro - MIT License
*/
var ajax = (function(){
var formify = function(data) {
var params = [], i = 0;
for (var name in data) {
params[i++] = encodeURIComponent(name) + '=' + encodeURIComponent(data[name]);
}
return params.join('&');
};
var deformify = function(form) {
var params = {};
form.replace(/(?:([^=&]*)=?([^&]*)?)(?:&|$)/g, function(_, name, value) {
if (name) {
params[name] = value || true;
}
return _;
});
return params;
};
/**
* ajax options. There are various properties with url being the only required property.
* @typedef ajaxOptions
* @property {string} [method='get'] - The HTTP method to use: 'get', 'post', 'put', 'delete', 'options',
* or any other standard method supported by the running environment.
* @property {string} url - The URL to make the ajax request to. e.g. 'http://www.example.com?name=value'
* @property {string} [type='text'] - The expected response format. Specify 'json' to have ajax parse
* the response as json and pass an object as the data parameter.
* @property {object} [data] - The request body, mainly to be used in combination with 'post' or 'put'.
* e.g. { username: 'guest' }
* @property {object} headers - Custom HTTP headers. Specify additional headers.
* e.g. { 'x-extra': 'Extra Header' }
* @property {boolean} [async=true] - Whether the request will be asynchronous.
* Specify false for a blocking, synchronous request.
* @property {boolean} [cache=true] - Whether the result may be cached.
* Specify false to use the internal cache buster which appends the URL with the query parameter _
* set to the current time in milliseconds.
*/
/**
* ajax allows you to make various http or https requests.
* See {@link ajaxOptions}
* @global
* @param {ajaxOptions} opt - Options specifying the type of ajax request to make.
* @param {function} success - The success handler that is called when a HTTP 200 response is given.
* @param {function} failure - The failure handler when the HTTP request fails or is not 200.
*/
var ajax = function(opt, success, failure) {
if (typeof opt === 'string') {
opt = { url: opt };
}
var method = opt.method || 'GET';
var url = opt.url;
//console.log(method + ' ' + url);
var onHandler = ajax.onHandler;
if (onHandler) {
if (success) { success = onHandler('success', success); }
if (failure) { failure = onHandler('failure', failure); }
}
if (opt.cache === false) {
var appendSymbol = url.indexOf('?') === -1 ? '?' : '&';
url += appendSymbol + '_=' + new Date().getTime();
}
var req = new XMLHttpRequest();
req.open(method.toUpperCase(), url, opt.async !== false);
var headers = opt.headers;
if (headers) {
for (var name in headers) {
req.setRequestHeader(name, headers[name]);
}
}
var data = null;
if (opt.data) {
if (opt.type === 'json') {
req.setRequestHeader('Content-Type', 'application/json');
data = JSON.stringify(opt.data);
} else {
data = formify(opt.data);
}
}
req.onreadystatechange = function(e) {
if (req.readyState == 4) {
var body = req.responseText;
var failed = req.status != 200;
if (opt.type == 'json') {
try {
body = JSON.parse(body);
}
catch (err) {
failed = true;
}
}
var callback = !failed ? success : failure;
if (callback) {
callback(body, req.status, req);
}
}
};
req.send(data);
};
ajax.formify = formify;
ajax.deformify = deformify;
if (typeof module !== 'undefined') {
module.exports = ajax;
} else {
window.ajax = ajax;
}
return ajax;
})();
|
exports.getResource = function (path, callback) {
var fs = require('fs');
fs.readFile(path, function (err, data) {
if (err) return callback(err, null);
var result = null;
try {
result = JSON.parse(data);
} catch (e) {
return callback(e, null);
}
callback(null, result);
});
};
exports.setResource = function (path, data, callback) {
var fs = require('fs');
var payload = null;
try {
payload = JSON.stringify(data);
} catch (e) {
return callback(e, null);
}
fs.writeFile(path, payload, function (err) {
if (err) return callback(err, null);
callback(null, payload);
});
};
|
var dnode = require( 'dnode' );
var socketio = require( 'socket.io' );
var Hash = require( 'hashish' );
var WebConnector = require( "./connector" );
var STATE_STOPPED = 0
var STATE_STARTED = 1
var ConnectorServer = function ( id , port ) {
if ( !(this instanceof ConnectorServer) ) {
return new ConnectorServer();
}
this.id = id;
this.port = port;
this.server = null;
this.clients = {};
this.state = STATE_STOPPED;
this.anonymousClients = [];
this.dnodeRoomManager = [];
};
module.exports = ConnectorServer;
ConnectorServer.prototype.start = function () {
if ( this.state == STATE_STARTED ) {
return;
}
var server = this.server = socketio.listen( this.port );
server.sockets.on( 'connection' , this.onConnection );
this.state = STATE_STARTED;
console.log( 'ConnectorServer started : ' + this.port + '\n' );
};
ConnectorServer.prototype.stop = function () {
if ( this.state == STATE_STOPPED ) {
return;
}
var self = this;
this.server.server.close( function () {
console.log( 'ConnectorServer closed : ' + self.port + '\n' );
} );
this.removeAnonymousConnectorAll();
this.removeConnectorAll();
this.server = null;
this.state = STATE_STOPPED;
};
ConnectorServer.prototype.onConnection = function ( socket ) {
console.log( 'accepted : ' + socket );
var connector = new WebConnector( this , socket );
this.anonymousClients.push( connector );
};
ConnectorServer.prototype.removeAnonymousConnectorAll = function () {
var clients = this.anonymousClients;
var length = clients.length;
for ( var i = 0 ; i < length ; i++ ) {
clients[i].close();
}
this.anonymousClients = [];
};
ConnectorServer.prototype.removeConnectorAll = function () {
var clients = this.clients;
Hash( clients ).forEach( function ( port , client ) {
client.close();
} );
this.clients = {};
};
ConnectorServer.prototype.removeAnonymousConnector = function ( webConnect ) {
var clients = this.anonymousClients;
var length = clients.length;
for ( var i = 0 ; i < length ; i++ ) {
if ( clients[i] == webConnect ) {
webConnect.close();
clients.splice( i , 1 );
break;
}
}
};
ConnectorServer.prototype.removeConnector = function ( id ) {
delete this.clients[id];
};
ConnectorServer.prototype.onDisconnectClient = function ( webConnector ) {
var id = webConnector.id;
if ( id == null ) {
this.removeAnonymousConnector( webConnector );
return;
}
this.removeConnector( id );
};
|
import React from 'react';
import HamburgerButton from './sidebarComponents/HamburgerButton';
import Sprite from './sidebarComponents/Sprite';
class RightSidebar extends React.Component {
static defaultProps = {
sprites: []
};
render () {
const SPRITES = this.props.sprites.map(
sprite => <Sprite key={sprite.title} icon={sprite.icon}
title={sprite.title} href={sprite.href}
target={sprite.target} />);
return (
<div className="col-md-1 hidden-sm hidden-xs">
<div className="right-sidebar">
<div className="sidebar-nav-item">
<HamburgerButton />
</div>
{SPRITES}
</div>
</div>
);
}
}
export default RightSidebar;
|
'use strict';
var Log = (function () {
function Log() {
}
Log.log = function (message) {
console.log(message);
};
Log.info = function (message) {
console.log(message);
};
Log.warning = function (message) {
console.log(message);
};
Log.error = function (err) {
console.log(err.message);
};
return Log;
}());
exports.Log = Log;
|
'use strict';
/* Controllers */
angular.module('myApp.controllers', [])
.controller('ListStudiesCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.imagedb.query("imreq", "studies", { include_docs: true });
}])
.controller('ViewStudyCtrl', ['$scope', '$rootScope', '$routeParams', function($scope, $rootScope, $routeParams) {
var doc_object = $rootScope.imagedb.newDoc();
doc_object.load($routeParams.studyId)
.success(function () {$scope.study = doc_object});
}])
.controller('EditStudyCtrl', ['$scope', '$rootScope', '$routeParams', '$location', function($scope, $rootScope, $routeParams, $location) {
if ('studyId' in $routeParams) {
var doc_object = $rootScope.imagedb.newDoc();
doc_object.load($routeParams.studyId)
.success(function () {$scope.study = doc_object});
} else {
$scope.study = $scope.imagedb.newDoc();
}
$scope.submitStudy = function() {
$scope.study.save()
.success( function() {
$location.path('/study/' + $scope.study._id);
});
};
$scope.attachClick = function() {
var fileInput = document.getElementById("upload");
console.log(fileInput);
$scope.study.attachMulti(fileInput.files, function () {
fileInput.value = "";
});
};
$scope.removeClick = function() {
$scope.study.remove()
.success(function() {
$location.path('/studies');
});
}
}]);
|
'use strict';
// Load modules
const Code = require('code');
const Joi = require('joi');
// Declare internals
const internals = {};
// Test shortcuts
const expect = Code.expect;
exports.validate = function (schema, config, callback) {
return exports.validateOptions(schema, config, null, callback);
};
exports.validateOptions = function (schema, config, options, callback) {
try {
const compiled = Joi.compile(schema);
for (let i = 0; i < config.length; ++i) {
const item = config[i];
const input = item[0];
const shouldValidate = item[1];
const validationOptions = item[2];
const expectedValueOrError = item[3];
if (!shouldValidate) {
expect(expectedValueOrError, 'Failing tests messages must be tested').to.exist();
}
const result = Joi.validate(input, compiled, validationOptions || options);
const err = result.error;
const value = result.value;
if (err !== null && shouldValidate) {
console.log(err);
}
if (err === null && !shouldValidate) {
console.log(input);
}
expect(err === null).to.equal(shouldValidate);
if (item.length >= 4) {
if (shouldValidate) {
expect(value).to.equal(expectedValueOrError);
}
else {
if (expectedValueOrError instanceof RegExp) {
expect(err.message).to.match(expectedValueOrError);
}
else {
expect(err.message).to.equal(expectedValueOrError);
}
}
}
}
}
catch (err) {
console.error(err.stack);
// Reframe the error location, we don't care about the helper
err.at = internals.thrownAt();
throw err;
}
if (callback) {
callback();
}
};
// Imported from Code
internals.thrownAt = function () {
const error = new Error();
const frame = error.stack.replace(error.toString(), '').split('\n').slice(1).filter((line) => line.indexOf(__filename) === -1)[0];
const at = frame.match(/^\s*at \(?(.+)\:(\d+)\:(\d+)\)?$/);
return {
filename: at[1],
line: at[2],
column: at[3]
};
};
|
// @flow
import Block from "./block";
import Key from "./key";
import Node from "./node";
import Reader from "./reader";
export default class NamedBlock extends Block {
static test (reader: Reader): boolean {
const lb = reader.match("{");
reader.next();
const colon = reader.match(":");
reader.next();
const key = Key.test(reader);
reader.prev();
reader.prev();
return lb && colon && key;
}
key: Key;
constructor (): void {
super();
this.type = Node.NamedBlock;
}
parse (reader: Reader): this {
super.parse(reader);
this.startToken = reader.expect("{");
reader.expect(":");
this.key = new Key().parse(reader);
const endToken = reader.expect("}");
this.finalize(this.startToken, endToken);
return this;
}
}
|
function http(t){return new Promise(function(n,s){function e(t,n){this.status=t,this.message=n}function u(t){return JSON.parse(t)}function r(t){return JSON.stringify(t)}function i(t){t&&Object.keys(t).forEach(function(n){o.setRequestHeader(n,t[n])})}var o=new XMLHttpRequest;o.open(t.method,t.url),o.onload=function(){return this.status>=200&&this.status<300?n(u(o.response)):s(new e(this.status,o.statusText))},o.onerror=function(){return s(new e(this.status,o.statusText))},i(t.headers),o.send(r(t.data))})}
|
"use strict";
var interfaces_1 = require('./util/interfaces');
var errors_1 = require('./util/errors');
var helpers_1 = require('./util/helpers');
var events_1 = require('./util/events');
var path_1 = require('path');
var config_1 = require('./util/config');
var logger_1 = require('./logger/logger');
var webpackApi = require('webpack');
var events_2 = require('events');
var eventEmitter = new events_2.EventEmitter();
var INCREMENTAL_BUILD_FAILED = 'incremental_build_failed';
var INCREMENTAL_BUILD_SUCCESS = 'incremental_build_success';
/*
* Due to how webpack watch works, sometimes we start an update event
* but it doesn't affect the bundle at all, for example adding a new typescript file
* not imported anywhere or adding an html file not used anywhere.
* In this case, we'll be left hanging and have screwed up logging when the bundle is modified
* because multiple promises will resolve at the same time (we queue up promises waiting for an event to occur)
* To mitigate this, store pending "webpack watch"/bundle update promises in this array and only resolve the
* the most recent one. reject all others at that time with an IgnorableError.
*/
var pendingPromises = [];
function webpack(context, configFile) {
context = config_1.generateContext(context);
configFile = config_1.getUserConfigFile(context, taskInfo, configFile);
logger_1.Logger.debug('Webpack: Setting Context on shared singleton');
helpers_1.setContext(context);
var logger = new logger_1.Logger('webpack');
return webpackWorker(context, configFile)
.then(function () {
context.bundleState = interfaces_1.BuildState.SuccessfulBuild;
logger.finish();
})
.catch(function (err) {
context.bundleState = interfaces_1.BuildState.RequiresBuild;
throw logger.fail(err);
});
}
exports.webpack = webpack;
function webpackUpdate(event, path, context, configFile) {
var logger = new logger_1.Logger('webpack update');
var webpackConfig = getWebpackConfig(context, configFile);
logger_1.Logger.debug('webpackUpdate: Starting Incremental Build');
var promisetoReturn = runWebpackIncrementalBuild(false, context, webpackConfig);
events_1.emit(events_1.EventType.WebpackFilesChanged, [path]);
return promisetoReturn.then(function (stats) {
// the webpack incremental build finished, so reset the list of pending promises
pendingPromises = [];
logger_1.Logger.debug('webpackUpdate: Incremental Build Done, processing Data');
return webpackBuildComplete(stats, context, webpackConfig);
}).then(function () {
context.bundleState = interfaces_1.BuildState.SuccessfulBuild;
return logger.finish();
}).catch(function (err) {
context.bundleState = interfaces_1.BuildState.RequiresBuild;
if (err instanceof errors_1.IgnorableError) {
throw err;
}
throw logger.fail(err);
});
}
exports.webpackUpdate = webpackUpdate;
function webpackWorker(context, configFile) {
var webpackConfig = getWebpackConfig(context, configFile);
var promise = null;
if (context.isWatch) {
promise = runWebpackIncrementalBuild(!context.webpackWatch, context, webpackConfig);
}
else {
promise = runWebpackFullBuild(webpackConfig);
}
return promise
.then(function (stats) {
return webpackBuildComplete(stats, context, webpackConfig);
});
}
exports.webpackWorker = webpackWorker;
function webpackBuildComplete(stats, context, webpackConfig) {
// set the module files used in this bundle
// this reference can be used elsewhere in the build (sass)
var files = stats.compilation.modules.map(function (webpackObj) {
if (webpackObj.resource) {
return webpackObj.resource;
}
else {
return webpackObj.context;
}
}).filter(function (path) {
// just make sure the path is not null
return path && path.length > 0;
});
context.moduleFiles = files;
return Promise.resolve();
}
function runWebpackFullBuild(config) {
return new Promise(function (resolve, reject) {
var callback = function (err, stats) {
if (err) {
reject(new errors_1.BuildError(err));
}
else {
resolve(stats);
}
};
var compiler = webpackApi(config);
compiler.run(callback);
});
}
function runWebpackIncrementalBuild(initializeWatch, context, config) {
var promise = new Promise(function (resolve, reject) {
// start listening for events, remove listeners once an event is received
eventEmitter.on(INCREMENTAL_BUILD_FAILED, function (err) {
logger_1.Logger.debug('Webpack Bundle Update Failed');
eventEmitter.removeAllListeners();
handleWebpackBuildFailure(resolve, reject, err, promise, pendingPromises);
});
eventEmitter.on(INCREMENTAL_BUILD_SUCCESS, function (stats) {
logger_1.Logger.debug('Webpack Bundle Updated');
eventEmitter.removeAllListeners();
handleWebpackBuildSuccess(resolve, reject, stats, promise, pendingPromises);
});
if (initializeWatch) {
startWebpackWatch(context, config);
}
});
pendingPromises.push(promise);
return promise;
}
function handleWebpackBuildFailure(resolve, reject, error, promise, pendingPromises) {
// check if the promise if the last promise in the list of pending promises
if (pendingPromises.length > 0 && pendingPromises[pendingPromises.length - 1] === promise) {
// reject this one with a build error
reject(new errors_1.BuildError(error));
return;
}
// for all others, reject with an ignorable error
reject(new errors_1.IgnorableError());
}
function handleWebpackBuildSuccess(resolve, reject, stats, promise, pendingPromises) {
// check if the promise if the last promise in the list of pending promises
if (pendingPromises.length > 0 && pendingPromises[pendingPromises.length - 1] === promise) {
logger_1.Logger.debug('handleWebpackBuildSuccess: Resolving with Webpack data');
resolve(stats);
return;
}
// for all others, reject with an ignorable error
logger_1.Logger.debug('handleWebpackBuildSuccess: Rejecting with ignorable error');
reject(new errors_1.IgnorableError());
}
function startWebpackWatch(context, config) {
logger_1.Logger.debug('Starting Webpack watch');
var compiler = webpackApi(config);
context.webpackWatch = compiler.watch({}, function (err, stats) {
if (err) {
eventEmitter.emit(INCREMENTAL_BUILD_FAILED, err);
}
else {
eventEmitter.emit(INCREMENTAL_BUILD_SUCCESS, stats);
}
});
}
function getWebpackConfig(context, configFile) {
configFile = config_1.getUserConfigFile(context, taskInfo, configFile);
var webpackConfig = config_1.fillConfigDefaults(configFile, taskInfo.defaultConfigFile);
webpackConfig.entry = config_1.replacePathVars(context, webpackConfig.entry);
webpackConfig.output.path = config_1.replacePathVars(context, webpackConfig.output.path);
return webpackConfig;
}
exports.getWebpackConfig = getWebpackConfig;
function getOutputDest(context, webpackConfig) {
return path_1.join(webpackConfig.output.path, webpackConfig.output.filename);
}
exports.getOutputDest = getOutputDest;
function typescriptFileChanged(fileChangedPath, fileCache) {
// convert to the .js file because those are the transpiled files in memory
var jsFilePath = helpers_1.changeExtension(fileChangedPath, '.js');
var sourceFile = fileCache.get(jsFilePath);
var mapFile = fileCache.get(jsFilePath + '.map');
return [sourceFile, mapFile];
}
function otherFileChanged(fileChangedPath) {
return helpers_1.readFileAsync(fileChangedPath).then(function (content) {
return { path: fileChangedPath, content: content };
});
}
var taskInfo = {
fullArg: '--webpack',
shortArg: '-w',
envVar: 'IONIC_WEBPACK',
packageConfig: 'ionic_webpack',
defaultConfigFile: 'webpack.config'
};
|
import React from 'react';
import {Link} from 'react-router';
import {getRandomScrap} from '../server';
import {hashHistory} from 'react-router';
export default class StartPage extends React.Component {
handleFindScrapToFinish(e){
e.stopPropagation();
getRandomScrap((scrapData)=>{
hashHistory.push("scraps/" + scrapData._id + "/finish-scrap");
});
}
render(){
var start = this;
return (
<div className="container text-center">
<Link to="/scraps-create" className="btn btn-default btn-block startpage-btn">
<h1 className="cover-heading">Make a Scrap</h1>
<br />Start half an idea for someone to finish.
</Link>
<br/>
<br/>
<div className="btn btn-default btn-block startpage-btn" onClick={(e)=>{start.handleFindScrapToFinish(e)}}>
Finish a scrapped idea.<br/>
<h1 className="cover-heading">Finish a Scrap</h1>
</div>
</div>
);
}
}
|
/** @ignore */
const Command = require('./../Command');
/** @ignore */
const Module = require('./utils/ChannelModule');
/**
* Modlog Command, allows server managers to toggle the
* modlog module on or off for any given channel.
*
* @extends {Command}
*/
class ModlogCommand extends Command {
/**
* Sets up the command by providing the prefix, command trigger, any
* aliases the command might have and additional options that
* might be usfull for the abstract command class.
*/
constructor() {
super('modlog', ['mlog'], {
allowDM: false,
middleware: [
'require.user:general.manage_server',
'throttle.guild:1,5'
]
});
}
/**
* Executes the given command.
*
* @param {IUser} sender The Discordie user object that ran the command.
* @param {IMessage} message The Discordie message object that triggered the command.
* @param {Array} args The arguments that was parsed to the command.
* @return {mixed}
*/
onCommand(sender, message, args) {
return Module.toggle(message, 'modlog', 'ModLog');
}
}
module.exports = ModlogCommand;
|
var app = angular.module('app', ['ui.router','custCtrl','marginService','angularMoment','ng-mfb']);
app.constant('AUTH_EVENTS', {
notAuthenticated: 'auth-not-authenticated'
})
app.constant('API_ENDPOINT', {
url: 'http://localhost:8000/api'
});
app.run(function ($rootScope, $window, AuthService, AUTH_EVENTS) {
$rootScope.$on('$locationChangeStart', function (event,next, nextParams, fromState) {
if (!AuthService.isAuthenticated()) {
if(next !== "http://127.0.0.1:8000/login.html" || next !== "http://127.0.0.1:8000" || next !== "http://127.0.0.1:8000/signup"){
$window.open('/','_self');
}
}
});
});
app.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/home")
$stateProvider
.state('home', {
url : "/home",
templateUrl : "templates/home_cust.html",
controller : 'custCtrl'
}).state('homeswap', {
url : "/homeswap",
templateUrl : "templates/home_cust_swap.html",
controller : 'custCtrlswap'
}).state('homeforward', {
url : "/homeforward",
templateUrl : "templates/home_cust_forward.html",
controller : 'custCtrl'
}).state('homemoneymarket', {
url : "/homemoneymarket",
templateUrl : "templates/home_cust_mm.html",
controller : 'custCtrl'
})
.state('newoffer', {
url : "/newoffer/:orderid",
templateUrl : "templates/newoffer.jsp",
controller : 'newofferCtrl'
})
.state('login', {
url : "/login",
templateUrl : "login.html"
})
.state('offeraccept', {
url : "/offeraccept/:offerid",
templateUrl : "templates/offeraccept.html",
controller : 'offeracceptCtrl'
}).state('forwardofferaccept', {
url : "/forwardofferaccept/:offerid",
templateUrl : "templates/offeraccept_forward.html",
controller : 'forwardofferacceptCtrl'
}).state('offeraccept_swap', {
url : "/offeraccept_swap/:offerid",
templateUrl : "templates/offeraccept_swap.html",
controller : 'offeracceptswapCtrl'
}).state('offeraccept_mm', {
url : "/offeraccept_mm/:offerid",
templateUrl : "templates/offeraccept_mm.html",
controller : 'offeracceptmmCtrl'
}).state('profile', {
url : "/profile",
templateUrl : "templates/profile_cust.html",
controller : 'profileCtrl'
}).state('rptorders', {
url : "/rptorders",
templateUrl : "templates/rptorders.html",
controller : 'reportCtrl'
}).state('rptconfirmations', {
url : "/rptconfirmations",
templateUrl : "templates/rptconfirmations.html",
controller : 'reportCtrl'
}).state('rptexceptions', {
url : "/rptexceptions",
templateUrl : "templates/rptexceptions.html",
controller : 'reportCtrl'
}).state('rptpayments', {
url : "/rptpayments",
templateUrl : "templates/rptpaymentscust.html",
controller : 'reportCtrl'
}).state('custconfirmations', {
url : "/custconfirmations",
templateUrl : "templates/custconfirmations.html",
controller : 'custconfirmationsCtrl'
}).state('custconfirmations_swap', {
url : "/custconfirmations_swap",
templateUrl : "templates/custconfirmations_swap.html",
controller : 'custconfirmations_swapCtrl'
}).state('custconfirmations_forward', {
url : "/custconfirmations_forward",
templateUrl : "templates/custconfirmations_forward.html",
controller : 'custconfirmations_forwardCtrl'
}).state('custconfirmations_mm', {
url : "/custconfirmations_mm",
templateUrl : "templates/custconfirmations_mm.html",
controller : 'custconfirmationsmmCtrl'
}).state('acceptDetails', {
url : "/acceptDetails/:offerid",
templateUrl : "templates/acceptDetails.html",
controller : 'acceptsdetailsCtrl'
}).state('forwardschedule', {
url : "/forwardschedule/:freq/:nofreq/:startdate/:buyorderamountccy/:buyorderamount/:sellorderamountccy/:sellorderamount",
templateUrl : "templates/forwardschedule.html",
controller : 'sheduleCtrl'
}).state('neworder', {
url : "/neworder",
templateUrl : "templates/neworder.html",
controller : 'neworderCtrl'
}).state('newswap', {
url : "/newswap",
templateUrl : "templates/newswap.html",
controller : 'newswaporderCtrl'
}).state('newforward', {
url : "/newforward",
templateUrl : "templates/newforward.html",
controller : 'newforwardorderCtrl'
}).state('newmoneymarket', {
url : "/newmoneymarket",
templateUrl : "templates/newmoneymarket.html",
controller : 'newmmorderCtrl'
}).state('confirmDetails', {
url : "/confirmDetails",
templateUrl : "templates/payment.html",
controller : 'paymentCtrl'
}).state('confirmoffer', {
url : "/confirmoffer/:offerid",
templateUrl : "templates/confirmbooking.html",
controller : 'confirmofferCtrl'
}).state('confirmofferforward', {
url : "/confirmofferforward/:offerid",
templateUrl : "templates/confirmbookingforward.html",
controller : 'confirmofferforwardCtrl'
}).state('confirmoffermm', {
url : "/confirmoffermm/:offerid",
templateUrl : "templates/confirmbookingmm.html",
controller : 'confirmoffermmCtrl'
}).state('confirmswapoffer', {
url : "/confirmswapoffer/:offerid",
templateUrl : "templates/confirmbookingswap.html",
controller : 'confirmswapofferCtrl'
}).state('payments', {
url : "/payments",
templateUrl : "templates/custpayments.html",
controller : 'custpaymentsCtrl'
}).state('paymentswap', {
url : "/paymentswap",
templateUrl : "templates/custpaymentswap.html",
controller : 'custpaymentsCtrl'
}).state('paymentforward', {
url : "/paymentforward",
templateUrl : "templates/custpaymentforward.html",
controller : 'custpaymentsCtrl'
}).state('paymentmm', {
url : "/paymentmm",
templateUrl : "templates/custpaymentmm.html",
controller : 'custpaymentsCtrl'
})
})
|
Router.configure({
// we use the master template to define the layout for the entire app
layoutTemplate: 'masterPublic',
// the notFound template is used for unknown routes and missing lists
notFoundTemplate: 'notFound',
// show the loading template whilst the subscriptions below load their data
loadingTemplate: 'loading',
yieldRegions: {
'headerNav': {
to: 'headerNav'
},
'sideNav': {
to: 'sideNav'
}
},
controller: 'ApplicationController'
});
Router.route('accessDenied', function() {
var req = this.request;
var res = this.response;
res.writeHead(403);
res.end('403 Access Denied.');
}, {
where: "server"
});
//auth
Router.route('login', function() {
if (Meteor.userId()) {
Router.go("/");
} else {
this.render();
}
});
Router.route('logout', function() {
Meteor.logout();
Router.go("login");
});
//story
Router.route('/', {
name: 'stories',
template: 'stories'
});
Router.route('story/add');
Router.route('story/edit/:_id', {
data: function() {
return Stories.findOne({
_id: this.params._id,
user: Meteor.userId()
});
},
template: "storyAdd"
});
Router.route('story/:_id', {
data: function() {
return Stories.findOne({
_id: this.params._id,
//user: Meteor.userId() //for the time being everybody can see each others story if knows the id
});
},
template: "storyView"
});
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {
ReactDOMResponderEvent,
ReactDOMResponderContext,
PointerType,
} from 'shared/ReactDOMTypes';
import type {
EventPriority,
ReactEventResponderListener,
} from 'shared/ReactTypes';
import React from 'react';
import {DiscreteEvent, UserBlockingEvent} from 'shared/ReactTypes';
import warning from 'shared/warning';
type PressProps = {|
disabled: boolean,
pressRetentionOffset: {
top: number,
right: number,
bottom: number,
left: number,
},
preventDefault: boolean,
onPress: (e: PressEvent) => void,
onPressChange: boolean => void,
onPressEnd: (e: PressEvent) => void,
onPressMove: (e: PressEvent) => void,
onPressStart: (e: PressEvent) => void,
|};
type PressState = {
activationPosition: null | $ReadOnly<{|
x: number,
y: number,
|}>,
addedRootEvents: boolean,
buttons: 0 | 1 | 4,
isActivePressed: boolean,
isActivePressStart: boolean,
isPressed: boolean,
isPressWithinResponderRegion: boolean,
pointerType: PointerType,
pressTarget: null | Element | Document,
responderRegionOnActivation: null | $ReadOnly<{|
bottom: number,
left: number,
right: number,
top: number,
|}>,
responderRegionOnDeactivation: null | $ReadOnly<{|
bottom: number,
left: number,
right: number,
top: number,
|}>,
ignoreEmulatedMouseEvents: boolean,
activePointerId: null | number,
shouldPreventClick: boolean,
touchEvent: null | Touch,
};
type PressEventType =
| 'press'
| 'pressmove'
| 'pressstart'
| 'pressend'
| 'presschange';
type PressEvent = {|
altKey: boolean,
buttons: 0 | 1 | 4,
clientX: null | number,
clientY: null | number,
ctrlKey: boolean,
defaultPrevented: boolean,
metaKey: boolean,
pageX: null | number,
pageY: null | number,
pointerType: PointerType,
screenX: null | number,
screenY: null | number,
shiftKey: boolean,
target: Element | Document,
timeStamp: number,
type: PressEventType,
x: null | number,
y: null | number,
preventDefault: () => void,
stopPropagation: () => void,
|};
const hasPointerEvents =
typeof window !== 'undefined' && window.PointerEvent !== undefined;
const isMac =
typeof window !== 'undefined' && window.navigator != null
? /^Mac/.test(window.navigator.platform)
: false;
const DEFAULT_PRESS_RETENTION_OFFSET = {
bottom: 20,
top: 20,
left: 20,
right: 20,
};
const targetEventTypes = hasPointerEvents
? ['keydown_active', 'pointerdown_active', 'click_active']
: ['keydown_active', 'touchstart', 'mousedown_active', 'click_active'];
const rootEventTypes = hasPointerEvents
? [
'pointerup_active',
'pointermove',
'pointercancel',
'click',
'keyup',
'scroll',
]
: [
'click',
'keyup',
'scroll',
'mousemove',
'touchmove',
'touchcancel',
// Used as a 'cancel' signal for mouse interactions
'dragstart',
'mouseup_active',
'touchend',
];
function isFunction(obj): boolean {
return typeof obj === 'function';
}
function createPressEvent(
context: ReactDOMResponderContext,
type: PressEventType,
target: Element | Document,
pointerType: PointerType,
event: ?ReactDOMResponderEvent,
touchEvent: null | Touch,
defaultPrevented: boolean,
state: PressState,
): PressEvent {
const timeStamp = context.getTimeStamp();
let clientX = null;
let clientY = null;
let pageX = null;
let pageY = null;
let screenX = null;
let screenY = null;
let altKey = false;
let ctrlKey = false;
let metaKey = false;
let shiftKey = false;
let nativeEvent;
if (event) {
nativeEvent = (event.nativeEvent: any);
({altKey, ctrlKey, metaKey, shiftKey} = nativeEvent);
// Only check for one property, checking for all of them is costly. We can assume
// if clientX exists, so do the rest.
let eventObject;
eventObject = (touchEvent: any) || (nativeEvent: any);
if (eventObject) {
({clientX, clientY, pageX, pageY, screenX, screenY} = eventObject);
}
}
const pressEvent = {
altKey,
buttons: state.buttons,
clientX,
clientY,
ctrlKey,
defaultPrevented,
metaKey,
pageX,
pageY,
pointerType,
screenX,
screenY,
shiftKey,
target,
timeStamp,
type,
x: clientX,
y: clientY,
preventDefault() {
state.shouldPreventClick = true;
if (nativeEvent) {
pressEvent.defaultPrevented = true;
nativeEvent.preventDefault();
}
},
stopPropagation() {
// NO-OP, we should remove this in the future
if (__DEV__) {
warning(
false,
'stopPropagation is not available on event objects created from event responder modules (React Flare). ' +
'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.stopPropagation() }`',
);
}
},
};
return pressEvent;
}
function dispatchEvent(
event: ?ReactDOMResponderEvent,
listener: any => void,
context: ReactDOMResponderContext,
state: PressState,
name: PressEventType,
eventPriority: EventPriority,
): void {
const target = ((state.pressTarget: any): Element | Document);
const pointerType = state.pointerType;
const defaultPrevented =
(event != null && event.nativeEvent.defaultPrevented === true) ||
(name === 'press' && state.shouldPreventClick);
const touchEvent = state.touchEvent;
const syntheticEvent = createPressEvent(
context,
name,
target,
pointerType,
event,
touchEvent,
defaultPrevented,
state,
);
context.dispatchEvent(syntheticEvent, listener, eventPriority);
}
function dispatchPressChangeEvent(
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
const onPressChange = props.onPressChange;
if (isFunction(onPressChange)) {
const bool = state.isActivePressed;
context.dispatchEvent(bool, onPressChange, DiscreteEvent);
}
}
function dispatchPressStartEvents(
event: ReactDOMResponderEvent,
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
state.isPressed = true;
if (!state.isActivePressStart) {
state.isActivePressStart = true;
const nativeEvent: any = event.nativeEvent;
const {clientX: x, clientY: y} = state.touchEvent || nativeEvent;
const wasActivePressed = state.isActivePressed;
state.isActivePressed = true;
if (x !== undefined && y !== undefined) {
state.activationPosition = {x, y};
}
const onPressStart = props.onPressStart;
if (isFunction(onPressStart)) {
dispatchEvent(
event,
onPressStart,
context,
state,
'pressstart',
DiscreteEvent,
);
}
if (!wasActivePressed) {
dispatchPressChangeEvent(context, props, state);
}
}
}
function dispatchPressEndEvents(
event: ?ReactDOMResponderEvent,
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
state.isActivePressStart = false;
state.isPressed = false;
if (state.isActivePressed) {
state.isActivePressed = false;
const onPressEnd = props.onPressEnd;
if (isFunction(onPressEnd)) {
dispatchEvent(
event,
onPressEnd,
context,
state,
'pressend',
DiscreteEvent,
);
}
dispatchPressChangeEvent(context, props, state);
}
state.responderRegionOnDeactivation = null;
}
function dispatchCancel(
event: ReactDOMResponderEvent,
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
state.touchEvent = null;
if (state.isPressed) {
state.ignoreEmulatedMouseEvents = false;
dispatchPressEndEvents(event, context, props, state);
}
removeRootEventTypes(context, state);
}
function isValidKeyboardEvent(nativeEvent: Object): boolean {
const {key, target} = nativeEvent;
const {tagName, isContentEditable} = target;
// Accessibility for keyboards. Space and Enter only.
// "Spacebar" is for IE 11
return (
(key === 'Enter' || key === ' ' || key === 'Spacebar') &&
(tagName !== 'INPUT' &&
tagName !== 'TEXTAREA' &&
isContentEditable !== true)
);
}
// TODO: account for touch hit slop
function calculateResponderRegion(
context: ReactDOMResponderContext,
target: Element,
props: PressProps,
) {
const pressRetentionOffset = context.objectAssign(
{},
DEFAULT_PRESS_RETENTION_OFFSET,
props.pressRetentionOffset,
);
let {left, right, bottom, top} = target.getBoundingClientRect();
if (pressRetentionOffset) {
if (pressRetentionOffset.bottom != null) {
bottom += pressRetentionOffset.bottom;
}
if (pressRetentionOffset.left != null) {
left -= pressRetentionOffset.left;
}
if (pressRetentionOffset.right != null) {
right += pressRetentionOffset.right;
}
if (pressRetentionOffset.top != null) {
top -= pressRetentionOffset.top;
}
}
return {
bottom,
top,
left,
right,
};
}
function getTouchFromPressEvent(nativeEvent: TouchEvent): null | Touch {
const targetTouches = nativeEvent.targetTouches;
if (targetTouches.length > 0) {
return targetTouches[0];
}
return null;
}
function unmountResponder(
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
if (state.isPressed) {
removeRootEventTypes(context, state);
dispatchPressEndEvents(null, context, props, state);
}
}
function addRootEventTypes(
context: ReactDOMResponderContext,
state: PressState,
): void {
if (!state.addedRootEvents) {
state.addedRootEvents = true;
context.addRootEventTypes(rootEventTypes);
}
}
function removeRootEventTypes(
context: ReactDOMResponderContext,
state: PressState,
): void {
if (state.addedRootEvents) {
state.addedRootEvents = false;
context.removeRootEventTypes(rootEventTypes);
}
}
function getTouchById(
nativeEvent: TouchEvent,
pointerId: null | number,
): null | Touch {
const changedTouches = nativeEvent.changedTouches;
for (let i = 0; i < changedTouches.length; i++) {
const touch = changedTouches[i];
if (touch.identifier === pointerId) {
return touch;
}
}
return null;
}
function getTouchTarget(context: ReactDOMResponderContext, touchEvent: Touch) {
const doc = context.getActiveDocument();
return doc.elementFromPoint(touchEvent.clientX, touchEvent.clientY);
}
function updateIsPressWithinResponderRegion(
nativeEventOrTouchEvent: Event | Touch,
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
// Calculate the responder region we use for deactivation if not
// already done during move event.
if (state.responderRegionOnDeactivation == null) {
state.responderRegionOnDeactivation = calculateResponderRegion(
context,
((state.pressTarget: any): Element),
props,
);
}
const {responderRegionOnActivation, responderRegionOnDeactivation} = state;
let left, top, right, bottom;
if (responderRegionOnActivation != null) {
left = responderRegionOnActivation.left;
top = responderRegionOnActivation.top;
right = responderRegionOnActivation.right;
bottom = responderRegionOnActivation.bottom;
if (responderRegionOnDeactivation != null) {
left = Math.min(left, responderRegionOnDeactivation.left);
top = Math.min(top, responderRegionOnDeactivation.top);
right = Math.max(right, responderRegionOnDeactivation.right);
bottom = Math.max(bottom, responderRegionOnDeactivation.bottom);
}
}
const {clientX: x, clientY: y} = (nativeEventOrTouchEvent: any);
state.isPressWithinResponderRegion =
left != null &&
right != null &&
top != null &&
bottom != null &&
x !== null &&
y !== null &&
(x >= left && x <= right && y >= top && y <= bottom);
}
// After some investigation work, screen reader virtual
// clicks (NVDA, Jaws, VoiceOver) do not have co-ords associated with the click
// event and "detail" is always 0 (where normal clicks are > 0)
function isScreenReaderVirtualClick(nativeEvent): boolean {
return (
nativeEvent.detail === 0 &&
nativeEvent.screenX === 0 &&
nativeEvent.screenY === 0 &&
nativeEvent.clientX === 0 &&
nativeEvent.clientY === 0
);
}
function targetIsDocument(target: null | Node): boolean {
// When target is null, it is the root
return target === null || target.nodeType === 9;
}
const pressResponderImpl = {
targetEventTypes,
getInitialState(): PressState {
return {
activationPosition: null,
addedRootEvents: false,
buttons: 0,
isActivePressed: false,
isActivePressStart: false,
isPressed: false,
isPressWithinResponderRegion: true,
pointerType: '',
pressTarget: null,
responderRegionOnActivation: null,
responderRegionOnDeactivation: null,
ignoreEmulatedMouseEvents: false,
activePointerId: null,
shouldPreventClick: false,
touchEvent: null,
};
},
onEvent(
event: ReactDOMResponderEvent,
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
const {pointerType, type} = event;
if (props.disabled) {
removeRootEventTypes(context, state);
dispatchPressEndEvents(event, context, props, state);
state.ignoreEmulatedMouseEvents = false;
return;
}
const nativeEvent: any = event.nativeEvent;
const isPressed = state.isPressed;
switch (type) {
// START
case 'pointerdown':
case 'keydown':
case 'mousedown':
case 'touchstart': {
if (!isPressed) {
const isTouchEvent = type === 'touchstart';
const isPointerEvent = type === 'pointerdown';
const isKeyboardEvent = pointerType === 'keyboard';
const isMouseEvent = pointerType === 'mouse';
// Ignore emulated mouse events
if (type === 'mousedown' && state.ignoreEmulatedMouseEvents) {
return;
}
state.shouldPreventClick = false;
if (isTouchEvent) {
state.ignoreEmulatedMouseEvents = true;
} else if (isKeyboardEvent) {
// Ignore unrelated key events
if (isValidKeyboardEvent(nativeEvent)) {
const {
altKey,
ctrlKey,
metaKey,
shiftKey,
} = (nativeEvent: MouseEvent);
if (nativeEvent.key === ' ') {
nativeEvent.preventDefault();
} else if (
props.preventDefault !== false &&
!shiftKey &&
!metaKey &&
!ctrlKey &&
!altKey
) {
state.shouldPreventClick = true;
}
} else {
return;
}
}
// We set these here, before the button check so we have this
// data around for handling of the context menu
state.pointerType = pointerType;
const pressTarget = (state.pressTarget = context.getResponderNode());
if (isPointerEvent) {
state.activePointerId = nativeEvent.pointerId;
} else if (isTouchEvent) {
const touchEvent = getTouchFromPressEvent(nativeEvent);
if (touchEvent === null) {
return;
}
state.touchEvent = touchEvent;
state.activePointerId = touchEvent.identifier;
}
// Ignore any device buttons except primary/middle and touch/pen contact.
// Additionally we ignore primary-button + ctrl-key with Macs as that
// acts like right-click and opens the contextmenu.
if (
nativeEvent.buttons === 2 ||
nativeEvent.buttons > 4 ||
(isMac && isMouseEvent && nativeEvent.ctrlKey)
) {
return;
}
// Exclude document targets
if (!targetIsDocument(pressTarget)) {
state.responderRegionOnActivation = calculateResponderRegion(
context,
((pressTarget: any): Element),
props,
);
}
state.responderRegionOnDeactivation = null;
state.isPressWithinResponderRegion = true;
state.buttons = nativeEvent.buttons;
dispatchPressStartEvents(event, context, props, state);
addRootEventTypes(context, state);
} else {
// Prevent spacebar press from scrolling the window
if (isValidKeyboardEvent(nativeEvent) && nativeEvent.key === ' ') {
nativeEvent.preventDefault();
}
}
break;
}
case 'click': {
if (state.shouldPreventClick) {
nativeEvent.preventDefault();
}
const onPress = props.onPress;
if (isFunction(onPress) && isScreenReaderVirtualClick(nativeEvent)) {
state.pointerType = 'keyboard';
state.pressTarget = context.getResponderNode();
const preventDefault = props.preventDefault;
if (preventDefault !== false) {
nativeEvent.preventDefault();
}
dispatchEvent(event, onPress, context, state, 'press', DiscreteEvent);
}
break;
}
}
},
onRootEvent(
event: ReactDOMResponderEvent,
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
): void {
let {pointerType, target, type} = event;
const nativeEvent: any = event.nativeEvent;
const isPressed = state.isPressed;
const activePointerId = state.activePointerId;
const previousPointerType = state.pointerType;
switch (type) {
// MOVE
case 'pointermove':
case 'mousemove':
case 'touchmove': {
let touchEvent;
// Ignore emulated events (pointermove will dispatch touch and mouse events)
// Ignore pointermove events during a keyboard press.
if (previousPointerType !== pointerType) {
return;
}
if (
type === 'pointermove' &&
activePointerId !== nativeEvent.pointerId
) {
return;
} else if (type === 'touchmove') {
touchEvent = getTouchById(nativeEvent, activePointerId);
if (touchEvent === null) {
return;
}
state.touchEvent = touchEvent;
}
const pressTarget = state.pressTarget;
if (pressTarget !== null && !targetIsDocument(pressTarget)) {
if (
pointerType === 'mouse' &&
context.isTargetWithinNode(target, pressTarget)
) {
state.isPressWithinResponderRegion = true;
} else {
// Calculate the responder region we use for deactivation, as the
// element dimensions may have changed since activation.
updateIsPressWithinResponderRegion(
touchEvent || nativeEvent,
context,
props,
state,
);
}
}
if (state.isPressWithinResponderRegion) {
if (isPressed) {
const onPressMove = props.onPressMove;
if (isFunction(onPressMove)) {
dispatchEvent(
event,
onPressMove,
context,
state,
'pressmove',
UserBlockingEvent,
);
}
} else {
dispatchPressStartEvents(event, context, props, state);
}
} else {
dispatchPressEndEvents(event, context, props, state);
}
break;
}
// END
case 'pointerup':
case 'keyup':
case 'mouseup':
case 'touchend': {
if (isPressed) {
const buttons = state.buttons;
let isKeyboardEvent = false;
let touchEvent;
if (
type === 'pointerup' &&
activePointerId !== nativeEvent.pointerId
) {
return;
} else if (type === 'touchend') {
touchEvent = getTouchById(nativeEvent, activePointerId);
if (touchEvent === null) {
return;
}
state.touchEvent = touchEvent;
target = getTouchTarget(context, touchEvent);
} else if (type === 'keyup') {
// Ignore unrelated keyboard events
if (!isValidKeyboardEvent(nativeEvent)) {
return;
}
isKeyboardEvent = true;
removeRootEventTypes(context, state);
} else if (buttons === 4) {
// Remove the root events here as no 'click' event is dispatched when this 'button' is pressed.
removeRootEventTypes(context, state);
}
// Determine whether to call preventDefault on subsequent native events.
if (
context.isTargetWithinResponder(target) &&
context.isTargetWithinHostComponent(target, 'a')
) {
const {
altKey,
ctrlKey,
metaKey,
shiftKey,
} = (nativeEvent: MouseEvent);
// Check "open in new window/tab" and "open context menu" key modifiers
const preventDefault = props.preventDefault;
if (
preventDefault !== false &&
!shiftKey &&
!metaKey &&
!ctrlKey &&
!altKey
) {
state.shouldPreventClick = true;
}
}
const pressTarget = state.pressTarget;
dispatchPressEndEvents(event, context, props, state);
const onPress = props.onPress;
if (pressTarget !== null && isFunction(onPress)) {
if (
!isKeyboardEvent &&
pressTarget !== null &&
!targetIsDocument(pressTarget)
) {
if (
pointerType === 'mouse' &&
context.isTargetWithinNode(target, pressTarget)
) {
state.isPressWithinResponderRegion = true;
} else {
// If the event target isn't within the press target, check if we're still
// within the responder region. The region may have changed if the
// element's layout was modified after activation.
updateIsPressWithinResponderRegion(
touchEvent || nativeEvent,
context,
props,
state,
);
}
}
if (state.isPressWithinResponderRegion && buttons !== 4) {
dispatchEvent(
event,
onPress,
context,
state,
'press',
DiscreteEvent,
);
}
}
state.touchEvent = null;
} else if (type === 'mouseup') {
state.ignoreEmulatedMouseEvents = false;
}
break;
}
case 'click': {
// "keyup" occurs after "click"
if (previousPointerType !== 'keyboard') {
removeRootEventTypes(context, state);
}
break;
}
// CANCEL
case 'scroll': {
// We ignore incoming scroll events when using mouse events
if (previousPointerType === 'mouse') {
return;
}
const pressTarget = state.pressTarget;
const scrollTarget = nativeEvent.target;
const doc = context.getActiveDocument();
// If the scroll target is the document or if the press target
// is inside the scroll target, then this a scroll that should
// trigger a cancel.
if (
pressTarget !== null &&
(scrollTarget === doc ||
context.isTargetWithinNode(pressTarget, scrollTarget))
) {
dispatchCancel(event, context, props, state);
}
break;
}
case 'pointercancel':
case 'touchcancel':
case 'dragstart': {
dispatchCancel(event, context, props, state);
}
}
},
onUnmount(
context: ReactDOMResponderContext,
props: PressProps,
state: PressState,
) {
unmountResponder(context, props, state);
},
};
export const PressResponder = React.unstable_createResponder(
'Press',
pressResponderImpl,
);
export function usePress(
props: PressProps,
): ReactEventResponderListener<any, any> {
return React.unstable_useResponder(PressResponder, props);
}
|
/* @flow */
import Container from './Container';
import Row from './Row';
import Col from './Col';
export {
Container,
Row,
Col,
};
|
'use strict';
const VersionChecker = require('ember-cli-version-checker');
// project cache that stores LCA hosts by lazy engine name
// eg, eventually this `WeakMap` will look like:
// {
// projectAObj: {
// testEngineName: Project|LazyEngineHost
// }
// }
const wm = new WeakMap();
/**
* Gets the level of the engine node or the total distance
* from the root
*
* @name getDistanceFromRoot
* @param {EngineAddon} engine The engine
* @returns {number} The distance
*/
function getDistanceFromRoot(engine) {
let distance = 0;
let curr = engine;
while (curr !== engine.project) {
distance++;
curr = curr.parent;
}
return distance;
}
/**
* For a given engine, this finds the lowest common ancestor that is considered a
* host amongst _all_ engines by the same name in the project.
*
* For example, given the following project addon structure:
*
* --Project--
* / \
* / \
* Lazy Engine A \
* Addon A
* |
* |
* Lazy Engine B
* / \
* / \
* Lazy Engine A Lazy Engine C
*
* - The LCA host for Lazy Engine A is the app
* - The LCA host for Lazy Engine B is the app
* - The LCA host for Lazy Engine C is Lazy Engine B
*
* Some context:
*
* The reason for this logic is that we want the host addons for deduplication
* purposes to always be the same, no matter which lazy engine you encounter.
* For instance, if we encounter Lazy Engine A at level 3 we wouldn't want its
* actual hosts host to determine which addons to dedupe; you could run into
* bugs whereby loading lazy engine A via the project won't actually load the
* expected assets & its bundle was created based on deduplication from invalid
* host addons.
*
* The way this is computed is:
*
* - Find all engines by the same name in the project
* - Compute each of their levels (distances from root project)
* - From the above levels, get the minimum level
* - Bring all engines up to the same level (traverse up parent until all levels
* are equal)
* - Check if the parent is strictly equal for all engines at this level and is
* considered a host; if this criteria is true return the parent (or the app for
* top-level project addons), otherwise traverse upward to the parent for each &
* try again
*
* @name findLCAHost
* @param {AddonEngine} engine
* @returns {Addon|Project}
*/
function findLCAHost(engine) {
const { project, name: engineName } = engine;
let cache = wm.get(project);
if (!cache) {
cache = new Map();
wm.set(project, cache);
}
// only compute once for a given engine
// we're using the engine name as the cache key here because regardless of its
// version, lazy engines will always get output to: `engines-dist/${engineName}`
const commonHost = cache.get(engineName);
if (commonHost) {
return commonHost;
}
const checker = VersionChecker.forProject(project);
const allEngines = checker.filterAddonsByName(engineName);
const levels = allEngines.map(currEngine => ({
engine: currEngine,
distance: getDistanceFromRoot(currEngine)
}));
const minLevel = levels.reduce(
(acc, { distance }) => Math.min(acc, distance),
Number.POSITIVE_INFINITY
);
let equivalentLevels = levels.map(
({ distance: currDistance, engine: currEngine }) => {
while (currDistance > minLevel) {
currEngine = currEngine.parent;
currDistance--;
}
return currEngine;
}
);
while (equivalentLevels[0].parent) {
const parentToCheck = equivalentLevels[0].parent;
const areAllParentsEqual = equivalentLevels.reduce((acc, curr) => {
if (!acc) {
return acc;
}
return curr.parent === parentToCheck;
}, true);
const isParentLazyEngine =
parentToCheck &&
parentToCheck.lazyLoading &&
parentToCheck.lazyLoading.enabled === true;
const isParentProject = parentToCheck === project;
if (areAllParentsEqual) {
if (isParentLazyEngine) {
cache.set(engineName, parentToCheck);
return parentToCheck;
}
// if the parent is the project, return the `app`
if (isParentProject) {
cache.set(engineName, equivalentLevels[0].app);
return equivalentLevels[0].app;
}
}
// traverse upwards for each engine/addon
equivalentLevels = equivalentLevels.map(({ parent }) => parent);
}
// this should never be triggered
throw new Error(
`[ember-engines] Could not find a common host for: \`${engineName}\`; its locations are: \`${allEngines
.map(engine => engine.root)
.join(', ')}\``
);
}
module.exports = { findLCAHost };
|
const ReferenceStore = require('../store/reference');
/**
* Built the store in order to the .
* @return {ReferenceStore} - An instanciated reference store.
*/
module.exports = new ReferenceStore();
|
export { default } from 'maximum-plaid/components/plaid-symbol';
|
import Intl from 'intl';
import React from 'react';
import Router from 'react-router';
import routes from './routes';
import {i18nCursor} from './core/state';
import * as scoreboard from './core/api/scoreboard-api';
const app = document.getElementById('root');
scoreboard.init();
Router.run(routes, (Handler) => {
React.render(<Handler {...i18nCursor().toJS()} />, app)
});
|
'use strict';
//Articles service used for articles REST endpoint
angular.module('mean').factory('Articles', ['$resource',
function($resource) {
//return $resource('uri', {}, {});
return $resource('articles/:articleId', {
articleId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
const ByteBuffer = require('bytebuffer');
const SteamID = require('steamid');
const Zlib = require('zlib');
const SteamUserConnection = require('./02-connection.js');
const Schema = require('../protobufs/generated/_load.js');
const EMsg = require('../enums/EMsg.js');
const EResult = require('../enums/EResult.js');
const JOBID_NONE = '18446744073709551615';
const PROTO_MASK = 0x80000000;
const VERBOSE_EMSG_LIST = [
EMsg.Multi,
EMsg.ClientHeartBeat
];
const protobufs = {};
protobufs[EMsg.Multi] = Schema.CMsgMulti;
protobufs[EMsg.ClientHeartBeat] = Schema.CMsgClientHeartBeat;
protobufs[EMsg.ClientLogon] = Schema.CMsgClientLogon;
protobufs[EMsg.ClientLogonGameServer] = Schema.CMsgClientLogon;
protobufs[EMsg.ClientLogOnResponse] = Schema.CMsgClientLogonResponse;
protobufs[EMsg.ClientLogOff] = Schema.CMsgClientLogOff;
protobufs[EMsg.ClientLoggedOff] = Schema.CMsgClientLoggedOff;
protobufs[EMsg.ClientUpdateMachineAuth] = Schema.CMsgClientUpdateMachineAuth;
protobufs[EMsg.ClientUpdateMachineAuthResponse] = Schema.CMsgClientUpdateMachineAuthResponse;
protobufs[EMsg.ClientNewLoginKey] = Schema.CMsgClientNewLoginKey;
protobufs[EMsg.ClientNewLoginKeyAccepted] = Schema.CMsgClientNewLoginKeyAccepted;
protobufs[EMsg.ClientRequestWebAPIAuthenticateUserNonce] = Schema.CMsgClientRequestWebAPIAuthenticateUserNonce;
protobufs[EMsg.ClientRequestWebAPIAuthenticateUserNonceResponse] = Schema.CMsgClientRequestWebAPIAuthenticateUserNonceResponse;
protobufs[EMsg.ClientCMList] = Schema.CMsgClientCMList;
protobufs[EMsg.ClientItemAnnouncements] = Schema.CMsgClientItemAnnouncements;
protobufs[EMsg.ClientRequestItemAnnouncements] = Schema.CMsgClientRequestItemAnnouncements;
protobufs[EMsg.ClientCommentNotifications] = Schema.CMsgClientCommentNotifications;
protobufs[EMsg.ClientRequestCommentNotifications] = Schema.CMsgClientRequestCommentNotifications;
protobufs[EMsg.ClientUserNotifications] = Schema.CMsgClientUserNotifications;
protobufs[EMsg.ClientFSOfflineMessageNotification] = Schema.CMsgClientOfflineMessageNotification;
protobufs[EMsg.ClientFSRequestOfflineMessageCount] = Schema.CMsgClientRequestOfflineMessageCount;
protobufs[EMsg.ClientGamesPlayed] = Schema.CMsgClientGamesPlayed;
protobufs[EMsg.ClientGamesPlayedWithDataBlob] = Schema.CMsgClientGamesPlayed;
protobufs[EMsg.ClientAccountInfo] = Schema.CMsgClientAccountInfo;
protobufs[EMsg.ClientEmailAddrInfo] = Schema.CMsgClientEmailAddrInfo;
protobufs[EMsg.ClientIsLimitedAccount] = Schema.CMsgClientIsLimitedAccount;
protobufs[EMsg.ClientWalletInfoUpdate] = Schema.CMsgClientWalletInfoUpdate;
protobufs[EMsg.ClientLicenseList] = Schema.CMsgClientLicenseList;
protobufs[EMsg.ClientServiceMethodLegacy] = Schema.CMsgClientServiceMethodLegacy;
protobufs[EMsg.ClientServiceMethodLegacyResponse] = Schema.CMsgClientServiceMethodLegacyResponse;
protobufs[EMsg.ClientGMSServerQuery] = Schema.CMsgClientGMSServerQuery;
protobufs[EMsg.GMSClientServerQueryResponse] = Schema.CMsgGMSClientServerQueryResponse;
protobufs[EMsg.ClientPICSChangesSinceRequest] = Schema.CMsgClientPICSChangesSinceRequest;
protobufs[EMsg.ClientPICSChangesSinceResponse] = Schema.CMsgClientPICSChangesSinceResponse;
protobufs[EMsg.ClientPICSProductInfoRequest] = Schema.CMsgClientPICSProductInfoRequest;
protobufs[EMsg.ClientPICSProductInfoResponse] = Schema.CMsgClientPICSProductInfoResponse;
protobufs[EMsg.ClientPICSAccessTokenRequest] = Schema.CMsgClientPICSAccessTokenRequest;
protobufs[EMsg.ClientPICSAccessTokenResponse] = Schema.CMsgClientPICSAccessTokenResponse;
protobufs[EMsg.EconTrading_InitiateTradeRequest] = Schema.CMsgTrading_InitiateTradeRequest;
protobufs[EMsg.EconTrading_InitiateTradeResponse] = Schema.CMsgTrading_InitiateTradeResponse;
protobufs[EMsg.EconTrading_CancelTradeRequest] = Schema.CMsgTrading_CancelTradeRequest;
protobufs[EMsg.EconTrading_InitiateTradeProposed] = Schema.CMsgTrading_InitiateTradeRequest;
protobufs[EMsg.EconTrading_InitiateTradeResult] = Schema.CMsgTrading_InitiateTradeResponse;
protobufs[EMsg.EconTrading_StartSession] = Schema.CMsgTrading_StartSession;
protobufs[EMsg.ClientChangeStatus] = Schema.CMsgClientChangeStatus;
protobufs[EMsg.ClientAddFriend] = Schema.CMsgClientAddFriend;
protobufs[EMsg.ClientAddFriendResponse] = Schema.CMsgClientAddFriendResponse;
protobufs[EMsg.ClientRemoveFriend] = Schema.CMsgClientRemoveFriend;
protobufs[EMsg.ClientFSGetFriendsSteamLevels] = Schema.CMsgClientFSGetFriendsSteamLevels;
protobufs[EMsg.ClientFSGetFriendsSteamLevelsResponse] = Schema.CMsgClientFSGetFriendsSteamLevelsResponse;
protobufs[EMsg.ClientPersonaState] = Schema.CMsgClientPersonaState;
protobufs[EMsg.ClientClanState] = Schema.CMsgClientClanState;
protobufs[EMsg.ClientFriendsList] = Schema.CMsgClientFriendsList;
protobufs[EMsg.ClientRequestFriendData] = Schema.CMsgClientRequestFriendData;
protobufs[EMsg.ClientFriendMsg] = Schema.CMsgClientFriendMsg;
protobufs[EMsg.ClientChatInvite] = Schema.CMsgClientChatInvite;
protobufs[EMsg.ClientFriendMsgIncoming] = Schema.CMsgClientFriendMsgIncoming;
protobufs[EMsg.ClientFriendMsgEchoToSender] = Schema.CMsgClientFriendMsgIncoming;
protobufs[EMsg.ClientFSGetFriendMessageHistory] = Schema.CMsgClientChatGetFriendMessageHistory;
protobufs[EMsg.ClientFSGetFriendMessageHistoryResponse] = Schema.CMsgClientChatGetFriendMessageHistoryResponse;
protobufs[EMsg.ClientFriendsGroupsList] = Schema.CMsgClientFriendsGroupsList;
protobufs[EMsg.AMClientCreateFriendsGroup] = Schema.CMsgClientCreateFriendsGroup;
protobufs[EMsg.AMClientCreateFriendsGroupResponse] = Schema.CMsgClientCreateFriendsGroupResponse;
protobufs[EMsg.AMClientDeleteFriendsGroup] = Schema.CMsgClientDeleteFriendsGroup;
protobufs[EMsg.AMClientDeleteFriendsGroupResponse] = Schema.CMsgClientDeleteFriendsGroupResponse;
protobufs[EMsg.AMClientRenameFriendsGroup] = Schema.CMsgClientManageFriendsGroup;
protobufs[EMsg.AMClientRenameFriendsGroupResponse] = Schema.CMsgClientManageFriendsGroupResponse;
protobufs[EMsg.AMClientAddFriendToGroup] = Schema.CMsgClientAddFriendToGroup;
protobufs[EMsg.AMClientAddFriendToGroupResponse] = Schema.CMsgClientAddFriendToGroupResponse;
protobufs[EMsg.AMClientRemoveFriendFromGroup] = Schema.CMsgClientRemoveFriendFromGroup;
protobufs[EMsg.AMClientRemoveFriendFromGroupResponse] = Schema.CMsgClientRemoveFriendFromGroupResponse;
protobufs[EMsg.ClientPlayerNicknameList] = Schema.CMsgClientPlayerNicknameList;
protobufs[EMsg.AMClientSetPlayerNickname] = Schema.CMsgClientSetPlayerNickname;
protobufs[EMsg.AMClientSetPlayerNicknameResponse] = Schema.CMsgClientSetPlayerNicknameResponse;
protobufs[EMsg.ClientRegisterKey] = Schema.CMsgClientRegisterKey;
protobufs[EMsg.ClientPurchaseResponse] = Schema.CMsgClientPurchaseResponse;
protobufs[EMsg.ClientRequestFreeLicense] = Schema.CMsgClientRequestFreeLicense;
protobufs[EMsg.ClientRequestFreeLicenseResponse] = Schema.CMsgClientRequestFreeLicenseResponse;
protobufs[EMsg.ClientGetNumberOfCurrentPlayersDP] = Schema.CMsgDPGetNumberOfCurrentPlayers;
protobufs[EMsg.ClientGetNumberOfCurrentPlayersDPResponse] = Schema.CMsgDPGetNumberOfCurrentPlayersResponse;
protobufs[EMsg.ClientGetAppOwnershipTicket] = Schema.CMsgClientGetAppOwnershipTicket;
protobufs[EMsg.ClientGetAppOwnershipTicketResponse] = Schema.CMsgClientGetAppOwnershipTicketResponse;
protobufs[EMsg.ClientGameConnectTokens] = Schema.CMsgClientGameConnectTokens;
protobufs[EMsg.ClientAuthList] = Schema.CMsgClientAuthList;
protobufs[EMsg.ClientAuthListAck] = Schema.CMsgClientAuthListAck;
protobufs[EMsg.ClientTicketAuthComplete] = Schema.CMsgClientTicketAuthComplete;
protobufs[EMsg.ClientRequestEncryptedAppTicket] = Schema.CMsgClientRequestEncryptedAppTicket;
protobufs[EMsg.ClientRequestEncryptedAppTicketResponse] = Schema.CMsgClientRequestEncryptedAppTicketResponse;
protobufs[EMsg.ClientCurrentUIMode] = Schema.CMsgClientUIMode;
protobufs[EMsg.ClientVanityURLChangedNotification] = Schema.CMsgClientVanityURLChangedNotification;
protobufs[EMsg.ClientAMGetPersonaNameHistory] = Schema.CMsgClientAMGetPersonaNameHistory;
protobufs[EMsg.ClientAMGetPersonaNameHistoryResponse] = Schema.CMsgClientAMGetPersonaNameHistoryResponse;
protobufs[EMsg.ClientUnlockStreaming] = Schema.CMsgAMUnlockStreaming;
protobufs[EMsg.ClientUnlockStreamingResponse] = Schema.CMsgAMUnlockStreamingResponse;
protobufs[EMsg.ClientGetDepotDecryptionKey] = Schema.CMsgClientGetDepotDecryptionKey;
protobufs[EMsg.ClientGetDepotDecryptionKeyResponse] = Schema.CMsgClientGetDepotDecryptionKeyResponse;
protobufs[EMsg.ClientGetCDNAuthToken] = Schema.CMsgClientGetCDNAuthToken;
protobufs[EMsg.ClientGetCDNAuthTokenResponse] = Schema.CMsgClientGetCDNAuthTokenResponse;
protobufs[EMsg.ClientCheckAppBetaPassword] = Schema.CMsgClientCheckAppBetaPassword;
protobufs[EMsg.ClientCheckAppBetaPasswordResponse] = Schema.CMsgClientCheckAppBetaPasswordResponse;
protobufs[EMsg.ClientKickPlayingSession] = Schema.CMsgClientKickPlayingSession;
protobufs[EMsg.ClientPlayingSessionState] = Schema.CMsgClientPlayingSessionState;
protobufs[EMsg.ClientToGC] = Schema.CMsgGCClient;
protobufs[EMsg.ClientFromGC] = Schema.CMsgGCClient;
protobufs[EMsg.ClientRichPresenceUpload] = Schema.CMsgClientRichPresenceUpload;
protobufs[EMsg.ClientRichPresenceRequest] = Schema.CMsgClientRichPresenceRequest;
protobufs[EMsg.ClientRichPresenceInfo] = Schema.CMsgClientRichPresenceInfo;
protobufs[EMsg.ClientGetEmoticonList] = Schema.CMsgClientGetEmoticonList;
protobufs[EMsg.ClientEmoticonList] = Schema.CMsgClientEmoticonList;
protobufs[EMsg.ClientGetAuthorizedDevicesResponse] = Schema.CMsgClientGetAuthorizedDevices;
protobufs[EMsg.ClientAuthorizeLocalDeviceRequest] = Schema.CMsgClientAuthorizeLocalDeviceRequest;
protobufs[EMsg.ClientAuthorizeLocalDeviceResponse] = Schema.CMsgClientAuthorizeLocalDevice;
protobufs[EMsg.ClientDeauthorizeDeviceRequest] = Schema.CMsgClientDeauthorizeDeviceRequest;
protobufs[EMsg.ClientDeauthorizeDevice] = Schema.CMsgClientDeauthorizeDevice;
protobufs[EMsg.ClientUseLocalDeviceAuthorizations] = Schema.CMsgClientUseLocalDeviceAuthorizations;
// Unified protobufs
protobufs['GameServers.GetServerList#1_Request'] = Schema.CGameServers_GetServerList_Request;
protobufs['GameServers.GetServerList#1_Response'] = Schema.CGameServers_GetServerList_Response;
protobufs['GameServers.GetServerSteamIDsByIP#1_Request'] = Schema.CGameServers_GetServerSteamIDsByIP_Request;
protobufs['GameServers.GetServerSteamIDsByIP#1_Response'] = Schema.CGameServers_IPsWithSteamIDs_Response;
protobufs['GameServers.GetServerIPsBySteamID#1_Request'] = Schema.CGameServers_GetServerIPsBySteamID_Request;
protobufs['GameServers.GetServerIPsBySteamID#1_Response'] = Schema.CGameServers_IPsWithSteamIDs_Response;
protobufs['TwoFactor.AddAuthenticator#1_Request'] = Schema.CTwoFactor_AddAuthenticator_Request;
protobufs['TwoFactor.AddAuthenticator#1_Response'] = Schema.CTwoFactor_AddAuthenticator_Response;
protobufs['TwoFactor.FinalizeAddAuthenticator#1_Request'] = Schema.CTwoFactor_FinalizeAddAuthenticator_Request;
protobufs['TwoFactor.FinalizeAddAuthenticator#1_Response'] = Schema.CTwoFactor_FinalizeAddAuthenticator_Response;
protobufs['TwoFactor.SendEmail#1_Request'] = Schema.CTwoFactor_SendEmail_Request;
protobufs['TwoFactor.SendEmail#1_Response'] = Schema.CTwoFactor_SendEmail_Response;
protobufs['TwoFactor.RemoveAuthenticator#1_Request'] = Schema.CTwoFactor_RemoveAuthenticator_Request;
protobufs['TwoFactor.RemoveAuthenticator#1_Response'] = Schema.CTwoFactor_RemoveAuthenticator_Response;
protobufs['Credentials.GetSteamGuardDetails#1_Request'] = Schema.CCredentials_GetSteamGuardDetails_Request;
protobufs['Credentials.GetSteamGuardDetails#1_Response'] = Schema.CCredentials_GetSteamGuardDetails_Response;
protobufs['Credentials.GetAccountAuthSecret#1_Request'] = Schema.CCredentials_GetAccountAuthSecret_Request;
protobufs['Credentials.GetAccountAuthSecret#1_Response'] = Schema.CCredentials_GetAccountAuthSecret_Response;
protobufs['Credentials.GetCredentialChangeTimeDetails#1_Request'] = Schema.CCredentials_LastCredentialChangeTime_Request;
protobufs['Credentials.GetCredentialChangeTimeDetails#1_Response'] = Schema.CCredentials_LastCredentialChangeTime_Response;
protobufs['PublishedFile.GetDetails#1_Request'] = Schema.CPublishedFile_GetDetails_Request;
protobufs['PublishedFile.GetDetails#1_Response'] = Schema.CPublishedFile_GetDetails_Response;
protobufs['Player.GetGameBadgeLevels#1_Request'] = Schema.CPlayer_GetGameBadgeLevels_Request;
protobufs['Player.GetGameBadgeLevels#1_Response'] = Schema.CPlayer_GetGameBadgeLevels_Response;
protobufs['Player.GetNicknameList#1_Request'] = Schema.CPlayer_GetNicknameList_Request;
protobufs['Player.GetNicknameList#1_Response'] = Schema.CPlayer_GetNicknameList_Response;
protobufs['Player.GetEmoticonList#1_Request'] = Schema.CPlayer_GetEmoticonList_Request;
protobufs['Player.GetEmoticonList#1_Response'] = Schema.CPlayer_GetEmoticonList_Response;
protobufs['Player.GetPrivacySettings#1_Request'] = Schema.CPlayer_GetPrivacySettings_Request;
protobufs['Player.GetPrivacySettings#1_Response'] = Schema.CPlayer_GetPrivacySettings_Response;
protobufs['Player.GetOwnedGames#1_Request'] = Schema.CPlayer_GetOwnedGames_Request;
protobufs['Player.GetOwnedGames#1_Response'] = Schema.CPlayer_GetOwnedGames_Response;
protobufs['Player.GetProfileItemsOwned#1_Request'] = Schema.CPlayer_GetProfileItemsOwned_Request;
protobufs['Player.GetProfileItemsOwned#1_Response'] = Schema.CPlayer_GetProfileItemsOwned_Response;
protobufs['Player.GetProfileItemsEquipped#1_Request'] = Schema.CPlayer_GetProfileItemsEquipped_Request;
protobufs['Player.GetProfileItemsEquipped#1_Response'] = Schema.CPlayer_GetProfileItemsEquipped_Response;
protobufs['Player.GetProfileBackground#1_Request'] = Schema.CPlayer_GetProfileBackground_Request;
protobufs['Player.GetProfileBackground#1_Response'] = Schema.CPlayer_GetProfileBackground_Response;
protobufs['Player.SetProfileBackground#1_Request'] = Schema.CPlayer_SetProfileBackground_Request;
protobufs['Player.SetProfileBackground#1_Response'] = Schema.CPlayer_SetProfileBackground_Response;
protobufs['PlayerClient.NotifyFriendNicknameChanged#1'] = Schema.CPlayer_FriendNicknameChanged_Notification;
protobufs['Econ.GetAssetClassInfo#1_Request'] = Schema.CEcon_GetAssetClassInfo_Request;
protobufs['Econ.GetAssetClassInfo#1_Response'] = Schema.CEcon_GetAssetClassInfo_Response;
protobufs['Store.GetLocalizedNameForTags#1_Request'] = Schema.CStore_GetLocalizedNameForTags_Request;
protobufs['Store.GetLocalizedNameForTags#1_Response'] = Schema.CStore_GetLocalizedNameForTags_Response;
protobufs['Econ.GetTradeOfferAccessToken#1_Request'] = Schema.CEcon_GetTradeOfferAccessToken_Request;
protobufs['Econ.GetTradeOfferAccessToken#1_Response'] = Schema.CEcon_GetTradeOfferAccessToken_Response;
protobufs['ChatRoom.CreateChatRoomGroup#1_Request'] = Schema.CChatRoom_CreateChatRoomGroup_Request;
protobufs['ChatRoom.CreateChatRoomGroup#1_Response'] = Schema.CChatRoom_CreateChatRoomGroup_Response;
protobufs['ChatRoom.SaveChatRoomGroup#1_Request'] = Schema.CChatRoom_SaveChatRoomGroup_Request;
protobufs['ChatRoom.SaveChatRoomGroup#1_Response'] = Schema.CChatRoom_SaveChatRoomGroup_Response;
protobufs['ChatRoom.RenameChatRoomGroup#1_Request'] = Schema.CChatRoom_RenameChatRoomGroup_Request;
protobufs['ChatRoom.RenameChatRoomGroup#1_Response'] = Schema.CChatRoom_RenameChatRoomGroup_Response;
protobufs['ChatRoom.SetChatRoomGroupTagline#1_Request'] = Schema.CChatRoom_SetChatRoomGroupTagline_Request;
protobufs['ChatRoom.SetChatRoomGroupTagline#1_Response'] = Schema.CChatRoom_SetChatRoomGroupTagline_Response;
protobufs['ChatRoom.SetChatRoomGroupAvatar#1_Request'] = Schema.CChatRoom_SetChatRoomGroupAvatar_Request;
protobufs['ChatRoom.SetChatRoomGroupAvatar#1_Response'] = Schema.CChatRoom_SetChatRoomGroupAvatar_Response;
protobufs['ChatRoom.MuteUserInGroup#1_Request'] = Schema.CChatRoom_MuteUser_Request;
protobufs['ChatRoom.MuteUserInGroup#1_Response'] = Schema.CChatRoom_MuteUser_Response;
protobufs['ChatRoom.KickUserFromGroup#1_Request'] = Schema.CChatRoom_KickUser_Request;
protobufs['ChatRoom.KickUserFromGroup#1_Response'] = Schema.CChatRoom_KickUser_Response;
protobufs['ChatRoom.SetUserBanState#1_Request'] = Schema.CChatRoom_SetUserBanState_Request;
protobufs['ChatRoom.SetUserBanState#1_Response'] = Schema.CChatRoom_SetUserBanState_Response;
protobufs['ChatRoom.RevokeInviteToGroup#1_Request'] = Schema.CChatRoom_RevokeInvite_Request;
protobufs['ChatRoom.RevokeInviteToGroup#1_Response'] = Schema.CChatRoom_RevokeInvite_Response;
protobufs['ChatRoom.CreateRole#1_Request'] = Schema.CChatRoom_CreateRole_Request;
protobufs['ChatRoom.CreateRole#1_Response'] = Schema.CChatRoom_CreateRole_Response;
protobufs['ChatRoom.GetRoles#1_Request'] = Schema.NotImplemented;
protobufs['ChatRoom.GetRoles#1_Response'] = Schema.CChatRoom_GetRoles_Response;
protobufs['ChatRoom.RenameRole#1_Request'] = Schema.CChatRoom_RenameRole_Request;
protobufs['ChatRoom.RenameRole#1_Response'] = Schema.CChatRoom_RenameRole_Response;
protobufs['ChatRoom.ReorderRole#1_Request'] = Schema.CChatRoom_ReorderRole_Request;
protobufs['ChatRoom.ReorderRole#1_Response'] = Schema.CChatRoom_ReorderRole_Response;
protobufs['ChatRoom.DeleteRole#1_Request'] = Schema.CChatRoom_DeleteRole_Request;
protobufs['ChatRoom.DeleteRole#1_Response'] = Schema.CChatRoom_DeleteRole_Response;
protobufs['ChatRoom.GetRoleActions#1_Request'] = Schema.NotImplemented;
protobufs['ChatRoom.GetRoleActions#1_Response'] = Schema.CChatRoom_GetRoleActions_Response;
protobufs['ChatRoom.ReplaceRoleActions#1_Request'] = Schema.CChatRoom_ReplaceRoleActions_Request;
protobufs['ChatRoom.ReplaceRoleActions#1_Response'] = Schema.CChatRoom_ReplaceRoleActions_Response;
protobufs['ChatRoom.AddRoleToUser#1_Request'] = Schema.CChatRoom_AddRoleToUser_Request;
protobufs['ChatRoom.AddRoleToUser#1_Response'] = Schema.CChatRoom_AddRoleToUser_Response;
protobufs['ChatRoom.GetRolesForUser#1_Request'] = Schema.NotImplemented;
protobufs['ChatRoom.GetRolesForUser#1_Response'] = Schema.CChatRoom_GetRolesForUser_Response;
protobufs['ChatRoom.DeleteRoleFromUser#1_Request'] = Schema.CChatRoom_DeleteRoleFromUser_Request;
protobufs['ChatRoom.DeleteRoleFromUser#1_Response'] = Schema.CChatRoom_DeleteRoleFromUser_Response;
protobufs['ChatRoom.JoinChatRoomGroup#1_Request'] = Schema.CChatRoom_JoinChatRoomGroup_Request;
protobufs['ChatRoom.JoinChatRoomGroup#1_Response'] = Schema.CChatRoom_JoinChatRoomGroup_Response;
protobufs['ChatRoom.InviteFriendToChatRoomGroup#1_Request'] = Schema.CChatRoom_InviteFriendToChatRoomGroup_Request;
protobufs['ChatRoom.InviteFriendToChatRoomGroup#1_Response'] = Schema.CChatRoom_InviteFriendToChatRoomGroup_Response;
protobufs['ChatRoom.LeaveChatRoomGroup#1_Request'] = Schema.CChatRoom_LeaveChatRoomGroup_Request;
protobufs['ChatRoom.LeaveChatRoomGroup#1_Response'] = Schema.CChatRoom_LeaveChatRoomGroup_Response;
protobufs['ChatRoom.CreateChatRoom#1_Request'] = Schema.CChatRoom_CreateChatRoom_Request;
protobufs['ChatRoom.CreateChatRoom#1_Response'] = Schema.CChatRoom_CreateChatRoom_Response;
protobufs['ChatRoom.DeleteChatRoom#1_Request'] = Schema.CChatRoom_DeleteChatRoom_Request;
protobufs['ChatRoom.DeleteChatRoom#1_Response'] = Schema.CChatRoom_DeleteChatRoom_Response;
protobufs['ChatRoom.RenameChatRoom#1_Request'] = Schema.CChatRoom_RenameChatRoom_Request;
protobufs['ChatRoom.RenameChatRoom#1_Response'] = Schema.CChatRoom_RenameChatRoom_Response;
protobufs['ChatRoom.SendChatMessage#1_Request'] = Schema.CChatRoom_SendChatMessage_Request;
protobufs['ChatRoom.SendChatMessage#1_Response'] = Schema.CChatRoom_SendChatMessage_Response;
protobufs['ChatRoom.JoinVoiceChat#1_Request'] = Schema.CChatRoom_JoinVoiceChat_Request;
protobufs['ChatRoom.JoinVoiceChat#1_Response'] = Schema.CChatRoom_JoinVoiceChat_Response;
protobufs['ChatRoom.LeaveVoiceChat#1_Request'] = Schema.CChatRoom_LeaveVoiceChat_Request;
protobufs['ChatRoom.LeaveVoiceChat#1_Response'] = Schema.CChatRoom_LeaveVoiceChat_Response;
protobufs['ChatRoom.GetMessageHistory#1_Request'] = Schema.CChatRoom_GetMessageHistory_Request;
protobufs['ChatRoom.GetMessageHistory#1_Response'] = Schema.CChatRoom_GetMessageHistory_Response;
protobufs['ChatRoom.GetMyChatRoomGroups#1_Request'] = Schema.CChatRoom_GetMyChatRoomGroups_Request;
protobufs['ChatRoom.GetMyChatRoomGroups#1_Response'] = Schema.CChatRoom_GetMyChatRoomGroups_Response;
protobufs['ChatRoom.GetChatRoomGroupState#1_Request'] = Schema.NotImplemented;
protobufs['ChatRoom.GetChatRoomGroupState#1_Response'] = Schema.CChatRoom_GetChatRoomGroupState_Response;
protobufs['ChatRoom.GetChatRoomGroupSummary#1_Request'] = Schema.NotImplemented;
protobufs['ChatRoom.GetChatRoomGroupSummary#1_Response'] = Schema.CChatRoom_GetChatRoomGroupSummary_Response;
protobufs['ChatRoom.AckChatMessage#1'] = Schema.CChatRoom_AckChatMessage_Notification;
protobufs['ChatRoom.CreateInviteLink#1_Request'] = Schema.CChatRoom_CreateInviteLink_Request;
protobufs['ChatRoom.CreateInviteLink#1_Response'] = Schema.CChatRoom_CreateInviteLink_Response;
protobufs['ChatRoom.GetInviteLinkInfo#1_Request'] = Schema.CChatRoom_GetInviteLinkInfo_Request;
protobufs['ChatRoom.GetInviteLinkInfo#1_Response'] = Schema.CChatRoom_GetInviteLinkInfo_Response;
protobufs['ChatRoom.GetInviteInfo#1_Request'] = Schema.CChatRoom_GetInviteInfo_Request;
protobufs['ChatRoom.GetInviteInfo#1_Response'] = Schema.CChatRoom_GetInviteInfo_Response;
protobufs['ChatRoom.GetInviteLinksForGroup#1_Request'] = Schema.CChatRoom_GetInviteLinksForGroup_Request;
protobufs['ChatRoom.GetInviteLinksForGroup#1_Response'] = Schema.CChatRoom_GetInviteLinksForGroup_Response;
protobufs['ChatRoom.GetBanList#1_Request'] = Schema.CChatRoom_GetBanList_Request;
protobufs['ChatRoom.GetBanList#1_Response'] = Schema.CChatRoom_GetBanList_Response;
protobufs['ChatRoom.GetInviteList#1_Request'] = Schema.CChatRoom_GetInviteList_Request;
protobufs['ChatRoom.GetInviteList#1_Response'] = Schema.CChatRoom_GetInviteList_Response;
protobufs['ChatRoom.DeleteInviteLink#1_Request'] = Schema.CChatRoom_DeleteInviteLink_Request;
protobufs['ChatRoom.DeleteInviteLink#1_Response'] = Schema.CChatRoom_DeleteInviteLink_Response;
protobufs['ChatRoom.SetSessionActiveChatRoomGroups#1_Request'] = Schema.CChatRoom_SetSessionActiveChatRoomGroups_Request;
protobufs['ChatRoom.SetSessionActiveChatRoomGroups#1_Response'] = Schema.CChatRoom_SetSessionActiveChatRoomGroups_Response;
protobufs['ChatRoom.SetUserChatGroupPreferences#1_Request'] = Schema.CChatRoom_SetUserChatGroupPreferences_Request;
protobufs['ChatRoom.SetUserChatGroupPreferences#1_Response'] = Schema.CChatRoom_SetUserChatGroupPreferences_Response;
protobufs['ChatRoom.DeleteChatMessages#1_Request'] = Schema.CChatRoom_DeleteChatMessages_Request;
protobufs['ChatRoom.DeleteChatMessages#1_Response'] = Schema.CChatRoom_DeleteChatMessages_Response;
protobufs['ChatRoomClient.NotifyIncomingChatMessage#1'] = Schema.CChatRoom_IncomingChatMessage_Notification;
protobufs['ChatRoomClient.NotifyChatMessageModified#1'] = Schema.CChatRoom_ChatMessageModified_Notification;
protobufs['ChatRoomClient.NotifyMemberStateChange#1'] = Schema.CChatRoom_MemberStateChange_Notification;
protobufs['ChatRoomClient.NotifyChatRoomHeaderStateChange#1'] = Schema.CChatRoom_ChatRoomHeaderState_Notification;
protobufs['ChatRoomClient.NotifyChatRoomGroupRoomsChange#1'] = Schema.CChatRoom_ChatRoomGroupRoomsChange_Notification;
protobufs['ChatRoomClient.NotifyShouldRejoinChatRoomVoiceChat#1'] = Schema.CChatRoom_NotifyShouldRejoinChatRoomVoiceChat_Notification;
protobufs['ChatRoomClient.NotifyChatGroupUserStateChanged#1'] = Schema.ChatRoomClient_NotifyChatGroupUserStateChanged_Notification;
protobufs['ChatRoomClient.NotifyAckChatMessageEcho#1'] = Schema.CChatRoom_AckChatMessage_Notification;
protobufs['ClanChatRooms.GetClanChatRoomInfo#1_Request'] = Schema.CClanChatRooms_GetClanChatRoomInfo_Request;
protobufs['ClanChatRooms.GetClanChatRoomInfo#1_Response'] = Schema.CClanChatRooms_GetClanChatRoomInfo_Response;
protobufs['FriendMessages.GetRecentMessages#1_Request'] = Schema.CFriendMessages_GetRecentMessages_Request;
protobufs['FriendMessages.GetRecentMessages#1_Response'] = Schema.CFriendMessages_GetRecentMessages_Response;
protobufs['FriendMessages.GetActiveMessageSessions#1_Request'] = Schema.CFriendsMessages_GetActiveMessageSessions_Request;
protobufs['FriendMessages.GetActiveMessageSessions#1_Response'] = Schema.CFriendsMessages_GetActiveMessageSessions_Response;
protobufs['FriendMessages.SendMessage#1_Request'] = Schema.CFriendMessages_SendMessage_Request;
protobufs['FriendMessages.SendMessage#1_Response'] = Schema.CFriendMessages_SendMessage_Response;
protobufs['FriendMessages.AckMessage#1'] = Schema.CFriendMessages_AckMessage_Notification;
protobufs['FriendMessages.IsInFriendsUIBeta#1_Request'] = Schema.CFriendMessages_IsInFriendsUIBeta_Request;
protobufs['FriendMessages.IsInFriendsUIBeta#1_Response'] = Schema.CFriendMessages_IsInFriendsUIBeta_Response;
protobufs['FriendMessagesClient.IncomingMessage#1'] = Schema.CFriendMessages_IncomingMessage_Notification;
protobufs['FriendMessagesClient.NotifyAckMessageEcho#1'] = Schema.CFriendMessages_AckMessage_Notification;
protobufs['Community.GetAppRichPresenceLocalization#1_Request'] = Schema.CCommunity_GetAppRichPresenceLocalization_Request;
protobufs['Community.GetAppRichPresenceLocalization#1_Response'] = Schema.CCommunity_GetAppRichPresenceLocalization_Response;
protobufs['UserAccount.CreateFriendInviteToken#1_Request'] = Schema.CUserAccount_CreateFriendInviteToken_Request;
protobufs['UserAccount.CreateFriendInviteToken#1_Response'] = Schema.CUserAccount_CreateFriendInviteToken_Response;
protobufs['UserAccount.GetFriendInviteTokens#1_Request'] = Schema.CUserAccount_GetFriendInviteTokens_Request;
protobufs['UserAccount.GetFriendInviteTokens#1_Response'] = Schema.CUserAccount_GetFriendInviteTokens_Response;
protobufs['UserAccount.ViewFriendInviteToken#1_Request'] = Schema.CUserAccount_ViewFriendInviteToken_Request;
protobufs['UserAccount.ViewFriendInviteToken#1_Response'] = Schema.CUserAccount_ViewFriendInviteToken_Response;
protobufs['UserAccount.RedeemFriendInviteToken#1_Request'] = Schema.CUserAccount_RedeemFriendInviteToken_Request;
protobufs['UserAccount.RedeemFriendInviteToken#1_Response'] = Schema.CUserAccount_RedeemFriendInviteToken_Response;
protobufs['UserAccount.RevokeFriendInviteToken#1_Request'] = Schema.CUserAccount_RevokeFriendInviteToken_Request;
protobufs['UserAccount.RevokeFriendInviteToken#1_Response'] = Schema.CUserAccount_RevokeFriendInviteToken_Response;
protobufs['DeviceAuth.GetOwnAuthorizedDevices#1_Request'] = Schema.CDeviceAuth_GetOwnAuthorizedDevices_Request;
protobufs['DeviceAuth.GetOwnAuthorizedDevices#1_Response'] = Schema.CDeviceAuth_GetOwnAuthorizedDevices_Response;
protobufs['DeviceAuth.AddAuthorizedBorrowers#1_Request'] = Schema.CDeviceAuth_AddAuthorizedBorrowers_Request;
protobufs['DeviceAuth.AddAuthorizedBorrowers#1_Response'] = Schema.CDeviceAuth_AddAuthorizedBorrowers_Response;
protobufs['DeviceAuth.RemoveAuthorizedBorrowers#1_Request'] = Schema.CDeviceAuth_RemoveAuthorizedBorrowers_Request;
protobufs['DeviceAuth.RemoveAuthorizedBorrowers#1_Response'] = Schema.CDeviceAuth_RemoveAuthorizedBorrowers_Response;
protobufs['DeviceAuth.GetAuthorizedBorrowers#1_Request'] = Schema.CDeviceAuth_GetAuthorizedBorrowers_Request;
protobufs['DeviceAuth.GetAuthorizedBorrowers#1_Response'] = Schema.CDeviceAuth_GetAuthorizedBorrowers_Response;
protobufs['ContentServerDirectory.GetManifestRequestCode#1_Request'] = Schema.CContentServerDirectory_GetManifestRequestCode_Request;
protobufs['ContentServerDirectory.GetManifestRequestCode#1_Response'] = Schema.CContentServerDirectory_GetManifestRequestCode_Response;
// Make sure that every protobuf we used actually exists
let hadMissingProtobuf = false;
for (let i in protobufs) {
if (typeof protobufs[i] != 'undefined') {
continue;
}
// The protobuf doesn't exist
if (i.match(/^\d+$/)) {
i = EMsg[i] || i;
}
console.error(`Protobuf for message ${i} does not exist!`);
hadMissingProtobuf = true;
}
if (hadMissingProtobuf) {
throw new Error('One or more protobuf schemas are missing');
}
class SteamUserMessages extends SteamUserConnection {
/**
* Encode a protobuf.
* @param {object} proto - The protobuf class
* @param {object} data - The data to serialize
* @returns {Buffer}
* @protected
*/
static _encodeProto(proto, data) {
return proto.encode(data).finish();
}
/**
* Decode a protobuf.
* @param {object} proto - The protobuf class
* @param {Buffer|ByteBuffer} encoded - The data to decode
* @returns {object}
* @protected
*/
static _decodeProto(proto, encoded) {
if (ByteBuffer.isByteBuffer(encoded)) {
encoded = encoded.toBuffer();
}
let decoded = proto.decode(encoded);
let objNoDefaults = proto.toObject(decoded, {"longs": String});
let objWithDefaults = proto.toObject(decoded, {"defaults": true, "longs": String});
return replaceDefaults(objNoDefaults, objWithDefaults);
function replaceDefaults(noDefaults, withDefaults) {
if (Array.isArray(withDefaults)) {
return withDefaults.map((val, idx) => replaceDefaults(noDefaults[idx], val));
}
for (let i in withDefaults) {
if (!withDefaults.hasOwnProperty(i)) {
continue;
}
if (withDefaults[i] && typeof withDefaults[i] === 'object' && !Buffer.isBuffer(withDefaults[i])) {
// Covers both object and array cases, both of which will work
// Won't replace empty arrays, but that's desired behavior
withDefaults[i] = replaceDefaults(noDefaults[i], withDefaults[i]);
} else if (typeof noDefaults[i] === 'undefined' && isReplaceableDefaultValue(withDefaults[i])) {
withDefaults[i] = null;
}
}
return withDefaults;
}
function isReplaceableDefaultValue(val) {
if (Buffer.isBuffer(val) && val.length == 0) {
// empty buffer is replaceable
return true;
}
if (Array.isArray(val)) {
// empty array is not replaceable (empty repeated fields)
return false;
}
if (val === '0') {
// Zero as a string is replaceable (64-bit integer)
return true;
}
// Anything falsy is true
return !val;
}
}
/**
* @param {int|object} emsgOrHeader
* @param {object|Buffer|ByteBuffer} body
* @param {function} [callback]
* @protected
*/
_send(emsgOrHeader, body, callback) {
// header fields: msg, proto, sourceJobID, targetJobID
let header = typeof emsgOrHeader === 'object' ? emsgOrHeader : {"msg": emsgOrHeader};
let emsg = header.msg;
let canWeSend = this.steamID || (this._tempSteamID && [EMsg.ChannelEncryptResponse, EMsg.ClientLogon].includes(emsg));
if (!canWeSend) {
// We're disconnected, drop it
this.emit('debug', 'Dropping message ' + emsg + ' because we\'re not logged on.');
return;
}
const Proto = protobufs[emsg];
if (Proto) {
header.proto = header.proto || {};
body = SteamUserMessages._encodeProto(Proto, body);
} else if (ByteBuffer.isByteBuffer(body)) {
body = body.toBuffer();
}
let jobIdSource = null;
if (callback) {
jobIdSource = ++this._currentJobID;
this._jobs[jobIdSource] = callback;
// Clean up old job callbacks after 2 minutes
this._jobCleanupTimers.push(setTimeout(() => delete this._jobs[jobIdSource], 1000 * 60 * 2));
}
let emsgName = EMsg[emsg] || emsg;
if (emsg == EMsg.ServiceMethodCallFromClient && header.proto && header.proto.target_job_name) {
emsgName = header.proto.target_job_name;
}
this.emit(VERBOSE_EMSG_LIST.includes(emsg) ? 'debug-verbose' : 'debug', 'Sending message: ' + emsgName);
// Make the header
let hdrBuf;
if (header.msg == EMsg.ChannelEncryptResponse) {
// since we're setting up the encrypted channel, we use this very minimal header
hdrBuf = ByteBuffer.allocate(4 + 8 + 8, ByteBuffer.LITTLE_ENDIAN);
hdrBuf.writeUint32(header.msg);
hdrBuf.writeUint64(header.targetJobID || JOBID_NONE);
hdrBuf.writeUint64(jobIdSource || header.sourceJobID || JOBID_NONE);
} else if (header.proto) {
// if we have a protobuf header, use that
header.proto.client_sessionid = this._sessionID || 0;
header.proto.steamid = (this.steamID || this._tempSteamID).getSteamID64();
header.proto.jobid_source = jobIdSource || header.proto.jobid_source || header.sourceJobID || JOBID_NONE;
header.proto.jobid_target = header.proto.jobid_target || header.targetJobID || JOBID_NONE;
let hdrProtoBuf = SteamUserMessages._encodeProto(Schema.CMsgProtoBufHeader, header.proto);
hdrBuf = ByteBuffer.allocate(4 + 4 + hdrProtoBuf.length, ByteBuffer.LITTLE_ENDIAN);
hdrBuf.writeUint32(header.msg | PROTO_MASK);
hdrBuf.writeUint32(hdrProtoBuf.length);
hdrBuf.append(hdrProtoBuf);
} else {
// this is the standard non-protobuf extended header
hdrBuf = ByteBuffer.allocate(4 + 1 + 2 + 8 + 8 + 1 + 8 + 4, ByteBuffer.LITTLE_ENDIAN);
hdrBuf.writeUint32(header.msg);
hdrBuf.writeByte(36);
hdrBuf.writeUint16(2);
hdrBuf.writeUint64(header.targetJobID || JOBID_NONE);
hdrBuf.writeUint64(jobIdSource || header.sourceJobID || JOBID_NONE);
hdrBuf.writeByte(239);
hdrBuf.writeUint64((this.steamID || this._tempSteamID).getSteamID64());
hdrBuf.writeUint32(this._sessionID || 0);
}
let outputBuffer = Buffer.concat([hdrBuf.flip().toBuffer(), body]);
this.emit('debug-traffic-outgoing', outputBuffer, header.msg);
this._connection.send(outputBuffer);
}
/**
* Handles a raw binary netmessage by parsing the header and routing it appropriately
* @param {Buffer|string} buffer
* @param {BaseConnection} [conn]
* @param {string} [multiId]
* @protected
*/
_handleNetMessage(buffer, conn, multiId) {
if (conn && conn != this._connection) {
let ghostConnId = conn.connectionType[0] + conn.connectionId;
let expectedConnId = this._connection ? (this._connection.connectionType[0] + this._connection.connectionId) : 'NO CONNECTION';
this.emit('debug', `Received net message from ghost connection ${ghostConnId} (expected ${expectedConnId})`);
return;
}
if (this._useMessageQueue && !multiId) {
// Multi sub-messages skip the queue because we need messages contained in a decoded multi to be processed first
this._incomingMessageQueue.push(arguments);
this.emit('debug', `Enqueued incoming message; queue size is now ${this._incomingMessageQueue.length}`);
return;
}
if (buffer === '__CLOSE__') {
// This is an enqueued connection closure
this._handleConnectionClose(conn);
return;
}
let buf = ByteBuffer.wrap(buffer, ByteBuffer.LITTLE_ENDIAN);
let rawEMsg = buf.readUint32();
let eMsg = rawEMsg & ~PROTO_MASK;
let isProtobuf = !!(rawEMsg & PROTO_MASK);
this.emit('debug-traffic-incoming', buffer, eMsg);
let header = {"msg": eMsg};
if ([EMsg.ChannelEncryptRequest, EMsg.ChannelEncryptResult].includes(eMsg)) {
// for encryption setup, we just have a very small header with two fields
header.targetJobID = buf.readUint64().toString();
header.sourceJobID = buf.readUint64().toString();
} else if (isProtobuf) {
// decode the protobuf header
let headerLength = buf.readUint32();
header.proto = SteamUserMessages._decodeProto(Schema.CMsgProtoBufHeader, buf.slice(buf.offset, buf.offset + headerLength));
buf.skip(headerLength);
header.targetJobID = header.proto.jobid_target && header.proto.jobid_target.toString();
header.sourceJobID = header.proto.jobid_source && header.proto.jobid_source.toString();
header.steamID = header.proto.steamid && header.proto.steamid.toString();
header.sessionID = header.proto.client_sessionid;
} else {
// decode the extended header
buf.skip(3); // 1 byte for header size (fixed at 36), 2 bytes for header version (fixed at 2)
header.targetJobID = buf.readUint64().toString();
header.sourceJobID = buf.readUint64().toString();
buf.skip(1); // 1 byte for header canary (fixed at 239)
header.steamID = buf.readUint64().toString();
header.sessionID = buf.readUint32();
}
let sessionID = (header.proto && header.proto.client_sessionid) || header.sessionID;
let steamID = (header.proto && header.proto.steamid) || header.steamID;
let ourCurrentSteamID = this.steamID ? this.steamID.toString() : null;
if (steamID && sessionID && (sessionID != this._sessionID || steamID.toString() != ourCurrentSteamID)) {
// TODO if we get a new sessionid, should we check if it matches a previously-closed session? probably not necessary...
this._sessionID = sessionID;
this.steamID = new SteamID(steamID.toString());
delete this._tempSteamID;
}
this._handleMessage(header, buf.slice(), conn, multiId);
}
/**
* Handles and routes a parsed message
* @param {object} header
* @param {ByteBuffer} bodyBuf
* @param {BaseConnection} [conn]
* @param {string} [multiId]
* @protected
*/
_handleMessage(header, bodyBuf, conn, multiId) {
// Is this a multi? If yes, short-circuit and just process it now.
if (header.msg == EMsg.Multi) {
this._processMulti(header, SteamUserMessages._decodeProto(protobufs[EMsg.Multi], bodyBuf), conn);
return;
}
let msgName = EMsg[header.msg] || header.msg;
let handlerName = header.msg;
let debugPrefix = multiId ? `[${multiId}] ` : (conn ? `[${conn.connectionType[0]}${conn.connectionId}] ` : '');
let isServiceMethodMsg = [EMsg.ServiceMethod, EMsg.ServiceMethodResponse].includes(header.msg);
if (isServiceMethodMsg) {
if (header.proto && header.proto.target_job_name) {
handlerName = msgName = header.proto.target_job_name;
if (header.msg == EMsg.ServiceMethodResponse) {
handlerName += '_Response';
msgName += '_Response';
}
} else {
this.emit('debug', debugPrefix + 'Got ' + (header.msg == EMsg.ServiceMethod ? 'ServiceMethod' : 'ServiceMethodResponse') + ' without target_job_name');
return;
}
}
if (!isServiceMethodMsg && header.proto && header.proto.target_job_name) {
this.emit('debug', debugPrefix + 'Got unknown target_job_name ' + header.proto.target_job_name + ' for msg ' + msgName);
}
if (!this._handlerManager.hasHandler(handlerName) && !this._jobs[header.targetJobID]) {
this.emit(VERBOSE_EMSG_LIST.includes(header.msg) ? 'debug-verbose' : 'debug', debugPrefix + 'Unhandled message: ' + msgName);
return;
}
let body = bodyBuf;
if (protobufs[handlerName]) {
body = SteamUserMessages._decodeProto(protobufs[handlerName], bodyBuf);
}
let handledMessageDebugMsg = debugPrefix + 'Handled message: ' + msgName;
if (header.msg == EMsg.ClientLogOnResponse) {
handledMessageDebugMsg += ` (${EResult[body.eresult] || body.eresult})`;
}
this.emit(VERBOSE_EMSG_LIST.includes(header.msg) ? 'debug-verbose' : 'debug', handledMessageDebugMsg);
let cb = null;
if (header.sourceJobID != JOBID_NONE) {
// this message expects a response. make a callback we can pass to the end-user.
cb = (emsgOrHeader, body) => {
// once invoked the callback should set the jobid_target
let responseHeader = typeof emsgOrHeader === 'object' ? emsgOrHeader : {"msg": emsgOrHeader};
let emsg = responseHeader.msg;
if (protobufs[emsg]) {
responseHeader.proto = {"jobid_target": header.sourceJobID};
} else {
responseHeader.targetJobID = header.sourceJobID;
}
this._send(responseHeader, body);
}
}
if (this._jobs[header.targetJobID]) {
// this is a response to something, so invoke the appropriate callback
this._jobs[header.targetJobID].call(this, body, header, cb);
} else {
this._handlerManager.emit(this, handlerName, body, header, cb);
}
}
/**
* @param {object} header
* @param {object} body
* @param {object} conn
* @returns {Promise<void>}
* @protected
*/
async _processMulti(header, body, conn) {
let multiId = conn.connectionType[0] + conn.connectionId + '#' + (++this._multiCount);
this.emit('debug-verbose', `=== Processing ${body.size_unzipped ? 'gzipped multi msg' : 'multi msg'} ${multiId} (${body.message_body.length} bytes) ===`);
let payload = body.message_body;
// Enable the message queue while we're unzipping the message (or waiting until the next event loop cycle).
// This prevents any messages from getting processed out of order.
this._useMessageQueue = true;
if (body.size_unzipped) {
try {
payload = await new Promise((resolve, reject) => {
Zlib.gunzip(payload, (err, unzipped) => {
if (err) {
return reject(err);
}
resolve(unzipped);
});
});
} catch (ex) {
this.emit('error', ex);
this._disconnect(true);
return;
}
} else {
// Await a setImmediate promise to guarantee that multi msg processing always takes at least one iteration of the event loop.
// This avoids message queue processing shenanigans. Waiting until the next iteration of the event loop enables
// _handleNetMessage at the end of this method to return immediately, which will thus exit the clear-queue loop
// because the queue got re-enabled. Prevents the queue from being cleared in multiple places at once.
await new Promise(resolve => setImmediate(resolve));
}
if (!this._connection || this._connection != conn) {
this.emit('debug', `=== Bailing out on processing multi msg ${multiId} because our connection is ${!this._connection ? 'lost' : 'different'}! ===`);
return;
}
while (payload.length && (this.steamID || this._tempSteamID)) {
let subSize = payload.readUInt32LE(0);
this._handleNetMessage(payload.slice(4, 4 + subSize), conn, multiId);
payload = payload.slice(4 + subSize);
}
this.emit('debug-verbose', `=== Finished processing multi msg ${multiId}; now clearing queue of size ${this._incomingMessageQueue.length} ===`);
// Go ahead and process anything in the queue now. First disable the message queue. We don't need to worry about
// newly-received messages sneaking in ahead of the queue being cleared, since message processing is synchronous.
// If we encounter another multi msg, the message queue will get re-enabled.
this._useMessageQueue = false;
// Continue to pop items from the message queue until it's empty, or it gets re-enabled. If the message queue gets
// re-enabled, immediately stop popping items from it to avoid stuff getting out of order.
while (this._incomingMessageQueue.length > 0 && !this._useMessageQueue) {
this._handleNetMessage.apply(this, this._incomingMessageQueue.shift());
}
if (this._incomingMessageQueue.length > 0) {
this.emit('debug-verbose', `[${multiId}] Message queue processing ended early with ${this._incomingMessageQueue.length} elements remaining`);
}
}
/**
* Send a unified message.
* @param {string} methodName - In format Interface.Method#Version, e.g. Foo.DoThing#1
* @param {object} methodData
* @param {function} [callback]
* @protected
*/
_sendUnified(methodName, methodData, callback) {
let Proto = protobufs[methodName + (callback ? '_Request' : '')];
let header = {
"msg": EMsg.ServiceMethodCallFromClient,
"proto": {
"target_job_name": methodName
}
};
this._send(header, SteamUserMessages._encodeProto(Proto, methodData), callback);
}
}
module.exports = SteamUserMessages;
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define("require exports ../../core/tsSupport/declareExtendsHelper ../../core/tsSupport/decorateHelper ../../Viewpoint ../../core/Accessor ../../core/Error ../../core/Evented ../../core/promiseUtils ../../core/accessorSupport/decorators ../support/GoTo".split(" "),function(p,q,f,d,g,h,k,l,m,c,n){return function(e){function a(b){b=e.call(this,b)||this;b._initialViewpoint=null;b._goingHome=null;b.go=b.go.bind(b);return b}f(a,e);a.prototype.destroy=function(){this._stopGoingHome();this.view=null};Object.defineProperty(a.prototype,
"state",{get:function(){return this.get("view.ready")?this._goingHome?"going-home":"ready":"disabled"},enumerable:!0,configurable:!0});Object.defineProperty(a.prototype,"view",{set:function(b){var a=this;this._initialViewpoint=null;b&&b.when(function(){a._initialViewpoint=b.viewpoint.clone();a.notifyChange("viewpoint")});this._set("view",b)},enumerable:!0,configurable:!0});Object.defineProperty(a.prototype,"viewpoint",{get:function(){return this._get("viewpoint")||this._initialViewpoint},set:function(b){this._set("viewpoint",
b)},enumerable:!0,configurable:!0});a.prototype.go=function(){var b=this;if(!this.get("view.ready"))return m.reject(new k("home:disabled-state","Cannot go when disabled."));this._stopGoingHome();this.emit("go");var a=!1,c=this.callGoTo({target:this.viewpoint}).always(function(){b.notifyChange("state");b._goingHome=null;a=!0});a||(this._goingHome=c,this.notifyChange("state"));return c};a.prototype._stopGoingHome=function(){this._goingHome&&(this._goingHome.cancel(),this._goingHome=null)};d([c.property({dependsOn:["view.ready"],
readOnly:!0})],a.prototype,"state",null);d([c.property()],a.prototype,"view",null);d([c.property({type:g})],a.prototype,"viewpoint",null);d([c.property()],a.prototype,"go",null);return a=d([c.subclass("esri.widgets.Home.HomeViewModel")],a)}(c.declared(h,l,n))});
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-disable global-require */
// The top-level (parent) route
export default {
path: '/',
// Keep in mind, routes are evaluated in order
children: [
require('./home').default,
require('./contact').default,
require('./login').default,
require('./register').default,
require('./about').default,
require('./privacy').default,
require('./admin').default,
require('./payroll').default,
// Wildcard routes, e.g. { path: '*', ... } (must go last)
require('./notFound').default,
],
async action({ next }) {
// Execute each child route until one of them return the result
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`;
route.description = route.description || '';
return route;
},
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:eb647ff6ada9273546ebda37b996d223b12a7bec5b6696a50e2bba5921b4f823
size 1544
|
/*
This Chess AI comes from here
https://github.com/glinscott/Garbochess-JS
Copyright (c) 2011 Gary Linscott
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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.
*/
// Perf TODO:
// Merge material updating with psq values
// Put move scoring inline in generator
// Remove need for fliptable in psq tables. Access them by color
// Optimize pawn move generation
// Non-perf todo:
// Checks in first q?
// Pawn eval.
// Better king evaluation
// Better move sorting in PV nodes (especially root)
// ECMAScript 5 strict mode
/* jshint globalstrict: true*/
/* jslint newcap: true */
/* global postMessage, self */
//"use strict";
var g_debug = false;
var g_timeout = 40;
var g_maxply = 99;
var worker = false;
try {
// not sure this will work on any browser
// and since it's just for debug,
// a try catch should be good enough
if ( self.constructor.name === "DedicatedWorkerContext") {
worker = true;
}
} catch(e) {}
debug ("worker = "+worker);
function GetFen() {
var result = "";
for (var row = 0; row < 8; row++) {
if (row !== 0) {
result += '/';
}
var empty = 0;
for (var col = 0; col < 8; col++) {
var piece = g_board[((row + 2) << 4) + col + 4];
if (piece === 0) {
empty++;
} else {
if (empty !== 0) {
result += empty;
}
empty = 0;
var pieceChar = [" ", "p", "n", "b", "r", "q", "k", " "][(piece & 0x7)];
result += ((piece & colorWhite) !== 0) ? pieceChar.toUpperCase() : pieceChar;
}
}
if (empty !== 0) {
result += empty;
}
}
result += g_toMove == colorWhite ? " w" : " b";
result += " ";
if (g_castleRights === 0) {
result += "-";
}
else {
if ((g_castleRights & 1) !== 0)
result += "K";
if ((g_castleRights & 2) !== 0)
result += "Q";
if ((g_castleRights & 4) !== 0)
result += "k";
if ((g_castleRights & 8) !== 0)
result += "q";
}
result += " ";
if (g_enPassentSquare == -1) {
result += '-';
}
else {
result += FormatSquare(g_enPassentSquare);
}
return result;
}
function GetMoveSAN(move, validMoves) {
var from = move & 0xFF;
var to = (move >> 8) & 0xFF;
if (move & moveflagCastleKing) return "O-O";
if (move & moveflagCastleQueen) return "O-O-O";
var pieceType = g_board[from] & 0x7;
var result = ["", "", "N", "B", "R", "Q", "K", ""][pieceType];
var dupe = false, rowDiff = true, colDiff = true;
if (validMoves === undefined) {
validMoves = GenerateValidMoves();
}
for (var i = 0; i < validMoves.length; i++) {
var moveFrom = validMoves[i] & 0xFF;
var moveTo = (validMoves[i] >> 8) & 0xFF;
if (moveFrom != from &&
moveTo == to &&
(g_board[moveFrom] & 0x7) == pieceType) {
dupe = true;
if ((moveFrom & 0xF0) == (from & 0xF0)) {
rowDiff = false;
}
if ((moveFrom & 0x0F) == (from & 0x0F)) {
colDiff = false;
}
}
}
if (dupe) {
if (colDiff) {
result += FormatSquare(from).charAt(0);
} else if (rowDiff) {
result += FormatSquare(from).charAt(1);
} else {
result += FormatSquare(from);
}
} else if (pieceType === piecePawn && (g_board[to] !== 0 || (move & moveflagEPC))) {
result += FormatSquare(from).charAt(0);
}
if (g_board[to] !== 0 || (move & moveflagEPC)) {
result += "x";
}
result += FormatSquare(to);
if (move & moveflagPromotion) {
if (move & moveflagPromoteBishop) result += "=B";
else if (move & moveflagPromoteKnight) result += "=N";
else if (move & moveflagPromoteQueen) result += "=Q";
else result += "=R";
}
MakeMove(move);
if (g_inCheck) {
result += GenerateValidMoves().length === 0 ? "#" : "+";
}
UnmakeMove(move);
return result;
}
function FormatSquare(square) {
var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
return letters[(square & 0xF) - 4] + ((9 - (square >> 4)) + 1);
}
function FormatMove(move) {
var result = FormatSquare(move & 0xFF) + FormatSquare((move >> 8) & 0xFF);
if (move & moveflagPromotion) {
if (move & moveflagPromoteBishop) result += "b";
else if (move & moveflagPromoteKnight) result += "n";
else if (move & moveflagPromoteQueen) result += "q";
else result += "r";
}
return result;
}
function GetMoveFromString(moveString) {
var moves = GenerateValidMoves();
for (var i = 0; i < moves.length; i++) {
if (FormatMove(moves[i]) == moveString) {
return moves[i];
}
}
alert("busted! ->" + moveString + " fen:" + GetFen());
}
function PVFromHash(move, ply) {
if (ply === 0)
return "";
if (move === 0) {
if (g_inCheck) return "checkmate";
return "stalemate";
}
var pvString = " " + GetMoveSAN(move);
MakeMove(move);
var hashNode = g_hashTable[g_hashKeyLow & g_hashMask];
if (hashNode !== undefined && hashNode.lock === g_hashKeyHigh && hashNode.bestMove !== undefined) {
pvString += PVFromHash(hashNode.bestMove, ply - 1);
}
UnmakeMove(move);
return pvString;
}
//
// Searching code
//
var g_startTime;
var g_nodeCount;
var g_qNodeCount;
var g_searchValid;
var g_globalPly = 0;
function Search(finishMoveCallback, maxPly, finishPlyCallback) {
debug("start search with maxPly:"+maxPly+" and timeout "+g_timeout);
if (GenerateValidMoves().length === 0) {
debug( g_inCheck ? 'Checkmate' : 'Stalemate' );
return false;
}
var lastEval;
var alpha = minEval;
var beta = maxEval;
g_globalPly++;
g_nodeCount = 0;
g_qNodeCount = 0;
g_searchValid = true;
var bestMove = 0;
var value;
g_startTime = (new Date()).getTime();
var i;
for (i = 1; i <= maxPly && g_searchValid; i++) {
var tmp = AlphaBeta(i, 0, alpha, beta);
if (!g_searchValid) break;
value = tmp;
if (value > alpha && value < beta) {
alpha = value - 500;
beta = value + 500;
if (alpha < minEval) alpha = minEval;
if (beta > maxEval) beta = maxEval;
} else if (alpha != minEval) {
alpha = minEval;
beta = maxEval;
i--;
}
if (g_hashTable[g_hashKeyLow & g_hashMask] !== undefined) {
bestMove = g_hashTable[g_hashKeyLow & g_hashMask].bestMove;
}
if (finishPlyCallback !== undefined) {
finishPlyCallback(bestMove, value, (new Date()).getTime() - g_startTime, i);
}
}
if (finishMoveCallback !== undefined) {
finishMoveCallback(bestMove, value, (new Date()).getTime() - g_startTime, i - 1);
}
}
var minEval = -2000000;
var maxEval = +2000000;
var minMateBuffer = minEval + 2000;
var maxMateBuffer = maxEval - 2000;
var materialTable = [0, 800, 3350, 3450, 5000, 9750, 600000];
var pawnAdj =
[
0, 0, 0, 0, 0, 0, 0, 0,
-25, 105, 135, 270, 270, 135, 105, -25,
-80, 0, 30, 176, 176, 30, 0, -80,
-85, -5, 25, 175, 175, 25, -5, -85,
-90, -10, 20, 125, 125, 20, -10, -90,
-95, -15, 15, 75, 75, 15, -15, -95,
-100, -20, 10, 70, 70, 10, -20, -100,
0, 0, 0, 0, 0, 0, 0, 0
];
var knightAdj =
[
-200, -100, -50, -50, -50, -50, -100, -200,
-100, 0, 0, 0, 0, 0, 0, -100,
-50, 0, 60, 60, 60, 60, 0, -50,
-50, 0, 30, 60, 60, 30, 0, -50,
-50, 0, 30, 60, 60, 30, 0, -50,
-50, 0, 30, 30, 30, 30, 0, -50,
-100, 0, 0, 0, 0, 0, 0, -100,
-200, -50, -25, -25, -25, -25, -50, -200
];
var bishopAdj =
[
-50,-50,-25,-10,-10,-25,-50,-50,
-50,-25,-10, 0, 0,-10,-25,-50,
-25,-10, 0, 25, 25, 0,-10,-25,
-10, 0, 25, 40, 40, 25, 0,-10,
-10, 0, 25, 40, 40, 25, 0,-10,
-25,-10, 0, 25, 25, 0,-10,-25,
-50,-25,-10, 0, 0,-10,-25,-50,
-50,-50,-25,-10,-10,-25,-50,-50
];
var rookAdj =
[
-60, -30, -10, 20, 20, -10, -30, -60,
40, 70, 90,120,120, 90, 70, 40,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60
];
var kingAdj =
[
50, 150, -25, -125, -125, -25, 150, 50,
50, 150, -25, -125, -125, -25, 150, 50,
50, 150, -25, -125, -125, -25, 150, 50,
50, 150, -25, -125, -125, -25, 150, 50,
50, 150, -25, -125, -125, -25, 150, 50,
50, 150, -25, -125, -125, -25, 150, 50,
50, 150, -25, -125, -125, -25, 150, 50,
150, 250, 75, -25, -25, 75, 250, 150
];
var emptyAdj =
[
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
];
var pieceSquareAdj = new Array(8);
// Returns the square flipped
var flipTable = new Array(256);
function PawnEval(color) {
var pieceIdx = (color | 1) << 4;
var from = g_pieceList[pieceIdx++];
while (from !== 0) {
from = g_pieceList[pieceIdx++];
}
}
//***********raksa mobility
function Mobility(color) {
var result = 0;
var from, to, mob, pieceIdx;
var enemy = color == 8 ? 0x10 : 0x8;
var mobUnit = color == 8 ? g_mobUnit[0] : g_mobUnit[1];
// Knight mobility
mob = -3;
pieceIdx = (color | 2) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
mob += mobUnit[g_board[from + 31]];
mob += mobUnit[g_board[from + 33]];
mob += mobUnit[g_board[from + 14]];
mob += mobUnit[g_board[from - 14]];
mob += mobUnit[g_board[from - 31]];
mob += mobUnit[g_board[from - 33]];
mob += mobUnit[g_board[from + 18]];
mob += mobUnit[g_board[from - 18]];
from = g_pieceList[pieceIdx++];
}
result += 65 * mob;
// Bishop mobility
mob = -4;
pieceIdx = (color | 3) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from - 15;
while (g_board[to] === 0) { to -= 15; mob++; }
if (g_board[to] & enemy) {
mob++;
if (!(g_board[to] & piecePawn)) {
to -= 15;
while (g_board[to] === 0) to -= 15;
mob += mobUnit[g_board[to]] << 2;
}
}
to = from - 17;
while (g_board[to] === 0) { to -= 17; mob++; }
if (g_board[to] & enemy) {
mob++;
if (!(g_board[to] & piecePawn)) {
to -= 17;
while (g_board[to] === 0) to -= 17;
mob += mobUnit[g_board[to]] << 2;
}
}
to = from + 15;
while (g_board[to] === 0) { to += 15; mob++; }
if (g_board[to] & enemy) {
mob++;
if (!(g_board[to] & piecePawn)) {
to += 15;
while (g_board[to] === 0) to += 15;
mob += mobUnit[g_board[to]] << 2;
}
}
to = from + 17;
while (g_board[to] === 0) { to += 17; mob++; }
if (g_board[to] & enemy) {
mob++;
if (!(g_board[to] & piecePawn)) {
to += 17;
while (g_board[to] === 0) to += 17;
mob += mobUnit[g_board[to]] << 2;
}
}
from = g_pieceList[pieceIdx++];
}
result += 44 * mob;
// Rook mobility
mob = -4;
pieceIdx = (color | 4) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from - 1;
while (g_board[to] === 0) { to--; mob++;}
if (g_board[to] & enemy) mob++;
to = from + 1;
while (g_board[to] === 0) { to++; mob++; }
if (g_board[to] & enemy) mob++;
to = from + 16;
while (g_board[to] === 0) { to += 16; mob++; }
if (g_board[to] & enemy) mob++;
to = from - 16;
while (g_board[to] === 0) { to -= 16; mob++; }
if (g_board[to] & enemy) mob++;
from = g_pieceList[pieceIdx++];
}
result += 25 * mob;
// Queen mobility
mob = -2;
pieceIdx = (color | 5) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from - 15;
while (g_board[to] === 0) { to -= 15; mob++; }
if (g_board[to] & enemy) mob++;
to = from - 17;
while (g_board[to] === 0) { to -= 17; mob++; }
if (g_board[to] & enemy) mob++;
to = from + 15;
while (g_board[to] === 0) { to += 15; mob++; }
if (g_board[to] & enemy) mob++;
to = from + 17;
while (g_board[to] === 0) { to += 17; mob++; }
if (g_board[to] & enemy) mob++;
to = from - 1;
while (g_board[to] === 0) { to--; mob++; }
if (g_board[to] & enemy) mob++;
to = from + 1;
while (g_board[to] === 0) { to++; mob++; }
if (g_board[to] & enemy) mob++;
to = from + 16;
while (g_board[to] === 0) { to += 16; mob++; }
if (g_board[to] & enemy) mob++;
to = from - 16;
while (g_board[to] === 0) { to -= 16; mob++; }
if (g_board[to] & enemy) mob++;
from = g_pieceList[pieceIdx++];
}
result += 22 * mob;
return result;
}
function Evaluate() {
var curEval = g_baseEval;
var evalAdjust = 0;
// Black queen gone, then cancel white's penalty for king movement
if (g_pieceList[pieceQueen << 4] === 0)
evalAdjust -= pieceSquareAdj[pieceKing][g_pieceList[(colorWhite | pieceKing) << 4]];
// White queen gone, then cancel black's penalty for king movement
if (g_pieceList[(colorWhite | pieceQueen) << 4] === 0)
evalAdjust += pieceSquareAdj[pieceKing][flipTable[g_pieceList[pieceKing << 4]]];
// Black bishop pair
if (g_pieceCount[pieceBishop] >= 2)
evalAdjust -= 500;
// White bishop pair
if (g_pieceCount[pieceBishop | colorWhite] >= 2)
evalAdjust += 500;
var mobility = Mobility(8) - Mobility(0);
if (g_toMove === 0) {
// Black
curEval -= mobility;
curEval -= evalAdjust;
}
else {
curEval += mobility;
curEval += evalAdjust;
}
return curEval;
}
function ScoreMove(move){
var moveTo = (move >> 8) & 0xFF;
var captured = g_board[moveTo] & 0x7;
var piece = g_board[move & 0xFF];
var score;
if (captured !== 0) {
var pieceType = piece & 0x7;
score = (captured << 5) - pieceType;
} else {
score = historyTable[piece & 0xF][moveTo];
}
return score;
}
function QSearch(alpha, beta, ply) {
g_qNodeCount++;
var realEval = g_inCheck ? (minEval + 1) : Evaluate();
if (realEval >= beta)
return realEval;
if (realEval > alpha)
alpha = realEval;
var moves = [];
var moveScores = [];
var wasInCheck = g_inCheck;
var i;
if (wasInCheck) {
// TODO: Fast check escape generator and fast checking moves generator
GenerateCaptureMoves(moves, null);
GenerateAllMoves(moves);
for (i = 0; i < moves.length; i++) {
moveScores[i] = ScoreMove(moves[i]);
}
} else {
GenerateCaptureMoves(moves, null);
for (i = 0; i < moves.length; i++) {
var captured = g_board[(moves[i] >> 8) & 0xFF] & 0x7;
var pieceType = g_board[moves[i] & 0xFF] & 0x7;
moveScores[i] = (captured << 5) - pieceType;
}
}
for (i = 0; i < moves.length; i++) {
var bestMove = i;
for (var j = moves.length - 1; j > i; j--) {
if (moveScores[j] > moveScores[bestMove]) {
bestMove = j;
}
}
var tmpMove = moves[i];
moves[i] = moves[bestMove];
moves[bestMove] = tmpMove;
var tmpScore = moveScores[i];
moveScores[i] = moveScores[bestMove];
moveScores[bestMove] = tmpScore;
if (!wasInCheck && !See(moves[i])) {
continue;
}
if (!MakeMove(moves[i])) {
continue;
}
var value = -QSearch(-beta, -alpha, ply - 1);
UnmakeMove(moves[i]);
if (value > realEval) {
if (value >= beta)
return value;
if (value > alpha)
alpha = value;
realEval = value;
}
}
/* Disable checks... Too slow currently
if (ply == 0 && !wasInCheck) {
moves = [];
GenerateAllMoves(moves);
for (var i = 0; i < moves.length; i++) {
moveScores[i] = ScoreMove(moves[i]);
}
for (var i = 0; i < moves.length; i++) {
var bestMove = i;
for (var j = moves.length - 1; j > i; j--) {
if (moveScores[j] > moveScores[bestMove]) {
bestMove = j;
}
}
{
var tmpMove = moves[i];
moves[i] = moves[bestMove];
moves[bestMove] = tmpMove;
var tmpScore = moveScores[i];
moveScores[i] = moveScores[bestMove];
moveScores[bestMove] = tmpScore;
}
if (!MakeMove(moves[i])) {
continue;
}
var checking = g_inCheck;
UnmakeMove(moves[i]);
if (!checking) {
continue;
}
if (!See(moves[i])) {
continue;
}
MakeMove(moves[i]);
var value = -QSearch(-beta, -alpha, ply - 1);
UnmakeMove(moves[i]);
if (value > realEval) {
if (value >= beta)
return value;
if (value > alpha)
alpha = value;
realEval = value;
}
}
}
*/
return realEval;
}
function StoreHash(value, flags, ply, move, depth) {
if (value >= maxMateBuffer)
value += depth;
else if (value <= minMateBuffer)
value -= depth;
g_hashTable[g_hashKeyLow & g_hashMask] = new HashEntry(g_hashKeyHigh, value, flags, ply, move);
}
function IsHashMoveValid(hashMove) {
var from = hashMove & 0xFF;
var to = (hashMove >> 8) & 0xFF;
var ourPiece = g_board[from];
var pieceType = ourPiece & 0x7;
if (pieceType < piecePawn || pieceType > pieceKing) return false;
// Can't move a piece we don't control
if (g_toMove != (ourPiece & 0x8))
return false;
// Can't move to a square that has something of the same color
if (g_board[to] !== 0 && (g_toMove == (g_board[to] & 0x8)))
return false;
if (pieceType == piecePawn) {
if (hashMove & moveflagEPC) {
return false;
}
// Valid moves are push, capture, double push, promotions
var dir = to - from;
if ((g_toMove == colorWhite) != (dir < 0)) {
// Pawns have to move in the right direction
return false;
}
var row = to & 0xF0;
if (((row == 0x90 && !g_toMove) ||
(row == 0x20 && g_toMove)) !== (hashMove & moveflagPromotion)) {
// Handle promotions
return false;
}
if (dir === -16 || dir === 16) {
// White/Black push
return g_board[to] === 0;
} else if (dir === -15 || dir === -17 || dir === 15 || dir === 17) {
// White/Black capture
return g_board[to] !== 0;
} else if (dir === -32) {
// Double white push
if (row !== 0x60) return false;
if (g_board[to] !== 0) return false;
if (g_board[from - 16] !== 0) return false;
} else if (dir == 32) {
// Double black push
if (row !== 0x50) return false;
if (g_board[to] !== 0) return false;
if (g_board[from + 16] !== 0) return false;
} else {
return false;
}
return true;
} else {
// This validates that this piece type can actually make the attack
if (hashMove >> 16) return false;
return IsSquareAttackableFrom(to, from);
}
}
function IsRepDraw() {
var stop = g_moveCount - 1 - g_move50;
stop = stop < 0 ? 0 : stop;
for (var i = g_moveCount - 5; i >= stop; i -= 2) {
if (g_repMoveStack[i] == g_hashKeyLow)
return true;
}
return false;
}
function MovePicker(hashMove, depth, killer1, killer2) {
this.hashMove = hashMove;
this.depth = depth;
this.killer1 = killer1;
this.killer2 = killer2;
this.moves = [];
this.losingCaptures = null;
this.moveCount = 0;
this.atMove = -1;
this.moveScores = null;
this.stage = 0;
this.nextMove = function () {
var i;
if (++this.atMove == this.moveCount) {
this.stage++;
if (this.stage == 1) {
if (this.hashMove !== undefined && IsHashMoveValid(hashMove)) {
this.moves[0] = hashMove;
this.moveCount = 1;
}
if (this.moveCount != 1) {
this.hashMove = undefined;
this.stage++;
}
}
if (this.stage == 2) {
GenerateCaptureMoves(this.moves, null);
this.moveCount = this.moves.length;
this.moveScores = new Array(this.moveCount);
// Move ordering
for (i = this.atMove; i < this.moveCount; i++) {
var captured = g_board[(this.moves[i] >> 8) & 0xFF] & 0x7;
var pieceType = g_board[this.moves[i] & 0xFF] & 0x7;
this.moveScores[i] = (captured << 5) - pieceType;
}
// No moves, onto next stage
if (this.atMove == this.moveCount) this.stage++;
}
if (this.stage == 3) {
if (IsHashMoveValid(this.killer1) &&
this.killer1 != this.hashMove) {
this.moves[this.moves.length] = this.killer1;
this.moveCount = this.moves.length;
} else {
this.killer1 = 0;
this.stage++;
}
}
if (this.stage == 4) {
if (IsHashMoveValid(this.killer2) &&
this.killer2 != this.hashMove) {
this.moves[this.moves.length] = this.killer2;
this.moveCount = this.moves.length;
} else {
this.killer2 = 0;
this.stage++;
}
}
if (this.stage == 5) {
GenerateAllMoves(this.moves);
this.moveCount = this.moves.length;
// Move ordering
for (i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]);
// No moves, onto next stage
if (this.atMove === this.moveCount) this.stage++;
}
if (this.stage === 6) {
// Losing captures
if (this.losingCaptures !== null) {
for (i = 0; i < this.losingCaptures.length; i++) {
this.moves[this.moves.length] = this.losingCaptures[i];
}
for (i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]);
this.moveCount = this.moves.length;
}
// No moves, onto next stage
if (this.atMove === this.moveCount) this.stage++;
}
if (this.stage === 7)
return 0;
}
var bestMove = this.atMove;
for (var j = this.atMove + 1; j < this.moveCount; j++) {
if (this.moveScores[j] > this.moveScores[bestMove]) {
bestMove = j;
}
}
if (bestMove != this.atMove) {
var tmpMove = this.moves[this.atMove];
this.moves[this.atMove] = this.moves[bestMove];
this.moves[bestMove] = tmpMove;
var tmpScore = this.moveScores[this.atMove];
this.moveScores[this.atMove] = this.moveScores[bestMove];
this.moveScores[bestMove] = tmpScore;
}
var candidateMove = this.moves[this.atMove];
if ((this.stage > 1 && candidateMove == this.hashMove) ||
(this.stage > 3 && candidateMove == this.killer1) ||
(this.stage > 4 && candidateMove == this.killer2)) {
return this.nextMove();
}
if (this.stage === 2 && !See(candidateMove)) {
if (this.losingCaptures === null) {
this.losingCaptures = [];
}
this.losingCaptures[this.losingCaptures.length] = candidateMove;
return this.nextMove();
}
return this.moves[this.atMove];
};
}
function AllCutNode(ply, depth, beta, allowNull) {
if (ply <= 0) {
return QSearch(beta - 1, beta, 0);
}
if ((g_nodeCount & 127) == 127) {
if ((new Date()).getTime() - g_startTime > g_timeout) {
// Time cutoff
g_searchValid = false;
return beta - 1;
}
}
g_nodeCount++;
if (IsRepDraw())
return 0;
// Mate distance pruning
if (minEval + depth >= beta)
return beta;
if (maxEval - (depth + 1) < beta)
return beta - 1;
var hashMove = null;
var hashNode = g_hashTable[g_hashKeyLow & g_hashMask];
if (hashNode !== undefined && hashNode.lock === g_hashKeyHigh) {
hashMove = hashNode.bestMove;
if (hashNode.hashDepth >= ply) {
var hashValue = hashNode.value;
// Fixup mate scores
if (hashValue >= maxMateBuffer)
hashValue -= depth;
else if (hashValue <= minMateBuffer)
hashValue += depth;
if (hashNode.flags === hashflagExact)
return hashValue;
if (hashNode.flags === hashflagAlpha && hashValue < beta)
return hashValue;
if (hashNode.flags === hashflagBeta && hashValue >= beta)
return hashValue;
}
}
// TODO - positional gain?
var value;
if (!g_inCheck &&
allowNull &&
beta > minMateBuffer &&
beta < maxMateBuffer) {
// Try some razoring
if (hashMove === undefined &&
ply < 4) {
var razorMargin = 2500 + 200 * ply;
if (g_baseEval < beta - razorMargin) {
var razorBeta = beta - razorMargin;
var v = QSearch(razorBeta - 1, razorBeta, 0);
if (v < razorBeta)
return v;
}
}
// TODO - static null move
// Null move
if (ply > 1 &&
g_baseEval >= beta - (ply >= 4 ? 2500 : 0) &&
// Disable null move if potential zugzwang (no big pieces)
(g_pieceCount[pieceBishop | g_toMove] !== 0 ||
g_pieceCount[pieceKnight | g_toMove] !== 0 ||
g_pieceCount[pieceRook | g_toMove] !== 0 ||
g_pieceCount[pieceQueen | g_toMove] !== 0)) {
var r = 3 + (ply >= 5 ? 1 : ply / 4);
if (g_baseEval - beta > 1500) r++;
g_toMove = 8 - g_toMove;
g_baseEval = -g_baseEval;
g_hashKeyLow ^= g_zobristBlackLow;
g_hashKeyHigh ^= g_zobristBlackHigh;
value = -AllCutNode(ply - r, depth + 1, -(beta - 1), false);
g_hashKeyLow ^= g_zobristBlackLow;
g_hashKeyHigh ^= g_zobristBlackHigh;
g_toMove = 8 - g_toMove;
g_baseEval = -g_baseEval;
if (value >= beta)
return beta;
}
}
var moveMade = false;
var realEval = minEval - 1;
var inCheck = g_inCheck;
var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]);
for (;;) {
var currentMove = movePicker.nextMove();
if (currentMove === 0) {
break;
}
var plyToSearch = ply - 1;
if (!MakeMove(currentMove)) {
continue;
}
value = null;
var doFullSearch = true;
if (g_inCheck) {
// Check extensions
plyToSearch++;
} else {
var reduced = plyToSearch - (movePicker.atMove > 14 ? 2 : 1);
// Futility pruning
/* if (movePicker.stage == 5 && !inCheck) {
if (movePicker.atMove >= (15 + (1 << (5 * ply) >> 2)) &&
realEval > minMateBuffer) {
UnmakeMove(currentMove);
continue;
}
if (ply < 7) {
var reducedPly = reduced <= 0 ? 0 : reduced;
var futilityValue = -g_baseEval + (900 * (reducedPly + 2)) - (movePicker.atMove * 10);
if (futilityValue < beta) {
if (futilityValue > realEval) {
realEval = futilityValue;
}
UnmakeMove(currentMove);
continue;
}
}
}*/
// Late move reductions
if (movePicker.stage == 5 && movePicker.atMove > 5 && ply >= 3) {
value = -AllCutNode(reduced, depth + 1, -(beta - 1), true);
doFullSearch = (value >= beta);
}
}
if (doFullSearch) {
value = -AllCutNode(plyToSearch, depth + 1, -(beta - 1), true);
}
moveMade = true;
UnmakeMove(currentMove);
if (!g_searchValid) {
return beta - 1;
}
if (value > realEval) {
if (value >= beta) {
var histTo = (currentMove >> 8) & 0xFF;
if (g_board[histTo] === 0) {
var histPiece = g_board[currentMove & 0xFF] & 0xF;
historyTable[histPiece][histTo] += ply * ply;
if (historyTable[histPiece][histTo] > 32767) {
historyTable[histPiece][histTo] >>= 1;
}
if (g_killers[depth][0] != currentMove) {
g_killers[depth][1] = g_killers[depth][0];
g_killers[depth][0] = currentMove;
}
}
StoreHash(value, hashflagBeta, ply, currentMove, depth);
return value;
}
realEval = value;
hashMove = currentMove;
}
}
if (!moveMade) {
// If we have no valid moves it's either stalemate or checkmate
if (g_inCheck)
// Checkmate.
return minEval + depth;
else
// Stalemate
return 0;
}
StoreHash(realEval, hashflagAlpha, ply, hashMove, depth);
return realEval;
}
function AlphaBeta(ply, depth, alpha, beta) {
if (ply <= 0) {
return QSearch(alpha, beta, 0);
}
g_nodeCount++;
if (depth > 0 && IsRepDraw())
return 0;
// Mate distance pruning
var oldAlpha = alpha;
alpha = alpha < minEval + depth ? alpha : minEval + depth;
beta = beta > maxEval - (depth + 1) ? beta : maxEval - (depth + 1);
if (alpha >= beta)
return alpha;
var hashMove = null;
var hashFlag = hashflagAlpha;
var hashNode = g_hashTable[g_hashKeyLow & g_hashMask];
if (hashNode !== undefined && hashNode.lock === g_hashKeyHigh) {
hashMove = hashNode.bestMove;
}
var inCheck = g_inCheck;
var moveMade = false;
var realEval = minEval;
var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]);
for (;;) {
var currentMove = movePicker.nextMove();
if (currentMove === 0) {
break;
}
var plyToSearch = ply - 1;
if (!MakeMove(currentMove)) {
continue;
}
if (g_inCheck) {
// Check extensions
plyToSearch++;
}
var value;
if (moveMade) {
value = -AllCutNode(plyToSearch, depth + 1, -alpha, true);
if (value > alpha) {
value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha);
}
} else {
value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha);
}
moveMade = true;
UnmakeMove(currentMove);
if (!g_searchValid) {
return alpha;
}
if (value > realEval) {
if (value >= beta) {
var histTo = (currentMove >> 8) & 0xFF;
if (g_board[histTo] === 0) {
var histPiece = g_board[currentMove & 0xFF] & 0xF;
historyTable[histPiece][histTo] += ply * ply;
if (historyTable[histPiece][histTo] > 32767) {
historyTable[histPiece][histTo] >>= 1;
}
if (g_killers[depth][0] !== currentMove) {
g_killers[depth][1] = g_killers[depth][0];
g_killers[depth][0] = currentMove;
}
}
StoreHash(value, hashflagBeta, ply, currentMove, depth);
return value;
}
if (value > oldAlpha) {
hashFlag = hashflagExact;
alpha = value;
}
realEval = value;
hashMove = currentMove;
}
}
if (!moveMade) {
// If we have no valid moves it's either stalemate or checkmate
if (inCheck)
// Checkmate.
return minEval + depth;
else
// Stalemate
return 0;
}
StoreHash(realEval, hashFlag, ply, hashMove, depth);
return realEval;
}
//
// Board code
//
// This somewhat funky scheme means that a piece is indexed by it's lower 4 bits when accessing in arrays. The fifth bit (black bit)
// is used to allow quick edge testing on the board.
var colorBlack = 0x10;
var colorWhite = 0x08;
var pieceEmpty = 0x00;
var piecePawn = 0x01;
var pieceKnight = 0x02;
var pieceBishop = 0x03;
var pieceRook = 0x04;
var pieceQueen = 0x05;
var pieceKing = 0x06;
var g_vectorDelta = new Array(256);
var g_bishopDeltas = [-15, -17, 15, 17];
var g_knightDeltas = [31, 33, 14, -14, -31, -33, 18, -18];
var g_rookDeltas = [-1, +1, -16, +16];
var g_queenDeltas = [-1, +1, -15, +15, -17, +17, -16, +16];
//var g_queenDeltas = [-15, -17, 15, 17];
var g_castleRightsMask = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 7,15,15,15, 3,15,15,11, 0, 0, 0, 0,
0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
0, 0, 0, 0,13,15,15,15,12,15,15,14, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];
var moveflagEPC = 0x2 << 16;
var moveflagCastleKing = 0x4 << 16;
var moveflagCastleQueen = 0x8 << 16;
var moveflagPromotion = 0x10 << 16;
var moveflagPromoteRook = 0x00 << 16;
var moveflagPromoteKnight = 0x20 << 16;
var moveflagPromoteQueen = 0x40 << 16;
var moveflagPromoteBishop = 0x80 << 16;
function MT() {
var N = 624;
var M = 397;
var MAG01 = [0x0, 0x9908b0df];
this.mt = new Array(N);
this.mti = N + 1;
this.setSeed = function()
{
var a = arguments;
var i,s,k;
switch (a.length) {
case 1:
if (a[0].constructor === Number) {
this.mt[0]= a[0];
for (i = 1; i < N; ++i) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] = (
(1812433253 * ((s & 0xffff0000) >>> 16))
<< 16
) +
1812433253 * (s & 0x0000ffff) +
i;
}
this.mti = N;
return;
}
this.setSeed(19650218);
var l = a[0].length;
var j = 0;
i = 1;
for (k = N > l ? N : l; k !== 0; --k) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] = (
this.mt[i] ^
(
((1664525 * ((s & 0xffff0000) >>> 16)) << 16) +
1664525 * (s & 0x0000ffff)
)
) + a[0][j] + j;
if (++i >= N) {
this.mt[0] = this.mt[N - 1];
i = 1;
}
if (++j >= l) {
j = 0;
}
}
for (k = N - 1; k !== 0; --k) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] = (
this.mt[i] ^
(
((1566083941 * ((s & 0xffff0000) >>> 16)) << 16) +
1566083941 * (s & 0x0000ffff)
)
) - i;
if (++i >= N) {
this.mt[0] = this.mt[N-1];
i = 1;
}
}
this.mt[0] = 0x80000000;
return;
default:
var seeds = [];
for (i = 0; i < a.length; ++i) {
seeds.push(a[i]);
}
this.setSeed(seeds);
return;
}
};
this.setSeed(0x1BADF00D);
this.next = function (bits)
{
var k;
if (this.mti >= N) {
var x = 0;
for (k = 0; k < N - M; ++k) {
x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff);
this.mt[k] = this.mt[k + M] ^ (x >>> 1) ^ MAG01[x & 0x1];
}
for (k = N - M; k < N - 1; ++k) {
x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff);
this.mt[k] = this.mt[k + (M - N)] ^ (x >>> 1) ^ MAG01[x & 0x1];
}
x = (this.mt[N - 1] & 0x80000000) | (this.mt[0] & 0x7fffffff);
this.mt[N - 1] = this.mt[M - 1] ^ (x >>> 1) ^ MAG01[x & 0x1];
this.mti = 0;
}
var y = this.mt[this.mti++];
y ^= y >>> 11;
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= y >>> 18;
return (y >>> (32 - bits)) & 0xFFFFFFFF;
};
}
// Position variables
var g_board = new Array(256); // Sentinel 0x80, pieces are in low 4 bits, 0x8 for color, 0x7 bits for piece type
var g_toMove; // side to move, 0 or 8, 0 = black, 8 = white
var g_castleRights; // bitmask representing castling rights, 1 = wk, 2 = wq, 4 = bk, 8 = bq
var g_enPassentSquare;
var g_baseEval;
var g_hashKeyLow, g_hashKeyHigh;
var g_inCheck;
// Utility variables
var g_moveCount = 0;
var g_moveUndoStack = [];
var g_move50 = 0;
var g_repMoveStack = [];
var g_hashSize = 1 << 22;
var g_hashMask = g_hashSize - 1;
var g_hashTable;
var g_killers;
var historyTable = new Array(32);
var g_zobristLow;
var g_zobristHigh;
var g_zobristBlackLow;
var g_zobristBlackHigh;
// Evaulation variables
var g_mobUnit;
var hashflagAlpha = 1;
var hashflagBeta = 2;
var hashflagExact = 3;
function HashEntry(lock, value, flags, hashDepth, bestMove, globalPly) {
this.lock = lock;
this.value = value;
this.flags = flags;
this.hashDepth = hashDepth;
this.bestMove = bestMove;
}
function MakeSquare(row, column) {
return ((row + 2) << 4) | (column + 4);
}
function MakeTable(table) {
var result = new Array(256);
for (var i = 0; i < 256; i++) {
result[i] = 0;
}
for (var row = 0; row < 8; row++) {
for (var col = 0; col < 8; col++) {
result[MakeSquare(row, col)] = table[row * 8 + col];
}
}
return result;
}
function ResetGame(fen) {
var i,j;
var row, col;
var square;
g_killers = new Array(128);
for (i = 0; i < 128; i++) {
g_killers[i] = [0, 0];
}
g_hashTable = new Array(g_hashSize);
for (i = 0; i < 32; i++) {
historyTable[i] = new Array(256);
for (j = 0; j < 256; j++)
historyTable[i][j] = 0;
}
var mt = new MT(0x1badf00d);
g_zobristLow = new Array(256);
g_zobristHigh = new Array(256);
for (i = 0; i < 256; i++) {
g_zobristLow[i] = new Array(16);
g_zobristHigh[i] = new Array(16);
for (j = 0; j < 16; j++) {
g_zobristLow[i][j] = mt.next(32);
g_zobristHigh[i][j] = mt.next(32);
}
}
g_zobristBlackLow = mt.next(32);
g_zobristBlackHigh = mt.next(32);
for (row = 0; row < 8; row++) {
for (col = 0; col < 8; col++) {
square = MakeSquare(row, col);
flipTable[square] = MakeSquare(7 - row, col);
}
}
pieceSquareAdj[piecePawn] = MakeTable(pawnAdj);
pieceSquareAdj[pieceKnight] = MakeTable(knightAdj);
pieceSquareAdj[pieceBishop] = MakeTable(bishopAdj);
pieceSquareAdj[pieceRook] = MakeTable(rookAdj);
pieceSquareAdj[pieceQueen] = MakeTable(emptyAdj);
pieceSquareAdj[pieceKing] = MakeTable(kingAdj);
var pieceDeltas = [[], [], g_knightDeltas, g_bishopDeltas, g_rookDeltas, g_queenDeltas, g_queenDeltas];
for (i = 0; i < 256; i++) {
g_vectorDelta[i] = {};
g_vectorDelta[i].delta = 0;
g_vectorDelta[i].pieceMask = new Array(2);
g_vectorDelta[i].pieceMask[0] = 0;
g_vectorDelta[i].pieceMask[1] = 0;
}
// Initialize the vector delta table
for (row = 0; row < 0x80; row += 0x10)
for (col = 0; col < 0x8; col++) {
square = row | col;
// Pawn moves
var index = square - (square - 17) + 128;
g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn);
index = square - (square - 15) + 128;
g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn);
index = square - (square + 17) + 128;
g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn);
index = square - (square + 15) + 128;
g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn);
for (i = pieceKnight; i <= pieceKing; i++) {
for (var dir = 0; dir < pieceDeltas[i].length; dir++) {
var target = square + pieceDeltas[i][dir];
while (!(target & 0x88)) {
index = square - target + 128;
g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << i);
g_vectorDelta[index].pieceMask[0] |= (1 << i);
var flip = -1;
if (square < target)
flip = 1;
if ((square & 0xF0) == (target & 0xF0)) {
// On the same row
g_vectorDelta[index].delta = flip * 1;
} else if ((square & 0x0F) == (target & 0x0F)) {
// On the same column
g_vectorDelta[index].delta = flip * 16;
} else if ((square % 15) == (target % 15)) {
g_vectorDelta[index].delta = flip * 15;
} else if ((square % 17) == (target % 17)) {
g_vectorDelta[index].delta = flip * 17;
}
if (i == pieceKnight) {
g_vectorDelta[index].delta = pieceDeltas[i][dir];
break;
}
if (i == pieceKing)
break;
target += pieceDeltas[i][dir];
}
}
}
}
InitializeEval();
InitializeFromFen("rnbqkbnr/8/pppppppp/8/8/PPPPPPPP/8/RNBKQBNR w QKkq - 0 1");
}
function InitializeEval() {
g_mobUnit = new Array(2);
for (var i = 0; i < 2; i++) {
g_mobUnit[i] = [];
var enemy = i === 0 ? 0x10 : 8;
var friend = i === 0 ? 8 : 0x10;
g_mobUnit[i][0] = 1;
g_mobUnit[i][0x80] = 0;
g_mobUnit[i][enemy | piecePawn] = 1;
g_mobUnit[i][enemy | pieceBishop] = 2;
g_mobUnit[i][enemy | pieceKnight] = 2;
g_mobUnit[i][enemy | pieceRook] = 4;
g_mobUnit[i][enemy | pieceQueen] = 6;
g_mobUnit[i][enemy | pieceKing] = 6;
g_mobUnit[i][friend | piecePawn] = 0;
g_mobUnit[i][friend | pieceBishop] = 0;
g_mobUnit[i][friend | pieceKnight] = 0;
g_mobUnit[i][friend | pieceRook] = 0;
g_mobUnit[i][friend | pieceQueen] = 0;
g_mobUnit[i][friend | pieceKing] = 0;
}
}
function SetHash() {
var result = {};
result.hashKeyLow = 0;
result.hashKeyHigh = 0;
for (var i = 0; i < 256; i++) {
var piece = g_board[i];
if (piece & 0x18) {
result.hashKeyLow ^= g_zobristLow[i][piece & 0xF];
result.hashKeyHigh ^= g_zobristHigh[i][piece & 0xF];
}
}
if (!g_toMove) {
result.hashKeyLow ^= g_zobristBlackLow;
result.hashKeyHigh ^= g_zobristBlackHigh;
}
return result;
}
function InitializeFromFen(fen) {
var i;
var row = 0;
var col = 0;
var chunks = fen.split(' ');
for (i = 0; i < 256; i++)
g_board[i] = 0x80;
var pieces = chunks[0];
for (i = 0; i < pieces.length; i++) {
var c = pieces.charAt(i);
if (c == '/') {
row++;
col = 0;
}
else {
if (c >= '0' && c <= '9') {
for (var j = 0; j < parseInt(c,10); j++) {
g_board[MakeSquare(row, col)] = 0;
col++;
}
}
else {
var isBlack = c >= 'a' && c <= 'z';
var piece = isBlack ? colorBlack : colorWhite;
if (!isBlack)
c = pieces.toLowerCase().charAt(i);
switch (c) {
case 'p':
piece |= piecePawn;
break;
case 'b':
piece |= pieceBishop;
break;
case 'n':
piece |= pieceKnight;
break;
case 'r':
piece |= pieceRook;
break;
case 'q':
piece |= pieceQueen;
break;
case 'k':
piece |= pieceKing;
break;
}
g_board[MakeSquare(row, col)] = piece;
col++;
}
}
}
InitializePieceList();
g_toMove = chunks[1].charAt(0) == 'w' ? colorWhite : 0;
var them = 8 - g_toMove;
g_castleRights = 0;
if (chunks[2].indexOf('K') != -1) {
if (g_board[MakeSquare(7, 4)] != (pieceKing | colorWhite) ||
g_board[MakeSquare(7, 7)] != (pieceRook | colorWhite)) {
return 'Invalid FEN: White kingside castling not allowed';
}
g_castleRights |= 1;
}
if (chunks[2].indexOf('Q') != -1) {
if (g_board[MakeSquare(7, 4)] != (pieceKing | colorWhite) ||
g_board[MakeSquare(7, 0)] != (pieceRook | colorWhite)) {
return 'Invalid FEN: White queenside castling not allowed';
}
g_castleRights |= 2;
}
if (chunks[2].indexOf('k') != -1) {
if (g_board[MakeSquare(0, 4)] != (pieceKing | colorBlack) ||
g_board[MakeSquare(0, 7)] != (pieceRook | colorBlack)) {
return 'Invalid FEN: Black kingside castling not allowed';
}
g_castleRights |= 4;
}
if (chunks[2].indexOf('q') != -1) {
if (g_board[MakeSquare(0, 4)] != (pieceKing | colorBlack) ||
g_board[MakeSquare(0, 0)] != (pieceRook | colorBlack)) {
return 'Invalid FEN: Black queenside castling not allowed';
}
g_castleRights |= 8;
}
g_enPassentSquare = -1;
if (chunks[3].indexOf('-') == -1) {
col = chunks[3].charAt(0).charCodeAt() - 'a'.charCodeAt();
row = 8 - (chunks[3].charAt(1).charCodeAt() - '0'.charCodeAt());
g_enPassentSquare = MakeSquare(row, col);
}
var hashResult = SetHash();
g_hashKeyLow = hashResult.hashKeyLow;
g_hashKeyHigh = hashResult.hashKeyHigh;
g_baseEval = 0;
for (i = 0; i < 256; i++) {
if (g_board[i] & colorWhite) {
g_baseEval += pieceSquareAdj[g_board[i] & 0x7][i];
g_baseEval += materialTable[g_board[i] & 0x7];
} else if (g_board[i] & colorBlack) {
g_baseEval -= pieceSquareAdj[g_board[i] & 0x7][flipTable[i]];
g_baseEval -= materialTable[g_board[i] & 0x7];
}
}
if (!g_toMove) g_baseEval = -g_baseEval;
g_move50 = 0;
g_inCheck = IsSquareAttackable(g_pieceList[(g_toMove | pieceKing) << 4], them);
// Check for king capture (invalid FEN)
if (IsSquareAttackable(g_pieceList[(them | pieceKing) << 4], g_toMove)) {
return 'Invalid FEN: Can capture king';
}
// Checkmate/stalemate
if (GenerateValidMoves().length === 0) {
return g_inCheck ? 'Checkmate' : 'Stalemate';
}
return '';
}
var g_pieceIndex = new Array(256);
var g_pieceList = new Array(2 * 8 * 16);
var g_pieceCount = new Array(2 * 8);
function InitializePieceList() {
var i;
for (i = 0; i < 16; i++) {
g_pieceCount[i] = 0;
for (var j = 0; j < 16; j++) {
// 0 is used as the terminator for piece lists
g_pieceList[(i << 4) | j] = 0;
}
}
for (i = 0; i < 256; i++) {
g_pieceIndex[i] = 0;
if (g_board[i] & (colorWhite | colorBlack)) {
var piece = g_board[i] & 0xF;
g_pieceList[(piece << 4) | g_pieceCount[piece]] = i;
g_pieceIndex[i] = g_pieceCount[piece];
g_pieceCount[piece]++;
}
}
}
function MakeMove(move){
// move format:
// --flags-- ---to---- --from---
// 0000 0000 0000 0000 0000 0000
// g_board is a 256x256 array
// representing the chess board
// right in the middle of it
// moveflagEPC = 0000 0010 0000 0000 0000 0000
// moveflagCastleKing = 0000 0100 0000 0000 0000 0000
// moveflagCastleQueen = 0000 1000 0000 0000 0000 0000
// moveflagPromotion = 0001 0000 0000 0000 0000 0000
// moveflagPromoteRook = 0000 0000 0000 0000 0000 0000
// moveflagPromoteKnight = 0010 0000 0000 0000 0000 0000
// moveflagPromoteQueen = 0100 0000 0000 0000 0000 0000
// moveflagPromoteBishop = 1000 0000 0000 0000 0000 0000
var me = g_toMove >> 3;
var otherColor = 8 - g_toMove;
var flags = move & 0xFF0000;
var to = (move >> 8) & 0xFF;
var from = move & 0xFF;
var captured = g_board[to];
var piece = g_board[from];
var epcEnd = to;
var rook, rookIndex;
if (flags & moveflagEPC) {
epcEnd = me ? (to + 0x10) : (to - 0x10);
captured = g_board[epcEnd];
g_board[epcEnd] = pieceEmpty;
}
g_moveUndoStack[g_moveCount] = new UndoHistory(g_enPassentSquare, g_castleRights, g_inCheck, g_baseEval, g_hashKeyLow, g_hashKeyHigh, g_move50, captured);
g_moveCount++;
g_enPassentSquare = -1;
if (flags) {
if (flags & moveflagCastleKing) {
if (IsSquareAttackable(from + 1, otherColor) ||
IsSquareAttackable(from + 2, otherColor)) {
g_moveCount--;
return false;
}
rook = g_board[to + 1];
g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF];
g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF];
g_hashKeyLow ^= g_zobristLow[to - 1][rook & 0xF];
g_hashKeyHigh ^= g_zobristHigh[to - 1][rook & 0xF];
g_board[to - 1] = rook;
g_board[to + 1] = pieceEmpty;
g_baseEval -= pieceSquareAdj[rook & 0x7][me === 0 ? flipTable[to + 1] : (to + 1)];
g_baseEval += pieceSquareAdj[rook & 0x7][me === 0 ? flipTable[to - 1] : (to - 1)];
rookIndex = g_pieceIndex[to + 1];
g_pieceIndex[to - 1] = rookIndex;
g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 1;
} else if (flags & moveflagCastleQueen) {
if (IsSquareAttackable(from - 1, otherColor) ||
IsSquareAttackable(from - 2, otherColor)) {
g_moveCount--;
return false;
}
rook = g_board[to - 2];
g_hashKeyLow ^= g_zobristLow[to -2][rook & 0xF];
g_hashKeyHigh ^= g_zobristHigh[to - 2][rook & 0xF];
g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF];
g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF];
g_board[to + 1] = rook;
g_board[to - 2] = pieceEmpty;
g_baseEval -= pieceSquareAdj[rook & 0x7][me === 0 ? flipTable[to - 2] : (to - 2)];
g_baseEval += pieceSquareAdj[rook & 0x7][me === 0 ? flipTable[to + 1] : (to + 1)];
rookIndex = g_pieceIndex[to - 2];
g_pieceIndex[to + 1] = rookIndex;
g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1;
}
}
if ((captured & 0x7) > 0) {
// Remove our piece from the piece list
var capturedType = captured & 0xF;
g_pieceCount[capturedType]--;
var lastPieceSquare = g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]];
g_pieceIndex[lastPieceSquare] = g_pieceIndex[epcEnd];
g_pieceList[(capturedType << 4) | g_pieceIndex[lastPieceSquare]] = lastPieceSquare;
g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]] = 0;
g_baseEval += materialTable[captured & 0x7];
g_baseEval += pieceSquareAdj[captured & 0x7][me ? flipTable[epcEnd] : epcEnd];
g_hashKeyLow ^= g_zobristLow[epcEnd][capturedType];
g_hashKeyHigh ^= g_zobristHigh[epcEnd][capturedType];
g_move50 = 0;
} else if ((piece & 0x7) == piecePawn) {
var diff = to - from;
if (diff < 0) diff = -diff;
if (diff > 16) {
g_enPassentSquare = me ? (to + 0x10) : (to - 0x10);
}
g_move50 = 0;
}
g_hashKeyLow ^= g_zobristLow[from][piece & 0xF];
g_hashKeyHigh ^= g_zobristHigh[from][piece & 0xF];
g_hashKeyLow ^= g_zobristLow[to][piece & 0xF];
g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF];
g_hashKeyLow ^= g_zobristBlackLow;
g_hashKeyHigh ^= g_zobristBlackHigh;
g_castleRights &= g_castleRightsMask[from] & g_castleRightsMask[to];
g_baseEval -= pieceSquareAdj[piece & 0x7][me === 0 ? flipTable[from] : from];
// Move our piece in the piece list
g_pieceIndex[to] = g_pieceIndex[from];
g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[to]] = to;
if (flags & moveflagPromotion) {
var newPiece = piece & (~0x7);
if (flags & moveflagPromoteKnight)
newPiece |= pieceKnight;
else if (flags & moveflagPromoteQueen)
newPiece |= pieceQueen;
else if (flags & moveflagPromoteBishop)
newPiece |= pieceBishop;
else
newPiece |= pieceRook;
g_hashKeyLow ^= g_zobristLow[to][piece & 0xF];
g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF];
g_board[to] = newPiece;
g_hashKeyLow ^= g_zobristLow[to][newPiece & 0xF];
g_hashKeyHigh ^= g_zobristHigh[to][newPiece & 0xF];
g_baseEval += pieceSquareAdj[newPiece & 0x7][me === 0 ? flipTable[to] : to];
g_baseEval -= materialTable[piecePawn];
g_baseEval += materialTable[newPiece & 0x7];
var pawnType = piece & 0xF;
var promoteType = newPiece & 0xF;
g_pieceCount[pawnType]--;
var lastPawnSquare = g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]];
g_pieceIndex[lastPawnSquare] = g_pieceIndex[to];
g_pieceList[(pawnType << 4) | g_pieceIndex[lastPawnSquare]] = lastPawnSquare;
g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]] = 0;
g_pieceIndex[to] = g_pieceCount[promoteType];
g_pieceList[(promoteType << 4) | g_pieceIndex[to]] = to;
g_pieceCount[promoteType]++;
} else {
g_board[to] = g_board[from];
g_baseEval += pieceSquareAdj[piece & 0x7][me === 0 ? flipTable[to] : to];
}
g_board[from] = pieceEmpty;
g_toMove = otherColor;
g_baseEval = -g_baseEval;
if ((piece & 0x7) == pieceKing || g_inCheck) {
if (IsSquareAttackable(g_pieceList[(pieceKing | (8 - g_toMove)) << 4], otherColor)) {
UnmakeMove(move);
return false;
}
} else {
var kingPos = g_pieceList[(pieceKing | (8 - g_toMove)) << 4];
if (ExposesCheck(from, kingPos)) {
UnmakeMove(move);
return false;
}
if (epcEnd != to) {
if (ExposesCheck(epcEnd, kingPos)) {
UnmakeMove(move);
return false;
}
}
}
g_inCheck = false;
if (flags <= moveflagEPC) {
var theirKingPos = g_pieceList[(pieceKing | g_toMove) << 4];
// First check if the piece we moved can attack the enemy king
g_inCheck = IsSquareAttackableFrom(theirKingPos, to);
if (!g_inCheck) {
// Now check if the square we moved from exposes check on the enemy king
g_inCheck = ExposesCheck(from, theirKingPos);
if (!g_inCheck) {
// Finally, ep. capture can cause another square to be exposed
if (epcEnd != to) {
g_inCheck = ExposesCheck(epcEnd, theirKingPos);
}
}
}
}
else {
// Castle or promotion, slow check
g_inCheck = IsSquareAttackable(g_pieceList[(pieceKing | g_toMove) << 4], 8 - g_toMove);
}
g_repMoveStack[g_moveCount - 1] = g_hashKeyLow;
g_move50++;
return true;
}
function UnmakeMove(move){
g_toMove = 8 - g_toMove;
g_baseEval = -g_baseEval;
g_moveCount--;
g_enPassentSquare = g_moveUndoStack[g_moveCount].ep;
g_castleRights = g_moveUndoStack[g_moveCount].castleRights;
g_inCheck = g_moveUndoStack[g_moveCount].inCheck;
g_baseEval = g_moveUndoStack[g_moveCount].baseEval;
g_hashKeyLow = g_moveUndoStack[g_moveCount].hashKeyLow;
g_hashKeyHigh = g_moveUndoStack[g_moveCount].hashKeyHigh;
g_move50 = g_moveUndoStack[g_moveCount].move50;
var otherColor = 8 - g_toMove;
var me = g_toMove >> 3;
var them = otherColor >> 3;
var flags = move & 0xFF0000;
var captured = g_moveUndoStack[g_moveCount].captured;
var to = (move >> 8) & 0xFF;
var from = move & 0xFF;
var piece = g_board[to];
var rook,rookIndex;
if (flags) {
if (flags & moveflagCastleKing) {
rook = g_board[to - 1];
g_board[to + 1] = rook;
g_board[to - 1] = pieceEmpty;
rookIndex = g_pieceIndex[to - 1];
g_pieceIndex[to + 1] = rookIndex;
g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1;
}
else if (flags & moveflagCastleQueen) {
rook = g_board[to + 1];
g_board[to - 2] = rook;
g_board[to + 1] = pieceEmpty;
rookIndex = g_pieceIndex[to + 1];
g_pieceIndex[to - 2] = rookIndex;
g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 2;
}
}
if (flags & moveflagPromotion) {
piece = (g_board[to] & (~0x7)) | piecePawn;
g_board[from] = piece;
var pawnType = g_board[from] & 0xF;
var promoteType = g_board[to] & 0xF;
g_pieceCount[promoteType]--;
var lastPromoteSquare = g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]];
g_pieceIndex[lastPromoteSquare] = g_pieceIndex[to];
g_pieceList[(promoteType << 4) | g_pieceIndex[lastPromoteSquare]] = lastPromoteSquare;
g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]] = 0;
g_pieceIndex[to] = g_pieceCount[pawnType];
g_pieceList[(pawnType << 4) | g_pieceIndex[to]] = to;
g_pieceCount[pawnType]++;
}
else {
g_board[from] = g_board[to];
}
var epcEnd = to;
if (flags & moveflagEPC) {
if (g_toMove == colorWhite)
epcEnd = to + 0x10;
else
epcEnd = to - 0x10;
g_board[to] = pieceEmpty;
}
g_board[epcEnd] = captured;
// Move our piece in the piece list
g_pieceIndex[from] = g_pieceIndex[to];
g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[from]] = from;
if (captured) {
// Restore our piece to the piece list
var captureType = captured & 0xF;
g_pieceIndex[epcEnd] = g_pieceCount[captureType];
g_pieceList[(captureType << 4) | g_pieceCount[captureType]] = epcEnd;
g_pieceCount[captureType]++;
}
}
function ExposesCheck(from, kingPos){
var index = kingPos - from + 128;
// If a queen can't reach it, nobody can!
if ((g_vectorDelta[index].pieceMask[0] & (1 << (pieceQueen))) !== 0) {
var delta = g_vectorDelta[index].delta;
var pos = kingPos + delta;
while (g_board[pos] === 0) pos += delta;
var piece = g_board[pos];
if (((piece & (g_board[kingPos] ^ 0x18)) & 0x18) === 0)
return false;
// Now see if the piece can actually attack the king
var backwardIndex = pos - kingPos + 128;
return (g_vectorDelta[backwardIndex].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) !== 0;
}
return false;
}
function IsSquareOnPieceLine(target, from) {
var index = from - target + 128;
var piece = g_board[from];
return (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) ? true : false;
}
function IsSquareAttackableFrom(target, from){
var index = from - target + 128;
var piece = g_board[from];
if (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) {
// Yes, this square is pseudo-attackable. Now, check for real attack
var inc = g_vectorDelta[index].delta;
do {
from += inc;
if (from == target)
return true;
} while (g_board[from] === 0);
}
return false;
}
function IsSquareAttackable(target, color) {
// Attackable by pawns?
var inc = color ? -16 : 16;
var pawn = (color ? colorWhite : colorBlack) | 1;
if (g_board[target - (inc - 1)] == pawn)
return true;
if (g_board[target - (inc + 1)] == pawn)
return true;
// Attackable by pieces?
for (var i = 2; i <= 6; i++) {
var index = (color | i) << 4;
var square = g_pieceList[index];
while (square !== 0) {
if (IsSquareAttackableFrom(target, square))
return true;
square = g_pieceList[++index];
}
}
return false;
}
function GenerateMove(from, to) {
return from | (to << 8);
}
function GenerateMove(from, to, flags){
return from | (to << 8) | flags;
}
function GenerateValidMoves() {
var moveList = [];
var allMoves = [];
GenerateCaptureMoves(allMoves, null);
GenerateAllMoves(allMoves);
for (var i = allMoves.length - 1; i >= 0; i--) {
if (MakeMove(allMoves[i])) {
moveList[moveList.length] = allMoves[i];
UnmakeMove(allMoves[i]);
} else {
}
}
return moveList;
}
//**********raksa move pos
function GenerateAllMoves(moveStack) {
var from, to, piece, pieceIdx;
// Pawn quiet moves
pieceIdx = (g_toMove | 1) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
GeneratePawnMoves(moveStack, from);
from = g_pieceList[pieceIdx++];
}
// Knight quiet moves
pieceIdx = (g_toMove | 2) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from + 31;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 33;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 14;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 14;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 31;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 33;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 18;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 18;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
from = g_pieceList[pieceIdx++];
}
// Bishop quiet moves
pieceIdx = (g_toMove | 3) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from - 15;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; }
to = from - 17;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; }
to = from + 15;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; }
to = from + 17;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; }
from = g_pieceList[pieceIdx++];
}
// Rook quiet moves
pieceIdx = (g_toMove | 4) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from - 1;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; }
to = from + 1;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; }
to = from + 16;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; }
to = from - 16;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; }
from = g_pieceList[pieceIdx++];
}
// Queen quiet moves
pieceIdx = (g_toMove | 5) << 4;
from = g_pieceList[pieceIdx++];
/*
while (from !== 0) {
to = from - 15;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; }
to = from - 17;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; }
to = from + 15;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; }
to = from + 17;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; }
to = from - 1;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; }
to = from + 1;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; }
to = from + 16;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; }
to = from - 16;
while (g_board[to] === 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; }
from = g_pieceList[pieceIdx++];
}*/
to = from - 15;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 17;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 15;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 17;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
// King quiet moves
pieceIdx = (g_toMove | 6) << 4;
from = g_pieceList[pieceIdx];
to = from - 15;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 17;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 15;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 17;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 1;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 1;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 16;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 16;
if (g_board[to] === 0) moveStack[moveStack.length] = GenerateMove(from, to);
/*
if (!g_inCheck) {
var castleRights = g_castleRights;
if (!g_toMove)
castleRights >>= 2;
if (castleRights & 1) {
// Kingside castle
if (g_board[from + 1] == pieceEmpty && g_board[from + 2] == pieceEmpty) {
moveStack[moveStack.length] = GenerateMove(from, from + 0x02, moveflagCastleKing);
}
}
if (castleRights & 2) {
// Queenside castle
if (g_board[from - 1] == pieceEmpty && g_board[from - 2] == pieceEmpty && g_board[from - 3] == pieceEmpty) {
moveStack[moveStack.length] = GenerateMove(from, from - 0x02, moveflagCastleQueen);
}
}
}*/
}
//****************raksa move capture
function GenerateCaptureMoves(moveStack, moveScores) {
var from, to, piece, pieceIdx;
var inc = (g_toMove == 8) ? -16 : 16;
var enemy = g_toMove == 8 ? 0x10 : 0x8;
// Pawn captures
pieceIdx = (g_toMove | 1) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from + inc - 1;
if (g_board[to] & enemy) {
MovePawnTo(moveStack, from, to);
}
to = from + inc + 1;
if (g_board[to] & enemy) {
MovePawnTo(moveStack, from, to);
}
from = g_pieceList[pieceIdx++];
}
if (g_enPassentSquare !== -1) {
inc = (g_toMove === colorWhite) ? -16 : 16;
var pawn = g_toMove | piecePawn;
from = g_enPassentSquare - (inc + 1);
if ((g_board[from] & 0xF) === pawn) {
moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC);
}
from = g_enPassentSquare - (inc - 1);
if ((g_board[from] & 0xF) === pawn) {
moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC);
}
}
// Knight captures
pieceIdx = (g_toMove | 2) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from + 31;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 33;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 14;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 14;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 31;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 33;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 18;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 18;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
from = g_pieceList[pieceIdx++];
}
// Bishop captures
pieceIdx = (g_toMove | 3) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from;
do { to -= 15; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to -= 17; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to += 15; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to += 17; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
from = g_pieceList[pieceIdx++];
}
// Rook captures
pieceIdx = (g_toMove | 4) << 4;
from = g_pieceList[pieceIdx++];
while (from !== 0) {
to = from;
do { to--; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to++; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to -= 16; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to += 16; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
from = g_pieceList[pieceIdx++];
}
// Queen captures
pieceIdx = (g_toMove | 5) << 4;
from = g_pieceList[pieceIdx++];
/*
while (from !== 0) {
to = from;
do { to -= 15; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to -= 17; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to += 15; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to += 17; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to--; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to++; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to -= 16; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from;
do { to += 16; } while (g_board[to] === 0);
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
from = g_pieceList[pieceIdx++];
}*/
to = from - 15;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 17;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 15;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 17;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
// King captures
pieceIdx = (g_toMove | 6) << 4;
from = g_pieceList[pieceIdx];
to = from - 15;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 17;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 15;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 17;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 1;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 1;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from - 16;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
to = from + 16;
if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
}
function MovePawnTo(moveStack, start, square) {
var row = square & 0xF0;
if ((row == 0x90) || (row == 0x20)) {
moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteQueen);
moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteKnight);
moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteBishop);
moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion);
}
else {
moveStack[moveStack.length] = GenerateMove(start, square, 0);
}
}
function GeneratePawnMoves(moveStack, from) {
var piece = g_board[from];
var color = piece & colorWhite;
var inc = (color === colorWhite) ? -16 : 16;
// Quiet pawn moves
var to = from + inc;
if (g_board[to] === 0) {
MovePawnTo(moveStack, from, to, pieceEmpty);
// Check if we can do a 2 square jump
/*if ((((from & 0xF0) === 0x30) && color !== colorWhite) ||
(((from & 0xF0) === 0x80) && color === colorWhite)) {
to += inc;
if (g_board[to] === 0) {
moveStack[moveStack.length] = GenerateMove(from, to);
}
}*/
}
}
function UndoHistory(ep, castleRights, inCheck, baseEval, hashKeyLow, hashKeyHigh, move50, captured) {
this.ep = ep;
this.castleRights = castleRights;
this.inCheck = inCheck;
this.baseEval = baseEval;
this.hashKeyLow = hashKeyLow;
this.hashKeyHigh = hashKeyHigh;
this.move50 = move50;
this.captured = captured;
}
var g_seeValues = [ 0, 1, 3, 3, 5, 9, 900, 0,
0, 1, 3, 3, 5, 9, 900, 0];
function See(move) {
var from = move & 0xFF;
var to = (move >> 8) & 0xFF;
var fromPiece = g_board[from];
var fromValue = g_seeValues[fromPiece & 0xF];
var toValue = g_seeValues[g_board[to] & 0xF];
var pieceType,pieceValue,i;
if (fromValue <= toValue) {
return true;
}
if (move >> 16) {
// Castles, promotion, ep are always good
return true;
}
var us = (fromPiece & colorWhite) ? colorWhite : 0;
var them = 8 - us;
// Pawn attacks
// If any opponent pawns can capture back, this capture is probably not worthwhile (as we must be using knight or above).
var inc = (fromPiece & colorWhite) ? -16 : 16; // Note: this is capture direction from to, so reversed from normal move direction
if (((g_board[to + inc + 1] & 0xF) == (piecePawn | them)) ||
((g_board[to + inc - 1] & 0xF) == (piecePawn | them))) {
return false;
}
var themAttacks = [];
// Knight attacks
// If any opponent knights can capture back, and the deficit we have to make up is greater than the knights value,
// it's not worth it. We can capture on this square again, and the opponent doesn't have to capture back.
var captureDeficit = fromValue - toValue;
SeeAddKnightAttacks(to, them, themAttacks);
if (themAttacks.length !== 0 && captureDeficit > g_seeValues[pieceKnight]) {
return false;
}
// Slider attacks
g_board[from] = 0;
for (pieceType = pieceBishop; pieceType <= pieceQueen; pieceType++) {
if (SeeAddSliderAttacks(to, them, themAttacks, pieceType)) {
if (captureDeficit > g_seeValues[pieceType]) {
g_board[from] = fromPiece;
return false;
}
}
}
// Pawn defenses
// At this point, we are sure we are making a "losing" capture. The opponent can not capture back with a
// pawn. They cannot capture back with a minor/major and stand pat either. So, if we can capture with
// a pawn, it's got to be a winning or equal capture.
if (((g_board[to - inc + 1] & 0xF) === (piecePawn | us)) ||
((g_board[to - inc - 1] & 0xF) === (piecePawn | us))) {
g_board[from] = fromPiece;
return true;
}
// King attacks
SeeAddSliderAttacks(to, them, themAttacks, pieceKing);
// Our attacks
var usAttacks = [];
SeeAddKnightAttacks(to, us, usAttacks);
for (pieceType = pieceBishop; pieceType <= pieceKing; pieceType++) {
SeeAddSliderAttacks(to, us, usAttacks, pieceType);
}
g_board[from] = fromPiece;
// We are currently winning the amount of material of the captured piece, time to see if the opponent
// can get it back somehow. We assume the opponent can capture our current piece in this score, which
// simplifies the later code considerably.
var seeValue = toValue - fromValue;
for (; ; ) {
var capturingPieceValue = 1000;
var capturingPieceIndex = -1;
// Find the least valuable piece of the opponent that can attack the square
for (i = 0; i < themAttacks.length; i++) {
if (themAttacks[i] !== 0) {
pieceValue = g_seeValues[g_board[themAttacks[i]] & 0x7];
if (pieceValue < capturingPieceValue) {
capturingPieceValue = pieceValue;
capturingPieceIndex = i;
}
}
}
if (capturingPieceIndex == -1) {
// Opponent can't capture back, we win
return true;
}
// Now, if seeValue < 0, the opponent is winning. If even after we take their piece,
// we can't bring it back to 0, then we have lost this battle.
seeValue += capturingPieceValue;
if (seeValue < 0) {
return false;
}
var capturingPieceSquare = themAttacks[capturingPieceIndex];
themAttacks[capturingPieceIndex] = 0;
// Add any x-ray attackers
SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks);
// Our turn to capture
capturingPieceValue = 1000;
capturingPieceIndex = -1;
// Find our least valuable piece that can attack the square
for (i = 0; i < usAttacks.length; i++) {
if (usAttacks[i] !== 0) {
pieceValue = g_seeValues[g_board[usAttacks[i]] & 0x7];
if (pieceValue < capturingPieceValue) {
capturingPieceValue = pieceValue;
capturingPieceIndex = i;
}
}
}
if (capturingPieceIndex == -1) {
// We can't capture back, we lose :(
return false;
}
// Assume our opponent can capture us back, and if we are still winning, we can stand-pat
// here, and assume we've won.
seeValue -= capturingPieceValue;
if (seeValue >= 0) {
return true;
}
capturingPieceSquare = usAttacks[capturingPieceIndex];
usAttacks[capturingPieceIndex] = 0;
// Add any x-ray attackers
SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks);
}
}
function SeeAddXrayAttack(target, square, us, usAttacks, themAttacks) {
var index = square - target + 128;
var delta = -g_vectorDelta[index].delta;
if (delta === 0)
return;
square += delta;
while (g_board[square] === 0) {
square += delta;
}
if ((g_board[square] & 0x18) && IsSquareOnPieceLine(target, square)) {
if ((g_board[square] & 8) == us) {
usAttacks[usAttacks.length] = square;
} else {
themAttacks[themAttacks.length] = square;
}
}
}
// target = attacking square, us = color of knights to look for, attacks = array to add squares to
function SeeAddKnightAttacks(target, us, attacks) {
var pieceIdx = (us | pieceKnight) << 4;
var attackerSq = g_pieceList[pieceIdx++];
while (attackerSq !== 0) {
if (IsSquareOnPieceLine(target, attackerSq)) {
attacks[attacks.length] = attackerSq;
}
attackerSq = g_pieceList[pieceIdx++];
}
}
function SeeAddSliderAttacks(target, us, attacks, pieceType) {
var pieceIdx = (us | pieceType) << 4;
var attackerSq = g_pieceList[pieceIdx++];
var hit = false;
while (attackerSq !== 0) {
if (IsSquareAttackableFrom(target, attackerSq)) {
attacks[attacks.length] = attackerSq;
hit = true;
}
attackerSq = g_pieceList[pieceIdx++];
}
return hit;
}
function BuildPVMessage(bestMove, value, timeTaken, ply) {
var totalNodes = g_nodeCount + g_qNodeCount;
return "Ply:" + ply + " Score:" + value + " Nodes:" + totalNodes + " NPS:" + ((totalNodes / (timeTaken / 1000)) | 0) + " " + PVFromHash(bestMove, 15);
}
//////////////////////////////////////////////////
// Test Harness
//////////////////////////////////////////////////
function FinishPlyCallback(bestMove, value, timeTaken, ply) {
postMessage("pv " + BuildPVMessage(bestMove, value, timeTaken, ply));
}
function FinishMoveLocalTesting(bestMove, value, timeTaken, ply) {
if (bestMove !== undefined) {
MakeMove(bestMove);
postMessage(FormatMove(bestMove));
}
}
var needsReset = true;
self.onmessage = function (e) {
if (e.data == "go" || needsReset) {
ResetGame();
needsReset = false;
if (e.data == "go") return;
}
if (e.data.match("^position") == "position") {
ResetGame();
var result = InitializeFromFen(e.data.substr(9, e.data.length - 9));
if (result.length !== 0) {
postMessage("message " + result);
}
} else if (e.data.match("^search") == "search") {
var level = e.data.substr(7,e.data.length-7).split(",");
g_timeout = parseInt(level[0], 10);
g_maxply = parseInt(level[1], 10);
Search(FinishMoveLocalTesting, g_maxply, FinishPlyCallback);
} else if (e.data == "analyze") {
g_timeout = 99999999999;
Search(null, g_maxply, FinishPlyCallback);
} else {
MakeMove(GetMoveFromString(e.data));
}
};
function debug(msg) {
if (g_debug) {
if(worker) {
postMessage("console: "+msg);
} else {
console.log(msg);
}
}
}
|
// StartView.js
// -------
define(["jquery", "backbone", "mustache", "text!templates/trulyAnswer/Start.html", "text!templates/trulyAnswer/StartSuccess.html", "models/Question", "Utils", "views/trulyAnswer/Configs"],
function ($, Backbone, Mustache, template, successTemplate, Question, Utils, Configs) {
var StartView = Backbone.View.extend({
// The DOM Element associated with this view
el: "#stage",
// View constructor
initialize: function (options) {
this.user = options.user;
this.listenTo(this, "render", this.postRender);
if (this.user.get("isFetchSuccess") === true) {
this.render();
} else {
this.listenTo(this.user, "onFetchSuccess", this.render);
}
},
// View Event Handlers
events: {
"click #confirmAndAsk": "shareOnCircle",
"click #shareOnCircle": "showShareOverlay",
"click #validThrough": "onFocusInput",
"blur #validThrough": "onBlurInput"
},
// Renders the view's template to the UI
render: function () {
this.beforeRender();
// Dynamically updates the UI with the view's template
this.$el.html(Mustache.render(template, this.user.toJSON()));
this.trigger("render");
// Maintains chainability
return this;
},
postRender: function () {
var titleText = Utils.getRandomItemFromArray(Configs.titleTexts);
var descText = Utils.getRandomItemFromArray(Configs.descTexts);
shareInfo.title = titleText.titleBefore + this.user.get("userName") + titleText.titleAfter;
shareInfo.desc = descText.descBefore + "3" + descText.descAfter;
shareInfo.shareTimelineTitle = shareInfo.title + shareInfo.desc;
shareInfo.link = window.location.href;
shareInfo.img_url = this.user.get("headImageUrl");
_hmt.push(['_trackPageview', "/start"]);
},
beforeRender: function() {
var sex = this.user.get("sex");
var subscribe = this.user.get("subscribe");
if ( sex === 1 ) {
this.user.set("isMale", true);
} else {
this.user.set("isMale", false);
}
if ( subscribe === 0 ) {
this.user.set("isSubscribe", false);
} else {
this.user.set("isSubscribe", true);
}
},
showSuccessInfo: function() {
var titleText = Utils.getRandomItemFromArray(Configs.titleTexts);
var descText = Utils.getRandomItemFromArray(Configs.descTexts);
shareInfo.title = titleText.titleBefore + this.user.get("userName") + titleText.titleAfter;
shareInfo.desc = descText.descBefore + this.question.get("expiresIn") + descText.descAfter;
shareInfo.shareTimelineTitle = shareInfo.title + shareInfo.desc;
shareInfo.link = window.location.href;
shareInfo.img_url = this.user.get("headImageUrl");
this.$el.find("#startContent").html(Mustache.render(successTemplate, this.user.toJSON()));
},
showShareOverlay: function () {
var self = this;
$('#stage').addClass("blur");
$('.overlay').fadeIn();
$('.overlay').click(function (e) {
$('.overlay').hide();
$('#stage').removeClass("blur");
window.location.reload();
});
},
validateInput: function() {
var input = parseInt(this.$el.find("#validThrough").val());
if ( input && !isNaN(input) && input > 0 && input < 49) {
return true;
} else {
return false;
}
},
onFocusInput: function(ev) {
this.$el.find(".form-group").removeClass("has-error");
this.$el.find(".control-label").text("我承诺在以下时间内,朋友问我什么我都回答");
},
onBlurInput: function(ev) {
},
startActivity: function() {
var self = this;
this.question = new Question({ "questionTypeId": 1, "userId": this.user.get("userId"), "questionText": "有问必答" });
var expiresIn = $("#validThrough").val();
this.question.set("expiresIn", expiresIn);
this.question.addQuestion({
success: function (data) {
self.shareCode = data.shareCode;
Backbone.history.navigate("trulyAnswer/reply/" + data.shareCode, { trigger: true, replace: true });
//self.showShareOverlay();
//self.showSuccessInfo();
},
error: function (msg) {
alert(msg);
}
});
},
shareOnCircle: function (ev) {
if ( !$(ev.currentTarget).hasClass("disabled") ) {
$(ev.currentTarget).addClass("disabled").text("正在创建...");
var self = this;
if ( this.validateInput() ) {
this.startActivity();
} else {
this.$el.find(".form-group").addClass("has-error");
this.$el.find(".control-label").text("请输入1-48以内的数字");
$("#confirmAndAsk").removeClass("disabled").text("现在开始有问必答");
}
}
}
});
// Returns the View class
return StartView;
}
);
|
var _ = require('lodash');
var expect = require('chai').expect;
describe('date Mode', function () {
describe('now', function () {
it('', function () {
console.log(_.now());
})
})
})
|
/**
* CMD: grunt hint
*
* ---------------------------------------------------------------
*
* Runs jshint, js coding stands and js validate to ensure general
* code integrity
*
*/
module.exports = function(grunt) {
grunt.registerTask('hint', [
'jshint:src',
'jscs:src'
]);
};
|
'use strict';
var deoopfy = require('deoopfy');
/**
* Returns the available model names for a mongoose Connection.
*
* @param {mongoose.Connection} connection
* @return {Array.<String>} model_names.
*/
exports.getModelNames = function getModelNames(connection) {
if(connection === connection.base.connection) {
return connection.modelNames().concat(connection.base.modelNames());
}
else {
return connection.modelNames();
}
};
/**
* Maps a function over an array.
*
* @param {Function} fn The mapping function
* @param {Array} arr The array to map over.
* @param {Mixed} [ctx] The context object
* @return {Array} ret The mapping result.
*/
exports.map = function(fn, arr, ctx) {
var ret = [],
len = arr.length,
cb = ctx && ('prototype' in fn) ? fn.bind(ctx) : fn;
for(var i = 0; i < len; i++) {
var value = arr[i];
ret.push(cb(value, i, arr));
}
return ret;
};
/**
* Maps a function over an object's properties, returning an object with the
* same keys, but the function's return values.
*
* @param {Function} fn The mapping function.
* @param {Object} obj The object to map over.
* @param {Mixed} [ctx] The context object
* @return {Object} ret The mapping result.
*/
exports.mapValues = function mapValues(fn, obj, ctx) {
var ret = {},
keys = Object.keys(obj),
len = keys.length,
cb = ctx && ('prototype' in fn) ? fn.bind(ctx) : fn;
for(var i = 0; i < len; i++) {
var key = keys[i],
value = obj[key];
ret[key] = cb(value, key, obj);
}
return ret;
};
/**
* Filters an array, based on a predicate function, which should take value,
* index and array as its arguments, and return a Boolean. If the predicate
* returns true, the item is kept, else, it's discarted from the return array.
*
* @param {Function} fn A predicate function.
* @param {Array} arr The array to filter.
* @param {Mixed} [ctx] The context object
* @return {Array} ret The filtered array.
*/
exports.filter = function(fn, arr, ctx) {
var ret = [],
len = arr.length,
cb = ctx && ('prototype' in fn) ? fn.bind(ctx) : fn;
for(var i = 0; i < len; i++) {
var value = arr[i];
if(cb(value, i, arr)) ret.push(value);
}
return ret;
};
var sliceF = deoopfy(Array.prototype.slice);
/**
* Composes two functions into one.
*
* @param {Function} f The outer function in the composition.
* @param {Function} g The inner function in the composition.
* @return {Function} fog The composed function f over g.
*
* @example
* function f(x) { return x + 10; } // f(x) = x + 10
* function g(x) { return x / 2; } // g(x) = x / 2
*
* var fog = compose(f, g); // fog(x) = f(g(x)) = (x/2) + 10
* fog(8) // => 14
*/
exports.compose = function(f, g) {
return function() {
var y = g.apply(this, arguments);
return f.call(this, y);
};
};
/**
* Partially applies a function to a set of arguments.
*
* @param {Function} fn The function to bind args to.
* @param {..Mixed} args A set of arguments.
* @return {Function} ret The partially applied function.
*/
exports.partial = function(fn, args) {
if(!Array.isArray(args)) args = sliceF(arguments, 1);
var len = args.length;
return function() {
var allargs = sliceF(arguments);
for(var i = 0; i < len; i++) allargs.unshift(args[i]);
return fn.apply(this, allargs);
};
};
|
var mod = angular.module('restaurant', ['ngResource', 'ngRoute']);
mod.factory('Restaurant', ['$resource',
function($resource) {
return $resource('/api/restaurants/restaurants/:slug', {}, {
query: {
method: 'GET',
isArray: true,
}
});
}
]);
mod.factory('Rating', ['$resource',
function($resource) {
return $resource('/api/restaurants/ratings/:id', {}, {
'create': {
method: 'POST',
}
});
}
]);
mod.controller('SearchCtrl', ['$scope', '$http', '$location', function($scope, $http, $location){
$scope.getRestaurants = function(val) {
return $http.get('/api/restaurants/restaurantsearch', {
params: {
name: val
}
}).then(function(response){
// maybe we can send the full array of json items then pull the name property out in the template
return response.data;
/*
return response.data.map(function(item){
return item.name;
});*/
});
};
$scope.onSelect = function($item, $model, $label) {
$location.path("/restaurant/"+$item.slug)
console.log($item);
}
}]);
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
release: ["public/**"]
},
assemble: {
release: {
options: {
layoutdir: 'www/templates/layouts',
partials: ['www/templates/includes/**/*.hbs']
},
files: [{
expand: true,
flatten: true,
cwd: './',
src: ['www/templates/pages/**/*.hbs'],
dest: 'public'
}]
}
},
concat: {
options: {
separator: "\n"
},
admin: {
src: [
'bower_components/bloxui/dist/js/bloxui.js',
'www/js/admin.js',
'www/js/admin/*.js',
'www/js/views/*.js',
'www/js/controllers/*.js'
],
dest: 'public/js/admin.js'
},
clientbase: {
src: [
'www/js/util.js',
'www/js/honeybadger.js',
'www/js/honeybadger/*.js'
],
dest: 'public/js/honeybadger.js'
},
css: {
src: [
'bower_components/bloxui/dist/css/bloxui.css',
'www/css/**.css',
],
dest: 'public/css/admin.css'
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
beautify: false
},
build: {
files: {
'public/js/honeybadger-min.js': ['public/js/honeybadger.js'],
'public/js/admin-min.js': ['public/js/admin.js']
}
}
},
cssmin: {
combine: {
files: [{
expand: true,
cwd: './',
src: ['www/css/evdp.css'],
dest: 'public',
ext: '-min.css'
}]
}
},
copy: {
release: {
files: [{
expand: true,
cwd: 'bower_components/bloxui/dist/css/fonts',
src: ['./**'],
dest: 'public/css/fonts'
}]
}
},
watch: {
js: {
files: ['www/js/**/*.js'],
tasks: ['newer:concat', 'newer:uglify'],
options: {
livereload: true
}
},
css: {
files: ['www/css/**/*.css'],
tasks: ['newer:concat:css', 'newer:cssmin'],
options: {
livereload: true
}
},
html: {
files: ['www/**/*.hbs'],
tasks: ['newer:assemble'],
options: {
livereload: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-newer');
grunt.loadNpmTasks('assemble');
// Default task(s).
grunt.registerTask('default', ['copy', 'concat', 'newer:uglify', 'newer:cssmin', 'newer:assemble']);
grunt.registerTask('release', ['clean', 'copy', 'concat', 'uglify', 'cssmin', 'assemble']);
};
|
import { FETCH_QUESTION_SUCCESS } from './actionTypes'
function fetchQusetionSuccess(questionitem) {
return {
type: FETCH_QUESTION_SUCCESS,
questionitem: questionitem
}
}
function fetchQuestion(questionId) {
return dispatch => {
return fetch('/api/selectquestion', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
questionId: questionId,
token: sessionStorage.token
})
})
.then(response => response.json())
.then(questionitem => dispatch(fetchQusetionSuccess(questionitem)))
}
}
export function fetchQuestionIfNeeded(questionId) {
return (dispatch, getState) => {
return dispatch(fetchQuestion(questionId))
}
}
|
'use strict';
var CAPABILITY_RESPONSE = 0x6C;
module.exports = function () {
return {
cmd: CAPABILITY_RESPONSE,
handle: function (cmd, data, board) {
var supportedModes = 0;
function pushModes(modesArray, mode) {
if (supportedModes & (1 << board.MODES[mode])) {
modesArray.push(board.MODES[mode]);
}
}
// Only create pins if none have been previously created on the instance.
if (!board.pins.length) {
for (var i = 0, n = 0; i < data.length; i++) {
if (data[i] === 127) {
var modesArray = [];
Object.keys(board.MODES).forEach(pushModes.bind(null, modesArray));
board.pins.push({
supportedModes: modesArray,
mode: board.MODES.UNKNOWN,
value: 0,
report: 1
});
supportedModes = 0;
n = 0;
continue;
}
if (n === 0) {
supportedModes |= (1 << data[i]);
}
n ^= 1;
}
}
board.emit("capability-query");
}
}
};
|
/* The ViewManager takes care of detecting whether the user uses the old or
* new Compose in Gmail. Once it finds out, it takes care of instantiating
* the appropriate view (regularView or updatedView).
*/
var ViewManager = function () {
if (arguments.callee.singleton_instance) {
return arguments.callee.singleton_instance;
}
arguments.callee.singleton_instance = new (function () {
var observerCallbacks = [];
var cloudy_view;
var mytimer;
var enabled;
this.addViewObserver = function (fn) {
observerCallbacks.push(fn);
}
this.getView = function(){
return cloudy_view;
}
/* Look for an element named "subject". If found, then a Compose window
* must be open. If a DOM element with name "from" exists, and it is of
* type "input", then we must be encountering the new Gmail Compose.
* Otherwise, we're dealing with the old one.
*/
var checkCompose = function() {
// #selector
if (enabled && document.getElementsByName("subject").length) {
if (!document.getElementsByClassName("I5").length) {
// Gmail's old interface
cloudy_view = new RegularView();
} else {
// Gmail's new interface
cloudy_view = new UpdatedView();
}
for (var i = 0; i < observerCallbacks.length; i++) {
cloudy_view.addObserver(observerCallbacks[i]);
}
clearInterval(mytimer);
enabled = false;
}
}
var loadSocialButtons = function() {
// Load Tweet button
(!function(d,s,id) {
console.log("loading twitter");
var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)) {
js=d.createElement(s);
js.id=id;
js.async = true;
js.src="https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);
}
} (document,"script","twitter-wjs"));
// Load Google +1 button
(function(d, s, id) {
console.log("loading G+");
var po = d.createElement(s);
if (d.getElementById(id)) return;
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = d.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})(document, 'script', 'googleplus-jssdk');
// Load Pinterest "Pin it" button
(function(d, s, id) {
console.log("loading Pinterest");
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "https://assets.pinterest.com/js/pinit.js";
js.async = true;
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'pinterest-jssdk'));
}
var init = function() {
// check for promo bubble, display it if loaded
var notification_bubble = $jQcl("#cloudy_bubble");
if (notification_bubble && notification_bubble.length > 0) {
console.log("Showing notification");
if (notification_bubble.hasClass("cloudy_social")) {
loadSocialButtons();
}
/* why does this not work? */
//notification_bubble.show();
notification_bubble.css("display", "block");
notification_bubble.delay(1500).fadeTo(1000, 1,
function() {
var cloudy_events =
document.getElementById("cloudy_events");
if (cloudy_events) {
var e = document.createEvent("Events");
e.initEvent("cloudy_notificationDisplayed",
false, true);
cloudy_events.dispatchEvent(e);
}
});
$jQcl("#cloudy_bubble_close").click(function(){
notification_bubble.fadeTo(600, 0, function(){
notification_bubble.hide();
//notification_bubble.parentNode.removeChild(
// notification_bubble);
});
});
}
// start timer
mytimer = setInterval(checkCompose, 500);
enabled = true;
}
init.call(this);
return this;
})();
return arguments.callee.singleton_instance;
}
|
import * as React from 'react';
import {findDOMNode} from 'react-dom';
import {render} from '../TestUtils';
import {Simulate} from 'react-dom/test-utils';
import Immutable from 'immutable';
import List from './List';
import {defaultOverscanIndicesGetter} from '../Grid';
describe('List', () => {
const array = [];
for (var i = 0; i < 100; i++) {
array.push(`Name ${i}`);
}
const names = Immutable.fromJS(array);
// Override default behavior of overscanning by at least 1 (for accessibility)
// Because it makes for simple tests below
function overscanIndicesGetter({startIndex, stopIndex}) {
return {
overscanStartIndex: startIndex,
overscanStopIndex: stopIndex,
};
}
function getMarkup(props = {}) {
function rowRenderer({index, key, style}) {
return (
<div className="listItem" key={key} style={style}>
{names.get(index)}
</div>
);
}
return (
<List
height={100}
overscanIndicesGetter={overscanIndicesGetter}
overscanRowCount={0}
rowHeight={10}
rowCount={names.size}
rowRenderer={rowRenderer}
width={100}
{...props}
/>
);
}
describe('number of rendered children', () => {
it('should render enough children to fill the view', () => {
const rendered = findDOMNode(render(getMarkup()));
expect(rendered.querySelectorAll('.listItem').length).toEqual(10);
});
it('should not render more children than available if the list is not filled', () => {
const rendered = findDOMNode(render(getMarkup({rowCount: 5})));
expect(rendered.querySelectorAll('.listItem').length).toEqual(5);
});
});
describe('scrollToPosition', () => {
it('should scroll to the top', () => {
const instance = render(
getMarkup({
rowHeight: 10,
}),
);
instance.scrollToPosition(100);
const rendered = findDOMNode(instance);
expect(rendered.textContent).toContain('Name 10');
expect(rendered.textContent).toContain('Name 19');
});
});
/** Tests scrolling via initial props */
describe('scrollToIndex', () => {
it('should scroll to the top', () => {
const rendered = findDOMNode(render(getMarkup({scrollToIndex: 0})));
expect(rendered.textContent).toContain('Name 0');
});
it('should scroll down to the middle', () => {
const rendered = findDOMNode(render(getMarkup({scrollToIndex: 49})));
// 100 items * 10 item height = 1,000 total item height
// 10 items can be visible at a time and :scrollTop is initially 0,
// So the minimum amount of scrolling leaves the 50th item at the bottom (just scrolled into view).
expect(rendered.textContent).toContain('Name 49');
});
it('should scroll to the bottom', () => {
const rendered = findDOMNode(render(getMarkup({scrollToIndex: 99})));
// 100 height - 10 header = 90 available scroll space.
// 100 items * 10 item height = 1,000 total item height
// Target height for the last item then is 1000 - 90
expect(rendered.textContent).toContain('Name 99');
});
it('should scroll to the correct position for :scrollToAlignment "start"', () => {
const rendered = findDOMNode(
render(
getMarkup({
scrollToAlignment: 'start',
scrollToIndex: 49,
}),
),
);
// 100 items * 10 item height = 1,000 total item height; 10 items can be visible at a time.
expect(rendered.textContent).toContain('Name 49');
expect(rendered.textContent).toContain('Name 58');
});
it('should scroll to the correct position for :scrollToAlignment "end"', () => {
render(
getMarkup({
scrollToIndex: 99,
}),
);
const rendered = findDOMNode(
render(
getMarkup({
scrollToAlignment: 'end',
scrollToIndex: 49,
}),
),
);
// 100 items * 10 item height = 1,000 total item height; 10 items can be visible at a time.
expect(rendered.textContent).toContain('Name 40');
expect(rendered.textContent).toContain('Name 49');
});
it('should scroll to the correct position for :scrollToAlignment "center"', () => {
render(
getMarkup({
scrollToIndex: 99,
}),
);
const rendered = findDOMNode(
render(
getMarkup({
scrollToAlignment: 'center',
scrollToIndex: 49,
}),
),
);
// 100 items * 10 item height = 1,000 total item height; 11 items can be visible at a time (the first and last item are only partially visible)
expect(rendered.textContent).toContain('Name 44');
expect(rendered.textContent).toContain('Name 54');
});
});
describe('property updates', () => {
it('should update :scrollToIndex position when :rowHeight changes', () => {
let rendered = findDOMNode(render(getMarkup({scrollToIndex: 50})));
expect(rendered.textContent).toContain('Name 50');
// Making rows taller pushes name off/beyond the scrolled area
rendered = findDOMNode(
render(getMarkup({scrollToIndex: 50, rowHeight: 20})),
);
expect(rendered.textContent).toContain('Name 50');
});
it('should update :scrollToIndex position when :height changes', () => {
let rendered = findDOMNode(render(getMarkup({scrollToIndex: 50})));
expect(rendered.textContent).toContain('Name 50');
// Making the list shorter leaves only room for 1 item
rendered = findDOMNode(
render(getMarkup({scrollToIndex: 50, height: 20})),
);
expect(rendered.textContent).toContain('Name 50');
});
it('should update :scrollToIndex position when :scrollToIndex changes', () => {
let rendered = findDOMNode(render(getMarkup()));
expect(rendered.textContent).not.toContain('Name 50');
rendered = findDOMNode(render(getMarkup({scrollToIndex: 50})));
expect(rendered.textContent).toContain('Name 50');
});
it('should update scroll position if size shrinks smaller than the current scroll', () => {
findDOMNode(render(getMarkup({scrollToIndex: 500})));
findDOMNode(render(getMarkup()));
const rendered = findDOMNode(
render(getMarkup({scrollToIndex: 500, rowCount: 10})),
);
expect(rendered.textContent).toContain('Name 9');
});
});
describe('noRowsRenderer', () => {
it('should call :noRowsRenderer if :rowCount is 0', () => {
let rendered = findDOMNode(
render(
getMarkup({
noRowsRenderer: () => <div>No rows!</div>,
rowCount: 0,
}),
),
);
expect(rendered.textContent).toEqual('No rows!');
});
it('should render an empty body if :rowCount is 0 and there is no :noRowsRenderer', () => {
let rendered = findDOMNode(
render(
getMarkup({
rowCount: 0,
}),
),
);
expect(rendered.textContent).toEqual('');
});
});
describe('onRowsRendered', () => {
it('should call :onRowsRendered if at least one row is rendered', () => {
let startIndex, stopIndex;
render(
getMarkup({
onRowsRendered: params => ({startIndex, stopIndex} = params),
}),
);
expect(startIndex).toEqual(0);
expect(stopIndex).toEqual(9);
});
it('should not call :onRowsRendered unless the start or stop indices have changed', () => {
let numCalls = 0;
let startIndex;
let stopIndex;
const onRowsRendered = params => {
startIndex = params.startIndex;
stopIndex = params.stopIndex;
numCalls++;
};
findDOMNode(render(getMarkup({onRowsRendered})));
expect(numCalls).toEqual(1);
expect(startIndex).toEqual(0);
expect(stopIndex).toEqual(9);
findDOMNode(render(getMarkup({onRowsRendered})));
expect(numCalls).toEqual(1);
expect(startIndex).toEqual(0);
expect(stopIndex).toEqual(9);
});
it('should call :onRowsRendered if the start or stop indices have changed', () => {
let numCalls = 0;
let startIndex;
let stopIndex;
const onRowsRendered = params => {
startIndex = params.startIndex;
stopIndex = params.stopIndex;
numCalls++;
};
findDOMNode(render(getMarkup({onRowsRendered})));
expect(numCalls).toEqual(1);
expect(startIndex).toEqual(0);
expect(stopIndex).toEqual(9);
findDOMNode(
render(
getMarkup({
height: 50,
onRowsRendered,
}),
),
);
expect(numCalls).toEqual(2);
expect(startIndex).toEqual(0);
expect(stopIndex).toEqual(4);
});
it('should not call :onRowsRendered if no rows are rendered', () => {
let startIndex, stopIndex;
render(
getMarkup({
height: 0,
onRowsRendered: params => ({startIndex, stopIndex} = params),
}),
);
expect(startIndex).toEqual(undefined);
expect(stopIndex).toEqual(undefined);
});
});
describe(':scrollTop property', () => {
it('should render correctly when an initial :scrollTop property is specified', () => {
let startIndex, stopIndex;
render(
getMarkup({
onRowsRendered: params => ({startIndex, stopIndex} = params),
scrollTop: 100,
}),
);
expect(startIndex).toEqual(10);
expect(stopIndex).toEqual(19);
});
it('should render correctly when :scrollTop property is updated', () => {
let startIndex, stopIndex;
findDOMNode(
render(
getMarkup({
onRowsRendered: params => ({startIndex, stopIndex} = params),
}),
),
);
expect(startIndex).toEqual(0);
expect(stopIndex).toEqual(9);
findDOMNode(
render(
getMarkup({
onRowsRendered: params => ({startIndex, stopIndex} = params),
scrollTop: 100,
}),
),
);
expect(startIndex).toEqual(10);
expect(stopIndex).toEqual(19);
});
});
describe('styles, classNames, and ids', () => {
it('should use the expected global CSS classNames', () => {
const node = findDOMNode(render(getMarkup()));
expect(node.className).toContain('ReactVirtualized__List');
});
it('should use a custom :className if specified', () => {
const node = findDOMNode(render(getMarkup({className: 'foo'})));
expect(node.className).toContain('foo');
});
it('should use a custom :id if specified', () => {
const node = findDOMNode(render(getMarkup({id: 'bar'})));
expect(node.getAttribute('id')).toEqual('bar');
});
it('should use a custom :style if specified', () => {
const style = {backgroundColor: 'red'};
const rendered = findDOMNode(render(getMarkup({style})));
expect(rendered.style.backgroundColor).toEqual('red');
});
it('should set the width of a row to be 100% by default', () => {
const rendered = findDOMNode(render(getMarkup()));
const cell = rendered.querySelector('.listItem');
expect(cell.style.width).toEqual('100%');
});
});
describe('overscanRowCount', () => {
it('should not overscan by default', () => {
const mock = jest.fn();
mock.mockImplementation(overscanIndicesGetter);
render(
getMarkup({
overscanIndicesGetter: mock,
}),
);
expect(mock.mock.calls[0][0].overscanCellsCount).toEqual(0);
expect(mock.mock.calls[1][0].overscanCellsCount).toEqual(0);
});
it('should overscan the specified amount', () => {
const mock = jest.fn();
mock.mockImplementation(overscanIndicesGetter);
render(
getMarkup({
overscanIndicesGetter: mock,
overscanRowCount: 10,
}),
);
expect(mock.mock.calls[0][0].overscanCellsCount).toEqual(0);
expect(mock.mock.calls[1][0].overscanCellsCount).toEqual(10);
});
});
describe('onScroll', () => {
it('should trigger callback when component initially mounts', () => {
const onScrollCalls = [];
render(
getMarkup({
onScroll: params => onScrollCalls.push(params),
}),
);
expect(onScrollCalls).toEqual([
{
clientHeight: 100,
scrollHeight: 1000,
scrollTop: 0,
},
]);
});
it('should trigger callback when component scrolls', () => {
const onScrollCalls = [];
const rendered = render(
getMarkup({
onScroll: params => onScrollCalls.push(params),
}),
);
const target = {
scrollLeft: 0,
scrollTop: 100,
};
rendered.Grid._scrollingContainer = target; // HACK to work around _onScroll target check
Simulate.scroll(findDOMNode(rendered), {target});
expect(onScrollCalls[onScrollCalls.length - 1]).toEqual({
clientHeight: 100,
scrollHeight: 1000,
scrollTop: 100,
});
});
});
describe('measureAllRows', () => {
it('should measure any unmeasured rows', () => {
const rendered = render(
getMarkup({
estimatedRowSize: 15,
height: 0,
rowCount: 10,
rowHeight: () => 20,
width: 0,
}),
);
expect(
rendered.Grid.state.instanceProps.rowSizeAndPositionManager.getTotalSize(),
).toEqual(150);
rendered.measureAllRows();
expect(
rendered.Grid.state.instanceProps.rowSizeAndPositionManager.getTotalSize(),
).toEqual(200);
});
});
describe('recomputeRowHeights', () => {
it('should recompute row heights and other values when called', () => {
const indices = [];
const rowHeight = ({index}) => {
indices.push(index);
return 10;
};
const component = render(
getMarkup({
rowHeight,
rowCount: 50,
}),
);
indices.splice(0);
component.recomputeRowHeights();
// Only the rows required to fill the current viewport will be rendered
expect(indices[0]).toEqual(0);
expect(indices[indices.length - 1]).toEqual(9);
indices.splice(0);
component.recomputeRowHeights(4);
expect(indices[0]).toEqual(4);
expect(indices[indices.length - 1]).toEqual(9);
});
});
describe('forceUpdateGrid', () => {
it('should refresh inner Grid content when called', () => {
let marker = 'a';
function rowRenderer({index, key, style}) {
return (
<div key={key} style={style}>
{index}
{marker}
</div>
);
}
const component = render(getMarkup({rowRenderer}));
const node = findDOMNode(component);
expect(node.textContent).toContain('1a');
marker = 'b';
component.forceUpdateGrid();
expect(node.textContent).toContain('1b');
});
});
describe('tabIndex', () => {
it('should be focusable by default', () => {
const rendered = findDOMNode(render(getMarkup()));
expect(rendered.tabIndex).toEqual(0);
});
it('should allow tabIndex to be overridden', () => {
const rendered = findDOMNode(
render(
getMarkup({
tabIndex: -1,
}),
),
);
expect(rendered.tabIndex).toEqual(-1);
});
});
it('should pass the cellRenderer an :isVisible flag', () => {
const rowRendererCalls = [];
function rowRenderer(props) {
rowRendererCalls.push(props);
return null;
}
findDOMNode(
render(
getMarkup({
height: 50,
overscanIndicesGetter: defaultOverscanIndicesGetter,
overscanRowCount: 1,
rowHeight: 50,
rowRenderer,
}),
),
);
expect(rowRendererCalls[0].isVisible).toEqual(true);
expect(rowRendererCalls[1].isVisible).toEqual(false);
});
it('should relay the Grid :parent param to the :rowRenderer', () => {
const rowRenderer = jest.fn().mockReturnValue(null);
findDOMNode(render(getMarkup({rowRenderer})));
expect(rowRenderer.mock.calls[0][0].parent).not.toBeUndefined();
});
describe('pure', () => {
it('should not re-render unless props have changed', () => {
let rowRendererCalled = false;
function rowRenderer({index, key, style}) {
rowRendererCalled = true;
return (
<div key={key} style={style}>
{index}
</div>
);
}
const markup = getMarkup({rowRenderer});
render(markup);
expect(rowRendererCalled).toEqual(true);
rowRendererCalled = false;
render(markup);
expect(rowRendererCalled).toEqual(false);
});
});
it('should set the width of the single-column inner Grid to auto', () => {
const rendered = findDOMNode(render(getMarkup()));
expect(
rendered.querySelector('.ReactVirtualized__Grid__innerScrollContainer')
.style.width,
).toEqual('auto');
});
});
|
import {createSelector} from 'reselect';
import Fuse from 'fuse.js';
import _ from 'lodash';
const options = {
keys: ['name', 'address'],
threshold: 0.45
};
const f = new Fuse([], options);
const getQuery = (state) => _.get(state.retailersView, 'query', '');
const getRetailers = (state) => _.map(_.get(state, 'retailers.allIds', []), id => state.retailers.byId[id]);
export const getVisibleRetailers = createSelector([getQuery, getRetailers], (query, retailers) => {
return _.sortBy(searchProducts(query, retailers), 'id');
});
export const getAllRetailers = createSelector([getQuery, getRetailers], (query, retailers) => {
return _.sortBy(retailers, 'id');
});
function searchProducts(query, retailers) {
f.set(retailers);
if (query && query.length < 32) {
return f.search(query);
} else {
return retailers;
}
}
|
/*
* This file is part of the Fxp package.
*
* (c) François Pluchino <francois.pluchino@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import $ from 'jquery';
import {checkContent} from './content';
/**
* Display the floating label.
*
* @param {jQuery.Event|Event} event
*/
export function onFocusOut(event) {
checkContent($(event.currentTarget));
}
|
(function() {
angular
.module('autoTracker')
.controller('serviceCtrl', serviceCtrl);
function serviceCtrl() {
var vm = this;
}
})();
|
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('..');
var dirname = __dirname.replace(/\\/g,"/");
} else {
dirname = '.';
};
//if(typeof exports === 'object' && false) {
describe('Test 168a - read XLSX', function() {
this.timeout(10000);
it("1. Read XLSX file", function(done) {
var res = alasql('select * from xlsx("'+dirname+'/test168.xlsx",{headers:false})',[],function(res){
assert(res.length == 6);
// console.log(res);
done();
});
});
it("2. Read XLSX file with Headers", function(done) {
var res = alasql('select column City from xlsx("'+dirname+'/test168.xlsx",{headers:true})\
where Population > 10000000 order by City',[],function(res){
assert.deepEqual(res,["Mexico","Moscow"])
done();
});
});
it("3. Read XLSX file with Headers and range", function(done) {
var res = alasql('select column City from xlsx("'+dirname+'/test168.xlsx",{headers:true, range:"A1:B3"})\
where Population > 10000000 order by City',[],function(res){
// console.log(res);
assert.deepEqual(res,["Moscow"])
done();
});
});
it("4. Read XLSX file with Headers and sheet", function(done) {
var res = alasql('select column City from xlsx("'+dirname+'/test168.xlsx",{headers:true, sheetid: "USA", range:"A1:B6"})\
where Population > 10000000 order by City',[],function(res){
// console.log(res);
assert.deepEqual(res,["New York"])
done();
});
});
});
describe('Test 168b - read XLS', function() {
this.timeout(9000);
it("1. Read XLS file", function(done) {
var res = alasql('select * from xls("'+dirname+'/test168.xls",{headers:false})',[],function(res){
assert(res.length == 6);
// console.log(res);
done();
});
});
it("2. Read XLS file with Headers", function(done) {
var res = alasql('select column City from xls("'+dirname+'/test168.xls",{headers:true})\
where Population > 10000000 order by City',[],function(res){
assert.deepEqual(res,["Mexico","Moscow"])
done();
});
});
it("3. Read XLS file with Headers and range", function(done) {
var res = alasql('select column City from xls("'+dirname+'/test168.xls",{headers:true, range:"A1:B3"})\
where Population > 10000000 order by City',[],function(res){
// console.log(res);
assert.deepEqual(res,["Moscow"])
done();
});
});
it("4. Read XLS file with Headers and sheet", function(done) {
var res = alasql('select column City from xls("'+dirname+'/test168.xls",{headers:true, sheetid: "USA", range:"A1:B6"})\
where Population > 10000000 order by City',[],function(res){
// console.log(res);
assert.deepEqual(res,["New York"])
done();
});
});
});
//}
|
const path = require("path");
// `@babel/preset-env: modules: false` is leaves `import`, that don't work on nodejs
require("@babel/register")({
babelrc: false,
extensions: [".js", ".jsx", ".ts", ".tsx"],
presets: [
[
"@babel/preset-env",
{
"targets": {
"node": true,
},
}
],
"@babel/typescript",
"@babel/preset-react"
],
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-destructuring",
"@babel/plugin-proposal-object-rest-spread",
["module-resolver", {
"alias": {
"^@skbkontur/react-icons/(.+)": path.join(__dirname, "./emptyModule"),
}
}]
],
});
require("creevey/lib/cli");
|
var events = require("bloody-events")
var asap = require("asap")
var expando = "dispatch" + String(Math.random())
function each(list, fn, thisValue){
var index = -1
var length = list.length
while(++index < length) {
fn.call(thisValue, list[index], index, list)
}
}
function indexOfCallback(array, value) {
var index = -1
var length = array.length
while(++index < length) {
if(array[index].cb === value) {
return index
}
}
return -1
}
function createCallback(options){
var cb = options.cb
var currentMutation = options.currentMutation
var additions = options.additions
var deletions = options.deletions
return function(item){
currentMutation.push(item)
asap(function(){
var item
if(!additions.length && !deletions.length) {
return
}
cb({
additions : additions.splice(0, additions.length),
deletions : deletions.splice(0, deletions.length),
result : options.array
})
})
}
}
function addCb(item){
this.emit("add", item)
this.emit("add" + expando, item)
this.emit("change")
}
function removeCb(item){
this.emit("remove", item)
this.emit("remove" + expando, item)
this.emit("change")
}
function accessor(methodName){
return function(){
return this.list[methodName].apply(this.list, arguments)
}
}
module.exports = events.extend({
constructor : function(list){
events.constructor.call(this)
this.list = list || []
this._dispatchers = []
},
destructor : function(){
events.destructor.call(this)
this._dispatchers.length = 0
},
push : function(){
var result = this.list.push.apply(this.list, arguments)
each(arguments, addCb, this)
return result
},
splice : function(index, length){
var removed = this.list.splice.apply(this.list, arguments)
var added = [].slice.call(arguments, 2)
each(removed, removeCb, this)
each(added, addCb, this)
return removed
},
sort : function(){
var result = this.list.sort.apply(this.list, arguments)
this.emit("sort")
return result
},
reverse : function(){
var result = this.list.reverse.apply(this.list, arguments)
this.emit("reverse")
return result
},
pop : function(){
var removed = this.list.pop.apply(this.list, arguments)
removeCb.call(this, removed)
return removed
},
shift : function(){
var removed = this.list.shift.apply(this.list, arguments)
removeCb.call(this, removed)
return removed
},
unshift : function(){
var result = this.list.unshift.apply(this.list, arguments)
each(arguments, addCb, this)
return result
},
length : function(length){
var previousLength = this.list.length
var removed
if(typeof length == "number") {
if(previousLength > length) {
removed = this.list.slice(length, previousLength)
}
this.list.length = length
if(removed) {
each(removed, removeCb, this)
}
}
return this.list.length
},
reduceRight : accessor("reduceRight"),
toLocaleString : accessor("toLocaleString"),
some : accessor("some"),
forEach : accessor("forEach"),
map : accessor("map"),
lastIndexOf : accessor("lastIndexOf"),
toString : accessor("toString"),
join : accessor("join"),
reduce : accessor("reduce"),
slice : accessor("slice"),
filter : accessor("filter"),
every : accessor("every"),
dispatch : function(cb){
var additions = []
var deletions = []
if(indexOfCallback(this._dispatchers, cb) != -1) {
return
}
var callbacks = {
cb : cb,
add : createCallback({
cb : cb,
currentMutation : additions,
additions : additions,
deletions : deletions,
array : this.list
}),
remove : createCallback({
cb : cb,
currentMutation : deletions,
additions : additions,
deletions : deletions,
array : this.list
})
}
this._dispatchers.push(callbacks)
this.on("add" + expando, callbacks.add)
this.on("remove" + expando, callbacks.remove)
},
stopDispatch : function(cb){
var index
if(cb == null) {
this.off("add" + expando)
this.off("remove" + expando)
return
}
index = indexOfCallback(this._dispatchers, cb)
if(index == -1) {
return
}
var callback = this._dispatchers.splice(index, 1)[0]
this.off("add" + expando, callback.add)
this.off("remove" + expando, callback.remove)
},
valueOf : function(){
return this.list
}
})
|
(function() {
'use strict';
angular.module('jverhaeghePortfolio.layout', []);
})();
|
"use strict";
var Github = require("github");
var _ = require("lodash");
var inquirer = require("inquirer");
var ttys = require("ttys");
var debug = require("debug")("github-todos:github");
var config = require("../config");
/**
* Format of an issue:
* * type: String - "issue"
* * number: Number
* * url: String
* * title: String
* * labels: [String]
*
* Format of a comment:
* * type: String - "comment"
* * issue: Number
* * url: String
**/
module.exports = {
"meta": {
"desc": "Github issue service",
"repo": "user/repository"
},
"connect": connect,
"findIssueByTitle": requireClient(findIssueByTitle),
"allIssues": requireClient(allIssues),
"getFileUrl": getFileUrl,
"createIssue": requireClient(createIssue),
"commentIssue": requireClient(commentIssue),
"tagIssue": requireClient(tagIssue),
"guessRepoFromUrl": guessRepoFromUrl
};
var CLIENT = null;
var FAKE_ISSUE = {
"type": "issue",
"number": -1,
"url": "http://nope",
"title": "FAKE",
"labels": []
};
var FAKE_COMMENT = {
"type": "comment",
"issue": -1,
"url": "http://nope"
};
// "work" is called only if github client is connected, otherwise try to authenticate and call work
// Function(…, cb) → Function(…, cb)
function requireClient (work) {
return function () {
var self = this;
var args = Array.prototype.slice.call(arguments);
var cb = args[args.length - 1];
if (!cb || !_.isFunction(cb)) {
cb = function (err) {
if (err) {
throw err;
}
};
}
if (!CLIENT) {
// Grab config…
debug("config.list");
config.list(function (err, conf) {
if (err) {
return cb(err);
}
// …then connect…
connect(conf, function (err) {
if (err) {
return cb(err);
}
// …then work!
work.apply(self, args);
});
});
} else {
// Already connected: work!
work.apply(self, args);
}
};
}
// String → {user, repo}
function extractRepo (repo) {
var parts = repo.split("/");
return {
"user": parts[0],
"repo": parts[1]
};
}
// Grab first issue with given title
// String, String ~→ Issue
function findIssueByTitle (repo, title, cb) {
debug("findIssueByTitle", repo, title);
title = title.toLowerCase();
allIssues(repo, function (err, issues) {
if (err) {
return cb(err);
}
cb(null, _.find(issues, function (issue) {
return issue.title.toLowerCase() === title;
}));
});
}
// Convert a Github issue into a lighter object
// Object → Issue
function fromGithubIssue (issue) {
return {
"type": "issue",
"number": issue.number,
"url": issue.html_url,
"title": issue.title,
"labels": _.pluck(issue.labels, "name")
};
}
// String ~→ [Issue]
function allIssues (repo, cb) {
debug("allIssues");
if (process.env.DRY_RUN) {
return cb(null, []);
}
CLIENT.issues.repoIssues(extractRepo(repo), function (err, issues) {
if (err) {
return cb(err);
}
cb(null, issues.map(fromGithubIssue));
});
}
// Generate Github URL to blob
// String, String, Sha, Number → String
function getFileUrl (repo, path, sha, line) {
var url = "https://github.com/" + repo + "/blob/";
if (sha) {
url += sha + "/";
}
url += path;
if (line) {
url += "#L" + line;
}
return url;
}
// String, String, String, [String] ~→ Issue
function createIssue (repo, title, body, labels, cb) {
debug("createIssue", repo, title, body);
if (process.env.DRY_RUN) {
return cb(null, FAKE_ISSUE);
}
CLIENT.issues.create(_.merge(extractRepo(repo), {
"title": title,
"body": body,
"labels": labels
}), function (err, issue) {
cb(err, issue && fromGithubIssue(issue));
});
}
// String, Number, String ~→ Comment
function commentIssue (repo, number, comment, cb) {
debug("commentIssue", repo, number, comment);
if (process.env.DRY_RUN) {
return cb(null, FAKE_COMMENT);
}
CLIENT.issues.createComment(_.merge(extractRepo(repo), {
"number": number,
"body": comment
}), function (err, comment) {
cb(err, comment && {
"type": "comment",
"issue": number,
"url": comment.html_url
});
});
}
// Add a label (append, not replace)
// String, Number, String ~→ Issue
function tagIssue (repo, number, label, cb) {
debug("tagIssue", repo, number, label);
if (process.env.DRY_RUN) {
return cb(null, FAKE_ISSUE);
}
CLIENT.issues.getRepoIssue(_.merge(extractRepo(repo), {
"number": number
}), function (err, issue) {
if (err) {
return cb(err);
}
var labels = _.pluck(issue.labels, "name");
if (!_.contains(labels, label)) {
CLIENT.issues.edit(_.merge(extractRepo(repo), {
"number": number,
"labels": labels.concat([label])
}), function (err, issue) {
cb(err, issue && fromGithubIssue(issue));
});
} else {
cb(null, fromGithubIssue(issue));
}
});
}
// Object, String → Mixed
function githubOption (conf, option) {
var key = "github." + option;
return (typeof conf[key] === "undefined") ? config.defaults[key] : conf[key];
}
// Authenticate to Github (will enable all other APIs)
// Object ~→ void
function connect (conf, cb) {
if (process.env.DRY_RUN) {
CLIENT = {};
return cb();
}
debug("connect", conf);
var client = new Github({
"debug": false,
"host": githubOption(conf, "host"),
"protocol": githubOption(conf, "secure") ? "https" : "http",
"version": githubOption(conf, "version")
});
var token = githubOption(conf, "token");
if (token) {
debug("token found: authenticate", token);
client.authenticate({
type: "oauth",
token: token
});
checkToken(client, cb);
} else {
getToken(client, cb);
}
}
// Check if OAuth token is still working with a simple API call
// Sets CLIENT (this enables "requireClient" functions)
// Client ~→ void
function checkToken (client, cb) {
debug("checkToken");
client.user.get({}, function (err) {
if (err) {
console.error("Failed to validate Github OAuth token: please check API access (network?) or force re-authentication with 'github-todos auth --force'");
return cb(err);
}
// Store client for next API calls
CLIENT = client;
cb();
});
}
// Authenticate then stores OAuth token to user's configuration for later use
// Client ~→ void
function getToken (client, cb) {
debug("getToken");
console.log("No token found to access Github API. I will now ask for your username and password to generate one.");
console.log("Those information ARE NOT STORED, only the generated token will be stored in your global git configuration.");
console.log("If you don't want to let this process go you'll have to generate a token yourself and then save it with 'github-todos config github.token <your token>'.");
inquirer.prompt([
{"type": "input", "message": "Github username", "name": "user"},
{"type": "password", "message": "Github password", "name": "password"}
], function (answers) {
client.authenticate({
"type": "basic",
"username": answers.user,
"password": answers.password
});
var payload = {
"note": "Github-Todos (" + (new Date()) + ")",
"note_url": "https://github.com/naholyr/github-todos",
"scopes": ["user", "repo"]
};
function onCreate (err, res) {
if (err) {
return cb(err);
}
if (!res.token) {
return cb(new Error("No token generated"));
}
config.set("github.token", res.token, function (err) {
if (err) {
return cb(err);
}
client.authenticate({
type: "oauth",
token: res.token
});
cb();
});
}
client.authorization.create(payload, function (err, res) {
if (err && err.code === 401 && err.message && err.message.indexOf("OTP") !== -1) {
// Two-factor authentication
console.log("You are using two-factor authentication, please enter your code to finish:");
inquirer.prompt([{"type": "input", "message": "Code", "name": "code"}], function (answers) {
_.merge(payload, {
"headers": {
"X-GitHub-OTP": answers.code
}
});
client.authorization.create(payload, onCreate);
}, {
input: ttys.stdin,
output: ttys.stdout
});
} else {
onCreate(err, res);
}
});
}, {
input: ttys.stdin,
output: ttys.stdout
});
}
function guessRepoFromUrl (url) {
var match = url.match(/github\.com[:\/]([^\/]+\/[^\/]+?)(?:\.git)?$/);
return match && match[1];
}
|
/**
* Angular.js sidebar service
*
* @author eugene.trounev(a)gmail.com
*/
angular.module('app')
.factory('$userService', [function(){
var user;
return user;
}]);
|
var express = require('express')
var router = express.Router()
var http = require('http')
var querystring = require('querystring')
var zlib = require('zlib')
/* GET home page. */
router.get('/hitokoto', function (req, res, next) {
var chuckList = []
var _html = ''
var ret = {}
var _query = querystring.stringify({
encode: 'json'
})
var _option = {
method: 'GET',
host: 'api.hitokoto.cn',
port: 80,
path: '/?' + _query,
headers: {
'Accept': '*/*; q=0.01',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
'Host': 'api.hitokoto.cn',
'Origin': 'https://cqupt.heitaov.cn',
'Referer': req.headers.referer,
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko' +
') Chrome/57.0.2987.133 Safari/537.36'
}
}
http.request(_option, function (_res) {
var encoding = _res.headers['content-encoding']
if (encoding === 'undefined') {
res.setEncoding('utf-8')
}
_res
.on('data', function (data) {
chuckList.push(data)
})
_res.on('end', function () {
var buffer = Buffer.concat(chuckList)
if (encoding === 'gzip') {
zlib.gunzip(buffer, function (err, decoded) {
if (err) {
throw err
} else {
resolve(decoded.toString())
}
})
} else if (encoding === 'deflate') {
zlib.inflate(buffer, function (err, decoded) {
if (err) {
throw err
} else {
resolve(decoded.toString())
}
})
} else {
resolve(buffer.toString())
}
function resolve(string) {
try {
ret = JSON.parse(string)
} catch (err) {
console.log('错误:' + new Date().toLocaleString())
console.log(string)
ret = {
code: -1,
msg: 'perse错误'
}
}
res.json(ret)
}
})
}).on('error', function (e) {
console.log(e)
res.json({
code: 1,
msg: '后台系统无法发出请求~请联系管理员~'
})
}).end()
})
module.exports = router
|
#import "../../jasmine-uiautomation.js"
#import "../../jasmine/lib/jasmine-core/jasmine.js"
#import "../../jasmine-uiautomation-reporter.js"
#import "../../helpers/general_helpers.js"
describe("Questions Backgrounding", function() {
var helpers = new EPHelpers();
var expectedFirstVisibleCellName = 'Content for question 5';
afterEach(function() {
helpers.goBack();
});
it("performs background fetch operation when server has exactly one page of questions available", function() {
helpers.enterQuestions(1);
helpers.enterBackgroundForDuration(4);
// we should have 40 questions cells and one fetch more cell after coming back from background mode
var expected_number_of_questions = 41;
helpers.checkThereIsACorrectNumberOfRowsInTheTableView(expected_number_of_questions);
expect(helpers.getCellTextForLastElementInTableView('Questions')).toContain("Pull up to download more questions.");
helpers.fetchMoreInTableView('Questions');
helpers.enterBackgroundForDuration(4);
expected_number_of_questions = 40;
helpers.checkThereIsACorrectNumberOfRowsInTheTableView(expected_number_of_questions);
expect(helpers.getFirstVisibleCellTextForTableView('Questions')).toContain(expectedFirstVisibleCellName);
});
it("displays the same set of questions when re-entering questions section", function() {
helpers.enterQuestions();
helpers.checkThereIsACorrectNumberOfRowsInTheTableView(40);
expect(helpers.getFirstVisibleCellTextForTableView('Questions')).toContain(expectedFirstVisibleCellName);
});
});
jasmine.getEnv().addReporter(new jasmine.UIAutomation.Reporter());
jasmine.getEnv().execute();
|
var View = Backbone.View.extend({
el: '#view',
id: 'mainView',
// Cache the template function for a single item.
// viewTpl: _.template( $('#item-template').html() ),
initialize: function (options) {
console.log('This View has been initialized.');
this.render();
},
// Re-render the title of the todo item.
render: function() {
console.log('This View has been rendered.');
var self = this;
this.$el.html(this.model.get('title'));
return this;
},
events: {
click: 'onClick'
},
onClick: function(e) {
// executed when view label is clicked
console.log("View Clicked");
},
});
|
HTMLWidgets.widget({
name: 'dimpleStepHor-cn',
type: 'output',
initialize: function(el, width, height) {
d3.select(el).append("div")
.attr("id","chartContainer")
.attr("width", width)
.attr("height", height);
var svg = dimple.newSvg("#chartContainer", width, height);
var data = []
var myChart = new dimple.chart(svg, data);
return myChart
},
renderValue: function(el, x, instance) {
var myChart = instance;
myChart.data = x.data;
var colNames = x.colNames
//myChart.setBounds(60, 30, 510, 305)
myChart.setMargins("15%", "15%", "15%", "15%");
var y = myChart.addCategoryAxis("y",colNames[0]);
var x = myChart.addMeasureAxis("x", colNames[1]);
var s = myChart.addSeries(null, dimple.plot.line);
s.interpolation = 'step';
myChart.draw();
},
resize: function(el, width, height, instance) {
d3.select(el).select("svg")
.attr("width", width)
.attr("height", height);
instance.draw(0, true);
}
});
|
const config = require('../config.js');
module.exports = (slackapp) =>
function(err, req, res) {
if (err) {
res.status(500).send(`ERROR: ${err}`);
} else {
slackapp.log(
`Use /incoming-webhooks/${req.identity.team_id}?businessUnitId=${
config.BUSINESS_UNIT_ID
} to receive new reviews.`
);
res.redirect(req.identity.url);
}
};
|
import { drawCircularText } from 'vizart-core';
import isFunction from 'lodash-es/isFunction';
import getAxisLabel from './get-axis-label';
const getLevelLabel = (opt, label) =>
opt.plots.levelLabel && isFunction(opt.plots.levelLabel)
? opt.plots.levelLabel(label)
: label;
const highlight = (context, opt, datum) => {
context.save();
context.translate(opt.chart.width / 2, opt.chart.height / 2);
context.beginPath();
context.setLineDash([5, 5]);
context.strokeStyle = opt.plots.highlightStrokeColor;
context.arc(0, 0, datum.d.r, 0, 2 * Math.PI, false);
context.stroke();
context.restore();
context.closePath();
context.save();
context.beginPath();
context.fillStyle = opt.plots.highlightNodeColor
? opt.plots.highlightNodeColor
: datum.c;
context.strokeStyle = 'white';
context.lineWidth = 3;
context.arc(datum.x, datum.y, 6, 2 * Math.PI, false);
context.fill();
context.stroke();
context.closePath();
context.restore();
context.save();
context.beginPath();
context.fillStyle = opt.plots.axisLabelColor;
drawCircularText(
context,
getAxisLabel(opt, datum.label, 1) + '',
14,
'Oswald',
opt.plots.highlightLabelColor,
opt.chart.width / 2,
opt.chart.height / 2,
datum.d.r + 10,
datum.d.angle,
5
);
context.restore();
const lineOffset = 8;
context.save();
context.beginPath();
context.textBaseline = 'alphabetic';
context.textAlign = 'center'; // Ensure we draw in exact center
context.fillStyle = opt.plots.highlightLabelColor;
context.fillText(
getLevelLabel(opt, datum.metric),
opt.chart.width / 2,
opt.chart.height / 2 - lineOffset
);
context.fillText(
datum.s,
opt.chart.width / 2,
opt.chart.height / 2 + lineOffset
);
context.restore();
};
export default highlight;
|
'use strict';
var socialsInstagramCredentialsService = angular.module('socialsInstagramCredentialsService', []);
socialsInstagramCredentialsService.factory('InstagramCredentials', ['$resource', 'REST_API',
function ($resource, REST_API) {
return $resource(REST_API.INSTAGRAM_CREDENTIALS, {});
}]);
|
const extend = require('lodash/extend');
const uuid = require('uuid/v4');
const Action = require('./action');
const Base = require('./base');
class PanelItem extends Base {
constructor(type, parent, id, name, desc, position) {
super(type, parent, id, name, desc);
this.position = position || -1;
this.readOnly = false;
this.actions = [];
this.visibleInEditOnly = false;
}
// eslint-disable-next-line camelcase
getParent_Panel() {
return this.parent;
}
get isReadOnly() {
return Boolean(this.readOnly);
}
get isVisibleInEditOnly() {
return Boolean(this.visibleInEditOnly);
}
toJSON() {
return extend({}, super.toJSON(), {
position: this.position,
readOnly: this.readOnly,
visibleInEditOnly: this.visibleInEditOnly,
actions: this.actions.map((action) => action.toJSON())
});
}
fromJSON(json) {
super.fromJSON(json);
this.position = json.position;
this.readOnly = json.readOnly;
this.visibleInEditOnly = json.visibleInEditOnly;
this.actions = this.fromJsonMapper(Action, json.actions);
}
toPersistenceJSON() {
const json = extend({}, super.toPersistenceJSON(), {
_id: this._id || uuid(),
position: this.position,
readOnly: this.readOnly,
visibleInEditOnly: this.visibleInEditOnly
});
json.embedded.push(this.mapChildrenPersistenceJSON(80, 'actions', this.actions));
return json;
}
async fromPersistenceJSON(persistence, json) {
await super.fromPersistenceJSON(persistence, json);
this._id = json._id;
this.position = json.position;
this.readOnly = json.readOnly;
this.visibleInEditOnly = json.visibleInEditOnly;
await this.fromPersistenceEmbeddedJson(persistence, json.embedded, 80, Action, 'actions');
return this;
}
toFormResourceBase() {
return extend({}, super.toFormResourceBase(), {
position: this.position,
readOnly: this.readOnly,
visibleInEditOnly: this.visibleInEditOnly
});
}
async toFormResource(persistence, instance, docLevel, relativeToDocument) {
throw new Error(`${this.constructor.name}.toFormResource() not implemented.`);
}
toStudioResource(persistence, instance, docLevel, relativeToDocument, routes) {
throw new Error(`${this.constructor.name}.toStudioResource() not implemented.`);
}
}
module.exports = PanelItem;
|
var calendar_charting = function() {
var chart
var init = function() {
load_data()
}
var resize_chart = function() {
chart.setSize($(window).width(), $(window).height() - 80)
}
var load_data = function() {
var y = new Date()
$.ajax({
url: '/calendar/events',
method: 'GET'
}).done(function(res){
chart = new Highcharts.chart('chart', {
chart: {
type: 'scatter',
style: {
fontFamily: 'Exo'
},
scrollablePlotArea: {
minWidth: 1200,
scrollPositionX: 0
},
panning: true,
zoomType: 'x',
height: res.category.length * 24,
},
credits: false,
series: [
{ data: res.data.national.data, name: 'National', marker: { symbol: 'diamond', fillColor: 'rgba(242, 143, 67, 0.8)', lineWidth: 2, lineColor: 'rgba(242, 143, 67, 0.8)' }, states: { hover: { halo: { attributes: { fill: 'rgba(242, 143, 67, 0.8)' }}}}},
{ data: res.data.west_coast.data, name: 'West Coast', marker: { symbol: 'circle', fillColor: 'rgba(139, 188, 33, 0.8)'}, states: { hover: { halo: { attributes: { fill: 'rgba(139, 188, 33, 0.8)' }}}}},
{ data: res.data.central.data, name: 'Central', marker: { symbol: 'square', fillColor: 'rgba(26, 173, 206, 0.8)' }, states: { hover: { halo: { attributes: { fill: 'rgba(26, 173, 206, 0.8)' }}}}},
{ data: res.data.south.data, name: 'South', marker: { symbol: 'diamond', fillColor: 'rgba(73, 41, 112, 0.8)', lineWidth: 2, lineColor: 'rgba(73, 41, 112, 0.8)' }, states: { hover: { halo: { attributes: { fill: 'rgba(73, 41, 112, 0.8)' }}}}},
{ data: res.data.east_coast.data, name: 'East Coast', marker: { symbol: 'circle', fillColor: 'rgba(242, 143, 67, 0.8)' }, states: { hover: { halo: { attributes: { fill: 'rgba(242, 143, 67, 0.8)' }}}}},
{ data: res.data.midwest.data, name: 'Midwest', marker: { symbol: 'square', fillColor: 'rgba(26, 173, 206, 0.8)' }, states: { hover: { halo: { attributes: { fill: 'rgba(26, 173, 206, 0.8)' }}}}},
{ data: res.data.north.data, name: 'North', marker: { symbol: 'diamond', fillColor: 'rgba(73, 41, 112, 0.8)', lineWidth: 2, lineColor: 'rgba(73, 41, 112, 0.8)' }, states: { hover: { halo: { attributes: { fill: 'rgba(73, 41, 112, 0.8)' }}}}},
],
title: false,
tooltip: {
formatter: function() {
var d = new Date(this.x)
return this.key + '<br />' + (d.getUTCMonth() + 1) + '/' + d.getUTCDate()
},
borderColor: '#aaa'
},
xAxis: [{
type: 'datetime',
scrollbar: { enabled: true },
minorTicks: true,
minRange: 24 * 60 * 60 * 7 * 1000,
min: Math.min(moment().add(-3, 'months').unix() * 1000, Date.UTC(y.getFullYear(), 0, 1)),
max: Date.UTC(y.getFullYear(), 11, 31),
gridLineWidth: 4,
opposite: true,
crosshair: {
borderWidth: 1,
snap: false
},
plotLines: [{
value: Date.UTC(y.getFullYear(), y.getUTCMonth(), y.getUTCDate()),
width: 4,
color: '#c42525',
zIndex: 2
}]
}, {
type: 'datetime',
linkedTo: 0,
opposite: false
}],
yAxis: {
type: 'category',
scrollbar: { enabled: true },
categories: res.category,
title: false,
labels: {
style: {
fontFamily: 'Exo',
}
},
minorTicks: true,
crosshair: {
borderWidth: 1,
snap: true
},
plotBands: [
{ from: 19.5, to: 20.5, color: 'rgba(242, 143, 67, 0.25)' },
{ from: 15.5, to: 19.5, color: 'rgba(139, 188, 33, 0.15)' },
{ from: 10.5, to: 15.5, color: 'rgba(26, 173, 206, 0.15)' },
{ from: 8.5, to: 10.5, color: 'rgba(73, 41, 112, 0.15)' },
{ from: 3.5, to: 8.5, color: 'rgba(242, 143, 67, 0.15)' },
{ from: 0.5, to: 3.5, color: 'rgba(26, 173, 206, 0.15)' },
{ from: -0.5, to: 0.5, color: 'rgba(73, 41, 112, 0.15)' },
]
},
plotOptions: {
scatter: {
}
},
})
})
}
return {
init: init,
get_chart: function() { return chart }
}
}();
|
(function(factory) {
if (typeof define === "function" && define.amd) {
define([ "jquery", "moment" ], factory);
}
else if (typeof exports === "object") {
module.exports = factory(require("jquery"), require("moment"));
}
else {
factory(jQuery, moment);
}
})(function($, moment) {
(function() {
//! moment.js locale configuration
//! locale : Czech [cs]
//! author : petrbela : https://github.com/petrbela
; 'use strict';
var months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'),
monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_');
function plural(n) {
return (n > 1) && (n < 5) && (~~(n / 10) !== 1);
}
function translate(number, withoutSuffix, key, isFuture) {
var result = number + ' ';
switch (key) {
case 's': // a few seconds / in a few seconds / a few seconds ago
return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami';
case 'm': // a minute / in a minute / a minute ago
return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou');
case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
if (withoutSuffix || isFuture) {
return result + (plural(number) ? 'minuty' : 'minut');
} else {
return result + 'minutami';
}
break;
case 'h': // an hour / in an hour / an hour ago
return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
case 'hh': // 9 hours / in 9 hours / 9 hours ago
if (withoutSuffix || isFuture) {
return result + (plural(number) ? 'hodiny' : 'hodin');
} else {
return result + 'hodinami';
}
break;
case 'd': // a day / in a day / a day ago
return (withoutSuffix || isFuture) ? 'den' : 'dnem';
case 'dd': // 9 days / in 9 days / 9 days ago
if (withoutSuffix || isFuture) {
return result + (plural(number) ? 'dny' : 'dní');
} else {
return result + 'dny';
}
break;
case 'M': // a month / in a month / a month ago
return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem';
case 'MM': // 9 months / in 9 months / 9 months ago
if (withoutSuffix || isFuture) {
return result + (plural(number) ? 'měsíce' : 'měsíců');
} else {
return result + 'měsíci';
}
break;
case 'y': // a year / in a year / a year ago
return (withoutSuffix || isFuture) ? 'rok' : 'rokem';
case 'yy': // 9 years / in 9 years / 9 years ago
if (withoutSuffix || isFuture) {
return result + (plural(number) ? 'roky' : 'let');
} else {
return result + 'lety';
}
break;
}
}
var cs = (moment.defineLocale || moment.lang).call(moment, 'cs', {
months : months,
monthsShort : monthsShort,
monthsParse : (function (months, monthsShort) {
var i, _monthsParse = [];
for (i = 0; i < 12; i++) {
// use custom parser to solve problem with July (červenec)
_monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i');
}
return _monthsParse;
}(months, monthsShort)),
shortMonthsParse : (function (monthsShort) {
var i, _shortMonthsParse = [];
for (i = 0; i < 12; i++) {
_shortMonthsParse[i] = new RegExp('^' + monthsShort[i] + '$', 'i');
}
return _shortMonthsParse;
}(monthsShort)),
longMonthsParse : (function (months) {
var i, _longMonthsParse = [];
for (i = 0; i < 12; i++) {
_longMonthsParse[i] = new RegExp('^' + months[i] + '$', 'i');
}
return _longMonthsParse;
}(months)),
weekdays : 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'),
weekdaysShort : 'ne_po_út_st_čt_pá_so'.split('_'),
weekdaysMin : 'ne_po_út_st_čt_pá_so'.split('_'),
longDateFormat : {
LT: 'H:mm',
LTS : 'H:mm:ss',
L : 'DD.MM.YYYY',
LL : 'D. MMMM YYYY',
LLL : 'D. MMMM YYYY H:mm',
LLLL : 'dddd D. MMMM YYYY H:mm',
l : 'D. M. YYYY'
},
calendar : {
sameDay: '[dnes v] LT',
nextDay: '[zítra v] LT',
nextWeek: function () {
switch (this.day()) {
case 0:
return '[v neděli v] LT';
case 1:
case 2:
return '[v] dddd [v] LT';
case 3:
return '[ve středu v] LT';
case 4:
return '[ve čtvrtek v] LT';
case 5:
return '[v pátek v] LT';
case 6:
return '[v sobotu v] LT';
}
},
lastDay: '[včera v] LT',
lastWeek: function () {
switch (this.day()) {
case 0:
return '[minulou neděli v] LT';
case 1:
case 2:
return '[minulé] dddd [v] LT';
case 3:
return '[minulou středu v] LT';
case 4:
case 5:
return '[minulý] dddd [v] LT';
case 6:
return '[minulou sobotu v] LT';
}
},
sameElse: 'L'
},
relativeTime : {
future : 'za %s',
past : 'před %s',
s : translate,
m : translate,
mm : translate,
h : translate,
hh : translate,
d : translate,
dd : translate,
M : translate,
MM : translate,
y : translate,
yy : translate
},
ordinalParse : /\d{1,2}\./,
ordinal : '%d.',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return cs;
})();
/* Czech initialisation for the jQuery UI date picker plugin. */
/* Written by Tomas Muller (tomas@tomas-muller.net). */
$.fullCalendar.datepickerLang('cs', 'cs', {
closeText: 'Zavřít',
prevText: '<Dříve',
nextText: 'Později>',
currentText: 'Nyní',
monthNames: ['leden','únor','březen','duben','květen','červen',
'červenec','srpen','září','říjen','listopad','prosinec'],
monthNamesShort: ['led','úno','bře','dub','kvě','čer',
'čvc','srp','zář','říj','lis','pro'],
dayNames: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
dayNamesShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
dayNamesMin: ['ne','po','út','st','čt','pá','so'],
weekHeader: 'Týd',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''});
$.fullCalendar.lang("cs", {
buttonText: {
month: "Měsíc",
week: "Týden",
day: "Den",
list: "Agenda"
},
allDayText: "Celý den",
eventLimitText: function(n) {
return "+další: " + n;
}
});
});
|
import React, { Component } from 'react'
import PropTypes from 'prop-types';
export default class FilterByPosition extends Component {
static propTypes = {
apiData__positions: PropTypes.array.isRequired,
updatePositionFilter: PropTypes.func.isRequired,
positionArr: PropTypes.array.isRequired,
className: PropTypes.string.isRequired
};
handleChange = e => {
this.props.updatePositionFilter(e.target.checked, Number(e.target.id));
}
renderCheckbox(thisVal){
let {positionArr, apiData__positions} = this.props
let checked = positionArr.includes(thisVal) ? true : false
return(
<li key={thisVal}>
<label htmlFor={thisVal}>{apiData__positions[thisVal-1].plural_name_short}</label>
<input type="checkbox" checked={checked} onChange={this.handleChange} id={thisVal}/>
</li>
);
}
buildPosBoxes(){
var positions = [];
this.props.apiData__positions.map((position) =>
positions.push(position.id)
)
var rows = [];
var self = this;
positions.forEach(function(thisVal, thisKey){
rows.push(self.renderCheckbox(thisVal));
})
return(
<ul className={this.props.className}>
{rows}
</ul>
);
}
render() {
return this.buildPosBoxes()
}
}
|
'use strict';
// Declare app level module which depends on filters, and services
var tdfTeamsApp = angular.module('tdfTeams', [
'ngRoute',
'ngSanitize',
'tdfTeams.filters',
'tdfTeams.services',
'tdfTeams.directives',
'tdfTeams.controllers',
'tdfRiders.controllers'
]);
tdfTeamsApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/teams', {
templateUrl: 'partials/team-list.html',
controller: 'TeamListCtrl'
}).
when('/teams/:teamId', {
templateUrl: 'partials/team-detailed.html',
controller: 'TeamDetailedCtrl'
}).
when('/teams/:teamId/riders/:riderId', {
templateUrl: 'partials/rider-detailed.html',
controller: 'RiderDetailedCtrl'
}).
otherwise({redirectTo: '/teams'});
}]);
|
import {renderComponent, expect} from '../test_helper';
import App from '../../src/components/app';
//core part of how mocha runs tests
//queue's up tests in the it blocks
//used to group together similar tests
describe('App Component', () => {
let component;
beforeEach(() => {
component = renderComponent(App);
})
it('shows a comment box', () => {
expect(component.find('.comment-box')).to.exist;
});
it('shows a comment list', () => {
expect(component.find('.comment-list')).to.exist;
});
});
|
define([
'jquery',
'App.views.OfficeList',
'App.collections.Office'
], function($, OfficeListView, OfficeCollection) {
'use strict';
var controller = function() {
var view = new OfficeListView({
offices: new OfficeCollection()
});
$('#content').html(view.el);
};
return controller;
});
|
function snap( point, e )
{
// grid
var pos = getMousePos(canvas, e);
if (objects[0].density != -1)
{
for ( var i = 0; i < objects[0].xes.length; i++ )
{
if ( Math.abs( pos.x - objects[0].xes[i] ) < 5)
{
point.x = objects[0].xes[i];
}
}
for ( var i = 0; i < objects[0].yes.length; i++ )
{
if ( Math.abs( pos.y - objects[0].yes[i] ) < 5)
{
point.y = objects[0].yes[i];
}
}
}
// elements
for ( var i = 0; i < points.length; i++ )
{
// points
if ( axisOn )
{
if ( Math.abs( pos.x - points[i].x ) < 5)
{
point.x = points[i].x;
}
if ( Math.abs( pos.y - points[i].y ) < 5)
{
point.y = points[i].y;
}
} else
{
if ( Math.abs( pos.x - points[i].x ) < 5 && Math.abs( pos.y - points[i].y ) < 5)
{
point.x = points[i].x;
point.y = points[i].y;
}
}
}
return point;
}
function snaPoint( e ) {
var point = new Point();
var pos = getMousePos(canvas, e);
point.x = pos.x;
point.y = pos.y;
point = snap( point, e);
canvasRedraw( point );
axis( e );
}
|
'use strict';
angular.module('myjamApp')
.factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) {
var currentUser = {};
if($cookieStore.get('token')) {
currentUser = User.get();
}
return {
/**
* Authenticate user and save token
*
* @param {Object} user - login info
* @param {Function} callback - optional
* @return {Promise}
*/
login: function(user, callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.post('/auth/local', {
email: user.email,
password: user.password
}).
success(function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
deferred.resolve(data);
return cb();
}).
error(function(err) {
this.logout();
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
/**
* Delete access token and user info
*
* @param {Function}
*/
logout: function() {
$cookieStore.remove('token');
currentUser = {};
},
/**
* Create a new user
*
* @param {Object} user - user info
* @param {Function} callback - optional
* @return {Promise}
*/
createUser: function(user, callback) {
var cb = callback || angular.noop;
return User.save(user,
function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
return cb(user);
},
function(err) {
this.logout();
return cb(err);
}.bind(this)).$promise;
},
/**
* Change password
*
* @param {String} oldPassword
* @param {String} newPassword
* @param {Function} callback - optional
* @return {Promise}
*/
changePassword: function(oldPassword, newPassword, callback) {
var cb = callback || angular.noop;
return User.changePassword({ id: currentUser._id }, {
oldPassword: oldPassword,
newPassword: newPassword
}, function(user) {
return cb(user);
}, function(err) {
return cb(err);
}).$promise;
},
/**
* Gets all available info on authenticated user
*
* @return {Object} user
*/
getCurrentUser: function() {
return currentUser;
},
/**
* Check if a user is logged in
*
* @return {Boolean}
*/
isLoggedIn: function() {
return currentUser.hasOwnProperty('role');
},
/**
* Waits for currentUser to resolve before checking if user is logged in
*/
isLoggedInAsync: function(cb) {
if(currentUser.hasOwnProperty('$promise')) {
currentUser.$promise.then(function() {
cb(true);
}).catch(function() {
cb(false);
});
} else if(currentUser.hasOwnProperty('role')) {
cb(true);
} else {
cb(false);
}
},
/**
* Check if a user is an admin
*
* @return {Boolean}
*/
isAdmin: function() {
return currentUser.role === 'admin';
},
/**
* Get auth token
*/
getToken: function() {
return $cookieStore.get('token');
}
};
});
|
/**
* Blocks are functions with executable code that make up a spec.
*
* A block function may return a "thenable" promise, in which case the
* test completes when the promise is resolved and fails if the promise
* fails or if it succeeds with an unexpected value.
*
* @constructor
* @param {jasmine.Env} env
* @param {Function} func
* @param {jasmine.Spec} spec
*/
jasmine.Block = function(env, func, spec) {
this.env = env;
this.func = func;
this.spec = spec;
};
jasmine.Block.prototype.execute = function(onComplete) {
var spec = this.spec;
var result;
try {
result = this.func.apply(spec);
} catch (error) {
spec.fail(error);
}
if (typeof result === 'undefined') {
// blocks that do not return promises complete immediately
onComplete();
} else if (typeof result !== 'object' || typeof result.then !== 'function') {
// if a block returns anything, it must return a promise as defined by
// CommonJS/A
spec.fail(new Error('`it` block returns non-promise: ' + result));
onComplete();
} else {
// Throwing an error from an attempt to use a returned promise fails
// the block
try {
result.then(function (value) {
// fulfillment
spec.resolved = true; // for verification;
// test block promises must fulfill to undefined. it is typical
// to pipe the final promise of a test to make note of an expected
// value and return no value
if (value !== undefined) {
spec.fail(new Error('Promise fulfilled with unexpected value: ' + value));
}
onComplete();
}, function (error) {
// rejection
spec.rejected = true; // for verification
if (!error || !('stack' in error)) {
spec.fail(new Error(error));
}
spec.fail(error);
onComplete();
});
} catch (error) {
spec.fail(error);
onComplete();
}
}
};
|
module.exports = {
Code: require('./code'),
Implicit: require('./implicit')
}
|
/**
* OJSO JavaScript Library v0.2alpha
*
* Released under the MIT license
*
* Date: 2017.06.26 - 18:50
*
* namespace
*
* @todo log dump handler
* @todo merge ojso mit new ojso
* @todo dump console.x
* @todo css class id identifier
* @todo events
* @todo get every component
* @todo css identifier getCreate css class
* @todo location
* @todo no shortcut vars params methods
* @todo window and document
* @todo attributes
* @todo window
* @todo navigator
* @todo screen
* @todo history
* @todo console
* @todo storage
* @todo cookie
* @todo jsdoc
*
* @constructor
*/
var OJSO = new function OJSO() {
'use strict';
/* keyword this in this class context */
var _this = this;
/**
* @type {OJSO}
* @private
*/
var _thisNamespace = _this;
/**
* @constructor
*/
_this.JSDoc = function JSDoc() {
/* keyword this in this class context */
var _this = this;
/**
* Description text...
*
* @type {undefined}
*/
_this.description = undefined;
/**
* @type {*}
*/
_this.anyType1 = undefined;
/**
* @type {boolean}
*/
_this.boolean1 = false;
/**
* @type {boolean|number}
*/
_this.booleanOrNumber1 = false;
/**
* @type {number}
*/
_this.number1 = 0;
/**
* @type {?number}
*/
_this.numberOrNull1 = 0;
/**
* @type {!number}
*/
_this.numberButNotNull1 = 0;
/**
* @type {string}
*/
_this.string1 = '';
/** */
_this.function1 = function function1() {
};
/**
* @param {boolean} param1
* @param {boolean} param2
*/
_this.function2 = function function2(param1, param2) {
};
/**
* This function accepts a variable number of numeric parameters.
*
* @param {...boolean} param
*/
_this.function3 = function function3(param) {
};
/**
* @param {boolean} [param]
*/
_this.function4 = function function4(param) {
};
/**
* @param {boolean=} param
*/
_this.function5 = function function5(param) {
};
/**
* @param {boolean} [param=false]
*/
_this.function6 = function function6(param) {
};
/**
* @type {Array}
*/
_this.array1 = [];
/**
* @type {Array.<MyClass2>}
*/
_this.arrayOfMyClass2_1 = [_this.MyClass2, _this.MyClass2];
/**
* @type {MyClass2[]}
*/
_this.arrayOfMyClass2_2 = [_this.MyClass2, _this.MyClass2];
/**
* @type {{}}
*/
_this.Object1 = {};
/**
* @type {Object}
*/
_this.Object2 = {};
/**
* @type {Object.<string, number>}
*/
_this.Object3 = {
'a': 0,
'b': 1
};
/**
* @type {{a: number, b: number}}
*/
_this.Object4 = {
'a': 0,
'b': 1
};
/**
* @type {Namespace1}
*/
var Namespace1 = {};
/**
* @type {Namespace1.Class1}
* @constructor
*/
Namespace1.Class1 = function Class1() {
};
/**
* @type {Namespace1.Class1}
*/
_this.Class2 = Namespace1.Class1;
/**
* @param {boolean} param1
*/
var callback1 = function callback1(param1) {
};
/**
* @callback callback1
* @param {boolean} param1
*/
/**
* @type {callback1}
*/
_this.callback2 = callback1;
/**
* @type {{a: boolean, b: number, c: string, d: d, e: Array, f: {}}}
*/
var TypeDef1 = {
a: false,
b: 0,
c: '',
d: function d() {
},
e: [],
f: {}
};
/**
* @typedef TypeDef2
* @type {Object}
* @property {boolean} a
* @property {number} b
* @property {string} c
* @property {function} d
* @property {Array} e
* @property {Object} f
*/
_this.TypeDef2 = TypeDef1;
/**
* @typedef {Object} TypeDef3
* @property {boolean} a
* @property {number} b
* @property {string} c
* @property {function} d
* @property {Array} e
* @property {Object} f
*/
_this.TypeDef3 = TypeDef1;
/**
* @typedef {TypeDef1} TypeDef4
* @property {boolean} a
* @property {number} b
* @property {string} c
* @property {function} d
* @property {Array} e
* @property {Object} f
*/
_this.TypeDef4 = TypeDef1;
/**
* @typedef TypeDef5
* @property {boolean} a
* @property {number} b
* @property {string} c
* @property {function} d
* @property {Array} e
* @property {Object} f
*/
_this.TypeDef5 = TypeDef1;
/**
* @typedef {boolean} Special
*/
/**
* @param {Special} param
*/
_this.TypeDef6 = function TypeDef6(param) {
};
/**
* @typedef {TypeDef1} TypeDef7~Typedef7param
* @property {boolean} a
* @property {number} b
* @property {string} c
*/
/**
* @param {TypeDef7~Typedef7param} typeDef7param
*/
_this.TypeDef7 = function TypeDef7(typeDef7param) {
};
/**
* Link inline {@link http://usejsdoc.org/tags-inline-link.html} description
*
* @type {undefined}
*/
_this.link1 = undefined;
/**
* @version 1.2.3
* @type {undefined}
*/
_this.version1 = undefined;
/**
* @todo I am todo360, at your service.
*/
_this.todo1 = function todo1() {
};
/**
* @throws {TestException} description
*/
_this.throw1 = function throw1() {
throw 'TestException';
};
/**
* @since 1234.12.12
*/
_this.since = function since() {
};
/**
* @see link1
* @see {@link link1} description
* @see {@link http://usejsdoc.org/tags-inline-link.html} description
*/
_this.see = function see() {
};
/**
* @returns {boolean} always false
*/
_this.return1 = function return1() {
return false;
};
/**
* @param {boolean|number|Namespace1} x
* @returns {boolean|number|Namespace1} depends on input
*/
_this.return2 = function return1(x) {
return x;
};
// /**
// * @const
// */
// /**
// * @const {number}
// */
};
/**
* @constructor
*/
_this.DummyTrait = function DummyTrait() {
/* keyword this in this class context */
var _this = this;
/**
* @param {*} parameter
*/
var traitFunctionPrivate = function traitFunctionPrivate(parameter) {
};
/**
* @param {*} parameter
*/
_this.traitFunctionPublic = function traitFunctionPublic(parameter) {
};
};
/**
* @param {string} parameter
* @constructor
*/
_this.DummyParent = function DummyParent(parameter) {
/* keyword this in this class context */
var _this = this;
/**
* @type {string}
*/
var privateParent = 'I am private parent';
/**
* @type {string}
*/
_this.publicParent = 'I am public parent';
/**
* @param {string} parameter
* @returns {string}
*/
var privateMethod = function privateMethod(parameter) {
privateParent += parameter;
return privateParent;
};
/**
* @param {string} parameter
* @returns {string}
*/
_this.publicMethod = function publicMethod(parameter) {
return privateMethod(parameter);
};
/* constructor */
(function (parameter) {
_this.publicParent += parameter;
})(parameter);
};
/**
* singleton
* @type {Dummy}
*/
var Dummy;
/**
* @param {string} parameter
* @returns {Dummy}
* @constructor
*/
_this.Dummy = function Dummy(parameter) {
/* singleton */
if (Dummy instanceof _thisNamespace.Dummy) {
return Dummy;
}
/* keyword this in this class context */
var _this = this;
/* extends simple inheritance */
_thisNamespace.DummyParent.call(_this, parameter);
/* trait use */
_thisNamespace.DummyTrait.call(_this);
/**
* @type {number}
*/
var privateProperty = 0;
/**
* @type {number}
*/
_this.publicProperty = 1;
/**
* @param {number} parameter
* @returns {number}
*/
var privateMethod = function privateMethod(parameter) {
privateProperty += parameter;
return privateProperty;
};
/**
* @param {number} parameter
* @returns {number}
*/
_this.publicMethod = function publicMethod(parameter) {
return privateMethod(parameter);
};
/* constructor */
(function (parameter) {
_this.publicParent += parameter + ' in child';
/* singleton */
Dummy = _this;
})(parameter);
};
/**
* @returns {number}
*/
_this.getMicroTime = function getMicroTime() {
return (new Date()).getTime();
};
/**
* @param {string} id
*/
_this.Benchmark = function Benchmark(id) {
/* keyword this in this class context */
var _this = this;
/**
* be an object for direct access over benchmark id without collecting empty indices [,,2,,4]
*
* @type {{0: {begin: number, end: number, time: number}}}
*/
var benchmarkCaseHash = {
dummyId: {
begin: 0,
end: 0,
time: 0
}
};
/**
* @param {string} id
*/
_this.begin = function begin(id) {
benchmarkCaseHash[id] = {
begin: _thisNamespace.getMicroTime()
};
};
/**
* @param {string} id
* @param {boolean|undefined} dump
*/
_this.end = function end(id, dump) {
benchmarkCaseHash[id].end = _thisNamespace.getMicroTime();
benchmarkCaseHash[id].time = benchmarkCaseHash[id].end - benchmarkCaseHash[id].begin;
if (_thisNamespace.isUndefined(dump) || dump) {
_this.dump(id);
}
};
/**
* @param {string} id
*/
_this.dump = function dump(id) {
console.log('benchmark run-time analysis: ' + id + ' = ' + benchmarkCaseHash[id].time + 'ms');
};
/** */
_this.dumpAll = function dumpAll() {
for (var id in benchmarkCaseHash) {
_this.dump(id);
}
};
/**
* @param {number} minRunTime
*/
_this.dumpAllGreaterThan = function dumpAllGreaterThan(minRunTime) {
var minRunTimeNumber = _thisNamespace.isUndefined(minRunTime) ? -1 : minRunTime;
for (var id in benchmarkCaseHash) {
if (benchmarkCaseHash[id].time > minRunTimeNumber) {
_this.dump(id);
}
}
};
/* constructor */
(function (id) {
benchmarkCaseHash = {};
_this.begin(id);
})(id);
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isUndefined = function isUndefined(value) {
return undefined === value;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isNull = function isNull(value) {
return null === value;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isNaN = function isNaN(value) {
return !_this.isNumber(value);
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isBoolean = function isBoolean(value) {
return 'boolean' === typeof value;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isNumeric = function isNumeric(value) {
return Number(value) == value;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isNumber = function isNumber(value) {
return Number(value) === value;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isInteger = function isInteger(value) {
return _this.isNumber(value) && 0 === value % 1 && !_this.isNaN(value % 1);
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isFloat = function isFloat(value) {
return _this.isInteger(value) || (_this.isNumber(value) && 0 !== value % 1 && !_this.isNaN(value % 1));
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isFinite = function isFinite(value) {
return _this.isNumber(value) && isFinite(value);
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isInfinite = function isInfinite(value) {
return _this.isNumber(value) && !isFinite(value);
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isString = function isString(value) {
return 'string' === typeof value;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isFunction = function isFunction(value) {
return 'function' === typeof value;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isArray = function isArray(value) {
return Array.isArray(value);
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isObject = function isObject(value) {
return 'object' === typeof value && !_this.isArray(value) && !_this.isNull(value);
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isSet = function isSet(value) {
var re;
if (_this.isNull(value) || _this.isUndefined(value)) {
re = false;
}
else if (_this.isBoolean(value) || _this.isNumber(value) || _this.isInfinite(value) || _this.isString(value) || _this.isFunction(value) || _this.isArray(value) || _this.isObject(value)) {
re = true;
}
else if (isNaN(value)) {
re = false;
}
else {
throw 'unable to solve: isSet(' + value + '); typeof ' + value + ' === unknown';
}
return re;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.isEmpty = function isEmpty(value) {
var re;
if (_this.isUndefined(value) || _this.isNull(value) || '' === value) {
re = true;
}
else if (_this.isBoolean(value) || _this.isNumber(value) || _this.isInfinite(value) || _this.isString(value) || _this.isFunction(value)) {
re = false;
}
else if (_this.isArray(value) || _this.isObject(value)) {
re = true;
for (var name in value) {
re = false;
break;
}
}
else if (isNaN(value)) {
re = true;
}
else {
throw 'unable to solve: isEmpty(' + value + '); typeof ' + value + ' === unknown';
}
return re;
};
/**
* @param {*} value
* @returns {boolean}
*/
_this.toBoolean = function toBoolean(value) {
var re;
if (_this.isBoolean(value)) {
re = value;
}
else if (_this.isNull(value) || _this.isUndefined(value)) {
re = false;
}
else if (_this.isInteger(value)) {
re = 0 !== value;
}
else if (_this.isFloat(value)) {
re = 0.0 !== value;
}
else if (_this.isInfinite(value)) {
re = -Infinity !== value;
}
else if (_this.isString(value)) {
var str = value.toLowerCase();
if ('false' === str) {
re = false;
}
else if ('true' === str) {
re = true;
}
else if ('0' === str || '0.0' === str) {
re = false;
}
else {
re = !!value;
}
}
else if (_this.isFunction(value)) {
re = true;
}
else if (_this.isArray(value) || _this.isObject(value)) {
re = !_this.isEmpty(value);
}
else if (isNaN(value)) {
re = false;
}
else {
re = !!value;
}
return re;
};
/**
* @todo toNumber
* @todo write test
*
* @param {*} value
* @returns {number}
*/
_this.toNumber = function toNumber(value) {
var re = Number(value);
if (_this.isNumber(re)) {
return re;
}
else if (_this.isNaN(re)) {
return _this.toNumber(_this.toBoolean(value));
}
};
/**
* @param {*} value
* @returns {number}
*/
_this.toInteger = function toInteger(value) {
var re;
if (_this.isInteger(value)) {
re = value;
}
else if (_this.isBoolean(value)) {
re = value ? 1 : 0;
}
else if (_this.isNull(value) || _this.isUndefined(value) || _this.isInfinite(value) || _this.isFunction(value) || _this.isArray(value) || _this.isObject(value)) {
re = _this.toInteger(_this.toBoolean(value));
}
else if (_this.isString(value)) {
var str = value.toLowerCase();
re = 'false' === str || 'true' === str ? _this.toInteger(_this.toBoolean(str)) : parseInt(value);
}
else {
re = parseInt(value);
}
if (isNaN(re)) {
re = 0;
}
return re;
};
/**
* @param {*} value
* @returns {number}
*/
_this.toFloat = function toFloat(value) {
var re;
if (_this.isFloat(value)) {
re = value;
}
else if (_this.isBoolean(value)) {
re = value ? 1.0 : 0.0;
}
else if (_this.isNull(value) || _this.isUndefined(value) || _this.isInfinite(value) || _this.isFunction(value) || _this.isArray(value) || _this.isObject(value)) {
re = _this.toFloat(_this.toBoolean(value));
}
else if (_this.isString(value)) {
var str = value.toLowerCase();
re = 'false' === str || 'true' === str ? _this.toFloat(_this.toBoolean(str)) : parseFloat(value);
}
else {
re = parseFloat(value);
}
if (isNaN(re)) {
re = 0;
}
return re;
};
/**
* @param {*} value
* @returns {string}
*/
_this.toString = function toString(value) {
return _this.isArray(value) || _this.isObject(value) ? JSON.stringify(value) : '' + value;
};
/**
* @todo toFunction
* @todo validate usefulness
*/
_this.toFunction = function toFunction(value) {
return _thisNamespace.isFunction(value) ? value : function () {
return value;
};
};
/**
* @todo toArray
* @todo write test
*/
_this.toArray = function toArray(value) {
var re;
if (_this.isArray(value)) {
re = value;
}
else if (_this.isObject(value)) {
re = [];
for (var i in value) {
re.push(value.i);
}
} else {
re = [value];
}
return re;
};
/**
* @todo toHash
*/
_this.toHash = function toHash() {
};
/**
* @todo toObject
*/
_this.toObject = function toObject() {
};
/**
* @returns {Event}
* @constructor
*/
var Event = function Event() {
/* keyword this in this class context */
var _this = this;
/**
* @type {string}
*/
_this.on = 'on';
/**
* @param {string} event
* @returns {string}
*/
_this.onEvent = function onEvent(event) {
return _this.on + event;
};
/**
* @constructor
*/
var Mouse = function Mouse() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when the user clicks on an element
*
* @type {string}
*/
_this.click = 'click';
/**
* The event occurs when the user right-clicks on an element to open a context menu
*
* @type {string}
*/
_this.contextMenu = 'contextmenu';
/**
* The event occurs when the user double-clicks on an element
*
* @type {string}
*/
_this.dblClick = 'dblclick';
/**
* The event occurs when the user double-clicks on an element
*
* @type {string}
*/
_this.doubleClick = _this.dblClick;
/**
* The event occurs when the user presses a mouse button over an element
*
* @type {string}
*/
_this.mouseDown = 'mousedown';
/**
* The event occurs when the pointer is moved onto an element
*
* @type {string}
*/
_this.mouseEnter = 'mouseenter';
/**
* The event occurs when the pointer is moved out of an element
*
* @type {string}
*/
_this.mouseLeave = 'mouseleave';
/**
* The event occurs when the pointer is moving while it is over an element
*
* @type {string}
*/
_this.mouseMove = 'mousemove';
/**
* The event occurs when a user moves the mouse pointer out of an element, or out of one of its children
*
* @type {string}
*/
_this.mouseOut = 'mouseout';
/**
* The event occurs when the pointer is moved onto an element, or onto one of its children
*
* @type {string}
*/
_this.mouseOver = 'mouseover';
/**
* The event occurs when a user releases a mouse button over an element
*
* @type {string}
*/
_this.mouseUp = 'mouseup';
/**
* The event occurs when the user right-clicks on an element to open a context menu
*
* @type {string}
*/
_this.rightClick = _this.contextMenu;
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Mouse}
*/
_this.Mouse = new Mouse();
/**
* @returns {Mouse}
*/
_this.getMouse = function getMouse() {
return Mouse;
};
/**
* @constructor
*/
var Keyboard = function Keyboard() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when the user is pressing a key
*
* @type {string}
*/
_this.keyDown = 'keydown';
/**
* The event occurs when the user presses a key
*
* @type {string}
*/
_this.keyPress = 'keypress';
/**
* The event occurs when the user releases a key
*
* @type {string}
*/
_this.keyUp = 'keyup';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Keyboard}
*/
_this.Keyboard = new Keyboard();
/**
* @returns {Keyboard}
*/
_this.getKeyboard = function getKeyboard() {
return Keyboard;
};
/**
* @constructor
*/
var Frame = function Frame() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when the loading of a resource has been aborted
*
* @type {string}
*/
_this.abord = 'abord';
/**
* The event occurs before the document is about to be unloaded
*
* @type {string}
*/
_this.beforeUnload = 'beforeunload';
/**
* The event occurs when an error occurs while loading an external file
*
* @type {string}
*/
_this.error = 'error';
/**
* The event occurs when there has been changes to the anchor part of a URL
*
* @type {string}
*/
_this.hashChange = 'hashchange';
/**
* The event occurs when an object has loaded
*
* @type {string}
*/
_this.load = 'load';
/**
* The event occurs when the user navigates away from a web page
*
* @type {string}
*/
_this.pageHide = 'pagehide';
/**
* The event occurs when the user navigates to a web page
*
* @type {string}
*/
_this.pageShow = 'pageshow';
/**
* The event occurs when the document view is resized
*
* @type {string}
*/
_this.resize = 'resize';
/**
* The event occurs when an element's scrollbar is being scrolled
*
* @type {string}
*/
_this.scroll = 'scroll';
/**
* The event occurs once a page has unloaded (for <body>)
*
* @type {string}
*/
_this.unload = 'unload';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Frame}
*/
_this.Frame = new Frame();
/**
* @returns {Frame}
*/
_this.getFrame = function getFrame() {
return Frame;
};
/**
* @constructor
*/
var Drag = function Drag() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when an element is being dragged
*
* @type {string}
*/
_this.drag = 'drag';
/**
* The event occurs when the user has finished dragging an element
*
* @type {string}
*/
_this.dragEnd = 'dragend';
/**
* The event occurs when the dragged element enters the drop target
*
* @type {string}
*/
_this.dragEnter = 'dragenter';
/**
* The event occurs when the dragged element leaves the drop target
*
* @type {string}
*/
_this.dragLeave = 'dragleave';
/**
* The event occurs when the dragged element is over the drop target
*
* @type {string}
*/
_this.dragOver = 'dragover';
/**
* The event occurs when the user starts to drag an element
*
* @type {string}
*/
_this.dragStart = 'dragstart';
/**
* The event occurs when the dragged element is dropped on the drop target
*
* @type {string}
*/
_this.drop = 'drop';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Drag}
*/
_this.Drag = new Drag();
/**
* @returns {Drag}
*/
_this.getDrag = function getDrag() {
return Drag;
};
/**
* @constructor
*/
var Clipboard = function Clipboard() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when the user copies the content of an element
*
* @type {string}
*/
_this.copy = 'copy';
/**
* The event occurs when the user cuts the content of an element
*
* @type {string}
*/
_this.cut = 'cut';
/**
*
The event occurs when the user pastes some content in an element
*
* @type {string}
*/
_this.paste = 'paste';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Clipboard}
*/
_this.Clipboard = new Clipboard();
/**
* @returns {Clipboard}
*/
_this.getClipboard = function getClipboard() {
return Clipboard;
};
/**
* @constructor
*/
var Print = function Print() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when a page has started printing, or if the print dialogue box has been closed
*
* @type {string}
*/
_this.afterPrint = 'afterprint';
/**
* The event occurs when a page is about to be printed
*
* @type {string}
*/
_this.beforePrint = 'beforeprint';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Print}
*/
_this.Print = new Print();
/**
* @returns {Print}
*/
_this.getPrint = function getPrint() {
return Print;
};
/**
* @constructor
*/
var Media = function Media() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when the loading of a media is aborted
*
* @type {string}
*/
_this.abort = 'abort';
/**
* The event occurs when the browser can start playing the media (when it has buffered enough to begin)
*
* @type {string}
*/
_this.canPlay = 'canplay';
/**
* The event occurs when the browser can play through the media without stopping for buffering
*
* @type {string}
*/
_this.canPlayThrough = 'canplaythrough';
/**
* The event occurs when the duration of the media is changed
*
* @type {string}
*/
_this.durationChange = 'durationchange';
/**
* The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects)
*
* @type {string}
*/
_this.emptied = 'emptied';
/**
* The event occurs when the media has reach the end (useful for messages like "thanks for listening")
*
* @type {string}
*/
_this.ended = 'ended';
/**
* The event occurs when an error occurred during the loading of a media file
*
* @type {string}
*/
_this.error = 'error';
/**
* The event occurs when media data is loaded
*
* @type {string}
*/
_this.loadedData = 'loadeddata';
/**
* The event occurs when meta data (like dimensions and duration) are loaded
*
* @type {string}
*/
_this.loadedMetaData = 'loadedmetadata';
/**
* The event occurs when the browser starts looking for the specified media
*
* @type {string}
*/
_this.loadStart = 'loadstart';
/**
* The event occurs when the media is paused either by the user or programmatically
*
* @type {string}
*/
_this.pause = 'pause';
/**
* The event occurs when the media has been started or is no longer paused
*
* @type {string}
*/
_this.play = 'play';
/**
* The event occurs when the media is playing after having been paused or stopped for buffering
*
* @type {string}
*/
_this.playing = 'playing';
/**
* The event occurs when the browser is in the process of getting the media data (downloading the media)
*
* @type {string}
*/
_this.progress = 'progress';
/**
* The event occurs when the playing speed of the media is changed
*
* @type {string}
*/
_this.rateChange = 'ratechange';
/**
* The event occurs when the user is finished moving/skipping to a new position in the media
*
* @type {string}
*/
_this.seeked = 'seeked';
/**
* The event occurs when the user starts moving/skipping to a new position in the media
*
* @type {string}
*/
_this.seeking = 'seeking';
/**
* The event occurs when the browser is trying to get media data, but data is not available
*
* @type {string}
*/
_this.stalled = 'stalled';
/**
* The event occurs when the browser is intentionally not getting media data
*
* @type {string}
*/
_this.suspend = 'suspend';
/**
* The event occurs when the playing position has changed (like when the user fast forwards to a different point in the media)
*
* @type {string}
*/
_this.timeUpdate = 'timeupdate';
/**
* The event occurs when the volume of the media has changed (includes setting the volume to "mute")
*
* @type {string}
*/
_this.volumeChange = 'volumechange';
/**
* The event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data)
*
* @type {string}
*/
_this.waiting = 'waiting';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Media}
*/
_this.Media = new Media();
/**
* @returns {Media}
*/
_this.getMedia = function getMedia() {
return Media;
};
/**
* @constructor
*/
var Animation = function Animation() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when a CSS animation has completed
*
* @type {string}
*/
_this.animationEnd = 'animationend';
/**
* The event occurs when a CSS animation is repeated
*
* @type {string}
*/
_this.animationIteration = 'animationiteration';
/**
* The event occurs when a CSS animation has started
*
* @type {string}
*/
_this.animationStart = 'animationstart';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Animation}
*/
_this.Animation = new Animation();
/**
* @returns {Animation}
*/
_this.getAnimation = function getAnimation() {
return Animation;
};
/**
* @constructor
*/
var Transition = function Transition() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when a CSS transition has completed
*
* @type {string}
*/
_this.transitionEnd = 'transitionend';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Transition}
*/
_this.Transition = new Transition();
/**
* @returns {Transition}
*/
_this.getTransition = function getTransition() {
return Transition;
};
/**
* @constructor
*/
var ServerSent = function ServerSent() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when an error occurs with the event source
*
* @type {string}
*/
_this.error = 'error';
/**
* The event occurs when a message is received through the event source
*
* @type {string}
*/
_this.message = 'message';
/**
* The event occurs when a connection with the event source is opened
*
* @type {string}
*/
_this.open = 'open';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {ServerSent}
*/
_this.ServerSent = new ServerSent();
/**
* @returns {ServerSent}
*/
_this.getServerSent = function getServerSent() {
return ServerSent;
};
/**
* @constructor
*/
var Misc = function Misc() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when a message is received through or from an object (WebSocket, Web Worker, Event Source or a child frame or a parent window)
*
* @type {string}
*/
_this.message = 'message';
/**
* Deprecated. Use the on wheel event instead on mouse wheel
*
* @type {string}
*/
_this.mouseWheel = 'mousewheel';
/**
* The event occurs when the browser starts to work offline
*
* @type {string}
*/
_this.offline = 'offline';
/**
* The event occurs when the browser starts to work online
*
* @type {string}
*/
_this.online = 'online';
/**
* The event occurs when the window's history changes
*
* @type {string}
*/
_this.popState = 'popstate';
/**
* The event occurs when a <menu> element is shown as a context menu
*
* @type {string}
*/
_this.show = 'show';
/**
* The event occurs when a Web Storage area is updated
*
* @type {string}
*/
_this.storage = 'storage';
/**
* The event occurs when the user opens or closes the <details> element
*
* @type {string}
*/
_this.toggle = 'toggle';
/**
* The event occurs when the mouse wheel rolls up or down over an element
*
* @type {string}
*/
_this.wheel = 'wheel';
};
/**
* singleton
* work-around for visibility of object-content-value in js-api
*
* @type {Misc}
*/
_this.Misc = new Misc();
/**
* @returns {Misc}
*/
_this.getMisc = function getMisc() {
return Misc;
};
/**
* @constructor
*/
var Touch = function Touch() {
/* keyword this in this class context */
var _this = this;
/**
* The event occurs when the touch is interrupted
*
* @type {string}
*/
_this.touchCancel = 'touchcancel';
/**
* The event occurs when a finger is removed from a touch screen
*
* @type {string}
*/
_this.touchEnd = 'touchend';
/**
* The event occurs when a finger is dragged across the screen
*
* @type {string}
*/
_this.touchMove = 'touchmove';
/**
* The event occurs when a finger is placed on a touch screen
*
* @type {string}
*/
_this.touchStart = 'touchstart';
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Touch}
*/
_this.Touch = new Touch();
/**
* @returns {Touch}
*/
_this.getTouch = function getTouch() {
return Touch;
};
};
/**
* singleton
* @type {Event}
*/
_this.Event = new Event();
/**
* @returns {Event}
*/
_this.getEvent = function getEvent() {
return Event;
};
/**
* @constructor
*/
var Css = function Css() {
/* keyword this in this class context */
var _this = this;
/**
* @constructor
*/
var Identifier = function Identifier() {
/* keyword this in this class context */
var _this = this;
/**
* @type {string}
*/
_this.class = '.';
/**
* @type {string}
*/
_this.id = '#';
/**
* @type {string}
*/
_this.tag = '';
};
/**
* @type {Identifier}
*/
_this.Identifier = new Identifier();
/**
* @returns {Identifier}
*/
_this.getIdentifier = function getIdentifier() {
return Identifier;
};
/**
* @param {string} selector
* @returns {string}
*/
_this.getClassSelector = function getClassSelector(selector) {
return _this.getSelector(_this.Identifier.class, selector);
};
/**
* @param {string} selector
* @returns {string}
*/
_this.getIdSelector = function getIdSelector(selector) {
return _this.getSelector(_this.Identifier.id, selector);
};
/**
* @param {string} selector
* @returns {string}
*/
_this.getTagSelector = function getTagSelector(selector) {
return _this.getSelector(_this.Identifier.tag, selector);
};
/**
* @param {string} attributeName
* @param {string} attributeValue
* @returns {string}
*/
_this.getAttributeSelector = function getAttributeSelector(attributeName, attributeValue) {
return '[' + attributeName + '="' + attributeValue + '"]';
};
/**
* @param {string} identifier
* @param {string} selector
* @returns {string}
*/
_this.getSelector = function getSelector(identifier, selector) {
return identifier + selector;
};
/**
* @todo all tags
* @todo html class
* @constructor
*/
var Tag = function Tag() {
/* keyword this in this class context */
var _this = this;
/**
* @type {string}
*/
_this.a = 'a';
/**
* @type {string}
*/
_this.anchor = _this.a;
/**
* @type {string}
*/
_this.div = 'div';
/**
* @type {string}
*/
_this.division = _this.div;
/**
* @type {HTMLDocument}
*/
_this.document = document;
/**
* @type {string}
*/
_this.p = 'p';
/**
* @type {string}
*/
_this.paragraph = _this.p;
/**
* @type {string}
*/
// _this.row;
/**
* @type {string}
*/
_this.span = 'span';
/**
* @type {string}
*/
_this.table = 'table';
/**
* @type {string}
*/
_this.td = 'td';
/**
* @type {string}
*/
_this.cell = _this.td;
/**
* @type {string}
*/
_this.tr = 'tr';
/**
* @type {string}
*/
_this.row = _this.tr;
/**
* @type {Window}
*/
_this.window = window;
};
/**
* singleton
* @type {Tag}
*/
_this.Tag = new Tag();
/**
* @returns {Tag}
*/
_this.getTag = function getTag() {
return Tag;
};
};
/**
* singleton
* @type {Css}
*/
_this.Css = new Css();
/**
* @returns {Css}
*/
_this.getCss = function getCss() {
return Css;
};
/**
* @type {DOMHandler&Css}
* @constructor
*/
var DOMHandler = function DOMHandler() {
/* keyword this in this class context */
var _this = this;
/* extends simple inheritance */
// Event.call(_this);
/* extends simple inheritance */
// Css.call(_this);
/**
* @type {Event}
*/
_this.Event = _thisNamespace.Event;
/**
* @type {Css}
*/
_this.Css = _thisNamespace.Css;
/**
* @param {string} selector
* @returns {*|jQuery|HTMLElement}
*/
_this.selectDOMElement = function selectDOMElement(selector) {
return jQuery(selector);
};
};
/**
* @type {DOMHandler&Event}
* @type {DOMHandler}
*/
_this.DOMHandler = new DOMHandler();
/**
* @returns {DOMHandler}
*/
_this.getDOMHandler = function getDOMHandler() {
return DOMHandler;
};
/**
* @constructor
*/
var Location = function Location() {
/* keyword this in this class context */
var _this = this;
/**
* Sets or returns the anchor part (#) of a URL
*
* @returns {string}
*/
_this.getHash = function getHash() {
return location.hash;
};
/**
* Sets or returns the anchor part (#) of a URL
*
* @param {string} hash
*/
_this.setHash = function setHash(hash) {
location.hash = hash;
};
/**
* Sets or returns the hostname and port number of a URL
*
* @returns {string}
*/
_this.getHost = function getHost() {
return location.host;
};
/**
* Sets or returns the hostname and port number of a URL
*
* @param {string} host
*/
_this.setHost = function setHost(host) {
location.host = host;
};
/**
* Sets or returns the hostname of a URL
*
* @returns {string}
*/
_this.getHostname = function getHostname() {
return location.hostname;
};
/**
* Sets or returns the hostname of a URL
*
* @param {string} hostname
*/
_this.setHostname = function setHostname(hostname) {
location.hostname = hostname;
};
/**
* Sets or returns the entire URL
*
* @returns {string}
*/
_this.getHref = function getHref() {
return location.href;
};
/**
* Sets or returns the entire URL
*
* @param {string} href
*/
_this.setHref = function setHref(href) {
location.href = href;
};
/**
* Returns the protocol, hostname and port number of a URL
*
* @returns {string}
*/
_this.getOrigin = function getOrigin() {
return location.origin;
};
/**
* Returns the protocol, hostname and port number of a URL
*
* @param {string} origin
*/
_this.setOrigin = function setOrigin(origin) {
location.origin = origin;
};
/**
* Sets or returns the path name of a URL
*
* @returns {string}
*/
_this.getPathname = function getPathname() {
return location.pathname;
};
/**
* Sets or returns the path name of a URL
*
* @param {string} pathname
*/
_this.setPathname = function setPathname(pathname) {
location.pathname = pathname;
};
/**
* Sets or returns the port number of a URL
*
* @returns {string}
*/
_this.getPort = function getPort() {
return location.port;
};
/**
* Sets or returns the port number of a URL
*
* @param {string} port
*/
_this.setPort = function setPort(port) {
location.port = port;
};
/**
* Sets or returns the protocol of a URL
*
* @returns {string}
*/
_this.getProtocol = function getProtocol() {
return location.protocol;
};
/**
* Sets or returns the protocol of a URL
*
* @param {string} protocol
*/
_this.setProtocol = function setProtocol(protocol) {
location.protocol = protocol;
};
/**
* Sets or returns the query string part of a URL
*
* @returns {string}
*/
_this.getSearch = function getSearch() {
return location.search;
};
/**
* Sets or returns the query string part of a URL
*
* @param {string} search
*/
_this.setSearch = function setSearch(search) {
location.search = search;
};
/**
* Loads a new document
*
* @param {string} url
*/
_this.assign = function assign(url) {
location.assign(url);
};
/**
* Reloads the current document
*
* false - Default. Reloads the current page from the cache.
* true - Reloads the current page from the server
*
* @param {boolean} forceGet
*/
_this.reload = function reload(forceGet) {
location.reload(forceGet);
};
/**
* Replaces the current document with a new one
*
* @param {string} url
*/
_this.replace = function replace(url) {
location.replace(url);
};
};
/**
* singleton
*
* work-around for visibility of object-content-value in js-api
*
* @type {Location}
*/
_this.Location = new Location();
/**
* @returns {Location}
*/
_this.getLocation = function getLocation() {
return Location;
};
};
|
/* global describe */
/* global it */
'use strict';
var Twitter = require('../index');
var optional = require('optional');
var optConfig = {consumer_key: 'random', consumer_secret: 'random', token: 'random', token_secret: 'random'};
var config = optional('./config.json') || optConfig;
var should = require('should');
describe('Twitter.Search Functions:', function () {
describe('Search loading', function () {
it('should create the Object', function () {
var search = new Twitter.Search(config);
search.should.be.an.instanceOf(Object);
});
});
describe('Search.query()', function () {
var search = new Twitter.Search(config);
it('should return an error about missing q in params', function (done) {
search.query({}, function (err) {
should.exist(err);
done();
});
});
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:52b68f56477ca93f7a4b6a90eb826ee92f4e827530b30a698d4131d71cb9bcea
size 664
|
var Readable = require('stream').Readable;
var readable = new Readable();
readable._read = function() {
setTimeout(function() {
// if (readable.readable) {
readable.push(new Buffer('some buffer'));
// }
}, 100);
};
['end', 'finish', 'close', 'data', 'error'].forEach(function(event) {
readable.on(event, function() {
if (event == 'data') {
process.stdout.write('D');
}
else {
console.log('\nevent: ', event, arguments);
}
});
});
setTimeout(function() {
readable.emit('error', new Error('hey'));
}, 2e3);
|
(function() {
/*
* Module dependencies
*/
var Getter = Completed.module.get("Getter");
var KeyMap = Completed.module.get("KeyMap");
var $ = Completed.module.get("$");
var console = Completed.module.get("Console");
/*
* Main
*/
var newCompleted = function(inputSelectors, userOptions) {
// options
userOptions = userOptions || {};
// internal values
this.doms = $(inputSelectors);
this.inputSelectors = inputSelectors;
this.autoCompleteData = userOptions.data || null;
this.autoCompleteDataSrc = userOptions.dataSrc || "public/data/autocomplete.json";
this.autoCompleteSearchTimer = null;
this.autoCompleteSearchDelay = userOptions.delay || 10;
this.autoCompleteWrapperClass = "autocomplete-wrapper";
this.autoCompleteListClass = "autocomplete-list"
this.autoCompleteOpening = false;
this.autoCompleteMatchedData = [];
// constants
this.AC_MAX_LIST_COUNT = 5;
this.AC_LIST_OFFSET = 30;
this.AC_WRAPPER_OFFSET = 5;
// start point
this.init();
};
newCompleted.prototype = {
init : function() {
// get data first
this.getAutocompleteData(function() {
this.createAutocompleteWrapper();
this.bindAutocompleteWrapperMouseEvent();
this.bindInputSearchEvent();
});
},
createAutocompleteWrapper : function() {
if ( $("." + this.autoCompleteWrapperClass).length === 0 ) {
var wrapperDiv = document.createElement("div");
wrapperDiv.className = this.autoCompleteWrapperClass + " close";
$("body")[0].appendChild(wrapperDiv);
}
},
createAutocompleteList : function() {
var fragment = document.createDocumentFragment(),
matches = this.autoCompleteMatchedData;
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i],
eachListDiv = document.createElement("div");
eachListDiv.innerHTML = match;
eachListDiv.className = this.autoCompleteListClass;
// select the first one
if (i === 0) {
eachListDiv.className += " selected";
}
fragment.appendChild(eachListDiv);
}
$("." + this.autoCompleteWrapperClass)[0].appendChild(fragment);
},
removeAutocompleteList : function() {
var $wrapper = $("." + this.autoCompleteWrapperClass)[0];
while($wrapper.firstChild) {
$wrapper.removeChild($wrapper.firstChild);
}
},
showAutocompleteWrapper : function() {
if (!this.autoCompleteOpening) {
$.removeClass("." + this.autoCompleteWrapperClass, "close");
}
this.autoCompleteOpening = true;
},
hideAutocompleteWrapper : function() {
if (this.autoCompleteOpening) {
$.addClass("." + this.autoCompleteWrapperClass, "close");
}
this.autoCompleteOpening = false;
},
repositionAutocompleteWrapper : function(dom) {
var rect = dom.getBoundingClientRect(),
$wrapper = $("." + this.autoCompleteWrapperClass)[0];
$wrapper.style.top = parseInt(rect.top + rect.height + this.AC_WRAPPER_OFFSET, 10) + "px";
$wrapper.style.left = parseInt(rect.left, 10) + "px";
},
scrollAutocompleteWrapper : function(direction) {
var $wrapper = $("." + this.autoCompleteWrapperClass)[0],
$selectedListItem = $("." + this.autoCompleteListClass + ".selected")[0];
if ($selectedListItem.offsetTop >= $wrapper.scrollTop &&
$selectedListItem.offsetTop <= $wrapper.scrollTop + (this.AC_MAX_LIST_COUNT - 1) * this.AC_LIST_OFFSET) {
// we won't change the scrollTop if the cursor is located in this zone
}
else {
if (direction === "UP") {
$wrapper.scrollTop -= this.AC_LIST_OFFSET;
}
else {
$wrapper.scrollTop += this.AC_LIST_OFFSET;
}
}
},
getAutocompleteData : function(callback) {
var that = this;
// we can pass autoCompleteData from userOptions directly or fetch from a link
if ( this.autoCompleteData === null ) {
Getter(this.autoCompleteDataSrc, function(data) {
// TODO
// check data here
var parsedData = JSON.parse(data);
that.autoCompleteData = parsedData["autoCompleteData"];
callback.call(that);
});
}
else {
callback.call(that);
}
},
bindAutocompleteWrapperMouseEvent : function() {
var that = this,
$wrapper = $("." + this.autoCompleteWrapperClass)[0];
// XXX
// Because Event trigger order : mousedown > blur > click,
// we have to make sure to get focus input before blur out.
$.on("mousedown", $wrapper, function(e) {
// Delegate
if (that.isAutocompleteList(e.target)) {
that.selectMatchedData();
that.hideAutocompleteWrapper();
}
});
$.on("mouseover", $wrapper, function(e) {
$.removeClass("." + that.autoCompleteListClass, "selected");
if (that.isAutocompleteList(e.target)) {
$.addClass(e.target, "selected");
}
});
},
bindInputSearchEvent : function() {
var that = this;
for (var i = 0, len = this.doms.length; i < len; i++) {
var dom = this.doms[i];
$.on("keydown", dom, function(e) {
if (KeyMap[e.which] === "ENTER") {
that.selectMatchedData();
that.hideAutocompleteWrapper();
}
else if (KeyMap[e.which] === "UP") {
that.moveAutocompleteSelector("UP");
e.preventDefault()
}
else if (KeyMap[e.which] === "DOWN") {
that.moveAutocompleteSelector("DOWN");
e.preventDefault()
}
else if (KeyMap[e.which] === "ESC") {
that.hideAutocompleteWrapper();
e.preventDefault()
}
else {
window.clearTimeout(that.autoCompleteSearchTimer);
that.autoCompleteSearchTimer = window.setTimeout(function() {
var userInputValue = $.trim(dom.value);
that.autoCompleteMatchedData = that.searchPossibleMatches(userInputValue);
if (that.isMatched()) {
// remove them first
that.removeAutocompleteList();
that.createAutocompleteList();
that.repositionAutocompleteWrapper(dom);
that.showAutocompleteWrapper();
}
else {
that.hideAutocompleteWrapper();
}
}, that.autoCompleteSearchDelay);
}
});
$.on("focus", dom, function(e) {
// because they are still left in the DOM tree
if (that.isMatched()) {
that.repositionAutocompleteWrapper(dom);
that.showAutocompleteWrapper();
}
});
$.on("blur", dom, function(e) {
that.hideAutocompleteWrapper();
});
}
},
searchPossibleMatches : function(userInputValue) {
if (userInputValue.length === 0) {
return [];
}
var matches = [],
regex = new RegExp("^" + userInputValue, "i");
for (var i = 0, len = this.autoCompleteData.length; i < len; i++) {
var currentAcData = this.autoCompleteData[i];
if (regex.test(currentAcData)) {
matches.push(currentAcData);
}
}
return matches;
},
moveAutocompleteSelector : function(direction) {
var siblings = $.siblings("." + this.autoCompleteListClass, "." + this.autoCompleteListClass + ".selected");
// make sure we have siblings so that we can move selector
if (siblings.prev && direction === "UP" || siblings.next && direction === "DOWN" ) {
$.removeClass("." + this.autoCompleteListClass, "selected");
if (direction === "UP") {
$.addClass(siblings.prev, "selected");
}
else {
$.addClass(siblings.next, "selected");
}
// then scroll
this.scrollAutocompleteWrapper(direction);
}
},
selectMatchedData : function() {
// make sure we can select data
if (!this.autoCompleteOpening) {
return;
}
var $focusedInput = $(this.inputSelectors + ":focus")[0],
$selectedListItem = $("." + this.autoCompleteListClass + ".selected")[0],
matchedData = $selectedListItem.innerHTML;
$focusedInput.value = matchedData;
},
isMatched : function() {
return (this.autoCompleteMatchedData.length > 0);
},
isAutocompleteList : function(dom) {
return (dom && $.hasClass(dom, this.autoCompleteListClass));
}
};
window.Completed = newCompleted;
}());
|
var express = require('express'),
app = module.exports = express();
app.set('views', __dirname);
app.on('mount', function () {
app.locals.mountpath = app.route;
});
function auth(req, res, next) {
if (req.body.username === 'pedro' && req.body.passwd === 'root') {
req.session.user = 'pedro';
return next();
}
res.render('index', {
msg: 'bad login'
});
}
app.get('/', function (req, res) {
res.render('index');
});
app.post('/', auth, function (req, res) {
res.redirect(req.query.r);
});
|
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Powers', {
ID: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
Name: {
type: DataTypes.STRING,
allowNull: false
},
GroupName: {
type: DataTypes.STRING,
allowNull: true
},
Title: {
type: DataTypes.STRING,
allowNull: true
},
Remark: {
type: DataTypes.STRING,
allowNull: true
}
}, {
tableName: 'Powers'
});
};
|
import React from "react";
import {Link} from "react-router";
export default React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render: function () {
let isActive = this.context.router.isActive(this.props.to, true),
className = isActive ? "active" : "";
return (
<li className={className}>
<Link {...this.props}>
{this.props.children}
</Link>
</li>
);
}
});
|
import {INCEREMENT, INCEREMENTX, DECEREMENT, SEND_REQUEST, GOT_REQUEST, UPDATE_USER_NAME} from './mutation-types'
export default {
[INCEREMENT] (state) {
state.count++
},
[SEND_REQUEST] (state) {
state.isRequesting = true
},
[GOT_REQUEST] (state) {
state.isRequesting = false
},
[INCEREMENTX] (state, x) {
state.count += x
},
[DECEREMENT] (state) {
state.count--
},
[UPDATE_USER_NAME] (state, name) {
state.user.name = name
}
}
|
const path = require('path');
const webpack = require('webpack');
// env
const buildDirectory = './dist/';
module.exports = {
entry: './lib/main.jsx',
devServer: {
hot: true,
inline: true,
port: 7700,
historyApiFallback: true,
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(buildDirectory),
filename: 'app.js',
publicPath: 'http://localhost:7700/dist',
},
externals: {
'cheerio': 'window',
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true,
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0'],
},
}],
},
plugins: [],
};
|
import { assign, swipeShouldReset } from '../util/util';
import { GESTURE_GO_BACK_SWIPE } from '../gestures/gesture-controller';
import { SlideEdgeGesture } from '../gestures/slide-edge-gesture';
import { NativeRafDebouncer } from '../util/debouncer';
export class SwipeBackGesture extends SlideEdgeGesture {
constructor(_nav, element, gestureCtlr, options) {
super(element, assign({
direction: 'x',
maxEdgeStart: 75,
zone: false,
threshold: 0,
debouncer: new NativeRafDebouncer(),
gesture: gestureCtlr.createGesture({
name: GESTURE_GO_BACK_SWIPE,
priority: 20,
disableScroll: true
})
}, options));
this._nav = _nav;
}
canStart(ev) {
return (this._nav.canSwipeBack() &&
super.canStart(ev));
}
onSlideBeforeStart(ev) {
this._nav.swipeBackStart();
}
onSlide(slide, ev) {
ev.preventDefault();
ev.stopPropagation();
let stepValue = (slide.distance / slide.max);
this._nav.swipeBackProgress(stepValue);
}
onSlideEnd(slide, ev) {
const currentStepValue = (slide.distance / slide.max);
const isResetDirecction = slide.velocity < 0;
const isMovingFast = Math.abs(slide.velocity) > 0.4;
const isInResetZone = Math.abs(slide.delta) < Math.abs(slide.max) * 0.5;
const shouldComplete = !swipeShouldReset(isResetDirecction, isMovingFast, isInResetZone);
this._nav.swipeBackEnd(shouldComplete, currentStepValue);
}
}
//# sourceMappingURL=swipe-back.js.map
|
module.exports = {
"env": {
"browser": false,
"node": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"plugins": [
],
"rules": {
"object-curly-spacing" : [2, "always"],
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
|
/**
* Livechat Page Visited model
*/
class LivechatPageVisited extends CaoLiao.models._Base {
constructor() {
super();
this._initModel('livechat_page_visited');
this.tryEnsureIndex({ 'token': 1 });
this.tryEnsureIndex({ 'ts': 1 });
// keep history for 1 month if the visitor does not register
this.tryEnsureIndex({ 'expireAt': 1 }, { sparse: 1, expireAfterSeconds: 0 });
}
saveByToken(token, pageInfo) {
// keep history of unregistered visitors for 1 month
var keepHistoryMiliseconds = 2592000000;
return this.insert({
token: token,
page: pageInfo,
ts: new Date(),
expireAt: new Date().getTime() + keepHistoryMiliseconds
});
}
findByToken(token) {
return this.find({ token: token }, { sort : { ts: -1 }, limit: 20 });
}
keepHistoryForToken(token) {
return this.update({
token: token,
expireAt: {
$exists: true
}
}, {
$unset: {
expireAt: 1
}
}, {
multi: true
});
}
}
CaoLiao.models.LivechatPageVisited = new LivechatPageVisited();
|
Ext.define('App.view.import.departement', {
extend: 'Ext.panel.Panel',
alias: 'widget.importdepartement',
bodyPadding: 10,
layout: { type: 'vbox', align: 'stretch'},
items: [
{ xtype: 'form', bodyPadding: 10, autoScroll: true, flex: 2, title: 'Form departement', layout: { type: 'hbox', align: 'stretch'},
items: [
{ xtype: 'container', flex: 3, bodyPadding: 10, layout: 'anchor', defaults: { anchor: '95%', allowBlank: false }, items: [
{ xtype: 'filefield', fieldLabel: 'File Excel', name: 'file'},
{ xtype: 'textfield', fieldLabel: 'Additional Information', name: 'info', allowBlank: true},
]},
{ xtype: 'container', flex: 1, layout: 'fit', items: [
{ xtype: 'button', text: 'Download Sample', iconCls: 'excel', itemId: 'download' }
]}
],
bbar: [
{ text: 'Help', iconCls: 'help'},
'->',
{ text: 'Upload', iconCls: 'excel', itemId: 'upload', formBind: true}
]
},
{ xtype: 'container', height: 10 },
{ xtype: 'container', flex: 3, layout: 'fit', items: [
{xtype: 'grid', title: 'Status ', itemId: 'griddept',
store: Ext.create('Ext.data.Store', { fields: ['id', 'name', 'status'] }),
columns: [
{xtype: 'rownumberer'},
{header: 'Id', dataIndex: 'id', flex: 1 },
{header: 'Name', dataIndex: 'name', flex: 2 },
{header: 'Status', dataIndex: 'status', flex: 3,
renderer: function (v) {
return (v == 0) ? '<span style="color:green">OK</span>' : '<span style="color:red">Fail, has Already on System</span>';
} }
]
}
]}
]
})
|
goog.provide('gmf.profileComponent');
goog.require('gmf');
goog.require('ngeo.CsvDownload');
goog.require('ngeo.FeatureOverlayMgr');
/** @suppress {extraRequire} */
goog.require('ngeo.profileDirective');
goog.require('ol.Feature');
goog.require('ol.Overlay');
goog.require('ol.geom.LineString');
goog.require('ol.geom.Point');
goog.require('ol.obj');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Style');
ngeo.module.value('gmfProfileTemplateUrl',
/**
* @param {!angular.JQLite} $element Element.
* @param {!angular.Attributes} $attrs Attributes.
* @return {string} Template.
*/
($element, $attrs) => {
const templateUrl = $attrs['gmfProfileTemplateurl'];
return templateUrl !== undefined ? templateUrl :
`${gmf.baseTemplateUrl}/profile.html`;
});
/**
* @param {!angular.JQLite} $element Element.
* @param {!angular.Attributes} $attrs Attributes.
* @param {!function(!angular.JQLite, !angular.Attributes): string} gmfProfileTemplateUrl Template function.
* @return {string} Template URL.
* @ngInject
*/
function gmfProfileTemplateUrl($element, $attrs, gmfProfileTemplateUrl) {
return gmfProfileTemplateUrl($element, $attrs);
}
/**
* Provide a component that display a profile panel. This profile use the given
* LineString geometry to request the c2cgeoportal profile.json service. The
* raster used in the request are the keys of the 'linesconfiguration' object.
* The 'map' attribute is optional and are only used to display on the map the
* information that concern the hovered point (in the profile and on the map)
* of the line.
* This profile relies on the ngeo.profile (d3) and ngeo.ProfileComponent.
*
* Example:
*
* <gmf-profile
* gmf-profile-active="ctrl.profileActive"
* gmf-profile-line="ctrl.profileLine"
* gmf-profile-map="::ctrl.map"
* gmf-profile-linesconfiguration="::ctrl.profileLinesconfiguration">
* </gmf-profile>
*
*
* @htmlAttribute {boolean} gmf-profile-active Active the component.
* @htmlAttribute {ol.geom.LineString} gmf-profile-line The linestring geometry
* to use to draw the profile.
* @htmlAttribute {ol.Map?} gmf-profile-map An optional map.
* @htmlAttribute {Object.<string, gmfx.ProfileLineConfiguration>}
* gmf-profile-linesconfiguration The configuration of the lines. Each keys
* will be used to request elevation layers.
* @htmlAttribute {ol.style.Style?} gmf-profile-hoverpointstyle Optional style
* for the 'on Hover' point on the line.
* @htmlAttribute {number?} gmf-profile-numberofpoints Optional maximum limit of
* points to request. Default to 100.
* @htmlAttribute {Object.<string, *>?} gmf-profile-options Optional options
* object like {@link ngeox.profile.ProfileOptions} but without any
* mandatory value. Will be passed to the ngeo profile component. Providing
* 'linesConfiguration', 'distanceExtractor', hoverCallback, outCallback
* or i18n will override native gmf profile values.
*
* @ngdoc component
* @ngname gmfProfile
*/
gmf.profileComponent = {
controller: 'GmfProfileController as ctrl',
bindings: {
'active': '=gmfProfileActive',
'line': '=gmfProfileLine',
'getMapFn': '&?gmfProfileMap',
'getLinesConfigurationFn': '&gmfProfileLinesconfiguration',
'getHoverPointStyleFn': '&?gmfProfileHoverpointstyle',
'getNbPointsFn': '&?gmfProfileNumberofpoints',
'getOptionsFn': '&?gmfProfileOptions'
},
templateUrl: gmfProfileTemplateUrl
};
gmf.module.component('gmfProfile', gmf.profileComponent);
/**
* @param {angular.Scope} $scope Angular scope.
* @param {angular.$http} $http Angular http service.
* @param {angular.JQLite} $element Element.
* @param {angular.$filter} $filter Angular filter
* @param {angularGettext.Catalog} gettextCatalog Gettext catalog.
* @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr Feature overlay
* manager.
* @param {string} gmfProfileJsonUrl URL of GMF service JSON profile.
* @param {ngeo.CsvDownload} ngeoCsvDownload CSV Download service.
* @constructor
* @private
* @ngInject
* @ngdoc Controller
* @ngname GmfProfileController
*/
gmf.ProfileController = function($scope, $http, $element, $filter,
gettextCatalog, ngeoFeatureOverlayMgr, gmfProfileJsonUrl,
ngeoCsvDownload) {
/**
* @type {angular.Scope}
* @private
*/
this.$scope_ = $scope;
/**
* @type {angular.$http}
* @private
*/
this.$http_ = $http;
/**
* @type {angular.JQLite}
* @private
*/
this.$element_ = $element;
/**
* @type {angular.$filter}
* @export
*/
this.$filter_ = $filter;
/**
* @type {angularGettext.Catalog}
* @private
*/
this.gettextCatalog_ = gettextCatalog;
/**
* @type {ngeo.FeatureOverlay}
* @private
*/
this.pointHoverOverlay_ = ngeoFeatureOverlayMgr.getFeatureOverlay();
/**
* @type {string}
* @private
*/
this.gmfProfileJsonUrl_ = gmfProfileJsonUrl;
/**
* @type {ngeo.CsvDownload}
* @private
*/
this.ngeoCsvDownload_ = ngeoCsvDownload;
/**
* @type {ol.Map}
* @private
*/
this.map_ = null;
/**
* @type {?Object<string, !gmfx.ProfileLineConfiguration>}
* @private
*/
this.linesConfiguration_ = null;
/**
* @type {!Array.<string>}
* @private
*/
this.layersNames_ = [];
/**
* @type {number}
* @private
*/
this.nbPoints_ = 100;
/**
* @type {ol.geom.LineString}
* @export
*/
this.line;
/**
* @type {Array.<Object>}
* @export
*/
this.profileData = [];
/**
* @type {gmfx.ProfileHoverPointInformations}
* @export
*/
this.currentPoint = {
coordinate: undefined,
distance: undefined,
elevations: {},
xUnits: undefined,
yUnits: undefined
};
/**
* Distance to highlight on the profile. (Property used in ngeo.Profile.)
* @type {number}
* @export
*/
this.profileHighlight = -1;
/**
* Overlay to show the measurement.
* @type {ol.Overlay}
* @private
*/
this.measureTooltip_ = null;
/**
* The measure tooltip element.
* @type {Element}
* @private
*/
this.measureTooltipElement_ = null;
/**
* @type {ol.Feature}
* @private
*/
this.snappedPoint_ = new ol.Feature();
this.pointHoverOverlay_.addFeature(this.snappedPoint_);
/**
* @type {ngeox.profile.I18n}
* @private
*/
this.profileLabels_ = {
xAxis: gettextCatalog.getString('Distance'),
yAxis: gettextCatalog.getString('Elevation')
};
/**
* @type {?ngeox.profile.ProfileOptions}
* @export
*/
this.profileOptions = null;
/**
* @type {boolean}
* @export
*/
this.active = false;
/**
* @type {ol.EventsKey}
* @private
*/
this.pointerMoveKey_;
/**
* @type {boolean}
* @export
*/
this.isErrored = false;
// Watch the active value to activate/deactive events listening.
$scope.$watch(
() => this.active,
(newValue, oldValue) => {
if (oldValue !== newValue) {
this.updateEventsListening_();
}
});
// Watch the line to update the profileData (data for the chart).
$scope.$watch(
() => this.line,
(newLine, oldLine) => {
if (oldLine !== newLine) {
this.update_();
}
});
this.updateEventsListening_();
};
/**
* Init the controller
*/
gmf.ProfileController.prototype.$onInit = function() {
this.map_ = this['getMapFn'] ? this['getMapFn']() : null;
this.nbPoints_ = this['getNbPointsFn'] ? this['getNbPointsFn']() : 100;
let hoverPointStyle;
const hoverPointStyleFn = this['getHoverPointStyleFn'];
if (hoverPointStyleFn) {
hoverPointStyle = hoverPointStyleFn();
goog.asserts.assertInstanceof(hoverPointStyle, ol.style.Style);
} else {
hoverPointStyle = new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({color: '#ffffff'}),
radius: 3
})
});
}
this.pointHoverOverlay_.setStyle(hoverPointStyle);
const linesConfiguration = this['getLinesConfigurationFn']();
goog.asserts.assertInstanceof(linesConfiguration, Object);
this.linesConfiguration_ = linesConfiguration;
for (const name in this.linesConfiguration_) {
// Keep an array of all layer names.
this.layersNames_.push(name);
// Add generic zExtractor to lineConfiguration object that doesn't have one.
const lineConfig = this.linesConfiguration_[name];
if (!lineConfig.zExtractor) {
this.linesConfiguration_[name].zExtractor = this.getZFactory_(name);
}
}
this.profileOptions = /** @type {ngeox.profile.ProfileOptions} */ ({
linesConfiguration: this.linesConfiguration_,
distanceExtractor: this.getDist_,
hoverCallback: this.hoverCallback_.bind(this),
outCallback: this.outCallback_.bind(this),
i18n: this.profileLabels_
});
const optionsFn = this['getOptionsFn'];
if (optionsFn) {
const options = optionsFn();
goog.asserts.assertObject(options);
ol.obj.assign(this.profileOptions, options);
}
};
/**
* @private
*/
gmf.ProfileController.prototype.update_ = function() {
this.isErrored = false;
if (this.line) {
this.getJsonProfile_();
} else {
this.profileData = [];
}
this.active = !!this.line;
};
/**
* @private
*/
gmf.ProfileController.prototype.updateEventsListening_ = function() {
if (this.active && this.map_ !== null) {
this.pointerMoveKey_ = ol.events.listen(this.map_, 'pointermove',
this.onPointerMove_.bind(this));
} else {
ol.Observable.unByKey(this.pointerMoveKey_);
}
};
/**
* @param {ol.MapBrowserPointerEvent} e An ol map browser pointer event.
* @private
*/
gmf.ProfileController.prototype.onPointerMove_ = function(e) {
if (e.dragging || !this.line) {
return;
}
const coordinate = this.map_.getEventCoordinate(e.originalEvent);
const closestPoint = this.line.getClosestPoint(coordinate);
// compute distance to line in pixels
const eventToLine = new ol.geom.LineString([closestPoint, coordinate]);
const pixelDist = eventToLine.getLength() / this.map_.getView().getResolution();
if (pixelDist < 16) {
this.profileHighlight = this.getDistanceOnALine_(closestPoint, this.line);
} else {
this.profileHighlight = -1;
}
this.$scope_.$apply();
};
/**
* Return the distance between the beginning of the line and the given point.
* The point must be on the line. If not, this function will return the total
* length of the line.
* @param {ol.Coordinate} pointOnLine A point on the given line.
* @param {ol.geom.LineString} line A line.
* @return {number} A distance.
* @private
*/
gmf.ProfileController.prototype.getDistanceOnALine_ = function(pointOnLine,
line) {
let segment;
let distOnLine = 0;
const fakeExtent = [
pointOnLine[0] - 0.5,
pointOnLine[1] - 0.5,
pointOnLine[0] + 0.5,
pointOnLine[1] + 0.5
];
this.line.forEachSegment((firstPoint, lastPoint) => {
segment = new ol.geom.LineString([firstPoint, lastPoint]);
// Is the pointOnLine on this swegement ?
if (segment.intersectsExtent(fakeExtent)) {
// If the closestPoint is on the line, add the distance between the first
// point of this segment and the pointOnLine.
segment.setCoordinates([firstPoint, pointOnLine]);
return distOnLine += segment.getLength(); // Assign value and break;
} else {
// Do the sum of the length of each eventual previous segment.
distOnLine += segment.getLength();
}
});
return distOnLine;
};
/**
* @param {Object} point Point.
* @param {number} dist distance on the line.
* @param {string} xUnits X units label.
* @param {Object.<string, number>} elevationsRef Elevations references.
* @param {string} yUnits Y units label.
* @private
*/
gmf.ProfileController.prototype.hoverCallback_ = function(point, dist, xUnits,
elevationsRef, yUnits) {
// Update information point.
let ref;
const coordinate = [point.x, point.y];
for (ref in elevationsRef) {
this.currentPoint.elevations[ref] = elevationsRef[ref];
}
this.currentPoint.distance = dist;
this.currentPoint.xUnits = xUnits;
this.currentPoint.yUnits = yUnits;
this.currentPoint.coordinate = coordinate;
// Update hover.
const geom = new ol.geom.Point(coordinate);
this.createMeasureTooltip_();
this.measureTooltipElement_.innerHTML = this.getTooltipHTML_();
this.measureTooltip_.setPosition(coordinate);
this.snappedPoint_.setGeometry(geom);
};
/**
* @private
*/
gmf.ProfileController.prototype.outCallback_ = function() {
// Reset information point.
this.currentPoint.coordinate = undefined;
this.currentPoint.distance = undefined;
this.currentPoint.elevations = {};
this.currentPoint.xUnits = undefined;
this.currentPoint.yUnits = undefined;
// Reset hover.
this.removeMeasureTooltip_();
this.snappedPoint_.setGeometry(null);
};
/**
* @return {string} A texte formatted to a tooltip.
* @private
*/
gmf.ProfileController.prototype.getTooltipHTML_ = function() {
const separator = ' : ';
let elevationName, translatedElevationName;
const innerHTML = [];
const number = this.$filter_('number');
const DistDecimal = this.currentPoint.xUnits === 'm' ? 0 : 2;
innerHTML.push(
`${this.profileLabels_.xAxis +
separator +
number(this.currentPoint.distance, DistDecimal)
} ${
this.currentPoint.xUnits}`
);
for (elevationName in this.currentPoint.elevations) {
translatedElevationName = this.gettextCatalog_.getString(elevationName);
innerHTML.push(
`${translatedElevationName +
separator +
number(this.currentPoint.elevations[elevationName], 0)
} ${this.currentPoint.yUnits}`
);
}
return innerHTML.join('</br>');
};
/**
* Creates a new 'hover' tooltip
* @private
*/
gmf.ProfileController.prototype.createMeasureTooltip_ = function() {
this.removeMeasureTooltip_();
this.measureTooltipElement_ = document.createElement('div');
this.measureTooltipElement_.className += 'tooltip ngeo-tooltip-measure';
this.measureTooltip_ = new ol.Overlay({
element: this.measureTooltipElement_,
offset: [0, -15],
positioning: 'bottom-center'
});
this.map_.addOverlay(this.measureTooltip_);
};
/**
* Destroy the 'hover' tooltip
* @private
*/
gmf.ProfileController.prototype.removeMeasureTooltip_ = function() {
if (this.measureTooltipElement_ !== null) {
this.measureTooltipElement_.parentNode.removeChild(
this.measureTooltipElement_);
this.measureTooltipElement_ = null;
this.map_.removeOverlay(this.measureTooltip_);
}
};
/**
* Return the color value of a gmfx.ProfileLineConfiguration.
* @param {string} layerName name of the elevation layer.
* @return {string|undefined} A HEX color or undefined is nothing is found.
* @export
*/
gmf.ProfileController.prototype.getColor = function(layerName) {
const lineConfiguration = this.linesConfiguration_[layerName];
if (!lineConfiguration) {
return undefined;
}
return lineConfiguration.color;
};
/**
* Return a copy of the existing layer names.
* @return {Array.<string>} The names of layers.
* @export
*/
gmf.ProfileController.prototype.getLayersNames = function() {
return this.layersNames_.slice(0);
};
/**
* @param {string} layerName name of the elevation layer.
* @return {function(Object):number} Z extractor function.
* @private
*/
gmf.ProfileController.prototype.getZFactory_ = function(layerName) {
/**
* Generic GMF extractor for the 'given' value in 'values' in profileData.
* @param {Object} item The item.
* @return {number} The elevation.
* @private
*/
const getZFn = function(item) {
if ('values' in item && layerName in item['values']) {
return parseFloat(item['values'][layerName]);
}
return 0;
};
return getZFn;
};
/**
* Extractor for the 'dist' value in profileData.
* @param {Object} item The item.
* @return {number} The distance.
* @private
*/
gmf.ProfileController.prototype.getDist_ = function(item) {
if ('dist' in item) {
return item['dist'];
}
return 0;
};
/**
* Request the profile.
* @private
*/
gmf.ProfileController.prototype.getJsonProfile_ = function() {
const geom = {
'type': 'LineString',
'coordinates': this.line.getCoordinates()
};
const params = {
'layers': this.layersNames_.join(','),
'geom': JSON.stringify(geom),
'nbPoints': this.nbPoints_
};
/** @type {Function} */ (this.$http_)({
url: this.gmfProfileJsonUrl_,
method: 'POST',
params,
paramSerializer: '$httpParamSerializerJQLike',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(
this.getProfileDataSuccess_.bind(this),
this.getProfileDataError_.bind(this)
);
};
/**
* @param {!angular.$http.Response} resp Response.
* @private
*/
gmf.ProfileController.prototype.getProfileDataSuccess_ = function(resp) {
const profileData = resp.data['profile'];
if (profileData instanceof Array) {
this.profileData = profileData;
}
};
/**
* @param {!angular.$http.Response} resp Response.
* @private
*/
gmf.ProfileController.prototype.getProfileDataError_ = function(resp) {
this.isErrored = true;
console.error('Can not get JSON profile.');
};
/**
* Request the csv profile with the current profile data.
* @export
*/
gmf.ProfileController.prototype.downloadCsv = function() {
if (this.profileData.length === 0) {
return;
}
/** @type {Array.<ngeox.GridColumnDef>} */
const headers = [];
let hasDistance = false;
const firstPoint = this.profileData[0];
if ('dist' in firstPoint) {
headers.push({name: 'distance'});
hasDistance = true;
}
const layers = [];
for (const layer in firstPoint['values']) {
headers.push({'name': layer});
layers.push(layer);
}
headers.push({name: 'x'});
headers.push({name: 'y'});
const rows = this.profileData.map((point) => {
const row = {};
if (hasDistance) {
row['distance'] = point['dist'];
}
layers.forEach((layer) => {
row[layer] = point['values'][layer];
});
row['x'] = point['x'];
row['y'] = point['y'];
return row;
});
this.ngeoCsvDownload_.startDownload(rows, headers, 'profile.csv');
};
gmf.module.controller('GmfProfileController', gmf.ProfileController);
|
const winston = require('winston');
const logTransports = require('./logging.config').logTransports;
const errorTransports = require('./logging.config').errorTransports;
const init = () => {
const logger = new winston.Logger({
transports: logTransports,
exceptionHandlers: errorTransports,
});
return logger;
};
module.exports = init;
|
/**
* Created by andyf on 4/14/2017.
*/
//------------------------------------------//
//------------------ROUTES------------------//
//------------------------------------------//
var multer = require("multer");
var express = require("express");
var app = express();
var multer = require("multer");
var mongoose = require("mongoose");
var createFile = require("create-file");
var jsonfile = require("jsonfile");
var fs = require("fs");
var db = mongoose.connect('mongodb://localhost/it410database');
// Upload Photos
var create = function(file){
createFile('app/image-info/' + file.originalname + "id.json",
'{"name": "' + file.originalname + '", "imageUrl":"img/' + file.originalname + '", "imageId":"' + file.originalname + 'id"}',
function(err) {
console.log("error");
}
);
var filePlace = __dirname + '/' + 'images.json';
var object = ',{"name": "' + file.originalname + '", "imageUrl":"img/' + file.originalname + '", "imageId":"' + file.originalname + 'id"}]'
var obj = jsonfile.readFileSync(filePlace);
console.log(obj);
var newObj = JSON.stringify(obj);
fs.unlinkSync(filePlace);
var brandNew = newObj.replace(']', object);
console.log(brandNew);
jsonfile.writeFileSync(filePlace, brandNew);
};
var storage = multer.diskStorage({
destination: function (req, file, callback) {
console.log(file, req.body);
callback(null, 'app/img');
},
filename: function (req, file, callback) {
create(file);
callback(null, file.originalname);
}
});
var upload = multer({ storage : storage}).single('userPhoto');
var User = require('./models/user');
module.exports = function(app, passport){
app.get('/authenticate', function(req, res){
res.render('authenticate.ejs');
});
app.post('/api/photo',function(req,res) {
console.log("got here", req.body);
upload(req, res, function(err) {
if (err) {
console.log(err);
return res.end("Error uploading file");
}
res.end("File has uploaded");
});
});
app.get('/', function(req, res){
res.sendfile('app/index.html');
});
app.get('/admin', function(req, res){
if(req.user) {
if(req.user.local.admin || req.user.google.admin) {
res.sendfile('app/admin.html');
}
else
res.send('You are not authorized to view this page </br> <a href="/authenticate">Return Home</a>');
}
else
res.render('authenticate.ejs');
});
app.get('/checkAdmin', function(req, res) {
if (req.user.admin){
res.sendfile('app/admin.html');
}
else {
res.sendfile('app/index.html');
}
});
app.get('/admin', function(req,res) {
res.sendfile('app/admin.html');
});
app.get('/users', function(req,res){
res.json(req.user);
// Find some documents
// User.find(function(err, docs) {
// console.log("Found the following records");
// console.dir(docs);
// res.json(req.user);
// });
});
app.get('/login', function(req, res){
res.render('login.ejs', { message: req.flash('loginMessage') });
});
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/checkAdmin',
failureRedirect: '/login',
failureFlash: true
}));
app.get('/signup', function(req, res){
res.render('signup.ejs', { message: req.flash('signupMessage') });
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/',
failureRedirect: '/signup',
failureFlash: true
}));
app.get('/profile', isLoggedIn, function(req, res){
res.render('profile.ejs', { user: req.user });
});
app.get('/auth/facebook', passport.authenticate('facebook', {scope: ['email']}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/checkAdmin',
failureRedirect: '/' }));
app.get('/auth/google', passport.authenticate('google', {scope: ['profile', 'email']}));
app.get('/auth/google/callback',
passport.authenticate('google', { successRedirect: '/checkAdmin',
failureRedirect: '/' }));
app.get('/logout', function(req, res){
req.logout();
res.redirect('/authenticate');
})
};
function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
return next();
}
res.redirect('/login');
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:64c6340edff360aebb02843efb9b18f66695b3251f409ff3960a03ff443abb3c
size 23415
|
// Example pony-config consumer
var config = require('../index.js');
console.log('');
console.log( 'Demonstrating loading configuration');
config
.options( { debug: true } )
.findRuntimeEnvironment( { paths:['./example-env-file'], env: 'ENVIRONMENT', default:'prod', debug: true} )
.always().object( {'organization': 'PonyCode' } )
.when(['dev']).file( 'example-dev-config.json' )
.when(['prod','stage'])
.file( 'example-prod-config.json' )
.object( { productionKey: 'pkey' })
.list();
console.log('');
console.log( 'Demonstrating reading and writing configuration ');
console.log('Initial State:', config.get('address.state', 'unset') );
config.set('address.state', 'TX' );
console.log('New State:', config.get('address.state', 'unset') );
console.log('');
console.log('New Address:', config.get('address') );
console.log('');
console.log('Done.');
|
/**
* Created by tim on 14/03/17.
*/
import styled from 'styled-components/native';
import React from 'react';
import FormFieldTitle from '../form/FormFieldTitle';
import StyledView from './StyledView';
const StyledText = styled.Text`
color: palevioletred;
`;
export default class StyledComponent extends React.Component {
render() {
return (
<StyledView>
<FormFieldTitle>{this.props.title}</FormFieldTitle>
<StyledText>Hello World!</StyledText>
</StyledView>
)
}
}
|
(function (global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global.nearestPeriodicValue = factory();
})(this, function () {
"use strict";
/*jshint -W018 */
function nearestPeriodicValue(point, value, period) {
var relation = (value - point) / period;
// We're equidistant from the nearest point if the
// distance from the point is a half-integer value
// of our period.
var equidistant = !(relation % 0.5) && relation % 1;
// If we're equidistant, then we add a period to
// ensure that we always pick the value in front
var mod = equidistant ? period : 0;
// Adjust our value by an amount given by the closest #
// of periods contained in the distance between the point
// and the value
return mod + (value - period * Math.round(relation));
}
var nearest_periodic_value = nearestPeriodicValue;
return nearest_periodic_value;
});
//# sourceMappingURL=./nearest-periodic-value.js.map
|
exports.User = require('./user')
exports.UserFollow = require('./user_follow')
exports.Post = require('./post')
exports.PostCollection = require('./post_collection')
exports.Tag = require('./tag')
exports.Message = require('./message')
exports.Reply = require('./reply')
|
var Barc= require ('../lib/barc')
fs = require('fs');
generate('defaults', new Barc());
generate('automatic border', new Barc({border:'auto'}));
generate('big font', new Barc({fontsize:40}));
generate('rotated', new Barc({fontsize:40, border:'auto'}), 45);
generate('flipped', new Barc({fontsize:40 }), 90);
function generate(title, barc, angle){
var buf = barc.code2of5('1122100017', 300, 200, angle);
var filename = 'code2of5-' + title + '.png';
fs.writeFile(__dirname + '/' + filename, buf, function(){
console.log('Created code2of5 and saved it as ', filename);
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.