id int32 0 58k | repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1 value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,200 | lorenwest/node-monitor | dist/monitor-all.js | function(connection) {
var t = this;
log.info('removeConnection', 'Conn_' + connection.id);
connection.disconnect('connection_removed');
t.connections.remove(connection);
t.trigger('connection:remove', connection);
} | javascript | function(connection) {
var t = this;
log.info('removeConnection', 'Conn_' + connection.id);
connection.disconnect('connection_removed');
t.connections.remove(connection);
t.trigger('connection:remove', connection);
} | [
"function",
"(",
"connection",
")",
"{",
"var",
"t",
"=",
"this",
";",
"log",
".",
"info",
"(",
"'removeConnection'",
",",
"'Conn_'",
"+",
"connection",
".",
"id",
")",
";",
"connection",
".",
"disconnect",
"(",
"'connection_removed'",
")",
";",
"t",
".",
"connections",
".",
"remove",
"(",
"connection",
")",
";",
"t",
".",
"trigger",
"(",
"'connection:remove'",
",",
"connection",
")",
";",
"}"
] | Remove a connection from the router.
This is called to remove the connection and associated routes from the router.
@method removeConnection
@protected
@param connection {Connection} - The connection to remove | [
"Remove",
"a",
"connection",
"from",
"the",
"router",
"."
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9405-L9411 | |
23,201 | lorenwest/node-monitor | dist/monitor-all.js | function(monitor, reason, callback) {
callback = callback || function(){};
var t = this, probe = monitor.probe, probeId = monitor.get('probeId');
// The monitor must be connected
if (!probe) {return callback('Monitor must be connected');}
// Called upon disconnect (internal or external)
var onDisconnect = function(error) {
if (error) {
return callback(error);
}
probe.off('change', monitor.probeChange);
monitor.set({probeId:null});
monitor.probe = monitor.probeChange = null;
return callback(null, reason);
};
// Disconnect from an internal or external probe
if (probe.connection) {
t.disconnectExternal(probe.connection, probeId, onDisconnect);
} else {
t.disconnectInternal(probeId, onDisconnect);
}
} | javascript | function(monitor, reason, callback) {
callback = callback || function(){};
var t = this, probe = monitor.probe, probeId = monitor.get('probeId');
// The monitor must be connected
if (!probe) {return callback('Monitor must be connected');}
// Called upon disconnect (internal or external)
var onDisconnect = function(error) {
if (error) {
return callback(error);
}
probe.off('change', monitor.probeChange);
monitor.set({probeId:null});
monitor.probe = monitor.probeChange = null;
return callback(null, reason);
};
// Disconnect from an internal or external probe
if (probe.connection) {
t.disconnectExternal(probe.connection, probeId, onDisconnect);
} else {
t.disconnectInternal(probeId, onDisconnect);
}
} | [
"function",
"(",
"monitor",
",",
"reason",
",",
"callback",
")",
"{",
"callback",
"=",
"callback",
"||",
"function",
"(",
")",
"{",
"}",
";",
"var",
"t",
"=",
"this",
",",
"probe",
"=",
"monitor",
".",
"probe",
",",
"probeId",
"=",
"monitor",
".",
"get",
"(",
"'probeId'",
")",
";",
"// The monitor must be connected",
"if",
"(",
"!",
"probe",
")",
"{",
"return",
"callback",
"(",
"'Monitor must be connected'",
")",
";",
"}",
"// Called upon disconnect (internal or external)",
"var",
"onDisconnect",
"=",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"probe",
".",
"off",
"(",
"'change'",
",",
"monitor",
".",
"probeChange",
")",
";",
"monitor",
".",
"set",
"(",
"{",
"probeId",
":",
"null",
"}",
")",
";",
"monitor",
".",
"probe",
"=",
"monitor",
".",
"probeChange",
"=",
"null",
";",
"return",
"callback",
"(",
"null",
",",
"reason",
")",
";",
"}",
";",
"// Disconnect from an internal or external probe",
"if",
"(",
"probe",
".",
"connection",
")",
"{",
"t",
".",
"disconnectExternal",
"(",
"probe",
".",
"connection",
",",
"probeId",
",",
"onDisconnect",
")",
";",
"}",
"else",
"{",
"t",
".",
"disconnectInternal",
"(",
"probeId",
",",
"onDisconnect",
")",
";",
"}",
"}"
] | Disconnect a monitor
This accepts an instance of a connected monitor, and disconnects it from
the remote probe.
The probe implementation will be released if this is the only monitor
object watching it.
@method disconnectMonitor
@protected
@param monitor {Monitor} - The connected monitor
@param reason {String} - Reason for the disconnect
@param callback {Function(error)} - (optional) Called when connected | [
"Disconnect",
"a",
"monitor"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9504-L9528 | |
23,202 | lorenwest/node-monitor | dist/monitor-all.js | function(probeJSON) {
var probeKey = probeJSON.probeClass,
initParams = probeJSON.initParams;
// Allow probes to be externally identified by name
if (probeJSON.probeName) {
return probeJSON.probeName;
}
if (initParams) {
_.keys(initParams).sort().forEach(function(key){
probeKey += ':' + key + '=' + initParams[key];
});
}
return probeKey;
} | javascript | function(probeJSON) {
var probeKey = probeJSON.probeClass,
initParams = probeJSON.initParams;
// Allow probes to be externally identified by name
if (probeJSON.probeName) {
return probeJSON.probeName;
}
if (initParams) {
_.keys(initParams).sort().forEach(function(key){
probeKey += ':' + key + '=' + initParams[key];
});
}
return probeKey;
} | [
"function",
"(",
"probeJSON",
")",
"{",
"var",
"probeKey",
"=",
"probeJSON",
".",
"probeClass",
",",
"initParams",
"=",
"probeJSON",
".",
"initParams",
";",
"// Allow probes to be externally identified by name",
"if",
"(",
"probeJSON",
".",
"probeName",
")",
"{",
"return",
"probeJSON",
".",
"probeName",
";",
"}",
"if",
"(",
"initParams",
")",
"{",
"_",
".",
"keys",
"(",
"initParams",
")",
".",
"sort",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"probeKey",
"+=",
"':'",
"+",
"key",
"+",
"'='",
"+",
"initParams",
"[",
"key",
"]",
";",
"}",
")",
";",
"}",
"return",
"probeKey",
";",
"}"
] | Build a probe key from the probe data
@method buildProbeKey
@protected
@param probeJSON {Object} - An object containing:
@param probeJSON.probeName {String} - The client-defined probe name
-or-
@param probeJSON.probeClass {String} - The probe class name (required)
@param probeJSON.initParams {Object} - Probe initialization parameters (if any)
@return probeKey {String} - A string identifying the probe | [
"Build",
"a",
"probe",
"key",
"from",
"the",
"probe",
"data"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9542-L9557 | |
23,203 | lorenwest/node-monitor | dist/monitor-all.js | function(hostName, appName, appInstance) {
var t = this, thisInstance = 0;
return t.connections.find(function(conn) {
// Host or app matches if not specified or if specified and equal
var matchesHost = !hostName || conn.isThisHost(hostName);
var matchesApp = !appName || appName === conn.get('remoteAppName');
var matchesInstance = !appInstance || appInstance === conn.get('remoteAppInstance');
var remoteFirewall = conn.get('remoteFirewall');
// This is a match if host + app + instance matches, and it's not firewalled
return (!remoteFirewall && matchesHost && matchesApp && matchesInstance);
});
} | javascript | function(hostName, appName, appInstance) {
var t = this, thisInstance = 0;
return t.connections.find(function(conn) {
// Host or app matches if not specified or if specified and equal
var matchesHost = !hostName || conn.isThisHost(hostName);
var matchesApp = !appName || appName === conn.get('remoteAppName');
var matchesInstance = !appInstance || appInstance === conn.get('remoteAppInstance');
var remoteFirewall = conn.get('remoteFirewall');
// This is a match if host + app + instance matches, and it's not firewalled
return (!remoteFirewall && matchesHost && matchesApp && matchesInstance);
});
} | [
"function",
"(",
"hostName",
",",
"appName",
",",
"appInstance",
")",
"{",
"var",
"t",
"=",
"this",
",",
"thisInstance",
"=",
"0",
";",
"return",
"t",
".",
"connections",
".",
"find",
"(",
"function",
"(",
"conn",
")",
"{",
"// Host or app matches if not specified or if specified and equal",
"var",
"matchesHost",
"=",
"!",
"hostName",
"||",
"conn",
".",
"isThisHost",
"(",
"hostName",
")",
";",
"var",
"matchesApp",
"=",
"!",
"appName",
"||",
"appName",
"===",
"conn",
".",
"get",
"(",
"'remoteAppName'",
")",
";",
"var",
"matchesInstance",
"=",
"!",
"appInstance",
"||",
"appInstance",
"===",
"conn",
".",
"get",
"(",
"'remoteAppInstance'",
")",
";",
"var",
"remoteFirewall",
"=",
"conn",
".",
"get",
"(",
"'remoteFirewall'",
")",
";",
"// This is a match if host + app + instance matches, and it's not firewalled",
"return",
"(",
"!",
"remoteFirewall",
"&&",
"matchesHost",
"&&",
"matchesApp",
"&&",
"matchesInstance",
")",
";",
"}",
")",
";",
"}"
] | Find an existing connection to use
This method looks into the existing known connections to find one
that matches the specified parameters.
Firewalled connections are not returned.
@method findConnection
@protected
@param hostName {String} - Host name to find a connection for (null = any host)
@param appName {String} - App name to find a connection with (null = any app)
@param appInstance {Any} - Application instance running on this host (null = any instance)
@return connection {Connection} - A Connection object if found, otherwise null | [
"Find",
"an",
"existing",
"connection",
"to",
"use"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9741-L9754 | |
23,204 | lorenwest/node-monitor | dist/monitor-all.js | function(hostName, appName) {
var t = this;
return t.connections.filter(function(conn) {
// Host or app matches if not specified or if specified and equal
var matchesHost = !hostName || conn.isThisHost(hostName);
var matchesApp = !appName || appName === conn.get('remoteAppName');
var remoteFirewall = conn.get('remoteFirewall');
// This is a match if host + app matches, and it's not firewalled
return (!remoteFirewall && matchesHost && matchesApp);
});
} | javascript | function(hostName, appName) {
var t = this;
return t.connections.filter(function(conn) {
// Host or app matches if not specified or if specified and equal
var matchesHost = !hostName || conn.isThisHost(hostName);
var matchesApp = !appName || appName === conn.get('remoteAppName');
var remoteFirewall = conn.get('remoteFirewall');
// This is a match if host + app matches, and it's not firewalled
return (!remoteFirewall && matchesHost && matchesApp);
});
} | [
"function",
"(",
"hostName",
",",
"appName",
")",
"{",
"var",
"t",
"=",
"this",
";",
"return",
"t",
".",
"connections",
".",
"filter",
"(",
"function",
"(",
"conn",
")",
"{",
"// Host or app matches if not specified or if specified and equal",
"var",
"matchesHost",
"=",
"!",
"hostName",
"||",
"conn",
".",
"isThisHost",
"(",
"hostName",
")",
";",
"var",
"matchesApp",
"=",
"!",
"appName",
"||",
"appName",
"===",
"conn",
".",
"get",
"(",
"'remoteAppName'",
")",
";",
"var",
"remoteFirewall",
"=",
"conn",
".",
"get",
"(",
"'remoteFirewall'",
")",
";",
"// This is a match if host + app matches, and it's not firewalled",
"return",
"(",
"!",
"remoteFirewall",
"&&",
"matchesHost",
"&&",
"matchesApp",
")",
";",
"}",
")",
";",
"}"
] | Find all connections matching the selection criteria
This method looks into the existing known connections to find all
that match the specified parameters.
Firewalled connections are not returned.
@method findConnections
@protected
@param hostName {String} - Host name to search for (null = any host)
@param appName {String} - App name to search for (null = any app)
@return connections {Array of Connection} - An array of Connection objects matching the criteria | [
"Find",
"all",
"connections",
"matching",
"the",
"selection",
"criteria"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9770-L9782 | |
23,205 | lorenwest/node-monitor | dist/monitor-all.js | function(hostName, callback) {
var t = this,
errStr = '',
connectedPorts = [],
portStart = Config.Monitor.serviceBasePort,
portEnd = Config.Monitor.serviceBasePort + Config.Monitor.portsToScan - 1;
// Create an array to hold callbacks for this host
if (!t.addHostCallbacks[hostName]) {
t.addHostCallbacks[hostName] = [];
}
// Remember this callback and return if we're already adding connections for this host
if (t.addHostCallbacks[hostName].push(callback) > 1) {
return;
}
// Called when done
var doneAdding = function(error) {
t.addHostCallbacks[hostName].forEach(function(cb) {
cb(error);
});
delete t.addHostCallbacks[hostName];
};
// Build the list of ports already connected
t.connections.each(function(connection){
var host = connection.get('hostName').toLowerCase();
var port = connection.get('hostPort');
if (host === hostName && port >= portStart && port <= portEnd) {
connectedPorts.push(port);
}
});
// Scan non-connected ports
var portsToScan = Config.Monitor.portsToScan - connectedPorts.length;
if (portsToScan === 0) {
errStr = 'All monitor ports in use. Increase the Config.Monitor.portsToScan configuration';
log.error('addHostConnections', errStr);
return doneAdding(errStr);
}
var doneScanning = function() {
var conn = this; // called in the context of the connection
conn.off('connect disconnect error', doneScanning);
if (--portsToScan === 0) {
return doneAdding();
}
};
for (var i = portStart; i <= portEnd; i++) {
if (connectedPorts.indexOf(i) < 0) {
var connection = t.addConnection({hostName:hostName, hostPort:i});
connection.on('connect disconnect error', doneScanning, connection);
}
}
} | javascript | function(hostName, callback) {
var t = this,
errStr = '',
connectedPorts = [],
portStart = Config.Monitor.serviceBasePort,
portEnd = Config.Monitor.serviceBasePort + Config.Monitor.portsToScan - 1;
// Create an array to hold callbacks for this host
if (!t.addHostCallbacks[hostName]) {
t.addHostCallbacks[hostName] = [];
}
// Remember this callback and return if we're already adding connections for this host
if (t.addHostCallbacks[hostName].push(callback) > 1) {
return;
}
// Called when done
var doneAdding = function(error) {
t.addHostCallbacks[hostName].forEach(function(cb) {
cb(error);
});
delete t.addHostCallbacks[hostName];
};
// Build the list of ports already connected
t.connections.each(function(connection){
var host = connection.get('hostName').toLowerCase();
var port = connection.get('hostPort');
if (host === hostName && port >= portStart && port <= portEnd) {
connectedPorts.push(port);
}
});
// Scan non-connected ports
var portsToScan = Config.Monitor.portsToScan - connectedPorts.length;
if (portsToScan === 0) {
errStr = 'All monitor ports in use. Increase the Config.Monitor.portsToScan configuration';
log.error('addHostConnections', errStr);
return doneAdding(errStr);
}
var doneScanning = function() {
var conn = this; // called in the context of the connection
conn.off('connect disconnect error', doneScanning);
if (--portsToScan === 0) {
return doneAdding();
}
};
for (var i = portStart; i <= portEnd; i++) {
if (connectedPorts.indexOf(i) < 0) {
var connection = t.addConnection({hostName:hostName, hostPort:i});
connection.on('connect disconnect error', doneScanning, connection);
}
}
} | [
"function",
"(",
"hostName",
",",
"callback",
")",
"{",
"var",
"t",
"=",
"this",
",",
"errStr",
"=",
"''",
",",
"connectedPorts",
"=",
"[",
"]",
",",
"portStart",
"=",
"Config",
".",
"Monitor",
".",
"serviceBasePort",
",",
"portEnd",
"=",
"Config",
".",
"Monitor",
".",
"serviceBasePort",
"+",
"Config",
".",
"Monitor",
".",
"portsToScan",
"-",
"1",
";",
"// Create an array to hold callbacks for this host",
"if",
"(",
"!",
"t",
".",
"addHostCallbacks",
"[",
"hostName",
"]",
")",
"{",
"t",
".",
"addHostCallbacks",
"[",
"hostName",
"]",
"=",
"[",
"]",
";",
"}",
"// Remember this callback and return if we're already adding connections for this host",
"if",
"(",
"t",
".",
"addHostCallbacks",
"[",
"hostName",
"]",
".",
"push",
"(",
"callback",
")",
">",
"1",
")",
"{",
"return",
";",
"}",
"// Called when done",
"var",
"doneAdding",
"=",
"function",
"(",
"error",
")",
"{",
"t",
".",
"addHostCallbacks",
"[",
"hostName",
"]",
".",
"forEach",
"(",
"function",
"(",
"cb",
")",
"{",
"cb",
"(",
"error",
")",
";",
"}",
")",
";",
"delete",
"t",
".",
"addHostCallbacks",
"[",
"hostName",
"]",
";",
"}",
";",
"// Build the list of ports already connected",
"t",
".",
"connections",
".",
"each",
"(",
"function",
"(",
"connection",
")",
"{",
"var",
"host",
"=",
"connection",
".",
"get",
"(",
"'hostName'",
")",
".",
"toLowerCase",
"(",
")",
";",
"var",
"port",
"=",
"connection",
".",
"get",
"(",
"'hostPort'",
")",
";",
"if",
"(",
"host",
"===",
"hostName",
"&&",
"port",
">=",
"portStart",
"&&",
"port",
"<=",
"portEnd",
")",
"{",
"connectedPorts",
".",
"push",
"(",
"port",
")",
";",
"}",
"}",
")",
";",
"// Scan non-connected ports",
"var",
"portsToScan",
"=",
"Config",
".",
"Monitor",
".",
"portsToScan",
"-",
"connectedPorts",
".",
"length",
";",
"if",
"(",
"portsToScan",
"===",
"0",
")",
"{",
"errStr",
"=",
"'All monitor ports in use. Increase the Config.Monitor.portsToScan configuration'",
";",
"log",
".",
"error",
"(",
"'addHostConnections'",
",",
"errStr",
")",
";",
"return",
"doneAdding",
"(",
"errStr",
")",
";",
"}",
"var",
"doneScanning",
"=",
"function",
"(",
")",
"{",
"var",
"conn",
"=",
"this",
";",
"// called in the context of the connection",
"conn",
".",
"off",
"(",
"'connect disconnect error'",
",",
"doneScanning",
")",
";",
"if",
"(",
"--",
"portsToScan",
"===",
"0",
")",
"{",
"return",
"doneAdding",
"(",
")",
";",
"}",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"portStart",
";",
"i",
"<=",
"portEnd",
";",
"i",
"++",
")",
"{",
"if",
"(",
"connectedPorts",
".",
"indexOf",
"(",
"i",
")",
"<",
"0",
")",
"{",
"var",
"connection",
"=",
"t",
".",
"addConnection",
"(",
"{",
"hostName",
":",
"hostName",
",",
"hostPort",
":",
"i",
"}",
")",
";",
"connection",
".",
"on",
"(",
"'connect disconnect error'",
",",
"doneScanning",
",",
"connection",
")",
";",
"}",
"}",
"}"
] | Add connections for the specified host
This performs a scan of monitor ports on the server, and adds connections
for newly discovered servers.
It can take a while to complete, and if called for the same host before
completion, it will save the callback and call all callbacks when the
original task is complete.
@method addHostConnections
@protected
@param hostName {String} - The host to add connections with
@param callback {Function(error)} - Called when complete | [
"Add",
"connections",
"for",
"the",
"specified",
"host"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9799-L9853 | |
23,206 | lorenwest/node-monitor | dist/monitor-all.js | function(error) {
t.addHostCallbacks[hostName].forEach(function(cb) {
cb(error);
});
delete t.addHostCallbacks[hostName];
} | javascript | function(error) {
t.addHostCallbacks[hostName].forEach(function(cb) {
cb(error);
});
delete t.addHostCallbacks[hostName];
} | [
"function",
"(",
"error",
")",
"{",
"t",
".",
"addHostCallbacks",
"[",
"hostName",
"]",
".",
"forEach",
"(",
"function",
"(",
"cb",
")",
"{",
"cb",
"(",
"error",
")",
";",
"}",
")",
";",
"delete",
"t",
".",
"addHostCallbacks",
"[",
"hostName",
"]",
";",
"}"
] | Called when done | [
"Called",
"when",
"done"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9817-L9822 | |
23,207 | lorenwest/node-monitor | dist/monitor-all.js | function(probeId, callback) {
var t = this, probeImpl = t.runningProbesById[probeId];
if (!probeImpl) {return callback('Probe not running');}
if (--probeImpl.refCount === 0) {
// Release probe resources & internal references if still no references after a while
setTimeout(function() {
if (probeImpl.refCount === 0) {
try {
probeImpl.release();
} catch (e){}
delete t.runningProbesByKey[probeImpl.probeKey];
delete t.runningProbesById[probeId];
}
}, PROBE_TIMEOUT_MS);
}
callback(null, probeImpl);
} | javascript | function(probeId, callback) {
var t = this, probeImpl = t.runningProbesById[probeId];
if (!probeImpl) {return callback('Probe not running');}
if (--probeImpl.refCount === 0) {
// Release probe resources & internal references if still no references after a while
setTimeout(function() {
if (probeImpl.refCount === 0) {
try {
probeImpl.release();
} catch (e){}
delete t.runningProbesByKey[probeImpl.probeKey];
delete t.runningProbesById[probeId];
}
}, PROBE_TIMEOUT_MS);
}
callback(null, probeImpl);
} | [
"function",
"(",
"probeId",
",",
"callback",
")",
"{",
"var",
"t",
"=",
"this",
",",
"probeImpl",
"=",
"t",
".",
"runningProbesById",
"[",
"probeId",
"]",
";",
"if",
"(",
"!",
"probeImpl",
")",
"{",
"return",
"callback",
"(",
"'Probe not running'",
")",
";",
"}",
"if",
"(",
"--",
"probeImpl",
".",
"refCount",
"===",
"0",
")",
"{",
"// Release probe resources & internal references if still no references after a while",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"probeImpl",
".",
"refCount",
"===",
"0",
")",
"{",
"try",
"{",
"probeImpl",
".",
"release",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"delete",
"t",
".",
"runningProbesByKey",
"[",
"probeImpl",
".",
"probeKey",
"]",
";",
"delete",
"t",
".",
"runningProbesById",
"[",
"probeId",
"]",
";",
"}",
"}",
",",
"PROBE_TIMEOUT_MS",
")",
";",
"}",
"callback",
"(",
"null",
",",
"probeImpl",
")",
";",
"}"
] | Disconnect with an internal probe implementation.
@method disconnectInternal
@protected
@param probeId {String} - The probe implementation ID to disconnect
@param callback {Function(error, probeImpl)} - Called when disconnected | [
"Disconnect",
"with",
"an",
"internal",
"probe",
"implementation",
"."
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9961-L9978 | |
23,208 | lorenwest/node-monitor | dist/monitor-all.js | function(monitorJSON, connection, callback) {
// Build a key for this probe from the probeClass and initParams
var t = this,
errStr = '',
probeKey = t.buildProbeKey(monitorJSON);
// Get the probe proxy
var probeId = connection.remoteProbeIdsByKey[probeKey];
var probeProxy = connection.remoteProbesById[probeId];
if (!probeProxy) {
// Connect with the remote probe
connection.emit('probe:connect', monitorJSON, function(error, probeJSON){
if (error) {
errStr = "probe:connect returned an error for probeClass '" + monitorJSON.probeClass +
"' on " + Monitor.toServerString(monitorJSON);
return callback({err: error, msg: errStr});
}
probeId = probeJSON.id;
// See if the proxy was created while waiting for return
probeProxy = connection.remoteProbesById[probeId];
if (probeProxy) {
probeProxy.refCount++;
log.info('connectExternal.connected.existingProxy', {probeId: probeId, refCount: probeProxy.refCount, whileWaiting: true});
return callback(null, probeProxy);
}
// Create the probe proxy
probeProxy = new Probe(probeJSON);
probeProxy.refCount = 1;
probeProxy.connection = connection;
connection.remoteProbeIdsByKey[probeKey] = probeId;
connection.remoteProbesById[probeId] = probeProxy;
connection.addEvent('probe:change:' + probeId, function(attrs){probeProxy.set(attrs);});
log.info('connectExternal.connected.newProxy', {probeId: probeId});
return callback(null, probeProxy);
});
return;
}
// Probes are released based on reference count
probeProxy.refCount++;
log.info('connectExternal.connected.existingProxy', {probeId: probeId, refCount: probeProxy.refCount});
return callback(null, probeProxy);
} | javascript | function(monitorJSON, connection, callback) {
// Build a key for this probe from the probeClass and initParams
var t = this,
errStr = '',
probeKey = t.buildProbeKey(monitorJSON);
// Get the probe proxy
var probeId = connection.remoteProbeIdsByKey[probeKey];
var probeProxy = connection.remoteProbesById[probeId];
if (!probeProxy) {
// Connect with the remote probe
connection.emit('probe:connect', monitorJSON, function(error, probeJSON){
if (error) {
errStr = "probe:connect returned an error for probeClass '" + monitorJSON.probeClass +
"' on " + Monitor.toServerString(monitorJSON);
return callback({err: error, msg: errStr});
}
probeId = probeJSON.id;
// See if the proxy was created while waiting for return
probeProxy = connection.remoteProbesById[probeId];
if (probeProxy) {
probeProxy.refCount++;
log.info('connectExternal.connected.existingProxy', {probeId: probeId, refCount: probeProxy.refCount, whileWaiting: true});
return callback(null, probeProxy);
}
// Create the probe proxy
probeProxy = new Probe(probeJSON);
probeProxy.refCount = 1;
probeProxy.connection = connection;
connection.remoteProbeIdsByKey[probeKey] = probeId;
connection.remoteProbesById[probeId] = probeProxy;
connection.addEvent('probe:change:' + probeId, function(attrs){probeProxy.set(attrs);});
log.info('connectExternal.connected.newProxy', {probeId: probeId});
return callback(null, probeProxy);
});
return;
}
// Probes are released based on reference count
probeProxy.refCount++;
log.info('connectExternal.connected.existingProxy', {probeId: probeId, refCount: probeProxy.refCount});
return callback(null, probeProxy);
} | [
"function",
"(",
"monitorJSON",
",",
"connection",
",",
"callback",
")",
"{",
"// Build a key for this probe from the probeClass and initParams",
"var",
"t",
"=",
"this",
",",
"errStr",
"=",
"''",
",",
"probeKey",
"=",
"t",
".",
"buildProbeKey",
"(",
"monitorJSON",
")",
";",
"// Get the probe proxy",
"var",
"probeId",
"=",
"connection",
".",
"remoteProbeIdsByKey",
"[",
"probeKey",
"]",
";",
"var",
"probeProxy",
"=",
"connection",
".",
"remoteProbesById",
"[",
"probeId",
"]",
";",
"if",
"(",
"!",
"probeProxy",
")",
"{",
"// Connect with the remote probe",
"connection",
".",
"emit",
"(",
"'probe:connect'",
",",
"monitorJSON",
",",
"function",
"(",
"error",
",",
"probeJSON",
")",
"{",
"if",
"(",
"error",
")",
"{",
"errStr",
"=",
"\"probe:connect returned an error for probeClass '\"",
"+",
"monitorJSON",
".",
"probeClass",
"+",
"\"' on \"",
"+",
"Monitor",
".",
"toServerString",
"(",
"monitorJSON",
")",
";",
"return",
"callback",
"(",
"{",
"err",
":",
"error",
",",
"msg",
":",
"errStr",
"}",
")",
";",
"}",
"probeId",
"=",
"probeJSON",
".",
"id",
";",
"// See if the proxy was created while waiting for return",
"probeProxy",
"=",
"connection",
".",
"remoteProbesById",
"[",
"probeId",
"]",
";",
"if",
"(",
"probeProxy",
")",
"{",
"probeProxy",
".",
"refCount",
"++",
";",
"log",
".",
"info",
"(",
"'connectExternal.connected.existingProxy'",
",",
"{",
"probeId",
":",
"probeId",
",",
"refCount",
":",
"probeProxy",
".",
"refCount",
",",
"whileWaiting",
":",
"true",
"}",
")",
";",
"return",
"callback",
"(",
"null",
",",
"probeProxy",
")",
";",
"}",
"// Create the probe proxy",
"probeProxy",
"=",
"new",
"Probe",
"(",
"probeJSON",
")",
";",
"probeProxy",
".",
"refCount",
"=",
"1",
";",
"probeProxy",
".",
"connection",
"=",
"connection",
";",
"connection",
".",
"remoteProbeIdsByKey",
"[",
"probeKey",
"]",
"=",
"probeId",
";",
"connection",
".",
"remoteProbesById",
"[",
"probeId",
"]",
"=",
"probeProxy",
";",
"connection",
".",
"addEvent",
"(",
"'probe:change:'",
"+",
"probeId",
",",
"function",
"(",
"attrs",
")",
"{",
"probeProxy",
".",
"set",
"(",
"attrs",
")",
";",
"}",
")",
";",
"log",
".",
"info",
"(",
"'connectExternal.connected.newProxy'",
",",
"{",
"probeId",
":",
"probeId",
"}",
")",
";",
"return",
"callback",
"(",
"null",
",",
"probeProxy",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"// Probes are released based on reference count",
"probeProxy",
".",
"refCount",
"++",
";",
"log",
".",
"info",
"(",
"'connectExternal.connected.existingProxy'",
",",
"{",
"probeId",
":",
"probeId",
",",
"refCount",
":",
"probeProxy",
".",
"refCount",
"}",
")",
";",
"return",
"callback",
"(",
"null",
",",
"probeProxy",
")",
";",
"}"
] | Connect to an external probe implementation.
This connects with a probe running in another process. It will
coordinate the remote instantiation of the probe if it's not running.
@method connectExternal
@protected
@param monitorJSON {Object} - An object containing:
@param monitorJSON.probeClass {String} - The probe class name (required)
@param monitorJSON.initParams {Object} - Probe initialization parameters (if any)
@param connection {Connection} - The connection to use
@param callback {Function(error, probeProxy)} - Called when connected | [
"Connect",
"to",
"an",
"external",
"probe",
"implementation",
"."
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9994-L10041 | |
23,209 | lorenwest/node-monitor | dist/monitor-all.js | function(connection, probeId, callback) {
var t = this, proxy = connection.remoteProbesById[probeId];
if (!proxy) {return callback('Probe not running');}
if (--proxy.refCount === 0) {
// Release probe resources
proxy.release();
proxy.connection = null;
delete connection.remoteProbesById[probeId];
delete connection.remoteProbeIdsByKey[proxy.probeKey];
connection.removeEvent('probe:change:' + probeId);
return connection.emit('probe:disconnect', {probeId:probeId}, function(error){
return callback(error);
});
}
callback(null);
} | javascript | function(connection, probeId, callback) {
var t = this, proxy = connection.remoteProbesById[probeId];
if (!proxy) {return callback('Probe not running');}
if (--proxy.refCount === 0) {
// Release probe resources
proxy.release();
proxy.connection = null;
delete connection.remoteProbesById[probeId];
delete connection.remoteProbeIdsByKey[proxy.probeKey];
connection.removeEvent('probe:change:' + probeId);
return connection.emit('probe:disconnect', {probeId:probeId}, function(error){
return callback(error);
});
}
callback(null);
} | [
"function",
"(",
"connection",
",",
"probeId",
",",
"callback",
")",
"{",
"var",
"t",
"=",
"this",
",",
"proxy",
"=",
"connection",
".",
"remoteProbesById",
"[",
"probeId",
"]",
";",
"if",
"(",
"!",
"proxy",
")",
"{",
"return",
"callback",
"(",
"'Probe not running'",
")",
";",
"}",
"if",
"(",
"--",
"proxy",
".",
"refCount",
"===",
"0",
")",
"{",
"// Release probe resources",
"proxy",
".",
"release",
"(",
")",
";",
"proxy",
".",
"connection",
"=",
"null",
";",
"delete",
"connection",
".",
"remoteProbesById",
"[",
"probeId",
"]",
";",
"delete",
"connection",
".",
"remoteProbeIdsByKey",
"[",
"proxy",
".",
"probeKey",
"]",
";",
"connection",
".",
"removeEvent",
"(",
"'probe:change:'",
"+",
"probeId",
")",
";",
"return",
"connection",
".",
"emit",
"(",
"'probe:disconnect'",
",",
"{",
"probeId",
":",
"probeId",
"}",
",",
"function",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
"callback",
"(",
"null",
")",
";",
"}"
] | Disconnect with an external probe implementation.
@method disconnectExternal
@protected
@param connection {Connection} - The connection to use
@param probeId {String} - Probe ID
@param callback {Function(error)} - Called when disconnected | [
"Disconnect",
"with",
"an",
"external",
"probe",
"implementation",
"."
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10052-L10067 | |
23,210 | lorenwest/node-monitor | dist/monitor-all.js | function(error) {
// Don't connect the instance monitor if errors
if (error) {
return callback(error);
}
// Called to disconnect the listeners
var disconnectListeners = function() {
logger.info('disconnectLiveSync', t.className, model.toJSON());
model.off('change', modelListener);
model.syncMonitor.off('change', monitorListener);
model.syncMonitor.disconnect();
model.syncMonitor = null;
};
// Client-side listener - for persisting changes to the server
var modelListener = function(changedModel, options) {
options = options || {};
// Don't persist unless the model is different
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(model.syncMonitor.get('model'))))) {
logger.info('modelListener.noChanges', t.className, model.toJSON());
return;
}
// Disconnect listeners if the ID changes
if (model.get('id') !== modelId) {
logger.info('modelListener.alteredId', t.className, model.toJSON());
return disconnectListeners();
}
// Persist changes to the server (unless the changes originated from there)
if (!options.isSyncChanging) {
logger.info('modelListener.saving', t.className, model.toJSON());
model.save();
}
};
// Server-side listener - for updating server changes into the model
var monitorListener = function(changedModel, options) {
// Don't update unless the model is different
var newModel = model.syncMonitor.get('model');
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(newModel)))) {
logger.info('monitorListener.noChanges', t.className, newModel);
return;
}
// Disconnect if the model was deleted or the ID isn't the same
var isDeleted = (_.size(newModel) === 0);
if (isDeleted || newModel.id !== modelId) {
logger.info('modelListener.deleted', t.className, newModel);
disconnectListeners();
}
// Forward changes to the model (including server-side delete)
var newOpts = {isSyncChanging:true};
if (isDeleted) {
logger.info('modelListener.deleting', t.className, newModel);
model.clear(newOpts);
} else {
// Make sure the model is set to exactly the new contents (vs. override)
logger.info('modelListener.setting', t.className, newModel);
model.clear({silent:true});
model.set(newModel, newOpts);
}
};
// Connect the listeners
model.on('change', modelListener);
model.syncMonitor.on('change', monitorListener);
// Send back the initial data model
logger.info('connectInstanceMonitor.done', t.className, model.toJSON());
callback(null, model.syncMonitor.get('model'));
} | javascript | function(error) {
// Don't connect the instance monitor if errors
if (error) {
return callback(error);
}
// Called to disconnect the listeners
var disconnectListeners = function() {
logger.info('disconnectLiveSync', t.className, model.toJSON());
model.off('change', modelListener);
model.syncMonitor.off('change', monitorListener);
model.syncMonitor.disconnect();
model.syncMonitor = null;
};
// Client-side listener - for persisting changes to the server
var modelListener = function(changedModel, options) {
options = options || {};
// Don't persist unless the model is different
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(model.syncMonitor.get('model'))))) {
logger.info('modelListener.noChanges', t.className, model.toJSON());
return;
}
// Disconnect listeners if the ID changes
if (model.get('id') !== modelId) {
logger.info('modelListener.alteredId', t.className, model.toJSON());
return disconnectListeners();
}
// Persist changes to the server (unless the changes originated from there)
if (!options.isSyncChanging) {
logger.info('modelListener.saving', t.className, model.toJSON());
model.save();
}
};
// Server-side listener - for updating server changes into the model
var monitorListener = function(changedModel, options) {
// Don't update unless the model is different
var newModel = model.syncMonitor.get('model');
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(newModel)))) {
logger.info('monitorListener.noChanges', t.className, newModel);
return;
}
// Disconnect if the model was deleted or the ID isn't the same
var isDeleted = (_.size(newModel) === 0);
if (isDeleted || newModel.id !== modelId) {
logger.info('modelListener.deleted', t.className, newModel);
disconnectListeners();
}
// Forward changes to the model (including server-side delete)
var newOpts = {isSyncChanging:true};
if (isDeleted) {
logger.info('modelListener.deleting', t.className, newModel);
model.clear(newOpts);
} else {
// Make sure the model is set to exactly the new contents (vs. override)
logger.info('modelListener.setting', t.className, newModel);
model.clear({silent:true});
model.set(newModel, newOpts);
}
};
// Connect the listeners
model.on('change', modelListener);
model.syncMonitor.on('change', monitorListener);
// Send back the initial data model
logger.info('connectInstanceMonitor.done', t.className, model.toJSON());
callback(null, model.syncMonitor.get('model'));
} | [
"function",
"(",
"error",
")",
"{",
"// Don't connect the instance monitor if errors",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"// Called to disconnect the listeners",
"var",
"disconnectListeners",
"=",
"function",
"(",
")",
"{",
"logger",
".",
"info",
"(",
"'disconnectLiveSync'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"model",
".",
"off",
"(",
"'change'",
",",
"modelListener",
")",
";",
"model",
".",
"syncMonitor",
".",
"off",
"(",
"'change'",
",",
"monitorListener",
")",
";",
"model",
".",
"syncMonitor",
".",
"disconnect",
"(",
")",
";",
"model",
".",
"syncMonitor",
"=",
"null",
";",
"}",
";",
"// Client-side listener - for persisting changes to the server",
"var",
"modelListener",
"=",
"function",
"(",
"changedModel",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// Don't persist unless the model is different",
"if",
"(",
"_",
".",
"isEqual",
"(",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"model",
")",
")",
",",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"model",
".",
"syncMonitor",
".",
"get",
"(",
"'model'",
")",
")",
")",
")",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.noChanges'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"return",
";",
"}",
"// Disconnect listeners if the ID changes",
"if",
"(",
"model",
".",
"get",
"(",
"'id'",
")",
"!==",
"modelId",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.alteredId'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"return",
"disconnectListeners",
"(",
")",
";",
"}",
"// Persist changes to the server (unless the changes originated from there)",
"if",
"(",
"!",
"options",
".",
"isSyncChanging",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.saving'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"model",
".",
"save",
"(",
")",
";",
"}",
"}",
";",
"// Server-side listener - for updating server changes into the model",
"var",
"monitorListener",
"=",
"function",
"(",
"changedModel",
",",
"options",
")",
"{",
"// Don't update unless the model is different",
"var",
"newModel",
"=",
"model",
".",
"syncMonitor",
".",
"get",
"(",
"'model'",
")",
";",
"if",
"(",
"_",
".",
"isEqual",
"(",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"model",
")",
")",
",",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"newModel",
")",
")",
")",
")",
"{",
"logger",
".",
"info",
"(",
"'monitorListener.noChanges'",
",",
"t",
".",
"className",
",",
"newModel",
")",
";",
"return",
";",
"}",
"// Disconnect if the model was deleted or the ID isn't the same",
"var",
"isDeleted",
"=",
"(",
"_",
".",
"size",
"(",
"newModel",
")",
"===",
"0",
")",
";",
"if",
"(",
"isDeleted",
"||",
"newModel",
".",
"id",
"!==",
"modelId",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.deleted'",
",",
"t",
".",
"className",
",",
"newModel",
")",
";",
"disconnectListeners",
"(",
")",
";",
"}",
"// Forward changes to the model (including server-side delete)",
"var",
"newOpts",
"=",
"{",
"isSyncChanging",
":",
"true",
"}",
";",
"if",
"(",
"isDeleted",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.deleting'",
",",
"t",
".",
"className",
",",
"newModel",
")",
";",
"model",
".",
"clear",
"(",
"newOpts",
")",
";",
"}",
"else",
"{",
"// Make sure the model is set to exactly the new contents (vs. override)",
"logger",
".",
"info",
"(",
"'modelListener.setting'",
",",
"t",
".",
"className",
",",
"newModel",
")",
";",
"model",
".",
"clear",
"(",
"{",
"silent",
":",
"true",
"}",
")",
";",
"model",
".",
"set",
"(",
"newModel",
",",
"newOpts",
")",
";",
"}",
"}",
";",
"// Connect the listeners",
"model",
".",
"on",
"(",
"'change'",
",",
"modelListener",
")",
";",
"model",
".",
"syncMonitor",
".",
"on",
"(",
"'change'",
",",
"monitorListener",
")",
";",
"// Send back the initial data model",
"logger",
".",
"info",
"(",
"'connectInstanceMonitor.done'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"callback",
"(",
"null",
",",
"model",
".",
"syncMonitor",
".",
"get",
"(",
"'model'",
")",
")",
";",
"}"
] | Called when done connecting | [
"Called",
"when",
"done",
"connecting"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10340-L10416 | |
23,211 | lorenwest/node-monitor | dist/monitor-all.js | function() {
logger.info('disconnectLiveSync', t.className, model.toJSON());
model.off('change', modelListener);
model.syncMonitor.off('change', monitorListener);
model.syncMonitor.disconnect();
model.syncMonitor = null;
} | javascript | function() {
logger.info('disconnectLiveSync', t.className, model.toJSON());
model.off('change', modelListener);
model.syncMonitor.off('change', monitorListener);
model.syncMonitor.disconnect();
model.syncMonitor = null;
} | [
"function",
"(",
")",
"{",
"logger",
".",
"info",
"(",
"'disconnectLiveSync'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"model",
".",
"off",
"(",
"'change'",
",",
"modelListener",
")",
";",
"model",
".",
"syncMonitor",
".",
"off",
"(",
"'change'",
",",
"monitorListener",
")",
";",
"model",
".",
"syncMonitor",
".",
"disconnect",
"(",
")",
";",
"model",
".",
"syncMonitor",
"=",
"null",
";",
"}"
] | Called to disconnect the listeners | [
"Called",
"to",
"disconnect",
"the",
"listeners"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10348-L10354 | |
23,212 | lorenwest/node-monitor | dist/monitor-all.js | function(changedModel, options) {
options = options || {};
// Don't persist unless the model is different
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(model.syncMonitor.get('model'))))) {
logger.info('modelListener.noChanges', t.className, model.toJSON());
return;
}
// Disconnect listeners if the ID changes
if (model.get('id') !== modelId) {
logger.info('modelListener.alteredId', t.className, model.toJSON());
return disconnectListeners();
}
// Persist changes to the server (unless the changes originated from there)
if (!options.isSyncChanging) {
logger.info('modelListener.saving', t.className, model.toJSON());
model.save();
}
} | javascript | function(changedModel, options) {
options = options || {};
// Don't persist unless the model is different
if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(model.syncMonitor.get('model'))))) {
logger.info('modelListener.noChanges', t.className, model.toJSON());
return;
}
// Disconnect listeners if the ID changes
if (model.get('id') !== modelId) {
logger.info('modelListener.alteredId', t.className, model.toJSON());
return disconnectListeners();
}
// Persist changes to the server (unless the changes originated from there)
if (!options.isSyncChanging) {
logger.info('modelListener.saving', t.className, model.toJSON());
model.save();
}
} | [
"function",
"(",
"changedModel",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// Don't persist unless the model is different",
"if",
"(",
"_",
".",
"isEqual",
"(",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"model",
")",
")",
",",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"model",
".",
"syncMonitor",
".",
"get",
"(",
"'model'",
")",
")",
")",
")",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.noChanges'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"return",
";",
"}",
"// Disconnect listeners if the ID changes",
"if",
"(",
"model",
".",
"get",
"(",
"'id'",
")",
"!==",
"modelId",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.alteredId'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"return",
"disconnectListeners",
"(",
")",
";",
"}",
"// Persist changes to the server (unless the changes originated from there)",
"if",
"(",
"!",
"options",
".",
"isSyncChanging",
")",
"{",
"logger",
".",
"info",
"(",
"'modelListener.saving'",
",",
"t",
".",
"className",
",",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"model",
".",
"save",
"(",
")",
";",
"}",
"}"
] | Client-side listener - for persisting changes to the server | [
"Client",
"-",
"side",
"listener",
"-",
"for",
"persisting",
"changes",
"to",
"the",
"server"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10357-L10377 | |
23,213 | lorenwest/node-monitor | dist/monitor-all.js | function(params, callback) {
var t = this,
connectError = false,
monitors = t.get('monitors');
if (t.get('started')) {
var err = {code:'RUNNING', msg:'Cannot start - the recipe is already running.'};
logger.warn(err);
return callback(err);
}
// Called when a monitor has connected
var onConnect = function(error) {
if (connectError) {return;}
if (error) {
var err = {code:'CONNECT_ERROR', err: error};
connectError = true;
logger.error('start', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (!t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:true});
t.connectListeners(true);
callback();
};
// Connect all monitors
for (var name2 in monitors) {
t.monitors[name2] = new Monitor(monitors[name2]);
t.monitors[name2].connect(onConnect);
}
} | javascript | function(params, callback) {
var t = this,
connectError = false,
monitors = t.get('monitors');
if (t.get('started')) {
var err = {code:'RUNNING', msg:'Cannot start - the recipe is already running.'};
logger.warn(err);
return callback(err);
}
// Called when a monitor has connected
var onConnect = function(error) {
if (connectError) {return;}
if (error) {
var err = {code:'CONNECT_ERROR', err: error};
connectError = true;
logger.error('start', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (!t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:true});
t.connectListeners(true);
callback();
};
// Connect all monitors
for (var name2 in monitors) {
t.monitors[name2] = new Monitor(monitors[name2]);
t.monitors[name2].connect(onConnect);
}
} | [
"function",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"t",
"=",
"this",
",",
"connectError",
"=",
"false",
",",
"monitors",
"=",
"t",
".",
"get",
"(",
"'monitors'",
")",
";",
"if",
"(",
"t",
".",
"get",
"(",
"'started'",
")",
")",
"{",
"var",
"err",
"=",
"{",
"code",
":",
"'RUNNING'",
",",
"msg",
":",
"'Cannot start - the recipe is already running.'",
"}",
";",
"logger",
".",
"warn",
"(",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Called when a monitor has connected",
"var",
"onConnect",
"=",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"connectError",
")",
"{",
"return",
";",
"}",
"if",
"(",
"error",
")",
"{",
"var",
"err",
"=",
"{",
"code",
":",
"'CONNECT_ERROR'",
",",
"err",
":",
"error",
"}",
";",
"connectError",
"=",
"true",
";",
"logger",
".",
"error",
"(",
"'start'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"for",
"(",
"var",
"name1",
"in",
"t",
".",
"monitors",
")",
"{",
"if",
"(",
"!",
"t",
".",
"monitors",
"[",
"name1",
"]",
".",
"isConnected",
"(",
")",
")",
"{",
"return",
";",
"}",
"}",
"t",
".",
"set",
"(",
"{",
"started",
":",
"true",
"}",
")",
";",
"t",
".",
"connectListeners",
"(",
"true",
")",
";",
"callback",
"(",
")",
";",
"}",
";",
"// Connect all monitors",
"for",
"(",
"var",
"name2",
"in",
"monitors",
")",
"{",
"t",
".",
"monitors",
"[",
"name2",
"]",
"=",
"new",
"Monitor",
"(",
"monitors",
"[",
"name2",
"]",
")",
";",
"t",
".",
"monitors",
"[",
"name2",
"]",
".",
"connect",
"(",
"onConnect",
")",
";",
"}",
"}"
] | Start the recipe
This connects to each monitor and sets up the recipe triggers
@method start_control | [
"Start",
"the",
"recipe"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10654-L10690 | |
23,214 | lorenwest/node-monitor | dist/monitor-all.js | function(error) {
if (connectError) {return;}
if (error) {
var err = {code:'CONNECT_ERROR', err: error};
connectError = true;
logger.error('start', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (!t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:true});
t.connectListeners(true);
callback();
} | javascript | function(error) {
if (connectError) {return;}
if (error) {
var err = {code:'CONNECT_ERROR', err: error};
connectError = true;
logger.error('start', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (!t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:true});
t.connectListeners(true);
callback();
} | [
"function",
"(",
"error",
")",
"{",
"if",
"(",
"connectError",
")",
"{",
"return",
";",
"}",
"if",
"(",
"error",
")",
"{",
"var",
"err",
"=",
"{",
"code",
":",
"'CONNECT_ERROR'",
",",
"err",
":",
"error",
"}",
";",
"connectError",
"=",
"true",
";",
"logger",
".",
"error",
"(",
"'start'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"for",
"(",
"var",
"name1",
"in",
"t",
".",
"monitors",
")",
"{",
"if",
"(",
"!",
"t",
".",
"monitors",
"[",
"name1",
"]",
".",
"isConnected",
"(",
")",
")",
"{",
"return",
";",
"}",
"}",
"t",
".",
"set",
"(",
"{",
"started",
":",
"true",
"}",
")",
";",
"t",
".",
"connectListeners",
"(",
"true",
")",
";",
"callback",
"(",
")",
";",
"}"
] | Called when a monitor has connected | [
"Called",
"when",
"a",
"monitor",
"has",
"connected"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10666-L10682 | |
23,215 | lorenwest/node-monitor | dist/monitor-all.js | function(params, callback) {
var t = this,
disconnectError = false;
if (!t.get('started')) {
var err = {code:'NOT_RUNNING', msg:'The recipe is already stopped.'};
logger.warn('precondition', err);
return callback(err);
}
// Called when a monitor has disconnected
var onDisconnect = function(error) {
if (disconnectError) {return;}
if (error) {
var err = {code:'DISONNECT_ERROR', err: error};
disconnectError = true;
logger.error('onDisconnect', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:false});
t.compiledScript = null;
callback();
};
// Disconnect all monitors
t.connectListeners(false);
t.context = null;
for (var name2 in t.monitors) {
t.monitors[name2].disconnect(onDisconnect);
}
} | javascript | function(params, callback) {
var t = this,
disconnectError = false;
if (!t.get('started')) {
var err = {code:'NOT_RUNNING', msg:'The recipe is already stopped.'};
logger.warn('precondition', err);
return callback(err);
}
// Called when a monitor has disconnected
var onDisconnect = function(error) {
if (disconnectError) {return;}
if (error) {
var err = {code:'DISONNECT_ERROR', err: error};
disconnectError = true;
logger.error('onDisconnect', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:false});
t.compiledScript = null;
callback();
};
// Disconnect all monitors
t.connectListeners(false);
t.context = null;
for (var name2 in t.monitors) {
t.monitors[name2].disconnect(onDisconnect);
}
} | [
"function",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"t",
"=",
"this",
",",
"disconnectError",
"=",
"false",
";",
"if",
"(",
"!",
"t",
".",
"get",
"(",
"'started'",
")",
")",
"{",
"var",
"err",
"=",
"{",
"code",
":",
"'NOT_RUNNING'",
",",
"msg",
":",
"'The recipe is already stopped.'",
"}",
";",
"logger",
".",
"warn",
"(",
"'precondition'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Called when a monitor has disconnected",
"var",
"onDisconnect",
"=",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"disconnectError",
")",
"{",
"return",
";",
"}",
"if",
"(",
"error",
")",
"{",
"var",
"err",
"=",
"{",
"code",
":",
"'DISONNECT_ERROR'",
",",
"err",
":",
"error",
"}",
";",
"disconnectError",
"=",
"true",
";",
"logger",
".",
"error",
"(",
"'onDisconnect'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"for",
"(",
"var",
"name1",
"in",
"t",
".",
"monitors",
")",
"{",
"if",
"(",
"t",
".",
"monitors",
"[",
"name1",
"]",
".",
"isConnected",
"(",
")",
")",
"{",
"return",
";",
"}",
"}",
"t",
".",
"set",
"(",
"{",
"started",
":",
"false",
"}",
")",
";",
"t",
".",
"compiledScript",
"=",
"null",
";",
"callback",
"(",
")",
";",
"}",
";",
"// Disconnect all monitors",
"t",
".",
"connectListeners",
"(",
"false",
")",
";",
"t",
".",
"context",
"=",
"null",
";",
"for",
"(",
"var",
"name2",
"in",
"t",
".",
"monitors",
")",
"{",
"t",
".",
"monitors",
"[",
"name2",
"]",
".",
"disconnect",
"(",
"onDisconnect",
")",
";",
"}",
"}"
] | Stop the recipe
This disconnects each monitor
@method stop_control | [
"Stop",
"the",
"recipe"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10699-L10734 | |
23,216 | lorenwest/node-monitor | dist/monitor-all.js | function(error) {
if (disconnectError) {return;}
if (error) {
var err = {code:'DISONNECT_ERROR', err: error};
disconnectError = true;
logger.error('onDisconnect', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:false});
t.compiledScript = null;
callback();
} | javascript | function(error) {
if (disconnectError) {return;}
if (error) {
var err = {code:'DISONNECT_ERROR', err: error};
disconnectError = true;
logger.error('onDisconnect', err);
return callback(err);
}
for (var name1 in t.monitors) {
if (t.monitors[name1].isConnected()) {
return;
}
}
t.set({started:false});
t.compiledScript = null;
callback();
} | [
"function",
"(",
"error",
")",
"{",
"if",
"(",
"disconnectError",
")",
"{",
"return",
";",
"}",
"if",
"(",
"error",
")",
"{",
"var",
"err",
"=",
"{",
"code",
":",
"'DISONNECT_ERROR'",
",",
"err",
":",
"error",
"}",
";",
"disconnectError",
"=",
"true",
";",
"logger",
".",
"error",
"(",
"'onDisconnect'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"for",
"(",
"var",
"name1",
"in",
"t",
".",
"monitors",
")",
"{",
"if",
"(",
"t",
".",
"monitors",
"[",
"name1",
"]",
".",
"isConnected",
"(",
")",
")",
"{",
"return",
";",
"}",
"}",
"t",
".",
"set",
"(",
"{",
"started",
":",
"false",
"}",
")",
";",
"t",
".",
"compiledScript",
"=",
"null",
";",
"callback",
"(",
")",
";",
"}"
] | Called when a monitor has disconnected | [
"Called",
"when",
"a",
"monitor",
"has",
"disconnected"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10710-L10726 | |
23,217 | lorenwest/node-monitor | dist/monitor-all.js | function(connect) {
var t = this,
triggeredBy = t.get('triggeredBy'),
onTrigger = t.onTrigger.bind(t);
// Default to listen on changes to all monitors
if (!triggeredBy) {
for (var monitorName in t.monitors) {
t.monitors[monitorName][connect ? 'on' : 'off']('change', t.onTrigger, t);
}
return;
}
// Process the elements in triggeredBy
for (var name in triggeredBy) {
var value = triggeredBy[name];
// Construct a new cron job
if (name === 'cron') {
if (connect) {
t.cronJob = new Cron.CronJob(value, onTrigger);
}
else {
if (t.cronJob.initiated) {
clearInterval(t.CronJob.timer);
}
else {
setTimeout(function(){clearInterval(t.cronJob.timer);}, 1000);
}
}
}
// Set a polling interval
else if (name === 'interval') {
if (connect) {
t.interval = setInterval(onTrigger, value);
}
else {
clearInterval(t.interval);
t.interval = null;
}
}
// Must be a monitor name
else {
t.monitors[name][connect ? 'on' : 'off'](value, onTrigger);
}
}
} | javascript | function(connect) {
var t = this,
triggeredBy = t.get('triggeredBy'),
onTrigger = t.onTrigger.bind(t);
// Default to listen on changes to all monitors
if (!triggeredBy) {
for (var monitorName in t.monitors) {
t.monitors[monitorName][connect ? 'on' : 'off']('change', t.onTrigger, t);
}
return;
}
// Process the elements in triggeredBy
for (var name in triggeredBy) {
var value = triggeredBy[name];
// Construct a new cron job
if (name === 'cron') {
if (connect) {
t.cronJob = new Cron.CronJob(value, onTrigger);
}
else {
if (t.cronJob.initiated) {
clearInterval(t.CronJob.timer);
}
else {
setTimeout(function(){clearInterval(t.cronJob.timer);}, 1000);
}
}
}
// Set a polling interval
else if (name === 'interval') {
if (connect) {
t.interval = setInterval(onTrigger, value);
}
else {
clearInterval(t.interval);
t.interval = null;
}
}
// Must be a monitor name
else {
t.monitors[name][connect ? 'on' : 'off'](value, onTrigger);
}
}
} | [
"function",
"(",
"connect",
")",
"{",
"var",
"t",
"=",
"this",
",",
"triggeredBy",
"=",
"t",
".",
"get",
"(",
"'triggeredBy'",
")",
",",
"onTrigger",
"=",
"t",
".",
"onTrigger",
".",
"bind",
"(",
"t",
")",
";",
"// Default to listen on changes to all monitors",
"if",
"(",
"!",
"triggeredBy",
")",
"{",
"for",
"(",
"var",
"monitorName",
"in",
"t",
".",
"monitors",
")",
"{",
"t",
".",
"monitors",
"[",
"monitorName",
"]",
"[",
"connect",
"?",
"'on'",
":",
"'off'",
"]",
"(",
"'change'",
",",
"t",
".",
"onTrigger",
",",
"t",
")",
";",
"}",
"return",
";",
"}",
"// Process the elements in triggeredBy",
"for",
"(",
"var",
"name",
"in",
"triggeredBy",
")",
"{",
"var",
"value",
"=",
"triggeredBy",
"[",
"name",
"]",
";",
"// Construct a new cron job",
"if",
"(",
"name",
"===",
"'cron'",
")",
"{",
"if",
"(",
"connect",
")",
"{",
"t",
".",
"cronJob",
"=",
"new",
"Cron",
".",
"CronJob",
"(",
"value",
",",
"onTrigger",
")",
";",
"}",
"else",
"{",
"if",
"(",
"t",
".",
"cronJob",
".",
"initiated",
")",
"{",
"clearInterval",
"(",
"t",
".",
"CronJob",
".",
"timer",
")",
";",
"}",
"else",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"clearInterval",
"(",
"t",
".",
"cronJob",
".",
"timer",
")",
";",
"}",
",",
"1000",
")",
";",
"}",
"}",
"}",
"// Set a polling interval",
"else",
"if",
"(",
"name",
"===",
"'interval'",
")",
"{",
"if",
"(",
"connect",
")",
"{",
"t",
".",
"interval",
"=",
"setInterval",
"(",
"onTrigger",
",",
"value",
")",
";",
"}",
"else",
"{",
"clearInterval",
"(",
"t",
".",
"interval",
")",
";",
"t",
".",
"interval",
"=",
"null",
";",
"}",
"}",
"// Must be a monitor name",
"else",
"{",
"t",
".",
"monitors",
"[",
"name",
"]",
"[",
"connect",
"?",
"'on'",
":",
"'off'",
"]",
"(",
"value",
",",
"onTrigger",
")",
";",
"}",
"}",
"}"
] | Connect the change listeners
@private
@method connectListeners | [
"Connect",
"the",
"change",
"listeners"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10742-L10790 | |
23,218 | lorenwest/node-monitor | dist/monitor-all.js | function(params, callback) {
var t = this,
error = null;
if (!t.get('started')) {
error = {code:'NOT_RUNNING', msg:'Cannot run - recipe not started.'};
logger.warn(error);
return callback(error);
}
// Name the probe
t.name = t.get('probeName') || t.get('id');
// Build a context to pass onto the script. The context contains
// a console, a logger, and each monitor by name.
if (!t.context) {
t.context = vm ? vm.createContext({}) : {};
t.context.console = console;
t.context.logger = Monitor.getLogger('Recipe.run.' + t.name);
for (var monitorName in t.monitors) {
t.context[monitorName] = t.monitors[monitorName];
}
}
// Run the script
try {
t.run(t.context);
} catch(e) {
error = "Error running script: " + e.toString();
logger.error('run_control', error);
}
callback(error);
} | javascript | function(params, callback) {
var t = this,
error = null;
if (!t.get('started')) {
error = {code:'NOT_RUNNING', msg:'Cannot run - recipe not started.'};
logger.warn(error);
return callback(error);
}
// Name the probe
t.name = t.get('probeName') || t.get('id');
// Build a context to pass onto the script. The context contains
// a console, a logger, and each monitor by name.
if (!t.context) {
t.context = vm ? vm.createContext({}) : {};
t.context.console = console;
t.context.logger = Monitor.getLogger('Recipe.run.' + t.name);
for (var monitorName in t.monitors) {
t.context[monitorName] = t.monitors[monitorName];
}
}
// Run the script
try {
t.run(t.context);
} catch(e) {
error = "Error running script: " + e.toString();
logger.error('run_control', error);
}
callback(error);
} | [
"function",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"t",
"=",
"this",
",",
"error",
"=",
"null",
";",
"if",
"(",
"!",
"t",
".",
"get",
"(",
"'started'",
")",
")",
"{",
"error",
"=",
"{",
"code",
":",
"'NOT_RUNNING'",
",",
"msg",
":",
"'Cannot run - recipe not started.'",
"}",
";",
"logger",
".",
"warn",
"(",
"error",
")",
";",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"// Name the probe",
"t",
".",
"name",
"=",
"t",
".",
"get",
"(",
"'probeName'",
")",
"||",
"t",
".",
"get",
"(",
"'id'",
")",
";",
"// Build a context to pass onto the script. The context contains",
"// a console, a logger, and each monitor by name.",
"if",
"(",
"!",
"t",
".",
"context",
")",
"{",
"t",
".",
"context",
"=",
"vm",
"?",
"vm",
".",
"createContext",
"(",
"{",
"}",
")",
":",
"{",
"}",
";",
"t",
".",
"context",
".",
"console",
"=",
"console",
";",
"t",
".",
"context",
".",
"logger",
"=",
"Monitor",
".",
"getLogger",
"(",
"'Recipe.run.'",
"+",
"t",
".",
"name",
")",
";",
"for",
"(",
"var",
"monitorName",
"in",
"t",
".",
"monitors",
")",
"{",
"t",
".",
"context",
"[",
"monitorName",
"]",
"=",
"t",
".",
"monitors",
"[",
"monitorName",
"]",
";",
"}",
"}",
"// Run the script",
"try",
"{",
"t",
".",
"run",
"(",
"t",
".",
"context",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"error",
"=",
"\"Error running script: \"",
"+",
"e",
".",
"toString",
"(",
")",
";",
"logger",
".",
"error",
"(",
"'run_control'",
",",
"error",
")",
";",
"}",
"callback",
"(",
"error",
")",
";",
"}"
] | Run the recipe script
This manually runs a started recipe. The callback is called immediately
after executing the script.
@method run_control | [
"Run",
"the",
"recipe",
"script"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10815-L10846 | |
23,219 | lorenwest/node-monitor | dist/monitor-all.js | function(context) {
var varName,
localVars = [];
for (varName in context) {
localVars.push('var ' + varName + ' = context.' + varName + ';');
}
return localVars.join('\n');
} | javascript | function(context) {
var varName,
localVars = [];
for (varName in context) {
localVars.push('var ' + varName + ' = context.' + varName + ';');
}
return localVars.join('\n');
} | [
"function",
"(",
"context",
")",
"{",
"var",
"varName",
",",
"localVars",
"=",
"[",
"]",
";",
"for",
"(",
"varName",
"in",
"context",
")",
"{",
"localVars",
".",
"push",
"(",
"'var '",
"+",
"varName",
"+",
"' = context.'",
"+",
"varName",
"+",
"';'",
")",
";",
"}",
"return",
"localVars",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] | Generate a script that brings context members into local scope
@private
@method bringLocal | [
"Generate",
"a",
"script",
"that",
"brings",
"context",
"members",
"into",
"local",
"scope"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L10883-L10890 | |
23,220 | lorenwest/node-monitor | dist/monitor-all.js | function(item) {
var t = this,
now = Date.now(),
msSinceLastSend = now - t.lastSendTime;
// Queue the item
t.queue.push(item);
// Send the bundle?
if (msSinceLastSend > t.interval) {
// It's been a while since the last send. Send it now.
t._send();
}
else {
// Start the timer if it's not already running
if (!t.timer) {
t.timer = setTimeout(function(){
t._send();
}, t.interval - msSinceLastSend);
}
}
} | javascript | function(item) {
var t = this,
now = Date.now(),
msSinceLastSend = now - t.lastSendTime;
// Queue the item
t.queue.push(item);
// Send the bundle?
if (msSinceLastSend > t.interval) {
// It's been a while since the last send. Send it now.
t._send();
}
else {
// Start the timer if it's not already running
if (!t.timer) {
t.timer = setTimeout(function(){
t._send();
}, t.interval - msSinceLastSend);
}
}
} | [
"function",
"(",
"item",
")",
"{",
"var",
"t",
"=",
"this",
",",
"now",
"=",
"Date",
".",
"now",
"(",
")",
",",
"msSinceLastSend",
"=",
"now",
"-",
"t",
".",
"lastSendTime",
";",
"// Queue the item",
"t",
".",
"queue",
".",
"push",
"(",
"item",
")",
";",
"// Send the bundle?",
"if",
"(",
"msSinceLastSend",
">",
"t",
".",
"interval",
")",
"{",
"// It's been a while since the last send. Send it now.",
"t",
".",
"_send",
"(",
")",
";",
"}",
"else",
"{",
"// Start the timer if it's not already running",
"if",
"(",
"!",
"t",
".",
"timer",
")",
"{",
"t",
".",
"timer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"t",
".",
"_send",
"(",
")",
";",
"}",
",",
"t",
".",
"interval",
"-",
"msSinceLastSend",
")",
";",
"}",
"}",
"}"
] | Queue an item in the stream
This method places the item into the stream and outputs it to the
monitor, or queues it up for the next bundle.
@method queueItem
@param item {Any} Item to place into the queue | [
"Queue",
"an",
"item",
"in",
"the",
"stream"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L11062-L11083 | |
23,221 | lorenwest/node-monitor | dist/monitor-all.js | function() {
var t = this,
now = Date.now();
// This kicks off the send
t.lastSendTime = now;
t.set({
bundle: t.queue,
sequence: t.get('sequence') + 1
});
// Reset
t.queue = [];
if (t.timer) {
clearTimeout(t.timer);
t.timer = null;
}
} | javascript | function() {
var t = this,
now = Date.now();
// This kicks off the send
t.lastSendTime = now;
t.set({
bundle: t.queue,
sequence: t.get('sequence') + 1
});
// Reset
t.queue = [];
if (t.timer) {
clearTimeout(t.timer);
t.timer = null;
}
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
",",
"now",
"=",
"Date",
".",
"now",
"(",
")",
";",
"// This kicks off the send",
"t",
".",
"lastSendTime",
"=",
"now",
";",
"t",
".",
"set",
"(",
"{",
"bundle",
":",
"t",
".",
"queue",
",",
"sequence",
":",
"t",
".",
"get",
"(",
"'sequence'",
")",
"+",
"1",
"}",
")",
";",
"// Reset",
"t",
".",
"queue",
"=",
"[",
"]",
";",
"if",
"(",
"t",
".",
"timer",
")",
"{",
"clearTimeout",
"(",
"t",
".",
"timer",
")",
";",
"t",
".",
"timer",
"=",
"null",
";",
"}",
"}"
] | Send the bundle to the montitor
@private
@method _send | [
"Send",
"the",
"bundle",
"to",
"the",
"montitor"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L11091-L11108 | |
23,222 | lorenwest/node-monitor | lib/probes/FileSyncProbe.js | function(error, content) {
var isInitializing = (callback !== null),
initCallback = callback;
callback = null;
if (error && error.code === 'ENOENT') {
// File doesn't exist. Set the model to null.
t.set({model: {}}, {silent: isInitializing});
// Convert the code from the sync probe spec
error.code = 'NOTFOUND';
}
if (error) {
if (isInitializing) {
t.release();
var err = {code: error.code, msg: 'LiveSync requires the file to exist and be readable'};
initCallback(err);
}
return;
}
// Parse the JSON content into a JS object.
try {
content = JSON.parse(content);
logger.info('fileParse', {id: t.get('modelId'), content: content});
} catch (e) {
// Fail the probe on first load error
if (isInitializing) {
t.release();
initCallback({code: 'BAD_FORMAT', msg: 'Non-JSON formatted file'});
}
// Nothing productive to do if the file can't be parsed. Just log it.
logger.error('fileParse', {error: e, id: t.get('modelId'), content: content});
return;
}
// Set the content into the model if it's different
// Have to compare raw objects because toJSON returns deep references to models
var priorModel = t.get('model');
if (!priorModel || !_.isEqual(content, JSON.parse(JSON.stringify(priorModel)))) {
t.set({model: content}, {silent: isInitializing});
}
// Call the initialization callback on first load
if (isInitializing) {
initCallback();
}
} | javascript | function(error, content) {
var isInitializing = (callback !== null),
initCallback = callback;
callback = null;
if (error && error.code === 'ENOENT') {
// File doesn't exist. Set the model to null.
t.set({model: {}}, {silent: isInitializing});
// Convert the code from the sync probe spec
error.code = 'NOTFOUND';
}
if (error) {
if (isInitializing) {
t.release();
var err = {code: error.code, msg: 'LiveSync requires the file to exist and be readable'};
initCallback(err);
}
return;
}
// Parse the JSON content into a JS object.
try {
content = JSON.parse(content);
logger.info('fileParse', {id: t.get('modelId'), content: content});
} catch (e) {
// Fail the probe on first load error
if (isInitializing) {
t.release();
initCallback({code: 'BAD_FORMAT', msg: 'Non-JSON formatted file'});
}
// Nothing productive to do if the file can't be parsed. Just log it.
logger.error('fileParse', {error: e, id: t.get('modelId'), content: content});
return;
}
// Set the content into the model if it's different
// Have to compare raw objects because toJSON returns deep references to models
var priorModel = t.get('model');
if (!priorModel || !_.isEqual(content, JSON.parse(JSON.stringify(priorModel)))) {
t.set({model: content}, {silent: isInitializing});
}
// Call the initialization callback on first load
if (isInitializing) {
initCallback();
}
} | [
"function",
"(",
"error",
",",
"content",
")",
"{",
"var",
"isInitializing",
"=",
"(",
"callback",
"!==",
"null",
")",
",",
"initCallback",
"=",
"callback",
";",
"callback",
"=",
"null",
";",
"if",
"(",
"error",
"&&",
"error",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"// File doesn't exist. Set the model to null.",
"t",
".",
"set",
"(",
"{",
"model",
":",
"{",
"}",
"}",
",",
"{",
"silent",
":",
"isInitializing",
"}",
")",
";",
"// Convert the code from the sync probe spec",
"error",
".",
"code",
"=",
"'NOTFOUND'",
";",
"}",
"if",
"(",
"error",
")",
"{",
"if",
"(",
"isInitializing",
")",
"{",
"t",
".",
"release",
"(",
")",
";",
"var",
"err",
"=",
"{",
"code",
":",
"error",
".",
"code",
",",
"msg",
":",
"'LiveSync requires the file to exist and be readable'",
"}",
";",
"initCallback",
"(",
"err",
")",
";",
"}",
"return",
";",
"}",
"// Parse the JSON content into a JS object.",
"try",
"{",
"content",
"=",
"JSON",
".",
"parse",
"(",
"content",
")",
";",
"logger",
".",
"info",
"(",
"'fileParse'",
",",
"{",
"id",
":",
"t",
".",
"get",
"(",
"'modelId'",
")",
",",
"content",
":",
"content",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Fail the probe on first load error",
"if",
"(",
"isInitializing",
")",
"{",
"t",
".",
"release",
"(",
")",
";",
"initCallback",
"(",
"{",
"code",
":",
"'BAD_FORMAT'",
",",
"msg",
":",
"'Non-JSON formatted file'",
"}",
")",
";",
"}",
"// Nothing productive to do if the file can't be parsed. Just log it.",
"logger",
".",
"error",
"(",
"'fileParse'",
",",
"{",
"error",
":",
"e",
",",
"id",
":",
"t",
".",
"get",
"(",
"'modelId'",
")",
",",
"content",
":",
"content",
"}",
")",
";",
"return",
";",
"}",
"// Set the content into the model if it's different",
"// Have to compare raw objects because toJSON returns deep references to models",
"var",
"priorModel",
"=",
"t",
".",
"get",
"(",
"'model'",
")",
";",
"if",
"(",
"!",
"priorModel",
"||",
"!",
"_",
".",
"isEqual",
"(",
"content",
",",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"priorModel",
")",
")",
")",
")",
"{",
"t",
".",
"set",
"(",
"{",
"model",
":",
"content",
"}",
",",
"{",
"silent",
":",
"isInitializing",
"}",
")",
";",
"}",
"// Call the initialization callback on first load",
"if",
"(",
"isInitializing",
")",
"{",
"initCallback",
"(",
")",
";",
"}",
"}"
] | Build the function to watch the file | [
"Build",
"the",
"function",
"to",
"watch",
"the",
"file"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/FileSyncProbe.js#L73-L122 | |
23,223 | lorenwest/node-monitor | lib/probes/FileSyncProbe.js | function(args, callback) {
// Make sure the ID exists
var t = this, model = args.model;
if (!model || !model.id) {
return callback({msg:'SyncProbe create - Data model with ID not present'});
}
// Make sure the file doesn't already exist
t.getFullPath(model.id, function(error, response) {
if (error) {
return callback(error);
}
if (response.stats) {
return callback({msg:'Document with this ID already exists'});
}
// Forward to the update control
t.update_control(args, callback);
});
} | javascript | function(args, callback) {
// Make sure the ID exists
var t = this, model = args.model;
if (!model || !model.id) {
return callback({msg:'SyncProbe create - Data model with ID not present'});
}
// Make sure the file doesn't already exist
t.getFullPath(model.id, function(error, response) {
if (error) {
return callback(error);
}
if (response.stats) {
return callback({msg:'Document with this ID already exists'});
}
// Forward to the update control
t.update_control(args, callback);
});
} | [
"function",
"(",
"args",
",",
"callback",
")",
"{",
"// Make sure the ID exists",
"var",
"t",
"=",
"this",
",",
"model",
"=",
"args",
".",
"model",
";",
"if",
"(",
"!",
"model",
"||",
"!",
"model",
".",
"id",
")",
"{",
"return",
"callback",
"(",
"{",
"msg",
":",
"'SyncProbe create - Data model with ID not present'",
"}",
")",
";",
"}",
"// Make sure the file doesn't already exist",
"t",
".",
"getFullPath",
"(",
"model",
".",
"id",
",",
"function",
"(",
"error",
",",
"response",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"if",
"(",
"response",
".",
"stats",
")",
"{",
"return",
"callback",
"(",
"{",
"msg",
":",
"'Document with this ID already exists'",
"}",
")",
";",
"}",
"// Forward to the update control",
"t",
".",
"update_control",
"(",
"args",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Documentation for these methods in SyncProbe | [
"Documentation",
"for",
"these",
"methods",
"in",
"SyncProbe"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/FileSyncProbe.js#L135-L155 | |
23,224 | lorenwest/node-monitor | lib/probes/FileSyncProbe.js | function(modelId, callback) {
var t = this,
dirPath = t.dirPath;
// Don't allow relative paths
var fullPath = Path.join(t.dirPath, modelId);
if (fullPath.indexOf(dirPath) !== 0) {
return callback({msg: 'Model ID ' + modelId + ' cannot represent a relative path'});
}
// See if the path represents a directory
FS.stat(fullPath, function(error, stats){
// If this is an existing directory, return a path to dir/index.json
if (!error && stats.isDirectory()) {
return t.getFullPath(modelId + '/index', callback);
}
// Normal case - return the path & stat to the json file
fullPath += '.json';
FS.stat(fullPath, function(error, stats){
// Not an error if error == ENOENT
if (error && error.code === 'ENOENT') {
error = null; stats = null;
}
// Process other FS errors
if (error) {
return callback({err: error, msg: "Error while observing file: " + fullPath});
}
// Forward the callback
return callback(null, {path: fullPath, stats: stats});
});
});
} | javascript | function(modelId, callback) {
var t = this,
dirPath = t.dirPath;
// Don't allow relative paths
var fullPath = Path.join(t.dirPath, modelId);
if (fullPath.indexOf(dirPath) !== 0) {
return callback({msg: 'Model ID ' + modelId + ' cannot represent a relative path'});
}
// See if the path represents a directory
FS.stat(fullPath, function(error, stats){
// If this is an existing directory, return a path to dir/index.json
if (!error && stats.isDirectory()) {
return t.getFullPath(modelId + '/index', callback);
}
// Normal case - return the path & stat to the json file
fullPath += '.json';
FS.stat(fullPath, function(error, stats){
// Not an error if error == ENOENT
if (error && error.code === 'ENOENT') {
error = null; stats = null;
}
// Process other FS errors
if (error) {
return callback({err: error, msg: "Error while observing file: " + fullPath});
}
// Forward the callback
return callback(null, {path: fullPath, stats: stats});
});
});
} | [
"function",
"(",
"modelId",
",",
"callback",
")",
"{",
"var",
"t",
"=",
"this",
",",
"dirPath",
"=",
"t",
".",
"dirPath",
";",
"// Don't allow relative paths",
"var",
"fullPath",
"=",
"Path",
".",
"join",
"(",
"t",
".",
"dirPath",
",",
"modelId",
")",
";",
"if",
"(",
"fullPath",
".",
"indexOf",
"(",
"dirPath",
")",
"!==",
"0",
")",
"{",
"return",
"callback",
"(",
"{",
"msg",
":",
"'Model ID '",
"+",
"modelId",
"+",
"' cannot represent a relative path'",
"}",
")",
";",
"}",
"// See if the path represents a directory",
"FS",
".",
"stat",
"(",
"fullPath",
",",
"function",
"(",
"error",
",",
"stats",
")",
"{",
"// If this is an existing directory, return a path to dir/index.json",
"if",
"(",
"!",
"error",
"&&",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"return",
"t",
".",
"getFullPath",
"(",
"modelId",
"+",
"'/index'",
",",
"callback",
")",
";",
"}",
"// Normal case - return the path & stat to the json file",
"fullPath",
"+=",
"'.json'",
";",
"FS",
".",
"stat",
"(",
"fullPath",
",",
"function",
"(",
"error",
",",
"stats",
")",
"{",
"// Not an error if error == ENOENT",
"if",
"(",
"error",
"&&",
"error",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"error",
"=",
"null",
";",
"stats",
"=",
"null",
";",
"}",
"// Process other FS errors",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"{",
"err",
":",
"error",
",",
"msg",
":",
"\"Error while observing file: \"",
"+",
"fullPath",
"}",
")",
";",
"}",
"// Forward the callback",
"return",
"callback",
"(",
"null",
",",
"{",
"path",
":",
"fullPath",
",",
"stats",
":",
"stats",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Get the full path to the file
This builds the full pathname to the file, and performs an fs.sync()
on that pathname, providing the pathname and sync object in the callback.
@method getFullPath
@param modelId {String} ID of the data model to sync
@param callback {Function(error, return)}
@param callback.error {Object} Error object (null if no error)
@param callback.return {Object} return object
@param callback.return.path {String} Full pathname to the file
@param callback.return.stat {fs.stats} Stats object (null if the file doesn't esixt) | [
"Get",
"the",
"full",
"path",
"to",
"the",
"file"
] | 7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8 | https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/FileSyncProbe.js#L275-L311 | |
23,225 | mscdex/node-ncurses | lib/widgets.js | extend | function extend() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !typeof target === 'function')
target = {};
var isPlainObject = function(obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval)
return false;
var has_own_constructor = hasOwnProperty.call(obj, "constructor");
var has_is_property_of_method = hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf");
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
return false;
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var last_key;
for (key in obj)
last_key = key;
return typeof last_key === "undefined" || hasOwnProperty.call(obj, last_key);
};
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) !== null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy)
continue;
// Recurse if we're merging object literal values or arrays
if (deep && copy && (isPlainObject(copy) || Array.isArray(copy))) {
var clone = src && (isPlainObject(src) || Array.isArray(src)) ? src : Array.isArray(copy) ? [] : {};
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (typeof copy !== "undefined")
target[name] = copy;
}
}
}
// Return the modified object
return target;
} | javascript | function extend() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !typeof target === 'function')
target = {};
var isPlainObject = function(obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval)
return false;
var has_own_constructor = hasOwnProperty.call(obj, "constructor");
var has_is_property_of_method = hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf");
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method)
return false;
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var last_key;
for (key in obj)
last_key = key;
return typeof last_key === "undefined" || hasOwnProperty.call(obj, last_key);
};
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) !== null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy)
continue;
// Recurse if we're merging object literal values or arrays
if (deep && copy && (isPlainObject(copy) || Array.isArray(copy))) {
var clone = src && (isPlainObject(src) || Array.isArray(src)) ? src : Array.isArray(copy) ? [] : {};
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (typeof copy !== "undefined")
target[name] = copy;
}
}
}
// Return the modified object
return target;
} | [
"function",
"extend",
"(",
")",
"{",
"// copy reference to target object",
"var",
"target",
"=",
"arguments",
"[",
"0",
"]",
"||",
"{",
"}",
",",
"i",
"=",
"1",
",",
"length",
"=",
"arguments",
".",
"length",
",",
"deep",
"=",
"false",
",",
"options",
",",
"name",
",",
"src",
",",
"copy",
";",
"// Handle a deep copy situation",
"if",
"(",
"typeof",
"target",
"===",
"\"boolean\"",
")",
"{",
"deep",
"=",
"target",
";",
"target",
"=",
"arguments",
"[",
"1",
"]",
"||",
"{",
"}",
";",
"// skip the boolean and the target",
"i",
"=",
"2",
";",
"}",
"// Handle case when target is a string or something (possible in deep copy)",
"if",
"(",
"typeof",
"target",
"!==",
"\"object\"",
"&&",
"!",
"typeof",
"target",
"===",
"'function'",
")",
"target",
"=",
"{",
"}",
";",
"var",
"isPlainObject",
"=",
"function",
"(",
"obj",
")",
"{",
"// Must be an Object.",
"// Because of IE, we also have to check the presence of the constructor property.",
"// Make sure that DOM nodes and window objects don't pass through, as well",
"if",
"(",
"!",
"obj",
"||",
"toString",
".",
"call",
"(",
"obj",
")",
"!==",
"\"[object Object]\"",
"||",
"obj",
".",
"nodeType",
"||",
"obj",
".",
"setInterval",
")",
"return",
"false",
";",
"var",
"has_own_constructor",
"=",
"hasOwnProperty",
".",
"call",
"(",
"obj",
",",
"\"constructor\"",
")",
";",
"var",
"has_is_property_of_method",
"=",
"hasOwnProperty",
".",
"call",
"(",
"obj",
".",
"constructor",
".",
"prototype",
",",
"\"isPrototypeOf\"",
")",
";",
"// Not own constructor property must be Object",
"if",
"(",
"obj",
".",
"constructor",
"&&",
"!",
"has_own_constructor",
"&&",
"!",
"has_is_property_of_method",
")",
"return",
"false",
";",
"// Own properties are enumerated firstly, so to speed up,",
"// if last one is own, then all properties are own.",
"var",
"last_key",
";",
"for",
"(",
"key",
"in",
"obj",
")",
"last_key",
"=",
"key",
";",
"return",
"typeof",
"last_key",
"===",
"\"undefined\"",
"||",
"hasOwnProperty",
".",
"call",
"(",
"obj",
",",
"last_key",
")",
";",
"}",
";",
"for",
"(",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"// Only deal with non-null/undefined values",
"if",
"(",
"(",
"options",
"=",
"arguments",
"[",
"i",
"]",
")",
"!==",
"null",
")",
"{",
"// Extend the base object",
"for",
"(",
"name",
"in",
"options",
")",
"{",
"src",
"=",
"target",
"[",
"name",
"]",
";",
"copy",
"=",
"options",
"[",
"name",
"]",
";",
"// Prevent never-ending loop",
"if",
"(",
"target",
"===",
"copy",
")",
"continue",
";",
"// Recurse if we're merging object literal values or arrays",
"if",
"(",
"deep",
"&&",
"copy",
"&&",
"(",
"isPlainObject",
"(",
"copy",
")",
"||",
"Array",
".",
"isArray",
"(",
"copy",
")",
")",
")",
"{",
"var",
"clone",
"=",
"src",
"&&",
"(",
"isPlainObject",
"(",
"src",
")",
"||",
"Array",
".",
"isArray",
"(",
"src",
")",
")",
"?",
"src",
":",
"Array",
".",
"isArray",
"(",
"copy",
")",
"?",
"[",
"]",
":",
"{",
"}",
";",
"// Never move original objects, clone them",
"target",
"[",
"name",
"]",
"=",
"extend",
"(",
"deep",
",",
"clone",
",",
"copy",
")",
";",
"// Don't bring in undefined values",
"}",
"else",
"if",
"(",
"typeof",
"copy",
"!==",
"\"undefined\"",
")",
"target",
"[",
"name",
"]",
"=",
"copy",
";",
"}",
"}",
"}",
"// Return the modified object",
"return",
"target",
";",
"}"
] | Adopted from jquery's extend method. Under the terms of MIT License.
http://code.jquery.com/jquery-1.4.2.js
Modified by Brian White to use Array.isArray instead of the custom isArray method | [
"Adopted",
"from",
"jquery",
"s",
"extend",
"method",
".",
"Under",
"the",
"terms",
"of",
"MIT",
"License",
"."
] | f013b5584ac62eb002e63632c61d98daafd2c4c5 | https://github.com/mscdex/node-ncurses/blob/f013b5584ac62eb002e63632c61d98daafd2c4c5/lib/widgets.js#L959-L1013 |
23,226 | retextjs/retext-smartypants | index.js | transformFactory | function transformFactory(methods) {
var length = methods.length
return transformer
// Transformer.
function transformer(cst) {
visit(cst, visitor)
}
function visitor(node, position, parent) {
var index = -1
if (node.type === punctuation || node.type === symbol) {
while (++index < length) {
methods[index](node, position, parent)
}
}
}
} | javascript | function transformFactory(methods) {
var length = methods.length
return transformer
// Transformer.
function transformer(cst) {
visit(cst, visitor)
}
function visitor(node, position, parent) {
var index = -1
if (node.type === punctuation || node.type === symbol) {
while (++index < length) {
methods[index](node, position, parent)
}
}
}
} | [
"function",
"transformFactory",
"(",
"methods",
")",
"{",
"var",
"length",
"=",
"methods",
".",
"length",
"return",
"transformer",
"// Transformer.",
"function",
"transformer",
"(",
"cst",
")",
"{",
"visit",
"(",
"cst",
",",
"visitor",
")",
"}",
"function",
"visitor",
"(",
"node",
",",
"position",
",",
"parent",
")",
"{",
"var",
"index",
"=",
"-",
"1",
"if",
"(",
"node",
".",
"type",
"===",
"punctuation",
"||",
"node",
".",
"type",
"===",
"symbol",
")",
"{",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"methods",
"[",
"index",
"]",
"(",
"node",
",",
"position",
",",
"parent",
")",
"}",
"}",
"}",
"}"
] | Create a transformer for the bound methods. | [
"Create",
"a",
"transformer",
"for",
"the",
"bound",
"methods",
"."
] | 4d4ce9059db4f4cafd07a31fedc218c11738435f | https://github.com/retextjs/retext-smartypants/blob/4d4ce9059db4f4cafd07a31fedc218c11738435f/index.js#L175-L194 |
23,227 | retextjs/retext-smartypants | index.js | oldschool | function oldschool(node) {
if (node.value === threeDashes) {
node.value = emDash
} else if (node.value === twoDashes) {
node.value = enDash
}
} | javascript | function oldschool(node) {
if (node.value === threeDashes) {
node.value = emDash
} else if (node.value === twoDashes) {
node.value = enDash
}
} | [
"function",
"oldschool",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"value",
"===",
"threeDashes",
")",
"{",
"node",
".",
"value",
"=",
"emDash",
"}",
"else",
"if",
"(",
"node",
".",
"value",
"===",
"twoDashes",
")",
"{",
"node",
".",
"value",
"=",
"enDash",
"}",
"}"
] | Transform three dahes into an em-dash, and two into an en-dash. | [
"Transform",
"three",
"dahes",
"into",
"an",
"em",
"-",
"dash",
"and",
"two",
"into",
"an",
"en",
"-",
"dash",
"."
] | 4d4ce9059db4f4cafd07a31fedc218c11738435f | https://github.com/retextjs/retext-smartypants/blob/4d4ce9059db4f4cafd07a31fedc218c11738435f/index.js#L197-L203 |
23,228 | retextjs/retext-smartypants | index.js | inverted | function inverted(node) {
if (node.value === threeDashes) {
node.value = enDash
} else if (node.value === twoDashes) {
node.value = emDash
}
} | javascript | function inverted(node) {
if (node.value === threeDashes) {
node.value = enDash
} else if (node.value === twoDashes) {
node.value = emDash
}
} | [
"function",
"inverted",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"value",
"===",
"threeDashes",
")",
"{",
"node",
".",
"value",
"=",
"enDash",
"}",
"else",
"if",
"(",
"node",
".",
"value",
"===",
"twoDashes",
")",
"{",
"node",
".",
"value",
"=",
"emDash",
"}",
"}"
] | Transform three dahes into an en-dash, and two into an em-dash. | [
"Transform",
"three",
"dahes",
"into",
"an",
"en",
"-",
"dash",
"and",
"two",
"into",
"an",
"em",
"-",
"dash",
"."
] | 4d4ce9059db4f4cafd07a31fedc218c11738435f | https://github.com/retextjs/retext-smartypants/blob/4d4ce9059db4f4cafd07a31fedc218c11738435f/index.js#L213-L219 |
23,229 | retextjs/retext-smartypants | index.js | backticks | function backticks(node) {
if (node.value === twoBackticks) {
node.value = openingDoubleQuote
} else if (node.value === twoSingleQuotes) {
node.value = closingDoubleQuote
}
} | javascript | function backticks(node) {
if (node.value === twoBackticks) {
node.value = openingDoubleQuote
} else if (node.value === twoSingleQuotes) {
node.value = closingDoubleQuote
}
} | [
"function",
"backticks",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"value",
"===",
"twoBackticks",
")",
"{",
"node",
".",
"value",
"=",
"openingDoubleQuote",
"}",
"else",
"if",
"(",
"node",
".",
"value",
"===",
"twoSingleQuotes",
")",
"{",
"node",
".",
"value",
"=",
"closingDoubleQuote",
"}",
"}"
] | Transform double backticks and single quotes into smart quotes. | [
"Transform",
"double",
"backticks",
"and",
"single",
"quotes",
"into",
"smart",
"quotes",
"."
] | 4d4ce9059db4f4cafd07a31fedc218c11738435f | https://github.com/retextjs/retext-smartypants/blob/4d4ce9059db4f4cafd07a31fedc218c11738435f/index.js#L222-L228 |
23,230 | retextjs/retext-smartypants | index.js | all | function all(node) {
backticks(node)
if (node.value === backtick) {
node.value = openingSingleQuote
} else if (node.value === singleQuote) {
node.value = closingSingleQuote
}
} | javascript | function all(node) {
backticks(node)
if (node.value === backtick) {
node.value = openingSingleQuote
} else if (node.value === singleQuote) {
node.value = closingSingleQuote
}
} | [
"function",
"all",
"(",
"node",
")",
"{",
"backticks",
"(",
"node",
")",
"if",
"(",
"node",
".",
"value",
"===",
"backtick",
")",
"{",
"node",
".",
"value",
"=",
"openingSingleQuote",
"}",
"else",
"if",
"(",
"node",
".",
"value",
"===",
"singleQuote",
")",
"{",
"node",
".",
"value",
"=",
"closingSingleQuote",
"}",
"}"
] | Transform single and double backticks and single quotes into smart quotes. | [
"Transform",
"single",
"and",
"double",
"backticks",
"and",
"single",
"quotes",
"into",
"smart",
"quotes",
"."
] | 4d4ce9059db4f4cafd07a31fedc218c11738435f | https://github.com/retextjs/retext-smartypants/blob/4d4ce9059db4f4cafd07a31fedc218c11738435f/index.js#L231-L239 |
23,231 | retextjs/retext-smartypants | index.js | ellipses | function ellipses(node, index, parent) {
var value = node.value
var siblings = parent.children
var position
var nodes
var sibling
var type
var count
var queue
// Simple node with three dots and without white-space.
if (threeFullStopsExpression.test(node.value)) {
node.value = ellipsis
return
}
if (!fullStopsExpression.test(value)) {
return
}
// Search for dot-nodes with white-space between.
nodes = []
position = index
count = 1
// It’s possible that the node is merged with an adjacent word-node. In that
// code, we cannot transform it because there’s no reference to the
// grandparent.
while (--position > 0) {
sibling = siblings[position]
if (sibling.type !== whiteSpace) {
break
}
queue = sibling
sibling = siblings[--position]
type = sibling && sibling.type
if (
sibling &&
(type === punctuation || type === symbol) &&
fullStopsExpression.test(sibling.value)
) {
nodes.push(queue, sibling)
count++
continue
}
break
}
if (count < 3) {
return
}
siblings.splice(index - nodes.length, nodes.length)
node.value = ellipsis
} | javascript | function ellipses(node, index, parent) {
var value = node.value
var siblings = parent.children
var position
var nodes
var sibling
var type
var count
var queue
// Simple node with three dots and without white-space.
if (threeFullStopsExpression.test(node.value)) {
node.value = ellipsis
return
}
if (!fullStopsExpression.test(value)) {
return
}
// Search for dot-nodes with white-space between.
nodes = []
position = index
count = 1
// It’s possible that the node is merged with an adjacent word-node. In that
// code, we cannot transform it because there’s no reference to the
// grandparent.
while (--position > 0) {
sibling = siblings[position]
if (sibling.type !== whiteSpace) {
break
}
queue = sibling
sibling = siblings[--position]
type = sibling && sibling.type
if (
sibling &&
(type === punctuation || type === symbol) &&
fullStopsExpression.test(sibling.value)
) {
nodes.push(queue, sibling)
count++
continue
}
break
}
if (count < 3) {
return
}
siblings.splice(index - nodes.length, nodes.length)
node.value = ellipsis
} | [
"function",
"ellipses",
"(",
"node",
",",
"index",
",",
"parent",
")",
"{",
"var",
"value",
"=",
"node",
".",
"value",
"var",
"siblings",
"=",
"parent",
".",
"children",
"var",
"position",
"var",
"nodes",
"var",
"sibling",
"var",
"type",
"var",
"count",
"var",
"queue",
"// Simple node with three dots and without white-space.",
"if",
"(",
"threeFullStopsExpression",
".",
"test",
"(",
"node",
".",
"value",
")",
")",
"{",
"node",
".",
"value",
"=",
"ellipsis",
"return",
"}",
"if",
"(",
"!",
"fullStopsExpression",
".",
"test",
"(",
"value",
")",
")",
"{",
"return",
"}",
"// Search for dot-nodes with white-space between.",
"nodes",
"=",
"[",
"]",
"position",
"=",
"index",
"count",
"=",
"1",
"// It’s possible that the node is merged with an adjacent word-node. In that",
"// code, we cannot transform it because there’s no reference to the",
"// grandparent.",
"while",
"(",
"--",
"position",
">",
"0",
")",
"{",
"sibling",
"=",
"siblings",
"[",
"position",
"]",
"if",
"(",
"sibling",
".",
"type",
"!==",
"whiteSpace",
")",
"{",
"break",
"}",
"queue",
"=",
"sibling",
"sibling",
"=",
"siblings",
"[",
"--",
"position",
"]",
"type",
"=",
"sibling",
"&&",
"sibling",
".",
"type",
"if",
"(",
"sibling",
"&&",
"(",
"type",
"===",
"punctuation",
"||",
"type",
"===",
"symbol",
")",
"&&",
"fullStopsExpression",
".",
"test",
"(",
"sibling",
".",
"value",
")",
")",
"{",
"nodes",
".",
"push",
"(",
"queue",
",",
"sibling",
")",
"count",
"++",
"continue",
"}",
"break",
"}",
"if",
"(",
"count",
"<",
"3",
")",
"{",
"return",
"}",
"siblings",
".",
"splice",
"(",
"index",
"-",
"nodes",
".",
"length",
",",
"nodes",
".",
"length",
")",
"node",
".",
"value",
"=",
"ellipsis",
"}"
] | Transform multiple dots into unicode ellipses. | [
"Transform",
"multiple",
"dots",
"into",
"unicode",
"ellipses",
"."
] | 4d4ce9059db4f4cafd07a31fedc218c11738435f | https://github.com/retextjs/retext-smartypants/blob/4d4ce9059db4f4cafd07a31fedc218c11738435f/index.js#L242-L303 |
23,232 | retextjs/retext-smartypants | index.js | quotes | function quotes(node, index, parent) {
var siblings = parent.children
var value = node.value
var next
var nextNext
var prev
var nextValue
if (value !== doubleQuote && value !== singleQuote) {
return
}
prev = siblings[index - 1]
next = siblings[index + 1]
nextNext = siblings[index + 2]
nextValue = next && nlcstToString(next)
if (
next &&
nextNext &&
(next.type === punctuation || next.type === symbol) &&
nextNext.type !== word
) {
// Special case if the very first character is a quote followed by
// punctuation at a non-word-break. Close the quotes by brute force.
node.value = closingQuotes[value]
} else if (
nextNext &&
(nextValue === doubleQuote || nextValue === singleQuote) &&
nextNext.type === word
) {
// Special case for double sets of quotes:
// `He said, "'Quoted' words in a larger quote."`
node.value = openingQuotes[value]
next.value = openingQuotes[nextValue]
} else if (next && decadeExpression.test(nextValue)) {
// Special case for decade abbreviations: `the '80s`
node.value = closingQuotes[value]
} else if (
prev &&
next &&
(prev.type === whiteSpace ||
prev.type === punctuation ||
prev.type === symbol) &&
next.type === word
) {
// Get most opening single quotes.
node.value = openingQuotes[value]
} else if (
prev &&
(prev.type !== whiteSpace &&
prev.type !== symbol &&
prev.type !== punctuation)
) {
// Closing quotes.
node.value = closingQuotes[value]
} else if (
!next ||
next.type === whiteSpace ||
((value === singleQuote || value === apostrophe) && nextValue === 's')
) {
node.value = closingQuotes[value]
} else {
node.value = openingQuotes[value]
}
} | javascript | function quotes(node, index, parent) {
var siblings = parent.children
var value = node.value
var next
var nextNext
var prev
var nextValue
if (value !== doubleQuote && value !== singleQuote) {
return
}
prev = siblings[index - 1]
next = siblings[index + 1]
nextNext = siblings[index + 2]
nextValue = next && nlcstToString(next)
if (
next &&
nextNext &&
(next.type === punctuation || next.type === symbol) &&
nextNext.type !== word
) {
// Special case if the very first character is a quote followed by
// punctuation at a non-word-break. Close the quotes by brute force.
node.value = closingQuotes[value]
} else if (
nextNext &&
(nextValue === doubleQuote || nextValue === singleQuote) &&
nextNext.type === word
) {
// Special case for double sets of quotes:
// `He said, "'Quoted' words in a larger quote."`
node.value = openingQuotes[value]
next.value = openingQuotes[nextValue]
} else if (next && decadeExpression.test(nextValue)) {
// Special case for decade abbreviations: `the '80s`
node.value = closingQuotes[value]
} else if (
prev &&
next &&
(prev.type === whiteSpace ||
prev.type === punctuation ||
prev.type === symbol) &&
next.type === word
) {
// Get most opening single quotes.
node.value = openingQuotes[value]
} else if (
prev &&
(prev.type !== whiteSpace &&
prev.type !== symbol &&
prev.type !== punctuation)
) {
// Closing quotes.
node.value = closingQuotes[value]
} else if (
!next ||
next.type === whiteSpace ||
((value === singleQuote || value === apostrophe) && nextValue === 's')
) {
node.value = closingQuotes[value]
} else {
node.value = openingQuotes[value]
}
} | [
"function",
"quotes",
"(",
"node",
",",
"index",
",",
"parent",
")",
"{",
"var",
"siblings",
"=",
"parent",
".",
"children",
"var",
"value",
"=",
"node",
".",
"value",
"var",
"next",
"var",
"nextNext",
"var",
"prev",
"var",
"nextValue",
"if",
"(",
"value",
"!==",
"doubleQuote",
"&&",
"value",
"!==",
"singleQuote",
")",
"{",
"return",
"}",
"prev",
"=",
"siblings",
"[",
"index",
"-",
"1",
"]",
"next",
"=",
"siblings",
"[",
"index",
"+",
"1",
"]",
"nextNext",
"=",
"siblings",
"[",
"index",
"+",
"2",
"]",
"nextValue",
"=",
"next",
"&&",
"nlcstToString",
"(",
"next",
")",
"if",
"(",
"next",
"&&",
"nextNext",
"&&",
"(",
"next",
".",
"type",
"===",
"punctuation",
"||",
"next",
".",
"type",
"===",
"symbol",
")",
"&&",
"nextNext",
".",
"type",
"!==",
"word",
")",
"{",
"// Special case if the very first character is a quote followed by",
"// punctuation at a non-word-break. Close the quotes by brute force.",
"node",
".",
"value",
"=",
"closingQuotes",
"[",
"value",
"]",
"}",
"else",
"if",
"(",
"nextNext",
"&&",
"(",
"nextValue",
"===",
"doubleQuote",
"||",
"nextValue",
"===",
"singleQuote",
")",
"&&",
"nextNext",
".",
"type",
"===",
"word",
")",
"{",
"// Special case for double sets of quotes:",
"// `He said, \"'Quoted' words in a larger quote.\"`",
"node",
".",
"value",
"=",
"openingQuotes",
"[",
"value",
"]",
"next",
".",
"value",
"=",
"openingQuotes",
"[",
"nextValue",
"]",
"}",
"else",
"if",
"(",
"next",
"&&",
"decadeExpression",
".",
"test",
"(",
"nextValue",
")",
")",
"{",
"// Special case for decade abbreviations: `the '80s`",
"node",
".",
"value",
"=",
"closingQuotes",
"[",
"value",
"]",
"}",
"else",
"if",
"(",
"prev",
"&&",
"next",
"&&",
"(",
"prev",
".",
"type",
"===",
"whiteSpace",
"||",
"prev",
".",
"type",
"===",
"punctuation",
"||",
"prev",
".",
"type",
"===",
"symbol",
")",
"&&",
"next",
".",
"type",
"===",
"word",
")",
"{",
"// Get most opening single quotes.",
"node",
".",
"value",
"=",
"openingQuotes",
"[",
"value",
"]",
"}",
"else",
"if",
"(",
"prev",
"&&",
"(",
"prev",
".",
"type",
"!==",
"whiteSpace",
"&&",
"prev",
".",
"type",
"!==",
"symbol",
"&&",
"prev",
".",
"type",
"!==",
"punctuation",
")",
")",
"{",
"// Closing quotes.",
"node",
".",
"value",
"=",
"closingQuotes",
"[",
"value",
"]",
"}",
"else",
"if",
"(",
"!",
"next",
"||",
"next",
".",
"type",
"===",
"whiteSpace",
"||",
"(",
"(",
"value",
"===",
"singleQuote",
"||",
"value",
"===",
"apostrophe",
")",
"&&",
"nextValue",
"===",
"'s'",
")",
")",
"{",
"node",
".",
"value",
"=",
"closingQuotes",
"[",
"value",
"]",
"}",
"else",
"{",
"node",
".",
"value",
"=",
"openingQuotes",
"[",
"value",
"]",
"}",
"}"
] | Transform straight single- and double quotes into smart quotes. | [
"Transform",
"straight",
"single",
"-",
"and",
"double",
"quotes",
"into",
"smart",
"quotes",
"."
] | 4d4ce9059db4f4cafd07a31fedc218c11738435f | https://github.com/retextjs/retext-smartypants/blob/4d4ce9059db4f4cafd07a31fedc218c11738435f/index.js#L306-L371 |
23,233 | ethjs/ethjs-util | src/index.js | padToEven | function padToEven(value) {
var a = value; // eslint-disable-line
if (typeof a !== 'string') {
throw new Error(`[ethjs-util] while padding to even, value must be string, is currently ${typeof a}, while padToEven.`);
}
if (a.length % 2) {
a = `0${a}`;
}
return a;
} | javascript | function padToEven(value) {
var a = value; // eslint-disable-line
if (typeof a !== 'string') {
throw new Error(`[ethjs-util] while padding to even, value must be string, is currently ${typeof a}, while padToEven.`);
}
if (a.length % 2) {
a = `0${a}`;
}
return a;
} | [
"function",
"padToEven",
"(",
"value",
")",
"{",
"var",
"a",
"=",
"value",
";",
"// eslint-disable-line",
"if",
"(",
"typeof",
"a",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"typeof",
"a",
"}",
"`",
")",
";",
"}",
"if",
"(",
"a",
".",
"length",
"%",
"2",
")",
"{",
"a",
"=",
"`",
"${",
"a",
"}",
"`",
";",
"}",
"return",
"a",
";",
"}"
] | Pads a `String` to have an even length
@param {String} value
@return {String} output | [
"Pads",
"a",
"String",
"to",
"have",
"an",
"even",
"length"
] | e9aede668177b6d1ea62d741ba1c19402bc337b3 | https://github.com/ethjs/ethjs-util/blob/e9aede668177b6d1ea62d741ba1c19402bc337b3/src/index.js#L9-L21 |
23,234 | ethjs/ethjs-util | src/index.js | arrayContainsArray | function arrayContainsArray(superset, subset, some) {
if (Array.isArray(superset) !== true) { throw new Error(`[ethjs-util] method arrayContainsArray requires input 'superset' to be an array got type '${typeof superset}'`); }
if (Array.isArray(subset) !== true) { throw new Error(`[ethjs-util] method arrayContainsArray requires input 'subset' to be an array got type '${typeof subset}'`); }
return subset[Boolean(some) && 'some' || 'every']((value) => (superset.indexOf(value) >= 0));
} | javascript | function arrayContainsArray(superset, subset, some) {
if (Array.isArray(superset) !== true) { throw new Error(`[ethjs-util] method arrayContainsArray requires input 'superset' to be an array got type '${typeof superset}'`); }
if (Array.isArray(subset) !== true) { throw new Error(`[ethjs-util] method arrayContainsArray requires input 'subset' to be an array got type '${typeof subset}'`); }
return subset[Boolean(some) && 'some' || 'every']((value) => (superset.indexOf(value) >= 0));
} | [
"function",
"arrayContainsArray",
"(",
"superset",
",",
"subset",
",",
"some",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"superset",
")",
"!==",
"true",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"typeof",
"superset",
"}",
"`",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"subset",
")",
"!==",
"true",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"typeof",
"subset",
"}",
"`",
")",
";",
"}",
"return",
"subset",
"[",
"Boolean",
"(",
"some",
")",
"&&",
"'some'",
"||",
"'every'",
"]",
"(",
"(",
"value",
")",
"=>",
"(",
"superset",
".",
"indexOf",
"(",
"value",
")",
">=",
"0",
")",
")",
";",
"}"
] | Returns TRUE if the first specified array contains all elements
from the second one. FALSE otherwise.
@param {array} superset
@param {array} subset
@returns {boolean} | [
"Returns",
"TRUE",
"if",
"the",
"first",
"specified",
"array",
"contains",
"all",
"elements",
"from",
"the",
"second",
"one",
".",
"FALSE",
"otherwise",
"."
] | e9aede668177b6d1ea62d741ba1c19402bc337b3 | https://github.com/ethjs/ethjs-util/blob/e9aede668177b6d1ea62d741ba1c19402bc337b3/src/index.js#L67-L72 |
23,235 | ethjs/ethjs-util | src/index.js | toUtf8 | function toUtf8(hex) {
const bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex');
return bufferValue.toString('utf8');
} | javascript | function toUtf8(hex) {
const bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex');
return bufferValue.toString('utf8');
} | [
"function",
"toUtf8",
"(",
"hex",
")",
"{",
"const",
"bufferValue",
"=",
"new",
"Buffer",
"(",
"padToEven",
"(",
"stripHexPrefix",
"(",
"hex",
")",
".",
"replace",
"(",
"/",
"^0+|0+$",
"/",
"g",
",",
"''",
")",
")",
",",
"'hex'",
")",
";",
"return",
"bufferValue",
".",
"toString",
"(",
"'utf8'",
")",
";",
"}"
] | Should be called to get utf8 from it's hex representation
@method toUtf8
@param {String} string in hex
@returns {String} ascii string representation of hex value | [
"Should",
"be",
"called",
"to",
"get",
"utf8",
"from",
"it",
"s",
"hex",
"representation"
] | e9aede668177b6d1ea62d741ba1c19402bc337b3 | https://github.com/ethjs/ethjs-util/blob/e9aede668177b6d1ea62d741ba1c19402bc337b3/src/index.js#L81-L85 |
23,236 | ethjs/ethjs-util | src/index.js | toAscii | function toAscii(hex) {
var str = ''; // eslint-disable-line
var i = 0, l = hex.length; // eslint-disable-line
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i += 2) {
const code = parseInt(hex.substr(i, 2), 16);
str += String.fromCharCode(code);
}
return str;
} | javascript | function toAscii(hex) {
var str = ''; // eslint-disable-line
var i = 0, l = hex.length; // eslint-disable-line
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i += 2) {
const code = parseInt(hex.substr(i, 2), 16);
str += String.fromCharCode(code);
}
return str;
} | [
"function",
"toAscii",
"(",
"hex",
")",
"{",
"var",
"str",
"=",
"''",
";",
"// eslint-disable-line",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"hex",
".",
"length",
";",
"// eslint-disable-line",
"if",
"(",
"hex",
".",
"substring",
"(",
"0",
",",
"2",
")",
"===",
"'0x'",
")",
"{",
"i",
"=",
"2",
";",
"}",
"for",
"(",
";",
"i",
"<",
"l",
";",
"i",
"+=",
"2",
")",
"{",
"const",
"code",
"=",
"parseInt",
"(",
"hex",
".",
"substr",
"(",
"i",
",",
"2",
")",
",",
"16",
")",
";",
"str",
"+=",
"String",
".",
"fromCharCode",
"(",
"code",
")",
";",
"}",
"return",
"str",
";",
"}"
] | Should be called to get ascii from it's hex representation
@method toAscii
@param {String} string in hex
@returns {String} ascii string representation of hex value | [
"Should",
"be",
"called",
"to",
"get",
"ascii",
"from",
"it",
"s",
"hex",
"representation"
] | e9aede668177b6d1ea62d741ba1c19402bc337b3 | https://github.com/ethjs/ethjs-util/blob/e9aede668177b6d1ea62d741ba1c19402bc337b3/src/index.js#L94-L108 |
23,237 | nathanbuchar/node-cipher | bin/actions/cipher.js | prompForPassword | function prompForPassword(done) {
inquirer.prompt([
{
type: 'password',
message: 'Enter the password',
name: 'password',
validate(input) {
return input.length > 0;
}
}
], answers => {
done(answers.password);
});
} | javascript | function prompForPassword(done) {
inquirer.prompt([
{
type: 'password',
message: 'Enter the password',
name: 'password',
validate(input) {
return input.length > 0;
}
}
], answers => {
done(answers.password);
});
} | [
"function",
"prompForPassword",
"(",
"done",
")",
"{",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"type",
":",
"'password'",
",",
"message",
":",
"'Enter the password'",
",",
"name",
":",
"'password'",
",",
"validate",
"(",
"input",
")",
"{",
"return",
"input",
".",
"length",
">",
"0",
";",
"}",
"}",
"]",
",",
"answers",
"=>",
"{",
"done",
"(",
"answers",
".",
"password",
")",
";",
"}",
")",
";",
"}"
] | Prompts the user to supply a password via Inquirer.
@param {Function} done | [
"Prompts",
"the",
"user",
"to",
"supply",
"a",
"password",
"via",
"Inquirer",
"."
] | e35ae0ad48a7907a0abd94a8f31daff0a967334f | https://github.com/nathanbuchar/node-cipher/blob/e35ae0ad48a7907a0abd94a8f31daff0a967334f/bin/actions/cipher.js#L19-L32 |
23,238 | nathanbuchar/node-cipher | bin/actions/cipher.js | parseOptions | function parseOptions(options) {
let opts = {};
_.each(nodecipher.defaults, (defaultVal, name) => {
if (!_.isUndefined(options[name])) {
opts[name] = options[name];
}
});
return opts;
} | javascript | function parseOptions(options) {
let opts = {};
_.each(nodecipher.defaults, (defaultVal, name) => {
if (!_.isUndefined(options[name])) {
opts[name] = options[name];
}
});
return opts;
} | [
"function",
"parseOptions",
"(",
"options",
")",
"{",
"let",
"opts",
"=",
"{",
"}",
";",
"_",
".",
"each",
"(",
"nodecipher",
".",
"defaults",
",",
"(",
"defaultVal",
",",
"name",
")",
"=>",
"{",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"options",
"[",
"name",
"]",
")",
")",
"{",
"opts",
"[",
"name",
"]",
"=",
"options",
"[",
"name",
"]",
";",
"}",
"}",
")",
";",
"return",
"opts",
";",
"}"
] | Parses the command line options into a more consise Object that will be
accepted by NodeCipher.
@param {Object} options
@returns {Object} opts | [
"Parses",
"the",
"command",
"line",
"options",
"into",
"a",
"more",
"consise",
"Object",
"that",
"will",
"be",
"accepted",
"by",
"NodeCipher",
"."
] | e35ae0ad48a7907a0abd94a8f31daff0a967334f | https://github.com/nathanbuchar/node-cipher/blob/e35ae0ad48a7907a0abd94a8f31daff0a967334f/bin/actions/cipher.js#L41-L51 |
23,239 | nathanbuchar/node-cipher | bin/actions/cipher.js | cipher | function cipher(command, input, output, options) {
if (_.isUndefined(options.password)) {
prompForPassword(password => {
cipher(command, input, output, options, _.assign(options, { password }));
});
} else {
let opts = _.assign(parseOptions(options), { input, output });
nodecipher[command](opts, err => {
handleCipher(opts, err);
});
}
} | javascript | function cipher(command, input, output, options) {
if (_.isUndefined(options.password)) {
prompForPassword(password => {
cipher(command, input, output, options, _.assign(options, { password }));
});
} else {
let opts = _.assign(parseOptions(options), { input, output });
nodecipher[command](opts, err => {
handleCipher(opts, err);
});
}
} | [
"function",
"cipher",
"(",
"command",
",",
"input",
",",
"output",
",",
"options",
")",
"{",
"if",
"(",
"_",
".",
"isUndefined",
"(",
"options",
".",
"password",
")",
")",
"{",
"prompForPassword",
"(",
"password",
"=>",
"{",
"cipher",
"(",
"command",
",",
"input",
",",
"output",
",",
"options",
",",
"_",
".",
"assign",
"(",
"options",
",",
"{",
"password",
"}",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"let",
"opts",
"=",
"_",
".",
"assign",
"(",
"parseOptions",
"(",
"options",
")",
",",
"{",
"input",
",",
"output",
"}",
")",
";",
"nodecipher",
"[",
"command",
"]",
"(",
"opts",
",",
"err",
"=>",
"{",
"handleCipher",
"(",
"opts",
",",
"err",
")",
";",
"}",
")",
";",
"}",
"}"
] | First checks if the password has been supplied. If not, the user is prompted
to provide one. Once the password is received, parse the options and then
call the appropriate NodeCipher method with the given options.
@see prompForPassword
@see handleCipher
@param {string} command
@param {string} input
@param {string} output
@param {Object} Options | [
"First",
"checks",
"if",
"the",
"password",
"has",
"been",
"supplied",
".",
"If",
"not",
"the",
"user",
"is",
"prompted",
"to",
"provide",
"one",
".",
"Once",
"the",
"password",
"is",
"received",
"parse",
"the",
"options",
"and",
"then",
"call",
"the",
"appropriate",
"NodeCipher",
"method",
"with",
"the",
"given",
"options",
"."
] | e35ae0ad48a7907a0abd94a8f31daff0a967334f | https://github.com/nathanbuchar/node-cipher/blob/e35ae0ad48a7907a0abd94a8f31daff0a967334f/bin/actions/cipher.js#L65-L77 |
23,240 | nathanbuchar/node-cipher | bin/actions/cipher.js | handleCipher | function handleCipher(opts, err) {
if (err) {
switch (err.name) {
case nodecipher.errors.BAD_ALGORITHM:
handleInvalidAlgorithm(opts, err);
break;
case nodecipher.errors.BAD_DIGEST:
handleInvalidHash(opts, err);
break;
case nodecipher.errors.BAD_FILE:
handleEnoentError(opts, err);
break;
case nodecipher.errors.BAD_DECRYPT:
handleBadDecrypt(opts, err);
break;
default:
handleUnknownErrors(opts, err);
}
process.exit(1);
} else {
handleCipherSuccess(opts, err);
}
} | javascript | function handleCipher(opts, err) {
if (err) {
switch (err.name) {
case nodecipher.errors.BAD_ALGORITHM:
handleInvalidAlgorithm(opts, err);
break;
case nodecipher.errors.BAD_DIGEST:
handleInvalidHash(opts, err);
break;
case nodecipher.errors.BAD_FILE:
handleEnoentError(opts, err);
break;
case nodecipher.errors.BAD_DECRYPT:
handleBadDecrypt(opts, err);
break;
default:
handleUnknownErrors(opts, err);
}
process.exit(1);
} else {
handleCipherSuccess(opts, err);
}
} | [
"function",
"handleCipher",
"(",
"opts",
",",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"switch",
"(",
"err",
".",
"name",
")",
"{",
"case",
"nodecipher",
".",
"errors",
".",
"BAD_ALGORITHM",
":",
"handleInvalidAlgorithm",
"(",
"opts",
",",
"err",
")",
";",
"break",
";",
"case",
"nodecipher",
".",
"errors",
".",
"BAD_DIGEST",
":",
"handleInvalidHash",
"(",
"opts",
",",
"err",
")",
";",
"break",
";",
"case",
"nodecipher",
".",
"errors",
".",
"BAD_FILE",
":",
"handleEnoentError",
"(",
"opts",
",",
"err",
")",
";",
"break",
";",
"case",
"nodecipher",
".",
"errors",
".",
"BAD_DECRYPT",
":",
"handleBadDecrypt",
"(",
"opts",
",",
"err",
")",
";",
"break",
";",
"default",
":",
"handleUnknownErrors",
"(",
"opts",
",",
"err",
")",
";",
"}",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"else",
"{",
"handleCipherSuccess",
"(",
"opts",
",",
"err",
")",
";",
"}",
"}"
] | Called when the cipher has completed. Handles errors if there are any.
@param {Object} opts
@param {Error|null} err | [
"Called",
"when",
"the",
"cipher",
"has",
"completed",
".",
"Handles",
"errors",
"if",
"there",
"are",
"any",
"."
] | e35ae0ad48a7907a0abd94a8f31daff0a967334f | https://github.com/nathanbuchar/node-cipher/blob/e35ae0ad48a7907a0abd94a8f31daff0a967334f/bin/actions/cipher.js#L85-L107 |
23,241 | nathanbuchar/node-cipher | bin/actions/cipher.js | handleEnoentError | function handleEnoentError(opts, err) {
console.log(chalk.red(
'\nError: ' + err.name + '. "' + err.path + '" does not exist.\n'
));
} | javascript | function handleEnoentError(opts, err) {
console.log(chalk.red(
'\nError: ' + err.name + '. "' + err.path + '" does not exist.\n'
));
} | [
"function",
"handleEnoentError",
"(",
"opts",
",",
"err",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'\\nError: '",
"+",
"err",
".",
"name",
"+",
"'. \"'",
"+",
"err",
".",
"path",
"+",
"'\" does not exist.\\n'",
")",
")",
";",
"}"
] | Handles NodeCipher ENOENT errors.
@param {Object} opts
@param {Error} err | [
"Handles",
"NodeCipher",
"ENOENT",
"errors",
"."
] | e35ae0ad48a7907a0abd94a8f31daff0a967334f | https://github.com/nathanbuchar/node-cipher/blob/e35ae0ad48a7907a0abd94a8f31daff0a967334f/bin/actions/cipher.js#L115-L119 |
23,242 | ghinda/angular-meditor | dist/meditor.js | function () {
var toolbarHeight = $toolbar[0].offsetHeight;
var toolbarWidth = $toolbar[0].offsetWidth;
var spacing = 5;
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var boundary = range.getBoundingClientRect();
var topPosition = boundary.top;
var leftPosition = boundary.left;
// if there isn't enough space at the top, place it at the bottom
// of the selection
if(boundary.top < (toolbarHeight + spacing)) {
scope.position.top = topPosition + boundary.height + spacing;
// tell me if it's above or below the selection
// used in the template to place the triangle above or below
scope.position.below = true;
} else {
scope.position.top = topPosition - toolbarHeight - spacing;
scope.position.below = false;
}
// center toolbar above selected text
scope.position.left = leftPosition - (toolbarWidth/2) + (boundary.width/2);
// cross-browser window scroll positions
var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
// add the scroll positions
// because getBoundingClientRect gives us the position
// relative to the viewport, not to the page
scope.position.top += scrollTop;
scope.position.left += scrollLeft;
return this;
} | javascript | function () {
var toolbarHeight = $toolbar[0].offsetHeight;
var toolbarWidth = $toolbar[0].offsetWidth;
var spacing = 5;
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var boundary = range.getBoundingClientRect();
var topPosition = boundary.top;
var leftPosition = boundary.left;
// if there isn't enough space at the top, place it at the bottom
// of the selection
if(boundary.top < (toolbarHeight + spacing)) {
scope.position.top = topPosition + boundary.height + spacing;
// tell me if it's above or below the selection
// used in the template to place the triangle above or below
scope.position.below = true;
} else {
scope.position.top = topPosition - toolbarHeight - spacing;
scope.position.below = false;
}
// center toolbar above selected text
scope.position.left = leftPosition - (toolbarWidth/2) + (boundary.width/2);
// cross-browser window scroll positions
var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
// add the scroll positions
// because getBoundingClientRect gives us the position
// relative to the viewport, not to the page
scope.position.top += scrollTop;
scope.position.left += scrollLeft;
return this;
} | [
"function",
"(",
")",
"{",
"var",
"toolbarHeight",
"=",
"$toolbar",
"[",
"0",
"]",
".",
"offsetHeight",
";",
"var",
"toolbarWidth",
"=",
"$toolbar",
"[",
"0",
"]",
".",
"offsetWidth",
";",
"var",
"spacing",
"=",
"5",
";",
"var",
"selection",
"=",
"window",
".",
"getSelection",
"(",
")",
";",
"var",
"range",
"=",
"selection",
".",
"getRangeAt",
"(",
"0",
")",
";",
"var",
"boundary",
"=",
"range",
".",
"getBoundingClientRect",
"(",
")",
";",
"var",
"topPosition",
"=",
"boundary",
".",
"top",
";",
"var",
"leftPosition",
"=",
"boundary",
".",
"left",
";",
"// if there isn't enough space at the top, place it at the bottom",
"// of the selection",
"if",
"(",
"boundary",
".",
"top",
"<",
"(",
"toolbarHeight",
"+",
"spacing",
")",
")",
"{",
"scope",
".",
"position",
".",
"top",
"=",
"topPosition",
"+",
"boundary",
".",
"height",
"+",
"spacing",
";",
"// tell me if it's above or below the selection",
"// used in the template to place the triangle above or below",
"scope",
".",
"position",
".",
"below",
"=",
"true",
";",
"}",
"else",
"{",
"scope",
".",
"position",
".",
"top",
"=",
"topPosition",
"-",
"toolbarHeight",
"-",
"spacing",
";",
"scope",
".",
"position",
".",
"below",
"=",
"false",
";",
"}",
"// center toolbar above selected text",
"scope",
".",
"position",
".",
"left",
"=",
"leftPosition",
"-",
"(",
"toolbarWidth",
"/",
"2",
")",
"+",
"(",
"boundary",
".",
"width",
"/",
"2",
")",
";",
"// cross-browser window scroll positions",
"var",
"scrollLeft",
"=",
"(",
"window",
".",
"pageXOffset",
"!==",
"undefined",
")",
"?",
"window",
".",
"pageXOffset",
":",
"(",
"document",
".",
"documentElement",
"||",
"document",
".",
"body",
".",
"parentNode",
"||",
"document",
".",
"body",
")",
".",
"scrollLeft",
";",
"var",
"scrollTop",
"=",
"(",
"window",
".",
"pageYOffset",
"!==",
"undefined",
")",
"?",
"window",
".",
"pageYOffset",
":",
"(",
"document",
".",
"documentElement",
"||",
"document",
".",
"body",
".",
"parentNode",
"||",
"document",
".",
"body",
")",
".",
"scrollTop",
";",
"// add the scroll positions",
"// because getBoundingClientRect gives us the position",
"// relative to the viewport, not to the page",
"scope",
".",
"position",
".",
"top",
"+=",
"scrollTop",
";",
"scope",
".",
"position",
".",
"left",
"+=",
"scrollLeft",
";",
"return",
"this",
";",
"}"
] | position the toolbar above or below the selected text | [
"position",
"the",
"toolbar",
"above",
"or",
"below",
"the",
"selected",
"text"
] | 97d1873303980d80850e034da128e241903167d7 | https://github.com/ghinda/angular-meditor/blob/97d1873303980d80850e034da128e241903167d7/dist/meditor.js#L134-L171 | |
23,243 | ghinda/angular-meditor | dist/meditor.js | function (e) {
// if you click something from the toolbar
// don't do anything
if(e && e.target && $toolbar.find(e.target).length) {
return false;
}
var newSelection = window.getSelection();
// get selection node
var anchorNode = newSelection.anchorNode;
// if nothing selected, hide the toolbar
if(newSelection.toString().trim() === '' || !anchorNode) {
// hide the toolbar
return $timeout(function() {
scope.model.showToolbar = false;
});
}
// check if selection is in the current editor/directive container
var parentNode = anchorNode.parentNode;
while (parentNode.tagName !== undefined && parentNode !== element[0]) {
parentNode = parentNode.parentNode;
}
// if the selection is in the current editor
if(parentNode === element[0]) {
// show the toolbar
$timeout(function() {
scope.model.showToolbar = true;
setToolbarPosition();
});
// check selection styles and active buttons based on it
checkActiveButtons(newSelection);
} else {
// hide the toolbar
$timeout(function() {
scope.model.showToolbar = false;
});
}
return this;
} | javascript | function (e) {
// if you click something from the toolbar
// don't do anything
if(e && e.target && $toolbar.find(e.target).length) {
return false;
}
var newSelection = window.getSelection();
// get selection node
var anchorNode = newSelection.anchorNode;
// if nothing selected, hide the toolbar
if(newSelection.toString().trim() === '' || !anchorNode) {
// hide the toolbar
return $timeout(function() {
scope.model.showToolbar = false;
});
}
// check if selection is in the current editor/directive container
var parentNode = anchorNode.parentNode;
while (parentNode.tagName !== undefined && parentNode !== element[0]) {
parentNode = parentNode.parentNode;
}
// if the selection is in the current editor
if(parentNode === element[0]) {
// show the toolbar
$timeout(function() {
scope.model.showToolbar = true;
setToolbarPosition();
});
// check selection styles and active buttons based on it
checkActiveButtons(newSelection);
} else {
// hide the toolbar
$timeout(function() {
scope.model.showToolbar = false;
});
}
return this;
} | [
"function",
"(",
"e",
")",
"{",
"// if you click something from the toolbar",
"// don't do anything",
"if",
"(",
"e",
"&&",
"e",
".",
"target",
"&&",
"$toolbar",
".",
"find",
"(",
"e",
".",
"target",
")",
".",
"length",
")",
"{",
"return",
"false",
";",
"}",
"var",
"newSelection",
"=",
"window",
".",
"getSelection",
"(",
")",
";",
"// get selection node",
"var",
"anchorNode",
"=",
"newSelection",
".",
"anchorNode",
";",
"// if nothing selected, hide the toolbar",
"if",
"(",
"newSelection",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
"===",
"''",
"||",
"!",
"anchorNode",
")",
"{",
"// hide the toolbar",
"return",
"$timeout",
"(",
"function",
"(",
")",
"{",
"scope",
".",
"model",
".",
"showToolbar",
"=",
"false",
";",
"}",
")",
";",
"}",
"// check if selection is in the current editor/directive container",
"var",
"parentNode",
"=",
"anchorNode",
".",
"parentNode",
";",
"while",
"(",
"parentNode",
".",
"tagName",
"!==",
"undefined",
"&&",
"parentNode",
"!==",
"element",
"[",
"0",
"]",
")",
"{",
"parentNode",
"=",
"parentNode",
".",
"parentNode",
";",
"}",
"// if the selection is in the current editor",
"if",
"(",
"parentNode",
"===",
"element",
"[",
"0",
"]",
")",
"{",
"// show the toolbar",
"$timeout",
"(",
"function",
"(",
")",
"{",
"scope",
".",
"model",
".",
"showToolbar",
"=",
"true",
";",
"setToolbarPosition",
"(",
")",
";",
"}",
")",
";",
"// check selection styles and active buttons based on it",
"checkActiveButtons",
"(",
"newSelection",
")",
";",
"}",
"else",
"{",
"// hide the toolbar",
"$timeout",
"(",
"function",
"(",
")",
"{",
"scope",
".",
"model",
".",
"showToolbar",
"=",
"false",
";",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] | get current selection and act on toolbar depending on it | [
"get",
"current",
"selection",
"and",
"act",
"on",
"toolbar",
"depending",
"on",
"it"
] | 97d1873303980d80850e034da128e241903167d7 | https://github.com/ghinda/angular-meditor/blob/97d1873303980d80850e034da128e241903167d7/dist/meditor.js#L174-L219 | |
23,244 | ghinda/angular-meditor | dist/meditor.js | function (selection) {
var parentNode = selection.anchorNode;
if (!parentNode.tagName) {
parentNode = selection.anchorNode.parentNode;
}
var childNode = parentNode.childNodes[0];
if(childNode && childNode.tagName && childNode.tagName.toLowerCase() in generatedTags) {
parentNode = parentNode.childNodes[0];
}
$timeout(function() {
// get real styles of selected element
scope.styles = window.getComputedStyle(parentNode, null);
if(scope.styles.fontSize !== scope.size.label + 'px') {
// set font size selector
angular.forEach(scope.sizeOptions, function(size, i) {
if(scope.styles.fontSize === (size.label + 'px')) {
scope.size = scope.sizeOptions[i].value;
return false;
}
});
}
});
} | javascript | function (selection) {
var parentNode = selection.anchorNode;
if (!parentNode.tagName) {
parentNode = selection.anchorNode.parentNode;
}
var childNode = parentNode.childNodes[0];
if(childNode && childNode.tagName && childNode.tagName.toLowerCase() in generatedTags) {
parentNode = parentNode.childNodes[0];
}
$timeout(function() {
// get real styles of selected element
scope.styles = window.getComputedStyle(parentNode, null);
if(scope.styles.fontSize !== scope.size.label + 'px') {
// set font size selector
angular.forEach(scope.sizeOptions, function(size, i) {
if(scope.styles.fontSize === (size.label + 'px')) {
scope.size = scope.sizeOptions[i].value;
return false;
}
});
}
});
} | [
"function",
"(",
"selection",
")",
"{",
"var",
"parentNode",
"=",
"selection",
".",
"anchorNode",
";",
"if",
"(",
"!",
"parentNode",
".",
"tagName",
")",
"{",
"parentNode",
"=",
"selection",
".",
"anchorNode",
".",
"parentNode",
";",
"}",
"var",
"childNode",
"=",
"parentNode",
".",
"childNodes",
"[",
"0",
"]",
";",
"if",
"(",
"childNode",
"&&",
"childNode",
".",
"tagName",
"&&",
"childNode",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
"in",
"generatedTags",
")",
"{",
"parentNode",
"=",
"parentNode",
".",
"childNodes",
"[",
"0",
"]",
";",
"}",
"$timeout",
"(",
"function",
"(",
")",
"{",
"// get real styles of selected element",
"scope",
".",
"styles",
"=",
"window",
".",
"getComputedStyle",
"(",
"parentNode",
",",
"null",
")",
";",
"if",
"(",
"scope",
".",
"styles",
".",
"fontSize",
"!==",
"scope",
".",
"size",
".",
"label",
"+",
"'px'",
")",
"{",
"// set font size selector",
"angular",
".",
"forEach",
"(",
"scope",
".",
"sizeOptions",
",",
"function",
"(",
"size",
",",
"i",
")",
"{",
"if",
"(",
"scope",
".",
"styles",
".",
"fontSize",
"===",
"(",
"size",
".",
"label",
"+",
"'px'",
")",
")",
"{",
"scope",
".",
"size",
"=",
"scope",
".",
"sizeOptions",
"[",
"i",
"]",
".",
"value",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | check current selection styles and activate buttons | [
"check",
"current",
"selection",
"styles",
"and",
"activate",
"buttons"
] | 97d1873303980d80850e034da128e241903167d7 | https://github.com/ghinda/angular-meditor/blob/97d1873303980d80850e034da128e241903167d7/dist/meditor.js#L222-L251 | |
23,245 | Azard/egg-oauth2-server | lib/server.js | replaceResponse | function replaceResponse(res) {
// copy for response.headers.hasOwnProperty is undefined case
// https://github.com/oauthjs/node-oauth2-server/pull/486
const newResponse = {
headers: {},
};
for (const property in res) {
if (property !== 'headers') {
newResponse[property] = res[property];
}
}
for (const field in res.headers) {
newResponse.headers[field] = res.headers[field];
}
newResponse.header = newResponse.headers;
return newResponse;
} | javascript | function replaceResponse(res) {
// copy for response.headers.hasOwnProperty is undefined case
// https://github.com/oauthjs/node-oauth2-server/pull/486
const newResponse = {
headers: {},
};
for (const property in res) {
if (property !== 'headers') {
newResponse[property] = res[property];
}
}
for (const field in res.headers) {
newResponse.headers[field] = res.headers[field];
}
newResponse.header = newResponse.headers;
return newResponse;
} | [
"function",
"replaceResponse",
"(",
"res",
")",
"{",
"// copy for response.headers.hasOwnProperty is undefined case",
"// https://github.com/oauthjs/node-oauth2-server/pull/486",
"const",
"newResponse",
"=",
"{",
"headers",
":",
"{",
"}",
",",
"}",
";",
"for",
"(",
"const",
"property",
"in",
"res",
")",
"{",
"if",
"(",
"property",
"!==",
"'headers'",
")",
"{",
"newResponse",
"[",
"property",
"]",
"=",
"res",
"[",
"property",
"]",
";",
"}",
"}",
"for",
"(",
"const",
"field",
"in",
"res",
".",
"headers",
")",
"{",
"newResponse",
".",
"headers",
"[",
"field",
"]",
"=",
"res",
".",
"headers",
"[",
"field",
"]",
";",
"}",
"newResponse",
".",
"header",
"=",
"newResponse",
".",
"headers",
";",
"return",
"newResponse",
";",
"}"
] | replace response. | [
"replace",
"response",
"."
] | 00f1c7eabdd2357c2b71afe366b356f2347e5f16 | https://github.com/Azard/egg-oauth2-server/blob/00f1c7eabdd2357c2b71afe366b356f2347e5f16/lib/server.js#L16-L32 |
23,246 | krg7880/json-schema-generator | lib/cli/in.js | function(url, callback) {
logger('Fetching URL resource: ' + url);
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
} else {
var errorString = [
'There was an error loading the requested resource',
'>>> ' + url
];
if (error) {
errorString.push(error.toString('utf8'));
}
errorHandler(errorString.join('\n'));
}
});
} | javascript | function(url, callback) {
logger('Fetching URL resource: ' + url);
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
} else {
var errorString = [
'There was an error loading the requested resource',
'>>> ' + url
];
if (error) {
errorString.push(error.toString('utf8'));
}
errorHandler(errorString.join('\n'));
}
});
} | [
"function",
"(",
"url",
",",
"callback",
")",
"{",
"logger",
"(",
"'Fetching URL resource: '",
"+",
"url",
")",
";",
"request",
"(",
"url",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"==",
"200",
")",
"{",
"callback",
"(",
"body",
")",
";",
"}",
"else",
"{",
"var",
"errorString",
"=",
"[",
"'There was an error loading the requested resource'",
",",
"'>>> '",
"+",
"url",
"]",
";",
"if",
"(",
"error",
")",
"{",
"errorString",
".",
"push",
"(",
"error",
".",
"toString",
"(",
"'utf8'",
")",
")",
";",
"}",
"errorHandler",
"(",
"errorString",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Fetches a remote JSON document and generate
the schema based on the contents of the remote
resource. If an output directory is specified,
the document will be saved locally.
@param {String} url - The location of the remote resource
@param {Function} callback | [
"Fetches",
"a",
"remote",
"JSON",
"document",
"and",
"generate",
"the",
"schema",
"based",
"on",
"the",
"contents",
"of",
"the",
"remote",
"resource",
".",
"If",
"an",
"output",
"directory",
"is",
"specified",
"the",
"document",
"will",
"be",
"saved",
"locally",
"."
] | 27d5a84721c4cd496a2a37bbefda09c07a59f6a1 | https://github.com/krg7880/json-schema-generator/blob/27d5a84721c4cd496a2a37bbefda09c07a59f6a1/lib/cli/in.js#L17-L34 | |
23,247 | krg7880/json-schema-generator | lib/cli/in.js | function(filePath, callback) {
if (!fs.existsSync(filePath)) {
errorHandler("File " + filePath + " does not exist. Please specify a valid path.");
}
var body = '';
var reader = fs.createReadStream(filePath);
reader.on('data', function(chunks) {
body += chunks;
}).on('end', function() {
callback(body);
}).on('error', function(e) {
throw e;
});
} | javascript | function(filePath, callback) {
if (!fs.existsSync(filePath)) {
errorHandler("File " + filePath + " does not exist. Please specify a valid path.");
}
var body = '';
var reader = fs.createReadStream(filePath);
reader.on('data', function(chunks) {
body += chunks;
}).on('end', function() {
callback(body);
}).on('error', function(e) {
throw e;
});
} | [
"function",
"(",
"filePath",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"errorHandler",
"(",
"\"File \"",
"+",
"filePath",
"+",
"\" does not exist. Please specify a valid path.\"",
")",
";",
"}",
"var",
"body",
"=",
"''",
";",
"var",
"reader",
"=",
"fs",
".",
"createReadStream",
"(",
"filePath",
")",
";",
"reader",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunks",
")",
"{",
"body",
"+=",
"chunks",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"callback",
"(",
"body",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"throw",
"e",
";",
"}",
")",
";",
"}"
] | Reads the specified JSON file from the
filesystem which is used to generate
the schema.
@param {String} filePath - Path to JSON document to load.
@param {Function} callback | [
"Reads",
"the",
"specified",
"JSON",
"file",
"from",
"the",
"filesystem",
"which",
"is",
"used",
"to",
"generate",
"the",
"schema",
"."
] | 27d5a84721c4cd496a2a37bbefda09c07a59f6a1 | https://github.com/krg7880/json-schema-generator/blob/27d5a84721c4cd496a2a37bbefda09c07a59f6a1/lib/cli/in.js#L44-L57 | |
23,248 | krg7880/json-schema-generator | bin/cli.js | getName | function getName(str) {
var name = path.basename(str);
if (name.lastIndexOf('.') === -1) {
name += '.json';
}
return name;
} | javascript | function getName(str) {
var name = path.basename(str);
if (name.lastIndexOf('.') === -1) {
name += '.json';
}
return name;
} | [
"function",
"getName",
"(",
"str",
")",
"{",
"var",
"name",
"=",
"path",
".",
"basename",
"(",
"str",
")",
";",
"if",
"(",
"name",
".",
"lastIndexOf",
"(",
"'.'",
")",
"===",
"-",
"1",
")",
"{",
"name",
"+=",
"'.json'",
";",
"}",
"return",
"name",
";",
"}"
] | Get the name of the JSON resource so the schema
matches the source. The .json extension is added
if it's missing from the filename.
@param {String} str File name
@return {String} The name of the file only. | [
"Get",
"the",
"name",
"of",
"the",
"JSON",
"resource",
"so",
"the",
"schema",
"matches",
"the",
"source",
".",
"The",
".",
"json",
"extension",
"is",
"added",
"if",
"it",
"s",
"missing",
"from",
"the",
"filename",
"."
] | 27d5a84721c4cd496a2a37bbefda09c07a59f6a1 | https://github.com/krg7880/json-schema-generator/blob/27d5a84721c4cd496a2a37bbefda09c07a59f6a1/bin/cli.js#L138-L144 |
23,249 | krg7880/json-schema-generator | lib/cli/out.js | handleOutput | function handleOutput(destConfig, jsonString) {
var type = destConfig.type,
destPath = destConfig.path,
defaultFileName = destConfig.defaultFileName,
force = destConfig.force,
pretty = destConfig.pretty;
if (!type || type === "omit") {
// don't even bother
return;
}
if (pretty) {
jsonString = prettyData.pd.json(jsonString);
}
switch (type) {
case IOType.FILE:
writeFile(jsonString, destPath, defaultFileName, force);
break;
case IOType.STDOUT:
stdout(jsonString);
break;
}
} | javascript | function handleOutput(destConfig, jsonString) {
var type = destConfig.type,
destPath = destConfig.path,
defaultFileName = destConfig.defaultFileName,
force = destConfig.force,
pretty = destConfig.pretty;
if (!type || type === "omit") {
// don't even bother
return;
}
if (pretty) {
jsonString = prettyData.pd.json(jsonString);
}
switch (type) {
case IOType.FILE:
writeFile(jsonString, destPath, defaultFileName, force);
break;
case IOType.STDOUT:
stdout(jsonString);
break;
}
} | [
"function",
"handleOutput",
"(",
"destConfig",
",",
"jsonString",
")",
"{",
"var",
"type",
"=",
"destConfig",
".",
"type",
",",
"destPath",
"=",
"destConfig",
".",
"path",
",",
"defaultFileName",
"=",
"destConfig",
".",
"defaultFileName",
",",
"force",
"=",
"destConfig",
".",
"force",
",",
"pretty",
"=",
"destConfig",
".",
"pretty",
";",
"if",
"(",
"!",
"type",
"||",
"type",
"===",
"\"omit\"",
")",
"{",
"// don't even bother",
"return",
";",
"}",
"if",
"(",
"pretty",
")",
"{",
"jsonString",
"=",
"prettyData",
".",
"pd",
".",
"json",
"(",
"jsonString",
")",
";",
"}",
"switch",
"(",
"type",
")",
"{",
"case",
"IOType",
".",
"FILE",
":",
"writeFile",
"(",
"jsonString",
",",
"destPath",
",",
"defaultFileName",
",",
"force",
")",
";",
"break",
";",
"case",
"IOType",
".",
"STDOUT",
":",
"stdout",
"(",
"jsonString",
")",
";",
"break",
";",
"}",
"}"
] | Save output to a certain location
@param {Object} destConfig
@param {String} jsonString | [
"Save",
"output",
"to",
"a",
"certain",
"location"
] | 27d5a84721c4cd496a2a37bbefda09c07a59f6a1 | https://github.com/krg7880/json-schema-generator/blob/27d5a84721c4cd496a2a37bbefda09c07a59f6a1/lib/cli/out.js#L53-L76 |
23,250 | wyattdanger/geocoder | index.js | function ( name, opts ) {
if ( ! name ) {
return cbk( new Error( "Geocoder.selectProvider requires a name.") );
}
this.provider = name;
this.providerOpts = opts || {};
this.providerObj = require("./providers/"+name);
} | javascript | function ( name, opts ) {
if ( ! name ) {
return cbk( new Error( "Geocoder.selectProvider requires a name.") );
}
this.provider = name;
this.providerOpts = opts || {};
this.providerObj = require("./providers/"+name);
} | [
"function",
"(",
"name",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"name",
")",
"{",
"return",
"cbk",
"(",
"new",
"Error",
"(",
"\"Geocoder.selectProvider requires a name.\"",
")",
")",
";",
"}",
"this",
".",
"provider",
"=",
"name",
";",
"this",
".",
"providerOpts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"providerObj",
"=",
"require",
"(",
"\"./providers/\"",
"+",
"name",
")",
";",
"}"
] | Selects a webservice provider
@param {String} name, required
@param {Object} opts, optional
@api public | [
"Selects",
"a",
"webservice",
"provider"
] | 135df34eba2082f7175c72c8c6f31aab6267d0f8 | https://github.com/wyattdanger/geocoder/blob/135df34eba2082f7175c72c8c6f31aab6267d0f8/index.js#L39-L49 | |
23,251 | wyattdanger/geocoder | index.js | function ( loc, cbk, opts ) {
if ( ! loc ) {
return cbk( new Error( "Geocoder.geocode requires a location.") );
}
return this.providerObj.geocode(this.providerOpts, loc, cbk, opts);
} | javascript | function ( loc, cbk, opts ) {
if ( ! loc ) {
return cbk( new Error( "Geocoder.geocode requires a location.") );
}
return this.providerObj.geocode(this.providerOpts, loc, cbk, opts);
} | [
"function",
"(",
"loc",
",",
"cbk",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"loc",
")",
"{",
"return",
"cbk",
"(",
"new",
"Error",
"(",
"\"Geocoder.geocode requires a location.\"",
")",
")",
";",
"}",
"return",
"this",
".",
"providerObj",
".",
"geocode",
"(",
"this",
".",
"providerOpts",
",",
"loc",
",",
"cbk",
",",
"opts",
")",
";",
"}"
] | Request geocoordinates of given `loc` from Google
@param {String} loc, required
@param {Function} cbk, required
@param {Object} opts, optional
@api public | [
"Request",
"geocoordinates",
"of",
"given",
"loc",
"from",
"Google"
] | 135df34eba2082f7175c72c8c6f31aab6267d0f8 | https://github.com/wyattdanger/geocoder/blob/135df34eba2082f7175c72c8c6f31aab6267d0f8/index.js#L60-L68 | |
23,252 | kentcdodds/nps-utils | src/index.js | concurrent | function concurrent(scripts) {
const {colors, scripts: quotedScripts, names} = Object.keys(scripts)
.reduce(reduceScripts, {
colors: [],
scripts: [],
names: [],
})
const flags = [
'--kill-others-on-fail',
`--prefix-colors "${colors.join(',')}"`,
'--prefix "[{name}]"',
`--names "${names.join(',')}"`,
shellEscape(quotedScripts),
]
const concurrently = runBin('concurrently')
return `${concurrently} ${flags.join(' ')}`
function reduceScripts(accumulator, scriptName, index) {
let scriptObj = scripts[scriptName]
if (!scriptObj) {
return accumulator
} else if (typeof scriptObj === 'string') {
scriptObj = {script: scriptObj}
}
const {
script,
color = defaultColors[index % defaultColors.length],
} = scriptObj
if (!script) {
return accumulator
}
accumulator.names.push(scriptName)
accumulator.colors.push(color)
accumulator.scripts.push(script)
return accumulator
}
} | javascript | function concurrent(scripts) {
const {colors, scripts: quotedScripts, names} = Object.keys(scripts)
.reduce(reduceScripts, {
colors: [],
scripts: [],
names: [],
})
const flags = [
'--kill-others-on-fail',
`--prefix-colors "${colors.join(',')}"`,
'--prefix "[{name}]"',
`--names "${names.join(',')}"`,
shellEscape(quotedScripts),
]
const concurrently = runBin('concurrently')
return `${concurrently} ${flags.join(' ')}`
function reduceScripts(accumulator, scriptName, index) {
let scriptObj = scripts[scriptName]
if (!scriptObj) {
return accumulator
} else if (typeof scriptObj === 'string') {
scriptObj = {script: scriptObj}
}
const {
script,
color = defaultColors[index % defaultColors.length],
} = scriptObj
if (!script) {
return accumulator
}
accumulator.names.push(scriptName)
accumulator.colors.push(color)
accumulator.scripts.push(script)
return accumulator
}
} | [
"function",
"concurrent",
"(",
"scripts",
")",
"{",
"const",
"{",
"colors",
",",
"scripts",
":",
"quotedScripts",
",",
"names",
"}",
"=",
"Object",
".",
"keys",
"(",
"scripts",
")",
".",
"reduce",
"(",
"reduceScripts",
",",
"{",
"colors",
":",
"[",
"]",
",",
"scripts",
":",
"[",
"]",
",",
"names",
":",
"[",
"]",
",",
"}",
")",
"const",
"flags",
"=",
"[",
"'--kill-others-on-fail'",
",",
"`",
"${",
"colors",
".",
"join",
"(",
"','",
")",
"}",
"`",
",",
"'--prefix \"[{name}]\"'",
",",
"`",
"${",
"names",
".",
"join",
"(",
"','",
")",
"}",
"`",
",",
"shellEscape",
"(",
"quotedScripts",
")",
",",
"]",
"const",
"concurrently",
"=",
"runBin",
"(",
"'concurrently'",
")",
"return",
"`",
"${",
"concurrently",
"}",
"${",
"flags",
".",
"join",
"(",
"' '",
")",
"}",
"`",
"function",
"reduceScripts",
"(",
"accumulator",
",",
"scriptName",
",",
"index",
")",
"{",
"let",
"scriptObj",
"=",
"scripts",
"[",
"scriptName",
"]",
"if",
"(",
"!",
"scriptObj",
")",
"{",
"return",
"accumulator",
"}",
"else",
"if",
"(",
"typeof",
"scriptObj",
"===",
"'string'",
")",
"{",
"scriptObj",
"=",
"{",
"script",
":",
"scriptObj",
"}",
"}",
"const",
"{",
"script",
",",
"color",
"=",
"defaultColors",
"[",
"index",
"%",
"defaultColors",
".",
"length",
"]",
",",
"}",
"=",
"scriptObj",
"if",
"(",
"!",
"script",
")",
"{",
"return",
"accumulator",
"}",
"accumulator",
".",
"names",
".",
"push",
"(",
"scriptName",
")",
"accumulator",
".",
"colors",
".",
"push",
"(",
"color",
")",
"accumulator",
".",
"scripts",
".",
"push",
"(",
"script",
")",
"return",
"accumulator",
"}",
"}"
] | A concurrent script object
@typedef {Object|string} ConcurrentScript
@property {string} script - the command to run
@property {string} color - the color to use
(see concurrently's docs for valid values)
An object of concurrent script objects
@typedef {Object.<ConcurrentScript>} ConcurrentScripts
Generates a command that uses `concurrently` to run
scripts concurrently. Adds a few flags to make it
behave as you probably want (like --kill-others-on-fail).
In addition, it adds color and labels where the color
can be specified or is defaulted and the label is based
on the key for the script.
@param {ConcurrentScripts} scripts - the scripts to run
note: this function filters out falsy values :)
@example
// returns a bit of a long script that can vary slightly
// based on your environment... :)
concurrent({
lint: {
script: 'eslint .',
color: 'bgGreen.white.dim',
},
test: 'jest',
build: {
script: 'webpack'
}
})
@return {string} - the command to run | [
"A",
"concurrent",
"script",
"object"
] | b20c1db9dd79945ee255eff27897d26f763dfd98 | https://github.com/kentcdodds/nps-utils/blob/b20c1db9dd79945ee255eff27897d26f763dfd98/src/index.js#L112-L148 |
23,253 | kentcdodds/nps-utils | src/index.js | includePackage | function includePackage(packageNameOrOptions) {
const packageScriptsPath = typeof packageNameOrOptions === 'string' ?
`./packages/${packageNameOrOptions}/package-scripts.js` :
packageNameOrOptions.path
const startingDir = process.cwd().split('\\').join('/')
const relativeDir = path
.relative(startingDir, path.dirname(packageScriptsPath))
.split('\\')
.join('/')
const relativeReturn = path
.relative(relativeDir, startingDir)
.split('\\')
.join('/')
const scripts = require(packageScriptsPath)
// eslint-disable-next-line
function replace(obj, prefix) {
const retObj = {}
const dot = prefix ? '.' : ''
for (const key in obj) {
if (key === 'description') {
retObj[key] = obj[key]
} else if (key === 'script') {
retObj[key] = series(
`cd ${relativeDir}`,
`npm start ${prefix}`,
`cd "${relativeReturn}"`,
)
} else if (typeof obj[key] === 'string') {
retObj[key] = series(
`cd ${relativeDir}`,
`npm start ${prefix}${dot}${key}`,
)
} else {
retObj[key] = Object.assign(
{},
replace(obj[key], `${prefix}${dot}${key}`, `cd "${startingDir}"`),
)
}
}
return retObj
}
return replace(scripts.scripts, '')
} | javascript | function includePackage(packageNameOrOptions) {
const packageScriptsPath = typeof packageNameOrOptions === 'string' ?
`./packages/${packageNameOrOptions}/package-scripts.js` :
packageNameOrOptions.path
const startingDir = process.cwd().split('\\').join('/')
const relativeDir = path
.relative(startingDir, path.dirname(packageScriptsPath))
.split('\\')
.join('/')
const relativeReturn = path
.relative(relativeDir, startingDir)
.split('\\')
.join('/')
const scripts = require(packageScriptsPath)
// eslint-disable-next-line
function replace(obj, prefix) {
const retObj = {}
const dot = prefix ? '.' : ''
for (const key in obj) {
if (key === 'description') {
retObj[key] = obj[key]
} else if (key === 'script') {
retObj[key] = series(
`cd ${relativeDir}`,
`npm start ${prefix}`,
`cd "${relativeReturn}"`,
)
} else if (typeof obj[key] === 'string') {
retObj[key] = series(
`cd ${relativeDir}`,
`npm start ${prefix}${dot}${key}`,
)
} else {
retObj[key] = Object.assign(
{},
replace(obj[key], `${prefix}${dot}${key}`, `cd "${startingDir}"`),
)
}
}
return retObj
}
return replace(scripts.scripts, '')
} | [
"function",
"includePackage",
"(",
"packageNameOrOptions",
")",
"{",
"const",
"packageScriptsPath",
"=",
"typeof",
"packageNameOrOptions",
"===",
"'string'",
"?",
"`",
"${",
"packageNameOrOptions",
"}",
"`",
":",
"packageNameOrOptions",
".",
"path",
"const",
"startingDir",
"=",
"process",
".",
"cwd",
"(",
")",
".",
"split",
"(",
"'\\\\'",
")",
".",
"join",
"(",
"'/'",
")",
"const",
"relativeDir",
"=",
"path",
".",
"relative",
"(",
"startingDir",
",",
"path",
".",
"dirname",
"(",
"packageScriptsPath",
")",
")",
".",
"split",
"(",
"'\\\\'",
")",
".",
"join",
"(",
"'/'",
")",
"const",
"relativeReturn",
"=",
"path",
".",
"relative",
"(",
"relativeDir",
",",
"startingDir",
")",
".",
"split",
"(",
"'\\\\'",
")",
".",
"join",
"(",
"'/'",
")",
"const",
"scripts",
"=",
"require",
"(",
"packageScriptsPath",
")",
"// eslint-disable-next-line",
"function",
"replace",
"(",
"obj",
",",
"prefix",
")",
"{",
"const",
"retObj",
"=",
"{",
"}",
"const",
"dot",
"=",
"prefix",
"?",
"'.'",
":",
"''",
"for",
"(",
"const",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"key",
"===",
"'description'",
")",
"{",
"retObj",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
"}",
"else",
"if",
"(",
"key",
"===",
"'script'",
")",
"{",
"retObj",
"[",
"key",
"]",
"=",
"series",
"(",
"`",
"${",
"relativeDir",
"}",
"`",
",",
"`",
"${",
"prefix",
"}",
"`",
",",
"`",
"${",
"relativeReturn",
"}",
"`",
",",
")",
"}",
"else",
"if",
"(",
"typeof",
"obj",
"[",
"key",
"]",
"===",
"'string'",
")",
"{",
"retObj",
"[",
"key",
"]",
"=",
"series",
"(",
"`",
"${",
"relativeDir",
"}",
"`",
",",
"`",
"${",
"prefix",
"}",
"${",
"dot",
"}",
"${",
"key",
"}",
"`",
",",
")",
"}",
"else",
"{",
"retObj",
"[",
"key",
"]",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"replace",
"(",
"obj",
"[",
"key",
"]",
",",
"`",
"${",
"prefix",
"}",
"${",
"dot",
"}",
"${",
"key",
"}",
"`",
",",
"`",
"${",
"startingDir",
"}",
"`",
")",
",",
")",
"}",
"}",
"return",
"retObj",
"}",
"return",
"replace",
"(",
"scripts",
".",
"scripts",
",",
"''",
")",
"}"
] | The options to pass to includePackage
@typedef {Object|string} IncludePackageOptions
@property {string} path - the path to the package scripts
Includes the scripts from a sub-package in your repo (for
yarn workspaces or lerna style projects).
@param {IncludePackageOptions} packageNameOrOptions - either a
simple name for the sub-package or an options object where you can
specify the exact path to the package to include.
If you just provide the name and not the options object, then the path
defaults to: ./packages/{package}/package-scripts.js
@return {any} will return an object of scripts loaded from that package | [
"The",
"options",
"to",
"pass",
"to",
"includePackage"
] | b20c1db9dd79945ee255eff27897d26f763dfd98 | https://github.com/kentcdodds/nps-utils/blob/b20c1db9dd79945ee255eff27897d26f763dfd98/src/index.js#L345-L393 |
23,254 | kentcdodds/nps-utils | src/index.js | getBin | function getBin(packageName, binName = packageName) {
const packagePath = require.resolve(`${packageName}/package.json`)
const concurrentlyDir = path.dirname(packagePath)
let {bin: binRelativeToPackage} = require(packagePath)
if (typeof binRelativeToPackage === 'object') {
binRelativeToPackage = binRelativeToPackage[binName]
}
const fullBinPath = path.join(concurrentlyDir, binRelativeToPackage)
return path.relative(process.cwd(), fullBinPath)
} | javascript | function getBin(packageName, binName = packageName) {
const packagePath = require.resolve(`${packageName}/package.json`)
const concurrentlyDir = path.dirname(packagePath)
let {bin: binRelativeToPackage} = require(packagePath)
if (typeof binRelativeToPackage === 'object') {
binRelativeToPackage = binRelativeToPackage[binName]
}
const fullBinPath = path.join(concurrentlyDir, binRelativeToPackage)
return path.relative(process.cwd(), fullBinPath)
} | [
"function",
"getBin",
"(",
"packageName",
",",
"binName",
"=",
"packageName",
")",
"{",
"const",
"packagePath",
"=",
"require",
".",
"resolve",
"(",
"`",
"${",
"packageName",
"}",
"`",
")",
"const",
"concurrentlyDir",
"=",
"path",
".",
"dirname",
"(",
"packagePath",
")",
"let",
"{",
"bin",
":",
"binRelativeToPackage",
"}",
"=",
"require",
"(",
"packagePath",
")",
"if",
"(",
"typeof",
"binRelativeToPackage",
"===",
"'object'",
")",
"{",
"binRelativeToPackage",
"=",
"binRelativeToPackage",
"[",
"binName",
"]",
"}",
"const",
"fullBinPath",
"=",
"path",
".",
"join",
"(",
"concurrentlyDir",
",",
"binRelativeToPackage",
")",
"return",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"fullBinPath",
")",
"}"
] | Get the path to one of the bin scripts exported by a package
@param {string} packageName - name of the npm package
@param {string} binName=packageName - name of the script
@returns {string} path, relative to process.cwd() | [
"Get",
"the",
"path",
"to",
"one",
"of",
"the",
"bin",
"scripts",
"exported",
"by",
"a",
"package"
] | b20c1db9dd79945ee255eff27897d26f763dfd98 | https://github.com/kentcdodds/nps-utils/blob/b20c1db9dd79945ee255eff27897d26f763dfd98/src/index.js#L409-L418 |
23,255 | glenjamin/mocha-multi | mocha-multi.js | done | function done(failures, fn, reportersWithDone, waitFor = identity) {
const count = reportersWithDone.length;
const waitReporter = waitOn((r, f) => r.done(failures, f));
const progress = v => debug('Awaiting on %j reporters to invoke done callback.', count - v);
promiseProgress(reportersWithDone.map(waitReporter), progress)
.then(() => {
debug('All reporters invoked done callback.');
})
.then(waitFor)
.then(() => fn && fn(failures));
} | javascript | function done(failures, fn, reportersWithDone, waitFor = identity) {
const count = reportersWithDone.length;
const waitReporter = waitOn((r, f) => r.done(failures, f));
const progress = v => debug('Awaiting on %j reporters to invoke done callback.', count - v);
promiseProgress(reportersWithDone.map(waitReporter), progress)
.then(() => {
debug('All reporters invoked done callback.');
})
.then(waitFor)
.then(() => fn && fn(failures));
} | [
"function",
"done",
"(",
"failures",
",",
"fn",
",",
"reportersWithDone",
",",
"waitFor",
"=",
"identity",
")",
"{",
"const",
"count",
"=",
"reportersWithDone",
".",
"length",
";",
"const",
"waitReporter",
"=",
"waitOn",
"(",
"(",
"r",
",",
"f",
")",
"=>",
"r",
".",
"done",
"(",
"failures",
",",
"f",
")",
")",
";",
"const",
"progress",
"=",
"v",
"=>",
"debug",
"(",
"'Awaiting on %j reporters to invoke done callback.'",
",",
"count",
"-",
"v",
")",
";",
"promiseProgress",
"(",
"reportersWithDone",
".",
"map",
"(",
"waitReporter",
")",
",",
"progress",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"debug",
"(",
"'All reporters invoked done callback.'",
")",
";",
"}",
")",
".",
"then",
"(",
"waitFor",
")",
".",
"then",
"(",
"(",
")",
"=>",
"fn",
"&&",
"fn",
"(",
"failures",
")",
")",
";",
"}"
] | Override done to allow done processing for any reporters that have a done method. | [
"Override",
"done",
"to",
"allow",
"done",
"processing",
"for",
"any",
"reporters",
"that",
"have",
"a",
"done",
"method",
"."
] | fdaba56dd70b49b2846decd8fa0aec9c79180899 | https://github.com/glenjamin/mocha-multi/blob/fdaba56dd70b49b2846decd8fa0aec9c79180899/mocha-multi.js#L241-L251 |
23,256 | jeffbski/bench-rest | lib/bench-rest.js | needsSubtitution | function needsSubtitution(prop) {
var needsSub = false;
if (typeof prop === 'string') {
if (prop.indexOf('#{INDEX}') !== -1) needsSub = true;
} else if (typeof prop === 'object') {
var str = JSON.stringify(prop);
if (str.indexOf('#{INDEX}') !== -1) needsSub = true;
}
return needsSub;
} | javascript | function needsSubtitution(prop) {
var needsSub = false;
if (typeof prop === 'string') {
if (prop.indexOf('#{INDEX}') !== -1) needsSub = true;
} else if (typeof prop === 'object') {
var str = JSON.stringify(prop);
if (str.indexOf('#{INDEX}') !== -1) needsSub = true;
}
return needsSub;
} | [
"function",
"needsSubtitution",
"(",
"prop",
")",
"{",
"var",
"needsSub",
"=",
"false",
";",
"if",
"(",
"typeof",
"prop",
"===",
"'string'",
")",
"{",
"if",
"(",
"prop",
".",
"indexOf",
"(",
"'#{INDEX}'",
")",
"!==",
"-",
"1",
")",
"needsSub",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"typeof",
"prop",
"===",
"'object'",
")",
"{",
"var",
"str",
"=",
"JSON",
".",
"stringify",
"(",
"prop",
")",
";",
"if",
"(",
"str",
".",
"indexOf",
"(",
"'#{INDEX}'",
")",
"!==",
"-",
"1",
")",
"needsSub",
"=",
"true",
";",
"}",
"return",
"needsSub",
";",
"}"
] | determines if a property needs substitution
@returns boolean true if needs substition | [
"determines",
"if",
"a",
"property",
"needs",
"substitution"
] | c9f3ee3420bcbabeb3cf650327662a26b0d6497f | https://github.com/jeffbski/bench-rest/blob/c9f3ee3420bcbabeb3cf650327662a26b0d6497f/lib/bench-rest.js#L311-L320 |
23,257 | jeffbski/bench-rest | lib/bench-rest.js | substituteFnWhereNeeded | function substituteFnWhereNeeded(actions) {
actions = actions || [];
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
if ((key === 'get' || key === 'head' || key === 'put' || key === 'post' || key === 'del' || key === 'patch') &&
needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return action[key].replace(/\#\{INDEX\}/g, tokens.INDEX);
};
} else if (key === 'json' && needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return JSON.parse(JSON.stringify(action[key]).replace(/\#\{INDEX\}/g, tokens.INDEX));
};
} else if (key === 'body' && typeof action.body === 'string' && needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return action[key].replace(/\#\{INDEX\}/g, tokens.INDEX);
};
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
} | javascript | function substituteFnWhereNeeded(actions) {
actions = actions || [];
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
if ((key === 'get' || key === 'head' || key === 'put' || key === 'post' || key === 'del' || key === 'patch') &&
needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return action[key].replace(/\#\{INDEX\}/g, tokens.INDEX);
};
} else if (key === 'json' && needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return JSON.parse(JSON.stringify(action[key]).replace(/\#\{INDEX\}/g, tokens.INDEX));
};
} else if (key === 'body' && typeof action.body === 'string' && needsSubtitution(action[key])) {
accum[key] = function (tokens) {
return action[key].replace(/\#\{INDEX\}/g, tokens.INDEX);
};
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
} | [
"function",
"substituteFnWhereNeeded",
"(",
"actions",
")",
"{",
"actions",
"=",
"actions",
"||",
"[",
"]",
";",
"return",
"actions",
".",
"map",
"(",
"function",
"(",
"action",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"action",
")",
".",
"reduce",
"(",
"function",
"(",
"accum",
",",
"key",
")",
"{",
"if",
"(",
"(",
"key",
"===",
"'get'",
"||",
"key",
"===",
"'head'",
"||",
"key",
"===",
"'put'",
"||",
"key",
"===",
"'post'",
"||",
"key",
"===",
"'del'",
"||",
"key",
"===",
"'patch'",
")",
"&&",
"needsSubtitution",
"(",
"action",
"[",
"key",
"]",
")",
")",
"{",
"accum",
"[",
"key",
"]",
"=",
"function",
"(",
"tokens",
")",
"{",
"return",
"action",
"[",
"key",
"]",
".",
"replace",
"(",
"/",
"\\#\\{INDEX\\}",
"/",
"g",
",",
"tokens",
".",
"INDEX",
")",
";",
"}",
";",
"}",
"else",
"if",
"(",
"key",
"===",
"'json'",
"&&",
"needsSubtitution",
"(",
"action",
"[",
"key",
"]",
")",
")",
"{",
"accum",
"[",
"key",
"]",
"=",
"function",
"(",
"tokens",
")",
"{",
"return",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"action",
"[",
"key",
"]",
")",
".",
"replace",
"(",
"/",
"\\#\\{INDEX\\}",
"/",
"g",
",",
"tokens",
".",
"INDEX",
")",
")",
";",
"}",
";",
"}",
"else",
"if",
"(",
"key",
"===",
"'body'",
"&&",
"typeof",
"action",
".",
"body",
"===",
"'string'",
"&&",
"needsSubtitution",
"(",
"action",
"[",
"key",
"]",
")",
")",
"{",
"accum",
"[",
"key",
"]",
"=",
"function",
"(",
"tokens",
")",
"{",
"return",
"action",
"[",
"key",
"]",
".",
"replace",
"(",
"/",
"\\#\\{INDEX\\}",
"/",
"g",
",",
"tokens",
".",
"INDEX",
")",
";",
"}",
";",
"}",
"else",
"{",
"accum",
"[",
"key",
"]",
"=",
"action",
"[",
"key",
"]",
";",
"}",
"return",
"accum",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
")",
";",
"}"
] | create modified actions object which has substituteFns for any keys that
are using substitution. These substituteFns have one argument `tokens` which
will be bound to them in the queuing loop, so at runtime, the fn will be
executed and returns the proper value.
Keys which do not need substitution, will be returned untouched and thus
will save the overhead of needing replacement and stringify/parse (json)
If adding keys, be sure to update the SUBSTITUTED_KEYS constant.
@returns actions object with replacements done as necessary | [
"create",
"modified",
"actions",
"object",
"which",
"has",
"substituteFns",
"for",
"any",
"keys",
"that",
"are",
"using",
"substitution",
".",
"These",
"substituteFns",
"have",
"one",
"argument",
"tokens",
"which",
"will",
"be",
"bound",
"to",
"them",
"in",
"the",
"queuing",
"loop",
"so",
"at",
"runtime",
"the",
"fn",
"will",
"be",
"executed",
"and",
"returns",
"the",
"proper",
"value",
"."
] | c9f3ee3420bcbabeb3cf650327662a26b0d6497f | https://github.com/jeffbski/bench-rest/blob/c9f3ee3420bcbabeb3cf650327662a26b0d6497f/lib/bench-rest.js#L335-L358 |
23,258 | jeffbski/bench-rest | lib/bench-rest.js | bindSubtituteFnsWithTokens | function bindSubtituteFnsWithTokens(actions, tokens) {
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
// if it is list of sub keys, and is a fn, then bind with tokens
if (SUBSTITUTED_KEYS.indexOf(key) !== -1 && typeof action[key] === 'function') {
accum[key] = action[key].bind(null, tokens);
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
} | javascript | function bindSubtituteFnsWithTokens(actions, tokens) {
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
// if it is list of sub keys, and is a fn, then bind with tokens
if (SUBSTITUTED_KEYS.indexOf(key) !== -1 && typeof action[key] === 'function') {
accum[key] = action[key].bind(null, tokens);
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
} | [
"function",
"bindSubtituteFnsWithTokens",
"(",
"actions",
",",
"tokens",
")",
"{",
"return",
"actions",
".",
"map",
"(",
"function",
"(",
"action",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"action",
")",
".",
"reduce",
"(",
"function",
"(",
"accum",
",",
"key",
")",
"{",
"// if it is list of sub keys, and is a fn, then bind with tokens",
"if",
"(",
"SUBSTITUTED_KEYS",
".",
"indexOf",
"(",
"key",
")",
"!==",
"-",
"1",
"&&",
"typeof",
"action",
"[",
"key",
"]",
"===",
"'function'",
")",
"{",
"accum",
"[",
"key",
"]",
"=",
"action",
"[",
"key",
"]",
".",
"bind",
"(",
"null",
",",
"tokens",
")",
";",
"}",
"else",
"{",
"accum",
"[",
"key",
"]",
"=",
"action",
"[",
"key",
"]",
";",
"}",
"return",
"accum",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
")",
";",
"}"
] | if any of the action properties that allow substitution are fns, then
bind the tokens to the fn, so when executed it will have proper value
@returns actions with fns bound | [
"if",
"any",
"of",
"the",
"action",
"properties",
"that",
"allow",
"substitution",
"are",
"fns",
"then",
"bind",
"the",
"tokens",
"to",
"the",
"fn",
"so",
"when",
"executed",
"it",
"will",
"have",
"proper",
"value"
] | c9f3ee3420bcbabeb3cf650327662a26b0d6497f | https://github.com/jeffbski/bench-rest/blob/c9f3ee3420bcbabeb3cf650327662a26b0d6497f/lib/bench-rest.js#L365-L377 |
23,259 | jeffbski/bench-rest | lib/bench-rest.js | execAnySubFns | function execAnySubFns(actions) {
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
// if it is list of sub keys, and is a fn, then bind with tokens
if (SUBSTITUTED_KEYS.indexOf(key) !== -1 && typeof action[key] === 'function') {
accum[key] = action[key](); // exec fn to get value
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
} | javascript | function execAnySubFns(actions) {
return actions.map(function (action) {
return Object.keys(action).reduce(function (accum, key) {
// if it is list of sub keys, and is a fn, then bind with tokens
if (SUBSTITUTED_KEYS.indexOf(key) !== -1 && typeof action[key] === 'function') {
accum[key] = action[key](); // exec fn to get value
} else {
accum[key] = action[key];
}
return accum;
}, {});
});
} | [
"function",
"execAnySubFns",
"(",
"actions",
")",
"{",
"return",
"actions",
".",
"map",
"(",
"function",
"(",
"action",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"action",
")",
".",
"reduce",
"(",
"function",
"(",
"accum",
",",
"key",
")",
"{",
"// if it is list of sub keys, and is a fn, then bind with tokens",
"if",
"(",
"SUBSTITUTED_KEYS",
".",
"indexOf",
"(",
"key",
")",
"!==",
"-",
"1",
"&&",
"typeof",
"action",
"[",
"key",
"]",
"===",
"'function'",
")",
"{",
"accum",
"[",
"key",
"]",
"=",
"action",
"[",
"key",
"]",
"(",
")",
";",
"// exec fn to get value",
"}",
"else",
"{",
"accum",
"[",
"key",
"]",
"=",
"action",
"[",
"key",
"]",
";",
"}",
"return",
"accum",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
")",
";",
"}"
] | If any substitutions need to be done, the properties will be
replaced with a fn which has been bound to tokens, so exec the
fn and return the value for the property
@returns actions with values ready for use | [
"If",
"any",
"substitutions",
"need",
"to",
"be",
"done",
"the",
"properties",
"will",
"be",
"replaced",
"with",
"a",
"fn",
"which",
"has",
"been",
"bound",
"to",
"tokens",
"so",
"exec",
"the",
"fn",
"and",
"return",
"the",
"value",
"for",
"the",
"property"
] | c9f3ee3420bcbabeb3cf650327662a26b0d6497f | https://github.com/jeffbski/bench-rest/blob/c9f3ee3420bcbabeb3cf650327662a26b0d6497f/lib/bench-rest.js#L385-L397 |
23,260 | mathew-kurian/Scribe.js | static/lib/autocomplete.js | function(scope, element, attrs, autoCtrl){
element.bind('mouseenter', function() {
autoCtrl.preSelect(attrs.val);
autoCtrl.setIndex(attrs.index);
});
element.bind('mouseleave', function() {
autoCtrl.preSelectOff();
});
} | javascript | function(scope, element, attrs, autoCtrl){
element.bind('mouseenter', function() {
autoCtrl.preSelect(attrs.val);
autoCtrl.setIndex(attrs.index);
});
element.bind('mouseleave', function() {
autoCtrl.preSelectOff();
});
} | [
"function",
"(",
"scope",
",",
"element",
",",
"attrs",
",",
"autoCtrl",
")",
"{",
"element",
".",
"bind",
"(",
"'mouseenter'",
",",
"function",
"(",
")",
"{",
"autoCtrl",
".",
"preSelect",
"(",
"attrs",
".",
"val",
")",
";",
"autoCtrl",
".",
"setIndex",
"(",
"attrs",
".",
"index",
")",
";",
"}",
")",
";",
"element",
".",
"bind",
"(",
"'mouseleave'",
",",
"function",
"(",
")",
"{",
"autoCtrl",
".",
"preSelectOff",
"(",
")",
";",
"}",
")",
";",
"}"
] | ^look for controller on parents element | [
"^look",
"for",
"controller",
"on",
"parents",
"element"
] | 8b5fb7e34e541a661fedcf89c8c910d0f355a11b | https://github.com/mathew-kurian/Scribe.js/blob/8b5fb7e34e541a661fedcf89c8c910d0f355a11b/static/lib/autocomplete.js#L273-L282 | |
23,261 | mathew-kurian/Scribe.js | static/js/services/scribeAPI.js | function (data) {
var lines = data.match(/[^\r\n]+/g); //cut lines
return lines.map(function (line) {
try {
return JSON.parse(line);
} catch (e) {
return line;
}
});
} | javascript | function (data) {
var lines = data.match(/[^\r\n]+/g); //cut lines
return lines.map(function (line) {
try {
return JSON.parse(line);
} catch (e) {
return line;
}
});
} | [
"function",
"(",
"data",
")",
"{",
"var",
"lines",
"=",
"data",
".",
"match",
"(",
"/",
"[^\\r\\n]+",
"/",
"g",
")",
";",
"//cut lines",
"return",
"lines",
".",
"map",
"(",
"function",
"(",
"line",
")",
"{",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"line",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"line",
";",
"}",
"}",
")",
";",
"}"
] | As logs are lines of JSON, we want to parse each lines one by one | [
"As",
"logs",
"are",
"lines",
"of",
"JSON",
"we",
"want",
"to",
"parse",
"each",
"lines",
"one",
"by",
"one"
] | 8b5fb7e34e541a661fedcf89c8c910d0f355a11b | https://github.com/mathew-kurian/Scribe.js/blob/8b5fb7e34e541a661fedcf89c8c910d0f355a11b/static/js/services/scribeAPI.js#L37-L48 | |
23,262 | linkedin/sepia | src/cache.js | playback | function playback(resHeaders, resBody) {
if (!forceLive) {
var headerContent = fs.readFileSync(filename + '.headers');
resHeaders = JSON.parse(headerContent);
}
var socket = new EventEmitter();
socket.setTimeout = socket.setEncoding = function() {};
// Needed for node 0.8.x
socket.destroy = socket.pause = socket.resume = function() {};
req.socket = socket;
req.emit('socket', socket);
if (resHeaders.timeout) {
socket.emit('timeout');
req.emit('error', new Error('Timeout'));
return;
}
if (resHeaders.error) {
req.emit('error', resHeaders.error);
return;
}
var res = new http.IncomingMessage(socket);
res.headers = resHeaders.headers || {};
res.statusCode = resHeaders.statusCode;
if (callback) {
callback(res);
}
if (!forceLive) {
resBody = fs.readFileSync(filename);
}
req.emit('response', res);
if (res.push) {
// node 0.10.x
res.push(resBody);
res.push(null);
} else {
// node 0.8.x
res.emit('data', resBody);
res.emit('end');
}
} | javascript | function playback(resHeaders, resBody) {
if (!forceLive) {
var headerContent = fs.readFileSync(filename + '.headers');
resHeaders = JSON.parse(headerContent);
}
var socket = new EventEmitter();
socket.setTimeout = socket.setEncoding = function() {};
// Needed for node 0.8.x
socket.destroy = socket.pause = socket.resume = function() {};
req.socket = socket;
req.emit('socket', socket);
if (resHeaders.timeout) {
socket.emit('timeout');
req.emit('error', new Error('Timeout'));
return;
}
if (resHeaders.error) {
req.emit('error', resHeaders.error);
return;
}
var res = new http.IncomingMessage(socket);
res.headers = resHeaders.headers || {};
res.statusCode = resHeaders.statusCode;
if (callback) {
callback(res);
}
if (!forceLive) {
resBody = fs.readFileSync(filename);
}
req.emit('response', res);
if (res.push) {
// node 0.10.x
res.push(resBody);
res.push(null);
} else {
// node 0.8.x
res.emit('data', resBody);
res.emit('end');
}
} | [
"function",
"playback",
"(",
"resHeaders",
",",
"resBody",
")",
"{",
"if",
"(",
"!",
"forceLive",
")",
"{",
"var",
"headerContent",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
"+",
"'.headers'",
")",
";",
"resHeaders",
"=",
"JSON",
".",
"parse",
"(",
"headerContent",
")",
";",
"}",
"var",
"socket",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"socket",
".",
"setTimeout",
"=",
"socket",
".",
"setEncoding",
"=",
"function",
"(",
")",
"{",
"}",
";",
"// Needed for node 0.8.x",
"socket",
".",
"destroy",
"=",
"socket",
".",
"pause",
"=",
"socket",
".",
"resume",
"=",
"function",
"(",
")",
"{",
"}",
";",
"req",
".",
"socket",
"=",
"socket",
";",
"req",
".",
"emit",
"(",
"'socket'",
",",
"socket",
")",
";",
"if",
"(",
"resHeaders",
".",
"timeout",
")",
"{",
"socket",
".",
"emit",
"(",
"'timeout'",
")",
";",
"req",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"'Timeout'",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"resHeaders",
".",
"error",
")",
"{",
"req",
".",
"emit",
"(",
"'error'",
",",
"resHeaders",
".",
"error",
")",
";",
"return",
";",
"}",
"var",
"res",
"=",
"new",
"http",
".",
"IncomingMessage",
"(",
"socket",
")",
";",
"res",
".",
"headers",
"=",
"resHeaders",
".",
"headers",
"||",
"{",
"}",
";",
"res",
".",
"statusCode",
"=",
"resHeaders",
".",
"statusCode",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"res",
")",
";",
"}",
"if",
"(",
"!",
"forceLive",
")",
"{",
"resBody",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
")",
";",
"}",
"req",
".",
"emit",
"(",
"'response'",
",",
"res",
")",
";",
"if",
"(",
"res",
".",
"push",
")",
"{",
"// node 0.10.x",
"res",
".",
"push",
"(",
"resBody",
")",
";",
"res",
".",
"push",
"(",
"null",
")",
";",
"}",
"else",
"{",
"// node 0.8.x",
"res",
".",
"emit",
"(",
"'data'",
",",
"resBody",
")",
";",
"res",
".",
"emit",
"(",
"'end'",
")",
";",
"}",
"}"
] | Only called if either the fixture with the constructed filename exists, or we're playing back passed in data. | [
"Only",
"called",
"if",
"either",
"the",
"fixture",
"with",
"the",
"constructed",
"filename",
"exists",
"or",
"we",
"re",
"playing",
"back",
"passed",
"in",
"data",
"."
] | 96e2093462d8229da271b5862008aa625d0fe048 | https://github.com/linkedin/sepia/blob/96e2093462d8229da271b5862008aa625d0fe048/src/cache.js#L88-L136 |
23,263 | gustavohenke/bselect | src/bselect.js | function( arg ) {
var listItems, listItem, i, len, results;
var options = _callMethod( this, "option" );
var searched = arg instanceof $.Event ? arg.target.value : arg;
var bselect = _callMethod( this, "element" );
if ( this[ 0 ].disabled ) {
return this;
}
// Avoid searching for nothing
if ( searched === "" ) {
_callMethod( this, "clearSearch" );
}
if ( !( arg instanceof $.Event ) ) {
bselect.find( ".bselect-search" ).val( searched );
}
// Same search/few chars? We won't search then!
if (
( searched === options.lastSearch ) ||
( searched.length < options.minSearchInput )
) {
return;
}
// Initialize the result collection
results = $();
listItems = bselect.find( "li" ).hide();
for ( i = 0, len = listItems.length; i < len; i++ ) {
listItem = listItems[ i ];
if ( listItem.textContent.toLowerCase().indexOf( searched.toLowerCase() ) > -1 ) {
results = results.add( $( listItem ).show() );
}
}
if ( results.length === 0 ) {
showNoOptionsAvailable( this );
} else {
bselect.find( ".bselect-message" ).hide();
}
this.trigger( "bselectsearch", [ searched, results ] );
adjustDropdownHeight( listItems.end() );
return this;
} | javascript | function( arg ) {
var listItems, listItem, i, len, results;
var options = _callMethod( this, "option" );
var searched = arg instanceof $.Event ? arg.target.value : arg;
var bselect = _callMethod( this, "element" );
if ( this[ 0 ].disabled ) {
return this;
}
// Avoid searching for nothing
if ( searched === "" ) {
_callMethod( this, "clearSearch" );
}
if ( !( arg instanceof $.Event ) ) {
bselect.find( ".bselect-search" ).val( searched );
}
// Same search/few chars? We won't search then!
if (
( searched === options.lastSearch ) ||
( searched.length < options.minSearchInput )
) {
return;
}
// Initialize the result collection
results = $();
listItems = bselect.find( "li" ).hide();
for ( i = 0, len = listItems.length; i < len; i++ ) {
listItem = listItems[ i ];
if ( listItem.textContent.toLowerCase().indexOf( searched.toLowerCase() ) > -1 ) {
results = results.add( $( listItem ).show() );
}
}
if ( results.length === 0 ) {
showNoOptionsAvailable( this );
} else {
bselect.find( ".bselect-message" ).hide();
}
this.trigger( "bselectsearch", [ searched, results ] );
adjustDropdownHeight( listItems.end() );
return this;
} | [
"function",
"(",
"arg",
")",
"{",
"var",
"listItems",
",",
"listItem",
",",
"i",
",",
"len",
",",
"results",
";",
"var",
"options",
"=",
"_callMethod",
"(",
"this",
",",
"\"option\"",
")",
";",
"var",
"searched",
"=",
"arg",
"instanceof",
"$",
".",
"Event",
"?",
"arg",
".",
"target",
".",
"value",
":",
"arg",
";",
"var",
"bselect",
"=",
"_callMethod",
"(",
"this",
",",
"\"element\"",
")",
";",
"if",
"(",
"this",
"[",
"0",
"]",
".",
"disabled",
")",
"{",
"return",
"this",
";",
"}",
"// Avoid searching for nothing\r",
"if",
"(",
"searched",
"===",
"\"\"",
")",
"{",
"_callMethod",
"(",
"this",
",",
"\"clearSearch\"",
")",
";",
"}",
"if",
"(",
"!",
"(",
"arg",
"instanceof",
"$",
".",
"Event",
")",
")",
"{",
"bselect",
".",
"find",
"(",
"\".bselect-search\"",
")",
".",
"val",
"(",
"searched",
")",
";",
"}",
"// Same search/few chars? We won't search then!\r",
"if",
"(",
"(",
"searched",
"===",
"options",
".",
"lastSearch",
")",
"||",
"(",
"searched",
".",
"length",
"<",
"options",
".",
"minSearchInput",
")",
")",
"{",
"return",
";",
"}",
"// Initialize the result collection\r",
"results",
"=",
"$",
"(",
")",
";",
"listItems",
"=",
"bselect",
".",
"find",
"(",
"\"li\"",
")",
".",
"hide",
"(",
")",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"listItems",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"listItem",
"=",
"listItems",
"[",
"i",
"]",
";",
"if",
"(",
"listItem",
".",
"textContent",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"searched",
".",
"toLowerCase",
"(",
")",
")",
">",
"-",
"1",
")",
"{",
"results",
"=",
"results",
".",
"add",
"(",
"$",
"(",
"listItem",
")",
".",
"show",
"(",
")",
")",
";",
"}",
"}",
"if",
"(",
"results",
".",
"length",
"===",
"0",
")",
"{",
"showNoOptionsAvailable",
"(",
"this",
")",
";",
"}",
"else",
"{",
"bselect",
".",
"find",
"(",
"\".bselect-message\"",
")",
".",
"hide",
"(",
")",
";",
"}",
"this",
".",
"trigger",
"(",
"\"bselectsearch\"",
",",
"[",
"searched",
",",
"results",
"]",
")",
";",
"adjustDropdownHeight",
"(",
"listItems",
".",
"end",
"(",
")",
")",
";",
"return",
"this",
";",
"}"
] | Searches every item in the list for the given text | [
"Searches",
"every",
"item",
"in",
"the",
"list",
"for",
"the",
"given",
"text"
] | 8ee485e3ef24e9498f9e32aac4a424a864a1eb99 | https://github.com/gustavohenke/bselect/blob/8ee485e3ef24e9498f9e32aac4a424a864a1eb99/src/bselect.js#L182-L230 | |
23,264 | gustavohenke/bselect | src/bselect.js | function() {
var bselect = _callMethod( this, "element" );
var optionList = bselect.find( ".bselect-option-list" ).empty();
var mapping = {};
var i = 0;
bselect.toggleClass( "disabled", this.prop( "disabled" ) );
this.find( "option, > optgroup" ).each(function() {
var classes, li;
var isOption = $( this ).is( "option" );
if ( isOption && !this.value ) {
return;
}
if ( isOption ) {
classes = "bselect-option";
if ( $( this ).closest( "optgroup" ).length ) {
classes += " grouped";
}
} else {
classes = "bselect-option-group";
}
li = $( "<li />" ).attr({
"class": classes,
// While there aren't roles for optgroup, we'll stick with the role option.
role: "option",
tabindex: isOption ? 2 : -1,
"aria-selected": "false"
});
if ( isOption ) {
li.data( "value", this.value );
mapping[ this.value ] = i;
li.html( "<a href='#'>" + this.text + "</a>" );
} else {
li.text( this.label );
}
li.appendTo( optionList );
i++;
});
if ( i === 0 ) {
showNoOptionsAvailable( this );
}
this.data( dataName ).itemsMap = mapping;
return this;
} | javascript | function() {
var bselect = _callMethod( this, "element" );
var optionList = bselect.find( ".bselect-option-list" ).empty();
var mapping = {};
var i = 0;
bselect.toggleClass( "disabled", this.prop( "disabled" ) );
this.find( "option, > optgroup" ).each(function() {
var classes, li;
var isOption = $( this ).is( "option" );
if ( isOption && !this.value ) {
return;
}
if ( isOption ) {
classes = "bselect-option";
if ( $( this ).closest( "optgroup" ).length ) {
classes += " grouped";
}
} else {
classes = "bselect-option-group";
}
li = $( "<li />" ).attr({
"class": classes,
// While there aren't roles for optgroup, we'll stick with the role option.
role: "option",
tabindex: isOption ? 2 : -1,
"aria-selected": "false"
});
if ( isOption ) {
li.data( "value", this.value );
mapping[ this.value ] = i;
li.html( "<a href='#'>" + this.text + "</a>" );
} else {
li.text( this.label );
}
li.appendTo( optionList );
i++;
});
if ( i === 0 ) {
showNoOptionsAvailable( this );
}
this.data( dataName ).itemsMap = mapping;
return this;
} | [
"function",
"(",
")",
"{",
"var",
"bselect",
"=",
"_callMethod",
"(",
"this",
",",
"\"element\"",
")",
";",
"var",
"optionList",
"=",
"bselect",
".",
"find",
"(",
"\".bselect-option-list\"",
")",
".",
"empty",
"(",
")",
";",
"var",
"mapping",
"=",
"{",
"}",
";",
"var",
"i",
"=",
"0",
";",
"bselect",
".",
"toggleClass",
"(",
"\"disabled\"",
",",
"this",
".",
"prop",
"(",
"\"disabled\"",
")",
")",
";",
"this",
".",
"find",
"(",
"\"option, > optgroup\"",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"classes",
",",
"li",
";",
"var",
"isOption",
"=",
"$",
"(",
"this",
")",
".",
"is",
"(",
"\"option\"",
")",
";",
"if",
"(",
"isOption",
"&&",
"!",
"this",
".",
"value",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isOption",
")",
"{",
"classes",
"=",
"\"bselect-option\"",
";",
"if",
"(",
"$",
"(",
"this",
")",
".",
"closest",
"(",
"\"optgroup\"",
")",
".",
"length",
")",
"{",
"classes",
"+=",
"\" grouped\"",
";",
"}",
"}",
"else",
"{",
"classes",
"=",
"\"bselect-option-group\"",
";",
"}",
"li",
"=",
"$",
"(",
"\"<li />\"",
")",
".",
"attr",
"(",
"{",
"\"class\"",
":",
"classes",
",",
"// While there aren't roles for optgroup, we'll stick with the role option.\r",
"role",
":",
"\"option\"",
",",
"tabindex",
":",
"isOption",
"?",
"2",
":",
"-",
"1",
",",
"\"aria-selected\"",
":",
"\"false\"",
"}",
")",
";",
"if",
"(",
"isOption",
")",
"{",
"li",
".",
"data",
"(",
"\"value\"",
",",
"this",
".",
"value",
")",
";",
"mapping",
"[",
"this",
".",
"value",
"]",
"=",
"i",
";",
"li",
".",
"html",
"(",
"\"<a href='#'>\"",
"+",
"this",
".",
"text",
"+",
"\"</a>\"",
")",
";",
"}",
"else",
"{",
"li",
".",
"text",
"(",
"this",
".",
"label",
")",
";",
"}",
"li",
".",
"appendTo",
"(",
"optionList",
")",
";",
"i",
"++",
";",
"}",
")",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"showNoOptionsAvailable",
"(",
"this",
")",
";",
"}",
"this",
".",
"data",
"(",
"dataName",
")",
".",
"itemsMap",
"=",
"mapping",
";",
"return",
"this",
";",
"}"
] | Refreshes the option list. Useful when new HTML is added | [
"Refreshes",
"the",
"option",
"list",
".",
"Useful",
"when",
"new",
"HTML",
"is",
"added"
] | 8ee485e3ef24e9498f9e32aac4a424a864a1eb99 | https://github.com/gustavohenke/bselect/blob/8ee485e3ef24e9498f9e32aac4a424a864a1eb99/src/bselect.js#L265-L317 | |
23,265 | gustavohenke/bselect | src/bselect.js | adjustDropdownHeight | function adjustDropdownHeight( $elem ) {
var list = $elem.find( ".bselect-option-list" );
var len = list.find( "li:visible" ).length;
list.innerHeight( parseInt( list.css( "line-height" ), 10 ) * 1.5 * ( len < 5 ? len : 5 ) );
} | javascript | function adjustDropdownHeight( $elem ) {
var list = $elem.find( ".bselect-option-list" );
var len = list.find( "li:visible" ).length;
list.innerHeight( parseInt( list.css( "line-height" ), 10 ) * 1.5 * ( len < 5 ? len : 5 ) );
} | [
"function",
"adjustDropdownHeight",
"(",
"$elem",
")",
"{",
"var",
"list",
"=",
"$elem",
".",
"find",
"(",
"\".bselect-option-list\"",
")",
";",
"var",
"len",
"=",
"list",
".",
"find",
"(",
"\"li:visible\"",
")",
".",
"length",
";",
"list",
".",
"innerHeight",
"(",
"parseInt",
"(",
"list",
".",
"css",
"(",
"\"line-height\"",
")",
",",
"10",
")",
"*",
"1.5",
"*",
"(",
"len",
"<",
"5",
"?",
"len",
":",
"5",
")",
")",
";",
"}"
] | Adjusts the dropdown height of an bselect. | [
"Adjusts",
"the",
"dropdown",
"height",
"of",
"an",
"bselect",
"."
] | 8ee485e3ef24e9498f9e32aac4a424a864a1eb99 | https://github.com/gustavohenke/bselect/blob/8ee485e3ef24e9498f9e32aac4a424a864a1eb99/src/bselect.js#L360-L365 |
23,266 | gustavohenke/bselect | src/bselect.js | updateOptions | function updateOptions( $elem, prev, curr ) {
var bselect = _callMethod( $elem, "element" );
$.each( prev, function(key, val) {
if ( curr[ key ] !== val ) {
if ( key === "size" ) {
var sizes = $.map( bootstrapButtonSizes.slice( 0 ), function( size ) {
return "bselect-" + size;
}).join( " " );
bselect.removeClass( sizes );
if ( bootstrapButtonSizes.indexOf( curr.size ) > -1 ) {
bselect.addClass( "bselect-" + curr.size );
}
}
}
});
} | javascript | function updateOptions( $elem, prev, curr ) {
var bselect = _callMethod( $elem, "element" );
$.each( prev, function(key, val) {
if ( curr[ key ] !== val ) {
if ( key === "size" ) {
var sizes = $.map( bootstrapButtonSizes.slice( 0 ), function( size ) {
return "bselect-" + size;
}).join( " " );
bselect.removeClass( sizes );
if ( bootstrapButtonSizes.indexOf( curr.size ) > -1 ) {
bselect.addClass( "bselect-" + curr.size );
}
}
}
});
} | [
"function",
"updateOptions",
"(",
"$elem",
",",
"prev",
",",
"curr",
")",
"{",
"var",
"bselect",
"=",
"_callMethod",
"(",
"$elem",
",",
"\"element\"",
")",
";",
"$",
".",
"each",
"(",
"prev",
",",
"function",
"(",
"key",
",",
"val",
")",
"{",
"if",
"(",
"curr",
"[",
"key",
"]",
"!==",
"val",
")",
"{",
"if",
"(",
"key",
"===",
"\"size\"",
")",
"{",
"var",
"sizes",
"=",
"$",
".",
"map",
"(",
"bootstrapButtonSizes",
".",
"slice",
"(",
"0",
")",
",",
"function",
"(",
"size",
")",
"{",
"return",
"\"bselect-\"",
"+",
"size",
";",
"}",
")",
".",
"join",
"(",
"\" \"",
")",
";",
"bselect",
".",
"removeClass",
"(",
"sizes",
")",
";",
"if",
"(",
"bootstrapButtonSizes",
".",
"indexOf",
"(",
"curr",
".",
"size",
")",
">",
"-",
"1",
")",
"{",
"bselect",
".",
"addClass",
"(",
"\"bselect-\"",
"+",
"curr",
".",
"size",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}"
] | Updates visual properties of the bselect after the plugin was initialized | [
"Updates",
"visual",
"properties",
"of",
"the",
"bselect",
"after",
"the",
"plugin",
"was",
"initialized"
] | 8ee485e3ef24e9498f9e32aac4a424a864a1eb99 | https://github.com/gustavohenke/bselect/blob/8ee485e3ef24e9498f9e32aac4a424a864a1eb99/src/bselect.js#L368-L385 |
23,267 | gustavohenke/bselect | src/bselect.js | showNoOptionsAvailable | function showNoOptionsAvailable( $elem ) {
var bselect = _callMethod( $elem, "element" );
bselect.find( ".bselect-message" ).text( $.bselect.i18n.noOptionsAvailable ).show();
} | javascript | function showNoOptionsAvailable( $elem ) {
var bselect = _callMethod( $elem, "element" );
bselect.find( ".bselect-message" ).text( $.bselect.i18n.noOptionsAvailable ).show();
} | [
"function",
"showNoOptionsAvailable",
"(",
"$elem",
")",
"{",
"var",
"bselect",
"=",
"_callMethod",
"(",
"$elem",
",",
"\"element\"",
")",
";",
"bselect",
".",
"find",
"(",
"\".bselect-message\"",
")",
".",
"text",
"(",
"$",
".",
"bselect",
".",
"i18n",
".",
"noOptionsAvailable",
")",
".",
"show",
"(",
")",
";",
"}"
] | Show the 'no options available' message | [
"Show",
"the",
"no",
"options",
"available",
"message"
] | 8ee485e3ef24e9498f9e32aac4a424a864a1eb99 | https://github.com/gustavohenke/bselect/blob/8ee485e3ef24e9498f9e32aac4a424a864a1eb99/src/bselect.js#L388-L391 |
23,268 | gustavohenke/bselect | src/bselect.js | setup | function setup( elem, options ) {
var caret, label, container, id, dropdown;
var $elem = $( elem );
// First of, let's build the base HTML of BSelect
id = ++elements;
container = $( "<div class='bselect' />", {
id: "bselect-" + id
});
dropdown = $( "<div class='bselect-dropdown' />" );
// Configure the search input
if ( options.searchInput === true ) {
var search = $( "<div class='bselect-search' />" );
$( "<input type='text' class='bselect-search-input' />" ).attr({
role: "combobox",
tabindex: 1,
"aria-expanded": "false",
"aria-owns": "bselect-option-list-" + id
// The W3C documentation says that role="combobox" should have aria-autocomplete,
// but the validator tells us that this is invalid. Very strange.
//"aria-autocomplete": "list"
}).appendTo( search );
$( "<span class='bselect-search-icon' />" )
.append( "<i class='icon-search'></i>" )
.appendTo( search );
search.appendTo( dropdown );
}
$( "<div class='bselect-message' role='status' />" ).appendTo( dropdown );
$( "<ul class='bselect-option-list' />" ).attr({
id: "bselect-option-list-" + id,
role: "listbox"
}).appendTo( dropdown );
container.append( dropdown ).insertAfter( $elem );
// Save some precious data in the original select now, as we have the container in the DOM
$elem.data( dataName, {
options: options,
element: container,
open: false
});
updateOptions( $elem, $.bselect.defaults, options );
_callMethod( $elem, "refresh" );
$elem.bind( "bselectselect.bselect", options.select );
$elem.bind( "bselectselected.bselect", options.selected );
$elem.bind( "bselectsearch.bselect", options.search );
label = $( "<span />" ).addClass( "bselect-label" ).text( getPlaceholder( $elem ) );
caret = $( "<button type='button' />" ).addClass( "bselect-caret" )
.html( "<span class='caret'></span>" );
container.prepend( caret ).prepend( label );
label.outerWidth( $elem.outerWidth() - caret.outerWidth() );
// Hide this ugly select!
$elem.addClass( "bselect-inaccessible" );
// We'll cache the container for some actions
instances.push( $elem );
// Event binding
container.find( ".bselect-search-input" ).keyup( $.proxy( methods.search, $elem ) );
container.on( "click", ".bselect-option", $.proxy( methods.select, $elem ) );
container.on( "click", ".bselect-caret, .bselect-label", $.proxy( methods.toggle, $elem ) );
container.on( "keydown", ".bselect-option, .bselect-search-input", handleKeypress );
// Issue #6 - Listen to the change event and update the selected value
$elem.bind( "change.bselect", function() {
var data = $elem.data( dataName );
var index = data.itemsMap[ this.value ];
if ( data.tempDisable ) {
data.tempDisable = false;
return;
}
_callMethod( $elem, "select", index );
}).trigger( "change.bselect" );
} | javascript | function setup( elem, options ) {
var caret, label, container, id, dropdown;
var $elem = $( elem );
// First of, let's build the base HTML of BSelect
id = ++elements;
container = $( "<div class='bselect' />", {
id: "bselect-" + id
});
dropdown = $( "<div class='bselect-dropdown' />" );
// Configure the search input
if ( options.searchInput === true ) {
var search = $( "<div class='bselect-search' />" );
$( "<input type='text' class='bselect-search-input' />" ).attr({
role: "combobox",
tabindex: 1,
"aria-expanded": "false",
"aria-owns": "bselect-option-list-" + id
// The W3C documentation says that role="combobox" should have aria-autocomplete,
// but the validator tells us that this is invalid. Very strange.
//"aria-autocomplete": "list"
}).appendTo( search );
$( "<span class='bselect-search-icon' />" )
.append( "<i class='icon-search'></i>" )
.appendTo( search );
search.appendTo( dropdown );
}
$( "<div class='bselect-message' role='status' />" ).appendTo( dropdown );
$( "<ul class='bselect-option-list' />" ).attr({
id: "bselect-option-list-" + id,
role: "listbox"
}).appendTo( dropdown );
container.append( dropdown ).insertAfter( $elem );
// Save some precious data in the original select now, as we have the container in the DOM
$elem.data( dataName, {
options: options,
element: container,
open: false
});
updateOptions( $elem, $.bselect.defaults, options );
_callMethod( $elem, "refresh" );
$elem.bind( "bselectselect.bselect", options.select );
$elem.bind( "bselectselected.bselect", options.selected );
$elem.bind( "bselectsearch.bselect", options.search );
label = $( "<span />" ).addClass( "bselect-label" ).text( getPlaceholder( $elem ) );
caret = $( "<button type='button' />" ).addClass( "bselect-caret" )
.html( "<span class='caret'></span>" );
container.prepend( caret ).prepend( label );
label.outerWidth( $elem.outerWidth() - caret.outerWidth() );
// Hide this ugly select!
$elem.addClass( "bselect-inaccessible" );
// We'll cache the container for some actions
instances.push( $elem );
// Event binding
container.find( ".bselect-search-input" ).keyup( $.proxy( methods.search, $elem ) );
container.on( "click", ".bselect-option", $.proxy( methods.select, $elem ) );
container.on( "click", ".bselect-caret, .bselect-label", $.proxy( methods.toggle, $elem ) );
container.on( "keydown", ".bselect-option, .bselect-search-input", handleKeypress );
// Issue #6 - Listen to the change event and update the selected value
$elem.bind( "change.bselect", function() {
var data = $elem.data( dataName );
var index = data.itemsMap[ this.value ];
if ( data.tempDisable ) {
data.tempDisable = false;
return;
}
_callMethod( $elem, "select", index );
}).trigger( "change.bselect" );
} | [
"function",
"setup",
"(",
"elem",
",",
"options",
")",
"{",
"var",
"caret",
",",
"label",
",",
"container",
",",
"id",
",",
"dropdown",
";",
"var",
"$elem",
"=",
"$",
"(",
"elem",
")",
";",
"// First of, let's build the base HTML of BSelect\r",
"id",
"=",
"++",
"elements",
";",
"container",
"=",
"$",
"(",
"\"<div class='bselect' />\"",
",",
"{",
"id",
":",
"\"bselect-\"",
"+",
"id",
"}",
")",
";",
"dropdown",
"=",
"$",
"(",
"\"<div class='bselect-dropdown' />\"",
")",
";",
"// Configure the search input\r",
"if",
"(",
"options",
".",
"searchInput",
"===",
"true",
")",
"{",
"var",
"search",
"=",
"$",
"(",
"\"<div class='bselect-search' />\"",
")",
";",
"$",
"(",
"\"<input type='text' class='bselect-search-input' />\"",
")",
".",
"attr",
"(",
"{",
"role",
":",
"\"combobox\"",
",",
"tabindex",
":",
"1",
",",
"\"aria-expanded\"",
":",
"\"false\"",
",",
"\"aria-owns\"",
":",
"\"bselect-option-list-\"",
"+",
"id",
"// The W3C documentation says that role=\"combobox\" should have aria-autocomplete,\r",
"// but the validator tells us that this is invalid. Very strange.\r",
"//\"aria-autocomplete\": \"list\"\r",
"}",
")",
".",
"appendTo",
"(",
"search",
")",
";",
"$",
"(",
"\"<span class='bselect-search-icon' />\"",
")",
".",
"append",
"(",
"\"<i class='icon-search'></i>\"",
")",
".",
"appendTo",
"(",
"search",
")",
";",
"search",
".",
"appendTo",
"(",
"dropdown",
")",
";",
"}",
"$",
"(",
"\"<div class='bselect-message' role='status' />\"",
")",
".",
"appendTo",
"(",
"dropdown",
")",
";",
"$",
"(",
"\"<ul class='bselect-option-list' />\"",
")",
".",
"attr",
"(",
"{",
"id",
":",
"\"bselect-option-list-\"",
"+",
"id",
",",
"role",
":",
"\"listbox\"",
"}",
")",
".",
"appendTo",
"(",
"dropdown",
")",
";",
"container",
".",
"append",
"(",
"dropdown",
")",
".",
"insertAfter",
"(",
"$elem",
")",
";",
"// Save some precious data in the original select now, as we have the container in the DOM\r",
"$elem",
".",
"data",
"(",
"dataName",
",",
"{",
"options",
":",
"options",
",",
"element",
":",
"container",
",",
"open",
":",
"false",
"}",
")",
";",
"updateOptions",
"(",
"$elem",
",",
"$",
".",
"bselect",
".",
"defaults",
",",
"options",
")",
";",
"_callMethod",
"(",
"$elem",
",",
"\"refresh\"",
")",
";",
"$elem",
".",
"bind",
"(",
"\"bselectselect.bselect\"",
",",
"options",
".",
"select",
")",
";",
"$elem",
".",
"bind",
"(",
"\"bselectselected.bselect\"",
",",
"options",
".",
"selected",
")",
";",
"$elem",
".",
"bind",
"(",
"\"bselectsearch.bselect\"",
",",
"options",
".",
"search",
")",
";",
"label",
"=",
"$",
"(",
"\"<span />\"",
")",
".",
"addClass",
"(",
"\"bselect-label\"",
")",
".",
"text",
"(",
"getPlaceholder",
"(",
"$elem",
")",
")",
";",
"caret",
"=",
"$",
"(",
"\"<button type='button' />\"",
")",
".",
"addClass",
"(",
"\"bselect-caret\"",
")",
".",
"html",
"(",
"\"<span class='caret'></span>\"",
")",
";",
"container",
".",
"prepend",
"(",
"caret",
")",
".",
"prepend",
"(",
"label",
")",
";",
"label",
".",
"outerWidth",
"(",
"$elem",
".",
"outerWidth",
"(",
")",
"-",
"caret",
".",
"outerWidth",
"(",
")",
")",
";",
"// Hide this ugly select!\r",
"$elem",
".",
"addClass",
"(",
"\"bselect-inaccessible\"",
")",
";",
"// We'll cache the container for some actions\r",
"instances",
".",
"push",
"(",
"$elem",
")",
";",
"// Event binding\r",
"container",
".",
"find",
"(",
"\".bselect-search-input\"",
")",
".",
"keyup",
"(",
"$",
".",
"proxy",
"(",
"methods",
".",
"search",
",",
"$elem",
")",
")",
";",
"container",
".",
"on",
"(",
"\"click\"",
",",
"\".bselect-option\"",
",",
"$",
".",
"proxy",
"(",
"methods",
".",
"select",
",",
"$elem",
")",
")",
";",
"container",
".",
"on",
"(",
"\"click\"",
",",
"\".bselect-caret, .bselect-label\"",
",",
"$",
".",
"proxy",
"(",
"methods",
".",
"toggle",
",",
"$elem",
")",
")",
";",
"container",
".",
"on",
"(",
"\"keydown\"",
",",
"\".bselect-option, .bselect-search-input\"",
",",
"handleKeypress",
")",
";",
"// Issue #6 - Listen to the change event and update the selected value\r",
"$elem",
".",
"bind",
"(",
"\"change.bselect\"",
",",
"function",
"(",
")",
"{",
"var",
"data",
"=",
"$elem",
".",
"data",
"(",
"dataName",
")",
";",
"var",
"index",
"=",
"data",
".",
"itemsMap",
"[",
"this",
".",
"value",
"]",
";",
"if",
"(",
"data",
".",
"tempDisable",
")",
"{",
"data",
".",
"tempDisable",
"=",
"false",
";",
"return",
";",
"}",
"_callMethod",
"(",
"$elem",
",",
"\"select\"",
",",
"index",
")",
";",
"}",
")",
".",
"trigger",
"(",
"\"change.bselect\"",
")",
";",
"}"
] | Run all the setup stuff | [
"Run",
"all",
"the",
"setup",
"stuff"
] | 8ee485e3ef24e9498f9e32aac4a424a864a1eb99 | https://github.com/gustavohenke/bselect/blob/8ee485e3ef24e9498f9e32aac4a424a864a1eb99/src/bselect.js#L438-L526 |
23,269 | hex7c0/mongodb-restore | index.js | someCollections | function someCollections(db, collections, next) {
var last = ~~collections.length, counter = 0;
if (last === 0) { // empty set
return next(null);
}
collections.forEach(function(collection) {
db.collection(collection, function(err, collection) {
logger('select collection ' + collection.collectionName);
if (err) {
return last === ++counter ? next(err) : error(err);
}
collection.drop(function(err) {
if (err) {
error(err); // log if missing
}
return last === ++counter ? next(null) : null;
});
});
});
} | javascript | function someCollections(db, collections, next) {
var last = ~~collections.length, counter = 0;
if (last === 0) { // empty set
return next(null);
}
collections.forEach(function(collection) {
db.collection(collection, function(err, collection) {
logger('select collection ' + collection.collectionName);
if (err) {
return last === ++counter ? next(err) : error(err);
}
collection.drop(function(err) {
if (err) {
error(err); // log if missing
}
return last === ++counter ? next(null) : null;
});
});
});
} | [
"function",
"someCollections",
"(",
"db",
",",
"collections",
",",
"next",
")",
"{",
"var",
"last",
"=",
"~",
"~",
"collections",
".",
"length",
",",
"counter",
"=",
"0",
";",
"if",
"(",
"last",
"===",
"0",
")",
"{",
"// empty set",
"return",
"next",
"(",
"null",
")",
";",
"}",
"collections",
".",
"forEach",
"(",
"function",
"(",
"collection",
")",
"{",
"db",
".",
"collection",
"(",
"collection",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"logger",
"(",
"'select collection '",
"+",
"collection",
".",
"collectionName",
")",
";",
"if",
"(",
"err",
")",
"{",
"return",
"last",
"===",
"++",
"counter",
"?",
"next",
"(",
"err",
")",
":",
"error",
"(",
"err",
")",
";",
"}",
"collection",
".",
"drop",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"error",
"(",
"err",
")",
";",
"// log if missing",
"}",
"return",
"last",
"===",
"++",
"counter",
"?",
"next",
"(",
"null",
")",
":",
"null",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | drop data from some collections
@function someCollections
@param {Object} db - database
@param {Array} collections - selected collections
@param {Function} next - callback | [
"drop",
"data",
"from",
"some",
"collections"
] | f67183bd8fcff89ce9bf2ccc79ab8691488d7667 | https://github.com/hex7c0/mongodb-restore/blob/f67183bd8fcff89ce9bf2ccc79ab8691488d7667/index.js#L304-L328 |
23,270 | prescottprue/firebase-ci | src/actions/mapEnv.js | strFromEnvironmentVarSetting | function strFromEnvironmentVarSetting(functionsVar, envVar) {
if (!process.env[envVar]) {
const msg = `${envVar} does not exist on within environment variables`
warn(msg)
return ''
}
return `${functionsVar}="${process.env[envVar]}"`
} | javascript | function strFromEnvironmentVarSetting(functionsVar, envVar) {
if (!process.env[envVar]) {
const msg = `${envVar} does not exist on within environment variables`
warn(msg)
return ''
}
return `${functionsVar}="${process.env[envVar]}"`
} | [
"function",
"strFromEnvironmentVarSetting",
"(",
"functionsVar",
",",
"envVar",
")",
"{",
"if",
"(",
"!",
"process",
".",
"env",
"[",
"envVar",
"]",
")",
"{",
"const",
"msg",
"=",
"`",
"${",
"envVar",
"}",
"`",
"warn",
"(",
"msg",
")",
"return",
"''",
"}",
"return",
"`",
"${",
"functionsVar",
"}",
"${",
"process",
".",
"env",
"[",
"envVar",
"]",
"}",
"`",
"}"
] | Build a string from mapEnv setting
@param {String} functionsVar - Name of variable within functions
@param {String} envVar - Variable within environment | [
"Build",
"a",
"string",
"from",
"mapEnv",
"setting"
] | e447765549678b6f72acd58b179d629a0cfa0b58 | https://github.com/prescottprue/firebase-ci/blob/e447765549678b6f72acd58b179d629a0cfa0b58/src/actions/mapEnv.js#L16-L23 |
23,271 | prescottprue/firebase-ci | src/actions/mapEnv.js | createConfigSetString | function createConfigSetString(mapEnvSettings) {
const settingsStrsArr = map(mapEnvSettings, strFromEnvironmentVarSetting)
const settingsStr = compact(settingsStrsArr).join(' ')
// Get project from passed options, falling back to branch name
const projectKey = getProjectKey(mapEnvSettings)
return `firebase functions:config:set ${settingsStr} -P ${projectKey}`
} | javascript | function createConfigSetString(mapEnvSettings) {
const settingsStrsArr = map(mapEnvSettings, strFromEnvironmentVarSetting)
const settingsStr = compact(settingsStrsArr).join(' ')
// Get project from passed options, falling back to branch name
const projectKey = getProjectKey(mapEnvSettings)
return `firebase functions:config:set ${settingsStr} -P ${projectKey}`
} | [
"function",
"createConfigSetString",
"(",
"mapEnvSettings",
")",
"{",
"const",
"settingsStrsArr",
"=",
"map",
"(",
"mapEnvSettings",
",",
"strFromEnvironmentVarSetting",
")",
"const",
"settingsStr",
"=",
"compact",
"(",
"settingsStrsArr",
")",
".",
"join",
"(",
"' '",
")",
"// Get project from passed options, falling back to branch name",
"const",
"projectKey",
"=",
"getProjectKey",
"(",
"mapEnvSettings",
")",
"return",
"`",
"${",
"settingsStr",
"}",
"${",
"projectKey",
"}",
"`",
"}"
] | Combine all functions config sets from mapEnv settings in
.firebaserc to a single functions config set command string.
@param {Object} mapEnvSettings - Settings for mapping environment | [
"Combine",
"all",
"functions",
"config",
"sets",
"from",
"mapEnv",
"settings",
"in",
".",
"firebaserc",
"to",
"a",
"single",
"functions",
"config",
"set",
"command",
"string",
"."
] | e447765549678b6f72acd58b179d629a0cfa0b58 | https://github.com/prescottprue/firebase-ci/blob/e447765549678b6f72acd58b179d629a0cfa0b58/src/actions/mapEnv.js#L30-L36 |
23,272 | philbooth/complexity-report | src/index.js | mergeResults | function mergeResults(jsRes, coffeeRes) {
if (!coffeeRes) {
return jsRes;
}
jsRes.reports = jsRes.reports.concat(coffeeRes.reports);
return escomplex.processResults(jsRes, cli.nocoresize || false);
} | javascript | function mergeResults(jsRes, coffeeRes) {
if (!coffeeRes) {
return jsRes;
}
jsRes.reports = jsRes.reports.concat(coffeeRes.reports);
return escomplex.processResults(jsRes, cli.nocoresize || false);
} | [
"function",
"mergeResults",
"(",
"jsRes",
",",
"coffeeRes",
")",
"{",
"if",
"(",
"!",
"coffeeRes",
")",
"{",
"return",
"jsRes",
";",
"}",
"jsRes",
".",
"reports",
"=",
"jsRes",
".",
"reports",
".",
"concat",
"(",
"coffeeRes",
".",
"reports",
")",
";",
"return",
"escomplex",
".",
"processResults",
"(",
"jsRes",
",",
"cli",
".",
"nocoresize",
"||",
"false",
")",
";",
"}"
] | merge the array of reports together and rerun through the code to compute aggregates | [
"merge",
"the",
"array",
"of",
"reports",
"together",
"and",
"rerun",
"through",
"the",
"code",
"to",
"compute",
"aggregates"
] | 5cbedd6138bbce74c0b87d4293fbb077e7c9dc2b | https://github.com/philbooth/complexity-report/blob/5cbedd6138bbce74c0b87d4293fbb077e7c9dc2b/src/index.js#L271-L279 |
23,273 | thrackle/express-zip | lib/express-zip.js | function(file, cb) {
zip.entry(fs.createReadStream(file.path), { name: file.name }, cb);
} | javascript | function(file, cb) {
zip.entry(fs.createReadStream(file.path), { name: file.name }, cb);
} | [
"function",
"(",
"file",
",",
"cb",
")",
"{",
"zip",
".",
"entry",
"(",
"fs",
".",
"createReadStream",
"(",
"file",
".",
"path",
")",
",",
"{",
"name",
":",
"file",
".",
"name",
"}",
",",
"cb",
")",
";",
"}"
] | res is a writable stream | [
"res",
"is",
"a",
"writable",
"stream"
] | 07ca4acce0835e164d202fdd474ca85914ce8b70 | https://github.com/thrackle/express-zip/blob/07ca4acce0835e164d202fdd474ca85914ce8b70/lib/express-zip.js#L54-L56 | |
23,274 | request/aws-sign | index.js | hmacSha1 | function hmacSha1 (options) {
return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
} | javascript | function hmacSha1 (options) {
return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
} | [
"function",
"hmacSha1",
"(",
"options",
")",
"{",
"return",
"crypto",
".",
"createHmac",
"(",
"'sha1'",
",",
"options",
".",
"secret",
")",
".",
"update",
"(",
"options",
".",
"message",
")",
".",
"digest",
"(",
"'base64'",
")",
"}"
] | Simple HMAC-SHA1 Wrapper
@param {Object} options
@return {String}
@api private | [
"Simple",
"HMAC",
"-",
"SHA1",
"Wrapper"
] | 7a31c117c9a6e03e44b73895c170b7af14d21c38 | https://github.com/request/aws-sign/blob/7a31c117c9a6e03e44b73895c170b7af14d21c38/index.js#L71-L73 |
23,275 | jonathantneal/posthtml-inline-assets | .tape.js | readFile | function readFile(file) {
return new Promise(
(resolve, reject) => {
fs.readFile(
file, 'utf8', (error, contents) => {
if (error) {
reject(error);
} else {
// console.log('readFile', [file, contents]);
resolve(contents);
}
}
)
}
);
} | javascript | function readFile(file) {
return new Promise(
(resolve, reject) => {
fs.readFile(
file, 'utf8', (error, contents) => {
if (error) {
reject(error);
} else {
// console.log('readFile', [file, contents]);
resolve(contents);
}
}
)
}
);
} | [
"function",
"readFile",
"(",
"file",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"readFile",
"(",
"file",
",",
"'utf8'",
",",
"(",
"error",
",",
"contents",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"// console.log('readFile', [file, contents]);",
"resolve",
"(",
"contents",
")",
";",
"}",
"}",
")",
"}",
")",
";",
"}"
] | promises the contents of a file | [
"promises",
"the",
"contents",
"of",
"a",
"file"
] | dc29fb59327dbdc90f72904518d3258410d54776 | https://github.com/jonathantneal/posthtml-inline-assets/blob/dc29fb59327dbdc90f72904518d3258410d54776/.tape.js#L212-L227 |
23,276 | jonathantneal/posthtml-inline-assets | .tape.js | writeFile | function writeFile(file, contents) {
return new Promise(
(resolve, reject) => {
fs.writeFile(
file, contents, error => {
if (error) {
reject(error);
} else {
// console.log('writeFile', [file, contents]);
resolve(contents);
}
}
)
}
);
} | javascript | function writeFile(file, contents) {
return new Promise(
(resolve, reject) => {
fs.writeFile(
file, contents, error => {
if (error) {
reject(error);
} else {
// console.log('writeFile', [file, contents]);
resolve(contents);
}
}
)
}
);
} | [
"function",
"writeFile",
"(",
"file",
",",
"contents",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"writeFile",
"(",
"file",
",",
"contents",
",",
"error",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"// console.log('writeFile', [file, contents]);",
"resolve",
"(",
"contents",
")",
";",
"}",
"}",
")",
"}",
")",
";",
"}"
] | promises contents written to a file | [
"promises",
"contents",
"written",
"to",
"a",
"file"
] | dc29fb59327dbdc90f72904518d3258410d54776 | https://github.com/jonathantneal/posthtml-inline-assets/blob/dc29fb59327dbdc90f72904518d3258410d54776/.tape.js#L230-L245 |
23,277 | jonschlinkert/write | index.js | writeFile | function writeFile(filepath, data, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof cb !== 'function') {
return writeFile.promise.apply(null, arguments);
}
if (typeof filepath !== 'string') {
cb(new TypeError('expected filepath to be a string'));
return;
}
mkdirp(path.dirname(filepath), options, function(err) {
if (err) {
cb(err);
return;
}
var preparedData = data;
if (options && options.ensureNewLine && data.slice(-1) !== "\n") {
preparedData += "\n";
}
fs.writeFile(filepath, preparedData, options, cb);
});
} | javascript | function writeFile(filepath, data, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof cb !== 'function') {
return writeFile.promise.apply(null, arguments);
}
if (typeof filepath !== 'string') {
cb(new TypeError('expected filepath to be a string'));
return;
}
mkdirp(path.dirname(filepath), options, function(err) {
if (err) {
cb(err);
return;
}
var preparedData = data;
if (options && options.ensureNewLine && data.slice(-1) !== "\n") {
preparedData += "\n";
}
fs.writeFile(filepath, preparedData, options, cb);
});
} | [
"function",
"writeFile",
"(",
"filepath",
",",
"data",
",",
"options",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"cb",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"{",
"return",
"writeFile",
".",
"promise",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"}",
"if",
"(",
"typeof",
"filepath",
"!==",
"'string'",
")",
"{",
"cb",
"(",
"new",
"TypeError",
"(",
"'expected filepath to be a string'",
")",
")",
";",
"return",
";",
"}",
"mkdirp",
"(",
"path",
".",
"dirname",
"(",
"filepath",
")",
",",
"options",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"return",
";",
"}",
"var",
"preparedData",
"=",
"data",
";",
"if",
"(",
"options",
"&&",
"options",
".",
"ensureNewLine",
"&&",
"data",
".",
"slice",
"(",
"-",
"1",
")",
"!==",
"\"\\n\"",
")",
"{",
"preparedData",
"+=",
"\"\\n\"",
";",
"}",
"fs",
".",
"writeFile",
"(",
"filepath",
",",
"preparedData",
",",
"options",
",",
"cb",
")",
";",
"}",
")",
";",
"}"
] | Asynchronously writes data to a file, replacing the file if it already
exists and creating any intermediate directories if they don't already
exist. Data can be a string or a buffer. Returns a promise if a callback
function is not passed.
```js
var writeFile = require('write');
writeFile('foo.txt', 'This is content...', function(err) {
if (err) console.log(err);
});
// promise
writeFile('foo.txt', 'This is content...')
.then(function() {
// do stuff
});
```
@name writeFile
@param {string|Buffer|integer} `filepath` filepath or file descriptor.
@param {string|Buffer|Uint8Array} `data` String to write to disk.
@param {object} `options` Options to pass to [fs.writeFile][fs]{#fs_fs_writefile_file_data_options_callback} and/or [mkdirp][]
@param {Function} `callback` (optional) If no callback is provided, a promise is returned.
@api public | [
"Asynchronously",
"writes",
"data",
"to",
"a",
"file",
"replacing",
"the",
"file",
"if",
"it",
"already",
"exists",
"and",
"creating",
"any",
"intermediate",
"directories",
"if",
"they",
"don",
"t",
"already",
"exist",
".",
"Data",
"can",
"be",
"a",
"string",
"or",
"a",
"buffer",
".",
"Returns",
"a",
"promise",
"if",
"a",
"callback",
"function",
"is",
"not",
"passed",
"."
] | 12fc942ba6cea79989f1cd08dd1516e271e0e89a | https://github.com/jonschlinkert/write/blob/12fc942ba6cea79989f1cd08dd1516e271e0e89a/index.js#L40-L68 |
23,278 | sabertooth-io/web-bluetooth | lib/errorHandler.js | errorHandler | function errorHandler(errorKey, nativeError, alternate) {
const errorMessages = {
add_characteristic_exists_error: `Characteristic ${alternate} already exists.`,
characteristic_error: `Characteristic ${alternate} not found. Add ${alternate} to device using addCharacteristic or try another characteristic.`,
connect_gatt: `Could not connect to GATT. Device might be out of range. Also check to see if filters are vaild.`,
connect_server: `Could not connect to server on device.`,
connect_service: `Could not find service.`,
disconnect_timeout: `Timed out. Could not disconnect.`,
disconnect_error: `Could not disconnect from device.`,
improper_characteristic_format: `${alternate} is not a properly formatted characteristic.`,
improper_properties_format: `${alternate} is not a properly formatted properties array.`,
improper_service_format: `${alternate} is not a properly formatted service.`,
issue_disconnecting: `Issue disconnecting with device.`,
new_characteristic_missing_params: `${alternate} is not a fully supported characteristic. Please provide an associated primary service and at least one property.`,
no_device: `No instance of device found.`,
no_filters: `No filters found on instance of Device. For more information, please visit http://sabertooth.io/#method-newdevice`,
no_read_property: `No read property on characteristic: ${alternate}.`,
no_write_property: `No write property on this characteristic.`,
not_connected: `Could not disconnect. Device not connected.`,
parsing_not_supported: `Parsing not supported for characterstic: ${alternate}.`,
read_error: `Cannot read value on the characteristic.`,
_returnCharacteristic_error: `Error accessing characteristic ${alternate}.`,
start_notifications_error: `Not able to read stream of data from characteristic: ${alternate}.`,
start_notifications_no_notify: `No notify property found on this characteristic: ${alternate}.`,
stop_notifications_not_notifying: `Notifications not established for characteristic: ${alternate} or you have not started notifications.`,
stop_notifications_error: `Issue stopping notifications for characteristic: ${alternate} or you have not started notifications.`,
user_cancelled: `User cancelled the permission request.`,
uuid_error: `Invalid UUID. For more information on proper formatting of UUIDs, visit https://webbluetoothcg.github.io/web-bluetooth/#uuids`,
write_error: `Could not change value of characteristic: ${alternate}.`,
write_permissions: `${alternate} characteristic does not have a write property.`
}
throw new Error(errorMessages[errorKey]);
return false;
} | javascript | function errorHandler(errorKey, nativeError, alternate) {
const errorMessages = {
add_characteristic_exists_error: `Characteristic ${alternate} already exists.`,
characteristic_error: `Characteristic ${alternate} not found. Add ${alternate} to device using addCharacteristic or try another characteristic.`,
connect_gatt: `Could not connect to GATT. Device might be out of range. Also check to see if filters are vaild.`,
connect_server: `Could not connect to server on device.`,
connect_service: `Could not find service.`,
disconnect_timeout: `Timed out. Could not disconnect.`,
disconnect_error: `Could not disconnect from device.`,
improper_characteristic_format: `${alternate} is not a properly formatted characteristic.`,
improper_properties_format: `${alternate} is not a properly formatted properties array.`,
improper_service_format: `${alternate} is not a properly formatted service.`,
issue_disconnecting: `Issue disconnecting with device.`,
new_characteristic_missing_params: `${alternate} is not a fully supported characteristic. Please provide an associated primary service and at least one property.`,
no_device: `No instance of device found.`,
no_filters: `No filters found on instance of Device. For more information, please visit http://sabertooth.io/#method-newdevice`,
no_read_property: `No read property on characteristic: ${alternate}.`,
no_write_property: `No write property on this characteristic.`,
not_connected: `Could not disconnect. Device not connected.`,
parsing_not_supported: `Parsing not supported for characterstic: ${alternate}.`,
read_error: `Cannot read value on the characteristic.`,
_returnCharacteristic_error: `Error accessing characteristic ${alternate}.`,
start_notifications_error: `Not able to read stream of data from characteristic: ${alternate}.`,
start_notifications_no_notify: `No notify property found on this characteristic: ${alternate}.`,
stop_notifications_not_notifying: `Notifications not established for characteristic: ${alternate} or you have not started notifications.`,
stop_notifications_error: `Issue stopping notifications for characteristic: ${alternate} or you have not started notifications.`,
user_cancelled: `User cancelled the permission request.`,
uuid_error: `Invalid UUID. For more information on proper formatting of UUIDs, visit https://webbluetoothcg.github.io/web-bluetooth/#uuids`,
write_error: `Could not change value of characteristic: ${alternate}.`,
write_permissions: `${alternate} characteristic does not have a write property.`
}
throw new Error(errorMessages[errorKey]);
return false;
} | [
"function",
"errorHandler",
"(",
"errorKey",
",",
"nativeError",
",",
"alternate",
")",
"{",
"const",
"errorMessages",
"=",
"{",
"add_characteristic_exists_error",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"characteristic_error",
":",
"`",
"${",
"alternate",
"}",
"${",
"alternate",
"}",
"`",
",",
"connect_gatt",
":",
"`",
"`",
",",
"connect_server",
":",
"`",
"`",
",",
"connect_service",
":",
"`",
"`",
",",
"disconnect_timeout",
":",
"`",
"`",
",",
"disconnect_error",
":",
"`",
"`",
",",
"improper_characteristic_format",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"improper_properties_format",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"improper_service_format",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"issue_disconnecting",
":",
"`",
"`",
",",
"new_characteristic_missing_params",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"no_device",
":",
"`",
"`",
",",
"no_filters",
":",
"`",
"`",
",",
"no_read_property",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"no_write_property",
":",
"`",
"`",
",",
"not_connected",
":",
"`",
"`",
",",
"parsing_not_supported",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"read_error",
":",
"`",
"`",
",",
"_returnCharacteristic_error",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"start_notifications_error",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"start_notifications_no_notify",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"stop_notifications_not_notifying",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"stop_notifications_error",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"user_cancelled",
":",
"`",
"`",
",",
"uuid_error",
":",
"`",
"`",
",",
"write_error",
":",
"`",
"${",
"alternate",
"}",
"`",
",",
"write_permissions",
":",
"`",
"${",
"alternate",
"}",
"`",
"}",
"throw",
"new",
"Error",
"(",
"errorMessages",
"[",
"errorKey",
"]",
")",
";",
"return",
"false",
";",
"}"
] | errorHandler - Consolodates error message configuration and logic
@param {string} errorKey - maps to a detailed error message
@param {object} nativeError - the native API error object, if present
@param {} alternate - | [
"errorHandler",
"-",
"Consolodates",
"error",
"message",
"configuration",
"and",
"logic"
] | ab1ec47fdd13dc992a9093d12443a258b47718db | https://github.com/sabertooth-io/web-bluetooth/blob/ab1ec47fdd13dc992a9093d12443a258b47718db/lib/errorHandler.js#L8-L43 |
23,279 | webdeveloperpr/draft-js-custom-styles | build/index.js | styleFn | function styleFn(prefix, cssProp) {
return function (style) {
if (!style.size) {
return {};
}
var value = style.filter(function (val) {
return val.startsWith(prefix);
}).first();
if (value) {
var newVal = value.replace(prefix, '');
return _defineProperty({}, (0, _lodash2.default)(cssProp), newVal);
}
return {};
};
} | javascript | function styleFn(prefix, cssProp) {
return function (style) {
if (!style.size) {
return {};
}
var value = style.filter(function (val) {
return val.startsWith(prefix);
}).first();
if (value) {
var newVal = value.replace(prefix, '');
return _defineProperty({}, (0, _lodash2.default)(cssProp), newVal);
}
return {};
};
} | [
"function",
"styleFn",
"(",
"prefix",
",",
"cssProp",
")",
"{",
"return",
"function",
"(",
"style",
")",
"{",
"if",
"(",
"!",
"style",
".",
"size",
")",
"{",
"return",
"{",
"}",
";",
"}",
"var",
"value",
"=",
"style",
".",
"filter",
"(",
"function",
"(",
"val",
")",
"{",
"return",
"val",
".",
"startsWith",
"(",
"prefix",
")",
";",
"}",
")",
".",
"first",
"(",
")",
";",
"if",
"(",
"value",
")",
"{",
"var",
"newVal",
"=",
"value",
".",
"replace",
"(",
"prefix",
",",
"''",
")",
";",
"return",
"_defineProperty",
"(",
"{",
"}",
",",
"(",
"0",
",",
"_lodash2",
".",
"default",
")",
"(",
"cssProp",
")",
",",
"newVal",
")",
";",
"}",
"return",
"{",
"}",
";",
"}",
";",
"}"
] | style is an OrderedSet type | [
"style",
"is",
"an",
"OrderedSet",
"type"
] | f3e6b533905de8eee6da54f9727b5e5803d53fc4 | https://github.com/webdeveloperpr/draft-js-custom-styles/blob/f3e6b533905de8eee6da54f9727b5e5803d53fc4/build/index.js#L167-L181 |
23,280 | Robinyo/ionic-angular-schematics | src/utility/find-module.js | findModuleFromOptions | function findModuleFromOptions(host, options) {
if (options.hasOwnProperty('skipImport') && options.skipImport) {
return undefined;
}
if (!options.module) {
const pathToCheck = (options.sourceDir || '') + '/' + (options.path || '')
+ (options.flat ? '' : '/' + strings_1.dasherize(options.name));
return core_1.normalize(findModule(host, pathToCheck));
}
else {
const modulePath = core_1.normalize('/' + options.sourceDir + '/' + (options.appRoot || options.path) + '/' + options.module);
const moduleBaseName = core_1.normalize(modulePath).split('/').pop();
if (host.exists(modulePath)) {
return core_1.normalize(modulePath);
}
else if (host.exists(modulePath + '.ts')) {
return core_1.normalize(modulePath + '.ts');
}
else if (host.exists(modulePath + '.module.ts')) {
return core_1.normalize(modulePath + '.module.ts');
}
else if (host.exists(modulePath + '/' + moduleBaseName + '.module.ts')) {
return core_1.normalize(modulePath + '/' + moduleBaseName + '.module.ts');
}
else {
throw new Error('Specified module does not exist');
}
}
} | javascript | function findModuleFromOptions(host, options) {
if (options.hasOwnProperty('skipImport') && options.skipImport) {
return undefined;
}
if (!options.module) {
const pathToCheck = (options.sourceDir || '') + '/' + (options.path || '')
+ (options.flat ? '' : '/' + strings_1.dasherize(options.name));
return core_1.normalize(findModule(host, pathToCheck));
}
else {
const modulePath = core_1.normalize('/' + options.sourceDir + '/' + (options.appRoot || options.path) + '/' + options.module);
const moduleBaseName = core_1.normalize(modulePath).split('/').pop();
if (host.exists(modulePath)) {
return core_1.normalize(modulePath);
}
else if (host.exists(modulePath + '.ts')) {
return core_1.normalize(modulePath + '.ts');
}
else if (host.exists(modulePath + '.module.ts')) {
return core_1.normalize(modulePath + '.module.ts');
}
else if (host.exists(modulePath + '/' + moduleBaseName + '.module.ts')) {
return core_1.normalize(modulePath + '/' + moduleBaseName + '.module.ts');
}
else {
throw new Error('Specified module does not exist');
}
}
} | [
"function",
"findModuleFromOptions",
"(",
"host",
",",
"options",
")",
"{",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'skipImport'",
")",
"&&",
"options",
".",
"skipImport",
")",
"{",
"return",
"undefined",
";",
"}",
"if",
"(",
"!",
"options",
".",
"module",
")",
"{",
"const",
"pathToCheck",
"=",
"(",
"options",
".",
"sourceDir",
"||",
"''",
")",
"+",
"'/'",
"+",
"(",
"options",
".",
"path",
"||",
"''",
")",
"+",
"(",
"options",
".",
"flat",
"?",
"''",
":",
"'/'",
"+",
"strings_1",
".",
"dasherize",
"(",
"options",
".",
"name",
")",
")",
";",
"return",
"core_1",
".",
"normalize",
"(",
"findModule",
"(",
"host",
",",
"pathToCheck",
")",
")",
";",
"}",
"else",
"{",
"const",
"modulePath",
"=",
"core_1",
".",
"normalize",
"(",
"'/'",
"+",
"options",
".",
"sourceDir",
"+",
"'/'",
"+",
"(",
"options",
".",
"appRoot",
"||",
"options",
".",
"path",
")",
"+",
"'/'",
"+",
"options",
".",
"module",
")",
";",
"const",
"moduleBaseName",
"=",
"core_1",
".",
"normalize",
"(",
"modulePath",
")",
".",
"split",
"(",
"'/'",
")",
".",
"pop",
"(",
")",
";",
"if",
"(",
"host",
".",
"exists",
"(",
"modulePath",
")",
")",
"{",
"return",
"core_1",
".",
"normalize",
"(",
"modulePath",
")",
";",
"}",
"else",
"if",
"(",
"host",
".",
"exists",
"(",
"modulePath",
"+",
"'.ts'",
")",
")",
"{",
"return",
"core_1",
".",
"normalize",
"(",
"modulePath",
"+",
"'.ts'",
")",
";",
"}",
"else",
"if",
"(",
"host",
".",
"exists",
"(",
"modulePath",
"+",
"'.module.ts'",
")",
")",
"{",
"return",
"core_1",
".",
"normalize",
"(",
"modulePath",
"+",
"'.module.ts'",
")",
";",
"}",
"else",
"if",
"(",
"host",
".",
"exists",
"(",
"modulePath",
"+",
"'/'",
"+",
"moduleBaseName",
"+",
"'.module.ts'",
")",
")",
"{",
"return",
"core_1",
".",
"normalize",
"(",
"modulePath",
"+",
"'/'",
"+",
"moduleBaseName",
"+",
"'.module.ts'",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Specified module does not exist'",
")",
";",
"}",
"}",
"}"
] | Find the module referred by a set of options passed to the schematics. | [
"Find",
"the",
"module",
"referred",
"by",
"a",
"set",
"of",
"options",
"passed",
"to",
"the",
"schematics",
"."
] | 2f8fdcf5c95713516212d8cbd4a30f64e96fae7a | https://github.com/Robinyo/ionic-angular-schematics/blob/2f8fdcf5c95713516212d8cbd4a30f64e96fae7a/src/utility/find-module.js#L15-L43 |
23,281 | Robinyo/ionic-angular-schematics | src/utility/find-module.js | findModule | function findModule(host, generateDir) {
let dir = host.getDir('/' + generateDir);
const moduleRe = /\.module\.ts$/;
const routingModuleRe = /-routing\.module\.ts/;
while (dir) {
const matches = dir.subfiles.filter(p => moduleRe.test(p) && !routingModuleRe.test(p));
if (matches.length == 1) {
return core_1.join(dir.path, matches[0]);
}
else if (matches.length > 1) {
throw new Error('More than one module matches. Use skip-import option to skip importing '
+ 'the component into the closest module.');
}
dir = dir.parent;
}
throw new Error('Could not find an NgModule for the new component. Use the skip-import '
+ 'option to skip importing components in NgModule.');
} | javascript | function findModule(host, generateDir) {
let dir = host.getDir('/' + generateDir);
const moduleRe = /\.module\.ts$/;
const routingModuleRe = /-routing\.module\.ts/;
while (dir) {
const matches = dir.subfiles.filter(p => moduleRe.test(p) && !routingModuleRe.test(p));
if (matches.length == 1) {
return core_1.join(dir.path, matches[0]);
}
else if (matches.length > 1) {
throw new Error('More than one module matches. Use skip-import option to skip importing '
+ 'the component into the closest module.');
}
dir = dir.parent;
}
throw new Error('Could not find an NgModule for the new component. Use the skip-import '
+ 'option to skip importing components in NgModule.');
} | [
"function",
"findModule",
"(",
"host",
",",
"generateDir",
")",
"{",
"let",
"dir",
"=",
"host",
".",
"getDir",
"(",
"'/'",
"+",
"generateDir",
")",
";",
"const",
"moduleRe",
"=",
"/",
"\\.module\\.ts$",
"/",
";",
"const",
"routingModuleRe",
"=",
"/",
"-routing\\.module\\.ts",
"/",
";",
"while",
"(",
"dir",
")",
"{",
"const",
"matches",
"=",
"dir",
".",
"subfiles",
".",
"filter",
"(",
"p",
"=>",
"moduleRe",
".",
"test",
"(",
"p",
")",
"&&",
"!",
"routingModuleRe",
".",
"test",
"(",
"p",
")",
")",
";",
"if",
"(",
"matches",
".",
"length",
"==",
"1",
")",
"{",
"return",
"core_1",
".",
"join",
"(",
"dir",
".",
"path",
",",
"matches",
"[",
"0",
"]",
")",
";",
"}",
"else",
"if",
"(",
"matches",
".",
"length",
">",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'More than one module matches. Use skip-import option to skip importing '",
"+",
"'the component into the closest module.'",
")",
";",
"}",
"dir",
"=",
"dir",
".",
"parent",
";",
"}",
"throw",
"new",
"Error",
"(",
"'Could not find an NgModule for the new component. Use the skip-import '",
"+",
"'option to skip importing components in NgModule.'",
")",
";",
"}"
] | Function to find the "closest" module to a generated file's path. | [
"Function",
"to",
"find",
"the",
"closest",
"module",
"to",
"a",
"generated",
"file",
"s",
"path",
"."
] | 2f8fdcf5c95713516212d8cbd4a30f64e96fae7a | https://github.com/Robinyo/ionic-angular-schematics/blob/2f8fdcf5c95713516212d8cbd4a30f64e96fae7a/src/utility/find-module.js#L48-L65 |
23,282 | Robinyo/ionic-angular-schematics | src/utility/find-module.js | buildRelativePath | function buildRelativePath(from, to) {
from = core_1.normalize(from);
to = core_1.normalize(to);
// Convert to arrays.
const fromParts = from.split('/');
const toParts = to.split('/');
// Remove file names (preserving destination)
fromParts.pop();
const toFileName = toParts.pop();
const relativePath = core_1.relative(core_1.normalize(fromParts.join('/')), core_1.normalize(toParts.join('/')));
let pathPrefix = '';
// Set the path prefix for same dir or child dir, parent dir starts with `..`
if (!relativePath) {
pathPrefix = '.';
}
else if (!relativePath.startsWith('.')) {
pathPrefix = `./`;
}
if (pathPrefix && !pathPrefix.endsWith('/')) {
pathPrefix += '/';
}
return pathPrefix + (relativePath ? relativePath + '/' : '') + toFileName;
} | javascript | function buildRelativePath(from, to) {
from = core_1.normalize(from);
to = core_1.normalize(to);
// Convert to arrays.
const fromParts = from.split('/');
const toParts = to.split('/');
// Remove file names (preserving destination)
fromParts.pop();
const toFileName = toParts.pop();
const relativePath = core_1.relative(core_1.normalize(fromParts.join('/')), core_1.normalize(toParts.join('/')));
let pathPrefix = '';
// Set the path prefix for same dir or child dir, parent dir starts with `..`
if (!relativePath) {
pathPrefix = '.';
}
else if (!relativePath.startsWith('.')) {
pathPrefix = `./`;
}
if (pathPrefix && !pathPrefix.endsWith('/')) {
pathPrefix += '/';
}
return pathPrefix + (relativePath ? relativePath + '/' : '') + toFileName;
} | [
"function",
"buildRelativePath",
"(",
"from",
",",
"to",
")",
"{",
"from",
"=",
"core_1",
".",
"normalize",
"(",
"from",
")",
";",
"to",
"=",
"core_1",
".",
"normalize",
"(",
"to",
")",
";",
"// Convert to arrays.",
"const",
"fromParts",
"=",
"from",
".",
"split",
"(",
"'/'",
")",
";",
"const",
"toParts",
"=",
"to",
".",
"split",
"(",
"'/'",
")",
";",
"// Remove file names (preserving destination)",
"fromParts",
".",
"pop",
"(",
")",
";",
"const",
"toFileName",
"=",
"toParts",
".",
"pop",
"(",
")",
";",
"const",
"relativePath",
"=",
"core_1",
".",
"relative",
"(",
"core_1",
".",
"normalize",
"(",
"fromParts",
".",
"join",
"(",
"'/'",
")",
")",
",",
"core_1",
".",
"normalize",
"(",
"toParts",
".",
"join",
"(",
"'/'",
")",
")",
")",
";",
"let",
"pathPrefix",
"=",
"''",
";",
"// Set the path prefix for same dir or child dir, parent dir starts with `..`",
"if",
"(",
"!",
"relativePath",
")",
"{",
"pathPrefix",
"=",
"'.'",
";",
"}",
"else",
"if",
"(",
"!",
"relativePath",
".",
"startsWith",
"(",
"'.'",
")",
")",
"{",
"pathPrefix",
"=",
"`",
"`",
";",
"}",
"if",
"(",
"pathPrefix",
"&&",
"!",
"pathPrefix",
".",
"endsWith",
"(",
"'/'",
")",
")",
"{",
"pathPrefix",
"+=",
"'/'",
";",
"}",
"return",
"pathPrefix",
"+",
"(",
"relativePath",
"?",
"relativePath",
"+",
"'/'",
":",
"''",
")",
"+",
"toFileName",
";",
"}"
] | Build a relative path from one file path to another file path. | [
"Build",
"a",
"relative",
"path",
"from",
"one",
"file",
"path",
"to",
"another",
"file",
"path",
"."
] | 2f8fdcf5c95713516212d8cbd4a30f64e96fae7a | https://github.com/Robinyo/ionic-angular-schematics/blob/2f8fdcf5c95713516212d8cbd4a30f64e96fae7a/src/utility/find-module.js#L70-L92 |
23,283 | Niryo/controllerim | src/Observer/mobxReactClone.js | getPreciseType | function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
} | javascript | function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
} | [
"function",
"getPreciseType",
"(",
"propValue",
")",
"{",
"var",
"propType",
"=",
"getPropType",
"(",
"propValue",
")",
";",
"if",
"(",
"propType",
"===",
"'object'",
")",
"{",
"if",
"(",
"propValue",
"instanceof",
"Date",
")",
"{",
"return",
"'date'",
";",
"}",
"else",
"if",
"(",
"propValue",
"instanceof",
"RegExp",
")",
"{",
"return",
"'regexp'",
";",
"}",
"}",
"return",
"propType",
";",
"}"
] | This handles more types than `getPropType`. Only used for error messages. Copied from React.PropTypes | [
"This",
"handles",
"more",
"types",
"than",
"getPropType",
".",
"Only",
"used",
"for",
"error",
"messages",
".",
"Copied",
"from",
"React",
".",
"PropTypes"
] | 551640bb2e42279a087832006d1534603288de89 | https://github.com/Niryo/controllerim/blob/551640bb2e42279a087832006d1534603288de89/src/Observer/mobxReactClone.js#L366-L376 |
23,284 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | setCanvasSize | function setCanvasSize (width, height) {
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
} | javascript | function setCanvasSize (width, height) {
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
} | [
"function",
"setCanvasSize",
"(",
"width",
",",
"height",
")",
"{",
"canvas",
".",
"setAttribute",
"(",
"'width'",
",",
"width",
")",
";",
"canvas",
".",
"setAttribute",
"(",
"'height'",
",",
"height",
")",
";",
"canvas",
".",
"style",
".",
"width",
"=",
"width",
"+",
"'px'",
";",
"canvas",
".",
"style",
".",
"height",
"=",
"height",
"+",
"'px'",
";",
"}"
] | Set the size of canvas | [
"Set",
"the",
"size",
"of",
"canvas"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L56-L61 |
23,285 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | getPointRelativeToCanvas | function getPointRelativeToCanvas (point) {
return {
x: point.x / canvas.width,
y: point.y / canvas.height
};
} | javascript | function getPointRelativeToCanvas (point) {
return {
x: point.x / canvas.width,
y: point.y / canvas.height
};
} | [
"function",
"getPointRelativeToCanvas",
"(",
"point",
")",
"{",
"return",
"{",
"x",
":",
"point",
".",
"x",
"/",
"canvas",
".",
"width",
",",
"y",
":",
"point",
".",
"y",
"/",
"canvas",
".",
"height",
"}",
";",
"}"
] | Returns a points x,y locations relative to the size of the canvase | [
"Returns",
"a",
"points",
"x",
"y",
"locations",
"relative",
"to",
"the",
"size",
"of",
"the",
"canvase"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L80-L85 |
23,286 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | getCursorRelativeToCanvas | function getCursorRelativeToCanvas (e) {
var cur = {};
if (isTouchEvent(e)) {
cur.x = e.touches[0].pageX - canvas.offsetLeft;
cur.y = e.touches[0].pageY - canvas.offsetTop;
} else {
var rect = that.canvas.getBoundingClientRect();
cur.x = e.clientX - rect.left;
cur.y = e.clientY - rect.top;
}
return getPointRelativeToCanvas(cur);
} | javascript | function getCursorRelativeToCanvas (e) {
var cur = {};
if (isTouchEvent(e)) {
cur.x = e.touches[0].pageX - canvas.offsetLeft;
cur.y = e.touches[0].pageY - canvas.offsetTop;
} else {
var rect = that.canvas.getBoundingClientRect();
cur.x = e.clientX - rect.left;
cur.y = e.clientY - rect.top;
}
return getPointRelativeToCanvas(cur);
} | [
"function",
"getCursorRelativeToCanvas",
"(",
"e",
")",
"{",
"var",
"cur",
"=",
"{",
"}",
";",
"if",
"(",
"isTouchEvent",
"(",
"e",
")",
")",
"{",
"cur",
".",
"x",
"=",
"e",
".",
"touches",
"[",
"0",
"]",
".",
"pageX",
"-",
"canvas",
".",
"offsetLeft",
";",
"cur",
".",
"y",
"=",
"e",
".",
"touches",
"[",
"0",
"]",
".",
"pageY",
"-",
"canvas",
".",
"offsetTop",
";",
"}",
"else",
"{",
"var",
"rect",
"=",
"that",
".",
"canvas",
".",
"getBoundingClientRect",
"(",
")",
";",
"cur",
".",
"x",
"=",
"e",
".",
"clientX",
"-",
"rect",
".",
"left",
";",
"cur",
".",
"y",
"=",
"e",
".",
"clientY",
"-",
"rect",
".",
"top",
";",
"}",
"return",
"getPointRelativeToCanvas",
"(",
"cur",
")",
";",
"}"
] | Get location of the cursor in the canvas | [
"Get",
"location",
"of",
"the",
"cursor",
"in",
"the",
"canvas"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L97-L110 |
23,287 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | clearCanvas | function clearCanvas () {
context.clearRect(0, 0, canvas.width, canvas.height);
if (opts.backgroundColor) {
context.fillStyle = opts.backgroundColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
} | javascript | function clearCanvas () {
context.clearRect(0, 0, canvas.width, canvas.height);
if (opts.backgroundColor) {
context.fillStyle = opts.backgroundColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
} | [
"function",
"clearCanvas",
"(",
")",
"{",
"context",
".",
"clearRect",
"(",
"0",
",",
"0",
",",
"canvas",
".",
"width",
",",
"canvas",
".",
"height",
")",
";",
"if",
"(",
"opts",
".",
"backgroundColor",
")",
"{",
"context",
".",
"fillStyle",
"=",
"opts",
".",
"backgroundColor",
";",
"context",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"canvas",
".",
"width",
",",
"canvas",
".",
"height",
")",
";",
"}",
"}"
] | Erase everything in the canvase | [
"Erase",
"everything",
"in",
"the",
"canvase"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L123-L130 |
23,288 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | normalizePoint | function normalizePoint (point) {
return {
x: point.x * canvas.width,
y: point.y * canvas.height
};
} | javascript | function normalizePoint (point) {
return {
x: point.x * canvas.width,
y: point.y * canvas.height
};
} | [
"function",
"normalizePoint",
"(",
"point",
")",
"{",
"return",
"{",
"x",
":",
"point",
".",
"x",
"*",
"canvas",
".",
"width",
",",
"y",
":",
"point",
".",
"y",
"*",
"canvas",
".",
"height",
"}",
";",
"}"
] | Since points are stored relative to the size of the canvas
this takes a point and converts it to actual x, y distances in the canvas | [
"Since",
"points",
"are",
"stored",
"relative",
"to",
"the",
"size",
"of",
"the",
"canvas",
"this",
"takes",
"a",
"point",
"and",
"converts",
"it",
"to",
"actual",
"x",
"y",
"distances",
"in",
"the",
"canvas"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L136-L141 |
23,289 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | drawStroke | function drawStroke (stroke) {
context.beginPath();
for (var j = 0; j < stroke.points.length - 1; j++) {
var start = normalizePoint(stroke.points[j]);
var end = normalizePoint(stroke.points[j + 1]);
context.moveTo(start.x, start.y);
context.lineTo(end.x, end.y);
}
context.closePath();
context.strokeStyle = stroke.color;
context.lineWidth = normalizeLineSize(stroke.size);
context.lineJoin = stroke.join;
context.lineCap = stroke.cap;
context.miterLimit = stroke.miterLimit;
context.stroke();
} | javascript | function drawStroke (stroke) {
context.beginPath();
for (var j = 0; j < stroke.points.length - 1; j++) {
var start = normalizePoint(stroke.points[j]);
var end = normalizePoint(stroke.points[j + 1]);
context.moveTo(start.x, start.y);
context.lineTo(end.x, end.y);
}
context.closePath();
context.strokeStyle = stroke.color;
context.lineWidth = normalizeLineSize(stroke.size);
context.lineJoin = stroke.join;
context.lineCap = stroke.cap;
context.miterLimit = stroke.miterLimit;
context.stroke();
} | [
"function",
"drawStroke",
"(",
"stroke",
")",
"{",
"context",
".",
"beginPath",
"(",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"stroke",
".",
"points",
".",
"length",
"-",
"1",
";",
"j",
"++",
")",
"{",
"var",
"start",
"=",
"normalizePoint",
"(",
"stroke",
".",
"points",
"[",
"j",
"]",
")",
";",
"var",
"end",
"=",
"normalizePoint",
"(",
"stroke",
".",
"points",
"[",
"j",
"+",
"1",
"]",
")",
";",
"context",
".",
"moveTo",
"(",
"start",
".",
"x",
",",
"start",
".",
"y",
")",
";",
"context",
".",
"lineTo",
"(",
"end",
".",
"x",
",",
"end",
".",
"y",
")",
";",
"}",
"context",
".",
"closePath",
"(",
")",
";",
"context",
".",
"strokeStyle",
"=",
"stroke",
".",
"color",
";",
"context",
".",
"lineWidth",
"=",
"normalizeLineSize",
"(",
"stroke",
".",
"size",
")",
";",
"context",
".",
"lineJoin",
"=",
"stroke",
".",
"join",
";",
"context",
".",
"lineCap",
"=",
"stroke",
".",
"cap",
";",
"context",
".",
"miterLimit",
"=",
"stroke",
".",
"miterLimit",
";",
"context",
".",
"stroke",
"(",
")",
";",
"}"
] | Draw a stroke on the canvas | [
"Draw",
"a",
"stroke",
"on",
"the",
"canvas"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L155-L173 |
23,290 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | redraw | function redraw () {
clearCanvas();
for (var i = 0; i < that.strokes.length; i++) {
drawStroke(that.strokes[i]);
}
} | javascript | function redraw () {
clearCanvas();
for (var i = 0; i < that.strokes.length; i++) {
drawStroke(that.strokes[i]);
}
} | [
"function",
"redraw",
"(",
")",
"{",
"clearCanvas",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"that",
".",
"strokes",
".",
"length",
";",
"i",
"++",
")",
"{",
"drawStroke",
"(",
"that",
".",
"strokes",
"[",
"i",
"]",
")",
";",
"}",
"}"
] | Redraw the canvas | [
"Redraw",
"the",
"canvas"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L178-L184 |
23,291 | theisensanders-wf/responsive-sketchpad | responsive-sketchpad.js | startLine | function startLine (e) {
e.preventDefault();
strokes = that.strokes;
sketching = true;
that.undos = [];
var cursor = getCursorRelativeToCanvas(e);
strokes.push({
points: [cursor],
color: opts.line.color,
size: getLineSizeRelativeToCanvas(opts.line.size),
cap: opts.line.cap,
join: opts.line.join,
miterLimit: opts.line.miterLimit
});
} | javascript | function startLine (e) {
e.preventDefault();
strokes = that.strokes;
sketching = true;
that.undos = [];
var cursor = getCursorRelativeToCanvas(e);
strokes.push({
points: [cursor],
color: opts.line.color,
size: getLineSizeRelativeToCanvas(opts.line.size),
cap: opts.line.cap,
join: opts.line.join,
miterLimit: opts.line.miterLimit
});
} | [
"function",
"startLine",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"strokes",
"=",
"that",
".",
"strokes",
";",
"sketching",
"=",
"true",
";",
"that",
".",
"undos",
"=",
"[",
"]",
";",
"var",
"cursor",
"=",
"getCursorRelativeToCanvas",
"(",
"e",
")",
";",
"strokes",
".",
"push",
"(",
"{",
"points",
":",
"[",
"cursor",
"]",
",",
"color",
":",
"opts",
".",
"line",
".",
"color",
",",
"size",
":",
"getLineSizeRelativeToCanvas",
"(",
"opts",
".",
"line",
".",
"size",
")",
",",
"cap",
":",
"opts",
".",
"line",
".",
"cap",
",",
"join",
":",
"opts",
".",
"line",
".",
"join",
",",
"miterLimit",
":",
"opts",
".",
"line",
".",
"miterLimit",
"}",
")",
";",
"}"
] | On mouse down, create a new stroke with a start location | [
"On",
"mouse",
"down",
"create",
"a",
"new",
"stroke",
"with",
"a",
"start",
"location"
] | aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f | https://github.com/theisensanders-wf/responsive-sketchpad/blob/aedc4d2aa710cc75e48e0df49aeff9b49e51ad5f/responsive-sketchpad.js#L187-L203 |
23,292 | umidbekkarimov/babel-plugin-direct-import | src/resolver.js | resolveFilename | function resolveFilename(fileName, cwd = process.cwd()) {
try {
const parent = new Module();
// eslint-disable-next-line no-underscore-dangle
parent.paths = Module._nodeModulePaths(cwd);
// eslint-disable-next-line no-underscore-dangle
return Module._resolveFilename(fileName, parent);
} catch (error) {
if (error.code === "MODULE_NOT_FOUND") {
console.warn(format("babel-plugin-direct-import: %s", error.message));
return null;
}
throw error;
}
} | javascript | function resolveFilename(fileName, cwd = process.cwd()) {
try {
const parent = new Module();
// eslint-disable-next-line no-underscore-dangle
parent.paths = Module._nodeModulePaths(cwd);
// eslint-disable-next-line no-underscore-dangle
return Module._resolveFilename(fileName, parent);
} catch (error) {
if (error.code === "MODULE_NOT_FOUND") {
console.warn(format("babel-plugin-direct-import: %s", error.message));
return null;
}
throw error;
}
} | [
"function",
"resolveFilename",
"(",
"fileName",
",",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
")",
"{",
"try",
"{",
"const",
"parent",
"=",
"new",
"Module",
"(",
")",
";",
"// eslint-disable-next-line no-underscore-dangle",
"parent",
".",
"paths",
"=",
"Module",
".",
"_nodeModulePaths",
"(",
"cwd",
")",
";",
"// eslint-disable-next-line no-underscore-dangle",
"return",
"Module",
".",
"_resolveFilename",
"(",
"fileName",
",",
"parent",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"code",
"===",
"\"MODULE_NOT_FOUND\"",
")",
"{",
"console",
".",
"warn",
"(",
"format",
"(",
"\"babel-plugin-direct-import: %s\"",
",",
"error",
".",
"message",
")",
")",
";",
"return",
"null",
";",
"}",
"throw",
"error",
";",
"}",
"}"
] | Resolve module file.
@param {String} fileName
@param {String} cwd
@returns {String|null} | [
"Resolve",
"module",
"file",
"."
] | d98ac4ed5c48f572856cc2963e62dcaaf3c305bd | https://github.com/umidbekkarimov/babel-plugin-direct-import/blob/d98ac4ed5c48f572856cc2963e62dcaaf3c305bd/src/resolver.js#L13-L31 |
23,293 | alexilyaev/stylelint-find-rules | src/lib/cli.js | handleError | function handleError(err) {
let errMsg = err;
if (err instanceof Object) {
errMsg = err.message || err.error || JSON.stringify(err);
}
printColumns(chalk.red('Error: ' + errMsg));
printColumns(
chalk.white(
"If you can't settle this, please open an issue at:" + EOL + chalk.cyan(pkg.bugs.url)
)
);
process.exit(1);
} | javascript | function handleError(err) {
let errMsg = err;
if (err instanceof Object) {
errMsg = err.message || err.error || JSON.stringify(err);
}
printColumns(chalk.red('Error: ' + errMsg));
printColumns(
chalk.white(
"If you can't settle this, please open an issue at:" + EOL + chalk.cyan(pkg.bugs.url)
)
);
process.exit(1);
} | [
"function",
"handleError",
"(",
"err",
")",
"{",
"let",
"errMsg",
"=",
"err",
";",
"if",
"(",
"err",
"instanceof",
"Object",
")",
"{",
"errMsg",
"=",
"err",
".",
"message",
"||",
"err",
".",
"error",
"||",
"JSON",
".",
"stringify",
"(",
"err",
")",
";",
"}",
"printColumns",
"(",
"chalk",
".",
"red",
"(",
"'Error: '",
"+",
"errMsg",
")",
")",
";",
"printColumns",
"(",
"chalk",
".",
"white",
"(",
"\"If you can't settle this, please open an issue at:\"",
"+",
"EOL",
"+",
"chalk",
".",
"cyan",
"(",
"pkg",
".",
"bugs",
".",
"url",
")",
")",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}"
] | Handle promise rejections and errors | [
"Handle",
"promise",
"rejections",
"and",
"errors"
] | 5c23235686c56ef463fc61bf6f912e64b23acb94 | https://github.com/alexilyaev/stylelint-find-rules/blob/5c23235686c56ef463fc61bf6f912e64b23acb94/src/lib/cli.js#L83-L97 |
23,294 | alexilyaev/stylelint-find-rules | src/lib/cli.js | printColumns | function printColumns(heading, data) {
const columns = columnify(data, {});
const spacer = EOL + EOL;
process.stdout.write(heading);
process.stdout.write(spacer);
if (columns) {
process.stdout.write(columns);
process.stdout.write(spacer);
}
} | javascript | function printColumns(heading, data) {
const columns = columnify(data, {});
const spacer = EOL + EOL;
process.stdout.write(heading);
process.stdout.write(spacer);
if (columns) {
process.stdout.write(columns);
process.stdout.write(spacer);
}
} | [
"function",
"printColumns",
"(",
"heading",
",",
"data",
")",
"{",
"const",
"columns",
"=",
"columnify",
"(",
"data",
",",
"{",
"}",
")",
";",
"const",
"spacer",
"=",
"EOL",
"+",
"EOL",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"heading",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"spacer",
")",
";",
"if",
"(",
"columns",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"columns",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"spacer",
")",
";",
"}",
"}"
] | Print to stdout
@param {string} heading
@param {Array?} data | [
"Print",
"to",
"stdout"
] | 5c23235686c56ef463fc61bf6f912e64b23acb94 | https://github.com/alexilyaev/stylelint-find-rules/blob/5c23235686c56ef463fc61bf6f912e64b23acb94/src/lib/cli.js#L105-L116 |
23,295 | alexilyaev/stylelint-find-rules | src/lib/cli.js | getUserRules | function getUserRules(cosmiconfig) {
const userConfig = cosmiconfig.config;
const configPath = cosmiconfig.filepath;
return (
Promise.resolve()
// Handle `extends`
.then(() => {
// If `extends` is defined, use stylelint's extends resolver
if (!_.isEmpty(userConfig.extends)) {
// We need this to fetch and merge all `extends` from the provided config
// This will also merge the `rules` on top of the `extends` rules
const linter = stylelint.createLinter();
// stylelint used cosmiconfig v4 at version 9, bumped to v5 somewhere 9.x
// So we pass both arguments to `load`, works in both versions
return linter._extendExplorer.load(configPath, configPath);
}
})
.then(extendedConfig => {
const finalConfig = extendedConfig ? extendedConfig.config : userConfig;
rules.userRulesNames = _.sortedUniq(_.keys(finalConfig.rules));
})
);
} | javascript | function getUserRules(cosmiconfig) {
const userConfig = cosmiconfig.config;
const configPath = cosmiconfig.filepath;
return (
Promise.resolve()
// Handle `extends`
.then(() => {
// If `extends` is defined, use stylelint's extends resolver
if (!_.isEmpty(userConfig.extends)) {
// We need this to fetch and merge all `extends` from the provided config
// This will also merge the `rules` on top of the `extends` rules
const linter = stylelint.createLinter();
// stylelint used cosmiconfig v4 at version 9, bumped to v5 somewhere 9.x
// So we pass both arguments to `load`, works in both versions
return linter._extendExplorer.load(configPath, configPath);
}
})
.then(extendedConfig => {
const finalConfig = extendedConfig ? extendedConfig.config : userConfig;
rules.userRulesNames = _.sortedUniq(_.keys(finalConfig.rules));
})
);
} | [
"function",
"getUserRules",
"(",
"cosmiconfig",
")",
"{",
"const",
"userConfig",
"=",
"cosmiconfig",
".",
"config",
";",
"const",
"configPath",
"=",
"cosmiconfig",
".",
"filepath",
";",
"return",
"(",
"Promise",
".",
"resolve",
"(",
")",
"// Handle `extends`",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"// If `extends` is defined, use stylelint's extends resolver",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"userConfig",
".",
"extends",
")",
")",
"{",
"// We need this to fetch and merge all `extends` from the provided config",
"// This will also merge the `rules` on top of the `extends` rules",
"const",
"linter",
"=",
"stylelint",
".",
"createLinter",
"(",
")",
";",
"// stylelint used cosmiconfig v4 at version 9, bumped to v5 somewhere 9.x",
"// So we pass both arguments to `load`, works in both versions",
"return",
"linter",
".",
"_extendExplorer",
".",
"load",
"(",
"configPath",
",",
"configPath",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"extendedConfig",
"=>",
"{",
"const",
"finalConfig",
"=",
"extendedConfig",
"?",
"extendedConfig",
".",
"config",
":",
"userConfig",
";",
"rules",
".",
"userRulesNames",
"=",
"_",
".",
"sortedUniq",
"(",
"_",
".",
"keys",
"(",
"finalConfig",
".",
"rules",
")",
")",
";",
"}",
")",
")",
";",
"}"
] | Get user rules
Gather rules from `extends` as well | [
"Get",
"user",
"rules",
"Gather",
"rules",
"from",
"extends",
"as",
"well"
] | 5c23235686c56ef463fc61bf6f912e64b23acb94 | https://github.com/alexilyaev/stylelint-find-rules/blob/5c23235686c56ef463fc61bf6f912e64b23acb94/src/lib/cli.js#L149-L174 |
23,296 | alexilyaev/stylelint-find-rules | src/lib/cli.js | findDeprecatedStylelintRules | function findDeprecatedStylelintRules() {
if (!argv.deprecated && !argv.unused) {
return Promise.resolve();
}
const isDeprecatedPromises = _.map(rules.stylelintAll, isDDeprecated);
return Promise.all(isDeprecatedPromises).then(rulesIsDeprecated => {
rules.stylelintDeprecated = _.filter(
rules.stylelintAll,
(rule, index) => rulesIsDeprecated[index]
);
// Don't remove, just for testing deprecated rules matching
if (argv.testDeprecated) {
rules.stylelintDeprecated.push('color-hex-case', 'color-hex-length');
}
if (argv.unused) {
rules.stylelintNoDeprecated = _.difference(rules.stylelintAll, rules.stylelintDeprecated);
}
return rules.stylelintDeprecated;
});
} | javascript | function findDeprecatedStylelintRules() {
if (!argv.deprecated && !argv.unused) {
return Promise.resolve();
}
const isDeprecatedPromises = _.map(rules.stylelintAll, isDDeprecated);
return Promise.all(isDeprecatedPromises).then(rulesIsDeprecated => {
rules.stylelintDeprecated = _.filter(
rules.stylelintAll,
(rule, index) => rulesIsDeprecated[index]
);
// Don't remove, just for testing deprecated rules matching
if (argv.testDeprecated) {
rules.stylelintDeprecated.push('color-hex-case', 'color-hex-length');
}
if (argv.unused) {
rules.stylelintNoDeprecated = _.difference(rules.stylelintAll, rules.stylelintDeprecated);
}
return rules.stylelintDeprecated;
});
} | [
"function",
"findDeprecatedStylelintRules",
"(",
")",
"{",
"if",
"(",
"!",
"argv",
".",
"deprecated",
"&&",
"!",
"argv",
".",
"unused",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"const",
"isDeprecatedPromises",
"=",
"_",
".",
"map",
"(",
"rules",
".",
"stylelintAll",
",",
"isDDeprecated",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"isDeprecatedPromises",
")",
".",
"then",
"(",
"rulesIsDeprecated",
"=>",
"{",
"rules",
".",
"stylelintDeprecated",
"=",
"_",
".",
"filter",
"(",
"rules",
".",
"stylelintAll",
",",
"(",
"rule",
",",
"index",
")",
"=>",
"rulesIsDeprecated",
"[",
"index",
"]",
")",
";",
"// Don't remove, just for testing deprecated rules matching",
"if",
"(",
"argv",
".",
"testDeprecated",
")",
"{",
"rules",
".",
"stylelintDeprecated",
".",
"push",
"(",
"'color-hex-case'",
",",
"'color-hex-length'",
")",
";",
"}",
"if",
"(",
"argv",
".",
"unused",
")",
"{",
"rules",
".",
"stylelintNoDeprecated",
"=",
"_",
".",
"difference",
"(",
"rules",
".",
"stylelintAll",
",",
"rules",
".",
"stylelintDeprecated",
")",
";",
"}",
"return",
"rules",
".",
"stylelintDeprecated",
";",
"}",
")",
";",
"}"
] | Find all deprecated rules from the list of stylelint rules
@returns {Promise} | [
"Find",
"all",
"deprecated",
"rules",
"from",
"the",
"list",
"of",
"stylelint",
"rules"
] | 5c23235686c56ef463fc61bf6f912e64b23acb94 | https://github.com/alexilyaev/stylelint-find-rules/blob/5c23235686c56ef463fc61bf6f912e64b23acb94/src/lib/cli.js#L181-L205 |
23,297 | alexilyaev/stylelint-find-rules | src/lib/cli.js | printUserCurrent | function printUserCurrent() {
if (!argv.current) {
return;
}
const heading = chalk.blue.underline('CURRENT: Currently configured user rules:');
const rulesToPrint = _.map(rules.userRulesNames, rule => {
return {
rule,
url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`)
};
});
printColumns(heading, rulesToPrint);
} | javascript | function printUserCurrent() {
if (!argv.current) {
return;
}
const heading = chalk.blue.underline('CURRENT: Currently configured user rules:');
const rulesToPrint = _.map(rules.userRulesNames, rule => {
return {
rule,
url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`)
};
});
printColumns(heading, rulesToPrint);
} | [
"function",
"printUserCurrent",
"(",
")",
"{",
"if",
"(",
"!",
"argv",
".",
"current",
")",
"{",
"return",
";",
"}",
"const",
"heading",
"=",
"chalk",
".",
"blue",
".",
"underline",
"(",
"'CURRENT: Currently configured user rules:'",
")",
";",
"const",
"rulesToPrint",
"=",
"_",
".",
"map",
"(",
"rules",
".",
"userRulesNames",
",",
"rule",
"=>",
"{",
"return",
"{",
"rule",
",",
"url",
":",
"chalk",
".",
"cyan",
"(",
"`",
"${",
"rule",
"}",
"`",
")",
"}",
";",
"}",
")",
";",
"printColumns",
"(",
"heading",
",",
"rulesToPrint",
")",
";",
"}"
] | Print currently configured rules | [
"Print",
"currently",
"configured",
"rules"
] | 5c23235686c56ef463fc61bf6f912e64b23acb94 | https://github.com/alexilyaev/stylelint-find-rules/blob/5c23235686c56ef463fc61bf6f912e64b23acb94/src/lib/cli.js#L217-L231 |
23,298 | alexilyaev/stylelint-find-rules | src/lib/cli.js | printAllAvailable | function printAllAvailable() {
if (!argv.available) {
return;
}
const heading = chalk.blue.underline('AVAILABLE: All available stylelint rules:');
const rulesToPrint = _.map(rules.stylelintAll, rule => {
return {
rule,
url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`)
};
});
printColumns(heading, rulesToPrint);
} | javascript | function printAllAvailable() {
if (!argv.available) {
return;
}
const heading = chalk.blue.underline('AVAILABLE: All available stylelint rules:');
const rulesToPrint = _.map(rules.stylelintAll, rule => {
return {
rule,
url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`)
};
});
printColumns(heading, rulesToPrint);
} | [
"function",
"printAllAvailable",
"(",
")",
"{",
"if",
"(",
"!",
"argv",
".",
"available",
")",
"{",
"return",
";",
"}",
"const",
"heading",
"=",
"chalk",
".",
"blue",
".",
"underline",
"(",
"'AVAILABLE: All available stylelint rules:'",
")",
";",
"const",
"rulesToPrint",
"=",
"_",
".",
"map",
"(",
"rules",
".",
"stylelintAll",
",",
"rule",
"=>",
"{",
"return",
"{",
"rule",
",",
"url",
":",
"chalk",
".",
"cyan",
"(",
"`",
"${",
"rule",
"}",
"`",
")",
"}",
";",
"}",
")",
";",
"printColumns",
"(",
"heading",
",",
"rulesToPrint",
")",
";",
"}"
] | Print all available stylelint rules | [
"Print",
"all",
"available",
"stylelint",
"rules"
] | 5c23235686c56ef463fc61bf6f912e64b23acb94 | https://github.com/alexilyaev/stylelint-find-rules/blob/5c23235686c56ef463fc61bf6f912e64b23acb94/src/lib/cli.js#L236-L250 |
23,299 | alexilyaev/stylelint-find-rules | src/lib/cli.js | printConfiguredUnavailable | function printConfiguredUnavailable() {
if (!argv.invalid) {
return;
}
const configuredUnavailable = _.difference(rules.userRulesNames, rules.stylelintAll);
if (!configuredUnavailable.length) {
return;
}
const heading = chalk.red.underline('INVALID: Configured rules that are no longer available:');
const rulesToPrint = _.map(configuredUnavailable, rule => {
return {
rule: chalk.redBright(rule)
};
});
printColumns(heading, rulesToPrint);
} | javascript | function printConfiguredUnavailable() {
if (!argv.invalid) {
return;
}
const configuredUnavailable = _.difference(rules.userRulesNames, rules.stylelintAll);
if (!configuredUnavailable.length) {
return;
}
const heading = chalk.red.underline('INVALID: Configured rules that are no longer available:');
const rulesToPrint = _.map(configuredUnavailable, rule => {
return {
rule: chalk.redBright(rule)
};
});
printColumns(heading, rulesToPrint);
} | [
"function",
"printConfiguredUnavailable",
"(",
")",
"{",
"if",
"(",
"!",
"argv",
".",
"invalid",
")",
"{",
"return",
";",
"}",
"const",
"configuredUnavailable",
"=",
"_",
".",
"difference",
"(",
"rules",
".",
"userRulesNames",
",",
"rules",
".",
"stylelintAll",
")",
";",
"if",
"(",
"!",
"configuredUnavailable",
".",
"length",
")",
"{",
"return",
";",
"}",
"const",
"heading",
"=",
"chalk",
".",
"red",
".",
"underline",
"(",
"'INVALID: Configured rules that are no longer available:'",
")",
";",
"const",
"rulesToPrint",
"=",
"_",
".",
"map",
"(",
"configuredUnavailable",
",",
"rule",
"=>",
"{",
"return",
"{",
"rule",
":",
"chalk",
".",
"redBright",
"(",
"rule",
")",
"}",
";",
"}",
")",
";",
"printColumns",
"(",
"heading",
",",
"rulesToPrint",
")",
";",
"}"
] | Print configured rules that are no longer available | [
"Print",
"configured",
"rules",
"that",
"are",
"no",
"longer",
"available"
] | 5c23235686c56ef463fc61bf6f912e64b23acb94 | https://github.com/alexilyaev/stylelint-find-rules/blob/5c23235686c56ef463fc61bf6f912e64b23acb94/src/lib/cli.js#L255-L274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.