code
stringlengths 2
1.05M
|
---|
import Immutable from "immutable";
import {Apis} from "sbitjs-ws";
import ChainTypes from "./ChainTypes";
import ChainValidation from "./ChainValidation";
import BigInteger from "bigi";
import ee from "./EmitterInstance";
const {object_type,impl_object_type} = ChainTypes;
let emitter = ee();
let op_history = parseInt(object_type.operation_history, 10);
let limit_order = parseInt(object_type.limit_order, 10);
let call_order = parseInt(object_type.call_order, 10);
let proposal = parseInt(object_type.proposal, 10);
// let balance_type = parseInt(object_type.balance, 10);
// let vesting_balance_type = parseInt(object_type.vesting_balance, 10);
let witness_object_type = parseInt(object_type.witness, 10);
let worker_object_type = parseInt(object_type.worker, 10);
let committee_member_object_type = parseInt(object_type.committee_member, 10);
let account_object_type = parseInt(object_type.account, 10);
let asset_object_type = parseInt(object_type.asset, 10);
let contract_object_type = parseInt(object_type.contract, 10);
let order_prefix = "1." + limit_order + ".";
let call_order_prefix = "1." + call_order + ".";
let proposal_prefix = "1." + proposal + ".";
let operation_history_prefix = "1." + op_history + ".";
let balance_prefix = "2." + parseInt(impl_object_type.account_balance,10) + ".";
let account_stats_prefix = "2." + parseInt(impl_object_type.account_statistics,10) + ".";
let transaction_prefix = "2." + parseInt(impl_object_type.transaction,10) + ".";
let account_transaction_history_prefix = "2." + parseInt(impl_object_type.account_transaction_history,10) + ".";
let asset_dynamic_data_prefix = "2." + parseInt(impl_object_type.asset_dynamic_data,10) + ".";
let bitasset_data_prefix = "2." + parseInt(impl_object_type.asset_bitasset_data,10) + ".";
let block_summary_prefix = "2." + parseInt(impl_object_type.block_summary,10) + ".";
// let vesting_balance_prefix = "1." + vesting_balance_type + ".";
let witness_prefix = "1." + witness_object_type + ".";
let worker_prefix = "1." + worker_object_type + ".";
let committee_prefix = "1." + committee_member_object_type + ".";
let asset_prefix = "1." + asset_object_type + ".";
let account_prefix = "1." + account_object_type + ".";
let contract_prefix = "1." + contract_object_type + ".";
const DEBUG = JSON.parse(process.env.npm_config__sbit_chain_chain_debug || false);
/**
* @brief maintains a local cache of blockchain state
*
* The ChainStore maintains a local cache of blockchain state and exposes
* an API that makes it easy to query objects and receive updates when
* objects are available.
*/
class ChainStore
{
constructor() {
/** tracks everyone who wants to receive updates when the cache changes */
this.subscribers = new Set();
this.subscribed = false;
this.clearCache();
// this.progress = 0;
// this.chain_time_offset is used to estimate the blockchain time
this.chain_time_offset = [];
this.dispatchFrequency = 40;
}
/**
* Clears all cached state. This should be called any time the network connection is
* reset.
*/
clearCache() {
/*
* Tracks specific objects such as accounts that can trigger additional
* fetching that should only happen if we're actually interested in the account
*/
this.subbed_accounts = new Set();
this.subbed_witnesses = new Set();
this.subbed_committee = new Set();
this.objects_by_id = new Map();
this.accounts_by_name = new Map();
this.assets_by_symbol = new Map();
this.account_ids_by_key = Immutable.Map();
this.account_ids_by_account = Immutable.Map();
this.balance_objects_by_address = new Map();
this.get_account_refs_of_keys_calls = new Set();
this.get_account_refs_of_accounts_calls = new Set();
this.account_history_requests = new Map(); ///< tracks pending history requests
this.witness_by_account_id = new Map();
this.committee_by_account_id = new Map();
this.objects_by_vote_id = new Map();
this.fetching_get_full_accounts = new Map();
this.get_full_accounts_subscriptions = new Map();
clearTimeout(this.timeout);
}
resetCache() {
this.subscribed = false;
this.subError = null;
this.clearCache();
this.head_block_time_string = null;
this.init().then(() => {
console.log("resetCache init success");
}).catch(err => {
console.log("resetCache init error"); //:", err);
});
}
setDispatchFrequency(freq) {
this.dispatchFrequency = freq;
}
init() {
let reconnectCounter = 0;
var _init = (resolve, reject) => {
if (this.subscribed) return resolve();
let db_api = Apis.instance().db_api();
if (!db_api) {
return reject(new Error("Api not found, please initialize the api instance before calling the ChainStore"));
}
return db_api.exec( "get_objects", [ ["2.1.0"] ] ).then( optional_objects => {
//if(DEBUG) console.log("... optional_objects",optional_objects ? optional_objects[0].id : null)
for(let i = 0; i < optional_objects.length; i++) {
let optional_object = optional_objects[i];
if( optional_object ) {
/*
** Because 2.1.0 gets fetched here before the set_subscribe_callback,
** the new witness_node subscription model makes it so we
** never get subscribed to that object, therefore
** this._updateObject is commented out here
*/
// this._updateObject( optional_object, true );
let head_time = new Date(optional_object.time+"+00:00").getTime();
this.head_block_time_string = optional_object.time;
this.chain_time_offset.push( (new Date).getTime() - timeStringToDate(optional_object.time).getTime() );
let now = (new Date).getTime();
let delta = (now - head_time)/1000;
// let start = Date.parse("Sep 1, 2015");
// let progress_delta = head_time - start;
// this.progress = progress_delta / (now-start);
if( delta < 60 ) {
Apis.instance().db_api().exec( "set_subscribe_callback", [ this.onUpdate.bind(this), true ] )
.then(() => {
console.log("synced and subscribed, chainstore ready");
this.subscribed = true;
this.subError = null;
resolve();
})
.catch( error => {
this.subscribed = false;
this.subError = error;
reject(error);
if (DEBUG) console.log( "Error: ", error );
});
} else {
console.log("not yet synced, retrying in 1s");
this.subscribed = false;
reconnectCounter++;
if (reconnectCounter > 5) {
this.subError = new Error("ChainStore sync error, please check your system clock");
return reject(this.subError);
}
setTimeout( _init.bind(this, resolve, reject), 1000 );
}
} else {
setTimeout( _init.bind(this, resolve, reject), 1000 );
}
}
}).catch( error => { // in the event of an error clear the pending state for id
if (DEBUG) console.log("!!! Chain API error", error);
this.objects_by_id.delete("2.1.0");
reject(error);
});
};
return new Promise((resolve, reject) => _init(resolve, reject));
}
_subTo(type, id) {
let key = "subbed_" + type;
if (!this[key].has(id)) this[key].add(id);
}
unSubFrom(type, id) {
let key = "subbed_" + type;
this[key].delete(id);
this.objects_by_id.delete(id);
}
_isSubbedTo(type, id) {
let key = "subbed_" + type;
return this[key].has(id);
}
onUpdate( updated_objects ) /// map from account id to objects
{
let cancelledOrders = [];
let closedCallOrders = [];
for( let a = 0; a < updated_objects.length; ++a )
{
for( let i = 0; i < updated_objects[a].length; ++i )
{
let obj = updated_objects[a][i];
if( ChainValidation.is_object_id( obj ) ) {
// An entry containing only an object ID means that object was removed
// console.log("removed obj", obj);
// Check if the object exists in the ChainStore
let old_obj = this.objects_by_id.get(obj);
if( obj.search( order_prefix ) == 0 ) {
// Limit orders
cancelledOrders.push(obj);
if (old_obj) {
let account = this.objects_by_id.get(old_obj.get("seller"));
if (account && account.has("orders")) {
let limit_orders = account.get("orders");
if (account.get("orders").has(obj)) {
account = account.set("orders", limit_orders.delete(obj));
this.objects_by_id.set( account.get("id"), account );
}
}
}
}
if( obj.search( call_order_prefix ) == 0 ) {
// Call orders
closedCallOrders.push(obj);
if (old_obj) {
let account = this.objects_by_id.get(old_obj.get("borrower"));
if (account && account.has("call_orders")) {
let call_orders = account.get("call_orders");
if (account.get("call_orders").has(obj)) {
account = account.set("call_orders", call_orders.delete(obj));
this.objects_by_id.set( account.get("id"), account );
}
}
}
}
// Remove the object (if it already exists), set to null to indicate it does not exist
if (old_obj) this.objects_by_id.set( obj, null );
}
else {
this._updateObject( obj );
}
}
}
// Cancelled limit order(s), emit event for any listeners to update their state
if (cancelledOrders.length) emitter.emit("cancel-order", cancelledOrders);
// Closed call order, emit event for any listeners to update their state
if (closedCallOrders.length) emitter.emit("close-call", closedCallOrders);
// console.log("objects in store count:", this.objects_by_id.size, updated_objects[0].reduce((final, o) => {
// if (o && o.id) {
// final.changed.push(o.id);
// } else {
// final.removed.push(o);
// }
// return final;
// }, {changed: [], removed: []}));
this.notifySubscribers();
}
notifySubscribers()
{
// Dispatch at most only once every x milliseconds
if( ! this.dispatched ) {
this.dispatched = true;
this.timeout = setTimeout( () => {
this.dispatched = false;
this.subscribers.forEach( (callback) => { callback();} );
}, this.dispatchFrequency );
}
}
/**
* Add a callback that will be called anytime any object in the cache is updated
*/
subscribe( callback ) {
if(this.subscribers.has(callback))
console.error("Subscribe callback already exists", callback);
this.subscribers.add( callback );
}
/**
* Remove a callback that was previously added via subscribe
*/
unsubscribe( callback ) {
if( ! this.subscribers.has(callback))
console.error("Unsubscribe callback does not exists", callback);
this.subscribers.delete( callback );
}
/** Clear an object from the cache to force it to be fetched again. This may
* be useful if a query failed the first time and the wallet has reason to believe
* it may succeede the second time.
*/
clearObjectCache( id ) {
this.objects_by_id.delete(id);
}
/**
* There are three states an object id could be in:
*
* 1. undefined - returned if a query is pending
* 3. defined - return an object
* 4. null - query return null
*
*/
getObject( id, force = false, autosubscribe = true )
{
if( !ChainValidation.is_object_id(id) )
throw Error( "argument is not an object id: " + JSON.stringify(id) );
let result = this.objects_by_id.get( id );
let subChange = id.substring(0,account_prefix.length) == account_prefix && !this.get_full_accounts_subscriptions.get(id, false) && autosubscribe;
if( result === undefined || force || subChange )
return this.fetchObject( id, force, autosubscribe );
if( result === true )
return undefined;
return result;
}
/**
* @return undefined if a query is pending
* @return null if id_or_symbol has been queired and does not exist
* @return object if the id_or_symbol exists
*/
getAsset( id_or_symbol )
{
if( !id_or_symbol )
return null;
if ( ChainValidation.is_object_id( id_or_symbol ) ) {
let asset = this.getObject( id_or_symbol );
if (asset && (asset.get("bitasset") && !asset.getIn(["bitasset", "current_feed"]))) {
return undefined;
}
return asset;
}
/// TODO: verify id_or_symbol is a valid symbol name
let asset_id = this.assets_by_symbol.get( id_or_symbol );
if( ChainValidation.is_object_id(asset_id)) {
let asset = this.getObject( asset_id );
if (asset && (asset.get("bitasset") && !asset.getIn(["bitasset", "current_feed"]))) {
return undefined;
}
return asset;
}
if( asset_id === null )
return null;
if( asset_id === true )
return undefined;
Apis.instance().db_api().exec( "lookup_asset_symbols", [ [id_or_symbol] ] )
.then( asset_objects => {
// console.log( "lookup symbol ", id_or_symbol )
if( asset_objects.length && asset_objects[0] )
this._updateObject( asset_objects[0], true );
else {
this.assets_by_symbol.set( id_or_symbol, null );
this.notifySubscribers();
}
}).catch( error => {
if (DEBUG) console.log( "Error: ", error );
this.assets_by_symbol.delete( id_or_symbol );
});
return undefined;
}
/**
* @param the public key to find accounts that reference it
*
* @return Set of account ids that reference the given key
* @return a empty Set if no items are found
* @return undefined if the result is unknown
*
* If this method returns undefined, then it will send a request to
* the server for the current set of accounts after which the
* server will notify us of any accounts that reference these keys
*/
getAccountRefsOfKey( key )
{
if( this.get_account_refs_of_keys_calls.has(key) )
return this.account_ids_by_key.get( key );
else
{
this.get_account_refs_of_keys_calls.add(key);
Apis.instance().db_api().exec( "get_key_references", [ [key] ] )
.then( vec_account_id => {
let refs = Immutable.Set();
vec_account_id = vec_account_id[0];
refs = refs.withMutations( r => {
for( let i = 0; i < vec_account_id.length; ++i ) {
r.add(vec_account_id[i]);
}
});
this.account_ids_by_key = this.account_ids_by_key.set( key, refs );
this.notifySubscribers();
}).catch(err => {
console.error("get_key_references", err);
this.account_ids_by_key = this.account_ids_by_key.delete( key );
this.get_account_refs_of_keys_calls.delete(key);
});
return undefined;
}
return undefined;
}
/**
* @param the account id to find accounts that reference it
*
* @return Set of account ids that reference the given key
* @return a empty Set if no items are found
* @return undefined if the result is unknown
*
* If this method returns undefined, then it will send a request to
* the server for the current set of accounts after which the
* server will notify us of any accounts that reference these keys
*/
getAccountRefsOfAccount( account_id )
{
if( this.get_account_refs_of_accounts_calls.has(account_id) )
return this.account_ids_by_account.get( account_id );
else
{
this.get_account_refs_of_accounts_calls.add(account_id);
Apis.instance().db_api().exec( "get_account_references", [ account_id ] )
.then( vec_account_id => {
let refs = Immutable.Set();
refs = refs.withMutations( r => {
for( let i = 0; i < vec_account_id.length; ++i ) {
r.add(vec_account_id[i]);
}
});
this.account_ids_by_account = this.account_ids_by_account.set( account_id, refs );
this.notifySubscribers();
}).catch(err => {
console.error("get_account_references", err);
this.account_ids_by_account = this.account_ids_by_account.delete( account_id );
this.get_account_refs_of_accounts_calls.delete(account_id);
});
return undefined;
}
return undefined;
}
/**
* @return a Set of balance ids that are claimable with the given address
* @return undefined if a query is pending and the set is not known at this time
* @return a empty Set if no items are found
*
* If this method returns undefined, then it will send a request to the server for
* the current state after which it will be subscribed to changes to this set.
*/
getBalanceObjects( address )
{
let current = this.balance_objects_by_address.get( address );
if( current === undefined )
{
/** because balance objects are simply part of the genesis state, there is no need to worry about
* having to update them / merge them or index them in updateObject.
*/
this.balance_objects_by_address.set( address, Immutable.Set() );
Apis.instance().db_api().exec( "get_balance_objects", [ [address] ] )
.then( balance_objects => {
let set = new Set();
for( let i = 0; i < balance_objects.length; ++i )
{
this._updateObject( balance_objects[i] );
set.add(balance_objects[i].id);
}
this.balance_objects_by_address.set( address, Immutable.Set(set) );
this.notifySubscribers();
},
() => {
this.balance_objects_by_address.delete( address );
});
}
return this.balance_objects_by_address.get( address );
}
/**
* If there is not already a pending request to fetch this object, a new
* request will be made.
*
* @return null if the object does not exist,
* @return undefined if the object might exist but is not in cache
* @return the object if it does exist and is in our cache
*/
fetchObject( id, force = false, autosubscribe = true )
{
if( typeof id !== "string" )
{
let result = [];
for( let i = 0; i < id.length; ++i )
result.push( this.fetchObject( id[i], force, autosubscribe ) );
return result;
}
if(DEBUG) console.log( "!!! fetchObject: ", id, this.subscribed, !this.subscribed && !force );
if( !this.subscribed && !force ) return undefined;
if(DEBUG) console.log( "maybe fetch object: ", id );
if( !ChainValidation.is_object_id(id) )
throw Error( "argument is not an object id: " + id );
if( id.search("1.2.") === 0 ) return this.fetchFullAccount( id, autosubscribe );
if (id.search(witness_prefix) === 0) this._subTo("witnesses", id);
if (id.search(committee_prefix) === 0) this._subTo("committee", id);
let result = this.objects_by_id.get( id );
if( result === undefined ) { // the fetch
if(DEBUG) console.log( "fetching object: ", id );
this.objects_by_id.set( id, true );
Apis.instance().db_api().exec( "get_objects", [ [id] ] ).then( optional_objects => {
//if(DEBUG) console.log("... optional_objects",optional_objects ? optional_objects[0].id : null)
for(let i = 0; i < optional_objects.length; i++) {
let optional_object = optional_objects[i];
if( optional_object )
this._updateObject( optional_object, true );
else {
this.objects_by_id.set( id, null );
this.notifySubscribers();
}
}
}).catch( error => { // in the event of an error clear the pending state for id
if (DEBUG) console.log("!!! Chain API error",error);
this.objects_by_id.delete(id);
});
}
else if( result === true ) // then we are waiting a response
return undefined;
return result; // we have a response, return it
}
/**
* @return null if no such account exists
* @return undefined if such an account may exist, and fetch the the full account if not already pending
* @return the account object if it does exist
*/
getAccount( name_or_id, autosubscribe = true ) {
if( !name_or_id )
return null;
if( typeof name_or_id === "object" )
{
if( name_or_id.id ) return this.getAccount( name_or_id.id, autosubscribe );
else if( name_or_id.get ) return this.getAccount( name_or_id.get("id"), autosubscribe );
else return undefined;
}
if( ChainValidation.is_object_id(name_or_id) )
{
let account = this.getObject( name_or_id, false, autosubscribe );
if (account === null) {
return null;
}
/* If sub status changes from false to true, force full fetch */
const currentSub = this.get_full_accounts_subscriptions.get(name_or_id, false);
if( (!currentSub && autosubscribe) || account === undefined || account.get("name") === undefined ) {
return this.fetchFullAccount( name_or_id, autosubscribe );
}
return account;
}
else if( ChainValidation.is_account_name( name_or_id, true ) )
{
let account_id = this.accounts_by_name.get( name_or_id );
if(account_id === null) return null; // already fetched and it wasn't found
if( account_id === undefined ) // then no query, fetch it
return this.fetchFullAccount( name_or_id, autosubscribe );
return this.getObject( account_id, false, autosubscribe ); // return it
}
//throw Error( `Argument is not an account name or id: ${name_or_id}` )
}
/**
* This method will attempt to lookup witness by account_id.
* If witness doesn't exist it will return null, if witness is found it will return witness object,
* if it's not fetched yet it will return undefined.
* @param account_id - account id
*/
getWitnessById(account_id) {
let witness_id = this.witness_by_account_id.get(account_id);
if (witness_id === undefined) {
this.fetchWitnessByAccount(account_id);
return undefined;
} else if (witness_id) {
this._subTo("witnesses", witness_id);
}
return witness_id ? this.getObject(witness_id) : null;
}
/**
* This method will attempt to lookup committee member by account_id.
* If committee member doesn't exist it will return null, if committee member is found it will return committee member object,
* if it's not fetched yet it will return undefined.
* @param account_id - account id
*/
getCommitteeMemberById(account_id) {
let cm_id = this.committee_by_account_id.get(account_id);
if (cm_id === undefined) {
this.fetchCommitteeMemberByAccount(account_id);
return undefined;
} else if (cm_id) {
this._subTo("committee", cm_id);
}
return cm_id ? this.getObject(cm_id) : null;
}
/**
* Obsolete! Please use getWitnessById
* This method will attempt to lookup the account, and then query to see whether or not there is
* a witness for this account. If the answer is known, it will return the witness_object, otherwise
* it will attempt to look it up and return null. Once the lookup has completed on_update will
* be called.
*
* @param id_or_account may either be an account_id, a witness_id, or an account_name
*/
// getWitness( id_or_account )
// {
// let account = this.getAccount( id_or_account );
// if( !account ) return null;
// let account_id = account.get("id");
//
// let witness_id = this.witness_by_account_id.get( account_id );
// if( witness_id === undefined )
// this.fetchWitnessByAccount( account_id );
// return this.getObject( witness_id );
//
// if( ChainValidation.is_account_name(id_or_account, true) || (id_or_account.substring(0,4) == "1.2."))
// {
// let account = this.getAccount( id_or_account );
// if( !account )
// {
// this.lookupAccountByName( id_or_account ).then ( account => {
// if( !account ) return null;
//
// let account_id = account.get("id");
// let witness_id = this.witness_by_account_id.get( account_id );
// if( ChainValidation.is_object_id( witness_id ) )
// return this.getObject( witness_id, on_update );
//
// if( witness_id == undefined )
// this.fetchWitnessByAccount( account_id ).then( witness => {
// this.witness_by_account_id.set( account_id, witness?witness.get("id"):null );
// if( witness && on_update ) on_update();
// })
// }, () => {
// let witness_id = this.witness_by_account_id.set( id_or_account, null )
// } )
// }
// else
// {
// let account_id = account.get("id")
// let witness_id = this.witness_by_account_id.get( account_id )
// if( ChainValidation.is_object_id( witness_id ) )
// return this.getObject( witness_id, on_update )
//
// if( witness_id == undefined )
// this.fetchWitnessByAccount( account_id ).then( witness => {
// this.witness_by_account_id.set( account_id, witness?witness.get("id"):null )
// if( witness && on_update ) on_update()
// })
// }
// return null
// }
// return null
// }
// Obsolete! Please use getCommitteeMemberById
// getCommitteeMember( id_or_account, on_update = null )
// {
// if( ChainValidation.is_account_name(id_or_account, true) || (id_or_account.substring(0,4) == "1.2."))
// {
// let account = this.getAccount( id_or_account )
//
// if( !account )
// {
// this.lookupAccountByName( id_or_account ).then( account=>{
// let account_id = account.get("id")
// let committee_id = this.committee_by_account_id.get( account_id )
// if( ChainValidation.is_object_id( committee_id ) ) return this.getObject( committee_id, on_update )
//
// if( committee_id == undefined )
// {
// this.fetchCommitteeMemberByAccount( account_id ).then( committee => {
// this.committee_by_account_id.set( account_id, committee ? committee.get("id") : null )
// if( on_update && committee) on_update()
// } )
// }
// }, error => {
// let witness_id = this.committee_by_account_id.set( id_or_account, null )
// })
// }
// else
// {
// let account_id = account.get("id")
// let committee_id = this.committee_by_account_id.get( account_id )
// if( ChainValidation.is_object_id( committee_id ) ) return this.getObject( committee_id, on_update )
//
// if( committee_id == undefined )
// {
// this.fetchCommitteeMemberByAccount( account_id ).then( committee => {
// this.committee_by_account_id.set( account_id, committee ? committee.get("id") : null )
// if( on_update && committee) on_update()
// } )
// }
// }
// }
// return null
// }
/**
*
* @return a promise with the witness object
*/
fetchWitnessByAccount( account_id )
{
return new Promise( (resolve,reject ) => {
Apis.instance().db_api().exec( "get_witness_by_account", [ account_id ] )
.then( optional_witness_object => {
if( optional_witness_object )
{
this._subTo("witnesses", optional_witness_object.id);
this.witness_by_account_id = this.witness_by_account_id.set( optional_witness_object.witness_account, optional_witness_object.id );
let witness_object = this._updateObject( optional_witness_object, true );
resolve(witness_object);
}
else
{
this.witness_by_account_id = this.witness_by_account_id.set( account_id, null );
this.notifySubscribers();
resolve(null);
}
}, reject );
});
}
/**
*
* @return a promise with the witness object
*/
fetchCommitteeMemberByAccount( account_id )
{
return new Promise( (resolve,reject ) => {
Apis.instance().db_api().exec( "get_committee_member_by_account", [ account_id ] )
.then( optional_committee_object => {
if( optional_committee_object )
{
this._subTo("committee", optional_committee_object.id);
this.committee_by_account_id = this.committee_by_account_id.set( optional_committee_object.committee_member_account, optional_committee_object.id );
let committee_object = this._updateObject( optional_committee_object, true );
resolve(committee_object);
}
else
{
this.committee_by_account_id = this.committee_by_account_id.set( account_id, null );
this.notifySubscribers();
resolve(null);
}
}, reject );
});
}
/**
* Fetches an account and all of its associated data in a single query
*
* @param an account name or account id
*
* @return undefined if the account in question is in the process of being fetched
* @return the object if it has already been fetched
* @return null if the object has been queried and was not found
*/
fetchFullAccount( name_or_id, autosubscribe = true )
{
if(DEBUG) console.log( "Fetch full account: ", name_or_id );
let fetch_account = false;
const subChanged = this.get_full_accounts_subscriptions.has(name_or_id) && (this.get_full_accounts_subscriptions.get(name_or_id) === false && autosubscribe);
if( ChainValidation.is_object_id(name_or_id) && !subChanged ) {
let current = this.objects_by_id.get( name_or_id );
fetch_account = current === undefined;
if( !fetch_account && current.get("name") ) return current;
} else if (!subChanged) {
if( !ChainValidation.is_account_name( name_or_id, true ) )
throw Error( "argument is not an account name: " + name_or_id );
let account_id = this.accounts_by_name.get( name_or_id );
if( ChainValidation.is_object_id( account_id ) )
return this.getAccount(account_id, autosubscribe);
}
/// only fetch once every 5 seconds if it wasn't found, or if the subscribe status changed to true
if( subChanged || !this.fetching_get_full_accounts.has(name_or_id) || (Date.now() - this.fetching_get_full_accounts.get(name_or_id)) > 5000 ) {
this.fetching_get_full_accounts.set(name_or_id, Date.now() );
// console.log( "FETCHING FULL ACCOUNT: ", name_or_id, autosubscribe );
Apis.instance().db_api().exec("get_full_accounts", [[name_or_id], autosubscribe])
.then( results => {
if(results.length === 0 ) {
if( ChainValidation.is_object_id(name_or_id) ) {
this.objects_by_id.set( name_or_id, null );
this.notifySubscribers();
}
return;
}
let full_account = results[0][1];
this.get_full_accounts_subscriptions.set(full_account.account.name, autosubscribe);
this.get_full_accounts_subscriptions.set(full_account.account.id, autosubscribe);
if(DEBUG) console.log( "full_account: ", full_account );
/* Add this account to list of subbed accounts */
this._subTo("accounts", full_account.account.id);
let {
account,
vesting_balances,
statistics,
call_orders,
limit_orders,
referrer_name, registrar_name, lifetime_referrer_name,
votes,
proposals
} = full_account;
this.accounts_by_name.set( account.name, account.id );
account.referrer_name = referrer_name;
account.lifetime_referrer_name = lifetime_referrer_name;
account.registrar_name = registrar_name;
account.balances = {};
account.orders = new Immutable.Set();
account.vesting_balances = new Immutable.Set();
account.balances = new Immutable.Map();
account.call_orders = new Immutable.Set();
account.proposals = new Immutable.Set();
account.vesting_balances = account.vesting_balances.withMutations(set => {
vesting_balances.forEach(vb => {
this._updateObject( vb );
set.add( vb.id );
});
});
let sub_to_objects = [];
votes.forEach(v => this._updateObject( v ));
account.balances = account.balances.withMutations(map => {
full_account.balances.forEach(b => {
this._updateObject( b );
map.set( b.asset_type, b.id );
sub_to_objects.push(b.id);
});
});
account.orders = account.orders.withMutations(set => {
limit_orders.forEach(order => {
this._updateObject( order );
set.add( order.id );
sub_to_objects.push(order.id);
});
});
account.call_orders = account.call_orders.withMutations(set => {
call_orders.forEach(co => {
this._updateObject( co );
set.add( co.id );
sub_to_objects.push(co.id);
});
});
account.proposals = account.proposals.withMutations(set => {
proposals.forEach(p => {
this._updateObject( p );
set.add( p.id );
sub_to_objects.push(p.id);
});
});
if (sub_to_objects.length) Apis.instance().db_api().exec("get_objects", [sub_to_objects]);
this._updateObject( statistics );
let updated_account = this._updateObject( account );
this.fetchRecentHistory( updated_account );
this.notifySubscribers();
}, error => {
if (DEBUG) console.log( "Error: ", error );
if( ChainValidation.is_object_id(name_or_id) )
this.objects_by_id.delete( name_or_id );
else
this.accounts_by_name.delete( name_or_id );
});
}
return undefined;
}
getAccountMemberStatus( account ) {
if( account === undefined ) return undefined;
if( account === null ) return "unknown";
if( account.get( "lifetime_referrer" ) == account.get( "id" ) )
return "lifetime";
let exp = new Date( account.get("membership_expiration_date") ).getTime();
let now = new Date().getTime();
if( exp < now )
return "basic";
return "annual";
}
getAccountBalance( account, asset_type )
{
let balances = account.get( "balances" );
if( !balances )
return 0;
let balance_obj_id = balances.get( asset_type );
if( balance_obj_id )
{
let bal_obj = this.objects_by_id.get( balance_obj_id );
if( bal_obj ) return bal_obj.get( "balance" );
}
return 0;
}
/**
* There are two ways to extend the account history, add new more
* recent history, and extend historic hstory. This method will fetch
* the most recent account history and prepend it to the list of
* historic operations.
*
* @param account immutable account object
* @return a promise with the account history
*/
fetchRecentHistory( account, limit = 100 )
{
// console.log( "get account history: ", account )
/// TODO: make sure we do not submit a query if there is already one
/// in flight...
let account_id = account;
if( !ChainValidation.is_object_id(account_id) && account.toJS )
account_id = account.get("id");
if( !ChainValidation.is_object_id(account_id) )
return;
account = this.objects_by_id.get(account_id);
if( !account ) return;
let pending_request = this.account_history_requests.get(account_id);
if( pending_request ) {
pending_request.requests++;
return pending_request.promise;
}
else pending_request = { requests: 0 };
let most_recent = "1." + op_history + ".0";
let history = account.get( "history" );
if( history && history.size ) most_recent = history.first().get("id");
/// starting at 0 means start at NOW, set this to something other than 0
/// to skip recent transactions and fetch the tail
let start = "1." + op_history + ".0";
pending_request.promise = new Promise( (resolve, reject) => {
Apis.instance().history_api().exec("get_account_history",
[ account_id, most_recent, limit, start])
.then( operations => {
let current_account = this.objects_by_id.get( account_id );
let current_history = current_account.get( "history" );
if( !current_history ) current_history = Immutable.List();
let updated_history = Immutable.fromJS(operations);
updated_history = updated_history.withMutations( list => {
for( let i = 0; i < current_history.size; ++i )
list.push( current_history.get(i) );
});
let updated_account = current_account.set( "history", updated_history );
this.objects_by_id.set( account_id, updated_account );
//if( current_history != updated_history )
// this._notifyAccountSubscribers( account_id )
let pending_request = this.account_history_requests.get(account_id);
this.account_history_requests.delete(account_id);
if( pending_request.requests > 0 )
{
// it looks like some more history may have come in while we were
// waiting on the result, lets fetch anything new before we resolve
// this query.
this.fetchRecentHistory(updated_account, limit ).then( resolve, reject );
}
else
resolve(updated_account);
}); // end then
});
this.account_history_requests.set( account_id, pending_request );
return pending_request.promise;
}
//_notifyAccountSubscribers( account_id )
//{
// let sub = this.subscriptions_by_account.get( account_id )
// let acnt = this.objects_by_id.get(account_id)
// if( !sub ) return
// for( let item of sub.subscriptions )
// item( acnt )
//}
/**
* Callback that receives notification of objects that have been
* added, remove, or changed and are relevant to account_id
*
* This method updates or removes objects from the main index and
* then updates the account object with relevant meta-info depending
* upon the type of account
*/
// _updateAccount( account_id, payload )
// {
// let updates = payload[0]
// for( let i = 0; i < updates.length; ++i )
// {
// let update = updates[i]
// if( typeof update == 'string' )
// {
// let old_obj = this._removeObject( update )
// if( update.search( order_prefix ) == 0 )
// {
// acnt = acnt.setIn( ['orders'], set => set.delete(update) )
// }
// else if( update.search( vesting_balance_prefix ) == 0 )
// {
// acnt = acnt.setIn( ['vesting_balances'], set => set.delete(update) )
// }
// }
// else
// {
// let updated_obj = this._updateObject( update )
// if( update.id.search( balance_prefix ) == 0 )
// {
// if( update.owner == account_id )
// acnt = acnt.setIn( ["balances"], map => map.set(update.asset_type,update.id) )
// }
// else if( update.id.search( order_prefix ) == 0 )
// {
// if( update.owner == account_id )
// acnt = acnt.setIn( ['orders'], set => set.add(update.id) )
// }
// else if( update.id.search( vesting_balance_prefix ) == 0 )
// {
// if( update.owner == account_id )
// acnt = acnt.setIn( ['vesting_balances'], set => set.add(update.id) )
// }
// this.objects_by_id.set( acnt.id, acnt )
// }
// }
// this.fetchRecentHistory( acnt )
// }
/**
* Updates the object in place by only merging the set
* properties of object.
*
* This method will create an immutable object with the given ID if
* it does not already exist.
*
* This is a "private" method called when data is received from the
* server and should not be used by others.
*
* @pre object.id must be a valid object ID
* @return an Immutable constructed from object and deep merged with the current state
*/
_updateObject( object, notify_subscribers = false, emit = true )
{
if (!("id" in object)) {
if (DEBUG) console.log("object with no id:", object);
/* Settle order updates look different and need special handling */
if ("balance" in object && "owner" in object && "settlement_date" in object) {
// Settle order object
emitter.emit("settle-order-update", object);
}
return;
}
/*
* A lot of objects get spammed by the API that we don't care about, filter these out here
*/
// Transaction object
if( object.id.substring(0,transaction_prefix.length) == transaction_prefix ) {
return; // console.log("not interested in transaction:", object);
} else if( object.id.substring(0, account_transaction_history_prefix.length) == account_transaction_history_prefix ) {
// transaction_history object
if (!this._isSubbedTo("accounts", object.account)) {
return; // console.log("not interested in transaction_history of", object.account);
}
} else if( object.id.substring(0, order_prefix.length) == order_prefix ) {
// limit_order object
if (!this._isSubbedTo("accounts", object.seller)) {
return; // console.log("not interested in limit_orders of", object.seller);
}
} else if( object.id.substring(0, call_order_prefix.length) == call_order_prefix ) {
// call_order object
if (!this._isSubbedTo("accounts", object.borrower)) {
return; // console.log("not interested in call_orders of", object.borrower);
}
} else if (object.id.substring(0, balance_prefix.length) == balance_prefix) {
// balance object
if (!this._isSubbedTo("accounts", object.owner)) {
return; // console.log("not interested in balance_object of", object.owner);
}
} else if( object.id.substring(0, operation_history_prefix.length) == operation_history_prefix ) {
// operation_history object
return; // console.log("not interested in operation_history", object);
} else if( object.id.substring(0, block_summary_prefix.length) == block_summary_prefix ) {
// block_summary object
return; // console.log("not interested in block_summary_prefix", object);
} else if( object.id.substring(0,account_stats_prefix.length) == account_stats_prefix ) {
// account_stats object
if (!this._isSubbedTo("accounts", object.owner)) {
return; // console.log("not interested in stats of", object.owner);
}
} else if( object.id.substring(0,witness_prefix.length) == witness_prefix ) {
// witness object
if (!this._isSubbedTo("witnesses", object.id)) {
return;
}
} else if( object.id.substring(0,committee_prefix.length) == committee_prefix ) {
// committee_member object
if (!this._isSubbedTo("committee", object.id)) {
return;
}
} else if (object.id.substring(0, 4) === "0.0." || object.id.substring(0, 4) === "5.1.") {
/*
** The witness node spams these random objects related to markets,
** they are never needed by the GUI and thus only fill up the memory,
** so we ignore them
*/
return;
}
// DYNAMIC GLOBAL OBJECT
if( object.id == "2.1.0" ) {
object.participation = 100*(BigInteger(object.recent_slots_filled).bitCount() / 128.0);
this.head_block_time_string = object.time;
this.chain_time_offset.push( Date.now() - timeStringToDate(object.time).getTime() );
if(this.chain_time_offset.length > 10) this.chain_time_offset.shift(); // remove first
}
let current = this.objects_by_id.get( object.id );
if( !current ) {
// console.log("add object:", object.id);
current = Immutable.Map();
}
let prior = current;
if( current === undefined || current === true )
this.objects_by_id.set( object.id, current = Immutable.fromJS(object) );
else
{
this.objects_by_id.set( object.id, current = current.mergeDeep( Immutable.fromJS(object) ) );
}
// BALANCE OBJECT
if( object.id.substring(0,balance_prefix.length) == balance_prefix ) {
let owner = this.objects_by_id.get( object.owner );
if( owner === undefined || owner === null ) {
return;
/* This prevents the full account from being looked up later
owner = {id:object.owner, balances:{ } }
owner.balances[object.asset_type] = object.id
owner = Immutable.fromJS( owner )
*/
} else {
let balances = owner.get( "balances" );
if( !balances )
owner = owner.set( "balances", Immutable.Map() );
owner = owner.setIn( ["balances",object.asset_type], object.id );
}
this.objects_by_id.set( object.owner, owner );
} else if( object.id.substring(0,account_stats_prefix.length) == account_stats_prefix ) {
// ACCOUNT STATS OBJECT
try {
let prior_most_recent_op = prior.get("most_recent_op", "2.9.0");
if( prior_most_recent_op != object.most_recent_op) {
this.fetchRecentHistory( object.owner );
}
} catch(err) {
if (DEBUG) console.log("prior error:", "object:", obj, "prior", prior, "err:", err);
}
} else if( object.id.substring(0,witness_prefix.length) == witness_prefix ) {
// WITNESS OBJECT
if (this._isSubbedTo("witnesses", object.id)) {
this.witness_by_account_id.set( object.witness_account, object.id );
this.objects_by_vote_id.set( object.vote_id, object.id );
} else {
return;
}
} else if( object.id.substring(0,committee_prefix.length) == committee_prefix ) {
// COMMITTEE MEMBER OBJECT
if (this._isSubbedTo("committee", object.id)) {
this.committee_by_account_id.set( object.committee_member_account, object.id );
this.objects_by_vote_id.set( object.vote_id, object.id );
} else {
return;
}
} else if( object.id.substring(0,account_prefix.length) == account_prefix ) {
// ACCOUNT OBJECT
current = current.set( "active", Immutable.fromJS( object.active ) );
current = current.set( "owner", Immutable.fromJS( object.owner ) );
current = current.set( "options", Immutable.fromJS( object.options ) );
current = current.set( "whitelisting_accounts", Immutable.fromJS( object.whitelisting_accounts ) );
current = current.set( "blacklisting_accounts", Immutable.fromJS( object.blacklisting_accounts ) );
current = current.set( "whitelisted_accounts", Immutable.fromJS( object.whitelisted_accounts ) );
current = current.set( "blacklisted_accounts", Immutable.fromJS( object.blacklisted_accounts ) );
this.objects_by_id.set( object.id, current );
this.accounts_by_name.set( object.name, object.id );
} else if( object.id.substring(0,asset_prefix.length) == asset_prefix ) {
// ASSET OBJECT
this.assets_by_symbol.set( object.symbol, object.id );
let dynamic = current.get( "dynamic" );
if( !dynamic ) {
let dad = this.getObject( object.dynamic_asset_data_id, true );
if( !dad )
dad = Immutable.Map();
if( !dad.get( "asset_id" ) ) {
dad = dad.set( "asset_id", object.id );
}
this.objects_by_id.set( object.dynamic_asset_data_id, dad );
current = current.set( "dynamic", dad );
this.objects_by_id.set( object.id, current );
}
let bitasset = current.get( "bitasset" );
if( !bitasset && object.bitasset_data_id ) {
let bad = this.getObject( object.bitasset_data_id, true );
if( !bad )
bad = Immutable.Map();
if( !bad.get( "asset_id" ) ) {
bad = bad.set( "asset_id", object.id );
}
this.objects_by_id.set( object.bitasset_data_id, bad );
current = current.set( "bitasset", bad );
this.objects_by_id.set( object.id, current );
}
} else if( object.id.substring(0,asset_dynamic_data_prefix.length) == asset_dynamic_data_prefix ) {
// ASSET DYNAMIC DATA OBJECT
// let asset_id = asset_prefix + object.id.substring( asset_dynamic_data_prefix.length )
let asset_id = current.get( "asset_id" );
if (asset_id) {
let asset_obj = this.getObject( asset_id );
if(asset_obj && asset_obj.set) {
asset_obj = asset_obj.set( "dynamic", current );
this.objects_by_id.set( asset_id, asset_obj );
}
}
} else if( object.id.substring(0,worker_prefix.length ) == worker_prefix ) {
// WORKER OBJECT
this.objects_by_vote_id.set( object.vote_for, object.id );
this.objects_by_vote_id.set( object.vote_against, object.id );
} else if( object.id.substring(0,bitasset_data_prefix.length) == bitasset_data_prefix ) {
// BITASSET DATA OBJECT
let asset_id = current.get( "asset_id" );
if( asset_id ) {
let asset = this.getObject( asset_id );
if( asset ) {
asset = asset.set( "bitasset", current );
emitter.emit("bitasset-update", asset);
this.objects_by_id.set( asset_id, asset );
}
}
} else if( object.id.substring(0,call_order_prefix.length ) == call_order_prefix ) {
// CALL ORDER OBJECT
// Update nested call_orders inside account object
if (emit) {
emitter.emit("call-order-update", object);
}
let account = this.objects_by_id.get(object.borrower);
if (account) {
if (!account.has("call_orders")) account = account.set("call_orders", new Immutable.Set());
let call_orders = account.get("call_orders");
if (!call_orders.has(object.id)) {
account = account.set("call_orders", call_orders.add(object.id));
this.objects_by_id.set( account.get("id"), account );
Apis.instance().db_api().exec("get_objects", [[object.id]]); // Force subscription to the object in the witness node by calling get_objects
}
}
}
else if( object.id.substring(0,order_prefix.length ) == order_prefix ) {
// LIMIT ORDER OBJECT
let account = this.objects_by_id.get(object.seller);
if (account) {
if (!account.has("orders")) account = account.set("orders", new Immutable.Set());
let limit_orders = account.get("orders");
if (!limit_orders.has(object.id)) {
account = account.set("orders", limit_orders.add(object.id));
this.objects_by_id.set( account.get("id"), account );
Apis.instance().db_api().exec("get_objects", [[object.id]]); // Force subscription to the object in the witness node by calling get_objects
}
}
// POROPOSAL OBJECT
} else if ( object.id.substring(0,proposal_prefix.length ) == proposal_prefix ) {
this.addProposalData(object.required_active_approvals, object.id);
this.addProposalData(object.required_owner_approvals, object.id);
}
if( notify_subscribers ) {
this.notifySubscribers();
}
return current;
}
getObjectsByVoteIds( vote_ids )
{
let result = [];
let missing = [];
for( let i = 0; i < vote_ids.length; ++i )
{
let obj = this.objects_by_vote_id.get( vote_ids[i] );
if( obj )
result.push(this.getObject( obj ) );
else
{
result.push( null );
missing.push( vote_ids[i] );
}
}
if( missing.length ) {
// we may need to fetch some objects
Apis.instance().db_api().exec( "lookup_vote_ids", [ missing ] )
.then( vote_obj_array => {
if (DEBUG) console.log( "missing ===========> ", missing );
if (DEBUG) console.log( "vote objects ===========> ", vote_obj_array );
for( let i = 0; i < vote_obj_array.length; ++i )
{
if( vote_obj_array[i] )
{
let isWitness = vote_obj_array[i].id.substring(0, witness_prefix.length ) == witness_prefix;
this._subTo(isWitness ? "witnesses" : "committee", vote_obj_array[i].id);
this._updateObject( vote_obj_array[i] );
}
}
}, error => { if (DEBUG) console.log( "Error looking up vote ids: ", error ) } );
}
return result;
}
getObjectByVoteID( vote_id )
{
let obj_id = this.objects_by_vote_id.get( vote_id );
if( obj_id ) return this.getObject( obj_id );
return undefined;
}
getHeadBlockDate() {
return timeStringToDate( this.head_block_time_string );
}
getEstimatedChainTimeOffset() {
if( this.chain_time_offset.length === 0 ) return 0;
// Immutable is fast, sorts numbers correctly, and leaves the original unmodified
// This will fix itself if the user changes their clock
var median_offset = Immutable.List(this.chain_time_offset)
.sort().get(Math.floor( (this.chain_time_offset.length - 1) / 2 ));
// console.log("median_offset", median_offset)
return median_offset;
}
addProposalData(approvals, objectId) {
approvals.forEach(id => {
let impactedAccount = this.objects_by_id.get(id);
if (impactedAccount) {
let proposals = impactedAccount.get("proposals", Immutable.Set());
if (!proposals.includes(objectId)) {
proposals = proposals.add(objectId);
impactedAccount = impactedAccount.set("proposals", proposals);
this._updateObject( impactedAccount.toJS() );
}
}
});
}
}
let chain_store = new ChainStore();
function FetchChainObjects(method, object_ids, timeout, subMap) {
let get_object = method.bind(chain_store);
return new Promise((resolve, reject) => {
let timeout_handle = null;
function onUpdate(not_subscribed_yet = false) {
let res = object_ids.map(id => {
if (method.name === "getAccount") return get_object(id, subMap[id]);
if (method.name === "getObject") return get_object(id, false, subMap[id]);
return get_object(id);
});
if (res.findIndex(o => o === undefined) === -1) {
if(timeout_handle) clearTimeout(timeout_handle);
if(!not_subscribed_yet) chain_store.unsubscribe(onUpdate);
resolve(res);
return true;
}
return false;
}
let resolved = onUpdate(true);
if(!resolved) chain_store.subscribe(onUpdate);
if(timeout && !resolved) timeout_handle = setTimeout(() => {
chain_store.unsubscribe(onUpdate);
reject("timeout");
}, timeout);
});
}
chain_store.FetchChainObjects = FetchChainObjects;
function FetchChain(methodName, objectIds, timeout = 1900, subMap = {}) {
let method = chain_store[methodName];
if( ! method ) throw new Error("ChainStore does not have method " + methodName);
let arrayIn = Array.isArray(objectIds);
if( ! arrayIn ) objectIds = [ objectIds ];
return chain_store.FetchChainObjects(method, Immutable.List(objectIds), timeout, subMap)
.then( res => arrayIn ? res : res.get(0) );
}
chain_store.FetchChain = FetchChain;
function timeStringToDate(time_string) {
if( ! time_string) return new Date("1970-01-01T00:00:00.000Z");
if( ! /Z$/.test(time_string)); //does not end in Z
time_string = time_string + "Z";
return new Date(time_string);
}
export default chain_store;
|
'use strict';
var _ = require('underscore'),
colors = require('colors/safe');
var prefix = colors.cyan('<npack>');
var addPreffix = function(args) {
args = _(args).clone();
if (args.length && _.isString(args[0])) {
args[0] = prefix + ' ' + args[0];
} else {
args.unshift(prefix);
}
return args;
};
exports.log = function() {
console.log.apply(console, addPreffix(_.toArray(arguments)));
};
exports.done = function(msg) {
exports.log.apply(null, [colors.green(msg)].concat(_(arguments).rest()));
};
exports.error = function() {
console.error.apply(console, addPreffix(_.toArray(arguments)));
};
exports.warn = function(msg) {
exports.log.apply(null, [colors.yellow(msg)].concat(_(arguments).rest()));
};
exports.logError = function(err, options) {
options = options || {};
exports.error(
colors.red(options.trace ? err.stack : ('Error: ' + err.message))
);
};
exports.writePkgInfo = function(pkgInfo, options) {
options = _({}).defaults(options, {
markCurrent: false,
spaces: 2
});
var spacesStr = (new Array(options.spaces + 1)).join(' ');
if (options.markCurrent && pkgInfo.current) {
console.log(
colors.green('%sname: %s [*current]'),
spacesStr,
pkgInfo.name
);
} else {
console.log('%sname: %s', spacesStr, pkgInfo.name);
}
console.log('%spath: %s', spacesStr, pkgInfo.path);
if (pkgInfo.npm) {
console.log('%snpm name: %s', spacesStr, pkgInfo.npm.name);
console.log('%snpm version: %s', spacesStr, pkgInfo.npm.version);
}
if (pkgInfo.compatibility) {
console.log('%scompatibility: %s', spacesStr, pkgInfo.compatibility);
}
if (!_(pkgInfo.hooks).isEmpty()) {
console.log('%shooks:', spacesStr);
_(pkgInfo.hooks).each(function(action, hook) {
console.log('%s %s: %s', spacesStr, hook, action);
});
}
if (!_(pkgInfo.scripts).isEmpty()) {
console.log('%sscripts: %s', spacesStr, _(pkgInfo.scripts).keys().join(', '));
}
};
exports.writePkgsList = function(pkgInfos, options) {
options = _({}).defaults(options, {
info: false,
spaces: 2
});
var spacesStr = (new Array(options.spaces + 1)).join(' ');
_(pkgInfos).each(function(pkgInfo, index) {
if (options.info && index ) console.log('');
var str = spacesStr + '[' + index + '] ' + pkgInfo.name;
if (pkgInfo.npm) {
str += ' (' + pkgInfo.npm.name + ' ' + pkgInfo.npm.version + ')';
}
if (pkgInfo.current) {
str += ' [*current]';
str = colors.green(str);
}
console.log(str);
if (options.info) {
exports.writePkgInfo(pkgInfo, {spaces: options.spaces + 2});
}
});
};
exports.writeScriptsList = function(scripts) {
_(scripts).each(function(script, name) {
console.log(' %s', name);
console.log(' %s', script || '-');
});
};
|
/* eslint-disable no-console */
const fsp = require('fs-promise');
const cp = require('child_process');
const webpack = require('webpack');
const webpackConfig = require('../webpack.config');
function buildClient() {
return new Promise((resolve, reject) => {
webpack(webpackConfig).run((err, stats) => {
if (err) {
reject(err);
}
console.log(stats.toString({
colors: true,
reasons: true,
hash: true,
version: true,
timings: true,
chunks: false,
chunkModules: false,
cached: false,
cachedAssets: false,
}));
resolve();
});
});
}
function buildServer() {
return new Promise((resolve, reject) => {
// cp.execFile('babel', ['src/server', '-d', 'dist/server'], (err, stdout, stderr) => {
cp.exec('babel src/server -d dist/server', (err, stdout, stderr) => {
if (stdout) {
console.info(stdout);
}
if (stderr) {
console.error(stderr);
}
if (err) {
reject(err);
}
resolve();
});
});
}
if (!fsp.existsSync('dist')) {
fsp.mkdirSync('dist');
}
fsp.copySync('src/public', 'dist/public');
Promise.all([
buildClient(),
buildServer(),
]).catch((err) => {
console.error('Could not build.', err);
});
|
/*
* Timeliner.js
* @version 1.5.1
* @copyright Tarek Anandan (http://www.technotarek.com)
*/
;
(function(e) {
var t;
e.timeliner = function(n) {
t = jQuery.extend({
timelineContainer: "#timelineContainer",
startState: "closed",
startOpen: [],
baseSpeed: 200,
speed: 4,
fontOpen: "1.2em",
fontClosed: "1em",
expandAllText: "+ expand all",
collapseAllText: "- collapse all"
}, n);
e(document).ready(function() {
function n(n, r) {
e(n).removeClass("closed").addClass("open").animate({
fontSize: t.fontOpen
}, t.baseSpeed);
e(r).show(t.speed * t.baseSpeed)
}
function r(n, r) {
e(n).animate({
fontSize: t.fontClosed
}, 0).removeClass("open").addClass("closed");
e(r).hide(t.speed * t.baseSpeed)
}
if (t.startState === "closed") {
e(".timelineEvent").hide();
e.each(e(t.startOpen), function(t, r) {
n(e(r).parent(".timelineMinor").find("dt a"), e(r))
})
} else {
n(e(".timelineMinor dt a"), e(".timelineEvent"))
}
e(t.timelineContainer).on("click", ".timelineMinor dt", function() {
var t = e(this).attr("id");
if (e(this).find("a").is(".open")) {
r(e("a", this), e("#" + t + "EX"))
} else {
n(e("a", this), e("#" + t + "EX"))
}
});
e(t.timelineContainer).on("click", ".timelineMajorMarker", function() {
var t = e(this).parents(".timelineMajor").find(".timelineMinor").length;
var i = e(this).parents(".timelineMajor").find(".open").length;
if (t > i) {
n(e(this).parents(".timelineMajor").find("dt a", "dl.timelineMinor"), e(this).parents(".timelineMajor").find(".timelineEvent"))
} else {
r(e(this).parents(".timelineMajor").find("dl.timelineMinor a"), e(this).parents(".timelineMajor").find(".timelineEvent"))
}
});
e(".expandAll").click(function() {
if (e(this).hasClass("expanded")) {
r(e(this).parents(t.timelineContainer).find("dt a", "dl.timelineMinor"), e(this).parents(t.timelineContainer).find(".timelineEvent"));
e(this).removeClass("expanded").html(t.expandAllText)
} else {
n(e(this).parents(t.timelineContainer).find("dt a", "dl.timelineMinor"), e(this).parents(t.timelineContainer).find(".timelineEvent"));
e(this).addClass("expanded").html(t.collapseAllText)
}
})
})
}
})(jQuery);
|
initSidebarItems({"struct":[["Background","Handle to the reactor running on a background thread."],["Handle","A reference to a reactor."],["PollEvented2","Associates an I/O resource that implements the `std::io::Read` and/or `std::io::Write` traits with the reactor that drives it."],["Reactor","The core reactor, or event loop."],["Registration","Associates an I/O resource with the reactor instance that drives it."],["Turn","Return value from the `turn` method on `Reactor`."]]});
|
// pngy by Nathan Ford - pngy.artequalswork.com
pngy = function (ob) {
var defaults = {
loadspeed : false,
loadsize : false,
selector : '.pngy',
display_results : false,
apply_to_all_imgs: false,
limits : {
fast : 40,
normal : 10,
slow : 0
},
base: 'slow'
}, p = new Object(), inittime;
// pull in custom setting or use defaults
if (ob) for (k in defaults) p[k] = (ob[k] != undefined) ? ob[k] : defaults[k];
else p = defaults;
// add all IMGs to p.selector if apply_to_all_imgs is true
if (p.apply_to_all_imgs) p.selector += ', img';
// get all elements that match the selector
p.imgs = $(p.selector);
if ($(p.imgs).length) { // only run the rest if there are elements that match p.selector
var pngy1 = (p.imgs[0].tagName == 'IMG') ? $(p.imgs[0]).attr('src') : $(p.imgs[0]).css('background-image').replace('url("','').replace('")','');
$.ajax({
url: pngy1 + '?' + Math.random(), // pngy1
beforeSend: function () {
// get time before ajax request
var initdate = new Date();
inittime = initdate.getTime();
},
success: function (d) {
var loaddate = new Date(), limits = [], i = 0, j = 0;
// get image size in Kb
if (!p.loadsize) p.loadsize = d.length / 1024;
// get loadspeed in seconds
if (!p.loadspeed) p.loadspeed = (loaddate.getTime() - inittime) / 1000;
// get Kbs
p.mbs = Math.floor((p.loadsize / p.loadspeed) * 100) / 100;
// output speed if display_results has a selector
$(p.display_results).html(p.mbs + ' Kbs');
// uncomment to get a log of your load speed
//console.log('Load speed: ' + p.mbs + ' Kbs');
// reorder limits to highest to lowest
for (k in p.limits) limits.push([k, p.limits[k]]);
limits.sort(function(a, b) {return a[1] - b[1]});
limits.reverse();
// find the limit
while (limits[i]) {
p.speed = limits[i][0];
if (limits[i][1] < p.mbs) break;
i++;
}
p.base = limits[limits.length-1][0];
// edit image paths
while( p.imgs[j] ) {
var t = p.imgs[j], reg = new RegExp("(\-" + p.base + "\.([A-Za-z]{3,4})\"*)$");
if (t.tagName == 'IMG')
$(t).attr('src', $(t).attr('src').replace(reg, '-' + p.speed + ".$2"));
else
$(t).css('background-image', 'url(' + $(t).css('background-image').replace('url("','').replace('")','').replace(reg, '-' + p.speed + ".$2") + ')');
j++;
}
}
});
}
};
|
/**
*
*/
angular.module( 'sp4k.parents.items', [
'resources.parents',
'ui.router'
])
.config(function config( $stateProvider ) {
})
/**
* And of course we define a controller for our route.
*/
.controller( 'ParentsItemsCtrl', function ParentsItemsController(
$scope, $mdSidenav, $timeout, $log, parentsData, parentsRestService, AutocompleteParents
) {
console.log(AutocompleteParents.parent);
this.items = parentsData.items;
this.total_items = parentsData.count;
this.pageSize = 20;
this.currentPage = 1;
this.filters = {
state: '1'
};
this.count = 0;
//this.filters.parent = AutocompleteParents().parent;
$scope.$watch(function(){return AutocompleteParents.getParent()},
angular.bind(this, function(newVal,oldVal){
this.filters.id = newVal.id;
}),
true
);
$scope.$watch(
angular.bind(this,
function (currentPage) {
return this.currentPage;
}
),
angular.bind(this ,
function(newVal,oldVal) {
if(newVal !== oldVal){
this.getPage(newVal);
}
}
)
);
$scope.$watch(
angular.bind(this,
function (filters) {
return this.filters;
}
),
angular.bind(this ,
function(newVal,oldVal) {
if(newVal !== oldVal){
this.count = 1;//changing filters will change the number of results so get the count so that we can adjust the pagination
if(this.currentPage == 1)
{
//if its already one, just fire the getPage() function to get the new data
this.getPage();
}else{
//if we aren't on page 1, just change it and let the watcher fire the getPage() function.
this.currentPage = 1;
}
}
}
),
true//deep watch
);
this.getPage = function(){
var limit = {};
limit.limit = this.pageSize;
limit.offset = (this.currentPage-1) * this.pageSize;
if(this.count){
var result = parentsRestService.get( { paging:true, filters:this.filters, limit:limit, count:this.count} );
}else{
var result = parentsRestService.query( { paging:true, filters:this.filters, limit:limit, count:this.count}) ;
}
result.$promise.then(
angular.bind(this,
function(){
if(this.count){
this.total_items = result.count;
this.items = result.items;
this.count = 0;
}else{
this.items = result;
}
//turn it back off for the next query.
}
)
);
};
/*
* Toggle Left Slidout Filterbar.
*/
this.toggleLeft = buildDelayedToggler('left');
this.isOpenLeft = function(){
return $mdSidenav('left').isOpen();
};
function debounce(func, wait, context) {
var timer;
return function debounced() {
var context = $scope,
args = Array.prototype.slice.call(arguments);
$timeout.cancel(timer);
timer = $timeout(function() {
timer = undefined;
func.apply(context, args);
}, wait || 10);
};
}
/**
* Build handler to open/close a SideNav; when animation finishes
* report completion in console
*/
function buildDelayedToggler(navID) {
return debounce(function() {
$mdSidenav(navID)
.toggle()
.then(function () {
$log.debug("toggle " + navID + " is done");
});
}, 200);
}
function buildToggler(navID) {
return function() {
$mdSidenav(navID)
.toggle()
.then(function () {
$log.debug("toggle " + navID + " is done");
});
}
}
})
.controller('LeftCtrl', function ($scope, $timeout, $mdSidenav, $log) {
$scope.close = function () {
$mdSidenav('left').close()
.then(function () {
$log.debug("close LEFT is done");
});
};
})
//.controller('ParentSearchCtrl',function ParentSearchController( $scope, $log, parentsRestService ){
// this.parent = {};
// this.searchText = '';
// this.searchTextChange = function(text){
// this.searchText = text;
// };
// this.selectedItemChange = function(item)
// {
// $log.log(item);
// };
//
// this.querySearch = function(searchText){
// if(searchText.length > 3){
// console.log(searchText);
// var q = {};
// q.name = searchText;
// var limit = {};
// limit.offset = 0;
// limit.limit = 50;
// return parentsRestService.query({q:q,limit:limit}).$promise;
// }
// };
//})
//.filter('yesno',function(){
// return function(value){
// return value === '1' ? 'Yes' : 'No'
// };
//})
;
|
/* @flow */
import invariant from "invariant";
import type { MethodApi } from "../types";
export default ({ client }: MethodApi) => (fileid: number, tofolderid: number): Promise<boolean> => {
invariant(typeof fileid === "number", "`fileid` must be number.");
invariant(fileid !== 0, "`fileid` cannot be 0.");
invariant(tofolderid, "`tofolderid` is required.");
return client
.api("renamefile", {
params: {
fileid: fileid,
tofolderid: tofolderid,
},
})
.then(response => response.metadata);
};
|
#!/usr/bin/env node-canvas
/*jslint indent: 2, node: true */
/*global Image: true */
"use strict";
var Canvas = require('../lib/canvas');
var Image = Canvas.Image;
var canvas = new Canvas(200, 200);
var ctx = canvas.getContext('2d');
var fs = require('fs');
var eu = require('./util');
var shapes = require('./shapes');
var squareSize = 120;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(0, 0, 150, 150);
ctx.fillStyle = '#ff8000';
shapes.drawSquare(ctx, squareSize);
ctx.save();
ctx.translate(0, canvas.height - squareSize);
ctx.fillStyle = '#0080ff';
shapes.drawSquare(ctx, squareSize);
ctx.restore();
ctx.save();
ctx.translate(canvas.width - squareSize, canvas.height - squareSize);
ctx.fillStyle = '#8000ff';
shapes.drawSquare(ctx, squareSize);
ctx.restore();
ctx.save();
ctx.translate(canvas.width - squareSize, 0);
ctx.fillStyle = '#ff0080';
shapes.drawSquare(ctx, squareSize);
ctx.restore();
var img = ctx.getImageData(0, 0, 120, 120);
ctx.putImageData(img, 200, 200);
ctx.putImageData(img, 400, 200);
ctx.putImageData(img, 200, 400);
ctx.putImageData(img, 400, 400);
canvas.vgSwapBuffers();
eu.waitForInput();
|
export function initialize(app) {
app.deferReadiness();
let container = app.__container__;
container.lookup('service:dofus-data').loadDofusData().then(function() {
app.advanceReadiness();
});
}
export default {
name: 'dofus-data',
initialize
};
|
/*!
* jQuery Show when empty
* http://jquery.com/
*
* Copyright 2015 Júlio César <talk@juliocesar.me>
* Released under the MIT license
* http://jquery.org/license
*
*
*/
(function ( $ ) {
// Init Plugin Statement
$.fn.swe = function() {
// Loop by each element
this.each(function () {
// Get Master Element (Element that is checked if is empty)
var master = $(this);
// Check if master have swe (Show when empty data)
if(master.data('swe')) {
// Get Show element
var e = master.data('swe');
// Get effects from data
var effects = master.data('swe-effect') ? master.data('swe-effect') : 'show/hide';
// Split effects
effects = effects.split('/');
// Check if swe exists
if($(e).length) {
// Check if master have children
if($(master).children().length == 0) {
// Run the effect
$(e)[effects[0]]();
} else {
// Run the effect
$(e)[effects[1]]();
}
}
}
});
return this;
};
// Apply SWE to all elements with swe data
$(document).on('DOMSubtreeModified', '[data-swe!=""]', function () {
// Run the plugin
$(this).swe();
}).ready(function () {
// Run the plugin
$('[data-swe!=""]').swe();
});
}( jQuery ));
|
import minimatch from 'minimatch';
import arrayUnion from 'array-union';
import arrayDiffer from 'array-differ';
export default function multimatch(list, patterns, options = {}) {
list = [list].flat();
patterns = [patterns].flat();
if (list.length === 0 || patterns.length === 0) {
return [];
}
let result = [];
for (const item of list) {
for (let pattern of patterns) {
let process = arrayUnion;
if (pattern[0] === '!') {
pattern = pattern.slice(1);
process = arrayDiffer;
}
result = process(result, minimatch.match([item], pattern, options));
}
}
return result;
}
|
(function($) {
/**
* Base class for effects creating circles
*/
Coo.Effect._Circle = Coo.Effect._Base.extend({
_numCircles: 10, // {Number} The number of circles
_minDiameter: null,
_createCircles: function(element) {
this._slider.$viewPort.find('.' + this._slider.getOption('classPrefix') + 'clone').remove();
this._numCircles = this._slider.getOption('circles') || 10;
if (Math.round(this._slider.$viewPort.width()) % 2 == 0) {
this._numCircles--;
}
this._minDiameter = this._slider.$viewPort.width() / this._numCircles;
var $img = $(element).is('img') ? $(element) : $(element).find('img:first'),
zIndex = 100;
for (var i = 0; i < this._numCircles; i++) {
var width = (i + 1) * this._minDiameter;
// Use backgroundSize property to set the size of background image
$('<div/>')
.css({
backgroundImage: 'url(' + $img.attr('src') + ')',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
backgroundSize: this._slider.$viewPort.width() + 'px ' + this._slider.$viewPort.height() + 'px',
height: width + 'px',
width: width + 'px',
opacity: 0,
overflow: 'hidden',
position: 'absolute',
left: (this._slider.$viewPort.width() / 2) - (width / 2),
top: (this._slider.$viewPort.height() / 2) - (width / 2),
zIndex: zIndex--
})
.addClass(this._slider.getOption('classPrefix') + 'circle')
.addClass(this._slider.getOption('classPrefix') + 'clone')
.attr('data-circle', i)
.appendTo(this._slider.$viewPort);
}
},
clean: function() {
this._slider.$viewPort.find('.' + this._slider.getOption('classPrefix') + 'clone').remove();
},
getFeatures: function() {
return ['css3'];
},
getClass: function() {
return 'Coo.Effect._Circle';
},
_supportByBrowser: function() {
// backgroundSize is not supported in IE8 and earlier
var ie = Coo.Browser.ie();
return (ie == undefined || ie >= 9);
}
});
})(window.jQuery);
|
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== document.activeElement && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === document.activeElement && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 10+
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox 10+
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
|
module.exports = function (e) {
function tree (e, ordered, parent, path) {
let index = ordered.indexOf(e)
if (!~index) {
index = ordered.length
ordered.push(e)
}
const seen = path.indexOf(index)
if (~seen) {
return { type: 'cycle', index: index, parent: parent }
}
const node = {
id: nodes.length,
index: index,
message: e instanceof Error ? e.message : e.toString(),
parent: parent,
errors: []
}
nodes.push(node)
if (e instanceof Error) {
const errors = Array.isArray(e.errors) ? e.errors : []
for (let i = 0, I = errors.length; i < I; i++) {
node.errors.push(tree(errors[i], ordered, node.id, path.concat(index)))
}
}
return node
}
const node = {
index: '?',
parent: 0,
errors: null
}
const errors = [], nodes = [ null, node ]
nodes[1].errors = [ tree(e, errors, 1, []) ]
return { node, errors, nodes }
}
|
import { warn } from '@ember/debug';
import renderChart from 'ember-google-charts/utils/render-chart';
export default function renderClassicChart(data, options) {
warn(`renderClassicChart() has been deprecated. Use renderChart() instead. See https://github.com/sir-dunxalot/ember-google-charts#custom-charts`, {
id: 'ember-google-charts.unified-render-util',
});
const {
design,
element,
type,
} = this;
return renderChart(element, {
data,
design,
options,
type,
});
}
|
/*
* grunt-i18n
* https://github.com/falsanu/grunt-i18n
*
* Copyright (c) 2015 Jan Fanslau
* Licensed under the MIT license.
*/
'use strict';
var jsSourceFilter = function(filename) {
return (filename.indexOf('js/source') === -1);
};
var nopFilter = function(filename) {
return filename !== null;
};
module.exports = function(grunt) {
// require('load-grunt-tasks')(grunt);
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('importlanguages', 'Imports PO-Files into given project.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
paths: {
pathToConfig: 'test/languages.json',
source: 'test/src',
i18n: {
base: 'i18n',
templates: 'test/i18n/templates/LC_MESSAGES',
pot: 'test/i18n/templates/LC_MESSAGES/messages.pot',
json: 'test/src/i18n'
}
}
});
grunt.config.data.clean.test = {
src: options.paths.i18n.json,
force: true
};
grunt.task.run('clean:test');
if (!grunt.config.data.copy) {
grunt.config.data.copy = {};
}
grunt.config.data.copy.importlanguages = {
files: [{
src: options.paths.i18n.base + '/**/*.po',
dest: options.paths.source,
expand: true,
flatten: false,
filter: nopFilter
}]
};
grunt.task.run('copy:importlanguages');
});
};
|
'use strict';
var mongoose = require('mongoose'),
Event = mongoose.model('Event');
exports.index = function (req, res) {
Event.find(function (err, articles) {
if (err) {
throw new Error(err);
}
res.render('home/index', {
title: 'Generator-Express MVC',
articles: articles
});
});
};
|
'use strict';var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var collection_1 = require('angular2/src/core/facade/collection');
var lang_1 = require('angular2/src/core/facade/lang');
var metadata_1 = require('../core/metadata');
var view_resolver_1 = require('angular2/src/core/compiler/view_resolver');
var MockViewResolver = (function (_super) {
__extends(MockViewResolver, _super);
function MockViewResolver() {
_super.call(this);
this._views = new collection_1.Map();
this._inlineTemplates = new collection_1.Map();
this._viewCache = new collection_1.Map();
this._directiveOverrides = new collection_1.Map();
}
/**
* Overrides the {@link ViewMetadata} for a component.
*
* @param {Type} component
* @param {ViewDefinition} view
*/
MockViewResolver.prototype.setView = function (component, view) {
this._checkOverrideable(component);
this._views.set(component, view);
};
/**
* Overrides the inline template for a component - other configuration remains unchanged.
*
* @param {Type} component
* @param {string} template
*/
MockViewResolver.prototype.setInlineTemplate = function (component, template) {
this._checkOverrideable(component);
this._inlineTemplates.set(component, template);
};
/**
* Overrides a directive from the component {@link ViewMetadata}.
*
* @param {Type} component
* @param {Type} from
* @param {Type} to
*/
MockViewResolver.prototype.overrideViewDirective = function (component, from, to) {
this._checkOverrideable(component);
var overrides = this._directiveOverrides.get(component);
if (lang_1.isBlank(overrides)) {
overrides = new collection_1.Map();
this._directiveOverrides.set(component, overrides);
}
overrides.set(from, to);
};
/**
* Returns the {@link ViewMetadata} for a component:
* - Set the {@link ViewMetadata} to the overridden view when it exists or fallback to the default
* `ViewResolver`,
* see `setView`.
* - Override the directives, see `overrideViewDirective`.
* - Override the @View definition, see `setInlineTemplate`.
*
* @param component
* @returns {ViewDefinition}
*/
MockViewResolver.prototype.resolve = function (component) {
var view = this._viewCache.get(component);
if (lang_1.isPresent(view))
return view;
view = this._views.get(component);
if (lang_1.isBlank(view)) {
view = _super.prototype.resolve.call(this, component);
}
var directives = view.directives;
var overrides = this._directiveOverrides.get(component);
if (lang_1.isPresent(overrides) && lang_1.isPresent(directives)) {
directives = collection_1.ListWrapper.clone(view.directives);
collection_1.MapWrapper.forEach(overrides, function (to, from) {
var srcIndex = directives.indexOf(from);
if (srcIndex == -1) {
throw new lang_1.BaseException("Overriden directive " + lang_1.stringify(from) + " not found in the template of " + lang_1.stringify(component));
}
directives[srcIndex] = to;
});
view = new metadata_1.ViewMetadata({ template: view.template, templateUrl: view.templateUrl, directives: directives });
}
var inlineTemplate = this._inlineTemplates.get(component);
if (lang_1.isPresent(inlineTemplate)) {
view = new metadata_1.ViewMetadata({ template: inlineTemplate, templateUrl: null, directives: view.directives });
}
this._viewCache.set(component, view);
return view;
};
/**
* Once a component has been compiled, the AppProtoView is stored in the compiler cache.
*
* Then it should not be possible to override the component configuration after the component
* has been compiled.
*
* @param {Type} component
*/
MockViewResolver.prototype._checkOverrideable = function (component) {
var cached = this._viewCache.get(component);
if (lang_1.isPresent(cached)) {
throw new lang_1.BaseException("The component " + lang_1.stringify(component) + " has already been compiled, its configuration can not be changed");
}
};
return MockViewResolver;
})(view_resolver_1.ViewResolver);
exports.MockViewResolver = MockViewResolver;
//# sourceMappingURL=view_resolver_mock.js.map
|
var options = { useTabToIndent: [true, 'partial', false] };
var optionsNode = document.getElementById('options');
var node, select, tmp;
for (var i in options) {
node = document.createElement('div');
select = document.createElement('select');
for (var j in options[i]) {
tmp = document.createElement('option');
tmp.innerHTML = options[i][j].toString();
tmp.value = j;
if (editor.options[i] === options[i][j]) {
tmp.selected = true;
}
select.appendChild(tmp);
}
node.innerHTML = i.toString() + ': ';
node.appendChild(select);
optionsNode.appendChild(node);
node.addEventListener('change', function() {
editor.options[i] = options[i][select.options[select.selectedIndex].value];
});
}
|
Template._topic.helpers({
alreadyVoted: function() {
return Meteor.user() && _(Meteor.user().profile.votedTopicIds).contains(this._id)
},
hasComments: function() {
return this.numberOfComments > 0;
}
});
Template._topic.events({
'click [data-vote]': function(event, template) {
event.preventDefault();
if (!Meteor.user()) {
alert(TAPi18n.__("Log in with Meetup to vote!"));
return false;
}
var alreadyVoted = _(Meteor.user().profile.votedTopicIds).contains(this._id);
if (!alreadyVoted) {
Meteor.call('voteOnTopic', this);
}
},
'click [data-remove]': function(event, template) {
event.preventDefault();
if(Roles.userIsInRole(Meteor.userId(), ['admin'])) {
if (confirm(TAPi18n.__("Are you sure you want to remove this topic"))) {
Topics.remove({_id: this._id});
}
}
}
});
|
var authShit = require('./controllers/auth'),
dashShit = require('./controllers/dash')
user = require('./models/auth.schema.js');
module.exports = (app) => {
app.get('/', (req, res)=>{
res.sendFile('index.html', {root : './public/html'});
});
app.get('/dashboard', (req,res)=>{
res.sendFile('dashboard.html', {root:'./public/html'});
});
app.post('/register', authShit.registerUser);
app.post('/login', authShit.loginUser);
app.get('/me',authShit.me);
app.post('/season', authShit.season);
app.post('/questions', authShit.questions);
app.get('/designs', dashShit.getDesigns);
}
|
(function(sim, undefined) {
stc.Node = function(name, owner) {
var self = this;
this.name = name;
this.owner = owner;
this.color = this.owner.color;
this.type = 'node';
this.mouse = false;
};
})(stc)
|
// .mocharc.js
module.exports = {
diff: true,
extension: ['ts', 'tsx', 'js'], // include extensions
opts: './mocha.opts', // point to you mocha options file. the rest is whatever.
package: './package.json',
reporter: 'spec',
slow: 75,
timeout: 2000,
ui: 'bdd'
};
|
const job = require('./index');
job.refactorAllInDirectory(process.argv[2], [
require('./rewriters/labelRewriter')
]);
|
/*globals define, _, WebGMEGlobal*/
/*jshint browser: true*/
/**
* Generated by VisualizerGenerator 1.7.0 from webgme on Tue Sep 27 2016 23:15:32 GMT-0500 (Central Daylight Time).
*/
define([
'js/PanelBase/PanelBaseWithHeader',
'js/PanelManager/IActivePanel',
'widgets/CommViz/CommVizWidget',
'./CommVizControl'
], function (
PanelBaseWithHeader,
IActivePanel,
CommVizWidget,
CommVizControl
) {
'use strict';
var CommVizPanel;
CommVizPanel = function (layoutManager, params) {
var options = {};
//set properties from options
options[PanelBaseWithHeader.OPTIONS.LOGGER_INSTANCE_NAME] = 'CommVizPanel';
options[PanelBaseWithHeader.OPTIONS.FLOATING_TITLE] = true;
//call parent's constructor
PanelBaseWithHeader.apply(this, [options, layoutManager]);
this._client = params.client;
//initialize UI
this._initialize();
this.logger.debug('ctor finished');
};
//inherit from PanelBaseWithHeader
_.extend(CommVizPanel.prototype, PanelBaseWithHeader.prototype);
_.extend(CommVizPanel.prototype, IActivePanel.prototype);
CommVizPanel.prototype._initialize = function () {
var self = this;
//set Widget title
this.setTitle('');
this.widget = new CommVizWidget(this.logger, this.$el, this._client);
this.widget.setTitle = function (title) {
self.setTitle(title);
};
this.control = new CommVizControl({
logger: this.logger,
client: this._client,
widget: this.widget
});
this.onActivate();
};
/* * * * * * * * Toolbar related Functions * * * * * * * */
CommVizPanel.prototype.getSplitPanelToolbarEl = function() {
this._splitPanelToolbarEl = IActivePanel.prototype.getSplitPanelToolbarEl.call(this);
// Set the size bigger than 40 x 40 and add some padding for the scroll-bar.
this._splitPanelToolbarEl.css({
'padding-right': '10px'
});
this.widget._addSplitPanelToolbarBtns(this._splitPanelToolbarEl);
return this._splitPanelToolbarEl;
};
/* OVERRIDE FROM WIDGET-WITH-HEADER */
/* METHOD CALLED WHEN THE WIDGET'S READ-ONLY PROPERTY CHANGES */
CommVizPanel.prototype.onReadOnlyChanged = function (isReadOnly) {
//apply parent's onReadOnlyChanged
PanelBaseWithHeader.prototype.onReadOnlyChanged.call(this, isReadOnly);
};
CommVizPanel.prototype.onResize = function (width, height) {
this.logger.debug('onResize --> width: ' + width + ', height: ' + height);
this.widget.onWidgetContainerResize(width, height);
};
/* * * * * * * * Visualizer life cycle callbacks * * * * * * * */
CommVizPanel.prototype.destroy = function () {
this.control.destroy();
this.widget.destroy();
PanelBaseWithHeader.prototype.destroy.call(this);
WebGMEGlobal.KeyboardManager.setListener(undefined);
};
CommVizPanel.prototype.onActivate = function () {
this.widget.onActivate();
this.control.onActivate();
WebGMEGlobal.KeyboardManager.setListener(this.widget);
};
CommVizPanel.prototype.onDeactivate = function () {
this.widget.onDeactivate();
this.control.onDeactivate();
WebGMEGlobal.KeyboardManager.setListener(undefined);
};
return CommVizPanel;
});
|
(function() {
'use strict';
})();
/*global angular, $snaphy, $*/
angular.module($snaphy.getModuleName())
/**
Defigning custom templates for angular-formly.
*/
.run(['formlyConfig', '$timeout', function(formlyConfig, $timeout) {
formlyConfig.setType({
name: 'belongsTo',
templateUrl: '/formlyTemplate/views/autocomplete.html',
controller: ["$scope", function($scope) {
//set initial view..
$scope.to.hide = $scope.to.hide !== undefined? $scope.to.hide : false;
//Where tracker object for tracking where where values..
var whereTracker = {};
//Set the value initially to hide position..
$scope.hide = $scope.to.hide;
$scope.display = $scope.to.display !== undefined ? $scope.to.display : true;
$scope.showOrHide = function(){
if($scope.hide){
//Show opposite
return "show";
}else{
return "hide";
}
};
var trackWhere = function(){
//If where query added for filter..
if($scope.to.where){
//Form the where query..
for(var key in $scope.to.where){
if($scope.to.where.hasOwnProperty(key)){
var keyObj = $scope.to.where[key];
whereTracker[key] = keyObj;
}
}
}
//Now reset where..
$scope.to.where = {};
/**
* Watch the model change for applying the where query..
* @param {String} whereKey key of the where object
* @param {String} mainModelObj value of the where object.
* @example
* "where":{
"postId": {
"relationName": "post",
"relationKey": "id",
"key": "postId"
}
}
*/
//Watch for monotoring the where model for perfect search.
$scope.$watch("model",
function() {
if(whereTracker){
//RUn a loop and add all value to where..
for(var whereKey in whereTracker){
if(whereTracker.hasOwnProperty(whereKey)){
var mainModelObj = whereTracker[whereKey];
if(mainModelObj){
//var key = mainModelObj.key;
var relationName = mainModelObj.relationName;
var relationKey = mainModelObj.relationKey;
if(typeof mainModelObj === "string"){
/*
IN case if where key and value is already given static way..
"where":{
"type": "category"
}
*/
//Just add the value to the key..
$scope.to.where[whereKey] = mainModelObj;
}else{
if($scope.model[whereKey]){
$timeout(function() {
$scope.to.where[whereKey] = $scope.model[whereKey];
}, 0);
}
else if(relationName && relationKey){
if($scope.model[relationName]){
if($scope.model[relationName][relationKey]){
$timeout(function() {
$scope.to.where[whereKey] = $scope.model[relationName][relationKey];
}, 0);
}else{
$timeout(function() {
$scope.to.where[whereKey] = null;
}, 0);
}
}else{
$timeout(function() {
$scope.to.where[whereKey] = null;
}, 0);
}
}else{
$timeout(function() {
$scope.to.where[whereKey] = null;
}, 0);
}
}
} //if
}
}
}
},
true
);
}; //trackWhere
trackWhere();
if($scope.to.init){
//Display show create if forcefully displayed set to true..
$scope.forceDisplayAddFields = true;
}else{
//Display show create if forcefully displayed set to false..
$scope.forceDisplayAddFields = false;
}
$scope.$watch("model[options.key]",
function() {
if($scope.model[$scope.options.key] === undefined && $scope.forceDisplayAddFields && $scope.to.create){
$timeout(function() {
$scope.model[$scope.options.key] = {};
},0);
}
}
);
$scope.isHidden = function(){
return $scope.hide;
};
$scope.toggleShow = function(){
$scope.hide = !$scope.hide;
return $scope.hide;
};
$scope.showSearch = function(){
if($scope.to.search !== undefined){
if($scope.to.search ){
return true;
}
else {
return false;
}
}else{
return true;
}
};
$scope.resetCreate = resetCreate;
$scope.showCreate = function() {
//Display show create if forcefully displayed set to true..
if($scope.forceDisplayAddFields){
return true;
}
//if create is true then show only
if($scope.to.create || $scope.to.create === undefined){
//model has value then put create == true
var containValue = $.isEmptyObject($scope.model[$scope.options.key]);
if (containValue) {
//put $scope.create == false;
$scope.create = false;
} else {
$scope.create = true;
}
return $scope.create;
}
else{
return false;
}
};
function resetCreate() {
$timeout(function() {
$scope.model[$scope.options.key] = {};
//Set the forceDisplay option to false..
$scope.forceDisplayAddFields = false;
}, 0);
}
$scope.forceDisplay = function() {
//Just add a dummy property.
if ($scope.to.fields.length) {
$timeout(function() {
$scope.model[$scope.options.key] = {};
$scope.model[$scope.options.key][$scope.to.fields[0].key] = "";
$scope.forceDisplayAddFields = true;
}, 0);
}
};
$scope.getName = function(){
if($scope.to.name){
return $scope.to.name;
}
return $scope.getId();
};
$scope.getId = function(){
if($scope.to.id){
return $scope.to.id;
}
//fetch a random id..
$scope.to.id = getRandomInt();
return $scope.to.id;
};
}]
});
formlyConfig.setType({
name: 'repeatSection',
templateUrl: '/formlyTemplate/views/hasManyTemplate.html',
controller: ["$scope", function($scope) {
$scope.to.hide = $scope.to.hide || false;
//Set the value initially to hide position..
$scope.hide = $scope.to.hide;
$scope.showOrHide = function(){
if($scope.hide){
//Show opposite
return "show";
}else{
return "hide";
}
};
$scope.isHidden = function(){
return $scope.hide;
};
$scope.toggleShow = function(){
$scope.hide = !$scope.hide;
return $scope.hide;
};
$scope.showSearch = function(){
if($scope.to.search !== undefined){
if($scope.to.search ){
return true;
}
else {
return false;
}
}else{
return true;
}
};
var unique = 1;
$scope.formOptions = {
formState: $scope.formState
};
$scope.addNew = addNew;
$scope.copyFields = copyFields;
function copyFields(fields) {
fields = angular.copy(fields);
addRandomIds(fields);
return fields;
}
function addNew() {
$scope.model[$scope.options.key] = $scope.model[$scope.options.key] || [];
var repeatsection = $scope.model[$scope.options.key];
//var lastSection = repeatsection[repeatsection.length - 1];
var newsection = {};
// if (lastSection) {
// newsection = angular.copy(lastSection);
// }
repeatsection.push(newsection);
}
if($scope.to.init === true){
//Add a new field..
$scope.addNew();
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function addRandomIds(fields) {
unique++;
angular.forEach(fields, function(field, index) {
if (field.fieldGroup) {
addRandomIds(field.fieldGroup);
return; // fieldGroups don't need an ID
}
if (field.templateOptions && field.templateOptions.fields) {
addRandomIds(field.templateOptions.fields);
}
field.id = field.id || (field.key + '_' + index + '_' + unique + getRandomInt());
});
}
}]
});
formlyConfig.setType({
name: 'arrayValue',
templateUrl: '/formlyTemplate/views/arrayTemplate.html',
link: function(scope, element, attrs) {},
controller: ["$scope", function($scope) {
var unique = 1;
$scope.formOptions = {
formState: $scope.formState
};
var methods = (function() {
//Run the constructor on start..
function init() {
//Initialize the methods..
if ($scope.model[$scope.options.key] === undefined) {
addNew();
} else {
if ($scope.model[$scope.options.key].length === 0) {
//Add one data to the begining ..
addNew();
}
}
}
function copyFields(fields) {
fields = angular.copy(fields);
addRandomIds(fields);
return fields;
}
function addNew() {
$scope.model[$scope.options.key] = $scope.model[$scope.options.key] || [];
var repeatsection = $scope.model[$scope.options.key];
//var lastSection = repeatsection[repeatsection.length - 1];
var newsection = {};
// if (lastSection) {
// newsection = angular.copy(lastSection);
// }
//console.log(newsection);
repeatsection.push(newsection);
}
function addRandomIds(fields) {
unique++;
angular.forEach(fields, function(field, index) {
if (field.fieldGroup) {
addRandomIds(field.fieldGroup);
return; // fieldGroups don't need an ID
}
if (field.templateOptions && field.templateOptions.fields) {
addRandomIds(field.templateOptions.fields);
}
field.id = field.id || (field.key + '_' + index + '_' + unique + getRandomInt(0, 9999));
});
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
//call the constructor method..
init();
return {
copyFields: copyFields,
addNew: addNew
};
})();
$scope.getName = function(){
if($scope.to.name){
return $scope.to.name;
}
return $scope.getId();
};
$scope.addNew = methods.addNew;
$scope.copyFields = methods.copyFields;
}]
});
/*
For adding object type values..
*/
formlyConfig.setType({
name: 'objectValue',
templateUrl: '/formlyTemplate/views/objectTemplate.html',
controller: ['$scope', function($scope) {
}],
link: function(scope, element) {
if(scope.model[scope.options.key] === undefined){
scope.model[scope.options.key] = {};
}
var updateData = function(modelDataObj, tempModelObj, property){
$timeout(function(){
tempModelObj[property] = modelDataObj[property];
});
};
scope.objModel = scope.model[scope.options.key] ;
scope.$watch('model[options.key]', function(value) {
if($.isEmptyObject( scope.model[scope.options.key] )){
scope.objModel = {};
}
for(var modelData in scope.model[scope.options.key]){
if(scope.model[scope.options.key].hasOwnProperty(modelData)){
if(scope.objModel[modelData] !== scope.model[scope.options.key][modelData]){
updateData(scope.model[scope.options.key], scope.objModel, modelData);
}
}
}
}, true);
scope.$watch('objModel', function(value) {
if(scope.model[scope.options.key] === undefined){
scope.model[scope.options.key] = {};
}
if(scope.objModel === undefined){
scope.objModel = scope.model[scope.options.key];
}
for(var modelData in scope.objModel){
if(scope.objModel.hasOwnProperty(modelData)){
if(scope.objModel[modelData] !== scope.model[scope.options.key][modelData]){
//Update the model..
scope.model[scope.options.key][modelData] = scope.objModel[modelData];
}
}
}
$timeout(function(){
scope.objModel = scope.model[scope.options.key];
});
}, true);
}
});
formlyConfig.setType({
name: 'multipleFileUpload',
templateUrl: '/formlyTemplate/views/multiFileUpload.html',
link: function(scope, element) {
// Randomize progress bars values
scope.addValue = function(value) {
$(element)
.find('.progress-bar')
.each(function() {
var $this = jQuery(this);
var $random = value + '%';
$this.css('width', $random);
});
};
},
controller: ['$scope', 'Upload', '$timeout', '$http', 'Database', 'SnaphyTemplate', 'ImageUploadingTracker',
function($scope, Upload, $timeout, $http, Database, SnaphyTemplate, ImageUploadingTracker) {
//Initialize the model..
$scope.model[$scope.options.key] = $scope.model[$scope.options.key] || [];
$scope.files = [];
var dbService;
var url;
if ($scope.options.templateOptions.containerModel) {
dbService = Database.loadDb($scope.options.templateOptions.containerModel);
} else if ($scope.options.templateOptions.url) {
url = $scope.options.templateOptions.url;
} else {
console.error("Either url property of containerModel is required in formly templateOptions for image uploading");
}
var uploadUrl;
if (dbService) {
uploadUrl = "/api/containers/" + $scope.options.templateOptions.containerName + "/upload";
} else {
uploadUrl = url.upload;
}
$scope.checkData = function() {
if ($scope.files.length) {
if ($scope.model[$scope.options.key] === undefined) {
$scope.model[$scope.options.key] = [];
}
return true;
} else {
return false;
}
};
/**
* Check if file is loaded from server or not.
* @param file
* @returns {boolean}
*/
$scope.loadFromServer = function(file) {
if(file){
if(file.progress){
return false;
}
if (file.result) {
return true;
}
return false;
}else{
return false;
}
};
$scope.loadUrl = function(file) {
//TODO adding medium for small images load..
if(file.result){
if(file.result.url){
if(file.result.url.unSignedUrl){
return file.result.url.unSignedUrl;
}
}
}
var url = "/api/containers/" + file.result.container + "/download/medium_" + file.result.name;
return url;
};
$scope.$watch('model[options.key].length', function(value) {
if ($scope.model[$scope.options.key]) {
$scope.model[$scope.options.key].forEach(function(modelData, index) {
if ($scope.files.length !== 0) {
var matchFound = false;
$scope.files.forEach(function(dataObj, index) {
if (dataObj.result.name === modelData.name) {
matchFound = true;
}
});
if (!matchFound) {
$scope.files.push({
result: modelData
});
}
} else {
$scope.files.push({
result: modelData
});
}
}); //model loop
} else {
//Clean files data too..
$scope.files = [];
}
}); //$watch
$scope.uploadFiles = function($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event) {
//Increment tracker..TODO CHECK HERE FOR ERROR POSIBILITY.
ImageUploadingTracker.incrementTracker();
//First initialize progress bar to zero..
$scope.addValue(0);
var file = $newFiles[0];
$scope.f = file;
var errFiles = $invalidFiles;
$scope.errFile = errFiles && errFiles[0];
//Only upload file if it is not a duplicate file..
if (file && $duplicateFiles.length === 0 && errFiles.length === 0) {
file.upload = Upload.upload({
url: uploadUrl,
data: {
file: file
}
});
file.upload.then(function(response) {
$timeout(function() {
//file.result = response.data.result.files.file[0];
file.result = response.data;
if ($scope.model[$scope.options.key] === undefined) {
$scope.model[$scope.options.key] = [];
}
//console.log(response);
//Adding data to the model.
$scope.model[$scope.options.key].push(file.result);
});
//Decrement tracker..TODO CHECK HERE FOR ERROR POSIBILITY.
ImageUploadingTracker.decrementTracker();
SnaphyTemplate.notify({
message: "Image successfully saved to server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
}, function(response) {
if (response.status > 0) {
//Decrement tracker..TODO CHECK HERE FOR ERROR POSIBILITY.
ImageUploadingTracker.decrementTracker();
SnaphyTemplate.notify({
message: "Error saving image to server. Please remove that image and try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
$scope.errorMsg = response.status + ': ' + response.data;
}
}, function(evt) {
$timeout(function() {
file.progress = Math.min(100, parseInt(100.0 *
evt.loaded / evt.total));
$scope.addValue(file.progress);
}, 10);
});
}else{
ImageUploadingTracker.decrementTracker();
}
};
//Delete the given image...
$scope.deleteImage = function(files, index) {
var backUpFile = files[index];
if (backUpFile.result) {
var fileName = backUpFile.result.name;
var containerName = $scope.options.templateOptions.containerName;
var filePath = '/api/containers/' + containerName + '/files/' + fileName;
//Now remove the file
files.splice(index, 1);
$scope.model[$scope.options.key].splice(index, 1);
//console.log(backUpFile);
// Simple DELETE request example:
//console.log(filePath);
if (dbService) {
dbService.removeFile({
container: containerName,
file: "original_" + fileName
}, function(values) {
console.log("file successfully deleted");
SnaphyTemplate.notify({
message: "Image successfully deleted from server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
if(fileName){
//var absFileName = fileName.replace(original, '');
//var originalFileName = "original_" + absFileName;
var mediumFileName = "medium_" + fileName;
var smallFileName = "small_" + fileName;
var thumbFilename = "thumb_" + fileName;
var deleteImage = function(dbService, containerName, fileName){
dbService.removeFile({
container: containerName,
file: fileName
}, function(){
//success do nothing..
}, function(){
//Error do nothing..
});
};
//Now delete all the related images too..
deleteImage(dbService, containerName, mediumFileName);
//deleteImage(dbService, containerName, originalFileName);
deleteImage(dbService, containerName, smallFileName);
deleteImage(dbService, containerName, thumbFilename);
}
}, function(err) {
console.error("error deleting file.");
SnaphyTemplate.notify({
message: "Error deleting image from server. Please try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
console.error(err);
//Add backup file ..
files.push(backUpFile);
$scope.model[$scope.options.key].push(backUpFile.result);
});
} else {
$http({
method: 'DELETE',
url: url.delete,
}).then(function successCallback(response) {
console.log("File successfully deleted.");
SnaphyTemplate.notify({
message: "Image successfully deleted from server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
}, function errorCallback(response) {
console.log(response);
SnaphyTemplate.notify({
message: "Error deleting image from server. Please try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
//Add backup file ..
files.push(backUpFile);
});
}
} else {
//simply remove the file
files.splice(index, 1);
$scope.model[$scope.options.key].splice(index, 1);
}
};
}
]
});
formlyConfig.setType({
name: 'dummy',
template:
'<div style="display:none" class="form-group">'+
'<div ng-class="[options.templateOptions.colSize, options.templateOptions.color]">'+
'<div class="form-material" ng-class="options.templateOptions.color">'+
'<input class="form-control" type="{{options.templateOptions.type}}" ng-class="options.templateOptions.class" name="{{options.templateOptions.id}}" id="{{options.templateOptions.id}}" ng-model="model[options.key]">'+
'<label for="{{options.templateOptions.id}}">{{options.templateOptions.label}}</label>'+
'</div>'+
'</div>'+
'</div>',
link: function(scope, element, attrs) {
// ID PROPERTY IS NEEDED FOR VALIDATE TO WORK
if(scope.options.templateOptions){
if(!scope.options.templateOptions.colSize){
scope.options.templateOptions.colSize = 'col-xs-12';
}
}//if
if(scope.model[scope.options.key] === ""){
//remove the option..
delete scope.model[scope.options.key];
}
}//link function..
});
formlyConfig.setType({
name: 'singleFileUpload',
templateUrl: '/formlyTemplate/views/singleFileUpload.html',
link: function(scope, element, attrs) {
// Randomize progress bars values
scope.addValue = function(value) {
$(element)
.find('.progress-bar')
.each(function() {
var $this = jQuery(this);
var $random = value + '%';
$this.css('width', $random);
});
};
},
controller: ['$scope', 'Upload', '$timeout', '$http', 'Database', 'SnaphyTemplate', 'ImageUploadingTracker',
function($scope, Upload, $timeout, $http, Database, SnaphyTemplate, ImageUploadingTracker) {
//Initialize the model..
$scope.model[$scope.options.key] = $scope.model[$scope.options.key] || {};
$scope.file = {};
var dbService;
var url;
if ($scope.options.templateOptions.containerModel) {
dbService = Database.loadDb($scope.options.templateOptions.containerModel);
} else if ($scope.options.templateOptions.url) {
url = $scope.options.templateOptions.url;
} else {
console.error("Either url property of containerModel is required in formly templateOptions for image uploading");
}
var uploadUrl;
if (dbService) {
uploadUrl = "/api/containers/" + $scope.options.templateOptions.containerName + "/upload";
} else {
uploadUrl = url.upload;
}
//TODO REMOVE this
//uploadUrl = "/api/AmazonImages/" + $scope.options.templateOptions.containerName + "/upload";
$scope.checkData = function() {
if ($scope.file) {
if ($scope.model[$scope.options.key] === undefined) {
$scope.model[$scope.options.key] = {};
}
return true;
} else {
return false;
}
};
/**
* Check if file is loaded from server or not.
* @param file
* @returns {boolean}
*/
$scope.loadFromServer = function(file) {
if(file){
if(file.progress){
return false;
}
if (file.result) {
return true;
/*//Check if file really has one params..
var count = 0;
for (var key in file) {
if (file.hasOwnProperty(key)) {
count++;
}
}
if (count === 3) {
return true;
} else {
return false;
}*/
}
return false;
}else{
return false;
}
};
/**
* Return the absolute url for loading file.
* @param file
* @returns {*}
*/
$scope.loadUrl = function(file) {
if(file){
if(file.result){
if(file.result.url){
if(file.result.url.unSignedUrl){
return file.result.url.unSignedUrl;
}
}
if(file.result.container){
return "/api/containers/" + file.result.container + "/download/medium_" + file.result.name;
}
}
}
return null;
};
$scope.$watch('model[options.key]', function() {
if (!$.isEmptyObject($scope.model[$scope.options.key])) {
var modelData = $scope.model[$scope.options.key];
if ($.isEmptyObject($scope.file)) {
//Just add the data..
$scope.file = $scope.file || {};
$scope.file.result = modelData;
} else {
if ($scope.file.result) {
if ($scope.file.result.name !== modelData.name) {
$scope.file = {};
$scope.file.result = modelData;
}
} else {
$scope.file = $scope.file || {};
$scope.file.result = modelData;
}
}
} else {
//Clean files data too..
$scope.file = {};
}
}); //$watch
$scope.uploadFiles = function($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event) {
if ($newFiles === null) {
return false;
}
//Increment tracker..TODO CHECK HERE FOR ERROR POSIBILITY.
ImageUploadingTracker.incrementTracker();
//First initialize progress bar to zero..
$scope.addValue(0);
var file = $newFiles[0];
$scope.file = file;
var errFiles = $invalidFiles;
$scope.errFile = errFiles && errFiles[0];
//Only upload file if it is not a duplicate file..
if (file && $duplicateFiles.length === 0 && errFiles.length === 0) {
file.upload = Upload.upload({
url: uploadUrl,
data: {
file: file,
container: $scope.options.templateOptions.containerName
}
});
file.upload.then(function(response) {
$timeout(function() {
//file.result = response.data.result.files.file[0];
//console.log(response.result);
file.result = response.data;
if ($scope.model[$scope.options.key] === undefined) {
$scope.model[$scope.options.key] = {};
}
//Adding data to the model.
$scope.model[$scope.options.key] = file.result;
});
//decrement the tracker..
ImageUploadingTracker.decrementTracker();
SnaphyTemplate.notify({
message: "Image successfully saved to server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
}, function(response) {
//decrement the tracker..
ImageUploadingTracker.decrementTracker();
if (response.status > 0) {
SnaphyTemplate.notify({
message: "Error saving image to server. Please remove the image and try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
$scope.errorMsg = response.status + ': ' + response.data;
}
}, function(evt) {
$timeout(function() {
file.progress = Math.min(100, parseInt(100.0 *
evt.loaded / evt.total));
$scope.addValue(file.progress);
}, 10);
});
}else{
ImageUploadingTracker.decrementTracker();
}
};
//Delete the given image...
$scope.deleteImage = function(file) {
var backUpFile = angular.copy(file);
if (backUpFile.result) {
var fileName = backUpFile.result.name;
var containerName = $scope.options.templateOptions.containerName;
//var filePath = '/api/containers/' + containerName + '/files/' + fileName;
//Now remove the file
file = {};
$scope.model[$scope.options.key] = {};
//console.log(backUpFile);
// Simple DELETE request example:
//console.log(filePath);
if (dbService) {
dbService.removeFile({
container: containerName,
file: "original_" + fileName
}, function() {
//console.log("file successfully deleted");
SnaphyTemplate.notify({
message: "Image successfully deleted from server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
//Now also delete the remaining..
if(fileName){
//var absFileName = fileName.replace(original, '');
//var originalFileName = "original_" + absFileName;
var mediumFileName = "medium_" + fileName;
var smallFileName = "small_" + fileName;
var thumbFilename = "thumb_" + fileName;
var deleteImage = function(dbService, containerName, fileName){
dbService.removeFile({
container: containerName,
file: fileName
}, function(){
//success do nothing..
}, function(){
//Error do nothing..
});
};
//Now delete all the related images too..
deleteImage(dbService, containerName, mediumFileName);
//deleteImage(dbService, containerName, originalFileName);
deleteImage(dbService, containerName, smallFileName);
deleteImage(dbService, containerName, thumbFilename);
}
}, function() {
//console.error("error deleting file.");
//console.error(err);
$timeout(function() {
//Add backup file ..
$scope.file = backUpFile;
$scope.model[$scope.options.key] = backUpFile.result;
}, 0);
SnaphyTemplate.notify({
message: "Error deleting image from server. Please try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
});
} else {
$http({
method: 'DELETE',
url: url.delete,
}).then(function successCallback() {
// console.log("File successfully deleted.");
SnaphyTemplate.notify({
message: "Image successfully deleted from server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
}, function errorCallback(response) {
//console.log(response);
//Add backup file ..
$scope.file = backUpFile;
SnaphyTemplate.notify({
message: "Error deleting image from server. Please try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
});
}
} else {
//simply remove the file
$scope.files = {};
$scope.model[$scope.options.key] = {};
}
};
}
]
});
formlyConfig.setType({
name: 'singlePDFUpload',
templateUrl: '/formlyTemplate/views/singlePDFUpload.html',
link: function(scope, element, attrs) {
// Randomize progress bars values
scope.addValue = function(value) {
$(element)
.find('.progress-bar')
.each(function() {
var $this = jQuery(this);
var $random = value + '%';
$this.css('width', $random);
});
};
},
controller: ['$scope', 'Upload', '$timeout', '$http', 'Database', 'SnaphyTemplate', 'ImageUploadingTracker',
function($scope, Upload, $timeout, $http, Database, SnaphyTemplate, ImageUploadingTracker) {
//Initialize the model..
$scope.model[$scope.options.key] = $scope.model[$scope.options.key] || {};
$scope.file = {};
$scope.options.templateOptions.maxSize = $scope.options.templateOptions.maxSize || "'20MB'";
$scope.options.templateOptions.pattern = $scope.options.templateOptions.pattern || 'application/*';
var dbService;
var url;
if ($scope.options.templateOptions.containerModel) {
dbService = Database.loadDb($scope.options.templateOptions.containerModel);
} else if ($scope.options.templateOptions.url) {
url = $scope.options.templateOptions.url;
} else {
console.error("Either url property of containerModel is required in formly templateOptions for file uploading");
}
var uploadUrl;
if (dbService) {
uploadUrl = "/api/containers/" + $scope.options.templateOptions.containerName + "/upload";
} else {
uploadUrl = url.upload;
}
//TODO REMOVE this
//uploadUrl = "/api/AmazonImages/" + $scope.options.templateOptions.containerName + "/upload";
$scope.checkData = function() {
if ($scope.file) {
if ($scope.model[$scope.options.key] === undefined) {
$scope.model[$scope.options.key] = {};
}
return true;
} else {
return false;
}
};
/**
* Check if file is loaded from server or not.
* @param file
* @returns {boolean}
*/
$scope.loadFromServer = function(file) {
if(file){
if(file.progress){
return false;
}
if (file.result) {
return true;
}
return false;
}else{
return false;
}
};
/*
Old Method
$scope.loadFromServer = function(file) {
if (file.result) {
//Check if file really has one params..
var count = 0;
for (var key in file) {
if (file.hasOwnProperty(key)) {
count++;
}
}
if (count === 3) {
return true;
} else {
return false;
}
}
return false;
};
*/
$scope.loadUrl = function(file) {
var url = "/api/containers/" + file.result.container + "/download/" + file.result.name;
return url;
};
$scope.$watch('model[options.key]', function() {
if (!$.isEmptyObject($scope.model[$scope.options.key])) {
var modelData = $scope.model[$scope.options.key];
if ($.isEmptyObject($scope.file)) {
//Just add the data..
$scope.file = $scope.file || {};
$scope.file.result = modelData;
} else {
if ($scope.file.result) {
if ($scope.file.result.name !== modelData.name) {
$scope.file = {};
$scope.file.result = modelData;
}
} else {
$scope.file = $scope.file || {};
$scope.file.result = modelData;
}
}
} else {
//Clean files data too..
$scope.file = {};
}
}); //$watch
$scope.uploadFiles = function($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event) {
if ($newFiles === null) {
return false;
}
//Increment tracker..TODO CHECK HERE FOR ERROR POSIBILITY.
ImageUploadingTracker.incrementTracker();
//First initialize progress bar to zero..
$scope.addValue(0);
var file = $newFiles[0];
$scope.file = file;
var errFiles = $invalidFiles;
$scope.errFile = errFiles && errFiles[0];
//Only upload file if it is not a duplicate file..
if (file && $duplicateFiles.length === 0 && errFiles.length === 0) {
file.upload = Upload.upload({
url: uploadUrl,
data: {
file: file,
container: $scope.options.templateOptions.containerName
}
});
file.upload.then(function(response) {
$timeout(function() {
//file.result = response.data.result.files.file[0];
//console.log(response.result);
file.result = response.data;
if ($scope.model[$scope.options.key] === undefined) {
$scope.model[$scope.options.key] = {};
}
//Adding data to the model.
$scope.model[$scope.options.key] = file.result;
});
//decrement the tracker..
ImageUploadingTracker.decrementTracker();
SnaphyTemplate.notify({
message: "File successfully saved to server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
}, function(response) {
//decrement the tracker..
ImageUploadingTracker.decrementTracker();
if (response.status > 0) {
SnaphyTemplate.notify({
message: "Error saving file to server. Please remove the file and try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
$scope.errorMsg = response.status + ': ' + response.data;
}
}, function(evt) {
$timeout(function() {
file.progress = Math.min(100, parseInt(100.0 *
evt.loaded / evt.total));
$scope.addValue(file.progress);
}, 10);
});
}else{
ImageUploadingTracker.decrementTracker();
}
};
//Delete the given image...
$scope.deleteImage = function(file) {
var backUpFile = angular.copy(file);
if (backUpFile.result) {
var fileName = backUpFile.result.name;
var containerName = $scope.options.templateOptions.containerName;
//var filePath = '/api/containers/' + containerName + '/files/' + fileName;
//Now remove the file
file = {};
$scope.model[$scope.options.key] = {};
//console.log(backUpFile);
// Simple DELETE request example:
//console.log(filePath);
if (dbService) {
dbService.removeFile({
container: containerName,
file: fileName
}, function() {
//console.log("file successfully deleted");
SnaphyTemplate.notify({
message: "File successfully deleted from server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
}, function() {
//console.error("error deleting file.");
//console.error(err);
$timeout(function() {
//Add backup file ..
$scope.file = backUpFile;
$scope.model[$scope.options.key] = backUpFile.result;
}, 0);
SnaphyTemplate.notify({
message: "Error deleting file from server. Please try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
});
} else {
$http({
method: 'DELETE',
url: url.delete
}).then(function successCallback() {
// console.log("File successfully deleted.");
SnaphyTemplate.notify({
message: "File successfully deleted from server.",
type: 'success',
icon: 'fa fa-check',
align: 'right'
});
}, function errorCallback(response) {
//console.log(response);
//Add backup file ..
$scope.file = backUpFile;
SnaphyTemplate.notify({
message: "Error deleting File from server. Please try again.",
type: 'danger',
icon: 'fa fa-times',
align: 'right'
});
});
}
} else {
//simply remove the file
$scope.files = {};
$scope.model[$scope.options.key] = {};
}
};
}
]
});
//Date template..
formlyConfig.setType({
name: 'date',
templateUrl:'/formlyTemplate/views/date.html',
link: function(scope, elem, attrs){
App.initHelpers(['datepicker']);
var getRandom = function(){
return Math.floor((Math.random()*6)+1);
};
scope.to.format = scope.to.format || "mm/dd/yyyy";
scope.to.id = scope.to.id || "date_" + getRandom();
scope.to.placeholder = scope.to.placeholder || "Enter date";
}
});
}]);
|
export loadWishes from './loadWishes';
export createWish from './createWish';
export destroyWish from './destroyWish';
export loadAuth from './loadAuth';
export login from './login';
export logout from './logout';
|
$(document).ready(function() {
// manually reset the hash to force the browser to go to the selected menu item on page refresh
var hash = window.location.hash;
window.location.hash = "";
window.location.hash = hash;
$('.coveo-slider-input').slider();
$('.coveo-datepicker').DatePicker({
mode: 'single',
inline: true,
date: new Date()
});
$('[title]').tooltip({
container: 'body'
});
var selectedTab;
if (window.location.hash) {
var selectedTabChild = $('.navigation-menu-section-item-link[href="' + window.location.pathname + window.location.hash + '"]');
selectedTab = selectedTabChild.parent().addClass('state-active');
} else {
var selectedTabParend = $('.navigation-menu-section-item-link[href*="' + window.location.pathname + '"]');
selectedTab = $(selectedTabParend[0]).parent().addClass('state-active');
}
$('.navigation-menu-section-item').click(function() {
if (selectedTab) {
selectedTab.removeClass('state-active');
}
$(this).addClass('state-active');
selectedTab = $(this);
});
// Simple script to handle opening/closing modals
function modalHandler() {
var backdrop = $('.modal-backdrop');
$('.js-modal-trigger').each(function(i, modalTrigger) {
var modal = $('#' + modalTrigger.getAttribute('data-modal'));
var modalPrompt = $('#' + modalTrigger.getAttribute('data-modal') + 'Prompt');
var closeButton = modal.find('.js-modal-close');
var promptCloseButton = modalPrompt.find('.js-modal-close');
function removeModal() {
modal.removeClass('opened');
backdrop.addClass('closed');
backdrop.off('click', removeModal);
}
function removePrompt() {
modalPrompt.removeClass('opened');
modal.find('.prompt-backdrop').addClass('closed');
backdrop.off('click', removePrompt);
backdrop.on('click', removeModal);
}
$(modalTrigger).on('click', function() {
modal.addClass('opened');
backdrop.removeClass('closed');
if (modalPrompt.length > 0) {
modalPrompt.addClass('opened');
backdrop.on('click', removePrompt);
} else {
backdrop.on('click', removeModal);
}
});
closeButton.on('click', function(event) {
event.stopPropagation();
removeModal();
});
promptCloseButton.on('click', function(event) {
event.stopPropagation();
removePrompt();
});
});
}
modalHandler();
function expandRowView($el) {
$el.find('tr.heading-row').addClass('opened');
$el.find('tr.collapsible-row').addClass('in');
$el.find('tr.collapsible-row .container').slideDown(400);
$el.find('[data-collapse-state]').attr('data-collapse-state', 'expanded');
}
function collapseRowView($el) {
$el.find('tr.heading-row').removeClass('opened');
$el.find('tr.collapsible-row').removeClass('in');
$el.find('tr.collapsible-row .container').slideUp(400);
$el.find('[data-collapse-state]').attr('data-collapse-state', 'collapsed');
}
$('tr.heading-row').click(function(jQueryEventObject) {
var $el = $(jQueryEventObject.currentTarget);
if ($el.hasClass('opened')) {
collapseRowView($el.parent());
} else {
expandRowView($el.parent());
}
});
// Handle open/close dropdown
$('button.dropdown-toggle').click(function(event) {
var dropdownEl = $(event.currentTarget).parent();
dropdownEl.toggleClass('open', !dropdownEl.hasClass('open'));
});
// Handle selection in flat-select
$('.flat-select-option').click(function(event) {
var optionEl = $(event.currentTarget);
var flatSelectEl = optionEl.parent();
flatSelectEl.find('.flat-select-option:not(.selectable)').addClass('selectable');
optionEl.removeClass('selectable');
});
});
|
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) {
throw err;
};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
});
|
/**
* @license
* Copyright (C) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
*
* <p>
* For a fairly comprehensive set of languages see the
* <a href="https://github.com/google/code-prettify#for-which-languages-does-it-work">README</a>
* file that came with this source. At a minimum, the lexer should work on a
* number of languages including C and friends, Java, Python, Bash, SQL, HTML,
* XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
* and a subset of Perl, but, because of commenting conventions, doesn't work on
* Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
* <p>
* Usage: <ol>
* <li> include this source file in an html page via
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
* <li> define style rules. See the example page for examples.
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
* {@code class=prettyprint.}
* You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
* printer needs to do more substantial DOM manipulations to support that, so
* some css styles may not be preserved.
* </ol>
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in, but if you wish, you can add
* another class to the {@code <pre>} or {@code <code>} element to specify the
* language, as in {@code <pre class="prettyprint lang-java">}. Any class that
* starts with "lang-" followed by a file extension, specifies the file type.
* See the "lang-*.js" files in this directory for code that implements
* per-language file handlers.
* <p>
* Change log:<br>
* cbeust, 2006/08/22
* <blockquote>
* Java annotations (start with "@") are now captured as literals ("lit")
* </blockquote>
* @requires console
*/
// JSLint declarations
/*global console, document, navigator, setTimeout, window, define */
/* @ifndef RUN_PRETTIFY */
/* @include defs.js */
/* @endif */
/**
* {@type !{
* 'createSimpleLexer': function (Array, Array): (function (JobT)),
* 'registerLangHandler': function (function (JobT), Array.<string>),
* 'PR_ATTRIB_NAME': string,
* 'PR_ATTRIB_NAME': string,
* 'PR_ATTRIB_VALUE': string,
* 'PR_COMMENT': string,
* 'PR_DECLARATION': string,
* 'PR_KEYWORD': string,
* 'PR_LITERAL': string,
* 'PR_NOCODE': string,
* 'PR_PLAIN': string,
* 'PR_PUNCTUATION': string,
* 'PR_SOURCE': string,
* 'PR_STRING': string,
* 'PR_TAG': string,
* 'PR_TYPE': string,
* 'prettyPrintOne': function (string, string, number|boolean),
* 'prettyPrint': function (?function, ?(HTMLElement|HTMLDocument))
* }}
* @const
*/
var PR;
/**
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
* UI events.
* If set to {@code false}, {@code prettyPrint()} is synchronous.
*/
var PR_SHOULD_USE_CONTINUATION = true
if (typeof window !== 'undefined') {
window['PR_SHOULD_USE_CONTINUATION'] = PR_SHOULD_USE_CONTINUATION;
}
/**
* Pretty print a chunk of code.
* @param {string} sourceCodeHtml The HTML to pretty print.
* @param {string} opt_langExtension The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param {number|boolean} opt_numberLines True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
* @return {string} code as html, but prettier
*/
var prettyPrintOne;
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function} opt_whenDone called when prettifying is done.
* @param {HTMLElement|HTMLDocument} opt_root an element or document
* containing all the elements to pretty print.
* Defaults to {@code document.body}.
*/
var prettyPrint;
(function () {
var win = (typeof window !== 'undefined') ? window : {};
// Keyword lists for various languages.
// We use things that coerce to strings to make them compact when minified
// and to defeat aggressive optimizers that fold large string constants.
var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
"double,enum,extern,float,goto,inline,int,long,register,restrict,short,signed," +
"sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
"new,operator,private,protected,public,this,throw,true,try,typeof"];
var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignas,alignof,align_union,asm,axiom,bool," +
"concept,concept_map,const_cast,constexpr,decltype,delegate," +
"dynamic_cast,explicit,export,friend,generic,late_check," +
"mutable,namespace,noexcept,noreturn,nullptr,property,reinterpret_cast,static_assert," +
"static_cast,template,typeid,typename,using,virtual,where"];
var JAVA_KEYWORDS = [COMMON_KEYWORDS,
"abstract,assert,boolean,byte,extends,finally,final,implements,import," +
"instanceof,interface,null,native,package,strictfp,super,synchronized," +
"throws,transient"];
var CSHARP_KEYWORDS = [COMMON_KEYWORDS,
"abstract,add,alias,as,ascending,async,await,base,bool,by,byte,checked,decimal,delegate,descending," +
"dynamic,event,finally,fixed,foreach,from,get,global,group,implicit,in,interface," +
"internal,into,is,join,let,lock,null,object,out,override,orderby,params," +
"partial,readonly,ref,remove,sbyte,sealed,select,set,stackalloc,string,select,uint,ulong," +
"unchecked,unsafe,ushort,value,var,virtual,where,yield"];
var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
"for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
"throw,true,try,unless,until,when,while,yes";
var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
"abstract,async,await,constructor,debugger,enum,eval,export,function," +
"get,import,implements,instanceof,interface,let,null,of,set,undefined," +
"var,with,yield,Infinity,NaN"];
var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
"goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
"sub,undef,unless,until,use,wantarray,while,BEGIN,END";
var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
"elif,except,exec,finally,from,global,import,in,is,lambda," +
"nonlocal,not,or,pass,print,raise,try,with,yield," +
"False,True,None"];
var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
"def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
"rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
"BEGIN,END"];
var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
"function,in,local,set,then,until"];
var ALL_KEYWORDS = [
CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_KEYWORDS, JSCRIPT_KEYWORDS,
PERL_KEYWORDS, PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
var C_TYPES = /^(DIR|FILE|array|vector|(de|priority_)?queue|(forward_)?list|stack|(const_)?(reverse_)?iterator|(unordered_)?(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
// token style names. correspond to css classes
/**
* token style for a string literal
* @const
*/
var PR_STRING = 'str';
/**
* token style for a keyword
* @const
*/
var PR_KEYWORD = 'kwd';
/**
* token style for a comment
* @const
*/
var PR_COMMENT = 'com';
/**
* token style for a type
* @const
*/
var PR_TYPE = 'typ';
/**
* token style for a literal value. e.g. 1, null, true.
* @const
*/
var PR_LITERAL = 'lit';
/**
* token style for a punctuation string.
* @const
*/
var PR_PUNCTUATION = 'pun';
/**
* token style for plain text.
* @const
*/
var PR_PLAIN = 'pln';
/**
* token style for an sgml tag.
* @const
*/
var PR_TAG = 'tag';
/**
* token style for a markup declaration such as a DOCTYPE.
* @const
*/
var PR_DECLARATION = 'dec';
/**
* token style for embedded source.
* @const
*/
var PR_SOURCE = 'src';
/**
* token style for an sgml attribute name.
* @const
*/
var PR_ATTRIB_NAME = 'atn';
/**
* token style for an sgml attribute value.
* @const
*/
var PR_ATTRIB_VALUE = 'atv';
/**
* A class that indicates a section of markup that is not code, e.g. to allow
* embedding of line numbers within code listings.
* @const
*/
var PR_NOCODE = 'nocode';
/* @include regexpPrecederPatterns.js */
/* @include combinePrefixPatterns.js */
/* @include extractSourceSpans.js */
/**
* Apply the given language handler to sourceCode and add the resulting
* decorations to out.
* @param {!Element} sourceNode
* @param {number} basePos the index of sourceCode within the chunk of source
* whose decorations are already present on out.
* @param {string} sourceCode
* @param {function(JobT)} langHandler
* @param {DecorationsT} out
*/
function appendDecorations(
sourceNode, basePos, sourceCode, langHandler, out) {
if (!sourceCode) { return; }
/** @type {JobT} */
var job = {
sourceNode: sourceNode,
pre: 1,
langExtension: null,
numberLines: null,
sourceCode: sourceCode,
spans: null,
basePos: basePos,
decorations: null
};
langHandler(job);
out.push.apply(out, job.decorations);
}
var notWs = /\S/;
/**
* Given an element, if it contains only one child element and any text nodes
* it contains contain only space characters, return the sole child element.
* Otherwise returns undefined.
* <p>
* This is meant to return the CODE element in {@code <pre><code ...>} when
* there is a single child element that contains all the non-space textual
* content, but not to return anything where there are multiple child elements
* as in {@code <pre><code>...</code><code>...</code></pre>} or when there
* is textual content.
*/
function childContentWrapper(element) {
var wrapper = undefined;
for (var c = element.firstChild; c; c = c.nextSibling) {
var type = c.nodeType;
wrapper = (type === 1) // Element Node
? (wrapper ? element : c)
: (type === 3) // Text Node
? (notWs.test(c.nodeValue) ? element : wrapper)
: wrapper;
}
return wrapper === element ? undefined : wrapper;
}
/** Given triples of [style, pattern, context] returns a lexing function,
* The lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
* where index_n is an index into the sourceCode, and style_n is a style
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
* all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form
* [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
*
* Style is a style constant like PR_PLAIN, or can be a string of the
* form 'lang-FOO', where FOO is a language extension describing the
* language of the portion of the token in $1 after pattern executes.
* E.g., if style is 'lang-lisp', and group 1 contains the text
* '(hello (world))', then that portion of the token will be passed to the
* registered lisp handler for formatting.
* The text before and after group 1 will be restyled using this decorator
* so decorators should take care that this doesn't result in infinite
* recursion. For example, the HTML lexer rule for SCRIPT elements looks
* something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
* '<script>foo()<\/script>', which would cause the current decorator to
* be called with '<script>' which would not match the same rule since
* group 1 must not be empty, so it would be instead styled as PR_TAG by
* the generic tag rule. The handler registered for the 'js' extension would
* then be called with 'foo()', and finally, the current decorator would
* be called with '<\/script>' which would not match the original rule and
* so the generic tag rule would identify it as a tag.
*
* Pattern must only match prefixes, and if it matches a prefix, then that
* match is considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token
* recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array} shortcutStylePatterns patterns that always start with
* a known character. Must have a shortcut string.
* @param {Array} fallthroughStylePatterns patterns that will be tried in
* order if the shortcut ones fail. May have shortcuts.
*
* @return {function (JobT)} a function that takes an undecorated job and
* attaches a list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
var shortcuts = {};
var tokenizer;
(function () {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
var allRegexs = [];
var regexKeys = {};
for (var i = 0, n = allPatterns.length; i < n; ++i) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for (var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
var regex = patternParts[1];
var k = '' + regex;
if (!regexKeys.hasOwnProperty(k)) {
allRegexs.push(regex);
regexKeys[k] = null;
}
}
allRegexs.push(/[\0-\uffff]/);
tokenizer = combinePrefixPatterns(allRegexs);
})();
var nPatterns = fallthroughStylePatterns.length;
/**
* Lexes job.sourceCode and attaches an output array job.decorations of
* style classes preceded by the position at which they start in
* job.sourceCode in order.
*
* @type{function (JobT)}
*/
var decorate = function (job) {
var sourceCode = job.sourceCode, basePos = job.basePos;
var sourceNode = job.sourceNode;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {DecorationsT}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) { styleCache[token] = style; }
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
sourceNode,
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
sourceNode,
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
sourceNode,
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
}
}
job.decorations = decorations;
};
return decorate;
}
/** returns a function that produces a list of decorations from source text.
*
* This code treats ", ', and ` as string delimiters, and \ as a string
* escape. It does not recognize perl's qq() style strings.
* It has no special handling for double delimiter escapes as in basic, or
* the tripled delimiters used in python, but should work on those regardless
* although in those cases a single string literal may be broken up into
* multiple adjacent string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {Object} options a set of optional parameters.
* @return {function (JobT)} a function that examines the source code
* in the input job and builds a decoration list which it attaches to
* the job.
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
fallthroughStylePatterns.push(
[PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
}
var hc = options['hashComments'];
if (hc) {
if (options['cStyleComments']) {
if (hc > 1) { // multiline hash comments
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
} else {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#']);
}
// #include <stdio.h>
fallthroughStylePatterns.push(
[PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
null]);
} else {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
var regexLiterals = options['regexLiterals'];
if (regexLiterals) {
/**
* @const
*/
var regexExcls = regexLiterals > 1
? '' // Multiline regex literals
: '\n\r';
/**
* @const
*/
var regexAny = regexExcls ? '.' : '[\\S\\s]';
/**
* @const
*/
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*' + regexExcls + '])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C' + regexExcls + ']'
// escape sequences (\x5C),
+ '|\\x5C' + regexAny
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
+ '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var types = options['types'];
if (types) {
fallthroughStylePatterns.push([PR_TYPE, types]);
}
var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
if (keywords.length) {
fallthroughStylePatterns.push(
[PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
null]);
}
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
var punctuation =
// The Bash man page says
// A word is a sequence of characters considered as a single
// unit by GRUB. Words are separated by metacharacters,
// which are the following plus space, tab, and newline: { }
// | & $ ; < >
// ...
// A word beginning with # causes that word and all remaining
// characters on that line to be ignored.
// which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
// comment but empirically
// $ echo {#}
// {#}
// $ echo \$#
// $#
// $ echo }#
// }#
// so /(?:^|[|&;<>\s])/ is more appropriate.
// http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
// suggests that this definition is compatible with a
// default mode that tries to use a single token definition
// to recognize both bash/python style comments and C
// preprocessor directives.
// This definition of punctuation does not include # in the list of
// follow-on exclusions, so # will not be broken before if preceeded
// by a punctuation character. We could try to exclude # after
// [|&;<>] but that doesn't seem to cause many major problems.
// If that does turn out to be a problem, we should change the below
// when hc is truthy to include # in the run of punctuation characters
// only when not followint [|&;<>].
'^.[^\\s\\w.$@\'"`/\\\\]*';
if (options['regexLiterals']) {
punctuation += '(?!\s*\/)';
}
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
[PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
[PR_LITERAL,
new RegExp(
'^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?'
+ ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
// Don't treat escaped quotes in bash as starting strings.
// See issue 144.
[PR_PLAIN, /^\\[\s\S]?/, null],
[PR_PUNCTUATION, new RegExp(punctuation), null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
}
var decorateSource = sourceDecorator({
'keywords': ALL_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'multiLineStrings': true,
'regexLiterals': true
});
/* @include numberLines.js */
/* @include recombineTagsAndDecorations.js */
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/** Register a language handler for the given file extensions.
* @param {function (JobT)} handler a function from source code to a list
* of decorations. Takes a single argument job which describes the
* state of the computation and attaches the decorations to it.
* @param {Array.<string>} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if (win['console']) {
console['warn']('cannot override language handler %s', ext);
}
}
}
function langHandlerForExtension(extension, source) {
if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
// Treat it as markup if the first non whitespace character is a < and
// the last non-whitespace character is a >.
extension = /^\s*</.test(source)
? 'default-markup'
: 'default-code';
}
return langHandlerRegistry[extension];
}
registerLangHandler(decorateSource, ['default-code']);
registerLangHandler(
createSimpleLexer(
[],
[
[PR_PLAIN, /^[^<?]+/],
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
[PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
// Unescaped content in an unknown language
['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
['lang-', /^<%([\s\S]+?)(?:%>|$)/],
[PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
// Unescaped content in javascript. (Or possibly vbscript).
['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
// Contains unescaped stylesheet content
['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
]),
['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
registerLangHandler(
createSimpleLexer(
[
[PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
[PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
],
[
[PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
[PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
[PR_PUNCTUATION, /^[=<>\/]+/],
['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
]),
['in.tag']);
registerLangHandler(
createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
registerLangHandler(sourceDecorator({
'keywords': CPP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'types': C_TYPES
}), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
registerLangHandler(sourceDecorator({
'keywords': 'null,true,false'
}), ['json']);
registerLangHandler(sourceDecorator({
'keywords': CSHARP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'verbatimStrings': true,
'types': C_TYPES
}), ['cs']);
registerLangHandler(sourceDecorator({
'keywords': JAVA_KEYWORDS,
'cStyleComments': true
}), ['java']);
registerLangHandler(sourceDecorator({
'keywords': SH_KEYWORDS,
'hashComments': true,
'multiLineStrings': true
}), ['bash', 'bsh', 'csh', 'sh']);
registerLangHandler(sourceDecorator({
'keywords': PYTHON_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'tripleQuotedStrings': true
}), ['cv', 'py', 'python']);
registerLangHandler(sourceDecorator({
'keywords': PERL_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': 2 // multiline regex literals
}), ['perl', 'pl', 'pm']);
registerLangHandler(sourceDecorator({
'keywords': RUBY_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': true
}), ['rb', 'ruby']);
registerLangHandler(sourceDecorator({
'keywords': JSCRIPT_KEYWORDS,
'cStyleComments': true,
'regexLiterals': true
}), ['javascript', 'js', 'ts', 'typescript']);
registerLangHandler(sourceDecorator({
'keywords': COFFEE_KEYWORDS,
'hashComments': 3, // ### style block comments
'cStyleComments': true,
'multilineStrings': true,
'tripleQuotedStrings': true,
'regexLiterals': true
}), ['coffee']);
registerLangHandler(
createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
/** @param {JobT} job */
function applyDecorator(job) {
var opt_langExtension = job.langExtension;
try {
// Extract tags, and convert the source code to plain text.
var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
/** Plain text. @type {string} */
var source = sourceAndSpans.sourceCode;
job.sourceCode = source;
job.spans = sourceAndSpans.spans;
job.basePos = 0;
// Apply the appropriate language handler
langHandlerForExtension(opt_langExtension, source)(job);
// Integrate the decorations and tags back into the source code,
// modifying the sourceNode in place.
recombineTagsAndDecorations(job);
} catch (e) {
if (win['console']) {
console['log'](e && e['stack'] || e);
}
}
}
/**
* Pretty print a chunk of code.
* @param sourceCodeHtml {string} The HTML to pretty print.
* @param opt_langExtension {string} The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param opt_numberLines {number|boolean} True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
*/
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
/** @type{number|boolean} */
var nl = opt_numberLines || false;
/** @type{string|null} */
var langExtension = opt_langExtension || null;
/** @type{!Element} */
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
// We assume that the inner HTML is from a trusted source.
// The pre-tag is required for IE8 which strips newlines from innerHTML
// when it is injected into a <pre> tag.
// http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
// http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
container = /** @type{!Element} */(container.firstChild);
if (nl) {
numberLines(container, nl, true);
}
/** @type{JobT} */
var job = {
langExtension: langExtension,
numberLines: nl,
sourceNode: container,
pre: 1,
sourceCode: null,
basePos: null,
spans: null,
decorations: null
};
applyDecorator(job);
return container.innerHTML;
}
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function} opt_whenDone called when prettifying is done.
* @param {HTMLElement|HTMLDocument} opt_root an element or document
* containing all the elements to pretty print.
* Defaults to {@code document.body}.
*/
function $prettyPrint(opt_whenDone, opt_root) {
var root = opt_root || document.body;
var doc = root.ownerDocument || document;
function byTagName(tn) { return root.getElementsByTagName(tn); }
// fetch a list of nodes to rewrite
var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
var elements = [];
for (var i = 0; i < codeSegments.length; ++i) {
for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
var clock = Date;
if (!clock['now']) {
clock = { 'now': function () { return +(new Date); } };
}
// The loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
var prettyPrintRe = /\bprettyprint\b/;
var prettyPrintedRe = /\bprettyprinted\b/;
var preformattedTagNameRe = /pre|xmp/i;
var codeRe = /^code$/i;
var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
var EMPTY = {};
function doWork() {
var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
clock['now']() + 250 /* ms */ :
Infinity);
for (; k < elements.length && clock['now']() < endTime; k++) {
var cs = elements[k];
// Look for a preceding comment like
// <?prettify lang="..." linenums="..."?>
var attrs = EMPTY;
{
for (var preceder = cs; (preceder = preceder.previousSibling);) {
var nt = preceder.nodeType;
// <?foo?> is parsed by HTML 5 to a comment node (8)
// like <!--?foo?-->, but in XML is a processing instruction
var value = (nt === 7 || nt === 8) && preceder.nodeValue;
if (value
? !/^\??prettify\b/.test(value)
: (nt !== 3 || /\S/.test(preceder.nodeValue))) {
// Skip over white-space text nodes but not others.
break;
}
if (value) {
attrs = {};
value.replace(
/\b(\w+)=([\w:.%+-]+)/g,
function (_, name, value) { attrs[name] = value; });
break;
}
}
}
var className = cs.className;
if ((attrs !== EMPTY || prettyPrintRe.test(className))
// Don't redo this if we've already done it.
// This allows recalling pretty print to just prettyprint elements
// that have been added to the page since last call.
&& !prettyPrintedRe.test(className)) {
// make sure this is not nested in an already prettified element
var nested = false;
for (var p = cs.parentNode; p; p = p.parentNode) {
var tn = p.tagName;
if (preCodeXmpRe.test(tn)
&& p.className && prettyPrintRe.test(p.className)) {
nested = true;
break;
}
}
if (!nested) {
// Mark done. If we fail to prettyprint for whatever reason,
// we shouldn't try again.
cs.className += ' prettyprinted';
// If the classes includes a language extensions, use it.
// Language extensions can be specified like
// <pre class="prettyprint lang-cpp">
// the language extension "cpp" is used to find a language handler
// as passed to PR.registerLangHandler.
// HTML5 recommends that a language be specified using "language-"
// as the prefix instead. Google Code Prettify supports both.
// http://dev.w3.org/html5/spec-author-view/the-code-element.html
var langExtension = attrs['lang'];
if (!langExtension) {
langExtension = className.match(langExtensionRe);
// Support <pre class="prettyprint"><code class="language-c">
var wrapper;
if (!langExtension && (wrapper = childContentWrapper(cs))
&& codeRe.test(wrapper.tagName)) {
langExtension = wrapper.className.match(langExtensionRe);
}
if (langExtension) { langExtension = langExtension[1]; }
}
var preformatted;
if (preformattedTagNameRe.test(cs.tagName)) {
preformatted = 1;
} else {
var currentStyle = cs['currentStyle'];
var defaultView = doc.defaultView;
var whitespace = (
currentStyle
? currentStyle['whiteSpace']
: (defaultView
&& defaultView.getComputedStyle)
? defaultView.getComputedStyle(cs, null)
.getPropertyValue('white-space')
: 0);
preformatted = whitespace
&& 'pre' === whitespace.substring(0, 3);
}
// Look for a class like linenums or linenums:<n> where <n> is the
// 1-indexed number of the first line.
var lineNums = attrs['linenums'];
if (!(lineNums = lineNums === 'true' || +lineNums)) {
lineNums = className.match(/\blinenums\b(?::(\d+))?/);
lineNums =
lineNums
? lineNums[1] && lineNums[1].length
? +lineNums[1] : true
: false;
}
if (lineNums) { numberLines(cs, lineNums, preformatted); }
// do the pretty printing
var prettyPrintingJob = {
langExtension: langExtension,
sourceNode: cs,
numberLines: lineNums,
pre: preformatted,
sourceCode: null,
basePos: null,
spans: null,
decorations: null
};
applyDecorator(prettyPrintingJob);
}
}
}
if (k < elements.length) {
// finish up in a continuation
win.setTimeout(doWork, 250);
} else if ('function' === typeof opt_whenDone) {
opt_whenDone();
}
}
doWork();
}
/**
* Contains functions for creating and registering new language handlers.
* @type {Object}
*/
var PR = win['PR'] = {
'createSimpleLexer': createSimpleLexer,
'registerLangHandler': registerLangHandler,
'sourceDecorator': sourceDecorator,
'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
'PR_COMMENT': PR_COMMENT,
'PR_DECLARATION': PR_DECLARATION,
'PR_KEYWORD': PR_KEYWORD,
'PR_LITERAL': PR_LITERAL,
'PR_NOCODE': PR_NOCODE,
'PR_PLAIN': PR_PLAIN,
'PR_PUNCTUATION': PR_PUNCTUATION,
'PR_SOURCE': PR_SOURCE,
'PR_STRING': PR_STRING,
'PR_TAG': PR_TAG,
'PR_TYPE': PR_TYPE,
'prettyPrintOne':
IN_GLOBAL_SCOPE
? (win['prettyPrintOne'] = $prettyPrintOne)
: (prettyPrintOne = $prettyPrintOne),
'prettyPrint':
IN_GLOBAL_SCOPE
? (win['prettyPrint'] = $prettyPrint)
: (prettyPrint = $prettyPrint)
};
// Make PR available via the Asynchronous Module Definition (AMD) API.
// Per https://github.com/amdjs/amdjs-api/wiki/AMD:
// The Asynchronous Module Definition (AMD) API specifies a
// mechanism for defining modules such that the module and its
// dependencies can be asynchronously loaded.
// ...
// To allow a clear indicator that a global define function (as
// needed for script src browser loading) conforms to the AMD API,
// any global define function SHOULD have a property called "amd"
// whose value is an object. This helps avoid conflict with any
// other existing JavaScript code that could have defined a define()
// function that does not conform to the AMD API.
var define = win['define'];
if (typeof define === "function" && define['amd']) {
define("google-code-prettify", [], function () {
return PR;
});
}
})();
|
var fs = require('fs');
var path = require('path');
var flokme = require('./flok');
var flok = flokme('status-file');
var statusPath = path.join(__dirname, 'status-file', 'flokStatus', 'basic.json');
describe('status-file', function () {
describe('loadMigrationsStatus', function () {
var loadMigrationsStatusEmitted = 0;
var loadedMigrationStatus = 'foobar';
before(function () {
flok.on('loadMigrationsStatus', function (migrations) {
loadMigrationsStatusEmitted++;
loadedMigrationStatus = migrations;
});
});
it('should load status', function (done) {
flok._loadMigrationsStatus(function (err) {
if (err) return done(err);
done();
});
});
it('should emit loadMigrationsStatus', function () {
loadMigrationsStatusEmitted.should.equal(1);
loadedMigrationStatus.should.be.instanceof(Array);
});
});
describe('clearMigrationStatus', function () {
var status;
before(function (done) {
status = fs.readFileSync(statusPath);
flok._loadMigrations(function (err) {
if (err) return done(err);
flok._loadMigrationsStatus(done);
});
});
after(function () {
if (status) fs.writeFileSync(statusPath, status);
});
it('should remove migration status files', function (done) {
flok._clearMigrationStatus(flok.migrations[0], function (err) {
if (err) return done(err);
fs.existsSync(statusPath).should.equal(false);
done();
});
});
});
});
|
var browserSync = require('browser-sync');
var gulp = require('gulp');
var config = require('../config').browserSync;
gulp.task('browserSync', function() {
browserSync(config, function(err, bs) {
// bs.options.url contains the original url, so
// replace the port with the correct one:
var url = bs.options.getIn(["urls", "local"]).replace(':3000', ':3002');
require('opn')(url);
console.log('Started browserSync on ' + url);
});
});
|
export { default } from 'nypr-ui/components/nypr-card/button';
|
var camelize = require('camelize')
var fs = require('fs')
var path = require('path')
var jsFile = /^(.*)[.]js$/
var ignoreFiles = /^(index|chain)[.]js$/
module.exports = fs.readdirSync(path.resolve(__dirname, '../..'))
.filter(function (filename) {
return jsFile.test(filename) && !ignoreFiles.test(filename)
})
.map(function (filename) {
return jsFile.exec(filename)[1]
})
.map(camelize)
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from './webApp.scss';
import Board from '../../components/Board';
import Tips from '../../components/Tips';
import ControlPanel from '../ControlPanel';
import GameOverCard from '../GameOver';
import Scores from '../../components/Scores';
import i18n from '../../utils/i18n';
// Desktop application entry
export default class WebApp extends Component {
static propTypes = {
matrix: PropTypes.arrayOf(PropTypes.array).isRequired,
audioMove: PropTypes.instanceOf(Audio).isRequired,
audioPopup: PropTypes.instanceOf(Audio).isRequired,
score: PropTypes.number,
bestScore: PropTypes.number,
gameOver: PropTypes.bool,
onReset: PropTypes.func
};
static defaultProps = {
score: 0,
bestScore: 0,
gameOver: false,
onReset() {}
};
constructor(...args) {
super(...args);
// debounce delay in ms
this.delay = process.env.NODE_ENV === 'production' ? 300 : 1;
}
render() {
const { delay } = this;
const {
matrix,
audioMove,
audioPopup,
bestScore,
score,
gameOver,
onReset
} = this.props;
return (
<div className={styles.app}>
<div className={styles.box}>
<div className={styles.board}>
<h1 className={styles.title}>2048</h1>
<Board matrix={matrix} />
</div>
<div className={styles.panel}>
<div>
<Scores bestScore={bestScore} score={score} />
</div>
<ControlPanel
delay={delay}
audioMove={audioMove}
audioPopup={audioPopup}
/>
</div>
</div>
<Tips title={i18n.tipTitle} content={i18n.tipContent} />
<GameOverCard gameOver={gameOver} score={score} onReset={onReset} />
</div>
);
}
}
|
const express = require('express');
//const infermedica = require('../request/infermedica');
//const mw = require('../request/merrian_webster');
const router = express.Router();
const fs = require('fs');
const db = require('../database/query');
//insert
router.post('/', function (req, res) {
if (!req.user.id || !req.body.medicalId) {
res.status(400).json({
message: 'Query param missing'
});
return;
}
db.insertRiskFactorsInfo(req.user.id, req.body.medicalId)
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.log(err);
res.status(400).json({
message: err
})
})
});
router.delete('/', function (req, res) {
if (!req.user.id || !req.body.riskFactorId) {
res.status(400).json({
message: 'Query param missing'
});
return;
}
db.removeRiskFactorInfo(req.user.id, req.body.riskFactorId)
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.log(err);
res.status(400).json({
message: err
})
})
});
router.get('/', function (req, res) {
if (!req.user.id) {
res.status(400).json({
message: 'User id missing'
});
return;
}
db.getRiskFactorsInfo(req.user.id)
.then((riskfactors) => {
res.json(riskfactors)
})
.catch((err) => {
res.sendStatus(500);
})
});
module.exports = router;
|
'use strict';
// Reports controller
angular.module('reports').controller('ReportsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Reports', 'Articles', 'Requests', 'Discounts', 'Users', 'Questions',
function ($scope, $stateParams, $location, Authentication, Reports, Articles, Requests, Discounts, Users, Questions) {
//$scope.self=_this;
$scope.authentication = Authentication;
if ($scope.authentication.user && $scope.authentication.user.roles.indexOf("admin") > -1) console.log("Admin"); //Autorizacija je prosla nema problema Admin je u pitanju
else {
$location.path('/');//Autorizacija nije prosla, Reports nisu ucitani, nije Admin, redirectaj na pocetnu stranicu.
};
$scope.progress = 0;
// Remove existing Report
$scope.remove = function (report) {
if (report) {
report.$remove();
for (var i in $scope.reports) {
if ($scope.reports [i] === report) {
$scope.reports.splice(i, 1);
}
}
} else {
$scope.report.$remove(function () {
$location.path('reports');
});
}
};
// Update existing Report
$scope.update = function () {
var report = $scope.report;
report.$update(function () {
$location.path('reports/' + report._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Reports
$scope.find = function () {
$scope.reports = Reports.query();
};
$scope.findOne = function () {
$scope.report = Reports.get({
reportId: $stateParams.reportId
});
};
$scope.today = function () {
$scope.dt1 = new Date();
$scope.dt2 = new Date();
};
$scope.today();
$scope.clear = function () {
$scope.dt1 = null;
$scope.dt2 = null;
};
$scope.toggleMin = function () {
$scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
$scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 2);
$scope.events =
[
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
$scope.getDayClass = function (date, mode) {
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0, 0, 0, 0);
for (var i = 0; i < $scope.events.length; i++) {
var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
};
//Filtrira grafik prema datepickerima, tako sto unistava stari graf i crta novi
$scope.filterGraph = function () {
$scope.dateerror = '';
var e = false;
if ($scope.dt1 > $scope.dt2) {
$scope.dateerror = 'Greška sa datumom!';
e = true;
}
if (!e) {
$scope.progressionChart1.destroy();
$scope.graph1data.datasets[0].data = [];
$scope.graph1data.datasets[1].data = [];
$scope.graph1data.datasets[2].data = [];
$scope.graph1data.datasets[3].data = [];
$scope.graph1data.labels = [];
angular.forEach($scope.reports, function (value) {
var temp = value.created.replace(/-/g, '/');
temp = temp.replace('T', ' ');
temp = temp.replace('Z', ' ');
if ((new Date(temp) >= $scope.dt1) && (new Date(temp) <= $scope.dt2)) {
$scope.graph1data.labels.push(value.created.split("T")[0]);
$scope.graph1data.datasets[0].data.push(value.totalnumberofquestions);
$scope.graph1data.datasets[1].data.push(value.totalnumberofarticles);
$scope.graph1data.datasets[2].data.push(value.totalnumberofartisans);
$scope.graph1data.datasets[3].data.push(value.totalnumberofrequests);
}
});
$scope.graph1data.labels.reverse();
$scope.graph1data.datasets[0].data.reverse();
$scope.graph1data.datasets[1].data.reverse();
$scope.graph1data.datasets[2].data.reverse();
$scope.graph1data.datasets[3].data.reverse();
var ctx1 = document.getElementById("progressionChart1").getContext("2d");
var options = {};
$scope.progressionChart1 = new Chart(ctx1).Line($scope.graph1data, options);
}
};
//Gradi izvjestaj, poziva query() funkcije jednu u drugoj, jer su asihrone. Nakon toga, dostupne su sve liste da se manipuliraju
$scope.buildReport = function () {
//Ne treba ovako raditi ovo treba promijeniti
$scope.reports = Reports.query(function () {
$scope.discounts = Discounts.query(function () {
$scope.articles = Articles.query(function () {
$scope.progress += 25;
$scope.requests = Requests.query(function () {
$scope.progress += 25;
$scope.users = Users.query(function () {
$scope.progress += 25;
$scope.questions = Questions.query(function () {
$scope.report = new Reports({
name: 'Report for ' + Date.now(),
totalnumberofusers: $scope.users.length,
totalnumberofarticles: $scope.articles.length,
totalnumberofrequests: $scope.requests.length,
totalnumberofquestions: $scope.questions.length,
totalnumberofdiscounts: $scope.discounts.length
});
var ctx1 = document.getElementById("progressionChart1").getContext("2d");
var ctx2 = document.getElementById("pieChart2").getContext("2d");
var ctx3 = document.getElementById("pieChart3").getContext("2d");
$scope.graph1data = {
labels: [],
datasets: [
{
label: "Sesije",
fillColor: "rgba(255,220,100,0.3)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: []
},
{
label: "Artikli",
fillColor: "rgba(0,255,205,0.3)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: []
},
{
label: "Korisnici",
fillColor: "rgba(151,0,205,0.3)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: []
},
{
label: "Zahtjevi",
fillColor: "rgba(255,187,205,0.3)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: []
}
]
};
$scope.pieDataP = [];
$scope.pieDataZ = [];
var options = {
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
};
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth: 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
};
$scope.report.$save(function () {
$scope.temp = $scope.reports[0].name;
angular.forEach($scope.reports, function (value, key) {
var temp = value.created.replace(/-/g, '/');
temp = temp.replace('T', ' ');
temp = temp.replace('Z', ' ');
if (Math.abs(Date.now() - new Date(temp)) / (1000 * 3600) < 99) {
$scope.graph1data.labels.push(value.created.split("T")[0]);
$scope.graph1data.datasets[0].data.push(value.totalnumberofquestions);
$scope.graph1data.datasets[1].data.push(value.totalnumberofarticles);
$scope.graph1data.datasets[2].data.push(value.totalnumberofusers);
$scope.graph1data.datasets[3].data.push(value.totalnumberofrequests);
}
});
$scope.graph1data.labels.reverse();
$scope.graph1data.datasets[0].data.reverse();
$scope.graph1data.datasets[1].data.reverse();
$scope.graph1data.datasets[2].data.reverse();
$scope.graph1data.datasets[3].data.reverse();
$scope.graph1data.datasets[0].data.push($scope.questions.length);
$scope.graph1data.datasets[1].data.push($scope.articles.length);
$scope.graph1data.datasets[2].data.push($scope.users.length);
$scope.graph1data.datasets[3].data.push($scope.requests.length);
$scope.graph1data.labels.push('Danas');
//za pie chart
var brojacOdgovorenihP = 0, brojacNeodgovorenihP = 0;
var brojacOdgovorenihZ = 0, brojacNeodgovorenihZ = 0;
angular.forEach($scope.questions, function (value) {
if (value.responsenumber == 0) brojacOdgovorenihP++;
else brojacNeodgovorenihP++;
});
angular.forEach($scope.requests, function (value) {
if (value.responsenumber == 0) brojacOdgovorenihZ++;
else brojacNeodgovorenihZ++;
});
$scope.pieDataP.push({
value: brojacNeodgovorenihP,
color: "#F7464A",
highlight: "#FF5A5E",
label: "Neodgovorene"
});
$scope.pieDataP.push({
value: brojacOdgovorenihP,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Odgovorena"
});
$scope.pieDataZ.push({
value: brojacNeodgovorenihZ,
color: "#F7464A",
highlight: "#FF5A5E",
label: "Neodgovoreni"
});
$scope.pieDataZ.push({
value: brojacOdgovorenihZ,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Odgovoreni"
});
$scope.progressionChart1 = new Chart(ctx1).Line($scope.graph1data, options);
$scope.pieChart2 = new Chart(ctx2).Pie($scope.pieDataP, pieOptions);
$scope.pieChart3 = new Chart(ctx3).Pie($scope.pieDataZ, pieOptions);
$scope.progress += 25;
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
})
}
)
})
}
);
});
});
};
}
]);
|
'use strict';
// Workoutplans controller
angular.module('workoutplans').controller('WorkoutplansController', ['$scope', '$stateParams', '$location', 'Authentication', 'Workoutplans', 'Tasks',
function($scope, $stateParams, $location, Authentication, Workoutplans, Tasks) {
$scope.authentication = Authentication;
$scope.bases = [
{name: 'Squat', lift: 'squat'},
{name: 'Deadlift', lift: 'deadlift'},
{name: 'Bench Press', lift: 'benchPress'},
{name: 'Clean and Jerk', lift: 'cleanJerk'},
{name: 'Snatch', lift: 'snatch'},
{name: 'Front Squat', lift: 'frontSquat'}
];
$scope.programs = [
{name: 'Group Training'},
{name: 'Athletes'},
{name: 'BABEies'},
{name: 'Performance'},
{name: 'Bootcamp'},
{name: 'Lift'}
];
// Create new Workoutplan
$scope.create = function() {
// Create new Workoutplan object
var workoutplan = new Workoutplans ({
name: this.name,
description: this.description,
phase: this.phase,
program: this.program,
date: this.date
});
// Redirect after save
workoutplan.$save(function(response) {
$location.path('workoutplans/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.createTask = function() {
// Create new Task object
var task = new Tasks ({
name: this.taskName,
description: this.taskDescription,
reps: this.taskReps,
sets: this.taskSets,
weights: this.taskWeights,
baseLift: this.taskBaseLift,
workoutplan: this.workoutplan._id
});
// Redirect after save
task.$save(function(response) {
$location.path('workoutplans/' + response._id);
// Clear form fields
$scope.taskName = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Workoutplan
$scope.remove = function(workoutplan) {
if ( workoutplan ) {
workoutplan.$remove();
for (var i in $scope.workoutplans) {
if ($scope.workoutplans [i] === workoutplan) {
$scope.workoutplans.splice(i, 1);
}
}
} else {
$scope.workoutplan.$remove(function() {
$location.path('workoutplans');
});
}
};
// Update existing Workoutplan
$scope.update = function() {
var workoutplan = $scope.workoutplan;
workoutplan.$update(function() {
$location.path('workoutplans/' + workoutplan._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Add a task to existing workout
$scope.addTask = function() {
$scope.workoutplan.tasks.push({
name: $scope.addTaskName,
sets: $scope.addTaskSets,
reps: $scope.addTaskReps,
baseLift: $scope.addTaskBaseLift,
weight: $scope.addTaskWeight,
description: $scope.addTaskDescription
});
var workoutplan = $scope.workoutplan;
workoutplan.$update(function() {
$location.path('workoutplans/' + workoutplan._id +'/edit');
//clear form fields
$scope.addTaskName = '';
$scope.addTaskSets = '';
$scope.addTaskReps = '';
$scope.addTaskBaseLift = '';
$scope.addTaskWeight = '';
$scope.addTaskDescription = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Workoutplans
$scope.find = function() {
$scope.workoutplans = Workoutplans.query();
};
// Find existing Workoutplan
$scope.findOne = function() {
$scope.workoutplan = Workoutplans.get({
workoutplanId: $stateParams.workoutplanId
});
};
}
]);
|
import angular from 'angular';
import DetailController from './detail.controller'
import detailConfig from './detail.config'
let detailModule = angular.module('detail.module', [])
.controller('DetailController', DetailController)
.config(detailConfig)
export default detailModule;
|
/*!
Copyright (C) 2010-2013 Raymond Hill: https://github.com/gorhill/Javascript-Voronoi
MIT License: See https://github.com/gorhill/Javascript-Voronoi/LICENSE.md
*/
/*
Author: Raymond Hill (rhill@raymondhill.net)
Contributor: Jesse Morgan (morgajel@gmail.com)
File: rhill-voronoi-core.js
Version: 0.98
Date: January 21, 2013
Description: This is my personal Javascript implementation of
Steven Fortune's algorithm to compute Voronoi diagrams.
License: See https://github.com/gorhill/Javascript-Voronoi/LICENSE.md
Credits: See https://github.com/gorhill/Javascript-Voronoi/CREDITS.md
History: See https://github.com/gorhill/Javascript-Voronoi/CHANGELOG.md
## Usage:
var sites = [{x:300,y:300}, {x:100,y:100}, {x:200,y:500}, {x:250,y:450}, {x:600,y:150}];
// xl, xr means x left, x right
// yt, yb means y top, y bottom
var bbox = {xl:0, xr:800, yt:0, yb:600};
var voronoi = new Voronoi();
// pass an object which exhibits xl, xr, yt, yb properties. The bounding
// box will be used to connect unbound edges, and to close open cells
result = voronoi.compute(sites, bbox);
// render, further analyze, etc.
Return value:
An object with the following properties:
result.vertices = an array of unordered, unique Voronoi.Vertex objects making
up the Voronoi diagram.
result.edges = an array of unordered, unique Voronoi.Edge objects making up
the Voronoi diagram.
result.cells = an array of Voronoi.Cell object making up the Voronoi diagram.
A Cell object might have an empty array of halfedges, meaning no Voronoi
cell could be computed for a particular cell.
result.execTime = the time it took to compute the Voronoi diagram, in
milliseconds.
Voronoi.Vertex object:
x: The x position of the vertex.
y: The y position of the vertex.
Voronoi.Edge object:
lSite: the Voronoi site object at the left of this Voronoi.Edge object.
rSite: the Voronoi site object at the right of this Voronoi.Edge object (can
be null).
va: an object with an 'x' and a 'y' property defining the start point
(relative to the Voronoi site on the left) of this Voronoi.Edge object.
vb: an object with an 'x' and a 'y' property defining the end point
(relative to Voronoi site on the left) of this Voronoi.Edge object.
For edges which are used to close open cells (using the supplied bounding
box), the rSite property will be null.
Voronoi.Cell object:
site: the Voronoi site object associated with the Voronoi cell.
halfedges: an array of Voronoi.Halfedge objects, ordered counterclockwise,
defining the polygon for this Voronoi cell.
Voronoi.Halfedge object:
site: the Voronoi site object owning this Voronoi.Halfedge object.
edge: a reference to the unique Voronoi.Edge object underlying this
Voronoi.Halfedge object.
getStartpoint(): a method returning an object with an 'x' and a 'y' property
for the start point of this halfedge. Keep in mind halfedges are always
countercockwise.
getEndpoint(): a method returning an object with an 'x' and a 'y' property
for the end point of this halfedge. Keep in mind halfedges are always
countercockwise.
TODO: Identify opportunities for performance improvement.
TODO: Let the user close the Voronoi cells, do not do it automatically. Not only let
him close the cells, but also allow him to close more than once using a different
bounding box for the same Voronoi diagram.
*/
/*global Math */
// ---------------------------------------------------------------------------
function Voronoi() {
this.vertices = null;
this.edges = null;
this.cells = null;
this.toRecycle = null;
this.beachsectionJunkyard = [];
this.circleEventJunkyard = [];
this.vertexJunkyard = [];
this.edgeJunkyard = [];
this.cellJunkyard = [];
}
// ---------------------------------------------------------------------------
Voronoi.prototype.reset = function() {
if (!this.beachline) {
this.beachline = new this.RBTree();
}
// Move leftover beachsections to the beachsection junkyard.
if (this.beachline.root) {
var beachsection = this.beachline.getFirst(this.beachline.root);
while (beachsection) {
this.beachsectionJunkyard.push(beachsection); // mark for reuse
beachsection = beachsection.rbNext;
}
}
this.beachline.root = null;
if (!this.circleEvents) {
this.circleEvents = new this.RBTree();
}
this.circleEvents.root = this.firstCircleEvent = null;
this.vertices = [];
this.edges = [];
this.cells = [];
};
Voronoi.prototype.sqrt = Math.sqrt;
Voronoi.prototype.abs = Math.abs;
Voronoi.prototype.ε = Voronoi.ε = 1e-9;
Voronoi.prototype.invε = Voronoi.invε = 1.0 / Voronoi.ε;
Voronoi.prototype.equalWithEpsilon = function(a,b){return this.abs(a-b)<1e-9;};
Voronoi.prototype.greaterThanWithEpsilon = function(a,b){return a-b>1e-9;};
Voronoi.prototype.greaterThanOrEqualWithEpsilon = function(a,b){return b-a<1e-9;};
Voronoi.prototype.lessThanWithEpsilon = function(a,b){return b-a>1e-9;};
Voronoi.prototype.lessThanOrEqualWithEpsilon = function(a,b){return a-b<1e-9;};
// ---------------------------------------------------------------------------
// Red-Black tree code (based on C version of "rbtree" by Franck Bui-Huu
// https://github.com/fbuihuu/libtree/blob/master/rb.c
Voronoi.prototype.RBTree = function() {
this.root = null;
};
Voronoi.prototype.RBTree.prototype.rbInsertSuccessor = function(node, successor) {
var parent;
if (node) {
// >>> rhill 2011-05-27: Performance: cache previous/next nodes
successor.rbPrevious = node;
successor.rbNext = node.rbNext;
if (node.rbNext) {
node.rbNext.rbPrevious = successor;
}
node.rbNext = successor;
// <<<
if (node.rbRight) {
// in-place expansion of node.rbRight.getFirst();
node = node.rbRight;
while (node.rbLeft) {node = node.rbLeft;}
node.rbLeft = successor;
}
else {
node.rbRight = successor;
}
parent = node;
}
// rhill 2011-06-07: if node is null, successor must be inserted
// to the left-most part of the tree
else if (this.root) {
node = this.getFirst(this.root);
// >>> Performance: cache previous/next nodes
successor.rbPrevious = null;
successor.rbNext = node;
node.rbPrevious = successor;
// <<<
node.rbLeft = successor;
parent = node;
}
else {
// >>> Performance: cache previous/next nodes
successor.rbPrevious = successor.rbNext = null;
// <<<
this.root = successor;
parent = null;
}
successor.rbLeft = successor.rbRight = null;
successor.rbParent = parent;
successor.rbRed = true;
// Fixup the modified tree by recoloring nodes and performing
// rotations (2 at most) hence the red-black tree properties are
// preserved.
var grandpa, uncle;
node = successor;
while (parent && parent.rbRed) {
grandpa = parent.rbParent;
if (parent === grandpa.rbLeft) {
uncle = grandpa.rbRight;
if (uncle && uncle.rbRed) {
parent.rbRed = uncle.rbRed = false;
grandpa.rbRed = true;
node = grandpa;
}
else {
if (node === parent.rbRight) {
this.rbRotateLeft(parent);
node = parent;
parent = node.rbParent;
}
parent.rbRed = false;
grandpa.rbRed = true;
this.rbRotateRight(grandpa);
}
}
else {
uncle = grandpa.rbLeft;
if (uncle && uncle.rbRed) {
parent.rbRed = uncle.rbRed = false;
grandpa.rbRed = true;
node = grandpa;
}
else {
if (node === parent.rbLeft) {
this.rbRotateRight(parent);
node = parent;
parent = node.rbParent;
}
parent.rbRed = false;
grandpa.rbRed = true;
this.rbRotateLeft(grandpa);
}
}
parent = node.rbParent;
}
this.root.rbRed = false;
};
Voronoi.prototype.RBTree.prototype.rbRemoveNode = function(node) {
// >>> rhill 2011-05-27: Performance: cache previous/next nodes
if (node.rbNext) {
node.rbNext.rbPrevious = node.rbPrevious;
}
if (node.rbPrevious) {
node.rbPrevious.rbNext = node.rbNext;
}
node.rbNext = node.rbPrevious = null;
// <<<
var parent = node.rbParent,
left = node.rbLeft,
right = node.rbRight,
next;
if (!left) {
next = right;
}
else if (!right) {
next = left;
}
else {
next = this.getFirst(right);
}
if (parent) {
if (parent.rbLeft === node) {
parent.rbLeft = next;
}
else {
parent.rbRight = next;
}
}
else {
this.root = next;
}
// enforce red-black rules
var isRed;
if (left && right) {
isRed = next.rbRed;
next.rbRed = node.rbRed;
next.rbLeft = left;
left.rbParent = next;
if (next !== right) {
parent = next.rbParent;
next.rbParent = node.rbParent;
node = next.rbRight;
parent.rbLeft = node;
next.rbRight = right;
right.rbParent = next;
}
else {
next.rbParent = parent;
parent = next;
node = next.rbRight;
}
}
else {
isRed = node.rbRed;
node = next;
}
// 'node' is now the sole successor's child and 'parent' its
// new parent (since the successor can have been moved)
if (node) {
node.rbParent = parent;
}
// the 'easy' cases
if (isRed) {return;}
if (node && node.rbRed) {
node.rbRed = false;
return;
}
// the other cases
var sibling;
do {
if (node === this.root) {
break;
}
if (node === parent.rbLeft) {
sibling = parent.rbRight;
if (sibling.rbRed) {
sibling.rbRed = false;
parent.rbRed = true;
this.rbRotateLeft(parent);
sibling = parent.rbRight;
}
if ((sibling.rbLeft && sibling.rbLeft.rbRed) || (sibling.rbRight && sibling.rbRight.rbRed)) {
if (!sibling.rbRight || !sibling.rbRight.rbRed) {
sibling.rbLeft.rbRed = false;
sibling.rbRed = true;
this.rbRotateRight(sibling);
sibling = parent.rbRight;
}
sibling.rbRed = parent.rbRed;
parent.rbRed = sibling.rbRight.rbRed = false;
this.rbRotateLeft(parent);
node = this.root;
break;
}
}
else {
sibling = parent.rbLeft;
if (sibling.rbRed) {
sibling.rbRed = false;
parent.rbRed = true;
this.rbRotateRight(parent);
sibling = parent.rbLeft;
}
if ((sibling.rbLeft && sibling.rbLeft.rbRed) || (sibling.rbRight && sibling.rbRight.rbRed)) {
if (!sibling.rbLeft || !sibling.rbLeft.rbRed) {
sibling.rbRight.rbRed = false;
sibling.rbRed = true;
this.rbRotateLeft(sibling);
sibling = parent.rbLeft;
}
sibling.rbRed = parent.rbRed;
parent.rbRed = sibling.rbLeft.rbRed = false;
this.rbRotateRight(parent);
node = this.root;
break;
}
}
sibling.rbRed = true;
node = parent;
parent = parent.rbParent;
} while (!node.rbRed);
if (node) {node.rbRed = false;}
};
Voronoi.prototype.RBTree.prototype.rbRotateLeft = function(node) {
var p = node,
q = node.rbRight, // can't be null
parent = p.rbParent;
if (parent) {
if (parent.rbLeft === p) {
parent.rbLeft = q;
}
else {
parent.rbRight = q;
}
}
else {
this.root = q;
}
q.rbParent = parent;
p.rbParent = q;
p.rbRight = q.rbLeft;
if (p.rbRight) {
p.rbRight.rbParent = p;
}
q.rbLeft = p;
};
Voronoi.prototype.RBTree.prototype.rbRotateRight = function(node) {
var p = node,
q = node.rbLeft, // can't be null
parent = p.rbParent;
if (parent) {
if (parent.rbLeft === p) {
parent.rbLeft = q;
}
else {
parent.rbRight = q;
}
}
else {
this.root = q;
}
q.rbParent = parent;
p.rbParent = q;
p.rbLeft = q.rbRight;
if (p.rbLeft) {
p.rbLeft.rbParent = p;
}
q.rbRight = p;
};
Voronoi.prototype.RBTree.prototype.getFirst = function(node) {
while (node.rbLeft) {
node = node.rbLeft;
}
return node;
};
Voronoi.prototype.RBTree.prototype.getLast = function(node) {
while (node.rbRight) {
node = node.rbRight;
}
return node;
};
// ---------------------------------------------------------------------------
// Diagram methods
Voronoi.prototype.Diagram = function(site) {
this.site = site;
};
// ---------------------------------------------------------------------------
// Cell methods
Voronoi.prototype.Cell = function(site) {
this.site = site;
this.halfedges = [];
this.closeMe = false;
};
Voronoi.prototype.Cell.prototype.init = function(site) {
this.site = site;
this.halfedges = [];
this.closeMe = false;
return this;
};
Voronoi.prototype.createCell = function(site) {
var cell = this.cellJunkyard.pop();
if ( cell ) {
return cell.init(site);
}
return new this.Cell(site);
};
Voronoi.prototype.Cell.prototype.prepareHalfedges = function() {
var halfedges = this.halfedges,
iHalfedge = halfedges.length,
edge;
// get rid of unused halfedges
// rhill 2011-05-27: Keep it simple, no point here in trying
// to be fancy: dangling edges are a typically a minority.
while (iHalfedge--) {
edge = halfedges[iHalfedge].edge;
if (!edge.vb || !edge.va) {
halfedges.splice(iHalfedge,1);
}
}
// rhill 2011-05-26: I tried to use a binary search at insertion
// time to keep the array sorted on-the-fly (in Cell.addHalfedge()).
// There was no real benefits in doing so, performance on
// Firefox 3.6 was improved marginally, while performance on
// Opera 11 was penalized marginally.
halfedges.sort(function(a,b){return b.angle-a.angle;});
return halfedges.length;
};
// Return a list of the neighbor Ids
Voronoi.prototype.Cell.prototype.getNeighborIds = function() {
var neighbors = [],
iHalfedge = this.halfedges.length,
edge;
while (iHalfedge--){
edge = this.halfedges[iHalfedge].edge;
if (edge.lSite !== null && edge.lSite.voronoiId != this.site.voronoiId) {
neighbors.push(edge.lSite.voronoiId);
}
else if (edge.rSite !== null && edge.rSite.voronoiId != this.site.voronoiId){
neighbors.push(edge.rSite.voronoiId);
}
}
return neighbors;
};
// Compute bounding box
//
Voronoi.prototype.Cell.prototype.getBbox = function() {
var halfedges = this.halfedges,
iHalfedge = halfedges.length,
xmin = Infinity,
ymin = Infinity,
xmax = -Infinity,
ymax = -Infinity,
v, vx, vy;
while (iHalfedge--) {
v = halfedges[iHalfedge].getStartpoint();
vx = v.x;
vy = v.y;
if (vx < xmin) {xmin = vx;}
if (vy < ymin) {ymin = vy;}
if (vx > xmax) {xmax = vx;}
if (vy > ymax) {ymax = vy;}
// we dont need to take into account end point,
// since each end point matches a start point
}
return {
x: xmin,
y: ymin,
width: xmax-xmin,
height: ymax-ymin
};
};
// Return whether a point is inside, on, or outside the cell:
// -1: point is outside the perimeter of the cell
// 0: point is on the perimeter of the cell
// 1: point is inside the perimeter of the cell
//
Voronoi.prototype.Cell.prototype.pointIntersection = function(x, y) {
// Check if point in polygon. Since all polygons of a Voronoi
// diagram are convex, then:
// http://paulbourke.net/geometry/polygonmesh/
// Solution 3 (2D):
// "If the polygon is convex then one can consider the polygon
// "as a 'path' from the first vertex. A point is on the interior
// "of this polygons if it is always on the same side of all the
// "line segments making up the path. ...
// "(y - y0) (x1 - x0) - (x - x0) (y1 - y0)
// "if it is less than 0 then P is to the right of the line segment,
// "if greater than 0 it is to the left, if equal to 0 then it lies
// "on the line segment"
var halfedges = this.halfedges,
iHalfedge = halfedges.length,
halfedge,
p0, p1, r;
while (iHalfedge--) {
halfedge = halfedges[iHalfedge];
p0 = halfedge.getStartpoint();
p1 = halfedge.getEndpoint();
r = (y-p0.y)*(p1.x-p0.x)-(x-p0.x)*(p1.y-p0.y);
if (!r) {
return 0;
}
if (r > 0) {
return -1;
}
}
return 1;
};
// ---------------------------------------------------------------------------
// Edge methods
//
Voronoi.prototype.Vertex = function(x, y) {
this.x = x;
this.y = y;
};
Voronoi.prototype.Edge = function(lSite, rSite) {
this.lSite = lSite;
this.rSite = rSite;
this.va = this.vb = null;
};
Voronoi.prototype.Halfedge = function(edge, lSite, rSite) {
this.site = lSite;
this.edge = edge;
// 'angle' is a value to be used for properly sorting the
// halfsegments counterclockwise. By convention, we will
// use the angle of the line defined by the 'site to the left'
// to the 'site to the right'.
// However, border edges have no 'site to the right': thus we
// use the angle of line perpendicular to the halfsegment (the
// edge should have both end points defined in such case.)
if (rSite) {
this.angle = Math.atan2(rSite.y-lSite.y, rSite.x-lSite.x);
}
else {
var va = edge.va,
vb = edge.vb;
// rhill 2011-05-31: used to call getStartpoint()/getEndpoint(),
// but for performance purpose, these are expanded in place here.
this.angle = edge.lSite === lSite ?
Math.atan2(vb.x-va.x, va.y-vb.y) :
Math.atan2(va.x-vb.x, vb.y-va.y);
}
};
Voronoi.prototype.createHalfedge = function(edge, lSite, rSite) {
return new this.Halfedge(edge, lSite, rSite);
};
Voronoi.prototype.Halfedge.prototype.getStartpoint = function() {
return this.edge.lSite === this.site ? this.edge.va : this.edge.vb;
};
Voronoi.prototype.Halfedge.prototype.getEndpoint = function() {
return this.edge.lSite === this.site ? this.edge.vb : this.edge.va;
};
// this create and add a vertex to the internal collection
Voronoi.prototype.createVertex = function(x, y) {
var v = this.vertexJunkyard.pop();
if ( !v ) {
v = new this.Vertex(x, y);
}
else {
v.x = x;
v.y = y;
}
this.vertices.push(v);
return v;
};
// this create and add an edge to internal collection, and also create
// two halfedges which are added to each site's counterclockwise array
// of halfedges.
Voronoi.prototype.createEdge = function(lSite, rSite, va, vb) {
var edge = this.edgeJunkyard.pop();
if ( !edge ) {
edge = new this.Edge(lSite, rSite);
}
else {
edge.lSite = lSite;
edge.rSite = rSite;
edge.va = edge.vb = null;
}
this.edges.push(edge);
if (va) {
this.setEdgeStartpoint(edge, lSite, rSite, va);
}
if (vb) {
this.setEdgeEndpoint(edge, lSite, rSite, vb);
}
this.cells[lSite.voronoiId].halfedges.push(this.createHalfedge(edge, lSite, rSite));
this.cells[rSite.voronoiId].halfedges.push(this.createHalfedge(edge, rSite, lSite));
return edge;
};
Voronoi.prototype.createBorderEdge = function(lSite, va, vb) {
var edge = this.edgeJunkyard.pop();
if ( !edge ) {
edge = new this.Edge(lSite, null);
}
else {
edge.lSite = lSite;
edge.rSite = null;
}
edge.va = va;
edge.vb = vb;
this.edges.push(edge);
return edge;
};
Voronoi.prototype.setEdgeStartpoint = function(edge, lSite, rSite, vertex) {
if (!edge.va && !edge.vb) {
edge.va = vertex;
edge.lSite = lSite;
edge.rSite = rSite;
}
else if (edge.lSite === rSite) {
edge.vb = vertex;
}
else {
edge.va = vertex;
}
};
Voronoi.prototype.setEdgeEndpoint = function(edge, lSite, rSite, vertex) {
this.setEdgeStartpoint(edge, rSite, lSite, vertex);
};
// ---------------------------------------------------------------------------
// Beachline methods
// rhill 2011-06-07: For some reasons, performance suffers significantly
// when instanciating a literal object instead of an empty ctor
Voronoi.prototype.Beachsection = function() {
};
// rhill 2011-06-02: A lot of Beachsection instanciations
// occur during the computation of the Voronoi diagram,
// somewhere between the number of sites and twice the
// number of sites, while the number of Beachsections on the
// beachline at any given time is comparatively low. For this
// reason, we reuse already created Beachsections, in order
// to avoid new memory allocation. This resulted in a measurable
// performance gain.
Voronoi.prototype.createBeachsection = function(site) {
var beachsection = this.beachsectionJunkyard.pop();
if (!beachsection) {
beachsection = new this.Beachsection();
}
beachsection.site = site;
return beachsection;
};
// calculate the left break point of a particular beach section,
// given a particular sweep line
Voronoi.prototype.leftBreakPoint = function(arc, directrix) {
// http://en.wikipedia.org/wiki/Parabola
// http://en.wikipedia.org/wiki/Quadratic_equation
// h1 = x1,
// k1 = (y1+directrix)/2,
// h2 = x2,
// k2 = (y2+directrix)/2,
// p1 = k1-directrix,
// a1 = 1/(4*p1),
// b1 = -h1/(2*p1),
// c1 = h1*h1/(4*p1)+k1,
// p2 = k2-directrix,
// a2 = 1/(4*p2),
// b2 = -h2/(2*p2),
// c2 = h2*h2/(4*p2)+k2,
// x = (-(b2-b1) + Math.sqrt((b2-b1)*(b2-b1) - 4*(a2-a1)*(c2-c1))) / (2*(a2-a1))
// When x1 become the x-origin:
// h1 = 0,
// k1 = (y1+directrix)/2,
// h2 = x2-x1,
// k2 = (y2+directrix)/2,
// p1 = k1-directrix,
// a1 = 1/(4*p1),
// b1 = 0,
// c1 = k1,
// p2 = k2-directrix,
// a2 = 1/(4*p2),
// b2 = -h2/(2*p2),
// c2 = h2*h2/(4*p2)+k2,
// x = (-b2 + Math.sqrt(b2*b2 - 4*(a2-a1)*(c2-k1))) / (2*(a2-a1)) + x1
// change code below at your own risk: care has been taken to
// reduce errors due to computers' finite arithmetic precision.
// Maybe can still be improved, will see if any more of this
// kind of errors pop up again.
var site = arc.site,
rfocx = site.x,
rfocy = site.y,
pby2 = rfocy-directrix;
// parabola in degenerate case where focus is on directrix
if (!pby2) {
return rfocx;
}
var lArc = arc.rbPrevious;
if (!lArc) {
return -Infinity;
}
site = lArc.site;
var lfocx = site.x,
lfocy = site.y,
plby2 = lfocy-directrix;
// parabola in degenerate case where focus is on directrix
if (!plby2) {
return lfocx;
}
var hl = lfocx-rfocx,
aby2 = 1/pby2-1/plby2,
b = hl/plby2;
if (aby2) {
return (-b+this.sqrt(b*b-2*aby2*(hl*hl/(-2*plby2)-lfocy+plby2/2+rfocy-pby2/2)))/aby2+rfocx;
}
// both parabolas have same distance to directrix, thus break point is midway
return (rfocx+lfocx)/2;
};
// calculate the right break point of a particular beach section,
// given a particular directrix
Voronoi.prototype.rightBreakPoint = function(arc, directrix) {
var rArc = arc.rbNext;
if (rArc) {
return this.leftBreakPoint(rArc, directrix);
}
var site = arc.site;
return site.y === directrix ? site.x : Infinity;
};
Voronoi.prototype.detachBeachsection = function(beachsection) {
this.detachCircleEvent(beachsection); // detach potentially attached circle event
this.beachline.rbRemoveNode(beachsection); // remove from RB-tree
this.beachsectionJunkyard.push(beachsection); // mark for reuse
};
Voronoi.prototype.removeBeachsection = function(beachsection) {
var circle = beachsection.circleEvent,
x = circle.x,
y = circle.ycenter,
vertex = this.createVertex(x, y),
previous = beachsection.rbPrevious,
next = beachsection.rbNext,
disappearingTransitions = [beachsection],
abs_fn = Math.abs;
// remove collapsed beachsection from beachline
this.detachBeachsection(beachsection);
// there could be more than one empty arc at the deletion point, this
// happens when more than two edges are linked by the same vertex,
// so we will collect all those edges by looking up both sides of
// the deletion point.
// by the way, there is *always* a predecessor/successor to any collapsed
// beach section, it's just impossible to have a collapsing first/last
// beach sections on the beachline, since they obviously are unconstrained
// on their left/right side.
// look left
var lArc = previous;
while (lArc.circleEvent && abs_fn(x-lArc.circleEvent.x)<1e-9 && abs_fn(y-lArc.circleEvent.ycenter)<1e-9) {
previous = lArc.rbPrevious;
disappearingTransitions.unshift(lArc);
this.detachBeachsection(lArc); // mark for reuse
lArc = previous;
}
// even though it is not disappearing, I will also add the beach section
// immediately to the left of the left-most collapsed beach section, for
// convenience, since we need to refer to it later as this beach section
// is the 'left' site of an edge for which a start point is set.
disappearingTransitions.unshift(lArc);
this.detachCircleEvent(lArc);
// look right
var rArc = next;
while (rArc.circleEvent && abs_fn(x-rArc.circleEvent.x)<1e-9 && abs_fn(y-rArc.circleEvent.ycenter)<1e-9) {
next = rArc.rbNext;
disappearingTransitions.push(rArc);
this.detachBeachsection(rArc); // mark for reuse
rArc = next;
}
// we also have to add the beach section immediately to the right of the
// right-most collapsed beach section, since there is also a disappearing
// transition representing an edge's start point on its left.
disappearingTransitions.push(rArc);
this.detachCircleEvent(rArc);
// walk through all the disappearing transitions between beach sections and
// set the start point of their (implied) edge.
var nArcs = disappearingTransitions.length,
iArc;
for (iArc=1; iArc<nArcs; iArc++) {
rArc = disappearingTransitions[iArc];
lArc = disappearingTransitions[iArc-1];
this.setEdgeStartpoint(rArc.edge, lArc.site, rArc.site, vertex);
}
// create a new edge as we have now a new transition between
// two beach sections which were previously not adjacent.
// since this edge appears as a new vertex is defined, the vertex
// actually define an end point of the edge (relative to the site
// on the left)
lArc = disappearingTransitions[0];
rArc = disappearingTransitions[nArcs-1];
rArc.edge = this.createEdge(lArc.site, rArc.site, undefined, vertex);
// create circle events if any for beach sections left in the beachline
// adjacent to collapsed sections
this.attachCircleEvent(lArc);
this.attachCircleEvent(rArc);
};
Voronoi.prototype.addBeachsection = function(site) {
var x = site.x,
directrix = site.y;
// find the left and right beach sections which will surround the newly
// created beach section.
// rhill 2011-06-01: This loop is one of the most often executed,
// hence we expand in-place the comparison-against-epsilon calls.
var lArc, rArc,
dxl, dxr,
node = this.beachline.root;
while (node) {
dxl = this.leftBreakPoint(node,directrix)-x;
// x lessThanWithEpsilon xl => falls somewhere before the left edge of the beachsection
if (dxl > 1e-9) {
// this case should never happen
// if (!node.rbLeft) {
// rArc = node.rbLeft;
// break;
// }
node = node.rbLeft;
}
else {
dxr = x-this.rightBreakPoint(node,directrix);
// x greaterThanWithEpsilon xr => falls somewhere after the right edge of the beachsection
if (dxr > 1e-9) {
if (!node.rbRight) {
lArc = node;
break;
}
node = node.rbRight;
}
else {
// x equalWithEpsilon xl => falls exactly on the left edge of the beachsection
if (dxl > -1e-9) {
lArc = node.rbPrevious;
rArc = node;
}
// x equalWithEpsilon xr => falls exactly on the right edge of the beachsection
else if (dxr > -1e-9) {
lArc = node;
rArc = node.rbNext;
}
// falls exactly somewhere in the middle of the beachsection
else {
lArc = rArc = node;
}
break;
}
}
}
// at this point, keep in mind that lArc and/or rArc could be
// undefined or null.
// create a new beach section object for the site and add it to RB-tree
var newArc = this.createBeachsection(site);
this.beachline.rbInsertSuccessor(lArc, newArc);
// cases:
//
// [null,null]
// least likely case: new beach section is the first beach section on the
// beachline.
// This case means:
// no new transition appears
// no collapsing beach section
// new beachsection become root of the RB-tree
if (!lArc && !rArc) {
return;
}
// [lArc,rArc] where lArc == rArc
// most likely case: new beach section split an existing beach
// section.
// This case means:
// one new transition appears
// the left and right beach section might be collapsing as a result
// two new nodes added to the RB-tree
if (lArc === rArc) {
// invalidate circle event of split beach section
this.detachCircleEvent(lArc);
// split the beach section into two separate beach sections
rArc = this.createBeachsection(lArc.site);
this.beachline.rbInsertSuccessor(newArc, rArc);
// since we have a new transition between two beach sections,
// a new edge is born
newArc.edge = rArc.edge = this.createEdge(lArc.site, newArc.site);
// check whether the left and right beach sections are collapsing
// and if so create circle events, to be notified when the point of
// collapse is reached.
this.attachCircleEvent(lArc);
this.attachCircleEvent(rArc);
return;
}
// [lArc,null]
// even less likely case: new beach section is the *last* beach section
// on the beachline -- this can happen *only* if *all* the previous beach
// sections currently on the beachline share the same y value as
// the new beach section.
// This case means:
// one new transition appears
// no collapsing beach section as a result
// new beach section become right-most node of the RB-tree
if (lArc && !rArc) {
newArc.edge = this.createEdge(lArc.site,newArc.site);
return;
}
// [null,rArc]
// impossible case: because sites are strictly processed from top to bottom,
// and left to right, which guarantees that there will always be a beach section
// on the left -- except of course when there are no beach section at all on
// the beach line, which case was handled above.
// rhill 2011-06-02: No point testing in non-debug version
//if (!lArc && rArc) {
// throw "Voronoi.addBeachsection(): What is this I don't even";
// }
// [lArc,rArc] where lArc != rArc
// somewhat less likely case: new beach section falls *exactly* in between two
// existing beach sections
// This case means:
// one transition disappears
// two new transitions appear
// the left and right beach section might be collapsing as a result
// only one new node added to the RB-tree
if (lArc !== rArc) {
// invalidate circle events of left and right sites
this.detachCircleEvent(lArc);
this.detachCircleEvent(rArc);
// an existing transition disappears, meaning a vertex is defined at
// the disappearance point.
// since the disappearance is caused by the new beachsection, the
// vertex is at the center of the circumscribed circle of the left,
// new and right beachsections.
// http://mathforum.org/library/drmath/view/55002.html
// Except that I bring the origin at A to simplify
// calculation
var lSite = lArc.site,
ax = lSite.x,
ay = lSite.y,
bx=site.x-ax,
by=site.y-ay,
rSite = rArc.site,
cx=rSite.x-ax,
cy=rSite.y-ay,
d=2*(bx*cy-by*cx),
hb=bx*bx+by*by,
hc=cx*cx+cy*cy,
vertex = this.createVertex((cy*hb-by*hc)/d+ax, (bx*hc-cx*hb)/d+ay);
// one transition disappear
this.setEdgeStartpoint(rArc.edge, lSite, rSite, vertex);
// two new transitions appear at the new vertex location
newArc.edge = this.createEdge(lSite, site, undefined, vertex);
rArc.edge = this.createEdge(site, rSite, undefined, vertex);
// check whether the left and right beach sections are collapsing
// and if so create circle events, to handle the point of collapse.
this.attachCircleEvent(lArc);
this.attachCircleEvent(rArc);
return;
}
};
// ---------------------------------------------------------------------------
// Circle event methods
// rhill 2011-06-07: For some reasons, performance suffers significantly
// when instanciating a literal object instead of an empty ctor
Voronoi.prototype.CircleEvent = function() {
// rhill 2013-10-12: it helps to state exactly what we are at ctor time.
this.arc = null;
this.rbLeft = null;
this.rbNext = null;
this.rbParent = null;
this.rbPrevious = null;
this.rbRed = false;
this.rbRight = null;
this.site = null;
this.x = this.y = this.ycenter = 0;
};
Voronoi.prototype.attachCircleEvent = function(arc) {
var lArc = arc.rbPrevious,
rArc = arc.rbNext;
if (!lArc || !rArc) {return;} // does that ever happen?
var lSite = lArc.site,
cSite = arc.site,
rSite = rArc.site;
// If site of left beachsection is same as site of
// right beachsection, there can't be convergence
if (lSite===rSite) {return;}
// Find the circumscribed circle for the three sites associated
// with the beachsection triplet.
// rhill 2011-05-26: It is more efficient to calculate in-place
// rather than getting the resulting circumscribed circle from an
// object returned by calling Voronoi.circumcircle()
// http://mathforum.org/library/drmath/view/55002.html
// Except that I bring the origin at cSite to simplify calculations.
// The bottom-most part of the circumcircle is our Fortune 'circle
// event', and its center is a vertex potentially part of the final
// Voronoi diagram.
var bx = cSite.x,
by = cSite.y,
ax = lSite.x-bx,
ay = lSite.y-by,
cx = rSite.x-bx,
cy = rSite.y-by;
// If points l->c->r are clockwise, then center beach section does not
// collapse, hence it can't end up as a vertex (we reuse 'd' here, which
// sign is reverse of the orientation, hence we reverse the test.
// http://en.wikipedia.org/wiki/Curve_orientation#Orientation_of_a_simple_polygon
// rhill 2011-05-21: Nasty finite precision error which caused circumcircle() to
// return infinites: 1e-12 seems to fix the problem.
var d = 2*(ax*cy-ay*cx);
if (d >= -2e-12){return;}
var ha = ax*ax+ay*ay,
hc = cx*cx+cy*cy,
x = (cy*ha-ay*hc)/d,
y = (ax*hc-cx*ha)/d,
ycenter = y+by;
// Important: ybottom should always be under or at sweep, so no need
// to waste CPU cycles by checking
// recycle circle event object if possible
var circleEvent = this.circleEventJunkyard.pop();
if (!circleEvent) {
circleEvent = new this.CircleEvent();
}
circleEvent.arc = arc;
circleEvent.site = cSite;
circleEvent.x = x+bx;
circleEvent.y = ycenter+this.sqrt(x*x+y*y); // y bottom
circleEvent.ycenter = ycenter;
arc.circleEvent = circleEvent;
// find insertion point in RB-tree: circle events are ordered from
// smallest to largest
var predecessor = null,
node = this.circleEvents.root;
while (node) {
if (circleEvent.y < node.y || (circleEvent.y === node.y && circleEvent.x <= node.x)) {
if (node.rbLeft) {
node = node.rbLeft;
}
else {
predecessor = node.rbPrevious;
break;
}
}
else {
if (node.rbRight) {
node = node.rbRight;
}
else {
predecessor = node;
break;
}
}
}
this.circleEvents.rbInsertSuccessor(predecessor, circleEvent);
if (!predecessor) {
this.firstCircleEvent = circleEvent;
}
};
Voronoi.prototype.detachCircleEvent = function(arc) {
var circleEvent = arc.circleEvent;
if (circleEvent) {
if (!circleEvent.rbPrevious) {
this.firstCircleEvent = circleEvent.rbNext;
}
this.circleEvents.rbRemoveNode(circleEvent); // remove from RB-tree
this.circleEventJunkyard.push(circleEvent);
arc.circleEvent = null;
}
};
// ---------------------------------------------------------------------------
// Diagram completion methods
// connect dangling edges (not if a cursory test tells us
// it is not going to be visible.
// return value:
// false: the dangling endpoint couldn't be connected
// true: the dangling endpoint could be connected
Voronoi.prototype.connectEdge = function(edge, bbox) {
// skip if end point already connected
var vb = edge.vb;
if (!!vb) {return true;}
// make local copy for performance purpose
var va = edge.va,
xl = bbox.xl,
xr = bbox.xr,
yt = bbox.yt,
yb = bbox.yb,
lSite = edge.lSite,
rSite = edge.rSite,
lx = lSite.x,
ly = lSite.y,
rx = rSite.x,
ry = rSite.y,
fx = (lx+rx)/2,
fy = (ly+ry)/2,
fm, fb;
// if we reach here, this means cells which use this edge will need
// to be closed, whether because the edge was removed, or because it
// was connected to the bounding box.
this.cells[lSite.voronoiId].closeMe = true;
this.cells[rSite.voronoiId].closeMe = true;
// get the line equation of the bisector if line is not vertical
if (ry !== ly) {
fm = (lx-rx)/(ry-ly);
fb = fy-fm*fx;
}
// remember, direction of line (relative to left site):
// upward: left.x < right.x
// downward: left.x > right.x
// horizontal: left.x == right.x
// upward: left.x < right.x
// rightward: left.y < right.y
// leftward: left.y > right.y
// vertical: left.y == right.y
// depending on the direction, find the best side of the
// bounding box to use to determine a reasonable start point
// rhill 2013-12-02:
// While at it, since we have the values which define the line,
// clip the end of va if it is outside the bbox.
// https://github.com/gorhill/Javascript-Voronoi/issues/15
// TODO: Do all the clipping here rather than rely on Liang-Barsky
// which does not do well sometimes due to loss of arithmetic
// precision. The code here doesn't degrade if one of the vertex is
// at a huge distance.
// special case: vertical line
if (fm === undefined) {
// doesn't intersect with viewport
if (fx < xl || fx >= xr) {return false;}
// downward
if (lx > rx) {
if (!va || va.y < yt) {
va = this.createVertex(fx, yt);
}
else if (va.y >= yb) {
return false;
}
vb = this.createVertex(fx, yb);
}
// upward
else {
if (!va || va.y > yb) {
va = this.createVertex(fx, yb);
}
else if (va.y < yt) {
return false;
}
vb = this.createVertex(fx, yt);
}
}
// closer to vertical than horizontal, connect start point to the
// top or bottom side of the bounding box
else if (fm < -1 || fm > 1) {
// downward
if (lx > rx) {
if (!va || va.y < yt) {
va = this.createVertex((yt-fb)/fm, yt);
}
else if (va.y >= yb) {
return false;
}
vb = this.createVertex((yb-fb)/fm, yb);
}
// upward
else {
if (!va || va.y > yb) {
va = this.createVertex((yb-fb)/fm, yb);
}
else if (va.y < yt) {
return false;
}
vb = this.createVertex((yt-fb)/fm, yt);
}
}
// closer to horizontal than vertical, connect start point to the
// left or right side of the bounding box
else {
// rightward
if (ly < ry) {
if (!va || va.x < xl) {
va = this.createVertex(xl, fm*xl+fb);
}
else if (va.x >= xr) {
return false;
}
vb = this.createVertex(xr, fm*xr+fb);
}
// leftward
else {
if (!va || va.x > xr) {
va = this.createVertex(xr, fm*xr+fb);
}
else if (va.x < xl) {
return false;
}
vb = this.createVertex(xl, fm*xl+fb);
}
}
edge.va = va;
edge.vb = vb;
return true;
};
// line-clipping code taken from:
// Liang-Barsky function by Daniel White
// http://www.skytopia.com/project/articles/compsci/clipping.html
// Thanks!
// A bit modified to minimize code paths
Voronoi.prototype.clipEdge = function(edge, bbox) {
var ax = edge.va.x,
ay = edge.va.y,
bx = edge.vb.x,
by = edge.vb.y,
t0 = 0,
t1 = 1,
dx = bx-ax,
dy = by-ay;
// left
var q = ax-bbox.xl;
if (dx===0 && q<0) {return false;}
var r = -q/dx;
if (dx<0) {
if (r<t0) {return false;}
if (r<t1) {t1=r;}
}
else if (dx>0) {
if (r>t1) {return false;}
if (r>t0) {t0=r;}
}
// right
q = bbox.xr-ax;
if (dx===0 && q<0) {return false;}
r = q/dx;
if (dx<0) {
if (r>t1) {return false;}
if (r>t0) {t0=r;}
}
else if (dx>0) {
if (r<t0) {return false;}
if (r<t1) {t1=r;}
}
// top
q = ay-bbox.yt;
if (dy===0 && q<0) {return false;}
r = -q/dy;
if (dy<0) {
if (r<t0) {return false;}
if (r<t1) {t1=r;}
}
else if (dy>0) {
if (r>t1) {return false;}
if (r>t0) {t0=r;}
}
// bottom
q = bbox.yb-ay;
if (dy===0 && q<0) {return false;}
r = q/dy;
if (dy<0) {
if (r>t1) {return false;}
if (r>t0) {t0=r;}
}
else if (dy>0) {
if (r<t0) {return false;}
if (r<t1) {t1=r;}
}
// if we reach this point, Voronoi edge is within bbox
// if t0 > 0, va needs to change
// rhill 2011-06-03: we need to create a new vertex rather
// than modifying the existing one, since the existing
// one is likely shared with at least another edge
if (t0 > 0) {
edge.va = this.createVertex(ax+t0*dx, ay+t0*dy);
}
// if t1 < 1, vb needs to change
// rhill 2011-06-03: we need to create a new vertex rather
// than modifying the existing one, since the existing
// one is likely shared with at least another edge
if (t1 < 1) {
edge.vb = this.createVertex(ax+t1*dx, ay+t1*dy);
}
// va and/or vb were clipped, thus we will need to close
// cells which use this edge.
if ( t0 > 0 || t1 < 1 ) {
this.cells[edge.lSite.voronoiId].closeMe = true;
this.cells[edge.rSite.voronoiId].closeMe = true;
}
return true;
};
// Connect/cut edges at bounding box
Voronoi.prototype.clipEdges = function(bbox) {
// connect all dangling edges to bounding box
// or get rid of them if it can't be done
var edges = this.edges,
iEdge = edges.length,
edge,
abs_fn = Math.abs;
// iterate backward so we can splice safely
while (iEdge--) {
edge = edges[iEdge];
// edge is removed if:
// it is wholly outside the bounding box
// it is looking more like a point than a line
if (!this.connectEdge(edge, bbox) ||
!this.clipEdge(edge, bbox) ||
(abs_fn(edge.va.x-edge.vb.x)<1e-9 && abs_fn(edge.va.y-edge.vb.y)<1e-9)) {
edge.va = edge.vb = null;
edges.splice(iEdge,1);
}
}
};
// Close the cells.
// The cells are bound by the supplied bounding box.
// Each cell refers to its associated site, and a list
// of halfedges ordered counterclockwise.
Voronoi.prototype.closeCells = function(bbox) {
var xl = bbox.xl,
xr = bbox.xr,
yt = bbox.yt,
yb = bbox.yb,
cells = this.cells,
iCell = cells.length,
cell,
iLeft,
halfedges, nHalfedges,
edge,
va, vb, vz,
lastBorderSegment,
abs_fn = Math.abs;
while (iCell--) {
cell = cells[iCell];
// prune, order halfedges counterclockwise, then add missing ones
// required to close cells
if (!cell.prepareHalfedges()) {
continue;
}
if (!cell.closeMe) {
continue;
}
// find first 'unclosed' point.
// an 'unclosed' point will be the end point of a halfedge which
// does not match the start point of the following halfedge
halfedges = cell.halfedges;
nHalfedges = halfedges.length;
// special case: only one site, in which case, the viewport is the cell
// ...
// all other cases
iLeft = 0;
while (iLeft < nHalfedges) {
va = halfedges[iLeft].getEndpoint();
vz = halfedges[(iLeft+1) % nHalfedges].getStartpoint();
// if end point is not equal to start point, we need to add the missing
// halfedge(s) up to vz
if (abs_fn(va.x-vz.x)>=1e-9 || abs_fn(va.y-vz.y)>=1e-9) {
// rhill 2013-12-02:
// "Holes" in the halfedges are not necessarily always adjacent.
// https://github.com/gorhill/Javascript-Voronoi/issues/16
// find entry point:
switch (true) {
// walk downward along left side
case this.equalWithEpsilon(va.x,xl) && this.lessThanWithEpsilon(va.y,yb):
lastBorderSegment = this.equalWithEpsilon(vz.x,xl);
vb = this.createVertex(xl, lastBorderSegment ? vz.y : yb);
edge = this.createBorderEdge(cell.site, va, vb);
iLeft++;
halfedges.splice(iLeft, 0, this.createHalfedge(edge, cell.site, null));
nHalfedges++;
if ( lastBorderSegment ) { break; }
va = vb;
// fall through
// walk rightward along bottom side
case this.equalWithEpsilon(va.y,yb) && this.lessThanWithEpsilon(va.x,xr):
lastBorderSegment = this.equalWithEpsilon(vz.y,yb);
vb = this.createVertex(lastBorderSegment ? vz.x : xr, yb);
edge = this.createBorderEdge(cell.site, va, vb);
iLeft++;
halfedges.splice(iLeft, 0, this.createHalfedge(edge, cell.site, null));
nHalfedges++;
if ( lastBorderSegment ) { break; }
va = vb;
// fall through
// walk upward along right side
case this.equalWithEpsilon(va.x,xr) && this.greaterThanWithEpsilon(va.y,yt):
lastBorderSegment = this.equalWithEpsilon(vz.x,xr);
vb = this.createVertex(xr, lastBorderSegment ? vz.y : yt);
edge = this.createBorderEdge(cell.site, va, vb);
iLeft++;
halfedges.splice(iLeft, 0, this.createHalfedge(edge, cell.site, null));
nHalfedges++;
if ( lastBorderSegment ) { break; }
va = vb;
// fall through
// walk leftward along top side
case this.equalWithEpsilon(va.y,yt) && this.greaterThanWithEpsilon(va.x,xl):
lastBorderSegment = this.equalWithEpsilon(vz.y,yt);
vb = this.createVertex(lastBorderSegment ? vz.x : xl, yt);
edge = this.createBorderEdge(cell.site, va, vb);
iLeft++;
halfedges.splice(iLeft, 0, this.createHalfedge(edge, cell.site, null));
nHalfedges++;
if ( lastBorderSegment ) { break; }
va = vb;
// fall through
// walk downward along left side
lastBorderSegment = this.equalWithEpsilon(vz.x,xl);
vb = this.createVertex(xl, lastBorderSegment ? vz.y : yb);
edge = this.createBorderEdge(cell.site, va, vb);
iLeft++;
halfedges.splice(iLeft, 0, this.createHalfedge(edge, cell.site, null));
nHalfedges++;
if ( lastBorderSegment ) { break; }
va = vb;
// fall through
// walk rightward along bottom side
lastBorderSegment = this.equalWithEpsilon(vz.y,yb);
vb = this.createVertex(lastBorderSegment ? vz.x : xr, yb);
edge = this.createBorderEdge(cell.site, va, vb);
iLeft++;
halfedges.splice(iLeft, 0, this.createHalfedge(edge, cell.site, null));
nHalfedges++;
if ( lastBorderSegment ) { break; }
va = vb;
// fall through
// walk upward along right side
lastBorderSegment = this.equalWithEpsilon(vz.x,xr);
vb = this.createVertex(xr, lastBorderSegment ? vz.y : yt);
edge = this.createBorderEdge(cell.site, va, vb);
iLeft++;
halfedges.splice(iLeft, 0, this.createHalfedge(edge, cell.site, null));
nHalfedges++;
if ( lastBorderSegment ) { break; }
// fall through
default:
throw "Voronoi.closeCells() > this makes no sense!";
}
}
iLeft++;
}
cell.closeMe = false;
}
};
// ---------------------------------------------------------------------------
// Debugging helper
/*
Voronoi.prototype.dumpBeachline = function(y) {
console.log('Voronoi.dumpBeachline(%f) > Beachsections, from left to right:', y);
if ( !this.beachline ) {
console.log(' None');
}
else {
var bs = this.beachline.getFirst(this.beachline.root);
while ( bs ) {
console.log(' site %d: xl: %f, xr: %f', bs.site.voronoiId, this.leftBreakPoint(bs, y), this.rightBreakPoint(bs, y));
bs = bs.rbNext;
}
}
};
*/
// ---------------------------------------------------------------------------
// Helper: Quantize sites
// rhill 2013-10-12:
// This is to solve https://github.com/gorhill/Javascript-Voronoi/issues/15
// Since not all users will end up using the kind of coord values which would
// cause the issue to arise, I chose to let the user decide whether or not
// he should sanitize his coord values through this helper. This way, for
// those users who uses coord values which are known to be fine, no overhead is
// added.
Voronoi.prototype.quantizeSites = function(sites) {
var ε = this.ε,
n = sites.length,
site;
while ( n-- ) {
site = sites[n];
site.x = Math.floor(site.x / ε) * ε;
site.y = Math.floor(site.y / ε) * ε;
}
};
// ---------------------------------------------------------------------------
// Helper: Recycle diagram: all vertex, edge and cell objects are
// "surrendered" to the Voronoi object for reuse.
// TODO: rhill-voronoi-core v2: more performance to be gained
// when I change the semantic of what is returned.
Voronoi.prototype.recycle = function(diagram) {
if ( diagram ) {
if ( diagram instanceof this.Diagram ) {
this.toRecycle = diagram;
}
else {
throw 'Voronoi.recycleDiagram() > Need a Diagram object.';
}
}
};
// ---------------------------------------------------------------------------
// Top-level Fortune loop
// rhill 2011-05-19:
// Voronoi sites are kept client-side now, to allow
// user to freely modify content. At compute time,
// *references* to sites are copied locally.
Voronoi.prototype.compute = function(sites, bbox) {
// to measure execution time
var startTime = new Date();
// init internal state
this.reset();
// any diagram data available for recycling?
// I do that here so that this is included in execution time
if ( this.toRecycle ) {
this.vertexJunkyard = this.vertexJunkyard.concat(this.toRecycle.vertices);
this.edgeJunkyard = this.edgeJunkyard.concat(this.toRecycle.edges);
this.cellJunkyard = this.cellJunkyard.concat(this.toRecycle.cells);
this.toRecycle = null;
}
// Initialize site event queue
var siteEvents = sites.slice(0);
siteEvents.sort(function(a,b){
var r = b.y - a.y;
if (r) {return r;}
return b.x - a.x;
});
// process queue
var site = siteEvents.pop(),
siteid = 0,
xsitex, // to avoid duplicate sites
xsitey,
cells = this.cells,
circle;
// main loop
for (;;) {
// we need to figure whether we handle a site or circle event
// for this we find out if there is a site event and it is
// 'earlier' than the circle event
circle = this.firstCircleEvent;
// add beach section
if (site && (!circle || site.y < circle.y || (site.y === circle.y && site.x < circle.x))) {
// only if site is not a duplicate
if (site.x !== xsitex || site.y !== xsitey) {
// first create cell for new site
cells[siteid] = this.createCell(site);
site.voronoiId = siteid++;
// then create a beachsection for that site
this.addBeachsection(site);
// remember last site coords to detect duplicate
xsitey = site.y;
xsitex = site.x;
}
site = siteEvents.pop();
}
// remove beach section
else if (circle) {
this.removeBeachsection(circle.arc);
}
// all done, quit
else {
break;
}
}
// wrapping-up:
// connect dangling edges to bounding box
// cut edges as per bounding box
// discard edges completely outside bounding box
// discard edges which are point-like
this.clipEdges(bbox);
// add missing edges in order to close opened cells
this.closeCells(bbox);
// to measure execution time
var stopTime = new Date();
// prepare return values
var diagram = new this.Diagram();
diagram.cells = this.cells;
diagram.edges = this.edges;
diagram.vertices = this.vertices;
diagram.execTime = stopTime.getTime()-startTime.getTime();
// clean up
this.reset();
return diagram;
};
module.exports = Voronoi;
|
// All symbols in the `Inherited` script as per Unicode v8.0.0:
[
'\u0300',
'\u0301',
'\u0302',
'\u0303',
'\u0304',
'\u0305',
'\u0306',
'\u0307',
'\u0308',
'\u0309',
'\u030A',
'\u030B',
'\u030C',
'\u030D',
'\u030E',
'\u030F',
'\u0310',
'\u0311',
'\u0312',
'\u0313',
'\u0314',
'\u0315',
'\u0316',
'\u0317',
'\u0318',
'\u0319',
'\u031A',
'\u031B',
'\u031C',
'\u031D',
'\u031E',
'\u031F',
'\u0320',
'\u0321',
'\u0322',
'\u0323',
'\u0324',
'\u0325',
'\u0326',
'\u0327',
'\u0328',
'\u0329',
'\u032A',
'\u032B',
'\u032C',
'\u032D',
'\u032E',
'\u032F',
'\u0330',
'\u0331',
'\u0332',
'\u0333',
'\u0334',
'\u0335',
'\u0336',
'\u0337',
'\u0338',
'\u0339',
'\u033A',
'\u033B',
'\u033C',
'\u033D',
'\u033E',
'\u033F',
'\u0340',
'\u0341',
'\u0342',
'\u0343',
'\u0344',
'\u0345',
'\u0346',
'\u0347',
'\u0348',
'\u0349',
'\u034A',
'\u034B',
'\u034C',
'\u034D',
'\u034E',
'\u034F',
'\u0350',
'\u0351',
'\u0352',
'\u0353',
'\u0354',
'\u0355',
'\u0356',
'\u0357',
'\u0358',
'\u0359',
'\u035A',
'\u035B',
'\u035C',
'\u035D',
'\u035E',
'\u035F',
'\u0360',
'\u0361',
'\u0362',
'\u0363',
'\u0364',
'\u0365',
'\u0366',
'\u0367',
'\u0368',
'\u0369',
'\u036A',
'\u036B',
'\u036C',
'\u036D',
'\u036E',
'\u036F',
'\u0485',
'\u0486',
'\u064B',
'\u064C',
'\u064D',
'\u064E',
'\u064F',
'\u0650',
'\u0651',
'\u0652',
'\u0653',
'\u0654',
'\u0655',
'\u0670',
'\u0951',
'\u0952',
'\u1AB0',
'\u1AB1',
'\u1AB2',
'\u1AB3',
'\u1AB4',
'\u1AB5',
'\u1AB6',
'\u1AB7',
'\u1AB8',
'\u1AB9',
'\u1ABA',
'\u1ABB',
'\u1ABC',
'\u1ABD',
'\u1ABE',
'\u1CD0',
'\u1CD1',
'\u1CD2',
'\u1CD4',
'\u1CD5',
'\u1CD6',
'\u1CD7',
'\u1CD8',
'\u1CD9',
'\u1CDA',
'\u1CDB',
'\u1CDC',
'\u1CDD',
'\u1CDE',
'\u1CDF',
'\u1CE0',
'\u1CE2',
'\u1CE3',
'\u1CE4',
'\u1CE5',
'\u1CE6',
'\u1CE7',
'\u1CE8',
'\u1CED',
'\u1CF4',
'\u1CF8',
'\u1CF9',
'\u1DC0',
'\u1DC1',
'\u1DC2',
'\u1DC3',
'\u1DC4',
'\u1DC5',
'\u1DC6',
'\u1DC7',
'\u1DC8',
'\u1DC9',
'\u1DCA',
'\u1DCB',
'\u1DCC',
'\u1DCD',
'\u1DCE',
'\u1DCF',
'\u1DD0',
'\u1DD1',
'\u1DD2',
'\u1DD3',
'\u1DD4',
'\u1DD5',
'\u1DD6',
'\u1DD7',
'\u1DD8',
'\u1DD9',
'\u1DDA',
'\u1DDB',
'\u1DDC',
'\u1DDD',
'\u1DDE',
'\u1DDF',
'\u1DE0',
'\u1DE1',
'\u1DE2',
'\u1DE3',
'\u1DE4',
'\u1DE5',
'\u1DE6',
'\u1DE7',
'\u1DE8',
'\u1DE9',
'\u1DEA',
'\u1DEB',
'\u1DEC',
'\u1DED',
'\u1DEE',
'\u1DEF',
'\u1DF0',
'\u1DF1',
'\u1DF2',
'\u1DF3',
'\u1DF4',
'\u1DF5',
'\u1DFC',
'\u1DFD',
'\u1DFE',
'\u1DFF',
'\u200C',
'\u200D',
'\u20D0',
'\u20D1',
'\u20D2',
'\u20D3',
'\u20D4',
'\u20D5',
'\u20D6',
'\u20D7',
'\u20D8',
'\u20D9',
'\u20DA',
'\u20DB',
'\u20DC',
'\u20DD',
'\u20DE',
'\u20DF',
'\u20E0',
'\u20E1',
'\u20E2',
'\u20E3',
'\u20E4',
'\u20E5',
'\u20E6',
'\u20E7',
'\u20E8',
'\u20E9',
'\u20EA',
'\u20EB',
'\u20EC',
'\u20ED',
'\u20EE',
'\u20EF',
'\u20F0',
'\u302A',
'\u302B',
'\u302C',
'\u302D',
'\u3099',
'\u309A',
'\uFE00',
'\uFE01',
'\uFE02',
'\uFE03',
'\uFE04',
'\uFE05',
'\uFE06',
'\uFE07',
'\uFE08',
'\uFE09',
'\uFE0A',
'\uFE0B',
'\uFE0C',
'\uFE0D',
'\uFE0E',
'\uFE0F',
'\uFE20',
'\uFE21',
'\uFE22',
'\uFE23',
'\uFE24',
'\uFE25',
'\uFE26',
'\uFE27',
'\uFE28',
'\uFE29',
'\uFE2A',
'\uFE2B',
'\uFE2C',
'\uFE2D',
'\uD800\uDDFD',
'\uD800\uDEE0',
'\uD834\uDD67',
'\uD834\uDD68',
'\uD834\uDD69',
'\uD834\uDD7B',
'\uD834\uDD7C',
'\uD834\uDD7D',
'\uD834\uDD7E',
'\uD834\uDD7F',
'\uD834\uDD80',
'\uD834\uDD81',
'\uD834\uDD82',
'\uD834\uDD85',
'\uD834\uDD86',
'\uD834\uDD87',
'\uD834\uDD88',
'\uD834\uDD89',
'\uD834\uDD8A',
'\uD834\uDD8B',
'\uD834\uDDAA',
'\uD834\uDDAB',
'\uD834\uDDAC',
'\uD834\uDDAD',
'\uDB40\uDD00',
'\uDB40\uDD01',
'\uDB40\uDD02',
'\uDB40\uDD03',
'\uDB40\uDD04',
'\uDB40\uDD05',
'\uDB40\uDD06',
'\uDB40\uDD07',
'\uDB40\uDD08',
'\uDB40\uDD09',
'\uDB40\uDD0A',
'\uDB40\uDD0B',
'\uDB40\uDD0C',
'\uDB40\uDD0D',
'\uDB40\uDD0E',
'\uDB40\uDD0F',
'\uDB40\uDD10',
'\uDB40\uDD11',
'\uDB40\uDD12',
'\uDB40\uDD13',
'\uDB40\uDD14',
'\uDB40\uDD15',
'\uDB40\uDD16',
'\uDB40\uDD17',
'\uDB40\uDD18',
'\uDB40\uDD19',
'\uDB40\uDD1A',
'\uDB40\uDD1B',
'\uDB40\uDD1C',
'\uDB40\uDD1D',
'\uDB40\uDD1E',
'\uDB40\uDD1F',
'\uDB40\uDD20',
'\uDB40\uDD21',
'\uDB40\uDD22',
'\uDB40\uDD23',
'\uDB40\uDD24',
'\uDB40\uDD25',
'\uDB40\uDD26',
'\uDB40\uDD27',
'\uDB40\uDD28',
'\uDB40\uDD29',
'\uDB40\uDD2A',
'\uDB40\uDD2B',
'\uDB40\uDD2C',
'\uDB40\uDD2D',
'\uDB40\uDD2E',
'\uDB40\uDD2F',
'\uDB40\uDD30',
'\uDB40\uDD31',
'\uDB40\uDD32',
'\uDB40\uDD33',
'\uDB40\uDD34',
'\uDB40\uDD35',
'\uDB40\uDD36',
'\uDB40\uDD37',
'\uDB40\uDD38',
'\uDB40\uDD39',
'\uDB40\uDD3A',
'\uDB40\uDD3B',
'\uDB40\uDD3C',
'\uDB40\uDD3D',
'\uDB40\uDD3E',
'\uDB40\uDD3F',
'\uDB40\uDD40',
'\uDB40\uDD41',
'\uDB40\uDD42',
'\uDB40\uDD43',
'\uDB40\uDD44',
'\uDB40\uDD45',
'\uDB40\uDD46',
'\uDB40\uDD47',
'\uDB40\uDD48',
'\uDB40\uDD49',
'\uDB40\uDD4A',
'\uDB40\uDD4B',
'\uDB40\uDD4C',
'\uDB40\uDD4D',
'\uDB40\uDD4E',
'\uDB40\uDD4F',
'\uDB40\uDD50',
'\uDB40\uDD51',
'\uDB40\uDD52',
'\uDB40\uDD53',
'\uDB40\uDD54',
'\uDB40\uDD55',
'\uDB40\uDD56',
'\uDB40\uDD57',
'\uDB40\uDD58',
'\uDB40\uDD59',
'\uDB40\uDD5A',
'\uDB40\uDD5B',
'\uDB40\uDD5C',
'\uDB40\uDD5D',
'\uDB40\uDD5E',
'\uDB40\uDD5F',
'\uDB40\uDD60',
'\uDB40\uDD61',
'\uDB40\uDD62',
'\uDB40\uDD63',
'\uDB40\uDD64',
'\uDB40\uDD65',
'\uDB40\uDD66',
'\uDB40\uDD67',
'\uDB40\uDD68',
'\uDB40\uDD69',
'\uDB40\uDD6A',
'\uDB40\uDD6B',
'\uDB40\uDD6C',
'\uDB40\uDD6D',
'\uDB40\uDD6E',
'\uDB40\uDD6F',
'\uDB40\uDD70',
'\uDB40\uDD71',
'\uDB40\uDD72',
'\uDB40\uDD73',
'\uDB40\uDD74',
'\uDB40\uDD75',
'\uDB40\uDD76',
'\uDB40\uDD77',
'\uDB40\uDD78',
'\uDB40\uDD79',
'\uDB40\uDD7A',
'\uDB40\uDD7B',
'\uDB40\uDD7C',
'\uDB40\uDD7D',
'\uDB40\uDD7E',
'\uDB40\uDD7F',
'\uDB40\uDD80',
'\uDB40\uDD81',
'\uDB40\uDD82',
'\uDB40\uDD83',
'\uDB40\uDD84',
'\uDB40\uDD85',
'\uDB40\uDD86',
'\uDB40\uDD87',
'\uDB40\uDD88',
'\uDB40\uDD89',
'\uDB40\uDD8A',
'\uDB40\uDD8B',
'\uDB40\uDD8C',
'\uDB40\uDD8D',
'\uDB40\uDD8E',
'\uDB40\uDD8F',
'\uDB40\uDD90',
'\uDB40\uDD91',
'\uDB40\uDD92',
'\uDB40\uDD93',
'\uDB40\uDD94',
'\uDB40\uDD95',
'\uDB40\uDD96',
'\uDB40\uDD97',
'\uDB40\uDD98',
'\uDB40\uDD99',
'\uDB40\uDD9A',
'\uDB40\uDD9B',
'\uDB40\uDD9C',
'\uDB40\uDD9D',
'\uDB40\uDD9E',
'\uDB40\uDD9F',
'\uDB40\uDDA0',
'\uDB40\uDDA1',
'\uDB40\uDDA2',
'\uDB40\uDDA3',
'\uDB40\uDDA4',
'\uDB40\uDDA5',
'\uDB40\uDDA6',
'\uDB40\uDDA7',
'\uDB40\uDDA8',
'\uDB40\uDDA9',
'\uDB40\uDDAA',
'\uDB40\uDDAB',
'\uDB40\uDDAC',
'\uDB40\uDDAD',
'\uDB40\uDDAE',
'\uDB40\uDDAF',
'\uDB40\uDDB0',
'\uDB40\uDDB1',
'\uDB40\uDDB2',
'\uDB40\uDDB3',
'\uDB40\uDDB4',
'\uDB40\uDDB5',
'\uDB40\uDDB6',
'\uDB40\uDDB7',
'\uDB40\uDDB8',
'\uDB40\uDDB9',
'\uDB40\uDDBA',
'\uDB40\uDDBB',
'\uDB40\uDDBC',
'\uDB40\uDDBD',
'\uDB40\uDDBE',
'\uDB40\uDDBF',
'\uDB40\uDDC0',
'\uDB40\uDDC1',
'\uDB40\uDDC2',
'\uDB40\uDDC3',
'\uDB40\uDDC4',
'\uDB40\uDDC5',
'\uDB40\uDDC6',
'\uDB40\uDDC7',
'\uDB40\uDDC8',
'\uDB40\uDDC9',
'\uDB40\uDDCA',
'\uDB40\uDDCB',
'\uDB40\uDDCC',
'\uDB40\uDDCD',
'\uDB40\uDDCE',
'\uDB40\uDDCF',
'\uDB40\uDDD0',
'\uDB40\uDDD1',
'\uDB40\uDDD2',
'\uDB40\uDDD3',
'\uDB40\uDDD4',
'\uDB40\uDDD5',
'\uDB40\uDDD6',
'\uDB40\uDDD7',
'\uDB40\uDDD8',
'\uDB40\uDDD9',
'\uDB40\uDDDA',
'\uDB40\uDDDB',
'\uDB40\uDDDC',
'\uDB40\uDDDD',
'\uDB40\uDDDE',
'\uDB40\uDDDF',
'\uDB40\uDDE0',
'\uDB40\uDDE1',
'\uDB40\uDDE2',
'\uDB40\uDDE3',
'\uDB40\uDDE4',
'\uDB40\uDDE5',
'\uDB40\uDDE6',
'\uDB40\uDDE7',
'\uDB40\uDDE8',
'\uDB40\uDDE9',
'\uDB40\uDDEA',
'\uDB40\uDDEB',
'\uDB40\uDDEC',
'\uDB40\uDDED',
'\uDB40\uDDEE',
'\uDB40\uDDEF'
];
|
require('ralph/core');
{
var $module = Object.create($moduleRoot);
{
($module)['%export'] = function B1930(name__1931, value__1932) {
var B1934 = (exports);
return(B1934[name__1931] = value__1932);
};
{
($module)['%eval'] = function B1933() {
return(eval((arguments[0])));
};
($module)['%export']('%eval', ($module)['%eval']);
}
}
}
var B1935 = require('ralph/core');
{
var B1936 = require('ralph/format');
var B1937 = require('ralph/compiler/utilities');
}
{
var B1941 = $S('bind-properties', 'ralph/core');
{
var B1942 = $S('%keys', 'ralph/core');
{
var B1943 = $S('%object', 'ralph/core');
{
($module)['wrap-keys'] = function B1944(form__1945, rest_parameter__1946, keyword_parameters__1947) {
var keyword_parametersT__1950 = B1935['map'](function B1948(parameter__1949) {
if (($T)(B1935['instance?'](parameter__1949, B1935['<array>'])))
return(parameter__1949);
else
return([
parameter__1949,
false
]);
}, keyword_parameters__1947);
return([
B1941,
B1935['map'](B1935['first'], keyword_parametersT__1950),
[
B1942,
rest_parameter__1946,
B1935['%concat']([B1943], B1935['reduce1'](B1935['concatenate'], B1935['map'](function B1951(parameter__1952) {
var key__1953 = parameter__1952[0];
{
var value__1954 = parameter__1952[1];
return([
B1935['symbol-name'](key__1953),
value__1954
]);
}
}, keyword_parametersT__1950)))
],
form__1945
]);
};
B1935['%annotate-function'](($module)['wrap-keys'], 'wrap-keys', false);
}
}
}
}
{
var B1958 = $S('bind', 'ralph/core');
{
var B1959 = $S('%native-call', 'ralph/core');
{
($module)['wrap-rest/keys'] = function B1960(form__1961, all_parameters__1962, normal_parameters__1963, rest_parameter__1964, keyword_parameters__1965) {
var restQ__1966 = rest_parameter__1964;
{
var B1967 = rest_parameter__1964;
{
var rest_parameter__1968 = false;
if (($T)(B1967))
rest_parameter__1968 = B1967;
else if (($T)(B1935['not'](B1935['empty?'](keyword_parameters__1965))))
rest_parameter__1968 = B1935['generate-symbol']();
else
rest_parameter__1968 = false;
{
var formT__1969 = false;
if (($T)(B1935['empty?'](keyword_parameters__1965)))
formT__1969 = form__1961;
else
formT__1969 = ($module)['wrap-keys'](form__1961, rest_parameter__1968, keyword_parameters__1965);
{
var B1970 = restQ__1966;
{
var B1971 = false;
if (($T)(B1970))
B1971 = B1970;
else
B1971 = B1935['not'](B1935['empty?'](keyword_parameters__1965));
if (($T)(B1971))
return([
B1958,
[[
rest_parameter__1968,
[
B1959,
'$SL.call',
all_parameters__1962,
B1935['size'](normal_parameters__1963)
]
]],
formT__1969
]);
else
return(formT__1969);
}
}
}
}
}
};
B1935['%annotate-function'](($module)['wrap-rest/keys'], 'wrap-rest/keys', false);
}
}
}
{
($module)['strip-types'] = function B1974(parameters__1975) {
return(B1935['map'](function B1976(parameter__1977) {
if (($T)(B1935['instance?'](parameter__1977, B1935['<array>'])))
return(B1935['first'](parameter__1977));
else
return(parameter__1977);
}, parameters__1975));
};
B1935['%annotate-function'](($module)['strip-types'], 'strip-types', false);
}
{
var B1980 = $S('%method', 'ralph/core');
{
var B1981 = $S('%all-arguments');
{
($module)['named-method'] = function B1982(name__1983, parameter_list__1984, form__1985) {
var B1986 = B1937['destructure-parameter-list'](parameter_list__1984);
{
var normal_parameters__1987 = B1986[0];
{
var rest_parameter__1988 = B1986[1];
{
var keyword_parameters__1989 = B1986[2];
return([
B1980,
name__1983,
($module)['strip-types'](normal_parameters__1987),
($module)['wrap-rest/keys'](form__1985, B1981, normal_parameters__1987, rest_parameter__1988, keyword_parameters__1989)
]);
}
}
}
};
B1935['%annotate-function'](($module)['named-method'], 'named-method', false);
}
}
}
{
($module)['$core-macros'] = B1935['make-plain-object']();
($module)['%export']('$core-macros', ($module)['$core-macros']);
}
{
var B1991 = $S('if', 'ralph/core');
{
var B1992 = $S('begin', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'when', function B1993(____1994, test__1995) {
var forms__1996 = $SL.call(arguments, 2);
return([
B1991,
test__1995,
B1935['%concat']([B1992], forms__1996),
false
]);
});
}
}
{
var B1998 = $S('not', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'unless', function B1999(____2000, test__2001) {
var forms__2002 = $SL.call(arguments, 2);
return([
B1991,
[
B1998,
test__2001
],
B1935['%concat']([B1992], forms__2002),
false
]);
});
}
{
var B2004 = $S('set!', 'ralph/core');
{
var B2005 = $S('parallel-set!', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'parallel-set!', function B2006(____2007, identifier__2008, new_value__2009) {
var clauses__2010 = $SL.call(arguments, 3);
if (($T)(B1935['empty?'](clauses__2010)))
return([
B2004,
identifier__2008,
new_value__2009
]);
else {
var value__2011 = B1935['generate-symbol']();
return([
B1958,
[[
value__2011,
new_value__2009
]],
B1935['%concat']([B2005], clauses__2010),
[
B2004,
identifier__2008,
value__2011
]
]);
}
});
}
}
{
var B2013 = $K('else');
{
var B2014 = $S('cond', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'cond', function B2015(____2016) {
var cases__2017 = $SL.call(arguments, 1);
if (($T)(B1935['not'](B1935['empty?'](cases__2017)))) {
var case__2018 = B1935['first'](cases__2017);
{
B1937['check-type'](case__2018, B1935['<array>'], 'Non-array case in cond: %=');
{
var test__2019 = case__2018[0];
{
var forms__2020 = $SL.call(case__2018, 1);
{
var form__2021 = B1935['%concat']([B1992], forms__2020);
if (($T)(B1935['=='](test__2019, B2013)))
return(form__2021);
else
return([
B1991,
test__2019,
form__2021,
B1935['%concat']([B2014], B1935['rest'](cases__2017))
]);
}
}
}
}
} else
return(false);
});
}
}
{
var B2024 = $S('when', 'ralph/core');
{
var B2025 = $S('and', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'and', function B2026(____2027) {
var forms__2028 = $SL.call(arguments, 1);
{
var B2029 = B1935['size'](forms__2028);
if (($T)(B1935['=='](B2029, 0)))
return(true);
else if (($T)(B1935['=='](B2029, 1)))
return(B1935['first'](forms__2028));
else
return([
B2024,
B1935['first'](forms__2028),
B1935['%concat']([B2025], B1935['rest'](forms__2028))
]);
}
});
}
}
{
var B2032 = $S('or', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'or', function B2033(____2034) {
var forms__2035 = $SL.call(arguments, 1);
{
var B2036 = B1935['size'](forms__2035);
if (($T)(B1935['=='](B2036, 0)))
return(false);
else if (($T)(B1935['=='](B2036, 1)))
return(B1935['first'](forms__2035));
else {
var value__2037 = B1935['generate-symbol']();
return([
B1958,
[[
value__2037,
B1935['first'](forms__2035)
]],
[
B1991,
value__2037,
value__2037,
B1935['%concat']([B2032], B1935['rest'](forms__2035))
]
]);
}
}
});
}
B1935['get-setter'](($module)['$core-macros'], 'if-bind', function B2039(____2040, binding__2041, consequent__2042, alternate__2043) {
var superflous__2044 = $SL.call(arguments, 4);
{
B1937['check-type'](binding__2041, B1935['<array>'], 'Non-array binding in if-bind: %=');
{
var var__2045 = binding__2041[0];
{
var value__2046 = binding__2041[1];
{
var temp__2047 = B1935['generate-symbol']();
return([
B1958,
[[
temp__2047,
value__2046
]],
[
B1991,
temp__2047,
[
B1958,
[[
var__2045,
temp__2047
]],
consequent__2042
],
alternate__2043
]
]);
}
}
}
}
});
{
var B2049 = $S('while', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'until', function B2050(____2051, test__2052) {
var forms__2053 = $SL.call(arguments, 2);
return(B1935['%concat']([
B2049,
[
B1998,
test__2052
]
], forms__2053));
});
}
{
var B2056 = $S('for', 'ralph/core');
{
var B2057 = $S('inc', 'ralph/core');
{
var B2058 = $S('binary>=', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'dotimes', function B2059(____2060, binding__2061) {
var forms__2062 = $SL.call(arguments, 2);
{
B1937['check-type'](binding__2061, B1935['<array>'], 'Non-array binding in dotimes: %=');
{
var temp__2063 = B1935['generate-symbol']();
{
var var__2064 = binding__2061[0];
{
var count__2065 = binding__2061[1];
{
var result__2066 = binding__2061[2];
{
B1937['check-type'](var__2064, B1935['<symbol>'], 'Non-symbol var in dotimes: %=');
{
var B2068 = [[
temp__2063,
count__2065
]];
{
var B2069 = B1935['%concat'];
{
var B2070 = [[
var__2064,
0,
[
B2057,
var__2064
]
]];
{
var B2071 = [
B2058,
var__2064,
temp__2063
];
{
var B2067 = result__2066;
{
var B2072 = false;
if (($T)(B2067))
B2072 = B2067;
else
B2072 = false;
{
var B2073 = [
B2071,
B2072
];
{
var B2074 = [
B2056,
B2070,
B2073
];
{
var B2075 = B2069(B2074, forms__2062);
return([
B1958,
B2068,
B2075
]);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
});
}
}
}
{
var B2084 = $S('method', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'for', function B2085(____2086, clauses__2087, end_clause__2088) {
var forms__2089 = $SL.call(arguments, 3);
{
B1937['check-type'](clauses__2087, B1935['<array>'], 'Non-array set of clauses in for: %=');
{
B1937['check-type'](end_clause__2088, B1935['<array>'], 'Non-array end-clause in for: %=');
{
var init_clauses__2090 = [];
{
var next_clauses__2091 = [];
{
var vars__2092 = B1935['map'](B1935['first'], clauses__2087);
{
var B2093 = clauses__2087;
{
var B2094 = false;
{
var B2095 = false;
{
var B2096 = [B2093];
{
while (true) {
var B2102 = B1935['not'];
{
var B2097 = B2094;
{
var B2103 = false;
if (($T)(B2097))
B2103 = B2097;
else
B2103 = B1935['any?'](B1935['empty?'], B2096);
{
var B2104 = B2102(B2103);
if (($T)(B2104)) {
var clause__2098 = B1935['first'](B2093);
{
(function B2099(clause__2100) {
B1937['check-type'](clause__2100, B1935['<array>'], 'Non-array clause in for: %=');
{
B1935['push-last'](init_clauses__2090, B1935['slice'](clause__2100, 0, 2));
{
B1935['push-last'](next_clauses__2091, B1935['first'](clause__2100));
return(B1935['push-last'](next_clauses__2091, B1935['third'](clause__2100)));
}
}
}(clause__2098));
{
B2093 = B1935['rest'](B2093);
B2096 = [B2093];
}
}
} else
break;
}
}
}
}
{
B2095;
{
var B2101 = B1935['empty?'](end_clause__2088);
{
var B2105 = false;
if (($T)(B2101))
B2105 = B2101;
else
B2105 = [
B1998,
B1935['first'](end_clause__2088)
];
{
var B2106 = B1935['%concat']([B1935['%concat']([
B2084,
vars__2092
], forms__2089)], vars__2092);
{
var B2107 = B1935['%concat']([B2005], next_clauses__2091);
{
var B2108 = [
B2049,
B2105,
B2106,
B2107
];
{
var B2109 = B1935['%concat']([B1992], B1935['rest'](end_clause__2088));
return([
B1958,
init_clauses__2090,
B2108,
B2109
]);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
});
}
{
var B2116 = $S('rest', 'ralph/core');
{
var B2117 = $S('%array', 'ralph/core');
{
var B2118 = $S('until', 'ralph/core');
{
var B2119 = $S('any?', 'ralph/core');
{
var B2120 = $S('empty?', 'ralph/core');
{
var B2121 = $S('first', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'for-each', function B2122(____2123, clauses__2124, end_clause__2125) {
var forms__2126 = $SL.call(arguments, 3);
{
B1937['check-type'](clauses__2124, B1935['<array>'], 'Non-array set of clauses in for: %=');
{
B1937['check-type'](end_clause__2125, B1935['<array>'], 'Non-array end-clause in for: %=');
{
var clauses__2129 = B1935['map'](function B2127(clause__2128) {
B1937['check-type'](clause__2128, B1935['<array>'], 'Non-array clause in for-each: %=');
return(B1935['cons'](B1935['generate-symbol'](), clause__2128));
}, clauses__2124);
{
var endQ__2130 = B1935['generate-symbol']();
{
var values__2131 = B1935['generate-symbol']();
{
var result__2132 = B1935['generate-symbol']();
{
var B2149 = B1935['%concat'];
{
var B2150 = B1935['%concat'];
{
var vars__2133 = B1935['map'](B1935['second'], clauses__2129);
{
var B2151 = B1935['%concat']([B1935['%concat']([
B2084,
vars__2133
], forms__2126)], vars__2133);
{
var B2152 = [
B1992,
B2151
];
{
var B2153 = B1935['map'](function B2134(clause__2135) {
return([
B2004,
B1935['first'](clause__2135),
[
B2116,
B1935['first'](clause__2135)
]
]);
}, clauses__2129);
{
var B2154 = B2150(B2152, B2153);
{
var B2155 = [[
B2004,
values__2131,
B1935['%concat']([B2117], B1935['map'](B1935['first'], clauses__2129))
]];
{
var form__2136 = B2149(B2154, B2155);
{
var B2156 = B1935['%concat'](B1935['%concat']([], B1935['map'](function B2137(clause__2138) {
var temp__2139 = clause__2138[0];
{
var var__2140 = clause__2138[1];
{
var values__2141 = clause__2138[2];
return([
temp__2139,
values__2141
]);
}
}
}, clauses__2129)), [
[
endQ__2130,
false
],
[
result__2132,
false
],
[
values__2131,
B1935['%concat']([B2117], B1935['map'](B1935['first'], clauses__2129))
]
]);
{
var B2157 = [
B2032,
endQ__2130,
[
B2119,
B2120,
values__2131
]
];
{
var B2158 = B1935['map'](function B2142(clause__2143) {
var temp__2144 = clause__2143[0];
{
var var__2145 = clause__2143[1];
{
var values__2146 = clause__2143[2];
return([
var__2145,
[
B2121,
temp__2144
]
]);
}
}
}, clauses__2129);
{
var B2147 = B1935['first'](end_clause__2125);
{
var B2159 = false;
if (($T)(B2147)) {
var end_test__2148 = B2147;
B2159 = [
B1991,
end_test__2148,
[
B1992,
[
B2004,
result__2132,
B1935['%concat']([B1992], B1935['rest'](end_clause__2125))
],
[
B2004,
endQ__2130,
true
]
],
form__2136
];
} else
B2159 = form__2136;
{
var B2160 = [
B1958,
B2158,
B2159
];
{
var B2161 = [
B2118,
B2157,
B2160
];
return([
B1958,
B2156,
B2161,
result__2132
]);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
});
}
}
}
}
}
}
B1935['get-setter'](($module)['$core-macros'], 'select', function B2165(____2166, value__2167, test__2168) {
var cases__2169 = $SL.call(arguments, 3);
{
var valueT__2170 = B1935['generate-symbol']();
{
var testT__2171 = false;
if (($T)(B1935['instance?'](test__2168, B1935['<symbol>'])))
testT__2171 = test__2168;
else
testT__2171 = B1935['generate-symbol']();
{
var test_expression__2172 = false;
{
test_expression__2172 = function B2173(test_value__2174) {
return([
testT__2171,
valueT__2170,
test_value__2174
]);
};
{
var B2179 = B1935['concatenate'];
{
var B2180 = [[
valueT__2170,
value__2167
]];
{
var B2181 = false;
if (($T)(B1935['instance?'](test__2168, B1935['<symbol>'])))
B2181 = [];
else
B2181 = [[
testT__2171,
test__2168
]];
{
var B2182 = B2179(B2180, B2181);
{
var B2183 = B1935['%concat']([B2014], B1935['map'](function B2175(case__2176) {
B1937['check-type'](case__2176, B1935['<array>'], 'Non-array case in select: %=');
{
var test_forms__2177 = case__2176[0];
{
var forms__2178 = $SL.call(case__2176, 1);
if (($T)(B1935['=='](test_forms__2177, B2013)))
return(case__2176);
else {
B1937['check-type'](test_forms__2177, B1935['<array>'], 'Non-array set of test forms in select: %=');
return(B1935['%concat']([B1935['%concat']([B2032], B1935['map'](test_expression__2172, test_forms__2177))], forms__2178));
}
}
}
}, cases__2169));
return([
B1958,
B2182,
B2183
]);
}
}
}
}
}
}
}
}
}
});
{
var B2187 = $S('%get-property', 'ralph/core');
{
($module)['destructure'] = function B2188(bindings__2189, values__2190, form__2191) {
if (($T)(B1935['instance?'](values__2190, B1935['<symbol>']))) {
B1937['check-type'](bindings__2189, B1935['<array>'], 'Non-array set of bindings while destructuring: %=');
{
var B2192 = B1937['destructure-parameter-list'](bindings__2189);
{
var normal_parameters__2193 = B2192[0];
{
var rest_parameter__2194 = B2192[1];
{
var keyword_parameters__2195 = B2192[2];
{
var i__2196 = B1935['size'](normal_parameters__2193);
return(B1935['reduce'](function B2197(form__2198, binding__2199) {
i__2196 = B1935['-'](i__2196, 1);
if (($T)(B1935['instance?'](binding__2199, B1935['<symbol>'])))
return([
B1958,
[[
binding__2199,
[
B2187,
values__2190,
i__2196
]
]],
form__2198
]);
else
return(($module)['destructure'](binding__2199, [
B2187,
values__2190,
i__2196
], form__2198));
}, ($module)['wrap-rest/keys'](form__2191, values__2190, normal_parameters__2193, rest_parameter__2194, keyword_parameters__2195), B1935['reverse'](normal_parameters__2193)));
}
}
}
}
}
} else {
var var__2200 = B1935['generate-symbol']();
return([
B1958,
[[
var__2200,
values__2190
]],
($module)['destructure'](bindings__2189, var__2200, form__2191)
]);
}
};
B1935['%annotate-function'](($module)['destructure'], 'destructure', false);
}
}
B1935['get-setter'](($module)['$core-macros'], 'destructuring-bind', function B2202(____2203, bindings__2204, values__2205) {
var forms__2206 = $SL.call(arguments, 3);
return(($module)['destructure'](bindings__2204, values__2205, B1935['%concat']([B1992], forms__2206)));
});
B1935['get-setter'](($module)['$core-macros'], 'bind-properties', function B2209(____2210, properties__2211, object__2212) {
var forms__2213 = $SL.call(arguments, 3);
{
var objectT__2214 = B1935['generate-symbol']();
return(B1935['%concat']([
B1958,
B1935['%concat']([[
objectT__2214,
object__2212
]], B1935['map'](function B2215(property__2216) {
return([
property__2216,
[
B2187,
objectT__2214,
B1935['symbol-name'](property__2216)
]
]);
}, properties__2211))
], forms__2213));
}
});
B1935['get-setter'](($module)['$core-macros'], 'bind-methods', function B2219(____2220, bindings__2221) {
var forms__2222 = $SL.call(arguments, 2);
{
B1937['check-type'](bindings__2221, B1935['<array>'], 'Non-array set of bindings in bind-methods: %=');
return(B1935['%concat'](B1935['%concat']([
B1958,
B1935['map'](B1935['first'], bindings__2221)
], B1935['map'](function B2223(binding__2224) {
B1937['check-type'](bindings__2221, B1935['<array>'], 'Non-array binding in bind-methods: %=');
{
var identifier__2225 = binding__2224[0];
{
var parameter_list__2226 = binding__2224[1];
{
var forms__2227 = $SL.call(binding__2224, 2);
return([
B2004,
identifier__2225,
B1935['%concat']([
B2084,
parameter_list__2226
], forms__2227)
]);
}
}
}
}, bindings__2221)), forms__2222));
}
});
{
var B2233 = $S('generate-symbol', 'ralph/core');
{
var B2234 = $S('quote', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'once-only', function B2235(____2236, names__2237) {
var forms__2238 = $SL.call(arguments, 2);
{
var symbols__2241 = B1935['map'](function B2239(name__2240) {
return(B1935['generate-symbol']());
}, names__2237);
return([
B1958,
B1935['%concat']([], B1935['map'](function B2242(symbol__2243) {
return([
symbol__2243,
[B2233]
]);
}, symbols__2241)),
[
B2117,
[
B2234,
B1958
],
B1935['%concat']([B2117], B1935['map'](function B2244(symbol__2245, name__2246) {
return([
B2117,
symbol__2245,
name__2246
]);
}, symbols__2241, names__2237)),
B1935['%concat']([
B1958,
B1935['%concat']([], B1935['map'](function B2247(name__2248, symbol__2249) {
return([
name__2248,
symbol__2249
]);
}, names__2237, symbols__2241))
], forms__2238)
]
]);
}
});
}
}
{
var B2252 = $S('+', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'inc!', function B2253(____2254, object__2255, value__2256) {
var B2257 = value__2256;
{
var B2258 = false;
if (($T)(B2257))
B2258 = B2257;
else
B2258 = 1;
{
var B2259 = [
B2252,
object__2255,
B2258
];
return([
B2004,
object__2255,
B2259
]);
}
}
});
}
{
var B2262 = $S('-', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'dec!', function B2263(____2264, object__2265, value__2266) {
var B2267 = value__2266;
{
var B2268 = false;
if (($T)(B2267))
B2268 = B2267;
else
B2268 = 1;
{
var B2269 = [
B2262,
object__2265,
B2268
];
return([
B2004,
object__2265,
B2269
]);
}
}
});
}
{
($module)['signal-unsupported-dot-name'] = function B2271(property__2272) {
return(B1935['signal'](B1936['format-to-string']('Unsupported name for call in dot: %=', property__2272)));
};
B1935['%annotate-function'](($module)['signal-unsupported-dot-name'], 'signal-unsupported-dot-name', false);
}
B1935['get-setter'](($module)['$core-macros'], '.', function B2277(____2278, form__2279) {
var calls__2280 = $SL.call(arguments, 2);
return(B1935['reduce'](function B2281(form__2282, call__2283) {
B1937['check-type'](call__2283, B1935['<array>'], 'Non-array call in dot: %=');
{
var property__2284 = call__2283[0];
{
var arguments__2285 = $SL.call(call__2283, 1);
{
var bindings__2288 = B1935['map'](function B2286(argument__2287) {
return([
B1935['generate-symbol'](),
argument__2287
]);
}, arguments__2285);
{
var formT__2289 = B1935['generate-symbol']();
{
var B2291 = [[
formT__2289,
form__2282
]];
{
var B2292 = B1935['%concat'];
{
var B2290 = property__2284;
{
var B2293 = false;
if (($T)(B1935['instance?'](B2290, B1935['<string>'])))
B2293 = property__2284;
else if (($T)(B1935['instance?'](B2290, B1935['<symbol>'])))
B2293 = B1935['symbol-name'](property__2284);
else
B2293 = ($module)['signal-unsupported-dot-name'](property__2284);
{
var B2294 = [
B2187,
formT__2289,
B2293
];
{
var B2295 = [B2294];
{
var B2296 = B1935['map'](B1935['first'], bindings__2288);
{
var B2297 = B2292(B2295, B2296);
{
var B2298 = [
B1958,
bindings__2288,
B2297
];
return([
B1958,
B2291,
B2298
]);
}
}
}
}
}
}
}
}
}
}
}
}
}
}, form__2279, calls__2280));
});
{
var B2302 = $S('define', 'ralph/core');
{
var B2303 = $S('%make-method', 'ralph/core');
{
var B2304 = $S('<object>', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'define-method', function B2305(env__2306, identifier__2307, parameter_list__2308) {
var forms__2309 = $SL.call(arguments, 3);
{
var B2310 = false;
if (($T)(B1937['setter-identifier?'](identifier__2307)))
B2310 = [
true,
B1937['transform-setter-identifier'](B1935['second'](identifier__2307))
];
else
B2310 = [
false,
identifier__2307
];
{
var setterQ__2311 = B2310[0];
{
var identifier__2312 = B2310[1];
{
var B2317 = B1935['not'];
{
var B2313 = B1935['instance?'](identifier__2312, B1935['<symbol>']);
{
var B2318 = false;
if (($T)(B2313))
B2318 = B2313;
else
B2318 = setterQ__2311;
{
var B2319 = B2317(B2318);
{
if (($T)(B2319))
B1935['signal'](B1936['format-to-string']('Identifier not symbol or setter in define-method: %=', identifier__2312));
{
if (($T)(B1935['empty?'](parameter_list__2308)))
B1935['signal'](B1936['format-to-string']('Empty parameter-list in define-method: %=', identifier__2312));
{
var name__2314 = B1935['symbol-name'](identifier__2312);
{
var definition__2315 = B1935['%concat']([
B2084,
parameter_list__2308
], forms__2309);
{
var head__2316 = B1935['first'](parameter_list__2308);
{
var B2320 = false;
if (($T)(B1935['instance?'](head__2316, B1935['<array>'])))
B2320 = B1935['>'](B1935['size'](head__2316), 1);
else
B2320 = false;
{
var B2321 = false;
if (($T)(B2320))
B2321 = B1935['second'](head__2316);
else
B2321 = B2304;
{
var B2322 = [
B2303,
name__2314,
definition__2315,
setterQ__2311,
B2321,
identifier__2312
];
return([
B2302,
identifier__2312,
B2322
]);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
});
}
}
}
{
var B2326 = $S('%begin', 'ralph/core');
{
var B2327 = $S('%annotate-function', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'define-function', function B2328(env__2329, identifier__2330, parameter_list__2331) {
var forms__2332 = $SL.call(arguments, 3);
{
var B2333 = false;
if (($T)(B1937['setter-identifier?'](identifier__2330)))
B2333 = [
true,
B1937['transform-setter-identifier'](B1935['second'](identifier__2330))
];
else
B2333 = [
false,
identifier__2330
];
{
var setterQ__2334 = B2333[0];
{
var identifier__2335 = B2333[1];
{
var B2339 = B1935['not'];
{
var B2336 = B1935['instance?'](identifier__2335, B1935['<symbol>']);
{
var B2340 = false;
if (($T)(B2336))
B2340 = B2336;
else
B2340 = setterQ__2334;
{
var B2341 = B2339(B2340);
{
if (($T)(B2341))
B1935['signal'](B1936['format-to-string']('Identifier not symbol or setter in define-function: %=', identifier__2335));
{
var name__2337 = B1935['symbol-name'](identifier__2335);
{
var definition__2338 = B1935['%concat']([
B2084,
parameter_list__2331
], forms__2332);
{
B1935['get-setter'](env__2329, 'module', 'functions', name__2337, definition__2338);
return([
B2326,
[
B2302,
identifier__2335,
definition__2338
],
[
B2327,
identifier__2335,
name__2337,
setterQ__2334
]
]);
}
}
}
}
}
}
}
}
}
}
}
});
}
}
{
var B2343 = $S('%make-generic', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'define-generic', function B2344(____2345, identifier__2346, arguments__2347) {
var superflous__2348 = $SL.call(arguments, 3);
return([
B2302,
identifier__2346,
[
B2343,
B1935['symbol-name'](identifier__2346)
]
]);
});
}
{
var B2352 = $S('%make-class', 'ralph/core');
{
var B2353 = $S('%set', 'ralph/core');
{
var B2354 = $S('%native', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'define-class', function B2355(____2356, identifier__2357, superclass__2358) {
var properties__2359 = $SL.call(arguments, 3);
{
var B2364 = false;
if (($T)(B1935['not'](B1935['empty?'](superclass__2358))))
B2364 = B1935['first'](superclass__2358);
else
B2364 = false;
{
var B2365 = B1935['%concat']([B1943], B1935['reduce1'](B1935['concatenate'], B1935['map'](function B2360(property__2361) {
if (($T)(B1935['instance?'](property__2361, B1935['<array>'])))
return([
B1935['symbol-name'](B1935['first'](property__2361)),
[
B2084,
[],
B1935['second'](property__2361)
]
]);
else
return([
B1935['symbol-name'](property__2361),
false
]);
}, properties__2359)));
{
var B2370 = [
B1980,
identifier__2357,
[],
B1935['%concat']([B2326], B1935['map'](function B2362(property__2363) {
var B2366 = [
B2354,
'this'
];
{
var B2367 = false;
if (($T)(B1935['instance?'](property__2363, B1935['<array>'])))
B2367 = B1935['symbol-name'](B1935['first'](property__2363));
else
B2367 = B1935['symbol-name'](property__2363);
{
var B2368 = [
B2187,
B2366,
B2367
];
{
var B2369 = [
B2354,
'undefined'
];
return([
B2353,
B2368,
B2369
]);
}
}
}
}, properties__2359))
];
{
var B2371 = [
B2352,
B2364,
B2365,
B2370
];
return([
B2302,
identifier__2357,
B2371
]);
}
}
}
}
});
}
}
}
{
var B2373 = $S('define-function', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'define-macro', function B2374(____2375, identifier__2376, parameter_list__2377) {
var forms__2378 = $SL.call(arguments, 3);
{
B1937['check-type'](identifier__2376, B1935['<symbol>'], 'Non-symbol identifier in define-macro: %=');
{
B1937['check-type'](parameter_list__2377, B1935['<array>'], 'Non-array parameter-list in define-macro: %=');
return([
B1992,
B1935['%concat']([
B2373,
identifier__2376,
B1935['%concat']([B1935['generate-symbol']()], parameter_list__2377)
], forms__2378),
[
B2004,
[
B2187,
identifier__2376,
'%macro?'
],
true
]
]);
}
}
});
}
B1935['get-setter'](($module)['$core-macros'], 'define-symbol-macro', function B2380(____2381, identifier__2382, parameter_list__2383) {
var forms__2384 = $SL.call(arguments, 3);
{
B1937['check-type'](identifier__2382, B1935['<symbol>'], 'Non-symbol identifier in define-symbol-macro: %=');
{
B1937['check-type'](parameter_list__2383, B1935['<array>'], 'Non-array parameter-list in define-symbol-macro: %=');
return([
B1992,
B1935['%concat']([
B2373,
identifier__2382,
[]
], forms__2384),
[
B2004,
[
B2187,
identifier__2382,
'%symbol-macro?'
],
true
]
]);
}
}
});
{
var B2386 = $S('next-method', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'call-next-method', function B2387(____2388) {
var superflous__2389 = $SL.call(arguments, 1);
return([
[
B2187,
B2386,
'apply'
],
[
B2354,
'null'
],
B1981
]);
});
}
{
var B2392 = $S('%make-exit-function', 'ralph/core');
{
var B2393 = $S('%try', 'ralph/core');
{
var B2394 = $S('instance?', 'ralph/core');
{
var B2395 = $S('<non-local-exit>', 'ralph/core');
{
var B2396 = $S('%infix', 'ralph/core');
{
var B2397 = $S('signal', 'ralph/core');
B1935['get-setter'](($module)['$core-macros'], 'block', function B2398(____2399, name__2400) {
var body__2401 = $SL.call(arguments, 2);
{
var B2402 = false;
if (($T)(B1935['not'](B1935['empty?'](name__2400))))
B2402 = B1935['first'](name__2400);
else
B2402 = false;
if (($T)(B2402)) {
var name__2403 = B2402;
{
var block_var__2404 = B1935['generate-symbol']();
{
var condition_var__2405 = B1935['generate-symbol']();
return([
B1958,
[
[
name__2403,
[B2392]
],
[
block_var__2404,
B1935['%concat']([
B2084,
[]
], body__2401)
]
],
[
B2393,
[block_var__2404],
condition_var__2405,
[
B1991,
[
B2025,
[
B2394,
condition_var__2405,
B2395
],
[
B2396,
'===',
[
B2187,
condition_var__2405,
'identifier'
],
[
B2187,
name__2403,
'identifier'
]
]
],
[
B2187,
condition_var__2405,
'return-value'
],
[
B2397,
condition_var__2405
]
]
]
]);
}
}
} else
return(B1935['%concat']([B1992], body__2401));
}
});
}
}
}
}
}
}
{
($module)['$core-symbol-macros'] = B1935['make-plain-object']();
($module)['%export']('$core-symbol-macros', ($module)['$core-symbol-macros']);
}
{
var B2407 = $S('%next-method', 'ralph/core');
{
var B2408 = $S('%this-method');
B1935['get-setter'](($module)['$core-symbol-macros'], 'next-method', function B2409(____2410) {
var superflous__2411 = $SL.call(arguments, 1);
return([
B2407,
B2408
]);
});
}
}
{
($module)['$internal-macros'] = B1935['make-plain-object']();
($module)['%export']('$internal-macros', ($module)['$internal-macros']);
}
{
var B2414 = $S('%quote', 'ralph/core');
{
($module)['transform-quoted'] = function B2415(form__2416) {
var B2417 = form__2416;
if (($T)(B1935['instance?'](B2417, B1935['<array>'])))
return(B1935['%concat']([B2117], B1935['map'](($module)['transform-quoted'], form__2416)));
else if (($T)(B1935['instance?'](B2417, B1935['<symbol>'])))
return([
B2414,
form__2416
]);
else
return(form__2416);
};
B1935['%annotate-function'](($module)['transform-quoted'], 'transform-quoted', false);
}
}
B1935['get-setter'](($module)['$internal-macros'], 'quote', function B2419(____2420, form__2421) {
var superflous__2422 = $SL.call(arguments, 2);
return(($module)['transform-quoted'](form__2421));
});
B1935['get-setter'](($module)['$internal-macros'], 'begin', function B2425(____2426) {
var forms__2427 = $SL.call(arguments, 1);
{
var B2428 = B1935['size'](forms__2427);
if (($T)(B1935['=='](B2428, 0)))
return(false);
else if (($T)(B1935['=='](B2428, 1)))
return(B1935['first'](forms__2427));
else
return(B1935['%concat']([B2326], forms__2427));
}
});
{
var B2431 = $S('%bind', 'ralph/core');
B1935['get-setter'](($module)['$internal-macros'], 'bind', function B2432(____2433, bindings__2434) {
var forms__2435 = $SL.call(arguments, 2);
return(B1935['reduce'](function B2436(form__2437, binding__2438) {
var B2439 = false;
if (($T)(B1935['instance?'](binding__2438, B1935['<symbol>'])))
B2439 = [
binding__2438,
false
];
else
B2439 = binding__2438;
return([
B2431,
B2439,
form__2437
]);
}, B1935['%concat']([B1992], forms__2435), B1935['reverse'](bindings__2434)));
});
}
B1935['get-setter'](($module)['$internal-macros'], 'method', function B2441(____2442, parameter_list__2443) {
var forms__2444 = $SL.call(arguments, 2);
return(($module)['named-method'](B1935['generate-symbol'](), parameter_list__2443, B1935['%concat']([B1992], forms__2444)));
});
{
var B2446 = $S('%while', 'ralph/core');
B1935['get-setter'](($module)['$internal-macros'], 'while', function B2447(____2448, test__2449) {
var forms__2450 = $SL.call(arguments, 2);
return([
B2446,
test__2449,
B1935['%concat']([B1992], forms__2450)
]);
});
}
{
var B2452 = $S('%if', 'ralph/core');
B1935['get-setter'](($module)['$internal-macros'], 'if', function B2453(____2454, test__2455, then__2456, else__2457) {
var superflous__2458 = $SL.call(arguments, 4);
return([
B2452,
test__2455,
then__2456,
else__2457
]);
});
}
B1935['get-setter'](($module)['$internal-macros'], 'set!', function B2460(____2461, place__2462) {
var new_values__2463 = $SL.call(arguments, 2);
{
var B2464 = false;
if (($T)(B1935['instance?'](place__2462, B1935['<array>'])))
B2464 = B1935['not'](B1935['=='](B1935['symbol-name'](B1935['first'](place__2462)), '%get-property'));
else
B2464 = false;
if (($T)(B2464))
return(B1935['%concat'](B1935['%concat']([B1937['transform-setter-identifier'](B1935['first'](place__2462))], B1935['rest'](place__2462)), new_values__2463));
else
return([
B2353,
place__2462,
B1935['first'](new_values__2463)
]);
}
});
{
var B2467 = $S('%define', 'ralph/core');
B1935['get-setter'](($module)['$internal-macros'], 'define', function B2468(env__2469, identifier__2470, value__2471) {
var B2472 = value__2471;
{
var B2473 = false;
if (($T)(B2472))
B2473 = B2472;
else
B2473 = false;
return([
B2467,
identifier__2470,
B2473
]);
}
});
}
B1935['get-setter'](($module)['$internal-macros'], 'handler-case', function B2479(____2480, protected_form__2481) {
var cases__2482 = $SL.call(arguments, 2);
{
var condition_var__2483 = B1935['generate-symbol']();
return([
B2393,
protected_form__2481,
condition_var__2483,
B1935['%concat']([B2014], B1935['map'](function B2484(case__2485) {
var B2486 = case__2485[0];
{
var type__2487 = B2486[0];
{
var B2488 = $SL.call(B2486, 1);
{
var B2489 = B1935['%keys'](B2488, { 'condition': false });
{
var condition__2490 = B2489['condition'];
{
var body__2491 = $SL.call(case__2485, 1);
{
var B2492 = B1935['concatenate'];
{
var B2493 = [[
B2394,
condition_var__2483,
type__2487
]];
{
var B2494 = false;
if (($T)(condition__2490))
B2494 = [B1935['%concat']([
B1958,
[[
condition__2490,
condition_var__2483
]]
], body__2491)];
else
B2494 = body__2491;
return(B2492(B2493, B2494));
}
}
}
}
}
}
}
}
}, cases__2482))
]);
}
});
{
($module)['$internal-symbol-macros'] = B1935['make-plain-object']();
($module)['%export']('$internal-symbol-macros', ($module)['$internal-symbol-macros']);
}
|
// Compiled by ClojureScript 1.7.228 {}
goog.provide('clojure.browser.repl');
goog.require('cljs.core');
goog.require('goog.dom');
goog.require('goog.userAgent.product');
goog.require('goog.array');
goog.require('goog.object');
goog.require('clojure.browser.net');
goog.require('clojure.browser.event');
goog.require('cljs.repl');
clojure.browser.repl.xpc_connection = cljs.core.atom.call(null,null);
clojure.browser.repl.print_queue = [];
clojure.browser.repl.flush_print_queue_BANG_ = (function clojure$browser$repl$flush_print_queue_BANG_(conn){
var seq__14016_14020 = cljs.core.seq.call(null,clojure.browser.repl.print_queue);
var chunk__14017_14021 = null;
var count__14018_14022 = (0);
var i__14019_14023 = (0);
while(true){
if((i__14019_14023 < count__14018_14022)){
var str_14024 = cljs.core._nth.call(null,chunk__14017_14021,i__14019_14023);
clojure.browser.net.transmit.call(null,conn,new cljs.core.Keyword(null,"print","print",1299562414),str_14024);
var G__14025 = seq__14016_14020;
var G__14026 = chunk__14017_14021;
var G__14027 = count__14018_14022;
var G__14028 = (i__14019_14023 + (1));
seq__14016_14020 = G__14025;
chunk__14017_14021 = G__14026;
count__14018_14022 = G__14027;
i__14019_14023 = G__14028;
continue;
} else {
var temp__4425__auto___14029 = cljs.core.seq.call(null,seq__14016_14020);
if(temp__4425__auto___14029){
var seq__14016_14030__$1 = temp__4425__auto___14029;
if(cljs.core.chunked_seq_QMARK_.call(null,seq__14016_14030__$1)){
var c__7592__auto___14031 = cljs.core.chunk_first.call(null,seq__14016_14030__$1);
var G__14032 = cljs.core.chunk_rest.call(null,seq__14016_14030__$1);
var G__14033 = c__7592__auto___14031;
var G__14034 = cljs.core.count.call(null,c__7592__auto___14031);
var G__14035 = (0);
seq__14016_14020 = G__14032;
chunk__14017_14021 = G__14033;
count__14018_14022 = G__14034;
i__14019_14023 = G__14035;
continue;
} else {
var str_14036 = cljs.core.first.call(null,seq__14016_14030__$1);
clojure.browser.net.transmit.call(null,conn,new cljs.core.Keyword(null,"print","print",1299562414),str_14036);
var G__14037 = cljs.core.next.call(null,seq__14016_14030__$1);
var G__14038 = null;
var G__14039 = (0);
var G__14040 = (0);
seq__14016_14020 = G__14037;
chunk__14017_14021 = G__14038;
count__14018_14022 = G__14039;
i__14019_14023 = G__14040;
continue;
}
} else {
}
}
break;
}
return goog.array.clear(clojure.browser.repl.print_queue);
});
clojure.browser.repl.repl_print = (function clojure$browser$repl$repl_print(data){
clojure.browser.repl.print_queue.push(cljs.core.pr_str.call(null,data));
var temp__4425__auto__ = cljs.core.deref.call(null,clojure.browser.repl.xpc_connection);
if(cljs.core.truth_(temp__4425__auto__)){
var conn = temp__4425__auto__;
return clojure.browser.repl.flush_print_queue_BANG_.call(null,conn);
} else {
return null;
}
});
cljs.core._STAR_print_fn_STAR_ = clojure.browser.repl.repl_print;
cljs.core._STAR_print_err_fn_STAR_ = clojure.browser.repl.repl_print;
cljs.core._STAR_print_newline_STAR_ = true;
clojure.browser.repl.get_ua_product = (function clojure$browser$repl$get_ua_product(){
if(cljs.core.truth_(goog.userAgent.product.SAFARI)){
return new cljs.core.Keyword(null,"safari","safari",497115653);
} else {
if(cljs.core.truth_(goog.userAgent.product.CHROME)){
return new cljs.core.Keyword(null,"chrome","chrome",1718738387);
} else {
if(cljs.core.truth_(goog.userAgent.product.FIREFOX)){
return new cljs.core.Keyword(null,"firefox","firefox",1283768880);
} else {
if(cljs.core.truth_(goog.userAgent.product.IE)){
return new cljs.core.Keyword(null,"ie","ie",2038473780);
} else {
return null;
}
}
}
}
});
/**
* Process a single block of JavaScript received from the server
*/
clojure.browser.repl.evaluate_javascript = (function clojure$browser$repl$evaluate_javascript(conn,block){
var result = (function (){try{return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"status","status",-1997798413),new cljs.core.Keyword(null,"success","success",1890645906),new cljs.core.Keyword(null,"value","value",305978217),[cljs.core.str(eval(block))].join('')], null);
}catch (e14042){var e = e14042;
return new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"status","status",-1997798413),new cljs.core.Keyword(null,"exception","exception",-335277064),new cljs.core.Keyword(null,"ua-product","ua-product",938384227),clojure.browser.repl.get_ua_product.call(null),new cljs.core.Keyword(null,"value","value",305978217),[cljs.core.str(e)].join(''),new cljs.core.Keyword(null,"stacktrace","stacktrace",-95588394),(cljs.core.truth_(e.hasOwnProperty("stack"))?e.stack:"No stacktrace available.")], null);
}})();
return cljs.core.pr_str.call(null,result);
});
clojure.browser.repl.send_result = (function clojure$browser$repl$send_result(connection,url,data){
return clojure.browser.net.transmit.call(null,connection,url,"POST",data,null,(0));
});
/**
* Send data to be printed in the REPL. If there is an error, try again
* up to 10 times.
*/
clojure.browser.repl.send_print = (function clojure$browser$repl$send_print(var_args){
var args14043 = [];
var len__7847__auto___14046 = arguments.length;
var i__7848__auto___14047 = (0);
while(true){
if((i__7848__auto___14047 < len__7847__auto___14046)){
args14043.push((arguments[i__7848__auto___14047]));
var G__14048 = (i__7848__auto___14047 + (1));
i__7848__auto___14047 = G__14048;
continue;
} else {
}
break;
}
var G__14045 = args14043.length;
switch (G__14045) {
case 2:
return clojure.browser.repl.send_print.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)]));
break;
case 3:
return clojure.browser.repl.send_print.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)]));
break;
default:
throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args14043.length)].join('')));
}
});
clojure.browser.repl.send_print.cljs$core$IFn$_invoke$arity$2 = (function (url,data){
return clojure.browser.repl.send_print.call(null,url,data,(0));
});
clojure.browser.repl.send_print.cljs$core$IFn$_invoke$arity$3 = (function (url,data,n){
var conn = clojure.browser.net.xhr_connection.call(null);
clojure.browser.event.listen.call(null,conn,new cljs.core.Keyword(null,"error","error",-978969032),((function (conn){
return (function (_){
if((n < (10))){
return clojure.browser.repl.send_print.call(null,url,data,(n + (1)));
} else {
return console.log([cljs.core.str("Could not send "),cljs.core.str(data),cljs.core.str(" after "),cljs.core.str(n),cljs.core.str(" attempts.")].join(''));
}
});})(conn))
);
return clojure.browser.net.transmit.call(null,conn,url,"POST",data,null,(0));
});
clojure.browser.repl.send_print.cljs$lang$maxFixedArity = 3;
clojure.browser.repl.order = cljs.core.atom.call(null,(0));
clojure.browser.repl.wrap_message = (function clojure$browser$repl$wrap_message(t,data){
return cljs.core.pr_str.call(null,new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"type","type",1174270348),t,new cljs.core.Keyword(null,"content","content",15833224),data,new cljs.core.Keyword(null,"order","order",-1254677256),cljs.core.swap_BANG_.call(null,clojure.browser.repl.order,cljs.core.inc)], null));
});
/**
* Start the REPL server connection.
*/
clojure.browser.repl.start_evaluator = (function clojure$browser$repl$start_evaluator(url){
var temp__4423__auto__ = clojure.browser.net.xpc_connection.call(null);
if(cljs.core.truth_(temp__4423__auto__)){
var repl_connection = temp__4423__auto__;
var connection = clojure.browser.net.xhr_connection.call(null);
clojure.browser.event.listen.call(null,connection,new cljs.core.Keyword(null,"success","success",1890645906),((function (connection,repl_connection,temp__4423__auto__){
return (function (e){
return clojure.browser.net.transmit.call(null,repl_connection,new cljs.core.Keyword(null,"evaluate-javascript","evaluate-javascript",-315749780),e.currentTarget.getResponseText(cljs.core.List.EMPTY));
});})(connection,repl_connection,temp__4423__auto__))
);
clojure.browser.net.register_service.call(null,repl_connection,new cljs.core.Keyword(null,"send-result","send-result",35388249),((function (connection,repl_connection,temp__4423__auto__){
return (function (data){
return clojure.browser.repl.send_result.call(null,connection,url,clojure.browser.repl.wrap_message.call(null,new cljs.core.Keyword(null,"result","result",1415092211),data));
});})(connection,repl_connection,temp__4423__auto__))
);
clojure.browser.net.register_service.call(null,repl_connection,new cljs.core.Keyword(null,"print","print",1299562414),((function (connection,repl_connection,temp__4423__auto__){
return (function (data){
return clojure.browser.repl.send_print.call(null,url,clojure.browser.repl.wrap_message.call(null,new cljs.core.Keyword(null,"print","print",1299562414),data));
});})(connection,repl_connection,temp__4423__auto__))
);
clojure.browser.net.connect.call(null,repl_connection,cljs.core.constantly.call(null,null));
return setTimeout(((function (connection,repl_connection,temp__4423__auto__){
return (function (){
return clojure.browser.repl.send_result.call(null,connection,url,clojure.browser.repl.wrap_message.call(null,new cljs.core.Keyword(null,"ready","ready",1086465795),"ready"));
});})(connection,repl_connection,temp__4423__auto__))
,(50));
} else {
return alert("No 'xpc' param provided to child iframe.");
}
});
clojure.browser.repl.load_queue = null;
/**
* Reusable browser REPL bootstrapping. Patches the essential functions
* in goog.base to support re-loading of namespaces after page load.
*/
clojure.browser.repl.bootstrap = (function clojure$browser$repl$bootstrap(){
if(cljs.core.truth_(COMPILED)){
return null;
} else {
goog.require__ = goog.require;
goog.isProvided_ = (function (name){
return false;
});
goog.constructNamespace_("cljs.user");
goog.writeScriptTag__ = (function (src,opt_sourceText){
var loaded = cljs.core.atom.call(null,false);
var onload = ((function (loaded){
return (function (){
if(cljs.core.truth_((function (){var and__6777__auto__ = clojure.browser.repl.load_queue;
if(cljs.core.truth_(and__6777__auto__)){
return cljs.core.deref.call(null,loaded) === false;
} else {
return and__6777__auto__;
}
})())){
cljs.core.swap_BANG_.call(null,loaded,cljs.core.not);
if((clojure.browser.repl.load_queue.length === (0))){
return clojure.browser.repl.load_queue = null;
} else {
return goog.writeScriptTag__.apply(null,clojure.browser.repl.load_queue.shift());
}
} else {
return null;
}
});})(loaded))
;
return document.body.appendChild((function (){var script = document.createElement("script");
var script__$1 = (function (){var G__14053 = script;
goog.object.set(G__14053,"type","text/javascript");
goog.object.set(G__14053,"onload",onload);
goog.object.set(G__14053,"onreadystatechange",onload);
return G__14053;
})();
var script__$2 = (((opt_sourceText == null))?(function (){var G__14054 = script__$1;
goog.object.set(G__14054,"src",src);
return G__14054;
})():(function (){var G__14055 = script__$1;
goog.dom.setTextContext(G__14055,opt_sourceText);
return G__14055;
})());
return script__$2;
})());
});
goog.writeScriptTag_ = (function (src,opt_sourceText){
if(cljs.core.truth_(clojure.browser.repl.load_queue)){
return clojure.browser.repl.load_queue.push([src,opt_sourceText]);
} else {
clojure.browser.repl.load_queue = [];
return goog.writeScriptTag__(src,opt_sourceText);
}
});
return goog.require = (function (src,reload){
if(cljs.core._EQ_.call(null,reload,"reload-all")){
goog.cljsReloadAll_ = true;
} else {
}
var reload_QMARK_ = (function (){var or__6789__auto__ = reload;
if(cljs.core.truth_(or__6789__auto__)){
return or__6789__auto__;
} else {
return goog.cljsReloadAll__;
}
})();
if(cljs.core.truth_(reload_QMARK_)){
var path_14056 = (goog.dependencies_.nameToPath[src]);
goog.object.remove(goog.dependencies_.visited,path_14056);
goog.object.remove(goog.dependencies_.written,path_14056);
goog.object.remove(goog.dependencies_.written,[cljs.core.str(goog.basePath),cljs.core.str(path_14056)].join(''));
} else {
}
var ret = goog.require__(src);
if(cljs.core._EQ_.call(null,reload,"reload-all")){
goog.cljsReloadAll_ = false;
} else {
}
return ret;
});
}
});
/**
* Connects to a REPL server from an HTML document. After the
* connection is made, the REPL will evaluate forms in the context of
* the document that called this function.
*/
clojure.browser.repl.connect = (function clojure$browser$repl$connect(repl_server_url){
var repl_connection = clojure.browser.net.xpc_connection.call(null,new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"peer_uri","peer_uri",910305997),repl_server_url], null));
cljs.core.swap_BANG_.call(null,clojure.browser.repl.xpc_connection,cljs.core.constantly.call(null,repl_connection));
clojure.browser.net.register_service.call(null,repl_connection,new cljs.core.Keyword(null,"evaluate-javascript","evaluate-javascript",-315749780),((function (repl_connection){
return (function (js){
return clojure.browser.net.transmit.call(null,repl_connection,new cljs.core.Keyword(null,"send-result","send-result",35388249),clojure.browser.repl.evaluate_javascript.call(null,repl_connection,js));
});})(repl_connection))
);
clojure.browser.net.connect.call(null,repl_connection,cljs.core.constantly.call(null,null),((function (repl_connection){
return (function (iframe){
return iframe.style.display = "none";
});})(repl_connection))
);
clojure.browser.repl.bootstrap.call(null);
return repl_connection;
});
//# sourceMappingURL=repl.js.map
|
// Polyfills
//
(function() {
// Array indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
if ( this === undefined || this === null ) {
throw new TypeError( '"this" is null or not defined' );
}
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if (Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if (fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for (;fromIndex < length; fromIndex++) {
if (this[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
}
// Event listener
if (!Event.prototype.preventDefault) {
Event.prototype.preventDefault=function() {
this.returnValue=false;
};
}
if (!Event.prototype.stopPropagation) {
Event.prototype.stopPropagation=function() {
this.cancelBubble=true;
};
}
if (!Element.prototype.addEventListener) {
var eventListeners=[];
var addEventListener=function(type,listener /*, useCapture (will be ignored) */) {
var self=this;
var wrapper=function(e) {
e.target=e.srcElement;
e.currentTarget=self;
if (listener.handleEvent) {
listener.handleEvent(e);
} else {
listener.call(self,e);
}
};
if (type=="DOMContentLoaded") {
var wrapper2=function(e) {
if (document.readyState=="complete") {
wrapper(e);
}
};
document.attachEvent("onreadystatechange",wrapper2);
eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2});
if (document.readyState=="complete") {
var e=new Event();
e.srcElement=window;
wrapper2(e);
}
} else {
this.attachEvent("on"+type,wrapper);
eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper});
}
};
var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) {
var counter=0;
while (counter<eventListeners.length) {
var eventListener=eventListeners[counter];
if (eventListener.object==this && eventListener.type==type && eventListener.listener==listener) {
if (type=="DOMContentLoaded") {
this.detachEvent("onreadystatechange",eventListener.wrapper);
} else {
this.detachEvent("on"+type,eventListener.wrapper);
}
break;
}
++counter;
}
};
Element.prototype.addEventListener=addEventListener;
Element.prototype.removeEventListener=removeEventListener;
if (HTMLDocument) {
HTMLDocument.prototype.addEventListener=addEventListener;
HTMLDocument.prototype.removeEventListener=removeEventListener;
}
if (Window) {
Window.prototype.addEventListener=addEventListener;
Window.prototype.removeEventListener=removeEventListener;
}
}
})();
// Demo
//
(function() {
var storageSupported = (typeof(window.Storage)!=="undefined");
// Functions
//
var reloadPage = function () {
location.reload();
}
var testTheme = function (name) {
for (var j=0; j<demo_themes.length; j++) {
if (demo_themes[j].name === name) {
return demo_themes[j].name;
}
}
return 'default';
}
var loadDemoSettings = function () {
var result = {
fixed_navbar: false,
fixed_menu: false,
rtl: false,
menu_right: false,
theme: 'default'
};
if (storageSupported) {
try {
result.fixed_navbar = (window.localStorage.demo_fixed_navbar && window.localStorage.demo_fixed_navbar === '1');
result.fixed_menu = (window.localStorage.demo_fixed_menu && window.localStorage.demo_fixed_menu === '1');
result.rtl = (window.localStorage.demo_rtl && window.localStorage.demo_rtl === '1');
result.menu_right = (window.localStorage.demo_menu_right && window.localStorage.demo_menu_right === '1');
result.theme = testTheme((window.localStorage.demo_theme) ? window.localStorage.demo_theme : '');
return result;
} catch (e) {}
}
var key, val, pos, demo_cookies = document.cookie.split(';');
for (var i=0, l=demo_cookies.length; i < l; i++) {
pos = demo_cookies[i].indexOf('=');
key = demo_cookies[i].substr(0, pos).replace(/^\s+|\s+$/g, '');
val = demo_cookies[i].substr(pos + 1).replace(/^\s+|\s+$/g, '');
if (key === 'demo_fixed_navbar') {
result.fixed_navbar = (val === '1') ? true : false;
} else if (key === 'demo_fixed_menu') {
result.fixed_menu = (val === '1') ? true : false;
} else if (key === 'demo_rtl') {
result.rtl = (val === '1') ? true : false;
} else if (key === 'demo_menu_right') {
result.menu_right = (val === '1') ? true : false;
} else if (key === 'demo_theme') {
result.theme = testTheme(val);
}
}
return result;
}
var saveDemoSettings = function () {
if (storageSupported) {
try {
window.localStorage.demo_fixed_navbar = escape((demo_settings.fixed_navbar) ? '1' : '0');
window.localStorage.demo_fixed_menu = escape((demo_settings.fixed_menu) ? '1' : '0');
window.localStorage.demo_rtl = escape((demo_settings.rtl) ? '1' : '0');
window.localStorage.demo_menu_right = escape((demo_settings.menu_right) ? '1' : '0');
window.localStorage.demo_theme = escape(demo_settings.theme);
return;
} catch (e) {}
}
document.cookie = 'demo_fixed_navbar=' + escape((demo_settings.fixed_navbar) ? '1' : '0');
document.cookie = 'demo_fixed_menu=' + escape((demo_settings.fixed_menu) ? '1' : '0');
document.cookie = 'demo_rtl=' + escape((demo_settings.rtl) ? '1' : '0');
document.cookie = 'demo_menu_right=' + escape((demo_settings.menu_right) ? '1' : '0');
document.cookie = 'demo_theme=' + escape(demo_settings.theme);
}
var getThemesTemplate = function () {
result = '';
for (var i=0, l=demo_themes.length-1; i <= l; i++) {
if (i % 2 == 0) {
result = result + '<div class="demo-themes-row">';
result = result + '<a href="#" class="demo-theme" data-theme="' + demo_themes[i].name + '"><div class="theme-preview"><img src="' + demo_themes[i].img + '" alt=""></div><div class="overlay"></div><span>' + demo_themes[i].title + '</span></a>';
} else {
result = result + '<a href="#" class="demo-theme" data-theme="' + demo_themes[i].name + '"><div class="theme-preview"><img src="' + demo_themes[i].img + '" alt=""></div><div class="overlay"></div><span>' + demo_themes[i].title + '</span></a>';
result = result + '</div>';
}
if (i == l && i % 2 == 0) {
result = result + '<div class="demo-theme"></div></div>';
}
}
return result;
}
var activateTheme = function (btns) {
document.body.className = document.body.className.replace(/theme\-[a-z0-9\-\_]+/ig, 'theme-' + demo_settings.theme);
if (! btns) return;
btns.removeClass('dark');
if (demo_settings.theme != 'clean' && demo_settings.theme != 'white') {
btns.addClass('dark');
}
}
// Load and apply settings
//
var panel_width = 260;
var demo_themes = [
{ name: 'default', title: 'Default', img: '/symfony/web/assets/demo/themes/default.png' },
{ name: 'asphalt', title: 'Asphalt', img: '/symfony/web/assets/demo/themes/asphalt.png' },
{ name: 'purple-hills', title: 'Purple Hills', img: '/symfony/web/assets/demo/themes/purple-hills.png' },
{ name: 'adminflare', title: 'Adminflare', img: '/symfony/web/assets/demo/themes/adminflare.png' },
{ name: 'dust', title: 'Dust', img: '/symfony/web/assets/demo/themes/dust.png' },
{ name: 'frost', title: 'Frost', img: '/symfony/web/assets/demo/themes/frost.png' },
{ name: 'fresh', title: 'Fresh', img: '/symfony/web/assets/demo/themes/fresh.png' },
{ name: 'silver', title: 'Silver', img: '/symfony/web/assets/demo/themes/silver.png' },
{ name: 'clean', title: 'Clean', img: '/symfony/web/assets/demo/themes/clean.png' },
{ name: 'white', title: 'White', img: '/symfony/web/assets/demo/themes/white.png' }
];
var demo_settings = loadDemoSettings();
if (demo_settings.fixed_navbar) {
document.body.className = document.body.className + ' main-navbar-fixed';
}
if (demo_settings.fixed_menu) {
document.body.className = document.body.className + ' main-menu-fixed';
}
if (demo_settings.rtl) {
document.body.className = document.body.className + ' right-to-left';
}
if (demo_settings.menu_right) {
document.body.className = document.body.className + ' main-menu-right';
}
activateTheme();
// Templates
//
var demo_styles = [
'#demo-themes {',
' display: table;',
' table-layout: fixed;',
' width: 100%;',
' border-bottom-left-radius: 5px;',
' overflow: hidden;',
'}',
'#demo-themes .demo-themes-row {',
' display: block;',
'}',
'#demo-themes .demo-theme {',
' display: block;',
' float: left;',
' text-align: center;',
' width: 50%;',
' padding: 25px 0;',
' color: #888;',
' position: relative;',
' overflow: hidden;',
'}',
'#demo-themes .demo-theme:hover {',
' color: #fff;',
'}',
'#demo-themes .theme-preview {',
' width: 100%;',
' position: absolute;',
' top: 0;',
' left: 0;',
' bottom: 0;',
' overflow: hidden !important;',
'}',
'#demo-themes .theme-preview img {',
' width: 100%;',
' position: absolute;',
' display: block;',
' top: 0;',
' left: 0;',
'}',
'#demo-themes .demo-theme .overlay {',
' background: #1d1d1d;',
' background: rgba(0,0,0,.8);',
' position: absolute;',
' top: 0;',
' bottom: 0;',
' left: -100%;',
' width: 100%;',
'}',
'#demo-themes .demo-theme span {',
' position: relative;',
' color: #fff;',
' color: rgba(255,255,255,0);',
'}',
'#demo-themes .demo-theme span,',
'#demo-themes .demo-theme .overlay {',
' -webkit-transition: all .3s;',
' -moz-transition: all .3s;',
' -ms-transition: all .3s;',
' -o-transition: all .3s;',
' transition: all .3s;',
'}',
'#demo-themes .demo-theme.active span,',
'#demo-themes .demo-theme:hover span {',
' color: #fff;',
' color: rgba(255,255,255,1);',
'}',
'#demo-themes .demo-theme.active .overlay,',
'#demo-themes .demo-theme:hover .overlay {',
' left: 0;',
'}',
'#demo-settings {',
' position: fixed;',
' right: -' + (panel_width + 10) + 'px;',
' width: ' + (panel_width + 10) + 'px;',
' top: 70px;',
' padding-right: 10px; ',
' background: #333;',
' border-radius: 5px;',
' -webkit-transition: all .3s;',
' -moz-transition: all .3s;',
' -ms-transition: all .3s;',
' -o-transition: all .3s;',
' transition: all .3s;',
' -webkit-touch-callout: none;',
' -webkit-user-select: none;',
' -khtml-user-select: none;',
' -moz-user-select: none;',
' -ms-user-select: none;',
' user-select: none;',
' z-index: 999998;',
'}',
'#demo-settings.open {',
' right: -10px;',
'}',
'#demo-settings > .header {',
' position: relative;',
' z-index: 100000;',
' line-height: 20px;',
' background: #444;',
' color: #fff;',
' font-size: 11px;',
' font-weight: 600;',
' padding: 10px 20px;',
' margin: 0;',
'}',
'#demo-settings > div {',
' position: relative;',
' z-index: 100000;',
' background: #282828;',
' border-bottom-right-radius: 5px;',
' border-bottom-left-radius: 5px;',
'}',
'#demo-settings-toggler {',
' font-size: 21px;',
' width: 50px;',
' height: 40px;',
' padding-right: 10px;',
' position: absolute;',
' left: -40px;',
' top: 0;',
' background: #444;',
' text-align: center;',
' line-height: 40px;',
' color: #fff;',
' border-radius: 5px;',
' z-index: 99999;',
' text-decoration: none !important;',
' -webkit-transition: color .3s;',
' -moz-transition: color .3s;',
' -ms-transition: color .3s;',
' -o-transition: color .3s;',
' transition: color .3s;',
'}',
'#demo-settings.open #demo-settings-toggler {',
' font-size: 16px;',
' color: #888;',
'}',
'#demo-settings.open #demo-settings-toggler:hover {',
' color: #fff;',
'}',
'#demo-settings.open #demo-settings-toggler:before {',
' content: "\\f00d";',
'}',
'#demo-settings-list {',
' padding: 0;',
' margin: 0;',
'}',
'#demo-settings-list li {',
' padding: 0;',
' margin: 0;',
' list-style: none;',
' position: relative;',
'}',
'#demo-settings-list li > span {',
' line-height: 20px;',
' color: #fff;',
' display: block;',
' padding: 12px 20px;',
' cursor: pointer;',
'}',
'#demo-settings-list li + li {',
' border-top: 1px solid #333;',
'}',
'#demo-settings .demo-checkbox {',
' position: absolute;',
' right: 20px;',
' top: 12px;',
'}',
'.right-to-left #demo-settings {',
' left: -270px;',
' right: auto;',
' padding-right: 0;',
' padding-left: 10px;',
'}',
'.right-to-left #demo-settings.open {',
' left: -10px;',
' right: auto;',
'}',
'.right-to-left #demo-settings-toggler {',
' padding-left: 10px;',
' padding-right: 0;',
' left: auto;',
' right: -40px;',
'}',
'.right-to-left #demo-settings .demo-checkbox {',
' right: auto;',
' left: 20px;',
'}'
];
var demo_template = [
'<div id="demo-settings">',
' <a href="#" id="demo-settings-toggler" class="fa fa-cogs"></a>',
' <h5 class="header">SETTINGS</h5>',
' <div>',
' <ul id="demo-settings-list">',
' <li class="clearfix">',
' <span>Fixed navbar</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-fixed-navbar" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.fixed_navbar) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Fixed main menu</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-fixed-menu" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.fixed_menu) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Right-to-left direction</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-rtl" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.rtl) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Main menu on the right</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-menu-rigth" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.menu_right) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Hide main menu</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-no-menu" class="demo-settings-switcher" data-class="switcher-sm"></div>',
' </li>',
' </ul>',
' </div>',
' <h5 class="header">THEMES</h5>',
' <div id="demo-themes">',
getThemesTemplate(),
' </div>',
'</div>'
];
// Initialize
//
window.addEventListener("load", function () {
activateTheme($('#main-menu .btn-outline'));
$('head').append($('<style>\n' + demo_styles.join('\n') + '\n</style>'));
$('body').append($(demo_template.join('\n')));
// Activate theme
$('#demo-themes .demo-theme[data-theme="' + demo_settings.theme + '"]').addClass('active');
// Add callbacks
//
// Initialize switchers
$('.demo-settings-switcher').switcher({
theme: 'square',
on_state_content: '<span class="fa fa-check" style="font-size:11px;"></span>',
off_state_content: '<span class="fa fa-times" style="font-size:11px;"></span>'
});
// Demo panel toggle
$('#demo-settings-toggler').click(function () {
$('#demo-settings').toggleClass('open');
return false;
});
// Toggle switchers on label click
$('#demo-settings-list li > span').click(function () {
$(this).parents('li').find('.switcher').click();
});
// Fix/unfix main navbar
$('#demo-fixed-navbar').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
var uncheck_menu_chk = (! $(this).is(':checked') && $('#demo-fixed-menu').is(':checked')) ? true : false;
demo_settings.fixed_navbar = $(this).is(':checked');
if (uncheck_menu_chk) {
$('#demo-fixed-menu').switcher('off');
} else {
saveDemoSettings();
reloadPage();
}
});
// Fix/unfix main menu
$('#demo-fixed-menu').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
var check_navbar_chk = ($(this).is(':checked') && ! $('#demo-fixed-navbar').is(':checked')) ? true : false;
demo_settings.fixed_menu = $(this).is(':checked');
if (check_navbar_chk) {
$('#demo-fixed-navbar').switcher('on');
} else {
saveDemoSettings();
reloadPage();
}
});
// RTL
$('#demo-rtl').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
demo_settings.rtl = $(this).is(':checked');
saveDemoSettings();
reloadPage();
});
// Fix/unfix main menu
$('#demo-menu-rigth').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
demo_settings.menu_right = $(this).is(':checked');
saveDemoSettings();
reloadPage();
});
// Hide/show main menu
$('#demo-no-menu').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
if ($(this).is(':checked')) {
$('body').addClass('no-main-menu');
} else {
$('body').removeClass('no-main-menu');
}
});
// Change theme
$('#demo-themes .demo-theme').on('click', function () {
if ($(this).hasClass('active')) return;
$('#demo-themes .active').removeClass('active');
$(this).addClass('active');
demo_settings.theme = $(this).attr('data-theme');
saveDemoSettings();
activateTheme($('#main-menu .btn-outline'));
return false;
});
// Custom menu content demo
//
$('#menu-content-demo .close').click(function () {
var $p = $(this).parents('.menu-content');
$p.addClass('fadeOut');
setTimeout(function () {
$p.css({ height: $p.outerHeight(), overflow: 'hidden' }).animate({'padding-top': 0, height: $('#main-navbar').outerHeight()}, 500, function () {
$p.remove();
});
}, 300);
return false;
});
});
})();
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// paths is just a variable for common storage during the build and templating process
paths: {
src: 'src', // source directory for content
dest: 'dest', // final document root, symlink this into htdocs
build: 'build', // build directory for all the tooling to build the content
}
});
// Load Grunt plugins.
grunt.loadTasks( 'build/grunt' );
grunt.registerTask(
'css',
[
'less',
'postcss',
'cssmin',
]
);
grunt.registerTask(
'html',
[
'concat',
]
);
grunt.registerTask(
'default',
[
'css',
'html',
]
)
};
|
/* !
This is the setup script to register all demo related AccDC Object declarations.
This file is only parsed when the Live Demo tab is opened from the left navigation links.
*/
// Configure the AccDC Objects for the demo on the Live Demo tab
// Keyboard Accessible Drag and Drop
// Bind a click handler to the Convert button
$A.bind('input.morphBtn', 'click', function(ev){
// Configure the Keyboard accessible drag and drop sample by morphing all planet images into draggable AccDC Objects
$A.query('div.dndContainer ul li > img', function(i, obj){
// Set the mcDemo AccDC Object as the parent
$A.morph($A.reg.mcDemo, obj,
{
// Dynamically generate a unique ID
id: 'list' + i,
// Use the alt attribute value of the image to set the role (to be used later for keyboard accessibility)
role: $A.getAttr(obj, 'alt'),
// Prevent hidden boundary information from being displayed to screen reader users
showHiddenBounds: false,
// Prevent the object from being closable from the keyboard.
showHiddenClose: false,
// Set initial visual styling
cssObj:
{
position: 'absolute',
zIndex: 3
},
// Make the object draggable
isDraggable: true,
// Set temporary variables for tracking
inUniverse: true,
dropped: false,
// Store object to prevent same - side drop triggering
currentZone: null,
// Run script after rendering completes
runAfter: function(dc){
// Set additional styling for the drag links to allow for color contrast differences
dc.accDD.dragLinkStyle =
{
color: 'white',
backgroundColor: 'black',
border: 'solid thin white'
};
// CSS to reset positioning
dc.clearCSS =
{
zIndex: 3,
top: '',
left: '',
height: '',
width: ''
};
// Save references to the relevant list objects to prevent unnecessary queries later
var lists = $A.query('div.dndContainer ul, div.dndContainer ol');
// Set initial drag and drop options
dc.dropTarget = 'div.subDivR';
// Limit dragging to the bounds of a specific container
dc.drag.confineTo = 'div.dndContainer';
// Enable keyboard accessibility for the drag and drop action
dc.accDD.on = true;
// Set the drop animation duration in milliseconds
dc.accDD.duration = 3000;
// Set a point to return keyboard focus to after dragging has begun to ensure keyboard accessibility
dc.accDD.returnFocusTo = 'div.subDivL ul';
// Configure the drag / drop event handlers
dc.onDragStart = function(ev, dd, dc){
dc.css('z-index', 4);
dc.originalXY =
{
top: dd.originalY,
left: dd.originalX
};
};
dc.onDrop = function(ev, dd, dc){
if (dc.currentZone != this){
dc.currentZone = this;
dc.dropped = true;
var tmp = dc.dropTarget;
// Remove old drag and drop bindings
dc.unsetDrag();
// Clear drag styling
dc.css(dc.clearCSS);
if (dc.inUniverse){
dc.inUniverse = false;
dc.dropTarget = 'div.subDivL';
dc.accDD.returnFocusTo = 'div.subDivR ol';
// Move the dragged element into the galaxy list
lists[1].appendChild(dc.accDCObj.parentNode);
}
else{
dc.inUniverse = true;
dc.dropTarget = 'div.subDivR';
dc.accDD.returnFocusTo = 'div.subDivL ul';
// Move the dragged element into the Universe list
lists[0].appendChild(dc.accDCObj.parentNode);
}
// Now set drag and drop bindings with the newly configured options
dc.setDrag();
}
};
dc.onDragEnd = function(ev, dd, dc){
// Check if a valid drop has occurred, and move back to the starting point if not
if (!dc.dropped)
dropIntoTheSun(dc);
dc.dropped = false;
};
// Now set initial event bindings
dc.setDrag();
// Expand parent li tag to account for position absolute
$A.css(dc.accDCObj.parentNode,
{
height: dc.accDCObj.offsetHeight,
width: dc.accDCObj.offsetWidth
});
dc.accDCObj.parentNode.appendChild($A.createEl('div', null,
{
clear: 'both'
}, null, document.createTextNode(' ')));
}
});
});
// Make the sun a draggable AccDC Object as well
var sunImg = $A.query('div.dndContainer img.sun')[0];
$A.morph($A.reg.mcDemo, sunImg,
{
id: 'sun',
role: 'Sun',
showHiddenBounds: false,
showHiddenClose: false,
isDraggable: true,
drag:
{
confineTo: 'div.dndContainer'
},
cssObj:
{
position: 'absolute',
// Copy the current coordinates for the image
left: $A.xOffset(sunImg).left,
top: $A.xOffset(sunImg).top,
// Set the depth
zIndex: 2
}
});
// Change the status message and announce it to screen reader users
$A.announce($A.getEl('morphI').innerHTML = 'Converted all images into draggable AccDC Objects');
ev.preventDefault();
});
function dropIntoTheSun(dc){
var sun = firstChild($A.reg.sun.containerDiv, 'img'), planet = firstChild(dc.containerDiv, 'img'),
additional = sun.offsetHeight / 2, sunOS = $A.xOffset(sun);
// Move planet to the sun
transition(dc.accDCObj,
{
top: sunOS.top + additional,
left: sunOS.left + additional
},
{
duration: 3000,
complete: function(cb){
// Fall into the sun
transition(dc.accDCObj,
{
height: 0,
width: 0,
transform: 360
},
{
duration: 2000,
step: function(cb){
// cb contains cb.top and cb.left to match the wrapper, so sync the image to this at runtime
$A.css(planet, cb);
},
complete: function(cb){
// Stick the planet behind the sun and resize it, including both the wrapper and the image
$A.css(
[
dc.accDCObj,
planet
],
{
zIndex: 1,
height: '20px',
width: '20px'
});
// Move the planet back to its original position
transition(dc.accDCObj, dc.originalXY,
{
duration: 3000,
complete: function(cb){
// Bring the planet to the front once again
$A.css(dc.accDCObj, 'z-index', 4);
// Zoom the planet back into focus
transition(dc.accDCObj,
{
height: 75,
width: 75,
transform: 0
},
{
duration: 2000,
step: function(cb){
$A.css(planet, cb);
},
complete: function(cb){
// Now clear css !
dc.css(dc.clearCSS);
}
});
}
});
}
});
}
});
}
|
/* */
"format cjs";
import runTransitionHook from './runTransitionHook'
function useBasename(createHistory) {
return function (options={}) {
let { basename, ...historyOptions } = options
let history = createHistory(historyOptions)
function addBasename(location) {
if (basename && location.basename == null) {
if (location.pathname.indexOf(basename) === 0) {
location.pathname = location.pathname.substring(basename.length)
location.basename = basename
if (location.pathname === '')
location.pathname = '/'
} else {
location.basename = ''
}
}
return location
}
function prependBasename(path) {
return basename ? basename + path : path
}
// Override all read methods with basename-aware versions.
function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
runTransitionHook(hook, addBasename(location), callback)
})
}
function listen(listener) {
return history.listen(function (location) {
listener(addBasename(location))
})
}
// Override all write methods with basename-aware versions.
function pushState(state, path) {
history.pushState(state, prependBasename(path))
}
function replaceState(state, path) {
history.replaceState(state, prependBasename(path))
}
function createPath(path) {
return history.createPath(prependBasename(path))
}
function createHref(path) {
return history.createHref(prependBasename(path))
}
function createLocation() {
return addBasename(history.createLocation.apply(history, arguments))
}
return {
...history,
listenBefore,
listen,
pushState,
replaceState,
createPath,
createHref,
createLocation
}
}
}
export default useBasename
|
Function.prototype.bind = Function.prototype.bind || bind
require("./test")
require("./stream")
function bind(context) {
var f = this
return function () {
f.apply(context, arguments)
}
}
|
var expect = require('expect.js');
var queue = require('../queue');
describe('queue', function () {
it('queue.next queue.prev queue.start', function(){
queue({
step: 0
})
.next(function(next){
expect(this.step++).to.be(1);
next();
})
.prev(function(next){
expect(++this.step).to.be(1);
next();
})
.start(function(){
expect(this.step).to.be(2);
});
});
it('queue.start', function(){
var num = 0;
queue().next(function(next){
expect(num).to.be(0);
next();
}).start();
queue().next(function(next){
expect(num).to.be(1);
next();
}).start(true);
num++;
});
it('queue.proxy queue.clone', function(){
queue({
step: 0
})
.proxy(function(that){
expect(this).to.eql(that);
that.next(function(next){
expect(this.step++).to.be(1);
next();
});
})
.proxy(function(that){
expect(this).to.not.eql(that);
that.prev(function(next){
expect(++this.step).to.be(1);
next();
})
}, "x")
.start(true, function(){
expect(this.step).to.be(2);
})
.clone({step:0}, function(){
expect(this.step).to.be(2);
})
.start();
});
});
|
const rowAt = (text, charNo) => {
let sub = text.substr(0, charNo)
let rows = sub.split('\n')
return rows.length
}
export default rowAt
|
import { Party, Search, Summary } from '../src/data/models';
export default async function updateSearch() {
console.log('Summary syncing');
await Summary.sync();
console.log('Party updating aggregate data');
await Party.updateAggregateData();
console.log('Search syncing');
await Search.sync();
console.log('Search refreshing view');
await Search.refreshView();
}
|
import $ from 'jquery';
import { sprintf, __ } from '~/locale';
import flash from '~/flash';
import * as rootTypes from '../../mutation_types';
import { createCommitPayload, createNewMergeRequestUrl } from '../../utils';
import router from '../../../ide_router';
import service from '../../../services';
import * as types from './mutation_types';
import consts from './constants';
import { activityBarViews } from '../../../constants';
import eventHub from '../../../eventhub';
export const updateCommitMessage = ({ commit }, message) => {
commit(types.UPDATE_COMMIT_MESSAGE, message);
};
export const discardDraft = ({ commit }) => {
commit(types.UPDATE_COMMIT_MESSAGE, '');
};
export const updateCommitAction = ({ commit, getters }, commitAction) => {
commit(types.UPDATE_COMMIT_ACTION, {
commitAction,
});
commit(types.TOGGLE_SHOULD_CREATE_MR, !getters.shouldHideNewMrOption);
};
export const toggleShouldCreateMR = ({ commit }) => {
commit(types.TOGGLE_SHOULD_CREATE_MR);
};
export const updateBranchName = ({ commit }, branchName) => {
commit(types.UPDATE_NEW_BRANCH_NAME, branchName);
};
export const setLastCommitMessage = ({ commit, rootGetters }, data) => {
const { currentProject } = rootGetters;
const commitStats = data.stats
? sprintf(__('with %{additions} additions, %{deletions} deletions.'), {
additions: data.stats.additions,
deletions: data.stats.deletions,
})
: '';
const commitMsg = sprintf(
__('Your changes have been committed. Commit %{commitId} %{commitStats}'),
{
commitId: `<a href="${currentProject.web_url}/commit/${data.short_id}" class="commit-sha">${data.short_id}</a>`,
commitStats,
},
false,
);
commit(rootTypes.SET_LAST_COMMIT_MSG, commitMsg, { root: true });
};
export const updateFilesAfterCommit = ({ commit, dispatch, rootState, rootGetters }, { data }) => {
const selectedProject = rootGetters.currentProject;
const lastCommit = {
commit_path: `${selectedProject.web_url}/commit/${data.id}`,
commit: {
id: data.id,
message: data.message,
authored_date: data.committed_date,
author_name: data.committer_name,
},
};
commit(
rootTypes.SET_BRANCH_WORKING_REFERENCE,
{
projectId: rootState.currentProjectId,
branchId: rootState.currentBranchId,
reference: data.id,
},
{ root: true },
);
rootState.stagedFiles.forEach(file => {
const changedFile = rootState.changedFiles.find(f => f.path === file.path);
commit(
rootTypes.UPDATE_FILE_AFTER_COMMIT,
{
file,
lastCommit,
},
{ root: true },
);
commit(
rootTypes.TOGGLE_FILE_CHANGED,
{
file,
changed: false,
},
{ root: true },
);
dispatch('updateTempFlagForEntry', { file, tempFile: false }, { root: true });
eventHub.$emit(`editor.update.model.content.${file.key}`, {
content: file.content,
changed: Boolean(changedFile),
});
});
};
export const commitChanges = ({ commit, state, getters, dispatch, rootState, rootGetters }) => {
const newBranch = state.commitAction !== consts.COMMIT_TO_CURRENT_BRANCH;
const stageFilesPromise = rootState.stagedFiles.length
? Promise.resolve()
: dispatch('stageAllChanges', null, { root: true });
commit(types.UPDATE_LOADING, true);
return stageFilesPromise
.then(() => {
const payload = createCommitPayload({
branch: getters.branchName,
newBranch,
getters,
state,
rootState,
rootGetters,
});
return service.commit(rootState.currentProjectId, payload);
})
.then(({ data }) => {
commit(types.UPDATE_LOADING, false);
if (!data.short_id) {
flash(data.message, 'alert', document, null, false, true);
return null;
}
if (!data.parent_ids.length) {
commit(
rootTypes.TOGGLE_EMPTY_STATE,
{
projectPath: rootState.currentProjectId,
value: false,
},
{ root: true },
);
}
dispatch('setLastCommitMessage', data);
dispatch('updateCommitMessage', '');
return dispatch('updateFilesAfterCommit', {
data,
branch: getters.branchName,
})
.then(() => {
commit(rootTypes.CLEAR_STAGED_CHANGES, null, { root: true });
setTimeout(() => {
commit(rootTypes.SET_LAST_COMMIT_MSG, '', { root: true });
}, 5000);
if (state.shouldCreateMR) {
const { currentProject } = rootGetters;
const targetBranch = getters.isCreatingNewBranch
? rootState.currentBranchId
: currentProject.default_branch;
dispatch(
'redirectToUrl',
createNewMergeRequestUrl(currentProject.web_url, getters.branchName, targetBranch),
{ root: true },
);
}
})
.then(() => {
if (rootGetters.lastOpenedFile) {
dispatch(
'openPendingTab',
{
file: rootGetters.lastOpenedFile,
},
{ root: true },
)
.then(changeViewer => {
if (changeViewer) {
dispatch('updateViewer', 'diff', { root: true });
}
})
.catch(e => {
throw e;
});
} else {
dispatch('updateActivityBarView', activityBarViews.edit, { root: true });
dispatch('updateViewer', 'editor', { root: true });
if (rootGetters.activeFile) {
router.push(
`/project/${rootState.currentProjectId}/blob/${getters.branchName}/-/${rootGetters.activeFile.path}`,
);
}
}
})
.then(() => dispatch('updateCommitAction', consts.COMMIT_TO_CURRENT_BRANCH))
.then(() =>
dispatch(
'refreshLastCommitData',
{
projectId: rootState.currentProjectId,
branchId: rootState.currentBranchId,
},
{ root: true },
),
);
})
.catch(err => {
if (err.response.status === 400) {
$('#ide-create-branch-modal').modal('show');
} else {
dispatch(
'setErrorMessage',
{
text: __('An error occurred whilst committing your changes.'),
action: () =>
dispatch('commitChanges').then(() =>
dispatch('setErrorMessage', null, { root: true }),
),
actionText: __('Please try again'),
},
{ root: true },
);
window.dispatchEvent(new Event('resize'));
}
commit(types.UPDATE_LOADING, false);
});
};
// prevent babel-plugin-rewire from generating an invalid default during karma tests
export default () => {};
|
describe('rs.popover.Registry', function () {
'use strict';
var registry;
beforeEach(module('rs.popover'));
beforeEach(inject(function (_registry_) {
registry = _registry_;
}));
describe('register', function () {
it('raises exception for empty ID', function () {
expect(function () {
registry.register('', {});
}).toThrow('Popover ID must not be empty!');
});
it('raises exception for non-unique ID', function () {
registry.register('unique', {});
expect(function () {
registry.register('unique');
}).toThrow('Popover ID "unique" has already been registered!');
});
});
describe('popover', function () {
it('returns registered popover', function () {
var controller;
controller = {};
registry.register('mypopover', controller);
expect(registry.popover('mypopover')).toBe(controller);
});
it('raises exception for unregistered popover', function () {
expect(function () {
registry.popover('unregistered');
}).toThrow('Popover ID "unregistered" has not been registered!');
});
});
});
|
import Icon from '../components/Icon.vue'
Icon.register({"pencil-square-o":{"width":1792,"height":1792,"paths":[{"d":"M888 1184l116-116-152-152-116 116v56h96v96h56zM1328 464q-16-16-33 1l-350 350q-17 17-1 33t33-1l350-350q17-17 1-33zM1408 1058v190q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q63 0 117 25 15 7 18 23 3 17-9 29l-49 49q-14 14-32 8-23-6-45-6h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-126q0-13 9-22l64-64q15-15 35-7t20 29zM1312 320l288 288-672 672h-288v-288zM1756 452l-92 92-288-288 92-92q28-28 68-28t68 28l152 152q28 28 28 68t-28 68z"}]}})
|
const { send } = require('./utils/event-logger');
const { spawnStream, getPath } = require('./utils/helpers');
const events = {
lifeCycleBegin: 'format.lifeCycle.begin',
lifeCycleEnd: 'format.lifeCycle.end',
formatCommandFail: 'format.format.command.fail',
checkCommandFail: 'format.check.command.fail',
};
const format = async workingDir => {
send(events.lifeCycleBegin);
await runPrettier(true, workingDir);
send(events.lifeCycleEnd);
};
const check = async workingDir => {
send(events.lifeCycleBegin);
await runPrettier(false, workingDir);
send(events.lifeCycleEnd);
};
const runPrettier = async (isWrite, workingDir) => {
const writeOrCheck = isWrite ? '--write' : '--list-different';
const files = "'{src,test,lib,electron}/**/*.{js,jsx,ts,tsx,css}' '*.js'";
const configOption = `--config ${getPath(
`@jakedeichert/create-app/lib/env-configs/prettier-common/prettier.config.js`
)}`;
return spawnStream(
getPath('prettier/bin-prettier.js'),
[writeOrCheck, configOption, files],
{
stdio: 'inherit',
cwd: workingDir,
}
).catch(isWrite ? formatCommandFail : checkCommandFail);
};
const formatCommandFail = err => {
send(events.formatCommandFail, { err });
throw err;
};
const checkCommandFail = err => {
send(events.checkCommandFail, { err });
throw err;
};
module.exports = {
events,
format,
check,
};
|
import PostAbstractHelpers from './post-abstract';
import mobiledocRenderers from 'mobiledoc-kit/renderers/mobiledoc';
import MobiledocRenderer_0_2, { MOBILEDOC_VERSION as MOBILEDOC_VERSION_0_2 } from 'mobiledoc-kit/renderers/mobiledoc/0-2';
import MobiledocRenderer_0_3, { MOBILEDOC_VERSION as MOBILEDOC_VERSION_0_3 } from 'mobiledoc-kit/renderers/mobiledoc/0-3';
import Editor from 'mobiledoc-kit/editor/editor';
import { mergeWithOptions } from 'mobiledoc-kit/utils/merge';
/*
* usage:
* build(({post, section, marker, markup}) =>
* post([
* section('P', [
* marker('some text', [markup('B')])
* ])
* })
* )
*/
function build(treeFn, version) {
let post = PostAbstractHelpers.build(treeFn);
switch (version) {
case MOBILEDOC_VERSION_0_2:
return MobiledocRenderer_0_2.render(post);
case MOBILEDOC_VERSION_0_3:
return MobiledocRenderer_0_3.render(post);
case undefined:
case null:
return mobiledocRenderers.render(post);
default:
throw new Error(`Unknown version of mobiledoc renderer requested: ${version}`);
}
}
function renderInto(element, treeFn, editorOptions={}) {
let mobiledoc = build(treeFn);
mergeWithOptions(editorOptions, {mobiledoc});
let editor = new Editor(editorOptions);
editor.render(element);
return editor;
}
export default {
build,
renderInto
};
|
search_result['272']=["topic_0000000000000082.html","ChatService.GenerateJwtToken Method",""];
|
//
// jquery.xmlns.js: xml-namespace selector support for jQuery
//
// This plugin modifies the jQuery tag and attribute selectors to
// support optional namespace specifiers as defined in CSS 3:
//
// $("elem") - matches 'elem' nodes in the default namespace
// $("|elem") - matches 'elem' nodes that don't have a namespace
// $("NS|elem") - matches 'elem' nodes in declared namespace 'NS'
// $("*|elem") - matches 'elem' nodes in any namespace
// $("NS|*") - matches any nodes in declared namespace 'NS'
//
// A similar synax is also supported for attribute selectors, but note
// that the default namespace does *not* apply to attributes - a missing
// or empty namespace selector selects only attributes with no namespace.
//
// In a slight break from the W3C standards, and with a nod to ease of
// implementation, the empty namespace URI is treated as equivalent to
// an unspecified namespace. Plenty of browsers seem to make the same
// assumption...
//
// Namespace declarations live in the $.xmlns object, which is a simple
// mapping from namespace ids to namespace URIs. The default namespace
// is determined by the value associated with the empty string.
//
// $.xmlns.D = "DAV:"
// $.xmlns.FOO = "http://www.foo.com/xmlns/foobar"
// $.xmlns[""] = "http://www.example.com/new/default/namespace/"
//
// Unfortunately this is a global setting - I can't find a way to do
// query-object-specific namespaces since the jQuery selector machinery
// is stateless. However, you can use the 'xmlns' function to push and
// pop namespace delcarations with ease:
//
// $().xmlns({D:"DAV:"}) // pushes the DAV: namespace
// $().xmlns("DAV:") // makes DAV: the default namespace
// $().xmlns(false) // pops the namespace we just pushed
// $().xmlns(false) // pops again, returning to defaults
//
// To execute this as a kind of "transaction", pass a function as the
// second argument. It will be executed in the context of the current
// jQuery object:
//
// $().xmlns("DAV:",function() {
// // The default namespace is DAV: within this function,
// // but it is reset to the previous value on exit.
// return this.find("response").each(...);
// }).find("div")
//
// If you pass a string as a function, it will be executed against the
// current jQuery object using find(); i.e. the following will find all
// "href" elements in the "DAV:" namespace:
//
// $().xmlns("DAV:","href")
//
//
// And finally, the legal stuff:
//
// Copyright (c) 2009, Ryan Kelly.
// TAG and ATTR functions derived from jQuery's selector.js.
// Dual licensed under the MIT and GPL licenses.
// http://docs.jquery.com/License
//
(function($) {
// Some common default namespaces, that are treated specially by browsers.
//
var default_xmlns = {
"xml": "http://www.w3.org/XML/1998/namespace",
"xmlns": "http://www.w3.org/2000/xmlns/",
"html": "http://www.w3.org/1999/xhtml/"
};
// A reverse mapping for common namespace prefixes.
//
var default_xmlns_rev = {}
for(var k in default_xmlns) {
default_xmlns_rev[default_xmlns[k]] = k;
}
// $.xmlns is a mapping from namespace identifiers to namespace URIs.
// The default default-namespace is "*", and we provide some additional
// defaults that are specified in the XML Namespaces standard.
//
$.extend({xmlns: $.extend({},default_xmlns,{"":"*"})});
// jQuery method to push/pop namespace declarations.
//
// If a single argument is specified:
// * if it's a mapping, push those namespaces onto the stack
// * if it's a string, push that as the default namespace
// * if it evaluates to false, pop the latest namespace
//
// If two arguments are specified, the second is executed "transactionally"
// using the namespace declarations found in the first. It can be either a
// a selector string (in which case it is passed to this.find()) or a function
// (in which case it is called in the context of the current jQuery object).
// The given namespace mapping is automatically pushed before executing and
// popped afterwards.
//
var xmlns_stack = [];
$.fn.extend({xmlns: function(nsmap,func) {
if(typeof nsmap == "string") {
nsmap = {"":nsmap};
}
if(nsmap) {
xmlns_stack.push($.xmlns);
$.xmlns = $.extend({},$.xmlns,nsmap);
if(func !== undefined) {
if(typeof func == "string") {
return this.find(func).xmlns(undefined)
} else {
var self = this;
try {
self = func.call(this);
if(!self) {
self = this;
}
} finally {
self.xmlns(undefined);
}
return self
}
} else {
return this;
}
} else {
$.xmlns = (xmlns_stack ? xmlns_stack.pop() : {});
return this;
}
}});
// Convert a namespace prefix into a namespace URI, based
// on the delcarations made in $.xmlns.
//
var getNamespaceURI = function(id) {
// No namespace id, use the default.
if(!id) {
return $.xmlns[""];
}
// Strip the pipe character from the specifier
id = id.substr(0,id.length-1);
// Certain special namespaces aren't mapped to a URI
if(id == "" || id == "*") {
return id;
}
var ns = $.xmlns[id];
if(typeof(ns) == "undefined") {
throw "Syntax error, undefined namespace prefix '" + id + "'";
}
return ns;
};
// Update the regex used by $.expr to parse selector components for a
// particular type of selector (e.g. "TAG" or "ATTR").
//
// This logic is taken straight from the jQuery/Sizzle sources.
//
var setExprMatchRegex = function(type,regex) {
$.expr.match[type] = new RegExp(regex.source + /(?![^\[]*\])(?![^\(]*\))/.source);
if($.expr.leftMatch) {
$.expr.leftMatch[type] = new RegExp(/(^(?:.|\r|\n)*?)/.source + $.expr.match[type].source.replace(/\\(\d+)/g, function(all, num){
return "\\" + (num - 0 + 1);
}));
}
}
// Modify the TAG match regexp to include optional namespace selector.
// This is basically (namespace|)?(tagname).
//
setExprMatchRegex("TAG",/^((?:((?:[\w\u00c0-\uFFFF\*_-]*\|)?)((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)))/);
// Perform some capability-testing.
//
var div = document.createElement("div");
// Sometimes getElementsByTagName("*") will return comment nodes,
// which we will have to remove from the results.
//
var gebtn_yields_comments = false;
div.appendChild(document.createComment(""));
if(div.getElementsByTagName("*").length > 0) {
gebtn_yields_comments = true;
}
// Some browsers return node.localName in upper case, some in lower case.
//
var localname_is_uppercase = true;
if(div.localName && div.localName == "div") {
localname_is_uppercase = false;
}
// Allow the testing div to be garbage-collected.
//
div = null;
// Modify the TAG find function to account for a namespace selector.
//
$.expr.find.TAG = function(match,context,isXML) {
var ns = getNamespaceURI(match[2]);
var ln = match[3];
var res;
if(typeof context.getElementsByTagNameNS != "undefined") {
// Easy case - we have getElementsByTagNameNS
res = context.getElementsByTagNameNS(ns,ln);
} else if(typeof context.selectNodes != "undefined") {
// Use xpath if possible (not available on HTML DOM nodes in IE)
if(context.ownerDocument) {
context.ownerDocument.setProperty("SelectionLanguage","XPath");
} else {
context.setProperty("SelectionLanguage","XPath");
}
var predicate = "";
if(ns != "*") {
if(ln != "*") {
predicate="namespace-uri()='"+ns+"' and local-name()='"+ln+"'";
} else {
predicate="namespace-uri()='"+ns+"'";
}
} else {
if(ln != "*") {
predicate="local-name()='"+ln+"'";
}
}
if(predicate) {
res = context.selectNodes("descendant-or-self::*["+predicate+"]");
} else {
res = context.selectNodes("descendant-or-self::*");
}
} else {
// Otherwise, we need to simulate using getElementsByTagName
res = context.getElementsByTagName(ln);
if(gebtn_yields_comments && ln == "*") {
var tmp = [];
for(var i=0; res[i]; i++) {
if(res[i].nodeType == 1) {
tmp.push(res[i]);
}
}
res = tmp;
}
if(res && ns != "*") {
var tmp = [];
for(var i=0; res[i]; i++) {
if(res[i].namespaceURI == ns || res[i].tagUrn == ns) {
tmp.push(res[i]);
}
}
res = tmp;
}
}
return res;
};
// Check whether a node is part of an XML document.
// Copied verbatim from jQuery sources, needed in TAG preFilter below.
//
var isXML = function(elem){
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML";
};
// Modify the TAG preFilter function to work with modified match regexp.
// This normalises case of the tag name if we're in a HTML document.
//
$.expr.preFilter.TAG = function(match, curLoop, inplace, result, not, isXML) {
var ln = match[3];
if(!isXML) {
if(localname_is_uppercase) {
ln = ln.toUpperCase();
} else {
ln = ln.toLowerCase();
}
}
return [match[0],getNamespaceURI(match[2]),ln];
};
// Modify the TAG filter function to account for a namespace selector.
//
$.expr.filter.TAG = function(elem,match) {
var ns = match[1];
var ln = match[2];
var e_ns = elem.namespaceURI ? elem.namespaceURI : elem.tagUrn;
var e_ln = elem.localName ? elem.localName : elem.tagName;
if(ns == "*" || e_ns == ns || (ns == "" && !e_ns)) {
return ((ln == "*" && elem.nodeType == 1) || e_ln == ln);
}
return false;
};
// Modify the ATTR match regexp to extract a namespace selector.
// This is basically ([namespace|])(attrname)(op)(quote)(pattern)(quote)
//
setExprMatchRegex("ATTR",/\[\s*((?:((?:[\w\u00c0-\uFFFF\*_-]*\|)?)((?:[\w\u00c0-\uFFFF_-]|\\.)+)))\s*(?:(\S?=)\s*(['"]*)(.*?)\5|)\s*\]/);
// Modify the ATTR preFilter function to account for new regexp match groups,
// and normalise the namespace URI.
//
$.expr.preFilter.ATTR = function(match, curLoop, inplace, result, not, isXML) {
var name = match[3].replace(/\\/g, "");
if(!isXML && $.expr.attrMap[name]) {
match[3] = $.expr.attrMap[name];
}
if( match[4] == "~=" ) {
match[6] = " " + match[6] + " ";
}
if(!match[2] || match[2] == "|") {
match[2] = "";
} else {
match[2] = getNamespaceURI(match[2]);
}
return match;
};
// Modify the ATTR filter function to account for namespace selector.
// Unfortunately this means factoring out the attribute-checking code
// into a separate function, since it might be called multiple times.
//
var filter_attr = function(result,type,check) {
var value = result + "";
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value != check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0,check.length+1)===check+"-" :
false;
}
$.expr.filter.ATTR = function(elem, match) {
var ns = match[2];
var name = match[3];
var type = match[4];
var check = match[6];
var result;
// No namespace, just use ordinary attribute lookup.
if(ns == "") {
result = $.expr.attrHandle[name] ?
$.expr.attrHandle[name](elem) :
elem[name] != null ?
elem[name] :
elem.getAttribute(name);
return filter_attr(result,type,check);
}
// Directly use getAttributeNS if applicable and available
if(ns != "*" && typeof elem.getAttributeNS != "undefined") {
return filter_attr(elem.getAttributeNS(ns,name),type,check);
}
// Need to iterate over all attributes, either because we couldn't
// look it up or because we need to match all namespaces.
var attrs = elem.attributes;
for(var i=0; attrs[i]; i++) {
var ln = attrs[i].localName;
if(!ln) {
ln = attrs[i].nodeName
var idx = ln.indexOf(":");
if(idx >= 0) {
ln = ln.substr(idx+1);
}
}
if(ln == name) {
result = attrs[i].nodeValue;
if(ns == "*" || attrs[i].namespaceURI == ns) {
if(filter_attr(result,type,check)) {
return true;
}
}
if(attrs[i].namespaceURI === "" && attrs[i].prefix) {
if(attrs[i].prefix == default_xmlns_rev[ns]) {
if(filter_attr(result,type,check)) {
return true;
}
}
}
}
}
return false;
};
})(jQuery);
|
var encryption = require('../utilities/encryption');
var User = require('mongoose').model('User');
var Comment = require('mongoose').model('Comment');
module.exports = {
createUser: function(req, res, next) {
var newUserData = req.body;
newUserData.salt = encryption.generateSalt();
newUserData.hashPass = encryption.generateHashedPassword(newUserData.salt, newUserData.password);
User.create(newUserData, function(err, user) {
if (err) {
console.log('Failed to register new user: ' + err);
return;
}
req.logIn(user, function(err) {
if (err) {
res.status(400);
return res.send({reason: err.toString()});
};
res.redirect('/home');
})
});
},
updateUser: function(req, res, next) {
if (req.user._id == req.body._id || req.user.roles.indexOf('admin') > -1) {
var updatedUserData = req.body;
if (updatedUserData.password && updatedUserData.password.length > 0) {
updatedUserData.salt = encryption.generateSalt();
updatedUserData.hashPass = encryption.generateHashedPassword(newUserData.salt, newUserData.password);
}
User.update({_id: req.body._id}, updatedUserData, function() {
res.end();
})
}
else {
res.send({reason: 'You do not have permissions!'})
}
},
getAllUsers: function(req, res) {
User.find({}).exec(function(err, allUsers) {
if (err) {
console.log('Users could not be loaded: ' + err);
}
res.render('users/user-panel', {
title: 'Admin user panel',
user: req.user,
users: allUsers
});
})
},
deleteUser: function(req, res) {
console.log(req.body.userId);
User.findById(req.body.userId, function(err, user) {
if (err) {
console.log('Could not find user by id');
res.end();
return;
}
if (user == null) {
res.end();
return;
}
user.remove(function(err) {
if (err) {
console.log('Could not delete user');
res.end();
return;
}
res.end();
});
});
},
getUserDetails: function(req, res){
var data = {};
User.findById(req.params.id, function(err, user){
if (err) {
console.log('Could not find user by id');
res.end();
return;
}
if (user == null) {
res.end();
return;
}
console.log(user);
data.user = user;
Comment.find({userId: req.params.id}, function(err, comments){
if (err)
{
throw err;
}
data.comments = comments;
//console.log(comments);
res.render("users/user-details", data);
})
});
}
};
|
/** @babel */
import season from 'season'
import dedent from 'dedent'
import electron from 'electron'
import fs from 'fs-plus'
import path from 'path'
import AtomApplication from '../../src/main-process/atom-application'
import parseCommandLine from '../../src/main-process/parse-command-line'
import {timeoutPromise, conditionPromise} from '../async-spec-helpers'
const ATOM_RESOURCE_PATH = path.resolve(__dirname, '..', '..')
describe('AtomApplication', function () {
this.timeout(60 * 1000)
let originalAppQuit, originalAtomHome, atomApplicationsToDestroy
beforeEach(function () {
originalAppQuit = electron.app.quit
mockElectronAppQuit()
originalAtomHome = process.env.ATOM_HOME
process.env.ATOM_HOME = makeTempDir('atom-home')
// Symlinking the compile cache into the temporary home dir makes the windows load much faster
fs.symlinkSync(path.join(originalAtomHome, 'compile-cache'), path.join(process.env.ATOM_HOME, 'compile-cache'), 'junction')
season.writeFileSync(path.join(process.env.ATOM_HOME, 'config.cson'), {
'*': {
welcome: {showOnStartup: false},
core: {telemetryConsent: 'no'}
}
})
atomApplicationsToDestroy = []
})
afterEach(async function () {
process.env.ATOM_HOME = originalAtomHome
for (let atomApplication of atomApplicationsToDestroy) {
await atomApplication.destroy()
}
await clearElectronSession()
electron.app.quit = originalAppQuit
})
describe('launch', function () {
it('can open to a specific line number of a file', async function () {
const filePath = path.join(makeTempDir(), 'new-file')
fs.writeFileSync(filePath, '1\n2\n3\n4\n')
const atomApplication = buildAtomApplication()
const window = atomApplication.launch(parseCommandLine([filePath + ':3']))
await focusWindow(window)
const cursorRow = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (textEditor) {
if (textEditor) sendBackToMainProcess(textEditor.getCursorBufferPosition().row)
})
})
assert.equal(cursorRow, 2)
})
it('can open to a specific line and column of a file', async function () {
const filePath = path.join(makeTempDir(), 'new-file')
fs.writeFileSync(filePath, '1\n2\n3\n4\n')
const atomApplication = buildAtomApplication()
const window = atomApplication.launch(parseCommandLine([filePath + ':2:2']))
await focusWindow(window)
const cursorPosition = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (textEditor) {
if (textEditor) sendBackToMainProcess(textEditor.getCursorBufferPosition())
})
})
assert.deepEqual(cursorPosition, {row: 1, column: 1})
})
it('removes all trailing whitespace and colons from the specified path', async function () {
let filePath = path.join(makeTempDir(), 'new-file')
fs.writeFileSync(filePath, '1\n2\n3\n4\n')
const atomApplication = buildAtomApplication()
const window = atomApplication.launch(parseCommandLine([filePath + ':: ']))
await focusWindow(window)
const openedPath = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (textEditor) {
if (textEditor) sendBackToMainProcess(textEditor.getPath())
})
})
assert.equal(openedPath, filePath)
})
if (process.platform === 'darwin' || process.platform === 'win32') {
it('positions new windows at an offset distance from the previous window', async function () {
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([makeTempDir()]))
await focusWindow(window1)
window1.browserWindow.setBounds({width: 400, height: 400, x: 0, y: 0})
const window2 = atomApplication.launch(parseCommandLine([makeTempDir()]))
await focusWindow(window2)
assert.notEqual(window1, window2)
const window1Dimensions = window1.getDimensions()
const window2Dimensions = window2.getDimensions()
assert.isAbove(window2Dimensions.x, window1Dimensions.x)
assert.isAbove(window2Dimensions.y, window1Dimensions.y)
})
}
it('reuses existing windows when opening paths, but not directories', async function () {
const dirAPath = makeTempDir("a")
const dirBPath = makeTempDir("b")
const dirCPath = makeTempDir("c")
const existingDirCFilePath = path.join(dirCPath, 'existing-file')
fs.writeFileSync(existingDirCFilePath, 'this is an existing file')
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([path.join(dirAPath, 'new-file')]))
await focusWindow(window1)
let activeEditorPath
activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (textEditor) {
if (textEditor) sendBackToMainProcess(textEditor.getPath())
})
})
assert.equal(activeEditorPath, path.join(dirAPath, 'new-file'))
// Reuses the window when opening *files*, even if they're in a different directory
// Does not change the project paths when doing so.
const reusedWindow = atomApplication.launch(parseCommandLine([existingDirCFilePath]))
assert.equal(reusedWindow, window1)
assert.deepEqual(atomApplication.windows, [window1])
activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
sendBackToMainProcess(textEditor.getPath())
})
})
assert.equal(activeEditorPath, existingDirCFilePath)
assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath])
// Opens new windows when opening directories
const window2 = atomApplication.launch(parseCommandLine([dirCPath]))
assert.notEqual(window2, window1)
await focusWindow(window2)
assert.deepEqual(await getTreeViewRootDirectories(window2), [dirCPath])
})
it('adds folders to existing windows when the --add option is used', async function () {
const dirAPath = makeTempDir("a")
const dirBPath = makeTempDir("b")
const dirCPath = makeTempDir("c")
const existingDirCFilePath = path.join(dirCPath, 'existing-file')
fs.writeFileSync(existingDirCFilePath, 'this is an existing file')
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([path.join(dirAPath, 'new-file')]))
await focusWindow(window1)
let activeEditorPath
activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (textEditor) {
if (textEditor) sendBackToMainProcess(textEditor.getPath())
})
})
assert.equal(activeEditorPath, path.join(dirAPath, 'new-file'))
// When opening *files* with --add, reuses an existing window and adds
// parent directory to the project
let reusedWindow = atomApplication.launch(parseCommandLine([existingDirCFilePath, '--add']))
assert.equal(reusedWindow, window1)
assert.deepEqual(atomApplication.windows, [window1])
activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
sendBackToMainProcess(textEditor.getPath())
})
})
assert.equal(activeEditorPath, existingDirCFilePath)
assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath, dirCPath])
// When opening *directories* with add reuses an existing window and adds
// the directory to the project
reusedWindow = atomApplication.launch(parseCommandLine([dirBPath, '-a']))
assert.equal(reusedWindow, window1)
assert.deepEqual(atomApplication.windows, [window1])
await conditionPromise(async () => (await getTreeViewRootDirectories(reusedWindow)).length === 3)
assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath, dirCPath, dirBPath])
})
it('persists window state based on the project directories', async function () {
const tempDirPath = makeTempDir()
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([path.join(tempDirPath, 'new-file')]))
await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (textEditor) {
if (textEditor) {
textEditor.insertText('Hello World!')
sendBackToMainProcess(null)
}
})
})
window1.close()
await window1.closedPromise
const window2 = atomApplication.launch(parseCommandLine([path.join(tempDirPath)]))
const window2Text = await evalInWebContents(window2.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (textEditor) {
if (textEditor) sendBackToMainProcess(textEditor.getText())
})
})
assert.equal(window2Text, 'Hello World!')
})
it('shows all directories in the tree view when multiple directory paths are passed to Atom', async function () {
const dirAPath = makeTempDir("a")
const dirBPath = makeTempDir("b")
const dirBSubdirPath = path.join(dirBPath, 'c')
fs.mkdirSync(dirBSubdirPath)
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([dirAPath, dirBPath]))
await focusWindow(window1)
await timeoutPromise(1000)
let treeViewPaths = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
sendBackToMainProcess(
Array
.from(document.querySelectorAll('.tree-view .project-root > .header .name'))
.map(element => element.dataset.path)
)
})
assert.deepEqual(treeViewPaths, [dirAPath, dirBPath])
})
it('reuses windows with no project paths to open directories', async function () {
const tempDirPath = makeTempDir()
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([]))
await focusWindow(window1)
const reusedWindow = atomApplication.launch(parseCommandLine([tempDirPath]))
assert.equal(reusedWindow, window1)
await conditionPromise(async () => (await getTreeViewRootDirectories(reusedWindow)).length > 0)
})
it('opens a new window with a single untitled buffer when launched with no path, even if windows already exist', async function () {
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([]))
await focusWindow(window1)
const window1EditorTitle = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
sendBackToMainProcess(atom.workspace.getActiveTextEditor().getTitle())
})
assert.equal(window1EditorTitle, 'untitled')
const window2 = atomApplication.launch(parseCommandLine([]))
await focusWindow(window2)
const window2EditorTitle = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
sendBackToMainProcess(atom.workspace.getActiveTextEditor().getTitle())
})
assert.equal(window2EditorTitle, 'untitled')
assert.deepEqual(atomApplication.windows, [window1, window2])
})
it('does not open an empty editor when opened with no path if the core.openEmptyEditorOnStart config setting is false', async function () {
const configPath = path.join(process.env.ATOM_HOME, 'config.cson')
const config = season.readFileSync(configPath)
if (!config['*'].core) config['*'].core = {}
config['*'].core.openEmptyEditorOnStart = false
season.writeFileSync(configPath, config)
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([]))
await focusWindow(window1)
// wait a bit just to make sure we don't pass due to querying the render process before it loads
await timeoutPromise(1000)
const itemCount = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
sendBackToMainProcess(atom.workspace.getActivePane().getItems().length)
})
assert.equal(itemCount, 0)
})
it('opens an empty text editor and loads its parent directory in the tree-view when launched with a new file path', async function () {
const atomApplication = buildAtomApplication()
const newFilePath = path.join(makeTempDir(), 'new-file')
const window = atomApplication.launch(parseCommandLine([newFilePath]))
await focusWindow(window)
const {editorTitle, editorText} = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
atom.workspace.observeActivePaneItem(function (editor) {
if (editor) sendBackToMainProcess({editorTitle: editor.getTitle(), editorText: editor.getText()})
})
})
assert.equal(editorTitle, path.basename(newFilePath))
assert.equal(editorText, '')
assert.deepEqual(await getTreeViewRootDirectories(window), [path.dirname(newFilePath)])
})
it('adds a remote directory to the project when launched with a remote directory', async function () {
const packagePath = path.join(__dirname, '..', 'fixtures', 'packages', 'package-with-directory-provider')
const packagesDirPath = path.join(process.env.ATOM_HOME, 'packages')
fs.mkdirSync(packagesDirPath)
fs.symlinkSync(packagePath, path.join(packagesDirPath, 'package-with-directory-provider'), 'junction')
const atomApplication = buildAtomApplication()
atomApplication.config.set('core.disabledPackages', ['fuzzy-finder'])
const remotePath = 'remote://server:3437/some/directory/path'
let window = atomApplication.launch(parseCommandLine([remotePath]))
await focusWindow(window)
await conditionPromise(async () => (await getProjectDirectories()).length > 0)
let directories = await getProjectDirectories()
assert.deepEqual(directories, [{type: 'FakeRemoteDirectory', path: remotePath}])
await window.reload()
await focusWindow(window)
directories = await getProjectDirectories()
assert.deepEqual(directories, [{type: 'FakeRemoteDirectory', path: remotePath}])
function getProjectDirectories () {
return evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
sendBackToMainProcess(atom.project.getDirectories().map(d => ({ type: d.constructor.name, path: d.getPath() })))
})
}
})
it('reopens any previously opened windows when launched with no path', async function () {
const tempDirPath1 = makeTempDir()
const tempDirPath2 = makeTempDir()
const atomApplication1 = buildAtomApplication()
const app1Window1 = atomApplication1.launch(parseCommandLine([tempDirPath1]))
await app1Window1.loadedPromise
const app1Window2 = atomApplication1.launch(parseCommandLine([tempDirPath2]))
await app1Window2.loadedPromise
await app1Window1.saveState()
await app1Window2.saveState()
const atomApplication2 = buildAtomApplication()
const [app2Window1, app2Window2] = atomApplication2.launch(parseCommandLine([]))
await app2Window1.loadedPromise
await app2Window2.loadedPromise
assert.deepEqual(await getTreeViewRootDirectories(app2Window1), [tempDirPath1])
assert.deepEqual(await getTreeViewRootDirectories(app2Window2), [tempDirPath2])
})
it('does not reopen any previously opened windows when launched with no path and `core.restorePreviousWindowsOnStart` is false', async function () {
const atomApplication1 = buildAtomApplication()
const app1Window1 = atomApplication1.launch(parseCommandLine([makeTempDir()]))
await focusWindow(app1Window1)
const app1Window2 = atomApplication1.launch(parseCommandLine([makeTempDir()]))
await focusWindow(app1Window2)
const configPath = path.join(process.env.ATOM_HOME, 'config.cson')
const config = season.readFileSync(configPath)
if (!config['*'].core) config['*'].core = {}
config['*'].core.restorePreviousWindowsOnStart = false
season.writeFileSync(configPath, config)
const atomApplication2 = buildAtomApplication()
const app2Window = atomApplication2.launch(parseCommandLine([]))
await focusWindow(app2Window)
assert.deepEqual(await getTreeViewRootDirectories(app2Window), [])
})
describe('when closing the last window', function () {
if (process.platform === 'linux' || process.platform === 'win32') {
it('quits the application', async function () {
const atomApplication = buildAtomApplication()
const window = atomApplication.launch(parseCommandLine([path.join(makeTempDir("a"), 'file-a')]))
await focusWindow(window)
window.close()
await window.closedPromise
assert(electron.app.hasQuitted())
})
} else if (process.platform === 'darwin') {
it('leaves the application open', async function () {
const atomApplication = buildAtomApplication()
const window = atomApplication.launch(parseCommandLine([path.join(makeTempDir("a"), 'file-a')]))
await focusWindow(window)
window.close()
await window.closedPromise
assert(!electron.app.hasQuitted())
})
}
})
describe('when adding or removing project folders', function () {
it('stores the window state immediately', async function () {
const dirA = makeTempDir()
const dirB = makeTempDir()
const atomApplication = buildAtomApplication()
const window = atomApplication.launch(parseCommandLine([dirA, dirB]))
await focusWindow(window)
assert.deepEqual(await getTreeViewRootDirectories(window), [dirA, dirB])
await evalInWebContents(window.browserWindow.webContents, (sendBackToMainProcess) => {
atom.project.removePath(atom.project.getPaths()[0])
sendBackToMainProcess(null)
})
assert.deepEqual(await getTreeViewRootDirectories(window), [dirB])
// Window state should be saved when the project folder is removed
const atomApplication2 = buildAtomApplication()
const [window2] = atomApplication2.launch(parseCommandLine([]))
await focusWindow(window2)
assert.deepEqual(await getTreeViewRootDirectories(window2), [dirB])
})
})
})
describe('before quitting', function () {
it('waits until all the windows have saved their state and then quits', async function () {
const dirAPath = makeTempDir("a")
const dirBPath = makeTempDir("b")
const atomApplication = buildAtomApplication()
const window1 = atomApplication.launch(parseCommandLine([path.join(dirAPath, 'file-a')]))
await focusWindow(window1)
const window2 = atomApplication.launch(parseCommandLine([path.join(dirBPath, 'file-b')]))
await focusWindow(window2)
electron.app.quit()
assert(!electron.app.hasQuitted())
await Promise.all([window1.lastSaveStatePromise, window2.lastSaveStatePromise])
assert(electron.app.hasQuitted())
})
})
function buildAtomApplication () {
const atomApplication = new AtomApplication({
resourcePath: ATOM_RESOURCE_PATH,
atomHomeDirPath: process.env.ATOM_HOME
})
atomApplicationsToDestroy.push(atomApplication)
return atomApplication
}
async function focusWindow (window) {
window.focus()
await window.loadedPromise
await conditionPromise(() => window.atomApplication.lastFocusedWindow === window)
}
function mockElectronAppQuit () {
let quitted = false
electron.app.quit = function () {
let shouldQuit = true
electron.app.emit('before-quit', {preventDefault: () => { shouldQuit = false }})
if (shouldQuit) {
quitted = true
}
}
electron.app.hasQuitted = function () {
return quitted
}
}
function makeTempDir (name) {
return fs.realpathSync(require('temp').mkdirSync(name))
}
let channelIdCounter = 0
function evalInWebContents (webContents, source) {
const channelId = 'eval-result-' + channelIdCounter++
return new Promise(function (resolve) {
electron.ipcMain.on(channelId, receiveResult)
function receiveResult (event, result) {
electron.ipcMain.removeListener('eval-result', receiveResult)
resolve(result)
}
webContents.executeJavaScript(dedent`
function sendBackToMainProcess (result) {
require('electron').ipcRenderer.send('${channelId}', result)
}
(${source})(sendBackToMainProcess)
`)
})
}
function getTreeViewRootDirectories (atomWindow) {
return evalInWebContents(atomWindow.browserWindow.webContents, function (sendBackToMainProcess) {
sendBackToMainProcess(
Array
.from(document.querySelectorAll('.tree-view .project-root > .header .name'))
.map(element => element.dataset.path)
)
})
}
function clearElectronSession () {
return new Promise(function (resolve) {
electron.session.defaultSession.clearStorageData(function () {
// Resolve promise on next tick, otherwise the process stalls. This
// might be a bug in Electron, but it's probably fixed on the newer
// versions.
process.nextTick(resolve)
})
})
}
})
|
// import { fromJS } from 'immutable';
// import { makeSelectAuthContainerDomain } from '../selectors';
// const selector = makeSelectAuthContainerDomain();
describe('makeSelectAuthContainerDomain', () => {
it('Expect to have unit tests specified', () => {
expect(true).toEqual(false);
});
});
|
"use strict";
var shell = require('shelljs');
shell.cd('../moviespider');
shell.exec('/usr/local/bin/scrapy crawl cili006');
shell.exec('/usr/local/bin/scrapy crawl dytt8');
shell.exec('/usr/local/bin/scrapy crawl w6vhao');
shell.exec('/usr/local/bin/scrapy crawl dytt8proc');
shell.exec('/usr/local/bin/scrapy crawl w6vhaoproc');
shell.cd('../movieproc');
shell.exec('/root/.nvm/versions/node/v5.1.0/bin/node bin/movieproc.js');
|
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"1":"8","2":"C D e K I N J"},C:{"1":"0 1 2 3 4 5 7 9 L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB","2":"gB BB aB ZB","33":"F"},D:{"1":"0 1 2 3 4 5 7 8 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB"},E:{"1":"4 6 F L H G E A B C D UB VB WB XB YB p bB","2":"SB KB"},F:{"1":"0 1 2 3 5 7 K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z","2":"E B C cB dB eB fB p AB hB","132":"6"},G:{"2":"G D KB iB FB kB lB MB nB oB pB qB rB sB tB uB vB"},H:{"2":"wB"},I:{"1":"O","2":"BB F xB yB zB 0B FB 1B 2B"},J:{"2":"H A"},K:{"1":"M","2":"6 A B C p AB"},L:{"1":"LB"},M:{"1":"O"},N:{"2":"A B"},O:{"1":"3B"},P:{"1":"4B 5B 6B 7B 8B","2":"F"},Q:{"1":"9B"},R:{"1":"AC"},S:{"2":"BC"}},B:4,C:"CSS resize property"};
|
exports.index = function (req, res) {
var data = {};
res.render('index', data);
};
exports.help = function (req, res) {
var data = {
title: ['Help'],
path: 'help'
};
res.render('help', data);
};
exports.code = function (req, res) {
var data = {
title: ['Code'],
path: 'code'
};
res.render('code', data);
};
|
process.env.NODE_ENV = 'development';
const opn = require('opn');
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const proxyMiddleware = require('http-proxy-middleware');
const webpackConfig = require('./conf/webpack.dev.conf');
const appConf = require('./conf/app.conf');
const utils = require('./utils');
const port = process.env.PORT || appConf.devPort;
const autoOpenBrowser = true;
const proxyTable = appConf.proxyTable;
const app = express();
const compiler = webpack(webpackConfig);
const uri = 'http://localhost:' + port;
utils.checkLoaderEnable(webpackConfig, 'eslintEnable', 'eslint-loader');
utils.checkLoaderEnable(webpackConfig, 'babelEnable', 'babel-loader');
const devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
});
const hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {}
});
compiler.plugin('compilation', function(compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function(data, cb) {
hotMiddleware.publish({ action: 'reload' });
cb();
});
});
// proxy api requests
if (proxyTable) {
Object.keys(proxyTable).forEach(function(context) {
let options = proxyTable[context];
if (typeof options === 'string') {
options = { target: options };
}
app.use(proxyMiddleware(options.filter || context, options));
});
}
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')());
// serve webpack bundle output
app.use(devMiddleware);
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware);
// serve pure static assets
let staticPath = path.posix.join(appConf.assetsPublicPath, appConf.assetsSubDirectory);
app.use(staticPath, express.static('./static'));
devMiddleware.waitUntilValid(function() {
console.info('>>> Listening at ' + uri + '\n');
});
module.exports = app.listen(port, function(err) {
if (err) {
console.error(err);
return;
}
// when env is testing, don't need open it
if (autoOpenBrowser) {
opn(uri);
}
});
|
/*
* jQuery Mobile Framework : "mouse" plugin
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
(function($, window, document, undefined) {
var dataPropertyName = "virtualMouseBindings",
touchTargetPropertyName = "virtualTouchID",
virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split(" "),
touchEventProps = "clientX clientY pageX pageY screenX screenY".split(" "),
activeDocHandlers = {},
resetTimerID = 0,
startX = 0,
startY = 0,
didScroll = false,
clickBlockList = [],
blockMouseTriggers = false,
blockTouchTriggers = false,
eventCaptureSupported = $.support.eventCapture,
$document = $(document),
nextTouchID = 1,
lastTouchID = 0;
$.vmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent(event) {
while (event && typeof event.originalEvent !== "undefined") {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent(event, eventType) {
var t = event.type,
oe, props, ne, prop, ct, touch, i, j;
event = $.Event(event);
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if (oe) {
for (i = props.length,prop; i;) {
prop = props[ --i ];
event[ prop ] = oe[ prop ];
}
}
if (t.search(/^touch/) !== -1) {
ne = getNativeEvent(oe);
t = ne.touches;
ct = ne.changedTouches;
touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined );
if (touch) {
for (j = 0,len = touchEventProps.length; j < len; j++) {
prop = touchEventProps[ j ];
event[ prop ] = touch[ prop ];
}
}
}
return event;
}
function getVirtualBindingFlags(element) {
var flags = {},
b, k;
while (element) {
b = $.data(element, dataPropertyName);
for (k in b) {
if (b[ k ]) {
flags[ k ] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding(element, eventType) {
var b;
while (element) {
b = $.data(element, dataPropertyName);
if (b && ( !eventType || b[ eventType ] )) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout(function() {
resetTimerID = 0;
enableMouseBindings();
}, $.vmouse.resetTimerDuration);
}
function clearResetTimer() {
if (resetTimerID) {
clearTimeout(resetTimerID);
resetTimerID = 0;
}
}
function triggerVirtualEvent(eventType, event, flags) {
var ve;
if (( flags && flags[ eventType ] ) ||
( !flags && getClosestElementWithVirtualBinding(event.target, eventType) )) {
ve = createVirtualEvent(event, eventType);
$(event.target).trigger(ve);
}
return ve;
}
function mouseEventCallback(event) {
var touchID = $.data(event.target, touchTargetPropertyName);
if (!blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID )) {
var ve = triggerVirtualEvent("v" + event.type, event);
if (ve) {
if (ve.isDefaultPrevented()) {
event.preventDefault();
}
if (ve.isPropagationStopped()) {
event.stopPropagation();
}
if (ve.isImmediatePropagationStopped()) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart(event) {
var touches = getNativeEvent(event).touches,
target, flags;
if (touches && touches.length === 1) {
target = event.target;
flags = getVirtualBindingFlags(target);
if (flags.hasVirtualBinding) {
lastTouchID = nextTouchID++;
$.data(target, touchTargetPropertyName, lastTouchID);
clearResetTimer();
disableMouseBindings();
didScroll = false;
var t = getNativeEvent(event).touches[ 0 ];
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent("vmouseover", event, flags);
triggerVirtualEvent("vmousedown", event, flags);
}
}
}
function handleScroll(event) {
if (blockTouchTriggers) {
return;
}
if (!didScroll) {
triggerVirtualEvent("vmousecancel", event, getVirtualBindingFlags(event.target));
}
didScroll = true;
startResetTimer();
}
function handleTouchMove(event) {
if (blockTouchTriggers) {
return;
}
var t = getNativeEvent(event).touches[ 0 ],
didCancel = didScroll,
moveThreshold = $.vmouse.moveDistanceThreshold;
didScroll = didScroll ||
( Math.abs(t.pageX - startX) > moveThreshold ||
Math.abs(t.pageY - startY) > moveThreshold ),
flags = getVirtualBindingFlags(event.target);
if (didScroll && !didCancel) {
triggerVirtualEvent("vmousecancel", event, flags);
}
triggerVirtualEvent("vmousemove", event, flags);
startResetTimer();
}
function handleTouchEnd(event) {
if (blockTouchTriggers) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags(event.target),
t;
triggerVirtualEvent("vmouseup", event, flags);
if (!didScroll) {
var ve = triggerVirtualEvent("vclick", event, flags);
if (ve && ve.isDefaultPrevented()) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
t = getNativeEvent(event).changedTouches[ 0 ];
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent("vmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings(ele) {
var bindings = $.data(ele, dataPropertyName),
k;
if (bindings) {
for (k in bindings) {
if (bindings[ k ]) {
return true;
}
}
}
return false;
}
function dummyMouseHandler() {
}
function getSpecialEventObject(eventType) {
var realType = eventType.substr(1);
return {
setup: function(data, namespace) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if (!hasVirtualBindings(this)) {
$.data(this, dataPropertyName, {});
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data(this, dataPropertyName);
bindings[ eventType ] = true;
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
if (activeDocHandlers[ eventType ] === 1) {
$document.bind(realType, mouseEventCallback);
}
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$(this).bind(realType, dummyMouseHandler);
// For now, if event capture is not supported, we rely on mouse handlers.
if (eventCaptureSupported) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
if (activeDocHandlers[ "touchstart" ] === 1) {
$document.bind("touchstart", handleTouchStart)
.bind("touchend", handleTouchEnd)
// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
.bind("touchmove", handleTouchMove)
.bind("scroll", handleScroll);
}
}
},
teardown: function(data, namespace) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[ eventType ];
if (!activeDocHandlers[ eventType ]) {
$document.unbind(realType, mouseEventCallback);
}
if (eventCaptureSupported) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[ "touchstart" ];
if (!activeDocHandlers[ "touchstart" ]) {
$document.unbind("touchstart", handleTouchStart)
.unbind("touchmove", handleTouchMove)
.unbind("touchend", handleTouchEnd)
.unbind("scroll", handleScroll);
}
}
var $this = $(this),
bindings = $.data(this, dataPropertyName);
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if (bindings) {
bindings[ eventType ] = false;
}
// Unregister the dummy event handler.
$this.unbind(realType, dummyMouseHandler);
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if (!hasVirtualBindings(this)) {
$this.removeData(dataPropertyName);
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for (var i = 0; i < virtualEventNames.length; i++) {
$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject(virtualEventNames[ i ]);
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if (eventCaptureSupported) {
document.addEventListener("click", function(e) {
var cnt = clickBlockList.length,
target = e.target,
x, y, ele, i, o, touchID;
if (cnt) {
x = e.clientX;
y = e.clientY;
threshold = $.vmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// vclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the vclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while (ele) {
for (i = 0; i < cnt; i++) {
o = clickBlockList[ i ];
touchID = 0;
if (( ele === target && Math.abs(o.x - x) < threshold && Math.abs(o.y - y) < threshold ) ||
$.data(ele, touchTargetPropertyName) === o.touchID) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
})(jQuery, window, document);
|
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 把 kebab case 字符串转换成 camel case
*/
/**
* 把 kebab case 字符串转换成 camel case
*
* @param {string} source 源字符串
* @return {string}
*/
function kebab2camel(source) {
return source.replace(/-+(.)/ig, function (match, alpha) {
return alpha.toUpperCase();
});
}
exports = module.exports = kebab2camel;
|
import React from 'react';
import { Router as ReactRouter, Route, IndexRoute, browserHistory } from 'react-router';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import UrlSearchParams from 'main/components/UrlSearchParams';
import Layout from 'main/components/Layout';
import MembersView from 'members';
import Login from 'login';
import * as authActions from 'auth/actions';
const mapDispatchToProps = dispatch => {
return bindActionCreators(authActions, dispatch)
}
class Router extends React.Component {
constructor(props) {
super(props);
}
requireLogin(nextState, replaceState) {
if(!this.props.store.getState().auth.token) {
browserHistory.push('#/login');
}
}
requireLogout(nextState, replaceState) {
if(this.props.store.getState().auth.token) {
browserHistory.push('#/members');
}
}
componentWillMount()
{
let currentLocation = this.props.location;
if(currentLocation.hash)
{
let queryParams = UrlSearchParams(currentLocation.search);
let username = queryParams.get('username');
let token = queryParams.get('token');
if (this.props.store.getState().auth.token) {
browserHistory.push(currentLocation.hash);
}
else if(username && token)
{
this.props.setAuthToken(token, username);
browserHistory.push(currentLocation.hash);
}
else {
browserHistory.push('#/login');
}
}
}
render() {
return (
<ReactRouter history={this.props.history}>
<Route path="/" component={Layout}>
<IndexRoute component={Login} onEnter={this.requireLogout.bind(this)} />
<Route path='login' component={Login} onEnter={this.requireLogout.bind(this)} />
<Route path='members' component={MembersView} onEnter={this.requireLogin.bind(this)} />
</Route>
</ReactRouter>
);
}
}
export default connect(null, mapDispatchToProps)(Router);
|
export const AppComponent = {
template: `
<div class="app-wrapper">
<navbar></navbar>
<ui-view class="app-content"></ui-view>
<app-footer></app-footer>
</div>
`
}
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Memorize_IntentionAction = /** @class */ (function (_super) {
__extends(Memorize_IntentionAction, _super);
function Memorize_IntentionAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
Memorize_IntentionAction.prototype.canHandle = function (intention, ai) {
if (intention.functor.is_a(ai.o.getSort("action.memorize")))
return true;
return false;
};
Memorize_IntentionAction.prototype.execute = function (ir, ai) {
this.ir = ir;
var intention = ir.action;
var requester = ir.requester;
// execute the memorize action:
console.log(ai.selfID + " memorize: " + intention.attributes[2]);
// we add the sentence with positive sign, to see if it introduces a contradiction
var s_l = Term.termToSentences((intention.attributes[2]).term, ai.o);
console.log("term to sentences (#sentences = " + s_l.length + "): " + s_l);
var variablesPresent = false;
var timeModifierPresent = false;
// 1) see if it has variables AND is more than one sentence:
for (var _i = 0, s_l_1 = s_l; _i < s_l_1.length; _i++) {
var s = s_l_1[_i];
if (s.getAllVariables().length > 0)
variablesPresent = true;
for (var _a = 0, _b = s.terms; _a < _b.length; _a++) {
var t = _b[_a];
if (t.functor.is_a(ai.o.getSort("time.past")))
timeModifierPresent = true;
if (t.functor.is_a(ai.o.getSort("time.future")))
timeModifierPresent = true;
}
}
if (timeModifierPresent) {
console.warn("time modifiers present, not memorizing for now...");
var tmp = "action.talk('" + ai.selfID + "'[#id], perf.ack.unsure(" + requester + "))";
var term = Term.fromString(tmp, ai.o);
ai.intentions.push(new IntentionRecord(term, null, null, null, ai.timeStamp));
ir.succeeded = true;
return true;
}
// check for the special case where the player is stating that they "know/remember" something, so we follow up
// asking about it:
if (variablesPresent && s_l[0].terms.length == 1 && s_l[0].sign[0]) {
var term = s_l[0].terms[0];
if (term.functor.is_a(ai.o.getSort("verb.know")) &&
term.attributes.length == 2 &&
term.attributes[0] instanceof ConstantTermAttribute &&
term.attributes[1] instanceof TermTermAttribute &&
requester instanceof ConstantTermAttribute) {
var term2 = term.attributes[1].term;
if (term.attributes[0].value == requester.value &&
term2.functor.is_a(ai.o.getSort("property-with-value")) &&
term2.attributes.length == 2 &&
term2.attributes[0] instanceof ConstantTermAttribute &&
term2.attributes[1] instanceof VariableTermAttribute) {
// ask the requester about it, no need to memorize this yet:
var queryTerm = new Term(ai.o.getSort("perf.q.query"), [requester, term2.attributes[1], term.attributes[1]]);
var actionTerm = Term.fromString("action.talk('" + ai.selfID + "'[#id], " + queryTerm + ")", ai.o);
ai.intentions.push(new IntentionRecord(actionTerm, null, null, null, ai.timeStamp));
ir.succeeded = true;
return true;
}
}
}
if (s_l.length > 1 && variablesPresent) {
// Note: I added this case earlier in the development of the game, but I cannot figure out what case was it covering,
// so, I removed it as I cannot find any sentence for which this is needed.
// this is the complicated case, we can just launch an inference process to see if we need to memorize or we already knew
// console.log("executeIntention memorize: sentence of length > 1 with variables, this is a complex case, we need to try to negate the sentences: " + s_l);
// let negated_s_l:Sentence[] = [];
// let negated_s:Sentence = new Sentence([],[]);
// for(let s of s_l) {
// if (s.getAllVariables().length > 0) variablesPresent = true;
// for(let t of s.terms) {
// if (t.functor.is_a(ai.o.getSort("time.past"))) timeModifierPresent = true;
// if (t.functor.is_a(ai.o.getSort("time.future"))) timeModifierPresent = true;
// }
// let tmp:Sentence[] = s.negate();
// if (tmp == null || tmp.length != 1) {
// console.error("executeIntention memorize: cannot negate sentences in intention!: " + intention);
// let tmp:string = "action.talk('"+ai.selfID+"'[#id], perf.ack.unsure("+requester+"))";
// let term:Term = Term.fromString(tmp, ai.o);
// ai.intentions.push(new IntentionRecord(term, null, null, null, ai.timeStamp));
// return true;
// }
// negated_s.terms = negated_s.terms.concat(tmp[0].terms);
// negated_s.sign = negated_s.sign.concat(tmp[0].sign);
// }
// negated_s_l = [negated_s];
// ai.queuedInferenceProcesses.push(new InferenceRecord(ai, [], [negated_s_l], 1, 0, false, null, new Memorize_InferenceEffect(intention, true)));
// Alternative code with better negation:
// let targets:Sentence[][] = [];
// let negatedExpression:Term = new Term(ai.o.getSort("#not"),
// [new TermTermAttribute((<TermTermAttribute>(intention.attributes[2])).term)])
// console.log("Memorize, negatedExpression: " + negatedExpression);
// let target:Sentence[] = Term.termToSentences(negatedExpression, ai.o);
// targets.push(target)
// ai.queuedInferenceProcesses.push(new InferenceRecord(ai, [], targets, 1, 0, false, null, new Memorize_InferenceEffect(intention, true)));
ai.queuedInferenceProcesses.push(new InferenceRecord(ai, [], [s_l], 1, 0, false, null, new Memorize_InferenceEffect(intention, false)));
}
else {
if (s_l.length == 1 && s_l[0].terms.length == 1) {
// Check for the special case, where the player is just correcting a wrong statement she stated in the past:
var negatedToMemorize = new Sentence(s_l[0].terms, [!s_l[0].sign[0]]);
var se = ai.longTermMemory.findSentenceEntry(negatedToMemorize);
if (se != null && se.provenance == MEMORIZE_PROVENANCE) {
console.log("Correcting a wrong statement she stated in the past! checking if this would cause a contradiction");
// We can safely remove the "negatedToMemorize" sentence, since, if the new one causes a contradiction, it means it was already
// implied by the KB, so it wasn't needed. But if it does not, then we had to remove it anyway:
ai.longTermMemory.removeSentence(negatedToMemorize);
}
}
console.log("executeIntention memorize: sentence list of length 1, easy case: " + s_l);
ai.queuedInferenceProcesses.push(new InferenceRecord(ai, [], [s_l], 1, 0, false, null, new Memorize_InferenceEffect(intention, false)));
}
ir.succeeded = true;
return true;
};
Memorize_IntentionAction.prototype.saveToXML = function (ai) {
return "<IntentionAction type=\"Memorize_IntentionAction\"/>";
};
Memorize_IntentionAction.loadFromXML = function (xml, ai) {
return new Memorize_IntentionAction();
};
return Memorize_IntentionAction;
}(IntentionAction));
|
import Chart from './chart';
import { Decorators } from 'francy-core';
/* global d3 */
export default class BarChart extends Chart {
constructor({ appendTo, callbackHandler }, context) {
super({ appendTo: appendTo, callbackHandler: callbackHandler }, context);
}
@Decorators.Initializer.initialize()
async render() {
this.xScale = d3.scaleBand().range([0, this.width]).padding(0.1).domain(this.axis.x.domain);
if (!this.axis.x.domain.length) {
this.axis.x.domain = Chart.domainRange(this.allValues.length / this.datasetNames.length);
this.xScale.domain(this.axis.x.domain);
}
let barsGroup = this.element.selectAll('g.francy-bars');
if (!barsGroup.node()) {
barsGroup = this.element.append('g').attr('class', 'francy-bars');
}
var self = this;
this.datasetNames.forEach(function (key, index) {
let bar = barsGroup.selectAll(`.francy-bar-${index}`).data(self.datasets[key]);
bar.exit().transition().duration(750)
.style('fill-opacity', 1e-6)
.remove();
// append the rectangles for the bar chart
let barEnter = bar.enter()
.append('rect')
.style('fill', () => Chart.colors(index * 5))
.attr('class', `francy-bar-${index}`)
.attr('x', function (d, i) {
return self.xScale(self.axis.x.domain[i]) + index * (self.xScale.bandwidth() / self.datasetNames.length);
})
.attr('width', (self.xScale.bandwidth() / self.datasetNames.length) - 1)
.attr('y', function (d) {
return self.yScale(d);
})
.attr('height', function (d) {
return self.height - self.yScale(d);
})
.on('mouseenter', function (d) {
d3.select(this).transition()
.duration(250).style('fill-opacity', 0.5);
self.handlePromise(self.tooltip.load(Chart.tooltip(key, d), true).render());
})
.on('mouseleave', function () {
d3.select(this).transition()
.duration(250).style('fill-opacity', 1);
self.tooltip.unrender();
});
barEnter.merge(bar)
.attr('x', function (d, i) {
return self.xScale(self.axis.x.domain[i]) + index * (self.xScale.bandwidth() / self.datasetNames.length);
})
.attr('width', (self.xScale.bandwidth() / self.datasetNames.length) - 1)
.attr('y', function (d) {
return self.yScale(d);
})
.attr('height', function (d) {
return self.height - self.yScale(d);
});
});
this._renderAxis();
this._renderLegend();
return this;
}
}
|
Accounts.config({
"restrictCreationByEmailDomain": Meteor.settings.public.restrictedDomain
});
Accounts.onCreateUser(function(options, user) {
user.inGame = false;
if(options.profile) {
user.profile = options.profile;
}
return user;
});
Meteor.publish("adminInfo", function() {
if(!Roles.userIsInRole(this.userId, "admin")) {
this.ready();
}
return [
Meteor.users.find({}, {
fields: {
"alive": 1,
"inGame": 1,
"kills": 1,
"assassin": 1,
"target": 1,
"profile.name": 1
}
}),
Actions.find()
];
});
Meteor.publish("target", function() {
return Meteor.users.find(this.userId, {
fields: {
"target": 1
}
});
});
Meteor.publish("userList", function() {
return Meteor.users.find({"inGame": true}, {
fields: {
"alive": 1,
"inGame": 1,
"kills": 1,
"profile.name": 1
}
});
});
Meteor.publish("actions", function() {
return Actions.find();
});
Meteor.publish("posts", function() {
return Posts.find();
});
|
var nodemailer = require('nodemailer');
var express = require('express');
var router = express.Router();
var helper = require('sendgrid').mail;
var publicationemail = require('../app/models/publicationemail');
var user = require('../app/models/user');
var coaching = require('../app/models/coaching');
var subscriber = require('../app/models/subscriber');
var sendGridCredential = require('../app/models/sendGridCredential');
router.get('/', function(req, res) {
publicationemail
.find({ })
.exec(function (err, docs) {
if (!err){
res.json(docs);
} else {throw err;}
});
});
router.post('/publications', function(req, res) {
var thisEmail = req.body;
//console.log(thisEmail);
var templateName = thisEmail.templateName;
var from = thisEmail.from;
var sender = thisEmail.sender;
if(sender){
//console.log(sender);
var result = sender.split(" ");
//console.log(result);
sender = result[0] + " from Exambazaar";
}else{
sender = "Ayush from Exambazaar";
}
var senderId = thisEmail.senderId;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
var to = thisEmail.to;
var subject = thisEmail.subject;
var publication = thisEmail.publication;
var contactName = thisEmail.contact.name;
var contactMobile = thisEmail.contact.mobile;
if(!subject || subject == ''){
subject = '[Press Release] Story coverage of Exambazaar (IIT-IIM alumni Jaipur based startup)';
}
var html = thisEmail.html;
if(!html){
html = ' ';
}
//console.log("To: " + to + " Subject: " + subject + " from: " + from);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
var to_email2 = new helper.Email('gaurav@exambazaar.com');
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
var subject2 = "Copy: " + subject;
var mail2 = new helper.Mail(fromEmail, subject2, to_email2, content);
mail.setTemplateId(templateId);
mail2.setTemplateId(templateId);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
var request2 = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail2.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
sg.API(request2, function(error, response) {
if(!error){
var this_email = new publicationemail({
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
publication: publication,
contact : {
name: contactName,
mobile: contactMobile,
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
if (err) return console.error(err);
console.log('Email sent with id: ' + this_email._id);
res.json(response);
});
}else{
console.log('Could not send email! ' + error);
}
});
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
module.exports = router;
|
/**
* @fileOverview run browserSync task
*/
import gulp from 'gulp';
import config from '../config';
import runSequence from 'run-sequence';
gulp.task('build', ['clean'], cb => {
let buildSequence = [
['styles', 'images', 'fonts', 'views', 'browserify']
];
if (config.gzip) {
buildSequence.push('gzip');
}
buildSequence.push(cb);
runSequence.apply(null, buildSequence);
});
|
import { StyleSheet } from 'react-native';
import { Dimensions } from 'react-native';
const { height: windowHeight } = Dimensions.get('window');
const height = windowHeight - 66;
export default StyleSheet.create({
container: {
display: 'flex',
alignItems: 'center',
backgroundColor: '#fafbfa',
flex: 1,
justifyContent: 'center',
padding: 15,
height,
},
loading: {
padding: 10,
color: 'gray',
},
webview: {
height,
},
error: {
},
});
|
/*jslint node: true, browser: true */
"use strict";
/**
* Created by iain on 3/8/15.
*/
function Model(isCoop, isHost) {
var WIDTH = 20,
HEIGHT = 35,
portrait = true,
makeBrick = function (setx, sety, setw, seth, setc) { return {x: setx, y: sety, w: setw, h: seth, c: setc}; },
makeBricks = function () {
var result = [],
size = 1,
gap = 0.5,
rows = 4,
yOffset = isCoop || isHost ? HEIGHT/2 - ((rows*(size + gap)-gap))/2 : size + gap;
for (var x = gap; x < WIDTH; x += size + gap) {
for (var y = 0; y < (rows*(gap+size)); y += size + gap) {
result.push(makeBrick(x, y+yOffset, size, size, '#FF6600'));
}
}
return result;
},
makeBall = function (setPlayer) {
var setx = WIDTH/ 2,
sety = setPlayer === '2' ? 2.5 : HEIGHT - 2.5,
setXVel = 0,
setYVel = setPlayer === '2' ? 0.2 : -0.2;
return {x: setx, y: sety, xVel: setXVel, yVel: setYVel, player: setPlayer};
},
makeParticle = function (setx, sety, setXVel, setYVel, timeToLive, gravDirection) { return {x: setx, y: sety, t: timeToLive, xVel: setXVel, yVel: setYVel, grav: gravDirection}; },
makeExplosion = function (x, y, numParticles, player) {
var result = [];
for (var i = 0; i < numParticles; i++) {
result.push(makeParticle(x, y, Math.random()/2-0.25, (player === '2' ? Math.random() : -Math.random())/2, 2000, player === '2' ? -1 : 1));
}
return result;
},
explosions = [],
playerPaddle = {x: WIDTH/2, y: HEIGHT-2, l: 6, h: 1, color: '#66FF99'},
paddles = [],
bricks = makeBricks(),
balls = [makeBall('1')],
updateCallback = function () { return true; },
eventCallback = function () { return true;},
updatePlayerPaddle = function (newPaddle) {
paddles[0] = JSON.parse(newPaddle);
},
getPlayerPaddle = function () {
var getPaddleReq = new XMLHttpRequest();
getPaddleReq.open('GET', 'multi/getPlayerPaddle.php', true);
getPaddleReq.onload = function (e) {
if (getPaddleReq.readyState === 4) {
if (getPaddleReq.status === 200) {
updatePlayerPaddle(getPaddleReq.responseText);
getPlayerPaddle();
}
}
};
getPaddleReq.send();
},
updateState = function () {
var httpReq = new XMLHttpRequest();
httpReq = new XMLHttpRequest();
httpReq.open('POST', 'multi/setGameData.php', true);
httpReq.onload = function (e) {
if (httpReq.readyState === 4) {
if (httpReq.status === 200) {
updateState();
}
}
};
httpReq.send(getStateJson());
},
getStateJson = function () {
return JSON.stringify({
paddle: playerPaddle,
paddles: paddles,
balls: balls,
bricks: bricks,
explosions: explosions
});
};
if (isCoop || isHost) {
paddles.push({x: WIDTH/2, y: 1, l: 6, h: 1, color: '#66FF99', xVel: 0});
balls.push(makeBall('2'));
}
if (isHost) {
updateState();
getPlayerPaddle();
}
this.setUpdateCallback = function (newCallback) {
updateCallback = newCallback;
};
this.setEventCallback = function (newCallback) {
eventCallback = newCallback;
};
this.getBricks = function () {
return bricks;
};
this.setPlayerPaddleX = function (newPaddleX) {
playerPaddle.x = newPaddleX;
};
this.getWidth = function () {
return WIDTH;
};
this.getHeight = function () {
return HEIGHT;
};
this.getPlayerPaddle = function () {
return playerPaddle;
};
this.getPaddles = function () {
return paddles;
};
this.getBalls = function () {
return balls;
};
this.getExplosions = function () {
return explosions;
};
this.setPortrait = function (isPortait) {
portrait = isPortait;
};
this.tick = function() {
var newX,
newY;
// Stuff to do when the game is over
if (bricks.length <= 0) {
for (var i = 0; i < balls.length; i++) {
explosions.push(makeExplosion(balls[i].x, balls[i].y, 25));
}
balls = [];
paddles = [];
}
if (isCoop) {
// Moving non player paddles
for (var i = 0; i < paddles.length; i++) {
var current = paddles[i],
closest = balls[0];
for (u = 1; u < balls.length; u++) {
if (balls[u].y < closest.y)
closest = balls[u];
}
if (current.x + current.l / 2 < closest.x) {
current.xVel += current.xVel < 0.8 ? 0.2 : 0;
} else if (current.x - current.l / 2 > closest.x) {
current.xVel -= current.xVel > -0.8 ? 0.2 : 0;
} else {
current.xVel -= current.xVel != 0 ? current.xVel : 0;
}
if (current.x + current.xVel - current.l / 2 < 0) {
current.x = current.l / 2;
} else if (current.x + current.xVel + current.l / 2 > WIDTH) {
current.x = WIDTH - current.l / 2;
} else {
current.x += current.xVel;
}
}
}
// Collision checks for all the balls
for (var i = 0 ; i < balls.length; i++) {
newX = balls[i].x + balls[i].xVel;
newY = balls[i].y + balls[i].yVel;
// Check collision on player paddle
if (newX - 0.5 < playerPaddle.x + (playerPaddle.l / 2) && newX + 0.5 > playerPaddle.x - (playerPaddle.l / 2) && newY + 0.5 > playerPaddle.y && newY - 0.5 < playerPaddle.y + playerPaddle.h) {
eventCallback('bounce');
var dif = balls[i].x - playerPaddle.x;
if (balls[i].x + 0.5 <= playerPaddle.x - (playerPaddle.l / 2)) {
balls[i].xVel = -balls[i].xVel;
newX = balls[i].x + (balls[i].x + 0.5 - (playerPaddle.x - (playerPaddle.l / 2)));
} else if (balls[i].x - 0.5 >= playerPaddle.x + (playerPaddle.l / 2)) {
balls[i].xVel = -balls[i].xVel;
newX = balls[i].x - ((balls[i].x - 0.5) - (playerPaddle.x + (playerPaddle.l / 2)));
} else if (balls[i].y + 0.5 <= playerPaddle.y) {
balls[i].xVel += dif * 0.1;
balls[i].yVel = -balls[i].yVel;
newY = balls[i].y + (balls[i].y + 0.5 - playerPaddle.y);
} else if (balls[i].y - 0.5 >= playerPaddle.y+playerPaddle.h) {
balls[i].xVel += dif * 0.1;
balls[i].yVel = -balls[i].yVel;
newY = balls[i].y - ((balls[i].y - 0.5) - (playerPaddle.y + playerPaddle.h));
}
} else {
// Check collision on non player paddles
for (var p = 0; p < paddles.length; p++) {
var current = paddles[p];
if (newX - 0.5 < current.x + (current.l / 2) && newX + 0.5 > current.x - (current.l / 2) && newY + 0.5 > current.y && newY - 0.5 < current.y + current.h) {
eventCallback('bounce');
var dif = balls[i].x - current.x;
if (balls[i].x + 0.5 <= current.x - (current.l / 2)) {
balls[i].xVel = -balls[i].xVel;
newX = balls[i].x + (balls[i].x + 0.5 - (current.x - (current.l / 2)));
} else if (balls[i].x - 0.5 >= current.x + (current.l / 2)) {
balls[i].xVel = -balls[i].xVel;
newX = balls[i].x - ((balls[i].x - 0.5) - (current.x + (current.l / 2)));
} else if (balls[i].y + 0.5 <= current.y) {
balls[i].xVel += dif * 0.1;
balls[i].yVel = -balls[i].yVel;
newY = balls[i].y + (balls[i].y + 0.5 - current.y);
} else if (balls[i].y - 0.5 >= current.y+current.h) {
balls[i].xVel += dif * 0.1;
balls[i].yVel = -balls[i].yVel;
newY = balls[i].y - ((balls[i].y - 0.5) - (current.y + current.h));
}
}
}
var bounced = false,
destroy = [];
// Check collision on bricks
for (var u = 0; u < bricks.length; u++) {
if (!bounced && newX + 0.5 > bricks[u].x && newX - 0.5 < bricks[u].x + bricks[u].w && newY +0.5 > bricks[u].y && newY - 0.5 < bricks[u].y+bricks[u].h) {
bounced = true;
if (balls[i].x + 0.5 <= bricks[u].x) {
balls[i].xVel = -balls[i].xVel;
newX = balls[i].x + (balls[i].x + 0.5 - bricks[u].x);
} else if (balls[i].x - 0.5 >= bricks[u].x+bricks[u].w) {
balls[i].xVel = -balls[i].xVel;
newX = balls[i].x - ((balls[i].x - 0.5) - (bricks[u].x + bricks[u].w));
} else if (balls[i].y + 0.5 <= bricks[u].y) {
balls[i].yVel = -balls[i].yVel;
newY = balls[i].y + (balls[i].y + 0.5 - bricks[u].y);
} else if (balls[i].y - 0.5 >= bricks[u].y+bricks[u].h) {
balls[i].yVel = -balls[i].yVel;
newY = balls[i].y - ((balls[i].y - 0.5) - (bricks[u].y + bricks[u].h));
}
destroy.push(u);
explosions.push(makeExplosion(bricks[u].x+bricks[u].w/2, bricks[u].y+bricks[u].h/2, 20, balls[i].player));
eventCallback('break');
}
}
// Remove bricks that where hit
for (var z = 0; z < destroy.length; z++) {
bricks.splice(destroy[z], 1);
}
// Side wall collisions
if (newX + 0.5 >= WIDTH) {
eventCallback('bounce');
balls[i].xVel = -balls[i].xVel;
newX = WIDTH - 0.5;
} else if (newX - 0.5<= 0) {
eventCallback('bounce');
balls[i].xVel = -balls[i].xVel;
newX = 0.5;
}
// Top and bottom collisions/ball respawn
if (newY + 0.5 >= HEIGHT) {
balls[i] = makeBall(balls[i].player);
continue;
} else if (newY - 0.5 <= 0) {
if (isCoop || isHost) {
balls[i] = makeBall(balls[i].player);
continue;
} else {
eventCallback('bounce');
balls[i].yVel = -balls[i].yVel;
newY = 0.5;
}
}
}
balls[i].x = newX;
balls[i].y = newY;
}
// Update explosion particles
for (var i = 0; i < explosions.length; i++) {
if (explosions[i].length <= 0) {
explosions.splice(i, 1);
i--;
continue;
}
for (var u = 0; u < explosions[i].length; u++) {
explosions[i][u].t -= 30;
if (explosions[i][u].t < 0) {
explosions[i].splice(u, 1);
u--;
continue;
}
explosions[i][u].x += explosions[i][u].xVel;
explosions[i][u].y += explosions[i][u].yVel;
explosions[i][u].yVel += 0.025 * explosions[i][u].grav;
explosions[i][u].xVel -= explosions[i][u].xVel * 0.075;
}
}
// Notify view of update
updateCallback();
};
};
|
import { Template } from 'meteor/templating';
import Node from '/imports/api/nodes/nodes.js';
import '../../components/selectable/selectable.js';
import '../../components/editable-td/editable-td.js';
import '../../components/text-input/text-input.js';
import './nodes.html';
Template.Nodes.onCreated(function() {
Meteor.subscribe('nodes.all');
this.state = new ReactiveDict();
this.state.setDefault({
selected: [],
});
});
Template.Nodes.helpers({
allNodes() {
return Node.find();
},
hasSelected() {
return Template.instance().state.get('selected').length > 0;
},
onSelect(item) {
const state = Template.instance().state;
// it seems that the template make two function-applys
// so I wrapped the actual function with a lambda
return (() => (isSelected) => {
const currentSelected = state.get('selected');
if(isSelected) {
updatedSelected = [...currentSelected, item];
} else {
updatedSelected = currentSelected.filter(itm => itm._id !== item._id);
}
state.set('selected', updatedSelected);
});
},
});
Template.Nodes.events({
'submit .new-item' (event) {
event.preventDefault();
const form = event.target;
const newItem = {
title: form.title.value,
description: form.description.value,
};
const existItem = Node.findOne({title: newItem.title}) // TODO: better duplication checks
if(existItem) {
// TODO: alert something?
} else {
const newItemId = new Node(newItem).create();
}
form.title.value = "";
form.description.value = "";
},
'submit .action' (event, instance) {
event.preventDefault();
const action = event.target.action.value;
const selected = instance.state.get('selected');
const updatedSelected = selected.filter(itm => {
switch(action) {
case "REMOVE":
itm.delete();
return false;
default:
return true;
}
});
instance.state.set('selected', updatedSelected);
},
});
|
'use strict';
describe('nothing', function () {
it('should do nothing', function () {//
});
});
|
var test = require('tap').test;
var sentiment = require('../../lib/index');
var dataset = 'Hey you worthless scumbag';
sentiment(dataset, function (err, result) {
test('asynchronous negative', function (t) {
t.type(result, 'object');
t.equal(result.score, -6);
t.equal(result.comparative, -1.5);
t.equal(result.tokens.length, 4);
t.equal(result.words.length, 2);
t.end();
});
});
|
import process from 'node:process';
import fs, {promises as fsPromises} from 'node:fs';
import execa from 'execa';
function extractDarwin(line) {
const columns = line.split(':');
// Darwin passwd(5)
// 0 name User's login name.
// 1 password User's encrypted password.
// 2 uid User's id.
// 3 gid User's login group id.
// 4 class User's general classification (unused).
// 5 change Password change time.
// 6 expire Account expiration time.
// 7 gecos User's full name.
// 8 home_dir User's home directory.
// 9 shell User's login shell.
return {
username: columns[0],
password: columns[1],
userIdentifier: Number(columns[2]),
groupIdentifier: Number(columns[3]),
fullName: columns[7],
homeDirectory: columns[8],
shell: columns[9],
};
}
function extractLinux(line) {
const columns = line.split(':');
// Linux passwd(5):
// 0 login name
// 1 optional encrypted password
// 2 numerical user ID
// 3 numerical group ID
// 4 user name or comment field
// 5 user home directory
// 6 optional user command interpreter
return {
username: columns[0],
password: columns[1],
userIdentifier: Number(columns[2]),
groupIdentifier: Number(columns[3]),
fullName: columns[4] && columns[4].split(',')[0],
homeDirectory: columns[5],
shell: columns[6],
};
}
const extract = process.platform === 'linux' ? extractLinux : extractDarwin;
function getUser(passwd, username) {
const lines = passwd.split('\n');
const linesCount = lines.length;
let index = 0;
while (index < linesCount) {
const user = extract(lines[index++]);
if (user.username === username || user.userIdentifier === Number(username)) {
return user;
}
}
}
export async function passwdUser(username) {
if (username === undefined) {
if (typeof process.getuid !== 'function') {
// eslint-disable-next-line unicorn/prefer-type-error
throw new Error('Platform not supported');
}
username = process.getuid();
}
if (process.platform === 'linux') {
return getUser(await fsPromises.readFile('/etc/passwd', 'utf8'), username);
}
if (process.platform === 'darwin') {
const {stdout} = await execa('/usr/bin/id', ['-P', username]);
return getUser(stdout, username);
}
throw new Error('Platform not supported');
}
export function passwdUserSync(username) {
if (username === undefined) {
if (typeof process.getuid !== 'function') {
// eslint-disable-next-line unicorn/prefer-type-error
throw new Error('Platform not supported');
}
username = process.getuid();
}
if (process.platform === 'linux') {
return getUser(fs.readFileSync('/etc/passwd', 'utf8'), username);
}
if (process.platform === 'darwin') {
return getUser(execa.sync('/usr/bin/id', ['-P', username]).stdout, username);
}
throw new Error('Platform not supported');
}
|
import {
GraphQLSchema as Schema,
GraphQLObjectType as ObjectType,
} from 'graphql';
import content from './queries/content';
import champion from './queries/champion';
import champions from './queries/champions';
import item from './queries/item';
import items from './queries/items';
import languages from './queries/languages';
import languageStrings from './queries/languageStrings';
import maps from './queries/maps';
import server from './queries/server';
const schema = new Schema({
query: new ObjectType({
name: 'Query',
fields: {
content,
champion,
champions,
item,
items,
languages,
languageStrings,
maps,
server,
},
}),
});
export default schema;
|
"use strict";
angular.module('places')
.controller('MyPlaceCtrl', function($scope) {
var groups =[
{
name:'Quand partir?',
description:'Plusieurs variations de Lorem Ipsum peuvent être trouvées ici ou là, mais la majeure partie addition ne ressemblent pas une seconde à du texte standard.',
image:'http://lorempicsum.com/futurama/100/100/1'
},
{
name:'Avant le départ',
description:'Plusieurs variations de Lorem Ipsum peuvent être trouvées ici ou là, mais la majeure partie addition ou de mots aléatoires qui ne ressemblent pas une seconde à du texte standard.',
image:'http://lorempicsum.com/futurama/100/100/2'
},
{
name:'Culture',
description:'Cool place to see with great robots inside',
image:'http://lorempicsum.com/futurama/100/100/3'
},
{
name:'Hebergement',
description:'Cool place to see with great robots inside',
image:'http://lorempicsum.com/futurama/100/100/4'
},
{
name:'Transport',
description:'Cool place to see with great robots inside',
image:'http://lorempicsum.com/futurama/100/100/5'
},
{
name:'Devise',
description:'Cool place to see with great robots inside',
image:'http://lorempicsum.com/futurama/100/100/6'
},
{
name:'Partenaires',
description:'Cool place to see with great robots inside',
image:'http://lorempicsum.com/futurama/100/100/7'
},
{
name:'Vol',
description:'Cool place to see with great robots inside',
image:'http://lorempicsum.com/futurama/100/100/8'
}
];
$scope.groups = groups;
for (var i = 0; i < 8; i++) {
//$scope.groups = groups.concat(groups.slice(0))
$scope.groups[i] = {
name: i,
items: []
};
for (var j = 0; j < 3; j++) {
$scope.groups[i].items.push(i + 'groups.description' +j );
}
}
/*
* if given group is the selected group, deselect it
* else, select the given group
*/
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};
});
|
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var g = require('../globalize');
/**
* Data model for key-value databases.
*
* @class KeyValueModel
* @inherits {Model}
*/
module.exports = function(KeyValueModel) {
/**
* Return the value associated with a given key.
*
* @param {String} key Key to use when searching the database.
* @options {Object} options
* @callback {Function} callback
* @param {Error} err Error object.
* @param {Any} result Value associated with the given key.
* @promise
*
* @header KeyValueModel.get(key, cb)
*/
KeyValueModel.get = function(key, options, callback) {
throwNotAttached(this.modelName, 'get');
};
/**
* Persist a value and associate it with the given key.
*
* @param {String} key Key to associate with the given value.
* @param {Any} value Value to persist.
* @options {Number|Object} options Optional settings for the key-value
* pair. If a Number is provided, it is set as the TTL (time to live) in ms
* (milliseconds) for the key-value pair.
* @property {Number} ttl TTL for the key-value pair in ms.
* @callback {Function} callback
* @param {Error} err Error object.
* @promise
*
* @header KeyValueModel.set(key, value, cb)
*/
KeyValueModel.set = function(key, value, options, callback) {
throwNotAttached(this.modelName, 'set');
};
/**
* Set the TTL (time to live) in ms (milliseconds) for a given key. TTL is the
* remaining time before a key-value pair is discarded from the database.
*
* @param {String} key Key to use when searching the database.
* @param {Number} ttl TTL in ms to set for the key.
* @options {Object} options
* @callback {Function} callback
* @param {Error} err Error object.
* @promise
*
* @header KeyValueModel.expire(key, ttl, cb)
*/
KeyValueModel.expire = function(key, ttl, options, callback) {
throwNotAttached(this.modelName, 'expire');
};
/**
* Return the TTL (time to live) for a given key. TTL is the remaining time
* before a key-value pair is discarded from the database.
*
* @param {String} key Key to use when searching the database.
* @options {Object} options
* @callback {Function} callback
* @param {Error} error
* @param {Number} ttl Expiration time for the key-value pair. `undefined` if
* TTL was not initially set.
* @promise
*
* @header KeyValueModel.ttl(key, cb)
*/
KeyValueModel.ttl = function(key, options, callback) {
throwNotAttached(this.modelName, 'ttl');
};
/**
* Return all keys in the database.
*
* **WARNING**: This method is not suitable for large data sets as all
* key-values pairs are loaded into memory at once. For large data sets,
* use `iterateKeys()` instead.
*
* @param {Object} filter An optional filter object with the following
* @param {String} filter.match Glob string used to filter returned
* keys (i.e. `userid.*`). All connectors are required to support `*` and
* `?`, but may also support additional special characters specific to the
* database.
* @param {Object} options
* @callback {Function} callback
* @promise
*
* @header KeyValueModel.keys(filter, cb)
*/
KeyValueModel.keys = function(filter, options, callback) {
throwNotAttached(this.modelName, 'keys');
};
/**
* Asynchronously iterate all keys in the database. Similar to `.keys()` but
* instead allows for iteration over large data sets without having to load
* everything into memory at once.
*
* Callback example:
* ```js
* // Given a model named `Color` with two keys `red` and `blue`
* var iterator = Color.iterateKeys();
* it.next(function(err, key) {
* // key contains `red`
* it.next(function(err, key) {
* // key contains `blue`
* });
* });
* ```
*
* Promise example:
* ```js
* // Given a model named `Color` with two keys `red` and `blue`
* var iterator = Color.iterateKeys();
* Promise.resolve().then(function() {
* return it.next();
* })
* .then(function(key) {
* // key contains `red`
* return it.next();
* });
* .then(function(key) {
* // key contains `blue`
* });
* ```
*
* @param {Object} filter An optional filter object with the following
* @param {String} filter.match Glob string to use to filter returned
* keys (i.e. `userid.*`). All connectors are required to support `*` and
* `?`. They may also support additional special characters that are
* specific to the backing database.
* @param {Object} options
* @returns {AsyncIterator} An Object implementing `next(cb) -> Promise`
* function that can be used to iterate all keys.
*
* @header KeyValueModel.iterateKeys(filter)
*/
KeyValueModel.iterateKeys = function(filter, options) {
throwNotAttached(this.modelName, 'iterateKeys');
};
/*!
* Set up remoting metadata for this model.
*
* **Notes**:
* - The method is called automatically by `Model.extend` and/or
* `app.registry.createModel`
* - In general, base models use call this to ensure remote methods are
* inherited correctly, see bug at
* https://github.com/strongloop/loopback/issues/2350
*/
KeyValueModel.setup = function() {
KeyValueModel.base.setup.apply(this, arguments);
this.remoteMethod('get', {
accepts: {
arg: 'key', type: 'string', required: true,
http: {source: 'path'},
},
returns: {arg: 'value', type: 'any', root: true},
http: {path: '/:key', verb: 'get'},
rest: {after: convertNullToNotFoundError},
});
this.remoteMethod('set', {
accepts: [
{arg: 'key', type: 'string', required: true,
http: {source: 'path'}},
{arg: 'value', type: 'any', required: true,
http: {source: 'body'}},
{arg: 'ttl', type: 'number',
http: {source: 'query'},
description: 'time to live in milliseconds'},
],
http: {path: '/:key', verb: 'put'},
});
this.remoteMethod('expire', {
accepts: [
{arg: 'key', type: 'string', required: true,
http: {source: 'path'}},
{arg: 'ttl', type: 'number', required: true,
http: {source: 'form'}},
],
http: {path: '/:key/expire', verb: 'put'},
});
this.remoteMethod('ttl', {
accepts: {
arg: 'key', type: 'string', required: true,
http: {source: 'path'},
},
returns: {arg: 'value', type: 'any', root: true},
http: {path: '/:key/ttl', verb: 'get'},
});
this.remoteMethod('keys', {
accepts: {
arg: 'filter', type: 'object', required: false,
http: {source: 'query'},
},
returns: {arg: 'keys', type: ['string'], root: true},
http: {path: '/keys', verb: 'get'},
});
};
};
function throwNotAttached(modelName, methodName) {
throw new Error(g.f(
'Cannot call %s.%s(). ' +
'The %s method has not been setup. ' +
'The {{KeyValueModel}} has not been correctly attached ' +
'to a {{DataSource}}!',
modelName, methodName, methodName));
}
function convertNullToNotFoundError(ctx, cb) {
if (ctx.result !== null) return cb();
var modelName = ctx.method.sharedClass.name;
var id = ctx.getArgByName('id');
var msg = g.f('Unknown "%s" {{key}} "%s".', modelName, id);
var error = new Error(msg);
error.statusCode = error.status = 404;
error.code = 'KEY_NOT_FOUND';
cb(error);
}
|
/**
* Created by hejun on 15/4/15.
* 纯前端配置-微信分享
* 1.加载js后 请先执行init方法
* 2.当前只能在socialpark.com.cn 域名下使用 其他域名使用无效(受公众账号设置限制)
* 3.本组件依赖 http://res.wx.qq.com/open/js/jweixin-1.0.0.js 自动加载 自动依赖
* 4.支持 cmd amd 引用
* 5.全局对象 window.tp.wx
* 6.返回对象中wechat为微信jssdk方法
* 7.自动加上百度渠道统计,可统计 朋友圈 好友 qq
*/
!(function () {
var WX = {
version: '2.0.5'
};
var shareData = {
title: '',
desc: '',
link: '',
imgUrl: '',
success: function () {
},
cancel: function () {
}
};
var isDebug = false;
var isInit = false;
var _currShareData = null;
var initcallback = null;
var wechatSdkUrl = "//res.wx.qq.com/open/js/jweixin-1.0.0.js";
WX.wechat = null;
WX.setWechat = function (wechat) {
WX.wechat = wechat;
};
var jsApiList= [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'translateVoice',
'startRecord',
'stopRecord',
'onRecordEnd',
'playVoice',
'pauseVoice',
'stopVoice',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
];
/**
* 分享初始化
* @param {[type]} defaultshareData 默认分享文案
* @param {[type]} callback 初始化成功后回调函数
* @param {[type]} debug 调试是否打开 默认false
*/
WX.init = function (defaultshareData, callback, debug) {
defaultshareData = defaultshareData || {};
shareData = extend(shareData, defaultshareData);
debug = debug || isDebug;
initcallback = typeof(callback) === "function" ? callback : null;
isDebug = !!debug;
var url = "http://wechat.thinkpark.com.cn/wechat-service/getshare.php?t=" + new Date().getTime() + "&callback=tp.wx.config&url=" + encodeURIComponent(location.href.replace(location.hash, ""));
if ("function" == typeof define) {
require(["http://wechat.thinkpark.com.cn/wechat-service/getshare.php?t=" + new Date().getTime() + "&callback=define&url=" + encodeURIComponent(location.href.replace(location.hash, ""))], function (data) {
WX.config(data);
});
}
else if (window.wx) {
WX.setWechat(window.wx);
loadScript(url);
} else {
loadScript(wechatSdkUrl, function () {
WX.setWechat(window.wx);
loadScript(url);
})
}
};
WX.config = function (d) {
if (d.ret != 200) {
if (isDebug)alert(JSON.stringify(d));
return;
}
WX.wechat.config({
debug: isDebug,
appId: d.appid,
timestamp: d.timestamp,
nonceStr: d.noncestr,
signature: d.signature,
jsApiList: jsApiList
});
WX.wechat.ready(function () {
WX.wechat.checkJsApi({
jsApiList:jsApiList,
success: function(res) {
typeof (initcallback) === "function" && initcallback();
WX.wechat.hideMenuItems({
menuList: ['menuItem:share:weiboApp', 'menuItem:share:facebook']
});
WX.wechat.showMenuItems({
menuList: ['menuItem:profile', 'menuItem:addContact']
});
isInit = true;
WX.setshare(_currShareData);
}
});
});
};
WX.setshare = function (d) {
_currShareData = d || {};
if (!isInit) {
return;
}
var currShareData = extend(shareData, _currShareData);
var _link = currShareData.link.split('#')[0] + (currShareData.link.split('#')[0].indexOf("?") != -1 ? '&' : '?') + "hmsr={from}" + (currShareData.link.split('#').length == 2 ? '#' + currShareData.link.split('#')[1]:'');
// 分享到微信朋友圈
WX.wechat.onMenuShareTimeline({
title: currShareData.title,
link: _link.replace("hmsr={from}", 'hmsr=%E5%BE%AE%E4%BF%A1%E6%9C%8B%E5%8F%8B%E5%9C%88'),
imgUrl: currShareData.imgUrl,
success: function () {
currShareData.success && currShareData.success();
try {
_hmt.push(['_trackEvent', "分享成功", '分享到朋友圈']);
} catch (e) {
}
},
cancel: function () {
currShareData.cancel && currShareData.cancel();
try {
_hmt.push(['_trackEvent', "取消分享", '取消分享']);
} catch (e) {
}
}
});
// 发送给指定微信好友
WX.wechat.onMenuShareAppMessage({
title: currShareData.title,
desc: currShareData.desc,
link: _link.replace("hmsr={from}", 'hmsr=%E5%BE%AE%E4%BF%A1%E5%A5%BD%E5%8F%8B'),
imgUrl: currShareData.imgUrl,
success: function () {
currShareData.success && currShareData.success();
try {
_hmt.push(['_trackEvent', "分享成功", '分享给好友']);
} catch (e) {
}
},
cancel: function () {
currShareData.cancel && currShareData.cancel();
try {
_hmt.push(['_trackEvent', "取消分享", '取消分享']);
} catch (e) {
}
}
});
WX.wechat.onMenuShareQQ({
title: currShareData.title, // 分享标题
desc: currShareData.desc, // 分享描述
link: _link.replace("hmsr={from}","hmsr=qq"), // 分享链接
imgUrl: currShareData.imgUrl, // 分享图标
success: function () {
currShareData.success && currShareData.success();
try {
_hmt.push(['_trackEvent', "分享成功", '分享成功']);
} catch (e) {
}
},
cancel: function () {
currShareData.cancel && currShareData.cancel();
try {
_hmt.push(['_trackEvent', "取消分享", '取消分享']);
} catch (e) {
}
}
});
};
function loadScript(url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" ||
script.readyState == "complete") {
script.onreadystatechange = null;
typeof (callback) === "function" && callback();
}
};
} else { //Others: Firefox, Safari, Chrome, and Opera
script.onload = function () {
typeof (callback) === "function" && callback();
};
}
script.src = url;
DOMReady(function () {
document.body.appendChild(script);
});
}
var isDOMReady = false;
function DOMReady(callback) {
if (isDOMReady) {
typeof (callback) === "function" && callback();
} else {
setTimeout(function () {
if (document.body) {
isDOMReady = true;
}
DOMReady(callback);
}, 1);
}
}
function extend(target, source) {
target = target || {};
var result = {};
for (var p in target) {
if (source.hasOwnProperty(p)) {
result[p] = source[p];
} else {
result[p] = target[p];
}
}
return result;
}
"function" == typeof define ? define([wechatSdkUrl], function (wx) {
WX.setWechat(wx);
return WX;
}) : (function () {
window.tp = window.tp || {};
window.tp['wx'] = WX;
})();
})();
|
class cdo_ss_nntponpostfinalsink_1 {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = cdo_ss_nntponpostfinalsink_1;
|
//= require d3.v2
//= require rickshaw
|
/**
* @license Highstock JS v8.0.0 (2019-12-10)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Paweł Fus
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/rsi', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'indicators/rsi.src.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js']], function (H, U) {
/* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var isArray = U.isArray;
/* eslint-disable require-jsdoc */
// Utils:
function toFixed(a, n) {
return parseFloat(a.toFixed(n));
}
/* eslint-enable require-jsdoc */
/**
* The RSI series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.rsi
*
* @augments Highcharts.Series
*/
H.seriesType('rsi', 'sma',
/**
* Relative strength index (RSI) technical indicator. This series
* requires the `linkedTo` option to be set and should be loaded after
* the `stock/indicators/indicators.js` file.
*
* @sample stock/indicators/rsi
* RSI indicator
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/rsi
* @optionparent plotOptions.rsi
*/
{
/**
* @excluding index
*/
params: {
period: 14,
/**
* Number of maximum decimals that are used in RSI calculations.
*/
decimals: 4
}
},
/**
* @lends Highcharts.Series#
*/
{
getValues: function (series, params) {
var period = params.period,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
decimals = params.decimals,
// RSI starts calculations from the second point
// Cause we need to calculate change between two points
range = 1,
RSI = [],
xData = [],
yData = [],
index = 3,
gain = 0,
loss = 0,
RSIPoint,
change,
avgGain,
avgLoss,
i;
// RSI requires close value
if ((xVal.length < period) || !isArray(yVal[0]) ||
yVal[0].length !== 4) {
return;
}
// Calculate changes for first N points
while (range < period) {
change = toFixed(yVal[range][index] - yVal[range - 1][index], decimals);
if (change > 0) {
gain += change;
}
else {
loss += Math.abs(change);
}
range++;
}
// Average for first n-1 points:
avgGain = toFixed(gain / (period - 1), decimals);
avgLoss = toFixed(loss / (period - 1), decimals);
for (i = range; i < yValLen; i++) {
change = toFixed(yVal[i][index] - yVal[i - 1][index], decimals);
if (change > 0) {
gain = change;
loss = 0;
}
else {
gain = 0;
loss = Math.abs(change);
}
// Calculate smoothed averages, RS, RSI values:
avgGain = toFixed((avgGain * (period - 1) + gain) / period, decimals);
avgLoss = toFixed((avgLoss * (period - 1) + loss) / period, decimals);
// If average-loss is equal zero, then by definition RSI is set
// to 100:
if (avgLoss === 0) {
RSIPoint = 100;
// If average-gain is equal zero, then by definition RSI is set
// to 0:
}
else if (avgGain === 0) {
RSIPoint = 0;
}
else {
RSIPoint = toFixed(100 - (100 / (1 + (avgGain / avgLoss))), decimals);
}
RSI.push([xVal[i], RSIPoint]);
xData.push(xVal[i]);
yData.push(RSIPoint);
}
return {
values: RSI,
xData: xData,
yData: yData
};
}
});
/**
* A `RSI` series. If the [type](#series.rsi.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.rsi
* @since 6.0.0
* @product highstock
* @excluding dataParser, dataURL
* @requires stock/indicators/indicators
* @requires stock/indicators/rsi
* @apioption series.rsi
*/
''; // to include the above in the js output
});
_registerModule(_modules, 'masters/indicators/rsi.src.js', [], function () {
});
}));
|
const hammerhead = window.getTestCafeModule('hammerhead');
const browserUtils = hammerhead.utils.browser;
asyncTest('isIFrameWindowInDOM', function () {
expect(browserUtils.isIE ? 2 : 1);
let messageCounter = 0;
function finishTest () {
window.removeEventListener('message', onMessage, false);
start();
}
function onMessage (event) {
if (messageCounter === 0) {
equal(event.data, 'true');
const iFramePostMessage = iframe.contentWindow.postMessage.bind(iframe.contentWindow);
document.body.removeChild(iframe);
//NOTE: In WebKit, scripts cannot be executed in a removed iframe. Therefore, the test is finished here.
if (browserUtils.isIE)
iFramePostMessage('isIFrameWindowInDOM', '*');
else
finishTest();
}
else {
equal(event.data, 'false');
finishTest();
}
messageCounter++;
}
window.addEventListener('message', onMessage, false);
const iframe = $('<iframe>')[0];
iframe.src = window.getCrossDomainPageUrl('../../data/dom-utils/iframe.html');
window.QUnitGlobals.waitForIframe(iframe).then(function () {
iframe.contentWindow.postMessage('isIFrameWindowInDOM', '*');
});
document.body.appendChild(iframe);
});
|
var app = require('express')(),
wizard = require('hmpo-form-wizard'),
steps = require('./steps'),
fields = require('./fields');
app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' }));
app.use(wizard(steps, fields, {
controller: require('../../../controllers/form'),
templatePath: 'change_of_name_171218/overseas-first' }));
module.exports = app;
|
import ApplicationAdapter from 'ghost-admin/adapters/application';
export default class CustomThemeSettingListAdapter extends ApplicationAdapter {
// we use `custom-theme-setting-list` model as a workaround for saving all
// custom theme setting records in one request so it uses the base model url
pathForType() {
return 'custom_theme_settings';
}
// there's no custom theme setting creation
// newListModel.save() acts as an overall update request so force a PUT
createRecord(store, type, snapshot) {
return this.saveRecord(store, type, snapshot, {method: 'PUT'}, 'createRecord');
}
}
|
const five = require('johnny-five');
const board = new five.Board();
board.on('ready', () => {
const led1 = new five.Led(2);
const led2 = new five.Led(3);
board.repl.inject({
led1: led1,
led2: led2
});
});
|
'use strict';
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
/* Controllers */
function UserListCtrl($scope, $http, $templateCache) {
var method = 'POST';
var inserturl = 'http://localhost:1212/insertangularcouchuser';
$scope.codeStatus = "";
$scope.save = function() {
var formData = {
'username' : this.username,
'password' : this.password,
'email' : this.email
};
this.username = '';
this.password = '';
this.email = '';
var jdata = 'mydata='+JSON.stringify(formData);
$http({
method: method,
url: inserturl,
data: jdata ,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).
success(function(response) {
console.log("success");
$scope.codeStatus = response.data;
console.log($scope.codeStatus);
}).
error(function(response) {
console.log("error");
$scope.codeStatus = response || "Request failed";
console.log($scope.codeStatus);
});
$scope.list();
return false;
};
$scope.list = function() {
var url = 'http://localhost:1212/getangularusers';
$http.get(url).success(function(data) {
console.log(data);
$scope.users = data;
});
};
$scope.list();
}
//PhoneListCtrl.$inject = ['$scope', '$http'];
|
define(function (require) {
'use strict';
function withDataAttributes() {
this.loadDataAttributes = function () {
$.each(this.$node.data(), function (key, value) {
if(!this.strictMode || this.attr[key] !== undefined) {
this.attr[key] = value;
}
}.bind(this));
};
this.after('initialize', function () {
this.strictMode = this.attr.strictMode || false;
this.loadDataAttributes();
});
}
return withDataAttributes;
});
|
// options with associated default value defined in chartNew.js
// annotateDisplay: false,
// annotateRelocate: false,
// annotateFunction: "mousemove",
// annotateFontFamily: "'Arial'",
// annotateBorder: 'none',
// annotateBorderRadius: '2px',
// annotateBackgroundColor: 'rgba(0,0,0,0.8)',
// annotateFontSize: 12,
// annotateFontColor: 'white',
// annotateFontStyle: "normal",
// annotatePadding: "3px",
// annotateClassName: "",
// annotateFunctionIn: null,
// annotateFunctionOut : null,
// annotateBarMinimumDetectionHeight : 0,
// chart.defaults.IExplorer8 ={
// annotateBackgroundColor : "black",
// annotateFontColor: "white"
var style = document.createElement('style');
style.type = 'text/css';
line="";
line=line+".toolTipTopRight { ";
line=line+"} ";
line=line+".toolTipTopLeft { ";
line=line+"} ";
line=line+".toolTipTopCenter { ";
line=line+"} ";
line=line+".toolTipBottomRight { ";
line=line+"} ";
line=line+".toolTipBottomLeft { ";
line=line+"} ";
line=line+".toolTipBottomCenter { ";
line=line+"} ";
line=line+".toolTipRightTop { ";
line=line+"} ";
line=line+".toolTipRightBottom { ";
line=line+"} ";
line=line+".toolTipRightCenter { ";
line=line+"} ";
line=line+".toolTipLeftTop { ";
line=line+"} ";
line=line+".toolTipLeftBottom { ";
line=line+"} ";
line=line+".toolTipLeftCenter { ";
line=line+"} ";
line=line+".toolTipLeftNone { ";
line=line+"}";
line=line+'.toolTipTopRight .toolTipTopRightText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent transparent #555 transparent; ';
line=line+' ';
line=line+' bottom: 100%; ';
line=line+' right: 5px; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-left: 5px solid transparent; ';
line=line+' border-right: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-bottom: 5px solid black; */ ';
line=line+'} ';
line=line+'.toolTipTopLeft .toolTipTopLeftText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent transparent #555 transparent; ';
line=line+' ';
line=line+' bottom: 100%; ';
line=line+' left: 5px; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-left: 5px solid transparent; ';
line=line+' border-right: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-bottom: 5px solid black; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipTopCenter .toolTipTopCenterText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent transparent #555 transparent; ';
line=line+' ';
line=line+' bottom: 100%; ';
line=line+' left: 50%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-left: 5px solid transparent; ';
line=line+' border-right: 5px solid transparent; ';
line=line+' margin-left : -5px; ';
line=line+' ';
line=line+'/* border-bottom: 5px solid black; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipBottomRight .toolTipBottomRightText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: #555 transparent transparent transparent; ';
line=line+' ';
line=line+' top: 100%; ';
line=line+' right: 5px; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-left: 5px solid transparent; ';
line=line+' border-right: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-top: 5px solid black;*/ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipBottomLeft .toolTipBottomLeftText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: #555 transparent transparent transparent; ';
line=line+' ';
line=line+' top: 100%; ';
line=line+' left: 5px; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-left: 5px solid transparent; ';
line=line+' border-right: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-top: 5px solid black; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipBottomCenter .toolTipBottomCenterText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: #555 transparent transparent transparent; ';
line=line+' ';
line=line+' top: 100%; ';
line=line+' left: 50%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-left: 5px solid transparent; ';
line=line+' border-right: 5px solid transparent; ';
line=line+' ';
line=line+' margin-left: -5px; ';
line=line+' ';
line=line+'/* border-top: 5px solid black; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipRightTop .toolTipRightTopText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent transparent transparent #555 ; ';
line=line+' ';
line=line+' top: 5px; ';
line=line+' left: 100%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-top: 5px solid transparent; ';
line=line+' border-bottom: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-left: 5px solid green; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipRightBottom .toolTipRightBottomText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent transparent transparent #555 ; ';
line=line+' ';
line=line+' bottom: 5px; ';
line=line+' left: 100%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-top: 5px solid transparent; ';
line=line+' border-bottom: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-left: 5px solid green; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipRightCenter .toolTipRightCenterText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent transparent transparent #555 ; ';
line=line+' ';
line=line+' bottom: 50%; ';
line=line+' left: 100%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-top: 5px solid transparent; ';
line=line+' border-bottom: 5px solid transparent; ';
line=line+' margin-bottom: -5px; ';
line=line+' ';
line=line+'/* border-left: 5px solid green; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipLeftBottom .toolTipLeftBottomText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent #555 transparent transparent ; ';
line=line+' ';
line=line+' bottom: 5px; ';
line=line+' right: 100%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-top: 5px solid transparent; ';
line=line+' border-bottom: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-right: 5px solid green; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipLeftTop .toolTipLeftTopText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent #555 transparent transparent ; ';
line=line+' ';
line=line+' top: 5px; ';
line=line+' right: 100%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-top: 5px solid transparent; ';
line=line+' border-bottom: 5px solid transparent; ';
line=line+' ';
line=line+'/* border-right: 5px solid green; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipLeftCenter .toolTipLeftCenterText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+' border-style: solid; ';
line=line+' border-color: transparent #555 transparent transparent ; ';
line=line+' ';
line=line+' bottom: 50%; ';
line=line+' right: 100%; ';
line=line+' ';
line=line+' width: 0; ';
line=line+' height: 0; ';
line=line+' border-top: 5px solid transparent; ';
line=line+' border-bottom: 5px solid transparent; ';
line=line+' margin-bottom: -5px; ';
line=line+' ';
line=line+'/* border-right: 5px solid green; */ ';
line=line+'} ';
line=line+' ';
line=line+'.toolTipNone .toolTipNoneText::after { ';
line=line+' content: ""; ';
line=line+' position: absolute; ';
line=line+'} ';
style.innerHTML = line
document.getElementsByTagName('head')[0].appendChild(style);
/////
var bubble_top_data = 'data:image/gif;base64,'+
'R0lGODlhkwAQANUxAP7+/sHBwePj4+Hh4eXl5XZ2dmdnZ7q6urOzs+zs7KSkpHR0dNfX15ubm7u7'+
'u4CAgKqqqo6Ojurq6rKyssrKyu/v73l5efr6+vv7+/Ly8vb29v39/Wtra6Ghoff392VlZZOTk9bW'+
'1oqKiufn52lpadPT0/n5+ZWVlbGxscDAwM7Ozvj4+Ovr6+jo6Ly8vGZmZv///////wAAAAAAAAAA'+
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAADEALAAAAACTABAAAAb2wJhw'+
'SCwaj8ikcslsOp/QaLFCgUQsnJd2y+16v+CweEwum7kcSwRCqcBgUiJhUmg4GInLe8/v+/+AgYKD'+
'hIWGfRcJDA4NBRMEb3EBDwgCh5eYmZqbhgIIDwEAcE8SBgoDnKmqq6yAAwoGEqNMAgsHrbi5upgH'+
'CwMATBILAbvFxsd7AQsjwEoGt8jR0qwHBh7NRwEK09zdmgooGhtHBA+o3ujpgQMPKhrYQxMI6vT1'+
'ewgnBCuiQxUFlvYCohNQIAALDNgoNBDI0FsDECEyjBMCwUHDi9IcFHBBwMSQCAwwijTGgESHEhmG'+
'WEgwsmWuBB9EpGiBAUYQADs=';
var bubble_middle_data = 'data:image/gif;base64,'+
'R0lGODlhkwA8AKIGAL+/v4CAgOrq6lVVVWZmZv///////wAAACH5BAEAAAYALAAAAACTADwAAAPp'+
'aFTc/jDKSau9OOtGRgBCoWxkaZ4o2n3hmL5wLF8rKC5zru9m3eK8oHDI8dhcxKQy5rstn9BSExmt'+
'WiNT4HV7zXK/Vi94vBSTz0Izep1Ts98vN3wuNf7o+J7dme9n5H6BEICChQWEhoGIiX2LjHiOj3OR'+
'km+UlWuXmGeam2Odnl+goVujpGF7VKdwpqtQra5lqVqxmbO1rLe4bLC7abq+nMDBn8PEosbHpcnK'+
'qCx8zVy90UzM1E/T1ynZ2ifc3XXPquBK3+Qa5ucY6eoW7O0U7/AS8vOD1vYz9flF4rT8bfABjCNw'+
'oIo9CQAAOw==';
var bubble_bottom_data = 'data:image/gif;base64,'+
'R0lGODlhkwAtAPetAEBAQICAgOrq6lVVVb+/v2ZmZkFBQf39/fr6+vj4+Pv7+/n5+UpKSp6enuzs'+
'7PLy8uXl5UNDQ0JCQqqqqlZWVkZGRt3d3fX19VJSUsLCwkRERFxcXF5eXvb29sTExOvr68vLy9TU'+
'1LOzs2pqauPj42hoaHR0dIqKiunp6VNTU+3t7Wtra+Hh4UdHR7q6uklJScDAwHZ2dpKSkvz8/EVF'+
'RW1tbXh4eKGhoU9PT4mJiWVlZU1NTWJiYq2trejo6Jubm9fX166uroyMjNvb26SkpISEhHp6enNz'+
'c2FhYVhYWHx8fN/f3/T09FRUVH9/f3d3d8XFxVFRUWdnZ+Dg4NbW1t7e3vDw8O/v74GBgbu7u05O'+
'TtPT06Wlpby8vO7u7vPz82xsbLCwsFdXV4ODg3BwcOfn59nZ2bKyspGRkb29vUtLS8bGxsrKysHB'+
'wfHx8f7+/ubm5q+vr3JyclBQUHl5eUxMTIeHh9zc3GBgYLi4uM7OzpOTk11dXWRkZL6+vpSUlI6O'+
'jtXV1aOjo4WFhZCQkFlZWWlpaX5+fltbW5WVlbe3t29vb3t7e+Tk5FpaWpeXl6mpqZiYmNHR0XFx'+
'cdra2rS0tJ2dnc3NzZycnKKioo2NjcfHx4iIiLGxsYuLi+Li4qurq6ysrNLS0rm5uZaWll9fX2Nj'+
'Y319fcPDw6CgoMnJydDQ0P///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAK0ALAAAAACTAC0A'+
'AAj/AFutQMCqoMGDCBMqXMiwocOHECNKnMgKgY4BAQgIYNWKjgOKIEOKHElSpAMkGDVyBASkpMuX'+
'MGM+BLKBQkYBrVpNyCKzp8+fIbNQoIAFBs5WbH4AXcq0qcEfWpIUyeAg55UYJJxq3eqSRIwWG3Ks'+
'UZGz1RkRXNOqlSgiRQUeMkBYKQshAIu1ePMeZBGgBYMRDUIwKdsqDRG9iNcSwSEBw5MeFhIQRiDF'+
'ReLLTl1IMdCCwwkYPhQQbrXERBvMqH22MUFDAg4yN7Y8eDN6gR4TllPrLunCRAsDL/Cc6AJhwehW'+
'Bx5skkLk7u7nElkQkULDQAUxRiZQeXDgeCsFH9hw/wogIiv08wpJiAiAA4D1AUcagPiggLb3BBA8'+
'yAAT40cWIA4QhF5qCDgARBY/xOCWARK8IMYRP3gAQQL2eddKByR40IANPGzAARI6FCDiiCSWaOKJ'+
'KKaoYoorCBHKElpNIYIQBeiAxAYD7BABgy3ggIcRDXhAQgcWEnZABxCAMMEJZHCAAQMV7GgAAFRW'+
'aeWVWGap5ZZcXtkgBhyM4cEBQIEwSClNvFClAQZEUAEDYJJxwgQgQNBBd0USlsAHVHRxwwlPjNBh'+
'EkMNYOihiCaq6KKMNuqook2kkAIiTgzR0xBOOKImgzQwgEMKYmzAwwhPnHBDF1R8IFmexynwAARb'+
'wP/QQwMy5FAEFgHkquuuvPbq66/ABuvrIUaYMAISJYRBpksJTMDHDu5pwEAKHBhighJj5CBDAz3A'+
'sAUED4jGqncHLPCADxaEAMIaGcBAwLvwxivvvPTWa++99KaRx6xCPFFAJAKOpAIWTUjQJgMD6GCD'+
'J9yOAsMaIIRggQ8PLIDnuEUqkAATVqjggAAghyzyyCSXbPLJKJeMAgoQVBGCB2GQsgggAYNkxhEY'+
'uNdCFKYwkkgQqGxRBRwCqGAFEwmIi/HSTDft9NPILcDEB1WwEYcNiSxLUQgrQBsBA4XIQUgcqlgg'+
'wBcWQ6322my3fUACXtzRxiFBgBTCCGoYoMEOPDj/cUMGd6iQwMVtF2744UXOcAEcUNgQwkRA4K33'+
'HCXkEMcqPtyJ+Oacd77AB2HEkEBEKCxShwE0YLACIXmYcQUCnccue+EFPlL3Qw8oEYXeGNTwRxpV'+
'fDHD7MQX7zQCjYyAgkMHoNEEABrMAcYfBLBwAeHGZ6/9cQsEIYhDZ1AAQARaGCKDH9Zjv/3627ux'+
'ghsMDVFCBBLU0YcQLixxPfv8s38AKGdYCAKUsAPgcKAIIhjCF9TXvwbOrgxGWMgEKGCdJDBiAoFw'+
'w/AcyEHjjQFGCLFACSQQgShMogGXcIDSOsjC2LkAEghRwCm0YAA16AANGYCDcVrIw845wAYIUQQF'+
'yCvgCCyIwAIX6KESOUeHDxjkCjXQQAnlkAlJWIGBS8zi01IBBYNwAQMGYEAfcOgD2GnxjGvLwPdY'+
'8YkSoC4JTuiEBYiExjo+bQqDKMgeEKEBLdTAEnq4AhbtSEjvIGAFB5gCGDbAAD7YoQuN2GEhJ8kq'+
'JaBgD0UoQSGOwIVAPICSoMxTEBSBCS7EoAaayAAKVhjKVuZEBTUQRSVyYIcJmCGJrsxlWTpQBg/c'+
'gAtQEMAGdalLL1DBD1BAIjGXeYEyUGIKXhhm9gICADs=';
var style = document.createElement('style');
style.type = 'text/css';
line="";
line=line+"#bubble_tooltip{ ";
line=line+"width:147px; ";
line=line+"position:absolute; ";
line=line+"display:none; ";
line=line+"} ";
line=line+"#bubble_tooltip .bubble_top{ ";
//line=line+"background-image: url('../Add-ins/bubble_top.gif'); ";
line=line+"background-image: url("+bubble_top_data+"); ";
line=line+"background-repeat:no-repeat; ";
line=line+"height:16px; ";
line=line+"} ";
line=line+"#bubble_tooltip .bubble_middle{ ";
//line=line+"background-image: url('../Add-ins/bubble_middle.gif'); ";
line=line+"background-image: url("+bubble_middle_data+"); ";
line=line+"background-repeat:repeat-y; ";
line=line+"background-position:bottom left; ";
line=line+"padding-left:7px; ";
line=line+"padding-right:7px; ";
line=line+"} ";
line=line+"#bubble_tooltip .bubble_middle span{ ";
line=line+"position:relative; ";
line=line+"top:-8px; ";
line=line+"font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; ";
line=line+"font-size:11px; ";
line=line+"} ";
line=line+"#bubble_tooltip .bubble_bottom{ ";
//line=line+"background-image: url('../Add-ins/bubble_bottom.gif'); ";
line=line+"background-image: url("+bubble_bottom_data+"); ";
line=line+"background-repeat:no-repeat; ";
line=line+"background-repeat:no-repeat; ";
line=line+"height:44px; ";
line=line+"position:relative; ";
line=line+"top:-6px; ";
line=line+"} ";
style.innerHTML = line
document.getElementsByTagName('head')[0].appendChild(style);
/////
function createCursorDiv(config) {
if (cursorDivCreated == false) {
cursorDivCreated=true;
if(annotate_shape=="bubble_tooltip") {
var div = document.createElement('div');
div.id = 'bubble_tooltip';
document.body.appendChild(div);
var subdiv1 = document.createElement('div');
subdiv1.id = 'bubble_top';
subdiv1.className = 'bubble_top';
div.appendChild(subdiv1);
var subdiv2 = document.createElement('div');
subdiv2.id = 'bubble_middle';
subdiv2.className = 'bubble_middle';
div.appendChild(subdiv2);
var subdiv3 = document.createElement('div');
subdiv3.id = 'bubble_bottom';
subdiv3.className = 'bubble_bottom';
div.appendChild(subdiv3);
var spa = document.createElement('span');
spa.id = "bubble_tooltip_content";
subdiv2.appendChild(spa);
} else if(annotate_shape == "ARROW") {
updateClass(".toolTipTopRight","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipTopLeft","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipTopCenter","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipBottomRight","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipBottomLeft","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipBottomCenter","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipRightTop","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipRightBottom","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipRightCenter","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipLeftTop","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipLeftBottom","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipLeftCenter","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipNone","font-size:"+config.annotateFontSize+"pt;font-style:"+config.annotateFontStyle+";font-family:"+config.annotateFontFamily+";background-color:"+config.annotateBackgroundColor+";padding:"+config.annotatePadding+"; border-style: "+config.annotateBorder+"; border-radius:"+config.annotateBorderRadius+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipTopRight .toolTipTopRightText::after","border-bottom: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipTopLeft .toolTipTopLeftText::after","border-bottom: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipTopCenter .toolTipTopCenterText::after","border-bottom: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipBottomRight .toolTipBottomRightText::after","border-top: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipBottomLeft .toolTipBottomLeftText::after","border-top: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipBottomCenter .toolTipBottomCenterText::after","border-top: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipRightTop .toolTipRightTopText::after","border-left: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipRightBottom .toolTipRightBottomText::after","border-left: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipRightCenter .toolTipRightCenterText::after","border-left: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipLeftTop .toolTipLeftTopText::after","border-right: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipLeftBottom .toolTipLeftBottomText::after","border-right: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipLeftCenter .toolTipLeftCenterText::after","border-right: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
updateClass(".toolTipNone .toolTipNoneText::after","border-right: 5px solid " +config.annotateBackgroundColor+"; color:"+config.annotateFontColor+";");
var div = document.createElement(annotate_shape);
div.id = annotate_shape;
div.style.position = 'absolute';
document.body.appendChild(div);
var spa = document.createElement('span');
spa.id = "arrow_content";
div.appendChild(spa);
} else {
var div = document.createElement(annotate_shape);
div.id = annotate_shape;
div.style.position = 'absolute';
document.body.appendChild(div);
}
}
};
function updateClass(name,rules){
var style = document.createElement('style');
style.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(style);
if(!(style.sheet||{}).insertRule) (style.styleSheet || style.sheet).addRule(name, rules);
else style.sheet.insertRule(name+"{"+rules+"}",0);
}
function initAnnotateDiv(annotateDIV,config,ctx) {
if(annotate_shape == "ARROW") {
} else if(annotate_shape!='divCursor'){
annotateDIV.className = annotate_shape;
annotateDIV.style.border = '' ;
annotateDIV.style.padding = '' ;
annotateDIV.style.borderRadius = '';
annotateDIV.style.backgroundColor = '' ;
annotateDIV.style.color = '' ;
annotateDIV.style.fontFamily = '' ;
annotateDIV.style.fontSize = '' ;
annotateDIV.style.fontStyle = '' ;
} else {
annotateDIV.className = (config.annotateClassName) ? config.annotateClassName : '';
annotateDIV.style.border = (config.annotateClassName) ? '' : config.annotateBorder;
annotateDIV.style.padding = (config.annotateClassName) ? '' : config.annotatePadding;
annotateDIV.style.borderRadius = (config.annotateClassName) ? '' : config.annotateBorderRadius;
annotateDIV.style.backgroundColor = (config.annotateClassName) ? '' : config.annotateBackgroundColor;
annotateDIV.style.color = (config.annotateClassName) ? '' : config.annotateFontColor;
annotateDIV.style.fontFamily = (config.annotateClassName) ? '' : config.annotateFontFamily;
annotateDIV.style.fontSize = (config.annotateClassName) ? '' : (Math.ceil(ctx.chartTextScale*config.annotateFontSize)).toString() + "pt";
annotateDIV.style.fontStyle = (config.annotateClassName) ? '' : config.annotateFontStyle;
}
annotateDIV.style.zIndex = 999;
};
function displayAnnotate(ctx,data,config,rect,event,annotateDIV,jsGraphAnnotate,piece,myStatData,statData) {
var arrow_class;
var dispString,newPosX,newPosY,decalX,decalY;
var addDecalX,addDecalY;
decalX=0;
decalY=0;
if(typeof config.annotatePaddingX==="number") addDecalX=1*config.annotatePaddingX;
else addDecalX=fromLeft;
if(typeof config.annotatePaddingY==="number") addDecalY=1*config.annotatePaddingY;
else addDecalY=fromTop;
if (jsGraphAnnotate[ctx.ChartNewId][piece.piece][0] == "ARC") dispString = tmplbis(setOptionValue(true,true,1,"ANNOTATELABEL",ctx,data,jsGraphAnnotate[ctx.ChartNewId][piece.piece][3],undefined,config.annotateLabel,"annotateLabel",jsGraphAnnotate[ctx.ChartNewId][piece.piece][1],-1,{otherVal:true}), myStatData,config);
else dispString = tmplbis(setOptionValue(true,true,1,"ANNOTATELABEL",ctx,data,jsGraphAnnotate[ctx.ChartNewId][piece.piece][3],undefined,config.annotateLabel,"annotateLabel",jsGraphAnnotate[ctx.ChartNewId][piece.piece][1],jsGraphAnnotate[ctx.ChartNewId][piece.piece][2],{otherVal:true}), myStatData,config);
if(annotate_shape=="bubble_tooltip") {
document.getElementById('bubble_tooltip_content').innerHTML = dispString;
annotateDIV.style.display='block';
var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)st=0;
var leftPos = event.clientX - 100;
if(leftPos<0)leftPos = 0;
annotateDIV.style.left = leftPos+'px';
annotateDIV.style.top = event.clientY - annotateDIV.offsetHeight -1 + st + 'px';
} else if(annotate_shape == "ARROW") {
document.getElementById('arrow_content').innerHTML = dispString;
} else {
annotateDIV.innerHTML = dispString;
}
if(annotate_shape=="bubble_tooltip") {
var textMsr={textHeight: 100, textWidth : 147};
} else {
var textMsr={};
annotateDIV.style.display = true ? '' : 'none';
var lrect = annotateDIV.getBoundingClientRect();
textMsr.textHeight=lrect.height;
textMsr.textWidth=lrect.width;
}
ctx.restore();
// set position;
var x,y;
x = bw.ns4 || bw.ns5 ? event.pageX : event.x;
y = bw.ns4 || bw.ns5 ? event.pageY : event.y;
if (bw.ie4 || bw.ie5) y = y + eval(scrolled);
if(config.annotateRelocate===true && (typeof config.annotatePosition)=="undefined" || config.annotatePosition=="mouse") {
var relocateX, relocateY;
relocateX=0;relocateY=0;
if(x+fromLeft+textMsr.textWidth > window.innerWidth-rect.left-fromLeft)relocateX=-textMsr.textWidth;
if(y+fromTop+textMsr.textHeight > 1*window.innerHeight-1*rect.top+fromTop)relocateY-=(textMsr.textHeight+2*fromTop);
newPosX=Math.max(8-rect.left,x + fromLeft+relocateX);
newPosY=Math.max(8-rect.top,y + fromTop + relocateY);
} else {
newPosX=x;
newPosY=y;
}
var mouse_posrect = getMousePos(ctx.canvas, event);
var vj;
var debj=piece.j;
var endj=piece.j+1;
var refpiecei=piece.i;
var refpiecej=piece.j;
var rayVal=-1;
var midPosX=0;
var midPosY=0;
var minDecalY,minDecalX,maxDecalY,maxDecalX,maxRayVal,minRayVal;
var angle=9999;
var minAngle, maxAngle;
var forceY=false;
var forceX=false;
var multX=0;
var multY=0;
tpchart=ctx.tpchart;
if(data.datasets[piece.i].type=="Line" && (ctx.tpchart=="Bar" || ctx.tpchart=="StackedBar"))tpchart="Line";
switch(config.annotatePositionAngle) {
case "center" :
case "middle" :
switch(tpchart) {
case "Pie" :
case "Doughnut" :
case "PolarArea" :
angle=(myStatData.startAngle+myStatData.endAngle)/2;
break;
default:
break;
}
break;
case "start" :
switch(tpchart) {
case "Pie" :
case "Doughnut" :
case "PolarArea" :
angle=myStatData.startAngle;
break;
default:
break;
}
break;
case "end" :
switch(tpchart) {
case "Pie" :
case "Doughnut" :
case "PolarArea" :
angle=myStatData.endAngle;
break;
default:
break;
}
break;
default:
switch(tpchart) {
case "Pie" :
case "Doughnut" :
case "PolarArea" :
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
if(midPosX == mouse_posrect.x && midPosX > mouse_posrect.y) angle=Math.PI/2;
else if(midPosX == mouse_posrect.x && midPosX > mouse_posrect.y) angle=-Math.PI/2;
else angle=Math.atan((midPosY-mouse_posrect.y)/(midPosX-mouse_posrect.x));
if(midPosX>mouse_posrect.x)angle+=Math.PI;
break;
default:
break;
}
break;
}
switch(config.annotatePositionRadius) {
case "MXout" :
case "Xout" :
switch(tpchart) {
case "Radar" :
decalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
decalX=myStatData.posX-mouse_posrect.x;
var refVal=myStatData.datavalue;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionRadius=="MXout"){debj=0;endj=statData[i].length;}
for(j=debj;j<endj;j++) {
if (refVal<statData[i][j].datavalue) {
refVal=statData[i][j].datavalue;
decalY=statData[i][j].posY-mouse_posrect.y - textMsr.textHeight;
decalX=statData[i][j].posX-mouse_posrect.x;
}
}
};
debj=piece.j;endj=piece.j+1;
break;
case "Pie" :
case "Doughnut" :
case "PolarArea" :
multX=1;
multY=1;
rayVal=myStatData.radiusOffset;
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionRadius=="MXout"){debj=0;endj=statData[i].length;}
for(j=0;j<data.labels.length;j++) {
rayVal=Math.max(rayVal,statData[i][j].radiusOffset);
}
};
debj=piece.j;endj=piece.j+1;
break;
default:
break;
};
break;
case "MXin" :
case "Xin" :
switch(tpchart) {
case "Radar" :
decalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
decalX=myStatData.posX-mouse_posrect.x;
var refVal=myStatData.datavalue;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionRadius=="MXin"){debj=0;endj=statData[i].length;}
for(j=debj;j<endj;j++) {
if (refVal>statData[i][j].datavalue) {
refVal=statData[i][j].datavalue;
decalY=statData[i][j].posY-mouse_posrect.y - textMsr.textHeight;
decalX=statData[i][j].posX-mouse_posrect.x;
}
}
};
debj=piece.j;endj=piece.j+1;
break;
case "Pie" :
case "Doughnut" :
case "PolarArea" :
multX=2;
multY=2;
rayVal=myStatData.int_radius;
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionRadius=="MXin"){debj=0;endj=statData[i].length;}
for(j=0;j<data.labels.length;j++) {
rayVal=Math.min(rayVal,statData[i][j].int_radius);
}
};
debj=piece.j;endj=piece.j+1;
break;
default:
break;
};
break;
case "in" :
switch(tpchart) {
case "Radar" :
decalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
decalX=myStatData.posX-mouse_posrect.x;
break;
case "Pie" :
case "Doughnut" :
case "PolarArea" :
multX=2;
multY=2;
rayVal=myStatData.int_radius;
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
break;
default:
break;
};
break;
case "out" :
switch(tpchart) {
case "Radar" :
decalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
decalX=myStatData.posX-mouse_posrect.x;
break;
case "Pie" :
case "Doughnut" :
case "PolarArea" :
multX=1;
multY=1;
rayVal=myStatData.radiusOffset;
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
break;
default:
break;
};
break;
case "MXcenter" :
case "MXmiddle" :
case "Lcenter" :
case "Lmiddle" :
switch(tpchart) {
case "Radar" :
minDecalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
minDecalX=myStatData.posX-mouse_posrect.x;
maxDecalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
maxDecalX=myStatData.posX-mouse_posrect.x;
var minRefVal=myStatData.datavalue;
var maxRefVal=myStatData.datavalue;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionRadius=="MXcenter" || config.annotatePositionRadius=="MXmiddle"){debj=0;endj=statData[i].length;}
for(j=debj;j<endj;j++) {
if (minRefVal>statData[i][j].datavalue) {
minRefVal=statData[i][j].datavalue;
minDecalY=statData[i][j].posY-mouse_posrect.y - textMsr.textHeight;
minDecalX=statData[i][j].posX-mouse_posrect.x;
}
if (maxRefVal<statData[i][j].datavalue) {
maxRefVal=statData[i][j].datavalue;
maxDecalY=statData[i][j].posY-mouse_posrect.y - textMsr.textHeight;
maxDecalX=statData[i][j].posX-mouse_posrect.x;
}
}
};
decalY=(maxDecalY+minDecalY)/2;
decalX=(maxDecalX+minDecalX)/2;
debj=piece.j;endj=piece.j+1;
break;
case "Pie" :
case "Doughnut" :
case "PolarArea" :
multX=3;
multY=3;
maxRayVal=myStatData.radiusOffset;
minRayVal=myStatData.int_radius;
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionRadius=="MXcenter" || config.annotatePositionRadius=="MXmiddle"){debj=0;endj=statData[i].length;}
for(j=debj;j<endj;j++) {
if (minRayVal>statData[i][j].int_radius) {
minRayVal=statData[i][j].int_radius;
}
if (maxRayVal<statData[i][j].radiusOffset) {
maxRayVal=statData[i][j].radiusOffset;
}
}
rayVal=(maxRayVal+minRayVal)/2;
};
break;
default:
break;
};
break;
case "center" :
case "middle" :
switch(tpchart) {
case "Radar" :
decalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
decalX=myStatData.posX-mouse_posrect.x;
break;
case "Pie" :
case "Doughnut" :
case "PolarArea" :
multX=3;
multY=3;
rayVal=(myStatData.int_radius+myStatData.radiusOffset)/2;
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
break;
default:
break;
};
break;
default:
switch(tpchart) {
case "Radar" :
decalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
decalX=myStatData.posX-mouse_posrect.x;
break;
case "Pie" :
case "Doughnut" :
case "PolarArea" :
midPosX=myStatData.midPosX;
midPosY=myStatData.midPosY;
rayVal=Math.sqrt(Math.pow(myStatData.midPosX-mouse_posrect.x,2)+Math.pow(myStatData.midPosY-mouse_posrect.y,2));
break;
default:
break;
};
break;
}
switch(config.annotatePositionY) {
case "LXtop" :
switch(tpchart) {
case "Line" :
decalY=statData[piece.i][piece.j].posY-mouse_posrect.y - 1*textMsr.textHeight;
for(vj=0;vj<statData[piece.i].length;vj++) decalY=Math.min(decalY,statData[piece.i][vj].posY-mouse_posrect.y - 1*textMsr.textHeight);
break;
default:
break;
}
if(tpchart=="Line") break;
case "MXtop" :
case "Xtop" :
case "SXtop" :
switch(tpchart) {
case "StackedBar" :
case "Bar" :
if(myStatData.datavalue>=0) {
decalY=myStatData.yPosTop-mouse_posrect.y - textMsr.textHeight
for(i=0;i<data.datasets.length;i++) {
if(statData[i][0].tpchart!="Line") {
if(config.annotatePositionY=="MXtop") {debj=0;endj=statData[i].length}
for(vj=debj;vj<endj;vj++)decalY=Math.min(decalY,statData[i][vj].yPosTop-mouse_posrect.y - textMsr.textHeight);
}
}
}
else {
if(config.annotatePositionY=="SXtop") {
addDecalY=-addDecalY;
for(i=0;i<data.datasets.length;i++) {
if(statData[i][0].tpchart!="Line")decalY=Math.max(decalY,statData[i][piece.j].yPosTop-mouse_posrect.y + 0*textMsr.textHeight);
}
} else {
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionY=="MXtop") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++) if(statData[i][0].tpchart!="Line")decalY=Math.min(decalY,Math.min(statData[i][vj].yPosTop,statData[i][vj].yPosBottom)-mouse_posrect.y - 1*textMsr.textHeight);
}
}
} ;
break;
case "Line" :
decalY=statData[piece.i][piece.j].posY-mouse_posrect.y - 1*textMsr.textHeight;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionY=="MXtop") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++) decalY=Math.min(decalY,statData[i][vj].posY-mouse_posrect.y - 1*textMsr.textHeight);
}
break;
default:
break;
}
if(tpchart=="StackedBar" || tpchart=="Bar" || tpchart=="Line") break;
case "top" :
case "Stop" :
switch(tpchart) {
case "StackedBar" :
case "Bar" :
if(myStatData.datavalue>=0) decalY=myStatData.yPosTop-mouse_posrect.y - textMsr.textHeight;
else {
if (config.annotatePositionY=="Stop" || config.annotatePositionY=="SXtop") { decalY=myStatData.yPosTop-mouse_posrect.y + 0*textMsr.textHeight; addDecalY=-addDecalY; }
else {decalY=myStatData.yPosBottom-mouse_posrect.y - textMsr.textHeight;}
}
break;
case "HorizontalBar" :
case "HorizontalStackedBar" :
decalY=myStatData.yPosTop-mouse_posrect.y - textMsr.textHeight;
if(config.annotatePositionY=="Stop") {
var lrect = ctx.canvas.getBoundingClientRect();
if(mouse_posrect.y<(lrect.height/2)) {
decalY=myStatData.yPosBottom-mouse_posrect.y - 0*textMsr.textHeight;
}
};
break;
case "Radar" :
break;
case "Line" :
decalY=myStatData.posY-mouse_posrect.y - textMsr.textHeight;
break;
default:
break;
};
break;
case "LXbottom" :
switch(tpchart) {
case "Line" :
decalY=statData[piece.i][piece.j].posY-mouse_posrect.y - 1*textMsr.textHeight;
for(vj=0;vj<statData[piece.i].length;vj++) decalY=Math.max(decalY,statData[piece.i][vj].posY-mouse_posrect.y - 1*textMsr.textHeight);
break;
default:
break;
}
if(tpchart=="Line") break;
case "MXbottom" :
case "Xbottom" :
case "SXbottom" :
switch(tpchart) {
case "StackedBar" :
case "Bar" :
if(myStatData.datavalue>=0) {
decalY=myStatData.yPosBottom-mouse_posrect.y + 0*textMsr.textHeight;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionY=="MXbottom") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++) {
if(statData[i][vj].datavalue>=0 || config.annotatePositionY=="Xbottom" || config.annotatePositionY=="MXbottom" ) {
if(statData[i][0].tpchart!="Line")decalY=Math.max(decalY,Math.max(statData[i][vj].yPosTop,statData[i][vj].yPosBottom)-mouse_posrect.y + 0*textMsr.textHeight);
}
}
}
}
else {
if (config.annotatePositionY=="SXbottom") {
addDecalY=-addDecalY;
decalY=myStatData.yPosBottom-mouse_posrect.y - textMsr.textHeight;
for(i=0;i<data.datasets.length;i++) {
if(statData[i][piece.j].datavalue<0) {
if(statData[i][0].tpchart!="Line")decalY=Math.min(decalY,statData[i][piece.j].yPosBottom-mouse_posrect.y - textMsr.textHeight);
}
}
} else {
decalY=myStatData.yPosTop-mouse_posrect.y + 0*textMsr.textHeight;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionY=="MXbottom") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++) {
if(statData[i][vj].datavalue<0) {
if(statData[i][0].tpchart!="Line")decalY=Math.max(decalY,statData[i][vj].yPosTop-mouse_posrect.y + 0*textMsr.textHeight);
}
}
}
}
} ;
break;
case "Line" :
decalY=statData[piece.i][piece.j].posY-mouse_posrect.y - 1*textMsr.textHeight;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionY=="MXbottom") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++) decalY=Math.max(decalY,statData[i][vj].posY-mouse_posrect.y - 1*textMsr.textHeight);
}
break;
default:
break;
}
if(tpchart=="StackedBar" || tpchart=="Bar" || tpchart=="Line") break;
case "bottom" :
case "Sbottom" :
switch(tpchart) {
case "StackedBar" :
case "Bar" :
if(myStatData.datavalue>=0) decalY=myStatData.yPosBottom-mouse_posrect.y + 0*textMsr.textHeight;
else {
if (config.annotatePositionY=="Sbottom" || config.annotatePositionY=="SXbottom") {decalY=myStatData.yPosBottom-mouse_posrect.y - textMsr.textHeight; addDecalY=-addDecalY; }
else decalY=myStatData.yPosTop-mouse_posrect.y + 0*textMsr.textHeight;
}
break;
case "HorizontalBar" :
case "HorizontalStackedBar" :
decalY=myStatData.yPosBottom-mouse_posrect.y - 0*textMsr.textHeight;
if(config.annotatePositionY=="Sbottom") {
var lrect = ctx.canvas.getBoundingClientRect();
if(mouse_posrect.y<(lrect.height/2)) {
decalY=myStatData.yPosTop-mouse_posrect.y - textMsr.textHeight;
}
};
break;
case "Radar" :
decalY+=textMsr.textHeight;
break;
case "Line" :
decalY=myStatData.posY-mouse_posrect.y - 0*textMsr.textHeight;
break;
default :
break;
};
break;
case "Xcenter" :
case "Xmiddle" :
switch(tpchart) {
case "HorizontalBar" :
var mtop=Math.min(statData[piece.i][piece.j].yPosTop,statData[piece.i][piece.j].yPosBottom);
var mbottom=Math.max(statData[piece.i][piece.j].yPosTop,statData[piece.i][piece.j].yPosBottom);
for(i=0;i<data.datasets.length;i++) {
if(statData[i][0].tpchart!="Line"){
mtop=Math.min(mtop,statData[i][piece.j].yPosTop,statData[i][piece.j].yPosBottom);
mbottom=Math.max(mbottom,statData[i][piece.j].yPosTop,statData[i][piece.j].yPosBottom);
}
}
decalY=(mtop+mbottom)/2 - mouse_posrect.y - 0.5*textMsr.textHeight;
break;
default:
break;
};
if(tpchart=="HorizontalBar") break;
case "center" :
case "middle" :
switch(tpchart) {
case "Bar" :
case "StackedBar" :
if(myStatData.datavalue>=0) decalY=(myStatData.yPosBottom+myStatData.yPosTop)/2-mouse_posrect.y - 0.5*textMsr.textHeight;
else decalY=(myStatData.yPosBottom+myStatData.yPosTop)/2-mouse_posrect.y - 0.5*textMsr.textHeight;
break;
case "HorizontalBar" :
case "HorizontalStackedBar" :
decalY=(myStatData.yPosBottom+myStatData.yPosTop)/2-mouse_posrect.y - 0.5*textMsr.textHeight;
break;
case "Radar" :
decalY+=0.5*textMsr.textHeight;
break;
case "Line" :
decalY=myStatData.posY-mouse_posrect.y - 0.5*textMsr.textHeight;
break;
default :
break;
};
break;
default:
if(typeof config.annotatePositionY==="number") {
var lrect = ctx.canvas.getBoundingClientRect();
decalY=-newPosY+1*config.annotatePositionY+lrect.top+window.pageYOffset;
forceY=true;
} else if (typeof config.annotatePositionY!="undefined" && config.annotatePositionY.indexOf("%")>0) {
var lrect = ctx.canvas.getBoundingClientRect();
var pct=1*config.annotatePositionY.substr(0,config.annotatePositionY.indexOf("%"));
decalY=-newPosY+(1*ctx.canvas.height*pct/100)/window.devicePixelRatio+lrect.top+window.pageYOffset;
if(Math.abs(pct-50) < config.zeroValue) {
decalY=decalY-textMsr.textHeight/2;
} else if(pct > 50) {
decalY=decalY-textMsr.textHeight;
}
forceY=true;
}
break;
}
switch(config.annotatePositionX) {
case "MXright" :
case "Xright" :
case "SXright" :
switch(tpchart) {
case "HorizontalStackedBar" :
case "HorizontalBar" :
if(myStatData.datavalue>=0) {
decalX=myStatData.xPosRight-mouse_posrect.x;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionX=="MXright") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++)decalX=Math.max(decalX,statData[i][vj].xPosRight-mouse_posrect.x);
}
} else {
if(config.annotatePositionX=="SXright") {
addDecalX=-addDecalX;
decalX=myStatData.xPosRight-mouse_posrect.x -textMsr.textWidth;
for(i=0;i<data.datasets.length;i++) {
decalX=Math.min(decalX,statData[i][piece.j].xPosRight-mouse_posrect.x -textMsr.textWidth);
}
} else {
decalX=myStatData.xPosLeft-mouse_posrect.x -textMsr.textWidth;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionX=="MXright") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++)decalX=Math.max(decalX,Math.max(statData[i][vj].xPosRight,statData[i][vj].xPosLeft)-mouse_posrect.x + 0*textMsr.textWidth);
}
}
}
break;
case "Line" :
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionY=="MXtop") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++) if(statData[i][0].tpchart!="Line")decalX=Math.min(decalY,statData[i][vj].posX-mouse_posrect.x - 1*textMsr.textWidth);
}
break;
default :
break;
}
if (tpchart=="HorizontalStackedBar" || tpchart=="HorizontalBar")break;
case "right" :
case "Sright" :
switch(tpchart) {
case "Bar" :
case "StackedBar" :
decalX=myStatData.xPosRight-mouse_posrect.x;
if(config.annotatePositionX=="Sright" || config.annotatePositionX=="SXright") {
var lrect = ctx.canvas.getBoundingClientRect();
if(mouse_posrect.x>(lrect.width/2)) {
decalX=myStatData.xPosLeft-mouse_posrect.x-textMsr.textWidth;
}
};
break;
case "HorizontalStackedBar" :
case "HorizontalBar" :
if(myStatData.datavalue>=0) decalX=myStatData.xPosRight-mouse_posrect.x;
else {
if(config.annotatePositionX=="SXright" || config.annotatePositionX=="Sright") {
decalX=myStatData.xPosRight-mouse_posrect.x -textMsr.textWidth;
addDecalX=-addDecalX;
} else {
decalX=myStatData.xPosLeft-mouse_posrect.x ;
}
}
break;
case "Radar" :
break;
case "Line" :
decalX=myStatData.xPos-mouse_posrect.x;
break;
default :
break;
};
break;
case "MXleft" :
case "SXleft" :
case "Xleft" :
switch(tpchart) {
case "HorizontalStackedBar" :
case "HorizontalBar" :
if(myStatData.datavalue>=0) {
decalX=myStatData.xPosLeft-mouse_posrect.x-textMsr.textWidth;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionX=="MXleft") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++) {
if(config.annotatePositionX=="Xleft" || config.annotatePositionX=="MXleft") {
decalX=Math.min(decalX,Math.min(statData[i][vj].xPosLeft,statData[i][vj].xPosRight)-mouse_posrect.x-textMsr.textWidth);
} else if(statData[i][vj].datavalue>0) {
decalX=Math.min(decalX,Math.min(statData[i][vj].xPosLeft,statData[i][vj].xPosRight)-mouse_posrect.x-textMsr.textWidth);
}
}
}
} else {
if(config.annotatePositionX=="SXleft") {
addDecalX=-addDecalX;
decalX=myStatData.xPosLeft-mouse_posrect.x ;
for(i=0;i<data.datasets.length;i++) {
if(statData[i][piece.j].datavalue<0) {
decalX=Math.max(decalX,statData[i][piece.j].xPosLeft-mouse_posrect.x);
}
}
} else {
decalX=myStatData.xPosLeft-mouse_posrect.x -textMsr.textWidth;
for(i=0;i<data.datasets.length;i++) {
if(config.annotatePositionX=="MXleft") {debj=0;endj=statData[i].length;}
for(vj=debj;vj<endj;vj++)if(statData[i][vj].datavalue<0)decalX=Math.min(decalX,Math.min(statData[i][vj].xPosLeft,statData[i][vj].xPosRight)-mouse_posrect.x-textMsr.textWidth);
}
}
}
break;
default :
break;
}
if (tpchart=="HorizontalStackedBar" || tpchart=="HorizontalBar")break;
case "Sleft" :
case "left" :
switch(tpchart) {
case "Bar" :
case "StackedBar" :
decalX=myStatData.xPosLeft-mouse_posrect.x-textMsr.textWidth;
if(config.annotatePositionX=="Sleft" || config.annotatePositionX=="SXleft") {
var lrect = ctx.canvas.getBoundingClientRect();
if(mouse_posrect.x>(lrect.width/2)) {
decalX=myStatData.xPosRight-mouse_posrect.x;
}
};
break;
case "HorizontalStackedBar" :
case "HorizontalBar" :
if(myStatData.datavalue>=0) decalX=myStatData.xPosLeft-mouse_posrect.x-textMsr.textWidth;
else {
if(config.annotatePositionX=="Sleft" || config.annotatePositionX=="SXleft"){
decalX=myStatData.xPosLeft-mouse_posrect.x ;
addDecalX=-addDecalX;
} else {
decalX=myStatData.xPosRight-mouse_posrect.x-textMsr.textWidth ;
}
}
break;
case "Radar" :
decalX-=textMsr.textWidth;
break;
case "Line" :
decalX=myStatData.xPos-mouse_posrect.x-textMsr.textWidth;
break;
default:
break;
};
break;
case "Xcenter" :
case "Xmiddle" :
switch(tpchart) {
case "Bar" :
var mright=Math.min(statData[piece.i][piece.j].xPosRight,statData[piece.i][piece.j].xPosLeft);
var mleft=Math.max(statData[piece.i][piece.j].xPosRight,statData[piece.i][piece.j].xPosLeft);
for(i=0;i<data.datasets.length;i++) {
if(statData[i][0].tpchart!="Line"){
mright=Math.min(mright,statData[i][piece.j].xPosRight,statData[i][piece.j].xPosLeft);
mleft=Math.max(mleft,statData[i][piece.j].xPosRight,statData[i][piece.j].xPosLeft);
}
}
decalX=(mright+mleft)/2 - mouse_posrect.x - 0.5*textMsr.textWidth;
break;
default:
break;
};
if(tpchart=="Bar") break;
case "center" :
case "middle" :
switch(tpchart) {
case "Bar" :
case "StackedBar" :
decalX=(myStatData.xPosLeft+myStatData.xPosRight)/2-mouse_posrect.x-textMsr.textWidth/2;
break;
case "HorizontalBar" :
case "HorizontalStackedBar" :
if(myStatData.datavalue>=0) decalX=(myStatData.xPosLeft+myStatData.xPosRight)/2-mouse_posrect.x-textMsr.textWidth/2;
else decalX=(myStatData.xPosLeft+myStatData.xPosRight)/2-mouse_posrect.x - textMsr.textWidth/2 ;
break;
case "Radar" :
decalX-=0.5*textMsr.textWidth;
break;
case "Line" :
decalX=myStatData.xPos-mouse_posrect.x-(textMsr.textWidth/2);
break;
default:
break;
};
break;
default:
if(typeof config.annotatePositionX==="number") {
var lrect = ctx.canvas.getBoundingClientRect();
decalX=-newPosX+1*config.annotatePositionX+lrect.left+window.pageXOffset;
forceX=true;
} else if (typeof config.annotatePositionX !="undefined" && config.annotatePositionX.indexOf("%")>0) {
var pct=1*config.annotatePositionX.substr(0,config.annotatePositionX.indexOf("%"));
decalX=-newPosX+(1*ctx.canvas.width*pct/100)/window.devicePixelRatio+lrect.left+window.pageXOffset;
if(Math.abs(pct-50) < config.zeroValue) {
decalX=decalX-textMsr.textWidth/2;
} else if(pct > 50) {
decalX=decalX-textMsr.textWidth;
}
forceX=true;
}
break;
}
if(tpchart=="Pie" || tpchart=="Doughnut" || tpchart=="PolarArea") {
if(typeof config.annotatePaddingAngle=="number" )angle+=Math.PI*(1*config.annotatePaddingAngle)/180;
if(typeof config.annotatePaddingRadius=="number")rayVal+=(1*config.annotatePaddingRadius);
while(angle<0){angle+=2*Math.PI;}
while(angle>2*Math.PI){angle-=2*Math.PI;}
var lrect = ctx.canvas.getBoundingClientRect();
if(!forceY){
decalY=-newPosY+1*midPosY+lrect.top+window.pageYOffset;
decalY+=rayVal*Math.sin(angle);
}
if(!forceX){
decalX=-newPosX+1*midPosX+lrect.left+window.pageXOffset;
decalX+=rayVal*Math.cos(angle);
}
if(angle>0.5*Math.PI && angle < 1.5*Math.PI) {
if(multX==1){decalX-=textMsr.textWidth;addDecalX=-addDecalX;}
else if(multX==3)decalX-=0.5*textMsr.textWidth;
}
if(angle<=0.5*Math.PI || angle >= 1.5*Math.PI) {
if(multX==2){decalX-=textMsr.textWidth;addDecalX-=addDecalX;}
else if(multX==3)decalX-=0.5*textMsr.textWidth;
}
if(angle>Math.PI) {
if(multY==1){decalY-=textMsr.textHeight;addDecalY=-addDecalY;}
else if(multY==3)decalY-=0.5*textMsr.textHeight;
}
if(angle<=Math.PI) {
if(multY==2){decalY-=textMsr.textHeight;addDecalY=-addDecalY;}
else if(multY==3)decalY-=0.5*textMsr.textHeight;
}
}
if(annotate_shape!='bubble_tooltip') {
if(annotate_shape == "ARROW") {
if(config.annotateClassName =="") {
var lrect = ctx.canvas.getBoundingClientRect();
arrow_class=arrowDirection(newPosX+decalX+addDecalX-(lrect.left+window.pageXOffset), newPosY+decalY+addDecalY-(lrect.top+window.pageYOffset), angle, rayVal, textMsr.textWidth,textMsr.textHeight,ctx,jsGraphAnnotate[ctx.ChartNewId][piece.piece],myStatData);
annotateDIV.className = "toolTip"+arrow_class;
document.getElementById('arrow_content').className="toolTip"+arrow_class+"Text";
} else {
annotateDIV.className = "toolTip"+config.annotateClassName;
document.getElementById('arrow_content').className="toolTip"+config.annotateClassName+"Text";
}
}
oCursor.moveIt(newPosX+decalX+addDecalX, newPosY+decalY+addDecalY);
annotateDIV.style.display = true ? '' : 'none';
}
};
function arrowDirection(x,y,angle,rayVal,width,height,ctx,jsGraphAnnotate,myStatData) {
var h_arrow="Center";
var h_in=true;
var v_arrow="Center";
var v_in=true;
switch(jsGraphAnnotate[0]) {
case "ARC":
return("None");
break;
case "MARC":
var centerPosX=myStatData.midPosX+((myStatData.radiusOffset+myStatData.int_radius)/2)*Math.cos((myStatData.startAngle+myStatData.endAngle)/2);
var centerPosY=myStatData.midPosY+((myStatData.radiusOffset+myStatData.int_radius)/2)*Math.sin((myStatData.startAngle+myStatData.endAngle)/2);
var minDist=Number.MAX_VALUE;
var arrow="None";
var topCenterPos=compAnglPos((2*x+width)/2,y-5,myStatData,centerPosX,centerPosY);
if(topCenterPos.distCenter < minDist){ arrow="TopCenter"; minDist=topCenterPos.distCenter; }
var bottomCenterPos=compAnglPos((2*x+width)/2,y+height+5,myStatData,centerPosX,centerPosY);
if(bottomCenterPos.distCenter < minDist){ arrow="BottomCenter"; minDist=bottomCenterPos.distCenter; }
var topLeftPos=compAnglPos(x+5+2.5,y-5,myStatData,centerPosX,centerPosY);
if(topLeftPos.distCenter < minDist){ arrow="TopLeft"; minDist=topLeftPos.distCenter; }
var topRightPos=compAnglPos(x+width-5-2.5,y-5,myStatData,centerPosX,centerPosY);
if(topRightPos.distCenter < minDist){ arrow="TopRight"; minDist=topRightPos.distCenter; }
var bottomLeftPos=compAnglPos(x+5+2.5,y+height+5,myStatData,centerPosX,centerPosY);
if(bottomLeftPos.distCenter < minDist){ arrow="BottomLeft"; minDist=bottomLeftPos.distCenter; }
var bottomRightPos=compAnglPos(x+width-5-2.5,y+height+5,myStatData,centerPosX,centerPosY);
if(bottomRightPos.distCenter < minDist){ arrow="BottomRight"; minDist=bottomRightPos.distCenter; }
var leftCenterPos=compAnglPos(x-5,(2*y+height)/2,myStatData,centerPosX,centerPosY);
if(leftCenterPos.distCenter < minDist){ arrow="LeftCenter"; minDist=leftCenterPos.distCenter; }
var leftTopPos=compAnglPos(x-5,y+5+2.5,myStatData,centerPosX,centerPosY);
if(leftTopPos.distCenter < minDist){ arrow="LeftTop"; minDist=leftTopPos.distCenter; }
var leftBottomPos=compAnglPos(x-5,y+height-5-2.5,myStatData,centerPosX,centerPosY);
if(leftBottomPos.distCenter < minDist){ arrow="LeftBottom"; minDist=leftBottomPos.distCenter; }
var rightCenterPos=compAnglPos(x+width+5,(2*y+height)/2,myStatData,centerPosX,centerPosY);
if(rightCenterPos.distCenter < minDist){ arrow="RightCenter"; minDist=rightCenterPos.distCenter; }
var rightTopPos=compAnglPos(x+width+5,y+5+2.5,myStatData,centerPosX,centerPosY);
if(rightTopPos.distCenter < minDist){ arrow="RightTop"; minDist=rightTopPos.distCenter; }
var rightBottomPos=compAnglPos(x+width+5,y+height-5-2.5,myStatData,centerPosX,centerPosY);
if(rightBottomPos.distCenter < minDist){ arrow="RightBottom"; minDist=rightBottomPos.distCenter; }
return(arrow);
break;
case "RECT" :
var xright=Math.min(myStatData.xPosRight,myStatData.xPosLeft);
var xleft=Math.max(myStatData.xPosRight,myStatData.xPosLeft);
var ytop=Math.min(myStatData.yPosBottom,myStatData.yPosTop);
var ybottom=Math.max(myStatData.yPosBottom,myStatData.yPosTop);
var minDistance,distance;
var arrow;
arrow="None";
if((2*x+width)/2 > xright && (2*x+width)/2 < xleft) {
if((2*y+height)/2 < (ytop+ybottom)/2) return("BottomCenter");
else return ("TopCenter");
} else if(x > xright+5 && x < xleft-5) {
if((2*y+height)/2 < (ytop+ybottom)/2) return("BottomLeft");
else return ("TopLeft");
} else if(x+width > xright+5 && x+width < xleft-5) {
if((2*y+height)/2 < (ytop+ybottom)/2) return("BottomRight");
else return ("TopRight");
} else if((2*y+height)/2 > ytop && (2*y+height)/2 < ybottom) {
if(x>xleft-5) return("LeftCenter");
else if (x+width < xright+5) return("RightCenter");
else return("None"); // Should never come here;
} else if(y < ybottom -5 && y > ytop+5) {
if(x>xleft-5) return("LeftTop");
else if (x+width < xright+5) return("RightTop");
else return("None"); // Should never come here;
} else if(y+height < ybottom -5 && y+height > ytop+5) {
if(x>xleft-5) return("LeftBottom");
else if (x+width < xright+5) return("RightBottom");
else return("None"); // Should never come here;
}
return("None");
break;
case "POINT" :
var xP=myStatData.posX;
var yP=myStatData.posY;
if(xP>x && xP<x+width && yP>y && yP<y+height)return("None") ;
else if(yP>y+height) {
if(xP>x && xP<x+width) {
if(xP<x+width/4) return("BottomLeft");
else if (xP>x+3*width/4) return("BottomRight");
else return("BottomCenter");
} else return("None")
} else if(yP<y) {
if(xP>x && xP<x+width) {
if(xP<x+width/4) return("TopLeft");
else if (xP>x+3*width/4) return("TopRight");
else return("TopCenter");
} else return("None")
} else if(xP>x+width) {
if(yP>y && yP<y+height) {
if(yP<y+height/4) return("RightTop");
else if (yP>y+3*height/4) return("RightBottom");
else return("RightCenter");
} else return("None")
} else if(xP<x) {
if(yP>y && yP<y+height) {
if(yP<y+height/4) return("LeftTop");
else if (yP>y+3*height/4) return("LeftBottom");
else return("LeftCenter");
} else return("None")
}
return("None");
break;
default:
return("None");
break;
}
};
function inArc(elt,myStatData) {
if(elt.rayVal<=myStatData.radiusOffset && elt.rayVal>=myStatData.int_radius && inAngle(elt.angle,myStatData.startAngle,myStatData.endAngle)) return(true);
else return(false);
};
function inAngle(angle,startAngle,stopAngle){
if(angle>startAngle && angle <stopAngle) return(true);
else if(angle+ 2*Math.PI>startAngle && angle+2*Math.PI <stopAngle) return(true);
else return(false);
};
function compAnglPos(x,y,myStatData,centerX,centerY) {
rayVal=Math.sqrt(Math.pow(x-myStatData.midPosX,2)+Math.pow(y-myStatData.midPosY,2));
angle=Math.acos((x-myStatData.midPosX)/rayVal);
if(y<myStatData.midPosY)angle=2*Math.PI-angle;
if(!inArc({rayVal:rayVal,angle:angle},myStatData)){
distCenter=1000+2*Math.sqrt(Math.pow(myStatData.midPosX-centerX,2)+Math.pow(myStatData.midPosY-centerY,2));
if(rayVal<myStatData.int_radius) {
if(inAngle(angle,myStatData.startAngle,myStatData.endAngle)) distCenter+=(myStatData.int_radius-rayVal);
else {
distCenter*=2;
if(angle<myStatData.startAngle)distCenter+=Math.sqrt(2*rayVal*rayVal*(1-Math.cos(myStatData.startAngle-angle)));
else distCenter+=Math.sqrt(2*rayVal*rayVal*(1-Math.cos(angle-myStatData.endAngle)));
}
} else if(rayVal>myStatData.radiusOffset) {
if(inAngle(angle,myStatData.startAngle,myStatData.endAngle)) distCenter+=(rayVal-myStatData.radiusOffset);
else {
distCenter*=2;
if(angle<myStatData.startAngle)distCenter+=Math.sqrt(2*rayVal*rayVal*(1-Math.cos(myStatData.startAngle-angle)));
else distCenter+=Math.sqrt(2*rayVal*rayVal*(1-Math.cos(angle-myStatData.endAngle)));
}
} else {
distCenter*=2;
if(angle<myStatData.startAngle)distCenter+=Math.sqrt(2*rayVal*rayVal*(1-Math.cos(myStatData.startAngle-angle)));
else distCenter+=Math.sqrt(2*rayVal*rayVal*(1-Math.cos(angle-myStatData.endAngle)));
}
} else distCenter=Math.sqrt(Math.pow(x-centerX,2)+Math.pow(y-centerY,2));
return { angle:angle, rayVal: rayVal, distCenter : distCenter};
};
|
(function () {
'use strict';
angular.module('MISTTSolution', ['ui.bootstrap'])
.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('/$/');
$interpolateProvider.endSymbol('/$/');
})
.controller('IndexController', function ($scope, $http, $log) {
$scope.refreshSessionsLoading = false;
$scope.cases_count = 0;
$scope.users_count = 0;
$scope.closeouts_count = 0;
$scope.interactions_count = 0;
$scope.service_plans_count = 0;
$scope.interview_7_days_count = 0;
$scope.pages_count = 0;
$scope.sessions_count = 0;
$scope.interview_90_days_count = 0;
$scope.biopsychosocial_assessments_count = 0;
// get item counts
$http.get('/metadata/').success(function (result) {
angular.forEach(result, function (each) {
var key = Object.keys(each)[0];
$scope[key + '_count'] = each[key];
});
}).error(function (error) {
$log.log(error);
});
$scope.exportSessions = function () {
$http.get('/sessions/export/');
};
$scope.greeting = 'MISTT Data Analysis Solution';
})
.controller('AllCasesDashboardController', function ($scope, $http, $log) {
$scope.currentPage = 1;
$scope.statistics = [
{'key': 'Average Time Spent On Page', 'value': '10s'}
];
$scope.tabs = [
{title: 'Goals Met By Pageview', content: 'Goals Met By Pageview'},
{title: 'Pages By Topic', content: 'Pages By Topic', disabled: true},
{title: 'Constructs By Pageview', content: 'Constructs By Pageview', disabled: true}
];
var init = function () {
$http.get('/cases/goals-met/by-pageview/').success(function (results) {
$scope.goalsMetByPageviews = results;
});
$http.get('/pages/by-topic').success(function (results) {
$scope.pagesByTopic = results;
});
$http.get('/sessons/pageviews/by-sex/').success(function (results) {
$scope.pageviewsBySex = results;
});
// $http.get('/pages/').success(function (casesResult) {
// $scope.pages = $.map(casesResult, function (value, index) {
// return casesResult[index];
// });
// }).error(function (error) {
// $log.log(error);
// });
// $http.get('/pages/count/').success(function (result) {
// $scope.totalPages = result;
// }).error(function (error) {
// $log.log(error);
// });
};
init();
})
.controller('SearchController', ['$scope', '$sce', function ($scope, $sce) {
$scope.highlight = function (text, search) {
console.log(text, search);
if (!search) {
return $sce.trustAsHtml(String(text));
}
if (text != null) {
angular.forEach(search, function (term) {
text = text.replace(new RegExp(term, 'gi'), '<span class="highlightedText">$&</span>')
});
}
return $sce.trustAsHtml(String(text));
};
$scope.formData = {};
$scope.processForm = function () {
$http({
method: 'GET',
url: '/cases/full-text-search/?term=' + $.param($scope.formData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'} // set the headers so angular passing info as form data (not request payload)
})
.success(function (data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
}])
.controller('CaseByCaseDashboardController', ['$scope', '$sce', '$http', '$log', '$window', function ($scope, $sce, $http, $log, $window) {
$scope.checkModel = {
arm1: false,
arm2: false,
arm3: false,
closeoutThirty: false,
closeoutSixty: false,
closeoutNinety: false,
servicePlanThirty: false,
servicePlanSixty: false,
servicePlanNinety: false
};
$scope.filterByCloseoutThirtyDay = function () {
console.log(this);
};
$scope.$watchCollection('checkModel', function () {
$scope.checkResults = [];
angular.forEach($scope.checkModel, function (value, key) {
if (value) {
$scope.checkResults.push(key);
}
});
});
$scope.search = ['website', 'web', 'internet', 'computer', 'online'];
$scope.highlight = function (text, search) {
if (!search) {
return $sce.trustAsHtml(text);
}
if (text != null) {
angular.forEach(search, function (term) {
text = text.replace(new RegExp(term, 'gi'), '<span class="highlightedText">$&</span>')
});
}
return $sce.trustAsHtml(text);
};
$scope.getCasesByArm = function (armNumber) {
if (armNumber == 1){
$scope.checkModel.arm1 = true;
} else if (armNumber == 2){
$scope.checkModel.arm2 = true;
} else if (armNumber == 3){
$scope.checkModel.arm3 = true;
}
$scope.loading = true;
$http.get('/cases/arm/' + armNumber).success(function (casesResult) {
$scope.theseCases = $.map(casesResult, function (value, index) {
return casesResult[index];
});
$scope.loading = false;
$scope.filterOn = true;
$window.scrollTo(0, 0)
}).error(function (error) {
$log.log(error);
});
};
$scope.oneAtATime = false;
$scope.pageChanged = function () {
$scope.loading = true;
$scope.filterOn = false;
$http.get('/cases/?page=' + $scope.currentPage).success(function (casesResult) {
$scope.theseCases = $.map(casesResult, function (value, index) {
return casesResult[index];
});
$scope.loading = false;
}).error(function (error) {
$log.log(error);
});
};
$scope.pageChangedBottom = function () {
$scope.loading = true;
$scope.filterOn = false;
$http.get('/cases/?page=' + $scope.currentPage).success(function (casesResult) {
$scope.theseCases = $.map(casesResult, function (value, index) {
return casesResult[index];
});
$window.scrollTo(0, 0);
$scope.loading = false;
}).error(function (error) {
$log.log(error);
});
};
var init = function () {
$scope.currentPage = 1;
$scope.loading = true;
$scope.filterOn = false;
$http.get('/cases/?page=1').success(function (casesResult) {
$scope.loading = false;
$scope.theseCases = $.map(casesResult, function (value, index) {
return casesResult[index];
});
}).error(function (error) {
$log.log(error);
});
$http.get('/cases/count/').success(function (result) {
$scope.totalItems = result;
}).error(function (error) {
$log.log(error);
});
};
init();
}])
.directive('pageviewsByInterviewSevenDays', ['$parse', '$http', '$document', function ($parse, $http, $document) {
return {
restrict: 'E',
replace: true,
scope: {
balls: '='
},
template: '<div class="col-md-2 pageviews-by-interview-seven-days widget"></div>',
link: function (scope, elem) {
var thisOne,
icon,
hyperlink;
scope.thisPage = scope.balls;
//console.log(scope.thisPage);
// hyperlink = document.createElement('a');
// icon = document.createElement('i');
// $(icon).addClass('fa fa-download fa-2x');
// $(hyperlink).attr('href', '/cases/' + scope.thisOne._id + '?format=csv');
// $(hyperlink).attr('class', 'download-icon');
// $(hyperlink).append(icon);
// elem.append(scope.thisOne._id.replace('_', ' '));
// elem.after(hyperlink);
}
}
}])
.directive('idWidget', ['$parse', '$http', '$document', function ($parse, $http, $document) {
return {
restrict: 'E',
replace: true,
scope: {
lmao: '='
},
template: '<div class="col-md-12 id-widget widget"></div>',
link: function (scope, elem) {
var span,
icon,
hyperlink;
scope.thisOne = scope.lmao;
hyperlink = document.createElement('a');
icon = document.createElement('i');
span = document.createElement('span');
span.style.float = 'left';
span.innerText = scope.thisOne._id.replace('_', ' ');
$(icon).addClass('fa fa-download');
$(hyperlink).attr('href', '/cases/' + scope.thisOne._id + '?format=csv');
$(hyperlink).attr('class', 'download-icon');
$(hyperlink).append(icon);
elem.append(span);
elem.append(hyperlink);
}
}
}])
.directive('descriptivesWidget', ['$parse', '$document', '$templateCache', function ($parse, $document, $templateCache) {
return {
restrict: 'E',
replace: true,
scope: {
lol: '='
},
template: '<div class="col-md-12 descriptives-widget widget">' +
'<table class="table-bordered table-hover table table-condensed">' +
'<thead>' +
'<tr>' +
'<th>Participant</th>' +
'<th>Age</th>' +
'<th>Gender</th>' +
'<th>Ethnicity</th>' +
'<th>Race</th>' +
'<th>Relationship Status</th>' +
'<th>Education</th>' +
'<th>Income</th>' +
'<th>Employment</th>' +
'<th>Working Hours</th>' +
'<th>Patient-Caregiver Relationship</th>' +
'<th>Patient-Caregiver Cohabitation</th>' +
'<th>Pre-Stroke Tech Use</th>' +
'<th>Post-Stroke Tech Use</th>' +
'<th>Computer Anxiety</th>' +
'<th>Computer Self-Efficacy</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr>' +
'<th>Patient</th>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'</tr>' +
'<tr>' +
'<th>Caregiver</th>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>',
link: function (scope, elem, attrs) {
var interviewSevenDay,
interviewNinetyDay,
_id,
ba,
table,
tableHead,
tableBody,
patientDataRow,
caregiverDataRow;
// grab data from scope
interviewSevenDay = scope.lol.interview_7_day;
interviewNinetyDay = scope.lol.interview_90_day;
ba = scope.lol.biopsychosocial_assessment;
// grab table and data rows
table = angular.element(elem.children()[0]);
tableHead = angular.element(table.children()[0]);
tableBody = angular.element(table.children()[1]);
patientDataRow = angular.element(tableBody.children()[0]);
caregiverDataRow = angular.element(tableBody.children()[1]);
if (ba) {
angular.element(patientDataRow.children()[1]).text(ba.ba_age);
angular.element(patientDataRow.children()[2]).text(ba.ba_gender);
angular.element(patientDataRow.children()[3]).text(ba.ba_ethnicity);
angular.element(caregiverDataRow.children()[3]).text('not asked');
angular.element(patientDataRow.children()[4]).text(ba.ba_race);
angular.element(patientDataRow.children()[5]).text(ba.ba_relationship);
angular.element(caregiverDataRow.children()[5]).text('not asked');
angular.element(patientDataRow.children()[6]).text(ba.ba_edu);
}
if (interviewSevenDay) {
angular.element(patientDataRow.children()[12]).text(interviewSevenDay.patient_pre_stroke_tech_use);
angular.element(patientDataRow.children()[14]).text(interviewSevenDay.patient_computer_anxiety);
angular.element(caregiverDataRow.children()[14]).text(interviewSevenDay.caregiver_computer_anxiety);
angular.element(caregiverDataRow.children()[15]).text('not asked');
angular.element(patientDataRow.children()[15]).text(interviewSevenDay.patient_computer_self_efficacy);
angular.element(caregiverDataRow.children()[1]).text(Math.abs(new Date(Date.now() - new Date(interviewSevenDay.cgd_dob_cg7)).getUTCFullYear() - 1970));
angular.element(caregiverDataRow.children()[2]).text(interviewSevenDay.cgd_sex_cg7);
angular.element(caregiverDataRow.children()[4]).text(interviewSevenDay.cgd_race_cg7);
angular.element(caregiverDataRow.children()[6]).text(interviewSevenDay.cgd_educ_cg7);
angular.element(caregiverDataRow.children()[7]).text(interviewSevenDay.cgd_income_cg7);
angular.element(caregiverDataRow.children()[8]).text(interviewSevenDay.cgd_employed_cg7);
angular.element(caregiverDataRow.children()[9]).text(interviewSevenDay.cgd_hrsweek_cg7);
angular.element(patientDataRow.children()[7]).text('not asked');
angular.element(patientDataRow.children()[8]).text('not asked');
angular.element(patientDataRow.children()[9]).text('not asked');
angular.element(patientDataRow.children()[10]).text('not asked');
angular.element(patientDataRow.children()[11]).text('not asked');
angular.element(caregiverDataRow.children()[10]).text(interviewSevenDay.cgd_relationship_cg7);
angular.element(caregiverDataRow.children()[11]).text(interviewSevenDay.cgd_livewithpatient_cg7);
angular.element(caregiverDataRow.children()[12]).text(interviewSevenDay.caregiver_pre_stroke_tech_use);
}
if (interviewNinetyDay) {
angular.element(patientDataRow.children()[13]).text(interviewNinetyDay.patient_post_stroke_tech_use);
angular.element(caregiverDataRow.children()[13]).text(interviewNinetyDay.caregiver_post_stroke_tech_use);
}
}
}
}])
.directive('servicePlanWidget', ['$parse', '$http', function ($parse, $http) {
return {
restrict: 'E',
replace: true,
scope: {
rofl: '='
},
template: '<div class="widget service-plan-widget">' +
'<table class="table-bordered table-hover table table-condensed">' +
'<thead>' +
'<tr>' +
'<th>Variable</th>' +
'<th>Value</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'</tbody>' +
'</table>' +
'</div>',
link: function (scope, elem) {
var servicePlan,
table,
tableHead,
tableBody,
problemRow,
datePattern,
textPattern1,
textPattern2,
textPattern3,
textPattern4,
textPattern5,
textPattern6,
newRow,
parent1,
parent2,
parent3,
newCell2,
panelHeader,
newRowHeader;
datePattern = /[0-9]{4}\-[0-9]{2}\-[0-9]{2}/g;
textPattern1 = /[Ww][Ee][Bb][Ss][Ii][Tt][Ee]/g;
textPattern2 = /[Ww][Ee][Bb]/g;
textPattern3 = /[Oo][Nn][Ll][Ii][Nn][Ee]/g;
textPattern4 = /[Ii][Nn][Tt][Ee][Rr][Nn][Ee][Tt]/g;
textPattern5 = /[Cc][Oo][Mm][Pp][Uu][Tt][Ee][Rr]/g;
textPattern6 = /[A-Z][a-z]/g;
parent1 = angular.element(elem.parent());
parent2 = angular.element(parent1.parent());
parent3 = angular.element(parent2.parent());
panelHeader = angular.element(parent3.children()[0]);
// grab table and data rows
table = angular.element(elem.children()[0]);
tableHead = angular.element(table.children()[0]);
tableBody = angular.element(table.children()[1]);
problemRow = angular.element(tableBody.children()[0]);
// grab data from scope
servicePlan = scope.rofl.service_plan;
if (servicePlan) {
Object.keys(servicePlan).forEach(function (variable, index) {
var matchDate = datePattern.exec(servicePlan[variable]);
var matchText1 = textPattern1.exec(servicePlan[variable]);
var matchText2 = textPattern2.exec(servicePlan[variable]);
var matchText3 = textPattern3.exec(servicePlan[variable]);
var matchText4 = textPattern4.exec(servicePlan[variable]);
var matchText5 = textPattern5.exec(servicePlan[variable]);
var matchText6 = textPattern6.exec(servicePlan[variable]);
if (matchDate) {
var match = datePattern.exec(servicePlan[variable]);
// new row for variable
var newRow1 = document.createElement('tr');
newRowHeader = document.createElement('th');
newRowHeader.innerText = variable;
// new data cells for variable name and value
newCell2 = document.createElement('td');
newCell2.appendChild(document.createTextNode(servicePlan[variable]));
newRow1.appendChild(newRowHeader);
newRow1.appendChild(newCell2);
tableBody.append(newRow1);
} else if (matchText1 || matchText2 || matchText3 || matchText4 || matchText5) {
// new row for variable
var newRow2 = document.createElement('tr');
newRowHeader = document.createElement('th');
newRowHeader.innerText = variable;
// new data cells for variable name and value
newCell2 = document.createElement('td');
newCell2.appendChild(document.createTextNode(servicePlan[variable]));
newRow2.appendChild(newRowHeader);
newRow2.appendChild(newCell2);
tableBody.append(newRow2);
if (matchText1) {
matchText1.forEach(function (m) {
angular.element(newRow2).addClass('website-mentioned-text');
});
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
}
if (matchText2) {
matchText2.forEach(function (m) {
angular.element(newRow2).addClass('website-mentioned-text');
});
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
}
if (matchText3) {
matchText3.forEach(function (m) {
angular.element(newRow2).addClass('website-mentioned-text');
});
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
}
if (matchText4) {
matchText4.forEach(function (m) {
angular.element(newRow2).addClass('website-mentioned-text');
});
}
if (matchText5) {
matchText5.forEach(function (m) {
angular.element(newRow2).addClass('website-mentioned-text');
});
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
}
} else if (matchText6) {
// new row for variable
var newRow3 = document.createElement('tr');
newRowHeader = document.createElement('th');
newRowHeader.innerText = variable;
// new data cells for variable name and value
newCell2 = document.createElement('td');
newCell2.appendChild(document.createTextNode(servicePlan[variable]));
newRow3.appendChild(newRowHeader);
newRow3.appendChild(newCell2);
tableBody.append(newRow3);
}
});
}
// if (servicePlan) {
// h5.innerHTML = thisOne.service_plan.sp_problem;
// $(elem).append(h5);
// }
}
}
}])
.directive('goalWidget', function () {
return {
restrict: 'E',
replace: true,
scope: {
wut: '='
},
template: '<div class="widget goal-widget">' +
'<table class="table-bordered table-hover table table-condensed">' +
'<thead>' +
'<tr>' +
'<th>#</th>' +
'<th>Description</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'</tbody>' +
'</table>' +
'</div>',
link: function (scope, elem, attrs) {
var thisOne,
goalsMet,
tableHead,
isBold,
dataRow,
table,
tr,
td,
tableBody,
textPattern1,
textPattern2,
textPattern3,
textPattern4,
textPattern5,
match1,
match2,
match3,
match4,
match5,
parent1,
parent2,
parent3,
panelHeader;
// declare regular expressions
textPattern1 = /[Ww][Ee][Bb][Ss][Ii][Tt][Ee]/g;
textPattern2 = /[Ww][Ee][Bb]/g;
textPattern3 = /[Oo][Nn][Ll][Ii][Nn][Ee]/g;
textPattern4 = /[Ii][Nn][Tt][Ee][Rr][Nn][Ee][Tt]/g;
textPattern5 = /[Cc][Oo][Mm][Pp][Uu][Tt][Ee][Rr]/g;
thisOne = scope.wut;
isBold = scope.isBold;
goalsMet = $.map(thisOne.goals_met, function (value, index) {
return thisOne.goals_met[index];
});
//add data
if (goalsMet) {
// grab and arrayify data from scope
// grab table and data rows
table = angular.element(elem.children()[0]);
tableHead = angular.element(table.children()[0]);
tableBody = angular.element(table.children()[1]);
// grab parent in order to adjust style if 'web' or 'website' found
parent1 = angular.element(elem.parent());
parent2 = angular.element(parent1.parent());
parent3 = angular.element(parent2.parent());
panelHeader = angular.element(parent3.children()[0]);
angular.forEach(goalsMet, function (goal, index) {
// new row
var newRow = document.createElement('tr');
// new data cells
var newCell1 = document.createElement('td');
var newCell2 = document.createElement('td');
// append data to cells
goal = goal.replace(/\s+/g, ' ');
newCell1.appendChild(document.createTextNode(index + 1));
newCell2.appendChild(document.createTextNode(goal));
match1 = textPattern1.exec(goal);
match2 = textPattern2.exec(goal);
match3 = textPattern3.exec(goal);
match4 = textPattern4.exec(goal);
match5 = textPattern5.exec(goal);
if (match1) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
match1.forEach(function (m) {
angular.element(newRow).addClass('website-mentioned-text');
});
} else if (match2) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
match2.forEach(function (m) {
angular.element(newRow).addClass('website-mentioned-text');
});
} else if (match3) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
match3.forEach(function (m) {
angular.element(newRow).addClass('website-mentioned-text');
});
} else if (match4) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
match4.forEach(function (m) {
angular.element(newRow).addClass('website-mentioned-text');
});
} else if (match5) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
match5.forEach(function (m) {
angular.element(newRow).addClass('website-mentioned-text');
});
}
newRow.append(newCell1);
newRow.append(newCell2);
angular.element(tableBody).append(newRow);
});
}
}
}
})
.directive('interactionWidget', function () {
return {
restrict: 'E',
replace: true,
scope: {
jeepers: '='
},
template: '<div class="widget interaction-widget">' +
'<table class="table-bordered table-hover table table-condensed">' +
'<thead>' +
'<tr>' +
'<th>#</th>' +
'<th>date</th>' +
'<th>refer_web</th>' +
'<th>resource_web</th>' +
'<th>train_web</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'</tbody>' +
'</table>' +
'</div>',
link: function (scope, elem) {
var thisOne;
thisOne = scope.jeepers;
if (thisOne.interactions != undefined) {
var interactionsArray, table, tableBody, tableHead, parent1, parent2, parent3, panelHeader;
// grab table and data rows
table = angular.element(elem.children()[0]);
tableHead = angular.element(table.children()[0]);
tableBody = angular.element(table.children()[1]);
// grab parent in order to adjust style if 'web' or 'website' found
parent1 = angular.element(elem.parent());
parent2 = angular.element(parent1.parent());
parent3 = angular.element(parent2.parent());
panelHeader = angular.element(parent3.children()[0]);
interactionsArray = $.map(thisOne.interactions, function (value, index) {
return thisOne.interactions[index];
});
interactionsArray.forEach(function (interaction, index) {
// new row
var newRow = document.createElement('tr');
// new data cells
var newHeadCell = document.createElement('th');
var newCell1 = document.createElement('td');
var newCell2 = document.createElement('td');
var newCell3 = document.createElement('td');
var newCell4 = document.createElement('td');
// append data to cells
newHeadCell.appendChild(document.createTextNode(index + 1));
if (interaction.swcm_refer_web === null) {
newCell2.appendChild(document.createTextNode(''));
} else {
newCell2.appendChild(document.createTextNode(interaction.swcm_refer_web));
}
if (interaction.swcm_resource_web === null) {
newCell3.appendChild(document.createTextNode(''));
} else {
newCell3.appendChild(document.createTextNode(interaction.swcm_resource_web));
}
if (interaction.swcm_train_web === null) {
newCell4.appendChild(document.createTextNode(''));
} else {
newCell4.appendChild(document.createTextNode(interaction.swcm_train_web));
}
newCell1.appendChild(document.createTextNode(interaction.swcm_date));
if (interaction.swcm_refer_web) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
angular.element(newRow).addClass('website-mentioned-text');
} else if (interaction.swcm_resource_web) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
angular.element(newRow).addClass('website-mentioned-text');
} else if (interaction.swcm_train_web) {
angular.element(parent3).removeClass('panel-default');
angular.element(panelHeader).addClass('website-mentioned-header');
angular.element(newRow).addClass('website-mentioned-text');
}
newRow.append(newHeadCell);
newRow.append(newCell1);
newRow.append(newCell2);
newRow.append(newCell3);
newRow.append(newCell4);
angular.element(tableBody).append(newRow);
});
}
}
}
})
.directive('webActivityWidget', function () {
return {
restrict: 'E',
replace: true,
scope: {
umm: '='
},
template: '<div class="widget web-activity-widget"></div>',
link: function (scope, elem, attrs) {
var thisOne, sessions, tableHead, tableHeadRow, tableHeadData1, tableHeadData2, tableHeadData3, tableHeadData4, sessionsArray, finalArray, table, h5, tableBody, sessionsPatient, sessionsCaregiver;
thisOne = scope.umm;
sessionsPatient = thisOne.sessions_patient;
sessionsCaregiver = thisOne.sessions_caregiver;
table = document.createElement('table');
tableHead = document.createElement('thead');
tableHeadRow = document.createElement('tr');
tableHeadData1 = document.createElement('th');
tableHeadData1.innerText = 'Date';
tableHeadRow.appendChild(tableHeadData1);
tableHeadData2 = document.createElement('th');
tableHeadData2.innerText = 'User';
tableHeadRow.appendChild(tableHeadData2);
tableHeadData3 = document.createElement('th');
tableHeadData3.innerText = 'Page';
tableHeadRow.appendChild(tableHeadData3);
tableHeadData4 = document.createElement('th');
tableHeadData4.innerText = 'Duration';
tableHeadRow.appendChild(tableHeadData4);
tableHead.append(tableHeadRow);
tableBody = document.createElement('tbody');
if (sessionsPatient != null || sessionsCaregiver != null) {
if (sessionsPatient != null) {
sessionsArray = $.map(sessionsPatient.history, function (value, index) {
return [sessionsPatient.history][index];
});
}
if (sessionsCaregiver != null) {
sessionsArray = $.map(sessionsCaregiver.history, function (value, index) {
return [sessionsCaregiver.history][index];
});
}
sessionsArray.sort(function (a, b) {
return parseInt(a.nth_minute) - parseFloat(b.nth_minute);
}).forEach(function (activity) {
var tr = document.createElement('tr');
var td_date = document.createElement('td');
var td_type = document.createElement('td');
var td_page_path = document.createElement('td');
var td_time_on_page = document.createElement('td');
var minuteIndex = activity.nth_minute;
td_date.appendChild(document.createTextNode(activity.date));
td_type.appendChild(document.createTextNode(activity.type[0].toUpperCase()));
td_page_path.appendChild(document.createTextNode(activity.page_path));
td_time_on_page.appendChild(document.createTextNode(activity.time_on_page + 's'));
tr.appendChild(td_date);
tr.appendChild(td_type);
tr.appendChild(td_page_path);
tr.appendChild(td_time_on_page);
tableBody.appendChild(tr);
});
table.appendChild(tableHead);
table.appendChild(tableBody);
$(table).addClass('table-bordered').addClass('table-hover').addClass('table').addClass('table-condensed');
elem[0].append(table);
}
}
}
})
.directive('overviewWidget', ['$parse', '$http', function ($parse, $http) {
return {
restrict: 'E',
replace: true,
scope: {
lol: '='
},
template: '<div class="row overview-widget widget"></div>',
link: function (scope, elem) {
var h1, h5a, h5b, h5c, thisOne;
thisOne = scope.lol;
h1 = document.createElement('h1');
h5a = document.createElement('h5');
h5b = document.createElement('h5');
h5c = document.createElement('h5');
h1.innerHTML = thisOne.case_id;
h5a.innerHTML = thisOne.interaction_count + ' interactions';
h5b.innerHTML = thisOne.home_visit_count + ' home visits';
h5c.innerHTML = thisOne.pageview_count + ' pageviews';
elem[0].append(h1, h5a, h5b, h5c);
}
};
}])
.directive('timelineWidget', ['$parse', '$http', function ($parse, $http) {
Date.prototype.addDays = function (days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
Date.prototype.subtractDays = function (days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() - days);
return date;
};
function getXAxis(startDate, stopDate) {
var dateArray = new Array('x');
var currentDate = startDate.subtractDays(1);
while (currentDate <= stopDate) {
dateArray.push(currentDate.toISOString().split('T')[0]);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
function getUniqueAndInstanceCount(arr) {
var a = [], b = [], prev;
arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== prev) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length - 1]++;
}
prev = arr[i];
}
return [a, b];
}
function getTimeSeries(timeSeriesObject, axis) {
if (timeSeriesObject.data.length > 0) {
var timeSeriesArray,
timeSeriesDates,
timeSeriesData,
uniqueData,
uniqueAndInstanceData,
occurrenceData;
if (timeSeriesObject.data[0]) {
timeSeriesDates = $.map(timeSeriesObject.data, function (value, index) {
return [timeSeriesObject.data][index];
});
timeSeriesData = [];
timeSeriesDates.forEach(function (timeSeriesDate) {
timeSeriesData.push(timeSeriesDate[timeSeriesObject.property]);
});
timeSeriesArray = new Array(timeSeriesObject.label);
uniqueAndInstanceData = getUniqueAndInstanceCount(timeSeriesData);
uniqueData = uniqueAndInstanceData[0];
occurrenceData = uniqueAndInstanceData[1];
for (var i = 1; i < axis.length; i++) {
var indexOfTickInUniqueData = uniqueData.indexOf(axis[i]);
if (uniqueData.indexOf(axis[i]) > -1) {
timeSeriesArray.push(occurrenceData[indexOfTickInUniqueData]);
} else {
timeSeriesArray.push(null);
}
}
return timeSeriesArray;
} else {
}
} else {
return [timeSeriesObject.label].concat(Array.apply(null, Array(axis.length - 1)).map(function () {
return null
}))
}
}
return {
restrict: 'E',
replace: true,
scope: {
heh: '='
},
template: '<div class="col-md-12 timeline-widget widget"></div>',
link: function (scope, elem) {
var xAxis,
dataColumns,
id,
thisOne,
chartDiv,
formattedStartDate,
dataRegions,
pattern,
textPattern1,
textPattern2,
textPattern3,
textPattern4,
textPattern5;
thisOne = scope.heh;
pattern = new RegExp(/[0-9]{4}\-[0-9]{2}\-[0-9]{2}/);
formattedStartDate = new Date().subtractDays(365).toISOString().split('T')[0];
xAxis = getXAxis(new Date(formattedStartDate), new Date());
dataColumns = [xAxis];
dataRegions = [];
if (thisOne.biopsychosocial_assessment != null) {
var ba = thisOne.biopsychosocial_assessment;
var tmpBAArray = new Array({'ba_strokedate': ba['ba_strokedate']});
dataColumns.push(getTimeSeries({
'data': tmpBAArray,
'label': 'Most Recent Stroke',
'property': 'ba_strokedate'
}, xAxis));
}
if (thisOne.sessions_patient != null) {
dataColumns.push(getTimeSeries({
'data': thisOne.sessions_patient.history,
'label': 'Patient Web Activity',
'property': 'date'
}, xAxis));
}
if (thisOne.sessions_caregiver != null) {
dataColumns.push(getTimeSeries({
'data': thisOne.sessions_caregiver.history,
'label': 'Caregiver Web Activity',
'property': 'date'
}, xAxis));
}
if (thisOne.interactions != null) {
var interactionsArray = $.map(thisOne.interactions, function (value, index) {
return thisOne.interactions[index];
});
dataArray = [];
interactionsArray.forEach(function (interaction) {
dataArray.push(interaction);
});
dataColumns.push(getTimeSeries({
'data': dataArray,
'label': 'Interaction',
'property': 'swcm_date'
}, xAxis));
}
if (thisOne.service_plan != null) {
var SPDateObjects = [];
var servicePlanStartDate = thisOne.service_plan.sp_date;
thisOne.service_plan.sp_date = null;
dataColumns.push(getTimeSeries({
'data': [{'sp_start_date': servicePlanStartDate}],
'label': 'Service Plan Creation',
'property': 'sp_start_date'
}, xAxis));
var keys = Object.keys(thisOne.service_plan);
for (var i = 0; i < keys.length; i++) {
if (thisOne.service_plan[keys[i]] && pattern.test(thisOne.service_plan[keys[i]])) {
SPDateObjects.push({'sp_event_date': thisOne.service_plan[keys[i]]});
}
}
dataColumns.push(getTimeSeries({
'data': SPDateObjects,
'label': 'Event in Service Plan',
'property': 'sp_event_date'
}, xAxis));
dataRegions.push({
start: servicePlanStartDate,
end: new Date(servicePlanStartDate).addDays(90).toISOString().split('T')[0],
class: 'service-plan-region'
});
}
if (thisOne.closeout != null) {
var dataArray = new Array({'closeout_date': thisOne.closeout.co_date});
dataColumns.push(getTimeSeries({
'data': dataArray,
'label': 'Closeout',
'property': 'closeout_date'
}, xAxis));
}
id = thisOne._id + '-timeline';
chartDiv = document.createElement('div');
$(chartDiv).attr('id', id);
$(elem).append(chartDiv);
c3.generate({
size: {
height: 200
},
bindto: '#' + id,
data: {
x: 'x',
format: '%Y-%m-%d',
columns: dataColumns,
colors: {
'Patient Web Activity': '#2aa198',
'Caregiver Web Activity': '#964B00',
'Closeout': '#f08521',
'Event in Service Plan': '#6e005f',
'Interaction': '#d1de3f',
'Most Recent Stroke': '#00e6e6',
'Service Plan Creation': '#FF00FF'
}
},
regions: dataRegions,
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
,
y: {
show: false,
max: 100,
label: {
show: false,
text: 'Events',
label: 'inner-bottom'
}
}
}
,
point: {
r: 7,
focus: {
expand: {
r: 12
}
}
}
,
grid: {
x: {
show: false
}
,
y: {
show: true
}
}
}
);
}
}
;
}])
;
}
()
)
;
|
'use strict';
angular.
module('peerUp').
component('careers', {
templateUrl: 'pages/careers/careers.html',
controllerAs: 'vm',
controller: function careersComponenet() {
var vm = this;
}
});
|
/**
* Created by yangyang on 2017/10/19.
*/
import React, {Component} from 'react'
import {connect} from 'react-redux'
import { Row, Col, Button, message } from 'antd'
import {profitAction, profitSelector} from './redux'
import {selector as authSelector} from '../../util/auth'
import {ROLE_CODE} from '../../util/rolePermission'
class WalletBar extends React.PureComponent {
constructor(props) {
super(props)
}
componentDidMount() {
this.props.getCurrentAdminProfit({
error: () => {
message.error('获取收益余额失败')
}
})
}
toggleModel = () => {
let {onClick} = this.props
onClick()
}
render() {
let {adminProfit, isInvestor, isProvider} = this.props
if (!adminProfit) {
return null
}
return (
<div>
<Row>
<Col span={22}>
<span style={{marginRight: 10}}>账户余额</span>
<span style={{color: 'red', marginRight: 30}}>¥ {Number(adminProfit.balance).toFixed(2).toLocaleString()}</span>
{
isInvestor ? (
<span>
<span style={{marginRight: 10}}>投资总收益</span>
<span style={{color: 'red', marginRight: 30}}>¥ {Number(adminProfit.investEarn).toFixed(2).toLocaleString()}</span>
</span>
) : null
}
{
isProvider ? (
<span>
<span style={{marginRight: 10}}>分红总收益</span>
<span style={{color: 'red', marginRight: 30}}>¥ {Number(adminProfit.providerEarn).toFixed(2).toLocaleString()}</span>
</span>
) : null
}
</Col>
<Col span={2}>
<span><Button type="primary" onClick={this.toggleModel}>取现</Button></span>
</Col>
</Row>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
let adminProfit = profitSelector.selectAdminProfit(state)
let isInvestor = authSelector.selectValidRoles(state, [ROLE_CODE.STATION_INVESTOR])
let isProvider = authSelector.selectValidRoles(state, [ROLE_CODE.STATION_PROVIDER])
return {
adminProfit,
isInvestor,
isProvider,
}
}
const mapDispatchToProps = {
...profitAction,
}
export default connect(mapStateToProps, mapDispatchToProps)(WalletBar)
|
import Intercom from 'intercom-client';
import { Connectors, getSetting /* addCallback, Utils */ } from 'meteor/vulcan:core';
import {
// addPageFunction,
addUserFunction,
// addInitFunction,
// addIdentifyFunction,
addTrackFunction,
} from 'meteor/vulcan:events';
import Users from 'meteor/vulcan:users';
const token = getSetting('intercom.accessToken');
if (!token) {
throw new Error('Please add your Intercom access token as intercom.accessToken in settings.json');
} else {
export const intercomClient = new Intercom.Client({ token });
const getDate = () =>
new Date()
.valueOf()
.toString()
.substr(0, 10);
/*
New User
*/
// eslint-disable-next-line no-inner-declarations
async function intercomNewUser({ user }) {
await intercomClient.users.create({
email: user.email,
user_id: user._id,
custom_attributes: {
name: user.displayName,
profileUrl: Users.getProfileUrl(user, true),
},
});
}
addUserFunction(intercomNewUser);
/*
Track Event
*/
// eslint-disable-next-line no-inner-declarations
function intercomTrackServer(eventName, eventProperties, currentUser = {}) {
intercomClient.events.create({
event_name: eventName,
created_at: getDate(),
email: currentUser.email,
user_id: currentUser._id,
metadata: {
...eventProperties,
},
});
}
addTrackFunction(intercomTrackServer);
}
|
/*
* grunt-gulp
* https://github.com/shama/grunt-gulp
*
* Copyright (c) 2016 Kyle Robinson Young
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
var coffee = require('gulp-coffee');
var concat = require('gulp-concat');
var gulp = require('gulp');
grunt.initConfig({
gulp: {
// Grunt src->dest config with gulp tasks
srcdest: {
options: {
tasks: function(stream) {
return stream.pipe(coffee());
}
},
src: ['test/fixtures/*.coffee'],
dest: 'tmp/srcdest.js',
},
// Grunt expand mapping
expand: {
expand: true,
cwd: 'test/fixtures/',
src: '*.js',
dest: 'tmp/expand',
},
// Or bypass everything while still integrating gulp
fn: function() {
var dest = gulp.dest('tmp/');
dest.on('end', function() {
grunt.log.ok('Created tmp/fn.js');
});
return gulp.src('test/fixtures/*.coffee')
.pipe(coffee())
.pipe(concat('fn.js'))
.pipe(dest);
},
},
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
clean: {
tmp: 'tmp',
},
nodeunit: {
tests: ['test/*_test.js'],
}
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('test', ['clean', 'gulp', 'nodeunit']);
grunt.registerTask('default', ['jshint']);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.