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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
smsapi/smsapi-javascript-client
lib/smsapi.js
SMSAPI
function SMSAPI(options) { options = options || {}; if (options.proxy) this.proxy(options.proxy); else this.proxy(new ProxyHttp({ server: options.server })); var moduleOptions = { proxy: this.proxy() }; // init authentication if (options.oauth) { // overwrite authentication object this.authentication = new AuthenticationOAuth( _.extend({}, moduleOptions, options.oauth) ); this.proxy().setAuth(this.authentication); } else { this.authentication = new AuthenticationSimple(moduleOptions); } // init modules this.points = new Points(moduleOptions); this.profile = new Profile(moduleOptions); this.sender = new Sender(moduleOptions); this.message = new Message(moduleOptions); this.hlr = new Hlr(moduleOptions); this.user = new User(moduleOptions); this.template = new Template(moduleOptions); this.push = new Push(moduleOptions); this.contacts = new Contacts(moduleOptions); /** * @deprecated * @type {Phonebook} */ this.phonebook = new Phonebook(moduleOptions); this.proxy().setAuth(this.authentication); }
javascript
function SMSAPI(options) { options = options || {}; if (options.proxy) this.proxy(options.proxy); else this.proxy(new ProxyHttp({ server: options.server })); var moduleOptions = { proxy: this.proxy() }; // init authentication if (options.oauth) { // overwrite authentication object this.authentication = new AuthenticationOAuth( _.extend({}, moduleOptions, options.oauth) ); this.proxy().setAuth(this.authentication); } else { this.authentication = new AuthenticationSimple(moduleOptions); } // init modules this.points = new Points(moduleOptions); this.profile = new Profile(moduleOptions); this.sender = new Sender(moduleOptions); this.message = new Message(moduleOptions); this.hlr = new Hlr(moduleOptions); this.user = new User(moduleOptions); this.template = new Template(moduleOptions); this.push = new Push(moduleOptions); this.contacts = new Contacts(moduleOptions); /** * @deprecated * @type {Phonebook} */ this.phonebook = new Phonebook(moduleOptions); this.proxy().setAuth(this.authentication); }
[ "function", "SMSAPI", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "proxy", ")", "this", ".", "proxy", "(", "options", ".", "proxy", ")", ";", "else", "this", ".", "proxy", "(", "new", "ProxyHttp", "(", "{", "server", ":", "options", ".", "server", "}", ")", ")", ";", "var", "moduleOptions", "=", "{", "proxy", ":", "this", ".", "proxy", "(", ")", "}", ";", "if", "(", "options", ".", "oauth", ")", "{", "this", ".", "authentication", "=", "new", "AuthenticationOAuth", "(", "_", ".", "extend", "(", "{", "}", ",", "moduleOptions", ",", "options", ".", "oauth", ")", ")", ";", "this", ".", "proxy", "(", ")", ".", "setAuth", "(", "this", ".", "authentication", ")", ";", "}", "else", "{", "this", ".", "authentication", "=", "new", "AuthenticationSimple", "(", "moduleOptions", ")", ";", "}", "this", ".", "points", "=", "new", "Points", "(", "moduleOptions", ")", ";", "this", ".", "profile", "=", "new", "Profile", "(", "moduleOptions", ")", ";", "this", ".", "sender", "=", "new", "Sender", "(", "moduleOptions", ")", ";", "this", ".", "message", "=", "new", "Message", "(", "moduleOptions", ")", ";", "this", ".", "hlr", "=", "new", "Hlr", "(", "moduleOptions", ")", ";", "this", ".", "user", "=", "new", "User", "(", "moduleOptions", ")", ";", "this", ".", "template", "=", "new", "Template", "(", "moduleOptions", ")", ";", "this", ".", "push", "=", "new", "Push", "(", "moduleOptions", ")", ";", "this", ".", "contacts", "=", "new", "Contacts", "(", "moduleOptions", ")", ";", "this", ".", "phonebook", "=", "new", "Phonebook", "(", "moduleOptions", ")", ";", "this", ".", "proxy", "(", ")", ".", "setAuth", "(", "this", ".", "authentication", ")", ";", "}" ]
SMSAPI main class @param {Object} [options] @param {String} [options.server] url to the server @param {Object} [options.oauth] if provided will use oauth, simple auth otherwise @param {String} options.oauth.clientId @param {String} options.oauth.clientSecret @param {String} [options.oauth.grantType] @param {String} [options.oauth.scope] @param {ProxyAbstract} [options.proxy] custom proxy that implements ProxyAbstract @constructor
[ "SMSAPI", "main", "class" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/smsapi.js#L28-L74
train
smsapi/smsapi-javascript-client
lib/authentication-oauth.js
AuthenticationOAuth
function AuthenticationOAuth(options) { AuthenticationAbstract.call(this, options); options = options || {}; this._token = { access: options.accessToken || null }; }
javascript
function AuthenticationOAuth(options) { AuthenticationAbstract.call(this, options); options = options || {}; this._token = { access: options.accessToken || null }; }
[ "function", "AuthenticationOAuth", "(", "options", ")", "{", "AuthenticationAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_token", "=", "{", "access", ":", "options", ".", "accessToken", "||", "null", "}", ";", "}" ]
use oauth for authentication @param {Object} options @param {String} options.accessToken @extends AuthenticationAbstract @constructor
[ "use", "oauth", "for", "authentication" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/authentication-oauth.js#L12-L18
train
smsapi/smsapi-javascript-client
lib/contacts-groups-permissions-get.js
ContactsGroupsPermissionsGet
function ContactsGroupsPermissionsGet(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
javascript
function ContactsGroupsPermissionsGet(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
[ "function", "ContactsGroupsPermissionsGet", "(", "options", ",", "groupId", ",", "username", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_username", "=", "username", ";", "}" ]
get group permissions for user @see http://dev.smsapi.pl/#!/contacts%2Fgroups/get_0 @param {Object} options @param {String} groupId @param {String} username @extends ActionAbstract @constructor
[ "get", "group", "permissions", "for", "user" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-permissions-get.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/contacts-groups-assignments-get.js
ContactsGroupsAssignmentsGet
function ContactsGroupsAssignmentsGet(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsAssignmentsGet(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsAssignmentsGet", "(", "options", ",", "contactId", ",", "groupId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId", ";", "}" ]
get group related to contact @see http://dev.smsapi.pl/#!/contacts/getGroup_0 @param {Object} options @param {String} contactId @param {String} groupId @extends ActionAbstract @constructor
[ "get", "group", "related", "to", "contact" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-assignments-get.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/contacts-groups-assignments-delete.js
ContactsGroupsAssignmentsDelete
function ContactsGroupsAssignmentsDelete(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsAssignmentsDelete(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsAssignmentsDelete", "(", "options", ",", "contactId", ",", "groupId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId", ";", "}" ]
unpin contact from group @see http://dev.smsapi.pl/#!/contacts/unpinContactGroup @param {Object} options @param {String} contactId @param {String} groupId @extends ActionAbstract @constructor
[ "unpin", "contact", "from", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-assignments-delete.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/contacts-groups-members-get.js
ContactsGroupsMembersGet
function ContactsGroupsMembersGet(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsMembersGet(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsMembersGet", "(", "options", ",", "groupId", ",", "contactId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId", ";", "}" ]
check whether contact is in group @see http://dev.smsapi.pl/#!/contacts%2Fgroups/contactsGet @param {Object} options @param {String} groupId @param {String} contactId @extends ActionAbstract @constructor
[ "check", "whether", "contact", "is", "in", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-members-get.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/contacts-groups-members-delete.js
ContactsGroupsMembersDelete
function ContactsGroupsMembersDelete(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsMembersDelete(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsMembersDelete", "(", "options", ",", "groupId", ",", "contactId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId", ";", "}" ]
unpin contact from the group @see http://dev.smsapi.pl/#!/contacts%2Fgroups/contactsDelete @param {Object} options @param {String} groupId @param {String} contactId @extends ActionAbstract @constructor
[ "unpin", "contact", "from", "the", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-members-delete.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/contacts-groups-assignments-add.js
ContactsGroupsAssignmentsAdd
function ContactsGroupsAssignmentsAdd(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsAssignmentsAdd(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsAssignmentsAdd", "(", "options", ",", "contactId", ",", "groupId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId", ";", "}" ]
Assign contact to group @see http://dev.smsapi.pl/#!/contacts/assignGroup @param {Object} options @param {String} contactId @param {String} groupId @extends ActionAbstract @constructor
[ "Assign", "contact", "to", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-assignments-add.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/contacts-groups-members-add.js
ContactsGroupsMembersAdd
function ContactsGroupsMembersAdd(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsMembersAdd(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsMembersAdd", "(", "options", ",", "groupId", ",", "contactId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId", ";", "}" ]
pin contact to the group @see http://dev.smsapi.pl/#!/contacts%2Fgroups/contactsPut @param {Object} options @param {String} groupId @param {String} contactId @extends ActionAbstract @constructor
[ "pin", "contact", "to", "the", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-members-add.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/contacts-groups-permissions-delete.js
ContactsGroupsPermissionsDelete
function ContactsGroupsPermissionsDelete(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
javascript
function ContactsGroupsPermissionsDelete(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
[ "function", "ContactsGroupsPermissionsDelete", "(", "options", ",", "groupId", ",", "username", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_username", "=", "username", ";", "}" ]
delete group permissions for user @see http://dev.smsapi.pl/#!/contacts%2Fgroups/delete_0 @param {Object} options @param {String} groupId @param {String} username @extends ActionAbstract @constructor
[ "delete", "group", "permissions", "for", "user" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-permissions-delete.js#L13-L17
train
smsapi/smsapi-javascript-client
lib/proxy-http.js
ProxyHttp
function ProxyHttp(options) { ProxyAbstract.call(this, options); this._server = options.server || 'https://api.smsapi.pl/'; this._auth = options.auth || null; }
javascript
function ProxyHttp(options) { ProxyAbstract.call(this, options); this._server = options.server || 'https://api.smsapi.pl/'; this._auth = options.auth || null; }
[ "function", "ProxyHttp", "(", "options", ")", "{", "ProxyAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_server", "=", "options", ".", "server", "||", "'https://api.smsapi.pl/'", ";", "this", ".", "_auth", "=", "options", ".", "auth", "||", "null", ";", "}" ]
proxy for http server @param {Object} [options] @param {String} [options.server] url to the server @param {AuthenticationAbstract} [options.auth] authentication object
[ "proxy", "for", "http", "server" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/proxy-http.js#L10-L14
train
smsapi/smsapi-javascript-client
lib/request.js
Request
function Request(options) { options = options || {}; this._server = options.server || ''; this._path = options.path || ''; this._json = options.json || false; this._data = options.data || {}; this._auth = options.auth || null; this._file = options.file || null; this._method = options.method || 'post'; }
javascript
function Request(options) { options = options || {}; this._server = options.server || ''; this._path = options.path || ''; this._json = options.json || false; this._data = options.data || {}; this._auth = options.auth || null; this._file = options.file || null; this._method = options.method || 'post'; }
[ "function", "Request", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_server", "=", "options", ".", "server", "||", "''", ";", "this", ".", "_path", "=", "options", ".", "path", "||", "''", ";", "this", ".", "_json", "=", "options", ".", "json", "||", "false", ";", "this", ".", "_data", "=", "options", ".", "data", "||", "{", "}", ";", "this", ".", "_auth", "=", "options", ".", "auth", "||", "null", ";", "this", ".", "_file", "=", "options", ".", "file", "||", "null", ";", "this", ".", "_method", "=", "options", ".", "method", "||", "'post'", ";", "}" ]
single request to the server @param {Object} [options] @param {String} [options.server] @param {String} [options.path] @param {Boolean} [options.json] @param {Object} [options.data] @param {AuthenticationAbstract} [options.auth] @param {String} [options.file]
[ "single", "request", "to", "the", "server" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/request.js#L16-L25
train
smsapi/smsapi-javascript-client
lib/contacts-groups-permissions-add.js
ContactsGroupsPermissionsAdd
function ContactsGroupsPermissionsAdd(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
javascript
function ContactsGroupsPermissionsAdd(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
[ "function", "ContactsGroupsPermissionsAdd", "(", "options", ",", "groupId", ",", "username", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_username", "=", "username", ";", "}" ]
add permissions for the user @see http://dev.smsapi.pl/#!/contacts%2Fgroups/edit_0 @param {Object} options @param {String} groupId @param {String} username @extends ActionAbstract @constructor
[ "add", "permissions", "for", "the", "user" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-permissions-add.js#L13-L17
train
amuramoto/messenger-node
lib/client/messages/message-creative/index.js
createMessageCreative
function createMessageCreative (message) { return new Promise (async (resolve, reject) => { if (!message) { reject('Valid message object required'); } let request_options = { 'api_version': 'v2.11', 'path': '/me/message_creatives', 'payload': { 'messages': [util.parseMessageProps(message)] } }; try { let response = await this.sendGraphRequest(request_options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function createMessageCreative (message) { return new Promise (async (resolve, reject) => { if (!message) { reject('Valid message object required'); } let request_options = { 'api_version': 'v2.11', 'path': '/me/message_creatives', 'payload': { 'messages': [util.parseMessageProps(message)] } }; try { let response = await this.sendGraphRequest(request_options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "createMessageCreative", "(", "message", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "message", ")", "{", "reject", "(", "'Valid message object required'", ")", ";", "}", "let", "request_options", "=", "{", "'api_version'", ":", "'v2.11'", ",", "'path'", ":", "'/me/message_creatives'", ",", "'payload'", ":", "{", "'messages'", ":", "[", "util", ".", "parseMessageProps", "(", "message", ")", "]", "}", "}", ";", "try", "{", "let", "response", "=", "await", "this", ".", "sendGraphRequest", "(", "request_options", ")", ";", "resolve", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Creates a new message creative. @param {Object} message An object that describes the message to send. @return {Promise<Object>} The API response @memberof Client# @example <caption>Text Message</caption> let message = {'text': 'my text message'}; Client.createMessageCreative(message) .then(res => { console.log(res); // {"message_creative_id": "953434576932424"} }); @example <caption>Template Message</caption> let message = { template_type: 'generic', elements: [ { 'title':'This is a generic template', 'subtitle':'Plus a subtitle!', 'image_url':'https://www.example.com/dog.jpg', 'buttons':[ { 'type':'postback', 'title':'Postback Button', 'payload':'postback_payload' }, { 'type': 'web_url', 'title': 'URL Button', 'url': 'https://www.example.com/' } ] } ] }; Client.createMessageCreative(message) .then(res => { console.log(res); // {"message_creative_id": "953434576932424"} });
[ "Creates", "a", "new", "message", "creative", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/message-creative/index.js#L45-L66
train
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
createCustomLabel
function createCustomLabel (name) { return new Promise (async (resolve, reject) => { if (!name) { reject('name required'); } let options = { 'payload': {'name': name} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function createCustomLabel (name) { return new Promise (async (resolve, reject) => { if (!name) { reject('name required'); } let options = { 'payload': {'name': name} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "createCustomLabel", "(", "name", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "name", ")", "{", "reject", "(", "'name required'", ")", ";", "}", "let", "options", "=", "{", "'payload'", ":", "{", "'name'", ":", "name", "}", "}", ";", "try", "{", "let", "response", "=", "await", "this", ".", "callCustomLabelsApi", "(", "options", ")", ";", "resolve", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Creates a new custom label. @param {String} name The name of the custom label. @return {Promise<Object>} The API response @memberof Client# @example Client.createCustomLabel('my_custom_label') .then(res => { console.log(res); // {"id": "9485676932424"} });
[ "Creates", "a", "new", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L23-L38
train
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
getAllCustomLabels
function getAllCustomLabels () { return new Promise (async (resolve, reject) => { let options = { 'qs': {'fields': 'id,name'} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function getAllCustomLabels () { return new Promise (async (resolve, reject) => { let options = { 'qs': {'fields': 'id,name'} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "getAllCustomLabels", "(", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "options", "=", "{", "'qs'", ":", "{", "'fields'", ":", "'id,name'", "}", "}", ";", "try", "{", "let", "response", "=", "await", "this", ".", "callCustomLabelsApi", "(", "options", ")", ";", "resolve", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Retrieves the list of all custom labels. @return {Promise<Object>} The API response @memberof Client# @example let field = ['name', 'id']; //optional Client.getAllCustomLabels(fields) .then(res => { console.log(res); // { // "data": [ // { "name": "myLabel", "id": "1001200005003"}, // { "name": "myOtherLabel", "id": "1001200005002"} // ], // "paging": { // "cursors": { // "before": "QVFIUmx1WTBpMGpJWXprYzVYaVhabW55dVpyc", // "after": "QVFIUmItNkpTbjVzakxFWGRydzdaVUFNNnNPaU" // } // } // } });
[ "Retrieves", "the", "list", "of", "all", "custom", "labels", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L138-L151
train
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
deleteCustomLabel
function deleteCustomLabel (label_id) { return new Promise (async (resolve, reject) => { if (!label_id) { reject('label_id required'); return; } let options = { 'method': 'DELETE', 'path': '/' + label_id }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function deleteCustomLabel (label_id) { return new Promise (async (resolve, reject) => { if (!label_id) { reject('label_id required'); return; } let options = { 'method': 'DELETE', 'path': '/' + label_id }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "deleteCustomLabel", "(", "label_id", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "label_id", ")", "{", "reject", "(", "'label_id required'", ")", ";", "return", ";", "}", "let", "options", "=", "{", "'method'", ":", "'DELETE'", ",", "'path'", ":", "'/'", "+", "label_id", "}", ";", "try", "{", "let", "response", "=", "await", "this", ".", "callCustomLabelsApi", "(", "options", ")", ";", "resolve", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Deletes a custom label. @param {Integer} label_id The ID of the custom label to delete. @return {Promise<Object>} The API response @memberof Client# @example Client.deleteCustomLabel(094730967209673) .then(res => { console.log(res); // {"success": true} });
[ "Deletes", "a", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L164-L182
train
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
addPsidtoCustomLabel
function addPsidtoCustomLabel (psid, label_id) { return new Promise (async (resolve, reject) => { if (!psid || !label_id) { reject('PSID and label_id required'); return; } let options = { 'path': `/${label_id}/label`, 'payload': {'user': psid} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function addPsidtoCustomLabel (psid, label_id) { return new Promise (async (resolve, reject) => { if (!psid || !label_id) { reject('PSID and label_id required'); return; } let options = { 'path': `/${label_id}/label`, 'payload': {'user': psid} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "addPsidtoCustomLabel", "(", "psid", ",", "label_id", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "psid", "||", "!", "label_id", ")", "{", "reject", "(", "'PSID and label_id required'", ")", ";", "return", ";", "}", "let", "options", "=", "{", "'path'", ":", "`", "${", "label_id", "}", "`", ",", "'payload'", ":", "{", "'user'", ":", "psid", "}", "}", ";", "try", "{", "let", "response", "=", "await", "this", ".", "callCustomLabelsApi", "(", "options", ")", ";", "resolve", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Associates a user's PSID to a custom label. @param {Integer} psid PSID of the user to associate with the custom label. @param {Integer} label_id The ID of a custom label. Created with {@link #createcustomlabel|createCustomLabel()}. @return {Promise<Object>} The API response @memberof Client# @example let psid = 49670354734069743, custom_label_id = 0957209720496743; Client.addPsidtoCustomLabel(psid, custom_label_id) .then(res => { console.log(res); // {"success": true} });
[ "Associates", "a", "user", "s", "PSID", "to", "a", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L198-L215
train
amuramoto/messenger-node
lib/client/index.js
Client
function Client (options) { let GraphRequest = new graphRequest(options); Object.assign( this, GraphRequest, new messages(GraphRequest), new messengerProfile(GraphRequest), new person(GraphRequest), new messengerCode(GraphRequest), new messagingInsights(GraphRequest), new attachment(GraphRequest), new nlp(GraphRequest), new handoverProtocol(GraphRequest) ); }
javascript
function Client (options) { let GraphRequest = new graphRequest(options); Object.assign( this, GraphRequest, new messages(GraphRequest), new messengerProfile(GraphRequest), new person(GraphRequest), new messengerCode(GraphRequest), new messagingInsights(GraphRequest), new attachment(GraphRequest), new nlp(GraphRequest), new handoverProtocol(GraphRequest) ); }
[ "function", "Client", "(", "options", ")", "{", "let", "GraphRequest", "=", "new", "graphRequest", "(", "options", ")", ";", "Object", ".", "assign", "(", "this", ",", "GraphRequest", ",", "new", "messages", "(", "GraphRequest", ")", ",", "new", "messengerProfile", "(", "GraphRequest", ")", ",", "new", "person", "(", "GraphRequest", ")", ",", "new", "messengerCode", "(", "GraphRequest", ")", ",", "new", "messagingInsights", "(", "GraphRequest", ")", ",", "new", "attachment", "(", "GraphRequest", ")", ",", "new", "nlp", "(", "GraphRequest", ")", ",", "new", "handoverProtocol", "(", "GraphRequest", ")", ")", ";", "}" ]
Creates an instance of `Client`, used for sending requests to the Messenger Platform APIs. @constructor @class Client @param {Object} options An object that contains the configuration settings for the `Client`. @param {String} options.page_token A valid Page-scoped access token. @param {String} options.app_token _Optional._ A valid app-scoped access token. Required for ID Matching. @param {String} options.graph_api_version _Optional._ The version of the Graph API to target for all API requests. Defaults to latest. Must be in the format `v2.11`. @returns {Client} @example const Messenger = require('messenger-node'); let options = { 'page_token': 'sd0we98h248n2g40gh4g80h32', 'app_token': 'ih908wh084ggh423940hg934g358h0358hg3', //optional 'api_version': 'v2.9' //optional } const Client = new Messenger.Client(options);
[ "Creates", "an", "instance", "of", "Client", "used", "for", "sending", "requests", "to", "the", "Messenger", "Platform", "APIs", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/index.js#L29-L45
train
amuramoto/messenger-node
lib/client/messages/broadcast/index.js
startBroadcastReachEstimation
function startBroadcastReachEstimation (custom_label_id) { return new Promise (async (resolve, reject) => { let options = { 'custom_label_id': custom_label_id || true }; try { let response = await this.callBroadcastApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function startBroadcastReachEstimation (custom_label_id) { return new Promise (async (resolve, reject) => { let options = { 'custom_label_id': custom_label_id || true }; try { let response = await this.callBroadcastApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "startBroadcastReachEstimation", "(", "custom_label_id", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "options", "=", "{", "'custom_label_id'", ":", "custom_label_id", "||", "true", "}", ";", "try", "{", "let", "response", "=", "await", "this", ".", "callBroadcastApi", "(", "options", ")", ";", "resolve", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Start a reach estimation for the number of people that will be reached by a broadcast to all users or to users associated with a custom label. @param {Integer} custom_label_id _Optional._ The ID of a custom label targeted by the broadcast. Created by calling {@link #createcustomlabel|Client.createCustomLabel()}. @return {Promise<Object>} The API Response @memberof Client# @example let custom_label_id = 3467390467035645 //optional Client.startBroadcastReachEstimation(custom_label_id) .then(res => { console.log(res); // {"reach_estimation_id": "9485676932424"} });
[ "Start", "a", "reach", "estimation", "for", "the", "number", "of", "people", "that", "will", "be", "reached", "by", "a", "broadcast", "to", "all", "users", "or", "to", "users", "associated", "with", "a", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/broadcast/index.js#L57-L69
train
cdiggins/myna-parser
tools/myna_markdown_to_html.js
startTag
function startTag(tag, attr) { let attrStr = ""; if (attr) { attrStr = " " + Object.keys(attr).map(function(k) { return k + ' = "' + attr[k] + '"'; }).join(" "); } return "<" + tag + attrStr + ">"; }
javascript
function startTag(tag, attr) { let attrStr = ""; if (attr) { attrStr = " " + Object.keys(attr).map(function(k) { return k + ' = "' + attr[k] + '"'; }).join(" "); } return "<" + tag + attrStr + ">"; }
[ "function", "startTag", "(", "tag", ",", "attr", ")", "{", "let", "attrStr", "=", "\"\"", ";", "if", "(", "attr", ")", "{", "attrStr", "=", "\" \"", "+", "Object", ".", "keys", "(", "attr", ")", ".", "map", "(", "function", "(", "k", ")", "{", "return", "k", "+", "' = \"'", "+", "attr", "[", "k", "]", "+", "'\"'", ";", "}", ")", ".", "join", "(", "\" \"", ")", ";", "}", "return", "\"<\"", "+", "tag", "+", "attrStr", "+", "\">\"", ";", "}" ]
Returns the HTML for a start tag
[ "Returns", "the", "HTML", "for", "a", "start", "tag" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L7-L15
train
cdiggins/myna-parser
tools/myna_markdown_to_html.js
mdAstToHtml
function mdAstToHtml(ast, lines) { if (lines == undefined) lines = []; // Adds each element of the array as markdown function addArray(ast) { for (let child of ast) mdAstToHtml(child, lines); return lines; } // Adds tagged content function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; } function addLink(url, astOrText) { lines.push(startTag('a', { href:url })); if (astOrText) { if (astOrText.children) addArray(astOrText.children); else lines.push(astOrText); } lines.push(endTag('a')) ; return lines; } function addImg(url) { lines.push(startTag('img', { src:url })); lines.push(endTag('img')) ; return lines; } switch (ast.name) { case "heading": { let headingLevel = ast.children[0]; let restOfLine = ast.children[1]; let h = headingLevel.allText.length; switch (h) { case 1: return addTag("h1", restOfLine, true); case 2: return addTag("h2", restOfLine, true); case 3: return addTag("h3", restOfLine, true); case 4: return addTag("h4", restOfLine, true); case 5: return addTag("h5", restOfLine, true); case 6: return addTag("h6", restOfLine, true); default: throw "Heading level must be from 1 to 6" } } case "paragraph": return addTag("p", ast.children, true); case "unorderedList": return addTag("ul", ast.children, true); case "orderedList": return addTag("ol", ast.children, true); case "unorderedListItem": return addTag("li", ast.children, true); case "orderedListItem": return addTag("li", ast.children, true); case "inlineUrl": return addLink(ast.allText, ast.allText); case "bold": return addTag("b", ast.children); case "italic": return addTag("i", ast.children); case "code": return addTag("code", ast.children); case "codeBlock": return addTag("pre", ast.children); case "quote": return addTag("blockquote", ast.children, true); case "link": return addLink(ast.children[1].allText, ast.children[0]); case "image": return addImg(ast.children[0]); default: if (ast.isLeaf) lines.push(ast.allText); else ast.children.forEach(function(c) { mdAstToHtml(c, lines); }); } return lines; }
javascript
function mdAstToHtml(ast, lines) { if (lines == undefined) lines = []; // Adds each element of the array as markdown function addArray(ast) { for (let child of ast) mdAstToHtml(child, lines); return lines; } // Adds tagged content function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; } function addLink(url, astOrText) { lines.push(startTag('a', { href:url })); if (astOrText) { if (astOrText.children) addArray(astOrText.children); else lines.push(astOrText); } lines.push(endTag('a')) ; return lines; } function addImg(url) { lines.push(startTag('img', { src:url })); lines.push(endTag('img')) ; return lines; } switch (ast.name) { case "heading": { let headingLevel = ast.children[0]; let restOfLine = ast.children[1]; let h = headingLevel.allText.length; switch (h) { case 1: return addTag("h1", restOfLine, true); case 2: return addTag("h2", restOfLine, true); case 3: return addTag("h3", restOfLine, true); case 4: return addTag("h4", restOfLine, true); case 5: return addTag("h5", restOfLine, true); case 6: return addTag("h6", restOfLine, true); default: throw "Heading level must be from 1 to 6" } } case "paragraph": return addTag("p", ast.children, true); case "unorderedList": return addTag("ul", ast.children, true); case "orderedList": return addTag("ol", ast.children, true); case "unorderedListItem": return addTag("li", ast.children, true); case "orderedListItem": return addTag("li", ast.children, true); case "inlineUrl": return addLink(ast.allText, ast.allText); case "bold": return addTag("b", ast.children); case "italic": return addTag("i", ast.children); case "code": return addTag("code", ast.children); case "codeBlock": return addTag("pre", ast.children); case "quote": return addTag("blockquote", ast.children, true); case "link": return addLink(ast.children[1].allText, ast.children[0]); case "image": return addImg(ast.children[0]); default: if (ast.isLeaf) lines.push(ast.allText); else ast.children.forEach(function(c) { mdAstToHtml(c, lines); }); } return lines; }
[ "function", "mdAstToHtml", "(", "ast", ",", "lines", ")", "{", "if", "(", "lines", "==", "undefined", ")", "lines", "=", "[", "]", ";", "function", "addArray", "(", "ast", ")", "{", "for", "(", "let", "child", "of", "ast", ")", "mdAstToHtml", "(", "child", ",", "lines", ")", ";", "return", "lines", ";", "}", "function", "addTag", "(", "tag", ",", "ast", ",", "newLine", ")", "{", "lines", ".", "push", "(", "startTag", "(", "tag", ")", ")", ";", "if", "(", "ast", "instanceof", "Array", ")", "addArray", "(", "ast", ")", ";", "else", "mdAstToHtml", "(", "ast", ",", "lines", ")", ";", "lines", ".", "push", "(", "endTag", "(", "tag", ")", ")", ";", "if", "(", "newLine", ")", "lines", ".", "push", "(", "'\\r\\n'", ")", ";", "\\r", "}", "\\n", "return", "lines", ";", "function", "addLink", "(", "url", ",", "astOrText", ")", "{", "lines", ".", "push", "(", "startTag", "(", "'a'", ",", "{", "href", ":", "url", "}", ")", ")", ";", "if", "(", "astOrText", ")", "{", "if", "(", "astOrText", ".", "children", ")", "addArray", "(", "astOrText", ".", "children", ")", ";", "else", "lines", ".", "push", "(", "astOrText", ")", ";", "}", "lines", ".", "push", "(", "endTag", "(", "'a'", ")", ")", ";", "return", "lines", ";", "}", "function", "addImg", "(", "url", ")", "{", "lines", ".", "push", "(", "startTag", "(", "'img'", ",", "{", "src", ":", "url", "}", ")", ")", ";", "lines", ".", "push", "(", "endTag", "(", "'img'", ")", ")", ";", "return", "lines", ";", "}", "}" ]
Returns HTML from a MarkDown AST
[ "Returns", "HTML", "from", "a", "MarkDown", "AST" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L23-L117
train
cdiggins/myna-parser
tools/myna_markdown_to_html.js
addTag
function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; }
javascript
function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; }
[ "function", "addTag", "(", "tag", ",", "ast", ",", "newLine", ")", "{", "lines", ".", "push", "(", "startTag", "(", "tag", ")", ")", ";", "if", "(", "ast", "instanceof", "Array", ")", "addArray", "(", "ast", ")", ";", "else", "mdAstToHtml", "(", "ast", ",", "lines", ")", ";", "lines", ".", "push", "(", "endTag", "(", "tag", ")", ")", ";", "if", "(", "newLine", ")", "lines", ".", "push", "(", "'\\r\\n'", ")", ";", "\\r", "}" ]
Adds tagged content
[ "Adds", "tagged", "content" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L35-L45
train
cdiggins/myna-parser
tools/myna_markdown_to_html.js
mdToHtml
function mdToHtml(input) { let rule = myna.allRules['markdown.document']; let ast = myna.parse(rule, input); return mdAstToHtml(ast, []).join(""); }
javascript
function mdToHtml(input) { let rule = myna.allRules['markdown.document']; let ast = myna.parse(rule, input); return mdAstToHtml(ast, []).join(""); }
[ "function", "mdToHtml", "(", "input", ")", "{", "let", "rule", "=", "myna", ".", "allRules", "[", "'markdown.document'", "]", ";", "let", "ast", "=", "myna", ".", "parse", "(", "rule", ",", "input", ")", ";", "return", "mdAstToHtml", "(", "ast", ",", "[", "]", ")", ".", "join", "(", "\"\"", ")", ";", "}" ]
Converts Markdown text to HTML
[ "Converts", "Markdown", "text", "to", "HTML" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L120-L124
train
cdiggins/myna-parser
myna.js
function () { var r = this.cloneImplementation(); if (typeof (r) !== typeof (this)) throw new Error("Error in implementation of cloneImplementation: not returning object of correct type"); r.name = this.name; r.grammarName = this.grammarName; r._createAstNode = this._createAstNode; return r; }
javascript
function () { var r = this.cloneImplementation(); if (typeof (r) !== typeof (this)) throw new Error("Error in implementation of cloneImplementation: not returning object of correct type"); r.name = this.name; r.grammarName = this.grammarName; r._createAstNode = this._createAstNode; return r; }
[ "function", "(", ")", "{", "var", "r", "=", "this", ".", "cloneImplementation", "(", ")", ";", "if", "(", "typeof", "(", "r", ")", "!==", "typeof", "(", "this", ")", ")", "throw", "new", "Error", "(", "\"Error in implementation of cloneImplementation: not returning object of correct type\"", ")", ";", "r", ".", "name", "=", "this", ".", "name", ";", "r", ".", "grammarName", "=", "this", ".", "grammarName", ";", "r", ".", "_createAstNode", "=", "this", ".", "_createAstNode", ";", "return", "r", ";", "}" ]
Returns a copy of this rule with all fields copied.
[ "Returns", "a", "copy", "of", "this", "rule", "with", "all", "fields", "copied", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L298-L306
train
cdiggins/myna-parser
myna.js
function () { if (this.min == 0 && this.max == 1) return this.firstChild.toString() + "?"; if (this.min == 0 && this.max == Infinity) return this.firstChild.toString() + "*"; if (this.min == 1 && this.max == Infinity) return this.firstChild.toString() + "+"; return this.firstChild.toString() + "{" + this.min + "," + this.max + "}"; }
javascript
function () { if (this.min == 0 && this.max == 1) return this.firstChild.toString() + "?"; if (this.min == 0 && this.max == Infinity) return this.firstChild.toString() + "*"; if (this.min == 1 && this.max == Infinity) return this.firstChild.toString() + "+"; return this.firstChild.toString() + "{" + this.min + "," + this.max + "}"; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "min", "==", "0", "&&", "this", ".", "max", "==", "1", ")", "return", "this", ".", "firstChild", ".", "toString", "(", ")", "+", "\"?\"", ";", "if", "(", "this", ".", "min", "==", "0", "&&", "this", ".", "max", "==", "Infinity", ")", "return", "this", ".", "firstChild", ".", "toString", "(", ")", "+", "\"*\"", ";", "if", "(", "this", ".", "min", "==", "1", "&&", "this", ".", "max", "==", "Infinity", ")", "return", "this", ".", "firstChild", ".", "toString", "(", ")", "+", "\"+\"", ";", "return", "this", ".", "firstChild", ".", "toString", "(", ")", "+", "\"{\"", "+", "this", ".", "min", "+", "\",\"", "+", "this", ".", "max", "+", "\"}\"", ";", "}" ]
Used for creating a human readable definition of the grammar.
[ "Used", "for", "creating", "a", "human", "readable", "definition", "of", "the", "grammar", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L654-L662
train
cdiggins/myna-parser
myna.js
seq
function seq() { var rules = []; for (var _i = 0; _i < arguments.length; _i++) { rules[_i - 0] = arguments[_i]; } var rs = rules.map(RuleTypeToRule); if (rs.length == 0) throw new Error("At least one rule is expected when calling `seq`"); if (rs.length == 1) return rs[0]; var rule1 = rs[0]; var rule2 = seq.apply(void 0, rs.slice(1)); if (rule1.nonAdvancing && rule2 instanceof Advance) return new AdvanceIf(rule1); else return new Sequence(rule1, rule2); }
javascript
function seq() { var rules = []; for (var _i = 0; _i < arguments.length; _i++) { rules[_i - 0] = arguments[_i]; } var rs = rules.map(RuleTypeToRule); if (rs.length == 0) throw new Error("At least one rule is expected when calling `seq`"); if (rs.length == 1) return rs[0]; var rule1 = rs[0]; var rule2 = seq.apply(void 0, rs.slice(1)); if (rule1.nonAdvancing && rule2 instanceof Advance) return new AdvanceIf(rule1); else return new Sequence(rule1, rule2); }
[ "function", "seq", "(", ")", "{", "var", "rules", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "rules", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i", "]", ";", "}", "var", "rs", "=", "rules", ".", "map", "(", "RuleTypeToRule", ")", ";", "if", "(", "rs", ".", "length", "==", "0", ")", "throw", "new", "Error", "(", "\"At least one rule is expected when calling `seq`\"", ")", ";", "if", "(", "rs", ".", "length", "==", "1", ")", "return", "rs", "[", "0", "]", ";", "var", "rule1", "=", "rs", "[", "0", "]", ";", "var", "rule2", "=", "seq", ".", "apply", "(", "void", "0", ",", "rs", ".", "slice", "(", "1", ")", ")", ";", "if", "(", "rule1", ".", "nonAdvancing", "&&", "rule2", "instanceof", "Advance", ")", "return", "new", "AdvanceIf", "(", "rule1", ")", ";", "else", "return", "new", "Sequence", "(", "rule1", ",", "rule2", ")", ";", "}" ]
Creates a rule that matches a series of rules in order, and succeeds if they all do
[ "Creates", "a", "rule", "that", "matches", "a", "series", "of", "rules", "in", "order", "and", "succeeds", "if", "they", "all", "do" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1012-L1028
train
cdiggins/myna-parser
myna.js
quantified
function quantified(rule, min, max) { if (min === void 0) { min = 0; } if (max === void 0) { max = Infinity; } if (min === 0 && max === 1) return new Optional(RuleTypeToRule(rule)); else return new Quantified(RuleTypeToRule(rule), min, max); }
javascript
function quantified(rule, min, max) { if (min === void 0) { min = 0; } if (max === void 0) { max = Infinity; } if (min === 0 && max === 1) return new Optional(RuleTypeToRule(rule)); else return new Quantified(RuleTypeToRule(rule), min, max); }
[ "function", "quantified", "(", "rule", ",", "min", ",", "max", ")", "{", "if", "(", "min", "===", "void", "0", ")", "{", "min", "=", "0", ";", "}", "if", "(", "max", "===", "void", "0", ")", "{", "max", "=", "Infinity", ";", "}", "if", "(", "min", "===", "0", "&&", "max", "===", "1", ")", "return", "new", "Optional", "(", "RuleTypeToRule", "(", "rule", ")", ")", ";", "else", "return", "new", "Quantified", "(", "RuleTypeToRule", "(", "rule", ")", ",", "min", ",", "max", ")", ";", "}" ]
Attempts to apply a rule between min and max number of times inclusive. If the maximum is set to Infinity, it will attempt to match as many times as it can, but throw an exception if the parser does not advance
[ "Attempts", "to", "apply", "a", "rule", "between", "min", "and", "max", "number", "of", "times", "inclusive", ".", "If", "the", "maximum", "is", "set", "to", "Infinity", "it", "will", "attempt", "to", "match", "as", "many", "times", "as", "it", "can", "but", "throw", "an", "exception", "if", "the", "parser", "does", "not", "advance" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1063-L1070
train
cdiggins/myna-parser
myna.js
log
function log(msg) { if (msg === void 0) { msg = ""; } return action(function (p) { console.log(msg); }).setType("log"); }
javascript
function log(msg) { if (msg === void 0) { msg = ""; } return action(function (p) { console.log(msg); }).setType("log"); }
[ "function", "log", "(", "msg", ")", "{", "if", "(", "msg", "===", "void", "0", ")", "{", "msg", "=", "\"\"", ";", "}", "return", "action", "(", "function", "(", "p", ")", "{", "console", ".", "log", "(", "msg", ")", ";", "}", ")", ".", "setType", "(", "\"log\"", ")", ";", "}" ]
Logs a message as an action
[ "Logs", "a", "message", "as", "an", "action" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1147-L1150
train
cdiggins/myna-parser
myna.js
guardedSeq
function guardedSeq(condition) { var rules = []; for (var _i = 1; _i < arguments.length; _i++) { rules[_i - 1] = arguments[_i]; } return seq(condition, seq.apply(void 0, rules.map(function (r) { return assert(r); }))).setType("guardedSeq"); }
javascript
function guardedSeq(condition) { var rules = []; for (var _i = 1; _i < arguments.length; _i++) { rules[_i - 1] = arguments[_i]; } return seq(condition, seq.apply(void 0, rules.map(function (r) { return assert(r); }))).setType("guardedSeq"); }
[ "function", "guardedSeq", "(", "condition", ")", "{", "var", "rules", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "1", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "rules", "[", "_i", "-", "1", "]", "=", "arguments", "[", "_i", "]", ";", "}", "return", "seq", "(", "condition", ",", "seq", ".", "apply", "(", "void", "0", ",", "rules", ".", "map", "(", "function", "(", "r", ")", "{", "return", "assert", "(", "r", ")", ";", "}", ")", ")", ")", ".", "setType", "(", "\"guardedSeq\"", ")", ";", "}" ]
If first part of a guarded sequence passes then each subsequent rule must pass as well otherwise an exception occurs. This helps create parsers that fail fast, and thus provide better feedback for badly formed input.
[ "If", "first", "part", "of", "a", "guarded", "sequence", "passes", "then", "each", "subsequent", "rule", "must", "pass", "as", "well", "otherwise", "an", "exception", "occurs", ".", "This", "helps", "create", "parsers", "that", "fail", "fast", "and", "thus", "provide", "better", "feedback", "for", "badly", "formed", "input", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1167-L1173
train
cdiggins/myna-parser
myna.js
keywords
function keywords() { var words = []; for (var _i = 0; _i < arguments.length; _i++) { words[_i - 0] = arguments[_i]; } return choice.apply(void 0, words.map(keyword)); }
javascript
function keywords() { var words = []; for (var _i = 0; _i < arguments.length; _i++) { words[_i - 0] = arguments[_i]; } return choice.apply(void 0, words.map(keyword)); }
[ "function", "keywords", "(", ")", "{", "var", "words", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "words", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i", "]", ";", "}", "return", "choice", ".", "apply", "(", "void", "0", ",", "words", ".", "map", "(", "keyword", ")", ")", ";", "}" ]
Chooses one of a a list of identifiers
[ "Chooses", "one", "of", "a", "a", "list", "of", "identifiers" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1206-L1212
train
cdiggins/myna-parser
myna.js
parse
function parse(r, s) { var p = new ParseState(s, 0, []); if (!(r instanceof AstRule)) r = r.ast; if (!r.parser(p)) return null; return p && p.nodes ? p.nodes[0] : null; }
javascript
function parse(r, s) { var p = new ParseState(s, 0, []); if (!(r instanceof AstRule)) r = r.ast; if (!r.parser(p)) return null; return p && p.nodes ? p.nodes[0] : null; }
[ "function", "parse", "(", "r", ",", "s", ")", "{", "var", "p", "=", "new", "ParseState", "(", "s", ",", "0", ",", "[", "]", ")", ";", "if", "(", "!", "(", "r", "instanceof", "AstRule", ")", ")", "r", "=", "r", ".", "ast", ";", "if", "(", "!", "r", ".", "parser", "(", "p", ")", ")", "return", "null", ";", "return", "p", "&&", "p", ".", "nodes", "?", "p", ".", "nodes", "[", "0", "]", ":", "null", ";", "}" ]
Returns the root node of the abstract syntax tree created by parsing the rule.
[ "Returns", "the", "root", "node", "of", "the", "abstract", "syntax", "tree", "created", "by", "parsing", "the", "rule", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1272-L1279
train
cdiggins/myna-parser
myna.js
allGrammarRules
function allGrammarRules() { return Object.keys(Myna.allRules).sort().map(function (k) { return Myna.allRules[k]; }); }
javascript
function allGrammarRules() { return Object.keys(Myna.allRules).sort().map(function (k) { return Myna.allRules[k]; }); }
[ "function", "allGrammarRules", "(", ")", "{", "return", "Object", ".", "keys", "(", "Myna", ".", "allRules", ")", ".", "sort", "(", ")", ".", "map", "(", "function", "(", "k", ")", "{", "return", "Myna", ".", "allRules", "[", "k", "]", ";", "}", ")", ";", "}" ]
Returns all rules as an array sorted by name.
[ "Returns", "all", "rules", "as", "an", "array", "sorted", "by", "name", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1296-L1298
train
cdiggins/myna-parser
myna.js
grammarToString
function grammarToString(grammarName) { return grammarRules(grammarName).map(function (r) { return r.fullName + " <- " + r.definition; }).join('\n'); }
javascript
function grammarToString(grammarName) { return grammarRules(grammarName).map(function (r) { return r.fullName + " <- " + r.definition; }).join('\n'); }
[ "function", "grammarToString", "(", "grammarName", ")", "{", "return", "grammarRules", "(", "grammarName", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "r", ".", "fullName", "+", "\" <- \"", "+", "r", ".", "definition", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Creates a string representation of a grammar
[ "Creates", "a", "string", "representation", "of", "a", "grammar" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1306-L1308
train
cdiggins/myna-parser
myna.js
astSchemaToString
function astSchemaToString(grammarName) { return grammarAstRules(grammarName).map(function (r) { return r.name + " <- " + r.astRuleDefn(); }).join('\n'); }
javascript
function astSchemaToString(grammarName) { return grammarAstRules(grammarName).map(function (r) { return r.name + " <- " + r.astRuleDefn(); }).join('\n'); }
[ "function", "astSchemaToString", "(", "grammarName", ")", "{", "return", "grammarAstRules", "(", "grammarName", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "r", ".", "name", "+", "\" <- \"", "+", "r", ".", "astRuleDefn", "(", ")", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Creates a string representation of the AST schema generated by parsing the grammar
[ "Creates", "a", "string", "representation", "of", "the", "AST", "schema", "generated", "by", "parsing", "the", "grammar" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1311-L1313
train
cdiggins/myna-parser
myna.js
registerGrammar
function registerGrammar(grammarName, grammar, defaultRule) { for (var k in grammar) { if (grammar[k] instanceof Rule) { var rule = grammar[k]; rule.setName(grammarName, k); Myna.allRules[rule.fullName] = rule; } } Myna.grammars[grammarName] = grammar; if (defaultRule) { Myna.parsers[grammarName] = function (text) { return parse(defaultRule, text); }; } return grammar; }
javascript
function registerGrammar(grammarName, grammar, defaultRule) { for (var k in grammar) { if (grammar[k] instanceof Rule) { var rule = grammar[k]; rule.setName(grammarName, k); Myna.allRules[rule.fullName] = rule; } } Myna.grammars[grammarName] = grammar; if (defaultRule) { Myna.parsers[grammarName] = function (text) { return parse(defaultRule, text); }; } return grammar; }
[ "function", "registerGrammar", "(", "grammarName", ",", "grammar", ",", "defaultRule", ")", "{", "for", "(", "var", "k", "in", "grammar", ")", "{", "if", "(", "grammar", "[", "k", "]", "instanceof", "Rule", ")", "{", "var", "rule", "=", "grammar", "[", "k", "]", ";", "rule", ".", "setName", "(", "grammarName", ",", "k", ")", ";", "Myna", ".", "allRules", "[", "rule", ".", "fullName", "]", "=", "rule", ";", "}", "}", "Myna", ".", "grammars", "[", "grammarName", "]", "=", "grammar", ";", "if", "(", "defaultRule", ")", "{", "Myna", ".", "parsers", "[", "grammarName", "]", "=", "function", "(", "text", ")", "{", "return", "parse", "(", "defaultRule", ",", "text", ")", ";", "}", ";", "}", "return", "grammar", ";", "}" ]
Initializes and register a grammar object and all of the rules. Sets names for all of the rules from the name of the field it is associated with combined with the name of the grammar. Each rule is stored in Myna.rules and each grammar is stored in Myna.grammars.
[ "Initializes", "and", "register", "a", "grammar", "object", "and", "all", "of", "the", "rules", ".", "Sets", "names", "for", "all", "of", "the", "rules", "from", "the", "name", "of", "the", "field", "it", "is", "associated", "with", "combined", "with", "the", "name", "of", "the", "grammar", ".", "Each", "rule", "is", "stored", "in", "Myna", ".", "rules", "and", "each", "grammar", "is", "stored", "in", "Myna", ".", "grammars", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1318-L1331
train
cdiggins/myna-parser
myna.js
RuleTypeToRule
function RuleTypeToRule(rule) { if (rule instanceof Rule) return rule; if (typeof (rule) === "string") return text(rule); if (typeof (rule) === "boolean") return rule ? Myna.truePredicate : Myna.falsePredicate; throw new Error("Invalid rule type: " + rule); }
javascript
function RuleTypeToRule(rule) { if (rule instanceof Rule) return rule; if (typeof (rule) === "string") return text(rule); if (typeof (rule) === "boolean") return rule ? Myna.truePredicate : Myna.falsePredicate; throw new Error("Invalid rule type: " + rule); }
[ "function", "RuleTypeToRule", "(", "rule", ")", "{", "if", "(", "rule", "instanceof", "Rule", ")", "return", "rule", ";", "if", "(", "typeof", "(", "rule", ")", "===", "\"string\"", ")", "return", "text", "(", "rule", ")", ";", "if", "(", "typeof", "(", "rule", ")", "===", "\"boolean\"", ")", "return", "rule", "?", "Myna", ".", "truePredicate", ":", "Myna", ".", "falsePredicate", ";", "throw", "new", "Error", "(", "\"Invalid rule type: \"", "+", "rule", ")", ";", "}" ]
Given a RuleType returns an instance of a Rule.
[ "Given", "a", "RuleType", "returns", "an", "instance", "of", "a", "Rule", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1342-L1350
train
cdiggins/myna-parser
grammars/grammar_arithmetic.js
CreateArithmeticGrammar
function CreateArithmeticGrammar(myna) { // Setup a shorthand for the Myna parsing library object let m = myna; // Construct a grammar let g = new function() { // These are helper rules, they do not create nodes in the parse tree. this.fraction = m.seq(".", m.digit.zeroOrMore); this.plusOrMinus = m.char("+-"); this.exponent = m.seq(m.char("eE"), this.plusOrMinus.opt, m.digits); this.comma = m.text(",").ws; // Using a lazy evaluation rule to allow recursive rule definitions let _this = this; this.expr = m.delay(function() { return _this.sum; }); // The following rules create nodes in the abstract syntax tree this.number = m.seq(m.integer, this.fraction.opt, this.exponent.opt).ast; this.parenExpr = m.parenthesized(this.expr.ws).ast; this.leafExpr = m.choice(this.parenExpr, this.number.ws); this.prefixOp = this.plusOrMinus.ast; this.prefixExpr = m.seq(this.prefixOp.ws.zeroOrMore, this.leafExpr).ast; this.divExpr = m.seq(m.char("/").ws, this.prefixExpr).ast; this.mulExpr = m.seq(m.char("*").ws, this.prefixExpr).ast; this.product = m.seq(this.prefixExpr.ws, this.mulExpr.or(this.divExpr).zeroOrMore).ast; this.subExpr = m.seq(m.char("-").ws, this.product).ast; this.addExpr = m.seq(m.char("+").ws, this.product).ast; this.sum = m.seq(this.product, this.addExpr.or(this.subExpr).zeroOrMore).ast; }; // Register the grammar, providing a name and the default parse rule return myna.registerGrammar("arithmetic", g, g.expr); }
javascript
function CreateArithmeticGrammar(myna) { // Setup a shorthand for the Myna parsing library object let m = myna; // Construct a grammar let g = new function() { // These are helper rules, they do not create nodes in the parse tree. this.fraction = m.seq(".", m.digit.zeroOrMore); this.plusOrMinus = m.char("+-"); this.exponent = m.seq(m.char("eE"), this.plusOrMinus.opt, m.digits); this.comma = m.text(",").ws; // Using a lazy evaluation rule to allow recursive rule definitions let _this = this; this.expr = m.delay(function() { return _this.sum; }); // The following rules create nodes in the abstract syntax tree this.number = m.seq(m.integer, this.fraction.opt, this.exponent.opt).ast; this.parenExpr = m.parenthesized(this.expr.ws).ast; this.leafExpr = m.choice(this.parenExpr, this.number.ws); this.prefixOp = this.plusOrMinus.ast; this.prefixExpr = m.seq(this.prefixOp.ws.zeroOrMore, this.leafExpr).ast; this.divExpr = m.seq(m.char("/").ws, this.prefixExpr).ast; this.mulExpr = m.seq(m.char("*").ws, this.prefixExpr).ast; this.product = m.seq(this.prefixExpr.ws, this.mulExpr.or(this.divExpr).zeroOrMore).ast; this.subExpr = m.seq(m.char("-").ws, this.product).ast; this.addExpr = m.seq(m.char("+").ws, this.product).ast; this.sum = m.seq(this.product, this.addExpr.or(this.subExpr).zeroOrMore).ast; }; // Register the grammar, providing a name and the default parse rule return myna.registerGrammar("arithmetic", g, g.expr); }
[ "function", "CreateArithmeticGrammar", "(", "myna", ")", "{", "let", "m", "=", "myna", ";", "let", "g", "=", "new", "function", "(", ")", "{", "this", ".", "fraction", "=", "m", ".", "seq", "(", "\".\"", ",", "m", ".", "digit", ".", "zeroOrMore", ")", ";", "this", ".", "plusOrMinus", "=", "m", ".", "char", "(", "\"+-\"", ")", ";", "this", ".", "exponent", "=", "m", ".", "seq", "(", "m", ".", "char", "(", "\"eE\"", ")", ",", "this", ".", "plusOrMinus", ".", "opt", ",", "m", ".", "digits", ")", ";", "this", ".", "comma", "=", "m", ".", "text", "(", "\",\"", ")", ".", "ws", ";", "let", "_this", "=", "this", ";", "this", ".", "expr", "=", "m", ".", "delay", "(", "function", "(", ")", "{", "return", "_this", ".", "sum", ";", "}", ")", ";", "this", ".", "number", "=", "m", ".", "seq", "(", "m", ".", "integer", ",", "this", ".", "fraction", ".", "opt", ",", "this", ".", "exponent", ".", "opt", ")", ".", "ast", ";", "this", ".", "parenExpr", "=", "m", ".", "parenthesized", "(", "this", ".", "expr", ".", "ws", ")", ".", "ast", ";", "this", ".", "leafExpr", "=", "m", ".", "choice", "(", "this", ".", "parenExpr", ",", "this", ".", "number", ".", "ws", ")", ";", "this", ".", "prefixOp", "=", "this", ".", "plusOrMinus", ".", "ast", ";", "this", ".", "prefixExpr", "=", "m", ".", "seq", "(", "this", ".", "prefixOp", ".", "ws", ".", "zeroOrMore", ",", "this", ".", "leafExpr", ")", ".", "ast", ";", "this", ".", "divExpr", "=", "m", ".", "seq", "(", "m", ".", "char", "(", "\"/\"", ")", ".", "ws", ",", "this", ".", "prefixExpr", ")", ".", "ast", ";", "this", ".", "mulExpr", "=", "m", ".", "seq", "(", "m", ".", "char", "(", "\"*\"", ")", ".", "ws", ",", "this", ".", "prefixExpr", ")", ".", "ast", ";", "this", ".", "product", "=", "m", ".", "seq", "(", "this", ".", "prefixExpr", ".", "ws", ",", "this", ".", "mulExpr", ".", "or", "(", "this", ".", "divExpr", ")", ".", "zeroOrMore", ")", ".", "ast", ";", "this", ".", "subExpr", "=", "m", ".", "seq", "(", "m", ".", "char", "(", "\"-\"", ")", ".", "ws", ",", "this", ".", "product", ")", ".", "ast", ";", "this", ".", "addExpr", "=", "m", ".", "seq", "(", "m", ".", "char", "(", "\"+\"", ")", ".", "ws", ",", "this", ".", "product", ")", ".", "ast", ";", "this", ".", "sum", "=", "m", ".", "seq", "(", "this", ".", "product", ",", "this", ".", "addExpr", ".", "or", "(", "this", ".", "subExpr", ")", ".", "zeroOrMore", ")", ".", "ast", ";", "}", ";", "return", "myna", ".", "registerGrammar", "(", "\"arithmetic\"", ",", "g", ",", "g", ".", "expr", ")", ";", "}" ]
Defines a grammar for basic arithmetic
[ "Defines", "a", "grammar", "for", "basic", "arithmetic" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/grammars/grammar_arithmetic.js#L4-L38
train
cdiggins/myna-parser
tools/myna_mustache_expander.js
mergeObjects
function mergeObjects(a, b) { var r = { }; for (var k in a) r[k] = a[k]; for (var k in b) r[k] = b[k]; return r; }
javascript
function mergeObjects(a, b) { var r = { }; for (var k in a) r[k] = a[k]; for (var k in b) r[k] = b[k]; return r; }
[ "function", "mergeObjects", "(", "a", ",", "b", ")", "{", "var", "r", "=", "{", "}", ";", "for", "(", "var", "k", "in", "a", ")", "r", "[", "k", "]", "=", "a", "[", "k", "]", ";", "for", "(", "var", "k", "in", "b", ")", "r", "[", "k", "]", "=", "b", "[", "k", "]", ";", "return", "r", ";", "}" ]
Creates a new object containing the properties of the first object and the second object. If any value has the same key in both values, the second object overrides the first.
[ "Creates", "a", "new", "object", "containing", "the", "properties", "of", "the", "first", "object", "and", "the", "second", "object", ".", "If", "any", "value", "has", "the", "same", "key", "in", "both", "values", "the", "second", "object", "overrides", "the", "first", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_mustache_expander.js#L25-L32
train
cdiggins/myna-parser
tools/myna_mustache_expander.js
expandAst
function expandAst(ast, data, lines) { if (lines == undefined) lines = []; // If there is a child "key" get the value associated with it. let keyNode = ast.child("key"); let key = keyNode ? keyNode.allText : ""; let val = data ? (key in data ? data[key] : "") : ""; // Functions are not supported if (typeof(val) == 'function') throw new Exception('Functions are not supported'); switch (ast.rule.name) { case "document": case "sectionContent": ast.children.forEach(function(c) { expandAst(c, data, lines); }); return lines; case "comment": return lines; case "plainText": lines.push(ast.allText); return lines; case "section": let content = ast.child("sectionContent"); if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") { if (val) expandAst(content, data, lines); } else if (val instanceof Array) { for (let x of val) expandAst(content, mergeObjects(data, x), lines); } else { expandAst(content, mergeObjects(data, val), lines); } return lines; case "invertedSection": if (!val || ((val instanceof Array) && val.length == 0)) expandAst(ast.child("sectionContent"), data, lines); return lines; case "escapedVar": if (val) lines.push( expand(escapeHtmlChars(String(val)), data)); return lines; case "unescapedVar": if (val) lines.push( expand(String(val), data)); return lines; } throw "Unrecognized AST node " + ast.rule.name; }
javascript
function expandAst(ast, data, lines) { if (lines == undefined) lines = []; // If there is a child "key" get the value associated with it. let keyNode = ast.child("key"); let key = keyNode ? keyNode.allText : ""; let val = data ? (key in data ? data[key] : "") : ""; // Functions are not supported if (typeof(val) == 'function') throw new Exception('Functions are not supported'); switch (ast.rule.name) { case "document": case "sectionContent": ast.children.forEach(function(c) { expandAst(c, data, lines); }); return lines; case "comment": return lines; case "plainText": lines.push(ast.allText); return lines; case "section": let content = ast.child("sectionContent"); if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") { if (val) expandAst(content, data, lines); } else if (val instanceof Array) { for (let x of val) expandAst(content, mergeObjects(data, x), lines); } else { expandAst(content, mergeObjects(data, val), lines); } return lines; case "invertedSection": if (!val || ((val instanceof Array) && val.length == 0)) expandAst(ast.child("sectionContent"), data, lines); return lines; case "escapedVar": if (val) lines.push( expand(escapeHtmlChars(String(val)), data)); return lines; case "unescapedVar": if (val) lines.push( expand(String(val), data)); return lines; } throw "Unrecognized AST node " + ast.rule.name; }
[ "function", "expandAst", "(", "ast", ",", "data", ",", "lines", ")", "{", "if", "(", "lines", "==", "undefined", ")", "lines", "=", "[", "]", ";", "let", "keyNode", "=", "ast", ".", "child", "(", "\"key\"", ")", ";", "let", "key", "=", "keyNode", "?", "keyNode", ".", "allText", ":", "\"\"", ";", "let", "val", "=", "data", "?", "(", "key", "in", "data", "?", "data", "[", "key", "]", ":", "\"\"", ")", ":", "\"\"", ";", "if", "(", "typeof", "(", "val", ")", "==", "'function'", ")", "throw", "new", "Exception", "(", "'Functions are not supported'", ")", ";", "switch", "(", "ast", ".", "rule", ".", "name", ")", "{", "case", "\"document\"", ":", "case", "\"sectionContent\"", ":", "ast", ".", "children", ".", "forEach", "(", "function", "(", "c", ")", "{", "expandAst", "(", "c", ",", "data", ",", "lines", ")", ";", "}", ")", ";", "return", "lines", ";", "case", "\"comment\"", ":", "return", "lines", ";", "case", "\"plainText\"", ":", "lines", ".", "push", "(", "ast", ".", "allText", ")", ";", "return", "lines", ";", "case", "\"section\"", ":", "let", "content", "=", "ast", ".", "child", "(", "\"sectionContent\"", ")", ";", "if", "(", "typeof", "val", "===", "\"boolean\"", "||", "typeof", "val", "===", "\"number\"", "||", "typeof", "val", "===", "\"string\"", ")", "{", "if", "(", "val", ")", "expandAst", "(", "content", ",", "data", ",", "lines", ")", ";", "}", "else", "if", "(", "val", "instanceof", "Array", ")", "{", "for", "(", "let", "x", "of", "val", ")", "expandAst", "(", "content", ",", "mergeObjects", "(", "data", ",", "x", ")", ",", "lines", ")", ";", "}", "else", "{", "expandAst", "(", "content", ",", "mergeObjects", "(", "data", ",", "val", ")", ",", "lines", ")", ";", "}", "return", "lines", ";", "case", "\"invertedSection\"", ":", "if", "(", "!", "val", "||", "(", "(", "val", "instanceof", "Array", ")", "&&", "val", ".", "length", "==", "0", ")", ")", "expandAst", "(", "ast", ".", "child", "(", "\"sectionContent\"", ")", ",", "data", ",", "lines", ")", ";", "return", "lines", ";", "case", "\"escapedVar\"", ":", "if", "(", "val", ")", "lines", ".", "push", "(", "expand", "(", "escapeHtmlChars", "(", "String", "(", "val", ")", ")", ",", "data", ")", ")", ";", "return", "lines", ";", "case", "\"unescapedVar\"", ":", "if", "(", "val", ")", "lines", ".", "push", "(", "expand", "(", "String", "(", "val", ")", ",", "data", ")", ")", ";", "return", "lines", ";", "}", "throw", "\"Unrecognized AST node \"", "+", "ast", ".", "rule", ".", "name", ";", "}" ]
Given an AST node, a data object, and an optional array of string, converts the nodes expanding the reserved characters.
[ "Given", "an", "AST", "node", "a", "data", "object", "and", "an", "optional", "array", "of", "string", "converts", "the", "nodes", "expanding", "the", "reserved", "characters", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_mustache_expander.js#L36-L98
train
cdiggins/myna-parser
tools/myna_mustache_expander.js
expand
function expand(template, data) { if (template.indexOf("{{") >= 0) { let ast = myna.parsers.mustache(template); let lines = expandAst(ast, data); return lines.join(""); } else { return template; } }
javascript
function expand(template, data) { if (template.indexOf("{{") >= 0) { let ast = myna.parsers.mustache(template); let lines = expandAst(ast, data); return lines.join(""); } else { return template; } }
[ "function", "expand", "(", "template", ",", "data", ")", "{", "if", "(", "template", ".", "indexOf", "(", "\"{{\"", ")", ">=", "0", ")", "{", "let", "ast", "=", "myna", ".", "parsers", ".", "mustache", "(", "template", ")", ";", "let", "lines", "=", "expandAst", "(", "ast", ",", "data", ")", ";", "return", "lines", ".", "join", "(", "\"\"", ")", ";", "}", "else", "{", "return", "template", ";", "}", "}" ]
Expands text containing CTemplate delimiters "{{" using the data object
[ "Expands", "text", "containing", "CTemplate", "delimiters", "{{", "using", "the", "data", "object" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_mustache_expander.js#L101-L110
train
cdiggins/myna-parser
tools/myna_escape_html_chars.js
escapeHtmlChars
function escapeHtmlChars(text) { let ast = myna.parsers.html_reserved_chars(text); if (!ast.children) return ""; return ast.children.map(astNodeToHtmlText).join(''); }
javascript
function escapeHtmlChars(text) { let ast = myna.parsers.html_reserved_chars(text); if (!ast.children) return ""; return ast.children.map(astNodeToHtmlText).join(''); }
[ "function", "escapeHtmlChars", "(", "text", ")", "{", "let", "ast", "=", "myna", ".", "parsers", ".", "html_reserved_chars", "(", "text", ")", ";", "if", "(", "!", "ast", ".", "children", ")", "return", "\"\"", ";", "return", "ast", ".", "children", ".", "map", "(", "astNodeToHtmlText", ")", ".", "join", "(", "''", ")", ";", "}" ]
Returns a string, replacing all of the reserved characters with entities
[ "Returns", "a", "string", "replacing", "all", "of", "the", "reserved", "characters", "with", "entities" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_escape_html_chars.js#L37-L43
train
cdiggins/myna-parser
grammars/grammar_pithy.js
guardedSeq
function guardedSeq() { var args = Array.prototype.slice.call(arguments, 1).map(function(r) { return m.seq(m.assert(r), _this.ws); }); return m.seq(arguments[0], _this.ws, m.seq.apply(m, args)); }
javascript
function guardedSeq() { var args = Array.prototype.slice.call(arguments, 1).map(function(r) { return m.seq(m.assert(r), _this.ws); }); return m.seq(arguments[0], _this.ws, m.seq.apply(m, args)); }
[ "function", "guardedSeq", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "m", ".", "seq", "(", "m", ".", "assert", "(", "r", ")", ",", "_this", ".", "ws", ")", ";", "}", ")", ";", "return", "m", ".", "seq", "(", "arguments", "[", "0", "]", ",", "_this", ".", "ws", ",", "m", ".", "seq", ".", "apply", "(", "m", ",", "args", ")", ")", ";", "}" ]
If the first rule argument passes, all subsequent rules must pass or an assert will throw
[ "If", "the", "first", "rule", "argument", "passes", "all", "subsequent", "rules", "must", "pass", "or", "an", "assert", "will", "throw" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/grammars/grammar_pithy.js#L42-L45
train
cdiggins/myna-parser
grammars/grammar_pithy.js
commaList
function commaList(r, trailing = true) { var result = r.then(guardedSeq(_this.comma, r).zeroOrMore); if (trailing) return result.then(_this.comma.opt); else return result; }
javascript
function commaList(r, trailing = true) { var result = r.then(guardedSeq(_this.comma, r).zeroOrMore); if (trailing) return result.then(_this.comma.opt); else return result; }
[ "function", "commaList", "(", "r", ",", "trailing", "=", "true", ")", "{", "var", "result", "=", "r", ".", "then", "(", "guardedSeq", "(", "_this", ".", "comma", ",", "r", ")", ".", "zeroOrMore", ")", ";", "if", "(", "trailing", ")", "return", "result", ".", "then", "(", "_this", ".", "comma", ".", "opt", ")", ";", "else", "return", "result", ";", "}" ]
Comma delimited list with a trailing comma
[ "Comma", "delimited", "list", "with", "a", "trailing", "comma" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/grammars/grammar_pithy.js#L48-L52
train
twolfson/layout
lib/layout.js
Layout
function Layout(algorithmName, options) { // Save the algorithmName as our algorithm (assume function) var algorithm = algorithmName || 'top-down'; // If the algorithm is a string, look it up if (typeof algorithm === 'string') { algorithm = algorithms[algorithmName]; // Assert that the algorithm was found assert(algorithm, 'Sorry, the \'' + algorithmName +'\' algorithm could not be loaded.'); } // Create a new PackingSmith with our algorithm and return var retSmith = new PackingSmith(algorithm, options); return retSmith; }
javascript
function Layout(algorithmName, options) { // Save the algorithmName as our algorithm (assume function) var algorithm = algorithmName || 'top-down'; // If the algorithm is a string, look it up if (typeof algorithm === 'string') { algorithm = algorithms[algorithmName]; // Assert that the algorithm was found assert(algorithm, 'Sorry, the \'' + algorithmName +'\' algorithm could not be loaded.'); } // Create a new PackingSmith with our algorithm and return var retSmith = new PackingSmith(algorithm, options); return retSmith; }
[ "function", "Layout", "(", "algorithmName", ",", "options", ")", "{", "var", "algorithm", "=", "algorithmName", "||", "'top-down'", ";", "if", "(", "typeof", "algorithm", "===", "'string'", ")", "{", "algorithm", "=", "algorithms", "[", "algorithmName", "]", ";", "assert", "(", "algorithm", ",", "'Sorry, the \\''", "+", "\\'", "+", "algorithmName", ")", ";", "}", "'\\' algorithm could not be loaded.'", "\\'", "}" ]
Layout adds items in an algorithmic fashion @constructor @param {String|Object} [algorithm="top-down"] Name of algorithm or custom algorithm to use @param {Mixed} [options] Options to provide for the algorithm
[ "Layout", "adds", "items", "in", "an", "algorithmic", "fashion" ]
eaf4c254dee37afbde0eec2c82b343869c6049db
https://github.com/twolfson/layout/blob/eaf4c254dee37afbde0eec2c82b343869c6049db/lib/layout.js#L12-L27
train
doowb/github-content
index.js
GithubContent
function GithubContent(options) { if (!(this instanceof GithubContent)) { return new GithubContent(options); } // setup our specific options var opts = extend({branch: 'master'}, options); opts.json = false; opts.apiurl = 'https://raw.githubusercontent.com'; GithubBase.call(this, opts); this.options = extend({}, opts, this.options); }
javascript
function GithubContent(options) { if (!(this instanceof GithubContent)) { return new GithubContent(options); } // setup our specific options var opts = extend({branch: 'master'}, options); opts.json = false; opts.apiurl = 'https://raw.githubusercontent.com'; GithubBase.call(this, opts); this.options = extend({}, opts, this.options); }
[ "function", "GithubContent", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "GithubContent", ")", ")", "{", "return", "new", "GithubContent", "(", "options", ")", ";", "}", "var", "opts", "=", "extend", "(", "{", "branch", ":", "'master'", "}", ",", "options", ")", ";", "opts", ".", "json", "=", "false", ";", "opts", ".", "apiurl", "=", "'https://raw.githubusercontent.com'", ";", "GithubBase", ".", "call", "(", "this", ",", "opts", ")", ";", "this", ".", "options", "=", "extend", "(", "{", "}", ",", "opts", ",", "this", ".", "options", ")", ";", "}" ]
Create an instance of GithubContent to setup downloading of files. ```js var options = { owner: 'doowb', repo: 'github-content', branch: 'master' // defaults to master }; var gc = new GithubContent(options); ``` @param {Object} `options` Options to set on instance. Additional options passed to [github-base] @param {String} `options.owner` Set the owner to be used for each file. @param {String} `options.repo` Set the repository to be used for each file. @param {String} `options.branch` Set the branch to be used for each file. Defaults to `master` @api public
[ "Create", "an", "instance", "of", "GithubContent", "to", "setup", "downloading", "of", "files", "." ]
1348f808083d14dde4f986ff9f93ee543183e1d3
https://github.com/doowb/github-content/blob/1348f808083d14dde4f986ff9f93ee543183e1d3/index.js#L33-L44
train
twolfson/layout
lib/smiths/packing.smith.js
function () { // Grab the items var items = this.items; // Find the most negative x and y var minX = Infinity, minY = Infinity; items.forEach(function (item) { var coords = item; minX = Math.min(minX, coords.x); minY = Math.min(minY, coords.y); }); // Offset each item by -minX, -minY; effectively resetting to 0, 0 items.forEach(function (item) { var coords = item; coords.x -= minX; coords.y -= minY; }); }
javascript
function () { // Grab the items var items = this.items; // Find the most negative x and y var minX = Infinity, minY = Infinity; items.forEach(function (item) { var coords = item; minX = Math.min(minX, coords.x); minY = Math.min(minY, coords.y); }); // Offset each item by -minX, -minY; effectively resetting to 0, 0 items.forEach(function (item) { var coords = item; coords.x -= minX; coords.y -= minY; }); }
[ "function", "(", ")", "{", "var", "items", "=", "this", ".", "items", ";", "var", "minX", "=", "Infinity", ",", "minY", "=", "Infinity", ";", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "coords", "=", "item", ";", "minX", "=", "Math", ".", "min", "(", "minX", ",", "coords", ".", "x", ")", ";", "minY", "=", "Math", ".", "min", "(", "minY", ",", "coords", ".", "y", ")", ";", "}", ")", ";", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "coords", "=", "item", ";", "coords", ".", "x", "-=", "minX", ";", "coords", ".", "y", "-=", "minY", ";", "}", ")", ";", "}" ]
Method to normalize coordinates to 0, 0 This is bad to do mid-addition since it messes up the algorithm
[ "Method", "to", "normalize", "coordinates", "to", "0", "0", "This", "is", "bad", "to", "do", "mid", "-", "addition", "since", "it", "messes", "up", "the", "algorithm" ]
eaf4c254dee37afbde0eec2c82b343869c6049db
https://github.com/twolfson/layout/blob/eaf4c254dee37afbde0eec2c82b343869c6049db/lib/smiths/packing.smith.js#L24-L43
train
giapnguyen74/nextql
samples/mongoose/index.js
normalizeFields
function normalizeFields(fields) { const _fields = {}; Object.keys(fields).forEach(k => { if (fields[k].constructor == Object && !fields[k].type) { _fields[k] = normalizeFields(fields[k]); } else { _fields[k] = 1; } }); return _fields; }
javascript
function normalizeFields(fields) { const _fields = {}; Object.keys(fields).forEach(k => { if (fields[k].constructor == Object && !fields[k].type) { _fields[k] = normalizeFields(fields[k]); } else { _fields[k] = 1; } }); return _fields; }
[ "function", "normalizeFields", "(", "fields", ")", "{", "const", "_fields", "=", "{", "}", ";", "Object", ".", "keys", "(", "fields", ")", ".", "forEach", "(", "k", "=>", "{", "if", "(", "fields", "[", "k", "]", ".", "constructor", "==", "Object", "&&", "!", "fields", "[", "k", "]", ".", "type", ")", "{", "_fields", "[", "k", "]", "=", "normalizeFields", "(", "fields", "[", "k", "]", ")", ";", "}", "else", "{", "_fields", "[", "k", "]", "=", "1", ";", "}", "}", ")", ";", "return", "_fields", ";", "}" ]
Simply convert mongoose schema to nextql fields
[ "Simply", "convert", "mongoose", "schema", "to", "nextql", "fields" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/samples/mongoose/index.js#L4-L14
train
giapnguyen74/nextql
src/resolvers.js
resolve_type_define
function resolve_type_define(nextql, fieldValue, fieldDefine, fieldPath) { let fd = fieldDefine; // First phrase resolve fieldDefine is auto or function into final fieldDefine if (fd === 1) { if (isPrimitive(fieldValue)) { return "*"; } else { fd = nextql.resolveType(fieldValue); nextql.afterResolveTypeHooks.forEach( hook => (fd = hook(fieldValue) || fd) ); } } if (typeof fd == "function") { fd = fieldDefine(fieldValue); } // Second phrase resolve fieldDefine is explicit into fieldModel name; if (fd == undefined) { return new NextQLError( "Cannot resolve model: " + JSON.stringify(fieldDefine), { path: fieldPath } ); } // InlineModel if (fd.constructor && fd.constructor == Object) { return new InlineModel(fd); } // ScalarModel if (fd === "*") { return "*"; } // NamedModel const model = nextql.model(fd); if (!model) { return new NextQLError("Model not found: " + fd, { path: fieldPath }); } return model; }
javascript
function resolve_type_define(nextql, fieldValue, fieldDefine, fieldPath) { let fd = fieldDefine; // First phrase resolve fieldDefine is auto or function into final fieldDefine if (fd === 1) { if (isPrimitive(fieldValue)) { return "*"; } else { fd = nextql.resolveType(fieldValue); nextql.afterResolveTypeHooks.forEach( hook => (fd = hook(fieldValue) || fd) ); } } if (typeof fd == "function") { fd = fieldDefine(fieldValue); } // Second phrase resolve fieldDefine is explicit into fieldModel name; if (fd == undefined) { return new NextQLError( "Cannot resolve model: " + JSON.stringify(fieldDefine), { path: fieldPath } ); } // InlineModel if (fd.constructor && fd.constructor == Object) { return new InlineModel(fd); } // ScalarModel if (fd === "*") { return "*"; } // NamedModel const model = nextql.model(fd); if (!model) { return new NextQLError("Model not found: " + fd, { path: fieldPath }); } return model; }
[ "function", "resolve_type_define", "(", "nextql", ",", "fieldValue", ",", "fieldDefine", ",", "fieldPath", ")", "{", "let", "fd", "=", "fieldDefine", ";", "if", "(", "fd", "===", "1", ")", "{", "if", "(", "isPrimitive", "(", "fieldValue", ")", ")", "{", "return", "\"*\"", ";", "}", "else", "{", "fd", "=", "nextql", ".", "resolveType", "(", "fieldValue", ")", ";", "nextql", ".", "afterResolveTypeHooks", ".", "forEach", "(", "hook", "=>", "(", "fd", "=", "hook", "(", "fieldValue", ")", "||", "fd", ")", ")", ";", "}", "}", "if", "(", "typeof", "fd", "==", "\"function\"", ")", "{", "fd", "=", "fieldDefine", "(", "fieldValue", ")", ";", "}", "if", "(", "fd", "==", "undefined", ")", "{", "return", "new", "NextQLError", "(", "\"Cannot resolve model: \"", "+", "JSON", ".", "stringify", "(", "fieldDefine", ")", ",", "{", "path", ":", "fieldPath", "}", ")", ";", "}", "if", "(", "fd", ".", "constructor", "&&", "fd", ".", "constructor", "==", "Object", ")", "{", "return", "new", "InlineModel", "(", "fd", ")", ";", "}", "if", "(", "fd", "===", "\"*\"", ")", "{", "return", "\"*\"", ";", "}", "const", "model", "=", "nextql", ".", "model", "(", "fd", ")", ";", "if", "(", "!", "model", ")", "{", "return", "new", "NextQLError", "(", "\"Model not found: \"", "+", "fd", ",", "{", "path", ":", "fieldPath", "}", ")", ";", "}", "return", "model", ";", "}" ]
Give field value and field define, resolve field model or error field path provided for log @param {*} nextql @param {string} path @param {*} value @param {*} typeDef @return {*} model
[ "Give", "field", "value", "and", "field", "define", "resolve", "field", "model", "or", "error", "field", "path", "provided", "for", "log" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L36-L81
train
giapnguyen74/nextql
src/resolvers.js
resolve_scalar_value
function resolve_scalar_value(nextql, value, valueQuery, info) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (valueQuery !== 1) { const keylen = Object.keys(valueQuery).length; const queryAsObject = valueQuery.$params ? keylen > 1 : keylen > 0; if (queryAsObject) { return Promise.reject( new NextQLError("Cannot query scalar as object", info) ); } } if (isPrimitive(value)) { set(info.result, info.path, value); return Promise.resolve(); } // non-primitive value as scalar, not good solution yet try { set(info.result, info.path, JSON.parse(JSON.stringify(value))); return Promise.resolve(); } catch (e) { return Promise.reject( new NextQLError("Cannot serialize return value", info) ); } }
javascript
function resolve_scalar_value(nextql, value, valueQuery, info) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (valueQuery !== 1) { const keylen = Object.keys(valueQuery).length; const queryAsObject = valueQuery.$params ? keylen > 1 : keylen > 0; if (queryAsObject) { return Promise.reject( new NextQLError("Cannot query scalar as object", info) ); } } if (isPrimitive(value)) { set(info.result, info.path, value); return Promise.resolve(); } // non-primitive value as scalar, not good solution yet try { set(info.result, info.path, JSON.parse(JSON.stringify(value))); return Promise.resolve(); } catch (e) { return Promise.reject( new NextQLError("Cannot serialize return value", info) ); } }
[ "function", "resolve_scalar_value", "(", "nextql", ",", "value", ",", "valueQuery", ",", "info", ")", "{", "if", "(", "value", "==", "undefined", ")", "{", "set", "(", "info", ".", "result", ",", "info", ".", "path", ",", "null", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "if", "(", "valueQuery", "!==", "1", ")", "{", "const", "keylen", "=", "Object", ".", "keys", "(", "valueQuery", ")", ".", "length", ";", "const", "queryAsObject", "=", "valueQuery", ".", "$params", "?", "keylen", ">", "1", ":", "keylen", ">", "0", ";", "if", "(", "queryAsObject", ")", "{", "return", "Promise", ".", "reject", "(", "new", "NextQLError", "(", "\"Cannot query scalar as object\"", ",", "info", ")", ")", ";", "}", "}", "if", "(", "isPrimitive", "(", "value", ")", ")", "{", "set", "(", "info", ".", "result", ",", "info", ".", "path", ",", "value", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "try", "{", "set", "(", "info", ".", "result", ",", "info", ".", "path", ",", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "value", ")", ")", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "Promise", ".", "reject", "(", "new", "NextQLError", "(", "\"Cannot serialize return value\"", ",", "info", ")", ")", ";", "}", "}" ]
Given value and valueQuery; resolve value as a scalar @param {*} nextql @param {*} value @param {*} valueQuery @param {*} info
[ "Given", "value", "and", "valueQuery", ";", "resolve", "value", "as", "a", "scalar" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L90-L120
train
giapnguyen74/nextql
src/resolvers.js
execute_conditional
function execute_conditional( nextql, value, valueModel, conditional, query, info, context ) { let model; const modelName = valueModel.check( value, conditional, query.$params, context, info ); if (modelName instanceof Error) { return Promise.reject(modelName); } if (modelName === true) { model = valueModel; } if (typeof modelName == "string" && modelName != "*") { model = nextql.model(modelName); } if (!model) return Promise.resolve(); return resolve_object_value(nextql, value, model, query, info, context); }
javascript
function execute_conditional( nextql, value, valueModel, conditional, query, info, context ) { let model; const modelName = valueModel.check( value, conditional, query.$params, context, info ); if (modelName instanceof Error) { return Promise.reject(modelName); } if (modelName === true) { model = valueModel; } if (typeof modelName == "string" && modelName != "*") { model = nextql.model(modelName); } if (!model) return Promise.resolve(); return resolve_object_value(nextql, value, model, query, info, context); }
[ "function", "execute_conditional", "(", "nextql", ",", "value", ",", "valueModel", ",", "conditional", ",", "query", ",", "info", ",", "context", ")", "{", "let", "model", ";", "const", "modelName", "=", "valueModel", ".", "check", "(", "value", ",", "conditional", ",", "query", ".", "$params", ",", "context", ",", "info", ")", ";", "if", "(", "modelName", "instanceof", "Error", ")", "{", "return", "Promise", ".", "reject", "(", "modelName", ")", ";", "}", "if", "(", "modelName", "===", "true", ")", "{", "model", "=", "valueModel", ";", "}", "if", "(", "typeof", "modelName", "==", "\"string\"", "&&", "modelName", "!=", "\"*\"", ")", "{", "model", "=", "nextql", ".", "model", "(", "modelName", ")", ";", "}", "if", "(", "!", "model", ")", "return", "Promise", ".", "resolve", "(", ")", ";", "return", "resolve_object_value", "(", "nextql", ",", "value", ",", "model", ",", "query", ",", "info", ",", "context", ")", ";", "}" ]
Given value, valueModel and conditional path; call conditional function and process result @param {*} nextql @param {*} value @param {*} valueModel @param {*} conditionalQuery @param {*} info @param {*} context
[ "Given", "value", "valueModel", "and", "conditional", "path", ";", "call", "conditional", "function", "and", "process", "result" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L131-L165
train
giapnguyen74/nextql
src/resolvers.js
resolve_object_value
function resolve_object_value( nextql, value, valueModel, valueQuery, info, context ) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (isPrimitive(value)) { return Promise.reject( new NextQLError("Cannot query scalar as " + valueModel.name, info) ); } return Promise.all( Object.keys(valueQuery).map(path => { if (path == "$params") return; const fieldName = path.split(nextql.aliasSeparator, 1)[0]; //Conditional query? if (fieldName[0] === "?") { return execute_conditional( nextql, value, valueModel, fieldName, valueQuery[path], info, context ); } const newInfo = info_append_path(info, path); return valueModel .get( value, fieldName, valueQuery[path].$params, context, newInfo ) .then(fieldValue => { let fieldDef; if (valueModel.computed[fieldName]) { fieldDef = valueModel.fields[fieldName] || 1; } else { fieldDef = valueModel.fields[fieldName]; } return resolve_value( nextql, fieldValue, fieldDef, valueQuery[path], newInfo, context ); }); }) ); }
javascript
function resolve_object_value( nextql, value, valueModel, valueQuery, info, context ) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (isPrimitive(value)) { return Promise.reject( new NextQLError("Cannot query scalar as " + valueModel.name, info) ); } return Promise.all( Object.keys(valueQuery).map(path => { if (path == "$params") return; const fieldName = path.split(nextql.aliasSeparator, 1)[0]; //Conditional query? if (fieldName[0] === "?") { return execute_conditional( nextql, value, valueModel, fieldName, valueQuery[path], info, context ); } const newInfo = info_append_path(info, path); return valueModel .get( value, fieldName, valueQuery[path].$params, context, newInfo ) .then(fieldValue => { let fieldDef; if (valueModel.computed[fieldName]) { fieldDef = valueModel.fields[fieldName] || 1; } else { fieldDef = valueModel.fields[fieldName]; } return resolve_value( nextql, fieldValue, fieldDef, valueQuery[path], newInfo, context ); }); }) ); }
[ "function", "resolve_object_value", "(", "nextql", ",", "value", ",", "valueModel", ",", "valueQuery", ",", "info", ",", "context", ")", "{", "if", "(", "value", "==", "undefined", ")", "{", "set", "(", "info", ".", "result", ",", "info", ".", "path", ",", "null", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "if", "(", "isPrimitive", "(", "value", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "NextQLError", "(", "\"Cannot query scalar as \"", "+", "valueModel", ".", "name", ",", "info", ")", ")", ";", "}", "return", "Promise", ".", "all", "(", "Object", ".", "keys", "(", "valueQuery", ")", ".", "map", "(", "path", "=>", "{", "if", "(", "path", "==", "\"$params\"", ")", "return", ";", "const", "fieldName", "=", "path", ".", "split", "(", "nextql", ".", "aliasSeparator", ",", "1", ")", "[", "0", "]", ";", "if", "(", "fieldName", "[", "0", "]", "===", "\"?\"", ")", "{", "return", "execute_conditional", "(", "nextql", ",", "value", ",", "valueModel", ",", "fieldName", ",", "valueQuery", "[", "path", "]", ",", "info", ",", "context", ")", ";", "}", "const", "newInfo", "=", "info_append_path", "(", "info", ",", "path", ")", ";", "return", "valueModel", ".", "get", "(", "value", ",", "fieldName", ",", "valueQuery", "[", "path", "]", ".", "$params", ",", "context", ",", "newInfo", ")", ".", "then", "(", "fieldValue", "=>", "{", "let", "fieldDef", ";", "if", "(", "valueModel", ".", "computed", "[", "fieldName", "]", ")", "{", "fieldDef", "=", "valueModel", ".", "fields", "[", "fieldName", "]", "||", "1", ";", "}", "else", "{", "fieldDef", "=", "valueModel", ".", "fields", "[", "fieldName", "]", ";", "}", "return", "resolve_value", "(", "nextql", ",", "fieldValue", ",", "fieldDef", ",", "valueQuery", "[", "path", "]", ",", "newInfo", ",", "context", ")", ";", "}", ")", ";", "}", ")", ")", ";", "}" ]
Given value, valueModel, valueQuery; recursive resolve field value @param {*} nextql @param {*} value @param {*} valueModel @param {*} valueQuery @param {*} info @param {*} context
[ "Given", "value", "valueModel", "valueQuery", ";", "recursive", "resolve", "field", "value" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L176-L241
train
frapontillo/node-rdp
lib/rdp-file.js
buildRdpFile
function buildRdpFile(config) { var deferred = Q.defer(); var fileContent = getRdpFileContent(config); var fileName = path.normalize(os.tmpdir() + '/' + sanitize(config.address) + '.rdp'); Q.nfcall(fs.writeFile, fileName, fileContent) .then(function() { deferred.resolve(fileName); }) .fail(deferred.reject); return deferred.promise; }
javascript
function buildRdpFile(config) { var deferred = Q.defer(); var fileContent = getRdpFileContent(config); var fileName = path.normalize(os.tmpdir() + '/' + sanitize(config.address) + '.rdp'); Q.nfcall(fs.writeFile, fileName, fileContent) .then(function() { deferred.resolve(fileName); }) .fail(deferred.reject); return deferred.promise; }
[ "function", "buildRdpFile", "(", "config", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "fileContent", "=", "getRdpFileContent", "(", "config", ")", ";", "var", "fileName", "=", "path", ".", "normalize", "(", "os", ".", "tmpdir", "(", ")", "+", "'/'", "+", "sanitize", "(", "config", ".", "address", ")", "+", "'.rdp'", ")", ";", "Q", ".", "nfcall", "(", "fs", ".", "writeFile", ",", "fileName", ",", "fileContent", ")", ".", "then", "(", "function", "(", ")", "{", "deferred", ".", "resolve", "(", "fileName", ")", ";", "}", ")", ".", "fail", "(", "deferred", ".", "reject", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Returns a promise that will be resolved as soon as the file is created. @param config @returns {promise|*|Q.promise}
[ "Returns", "a", "promise", "that", "will", "be", "resolved", "as", "soon", "as", "the", "file", "is", "created", "." ]
0d4e0acb15923aab29a86ee42c84af6bef8c50c1
https://github.com/frapontillo/node-rdp/blob/0d4e0acb15923aab29a86ee42c84af6bef8c50c1/lib/rdp-file.js#L202-L212
train
gchudnov/inkjet
build/lib/magic.js
magic
function magic(buf, cb) { setTimeout(() => { const sampleLength = 24; const sample = buf.slice(0, sampleLength).toString('hex'); // lookup data const found = Object.keys(_magicDb2.default).find(it => { return sample.indexOf(it) != -1; }); if (found) { cb(null, _magicDb2.default[found]); } else { cb(new Error('Magic number not found')); } }, 0); }
javascript
function magic(buf, cb) { setTimeout(() => { const sampleLength = 24; const sample = buf.slice(0, sampleLength).toString('hex'); // lookup data const found = Object.keys(_magicDb2.default).find(it => { return sample.indexOf(it) != -1; }); if (found) { cb(null, _magicDb2.default[found]); } else { cb(new Error('Magic number not found')); } }, 0); }
[ "function", "magic", "(", "buf", ",", "cb", ")", "{", "setTimeout", "(", "(", ")", "=>", "{", "const", "sampleLength", "=", "24", ";", "const", "sample", "=", "buf", ".", "slice", "(", "0", ",", "sampleLength", ")", ".", "toString", "(", "'hex'", ")", ";", "const", "found", "=", "Object", ".", "keys", "(", "_magicDb2", ".", "default", ")", ".", "find", "(", "it", "=>", "{", "return", "sample", ".", "indexOf", "(", "it", ")", "!=", "-", "1", ";", "}", ")", ";", "if", "(", "found", ")", "{", "cb", "(", "null", ",", "_magicDb2", ".", "default", "[", "found", "]", ")", ";", "}", "else", "{", "cb", "(", "new", "Error", "(", "'Magic number not found'", ")", ")", ";", "}", "}", ",", "0", ")", ";", "}" ]
Lookup the magic number in magic-number DB @param {Buffer} buf Data buffer @param {function} cb Callback to invoke on completion
[ "Lookup", "the", "magic", "number", "in", "magic", "-", "number", "DB" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/magic.js#L19-L34
train
gchudnov/inkjet
build/lib/encode.js
encode
function encode(buf, options, cb) { try { const imageData = { data: buf, width: options.width, height: options.height }; const data = (0, _encoder2.default)(imageData, options.quality); cb(null, data); } catch (err) { cb(err); } }
javascript
function encode(buf, options, cb) { try { const imageData = { data: buf, width: options.width, height: options.height }; const data = (0, _encoder2.default)(imageData, options.quality); cb(null, data); } catch (err) { cb(err); } }
[ "function", "encode", "(", "buf", ",", "options", ",", "cb", ")", "{", "try", "{", "const", "imageData", "=", "{", "data", ":", "buf", ",", "width", ":", "options", ".", "width", ",", "height", ":", "options", ".", "height", "}", ";", "const", "data", "=", "(", "0", ",", "_encoder2", ".", "default", ")", "(", "imageData", ",", "options", ".", "quality", ")", ";", "cb", "(", "null", ",", "data", ")", ";", "}", "catch", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", "}" ]
Encode the data to JPEG format @param buf Buffer|Uint8Array @param options Object { width: number, height: number, quality: number } @param cb Callback to invoke on completion @callback { width: number, height: number, data: Uint8Array }
[ "Encode", "the", "data", "to", "JPEG", "format" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/encode.js#L23-L35
train
gchudnov/inkjet
build/lib/buffer-utils.js
toBuffer
function toBuffer(buf) { if (buf instanceof ArrayBuffer) { return arrayBufferToBuffer(buf); } else if (Buffer.isBuffer(buf)) { return buf; } else if (buf instanceof Uint8Array) { return new Buffer(buf); } else { return buf; // type unknown, trust the user } }
javascript
function toBuffer(buf) { if (buf instanceof ArrayBuffer) { return arrayBufferToBuffer(buf); } else if (Buffer.isBuffer(buf)) { return buf; } else if (buf instanceof Uint8Array) { return new Buffer(buf); } else { return buf; // type unknown, trust the user } }
[ "function", "toBuffer", "(", "buf", ")", "{", "if", "(", "buf", "instanceof", "ArrayBuffer", ")", "{", "return", "arrayBufferToBuffer", "(", "buf", ")", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "buf", ")", ")", "{", "return", "buf", ";", "}", "else", "if", "(", "buf", "instanceof", "Uint8Array", ")", "{", "return", "new", "Buffer", "(", "buf", ")", ";", "}", "else", "{", "return", "buf", ";", "}", "}" ]
Converts the buffer to Buffer @param {Buffer|ArrayBuffer|Uint8Array} buf Input buffer @returns {Buffer}
[ "Converts", "the", "buffer", "to", "Buffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L18-L28
train
gchudnov/inkjet
build/lib/buffer-utils.js
toArrayBuffer
function toArrayBuffer(buf) { if (buf instanceof ArrayBuffer) { return buf; } else if (Buffer.isBuffer(buf)) { return bufferToArrayBuffer(buf); } else if (buf instanceof Uint8Array) { return bufferToArrayBuffer(buf); } else { return buf; // type unknown, trust the user } }
javascript
function toArrayBuffer(buf) { if (buf instanceof ArrayBuffer) { return buf; } else if (Buffer.isBuffer(buf)) { return bufferToArrayBuffer(buf); } else if (buf instanceof Uint8Array) { return bufferToArrayBuffer(buf); } else { return buf; // type unknown, trust the user } }
[ "function", "toArrayBuffer", "(", "buf", ")", "{", "if", "(", "buf", "instanceof", "ArrayBuffer", ")", "{", "return", "buf", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "buf", ")", ")", "{", "return", "bufferToArrayBuffer", "(", "buf", ")", ";", "}", "else", "if", "(", "buf", "instanceof", "Uint8Array", ")", "{", "return", "bufferToArrayBuffer", "(", "buf", ")", ";", "}", "else", "{", "return", "buf", ";", "}", "}" ]
Converts any buffer to ArrayBuffer @param {Buffer|ArrayBuffer|Uint8Array} buf Input buffer @returns {ArrayBuffer}
[ "Converts", "any", "buffer", "to", "ArrayBuffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L35-L45
train
gchudnov/inkjet
build/lib/buffer-utils.js
toUint8Array
function toUint8Array(buf) { if (buf instanceof Uint8Array) { return buf; } else if (buf instanceof ArrayBuffer) { return new Uint8Array(buf); } else if (Buffer.isBuffer(buf)) { return new Uint8Array(buf); } else { return buf; // type unknown, trust the user } }
javascript
function toUint8Array(buf) { if (buf instanceof Uint8Array) { return buf; } else if (buf instanceof ArrayBuffer) { return new Uint8Array(buf); } else if (Buffer.isBuffer(buf)) { return new Uint8Array(buf); } else { return buf; // type unknown, trust the user } }
[ "function", "toUint8Array", "(", "buf", ")", "{", "if", "(", "buf", "instanceof", "Uint8Array", ")", "{", "return", "buf", ";", "}", "else", "if", "(", "buf", "instanceof", "ArrayBuffer", ")", "{", "return", "new", "Uint8Array", "(", "buf", ")", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "buf", ")", ")", "{", "return", "new", "Uint8Array", "(", "buf", ")", ";", "}", "else", "{", "return", "buf", ";", "}", "}" ]
Converts any buffer to Uint8Array @param {Buffer|ArrayBuffer|Uint8Array} buf Input buffer @returns {Uint8Array}
[ "Converts", "any", "buffer", "to", "Uint8Array" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L52-L62
train
gchudnov/inkjet
build/lib/buffer-utils.js
bufferToArrayBuffer
function bufferToArrayBuffer(buf) { const arr = new ArrayBuffer(buf.length); const view = new Uint8Array(arr); for (let i = 0; i < buf.length; ++i) { view[i] = buf[i]; } return arr; }
javascript
function bufferToArrayBuffer(buf) { const arr = new ArrayBuffer(buf.length); const view = new Uint8Array(arr); for (let i = 0; i < buf.length; ++i) { view[i] = buf[i]; } return arr; }
[ "function", "bufferToArrayBuffer", "(", "buf", ")", "{", "const", "arr", "=", "new", "ArrayBuffer", "(", "buf", ".", "length", ")", ";", "const", "view", "=", "new", "Uint8Array", "(", "arr", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "buf", ".", "length", ";", "++", "i", ")", "{", "view", "[", "i", "]", "=", "buf", "[", "i", "]", ";", "}", "return", "arr", ";", "}" ]
Buffer -> ArrayBuffer @param {Buffer|Uint8Array} buf @returns {ArrayBuffer}
[ "Buffer", "-", ">", "ArrayBuffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L86-L93
train
gchudnov/inkjet
build/lib/decode.js
decode
function decode(buf, options, cb) { function getData(j, width, height) { const dest = { width: width, height: height, data: new Uint8Array(width * height * 4) }; j.copyToImageData(dest); return dest.data; } try { const j = new _jpg.JpegImage(); j.parse(buf); const width = options.width || j.width; const height = options.height || j.height; const data = getData(j, width, height); const result = { width: width, height: height, data: data }; cb(null, result); } catch (err) { if (typeof err === 'string') { // jpg.js throws 'string' values, convert to an Error err = new Error(err); } cb(err); } }
javascript
function decode(buf, options, cb) { function getData(j, width, height) { const dest = { width: width, height: height, data: new Uint8Array(width * height * 4) }; j.copyToImageData(dest); return dest.data; } try { const j = new _jpg.JpegImage(); j.parse(buf); const width = options.width || j.width; const height = options.height || j.height; const data = getData(j, width, height); const result = { width: width, height: height, data: data }; cb(null, result); } catch (err) { if (typeof err === 'string') { // jpg.js throws 'string' values, convert to an Error err = new Error(err); } cb(err); } }
[ "function", "decode", "(", "buf", ",", "options", ",", "cb", ")", "{", "function", "getData", "(", "j", ",", "width", ",", "height", ")", "{", "const", "dest", "=", "{", "width", ":", "width", ",", "height", ":", "height", ",", "data", ":", "new", "Uint8Array", "(", "width", "*", "height", "*", "4", ")", "}", ";", "j", ".", "copyToImageData", "(", "dest", ")", ";", "return", "dest", ".", "data", ";", "}", "try", "{", "const", "j", "=", "new", "_jpg", ".", "JpegImage", "(", ")", ";", "j", ".", "parse", "(", "buf", ")", ";", "const", "width", "=", "options", ".", "width", "||", "j", ".", "width", ";", "const", "height", "=", "options", ".", "height", "||", "j", ".", "height", ";", "const", "data", "=", "getData", "(", "j", ",", "width", ",", "height", ")", ";", "const", "result", "=", "{", "width", ":", "width", ",", "height", ":", "height", ",", "data", ":", "data", "}", ";", "cb", "(", "null", ",", "result", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "typeof", "err", "===", "'string'", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "cb", "(", "err", ")", ";", "}", "}" ]
Decode the JPEG data @param buf Uint8Array @param options Object { width: number, height: number } @param cb Callback to invoke on completion @callback { width: number, height: number, data: Uint8Array }
[ "Decode", "the", "JPEG", "data" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/decode.js#L19-L52
train
gchudnov/inkjet
build/lib/exif.js
exif
function exif(buf, options, cb) { try { const exif = new _ExifReader.ExifReader(); exif.load(buf); // The MakerNote tag can be really large. Remove it to lower memory usage. if (!options.hasOwnProperty('hasMakerNote') || !options.hasMakerNote) { exif.deleteTag('MakerNote'); } const metadata = exif.getAllTags(); cb(null, metadata); } catch (err) { if (err.message === 'No Exif data') { cb(null, {}); } else { cb(err); } } }
javascript
function exif(buf, options, cb) { try { const exif = new _ExifReader.ExifReader(); exif.load(buf); // The MakerNote tag can be really large. Remove it to lower memory usage. if (!options.hasOwnProperty('hasMakerNote') || !options.hasMakerNote) { exif.deleteTag('MakerNote'); } const metadata = exif.getAllTags(); cb(null, metadata); } catch (err) { if (err.message === 'No Exif data') { cb(null, {}); } else { cb(err); } } }
[ "function", "exif", "(", "buf", ",", "options", ",", "cb", ")", "{", "try", "{", "const", "exif", "=", "new", "_ExifReader", ".", "ExifReader", "(", ")", ";", "exif", ".", "load", "(", "buf", ")", ";", "if", "(", "!", "options", ".", "hasOwnProperty", "(", "'hasMakerNote'", ")", "||", "!", "options", ".", "hasMakerNote", ")", "{", "exif", ".", "deleteTag", "(", "'MakerNote'", ")", ";", "}", "const", "metadata", "=", "exif", ".", "getAllTags", "(", ")", ";", "cb", "(", "null", ",", "metadata", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "message", "===", "'No Exif data'", ")", "{", "cb", "(", "null", ",", "{", "}", ")", ";", "}", "else", "{", "cb", "(", "err", ")", ";", "}", "}", "}" ]
Read EXIF data from the provided buffer @param buf ArrayBuffer @param options Object { hasMakerNote: true|false } @param cb Callback to invoke on completion @callback Object { name: value, ... }
[ "Read", "EXIF", "data", "from", "the", "provided", "buffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/exif.js#L19-L39
train
gchudnov/inkjet
build/lib/info.js
info
function info(buf, cb) { setTimeout(() => { const info = (0, _imageinfo2.default)(buf); if (!info) { cb(new Error('Cannot get image info')); } else { cb(null, { type: info.type, mimeType: info.mimeType, extension: info.format.toLowerCase(), width: info.width, height: info.height }); } }, 0); }
javascript
function info(buf, cb) { setTimeout(() => { const info = (0, _imageinfo2.default)(buf); if (!info) { cb(new Error('Cannot get image info')); } else { cb(null, { type: info.type, mimeType: info.mimeType, extension: info.format.toLowerCase(), width: info.width, height: info.height }); } }, 0); }
[ "function", "info", "(", "buf", ",", "cb", ")", "{", "setTimeout", "(", "(", ")", "=>", "{", "const", "info", "=", "(", "0", ",", "_imageinfo2", ".", "default", ")", "(", "buf", ")", ";", "if", "(", "!", "info", ")", "{", "cb", "(", "new", "Error", "(", "'Cannot get image info'", ")", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "{", "type", ":", "info", ".", "type", ",", "mimeType", ":", "info", ".", "mimeType", ",", "extension", ":", "info", ".", "format", ".", "toLowerCase", "(", ")", ",", "width", ":", "info", ".", "width", ",", "height", ":", "info", ".", "height", "}", ")", ";", "}", "}", ",", "0", ")", ";", "}" ]
Get image information @param {Buffer} buf Image or image part that contains image parameters @param {function} cb Callback to invoke on completion
[ "Get", "image", "information" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/info.js#L19-L34
train
hdnpt/geartrack
src/malaysiaPosTracker.js
obtainInfo
function obtainInfo(action, id, cb) { request.post({ url: action, form: { trackingNo03: id }, timeout: 20000 }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('Please insert the correct Tracking Number.') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createMalaysiaPosEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }) }
javascript
function obtainInfo(action, id, cb) { request.post({ url: action, form: { trackingNo03: id }, timeout: 20000 }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('Please insert the correct Tracking Number.') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createMalaysiaPosEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }) }
[ "function", "obtainInfo", "(", "action", ",", "id", ",", "cb", ")", "{", "request", ".", "post", "(", "{", "url", ":", "action", ",", "form", ":", "{", "trackingNo03", ":", "id", "}", ",", "timeout", ":", "20000", "}", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "error", "||", "response", ".", "statusCode", "!=", "200", ")", "{", "cb", "(", "utils", ".", "errorDown", "(", ")", ")", "return", "}", "if", "(", "body", ".", "indexOf", "(", "'Please insert the correct Tracking Number.'", ")", "!=", "-", "1", ")", "{", "cb", "(", "utils", ".", "errorNoData", "(", ")", ")", "return", "}", "let", "entity", "=", "null", "try", "{", "entity", "=", "createMalaysiaPosEntity", "(", "body", ")", "}", "catch", "(", "error", ")", "{", "return", "cb", "(", "utils", ".", "errorParser", "(", "id", ",", "error", ".", "message", ")", ")", "}", "cb", "(", "null", ",", "entity", ")", "}", ")", "}" ]
Get info from malaysiaPos page @param action @param id @param postalcode @param cb
[ "Get", "info", "from", "malaysiaPos", "page" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/malaysiaPosTracker.js#L35-L63
train
hdnpt/geartrack
src/malaysiaPosTracker.js
createMalaysiaPosEntity
function createMalaysiaPosEntity(html) { let $ = parser.load(html) let id = $('#trackingNo03').get(0).children[0].data.trim() let init = html.indexOf("var strTD") init = html.indexOf('"', init + 1) let fin = html.indexOf('"', init + 1) let strTD = html.substring(init, fin) $ = parser.load(strTD) let trs = $('#tbDetails tbody tr') let states = utils.tableParser( trs, { 'date': { 'idx': 0, 'mandatory': true, 'parser': elem => { return moment.tz(elem, 'DD MMM YYYY HH:mm:ss', 'en', zone).format() } }, 'state': {'idx': 1, 'mandatory': true}, 'area': {'idx': 2} }, elem => { // On Maintenance there is a row with a td colspan=4, we want to skip it if(elem.children[0].attribs && elem.children[0].attribs.colspan && elem.children[0].attribs.colspan == 4) { return false } return true }) return new MalaysiaInfo({ id: id, state: states[0].state, states: states }) }
javascript
function createMalaysiaPosEntity(html) { let $ = parser.load(html) let id = $('#trackingNo03').get(0).children[0].data.trim() let init = html.indexOf("var strTD") init = html.indexOf('"', init + 1) let fin = html.indexOf('"', init + 1) let strTD = html.substring(init, fin) $ = parser.load(strTD) let trs = $('#tbDetails tbody tr') let states = utils.tableParser( trs, { 'date': { 'idx': 0, 'mandatory': true, 'parser': elem => { return moment.tz(elem, 'DD MMM YYYY HH:mm:ss', 'en', zone).format() } }, 'state': {'idx': 1, 'mandatory': true}, 'area': {'idx': 2} }, elem => { // On Maintenance there is a row with a td colspan=4, we want to skip it if(elem.children[0].attribs && elem.children[0].attribs.colspan && elem.children[0].attribs.colspan == 4) { return false } return true }) return new MalaysiaInfo({ id: id, state: states[0].state, states: states }) }
[ "function", "createMalaysiaPosEntity", "(", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "id", "=", "$", "(", "'#trackingNo03'", ")", ".", "get", "(", "0", ")", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "let", "init", "=", "html", ".", "indexOf", "(", "\"var strTD\"", ")", "init", "=", "html", ".", "indexOf", "(", "'\"'", ",", "init", "+", "1", ")", "let", "fin", "=", "html", ".", "indexOf", "(", "'\"'", ",", "init", "+", "1", ")", "let", "strTD", "=", "html", ".", "substring", "(", "init", ",", "fin", ")", "$", "=", "parser", ".", "load", "(", "strTD", ")", "let", "trs", "=", "$", "(", "'#tbDetails tbody tr'", ")", "let", "states", "=", "utils", ".", "tableParser", "(", "trs", ",", "{", "'date'", ":", "{", "'idx'", ":", "0", ",", "'mandatory'", ":", "true", ",", "'parser'", ":", "elem", "=>", "{", "return", "moment", ".", "tz", "(", "elem", ",", "'DD MMM YYYY HH:mm:ss'", ",", "'en'", ",", "zone", ")", ".", "format", "(", ")", "}", "}", ",", "'state'", ":", "{", "'idx'", ":", "1", ",", "'mandatory'", ":", "true", "}", ",", "'area'", ":", "{", "'idx'", ":", "2", "}", "}", ",", "elem", "=>", "{", "if", "(", "elem", ".", "children", "[", "0", "]", ".", "attribs", "&&", "elem", ".", "children", "[", "0", "]", ".", "attribs", ".", "colspan", "&&", "elem", ".", "children", "[", "0", "]", ".", "attribs", ".", "colspan", "==", "4", ")", "{", "return", "false", "}", "return", "true", "}", ")", "return", "new", "MalaysiaInfo", "(", "{", "id", ":", "id", ",", "state", ":", "states", "[", "0", "]", ".", "state", ",", "states", ":", "states", "}", ")", "}" ]
Create malaysiaPos entity from html @param html
[ "Create", "malaysiaPos", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/malaysiaPosTracker.js#L69-L108
train
hdnpt/geartrack
src/cttTracker.js
createCttEntity
function createCttEntity(id, html, cb) { let state = null let messages = [] try { html = htmlBeautify(html) let $ = parser.load(html) let table = $('table.full-width tr').get(1).children.filter(e => e.type == 'tag') let dayAndHours = table[2].children[0].data.trim() + ' ' + table[3].children[0].data.trim() state = { date: moment.tz(dayAndHours, "YYYY/MM/DD HH:mm", zone).format() } if(table[4].children.length == 0) { state['status'] = 'Sem estado' } else { if(table[4].children[0].data) { state['status'] = table[4].children[0].data.trim() } else { state['status'] = table[4].children[0].children[0].data.trim() } } let details = $('#details_0').find('tr') let day = "" let dayUnformated = "" let message = {} for(let i = 0; i < details.length; i++) { let tr = details.get(i) if(tr.children.length >= 8){ let idxsum = 0 if(tr.children.length >= 9) { day = tr.children[0].children[0].data.trim() dayUnformated = day.split(',')[1].trim() day = moment.tz(dayUnformated, "DD MMMM YYYY", 'pt', zone).format() message = { day: day, status: [] } messages.push(message) idxsum = 1 } let hours = tr.children[0+idxsum].children[0].data.trim() let time = moment.tz(dayUnformated + ' ' + hours, "DD MMMM YYYY HH:mm", 'pt', zone).format() let add = { time: time, status: tr.children[2+idxsum].children[0].data.trim(), local: tr.children[6+idxsum].children[0].data.trim() } message.status.push(add) } } } catch (error) { return cb(error) } cb(null, new CttInfo(id, state, messages)) }
javascript
function createCttEntity(id, html, cb) { let state = null let messages = [] try { html = htmlBeautify(html) let $ = parser.load(html) let table = $('table.full-width tr').get(1).children.filter(e => e.type == 'tag') let dayAndHours = table[2].children[0].data.trim() + ' ' + table[3].children[0].data.trim() state = { date: moment.tz(dayAndHours, "YYYY/MM/DD HH:mm", zone).format() } if(table[4].children.length == 0) { state['status'] = 'Sem estado' } else { if(table[4].children[0].data) { state['status'] = table[4].children[0].data.trim() } else { state['status'] = table[4].children[0].children[0].data.trim() } } let details = $('#details_0').find('tr') let day = "" let dayUnformated = "" let message = {} for(let i = 0; i < details.length; i++) { let tr = details.get(i) if(tr.children.length >= 8){ let idxsum = 0 if(tr.children.length >= 9) { day = tr.children[0].children[0].data.trim() dayUnformated = day.split(',')[1].trim() day = moment.tz(dayUnformated, "DD MMMM YYYY", 'pt', zone).format() message = { day: day, status: [] } messages.push(message) idxsum = 1 } let hours = tr.children[0+idxsum].children[0].data.trim() let time = moment.tz(dayUnformated + ' ' + hours, "DD MMMM YYYY HH:mm", 'pt', zone).format() let add = { time: time, status: tr.children[2+idxsum].children[0].data.trim(), local: tr.children[6+idxsum].children[0].data.trim() } message.status.push(add) } } } catch (error) { return cb(error) } cb(null, new CttInfo(id, state, messages)) }
[ "function", "createCttEntity", "(", "id", ",", "html", ",", "cb", ")", "{", "let", "state", "=", "null", "let", "messages", "=", "[", "]", "try", "{", "html", "=", "htmlBeautify", "(", "html", ")", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "table", "=", "$", "(", "'table.full-width tr'", ")", ".", "get", "(", "1", ")", ".", "children", ".", "filter", "(", "e", "=>", "e", ".", "type", "==", "'tag'", ")", "let", "dayAndHours", "=", "table", "[", "2", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "+", "' '", "+", "table", "[", "3", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "state", "=", "{", "date", ":", "moment", ".", "tz", "(", "dayAndHours", ",", "\"YYYY/MM/DD HH:mm\"", ",", "zone", ")", ".", "format", "(", ")", "}", "if", "(", "table", "[", "4", "]", ".", "children", ".", "length", "==", "0", ")", "{", "state", "[", "'status'", "]", "=", "'Sem estado'", "}", "else", "{", "if", "(", "table", "[", "4", "]", ".", "children", "[", "0", "]", ".", "data", ")", "{", "state", "[", "'status'", "]", "=", "table", "[", "4", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "}", "else", "{", "state", "[", "'status'", "]", "=", "table", "[", "4", "]", ".", "children", "[", "0", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "}", "}", "let", "details", "=", "$", "(", "'#details_0'", ")", ".", "find", "(", "'tr'", ")", "let", "day", "=", "\"\"", "let", "dayUnformated", "=", "\"\"", "let", "message", "=", "{", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "details", ".", "length", ";", "i", "++", ")", "{", "let", "tr", "=", "details", ".", "get", "(", "i", ")", "if", "(", "tr", ".", "children", ".", "length", ">=", "8", ")", "{", "let", "idxsum", "=", "0", "if", "(", "tr", ".", "children", ".", "length", ">=", "9", ")", "{", "day", "=", "tr", ".", "children", "[", "0", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "dayUnformated", "=", "day", ".", "split", "(", "','", ")", "[", "1", "]", ".", "trim", "(", ")", "day", "=", "moment", ".", "tz", "(", "dayUnformated", ",", "\"DD MMMM YYYY\"", ",", "'pt'", ",", "zone", ")", ".", "format", "(", ")", "message", "=", "{", "day", ":", "day", ",", "status", ":", "[", "]", "}", "messages", ".", "push", "(", "message", ")", "idxsum", "=", "1", "}", "let", "hours", "=", "tr", ".", "children", "[", "0", "+", "idxsum", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "let", "time", "=", "moment", ".", "tz", "(", "dayUnformated", "+", "' '", "+", "hours", ",", "\"DD MMMM YYYY HH:mm\"", ",", "'pt'", ",", "zone", ")", ".", "format", "(", ")", "let", "add", "=", "{", "time", ":", "time", ",", "status", ":", "tr", ".", "children", "[", "2", "+", "idxsum", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", ",", "local", ":", "tr", ".", "children", "[", "6", "+", "idxsum", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "}", "message", ".", "status", ".", "push", "(", "add", ")", "}", "}", "}", "catch", "(", "error", ")", "{", "return", "cb", "(", "error", ")", "}", "cb", "(", "null", ",", "new", "CttInfo", "(", "id", ",", "state", ",", "messages", ")", ")", "}" ]
Create ctt entity from html @param id @param html @param cb
[ "Create", "ctt", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/cttTracker.js#L75-L140
train
hdnpt/geartrack
src/pitneybowesTracker.js
obtainInfo
function obtainInfo(id, action, cb) { request.get({ url: action, timeout: 20000, strictSSL: false }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('errorMessage') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createParcelTrackerEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } if(entity != null) cb(null, entity) }) }
javascript
function obtainInfo(id, action, cb) { request.get({ url: action, timeout: 20000, strictSSL: false }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('errorMessage') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createParcelTrackerEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } if(entity != null) cb(null, entity) }) }
[ "function", "obtainInfo", "(", "id", ",", "action", ",", "cb", ")", "{", "request", ".", "get", "(", "{", "url", ":", "action", ",", "timeout", ":", "20000", ",", "strictSSL", ":", "false", "}", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "error", "||", "response", ".", "statusCode", "!=", "200", ")", "{", "cb", "(", "utils", ".", "errorDown", "(", ")", ")", "return", "}", "if", "(", "body", ".", "indexOf", "(", "'errorMessage'", ")", "!=", "-", "1", ")", "{", "cb", "(", "utils", ".", "errorNoData", "(", ")", ")", "return", "}", "let", "entity", "=", "null", "try", "{", "entity", "=", "createParcelTrackerEntity", "(", "body", ")", "}", "catch", "(", "error", ")", "{", "return", "cb", "(", "utils", ".", "errorParser", "(", "id", ",", "error", ".", "message", ")", ")", "}", "if", "(", "entity", "!=", "null", ")", "cb", "(", "null", ",", "entity", ")", "}", ")", "}" ]
Get info from parcel tracker request @param action @param id @param cb
[ "Get", "info", "from", "parcel", "tracker", "request" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/pitneybowesTracker.js#L30-L56
train
hdnpt/geartrack
src/pitneybowesTracker.js
createParcelTrackerEntity
function createParcelTrackerEntity(body) { const data = JSON.parse(body) const states = [] data.scanHistory.scanDetails.forEach((elem) => { const state = { state : elem.eventDescription, date : elem.eventDate + "T" + elem.eventTime } if(elem.eventLocation && elem.eventLocation.country && elem.eventLocation.countyOrRegion && elem.eventLocation.city){ state.area = elem.eventLocation.country + " - " + elem.eventLocation.countyOrRegion + " - " + elem.eventLocation.city } states.push(state) }) return new ParcelTrackerInfo({ attempts: 1, id: data.packageIdentifier, state: data.currentStatus.eventDescription, carrier: data.carrier, origin: data.senderLocation.country + " - " + data.senderLocation.countyOrRegion + " - " + data.senderLocation.city, destiny: data.destinationLocation.country + " - " + data.destinationLocation.countyOrRegion + " - " + data.destinationLocation.city, states: states }) }
javascript
function createParcelTrackerEntity(body) { const data = JSON.parse(body) const states = [] data.scanHistory.scanDetails.forEach((elem) => { const state = { state : elem.eventDescription, date : elem.eventDate + "T" + elem.eventTime } if(elem.eventLocation && elem.eventLocation.country && elem.eventLocation.countyOrRegion && elem.eventLocation.city){ state.area = elem.eventLocation.country + " - " + elem.eventLocation.countyOrRegion + " - " + elem.eventLocation.city } states.push(state) }) return new ParcelTrackerInfo({ attempts: 1, id: data.packageIdentifier, state: data.currentStatus.eventDescription, carrier: data.carrier, origin: data.senderLocation.country + " - " + data.senderLocation.countyOrRegion + " - " + data.senderLocation.city, destiny: data.destinationLocation.country + " - " + data.destinationLocation.countyOrRegion + " - " + data.destinationLocation.city, states: states }) }
[ "function", "createParcelTrackerEntity", "(", "body", ")", "{", "const", "data", "=", "JSON", ".", "parse", "(", "body", ")", "const", "states", "=", "[", "]", "data", ".", "scanHistory", ".", "scanDetails", ".", "forEach", "(", "(", "elem", ")", "=>", "{", "const", "state", "=", "{", "state", ":", "elem", ".", "eventDescription", ",", "date", ":", "elem", ".", "eventDate", "+", "\"T\"", "+", "elem", ".", "eventTime", "}", "if", "(", "elem", ".", "eventLocation", "&&", "elem", ".", "eventLocation", ".", "country", "&&", "elem", ".", "eventLocation", ".", "countyOrRegion", "&&", "elem", ".", "eventLocation", ".", "city", ")", "{", "state", ".", "area", "=", "elem", ".", "eventLocation", ".", "country", "+", "\" - \"", "+", "elem", ".", "eventLocation", ".", "countyOrRegion", "+", "\" - \"", "+", "elem", ".", "eventLocation", ".", "city", "}", "states", ".", "push", "(", "state", ")", "}", ")", "return", "new", "ParcelTrackerInfo", "(", "{", "attempts", ":", "1", ",", "id", ":", "data", ".", "packageIdentifier", ",", "state", ":", "data", ".", "currentStatus", ".", "eventDescription", ",", "carrier", ":", "data", ".", "carrier", ",", "origin", ":", "data", ".", "senderLocation", ".", "country", "+", "\" - \"", "+", "data", ".", "senderLocation", ".", "countyOrRegion", "+", "\" - \"", "+", "data", ".", "senderLocation", ".", "city", ",", "destiny", ":", "data", ".", "destinationLocation", ".", "country", "+", "\" - \"", "+", "data", ".", "destinationLocation", ".", "countyOrRegion", "+", "\" - \"", "+", "data", ".", "destinationLocation", ".", "city", ",", "states", ":", "states", "}", ")", "}" ]
Create parcel tracker entity from html @param html
[ "Create", "parcel", "tracker", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/pitneybowesTracker.js#L62-L95
train
hdnpt/geartrack
src/utils.js
function (type, error = null, id = null) { type = type.toUpperCase() let errors = { 'NO_DATA': 'No info for that id yet. Or maybe the data provided was wrong.', 'BUSY': 'The server providing the info is busy right now. Try again.', 'UNAVAILABLE': 'The server providing the info is unavailable right now. Try again later.', 'EMPTY': 'The provider server was parsed correctly, but has no data to show. Try Again later.', 'DOWN': 'The provider server is currently down. Try Again later.', 'PARSER': 'Something went wrong when parsing the provider website.', 'ACTION_REQUIRED': 'That tracker requires an aditional step in their website.' } let message = error != null ? error : errors[type] message = id != null ? message + ' ID:' + id : message return new Error(type + ' - ' + message) }
javascript
function (type, error = null, id = null) { type = type.toUpperCase() let errors = { 'NO_DATA': 'No info for that id yet. Or maybe the data provided was wrong.', 'BUSY': 'The server providing the info is busy right now. Try again.', 'UNAVAILABLE': 'The server providing the info is unavailable right now. Try again later.', 'EMPTY': 'The provider server was parsed correctly, but has no data to show. Try Again later.', 'DOWN': 'The provider server is currently down. Try Again later.', 'PARSER': 'Something went wrong when parsing the provider website.', 'ACTION_REQUIRED': 'That tracker requires an aditional step in their website.' } let message = error != null ? error : errors[type] message = id != null ? message + ' ID:' + id : message return new Error(type + ' - ' + message) }
[ "function", "(", "type", ",", "error", "=", "null", ",", "id", "=", "null", ")", "{", "type", "=", "type", ".", "toUpperCase", "(", ")", "let", "errors", "=", "{", "'NO_DATA'", ":", "'No info for that id yet. Or maybe the data provided was wrong.'", ",", "'BUSY'", ":", "'The server providing the info is busy right now. Try again.'", ",", "'UNAVAILABLE'", ":", "'The server providing the info is unavailable right now. Try again later.'", ",", "'EMPTY'", ":", "'The provider server was parsed correctly, but has no data to show. Try Again later.'", ",", "'DOWN'", ":", "'The provider server is currently down. Try Again later.'", ",", "'PARSER'", ":", "'Something went wrong when parsing the provider website.'", ",", "'ACTION_REQUIRED'", ":", "'That tracker requires an aditional step in their website.'", "}", "let", "message", "=", "error", "!=", "null", "?", "error", ":", "errors", "[", "type", "]", "message", "=", "id", "!=", "null", "?", "message", "+", "' ID:'", "+", "id", ":", "message", "return", "new", "Error", "(", "type", "+", "' - '", "+", "message", ")", "}" ]
Get the Error message by Type @param type @param error Error message @returns {Error}
[ "Get", "the", "Error", "message", "by", "Type" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/utils.js#L10-L25
train
hdnpt/geartrack
src/correosESTracker.js
createCorreosEsEntity
function createCorreosEsEntity(id, html) { let $ = parser.load(html) let table2 = $('#Table2').get(0); let states = [] const fields = ['date', 'info'] if (table2.children.length === 0 || (table2.children[1] !== undefined && table2.children[1].data !== undefined && table2.children[1].data.trim() === 'fin tabla descripciones')) return null; table2.children.forEach(function (elem) { if (elem.attribs !== undefined && elem.attribs.class.trim() === 'txtCabeceraTabla') { let state = {} elem.children.forEach(function (_child) { if (_child.attribs !== undefined && _child.attribs.class !== undefined) { let _class = _child.attribs.class.trim() if (_class === 'txtDescripcionTabla') { state['date'] = moment.tz(_child.children[0].data.trim(), "DD/MM/YYYY", zone).format() } else if (_class === 'txtContenidoTabla' || _class === 'txtContenidoTablaOff') { state['state'] = _child.children[1].children[0].data.trim() if (_child.children[1].attribs !== undefined && _child.children[1].attribs !== undefined && _child.children[1].attribs.title) { state['title'] = _child.children[1].attribs.title.trim() } } } }) if (Object.keys(state).length > 0) { states.push(state) } } }) return new CorreosESInfo({ 'id': id, 'state': states[states.length - 1].state, 'states': states.reverse() }) }
javascript
function createCorreosEsEntity(id, html) { let $ = parser.load(html) let table2 = $('#Table2').get(0); let states = [] const fields = ['date', 'info'] if (table2.children.length === 0 || (table2.children[1] !== undefined && table2.children[1].data !== undefined && table2.children[1].data.trim() === 'fin tabla descripciones')) return null; table2.children.forEach(function (elem) { if (elem.attribs !== undefined && elem.attribs.class.trim() === 'txtCabeceraTabla') { let state = {} elem.children.forEach(function (_child) { if (_child.attribs !== undefined && _child.attribs.class !== undefined) { let _class = _child.attribs.class.trim() if (_class === 'txtDescripcionTabla') { state['date'] = moment.tz(_child.children[0].data.trim(), "DD/MM/YYYY", zone).format() } else if (_class === 'txtContenidoTabla' || _class === 'txtContenidoTablaOff') { state['state'] = _child.children[1].children[0].data.trim() if (_child.children[1].attribs !== undefined && _child.children[1].attribs !== undefined && _child.children[1].attribs.title) { state['title'] = _child.children[1].attribs.title.trim() } } } }) if (Object.keys(state).length > 0) { states.push(state) } } }) return new CorreosESInfo({ 'id': id, 'state': states[states.length - 1].state, 'states': states.reverse() }) }
[ "function", "createCorreosEsEntity", "(", "id", ",", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "table2", "=", "$", "(", "'#Table2'", ")", ".", "get", "(", "0", ")", ";", "let", "states", "=", "[", "]", "const", "fields", "=", "[", "'date'", ",", "'info'", "]", "if", "(", "table2", ".", "children", ".", "length", "===", "0", "||", "(", "table2", ".", "children", "[", "1", "]", "!==", "undefined", "&&", "table2", ".", "children", "[", "1", "]", ".", "data", "!==", "undefined", "&&", "table2", ".", "children", "[", "1", "]", ".", "data", ".", "trim", "(", ")", "===", "'fin tabla descripciones'", ")", ")", "return", "null", ";", "table2", ".", "children", ".", "forEach", "(", "function", "(", "elem", ")", "{", "if", "(", "elem", ".", "attribs", "!==", "undefined", "&&", "elem", ".", "attribs", ".", "class", ".", "trim", "(", ")", "===", "'txtCabeceraTabla'", ")", "{", "let", "state", "=", "{", "}", "elem", ".", "children", ".", "forEach", "(", "function", "(", "_child", ")", "{", "if", "(", "_child", ".", "attribs", "!==", "undefined", "&&", "_child", ".", "attribs", ".", "class", "!==", "undefined", ")", "{", "let", "_class", "=", "_child", ".", "attribs", ".", "class", ".", "trim", "(", ")", "if", "(", "_class", "===", "'txtDescripcionTabla'", ")", "{", "state", "[", "'date'", "]", "=", "moment", ".", "tz", "(", "_child", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", ",", "\"DD/MM/YYYY\"", ",", "zone", ")", ".", "format", "(", ")", "}", "else", "if", "(", "_class", "===", "'txtContenidoTabla'", "||", "_class", "===", "'txtContenidoTablaOff'", ")", "{", "state", "[", "'state'", "]", "=", "_child", ".", "children", "[", "1", "]", ".", "children", "[", "0", "]", ".", "data", ".", "trim", "(", ")", "if", "(", "_child", ".", "children", "[", "1", "]", ".", "attribs", "!==", "undefined", "&&", "_child", ".", "children", "[", "1", "]", ".", "attribs", "!==", "undefined", "&&", "_child", ".", "children", "[", "1", "]", ".", "attribs", ".", "title", ")", "{", "state", "[", "'title'", "]", "=", "_child", ".", "children", "[", "1", "]", ".", "attribs", ".", "title", ".", "trim", "(", ")", "}", "}", "}", "}", ")", "if", "(", "Object", ".", "keys", "(", "state", ")", ".", "length", ">", "0", ")", "{", "states", ".", "push", "(", "state", ")", "}", "}", "}", ")", "return", "new", "CorreosESInfo", "(", "{", "'id'", ":", "id", ",", "'state'", ":", "states", "[", "states", ".", "length", "-", "1", "]", ".", "state", ",", "'states'", ":", "states", ".", "reverse", "(", ")", "}", ")", "}" ]
Create correos.es entity from html @param html
[ "Create", "correos", ".", "es", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/correosESTracker.js#L59-L103
train
hdnpt/geartrack
src/cjahTracker.js
createCjahEntity
function createCjahEntity(id, html, cb) { let entity = null try { let $ = parser.load(html) let trs = $('table tbody tr') // Not found if (!trs || trs.length === 0) { cb(utils.errorNoData()) return } let states = utils.tableParser( trs, { 'id': { 'idx': 1, 'mandatory': true }, 'date': {'idx': 3, 'mandatory': true, 'parser': elem => { return moment.tz( elem, 'DD/MM/YYYY h:mm:ssa', 'en', zone).format()}}, 'state': { 'idx': 5, 'mandatory': true } }, elem => true) entity = new CjahInfo({ id: states[0].id, state: states[0].state, states: states }) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }
javascript
function createCjahEntity(id, html, cb) { let entity = null try { let $ = parser.load(html) let trs = $('table tbody tr') // Not found if (!trs || trs.length === 0) { cb(utils.errorNoData()) return } let states = utils.tableParser( trs, { 'id': { 'idx': 1, 'mandatory': true }, 'date': {'idx': 3, 'mandatory': true, 'parser': elem => { return moment.tz( elem, 'DD/MM/YYYY h:mm:ssa', 'en', zone).format()}}, 'state': { 'idx': 5, 'mandatory': true } }, elem => true) entity = new CjahInfo({ id: states[0].id, state: states[0].state, states: states }) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }
[ "function", "createCjahEntity", "(", "id", ",", "html", ",", "cb", ")", "{", "let", "entity", "=", "null", "try", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "trs", "=", "$", "(", "'table tbody tr'", ")", "if", "(", "!", "trs", "||", "trs", ".", "length", "===", "0", ")", "{", "cb", "(", "utils", ".", "errorNoData", "(", ")", ")", "return", "}", "let", "states", "=", "utils", ".", "tableParser", "(", "trs", ",", "{", "'id'", ":", "{", "'idx'", ":", "1", ",", "'mandatory'", ":", "true", "}", ",", "'date'", ":", "{", "'idx'", ":", "3", ",", "'mandatory'", ":", "true", ",", "'parser'", ":", "elem", "=>", "{", "return", "moment", ".", "tz", "(", "elem", ",", "'DD/MM/YYYY h:mm:ssa'", ",", "'en'", ",", "zone", ")", ".", "format", "(", ")", "}", "}", ",", "'state'", ":", "{", "'idx'", ":", "5", ",", "'mandatory'", ":", "true", "}", "}", ",", "elem", "=>", "true", ")", "entity", "=", "new", "CjahInfo", "(", "{", "id", ":", "states", "[", "0", "]", ".", "id", ",", "state", ":", "states", "[", "0", "]", ".", "state", ",", "states", ":", "states", "}", ")", "}", "catch", "(", "error", ")", "{", "return", "cb", "(", "utils", ".", "errorParser", "(", "id", ",", "error", ".", "message", ")", ")", "}", "cb", "(", "null", ",", "entity", ")", "}" ]
Create cjah entity from html @param id @param html @param cb
[ "Create", "cjah", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/cjahTracker.js#L44-L75
train
hdnpt/geartrack
src/singpostTracker.js
createSingpostEntity
function createSingpostEntity(id, html) { let $ = parser.load(html) let date = [] $('span.tacking-date').each(function (i, elem) { date.push($(this).text().trim()) }) let status = [] $('div.tacking-status').each(function (i, elem) { status.push($(this).text().trim()) }) let messages = [] for(let i = 0; i < date.length; i++) { messages.push({ date: moment.tz(date[i], "DD-MM-YYYY", zone).format(), state: status[i].replace(/ \(Country.+\)/ig, "").trim() // remove '(Country: PT)' }) } return new SingpostInfo(id, messages) }
javascript
function createSingpostEntity(id, html) { let $ = parser.load(html) let date = [] $('span.tacking-date').each(function (i, elem) { date.push($(this).text().trim()) }) let status = [] $('div.tacking-status').each(function (i, elem) { status.push($(this).text().trim()) }) let messages = [] for(let i = 0; i < date.length; i++) { messages.push({ date: moment.tz(date[i], "DD-MM-YYYY", zone).format(), state: status[i].replace(/ \(Country.+\)/ig, "").trim() // remove '(Country: PT)' }) } return new SingpostInfo(id, messages) }
[ "function", "createSingpostEntity", "(", "id", ",", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "date", "=", "[", "]", "$", "(", "'span.tacking-date'", ")", ".", "each", "(", "function", "(", "i", ",", "elem", ")", "{", "date", ".", "push", "(", "$", "(", "this", ")", ".", "text", "(", ")", ".", "trim", "(", ")", ")", "}", ")", "let", "status", "=", "[", "]", "$", "(", "'div.tacking-status'", ")", ".", "each", "(", "function", "(", "i", ",", "elem", ")", "{", "status", ".", "push", "(", "$", "(", "this", ")", ".", "text", "(", ")", ".", "trim", "(", ")", ")", "}", ")", "let", "messages", "=", "[", "]", "for", "(", "let", "i", "=", "0", ";", "i", "<", "date", ".", "length", ";", "i", "++", ")", "{", "messages", ".", "push", "(", "{", "date", ":", "moment", ".", "tz", "(", "date", "[", "i", "]", ",", "\"DD-MM-YYYY\"", ",", "zone", ")", ".", "format", "(", ")", ",", "state", ":", "status", "[", "i", "]", ".", "replace", "(", "/", " \\(Country.+\\)", "/", "ig", ",", "\"\"", ")", ".", "trim", "(", ")", "}", ")", "}", "return", "new", "SingpostInfo", "(", "id", ",", "messages", ")", "}" ]
Create singpost entity from html @param id @param html
[ "Create", "singpost", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/singpostTracker.js#L66-L88
train
hdnpt/geartrack
src/panasiaTracker.js
createPanasiaEntity
function createPanasiaEntity(html, id) { let $ = parser.load(html) let td11 = $('.one-parcel .td11').contents() let orderNumber = td11[1].data let product = td11[3].data let td22 = $('.one-parcel .td22').contents() let trackingNumber = td22[1].data let country = utils.removeChineseChars(td22[3].data).trim() let td33 = $('.one-parcel .td33').contents() let dates = [] for(let i = 1; i < td33.length; ++i) { let date = td33[i].children[1].data dates.push(moment.tz(date, "YYYY-MM-DD HH:mm:ss", zone).format()) } let td44 = $('.one-parcel .td44').contents() let states = [] for(let i = 0; i < td44.length; ++i) { let s = td44[i].children[0].data states.push(s.replace(',', ', ').replace('En tr?nsito', 'En transito')) } let finalStates = [] for(let i = 0; i < dates.length; ++i) { finalStates.push({ state: states[i], date: dates[i] }) } return new PanasiaInfo({ orderNumber: orderNumber, product: product, id: id, country: country, states: finalStates.sort((a, b) => { let dateA = moment(a.date), dateB = moment(b.date) return dateA < dateB }) }) }
javascript
function createPanasiaEntity(html, id) { let $ = parser.load(html) let td11 = $('.one-parcel .td11').contents() let orderNumber = td11[1].data let product = td11[3].data let td22 = $('.one-parcel .td22').contents() let trackingNumber = td22[1].data let country = utils.removeChineseChars(td22[3].data).trim() let td33 = $('.one-parcel .td33').contents() let dates = [] for(let i = 1; i < td33.length; ++i) { let date = td33[i].children[1].data dates.push(moment.tz(date, "YYYY-MM-DD HH:mm:ss", zone).format()) } let td44 = $('.one-parcel .td44').contents() let states = [] for(let i = 0; i < td44.length; ++i) { let s = td44[i].children[0].data states.push(s.replace(',', ', ').replace('En tr?nsito', 'En transito')) } let finalStates = [] for(let i = 0; i < dates.length; ++i) { finalStates.push({ state: states[i], date: dates[i] }) } return new PanasiaInfo({ orderNumber: orderNumber, product: product, id: id, country: country, states: finalStates.sort((a, b) => { let dateA = moment(a.date), dateB = moment(b.date) return dateA < dateB }) }) }
[ "function", "createPanasiaEntity", "(", "html", ",", "id", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "td11", "=", "$", "(", "'.one-parcel .td11'", ")", ".", "contents", "(", ")", "let", "orderNumber", "=", "td11", "[", "1", "]", ".", "data", "let", "product", "=", "td11", "[", "3", "]", ".", "data", "let", "td22", "=", "$", "(", "'.one-parcel .td22'", ")", ".", "contents", "(", ")", "let", "trackingNumber", "=", "td22", "[", "1", "]", ".", "data", "let", "country", "=", "utils", ".", "removeChineseChars", "(", "td22", "[", "3", "]", ".", "data", ")", ".", "trim", "(", ")", "let", "td33", "=", "$", "(", "'.one-parcel .td33'", ")", ".", "contents", "(", ")", "let", "dates", "=", "[", "]", "for", "(", "let", "i", "=", "1", ";", "i", "<", "td33", ".", "length", ";", "++", "i", ")", "{", "let", "date", "=", "td33", "[", "i", "]", ".", "children", "[", "1", "]", ".", "data", "dates", ".", "push", "(", "moment", ".", "tz", "(", "date", ",", "\"YYYY-MM-DD HH:mm:ss\"", ",", "zone", ")", ".", "format", "(", ")", ")", "}", "let", "td44", "=", "$", "(", "'.one-parcel .td44'", ")", ".", "contents", "(", ")", "let", "states", "=", "[", "]", "for", "(", "let", "i", "=", "0", ";", "i", "<", "td44", ".", "length", ";", "++", "i", ")", "{", "let", "s", "=", "td44", "[", "i", "]", ".", "children", "[", "0", "]", ".", "data", "states", ".", "push", "(", "s", ".", "replace", "(", "',', ", " ", "'", " ').", " ", ".", "r", "e", "}", "place('", "E", "n tr?nsito', ", "n", " ", "'", "n transito'))", "}" ]
Create panasia entity from html @param html @param id
[ "Create", "panasia", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/panasiaTracker.js#L53-L101
train
hdnpt/geartrack
src/cainiaoTracker.js
createCainiaoEntity
function createCainiaoEntity(id, json) { let section = json.data[0].section3 || json.data[0].section2; let msgs = section.detailList.map(m => { return { state: fixStateName(m.desc), date: moment.tz(m.time, "YYYY-MM-DD HH:mm:ss", zone).format() } }) let destinyId = json.data[0].section2.mailNo || null return new CainiaoInfo(id, msgs, destinyId) }
javascript
function createCainiaoEntity(id, json) { let section = json.data[0].section3 || json.data[0].section2; let msgs = section.detailList.map(m => { return { state: fixStateName(m.desc), date: moment.tz(m.time, "YYYY-MM-DD HH:mm:ss", zone).format() } }) let destinyId = json.data[0].section2.mailNo || null return new CainiaoInfo(id, msgs, destinyId) }
[ "function", "createCainiaoEntity", "(", "id", ",", "json", ")", "{", "let", "section", "=", "json", ".", "data", "[", "0", "]", ".", "section3", "||", "json", ".", "data", "[", "0", "]", ".", "section2", ";", "let", "msgs", "=", "section", ".", "detailList", ".", "map", "(", "m", "=>", "{", "return", "{", "state", ":", "fixStateName", "(", "m", ".", "desc", ")", ",", "date", ":", "moment", ".", "tz", "(", "m", ".", "time", ",", "\"YYYY-MM-DD HH:mm:ss\"", ",", "zone", ")", ".", "format", "(", ")", "}", "}", ")", "let", "destinyId", "=", "json", ".", "data", "[", "0", "]", ".", "section2", ".", "mailNo", "||", "null", "return", "new", "CainiaoInfo", "(", "id", ",", "msgs", ",", "destinyId", ")", "}" ]
Create cainiao entity from html @param id @param json
[ "Create", "cainiao", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/cainiaoTracker.js#L68-L81
train
hdnpt/geartrack
src/expresso24Tracker.js
createExpressoEntity
function createExpressoEntity(html) { let $ = parser.load(html) let data = [] $('table span').each(function (i, elem) { if(i >= 10 ) data.push($(this).text().trim().replace(/\s\s+/g, ' ')) }) return new ExpressoInfo({ 'guide': data[0], 'origin': data[1], 'date': moment.tz(data[2], "YYYY-MM-DD", zone).format(), 'status': data[3], 'weight': data[4], 'parcels': data[5], 'receiver_name': data[6], 'address': parseAddress(data[7]), 'refund': data[8], 'ref': data[9], }) }
javascript
function createExpressoEntity(html) { let $ = parser.load(html) let data = [] $('table span').each(function (i, elem) { if(i >= 10 ) data.push($(this).text().trim().replace(/\s\s+/g, ' ')) }) return new ExpressoInfo({ 'guide': data[0], 'origin': data[1], 'date': moment.tz(data[2], "YYYY-MM-DD", zone).format(), 'status': data[3], 'weight': data[4], 'parcels': data[5], 'receiver_name': data[6], 'address': parseAddress(data[7]), 'refund': data[8], 'ref': data[9], }) }
[ "function", "createExpressoEntity", "(", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "data", "=", "[", "]", "$", "(", "'table span'", ")", ".", "each", "(", "function", "(", "i", ",", "elem", ")", "{", "if", "(", "i", ">=", "10", ")", "data", ".", "push", "(", "$", "(", "this", ")", ".", "text", "(", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\s\\s+", "/", "g", ",", "' '", ")", ")", "}", ")", "return", "new", "ExpressoInfo", "(", "{", "'guide'", ":", "data", "[", "0", "]", ",", "'origin'", ":", "data", "[", "1", "]", ",", "'date'", ":", "moment", ".", "tz", "(", "data", "[", "2", "]", ",", "\"YYYY-MM-DD\"", ",", "zone", ")", ".", "format", "(", ")", ",", "'status'", ":", "data", "[", "3", "]", ",", "'weight'", ":", "data", "[", "4", "]", ",", "'parcels'", ":", "data", "[", "5", "]", ",", "'receiver_name'", ":", "data", "[", "6", "]", ",", "'address'", ":", "parseAddress", "(", "data", "[", "7", "]", ")", ",", "'refund'", ":", "data", "[", "8", "]", ",", "'ref'", ":", "data", "[", "9", "]", ",", "}", ")", "}" ]
Create expresso entity from html @param html
[ "Create", "expresso", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/expresso24Tracker.js#L59-L80
train
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpEndpointNode
function amqpEndpointNode(n) { RED.nodes.createNode(this, n); // save node parameters this.host = n.host; this.port = n.port; this.username = n.username; this.password = n.password; this.container_id = n.container_id; this.rejectUnauthorized = n.rejectUnauthorized; this.usetls = n.usetls; if (this.usetls && n.tls) { this.tls = RED.nodes.getNode(n.tls) } // build options for connection var options = { host: this.host, port: this.port}; if (this.username) { options.username = this.username; } if (this.password) { options.password = this.password; } if (this.container_id) { options.container_id = this.container_id; } else { options.container_id = "node-red-rhea-" + container.generate_uuid(); } if (this.usetls && n.tls) { options.transport = 'tls'; if (this.tls.credentials.cadata) { options.ca = this.tls.credentials.cadata } } options.rejectUnauthorized = this.rejectUnauthorized; var node = this; this.connected = false; this.connecting = false; /** * Exposed function for connecting to the remote AMQP container * creating an AMQP connection object * * @param callback function called when the connection is established */ this.connect = function(callback) { // AMQP connection not established, trying to do that if (!node.connected && !node.connecting) { node.connecting = true; node.connection = container.connect(options); node.connection.on('connection_error', function(context) { node.connecting = false; node.connected = false; var error = context.connection.get_error(); node.error(error); }); node.connection.on('connection_open', function(context) { node.connecting = false; node.connected = true; callback(context.connection); }); node.connection.on('disconnected', function(context) { node.connected = false; }); // AMQP connection already established } else { callback(node.connection); } } }
javascript
function amqpEndpointNode(n) { RED.nodes.createNode(this, n); // save node parameters this.host = n.host; this.port = n.port; this.username = n.username; this.password = n.password; this.container_id = n.container_id; this.rejectUnauthorized = n.rejectUnauthorized; this.usetls = n.usetls; if (this.usetls && n.tls) { this.tls = RED.nodes.getNode(n.tls) } // build options for connection var options = { host: this.host, port: this.port}; if (this.username) { options.username = this.username; } if (this.password) { options.password = this.password; } if (this.container_id) { options.container_id = this.container_id; } else { options.container_id = "node-red-rhea-" + container.generate_uuid(); } if (this.usetls && n.tls) { options.transport = 'tls'; if (this.tls.credentials.cadata) { options.ca = this.tls.credentials.cadata } } options.rejectUnauthorized = this.rejectUnauthorized; var node = this; this.connected = false; this.connecting = false; /** * Exposed function for connecting to the remote AMQP container * creating an AMQP connection object * * @param callback function called when the connection is established */ this.connect = function(callback) { // AMQP connection not established, trying to do that if (!node.connected && !node.connecting) { node.connecting = true; node.connection = container.connect(options); node.connection.on('connection_error', function(context) { node.connecting = false; node.connected = false; var error = context.connection.get_error(); node.error(error); }); node.connection.on('connection_open', function(context) { node.connecting = false; node.connected = true; callback(context.connection); }); node.connection.on('disconnected', function(context) { node.connected = false; }); // AMQP connection already established } else { callback(node.connection); } } }
[ "function", "amqpEndpointNode", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "this", ".", "host", "=", "n", ".", "host", ";", "this", ".", "port", "=", "n", ".", "port", ";", "this", ".", "username", "=", "n", ".", "username", ";", "this", ".", "password", "=", "n", ".", "password", ";", "this", ".", "container_id", "=", "n", ".", "container_id", ";", "this", ".", "rejectUnauthorized", "=", "n", ".", "rejectUnauthorized", ";", "this", ".", "usetls", "=", "n", ".", "usetls", ";", "if", "(", "this", ".", "usetls", "&&", "n", ".", "tls", ")", "{", "this", ".", "tls", "=", "RED", ".", "nodes", ".", "getNode", "(", "n", ".", "tls", ")", "}", "var", "options", "=", "{", "host", ":", "this", ".", "host", ",", "port", ":", "this", ".", "port", "}", ";", "if", "(", "this", ".", "username", ")", "{", "options", ".", "username", "=", "this", ".", "username", ";", "}", "if", "(", "this", ".", "password", ")", "{", "options", ".", "password", "=", "this", ".", "password", ";", "}", "if", "(", "this", ".", "container_id", ")", "{", "options", ".", "container_id", "=", "this", ".", "container_id", ";", "}", "else", "{", "options", ".", "container_id", "=", "\"node-red-rhea-\"", "+", "container", ".", "generate_uuid", "(", ")", ";", "}", "if", "(", "this", ".", "usetls", "&&", "n", ".", "tls", ")", "{", "options", ".", "transport", "=", "'tls'", ";", "if", "(", "this", ".", "tls", ".", "credentials", ".", "cadata", ")", "{", "options", ".", "ca", "=", "this", ".", "tls", ".", "credentials", ".", "cadata", "}", "}", "options", ".", "rejectUnauthorized", "=", "this", ".", "rejectUnauthorized", ";", "var", "node", "=", "this", ";", "this", ".", "connected", "=", "false", ";", "this", ".", "connecting", "=", "false", ";", "this", ".", "connect", "=", "function", "(", "callback", ")", "{", "if", "(", "!", "node", ".", "connected", "&&", "!", "node", ".", "connecting", ")", "{", "node", ".", "connecting", "=", "true", ";", "node", ".", "connection", "=", "container", ".", "connect", "(", "options", ")", ";", "node", ".", "connection", ".", "on", "(", "'connection_error'", ",", "function", "(", "context", ")", "{", "node", ".", "connecting", "=", "false", ";", "node", ".", "connected", "=", "false", ";", "var", "error", "=", "context", ".", "connection", ".", "get_error", "(", ")", ";", "node", ".", "error", "(", "error", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'connection_open'", ",", "function", "(", "context", ")", "{", "node", ".", "connecting", "=", "false", ";", "node", ".", "connected", "=", "true", ";", "callback", "(", "context", ".", "connection", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "connected", "=", "false", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "node", ".", "connection", ")", ";", "}", "}", "}" ]
Node for configuring an AMQP endpoint
[ "Node", "for", "configuring", "an", "AMQP", "endpoint" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L24-L112
train
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpSenderNode
function amqpSenderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autosettle = config.autosettle; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (node.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); } } }
javascript
function amqpSenderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autosettle = config.autosettle; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (node.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); } } }
[ "function", "amqpSenderNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "this", ".", "endpoint", "=", "RED", ".", "nodes", ".", "getNode", "(", "config", ".", "endpoint", ")", ";", "this", ".", "address", "=", "config", ".", "address", ";", "this", ".", "autosettle", "=", "config", ".", "autosettle", ";", "this", ".", "dynamic", "=", "config", ".", "dynamic", ";", "this", ".", "sndsettlemode", "=", "config", ".", "sndsettlemode", ";", "this", ".", "rcvsettlemode", "=", "config", ".", "rcvsettlemode", ";", "this", ".", "durable", "=", "config", ".", "durable", ";", "this", ".", "expirypolicy", "=", "config", ".", "expirypolicy", ";", "var", "node", "=", "this", ";", "this", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "if", "(", "node", ".", "endpoint", ")", "{", "node", ".", "endpoint", ".", "connect", "(", "function", "(", "connection", ")", "{", "setup", "(", "connection", ")", ";", "}", ")", ";", "function", "setup", "(", "connection", ")", "{", "node", ".", "connection", "=", "connection", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";", "var", "options", "=", "{", "target", ":", "{", "address", ":", "node", ".", "address", ",", "dynamic", ":", "node", ".", "dynamic", ",", "durable", ":", "node", ".", "durable", ",", "expiry_policy", ":", "node", ".", "expirypolicy", "}", ",", "autosettle", ":", "node", ".", "autosettle", ",", "snd_settle_mode", ":", "node", ".", "sndsettlemode", ",", "rcv_settle_mode", ":", "node", ".", "rcvsettlemode", "}", ";", "node", ".", "sender", "=", "node", ".", "connection", ".", "open_sender", "(", "options", ")", ";", "node", ".", "sender", ".", "on", "(", "'accepted'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "sender", ".", "on", "(", "'released'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "sender", ".", "on", "(", "'rejected'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "node", ".", "sender", ".", "sendable", "(", ")", ")", "{", "node", ".", "sender", ".", "send", "(", "msg", ".", "payload", ")", ";", "}", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "node", ".", "sender", "!=", "null", ")", "node", ".", "sender", ".", "detach", "(", ")", ";", "node", ".", "connection", ".", "close", "(", ")", ";", "}", ")", ";", "}", "}", "}" ]
Node for AMQP sender
[ "Node", "for", "AMQP", "sender" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L119-L205
train
amqp/node-red-contrib-rhea
rhea/rhea.js
setup
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); }
javascript
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); }
[ "function", "setup", "(", "connection", ")", "{", "node", ".", "connection", "=", "connection", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";", "var", "options", "=", "{", "target", ":", "{", "address", ":", "node", ".", "address", ",", "dynamic", ":", "node", ".", "dynamic", ",", "durable", ":", "node", ".", "durable", ",", "expiry_policy", ":", "node", ".", "expirypolicy", "}", ",", "autosettle", ":", "node", ".", "autosettle", ",", "snd_settle_mode", ":", "node", ".", "sndsettlemode", ",", "rcv_settle_mode", ":", "node", ".", "rcvsettlemode", "}", ";", "node", ".", "sender", "=", "node", ".", "connection", ".", "open_sender", "(", "options", ")", ";", "node", ".", "sender", ".", "on", "(", "'accepted'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "sender", ".", "on", "(", "'released'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "sender", ".", "on", "(", "'rejected'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "node", ".", "sender", ".", "sendable", "(", ")", ")", "{", "node", ".", "sender", ".", "send", "(", "msg", ".", "payload", ")", ";", "}", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "node", ".", "sender", "!=", "null", ")", "node", ".", "sender", ".", "detach", "(", ")", ";", "node", ".", "connection", ".", "close", "(", ")", ";", "}", ")", ";", "}" ]
Node setup for creating sender link @param connection Connection instance
[ "Node", "setup", "for", "creating", "sender", "link" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L149-L202
train
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpReceiverNode
function amqpReceiverNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autoaccept = config.autoaccept; this.creditwindow = config.creditwindow; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; if (this.dynamic) this.address = undefined; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); } } }
javascript
function amqpReceiverNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autoaccept = config.autoaccept; this.creditwindow = config.creditwindow; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; if (this.dynamic) this.address = undefined; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); } } }
[ "function", "amqpReceiverNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "this", ".", "endpoint", "=", "RED", ".", "nodes", ".", "getNode", "(", "config", ".", "endpoint", ")", ";", "this", ".", "address", "=", "config", ".", "address", ";", "this", ".", "autoaccept", "=", "config", ".", "autoaccept", ";", "this", ".", "creditwindow", "=", "config", ".", "creditwindow", ";", "this", ".", "dynamic", "=", "config", ".", "dynamic", ";", "this", ".", "sndsettlemode", "=", "config", ".", "sndsettlemode", ";", "this", ".", "rcvsettlemode", "=", "config", ".", "rcvsettlemode", ";", "this", ".", "durable", "=", "config", ".", "durable", ";", "this", ".", "expirypolicy", "=", "config", ".", "expirypolicy", ";", "if", "(", "this", ".", "dynamic", ")", "this", ".", "address", "=", "undefined", ";", "var", "node", "=", "this", ";", "this", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "if", "(", "this", ".", "endpoint", ")", "{", "node", ".", "endpoint", ".", "connect", "(", "function", "(", "connection", ")", "{", "setup", "(", "connection", ")", ";", "}", ")", ";", "function", "setup", "(", "connection", ")", "{", "node", ".", "connection", "=", "connection", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";", "var", "options", "=", "{", "source", ":", "{", "address", ":", "node", ".", "address", ",", "dynamic", ":", "node", ".", "dynamic", ",", "durable", ":", "node", ".", "durable", ",", "expiry_policy", ":", "node", ".", "expirypolicy", "}", ",", "credit_window", ":", "node", ".", "creditwindow", ",", "autoaccept", ":", "node", ".", "autoaccept", ",", "snd_settle_mode", ":", "node", ".", "sndsettlemode", ",", "rcv_settle_mode", ":", "node", ".", "rcvsettlemode", "}", ";", "node", ".", "receiver", "=", "node", ".", "connection", ".", "open_receiver", "(", "options", ")", ";", "node", ".", "receiver", ".", "on", "(", "'message'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "{", "payload", ":", "context", ".", "message", ",", "delivery", ":", "context", ".", "delivery", "}", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "msg", ".", "credit", ")", "{", "node", ".", "receiver", ".", "flow", "(", "msg", ".", "credit", ")", ";", "}", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "node", ".", "receiver", "!=", "null", ")", "node", ".", "receiver", ".", "detach", "(", ")", ";", "node", ".", "connection", ".", "close", "(", ")", ";", "}", ")", ";", "}", "}", "}" ]
Node for AMQP receiver
[ "Node", "for", "AMQP", "receiver" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L220-L304
train
amqp/node-red-contrib-rhea
rhea/rhea.js
setup
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); }
javascript
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); }
[ "function", "setup", "(", "connection", ")", "{", "node", ".", "connection", "=", "connection", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";", "var", "options", "=", "{", "source", ":", "{", "address", ":", "node", ".", "address", ",", "dynamic", ":", "node", ".", "dynamic", ",", "durable", ":", "node", ".", "durable", ",", "expiry_policy", ":", "node", ".", "expirypolicy", "}", ",", "credit_window", ":", "node", ".", "creditwindow", ",", "autoaccept", ":", "node", ".", "autoaccept", ",", "snd_settle_mode", ":", "node", ".", "sndsettlemode", ",", "rcv_settle_mode", ":", "node", ".", "rcvsettlemode", "}", ";", "node", ".", "receiver", "=", "node", ".", "connection", ".", "open_receiver", "(", "options", ")", ";", "node", ".", "receiver", ".", "on", "(", "'message'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "{", "payload", ":", "context", ".", "message", ",", "delivery", ":", "context", ".", "delivery", "}", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "msg", ".", "credit", ")", "{", "node", ".", "receiver", ".", "flow", "(", "msg", ".", "credit", ")", ";", "}", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "node", ".", "receiver", "!=", "null", ")", "node", ".", "receiver", ".", "detach", "(", ")", ";", "node", ".", "connection", ".", "close", "(", ")", ";", "}", ")", ";", "}" ]
Node setup for creating receiver link @param connection Connection instance
[ "Node", "setup", "for", "creating", "receiver", "link" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L254-L301
train
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpRequesterNode
function amqpRequesterNode(config) { RED.nodes.createNode(this, config); //var container = rhea.create_container(); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link for sending the request * and the dynamic receiver for receiving reply * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var sender_options = { target: { address: node.address } }; node.sender = node.connection.open_sender(sender_options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); // build receiver options var receiver_options = { source: { dynamic: true } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send([ ,msg]); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (node.receiver.source.address) { node.sender.send({ reply_to: node.receiver.source.address, body: msg.payload.body }); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
javascript
function amqpRequesterNode(config) { RED.nodes.createNode(this, config); //var container = rhea.create_container(); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link for sending the request * and the dynamic receiver for receiving reply * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var sender_options = { target: { address: node.address } }; node.sender = node.connection.open_sender(sender_options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); // build receiver options var receiver_options = { source: { dynamic: true } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send([ ,msg]); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (node.receiver.source.address) { node.sender.send({ reply_to: node.receiver.source.address, body: msg.payload.body }); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
[ "function", "amqpRequesterNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "this", ".", "endpoint", "=", "RED", ".", "nodes", ".", "getNode", "(", "config", ".", "endpoint", ")", ";", "this", ".", "address", "=", "config", ".", "address", ";", "var", "node", "=", "this", ";", "this", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "if", "(", "this", ".", "endpoint", ")", "{", "node", ".", "endpoint", ".", "connect", "(", "function", "(", "connection", ")", "{", "setup", "(", "connection", ")", ";", "}", ")", ";", "function", "setup", "(", "connection", ")", "{", "node", ".", "connection", "=", "connection", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";", "var", "sender_options", "=", "{", "target", ":", "{", "address", ":", "node", ".", "address", "}", "}", ";", "node", ".", "sender", "=", "node", ".", "connection", ".", "open_sender", "(", "sender_options", ")", ";", "node", ".", "sender", ".", "on", "(", "'accepted'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "[", "msg", ",", "]", ")", ";", "}", ")", ";", "node", ".", "sender", ".", "on", "(", "'released'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "[", "msg", ",", "]", ")", ";", "}", ")", ";", "node", ".", "sender", ".", "on", "(", "'rejected'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "outDelivery", "(", "node", ",", "context", ".", "delivery", ")", ";", "node", ".", "send", "(", "[", "msg", ",", "]", ")", ";", "}", ")", ";", "var", "receiver_options", "=", "{", "source", ":", "{", "dynamic", ":", "true", "}", "}", ";", "node", ".", "receiver", "=", "node", ".", "connection", ".", "open_receiver", "(", "receiver_options", ")", ";", "node", ".", "receiver", ".", "on", "(", "'message'", ",", "function", "(", "context", ")", "{", "var", "msg", "=", "{", "payload", ":", "context", ".", "message", ",", "delivery", ":", "context", ".", "delivery", "}", ";", "node", ".", "send", "(", "[", ",", "msg", "]", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "node", ".", "sender", ".", "sendable", "(", ")", ")", "{", "if", "(", "node", ".", "receiver", ".", "source", ".", "address", ")", "{", "node", ".", "sender", ".", "send", "(", "{", "reply_to", ":", "node", ".", "receiver", ".", "source", ".", "address", ",", "body", ":", "msg", ".", "payload", ".", "body", "}", ")", ";", "}", "}", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "node", ".", "sender", "!=", "null", ")", "node", ".", "sender", ".", "detach", "(", ")", ";", "if", "(", "node", ".", "receiver", "!=", "null", ")", "node", ".", "receiver", ".", "detach", "(", ")", ";", "node", ".", "connection", ".", "close", "(", ")", ";", "}", ")", "}", "}", "}" ]
Node for AMQP requester
[ "Node", "for", "AMQP", "requester" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L311-L410
train
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpResponderNode
function amqpResponderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link for receiving the request * and the sender for sending reply * * @param connection Connection instance */ function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
javascript
function amqpResponderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link for receiving the request * and the sender for sending reply * * @param connection Connection instance */ function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
[ "function", "amqpResponderNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "this", ".", "endpoint", "=", "RED", ".", "nodes", ".", "getNode", "(", "config", ".", "endpoint", ")", ";", "this", ".", "address", "=", "config", ".", "address", ";", "var", "node", "=", "this", ";", "this", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "if", "(", "this", ".", "endpoint", ")", "{", "node", ".", "endpoint", ".", "connect", "(", "function", "(", "connection", ")", "{", "setup", "(", "connection", ")", ";", "}", ")", ";", "function", "setup", "(", "connection", ")", "{", "var", "request", "=", "undefined", ";", "var", "reply_to", "=", "undefined", ";", "var", "response", "=", "undefined", ";", "node", ".", "connection", "=", "connection", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";", "node", ".", "sender", "=", "node", ".", "connection", ".", "open_sender", "(", "{", "target", ":", "{", "}", "}", ")", ";", "var", "receiver_options", "=", "{", "source", ":", "{", "address", ":", "node", ".", "address", "}", "}", ";", "node", ".", "receiver", "=", "node", ".", "connection", ".", "open_receiver", "(", "receiver_options", ")", ";", "node", ".", "receiver", ".", "on", "(", "'message'", ",", "function", "(", "context", ")", "{", "request", "=", "context", ".", "message", ";", "reply_to", "=", "request", ".", "reply_to", ";", "var", "msg", "=", "{", "payload", ":", "context", ".", "message", ",", "delivery", ":", "context", ".", "delivery", "}", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "node", ".", "sender", ".", "sendable", "(", ")", ")", "{", "if", "(", "reply_to", ")", "{", "response", "=", "msg", ".", "payload", ";", "response", ".", "to", "=", "reply_to", ";", "node", ".", "sender", ".", "send", "(", "response", ")", ";", "}", "}", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "node", ".", "sender", "!=", "null", ")", "node", ".", "sender", ".", "detach", "(", ")", ";", "if", "(", "node", ".", "receiver", "!=", "null", ")", "node", ".", "receiver", ".", "detach", "(", ")", ";", "node", ".", "connection", ".", "close", "(", ")", ";", "}", ")", "}", "}", "}" ]
Node for AMQP responder
[ "Node", "for", "AMQP", "responder" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L417-L508
train
amqp/node-red-contrib-rhea
rhea/rhea.js
setup
function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) }
javascript
function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) }
[ "function", "setup", "(", "connection", ")", "{", "var", "request", "=", "undefined", ";", "var", "reply_to", "=", "undefined", ";", "var", "response", "=", "undefined", ";", "node", ".", "connection", "=", "connection", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";", "node", ".", "sender", "=", "node", ".", "connection", ".", "open_sender", "(", "{", "target", ":", "{", "}", "}", ")", ";", "var", "receiver_options", "=", "{", "source", ":", "{", "address", ":", "node", ".", "address", "}", "}", ";", "node", ".", "receiver", "=", "node", ".", "connection", ".", "open_receiver", "(", "receiver_options", ")", ";", "node", ".", "receiver", ".", "on", "(", "'message'", ",", "function", "(", "context", ")", "{", "request", "=", "context", ".", "message", ";", "reply_to", "=", "request", ".", "reply_to", ";", "var", "msg", "=", "{", "payload", ":", "context", ".", "message", ",", "delivery", ":", "context", ".", "delivery", "}", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "node", ".", "connection", ".", "on", "(", "'disconnected'", ",", "function", "(", "context", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'dot'", ",", "text", ":", "'disconnected'", "}", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "node", ".", "sender", ".", "sendable", "(", ")", ")", "{", "if", "(", "reply_to", ")", "{", "response", "=", "msg", ".", "payload", ";", "response", ".", "to", "=", "reply_to", ";", "node", ".", "sender", ".", "send", "(", "response", ")", ";", "}", "}", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "node", ".", "sender", "!=", "null", ")", "node", ".", "sender", ".", "detach", "(", ")", ";", "if", "(", "node", ".", "receiver", "!=", "null", ")", "node", ".", "receiver", ".", "detach", "(", ")", ";", "node", ".", "connection", ".", "close", "(", ")", ";", "}", ")", "}" ]
Node setup for creating receiver link for receiving the request and the sender for sending reply @param connection Connection instance
[ "Node", "setup", "for", "creating", "receiver", "link", "for", "receiving", "the", "request", "and", "the", "sender", "for", "sending", "reply" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L442-L505
train
hegemonic/requizzle
lib/requizzle.js
isNativeModule
function isNativeModule(targetPath, parentModule) { const lookupPaths = Module._resolveLookupPaths(targetPath, parentModule, true); /* istanbul ignore next */ return lookupPaths === null || (lookupPaths.length === 2 && lookupPaths[1].length === 0 && lookupPaths[0] === targetPath); }
javascript
function isNativeModule(targetPath, parentModule) { const lookupPaths = Module._resolveLookupPaths(targetPath, parentModule, true); /* istanbul ignore next */ return lookupPaths === null || (lookupPaths.length === 2 && lookupPaths[1].length === 0 && lookupPaths[0] === targetPath); }
[ "function", "isNativeModule", "(", "targetPath", ",", "parentModule", ")", "{", "const", "lookupPaths", "=", "Module", ".", "_resolveLookupPaths", "(", "targetPath", ",", "parentModule", ",", "true", ")", ";", "return", "lookupPaths", "===", "null", "||", "(", "lookupPaths", ".", "length", "===", "2", "&&", "lookupPaths", "[", "1", "]", ".", "length", "===", "0", "&&", "lookupPaths", "[", "0", "]", "===", "targetPath", ")", ";", "}" ]
Function that returns text to swizzle into the module. @typedef module:lib/requizzle~wrapperFunction @type {function} @param {string} targetPath - The path to the target module. @param {string} parentModulePath - The path to the module that is requiring the target module. @return {string} The text to insert before or after the module's source code. Options for the wrappers that will be swizzled into the target module. @typedef module:lib/requizzle~options @type {Object} @property {Object=} options.extras - Functions that generate text to swizzle into the target module. @property {module:lib/requizzle~wrapperFunction} options.extras.after - Function that returns text to insert after the module's source code. @property {module:lib/requizzle~wrapperFunction} options.extras.before - Function that returns text to insert before the module's source code. @property {(Array.<string>|string)} options.requirePaths - Additional paths to search when resolving module paths in the target module.
[ "Function", "that", "returns", "text", "to", "swizzle", "into", "the", "module", "." ]
3193e1bed6fdfe69fbde99496da6ed383a160680
https://github.com/hegemonic/requizzle/blob/3193e1bed6fdfe69fbde99496da6ed383a160680/lib/requizzle.js#L38-L46
train
oxyno-zeta/react-editable-json-tree
src/utils/objectTypes.js
isComponentWillChange
function isComponentWillChange(oldValue, newValue) { const oldType = getObjectType(oldValue); const newType = getObjectType(newValue); return ((oldType === 'Function' || newType === 'Function') && newType !== oldType); }
javascript
function isComponentWillChange(oldValue, newValue) { const oldType = getObjectType(oldValue); const newType = getObjectType(newValue); return ((oldType === 'Function' || newType === 'Function') && newType !== oldType); }
[ "function", "isComponentWillChange", "(", "oldValue", ",", "newValue", ")", "{", "const", "oldType", "=", "getObjectType", "(", "oldValue", ")", ";", "const", "newType", "=", "getObjectType", "(", "newValue", ")", ";", "return", "(", "(", "oldType", "===", "'Function'", "||", "newType", "===", "'Function'", ")", "&&", "newType", "!==", "oldType", ")", ";", "}" ]
Is Component will change ? @param oldValue {*} old value @param newValue {*} new value @returns {boolean} result
[ "Is", "Component", "will", "change", "?" ]
7f322b28c4da44098bc34cfd89b59308e26b20eb
https://github.com/oxyno-zeta/react-editable-json-tree/blob/7f322b28c4da44098bc34cfd89b59308e26b20eb/src/utils/objectTypes.js#L40-L44
train
dimerapp/markdown
src/transformers/relativeLinks.js
updateUrl
function updateUrl (cb, urlNode, options) { return cb(urlNode.url, options) .then((response) => { if (response) { Object.assign(urlNode, response) } }) .catch(() => { }) }
javascript
function updateUrl (cb, urlNode, options) { return cb(urlNode.url, options) .then((response) => { if (response) { Object.assign(urlNode, response) } }) .catch(() => { }) }
[ "function", "updateUrl", "(", "cb", ",", "urlNode", ",", "options", ")", "{", "return", "cb", "(", "urlNode", ".", "url", ",", "options", ")", ".", "then", "(", "(", "response", ")", "=>", "{", "if", "(", "response", ")", "{", "Object", ".", "assign", "(", "urlNode", ",", "response", ")", "}", "}", ")", ".", "catch", "(", "(", ")", "=>", "{", "}", ")", "}" ]
Updates the url of the image or link node by calling the callback promise @method updateUrl @param {Function} cb @param {Object} urlNode @param {Object} options @return {Promise}
[ "Updates", "the", "url", "of", "the", "image", "or", "link", "node", "by", "calling", "the", "callback", "promise" ]
a7cf95347be424b293931e1a0933dbd294209d7a
https://github.com/dimerapp/markdown/blob/a7cf95347be424b293931e1a0933dbd294209d7a/src/transformers/relativeLinks.js#L27-L36
train
dimerapp/markdown
src/transformers/toc.js
getTocNode
function getTocNode (tree) { const tocNode = toc(tree, { maxDepth: 3, loose: false }) if (!tocNode.map || !tocNode.map.children[0] || !tocNode.map.children[0].children[1]) { return } return { type: 'TocNode', data: { hName: 'div', hProperties: { className: ['toc-container'] } }, children: [ { type: 'TocTitleNode', data: { hName: 'h2' }, children: [{ type: 'text', value: 'Table of contents' }] }, tocNode.map.children[0].children[1] ] } }
javascript
function getTocNode (tree) { const tocNode = toc(tree, { maxDepth: 3, loose: false }) if (!tocNode.map || !tocNode.map.children[0] || !tocNode.map.children[0].children[1]) { return } return { type: 'TocNode', data: { hName: 'div', hProperties: { className: ['toc-container'] } }, children: [ { type: 'TocTitleNode', data: { hName: 'h2' }, children: [{ type: 'text', value: 'Table of contents' }] }, tocNode.map.children[0].children[1] ] } }
[ "function", "getTocNode", "(", "tree", ")", "{", "const", "tocNode", "=", "toc", "(", "tree", ",", "{", "maxDepth", ":", "3", ",", "loose", ":", "false", "}", ")", "if", "(", "!", "tocNode", ".", "map", "||", "!", "tocNode", ".", "map", ".", "children", "[", "0", "]", "||", "!", "tocNode", ".", "map", ".", "children", "[", "0", "]", ".", "children", "[", "1", "]", ")", "{", "return", "}", "return", "{", "type", ":", "'TocNode'", ",", "data", ":", "{", "hName", ":", "'div'", ",", "hProperties", ":", "{", "className", ":", "[", "'toc-container'", "]", "}", "}", ",", "children", ":", "[", "{", "type", ":", "'TocTitleNode'", ",", "data", ":", "{", "hName", ":", "'h2'", "}", ",", "children", ":", "[", "{", "type", ":", "'text'", ",", "value", ":", "'Table of contents'", "}", "]", "}", ",", "tocNode", ".", "map", ".", "children", "[", "0", "]", ".", "children", "[", "1", "]", "]", "}", "}" ]
Returns the node for TOC @method getTocNode @param {Object} tree @return {Object}
[ "Returns", "the", "node", "for", "TOC" ]
a7cf95347be424b293931e1a0933dbd294209d7a
https://github.com/dimerapp/markdown/blob/a7cf95347be424b293931e1a0933dbd294209d7a/src/transformers/toc.js#L23-L49
train
curran/d3-component
src/component.js
dataArray
function dataArray(data, context) { data = Array.isArray(data) ? data : [data]; return context ? data.map(d => Object.assign(Object.create(context), d)) : data; }
javascript
function dataArray(data, context) { data = Array.isArray(data) ? data : [data]; return context ? data.map(d => Object.assign(Object.create(context), d)) : data; }
[ "function", "dataArray", "(", "data", ",", "context", ")", "{", "data", "=", "Array", ".", "isArray", "(", "data", ")", "?", "data", ":", "[", "data", "]", ";", "return", "context", "?", "data", ".", "map", "(", "d", "=>", "Object", ".", "assign", "(", "Object", ".", "create", "(", "context", ")", ",", "d", ")", ")", ":", "data", ";", "}" ]
Computes the data to pass into the data join from component invocation arguments.
[ "Computes", "the", "data", "to", "pass", "into", "the", "data", "join", "from", "component", "invocation", "arguments", "." ]
bf620b4f6e5cd4684a1cd81a95011b490180ba50
https://github.com/curran/d3-component/blob/bf620b4f6e5cd4684a1cd81a95011b490180ba50/src/component.js#L15-L18
train
curran/d3-component
src/component.js
destroyDescendant
function destroyDescendant() { const instance = getInstance(this); if (instance) { const { selection, datum, destroy, index, } = instance; destroy(selection, datum, index); } }
javascript
function destroyDescendant() { const instance = getInstance(this); if (instance) { const { selection, datum, destroy, index, } = instance; destroy(selection, datum, index); } }
[ "function", "destroyDescendant", "(", ")", "{", "const", "instance", "=", "getInstance", "(", "this", ")", ";", "if", "(", "instance", ")", "{", "const", "{", "selection", ",", "datum", ",", "destroy", ",", "index", ",", "}", "=", "instance", ";", "destroy", "(", "selection", ",", "datum", ",", "index", ")", ";", "}", "}" ]
Destroys a descendant component instance. Does not remove its DOM node, as one if its ancestors will be removed.
[ "Destroys", "a", "descendant", "component", "instance", ".", "Does", "not", "remove", "its", "DOM", "node", "as", "one", "if", "its", "ancestors", "will", "be", "removed", "." ]
bf620b4f6e5cd4684a1cd81a95011b490180ba50
https://github.com/curran/d3-component/blob/bf620b4f6e5cd4684a1cd81a95011b490180ba50/src/component.js#L22-L30
train
curran/d3-component
src/component.js
destroyInstance
function destroyInstance() { const { selection, datum, destroy, index, } = getInstance(this); selection.selectAll('*').each(destroyDescendant); const transition = destroy(selection, datum, index); (transition || selection).remove(); }
javascript
function destroyInstance() { const { selection, datum, destroy, index, } = getInstance(this); selection.selectAll('*').each(destroyDescendant); const transition = destroy(selection, datum, index); (transition || selection).remove(); }
[ "function", "destroyInstance", "(", ")", "{", "const", "{", "selection", ",", "datum", ",", "destroy", ",", "index", ",", "}", "=", "getInstance", "(", "this", ")", ";", "selection", ".", "selectAll", "(", "'*'", ")", ".", "each", "(", "destroyDescendant", ")", ";", "const", "transition", "=", "destroy", "(", "selection", ",", "datum", ",", "index", ")", ";", "(", "transition", "||", "selection", ")", ".", "remove", "(", ")", ";", "}" ]
Destroys the component instance and its descendant component instances.
[ "Destroys", "the", "component", "instance", "and", "its", "descendant", "component", "instances", "." ]
bf620b4f6e5cd4684a1cd81a95011b490180ba50
https://github.com/curran/d3-component/blob/bf620b4f6e5cd4684a1cd81a95011b490180ba50/src/component.js#L33-L40
train
curran/d3-component
src/component.js
createInstance
function createInstance(datum, index) { const selection = select(this); setInstance(this, { component, selection, destroy, datum, index, }); create(selection, datum, index); }
javascript
function createInstance(datum, index) { const selection = select(this); setInstance(this, { component, selection, destroy, datum, index, }); create(selection, datum, index); }
[ "function", "createInstance", "(", "datum", ",", "index", ")", "{", "const", "selection", "=", "select", "(", "this", ")", ";", "setInstance", "(", "this", ",", "{", "component", ",", "selection", ",", "destroy", ",", "datum", ",", "index", ",", "}", ")", ";", "create", "(", "selection", ",", "datum", ",", "index", ")", ";", "}" ]
Creates a new component instance and stores it on the DOM node.
[ "Creates", "a", "new", "component", "instance", "and", "stores", "it", "on", "the", "DOM", "node", "." ]
bf620b4f6e5cd4684a1cd81a95011b490180ba50
https://github.com/curran/d3-component/blob/bf620b4f6e5cd4684a1cd81a95011b490180ba50/src/component.js#L65-L71
train
curran/d3-component
src/component.js
component
function component(container, data, context) { const selection = container.nodeName ? select(container) : container; const instances = selection .selectAll(mine) .data(dataArray(data, context), key); instances .exit() .each(destroyInstance); return instances .enter().append(tagName) .attr('class', className) .each(createInstance) .merge(instances) .each(renderInstance); }
javascript
function component(container, data, context) { const selection = container.nodeName ? select(container) : container; const instances = selection .selectAll(mine) .data(dataArray(data, context), key); instances .exit() .each(destroyInstance); return instances .enter().append(tagName) .attr('class', className) .each(createInstance) .merge(instances) .each(renderInstance); }
[ "function", "component", "(", "container", ",", "data", ",", "context", ")", "{", "const", "selection", "=", "container", ".", "nodeName", "?", "select", "(", "container", ")", ":", "container", ";", "const", "instances", "=", "selection", ".", "selectAll", "(", "mine", ")", ".", "data", "(", "dataArray", "(", "data", ",", "context", ")", ",", "key", ")", ";", "instances", ".", "exit", "(", ")", ".", "each", "(", "destroyInstance", ")", ";", "return", "instances", ".", "enter", "(", ")", ".", "append", "(", "tagName", ")", ".", "attr", "(", "'class'", ",", "className", ")", ".", "each", "(", "createInstance", ")", ".", "merge", "(", "instances", ")", ".", "each", "(", "renderInstance", ")", ";", "}" ]
The returned component instance.
[ "The", "returned", "component", "instance", "." ]
bf620b4f6e5cd4684a1cd81a95011b490180ba50
https://github.com/curran/d3-component/blob/bf620b4f6e5cd4684a1cd81a95011b490180ba50/src/component.js#L81-L95
train
quorrajs/NodeSession
lib/SessionManager.js
SessionManager
function SessionManager(config, encrypter) { /** * The configuration object * * @var Object * @protected */ this.__config = config; /** * The registered custom driver creators. * * @var Object * @protected */ this.__customCreators = {}; /** * The encrypter instance. * An encrypter implements encrypt and decrypt methods. * * @var Object * @protected */ this.__encrypter = encrypter; /** * The session database model instance * * @var Object * @protected */ this.__sessionModel; /** * The memory session handler storage * @type {null} * @protected */ this.__memorySession = Object.create(null); }
javascript
function SessionManager(config, encrypter) { /** * The configuration object * * @var Object * @protected */ this.__config = config; /** * The registered custom driver creators. * * @var Object * @protected */ this.__customCreators = {}; /** * The encrypter instance. * An encrypter implements encrypt and decrypt methods. * * @var Object * @protected */ this.__encrypter = encrypter; /** * The session database model instance * * @var Object * @protected */ this.__sessionModel; /** * The memory session handler storage * @type {null} * @protected */ this.__memorySession = Object.create(null); }
[ "function", "SessionManager", "(", "config", ",", "encrypter", ")", "{", "this", ".", "__config", "=", "config", ";", "this", ".", "__customCreators", "=", "{", "}", ";", "this", ".", "__encrypter", "=", "encrypter", ";", "this", ".", "__sessionModel", ";", "this", ".", "__memorySession", "=", "Object", ".", "create", "(", "null", ")", ";", "}" ]
Create a session manager instance. @param {Object} config @param {Object} [encrypter] @constructor
[ "Create", "a", "session", "manager", "instance", "." ]
c5f597a7a2eaf9f7c5b56fcbb338d69b048247f5
https://github.com/quorrajs/NodeSession/blob/c5f597a7a2eaf9f7c5b56fcbb338d69b048247f5/lib/SessionManager.js#L24-L64
train
quorrajs/NodeSession
index.js
NodeSession
function NodeSession(config, encrypter) { var defaults = { 'driver': 'file', 'lifetime': 300000, // five minutes 'expireOnClose': false, 'files': process.cwd()+'/sessions', 'connection': false, 'table': 'sessions', 'lottery': [2, 100], 'cookie': 'node_session', 'path': '/', 'domain': null, 'secure': false, 'httpOnly': true, 'encrypt': false }; /** * The Session configuration * * @type {Object} * @private */ this.__config = _.merge(defaults, config); if(this.__config.trustProxy && !this.__config.trustProxyFn) { this.__config.trustProxyFn = util.compileTrust(this.__config.trustProxy) } /** * The session manager instance * @type {SessionManager} * @private */ this.__manager = new SessionManager(this.__config, encrypter); if (!this.__config.secret) { throw new Error('secret option required for sessions'); } }
javascript
function NodeSession(config, encrypter) { var defaults = { 'driver': 'file', 'lifetime': 300000, // five minutes 'expireOnClose': false, 'files': process.cwd()+'/sessions', 'connection': false, 'table': 'sessions', 'lottery': [2, 100], 'cookie': 'node_session', 'path': '/', 'domain': null, 'secure': false, 'httpOnly': true, 'encrypt': false }; /** * The Session configuration * * @type {Object} * @private */ this.__config = _.merge(defaults, config); if(this.__config.trustProxy && !this.__config.trustProxyFn) { this.__config.trustProxyFn = util.compileTrust(this.__config.trustProxy) } /** * The session manager instance * @type {SessionManager} * @private */ this.__manager = new SessionManager(this.__config, encrypter); if (!this.__config.secret) { throw new Error('secret option required for sessions'); } }
[ "function", "NodeSession", "(", "config", ",", "encrypter", ")", "{", "var", "defaults", "=", "{", "'driver'", ":", "'file'", ",", "'lifetime'", ":", "300000", ",", "'expireOnClose'", ":", "false", ",", "'files'", ":", "process", ".", "cwd", "(", ")", "+", "'/sessions'", ",", "'connection'", ":", "false", ",", "'table'", ":", "'sessions'", ",", "'lottery'", ":", "[", "2", ",", "100", "]", ",", "'cookie'", ":", "'node_session'", ",", "'path'", ":", "'/'", ",", "'domain'", ":", "null", ",", "'secure'", ":", "false", ",", "'httpOnly'", ":", "true", ",", "'encrypt'", ":", "false", "}", ";", "this", ".", "__config", "=", "_", ".", "merge", "(", "defaults", ",", "config", ")", ";", "if", "(", "this", ".", "__config", ".", "trustProxy", "&&", "!", "this", ".", "__config", ".", "trustProxyFn", ")", "{", "this", ".", "__config", ".", "trustProxyFn", "=", "util", ".", "compileTrust", "(", "this", ".", "__config", ".", "trustProxy", ")", "}", "this", ".", "__manager", "=", "new", "SessionManager", "(", "this", ".", "__config", ",", "encrypter", ")", ";", "if", "(", "!", "this", ".", "__config", ".", "secret", ")", "{", "throw", "new", "Error", "(", "'secret option required for sessions'", ")", ";", "}", "}" ]
Create a new NodeSession instance @param {Object} config - session configuration object @param {Object | void} encrypter @constructor
[ "Create", "a", "new", "NodeSession", "instance" ]
c5f597a7a2eaf9f7c5b56fcbb338d69b048247f5
https://github.com/quorrajs/NodeSession/blob/c5f597a7a2eaf9f7c5b56fcbb338d69b048247f5/index.js#L23-L62
train
azu/podspec-bump
lib/podspec-searcher.js
searchPodspecFilePath
function searchPodspecFilePath(currentDir, callback) { var cDir = currentDir || process.cwd();// default: cwd fs.readdir(cDir, function (err, files) { if (err) { return callback(err); } var results = files.filter(function (file) { return path.extname(file) === '.podspec'; }); // return first filePath if (results.length == 0) { callback(new Error("not found podspec file")); } else { var filePath = results.shift(); callback(null, filePath); } }); }
javascript
function searchPodspecFilePath(currentDir, callback) { var cDir = currentDir || process.cwd();// default: cwd fs.readdir(cDir, function (err, files) { if (err) { return callback(err); } var results = files.filter(function (file) { return path.extname(file) === '.podspec'; }); // return first filePath if (results.length == 0) { callback(new Error("not found podspec file")); } else { var filePath = results.shift(); callback(null, filePath); } }); }
[ "function", "searchPodspecFilePath", "(", "currentDir", ",", "callback", ")", "{", "var", "cDir", "=", "currentDir", "||", "process", ".", "cwd", "(", ")", ";", "fs", ".", "readdir", "(", "cDir", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "var", "results", "=", "files", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "path", ".", "extname", "(", "file", ")", "===", "'.podspec'", ";", "}", ")", ";", "if", "(", "results", ".", "length", "==", "0", ")", "{", "callback", "(", "new", "Error", "(", "\"not found podspec file\"", ")", ")", ";", "}", "else", "{", "var", "filePath", "=", "results", ".", "shift", "(", ")", ";", "callback", "(", "null", ",", "filePath", ")", ";", "}", "}", ")", ";", "}" ]
find podspec and return find first file path @param currentDir @param callback
[ "find", "podspec", "and", "return", "find", "first", "file", "path" ]
9bc2ea57592aeff2920b70437f6ebf30a67b904e
https://github.com/azu/podspec-bump/blob/9bc2ea57592aeff2920b70437f6ebf30a67b904e/lib/podspec-searcher.js#L13-L30
train
mozillascience/software-citation-tools
CLI/argumentParser.js
getFormat
function getFormat(formatString) { let format = formatString.toLowerCase(); if(format == 'apa' || format == 'a') { return CitationCore.styles.apa; } else if(format == 'chicago' || format == 'c') { return CitationCore.styles.chicago; } else if(format == 'bibtexmisc' || format == 'bm') { return CitationCore.styles.bibtexMisc; } else if(format == 'bibtexsoftware' || format == 'bs'){ return CitationCore.styles.biblatexSoftware; } throw new Error(formatString + ' is an unsuported citation format. Try "apa" or "chicago"'); }
javascript
function getFormat(formatString) { let format = formatString.toLowerCase(); if(format == 'apa' || format == 'a') { return CitationCore.styles.apa; } else if(format == 'chicago' || format == 'c') { return CitationCore.styles.chicago; } else if(format == 'bibtexmisc' || format == 'bm') { return CitationCore.styles.bibtexMisc; } else if(format == 'bibtexsoftware' || format == 'bs'){ return CitationCore.styles.biblatexSoftware; } throw new Error(formatString + ' is an unsuported citation format. Try "apa" or "chicago"'); }
[ "function", "getFormat", "(", "formatString", ")", "{", "let", "format", "=", "formatString", ".", "toLowerCase", "(", ")", ";", "if", "(", "format", "==", "'apa'", "||", "format", "==", "'a'", ")", "{", "return", "CitationCore", ".", "styles", ".", "apa", ";", "}", "else", "if", "(", "format", "==", "'chicago'", "||", "format", "==", "'c'", ")", "{", "return", "CitationCore", ".", "styles", ".", "chicago", ";", "}", "else", "if", "(", "format", "==", "'bibtexmisc'", "||", "format", "==", "'bm'", ")", "{", "return", "CitationCore", ".", "styles", ".", "bibtexMisc", ";", "}", "else", "if", "(", "format", "==", "'bibtexsoftware'", "||", "format", "==", "'bs'", ")", "{", "return", "CitationCore", ".", "styles", ".", "biblatexSoftware", ";", "}", "throw", "new", "Error", "(", "formatString", "+", "' is an unsuported citation format. Try \"apa\" or \"chicago\"'", ")", ";", "}" ]
Determines the Formatter object from a string. @param {string} formatString - The string representation of a format. For example c or 'chicago' will return the Chicago Formatter. @return {Formatter} - The formatter for the given description. @throws {Error} Will throw an error if a formatter is not found
[ "Determines", "the", "Formatter", "object", "from", "a", "string", "." ]
65a73c4af3cd52c0b1997abc7de21fe4d4e0fdd0
https://github.com/mozillascience/software-citation-tools/blob/65a73c4af3cd52c0b1997abc7de21fe4d4e0fdd0/CLI/argumentParser.js#L58-L73
train
mozillascience/software-citation-tools
CLI/argumentParser.js
parseFormat
function parseFormat(index, args, formatOptions) { let nextValue = args.getNextValue(index); if(nextValue != null) { formatOptions.style = getFormat(nextValue); return index + 2; } throw new Error('No format provided'); }
javascript
function parseFormat(index, args, formatOptions) { let nextValue = args.getNextValue(index); if(nextValue != null) { formatOptions.style = getFormat(nextValue); return index + 2; } throw new Error('No format provided'); }
[ "function", "parseFormat", "(", "index", ",", "args", ",", "formatOptions", ")", "{", "let", "nextValue", "=", "args", ".", "getNextValue", "(", "index", ")", ";", "if", "(", "nextValue", "!=", "null", ")", "{", "formatOptions", ".", "style", "=", "getFormat", "(", "nextValue", ")", ";", "return", "index", "+", "2", ";", "}", "throw", "new", "Error", "(", "'No format provided'", ")", ";", "}" ]
Parses the format flag. @param The index
[ "Parses", "the", "format", "flag", "." ]
65a73c4af3cd52c0b1997abc7de21fe4d4e0fdd0
https://github.com/mozillascience/software-citation-tools/blob/65a73c4af3cd52c0b1997abc7de21fe4d4e0fdd0/CLI/argumentParser.js#L79-L87
train
mckamey/jsonml
jsonml-html.js
getType
function getType(val) { switch (typeof val) { case 'object': return !val ? NUL : (isArray(val) ? ARY : (isMarkup(val) ? RAW : ((val instanceof Date) ? VAL : OBJ))); case 'function': return FUN; case 'undefined': return NUL; default: return VAL; } }
javascript
function getType(val) { switch (typeof val) { case 'object': return !val ? NUL : (isArray(val) ? ARY : (isMarkup(val) ? RAW : ((val instanceof Date) ? VAL : OBJ))); case 'function': return FUN; case 'undefined': return NUL; default: return VAL; } }
[ "function", "getType", "(", "val", ")", "{", "switch", "(", "typeof", "val", ")", "{", "case", "'object'", ":", "return", "!", "val", "?", "NUL", ":", "(", "isArray", "(", "val", ")", "?", "ARY", ":", "(", "isMarkup", "(", "val", ")", "?", "RAW", ":", "(", "(", "val", "instanceof", "Date", ")", "?", "VAL", ":", "OBJ", ")", ")", ")", ";", "case", "'function'", ":", "return", "FUN", ";", "case", "'undefined'", ":", "return", "NUL", ";", "default", ":", "return", "VAL", ";", "}", "}" ]
Determines the type of the value @private @param {*} val the object being tested @return {number}
[ "Determines", "the", "type", "of", "the", "value" ]
16916da0cf9db226167a4cccb375ca5032daedf0
https://github.com/mckamey/jsonml/blob/16916da0cf9db226167a4cccb375ca5032daedf0/jsonml-html.js#L292-L303
train
mckamey/jsonml
jsonml-html.js
function(elem, name, handler) { if (name.substr(0,2) === 'on') { name = name.substr(2); } switch (typeof handler) { case 'function': if (elem.addEventListener) { // DOM Level 2 elem.addEventListener(name, handler, false); } else if (elem.attachEvent && getType(elem[name]) !== NUL) { // IE legacy events elem.attachEvent('on'+name, handler); } else { // DOM Level 0 var old = elem['on'+name] || elem[name]; elem['on'+name] = elem[name] = !isFunction(old) ? handler : function(e) { return (old.call(this, e) !== false) && (handler.call(this, e) !== false); }; } break; case 'string': // inline functions are DOM Level 0 /*jslint evil:true */ elem['on'+name] = new Function('event', handler); /*jslint evil:false */ break; } }
javascript
function(elem, name, handler) { if (name.substr(0,2) === 'on') { name = name.substr(2); } switch (typeof handler) { case 'function': if (elem.addEventListener) { // DOM Level 2 elem.addEventListener(name, handler, false); } else if (elem.attachEvent && getType(elem[name]) !== NUL) { // IE legacy events elem.attachEvent('on'+name, handler); } else { // DOM Level 0 var old = elem['on'+name] || elem[name]; elem['on'+name] = elem[name] = !isFunction(old) ? handler : function(e) { return (old.call(this, e) !== false) && (handler.call(this, e) !== false); }; } break; case 'string': // inline functions are DOM Level 0 /*jslint evil:true */ elem['on'+name] = new Function('event', handler); /*jslint evil:false */ break; } }
[ "function", "(", "elem", ",", "name", ",", "handler", ")", "{", "if", "(", "name", ".", "substr", "(", "0", ",", "2", ")", "===", "'on'", ")", "{", "name", "=", "name", ".", "substr", "(", "2", ")", ";", "}", "switch", "(", "typeof", "handler", ")", "{", "case", "'function'", ":", "if", "(", "elem", ".", "addEventListener", ")", "{", "elem", ".", "addEventListener", "(", "name", ",", "handler", ",", "false", ")", ";", "}", "else", "if", "(", "elem", ".", "attachEvent", "&&", "getType", "(", "elem", "[", "name", "]", ")", "!==", "NUL", ")", "{", "elem", ".", "attachEvent", "(", "'on'", "+", "name", ",", "handler", ")", ";", "}", "else", "{", "var", "old", "=", "elem", "[", "'on'", "+", "name", "]", "||", "elem", "[", "name", "]", ";", "elem", "[", "'on'", "+", "name", "]", "=", "elem", "[", "name", "]", "=", "!", "isFunction", "(", "old", ")", "?", "handler", ":", "function", "(", "e", ")", "{", "return", "(", "old", ".", "call", "(", "this", ",", "e", ")", "!==", "false", ")", "&&", "(", "handler", ".", "call", "(", "this", ",", "e", ")", "!==", "false", ")", ";", "}", ";", "}", "break", ";", "case", "'string'", ":", "elem", "[", "'on'", "+", "name", "]", "=", "new", "Function", "(", "'event'", ",", "handler", ")", ";", "break", ";", "}", "}" ]
Adds an event handler to an element @private @param {Node} elem The element @param {string} name The event name @param {function(Event)} handler The event handler
[ "Adds", "an", "event", "handler", "to", "an", "element" ]
16916da0cf9db226167a4cccb375ca5032daedf0
https://github.com/mckamey/jsonml/blob/16916da0cf9db226167a4cccb375ca5032daedf0/jsonml-html.js#L341-L373
train
mckamey/jsonml
jsonml-html.js
function(node, pattern) { if (!!node && (node.nodeType === 3) && pattern.exec(node.nodeValue)) { node.nodeValue = node.nodeValue.replace(pattern, ''); } }
javascript
function(node, pattern) { if (!!node && (node.nodeType === 3) && pattern.exec(node.nodeValue)) { node.nodeValue = node.nodeValue.replace(pattern, ''); } }
[ "function", "(", "node", ",", "pattern", ")", "{", "if", "(", "!", "!", "node", "&&", "(", "node", ".", "nodeType", "===", "3", ")", "&&", "pattern", ".", "exec", "(", "node", ".", "nodeValue", ")", ")", "{", "node", ".", "nodeValue", "=", "node", ".", "nodeValue", ".", "replace", "(", "pattern", ",", "''", ")", ";", "}", "}" ]
Trims whitespace pattern from the text node @private @param {Node} node The node
[ "Trims", "whitespace", "pattern", "from", "the", "text", "node" ]
16916da0cf9db226167a4cccb375ca5032daedf0
https://github.com/mckamey/jsonml/blob/16916da0cf9db226167a4cccb375ca5032daedf0/jsonml-html.js#L544-L548
train
mckamey/jsonml
jsonml-html.js
function(elem) { if (elem) { while (isWhitespace(elem.firstChild)) { // trim leading whitespace text nodes elem.removeChild(elem.firstChild); } // trim leading whitespace text trimPattern(elem.firstChild, LEADING); while (isWhitespace(elem.lastChild)) { // trim trailing whitespace text nodes elem.removeChild(elem.lastChild); } // trim trailing whitespace text trimPattern(elem.lastChild, TRAILING); } }
javascript
function(elem) { if (elem) { while (isWhitespace(elem.firstChild)) { // trim leading whitespace text nodes elem.removeChild(elem.firstChild); } // trim leading whitespace text trimPattern(elem.firstChild, LEADING); while (isWhitespace(elem.lastChild)) { // trim trailing whitespace text nodes elem.removeChild(elem.lastChild); } // trim trailing whitespace text trimPattern(elem.lastChild, TRAILING); } }
[ "function", "(", "elem", ")", "{", "if", "(", "elem", ")", "{", "while", "(", "isWhitespace", "(", "elem", ".", "firstChild", ")", ")", "{", "elem", ".", "removeChild", "(", "elem", ".", "firstChild", ")", ";", "}", "trimPattern", "(", "elem", ".", "firstChild", ",", "LEADING", ")", ";", "while", "(", "isWhitespace", "(", "elem", ".", "lastChild", ")", ")", "{", "elem", ".", "removeChild", "(", "elem", ".", "lastChild", ")", ";", "}", "trimPattern", "(", "elem", ".", "lastChild", ",", "TRAILING", ")", ";", "}", "}" ]
Removes leading and trailing whitespace nodes @private @param {Node} elem The node
[ "Removes", "leading", "and", "trailing", "whitespace", "nodes" ]
16916da0cf9db226167a4cccb375ca5032daedf0
https://github.com/mckamey/jsonml/blob/16916da0cf9db226167a4cccb375ca5032daedf0/jsonml-html.js#L556-L571
train