_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q4800
|
replaceLinkWithEmbedded
|
train
|
function replaceLinkWithEmbedded(node, index, parent, vFile) {
const { title, url, position } = node;
let newNode;
// If the node isn't mermaid, ignore it.
if (!isMermaid(title)) {
return node;
}
try {
const value = fs.readFileSync(`${vFile.dirname}/${url}`, { encoding: 'utf-8' });
newNode = createMermaidDiv(value);
|
javascript
|
{
"resource": ""
}
|
q4801
|
visitCodeBlock
|
train
|
function visitCodeBlock(ast, vFile, isSimple) {
return visit(ast, 'code', (node, index, parent) => {
const { lang, value, position } = node;
const destinationDir = getDestinationDir(vFile);
let newNode;
// If this codeblock is not mermaid, bail.
if (lang !== 'mermaid') {
return node;
}
// Are we just transforming to a <div>, or replacing with an image?
if (isSimple) {
newNode = createMermaidDiv(value);
vFile.info(`${lang} code block replaced with div`, position, PLUGIN_NAME);
// Otherwise, let's try and generate a graph!
} else {
let graphSvgFilename;
try {
graphSvgFilename = render(value, destinationDir);
vFile.info(`${lang}
|
javascript
|
{
"resource": ""
}
|
q4802
|
mermaid
|
train
|
function mermaid(options = {}) {
const simpleMode = options.simple || false;
/**
* @param {object} ast MDAST
* @param {vFile} vFile
* @param {function} next
* @return {object}
*/
return function transformer(ast, vFile, next) {
visitCodeBlock(ast, vFile,
|
javascript
|
{
"resource": ""
}
|
q4803
|
safeProcess
|
train
|
function safeProcess (ctx, fn) {
return function processRequest (req, res) {
try {
fn(ctx, req, res)
|
javascript
|
{
"resource": ""
}
|
q4804
|
ioSession
|
train
|
function ioSession(options) {
var cookieParser = options.cookieParser,
sessionStore = options.store,
key = options.key || "connect.sid";
function findCookie(handshake) {
return (handshake.secureCookies && handshake.secureCookies[key])
|| (handshake.signedCookies && handshake.signedCookies[key])
|| (handshake.cookies && handshake.cookies[key]);
}
function getSession(socketHandshake, callback) {
cookieParser(socketHandshake, {}, function (parseErr) {
if(parseErr) {
callback(parseErr);
return;
}
// use sessionStore.get() instead of deprecated sessionStore.load()
sessionStore.get(findCookie(socketHandshake), function (storeErr, session) {
if(storeErr) {
callback(storeErr);
return;
}
|
javascript
|
{
"resource": ""
}
|
q4805
|
normalizeError
|
train
|
function normalizeError(err, stack) {
err = coerceToError(err)
if (!err.normalized) {
addNonEnumerableValue(err, 'originalStack', stack || err.message)
addNonEnumerableValue(err, 'normalized', true)
|
javascript
|
{
"resource": ""
}
|
q4806
|
train
|
function (projection = '') {
//prepare projections
let fields = _.compact(projection.split(','));
fields = _.map(fields, _.trim);
fields = _.uniq(fields);
const accumulator = {};
_.forEach(fields, function (field) {
//if exclude e.g -name
if (field[0]
|
javascript
|
{
"resource": ""
}
|
|
q4807
|
DeviceOnMap
|
train
|
function DeviceOnMap (map, data) {
this.trace=[]; // keep trace of device trace on xx positions
this.count=0; // number of points created for this device
|
javascript
|
{
"resource": ""
}
|
q4808
|
TcpClientData
|
train
|
function TcpClientData (buffer) {
this.controller.Debug(7, "[%s] Data=[%s]", this.uid, buffer);
// call adapter specific
|
javascript
|
{
"resource": ""
}
|
q4809
|
train
|
function() {
that.bar = $('<div></div>').addClass('peek-a-bar').attr('id', '__peek_a_bar_' + rand);
|
javascript
|
{
"resource": ""
}
|
|
q4810
|
train
|
function() {
if(that.settings.cssClass !== null) {
|
javascript
|
{
"resource": ""
}
|
|
q4811
|
train
|
function() {
switch(that.settings.position) {
case 'top':
that.bar.css('top', 0);
break;
case 'bottom':
|
javascript
|
{
"resource": ""
}
|
|
q4812
|
GpsdHttpClient
|
train
|
function GpsdHttpClient (adapter, devid) {
this.debug = adapter.debug; // inherit debug level
this.uid = "httpclient//" + adapter.info + ":" + devid;
this.adapter = adapter;
this.gateway = adapter.gateway;
this.controller = adapter.controller;
this.socket = null; // we cannot rely on socket to talk to device
this.devid = false; // we get uid directly from device
this.name = false;
this.logged = false;
|
javascript
|
{
"resource": ""
}
|
q4813
|
ScanGpxDir
|
train
|
function ScanGpxDir (gpxdir) {
var availableRoutes=[];
var count=0;
var routesDir = gpxdir;
var directory = fs.readdirSync(routesDir);
for (var i in directory) {
var file = directory [i];
var route = path.basename (directory [i],".gpx");
var name = routesDir + route + '.gpx';
try {
if (fs.statSync(name).isFile()) {
count ++;
availableRoutes [route] = name;
|
javascript
|
{
"resource": ""
}
|
q4814
|
SetGarbage
|
train
|
function SetGarbage (proxy, timeout) {
// let's call back ourself after timeout*1000/4
proxy.Debug (4, "SetGarbage timeout=%d", timeout);
setTimeout (function(){SetGarbage (proxy, timeout);}, timeout*500);
// let compute timeout timeout limit
var lastshow = new Date().getTime() - (timeout *1000);
for (var mmsi in proxy.vessels) {
|
javascript
|
{
"resource": ""
}
|
q4815
|
MongoStore
|
train
|
function MongoStore(connection, options) {
if(arguments.length === 0 || typeof arguments[0] !== 'string') {
throw new Error('A valid connection string has to be provided');
}
TokenStore.call(this);
this._options = options || {};
this._collectionName = 'passwordless-token';
if(this._options.mongostore) {
if(this._options.mongostore.collection) {
|
javascript
|
{
"resource": ""
}
|
q4816
|
SetCrontab
|
train
|
function SetCrontab (gateway, inactivity) {
// let's call back ourself after inactivity*1000/4
gateway.Debug (5, "SetCrontab inactivity=%d", inactivity);
setTimeout (function(){SetCrontab (gateway, inactivity);}, inactivity*250);
// let compute inactivity timeout limit
var timeout = new Date().getTime() - (inactivity *1000);
for (var devid in gateway.activeClients) {
|
javascript
|
{
"resource": ""
}
|
q4817
|
JobCallback
|
train
|
function JobCallback (job) {
if (job !== null) {
job.gateway.Debug (6,"Queued Request:%s command=%s devid=%s
|
javascript
|
{
"resource": ""
}
|
q4818
|
TcpStreamConnect
|
train
|
function TcpStreamConnect () {
this.simulator.Debug (3, 'Dispatcher connected to %s:%s', simulator.opts.host, simulator.opts.port);
|
javascript
|
{
"resource": ""
}
|
q4819
|
TcpStreamEnd
|
train
|
function TcpStreamEnd () {
this.simulator.Debug (3,"TcpStream [%s:%s] connection ended", simulator.opts.host, simulator.opts.port);
delete ActiveClients[this];
|
javascript
|
{
"resource": ""
}
|
q4820
|
train
|
function (dbresult) {
if (dbresult === null || dbresult === undefined) {
this.Debug (1,"Hoops: no DB info for %s", data.devid);
return;
}
for (var idx = 0; (idx < dbresult.length); idx ++) {
var posi= dbresult[idx];
posi.lon = posi.lon.toFixed (4);
posi.lat = posi.lat.toFixed (4);
posi.sog = posi.sog.toFixed (2);
|
javascript
|
{
"resource": ""
}
|
|
q4821
|
DevAdapter
|
train
|
function DevAdapter (controller) {
this.id = controller.svc;
this.uid = "//" + controller.svcopts.adapter + "/" + controller.svc + "@" + controller.svcopts.hostname + ":" +controller.svcopts.remport;
this.info = 'nmeatcp';
this.control = 'tcpfeed'; // this adapter connect onto a remote server
this.debug = controller.svcopts.debug; // inherit debug from controller
this.controller= controller; // keep a link to device controller and TCP socket
this.mmsi = controller.svcopts.mmsi; // use fake MMSI provided by user application in service options
// Check mmsi is unique
|
javascript
|
{
"resource": ""
}
|
q4822
|
EventHandlerQueue
|
train
|
function EventHandlerQueue (status, job){
console.log ("#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d",
|
javascript
|
{
"resource": ""
}
|
q4823
|
mergeResolvedReflectiveProviders
|
train
|
function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
for (var /** @type {?} */ i = 0; i < providers.length; i++) {
var /** @type {?} */ provider = providers[i];
var /** @type {?} */ existing = normalizedProvidersMap.get(provider.key.id);
if (existing) {
if (provider.multiProvider !== existing.multiProvider) {
throw new MixingMultiProvidersWithRegularProvidersError(existing, provider);
}
if (provider.multiProvider) {
for (var /** @type {?} */ j = 0; j < provider.resolvedFactories.length; j++) {
existing.resolvedFactories.push(provider.resolvedFactories[j]);
}
}
else {
normalizedProvidersMap.set(provider.key.id, provider);
}
}
else {
|
javascript
|
{
"resource": ""
}
|
q4824
|
assertPlatform
|
train
|
function assertPlatform(requiredToken) {
var /** @type {?} */ platform = getPlatform();
if (!platform) {
throw new Error('No platform exists!');
}
if (!platform.injector.get(requiredToken, null)) {
|
javascript
|
{
"resource": ""
}
|
q4825
|
getLocale
|
train
|
function getLocale (key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
|
javascript
|
{
"resource": ""
}
|
q4826
|
ComponentLoader
|
train
|
function ComponentLoader(_viewContainerRef, _renderer, _elementRef, _injector, _componentFactoryResolver, _ngZone, _posService) {
this.onBeforeShow = new EventEmitter();
this.onShown = new EventEmitter();
this.onBeforeHide = new EventEmitter();
|
javascript
|
{
"resource": ""
}
|
q4827
|
delayWhen$2
|
train
|
function delayWhen$2(delayDurationSelector, subscriptionDelay) {
if (subscriptionDelay) {
return new SubscriptionDelayObservable(this, subscriptionDelay)
|
javascript
|
{
"resource": ""
}
|
q4828
|
leadingZeros
|
train
|
function leadingZeros(number, minLength = 0, padWith = '0') {
const stringNumber = number.toString()
const paddingLength = minLength - stringNumber.length
|
javascript
|
{
"resource": ""
}
|
q4829
|
train
|
function(dbresult) {
// start with response header
var jsonresponse= // validate syntaxe at http://geojsonlint.com/
{"type":"GeometryCollection"
,"device":
{"type":"Device"
,"class":device.class
,"model": device.model
,"call": device.call
},"properties":
{"type":"Properties"
,'id' : query.devid
,"name": device.name
,'url': devurl
,'img': device.img
}
,"geometries":[]
};
for (var idx in dbresult) {
var pos = dbresult [idx];
var ptsinfo=util.format ("%s<br>Position:[%s,%s] Speed:%s",pos.date,pos.lon.toFixed(4),pos.lat.toFixed(4),pos.sog.toFixed(1));
jsonresponse.geometries.push (
{'type':'Point'
,'coordinates' :[pos.lon, pos.lat]
,'sog' : pos.sog
,'cog' : pos.cog
,'date' : pos.date.getTime()
|
javascript
|
{
"resource": ""
}
|
|
q4830
|
ReadFileCB
|
train
|
function ReadFileCB (err, byteread, buffer) {
if (err) {
response.write(err.toString());
} else {
|
javascript
|
{
"resource": ""
}
|
q4831
|
OpenFileCB
|
train
|
function OpenFileCB (err, fd) {
if (err) {
response.setHeader('Content-Type','text/html');
response.writeHead(404, err.toString("utf8"));
response.write("Hoops:" + err );
|
javascript
|
{
"resource": ""
}
|
q4832
|
CreateConnection
|
train
|
function CreateConnection (backend) {
backend.Debug (4, "MongoDB creating connection [%s]", backend.uid);
MongoClient.connect(backend.uid, function (err, db) {
if (err) {
backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err)
|
javascript
|
{
"resource": ""
}
|
q4833
|
BackendStorage
|
train
|
function BackendStorage (gateway, opts){
// prepare ourself to make debug possible
this.debug =opts.debug;
this.gateway=gateway;
this.opts=
{ hostname : opts.mongodb.hostname || "localhost"
, username : opts.mongodb.username
, password : opts.mongodb.password
, basename : opts.mongodb.basename || opts.mongo.username
, port : opts.mongodb.port
|
javascript
|
{
"resource": ""
}
|
q4834
|
WriteIpAddr
|
train
|
function WriteIpAddr (buffer, offset, ipstring) {
var addr= ipstring.split('.');
buffer.writeUInt8(parseInt(addr[3]), offset);
buffer.writeUInt8(parseInt(addr[2]), offset + 1);
|
javascript
|
{
"resource": ""
}
|
q4835
|
NmeaAisEncoder
|
train
|
function NmeaAisEncoder (data) {
var msg;
// Use NMEA GRPMC or AIVDM depending on Vessel MMSI
if (data.mmsi === 0) {
// this ship has no MMSI let's use GPRMC format
switch (data.cmd) {
case 1:
msg = { // built a Fake NMEA authentication message
valid: true,
nmea: "FAKID" + data.mmsi +',' + data.shipname
};
break;
case 2:
msg = new GGencode.NmeaEncode(data);
break;
default:
msg = null;
}
} else {
// we are facing multiple boats use AIS ADVDM
switch (data.cmd) {
case 1:
if (data.class === 'A') data.aistype = 5; else data.aistype =
|
javascript
|
{
"resource": ""
}
|
q4836
|
JobQueuePost
|
train
|
function JobQueuePost (job, callback) {
// dummy job to activate jobqueue
if (job === null) {
callback ();
return;
} else {
// force change to simulator context
job.simulator.NewPosition.call (job.simulator, job);
}
// wait tic time before sending next message
job.simulator.queue.pause ();
// provide some randomization on tic with
|
javascript
|
{
"resource": ""
}
|
q4837
|
JobQueueActivate
|
train
|
function JobQueueActivate(queue, callback, timeout) {
setTimeout(function
|
javascript
|
{
"resource": ""
}
|
q4838
|
EventDevAuth
|
train
|
function EventDevAuth (device){
if (!device.mmsi) device.mmsi = parseInt (device.devid);
if (isNaN (device.mmsi)) device.mmsi=String2Hash(device.devid);
|
javascript
|
{
"resource": ""
}
|
q4839
|
SmsBatch
|
train
|
function SmsBatch (smsc, callback, smsarray) {
var idx=0;
// when message is processed move to next one otherwise call user applicationCB
function InternalCB (data) {
// [good or bad] let's notify user application
if (data.status != 0) callback (data);
|
javascript
|
{
"resource": ""
}
|
q4840
|
InternalCB
|
train
|
function InternalCB (data) {
// [good or bad] let's notify user application
if (data.status != 0) callback (data);
// it's time to move to next message
if (data.status <= 0) {
if (++idx < smsarray.length) {
|
javascript
|
{
"resource": ""
}
|
q4841
|
BackendStorage
|
train
|
function BackendStorage (gateway, opts){
// prepare ourself to make debug possible
this.uid="Dummy@nothing";
this.gateway =gateway;
this.debug=opts.debug;
this.count=0;
|
javascript
|
{
"resource": ""
}
|
q4842
|
train
|
function (job, callback) {
// decode AIS message ignoring any not AIDVM paquet
var nmea= job.toString ('ascii');
var ais = new AisDecode (nmea);
// if message valid and mssi not excluded by --mmsi option
if (ais.valid) {
// Some cleanup to make JSON/AIS more human readable
delete ais.bitarray;
delete ais.valid;
delete ais.length;
delete ais.channel;
delete ais.repeat;
delete ais.navstatus;
delete ais.utc;
ais.lon = (parseInt(ais.lon * 10000))/10000;
ais.lat = (parseInt(ais.lat * 10000))/10000;
|
javascript
|
{
"resource": ""
}
|
|
q4843
|
CheckDevAckCB
|
train
|
function CheckDevAckCB(err, results) {
self.retry ++; // retry counter for ACK
self.Debug (6, "CheckDevAckCB Phone=%s Retry=%d/%d Result=%j", smscmd.phone, self.retry, smsc.opts.retry, results);
// ack no received
if (results.length === 0) {
if (self.retry <= smsc.opts.retry) {
setTimeout (function() {CheckDevAck ();}, smsc.opts.delay);
} else {
self.Debug (7, "CheckDevAckCB Ack Abandoned MaxRetry=%s", smsc.opts.retry);
appcb ({status: -2, smsid: smscmd.id});
}
} else {
// we may have more than one responses for a given command
for (var slot in results) {
var ack =
{ status: 2
,
|
javascript
|
{
"resource": ""
}
|
q4844
|
CheckDevAck
|
train
|
function CheckDevAck() {
self.Debug (3,"Waiting Acknowledgment
|
javascript
|
{
"resource": ""
}
|
q4845
|
CheckOutboxCB
|
train
|
function CheckOutboxCB(err, results) {
var result = results[0]; // Query result is alway an array of response even when unique
self.retry ++; // update retry counter
// if message is still in queue retry
self.Debug (6,"CheckOutboxCB Phone=%s Result=%j Retry=%d/%d", smscmd.phone, result, self.retry, smsc.opts.retry);
if (result !== undefined) {
// message is still in queue loop one more time
if (self.retry <= smsc.opts.retry) {
setTimeout (function() {CheckOutbox (result.ID);}, smsc.opts.delay);
} else {
// notify appcb that SMS failed and was deleted
self.Debug (6,"CheckOutboxCB Fail SqlId=%s SMS=%j", result.ID, smscmd);
smsc.DelById (DelByIdCB, result.ID);
appcb ({status: -1, smsid: smscmd.id});
}
} else {
// le message à été
|
javascript
|
{
"resource": ""
}
|
q4846
|
CheckOutbox
|
train
|
function CheckOutbox (insertId) {
self.Debug (3,"Waiting Sent Confirmation %d/%d", self.retry, smsc.opts.retry);
|
javascript
|
{
"resource": ""
}
|
q4847
|
SendToCB
|
train
|
function SendToCB (err, result) {
// check if sms was sent from output table
self.Debug (7,"SendToCB SMS=%j result=%j err=%j", smscmd, result, err);
if (err) {
self.Debug (1, "Insert in MySql outbox refused %s", err);
appcb
|
javascript
|
{
"resource": ""
}
|
q4848
|
TcpClient
|
train
|
function TcpClient (socket) {
this.debug = socket.controller.debug; // inherit controller debug level
this.gateway = socket.controller.gateway;
this.controller= socket.controller;
this.adapter = socket.adapter;
this.socket = socket;
this.devid = false; // devid/mmsi directly from device or adapter
this.name = false;
this.logged = false;
this.alarmcount= 0; // count alarm messages
this.errorcount= 0; // number of ignore messages
this.jobcount = 0; // Job commands send to gateway
this.count
|
javascript
|
{
"resource": ""
}
|
q4849
|
train
|
function(lat){
// TK103 sample 4737.1024,N for 47°37'.1024
var deg= parseInt (lat[0]/100) || 0;
var min= lat[0] - (deg*100);
var dec= deg + (min/60);
|
javascript
|
{
"resource": ""
}
|
|
q4850
|
BatchCB
|
train
|
function BatchCB (response) {
console.log ("### Batch SMS CallBack --> Status=%j", response);
if (response.status === 0 || response.status === -4) {
|
javascript
|
{
"resource": ""
}
|
q4851
|
ResponseCB
|
train
|
function ResponseCB (response) {
console.log ("### Single SMS CallBack --> Status=%j", response);
if (response.status === 0) {
var batch = require('../sample/SmsCommand-batch');
smscontrol.ProcessBatch (BatchCB, phonenumber, password, batch);
}
if
|
javascript
|
{
"resource": ""
}
|
q4852
|
train
|
function(svg){
if (!svg){
throw new Error('.toString: No SVG found.');
}
[
['version', 1.1],
|
javascript
|
{
"resource": ""
}
|
|
q4853
|
train
|
function(cb){
this.toSvgImage(function(img){
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.width = img.width;
|
javascript
|
{
"resource": ""
}
|
|
q4854
|
train
|
function(cb){
this.toCanvas(function(canvas){
var canvasData = canvas.toDataURL("image/png");
var img = document.createElement('img');
img.onload = function(){
cb(img);
};
|
javascript
|
{
"resource": ""
}
|
|
q4855
|
train
|
function(cb){
this.toCanvas(function(canvas){
var dataUrl = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, "");
var byteString = atob(escape(dataUrl));
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for
|
javascript
|
{
"resource": ""
}
|
|
q4856
|
train
|
function(filename){
if (!filename){
filename = 'chart';
}
this.toImg(function(img){
var a = document.createElement("a");
// Name of the file being downloaded.
a.download = filename + ".png";
a.href = img.getAttribute('src');
// Support for Firefox
|
javascript
|
{
"resource": ""
}
|
|
q4857
|
_assignGenerator
|
train
|
function _assignGenerator(own) {
let _copy = function(target, ...source) {
let deep = true;
if (is.Boolean(target)) {
deep = target;
target = 0 in source
? source.shift()
: null;
}
if (is.Array(target)) {
source.forEach(sc => {
target.push(...sc);
});
} else if (is.Object(target)) {
source.forEach(sc => {
for (let key in sc) {
if (own && !sc.hasOwnProperty(key))
|
javascript
|
{
"resource": ""
}
|
q4858
|
train
|
function(req, res, next){
that.accessCheck(req, res, next,
|
javascript
|
{
"resource": ""
}
|
|
q4859
|
strictReplace
|
train
|
function strictReplace(str, pairs, multiline) {
var index;
var fromIndex = 0;
pairs.some(function (pair) {
var toReplace = pair[0];
var replaceWith = pair[1];
index = str.indexOf(toReplace, fromIndex);
if (index === -1) {
return true;
}
var lhs = str.substr(0, index);
var rhs = str.substr(index + toReplace.length);
|
javascript
|
{
"resource": ""
}
|
q4860
|
isMultipleArray
|
train
|
function isMultipleArray(valueStr) {
var wrappedValueStr = '[ ' + valueStr + ' ]';
var wrappedArray = createArray(wrappedValueStr, {}, {
|
javascript
|
{
"resource": ""
}
|
q4861
|
updateJob
|
train
|
function updateJob(jobId, attributes) {
var user = process.env.SAUCE_USERNAME;
var pass = process.env.SAUCE_ACCESS_KEY;
return utils
.makeRequest({
method: 'PUT',
|
javascript
|
{
"resource": ""
}
|
q4862
|
train
|
function(properties){
/**
* Create a new instance for the model
* @class Model
* @augments BaseModel
* @param {object} instance_values Key/value object containing values of the row *
* @classdesc Generic model. Use it statically to find documents on Cassandra. Any instance represent a
|
javascript
|
{
"resource": ""
}
|
|
q4863
|
train
|
function(){
var copy_fields = ['contactPoints'],
temp_connection = {},
connection = this._connection;
for(var fk in copy_fields){
|
javascript
|
{
"resource": ""
}
|
|
q4864
|
train
|
function(replication_option){
if( typeof replication_option == 'string'){
return replication_option;
}else{
var properties = [];
for(var k in replication_option){
properties.push(util.format("'%s': '%s'",
|
javascript
|
{
"resource": ""
}
|
|
q4865
|
train
|
function(callback){
var client = this._get_system_client();
var keyspace_name = this._connection.keyspace,
replication_text = '',
options = this._options;
replication_text = this._generate_replication_text(options.replication_strategy);
var query = util.format(
"CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = %s;",
|
javascript
|
{
"resource": ""
}
|
|
q4866
|
train
|
function(client){
var define_connection_options = lodash.clone(this._connection);
define_connection_options.policies = {
loadBalancing: new SingleNodePolicy()
};
//define_connection_options.hosts = define_connection_options.contactPoints;
this._client = client;
this._define_connection = new cql.Client(define_connection_options);
/*this._client.on('log',function(level, message){
|
javascript
|
{
"resource": ""
}
|
|
q4867
|
train
|
function(callback){
var on_keyspace = function(err){
if(err){ return callback(err);}
this._set_client(new cql.Client(this._connection));
callback(err, this);
};
if(this._keyspace){
|
javascript
|
{
"resource": ""
}
|
|
q4868
|
train
|
function(model_name, model_schema, options) {
if(!model_name || typeof(model_name) != "string")
throw("Si deve specificare un nome per il modello");
options = options || {};
options.mismatch_behaviour = options.mismatch_behaviour || 'fail';
if(options.mismatch_behaviour !== 'fail' && options.mismatch_behaviour !== 'drop')
throw 'Valid option values for "mismatch_behaviour": "fail" , "drop". Got: "'+options.mismatch_behaviour+'"';
//model_schema = schemer.normalize_model_schema(model_schema);
schemer.validate_model_schema(model_schema);
var base_properties = {
name : model_name,
schema : model_schema,
|
javascript
|
{
"resource": ""
}
|
|
q4869
|
train
|
function(callback){
callback = callback || noop;
if(!this._client){
return callback();
}
this._client.shutdown(function(err){
if(!this._define_connection){
return callback(err);
|
javascript
|
{
"resource": ""
}
|
|
q4870
|
triggerMultiSelectEvents
|
train
|
function triggerMultiSelectEvents ( collection, prevSelected, options, reselected ) {
function mapCidsToModels ( cids, collection, previousSelection ) {
function mapper ( cid ) {
// Find the model in the collection. If not found, it has been removed, so get it from the array of
// previously selected models.
return collection.get( cid ) || previousSelection[cid];
}
return _.map( cids, mapper );
}
if ( options.silent || options["@bbs:silentLocally"] ) return;
var diff,
label = getLabel( options, collection ),
selectionSize = getSelectionSize( collection, label ),
length = collection.length,
prevSelectedCids = _.keys( prevSelected ),
selectedCids = _.keys( collection[label] ),
addedCids = _.difference( selectedCids, prevSelectedCids ),
removedCids = _.difference( prevSelectedCids, selectedCids ),
unchanged = (selectionSize === prevSelectedCids.length && addedCids.length === 0 && removedCids.length === 0);
if ( reselected && reselected.length && !options["@bbs:silentReselect"] ) {
queueEventSet( "reselect:any", label, [ reselected, collection, toEventOptions( options, label, collection ) ], collection, options );
}
if ( unchanged ) return;
diff = {
selected: mapCidsToModels( addedCids, collection, prevSelected ),
|
javascript
|
{
"resource": ""
}
|
q4871
|
ensureModelMixin
|
train
|
function ensureModelMixin( model, collection, options ) {
var applyModelMixin;
if ( !model._pickyType ) {
applyModelMixin = Backbone.Select.Me.custom.applyModelMixin;
if ( applyModelMixin && _.isFunction( applyModelMixin ) ) {
|
javascript
|
{
"resource": ""
}
|
q4872
|
train
|
function ( model ) {
var trailing = this.collection.trailing && this.collection.trailing.id || this.collection.first().id,
view = this,
cbUpdateTrailing = function () {
view.collection.get( Math.round( this.trailingId ) ).select( { label: "trailing" } );
};
// Animate the trailing element and make it catch up. Use the .select() method with the label
|
javascript
|
{
"resource": ""
}
|
|
q4873
|
Maintainer
|
train
|
function Maintainer (name, store) {
if (!(this instanceof Maintainer)) {
return new Maintainer(name);
|
javascript
|
{
"resource": ""
}
|
q4874
|
template
|
train
|
function template(filePath, locals, fn) {
filePath = path.join(getConfig('template.folder'), filePath + '.' + getConfig('template.extension')); // i.e. index -> index.ejs
|
javascript
|
{
"resource": ""
}
|
q4875
|
parseDB
|
train
|
function parseDB(callback) {
pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'),
getConfig('database.password'),
|
javascript
|
{
"resource": ""
}
|
q4876
|
getBelongsToName
|
train
|
function getBelongsToName(fkc) {
var as = fkc.foreignKey(0).name(), // company_id
tableName = fkc.table().name(),
camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related
if (as.match(/_id$/i)) {
as = as.replace(/_id$/i, '');
|
javascript
|
{
"resource": ""
}
|
q4877
|
getBelongsToManyName
|
train
|
function getBelongsToManyName(hasManyThrough) {
var tfkc = hasManyThrough.throughForeignKeyConstraint(),
as = tfkc.foreignKey(0).name(), // company_id
throughTableName = hasManyThrough.through().name(),
relationName = hasManyThrough.throughForeignKeyConstraintToSelf().name(),
tableName = hasManyThrough.table().name(),
camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related
if (getSpecificConfig(tableName, 'generate.addRelationNameToManyToMany')) {
if (getSpecificConfig(tableName, 'generate.stripFirstTableNameFromManyToMany')) {
relationName = relationName.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_item
}
as = inflection.singularize(relationName) + '_' + as;
|
javascript
|
{
"resource": ""
}
|
q4878
|
getHasManyName
|
train
|
function getHasManyName(hasMany) {
var as, tableName;
if (hasMany.through() !== undefined) {
as = getBelongsToManyName(hasMany); //inflection.pluralize(getBelongsToName(hasMany.throughForeignKeyConstraint()));
} else {
as = inflection.pluralize(hasMany.name()); // cart_cart_line_items
tableName = hasMany.table().name();
if (getSpecificConfig(tableName, 'generate.stripFirstTableFromHasMany')) {
|
javascript
|
{
"resource": ""
}
|
q4879
|
getModelNameFor
|
train
|
function getModelNameFor(table) {
var schemaName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.schema().name()), true) : table.schema().name(),
tableName
|
javascript
|
{
"resource": ""
}
|
q4880
|
getTableOptions
|
train
|
function getTableOptions(table) {
logger.debug('table details are calculated for: %s', table.name());
var specificName = 'tableOptionsOverride.' + table.name(),
specificOptions = config.has(specificName) ? getConfig(specificName) : {},
generalOptions = getConfig('tableOptions'),
otherOptions = {
modelName : getModelNameFor(table),
tableName : table.name(),
schema : table.schema().name(),
comment : getSpecificConfig(table.name(), 'generate.tableDescription') ? table.description() : undefined,
|
javascript
|
{
"resource": ""
}
|
q4881
|
sequelizeType
|
train
|
function sequelizeType(column, varName) {
varName = varName || 'DataTypes'; // DataTypes.INTEGER etc. prefix
var enumValues = column.enumValues();
var type = enumValues ? '.ENUM' : sequelizeTypes[column.type()].type;
var realType = column.arrayDimension() >= 1 ? column.arrayType() : column.type(); // type or type of array (if array).
var hasLength = sequelizeTypes[realType].hasLength;
var hasPrecision = sequelizeTypes[realType].hasPrecision;
var isObject = type && type.indexOf('.') !== -1; // . ile başlıyorsa değişkene çevirmek için
var details;
var isArrayTypeObject;
if (isObject) { type = varName + type; }
details = function(num1, num2) {
var detail = '';
if (num1 >= 0 && num1 !== null && num2 && num2 !== null) {
detail = '(' + num1 + ',' + num2 + ')'; // (5,2)
} else if (num1 >= 0 && num1 !== null) {
detail = '(' + num1 + ')'; // (5)
}
return detail;
};
if (column.arrayDimension() >= 1) {
isArrayTypeObject = sequelizeTypes[column.arrayType()].type.indexOf('.') !== -1;
type += '(';
if (column.arrayDimension() > 1) { type += new Array(column.arrayDimension()).join(varName + '.ARRAY('); } // arrayDimension -1 tane 'ARRAY('
|
javascript
|
{
"resource": ""
}
|
q4882
|
getColumnDetails
|
train
|
function getColumnDetails(column) {
logger.debug('column details are calculated for: %s', column.name());
var result = filterAttributes({
source : 'generator',
accessorName : getSpecificConfig(column.table().name(), 'generate.columnAccessorCamelCase') ? inflection.camelize(inflection.underscore(column.name()), true) : column.name(),
name : column.name(),
primaryKey : column.isPrimaryKey(),
autoIncrement : column.isAutoIncrement() && getSpecificConfig(column.table().name(), 'generate.columnAutoIncrement') ? true : undefined,
allowNull : column.allowNull(),
defaultValue : getSpecificConfig(column.table().name(), 'generate.columnDefault') && column.default() !== null ? clearDefaultValue(column.default()) : undefined,
unique : column.unique(),
comment : getSpecificConfig(column.table().name(), 'generate.columnDescription') ? column.description() : undefined,
|
javascript
|
{
"resource": ""
}
|
q4883
|
getHasManyDetails
|
train
|
function getHasManyDetails(hasMany) {
logger.debug('hasMany%s details are calculated for: %s', hasMany.through() ? 'through' : '', hasMany.name());
var model = getModelNameFor(hasMany.referencesTable()),
as = getHasManyName(hasMany);
return filterAttributes({
type : 'hasMany',
source : 'generator',
name : hasMany.name(),
model : model,
as : getAlias(hasMany.table(), as, 'hasMany'),
|
javascript
|
{
"resource": ""
}
|
q4884
|
getBelongsToDetails
|
train
|
function getBelongsToDetails(fkc) {
logger.debug('belongsTo details are calculated for: %s', fkc.name());
var model = getModelNameFor(fkc.referencesTable()),
as = getBelongsToName(fkc);
return filterAttributes({
type : 'belongsTo',
source : 'generator',
name : fkc.name(),
model : model,
as
|
javascript
|
{
"resource": ""
}
|
q4885
|
getBelongsToManyDetails
|
train
|
function getBelongsToManyDetails(hasManyThrough) {
logger.debug('belongsToMany details are calculated for: %s', hasManyThrough.name());
var model = getModelNameFor(hasManyThrough.referencesTable()),
as = getBelongsToManyName(hasManyThrough);
return filterAttributes({
type : 'belongsToMany',
source : 'generator',
name : hasManyThrough.name(),
model : model,
as : getAlias(hasManyThrough.table(), as, 'belongsToMany'),
targetSchema : hasManyThrough.referencesTable().schema().name(),
targetTable
|
javascript
|
{
"resource": ""
}
|
q4886
|
getFileName
|
train
|
function getFileName(table) {
var fileName = table.name() + '.js';
if (getSpecificConfig(table.name(), 'generate.useSchemaName')) { // Prefix with schema name if config requested it.
|
javascript
|
{
"resource": ""
}
|
q4887
|
shouldSkip
|
train
|
function shouldSkip(table, detail) {
var skipTable = getConfig('generate.skipTable'); // Do not auto generate files for those tables.
if (skipTable.indexOf(table.name()) !== -1 || skipTable.indexOf(table.schema().name() + '.' + table.name()) !== -1) {
if (getConfig('output.log')) {
|
javascript
|
{
"resource": ""
}
|
q4888
|
generateModelFiles
|
train
|
function generateModelFiles(db, next) {
var q, templateTable, allNamingErrors = [];
q = async.queue(function (task, workerCallback) {
var output = getConfig('output.beautify') ? beautify(task.content, { indent_size: getConfig('output.indent'), preserve_newlines: getConfig('output.preserveNewLines') }) : task.content;
fs.writeFile(path.join(getConfig('output.folder'), 'definition-files', getFileName(task.table)), output, workerCallback);
if (getConfig('output.log')) { logger.info('(Created) File \'' + getFileName(task.table) + '\' is created for model \'' + getModelNameFor(task.table) + '\''); }
}, 4);
db.schemas(function (schema) {
schema.tables(function (table) {
var namingError = '';
logger.debug('Now parsing table: %s', table.name());
if (getSpecificConfig(table.name(), 'generate.hasManyThrough') && getSpecificConfig(table.name(), 'generate.belongsToMany')) {
next(new Error('Configuration error: Both "generate.hasManyThrough" and "generate.belongsToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.'));
}
if (shouldSkip(table, 'table')) { return; }
templateTable = getTableOptions(table);
table.columns(function (column) {
templateTable.columns.push(getColumnDetails(column));
});
table.hasManies(function (hasMany) {
if (shouldSkip(hasMany.referencesTable(), 'relation')) { return; }
templateTable.hasManies.push(getHasManyDetails(hasMany));
});
table.hasManyThroughs(function (hasManyThrough) {
if (getSpecificConfig(table.name(), 'generate.addRelationNameToManyToMany') && getSpecificConfig(table.name(), 'generate.addTableNameToManyToMany')) {
next(new Error('Configuration error: Both "generate.addRelationNameToManyToMany" and "generate.addTableNameToManyToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.'));
}
if (shouldSkip(hasManyThrough.referencesTable(), 'relation') || shouldSkip(hasManyThrough.through(), 'relation')) { return; }
if (getSpecificConfig(table.name(), 'generate.hasManyThrough')) {
templateTable.hasManies.push(getHasManyDetails(hasManyThrough)); // has many throughs are deprecated after Sequelize 2.0 RC3
}
if (getSpecificConfig(table.name(), 'generate.belongsToMany')) {
templateTable.belongsToManies.push(getBelongsToManyDetails(hasManyThrough));
}
});
|
javascript
|
{
"resource": ""
}
|
q4889
|
createOutputFolder
|
train
|
function createOutputFolder(next) {
var defPath = path.join(getConfig('output.folder'), 'definition-files'),
defPathCustom = path.join(getConfig('output.folder'), 'definition-files-custom');
fs.remove(defPath, function (err) {
if (err) { next(err); }
fs.createFile(path.join(defPath, '_Dont_add_or_edit_any_files'), function (err) {
|
javascript
|
{
"resource": ""
}
|
q4890
|
generateUtilityFiles
|
train
|
function generateUtilityFiles(next) {
fs.copy(path.join(getConfig('template.folder'), 'index.js'), path.join(getConfig('output.folder'), 'index.js'), function (err) {
if (err) { next(err); return; }
if (getConfig('output.log')) { logger.info('(Created) Index file: ' + path.resolve(path.join(getConfig('output.folder'), 'index.js'))); }
fs.copy(path.join(getConfig('template.folder'), '..', 'utils.js'), path.join(getConfig('output.folder'), 'utils.js'), function (err) {
|
javascript
|
{
"resource": ""
}
|
q4891
|
setupConfig
|
train
|
function setupConfig(options) {
if (options.resetConfig) {
// Reset your environment variables for resetting node-config module. node-config is a singleton.
// For testing it's necessary to reset and this is a workaround from node-config support.
global.NODE_CONFIG = null;
delete require.cache[require.resolve('config')];
config = require('config');
delete options.resetConfig;
|
javascript
|
{
"resource": ""
}
|
q4892
|
View
|
train
|
function View (name) {
if (!(this instanceof View)) {
return new View(name);
}
this.name = name;
|
javascript
|
{
"resource": ""
}
|
q4893
|
BaseModel
|
train
|
function BaseModel(store) {
if (!(this instanceof BaseModel)) {
return new BaseModel(store);
}
Base.call(this);
this.options = this.options || {};
|
javascript
|
{
"resource": ""
}
|
q4894
|
train
|
function(obj, name, callback, context, listening) {
obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
context: context,
ctx: obj,
listening: listening
});
if (listening) {
var
|
javascript
|
{
"resource": ""
}
|
|
q4895
|
train
|
function(obj) {
if (obj == null) return void 0;
return this._byId[obj] ||
|
javascript
|
{
"resource": ""
}
|
|
q4896
|
train
|
function() {
var path = this.decodeFragment(this.location.pathname);
var rootPath =
|
javascript
|
{
"resource": ""
}
|
|
q4897
|
train
|
function() {
var path = this.decodeFragment(
this.location.pathname +
|
javascript
|
{
"resource": ""
}
|
|
q4898
|
train
|
function(fragment) {
if (fragment == null) {
if (this._usePushState || !this._wantsHashChange) {
fragment = this.getPath();
} else {
fragment =
|
javascript
|
{
"resource": ""
}
|
|
q4899
|
respond
|
train
|
function respond () {
let res = this.res
let body = this.body
let code = this.status
if (this.respond === false) return endContext(this)
if (res.headersSent || this._finished != null) return
this.set('server', 'Toa/' + Toa.VERSION)
if (this.config.poweredBy) this.set('x-powered-by', this.config.poweredBy)
// ignore body
if (statuses.empty[code]) {
// strip headers
this.body = null
res.end()
} else if (this.method === 'HEAD') {
if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body))
res.end()
} else if (body == null) {
// status body
this.type = 'text'
body = this.message || String(code)
this.length = Buffer.byteLength(body)
res.end(body)
} else if (typeof body === 'string' || Buffer.isBuffer(body)) {
res.end(body)
} else if
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.