id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
16,200
Breeze/breeze.js
build/breeze.debug.js
mergeEntity
function mergeEntity(mc, node, meta) { node._$meta = meta; var em = mc.entityManager; var entityType = meta.entityType; if (typeof (entityType) === 'string') { entityType = mc.metadataStore._getEntityType(entityType, false); } node.entityType = entityType; var mergeStrategy = mc.mergeOptions.mergeStrategy; var isSaving = mc.query == null; var entityKey = entityType.getEntityKeyFromRawEntity(node, mc.rawValueFn); var targetEntity = em.findEntityByKey(entityKey); if (targetEntity) { if (isSaving && targetEntity.entityAspect.entityState.isDeleted()) { em.detachEntity(targetEntity); return targetEntity; } var targetEntityState = targetEntity.entityAspect.entityState; if (mergeStrategy === MergeStrategy.Disallowed) { throw new Error("A MergeStrategy of 'Disallowed' prevents " + entityKey.toString() + " from being merged"); } else if (mergeStrategy === MergeStrategy.SkipMerge) { updateEntityNoMerge(mc, targetEntity, node); } else { if (mergeStrategy === MergeStrategy.OverwriteChanges || targetEntityState.isUnchanged()) { updateEntity(mc, targetEntity, node); targetEntity.entityAspect.wasLoaded = true; if (meta.extraMetadata) { targetEntity.entityAspect.extraMetadata = meta.extraMetadata; } targetEntity.entityAspect.entityState = EntityState.Unchanged; clearOriginalValues(targetEntity); targetEntity.entityAspect.propertyChanged.publish({ entity: targetEntity, propertyName: null }); var action = isSaving ? EntityAction.MergeOnSave : EntityAction.MergeOnQuery; em.entityChanged.publish({ entityAction: action, entity: targetEntity }); // this is needed to handle an overwrite of a modified entity with an unchanged entity // which might in turn cause _hasChanges to change. if (!targetEntityState.isUnchanged()) { em._notifyStateChange(targetEntity, false); } } else { if (targetEntityState == EntityState.Deleted && !mc.mergeOptions.includeDeleted) { return null; } updateEntityNoMerge(mc, targetEntity, node); } } } else { targetEntity = entityType._createInstanceCore(); updateEntity(mc, targetEntity, node); if (meta.extraMetadata) { targetEntity.entityAspect.extraMetadata = meta.extraMetadata; } // em._attachEntityCore(targetEntity, EntityState.Unchanged, MergeStrategy.Disallowed); em._attachEntityCore(targetEntity, EntityState.Unchanged, mergeStrategy); targetEntity.entityAspect.wasLoaded = true; em.entityChanged.publish({ entityAction: EntityAction.AttachOnQuery, entity: targetEntity }); } return targetEntity; }
javascript
function mergeEntity(mc, node, meta) { node._$meta = meta; var em = mc.entityManager; var entityType = meta.entityType; if (typeof (entityType) === 'string') { entityType = mc.metadataStore._getEntityType(entityType, false); } node.entityType = entityType; var mergeStrategy = mc.mergeOptions.mergeStrategy; var isSaving = mc.query == null; var entityKey = entityType.getEntityKeyFromRawEntity(node, mc.rawValueFn); var targetEntity = em.findEntityByKey(entityKey); if (targetEntity) { if (isSaving && targetEntity.entityAspect.entityState.isDeleted()) { em.detachEntity(targetEntity); return targetEntity; } var targetEntityState = targetEntity.entityAspect.entityState; if (mergeStrategy === MergeStrategy.Disallowed) { throw new Error("A MergeStrategy of 'Disallowed' prevents " + entityKey.toString() + " from being merged"); } else if (mergeStrategy === MergeStrategy.SkipMerge) { updateEntityNoMerge(mc, targetEntity, node); } else { if (mergeStrategy === MergeStrategy.OverwriteChanges || targetEntityState.isUnchanged()) { updateEntity(mc, targetEntity, node); targetEntity.entityAspect.wasLoaded = true; if (meta.extraMetadata) { targetEntity.entityAspect.extraMetadata = meta.extraMetadata; } targetEntity.entityAspect.entityState = EntityState.Unchanged; clearOriginalValues(targetEntity); targetEntity.entityAspect.propertyChanged.publish({ entity: targetEntity, propertyName: null }); var action = isSaving ? EntityAction.MergeOnSave : EntityAction.MergeOnQuery; em.entityChanged.publish({ entityAction: action, entity: targetEntity }); // this is needed to handle an overwrite of a modified entity with an unchanged entity // which might in turn cause _hasChanges to change. if (!targetEntityState.isUnchanged()) { em._notifyStateChange(targetEntity, false); } } else { if (targetEntityState == EntityState.Deleted && !mc.mergeOptions.includeDeleted) { return null; } updateEntityNoMerge(mc, targetEntity, node); } } } else { targetEntity = entityType._createInstanceCore(); updateEntity(mc, targetEntity, node); if (meta.extraMetadata) { targetEntity.entityAspect.extraMetadata = meta.extraMetadata; } // em._attachEntityCore(targetEntity, EntityState.Unchanged, MergeStrategy.Disallowed); em._attachEntityCore(targetEntity, EntityState.Unchanged, mergeStrategy); targetEntity.entityAspect.wasLoaded = true; em.entityChanged.publish({ entityAction: EntityAction.AttachOnQuery, entity: targetEntity }); } return targetEntity; }
[ "function", "mergeEntity", "(", "mc", ",", "node", ",", "meta", ")", "{", "node", ".", "_$meta", "=", "meta", ";", "var", "em", "=", "mc", ".", "entityManager", ";", "var", "entityType", "=", "meta", ".", "entityType", ";", "if", "(", "typeof", "(", "entityType", ")", "===", "'string'", ")", "{", "entityType", "=", "mc", ".", "metadataStore", ".", "_getEntityType", "(", "entityType", ",", "false", ")", ";", "}", "node", ".", "entityType", "=", "entityType", ";", "var", "mergeStrategy", "=", "mc", ".", "mergeOptions", ".", "mergeStrategy", ";", "var", "isSaving", "=", "mc", ".", "query", "==", "null", ";", "var", "entityKey", "=", "entityType", ".", "getEntityKeyFromRawEntity", "(", "node", ",", "mc", ".", "rawValueFn", ")", ";", "var", "targetEntity", "=", "em", ".", "findEntityByKey", "(", "entityKey", ")", ";", "if", "(", "targetEntity", ")", "{", "if", "(", "isSaving", "&&", "targetEntity", ".", "entityAspect", ".", "entityState", ".", "isDeleted", "(", ")", ")", "{", "em", ".", "detachEntity", "(", "targetEntity", ")", ";", "return", "targetEntity", ";", "}", "var", "targetEntityState", "=", "targetEntity", ".", "entityAspect", ".", "entityState", ";", "if", "(", "mergeStrategy", "===", "MergeStrategy", ".", "Disallowed", ")", "{", "throw", "new", "Error", "(", "\"A MergeStrategy of 'Disallowed' prevents \"", "+", "entityKey", ".", "toString", "(", ")", "+", "\" from being merged\"", ")", ";", "}", "else", "if", "(", "mergeStrategy", "===", "MergeStrategy", ".", "SkipMerge", ")", "{", "updateEntityNoMerge", "(", "mc", ",", "targetEntity", ",", "node", ")", ";", "}", "else", "{", "if", "(", "mergeStrategy", "===", "MergeStrategy", ".", "OverwriteChanges", "||", "targetEntityState", ".", "isUnchanged", "(", ")", ")", "{", "updateEntity", "(", "mc", ",", "targetEntity", ",", "node", ")", ";", "targetEntity", ".", "entityAspect", ".", "wasLoaded", "=", "true", ";", "if", "(", "meta", ".", "extraMetadata", ")", "{", "targetEntity", ".", "entityAspect", ".", "extraMetadata", "=", "meta", ".", "extraMetadata", ";", "}", "targetEntity", ".", "entityAspect", ".", "entityState", "=", "EntityState", ".", "Unchanged", ";", "clearOriginalValues", "(", "targetEntity", ")", ";", "targetEntity", ".", "entityAspect", ".", "propertyChanged", ".", "publish", "(", "{", "entity", ":", "targetEntity", ",", "propertyName", ":", "null", "}", ")", ";", "var", "action", "=", "isSaving", "?", "EntityAction", ".", "MergeOnSave", ":", "EntityAction", ".", "MergeOnQuery", ";", "em", ".", "entityChanged", ".", "publish", "(", "{", "entityAction", ":", "action", ",", "entity", ":", "targetEntity", "}", ")", ";", "// this is needed to handle an overwrite of a modified entity with an unchanged entity", "// which might in turn cause _hasChanges to change.", "if", "(", "!", "targetEntityState", ".", "isUnchanged", "(", ")", ")", "{", "em", ".", "_notifyStateChange", "(", "targetEntity", ",", "false", ")", ";", "}", "}", "else", "{", "if", "(", "targetEntityState", "==", "EntityState", ".", "Deleted", "&&", "!", "mc", ".", "mergeOptions", ".", "includeDeleted", ")", "{", "return", "null", ";", "}", "updateEntityNoMerge", "(", "mc", ",", "targetEntity", ",", "node", ")", ";", "}", "}", "}", "else", "{", "targetEntity", "=", "entityType", ".", "_createInstanceCore", "(", ")", ";", "updateEntity", "(", "mc", ",", "targetEntity", ",", "node", ")", ";", "if", "(", "meta", ".", "extraMetadata", ")", "{", "targetEntity", ".", "entityAspect", ".", "extraMetadata", "=", "meta", ".", "extraMetadata", ";", "}", "// em._attachEntityCore(targetEntity, EntityState.Unchanged, MergeStrategy.Disallowed);", "em", ".", "_attachEntityCore", "(", "targetEntity", ",", "EntityState", ".", "Unchanged", ",", "mergeStrategy", ")", ";", "targetEntity", ".", "entityAspect", ".", "wasLoaded", "=", "true", ";", "em", ".", "entityChanged", ".", "publish", "(", "{", "entityAction", ":", "EntityAction", ".", "AttachOnQuery", ",", "entity", ":", "targetEntity", "}", ")", ";", "}", "return", "targetEntity", ";", "}" ]
can return null for a deleted entity if includeDeleted == false
[ "can", "return", "null", "for", "a", "deleted", "entity", "if", "includeDeleted", "==", "false" ]
06b4919202bd20388847ce7d0cf57b6011cca158
https://github.com/Breeze/breeze.js/blob/06b4919202bd20388847ce7d0cf57b6011cca158/build/breeze.debug.js#L15655-L15719
16,201
Breeze/breeze.js
build/breeze.debug.js
DefaultChangeRequestInterceptor
function DefaultChangeRequestInterceptor(saveContext, saveBundle) { /** Prepare and return the save data for an entity change-set. The adapter calls this method for each entity in the change-set, after it has prepared a "change request" for that object. The method can do anything to the request but it must return a valid, non-null request. @example this.getRequest = function (request, entity, index) { // alter the request that the adapter prepared for this entity // based on the entity, saveContext, and saveBundle // e.g., add a custom header or prune the originalValuesMap return request; }; @method getRequest @param request {Object} The object representing the adapter's request to save this entity. @param entity {Entity} The entity-to-be-save as it is in cache @param index {Integer} The zero-based index of this entity in the change-set array @return {Function} The potentially revised request. **/ this.getRequest = function (request, entity, index) { return request; }; /** Last chance to change anything about the 'requests' array after it has been built with requests for all of the entities-to-be-saved. The 'requests' array is the same as 'saveBundle.entities' in many implementations This method can do anything to the array including add and remove requests. It's up to you to ensure that server will accept the requests array data as valid. Returned value is ignored. @example this.done = function (requests) { // alter the array of requests representing the entire change-set // based on the saveContext and saveBundle }; @method done @param requests {Array of Object} The adapter's array of request for this changeset. **/ this.done = function (requests) { }; }
javascript
function DefaultChangeRequestInterceptor(saveContext, saveBundle) { /** Prepare and return the save data for an entity change-set. The adapter calls this method for each entity in the change-set, after it has prepared a "change request" for that object. The method can do anything to the request but it must return a valid, non-null request. @example this.getRequest = function (request, entity, index) { // alter the request that the adapter prepared for this entity // based on the entity, saveContext, and saveBundle // e.g., add a custom header or prune the originalValuesMap return request; }; @method getRequest @param request {Object} The object representing the adapter's request to save this entity. @param entity {Entity} The entity-to-be-save as it is in cache @param index {Integer} The zero-based index of this entity in the change-set array @return {Function} The potentially revised request. **/ this.getRequest = function (request, entity, index) { return request; }; /** Last chance to change anything about the 'requests' array after it has been built with requests for all of the entities-to-be-saved. The 'requests' array is the same as 'saveBundle.entities' in many implementations This method can do anything to the array including add and remove requests. It's up to you to ensure that server will accept the requests array data as valid. Returned value is ignored. @example this.done = function (requests) { // alter the array of requests representing the entire change-set // based on the saveContext and saveBundle }; @method done @param requests {Array of Object} The adapter's array of request for this changeset. **/ this.done = function (requests) { }; }
[ "function", "DefaultChangeRequestInterceptor", "(", "saveContext", ",", "saveBundle", ")", "{", "/**\n Prepare and return the save data for an entity change-set.\n\n The adapter calls this method for each entity in the change-set,\n after it has prepared a \"change request\" for that object.\n\n The method can do anything to the request but it must return a valid, non-null request.\n @example\n this.getRequest = function (request, entity, index) {\n // alter the request that the adapter prepared for this entity\n // based on the entity, saveContext, and saveBundle\n // e.g., add a custom header or prune the originalValuesMap\n return request;\n };\n @method getRequest\n @param request {Object} The object representing the adapter's request to save this entity.\n @param entity {Entity} The entity-to-be-save as it is in cache\n @param index {Integer} The zero-based index of this entity in the change-set array\n @return {Function} The potentially revised request.\n **/", "this", ".", "getRequest", "=", "function", "(", "request", ",", "entity", ",", "index", ")", "{", "return", "request", ";", "}", ";", "/**\n Last chance to change anything about the 'requests' array\n after it has been built with requests for all of the entities-to-be-saved.\n\n The 'requests' array is the same as 'saveBundle.entities' in many implementations\n\n This method can do anything to the array including add and remove requests.\n It's up to you to ensure that server will accept the requests array data as valid.\n\n Returned value is ignored.\n @example\n this.done = function (requests) {\n // alter the array of requests representing the entire change-set\n // based on the saveContext and saveBundle\n };\n @method done\n @param requests {Array of Object} The adapter's array of request for this changeset.\n **/", "this", ".", "done", "=", "function", "(", "requests", ")", "{", "}", ";", "}" ]
This is a default, no-op implementation that developers can replace.
[ "This", "is", "a", "default", "no", "-", "op", "implementation", "that", "developers", "can", "replace", "." ]
06b4919202bd20388847ce7d0cf57b6011cca158
https://github.com/Breeze/breeze.js/blob/06b4919202bd20388847ce7d0cf57b6011cca158/build/breeze.debug.js#L16155-L16200
16,202
Breeze/breeze.js
build/breeze.debug.js
toQueryString
function toQueryString(obj) { var parts = []; for (var i in obj) { if (obj.hasOwnProperty(i)) { parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i])); } } return parts.join("&"); }
javascript
function toQueryString(obj) { var parts = []; for (var i in obj) { if (obj.hasOwnProperty(i)) { parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i])); } } return parts.join("&"); }
[ "function", "toQueryString", "(", "obj", ")", "{", "var", "parts", "=", "[", "]", ";", "for", "(", "var", "i", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "parts", ".", "push", "(", "encodeURIComponent", "(", "i", ")", "+", "\"=\"", "+", "encodeURIComponent", "(", "obj", "[", "i", "]", ")", ")", ";", "}", "}", "return", "parts", ".", "join", "(", "\"&\"", ")", ";", "}" ]
crude serializer. Doesn't recurse
[ "crude", "serializer", ".", "Doesn", "t", "recurse" ]
06b4919202bd20388847ce7d0cf57b6011cca158
https://github.com/Breeze/breeze.js/blob/06b4919202bd20388847ce7d0cf57b6011cca158/build/breeze.debug.js#L16722-L16730
16,203
Breeze/breeze.js
build/breeze.debug.js
movePropDefsToProto
function movePropDefsToProto(proto) { var stype = proto.entityType || proto.complexType; var extra = stype._extra; var alreadyWrapped = extra.alreadyWrappedProps || {}; stype.getProperties().forEach(function (prop) { var propName = prop.name; // we only want to wrap props that haven't already been wrapped if (alreadyWrapped[propName]) return; // If property is already defined on the prototype then wrap it in another propertyDescriptor. // otherwise create a propDescriptor for it. var descr; if (propName in proto) { descr = wrapPropDescription(proto, prop); } else { descr = makePropDescription(proto, prop); } // descr will be null for a wrapped descr that is not configurable if (descr != null) { Object.defineProperty(proto, propName, descr); } alreadyWrapped[propName] = true; }); extra.alreadyWrappedProps = alreadyWrapped; }
javascript
function movePropDefsToProto(proto) { var stype = proto.entityType || proto.complexType; var extra = stype._extra; var alreadyWrapped = extra.alreadyWrappedProps || {}; stype.getProperties().forEach(function (prop) { var propName = prop.name; // we only want to wrap props that haven't already been wrapped if (alreadyWrapped[propName]) return; // If property is already defined on the prototype then wrap it in another propertyDescriptor. // otherwise create a propDescriptor for it. var descr; if (propName in proto) { descr = wrapPropDescription(proto, prop); } else { descr = makePropDescription(proto, prop); } // descr will be null for a wrapped descr that is not configurable if (descr != null) { Object.defineProperty(proto, propName, descr); } alreadyWrapped[propName] = true; }); extra.alreadyWrappedProps = alreadyWrapped; }
[ "function", "movePropDefsToProto", "(", "proto", ")", "{", "var", "stype", "=", "proto", ".", "entityType", "||", "proto", ".", "complexType", ";", "var", "extra", "=", "stype", ".", "_extra", ";", "var", "alreadyWrapped", "=", "extra", ".", "alreadyWrappedProps", "||", "{", "}", ";", "stype", ".", "getProperties", "(", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "propName", "=", "prop", ".", "name", ";", "// we only want to wrap props that haven't already been wrapped", "if", "(", "alreadyWrapped", "[", "propName", "]", ")", "return", ";", "// If property is already defined on the prototype then wrap it in another propertyDescriptor.", "// otherwise create a propDescriptor for it.", "var", "descr", ";", "if", "(", "propName", "in", "proto", ")", "{", "descr", "=", "wrapPropDescription", "(", "proto", ",", "prop", ")", ";", "}", "else", "{", "descr", "=", "makePropDescription", "(", "proto", ",", "prop", ")", ";", "}", "// descr will be null for a wrapped descr that is not configurable", "if", "(", "descr", "!=", "null", ")", "{", "Object", ".", "defineProperty", "(", "proto", ",", "propName", ",", "descr", ")", ";", "}", "alreadyWrapped", "[", "propName", "]", "=", "true", ";", "}", ")", ";", "extra", ".", "alreadyWrappedProps", "=", "alreadyWrapped", ";", "}" ]
private methods This method is called during Metadata initialization to correctly "wrap" properties.
[ "private", "methods", "This", "method", "is", "called", "during", "Metadata", "initialization", "to", "correctly", "wrap", "properties", "." ]
06b4919202bd20388847ce7d0cf57b6011cca158
https://github.com/Breeze/breeze.js/blob/06b4919202bd20388847ce7d0cf57b6011cca158/build/breeze.debug.js#L17355-L17381
16,204
Breeze/breeze.js
build/breeze.debug.js
movePropsToBackingStore
function movePropsToBackingStore(instance) { var bs = getBackingStore(instance); var proto = Object.getPrototypeOf(instance); var stype = proto.entityType || proto.complexType; stype.getProperties().forEach(function (prop) { var propName = prop.name; if (prop.isUnmapped) { // insure that any unmapped properties that were added after entityType // was first created are wrapped with a property descriptor. if (!core.getPropertyDescriptor(proto, propName)) { var descr = makePropDescription(proto, prop); Object.defineProperty(proto, propName, descr); } } if (!instance.hasOwnProperty(propName)) return; // pulls off the value, removes the instance property and then rewrites it via ES5 accessor var value = instance[propName]; delete instance[propName]; instance[propName] = value; }); return bs; }
javascript
function movePropsToBackingStore(instance) { var bs = getBackingStore(instance); var proto = Object.getPrototypeOf(instance); var stype = proto.entityType || proto.complexType; stype.getProperties().forEach(function (prop) { var propName = prop.name; if (prop.isUnmapped) { // insure that any unmapped properties that were added after entityType // was first created are wrapped with a property descriptor. if (!core.getPropertyDescriptor(proto, propName)) { var descr = makePropDescription(proto, prop); Object.defineProperty(proto, propName, descr); } } if (!instance.hasOwnProperty(propName)) return; // pulls off the value, removes the instance property and then rewrites it via ES5 accessor var value = instance[propName]; delete instance[propName]; instance[propName] = value; }); return bs; }
[ "function", "movePropsToBackingStore", "(", "instance", ")", "{", "var", "bs", "=", "getBackingStore", "(", "instance", ")", ";", "var", "proto", "=", "Object", ".", "getPrototypeOf", "(", "instance", ")", ";", "var", "stype", "=", "proto", ".", "entityType", "||", "proto", ".", "complexType", ";", "stype", ".", "getProperties", "(", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "propName", "=", "prop", ".", "name", ";", "if", "(", "prop", ".", "isUnmapped", ")", "{", "// insure that any unmapped properties that were added after entityType", "// was first created are wrapped with a property descriptor.", "if", "(", "!", "core", ".", "getPropertyDescriptor", "(", "proto", ",", "propName", ")", ")", "{", "var", "descr", "=", "makePropDescription", "(", "proto", ",", "prop", ")", ";", "Object", ".", "defineProperty", "(", "proto", ",", "propName", ",", "descr", ")", ";", "}", "}", "if", "(", "!", "instance", ".", "hasOwnProperty", "(", "propName", ")", ")", "return", ";", "// pulls off the value, removes the instance property and then rewrites it via ES5 accessor", "var", "value", "=", "instance", "[", "propName", "]", ";", "delete", "instance", "[", "propName", "]", ";", "instance", "[", "propName", "]", "=", "value", ";", "}", ")", ";", "return", "bs", ";", "}" ]
This method is called when an instance is first created via materialization or createEntity. this method cannot be called while a 'defineProperty' accessor is executing because of IE bug mentioned above.
[ "This", "method", "is", "called", "when", "an", "instance", "is", "first", "created", "via", "materialization", "or", "createEntity", ".", "this", "method", "cannot", "be", "called", "while", "a", "defineProperty", "accessor", "is", "executing", "because", "of", "IE", "bug", "mentioned", "above", "." ]
06b4919202bd20388847ce7d0cf57b6011cca158
https://github.com/Breeze/breeze.js/blob/06b4919202bd20388847ce7d0cf57b6011cca158/build/breeze.debug.js#L17387-L17409
16,205
Breeze/breeze.js
build/breeze.debug.js
getPendingBackingStore
function getPendingBackingStore(instance) { var proto = Object.getPrototypeOf(instance); var pendingStores = proto._pendingBackingStores; var pending = core.arrayFirst(pendingStores, function (pending) { return pending.entity === instance; }); if (pending) return pending.backingStore; var bs = {}; pendingStores.push({ entity: instance, backingStore: bs }); return bs; }
javascript
function getPendingBackingStore(instance) { var proto = Object.getPrototypeOf(instance); var pendingStores = proto._pendingBackingStores; var pending = core.arrayFirst(pendingStores, function (pending) { return pending.entity === instance; }); if (pending) return pending.backingStore; var bs = {}; pendingStores.push({ entity: instance, backingStore: bs }); return bs; }
[ "function", "getPendingBackingStore", "(", "instance", ")", "{", "var", "proto", "=", "Object", ".", "getPrototypeOf", "(", "instance", ")", ";", "var", "pendingStores", "=", "proto", ".", "_pendingBackingStores", ";", "var", "pending", "=", "core", ".", "arrayFirst", "(", "pendingStores", ",", "function", "(", "pending", ")", "{", "return", "pending", ".", "entity", "===", "instance", ";", "}", ")", ";", "if", "(", "pending", ")", "return", "pending", ".", "backingStore", ";", "var", "bs", "=", "{", "}", ";", "pendingStores", ".", "push", "(", "{", "entity", ":", "instance", ",", "backingStore", ":", "bs", "}", ")", ";", "return", "bs", ";", "}" ]
workaround for IE9 bug where instance properties cannot be changed when executing a property 'set' method.
[ "workaround", "for", "IE9", "bug", "where", "instance", "properties", "cannot", "be", "changed", "when", "executing", "a", "property", "set", "method", "." ]
06b4919202bd20388847ce7d0cf57b6011cca158
https://github.com/Breeze/breeze.js/blob/06b4919202bd20388847ce7d0cf57b6011cca158/build/breeze.debug.js#L17512-L17522
16,206
youzan/vant-icons
build/build-iconfont.js
font
function font() { return src([`${svgDir}/*.svg`]) .pipe( iconfontCss({ fontName: config.name, path: template, targetPath: '../src/index.less', normalize: true, firstGlyph: 0xf000, cssClass: fontName // this is a trick to pass fontName to template }) ) .pipe( iconfont({ fontName, formats }) ) .pipe(dest(srcDir)); }
javascript
function font() { return src([`${svgDir}/*.svg`]) .pipe( iconfontCss({ fontName: config.name, path: template, targetPath: '../src/index.less', normalize: true, firstGlyph: 0xf000, cssClass: fontName // this is a trick to pass fontName to template }) ) .pipe( iconfont({ fontName, formats }) ) .pipe(dest(srcDir)); }
[ "function", "font", "(", ")", "{", "return", "src", "(", "[", "`", "${", "svgDir", "}", "`", "]", ")", ".", "pipe", "(", "iconfontCss", "(", "{", "fontName", ":", "config", ".", "name", ",", "path", ":", "template", ",", "targetPath", ":", "'../src/index.less'", ",", "normalize", ":", "true", ",", "firstGlyph", ":", "0xf000", ",", "cssClass", ":", "fontName", "// this is a trick to pass fontName to template", "}", ")", ")", ".", "pipe", "(", "iconfont", "(", "{", "fontName", ",", "formats", "}", ")", ")", ".", "pipe", "(", "dest", "(", "srcDir", ")", ")", ";", "}" ]
generate font from svg && build index.less
[ "generate", "font", "from", "svg", "&&", "build", "index", ".", "less" ]
862774a99a8cfdfb8e70d7da59507dd93af4c38e
https://github.com/youzan/vant-icons/blob/862774a99a8cfdfb8e70d7da59507dd93af4c38e/build/build-iconfont.js#L32-L51
16,207
iMicknl/cordova-plugin-openalpr
www/OpenALPR.js
function(imageData, options, success, error) { exec( success, error, 'OpenALPR', 'scan', [imageData, validateOptions(options)] ) }
javascript
function(imageData, options, success, error) { exec( success, error, 'OpenALPR', 'scan', [imageData, validateOptions(options)] ) }
[ "function", "(", "imageData", ",", "options", ",", "success", ",", "error", ")", "{", "exec", "(", "success", ",", "error", ",", "'OpenALPR'", ",", "'scan'", ",", "[", "imageData", ",", "validateOptions", "(", "options", ")", "]", ")", "}" ]
Scan license plate with OpenALPR @param imageData {string} Base64 encoding of the image data or the image file URI @param options {object} Options to pass to the OpenALPR scanner @param success callback function on success @param error callback function on failure. @returns {array} licenseplate matches
[ "Scan", "license", "plate", "with", "OpenALPR" ]
530066e9c36e2e73c22ee2b0eb962817700a60e4
https://github.com/iMicknl/cordova-plugin-openalpr/blob/530066e9c36e2e73c22ee2b0eb962817700a60e4/www/OpenALPR.js#L19-L27
16,208
iMicknl/cordova-plugin-openalpr
www/OpenALPR.js
validateOptions
function validateOptions(options) { //Check if options is set and is an object. if(! options || ! typeof options === 'object') { return { country: DEFAULT_COUNTRY, amount: DEFAULT_AMOUNT } } //Check if country property is set. if (! options.hasOwnProperty('country')) { options.country = DEFAULT_COUNTRY; } //Check if amount property is set. if (! options.hasOwnProperty('amount')) { options.amount = DEFAULT_AMOUNT; } return options; }
javascript
function validateOptions(options) { //Check if options is set and is an object. if(! options || ! typeof options === 'object') { return { country: DEFAULT_COUNTRY, amount: DEFAULT_AMOUNT } } //Check if country property is set. if (! options.hasOwnProperty('country')) { options.country = DEFAULT_COUNTRY; } //Check if amount property is set. if (! options.hasOwnProperty('amount')) { options.amount = DEFAULT_AMOUNT; } return options; }
[ "function", "validateOptions", "(", "options", ")", "{", "//Check if options is set and is an object.", "if", "(", "!", "options", "||", "!", "typeof", "options", "===", "'object'", ")", "{", "return", "{", "country", ":", "DEFAULT_COUNTRY", ",", "amount", ":", "DEFAULT_AMOUNT", "}", "}", "//Check if country property is set.", "if", "(", "!", "options", ".", "hasOwnProperty", "(", "'country'", ")", ")", "{", "options", ".", "country", "=", "DEFAULT_COUNTRY", ";", "}", "//Check if amount property is set.", "if", "(", "!", "options", ".", "hasOwnProperty", "(", "'amount'", ")", ")", "{", "options", ".", "amount", "=", "DEFAULT_AMOUNT", ";", "}", "return", "options", ";", "}" ]
Function to validate and when neccessary correct the options object. @param {*} options @return {*} options
[ "Function", "to", "validate", "and", "when", "neccessary", "correct", "the", "options", "object", "." ]
530066e9c36e2e73c22ee2b0eb962817700a60e4
https://github.com/iMicknl/cordova-plugin-openalpr/blob/530066e9c36e2e73c22ee2b0eb962817700a60e4/www/OpenALPR.js#L36-L56
16,209
Ivshti/linvodb3
lib/document.js
deserialize
function deserialize (rawData) { return JSON.parse(rawData, function (k, v) { if (k === '$$date') { return new Date(v); } if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) { return v; } if (v && v.$$date) { return v.$$date; } if (v && v.$$regex) { return deserializeRegex(v.$$regex) } return v; }); }
javascript
function deserialize (rawData) { return JSON.parse(rawData, function (k, v) { if (k === '$$date') { return new Date(v); } if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) { return v; } if (v && v.$$date) { return v.$$date; } if (v && v.$$regex) { return deserializeRegex(v.$$regex) } return v; }); }
[ "function", "deserialize", "(", "rawData", ")", "{", "return", "JSON", ".", "parse", "(", "rawData", ",", "function", "(", "k", ",", "v", ")", "{", "if", "(", "k", "===", "'$$date'", ")", "{", "return", "new", "Date", "(", "v", ")", ";", "}", "if", "(", "typeof", "v", "===", "'string'", "||", "typeof", "v", "===", "'number'", "||", "typeof", "v", "===", "'boolean'", "||", "v", "===", "null", ")", "{", "return", "v", ";", "}", "if", "(", "v", "&&", "v", ".", "$$date", ")", "{", "return", "v", ".", "$$date", ";", "}", "if", "(", "v", "&&", "v", ".", "$$regex", ")", "{", "return", "deserializeRegex", "(", "v", ".", "$$regex", ")", "}", "return", "v", ";", "}", ")", ";", "}" ]
From a one-line representation of an object generate by the serialize function Return the object itself
[ "From", "a", "one", "-", "line", "representation", "of", "an", "object", "generate", "by", "the", "serialize", "function", "Return", "the", "object", "itself" ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/document.js#L94-L103
16,210
Ivshti/linvodb3
lib/document.js
compoundCompareThings
function compoundCompareThings (fields) { return function (a, b) { var i, len, comparison; // undefined if (a === undefined) { return b === undefined ? 0 : -1; } if (b === undefined) { return a === undefined ? 0 : 1; } // null if (a === null) { return b === null ? 0 : -1; } if (b === null) { return a === null ? 0 : 1; } for (i = 0, len = fields.length; i < len; i++) { comparison = compareThings(a[fields[i]], b[fields[i]]); if (comparison !== 0) { return comparison; } } return 0; }; }
javascript
function compoundCompareThings (fields) { return function (a, b) { var i, len, comparison; // undefined if (a === undefined) { return b === undefined ? 0 : -1; } if (b === undefined) { return a === undefined ? 0 : 1; } // null if (a === null) { return b === null ? 0 : -1; } if (b === null) { return a === null ? 0 : 1; } for (i = 0, len = fields.length; i < len; i++) { comparison = compareThings(a[fields[i]], b[fields[i]]); if (comparison !== 0) { return comparison; } } return 0; }; }
[ "function", "compoundCompareThings", "(", "fields", ")", "{", "return", "function", "(", "a", ",", "b", ")", "{", "var", "i", ",", "len", ",", "comparison", ";", "// undefined", "if", "(", "a", "===", "undefined", ")", "{", "return", "b", "===", "undefined", "?", "0", ":", "-", "1", ";", "}", "if", "(", "b", "===", "undefined", ")", "{", "return", "a", "===", "undefined", "?", "0", ":", "1", ";", "}", "// null", "if", "(", "a", "===", "null", ")", "{", "return", "b", "===", "null", "?", "0", ":", "-", "1", ";", "}", "if", "(", "b", "===", "null", ")", "{", "return", "a", "===", "null", "?", "0", ":", "1", ";", "}", "for", "(", "i", "=", "0", ",", "len", "=", "fields", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "comparison", "=", "compareThings", "(", "a", "[", "fields", "[", "i", "]", "]", ",", "b", "[", "fields", "[", "i", "]", "]", ")", ";", "if", "(", "comparison", "!==", "0", ")", "{", "return", "comparison", ";", "}", "}", "return", "0", ";", "}", ";", "}" ]
Used primarily in compound indexes. Returns a comparison function usable as an Index's compareKeys function.
[ "Used", "primarily", "in", "compound", "indexes", ".", "Returns", "a", "comparison", "function", "usable", "as", "an", "Index", "s", "compareKeys", "function", "." ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/document.js#L192-L211
16,211
Ivshti/linvodb3
lib/document.js
modify
function modify (obj, updateQuery) { var keys = Object.keys(updateQuery) , firstChars = _.map(keys, function (item) { return item[0]; }) , dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; }) , newDoc, modifiers ; if ((keys.indexOf('_id') !== -1) && (updateQuery._id !== obj._id)) { throw "You cannot change a document's _id"; } if ((dollarFirstChars.length !== 0) && (dollarFirstChars.length !== firstChars.length)) { throw "You cannot mix modifiers and normal fields"; } if (dollarFirstChars.length === 0) { // Simply replace the object with the update query contents newDoc = deepCopy(updateQuery); newDoc._id = obj._id; } else { // Apply modifiers modifiers = _.uniq(keys); newDoc = deepCopy(obj); modifiers.forEach(function (m) { var keys; if (!modifierFunctions[m]) { throw "Unknown modifier " + m; } try { keys = Object.keys(updateQuery[m]); } catch (e) { throw "Modifier " + m + "'s argument must be an object"; } keys.forEach(function (k) { modifierFunctions[m](newDoc, k, updateQuery[m][k]); }); }); } // Check result is valid and return it checkObject(newDoc); if (obj._id !== newDoc._id) { throw "You can't change a document's _id"; } return newDoc; }
javascript
function modify (obj, updateQuery) { var keys = Object.keys(updateQuery) , firstChars = _.map(keys, function (item) { return item[0]; }) , dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; }) , newDoc, modifiers ; if ((keys.indexOf('_id') !== -1) && (updateQuery._id !== obj._id)) { throw "You cannot change a document's _id"; } if ((dollarFirstChars.length !== 0) && (dollarFirstChars.length !== firstChars.length)) { throw "You cannot mix modifiers and normal fields"; } if (dollarFirstChars.length === 0) { // Simply replace the object with the update query contents newDoc = deepCopy(updateQuery); newDoc._id = obj._id; } else { // Apply modifiers modifiers = _.uniq(keys); newDoc = deepCopy(obj); modifiers.forEach(function (m) { var keys; if (!modifierFunctions[m]) { throw "Unknown modifier " + m; } try { keys = Object.keys(updateQuery[m]); } catch (e) { throw "Modifier " + m + "'s argument must be an object"; } keys.forEach(function (k) { modifierFunctions[m](newDoc, k, updateQuery[m][k]); }); }); } // Check result is valid and return it checkObject(newDoc); if (obj._id !== newDoc._id) { throw "You can't change a document's _id"; } return newDoc; }
[ "function", "modify", "(", "obj", ",", "updateQuery", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "updateQuery", ")", ",", "firstChars", "=", "_", ".", "map", "(", "keys", ",", "function", "(", "item", ")", "{", "return", "item", "[", "0", "]", ";", "}", ")", ",", "dollarFirstChars", "=", "_", ".", "filter", "(", "firstChars", ",", "function", "(", "c", ")", "{", "return", "c", "===", "'$'", ";", "}", ")", ",", "newDoc", ",", "modifiers", ";", "if", "(", "(", "keys", ".", "indexOf", "(", "'_id'", ")", "!==", "-", "1", ")", "&&", "(", "updateQuery", ".", "_id", "!==", "obj", ".", "_id", ")", ")", "{", "throw", "\"You cannot change a document's _id\"", ";", "}", "if", "(", "(", "dollarFirstChars", ".", "length", "!==", "0", ")", "&&", "(", "dollarFirstChars", ".", "length", "!==", "firstChars", ".", "length", ")", ")", "{", "throw", "\"You cannot mix modifiers and normal fields\"", ";", "}", "if", "(", "dollarFirstChars", ".", "length", "===", "0", ")", "{", "// Simply replace the object with the update query contents", "newDoc", "=", "deepCopy", "(", "updateQuery", ")", ";", "newDoc", ".", "_id", "=", "obj", ".", "_id", ";", "}", "else", "{", "// Apply modifiers", "modifiers", "=", "_", ".", "uniq", "(", "keys", ")", ";", "newDoc", "=", "deepCopy", "(", "obj", ")", ";", "modifiers", ".", "forEach", "(", "function", "(", "m", ")", "{", "var", "keys", ";", "if", "(", "!", "modifierFunctions", "[", "m", "]", ")", "{", "throw", "\"Unknown modifier \"", "+", "m", ";", "}", "try", "{", "keys", "=", "Object", ".", "keys", "(", "updateQuery", "[", "m", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "\"Modifier \"", "+", "m", "+", "\"'s argument must be an object\"", ";", "}", "keys", ".", "forEach", "(", "function", "(", "k", ")", "{", "modifierFunctions", "[", "m", "]", "(", "newDoc", ",", "k", ",", "updateQuery", "[", "m", "]", "[", "k", "]", ")", ";", "}", ")", ";", "}", ")", ";", "}", "// Check result is valid and return it", "checkObject", "(", "newDoc", ")", ";", "if", "(", "obj", ".", "_id", "!==", "newDoc", ".", "_id", ")", "{", "throw", "\"You can't change a document's _id\"", ";", "}", "return", "newDoc", ";", "}" ]
Modify a DB object according to an update query
[ "Modify", "a", "DB", "object", "according", "to", "an", "update", "query" ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/document.js#L422-L465
16,212
Ivshti/linvodb3
lib/document.js
match
function match (obj, query) { var queryKeys, queryKey, queryValue, i; // Primitive query against a primitive type // This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later // But I don't have time for a cleaner implementation now if (isPrimitiveType(obj) || isPrimitiveType(query)) { return matchQueryPart({ needAKey: obj }, 'needAKey', query); } // Normal query queryKeys = Object.keys(query); for (i = 0; i < queryKeys.length; i += 1) { queryKey = queryKeys[i]; queryValue = query[queryKey]; if (queryKey[0] === '$') { if (!logicalOperators[queryKey]) { throw "Unknown logical operator " + queryKey; } if (!logicalOperators[queryKey](obj, queryValue)) { return false; } } else { if (!matchQueryPart(obj, queryKey, queryValue)) { return false; } } } return true; }
javascript
function match (obj, query) { var queryKeys, queryKey, queryValue, i; // Primitive query against a primitive type // This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later // But I don't have time for a cleaner implementation now if (isPrimitiveType(obj) || isPrimitiveType(query)) { return matchQueryPart({ needAKey: obj }, 'needAKey', query); } // Normal query queryKeys = Object.keys(query); for (i = 0; i < queryKeys.length; i += 1) { queryKey = queryKeys[i]; queryValue = query[queryKey]; if (queryKey[0] === '$') { if (!logicalOperators[queryKey]) { throw "Unknown logical operator " + queryKey; } if (!logicalOperators[queryKey](obj, queryValue)) { return false; } } else { if (!matchQueryPart(obj, queryKey, queryValue)) { return false; } } } return true; }
[ "function", "match", "(", "obj", ",", "query", ")", "{", "var", "queryKeys", ",", "queryKey", ",", "queryValue", ",", "i", ";", "// Primitive query against a primitive type", "// This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later", "// But I don't have time for a cleaner implementation now", "if", "(", "isPrimitiveType", "(", "obj", ")", "||", "isPrimitiveType", "(", "query", ")", ")", "{", "return", "matchQueryPart", "(", "{", "needAKey", ":", "obj", "}", ",", "'needAKey'", ",", "query", ")", ";", "}", "// Normal query", "queryKeys", "=", "Object", ".", "keys", "(", "query", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "queryKeys", ".", "length", ";", "i", "+=", "1", ")", "{", "queryKey", "=", "queryKeys", "[", "i", "]", ";", "queryValue", "=", "query", "[", "queryKey", "]", ";", "if", "(", "queryKey", "[", "0", "]", "===", "'$'", ")", "{", "if", "(", "!", "logicalOperators", "[", "queryKey", "]", ")", "{", "throw", "\"Unknown logical operator \"", "+", "queryKey", ";", "}", "if", "(", "!", "logicalOperators", "[", "queryKey", "]", "(", "obj", ",", "queryValue", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "if", "(", "!", "matchQueryPart", "(", "obj", ",", "queryKey", ",", "queryValue", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Tell if a given document matches a query @param {Object} obj Document to check @param {Object} query
[ "Tell", "if", "a", "given", "document", "matches", "a", "query" ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/document.js#L678-L703
16,213
Ivshti/linvodb3
lib/indexes.js
projectForUnique
function projectForUnique (elt) { if (elt === null) { return '$null'; } if (typeof elt === 'string') { return '$string' + elt; } if (typeof elt === 'boolean') { return '$boolean' + elt; } if (typeof elt === 'number') { return '$number' + elt; } if (util.isArray(elt)) { return '$date' + elt.getTime(); } return elt; // Arrays and ob }
javascript
function projectForUnique (elt) { if (elt === null) { return '$null'; } if (typeof elt === 'string') { return '$string' + elt; } if (typeof elt === 'boolean') { return '$boolean' + elt; } if (typeof elt === 'number') { return '$number' + elt; } if (util.isArray(elt)) { return '$date' + elt.getTime(); } return elt; // Arrays and ob }
[ "function", "projectForUnique", "(", "elt", ")", "{", "if", "(", "elt", "===", "null", ")", "{", "return", "'$null'", ";", "}", "if", "(", "typeof", "elt", "===", "'string'", ")", "{", "return", "'$string'", "+", "elt", ";", "}", "if", "(", "typeof", "elt", "===", "'boolean'", ")", "{", "return", "'$boolean'", "+", "elt", ";", "}", "if", "(", "typeof", "elt", "===", "'number'", ")", "{", "return", "'$number'", "+", "elt", ";", "}", "if", "(", "util", ".", "isArray", "(", "elt", ")", ")", "{", "return", "'$date'", "+", "elt", ".", "getTime", "(", ")", ";", "}", "return", "elt", ";", "// Arrays and ob", "}" ]
Type-aware projection
[ "Type", "-", "aware", "projection" ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/indexes.js#L17-L25
16,214
Ivshti/linvodb3
lib/indexes.js
getDotValues
function getDotValues (doc, fields) { var field, key, i, len; if (util.isArray(fields)) { key = {}; for (i = 0, len = fields.length; i < len; i++) { field = fields[i]; key[field] = document.getDotValue(doc, field); } return key; } else { return document.getDotValue(doc, fields); } }
javascript
function getDotValues (doc, fields) { var field, key, i, len; if (util.isArray(fields)) { key = {}; for (i = 0, len = fields.length; i < len; i++) { field = fields[i]; key[field] = document.getDotValue(doc, field); } return key; } else { return document.getDotValue(doc, fields); } }
[ "function", "getDotValues", "(", "doc", ",", "fields", ")", "{", "var", "field", ",", "key", ",", "i", ",", "len", ";", "if", "(", "util", ".", "isArray", "(", "fields", ")", ")", "{", "key", "=", "{", "}", ";", "for", "(", "i", "=", "0", ",", "len", "=", "fields", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "field", "=", "fields", "[", "i", "]", ";", "key", "[", "field", "]", "=", "document", ".", "getDotValue", "(", "doc", ",", "field", ")", ";", "}", "return", "key", ";", "}", "else", "{", "return", "document", ".", "getDotValue", "(", "doc", ",", "fields", ")", ";", "}", "}" ]
Get dot values for either a bunch of fields or just one.
[ "Get", "dot", "values", "for", "either", "a", "bunch", "of", "fields", "or", "just", "one", "." ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/indexes.js#L30-L43
16,215
Ivshti/linvodb3
lib/model.js
Model
function Model (name, schema, options) { if (typeof(name) != "string") throw "model name must be provided and a string"; if (arguments.length==1) { options = {}; schema = {} }; if (arguments.length==2) { options = schema; schema = {} }; var self = function Document(raw) { return document.Document.call(this, self, raw) }; // Call the Document builder _.extend(self, Model.prototype); // Ugly but works - we need to return a function but still inherit prototype var emitter = new events.EventEmitter(); emitter.setMaxListeners(0); for (var prop in emitter) self[prop] = emitter[prop]; self.modelName = name; self.schema = schemas.normalize(Object.assign({}, schema)); // Normalize to allow for short-hands self.filename = path.normalize(options.filename || path.join(Model.dbPath || ".", name+".db")); self.options = _.extend({}, Model.defaults, options); // Indexed by field name, dot notation can be used // _id is always indexed and since _ids are generated randomly the underlying // binary is always well-balanced self.indexes = {}; self.indexes._id = new Index({ fieldName: '_id', unique: true }); schemas.indexes(schema).forEach(function(idx) { self.ensureIndex(idx) }); // Concurrency control for 1) index building and 2) pulling objects from LevelUP self._pipe = new bagpipe(1); self._pipe.pause(); self._retrQueue = new bagpipe(LEVELUP_RETR_CONCURRENCY); self._retrQueue._locked = {}; self._retrQueue._locks = {}; // Hide those in ._retrQueue self._methods = {}; if (self.options.autoLoad) self.initStore(); return self; }
javascript
function Model (name, schema, options) { if (typeof(name) != "string") throw "model name must be provided and a string"; if (arguments.length==1) { options = {}; schema = {} }; if (arguments.length==2) { options = schema; schema = {} }; var self = function Document(raw) { return document.Document.call(this, self, raw) }; // Call the Document builder _.extend(self, Model.prototype); // Ugly but works - we need to return a function but still inherit prototype var emitter = new events.EventEmitter(); emitter.setMaxListeners(0); for (var prop in emitter) self[prop] = emitter[prop]; self.modelName = name; self.schema = schemas.normalize(Object.assign({}, schema)); // Normalize to allow for short-hands self.filename = path.normalize(options.filename || path.join(Model.dbPath || ".", name+".db")); self.options = _.extend({}, Model.defaults, options); // Indexed by field name, dot notation can be used // _id is always indexed and since _ids are generated randomly the underlying // binary is always well-balanced self.indexes = {}; self.indexes._id = new Index({ fieldName: '_id', unique: true }); schemas.indexes(schema).forEach(function(idx) { self.ensureIndex(idx) }); // Concurrency control for 1) index building and 2) pulling objects from LevelUP self._pipe = new bagpipe(1); self._pipe.pause(); self._retrQueue = new bagpipe(LEVELUP_RETR_CONCURRENCY); self._retrQueue._locked = {}; self._retrQueue._locks = {}; // Hide those in ._retrQueue self._methods = {}; if (self.options.autoLoad) self.initStore(); return self; }
[ "function", "Model", "(", "name", ",", "schema", ",", "options", ")", "{", "if", "(", "typeof", "(", "name", ")", "!=", "\"string\"", ")", "throw", "\"model name must be provided and a string\"", ";", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "options", "=", "{", "}", ";", "schema", "=", "{", "}", "}", ";", "if", "(", "arguments", ".", "length", "==", "2", ")", "{", "options", "=", "schema", ";", "schema", "=", "{", "}", "}", ";", "var", "self", "=", "function", "Document", "(", "raw", ")", "{", "return", "document", ".", "Document", ".", "call", "(", "this", ",", "self", ",", "raw", ")", "}", ";", "// Call the Document builder", "_", ".", "extend", "(", "self", ",", "Model", ".", "prototype", ")", ";", "// Ugly but works - we need to return a function but still inherit prototype", "var", "emitter", "=", "new", "events", ".", "EventEmitter", "(", ")", ";", "emitter", ".", "setMaxListeners", "(", "0", ")", ";", "for", "(", "var", "prop", "in", "emitter", ")", "self", "[", "prop", "]", "=", "emitter", "[", "prop", "]", ";", "self", ".", "modelName", "=", "name", ";", "self", ".", "schema", "=", "schemas", ".", "normalize", "(", "Object", ".", "assign", "(", "{", "}", ",", "schema", ")", ")", ";", "// Normalize to allow for short-hands", "self", ".", "filename", "=", "path", ".", "normalize", "(", "options", ".", "filename", "||", "path", ".", "join", "(", "Model", ".", "dbPath", "||", "\".\"", ",", "name", "+", "\".db\"", ")", ")", ";", "self", ".", "options", "=", "_", ".", "extend", "(", "{", "}", ",", "Model", ".", "defaults", ",", "options", ")", ";", "// Indexed by field name, dot notation can be used", "// _id is always indexed and since _ids are generated randomly the underlying", "// binary is always well-balanced", "self", ".", "indexes", "=", "{", "}", ";", "self", ".", "indexes", ".", "_id", "=", "new", "Index", "(", "{", "fieldName", ":", "'_id'", ",", "unique", ":", "true", "}", ")", ";", "schemas", ".", "indexes", "(", "schema", ")", ".", "forEach", "(", "function", "(", "idx", ")", "{", "self", ".", "ensureIndex", "(", "idx", ")", "}", ")", ";", "// Concurrency control for 1) index building and 2) pulling objects from LevelUP", "self", ".", "_pipe", "=", "new", "bagpipe", "(", "1", ")", ";", "self", ".", "_pipe", ".", "pause", "(", ")", ";", "self", ".", "_retrQueue", "=", "new", "bagpipe", "(", "LEVELUP_RETR_CONCURRENCY", ")", ";", "self", ".", "_retrQueue", ".", "_locked", "=", "{", "}", ";", "self", ".", "_retrQueue", ".", "_locks", "=", "{", "}", ";", "// Hide those in ._retrQueue", "self", ".", "_methods", "=", "{", "}", ";", "if", "(", "self", ".", "options", ".", "autoLoad", ")", "self", ".", "initStore", "(", ")", ";", "return", "self", ";", "}" ]
We'll use that on a bagpipe instance regulating findById Create a new model
[ "We", "ll", "use", "that", "on", "a", "bagpipe", "instance", "regulating", "findById", "Create", "a", "new", "model" ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/model.js#L29-L62
16,216
Ivshti/linvodb3
lib/cursor.js
updated
function updated(docs) { // Refresh if any of the objects: have an ID which is in our results OR they match our query (this.query) var shouldRefresh = false; docs.forEach(function(doc) { // Avoid using .some since it would stop iterating after first match and we need to set _prefetched var interested = self._count || self._ids[doc._id] || document.match(doc, self.query); // _count queries never set _ids if (interested) self._prefetched[doc._id] = doc; shouldRefresh = shouldRefresh || interested; }); if (shouldRefresh) refresh(); }
javascript
function updated(docs) { // Refresh if any of the objects: have an ID which is in our results OR they match our query (this.query) var shouldRefresh = false; docs.forEach(function(doc) { // Avoid using .some since it would stop iterating after first match and we need to set _prefetched var interested = self._count || self._ids[doc._id] || document.match(doc, self.query); // _count queries never set _ids if (interested) self._prefetched[doc._id] = doc; shouldRefresh = shouldRefresh || interested; }); if (shouldRefresh) refresh(); }
[ "function", "updated", "(", "docs", ")", "{", "// Refresh if any of the objects: have an ID which is in our results OR they match our query (this.query)", "var", "shouldRefresh", "=", "false", ";", "docs", ".", "forEach", "(", "function", "(", "doc", ")", "{", "// Avoid using .some since it would stop iterating after first match and we need to set _prefetched", "var", "interested", "=", "self", ".", "_count", "||", "self", ".", "_ids", "[", "doc", ".", "_id", "]", "||", "document", ".", "match", "(", "doc", ",", "self", ".", "query", ")", ";", "// _count queries never set _ids", "if", "(", "interested", ")", "self", ".", "_prefetched", "[", "doc", ".", "_id", "]", "=", "doc", ";", "shouldRefresh", "=", "shouldRefresh", "||", "interested", ";", "}", ")", ";", "if", "(", "shouldRefresh", ")", "refresh", "(", ")", ";", "}" ]
Watch for changes
[ "Watch", "for", "changes" ]
6952de376e4761167cb0f9c29342d16d675874bf
https://github.com/Ivshti/linvodb3/blob/6952de376e4761167cb0f9c29342d16d675874bf/lib/cursor.js#L241-L250
16,217
adobe/git-server
lib/git.js
isCheckedOut
async function isCheckedOut(dir, ref) { let oidCurrent; return git.resolveRef({ dir, ref: 'HEAD' }) .then((oid) => { oidCurrent = oid; return git.resolveRef({ dir, ref }); }) .then(oid => oidCurrent === oid) .catch(() => false); }
javascript
async function isCheckedOut(dir, ref) { let oidCurrent; return git.resolveRef({ dir, ref: 'HEAD' }) .then((oid) => { oidCurrent = oid; return git.resolveRef({ dir, ref }); }) .then(oid => oidCurrent === oid) .catch(() => false); }
[ "async", "function", "isCheckedOut", "(", "dir", ",", "ref", ")", "{", "let", "oidCurrent", ";", "return", "git", ".", "resolveRef", "(", "{", "dir", ",", "ref", ":", "'HEAD'", "}", ")", ".", "then", "(", "(", "oid", ")", "=>", "{", "oidCurrent", "=", "oid", ";", "return", "git", ".", "resolveRef", "(", "{", "dir", ",", "ref", "}", ")", ";", "}", ")", ".", "then", "(", "oid", "=>", "oidCurrent", "===", "oid", ")", ".", "catch", "(", "(", ")", "=>", "false", ")", ";", "}" ]
Determines whether the specified reference is currently checked out in the working dir. @param {string} dir git repo path @param {string} ref reference (branch or tag) @returns {Promise<boolean>} `true` if the specified reference is checked out
[ "Determines", "whether", "the", "specified", "reference", "is", "currently", "checked", "out", "in", "the", "working", "dir", "." ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/git.js#L69-L78
16,218
adobe/git-server
lib/git.js
resolveCommit
async function resolveCommit(dir, ref) { return git.resolveRef({ dir, ref }) .catch(async (err) => { if (err.code === 'ResolveRefError') { // fallback: is ref a shortened oid prefix? const oid = await git.expandOid({ dir, oid: ref }).catch(() => { throw err; }); return git.resolveRef({ dir, ref: oid }); } // re-throw throw err; }); }
javascript
async function resolveCommit(dir, ref) { return git.resolveRef({ dir, ref }) .catch(async (err) => { if (err.code === 'ResolveRefError') { // fallback: is ref a shortened oid prefix? const oid = await git.expandOid({ dir, oid: ref }).catch(() => { throw err; }); return git.resolveRef({ dir, ref: oid }); } // re-throw throw err; }); }
[ "async", "function", "resolveCommit", "(", "dir", ",", "ref", ")", "{", "return", "git", ".", "resolveRef", "(", "{", "dir", ",", "ref", "}", ")", ".", "catch", "(", "async", "(", "err", ")", "=>", "{", "if", "(", "err", ".", "code", "===", "'ResolveRefError'", ")", "{", "// fallback: is ref a shortened oid prefix?", "const", "oid", "=", "await", "git", ".", "expandOid", "(", "{", "dir", ",", "oid", ":", "ref", "}", ")", ".", "catch", "(", "(", ")", "=>", "{", "throw", "err", ";", "}", ")", ";", "return", "git", ".", "resolveRef", "(", "{", "dir", ",", "ref", ":", "oid", "}", ")", ";", "}", "// re-throw", "throw", "err", ";", "}", ")", ";", "}" ]
Returns the commit oid of the curent commit referenced by `ref` @param {string} dir git repo path @param {string} ref reference (branch, tag or commit sha) @returns {Promise<string>} commit oid of the curent commit referenced by `ref` @throws {GitError} `err.code === 'ResolveRefError'`: invalid reference
[ "Returns", "the", "commit", "oid", "of", "the", "curent", "commit", "referenced", "by", "ref" ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/git.js#L88-L99
16,219
adobe/git-server
lib/git.js
resolveBlob
async function resolveBlob(dir, ref, pathName, includeUncommitted) { const commitSha = await resolveCommit(dir, ref); // project-helix/#150: check for uncommitted local changes // project-helix/#183: serve newly created uncommitted files // project-helix/#187: only serve uncommitted content if currently // checked-out and requested refs match if (!includeUncommitted) { return (await git.readObject({ dir, oid: commitSha, filepath: pathName })).oid; } // check working dir status const status = await git.status({ dir, filepath: pathName }); if (status.endsWith('unmodified')) { return (await git.readObject({ dir, oid: commitSha, filepath: pathName })).oid; } if (status.endsWith('absent') || status.endsWith('deleted')) { const err = new Error(`Not found: ${pathName}`); err.code = git.E.TreeOrBlobNotFoundError; throw err; } // return blob id representing working dir file const content = await fse.readFile(resolvePath(dir, pathName)); return git.writeObject({ dir, object: content, type: 'blob', format: 'content', }); }
javascript
async function resolveBlob(dir, ref, pathName, includeUncommitted) { const commitSha = await resolveCommit(dir, ref); // project-helix/#150: check for uncommitted local changes // project-helix/#183: serve newly created uncommitted files // project-helix/#187: only serve uncommitted content if currently // checked-out and requested refs match if (!includeUncommitted) { return (await git.readObject({ dir, oid: commitSha, filepath: pathName })).oid; } // check working dir status const status = await git.status({ dir, filepath: pathName }); if (status.endsWith('unmodified')) { return (await git.readObject({ dir, oid: commitSha, filepath: pathName })).oid; } if (status.endsWith('absent') || status.endsWith('deleted')) { const err = new Error(`Not found: ${pathName}`); err.code = git.E.TreeOrBlobNotFoundError; throw err; } // return blob id representing working dir file const content = await fse.readFile(resolvePath(dir, pathName)); return git.writeObject({ dir, object: content, type: 'blob', format: 'content', }); }
[ "async", "function", "resolveBlob", "(", "dir", ",", "ref", ",", "pathName", ",", "includeUncommitted", ")", "{", "const", "commitSha", "=", "await", "resolveCommit", "(", "dir", ",", "ref", ")", ";", "// project-helix/#150: check for uncommitted local changes", "// project-helix/#183: serve newly created uncommitted files", "// project-helix/#187: only serve uncommitted content if currently", "// checked-out and requested refs match", "if", "(", "!", "includeUncommitted", ")", "{", "return", "(", "await", "git", ".", "readObject", "(", "{", "dir", ",", "oid", ":", "commitSha", ",", "filepath", ":", "pathName", "}", ")", ")", ".", "oid", ";", "}", "// check working dir status", "const", "status", "=", "await", "git", ".", "status", "(", "{", "dir", ",", "filepath", ":", "pathName", "}", ")", ";", "if", "(", "status", ".", "endsWith", "(", "'unmodified'", ")", ")", "{", "return", "(", "await", "git", ".", "readObject", "(", "{", "dir", ",", "oid", ":", "commitSha", ",", "filepath", ":", "pathName", "}", ")", ")", ".", "oid", ";", "}", "if", "(", "status", ".", "endsWith", "(", "'absent'", ")", "||", "status", ".", "endsWith", "(", "'deleted'", ")", ")", "{", "const", "err", "=", "new", "Error", "(", "`", "${", "pathName", "}", "`", ")", ";", "err", ".", "code", "=", "git", ".", "E", ".", "TreeOrBlobNotFoundError", ";", "throw", "err", ";", "}", "// return blob id representing working dir file", "const", "content", "=", "await", "fse", ".", "readFile", "(", "resolvePath", "(", "dir", ",", "pathName", ")", ")", ";", "return", "git", ".", "writeObject", "(", "{", "dir", ",", "object", ":", "content", ",", "type", ":", "'blob'", ",", "format", ":", "'content'", ",", "}", ")", ";", "}" ]
Returns the blob oid of the file at revision `ref` and `pathName` @param {string} dir git repo path @param {string} ref reference (branch, tag or commit sha) @param {string} filePath relative path to file @param {boolean} includeUncommitted include uncommitted changes in working dir @returns {Promise<string>} blob oid of specified file @throws {GitError} `err.code === 'TreeOrBlobNotFoundError'`: resource not found `err.code === 'ResolveRefError'`: invalid reference
[ "Returns", "the", "blob", "oid", "of", "the", "file", "at", "revision", "ref", "and", "pathName" ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/git.js#L112-L141
16,220
adobe/git-server
lib/git.js
getRawContent
async function getRawContent(dir, ref, pathName, includeUncommitted) { return resolveBlob(dir, ref, pathName, includeUncommitted) .then(oid => git.readObject({ dir, oid, format: 'content' }).object); }
javascript
async function getRawContent(dir, ref, pathName, includeUncommitted) { return resolveBlob(dir, ref, pathName, includeUncommitted) .then(oid => git.readObject({ dir, oid, format: 'content' }).object); }
[ "async", "function", "getRawContent", "(", "dir", ",", "ref", ",", "pathName", ",", "includeUncommitted", ")", "{", "return", "resolveBlob", "(", "dir", ",", "ref", ",", "pathName", ",", "includeUncommitted", ")", ".", "then", "(", "oid", "=>", "git", ".", "readObject", "(", "{", "dir", ",", "oid", ",", "format", ":", "'content'", "}", ")", ".", "object", ")", ";", "}" ]
Returns the contents of the file at revision `ref` and `pathName` @param {string} dir git repo path @param {string} ref reference (branch, tag or commit sha) @param {string} filePath relative path to file @param {boolean} includeUncommitted include uncommitted changes in working dir @returns {Promise<Buffer>} content of specified file @throws {GitError} `err.code === 'TreeOrBlobNotFoundError'`: resource not found `err.code === 'ResolveRefError'`: invalid reference
[ "Returns", "the", "contents", "of", "the", "file", "at", "revision", "ref", "and", "pathName" ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/git.js#L154-L157
16,221
adobe/git-server
lib/git.js
createBlobReadStream
async function createBlobReadStream(dir, oid) { const { object: content } = await git.readObject({ dir, oid }); const stream = new PassThrough(); stream.end(content); return stream; }
javascript
async function createBlobReadStream(dir, oid) { const { object: content } = await git.readObject({ dir, oid }); const stream = new PassThrough(); stream.end(content); return stream; }
[ "async", "function", "createBlobReadStream", "(", "dir", ",", "oid", ")", "{", "const", "{", "object", ":", "content", "}", "=", "await", "git", ".", "readObject", "(", "{", "dir", ",", "oid", "}", ")", ";", "const", "stream", "=", "new", "PassThrough", "(", ")", ";", "stream", ".", "end", "(", "content", ")", ";", "return", "stream", ";", "}" ]
Returns a stream for reading the specified blob. @param {string} dir git repo path @param {string} oid blob sha1 @returns {Promise<Stream>} readable Stream instance
[ "Returns", "a", "stream", "for", "reading", "the", "specified", "blob", "." ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/git.js#L166-L171
16,222
adobe/git-server
lib/git.js
isValidSha
function isValidSha(str) { if (typeof str === 'string' && str.length === 40) { const res = str.match(/[0-9a-f]/g); return res && res.length === 40; } return false; }
javascript
function isValidSha(str) { if (typeof str === 'string' && str.length === 40) { const res = str.match(/[0-9a-f]/g); return res && res.length === 40; } return false; }
[ "function", "isValidSha", "(", "str", ")", "{", "if", "(", "typeof", "str", "===", "'string'", "&&", "str", ".", "length", "===", "40", ")", "{", "const", "res", "=", "str", ".", "match", "(", "/", "[0-9a-f]", "/", "g", ")", ";", "return", "res", "&&", "res", ".", "length", "===", "40", ";", "}", "return", "false", ";", "}" ]
Checks if the specified string is a valid SHA-1 value. @param {string} str @returns {boolean} `true` if `str` represents a valid SHA-1, otherwise `false`
[ "Checks", "if", "the", "specified", "string", "is", "a", "valid", "SHA", "-", "1", "value", "." ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/git.js#L190-L196
16,223
adobe/git-server
lib/git.js
commitLog
async function commitLog(dir, ref, path) { return git.log({ dir, ref, path }) .catch(async (err) => { if (err.code === 'ResolveRefError') { // fallback: is ref a shortened oid prefix? const oid = await git.expandOid({ dir, oid: ref }); return git.log({ dir, ref: oid, path }); } // re-throw throw err; }) .then(async (commits) => { if (typeof path === 'string' && path.length) { // filter by path let lastSHA = null; let lastCommit = null; const filteredCommits = []; for (let i = 0; i < commits.length; i += 1) { const commit = commits[i]; /* eslint-disable no-await-in-loop */ try { const o = await git.readObject({ dir, oid: commit.oid, filepath: path }); if (i === commits.length - 1) { // file already existed in first commit filteredCommits.push(commit); break; } if (o.oid !== lastSHA) { if (lastSHA !== null) { filteredCommits.push(lastCommit); } lastSHA = o.oid; } } catch (err) { // file no longer there filteredCommits.push(lastCommit); break; } lastCommit = commit; } // unfiltered commits return filteredCommits; } // unfiltered commits return commits; }); }
javascript
async function commitLog(dir, ref, path) { return git.log({ dir, ref, path }) .catch(async (err) => { if (err.code === 'ResolveRefError') { // fallback: is ref a shortened oid prefix? const oid = await git.expandOid({ dir, oid: ref }); return git.log({ dir, ref: oid, path }); } // re-throw throw err; }) .then(async (commits) => { if (typeof path === 'string' && path.length) { // filter by path let lastSHA = null; let lastCommit = null; const filteredCommits = []; for (let i = 0; i < commits.length; i += 1) { const commit = commits[i]; /* eslint-disable no-await-in-loop */ try { const o = await git.readObject({ dir, oid: commit.oid, filepath: path }); if (i === commits.length - 1) { // file already existed in first commit filteredCommits.push(commit); break; } if (o.oid !== lastSHA) { if (lastSHA !== null) { filteredCommits.push(lastCommit); } lastSHA = o.oid; } } catch (err) { // file no longer there filteredCommits.push(lastCommit); break; } lastCommit = commit; } // unfiltered commits return filteredCommits; } // unfiltered commits return commits; }); }
[ "async", "function", "commitLog", "(", "dir", ",", "ref", ",", "path", ")", "{", "return", "git", ".", "log", "(", "{", "dir", ",", "ref", ",", "path", "}", ")", ".", "catch", "(", "async", "(", "err", ")", "=>", "{", "if", "(", "err", ".", "code", "===", "'ResolveRefError'", ")", "{", "// fallback: is ref a shortened oid prefix?", "const", "oid", "=", "await", "git", ".", "expandOid", "(", "{", "dir", ",", "oid", ":", "ref", "}", ")", ";", "return", "git", ".", "log", "(", "{", "dir", ",", "ref", ":", "oid", ",", "path", "}", ")", ";", "}", "// re-throw", "throw", "err", ";", "}", ")", ".", "then", "(", "async", "(", "commits", ")", "=>", "{", "if", "(", "typeof", "path", "===", "'string'", "&&", "path", ".", "length", ")", "{", "// filter by path", "let", "lastSHA", "=", "null", ";", "let", "lastCommit", "=", "null", ";", "const", "filteredCommits", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "commits", ".", "length", ";", "i", "+=", "1", ")", "{", "const", "commit", "=", "commits", "[", "i", "]", ";", "/* eslint-disable no-await-in-loop */", "try", "{", "const", "o", "=", "await", "git", ".", "readObject", "(", "{", "dir", ",", "oid", ":", "commit", ".", "oid", ",", "filepath", ":", "path", "}", ")", ";", "if", "(", "i", "===", "commits", ".", "length", "-", "1", ")", "{", "// file already existed in first commit", "filteredCommits", ".", "push", "(", "commit", ")", ";", "break", ";", "}", "if", "(", "o", ".", "oid", "!==", "lastSHA", ")", "{", "if", "(", "lastSHA", "!==", "null", ")", "{", "filteredCommits", ".", "push", "(", "lastCommit", ")", ";", "}", "lastSHA", "=", "o", ".", "oid", ";", "}", "}", "catch", "(", "err", ")", "{", "// file no longer there", "filteredCommits", ".", "push", "(", "lastCommit", ")", ";", "break", ";", "}", "lastCommit", "=", "commit", ";", "}", "// unfiltered commits", "return", "filteredCommits", ";", "}", "// unfiltered commits", "return", "commits", ";", "}", ")", ";", "}" ]
Returns a commit log, i.e. an array of commits in reverse chronological order. @param {string} dir git repo path @param {string} ref reference (branch, tag or commit sha) @param {string} path only commits containing this file path will be returned @throws {GitError} `err.code === 'ResolveRefError'`: invalid reference `err.code === 'ReadObjectFail'`: not found
[ "Returns", "a", "commit", "log", "i", ".", "e", ".", "an", "array", "of", "commits", "in", "reverse", "chronological", "order", "." ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/git.js#L237-L283
16,224
adobe/git-server
lib/utils.js
randomFileOrFolderName
function randomFileOrFolderName(len = 32) { if (Number.isFinite(len)) { return crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len); } throw new Error(`illegal argument: ${len}`); }
javascript
function randomFileOrFolderName(len = 32) { if (Number.isFinite(len)) { return crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len); } throw new Error(`illegal argument: ${len}`); }
[ "function", "randomFileOrFolderName", "(", "len", "=", "32", ")", "{", "if", "(", "Number", ".", "isFinite", "(", "len", ")", ")", "{", "return", "crypto", ".", "randomBytes", "(", "Math", ".", "ceil", "(", "len", "/", "2", ")", ")", ".", "toString", "(", "'hex'", ")", ".", "slice", "(", "0", ",", "len", ")", ";", "}", "throw", "new", "Error", "(", "`", "${", "len", "}", "`", ")", ";", "}" ]
Generates a random name. @param {Number} len
[ "Generates", "a", "random", "name", "." ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/utils.js#L32-L37
16,225
adobe/git-server
lib/utils.js
resolveRepositoryPath
function resolveRepositoryPath(options, owner, repo) { let repPath = path.resolve(options.repoRoot, owner, repo); if (options.virtualRepos[owner] && options.virtualRepos[owner][repo]) { repPath = path.resolve(options.virtualRepos[owner][repo].path); } return repPath; }
javascript
function resolveRepositoryPath(options, owner, repo) { let repPath = path.resolve(options.repoRoot, owner, repo); if (options.virtualRepos[owner] && options.virtualRepos[owner][repo]) { repPath = path.resolve(options.virtualRepos[owner][repo].path); } return repPath; }
[ "function", "resolveRepositoryPath", "(", "options", ",", "owner", ",", "repo", ")", "{", "let", "repPath", "=", "path", ".", "resolve", "(", "options", ".", "repoRoot", ",", "owner", ",", "repo", ")", ";", "if", "(", "options", ".", "virtualRepos", "[", "owner", "]", "&&", "options", ".", "virtualRepos", "[", "owner", "]", "[", "repo", "]", ")", "{", "repPath", "=", "path", ".", "resolve", "(", "options", ".", "virtualRepos", "[", "owner", "]", "[", "repo", "]", ".", "path", ")", ";", "}", "return", "repPath", ";", "}" ]
Resolves the file system path of the specified repository. @param {object} options configuration hash @param {string} owner github org or user @param {string} repo repository name
[ "Resolves", "the", "file", "system", "path", "of", "the", "specified", "repository", "." ]
e0162b145c158560f785721349be04e2ca9e0379
https://github.com/adobe/git-server/blob/e0162b145c158560f785721349be04e2ca9e0379/lib/utils.js#L46-L53
16,226
davisjam/vuln-regex-detector
src/cache/client/npm/vuln-regex-detector-client.js
promiseResult
function promiseResult (options, data) { log(`promiseResult: data ${data}`); return new Promise((resolve, reject) => { /* Check cache to avoid I/O. */ const cacheHit = checkCache(config, pattern); if (cacheHit !== RESPONSE_UNKNOWN) { log(`Cache hit: ${cacheHit}`); return resolve(cacheHit); } const req = https.request(options, (res) => { res.setEncoding('utf8'); let response = ''; res.on('data', (chunk) => { log(`Got data`); response += chunk; }); res.on('end', () => { log(`end: I got ${JSON.stringify(response)}`); const result = serverResponseToRESPONSE(response); log(`end: result ${result}`); updateCache(config, postObject.pattern, result); if (result === RESPONSE_INVALID) { return reject(result); } else { return resolve(result); } }); }); req.on('error', (e) => { log(`Error: ${e}`); return reject(RESPONSE_INVALID); }); // Write data to request body. log(`Writing to req:\n${data}`); req.write(data); req.end(); }); }
javascript
function promiseResult (options, data) { log(`promiseResult: data ${data}`); return new Promise((resolve, reject) => { /* Check cache to avoid I/O. */ const cacheHit = checkCache(config, pattern); if (cacheHit !== RESPONSE_UNKNOWN) { log(`Cache hit: ${cacheHit}`); return resolve(cacheHit); } const req = https.request(options, (res) => { res.setEncoding('utf8'); let response = ''; res.on('data', (chunk) => { log(`Got data`); response += chunk; }); res.on('end', () => { log(`end: I got ${JSON.stringify(response)}`); const result = serverResponseToRESPONSE(response); log(`end: result ${result}`); updateCache(config, postObject.pattern, result); if (result === RESPONSE_INVALID) { return reject(result); } else { return resolve(result); } }); }); req.on('error', (e) => { log(`Error: ${e}`); return reject(RESPONSE_INVALID); }); // Write data to request body. log(`Writing to req:\n${data}`); req.write(data); req.end(); }); }
[ "function", "promiseResult", "(", "options", ",", "data", ")", "{", "log", "(", "`", "${", "data", "}", "`", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "/* Check cache to avoid I/O. */", "const", "cacheHit", "=", "checkCache", "(", "config", ",", "pattern", ")", ";", "if", "(", "cacheHit", "!==", "RESPONSE_UNKNOWN", ")", "{", "log", "(", "`", "${", "cacheHit", "}", "`", ")", ";", "return", "resolve", "(", "cacheHit", ")", ";", "}", "const", "req", "=", "https", ".", "request", "(", "options", ",", "(", "res", ")", "=>", "{", "res", ".", "setEncoding", "(", "'utf8'", ")", ";", "let", "response", "=", "''", ";", "res", ".", "on", "(", "'data'", ",", "(", "chunk", ")", "=>", "{", "log", "(", "`", "`", ")", ";", "response", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "log", "(", "`", "${", "JSON", ".", "stringify", "(", "response", ")", "}", "`", ")", ";", "const", "result", "=", "serverResponseToRESPONSE", "(", "response", ")", ";", "log", "(", "`", "${", "result", "}", "`", ")", ";", "updateCache", "(", "config", ",", "postObject", ".", "pattern", ",", "result", ")", ";", "if", "(", "result", "===", "RESPONSE_INVALID", ")", "{", "return", "reject", "(", "result", ")", ";", "}", "else", "{", "return", "resolve", "(", "result", ")", ";", "}", "}", ")", ";", "}", ")", ";", "req", ".", "on", "(", "'error'", ",", "(", "e", ")", "=>", "{", "log", "(", "`", "${", "e", "}", "`", ")", ";", "return", "reject", "(", "RESPONSE_INVALID", ")", ";", "}", ")", ";", "// Write data to request body.", "log", "(", "`", "\\n", "${", "data", "}", "`", ")", ";", "req", ".", "write", "(", "data", ")", ";", "req", ".", "end", "(", ")", ";", "}", ")", ";", "}" ]
Wrapper so we can return a Promise.
[ "Wrapper", "so", "we", "can", "return", "a", "Promise", "." ]
2cfdf7ac37985ba86caa052e5bb0f706b1553b9b
https://github.com/davisjam/vuln-regex-detector/blob/2cfdf7ac37985ba86caa052e5bb0f706b1553b9b/src/cache/client/npm/vuln-regex-detector-client.js#L98-L142
16,227
davisjam/vuln-regex-detector
src/cache/server/cache-server.js
collectionLookup
function collectionLookup (collection, query) { const id = createID(query.pattern, query.language); log(`collectionLookup: querying for ${id}`); return collection.find({_id: id}, {result: 1}).toArray() .then( (docs) => { log(`collectionLookup: Got ${docs.length} docs`); if (docs.length === 0) { log(`collectionLookup ${createID(query.pattern, query.language)}: no results`); return Promise.resolve(PATTERN_UNKNOWN); } else if (docs.length === 1) { log(`collectionLookup ${query.pattern}-${query.language}: result: ${docs[0].result}`); return Promise.resolve(docs[0]); } else { log(`collectionLookup unexpected multiple match: ${jsonStringify(docs)}`); return Promise.resolve(PATTERN_UNKNOWN); } }, (e) => { log(`collectionLookup error: ${e}`); return Promise.resolve(PATTERN_UNKNOWN); } ); }
javascript
function collectionLookup (collection, query) { const id = createID(query.pattern, query.language); log(`collectionLookup: querying for ${id}`); return collection.find({_id: id}, {result: 1}).toArray() .then( (docs) => { log(`collectionLookup: Got ${docs.length} docs`); if (docs.length === 0) { log(`collectionLookup ${createID(query.pattern, query.language)}: no results`); return Promise.resolve(PATTERN_UNKNOWN); } else if (docs.length === 1) { log(`collectionLookup ${query.pattern}-${query.language}: result: ${docs[0].result}`); return Promise.resolve(docs[0]); } else { log(`collectionLookup unexpected multiple match: ${jsonStringify(docs)}`); return Promise.resolve(PATTERN_UNKNOWN); } }, (e) => { log(`collectionLookup error: ${e}`); return Promise.resolve(PATTERN_UNKNOWN); } ); }
[ "function", "collectionLookup", "(", "collection", ",", "query", ")", "{", "const", "id", "=", "createID", "(", "query", ".", "pattern", ",", "query", ".", "language", ")", ";", "log", "(", "`", "${", "id", "}", "`", ")", ";", "return", "collection", ".", "find", "(", "{", "_id", ":", "id", "}", ",", "{", "result", ":", "1", "}", ")", ".", "toArray", "(", ")", ".", "then", "(", "(", "docs", ")", "=>", "{", "log", "(", "`", "${", "docs", ".", "length", "}", "`", ")", ";", "if", "(", "docs", ".", "length", "===", "0", ")", "{", "log", "(", "`", "${", "createID", "(", "query", ".", "pattern", ",", "query", ".", "language", ")", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_UNKNOWN", ")", ";", "}", "else", "if", "(", "docs", ".", "length", "===", "1", ")", "{", "log", "(", "`", "${", "query", ".", "pattern", "}", "${", "query", ".", "language", "}", "${", "docs", "[", "0", "]", ".", "result", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "docs", "[", "0", "]", ")", ";", "}", "else", "{", "log", "(", "`", "${", "jsonStringify", "(", "docs", ")", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_UNKNOWN", ")", ";", "}", "}", ",", "(", "e", ")", "=>", "{", "log", "(", "`", "${", "e", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_UNKNOWN", ")", ";", "}", ")", ";", "}" ]
Helper for isVulnerable. Returns a Promise that resolves to one of the PATTERN_X results.
[ "Helper", "for", "isVulnerable", ".", "Returns", "a", "Promise", "that", "resolves", "to", "one", "of", "the", "PATTERN_X", "results", "." ]
2cfdf7ac37985ba86caa052e5bb0f706b1553b9b
https://github.com/davisjam/vuln-regex-detector/blob/2cfdf7ac37985ba86caa052e5bb0f706b1553b9b/src/cache/server/cache-server.js#L167-L190
16,228
davisjam/vuln-regex-detector
src/cache/server/cache-server.js
reportResult
function reportResult (body) { // Reject invalid reports. if (!body) { log(`reportResult: no body`); return Promise.resolve(PATTERN_INVALID); } // Required fields. let isInvalid = false; ['pattern', 'language', 'result'].forEach((f) => { if (!body.hasOwnProperty(f) || body[f] === null) { isInvalid = true; } }); if (isInvalid) { log(`reportResult: invalid: ${jsonStringify(body)}`); return Promise.resolve(PATTERN_INVALID); } // Supported results. if (body.result === PATTERN_UNKNOWN || body.result === PATTERN_SAFE || body.result === PATTERN_VULNERABLE) { } else { log(`reportResult: invalid result ${body.result}`); return Promise.resolve(PATTERN_INVALID); } // Vulnerable must include proof. if (body.result === PATTERN_VULNERABLE && !body.hasOwnProperty('evilInput')) { log(`reportResult: ${body.result} but no evilInput`); return Promise.resolve(PATTERN_INVALID); } // Malicious client could spam us with already-solved requests. // Check if we know the answer already. return isVulnerable(body) .then((result) => { if (result !== PATTERN_UNKNOWN) { log(`reportResult: already known. Malicious client, or racing clients?`); return Promise.resolve(result); } // New pattern, add to dbUploadCollectionName. log(`reportResult: new result, updating dbUploadCollectionName`); return MongoClient.connect(dbUrl) .then((client) => { const db = client.db(dbName); log(`reportResult: connected, now updating DB for {${body.pattern}, ${body.language}} with ${body.result}`); return collectionUpdate(db.collection(dbUploadCollectionName), {pattern: body.pattern, language: body.language, result: body.result, evilInput: body.evilInput}) .then((result) => { client.close(); return result; }) .catch((e) => { log(`reportResult: db error: ${e}`); client.close(); return Promise.resolve(PATTERN_UNKNOWN); }); }) .catch((e) => { log(`reportResult: db error: ${e}`); return Promise.resolve(PATTERN_UNKNOWN); }); }); }
javascript
function reportResult (body) { // Reject invalid reports. if (!body) { log(`reportResult: no body`); return Promise.resolve(PATTERN_INVALID); } // Required fields. let isInvalid = false; ['pattern', 'language', 'result'].forEach((f) => { if (!body.hasOwnProperty(f) || body[f] === null) { isInvalid = true; } }); if (isInvalid) { log(`reportResult: invalid: ${jsonStringify(body)}`); return Promise.resolve(PATTERN_INVALID); } // Supported results. if (body.result === PATTERN_UNKNOWN || body.result === PATTERN_SAFE || body.result === PATTERN_VULNERABLE) { } else { log(`reportResult: invalid result ${body.result}`); return Promise.resolve(PATTERN_INVALID); } // Vulnerable must include proof. if (body.result === PATTERN_VULNERABLE && !body.hasOwnProperty('evilInput')) { log(`reportResult: ${body.result} but no evilInput`); return Promise.resolve(PATTERN_INVALID); } // Malicious client could spam us with already-solved requests. // Check if we know the answer already. return isVulnerable(body) .then((result) => { if (result !== PATTERN_UNKNOWN) { log(`reportResult: already known. Malicious client, or racing clients?`); return Promise.resolve(result); } // New pattern, add to dbUploadCollectionName. log(`reportResult: new result, updating dbUploadCollectionName`); return MongoClient.connect(dbUrl) .then((client) => { const db = client.db(dbName); log(`reportResult: connected, now updating DB for {${body.pattern}, ${body.language}} with ${body.result}`); return collectionUpdate(db.collection(dbUploadCollectionName), {pattern: body.pattern, language: body.language, result: body.result, evilInput: body.evilInput}) .then((result) => { client.close(); return result; }) .catch((e) => { log(`reportResult: db error: ${e}`); client.close(); return Promise.resolve(PATTERN_UNKNOWN); }); }) .catch((e) => { log(`reportResult: db error: ${e}`); return Promise.resolve(PATTERN_UNKNOWN); }); }); }
[ "function", "reportResult", "(", "body", ")", "{", "// Reject invalid reports.", "if", "(", "!", "body", ")", "{", "log", "(", "`", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_INVALID", ")", ";", "}", "// Required fields.", "let", "isInvalid", "=", "false", ";", "[", "'pattern'", ",", "'language'", ",", "'result'", "]", ".", "forEach", "(", "(", "f", ")", "=>", "{", "if", "(", "!", "body", ".", "hasOwnProperty", "(", "f", ")", "||", "body", "[", "f", "]", "===", "null", ")", "{", "isInvalid", "=", "true", ";", "}", "}", ")", ";", "if", "(", "isInvalid", ")", "{", "log", "(", "`", "${", "jsonStringify", "(", "body", ")", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_INVALID", ")", ";", "}", "// Supported results.", "if", "(", "body", ".", "result", "===", "PATTERN_UNKNOWN", "||", "body", ".", "result", "===", "PATTERN_SAFE", "||", "body", ".", "result", "===", "PATTERN_VULNERABLE", ")", "{", "}", "else", "{", "log", "(", "`", "${", "body", ".", "result", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_INVALID", ")", ";", "}", "// Vulnerable must include proof.", "if", "(", "body", ".", "result", "===", "PATTERN_VULNERABLE", "&&", "!", "body", ".", "hasOwnProperty", "(", "'evilInput'", ")", ")", "{", "log", "(", "`", "${", "body", ".", "result", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_INVALID", ")", ";", "}", "// Malicious client could spam us with already-solved requests.", "// Check if we know the answer already.", "return", "isVulnerable", "(", "body", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "if", "(", "result", "!==", "PATTERN_UNKNOWN", ")", "{", "log", "(", "`", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "result", ")", ";", "}", "// New pattern, add to dbUploadCollectionName.", "log", "(", "`", "`", ")", ";", "return", "MongoClient", ".", "connect", "(", "dbUrl", ")", ".", "then", "(", "(", "client", ")", "=>", "{", "const", "db", "=", "client", ".", "db", "(", "dbName", ")", ";", "log", "(", "`", "${", "body", ".", "pattern", "}", "${", "body", ".", "language", "}", "${", "body", ".", "result", "}", "`", ")", ";", "return", "collectionUpdate", "(", "db", ".", "collection", "(", "dbUploadCollectionName", ")", ",", "{", "pattern", ":", "body", ".", "pattern", ",", "language", ":", "body", ".", "language", ",", "result", ":", "body", ".", "result", ",", "evilInput", ":", "body", ".", "evilInput", "}", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "client", ".", "close", "(", ")", ";", "return", "result", ";", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "log", "(", "`", "${", "e", "}", "`", ")", ";", "client", ".", "close", "(", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_UNKNOWN", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "log", "(", "`", "${", "e", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_UNKNOWN", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Returns a Promise that resolves to one of the PATTERN_X results.
[ "Returns", "a", "Promise", "that", "resolves", "to", "one", "of", "the", "PATTERN_X", "results", "." ]
2cfdf7ac37985ba86caa052e5bb0f706b1553b9b
https://github.com/davisjam/vuln-regex-detector/blob/2cfdf7ac37985ba86caa052e5bb0f706b1553b9b/src/cache/server/cache-server.js#L193-L255
16,229
davisjam/vuln-regex-detector
src/cache/server/cache-server.js
collectionUpdate
function collectionUpdate (collection, result) { result._id = createID(result.pattern, result.language); return collection.insertOne(result) .catch((e) => { // May fail due to concurrent update on the same value. log(`collectionUpdate: error: ${e}`); return Promise.resolve(PATTERN_INVALID); }); }
javascript
function collectionUpdate (collection, result) { result._id = createID(result.pattern, result.language); return collection.insertOne(result) .catch((e) => { // May fail due to concurrent update on the same value. log(`collectionUpdate: error: ${e}`); return Promise.resolve(PATTERN_INVALID); }); }
[ "function", "collectionUpdate", "(", "collection", ",", "result", ")", "{", "result", ".", "_id", "=", "createID", "(", "result", ".", "pattern", ",", "result", ".", "language", ")", ";", "return", "collection", ".", "insertOne", "(", "result", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "// May fail due to concurrent update on the same value.", "log", "(", "`", "${", "e", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "PATTERN_INVALID", ")", ";", "}", ")", ";", "}" ]
Helper for reportResult.
[ "Helper", "for", "reportResult", "." ]
2cfdf7ac37985ba86caa052e5bb0f706b1553b9b
https://github.com/davisjam/vuln-regex-detector/blob/2cfdf7ac37985ba86caa052e5bb0f706b1553b9b/src/cache/server/cache-server.js#L258-L266
16,230
andismith/grunt-responsive-images
demo/dist/assets/js/picturefill.js
runPicturefill
function runPicturefill() { picturefill(); var intervalId = setInterval( function(){ // When the document has finished loading, stop checking for new images // https://github.com/ded/domready/blob/master/ready.js#L15 w.picturefill(); if ( /^loaded|^i|^c/.test( doc.readyState ) ) { clearInterval( intervalId ); return; } }, 250 ); if( w.addEventListener ){ var resizeThrottle; w.addEventListener( "resize", function() { w.clearTimeout( resizeThrottle ); resizeThrottle = w.setTimeout( function(){ picturefill({ reevaluate: true }); }, 60 ); }, false ); } }
javascript
function runPicturefill() { picturefill(); var intervalId = setInterval( function(){ // When the document has finished loading, stop checking for new images // https://github.com/ded/domready/blob/master/ready.js#L15 w.picturefill(); if ( /^loaded|^i|^c/.test( doc.readyState ) ) { clearInterval( intervalId ); return; } }, 250 ); if( w.addEventListener ){ var resizeThrottle; w.addEventListener( "resize", function() { w.clearTimeout( resizeThrottle ); resizeThrottle = w.setTimeout( function(){ picturefill({ reevaluate: true }); }, 60 ); }, false ); } }
[ "function", "runPicturefill", "(", ")", "{", "picturefill", "(", ")", ";", "var", "intervalId", "=", "setInterval", "(", "function", "(", ")", "{", "// When the document has finished loading, stop checking for new images", "// https://github.com/ded/domready/blob/master/ready.js#L15", "w", ".", "picturefill", "(", ")", ";", "if", "(", "/", "^loaded|^i|^c", "/", ".", "test", "(", "doc", ".", "readyState", ")", ")", "{", "clearInterval", "(", "intervalId", ")", ";", "return", ";", "}", "}", ",", "250", ")", ";", "if", "(", "w", ".", "addEventListener", ")", "{", "var", "resizeThrottle", ";", "w", ".", "addEventListener", "(", "\"resize\"", ",", "function", "(", ")", "{", "w", ".", "clearTimeout", "(", "resizeThrottle", ")", ";", "resizeThrottle", "=", "w", ".", "setTimeout", "(", "function", "(", ")", "{", "picturefill", "(", "{", "reevaluate", ":", "true", "}", ")", ";", "}", ",", "60", ")", ";", "}", ",", "false", ")", ";", "}", "}" ]
Sets up picture polyfill by polling the document and running the polyfill every 250ms until the document is ready. Also attaches picturefill on resize
[ "Sets", "up", "picture", "polyfill", "by", "polling", "the", "document", "and", "running", "the", "polyfill", "every", "250ms", "until", "the", "document", "is", "ready", ".", "Also", "attaches", "picturefill", "on", "resize" ]
c8def291ab152edb47153ca324722c86326ba573
https://github.com/andismith/grunt-responsive-images/blob/c8def291ab152edb47153ca324722c86326ba573/demo/dist/assets/js/picturefill.js#L509-L529
16,231
andismith/grunt-responsive-images
tasks/responsive_images.js
function(engine) { if (typeof GFX_ENGINES[engine] === 'undefined') { return grunt.fail.warn('Invalid render engine specified'); } grunt.verbose.ok('Using render engine: ' + GFX_ENGINES[engine].name); if (engine === 'im') { return gm.subClass({ imageMagick: (engine === 'im') }); } return gm; }
javascript
function(engine) { if (typeof GFX_ENGINES[engine] === 'undefined') { return grunt.fail.warn('Invalid render engine specified'); } grunt.verbose.ok('Using render engine: ' + GFX_ENGINES[engine].name); if (engine === 'im') { return gm.subClass({ imageMagick: (engine === 'im') }); } return gm; }
[ "function", "(", "engine", ")", "{", "if", "(", "typeof", "GFX_ENGINES", "[", "engine", "]", "===", "'undefined'", ")", "{", "return", "grunt", ".", "fail", ".", "warn", "(", "'Invalid render engine specified'", ")", ";", "}", "grunt", ".", "verbose", ".", "ok", "(", "'Using render engine: '", "+", "GFX_ENGINES", "[", "engine", "]", ".", "name", ")", ";", "if", "(", "engine", "===", "'im'", ")", "{", "return", "gm", ".", "subClass", "(", "{", "imageMagick", ":", "(", "engine", "===", "'im'", ")", "}", ")", ";", "}", "return", "gm", ";", "}" ]
Set the engine to ImageMagick or GraphicsMagick @private @param {string} engine im for ImageMagick, gm for GraphicsMagick
[ "Set", "the", "engine", "to", "ImageMagick", "or", "GraphicsMagick" ]
c8def291ab152edb47153ca324722c86326ba573
https://github.com/andismith/grunt-responsive-images/blob/c8def291ab152edb47153ca324722c86326ba573/tasks/responsive_images.js#L89-L100
16,232
andismith/grunt-responsive-images
tasks/responsive_images.js
function(properties, options) { var widthUnit = '', heightUnit = ''; // name takes precedence if (properties.name) { return properties.name; } else { // figure out the units for width and height (they can be different) widthUnit = ((properties.width || 0).toString().indexOf('%') > 0) ? options.units.percentage : options.units.pixel; heightUnit = ((properties.height || 0 ).toString().indexOf('%') > 0) ? options.units.percentage : options.units.pixel; if (properties.width && properties.height) { return parseFloat(properties.width) + widthUnit + options.units.multiply + parseFloat(properties.height) + heightUnit; } else { return (properties.width) ? parseFloat(properties.width) + widthUnit : parseFloat(properties.height) + heightUnit; } } }
javascript
function(properties, options) { var widthUnit = '', heightUnit = ''; // name takes precedence if (properties.name) { return properties.name; } else { // figure out the units for width and height (they can be different) widthUnit = ((properties.width || 0).toString().indexOf('%') > 0) ? options.units.percentage : options.units.pixel; heightUnit = ((properties.height || 0 ).toString().indexOf('%') > 0) ? options.units.percentage : options.units.pixel; if (properties.width && properties.height) { return parseFloat(properties.width) + widthUnit + options.units.multiply + parseFloat(properties.height) + heightUnit; } else { return (properties.width) ? parseFloat(properties.width) + widthUnit : parseFloat(properties.height) + heightUnit; } } }
[ "function", "(", "properties", ",", "options", ")", "{", "var", "widthUnit", "=", "''", ",", "heightUnit", "=", "''", ";", "// name takes precedence", "if", "(", "properties", ".", "name", ")", "{", "return", "properties", ".", "name", ";", "}", "else", "{", "// figure out the units for width and height (they can be different)", "widthUnit", "=", "(", "(", "properties", ".", "width", "||", "0", ")", ".", "toString", "(", ")", ".", "indexOf", "(", "'%'", ")", ">", "0", ")", "?", "options", ".", "units", ".", "percentage", ":", "options", ".", "units", ".", "pixel", ";", "heightUnit", "=", "(", "(", "properties", ".", "height", "||", "0", ")", ".", "toString", "(", ")", ".", "indexOf", "(", "'%'", ")", ">", "0", ")", "?", "options", ".", "units", ".", "percentage", ":", "options", ".", "units", ".", "pixel", ";", "if", "(", "properties", ".", "width", "&&", "properties", ".", "height", ")", "{", "return", "parseFloat", "(", "properties", ".", "width", ")", "+", "widthUnit", "+", "options", ".", "units", ".", "multiply", "+", "parseFloat", "(", "properties", ".", "height", ")", "+", "heightUnit", ";", "}", "else", "{", "return", "(", "properties", ".", "width", ")", "?", "parseFloat", "(", "properties", ".", "width", ")", "+", "widthUnit", ":", "parseFloat", "(", "properties", ".", "height", ")", "+", "heightUnit", ";", "}", "}", "}" ]
Create a name to suffix to our file. @private @param {object} properties Contains properties for name, width, height (where applicable) @return {string} A new name
[ "Create", "a", "name", "to", "suffix", "to", "our", "file", "." ]
c8def291ab152edb47153ca324722c86326ba573
https://github.com/andismith/grunt-responsive-images/blob/c8def291ab152edb47153ca324722c86326ba573/tasks/responsive_images.js#L168-L186
16,233
andismith/grunt-responsive-images
tasks/responsive_images.js
function(obj, keys, remove) { var i = 0, l = keys.length; for (i = 0; i < l; i++) { if (obj[keys[i]] && obj[keys[i]].toString().indexOf(remove) > -1) { obj[keys[i]] = obj[keys[i]].toString().replace(remove, ''); } } return obj; }
javascript
function(obj, keys, remove) { var i = 0, l = keys.length; for (i = 0; i < l; i++) { if (obj[keys[i]] && obj[keys[i]].toString().indexOf(remove) > -1) { obj[keys[i]] = obj[keys[i]].toString().replace(remove, ''); } } return obj; }
[ "function", "(", "obj", ",", "keys", ",", "remove", ")", "{", "var", "i", "=", "0", ",", "l", "=", "keys", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "obj", "[", "keys", "[", "i", "]", "]", "&&", "obj", "[", "keys", "[", "i", "]", "]", ".", "toString", "(", ")", ".", "indexOf", "(", "remove", ")", ">", "-", "1", ")", "{", "obj", "[", "keys", "[", "i", "]", "]", "=", "obj", "[", "keys", "[", "i", "]", "]", ".", "toString", "(", ")", ".", "replace", "(", "remove", ",", "''", ")", ";", "}", "}", "return", "obj", ";", "}" ]
Removes characters from the values of the object keys specified @private @param {object} obj The object to inspect. @param {array} keys The keys to check the values of. @param {string} remove The string to remove.
[ "Removes", "characters", "from", "the", "values", "of", "the", "object", "keys", "specified" ]
c8def291ab152edb47153ca324722c86326ba573
https://github.com/andismith/grunt-responsive-images/blob/c8def291ab152edb47153ca324722c86326ba573/tasks/responsive_images.js#L257-L266
16,234
andismith/grunt-responsive-images
tasks/responsive_images.js
function(error, engine) { if (error.message.indexOf('ENOENT') > -1) { grunt.log.error(error.message); grunt.fail.warn('\nPlease ensure ' + GFX_ENGINES[engine].name + ' is installed correctly.\n' + '`brew install ' + GFX_ENGINES[engine].brewurl + '` or see ' + GFX_ENGINES[engine].url + ' for more details.\n' + 'Alternatively, set options.engine to \'' + GFX_ENGINES[engine].alternative.code + '\' to use ' + GFX_ENGINES[engine].alternative.name + '.\n'); } else { grunt.fail.warn(error.message); } }
javascript
function(error, engine) { if (error.message.indexOf('ENOENT') > -1) { grunt.log.error(error.message); grunt.fail.warn('\nPlease ensure ' + GFX_ENGINES[engine].name + ' is installed correctly.\n' + '`brew install ' + GFX_ENGINES[engine].brewurl + '` or see ' + GFX_ENGINES[engine].url + ' for more details.\n' + 'Alternatively, set options.engine to \'' + GFX_ENGINES[engine].alternative.code + '\' to use ' + GFX_ENGINES[engine].alternative.name + '.\n'); } else { grunt.fail.warn(error.message); } }
[ "function", "(", "error", ",", "engine", ")", "{", "if", "(", "error", ".", "message", ".", "indexOf", "(", "'ENOENT'", ")", ">", "-", "1", ")", "{", "grunt", ".", "log", ".", "error", "(", "error", ".", "message", ")", ";", "grunt", ".", "fail", ".", "warn", "(", "'\\nPlease ensure '", "+", "GFX_ENGINES", "[", "engine", "]", ".", "name", "+", "' is installed correctly.\\n'", "+", "'`brew install '", "+", "GFX_ENGINES", "[", "engine", "]", ".", "brewurl", "+", "'` or see '", "+", "GFX_ENGINES", "[", "engine", "]", ".", "url", "+", "' for more details.\\n'", "+", "'Alternatively, set options.engine to \\''", "+", "GFX_ENGINES", "[", "engine", "]", ".", "alternative", ".", "code", "+", "'\\' to use '", "+", "GFX_ENGINES", "[", "engine", "]", ".", "alternative", ".", "name", "+", "'.\\n'", ")", ";", "}", "else", "{", "grunt", ".", "fail", ".", "warn", "(", "error", ".", "message", ")", ";", "}", "}" ]
Handle showing errors to the user. @private @param {string} error The error message. @param {string} engine The graphics engine being used.
[ "Handle", "showing", "errors", "to", "the", "user", "." ]
c8def291ab152edb47153ca324722c86326ba573
https://github.com/andismith/grunt-responsive-images/blob/c8def291ab152edb47153ca324722c86326ba573/tasks/responsive_images.js#L275-L286
16,235
andismith/grunt-responsive-images
tasks/responsive_images.js
function(count, name) { if (count) { grunt.log.writeln('Resized ' + count.toString().cyan + ' ' + grunt.util.pluralize(count, 'file/files') + ' for ' + name); } }
javascript
function(count, name) { if (count) { grunt.log.writeln('Resized ' + count.toString().cyan + ' ' + grunt.util.pluralize(count, 'file/files') + ' for ' + name); } }
[ "function", "(", "count", ",", "name", ")", "{", "if", "(", "count", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "'Resized '", "+", "count", ".", "toString", "(", ")", ".", "cyan", "+", "' '", "+", "grunt", ".", "util", ".", "pluralize", "(", "count", ",", "'file/files'", ")", "+", "' for '", "+", "name", ")", ";", "}", "}" ]
Outputs the result of the tally. @private @param {number} count The file count. @param {string} name Name of the image.
[ "Outputs", "the", "result", "of", "the", "tally", "." ]
c8def291ab152edb47153ca324722c86326ba573
https://github.com/andismith/grunt-responsive-images/blob/c8def291ab152edb47153ca324722c86326ba573/tasks/responsive_images.js#L304-L309
16,236
andismith/grunt-responsive-images
tasks/responsive_images.js
function(srcPath, dstPath, sizeOptions, customDest, origCwd) { var baseName = '', dirName = '', extName = ''; extName = path.extname(dstPath); baseName = path.basename(dstPath, extName); // filename without extension if (customDest) { sizeOptions.path = srcPath.replace(new RegExp(origCwd), "").replace(new RegExp(path.basename(srcPath)+"$"), ""); grunt.template.addDelimiters('size', '{%', '%}'); dirName = grunt.template.process(customDest, { delimiters: 'size', data: sizeOptions }); checkDirectoryExists(path.join(dirName)); return path.join(dirName, baseName + extName); } else { dirName = path.dirname(dstPath); checkDirectoryExists(path.join(dirName)); return path.join(dirName, baseName + sizeOptions.outputName + extName); } }
javascript
function(srcPath, dstPath, sizeOptions, customDest, origCwd) { var baseName = '', dirName = '', extName = ''; extName = path.extname(dstPath); baseName = path.basename(dstPath, extName); // filename without extension if (customDest) { sizeOptions.path = srcPath.replace(new RegExp(origCwd), "").replace(new RegExp(path.basename(srcPath)+"$"), ""); grunt.template.addDelimiters('size', '{%', '%}'); dirName = grunt.template.process(customDest, { delimiters: 'size', data: sizeOptions }); checkDirectoryExists(path.join(dirName)); return path.join(dirName, baseName + extName); } else { dirName = path.dirname(dstPath); checkDirectoryExists(path.join(dirName)); return path.join(dirName, baseName + sizeOptions.outputName + extName); } }
[ "function", "(", "srcPath", ",", "dstPath", ",", "sizeOptions", ",", "customDest", ",", "origCwd", ")", "{", "var", "baseName", "=", "''", ",", "dirName", "=", "''", ",", "extName", "=", "''", ";", "extName", "=", "path", ".", "extname", "(", "dstPath", ")", ";", "baseName", "=", "path", ".", "basename", "(", "dstPath", ",", "extName", ")", ";", "// filename without extension", "if", "(", "customDest", ")", "{", "sizeOptions", ".", "path", "=", "srcPath", ".", "replace", "(", "new", "RegExp", "(", "origCwd", ")", ",", "\"\"", ")", ".", "replace", "(", "new", "RegExp", "(", "path", ".", "basename", "(", "srcPath", ")", "+", "\"$\"", ")", ",", "\"\"", ")", ";", "grunt", ".", "template", ".", "addDelimiters", "(", "'size'", ",", "'{%'", ",", "'%}'", ")", ";", "dirName", "=", "grunt", ".", "template", ".", "process", "(", "customDest", ",", "{", "delimiters", ":", "'size'", ",", "data", ":", "sizeOptions", "}", ")", ";", "checkDirectoryExists", "(", "path", ".", "join", "(", "dirName", ")", ")", ";", "return", "path", ".", "join", "(", "dirName", ",", "baseName", "+", "extName", ")", ";", "}", "else", "{", "dirName", "=", "path", ".", "dirname", "(", "dstPath", ")", ";", "checkDirectoryExists", "(", "path", ".", "join", "(", "dirName", ")", ")", ";", "return", "path", ".", "join", "(", "dirName", ",", "baseName", "+", "sizeOptions", ".", "outputName", "+", "extName", ")", ";", "}", "}" ]
Gets the destination path @private @param {string} srcPath The source path @param {string} filename Image Filename @param {object} sizeOptions @param {string} customDest @param {string} origCwd @return The complete path and filename
[ "Gets", "the", "destination", "path" ]
c8def291ab152edb47153ca324722c86326ba573
https://github.com/andismith/grunt-responsive-images/blob/c8def291ab152edb47153ca324722c86326ba573/tasks/responsive_images.js#L461-L487
16,237
youzan/vant-doc
helper/touch-simulator.js
onMouse
function onMouse(touchType) { return function(ev) { // prevent mouse events if (ev.which !== 1) { return; } // The EventTarget on which the touch point started when it was first placed on the surface, // even if the touch point has since moved outside the interactive area of that element. // also, when the target doesnt exist anymore, we update it if (ev.type === 'mousedown' || !eventTarget || eventTarget && !eventTarget.dispatchEvent) { eventTarget = ev.target; } triggerTouch(touchType, ev); // reset if (ev.type === 'mouseup') { eventTarget = null; } }; }
javascript
function onMouse(touchType) { return function(ev) { // prevent mouse events if (ev.which !== 1) { return; } // The EventTarget on which the touch point started when it was first placed on the surface, // even if the touch point has since moved outside the interactive area of that element. // also, when the target doesnt exist anymore, we update it if (ev.type === 'mousedown' || !eventTarget || eventTarget && !eventTarget.dispatchEvent) { eventTarget = ev.target; } triggerTouch(touchType, ev); // reset if (ev.type === 'mouseup') { eventTarget = null; } }; }
[ "function", "onMouse", "(", "touchType", ")", "{", "return", "function", "(", "ev", ")", "{", "// prevent mouse events", "if", "(", "ev", ".", "which", "!==", "1", ")", "{", "return", ";", "}", "// The EventTarget on which the touch point started when it was first placed on the surface,", "// even if the touch point has since moved outside the interactive area of that element.", "// also, when the target doesnt exist anymore, we update it", "if", "(", "ev", ".", "type", "===", "'mousedown'", "||", "!", "eventTarget", "||", "eventTarget", "&&", "!", "eventTarget", ".", "dispatchEvent", ")", "{", "eventTarget", "=", "ev", ".", "target", ";", "}", "triggerTouch", "(", "touchType", ",", "ev", ")", ";", "// reset", "if", "(", "ev", ".", "type", "===", "'mouseup'", ")", "{", "eventTarget", "=", "null", ";", "}", "}", ";", "}" ]
only trigger touches when the left mousebutton has been pressed @param touchType @returns {Function}
[ "only", "trigger", "touches", "when", "the", "left", "mousebutton", "has", "been", "pressed" ]
f1770c3dfa221987c96cd1ec9785304e2cefae02
https://github.com/youzan/vant-doc/blob/f1770c3dfa221987c96cd1ec9785304e2cefae02/helper/touch-simulator.js#L100-L122
16,238
youzan/vant-doc
helper/touch-simulator.js
triggerTouch
function triggerTouch(eventName, mouseEv) { var touchEvent = document.createEvent('Event'); touchEvent.initEvent(eventName, true, true); touchEvent.altKey = mouseEv.altKey; touchEvent.ctrlKey = mouseEv.ctrlKey; touchEvent.metaKey = mouseEv.metaKey; touchEvent.shiftKey = mouseEv.shiftKey; touchEvent.touches = getActiveTouches(mouseEv); touchEvent.targetTouches = getActiveTouches(mouseEv); touchEvent.changedTouches = createTouchList(mouseEv); eventTarget.dispatchEvent(touchEvent); }
javascript
function triggerTouch(eventName, mouseEv) { var touchEvent = document.createEvent('Event'); touchEvent.initEvent(eventName, true, true); touchEvent.altKey = mouseEv.altKey; touchEvent.ctrlKey = mouseEv.ctrlKey; touchEvent.metaKey = mouseEv.metaKey; touchEvent.shiftKey = mouseEv.shiftKey; touchEvent.touches = getActiveTouches(mouseEv); touchEvent.targetTouches = getActiveTouches(mouseEv); touchEvent.changedTouches = createTouchList(mouseEv); eventTarget.dispatchEvent(touchEvent); }
[ "function", "triggerTouch", "(", "eventName", ",", "mouseEv", ")", "{", "var", "touchEvent", "=", "document", ".", "createEvent", "(", "'Event'", ")", ";", "touchEvent", ".", "initEvent", "(", "eventName", ",", "true", ",", "true", ")", ";", "touchEvent", ".", "altKey", "=", "mouseEv", ".", "altKey", ";", "touchEvent", ".", "ctrlKey", "=", "mouseEv", ".", "ctrlKey", ";", "touchEvent", ".", "metaKey", "=", "mouseEv", ".", "metaKey", ";", "touchEvent", ".", "shiftKey", "=", "mouseEv", ".", "shiftKey", ";", "touchEvent", ".", "touches", "=", "getActiveTouches", "(", "mouseEv", ")", ";", "touchEvent", ".", "targetTouches", "=", "getActiveTouches", "(", "mouseEv", ")", ";", "touchEvent", ".", "changedTouches", "=", "createTouchList", "(", "mouseEv", ")", ";", "eventTarget", ".", "dispatchEvent", "(", "touchEvent", ")", ";", "}" ]
trigger a touch event @param eventName @param mouseEv
[ "trigger", "a", "touch", "event" ]
f1770c3dfa221987c96cd1ec9785304e2cefae02
https://github.com/youzan/vant-doc/blob/f1770c3dfa221987c96cd1ec9785304e2cefae02/helper/touch-simulator.js#L129-L143
16,239
riot/route
dist/amd.route+tag.js
start
function start(autoExec) { debouncedEmit = debounce(emit, 1); win[ADD_EVENT_LISTENER](POPSTATE, debouncedEmit); win[ADD_EVENT_LISTENER](HASHCHANGE, debouncedEmit); doc[ADD_EVENT_LISTENER](clickEvent, click); if (autoExec) { emit(true); } }
javascript
function start(autoExec) { debouncedEmit = debounce(emit, 1); win[ADD_EVENT_LISTENER](POPSTATE, debouncedEmit); win[ADD_EVENT_LISTENER](HASHCHANGE, debouncedEmit); doc[ADD_EVENT_LISTENER](clickEvent, click); if (autoExec) { emit(true); } }
[ "function", "start", "(", "autoExec", ")", "{", "debouncedEmit", "=", "debounce", "(", "emit", ",", "1", ")", ";", "win", "[", "ADD_EVENT_LISTENER", "]", "(", "POPSTATE", ",", "debouncedEmit", ")", ";", "win", "[", "ADD_EVENT_LISTENER", "]", "(", "HASHCHANGE", ",", "debouncedEmit", ")", ";", "doc", "[", "ADD_EVENT_LISTENER", "]", "(", "clickEvent", ",", "click", ")", ";", "if", "(", "autoExec", ")", "{", "emit", "(", "true", ")", ";", "}", "}" ]
Set the window listeners to trigger the routes @param {boolean} autoExec - see route.start
[ "Set", "the", "window", "listeners", "to", "trigger", "the", "routes" ]
226d16c3ff2ef745b333de3de84a18c78c97737d
https://github.com/riot/route/blob/226d16c3ff2ef745b333de3de84a18c78c97737d/dist/amd.route+tag.js#L207-L214
16,240
nhn/tui.jsdoc-template
demo/src/class.js
function(a, b, retArr) { if (retArr) { return [a, b, a + b]; } return a + b; }
javascript
function(a, b, retArr) { if (retArr) { return [a, b, a + b]; } return a + b; }
[ "function", "(", "a", ",", "b", ",", "retArr", ")", "{", "if", "(", "retArr", ")", "{", "return", "[", "a", ",", "b", ",", "a", "+", "b", "]", ";", "}", "return", "a", "+", "b", ";", "}" ]
Returns the sum of a and b @param {Number} a @param {Number} b @param {Boolean} retArr If set to true, the function will return an array @returns {Number|Array} Sum of a and b or an array that contains a, b and the sum of a and b.
[ "Returns", "the", "sum", "of", "a", "and", "b" ]
13a8d08b4d1f01f41e46922549250eaed7e93733
https://github.com/nhn/tui.jsdoc-template/blob/13a8d08b4d1f01f41e46922549250eaed7e93733/demo/src/class.js#L128-L133
16,241
davehorton/drachtio-srf
lib/connect.js
createServer
function createServer() { function app(req, res, next) { app.handle(req, res, next); } app.method = '*'; merge(app, proto); merge(app, EventEmitter.prototype); app.stack = []; app.params = []; app._cachedEvents = [] ; app.routedMethods = {} ; app.locals = Object.create(null); for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } //create methods app.invite, app.register, etc.. methods.forEach((method) => { app[method.toLowerCase()] = app.use.bind(app, method.toLowerCase()) ; }) ; //special handling for cdr events app.on = function(event, listener) { if (0 === event.indexOf('cdr:')) { if (app.client) { app.client.on(event, function() { var args = Array.prototype.slice.call(arguments) ; EventEmitter.prototype.emit.apply(app, [event].concat(args)) ; }) ; } else { this._cachedEvents.push(event) ; } } //delegate all others to standard EventEmitter prototype return EventEmitter.prototype.addListener.call(app, event, listener) ; } ; return app; }
javascript
function createServer() { function app(req, res, next) { app.handle(req, res, next); } app.method = '*'; merge(app, proto); merge(app, EventEmitter.prototype); app.stack = []; app.params = []; app._cachedEvents = [] ; app.routedMethods = {} ; app.locals = Object.create(null); for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } //create methods app.invite, app.register, etc.. methods.forEach((method) => { app[method.toLowerCase()] = app.use.bind(app, method.toLowerCase()) ; }) ; //special handling for cdr events app.on = function(event, listener) { if (0 === event.indexOf('cdr:')) { if (app.client) { app.client.on(event, function() { var args = Array.prototype.slice.call(arguments) ; EventEmitter.prototype.emit.apply(app, [event].concat(args)) ; }) ; } else { this._cachedEvents.push(event) ; } } //delegate all others to standard EventEmitter prototype return EventEmitter.prototype.addListener.call(app, event, listener) ; } ; return app; }
[ "function", "createServer", "(", ")", "{", "function", "app", "(", "req", ",", "res", ",", "next", ")", "{", "app", ".", "handle", "(", "req", ",", "res", ",", "next", ")", ";", "}", "app", ".", "method", "=", "'*'", ";", "merge", "(", "app", ",", "proto", ")", ";", "merge", "(", "app", ",", "EventEmitter", ".", "prototype", ")", ";", "app", ".", "stack", "=", "[", "]", ";", "app", ".", "params", "=", "[", "]", ";", "app", ".", "_cachedEvents", "=", "[", "]", ";", "app", ".", "routedMethods", "=", "{", "}", ";", "app", ".", "locals", "=", "Object", ".", "create", "(", "null", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "++", "i", ")", "{", "app", ".", "use", "(", "arguments", "[", "i", "]", ")", ";", "}", "//create methods app.invite, app.register, etc..", "methods", ".", "forEach", "(", "(", "method", ")", "=>", "{", "app", "[", "method", ".", "toLowerCase", "(", ")", "]", "=", "app", ".", "use", ".", "bind", "(", "app", ",", "method", ".", "toLowerCase", "(", ")", ")", ";", "}", ")", ";", "//special handling for cdr events", "app", ".", "on", "=", "function", "(", "event", ",", "listener", ")", "{", "if", "(", "0", "===", "event", ".", "indexOf", "(", "'cdr:'", ")", ")", "{", "if", "(", "app", ".", "client", ")", "{", "app", ".", "client", ".", "on", "(", "event", ",", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "EventEmitter", ".", "prototype", ".", "emit", ".", "apply", "(", "app", ",", "[", "event", "]", ".", "concat", "(", "args", ")", ")", ";", "}", ")", ";", "}", "else", "{", "this", ".", "_cachedEvents", ".", "push", "(", "event", ")", ";", "}", "}", "//delegate all others to standard EventEmitter prototype", "return", "EventEmitter", ".", "prototype", ".", "addListener", ".", "call", "(", "app", ",", "event", ",", "listener", ")", ";", "}", ";", "return", "app", ";", "}" ]
Create a new server. @return {Function} @api public
[ "Create", "a", "new", "server", "." ]
a29e1a3a5c5f15e0b44fbdfbba9aa6e2ed31ca13
https://github.com/davehorton/drachtio-srf/blob/a29e1a3a5c5f15e0b44fbdfbba9aa6e2ed31ca13/lib/connect.js#L15-L54
16,242
node-ffi-napi/node-ffi-napi
lib/callback.js
Callback
function Callback (retType, argTypes, abi, func) { debug('creating new Callback'); if (typeof abi === 'function') { func = abi; abi = undefined; } // check args assert(!!retType, 'expected a return "type" object as the first argument'); assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the second argument'); assert.equal(typeof func, 'function', 'expected a function as the third argument'); // normalize the "types" (they could be strings, so turn into real type // instances) retType = ref.coerceType(retType); argTypes = argTypes.map(ref.coerceType); // create the `ffi_cif *` instance const cif = CIF(retType, argTypes, abi); const argc = argTypes.length; const callback = _Callback(cif, retType.size, argc, errorReportCallback, (retval, params) => { debug('Callback function being invoked') try { const args = []; for (var i = 0; i < argc; i++) { const type = argTypes[i]; const argPtr = params.readPointer(i * ref.sizeof.pointer, type.size); argPtr.type = type; args.push(argPtr.deref()); } // Invoke the user-given function const result = func.apply(null, args); try { ref.set(retval, 0, result, retType); } catch (e) { e.message = 'error setting return value - ' + e.message; throw e; } } catch (e) { return e; } }); return callback; }
javascript
function Callback (retType, argTypes, abi, func) { debug('creating new Callback'); if (typeof abi === 'function') { func = abi; abi = undefined; } // check args assert(!!retType, 'expected a return "type" object as the first argument'); assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the second argument'); assert.equal(typeof func, 'function', 'expected a function as the third argument'); // normalize the "types" (they could be strings, so turn into real type // instances) retType = ref.coerceType(retType); argTypes = argTypes.map(ref.coerceType); // create the `ffi_cif *` instance const cif = CIF(retType, argTypes, abi); const argc = argTypes.length; const callback = _Callback(cif, retType.size, argc, errorReportCallback, (retval, params) => { debug('Callback function being invoked') try { const args = []; for (var i = 0; i < argc; i++) { const type = argTypes[i]; const argPtr = params.readPointer(i * ref.sizeof.pointer, type.size); argPtr.type = type; args.push(argPtr.deref()); } // Invoke the user-given function const result = func.apply(null, args); try { ref.set(retval, 0, result, retType); } catch (e) { e.message = 'error setting return value - ' + e.message; throw e; } } catch (e) { return e; } }); return callback; }
[ "function", "Callback", "(", "retType", ",", "argTypes", ",", "abi", ",", "func", ")", "{", "debug", "(", "'creating new Callback'", ")", ";", "if", "(", "typeof", "abi", "===", "'function'", ")", "{", "func", "=", "abi", ";", "abi", "=", "undefined", ";", "}", "// check args", "assert", "(", "!", "!", "retType", ",", "'expected a return \"type\" object as the first argument'", ")", ";", "assert", "(", "Array", ".", "isArray", "(", "argTypes", ")", ",", "'expected Array of arg \"type\" objects as the second argument'", ")", ";", "assert", ".", "equal", "(", "typeof", "func", ",", "'function'", ",", "'expected a function as the third argument'", ")", ";", "// normalize the \"types\" (they could be strings, so turn into real type", "// instances)", "retType", "=", "ref", ".", "coerceType", "(", "retType", ")", ";", "argTypes", "=", "argTypes", ".", "map", "(", "ref", ".", "coerceType", ")", ";", "// create the `ffi_cif *` instance", "const", "cif", "=", "CIF", "(", "retType", ",", "argTypes", ",", "abi", ")", ";", "const", "argc", "=", "argTypes", ".", "length", ";", "const", "callback", "=", "_Callback", "(", "cif", ",", "retType", ".", "size", ",", "argc", ",", "errorReportCallback", ",", "(", "retval", ",", "params", ")", "=>", "{", "debug", "(", "'Callback function being invoked'", ")", "try", "{", "const", "args", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "argc", ";", "i", "++", ")", "{", "const", "type", "=", "argTypes", "[", "i", "]", ";", "const", "argPtr", "=", "params", ".", "readPointer", "(", "i", "*", "ref", ".", "sizeof", ".", "pointer", ",", "type", ".", "size", ")", ";", "argPtr", ".", "type", "=", "type", ";", "args", ".", "push", "(", "argPtr", ".", "deref", "(", ")", ")", ";", "}", "// Invoke the user-given function", "const", "result", "=", "func", ".", "apply", "(", "null", ",", "args", ")", ";", "try", "{", "ref", ".", "set", "(", "retval", ",", "0", ",", "result", ",", "retType", ")", ";", "}", "catch", "(", "e", ")", "{", "e", ".", "message", "=", "'error setting return value - '", "+", "e", ".", "message", ";", "throw", "e", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "e", ";", "}", "}", ")", ";", "return", "callback", ";", "}" ]
Turns a JavaScript function into a C function pointer. The function pointer may be used in other C functions that accept C callback functions.
[ "Turns", "a", "JavaScript", "function", "into", "a", "C", "function", "pointer", ".", "The", "function", "pointer", "may", "be", "used", "in", "other", "C", "functions", "that", "accept", "C", "callback", "functions", "." ]
998255a8009cbfca0fc2f2cb7e4fc0a7be30c422
https://github.com/node-ffi-napi/node-ffi-napi/blob/998255a8009cbfca0fc2f2cb7e4fc0a7be30c422/lib/callback.js#L32-L79
16,243
node-ffi-napi/node-ffi-napi
lib/foreign_function_var.js
variadic_function_generator
function variadic_function_generator () { debug('variadic_function_generator invoked'); // first get the types of variadic args we are working with const argTypes = fixedArgTypes.slice(); let key = fixedKey.slice(); for (let i = 0; i < arguments.length; i++) { const type = ref.coerceType(arguments[i]); argTypes.push(type); const ffi_type = Type(type); assert(ffi_type.name); key.push(getId(type)); } // now figure out the return type const rtnType = ref.coerceType(variadic_function_generator.returnType); const rtnName = getId(rtnType); assert(rtnName); // first let's generate the key and see if we got a cache-hit key = rtnName + key.join(''); let func = cache[key]; if (func) { debug('cache hit for key:', key); } else { // create the `ffi_cif *` instance debug('creating the variadic ffi_cif instance for key:', key); const cif = CIF_var(returnType, argTypes, numFixedArgs, abi); func = cache[key] = _ForeignFunction(cif, funcPtr, rtnType, argTypes); } return func; }
javascript
function variadic_function_generator () { debug('variadic_function_generator invoked'); // first get the types of variadic args we are working with const argTypes = fixedArgTypes.slice(); let key = fixedKey.slice(); for (let i = 0; i < arguments.length; i++) { const type = ref.coerceType(arguments[i]); argTypes.push(type); const ffi_type = Type(type); assert(ffi_type.name); key.push(getId(type)); } // now figure out the return type const rtnType = ref.coerceType(variadic_function_generator.returnType); const rtnName = getId(rtnType); assert(rtnName); // first let's generate the key and see if we got a cache-hit key = rtnName + key.join(''); let func = cache[key]; if (func) { debug('cache hit for key:', key); } else { // create the `ffi_cif *` instance debug('creating the variadic ffi_cif instance for key:', key); const cif = CIF_var(returnType, argTypes, numFixedArgs, abi); func = cache[key] = _ForeignFunction(cif, funcPtr, rtnType, argTypes); } return func; }
[ "function", "variadic_function_generator", "(", ")", "{", "debug", "(", "'variadic_function_generator invoked'", ")", ";", "// first get the types of variadic args we are working with", "const", "argTypes", "=", "fixedArgTypes", ".", "slice", "(", ")", ";", "let", "key", "=", "fixedKey", ".", "slice", "(", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "const", "type", "=", "ref", ".", "coerceType", "(", "arguments", "[", "i", "]", ")", ";", "argTypes", ".", "push", "(", "type", ")", ";", "const", "ffi_type", "=", "Type", "(", "type", ")", ";", "assert", "(", "ffi_type", ".", "name", ")", ";", "key", ".", "push", "(", "getId", "(", "type", ")", ")", ";", "}", "// now figure out the return type", "const", "rtnType", "=", "ref", ".", "coerceType", "(", "variadic_function_generator", ".", "returnType", ")", ";", "const", "rtnName", "=", "getId", "(", "rtnType", ")", ";", "assert", "(", "rtnName", ")", ";", "// first let's generate the key and see if we got a cache-hit", "key", "=", "rtnName", "+", "key", ".", "join", "(", "''", ")", ";", "let", "func", "=", "cache", "[", "key", "]", ";", "if", "(", "func", ")", "{", "debug", "(", "'cache hit for key:'", ",", "key", ")", ";", "}", "else", "{", "// create the `ffi_cif *` instance", "debug", "(", "'creating the variadic ffi_cif instance for key:'", ",", "key", ")", ";", "const", "cif", "=", "CIF_var", "(", "returnType", ",", "argTypes", ",", "numFixedArgs", ",", "abi", ")", ";", "func", "=", "cache", "[", "key", "]", "=", "_ForeignFunction", "(", "cif", ",", "funcPtr", ",", "rtnType", ",", "argTypes", ")", ";", "}", "return", "func", ";", "}" ]
what gets returned is another function that needs to be invoked with the rest of the variadic types that are being invoked from the function.
[ "what", "gets", "returned", "is", "another", "function", "that", "needs", "to", "be", "invoked", "with", "the", "rest", "of", "the", "variadic", "types", "that", "are", "being", "invoked", "from", "the", "function", "." ]
998255a8009cbfca0fc2f2cb7e4fc0a7be30c422
https://github.com/node-ffi-napi/node-ffi-napi/blob/998255a8009cbfca0fc2f2cb7e4fc0a7be30c422/lib/foreign_function_var.js#L50-L84
16,244
node-ffi-napi/node-ffi-napi
lib/foreign_function.js
ForeignFunction
function ForeignFunction (funcPtr, returnType, argTypes, abi) { debug('creating new ForeignFunction', funcPtr); // check args assert(Buffer.isBuffer(funcPtr), 'expected Buffer as first argument'); assert(!!returnType, 'expected a return "type" object as the second argument'); assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the third argument'); // normalize the "types" (they could be strings, // so turn into real type instances) returnType = ref.coerceType(returnType); argTypes = argTypes.map(ref.coerceType); // create the `ffi_cif *` instance const cif = CIF(returnType, argTypes, abi); // create and return the JS proxy function return _ForeignFunction(cif, funcPtr, returnType, argTypes); }
javascript
function ForeignFunction (funcPtr, returnType, argTypes, abi) { debug('creating new ForeignFunction', funcPtr); // check args assert(Buffer.isBuffer(funcPtr), 'expected Buffer as first argument'); assert(!!returnType, 'expected a return "type" object as the second argument'); assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the third argument'); // normalize the "types" (they could be strings, // so turn into real type instances) returnType = ref.coerceType(returnType); argTypes = argTypes.map(ref.coerceType); // create the `ffi_cif *` instance const cif = CIF(returnType, argTypes, abi); // create and return the JS proxy function return _ForeignFunction(cif, funcPtr, returnType, argTypes); }
[ "function", "ForeignFunction", "(", "funcPtr", ",", "returnType", ",", "argTypes", ",", "abi", ")", "{", "debug", "(", "'creating new ForeignFunction'", ",", "funcPtr", ")", ";", "// check args", "assert", "(", "Buffer", ".", "isBuffer", "(", "funcPtr", ")", ",", "'expected Buffer as first argument'", ")", ";", "assert", "(", "!", "!", "returnType", ",", "'expected a return \"type\" object as the second argument'", ")", ";", "assert", "(", "Array", ".", "isArray", "(", "argTypes", ")", ",", "'expected Array of arg \"type\" objects as the third argument'", ")", ";", "// normalize the \"types\" (they could be strings,", "// so turn into real type instances)", "returnType", "=", "ref", ".", "coerceType", "(", "returnType", ")", ";", "argTypes", "=", "argTypes", ".", "map", "(", "ref", ".", "coerceType", ")", ";", "// create the `ffi_cif *` instance", "const", "cif", "=", "CIF", "(", "returnType", ",", "argTypes", ",", "abi", ")", ";", "// create and return the JS proxy function", "return", "_ForeignFunction", "(", "cif", ",", "funcPtr", ",", "returnType", ",", "argTypes", ")", ";", "}" ]
Represents a foreign function in another library. Manages all of the aspects of function execution, including marshalling the data parameters for the function into native types and also unmarshalling the return from function execution.
[ "Represents", "a", "foreign", "function", "in", "another", "library", ".", "Manages", "all", "of", "the", "aspects", "of", "function", "execution", "including", "marshalling", "the", "data", "parameters", "for", "the", "function", "into", "native", "types", "and", "also", "unmarshalling", "the", "return", "from", "function", "execution", "." ]
998255a8009cbfca0fc2f2cb7e4fc0a7be30c422
https://github.com/node-ffi-napi/node-ffi-napi/blob/998255a8009cbfca0fc2f2cb7e4fc0a7be30c422/lib/foreign_function.js#L19-L37
16,245
node-ffi-napi/node-ffi-napi
lib/_foreign_function.js
function () { debug('invoking proxy function'); if (arguments.length !== numArgs) { throw new TypeError('Expected ' + numArgs + ' arguments, got ' + arguments.length); } // storage buffers for input arguments and the return value const result = Buffer.alloc(resultSize); const argsList = Buffer.alloc(argsArraySize); // write arguments to storage areas let i; try { for (i = 0; i < numArgs; i++) { const argType = argTypes[i]; const val = arguments[i]; const valPtr = ref.alloc(argType, val); argsList.writePointer(valPtr, i * POINTER_SIZE); } } catch (e) { // counting arguments from 1 is more human readable i++; e.message = 'error setting argument ' + i + ' - ' + e.message; throw e; } // invoke the `ffi_call()` function bindings.ffi_call(cif, funcPtr, result, argsList); result.type = returnType; return result.deref(); }
javascript
function () { debug('invoking proxy function'); if (arguments.length !== numArgs) { throw new TypeError('Expected ' + numArgs + ' arguments, got ' + arguments.length); } // storage buffers for input arguments and the return value const result = Buffer.alloc(resultSize); const argsList = Buffer.alloc(argsArraySize); // write arguments to storage areas let i; try { for (i = 0; i < numArgs; i++) { const argType = argTypes[i]; const val = arguments[i]; const valPtr = ref.alloc(argType, val); argsList.writePointer(valPtr, i * POINTER_SIZE); } } catch (e) { // counting arguments from 1 is more human readable i++; e.message = 'error setting argument ' + i + ' - ' + e.message; throw e; } // invoke the `ffi_call()` function bindings.ffi_call(cif, funcPtr, result, argsList); result.type = returnType; return result.deref(); }
[ "function", "(", ")", "{", "debug", "(", "'invoking proxy function'", ")", ";", "if", "(", "arguments", ".", "length", "!==", "numArgs", ")", "{", "throw", "new", "TypeError", "(", "'Expected '", "+", "numArgs", "+", "' arguments, got '", "+", "arguments", ".", "length", ")", ";", "}", "// storage buffers for input arguments and the return value", "const", "result", "=", "Buffer", ".", "alloc", "(", "resultSize", ")", ";", "const", "argsList", "=", "Buffer", ".", "alloc", "(", "argsArraySize", ")", ";", "// write arguments to storage areas", "let", "i", ";", "try", "{", "for", "(", "i", "=", "0", ";", "i", "<", "numArgs", ";", "i", "++", ")", "{", "const", "argType", "=", "argTypes", "[", "i", "]", ";", "const", "val", "=", "arguments", "[", "i", "]", ";", "const", "valPtr", "=", "ref", ".", "alloc", "(", "argType", ",", "val", ")", ";", "argsList", ".", "writePointer", "(", "valPtr", ",", "i", "*", "POINTER_SIZE", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "// counting arguments from 1 is more human readable", "i", "++", ";", "e", ".", "message", "=", "'error setting argument '", "+", "i", "+", "' - '", "+", "e", ".", "message", ";", "throw", "e", ";", "}", "// invoke the `ffi_call()` function", "bindings", ".", "ffi_call", "(", "cif", ",", "funcPtr", ",", "result", ",", "argsList", ")", ";", "result", ".", "type", "=", "returnType", ";", "return", "result", ".", "deref", "(", ")", ";", "}" ]
This is the actual JS function that gets returned. It handles marshalling input arguments into C values, and unmarshalling the return value back into a JS value
[ "This", "is", "the", "actual", "JS", "function", "that", "gets", "returned", ".", "It", "handles", "marshalling", "input", "arguments", "into", "C", "values", "and", "unmarshalling", "the", "return", "value", "back", "into", "a", "JS", "value" ]
998255a8009cbfca0fc2f2cb7e4fc0a7be30c422
https://github.com/node-ffi-napi/node-ffi-napi/blob/998255a8009cbfca0fc2f2cb7e4fc0a7be30c422/lib/_foreign_function.js#L32-L65
16,246
node-ffi-napi/node-ffi-napi
lib/function.js
Function
function Function (retType, argTypes, abi) { if (!(this instanceof Function)) { return new Function(retType, argTypes, abi); } debug('creating new FunctionType'); // check args assert(!!retType, 'expected a return "type" object as the first argument'); assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the second argument'); // normalize the "types" (they could be strings, so turn into real type // instances) this.retType = ref.coerceType(retType); this.argTypes = argTypes.map(ref.coerceType); this.abi = null == abi ? bindings.FFI_DEFAULT_ABI : abi; }
javascript
function Function (retType, argTypes, abi) { if (!(this instanceof Function)) { return new Function(retType, argTypes, abi); } debug('creating new FunctionType'); // check args assert(!!retType, 'expected a return "type" object as the first argument'); assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the second argument'); // normalize the "types" (they could be strings, so turn into real type // instances) this.retType = ref.coerceType(retType); this.argTypes = argTypes.map(ref.coerceType); this.abi = null == abi ? bindings.FFI_DEFAULT_ABI : abi; }
[ "function", "Function", "(", "retType", ",", "argTypes", ",", "abi", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Function", ")", ")", "{", "return", "new", "Function", "(", "retType", ",", "argTypes", ",", "abi", ")", ";", "}", "debug", "(", "'creating new FunctionType'", ")", ";", "// check args", "assert", "(", "!", "!", "retType", ",", "'expected a return \"type\" object as the first argument'", ")", ";", "assert", "(", "Array", ".", "isArray", "(", "argTypes", ")", ",", "'expected Array of arg \"type\" objects as the second argument'", ")", ";", "// normalize the \"types\" (they could be strings, so turn into real type", "// instances)", "this", ".", "retType", "=", "ref", ".", "coerceType", "(", "retType", ")", ";", "this", ".", "argTypes", "=", "argTypes", ".", "map", "(", "ref", ".", "coerceType", ")", ";", "this", ".", "abi", "=", "null", "==", "abi", "?", "bindings", ".", "FFI_DEFAULT_ABI", ":", "abi", ";", "}" ]
Creates and returns a "type" object for a C "function pointer". @api public
[ "Creates", "and", "returns", "a", "type", "object", "for", "a", "C", "function", "pointer", "." ]
998255a8009cbfca0fc2f2cb7e4fc0a7be30c422
https://github.com/node-ffi-napi/node-ffi-napi/blob/998255a8009cbfca0fc2f2cb7e4fc0a7be30c422/lib/function.js#L25-L41
16,247
overlookmotel/sequelize-hierarchy
lib/utils.js
replaceTableNames
function replaceTableNames(sql, identifiers, sequelize) { const {queryInterface} = sequelize; _.forIn(identifiers, (model, identifier) => { const tableName = model.getTableName(); sql = sql.replace( new RegExp(`\\*${identifier}(?![a-zA-Z0-9_])`, 'g'), tableName.schema ? tableName.toString() : queryInterface.quoteIdentifier(tableName) ); }); return sql; }
javascript
function replaceTableNames(sql, identifiers, sequelize) { const {queryInterface} = sequelize; _.forIn(identifiers, (model, identifier) => { const tableName = model.getTableName(); sql = sql.replace( new RegExp(`\\*${identifier}(?![a-zA-Z0-9_])`, 'g'), tableName.schema ? tableName.toString() : queryInterface.quoteIdentifier(tableName) ); }); return sql; }
[ "function", "replaceTableNames", "(", "sql", ",", "identifiers", ",", "sequelize", ")", "{", "const", "{", "queryInterface", "}", "=", "sequelize", ";", "_", ".", "forIn", "(", "identifiers", ",", "(", "model", ",", "identifier", ")", "=>", "{", "const", "tableName", "=", "model", ".", "getTableName", "(", ")", ";", "sql", "=", "sql", ".", "replace", "(", "new", "RegExp", "(", "`", "\\\\", "${", "identifier", "}", "`", ",", "'g'", ")", ",", "tableName", ".", "schema", "?", "tableName", ".", "toString", "(", ")", ":", "queryInterface", ".", "quoteIdentifier", "(", "tableName", ")", ")", ";", "}", ")", ";", "return", "sql", ";", "}" ]
Replace identifier with model's full table name taking schema into account
[ "Replace", "identifier", "with", "model", "s", "full", "table", "name", "taking", "schema", "into", "account" ]
f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4
https://github.com/overlookmotel/sequelize-hierarchy/blob/f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4/lib/utils.js#L50-L60
16,248
overlookmotel/sequelize-hierarchy
lib/utils.js
addOptions
function addOptions(queryOptions, options) { const {transaction, logging} = options; if (transaction !== undefined) queryOptions.transaction = transaction; if (logging !== undefined) queryOptions.logging = logging; return queryOptions; }
javascript
function addOptions(queryOptions, options) { const {transaction, logging} = options; if (transaction !== undefined) queryOptions.transaction = transaction; if (logging !== undefined) queryOptions.logging = logging; return queryOptions; }
[ "function", "addOptions", "(", "queryOptions", ",", "options", ")", "{", "const", "{", "transaction", ",", "logging", "}", "=", "options", ";", "if", "(", "transaction", "!==", "undefined", ")", "queryOptions", ".", "transaction", "=", "transaction", ";", "if", "(", "logging", "!==", "undefined", ")", "queryOptions", ".", "logging", "=", "logging", ";", "return", "queryOptions", ";", "}" ]
Add transaction and logging from options to query options
[ "Add", "transaction", "and", "logging", "from", "options", "to", "query", "options" ]
f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4
https://github.com/overlookmotel/sequelize-hierarchy/blob/f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4/lib/utils.js#L74-L79
16,249
overlookmotel/sequelize-hierarchy
lib/utils.js
inFields
function inFields(fieldName, options) { const {fields} = options; if (!fields) return true; return fields.includes(fieldName); }
javascript
function inFields(fieldName, options) { const {fields} = options; if (!fields) return true; return fields.includes(fieldName); }
[ "function", "inFields", "(", "fieldName", ",", "options", ")", "{", "const", "{", "fields", "}", "=", "options", ";", "if", "(", "!", "fields", ")", "return", "true", ";", "return", "fields", ".", "includes", "(", "fieldName", ")", ";", "}" ]
Check if field is in `fields` option
[ "Check", "if", "field", "is", "in", "fields", "option" ]
f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4
https://github.com/overlookmotel/sequelize-hierarchy/blob/f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4/lib/utils.js#L82-L86
16,250
overlookmotel/sequelize-hierarchy
lib/utils.js
valueFilteredByFields
function valueFilteredByFields(fieldName, item, options) { if (!inFields(fieldName, options)) return null; return item.dataValues[fieldName]; }
javascript
function valueFilteredByFields(fieldName, item, options) { if (!inFields(fieldName, options)) return null; return item.dataValues[fieldName]; }
[ "function", "valueFilteredByFields", "(", "fieldName", ",", "item", ",", "options", ")", "{", "if", "(", "!", "inFields", "(", "fieldName", ",", "options", ")", ")", "return", "null", ";", "return", "item", ".", "dataValues", "[", "fieldName", "]", ";", "}" ]
Get field value if is included in `options.fields`
[ "Get", "field", "value", "if", "is", "included", "in", "options", ".", "fields" ]
f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4
https://github.com/overlookmotel/sequelize-hierarchy/blob/f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4/lib/utils.js#L89-L92
16,251
overlookmotel/sequelize-hierarchy
lib/utils.js
addToFields
function addToFields(fieldName, options) { if (inFields(fieldName, options)) return; options.fields = options.fields.concat([fieldName]); }
javascript
function addToFields(fieldName, options) { if (inFields(fieldName, options)) return; options.fields = options.fields.concat([fieldName]); }
[ "function", "addToFields", "(", "fieldName", ",", "options", ")", "{", "if", "(", "inFields", "(", "fieldName", ",", "options", ")", ")", "return", ";", "options", ".", "fields", "=", "options", ".", "fields", ".", "concat", "(", "[", "fieldName", "]", ")", ";", "}" ]
Add a field to `options.fields`. NB Clones `options.fields` before adding to it, to avoid options being mutated externally.
[ "Add", "a", "field", "to", "options", ".", "fields", ".", "NB", "Clones", "options", ".", "fields", "before", "adding", "to", "it", "to", "avoid", "options", "being", "mutated", "externally", "." ]
f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4
https://github.com/overlookmotel/sequelize-hierarchy/blob/f1ec87beff0de4ae9df3db7d7bd67a2355e5a9b4/lib/utils.js#L96-L99
16,252
GameJs/gamejs
src/gamejs/thread.js
guid
function guid(moduleId) { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return moduleId + '@' + (S4()+S4()); }
javascript
function guid(moduleId) { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return moduleId + '@' + (S4()+S4()); }
[ "function", "guid", "(", "moduleId", ")", "{", "var", "S4", "=", "function", "(", ")", "{", "return", "(", "(", "(", "1", "+", "Math", ".", "random", "(", ")", ")", "*", "0x10000", ")", "|", "0", ")", ".", "toString", "(", "16", ")", ".", "substring", "(", "1", ")", ";", "}", ";", "return", "moduleId", "+", "'@'", "+", "(", "S4", "(", ")", "+", "S4", "(", ")", ")", ";", "}" ]
not a real GUID @ignore
[ "not", "a", "real", "GUID" ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/src/gamejs/thread.js#L245-L250
16,253
GameJs/gamejs
src/gamejs/event.js
w3cTouchConvert
function w3cTouchConvert(touchList) { var canvasOffset = display._getCanvasOffset(); var tList = []; for (var i = 0; i < touchList.length; i++) { var touchEvent = touchList.item(i); tList.push({ identifier: touchEvent.identifier, pos: [touchEvent.clientX - canvasOffset[0], touchEvent.clientY - canvasOffset[1]] }); } return tList; }
javascript
function w3cTouchConvert(touchList) { var canvasOffset = display._getCanvasOffset(); var tList = []; for (var i = 0; i < touchList.length; i++) { var touchEvent = touchList.item(i); tList.push({ identifier: touchEvent.identifier, pos: [touchEvent.clientX - canvasOffset[0], touchEvent.clientY - canvasOffset[1]] }); } return tList; }
[ "function", "w3cTouchConvert", "(", "touchList", ")", "{", "var", "canvasOffset", "=", "display", ".", "_getCanvasOffset", "(", ")", ";", "var", "tList", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "touchList", ".", "length", ";", "i", "++", ")", "{", "var", "touchEvent", "=", "touchList", ".", "item", "(", "i", ")", ";", "tList", ".", "push", "(", "{", "identifier", ":", "touchEvent", ".", "identifier", ",", "pos", ":", "[", "touchEvent", ".", "clientX", "-", "canvasOffset", "[", "0", "]", ",", "touchEvent", ".", "clientY", "-", "canvasOffset", "[", "1", "]", "]", "}", ")", ";", "}", "return", "tList", ";", "}" ]
convert a w3c touch event into gamejs event
[ "convert", "a", "w3c", "touch", "event", "into", "gamejs", "event" ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/src/gamejs/event.js#L489-L500
16,254
GameJs/gamejs
examples/threaded-noise/noise-worker.js
function(dimensions) { var simplex = new gamejs.math.noise.Simplex(Math); var surfaceData = []; for (var i=0;i<dimensions[0];i++) { surfaceData[i] = []; for (var j=0;j<dimensions[1];j++) { var val = simplex.get(i/50, j/50) * 255; surfaceData[i][j] = val; } } return surfaceData; }
javascript
function(dimensions) { var simplex = new gamejs.math.noise.Simplex(Math); var surfaceData = []; for (var i=0;i<dimensions[0];i++) { surfaceData[i] = []; for (var j=0;j<dimensions[1];j++) { var val = simplex.get(i/50, j/50) * 255; surfaceData[i][j] = val; } } return surfaceData; }
[ "function", "(", "dimensions", ")", "{", "var", "simplex", "=", "new", "gamejs", ".", "math", ".", "noise", ".", "Simplex", "(", "Math", ")", ";", "var", "surfaceData", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "dimensions", "[", "0", "]", ";", "i", "++", ")", "{", "surfaceData", "[", "i", "]", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "dimensions", "[", "1", "]", ";", "j", "++", ")", "{", "var", "val", "=", "simplex", ".", "get", "(", "i", "/", "50", ",", "j", "/", "50", ")", "*", "255", ";", "surfaceData", "[", "i", "]", "[", "j", "]", "=", "val", ";", "}", "}", "return", "surfaceData", ";", "}" ]
create array with noise data to display
[ "create", "array", "with", "noise", "data", "to", "display" ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/examples/threaded-noise/noise-worker.js#L5-L16
16,255
GameJs/gamejs
examples/touch/main.js
colorForTouch
function colorForTouch(touch) { var id = touch.identifier + (100 * Math.random()); var r = Math.floor(id % 16); var g = Math.floor(id / 3) % 16; var b = Math.floor(id / 7) % 16; r = r.toString(16); g = g.toString(16); b = b.toString(16); var color = "#" + r + g + b; gamejs.logging.log(color) return color; }
javascript
function colorForTouch(touch) { var id = touch.identifier + (100 * Math.random()); var r = Math.floor(id % 16); var g = Math.floor(id / 3) % 16; var b = Math.floor(id / 7) % 16; r = r.toString(16); g = g.toString(16); b = b.toString(16); var color = "#" + r + g + b; gamejs.logging.log(color) return color; }
[ "function", "colorForTouch", "(", "touch", ")", "{", "var", "id", "=", "touch", ".", "identifier", "+", "(", "100", "*", "Math", ".", "random", "(", ")", ")", ";", "var", "r", "=", "Math", ".", "floor", "(", "id", "%", "16", ")", ";", "var", "g", "=", "Math", ".", "floor", "(", "id", "/", "3", ")", "%", "16", ";", "var", "b", "=", "Math", ".", "floor", "(", "id", "/", "7", ")", "%", "16", ";", "r", "=", "r", ".", "toString", "(", "16", ")", ";", "g", "=", "g", ".", "toString", "(", "16", ")", ";", "b", "=", "b", ".", "toString", "(", "16", ")", ";", "var", "color", "=", "\"#\"", "+", "r", "+", "g", "+", "b", ";", "gamejs", ".", "logging", ".", "log", "(", "color", ")", "return", "color", ";", "}" ]
create random color from touch identifier
[ "create", "random", "color", "from", "touch", "identifier" ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/examples/touch/main.js#L11-L22
16,256
GameJs/gamejs
utils/qunit/qunit-close-enough.js
function(actual, expected, maxDifference, message) { var passes = (actual === expected) || Math.abs(actual - expected) <= maxDifference; QUnit.push(passes, actual, expected, message); }
javascript
function(actual, expected, maxDifference, message) { var passes = (actual === expected) || Math.abs(actual - expected) <= maxDifference; QUnit.push(passes, actual, expected, message); }
[ "function", "(", "actual", ",", "expected", ",", "maxDifference", ",", "message", ")", "{", "var", "passes", "=", "(", "actual", "===", "expected", ")", "||", "Math", ".", "abs", "(", "actual", "-", "expected", ")", "<=", "maxDifference", ";", "QUnit", ".", "push", "(", "passes", ",", "actual", ",", "expected", ",", "message", ")", ";", "}" ]
Checks that the first two arguments are equal, or are numbers close enough to be considered equal based on a specified maximum allowable difference. @example close(3.141, Math.PI, 0.001); @param Number actual @param Number expected @param Number maxDifference (the maximum inclusive difference allowed between the actual and expected numbers) @param String message (optional)
[ "Checks", "that", "the", "first", "two", "arguments", "are", "equal", "or", "are", "numbers", "close", "enough", "to", "be", "considered", "equal", "based", "on", "a", "specified", "maximum", "allowable", "difference", "." ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/utils/qunit/qunit-close-enough.js#L13-L16
16,257
GameJs/gamejs
utils/qunit/qunit-close-enough.js
function(actual, expected, minDifference, message) { var passes = Math.abs(actual - expected) > minDifference; ok(passes); QUnit.push(passes, actual, expected, message); }
javascript
function(actual, expected, minDifference, message) { var passes = Math.abs(actual - expected) > minDifference; ok(passes); QUnit.push(passes, actual, expected, message); }
[ "function", "(", "actual", ",", "expected", ",", "minDifference", ",", "message", ")", "{", "var", "passes", "=", "Math", ".", "abs", "(", "actual", "-", "expected", ")", ">", "minDifference", ";", "ok", "(", "passes", ")", ";", "QUnit", ".", "push", "(", "passes", ",", "actual", ",", "expected", ",", "message", ")", ";", "}" ]
Checks that the first two arguments are numbers with differences greater than the specified minimum difference. @example notClose(3.1, Math.PI, 0.001); @param Number actual @param Number expected @param Number minDifference (the minimum exclusive difference allowed between the actual and expected numbers) @param String message (optional)
[ "Checks", "that", "the", "first", "two", "arguments", "are", "numbers", "with", "differences", "greater", "than", "the", "specified", "minimum", "difference", "." ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/utils/qunit/qunit-close-enough.js#L29-L33
16,258
GameJs/gamejs
examples/minimal/main.js
Ball
function Ball(center) { this.center = center; this.growPerSec = Ball.GROW_PER_SEC; this.radius = this.growPerSec * 2; this.color = 0; return this; }
javascript
function Ball(center) { this.center = center; this.growPerSec = Ball.GROW_PER_SEC; this.radius = this.growPerSec * 2; this.color = 0; return this; }
[ "function", "Ball", "(", "center", ")", "{", "this", ".", "center", "=", "center", ";", "this", ".", "growPerSec", "=", "Ball", ".", "GROW_PER_SEC", ";", "this", ".", "radius", "=", "this", ".", "growPerSec", "*", "2", ";", "this", ".", "color", "=", "0", ";", "return", "this", ";", "}" ]
ball is a colored circle. ball can circle through color list. ball constantly pulsates in size.
[ "ball", "is", "a", "colored", "circle", ".", "ball", "can", "circle", "through", "color", "list", ".", "ball", "constantly", "pulsates", "in", "size", "." ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/examples/minimal/main.js#L15-L21
16,259
GameJs/gamejs
src/gamejs/display.js
function(event) { var wrapper = getCanvas(); wrapper.requestFullScreen = wrapper.requestFullScreen || wrapper.mozRequestFullScreen || wrapper.webkitRequestFullScreen; if (!wrapper.requestFullScreen) { return false; } // @xbrowser chrome allows keboard input onl if ask for it (why oh why?) if (Element.ALLOW_KEYBOARD_INPUT) { wrapper.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } else { wrapper.requestFullScreen(); } return true; }
javascript
function(event) { var wrapper = getCanvas(); wrapper.requestFullScreen = wrapper.requestFullScreen || wrapper.mozRequestFullScreen || wrapper.webkitRequestFullScreen; if (!wrapper.requestFullScreen) { return false; } // @xbrowser chrome allows keboard input onl if ask for it (why oh why?) if (Element.ALLOW_KEYBOARD_INPUT) { wrapper.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } else { wrapper.requestFullScreen(); } return true; }
[ "function", "(", "event", ")", "{", "var", "wrapper", "=", "getCanvas", "(", ")", ";", "wrapper", ".", "requestFullScreen", "=", "wrapper", ".", "requestFullScreen", "||", "wrapper", ".", "mozRequestFullScreen", "||", "wrapper", ".", "webkitRequestFullScreen", ";", "if", "(", "!", "wrapper", ".", "requestFullScreen", ")", "{", "return", "false", ";", "}", "// @xbrowser chrome allows keboard input onl if ask for it (why oh why?)", "if", "(", "Element", ".", "ALLOW_KEYBOARD_INPUT", ")", "{", "wrapper", ".", "webkitRequestFullScreen", "(", "Element", ".", "ALLOW_KEYBOARD_INPUT", ")", ";", "}", "else", "{", "wrapper", ".", "requestFullScreen", "(", ")", ";", "}", "return", "true", ";", "}" ]
Switches the display window normal browser mode and fullscreen. @ignore @returns {Boolean} true if operation was successfull, false otherwise
[ "Switches", "the", "display", "window", "normal", "browser", "mode", "and", "fullscreen", "." ]
f09bf3e27235e1ca7f029e30c7e9a05a74af6663
https://github.com/GameJs/gamejs/blob/f09bf3e27235e1ca7f029e30c7e9a05a74af6663/src/gamejs/display.js#L189-L202
16,260
JedWatson/react-tappable
dist/react-tappable.js
function (name, func, context, a, b, c, d, e, f) { invokeGuardedCallback$1.apply(ReactErrorUtils, arguments); }
javascript
function (name, func, context, a, b, c, d, e, f) { invokeGuardedCallback$1.apply(ReactErrorUtils, arguments); }
[ "function", "(", "name", ",", "func", ",", "context", ",", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "f", ")", "{", "invokeGuardedCallback$1", ".", "apply", "(", "ReactErrorUtils", ",", "arguments", ")", ";", "}" ]
Call a function while guarding against errors that happens within it. Returns an error if it throws, otherwise null. In production, this is implemented using a try-catch. The reason we don't use a try-catch directly is so that we can swap out a different implementation in DEV mode. @param {String} name of the guard to use for logging or debugging @param {Function} func The function to invoke @param {*} context The context to use when calling the function @param {...*} args Arguments for function
[ "Call", "a", "function", "while", "guarding", "against", "errors", "that", "happens", "within", "it", ".", "Returns", "an", "error", "if", "it", "throws", "otherwise", "null", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L2680-L2682
16,261
JedWatson/react-tappable
dist/react-tappable.js
accumulateTwoPhaseDispatchesSingleSkipTarget
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? getParentInstance(targetInst) : null; traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } }
javascript
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? getParentInstance(targetInst) : null; traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } }
[ "function", "accumulateTwoPhaseDispatchesSingleSkipTarget", "(", "event", ")", "{", "if", "(", "event", "&&", "event", ".", "dispatchConfig", ".", "phasedRegistrationNames", ")", "{", "var", "targetInst", "=", "event", ".", "_targetInst", ";", "var", "parentInst", "=", "targetInst", "?", "getParentInstance", "(", "targetInst", ")", ":", "null", ";", "traverseTwoPhase", "(", "parentInst", ",", "accumulateDirectionalDispatches", ",", "event", ")", ";", "}", "}" ]
Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
[ "Same", "as", "accumulateTwoPhaseDispatchesSingle", "but", "skips", "over", "the", "targetID", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L3524-L3530
16,262
JedWatson/react-tappable
dist/react-tappable.js
getPooledWarningPropertyDefinition
function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; warning(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result); } }
javascript
function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; warning(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result); } }
[ "function", "getPooledWarningPropertyDefinition", "(", "propName", ",", "getVal", ")", "{", "var", "isFunction", "=", "typeof", "getVal", "===", "'function'", ";", "return", "{", "configurable", ":", "true", ",", "set", ":", "set", ",", "get", ":", "get", "}", ";", "function", "set", "(", "val", ")", "{", "var", "action", "=", "isFunction", "?", "'setting the method'", ":", "'setting the property'", ";", "warn", "(", "action", ",", "'This is effectively a no-op'", ")", ";", "return", "val", ";", "}", "function", "get", "(", ")", "{", "var", "action", "=", "isFunction", "?", "'accessing the method'", ":", "'accessing the property'", ";", "var", "result", "=", "isFunction", "?", "'This is a no-op function'", ":", "'This is set to null'", ";", "warn", "(", "action", ",", "result", ")", ";", "return", "getVal", ";", "}", "function", "warn", "(", "action", ",", "result", ")", "{", "var", "warningCondition", "=", "false", ";", "warning", "(", "warningCondition", ",", "\"This synthetic event is reused for performance reasons. If you're seeing this, \"", "+", "\"you're %s `%s` on a released/nullified synthetic event. %s. \"", "+", "'If you must keep the original synthetic event around, use event.persist(). '", "+", "'See https://fb.me/react-event-pooling for more information.'", ",", "action", ",", "propName", ",", "result", ")", ";", "}", "}" ]
Helper to nullify syntheticEvent instance properties when destructing @param {String} propName @param {?object} getVal @return {object} defineProperty object
[ "Helper", "to", "nullify", "syntheticEvent", "instance", "properties", "when", "destructing" ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L3891-L3916
16,263
JedWatson/react-tappable
dist/react-tappable.js
isEventSupported
function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } return isSupported; }
javascript
function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } return isSupported; }
[ "function", "isEventSupported", "(", "eventNameSuffix", ",", "capture", ")", "{", "if", "(", "!", "ExecutionEnvironment", ".", "canUseDOM", "||", "capture", "&&", "!", "(", "'addEventListener'", "in", "document", ")", ")", "{", "return", "false", ";", "}", "var", "eventName", "=", "'on'", "+", "eventNameSuffix", ";", "var", "isSupported", "=", "eventName", "in", "document", ";", "if", "(", "!", "isSupported", ")", "{", "var", "element", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "element", ".", "setAttribute", "(", "eventName", ",", "'return;'", ")", ";", "isSupported", "=", "typeof", "element", "[", "eventName", "]", "===", "'function'", ";", "}", "return", "isSupported", ";", "}" ]
Checks if an event is supported in the current execution environment. NOTE: This will not work correctly for non-generic events such as `change`, `reset`, `load`, `error`, and `select`. Borrows from Modernizr. @param {string} eventNameSuffix Event name, e.g. "click". @param {?boolean} capture Check if the capture phase is supported. @return {boolean} True if the event is supported. @internal @license Modernizr 3.0.0pre (Custom Build) | MIT
[ "Checks", "if", "an", "event", "is", "supported", "in", "the", "current", "execution", "environment", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L4544-L4559
16,264
JedWatson/react-tappable
dist/react-tappable.js
function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win = void 0; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from = void 0; var to = void 0; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : getNodeFromInstance$1(from); var toNode = to == null ? win : getNodeFromInstance$1(to); var leave = SyntheticMouseEvent.getPooled(eventTypes$2.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes$2.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; }
javascript
function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win = void 0; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from = void 0; var to = void 0; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : getNodeFromInstance$1(from); var toNode = to == null ? win : getNodeFromInstance$1(to); var leave = SyntheticMouseEvent.getPooled(eventTypes$2.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes$2.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; }
[ "function", "(", "topLevelType", ",", "targetInst", ",", "nativeEvent", ",", "nativeEventTarget", ")", "{", "if", "(", "topLevelType", "===", "'topMouseOver'", "&&", "(", "nativeEvent", ".", "relatedTarget", "||", "nativeEvent", ".", "fromElement", ")", ")", "{", "return", "null", ";", "}", "if", "(", "topLevelType", "!==", "'topMouseOut'", "&&", "topLevelType", "!==", "'topMouseOver'", ")", "{", "// Must not be a mouse in or mouse out - ignoring.", "return", "null", ";", "}", "var", "win", "=", "void", "0", ";", "if", "(", "nativeEventTarget", ".", "window", "===", "nativeEventTarget", ")", "{", "// `nativeEventTarget` is probably a window object.", "win", "=", "nativeEventTarget", ";", "}", "else", "{", "// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.", "var", "doc", "=", "nativeEventTarget", ".", "ownerDocument", ";", "if", "(", "doc", ")", "{", "win", "=", "doc", ".", "defaultView", "||", "doc", ".", "parentWindow", ";", "}", "else", "{", "win", "=", "window", ";", "}", "}", "var", "from", "=", "void", "0", ";", "var", "to", "=", "void", "0", ";", "if", "(", "topLevelType", "===", "'topMouseOut'", ")", "{", "from", "=", "targetInst", ";", "var", "related", "=", "nativeEvent", ".", "relatedTarget", "||", "nativeEvent", ".", "toElement", ";", "to", "=", "related", "?", "getClosestInstanceFromNode", "(", "related", ")", ":", "null", ";", "}", "else", "{", "// Moving to a node from outside the window.", "from", "=", "null", ";", "to", "=", "targetInst", ";", "}", "if", "(", "from", "===", "to", ")", "{", "// Nothing pertains to our managed components.", "return", "null", ";", "}", "var", "fromNode", "=", "from", "==", "null", "?", "win", ":", "getNodeFromInstance$1", "(", "from", ")", ";", "var", "toNode", "=", "to", "==", "null", "?", "win", ":", "getNodeFromInstance$1", "(", "to", ")", ";", "var", "leave", "=", "SyntheticMouseEvent", ".", "getPooled", "(", "eventTypes$2", ".", "mouseLeave", ",", "from", ",", "nativeEvent", ",", "nativeEventTarget", ")", ";", "leave", ".", "type", "=", "'mouseleave'", ";", "leave", ".", "target", "=", "fromNode", ";", "leave", ".", "relatedTarget", "=", "toNode", ";", "var", "enter", "=", "SyntheticMouseEvent", ".", "getPooled", "(", "eventTypes$2", ".", "mouseEnter", ",", "to", ",", "nativeEvent", ",", "nativeEventTarget", ")", ";", "enter", ".", "type", "=", "'mouseenter'", ";", "enter", ".", "target", "=", "toNode", ";", "enter", ".", "relatedTarget", "=", "fromNode", ";", "accumulateEnterLeaveDispatches", "(", "leave", ",", "enter", ",", "from", ",", "to", ")", ";", "return", "[", "leave", ",", "enter", "]", ";", "}" ]
For almost every interaction we care about, there will be both a top-level `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that we do not extract duplicate events. However, moving the mouse into the browser from outside will not fire a `mouseout` event. In this case, we use the `mouseover` top-level event.
[ "For", "almost", "every", "interaction", "we", "care", "about", "there", "will", "be", "both", "a", "top", "-", "level", "mouseover", "and", "mouseout", "event", "that", "occurs", ".", "Only", "use", "mouseout", "so", "that", "we", "do", "not", "extract", "duplicate", "events", ".", "However", "moving", "the", "mouse", "into", "the", "browser", "from", "outside", "will", "not", "fire", "a", "mouseout", "event", ".", "In", "this", "case", "we", "use", "the", "mouseover", "top", "-", "level", "event", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L5829-L5885
16,265
JedWatson/react-tappable
dist/react-tappable.js
trapBubbledEvent
function trapBubbledEvent(topLevelType, handlerBaseName, element) { if (!element) { return null; } var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; addEventBubbleListener(element, handlerBaseName, // Check if interactive and wrap in interactiveUpdates dispatch.bind(null, topLevelType)); }
javascript
function trapBubbledEvent(topLevelType, handlerBaseName, element) { if (!element) { return null; } var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; addEventBubbleListener(element, handlerBaseName, // Check if interactive and wrap in interactiveUpdates dispatch.bind(null, topLevelType)); }
[ "function", "trapBubbledEvent", "(", "topLevelType", ",", "handlerBaseName", ",", "element", ")", "{", "if", "(", "!", "element", ")", "{", "return", "null", ";", "}", "var", "dispatch", "=", "isInteractiveTopLevelEventType", "(", "topLevelType", ")", "?", "dispatchInteractiveEvent", ":", "dispatchEvent", ";", "addEventBubbleListener", "(", "element", ",", "handlerBaseName", ",", "// Check if interactive and wrap in interactiveUpdates", "dispatch", ".", "bind", "(", "null", ",", "topLevelType", ")", ")", ";", "}" ]
Traps top-level events by using event bubbling. @param {string} topLevelType Record from `BrowserEventConstants`. @param {string} handlerBaseName Event name (e.g. "click"). @param {object} element Element on which to attach listener. @return {?object} An object with a remove function which will forcefully remove the listener. @internal
[ "Traps", "top", "-", "level", "events", "by", "using", "event", "bubbling", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L6713-L6722
16,266
JedWatson/react-tappable
dist/react-tappable.js
trapCapturedEvent
function trapCapturedEvent(topLevelType, handlerBaseName, element) { if (!element) { return null; } var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; addEventCaptureListener(element, handlerBaseName, // Check if interactive and wrap in interactiveUpdates dispatch.bind(null, topLevelType)); }
javascript
function trapCapturedEvent(topLevelType, handlerBaseName, element) { if (!element) { return null; } var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; addEventCaptureListener(element, handlerBaseName, // Check if interactive and wrap in interactiveUpdates dispatch.bind(null, topLevelType)); }
[ "function", "trapCapturedEvent", "(", "topLevelType", ",", "handlerBaseName", ",", "element", ")", "{", "if", "(", "!", "element", ")", "{", "return", "null", ";", "}", "var", "dispatch", "=", "isInteractiveTopLevelEventType", "(", "topLevelType", ")", "?", "dispatchInteractiveEvent", ":", "dispatchEvent", ";", "addEventCaptureListener", "(", "element", ",", "handlerBaseName", ",", "// Check if interactive and wrap in interactiveUpdates", "dispatch", ".", "bind", "(", "null", ",", "topLevelType", ")", ")", ";", "}" ]
Traps a top-level event by using event capturing. @param {string} topLevelType Record from `BrowserEventConstants`. @param {string} handlerBaseName Event name (e.g. "click"). @param {object} element Element on which to attach listener. @return {?object} An object with a remove function which will forcefully remove the listener. @internal
[ "Traps", "a", "top", "-", "level", "event", "by", "using", "event", "capturing", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L6734-L6743
16,267
JedWatson/react-tappable
dist/react-tappable.js
computeUniqueAsyncExpiration
function computeUniqueAsyncExpiration() { var currentTime = recalculateCurrentTime(); var result = computeAsyncExpiration(currentTime); if (result <= lastUniqueAsyncExpiration) { // Since we assume the current time monotonically increases, we only hit // this branch when computeUniqueAsyncExpiration is fired multiple times // within a 200ms window (or whatever the async bucket size is). result = lastUniqueAsyncExpiration + 1; } lastUniqueAsyncExpiration = result; return lastUniqueAsyncExpiration; }
javascript
function computeUniqueAsyncExpiration() { var currentTime = recalculateCurrentTime(); var result = computeAsyncExpiration(currentTime); if (result <= lastUniqueAsyncExpiration) { // Since we assume the current time monotonically increases, we only hit // this branch when computeUniqueAsyncExpiration is fired multiple times // within a 200ms window (or whatever the async bucket size is). result = lastUniqueAsyncExpiration + 1; } lastUniqueAsyncExpiration = result; return lastUniqueAsyncExpiration; }
[ "function", "computeUniqueAsyncExpiration", "(", ")", "{", "var", "currentTime", "=", "recalculateCurrentTime", "(", ")", ";", "var", "result", "=", "computeAsyncExpiration", "(", "currentTime", ")", ";", "if", "(", "result", "<=", "lastUniqueAsyncExpiration", ")", "{", "// Since we assume the current time monotonically increases, we only hit", "// this branch when computeUniqueAsyncExpiration is fired multiple times", "// within a 200ms window (or whatever the async bucket size is).", "result", "=", "lastUniqueAsyncExpiration", "+", "1", ";", "}", "lastUniqueAsyncExpiration", "=", "result", ";", "return", "lastUniqueAsyncExpiration", ";", "}" ]
Creates a unique async expiration time.
[ "Creates", "a", "unique", "async", "expiration", "time", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L14383-L14394
16,268
JedWatson/react-tappable
dist/react-tappable.js
function (config) { var getPublicInstance = config.getPublicInstance; var _ReactFiberScheduler = ReactFiberScheduler(config), computeUniqueAsyncExpiration = _ReactFiberScheduler.computeUniqueAsyncExpiration, recalculateCurrentTime = _ReactFiberScheduler.recalculateCurrentTime, computeExpirationForFiber = _ReactFiberScheduler.computeExpirationForFiber, scheduleWork = _ReactFiberScheduler.scheduleWork, requestWork = _ReactFiberScheduler.requestWork, flushRoot = _ReactFiberScheduler.flushRoot, batchedUpdates = _ReactFiberScheduler.batchedUpdates, unbatchedUpdates = _ReactFiberScheduler.unbatchedUpdates, flushSync = _ReactFiberScheduler.flushSync, flushControlled = _ReactFiberScheduler.flushControlled, deferredUpdates = _ReactFiberScheduler.deferredUpdates, syncUpdates = _ReactFiberScheduler.syncUpdates, interactiveUpdates = _ReactFiberScheduler.interactiveUpdates, flushInteractiveUpdates = _ReactFiberScheduler.flushInteractiveUpdates, legacyContext = _ReactFiberScheduler.legacyContext; var findCurrentUnmaskedContext = legacyContext.findCurrentUnmaskedContext, isContextProvider = legacyContext.isContextProvider, processChildContext = legacyContext.processChildContext; function getContextForSubtree(parentComponent) { if (!parentComponent) { return emptyObject; } var fiber = get(parentComponent); var parentContext = findCurrentUnmaskedContext(fiber); return isContextProvider(fiber) ? processChildContext(fiber, parentContext) : parentContext; } function scheduleRootUpdate(current, element, currentTime, expirationTime, callback) { { if (ReactDebugCurrentFiber.phase === 'render' && ReactDebugCurrentFiber.current !== null && !didWarnAboutNestedUpdates) { didWarnAboutNestedUpdates = true; warning(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(ReactDebugCurrentFiber.current) || 'Unknown'); } } callback = callback === undefined ? null : callback; { warning(callback === null || typeof callback === 'function', 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); } var update = { expirationTime: expirationTime, partialState: { element: element }, callback: callback, isReplace: false, isForced: false, capturedValue: null, next: null }; insertUpdateIntoFiber(current, update); scheduleWork(current, expirationTime); return expirationTime; } function updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback) { // TODO: If this is a nested container, this won't be the root. var current = container.current; { if (ReactFiberInstrumentation_1.debugTool) { if (current.alternate === null) { ReactFiberInstrumentation_1.debugTool.onMountContainer(container); } else if (element === null) { ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); } else { ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); } } } var context = getContextForSubtree(parentComponent); if (container.context === null) { container.context = context; } else { container.pendingContext = context; } return scheduleRootUpdate(current, element, currentTime, expirationTime, callback); } function findHostInstance(fiber) { var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } return { createContainer: function (containerInfo, isAsync, hydrate) { return createFiberRoot(containerInfo, isAsync, hydrate); }, updateContainer: function (element, container, parentComponent, callback) { var current = container.current; var currentTime = recalculateCurrentTime(); var expirationTime = computeExpirationForFiber(current); return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback); }, updateContainerAtExpirationTime: function (element, container, parentComponent, expirationTime, callback) { var currentTime = recalculateCurrentTime(); return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback); }, flushRoot: flushRoot, requestWork: requestWork, computeUniqueAsyncExpiration: computeUniqueAsyncExpiration, batchedUpdates: batchedUpdates, unbatchedUpdates: unbatchedUpdates, deferredUpdates: deferredUpdates, syncUpdates: syncUpdates, interactiveUpdates: interactiveUpdates, flushInteractiveUpdates: flushInteractiveUpdates, flushControlled: flushControlled, flushSync: flushSync, getPublicRootInstance: function (container) { var containerFiber = container.current; if (!containerFiber.child) { return null; } switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); default: return containerFiber.child.stateNode; } }, findHostInstance: findHostInstance, findHostInstanceWithNoPortals: function (fiber) { var hostFiber = findCurrentHostFiberWithNoPortals(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; }, injectIntoDevTools: function (devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; return injectInternals(_assign({}, devToolsConfig, { findHostInstanceByFiber: function (fiber) { return findHostInstance(fiber); }, findFiberByHostInstance: function (instance) { if (!findFiberByHostInstance) { // Might not be implemented by the renderer. return null; } return findFiberByHostInstance(instance); } })); } }; }
javascript
function (config) { var getPublicInstance = config.getPublicInstance; var _ReactFiberScheduler = ReactFiberScheduler(config), computeUniqueAsyncExpiration = _ReactFiberScheduler.computeUniqueAsyncExpiration, recalculateCurrentTime = _ReactFiberScheduler.recalculateCurrentTime, computeExpirationForFiber = _ReactFiberScheduler.computeExpirationForFiber, scheduleWork = _ReactFiberScheduler.scheduleWork, requestWork = _ReactFiberScheduler.requestWork, flushRoot = _ReactFiberScheduler.flushRoot, batchedUpdates = _ReactFiberScheduler.batchedUpdates, unbatchedUpdates = _ReactFiberScheduler.unbatchedUpdates, flushSync = _ReactFiberScheduler.flushSync, flushControlled = _ReactFiberScheduler.flushControlled, deferredUpdates = _ReactFiberScheduler.deferredUpdates, syncUpdates = _ReactFiberScheduler.syncUpdates, interactiveUpdates = _ReactFiberScheduler.interactiveUpdates, flushInteractiveUpdates = _ReactFiberScheduler.flushInteractiveUpdates, legacyContext = _ReactFiberScheduler.legacyContext; var findCurrentUnmaskedContext = legacyContext.findCurrentUnmaskedContext, isContextProvider = legacyContext.isContextProvider, processChildContext = legacyContext.processChildContext; function getContextForSubtree(parentComponent) { if (!parentComponent) { return emptyObject; } var fiber = get(parentComponent); var parentContext = findCurrentUnmaskedContext(fiber); return isContextProvider(fiber) ? processChildContext(fiber, parentContext) : parentContext; } function scheduleRootUpdate(current, element, currentTime, expirationTime, callback) { { if (ReactDebugCurrentFiber.phase === 'render' && ReactDebugCurrentFiber.current !== null && !didWarnAboutNestedUpdates) { didWarnAboutNestedUpdates = true; warning(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(ReactDebugCurrentFiber.current) || 'Unknown'); } } callback = callback === undefined ? null : callback; { warning(callback === null || typeof callback === 'function', 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); } var update = { expirationTime: expirationTime, partialState: { element: element }, callback: callback, isReplace: false, isForced: false, capturedValue: null, next: null }; insertUpdateIntoFiber(current, update); scheduleWork(current, expirationTime); return expirationTime; } function updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback) { // TODO: If this is a nested container, this won't be the root. var current = container.current; { if (ReactFiberInstrumentation_1.debugTool) { if (current.alternate === null) { ReactFiberInstrumentation_1.debugTool.onMountContainer(container); } else if (element === null) { ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); } else { ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); } } } var context = getContextForSubtree(parentComponent); if (container.context === null) { container.context = context; } else { container.pendingContext = context; } return scheduleRootUpdate(current, element, currentTime, expirationTime, callback); } function findHostInstance(fiber) { var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } return { createContainer: function (containerInfo, isAsync, hydrate) { return createFiberRoot(containerInfo, isAsync, hydrate); }, updateContainer: function (element, container, parentComponent, callback) { var current = container.current; var currentTime = recalculateCurrentTime(); var expirationTime = computeExpirationForFiber(current); return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback); }, updateContainerAtExpirationTime: function (element, container, parentComponent, expirationTime, callback) { var currentTime = recalculateCurrentTime(); return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback); }, flushRoot: flushRoot, requestWork: requestWork, computeUniqueAsyncExpiration: computeUniqueAsyncExpiration, batchedUpdates: batchedUpdates, unbatchedUpdates: unbatchedUpdates, deferredUpdates: deferredUpdates, syncUpdates: syncUpdates, interactiveUpdates: interactiveUpdates, flushInteractiveUpdates: flushInteractiveUpdates, flushControlled: flushControlled, flushSync: flushSync, getPublicRootInstance: function (container) { var containerFiber = container.current; if (!containerFiber.child) { return null; } switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); default: return containerFiber.child.stateNode; } }, findHostInstance: findHostInstance, findHostInstanceWithNoPortals: function (fiber) { var hostFiber = findCurrentHostFiberWithNoPortals(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; }, injectIntoDevTools: function (devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; return injectInternals(_assign({}, devToolsConfig, { findHostInstanceByFiber: function (fiber) { return findHostInstance(fiber); }, findFiberByHostInstance: function (instance) { if (!findFiberByHostInstance) { // Might not be implemented by the renderer. return null; } return findFiberByHostInstance(instance); } })); } }; }
[ "function", "(", "config", ")", "{", "var", "getPublicInstance", "=", "config", ".", "getPublicInstance", ";", "var", "_ReactFiberScheduler", "=", "ReactFiberScheduler", "(", "config", ")", ",", "computeUniqueAsyncExpiration", "=", "_ReactFiberScheduler", ".", "computeUniqueAsyncExpiration", ",", "recalculateCurrentTime", "=", "_ReactFiberScheduler", ".", "recalculateCurrentTime", ",", "computeExpirationForFiber", "=", "_ReactFiberScheduler", ".", "computeExpirationForFiber", ",", "scheduleWork", "=", "_ReactFiberScheduler", ".", "scheduleWork", ",", "requestWork", "=", "_ReactFiberScheduler", ".", "requestWork", ",", "flushRoot", "=", "_ReactFiberScheduler", ".", "flushRoot", ",", "batchedUpdates", "=", "_ReactFiberScheduler", ".", "batchedUpdates", ",", "unbatchedUpdates", "=", "_ReactFiberScheduler", ".", "unbatchedUpdates", ",", "flushSync", "=", "_ReactFiberScheduler", ".", "flushSync", ",", "flushControlled", "=", "_ReactFiberScheduler", ".", "flushControlled", ",", "deferredUpdates", "=", "_ReactFiberScheduler", ".", "deferredUpdates", ",", "syncUpdates", "=", "_ReactFiberScheduler", ".", "syncUpdates", ",", "interactiveUpdates", "=", "_ReactFiberScheduler", ".", "interactiveUpdates", ",", "flushInteractiveUpdates", "=", "_ReactFiberScheduler", ".", "flushInteractiveUpdates", ",", "legacyContext", "=", "_ReactFiberScheduler", ".", "legacyContext", ";", "var", "findCurrentUnmaskedContext", "=", "legacyContext", ".", "findCurrentUnmaskedContext", ",", "isContextProvider", "=", "legacyContext", ".", "isContextProvider", ",", "processChildContext", "=", "legacyContext", ".", "processChildContext", ";", "function", "getContextForSubtree", "(", "parentComponent", ")", "{", "if", "(", "!", "parentComponent", ")", "{", "return", "emptyObject", ";", "}", "var", "fiber", "=", "get", "(", "parentComponent", ")", ";", "var", "parentContext", "=", "findCurrentUnmaskedContext", "(", "fiber", ")", ";", "return", "isContextProvider", "(", "fiber", ")", "?", "processChildContext", "(", "fiber", ",", "parentContext", ")", ":", "parentContext", ";", "}", "function", "scheduleRootUpdate", "(", "current", ",", "element", ",", "currentTime", ",", "expirationTime", ",", "callback", ")", "{", "{", "if", "(", "ReactDebugCurrentFiber", ".", "phase", "===", "'render'", "&&", "ReactDebugCurrentFiber", ".", "current", "!==", "null", "&&", "!", "didWarnAboutNestedUpdates", ")", "{", "didWarnAboutNestedUpdates", "=", "true", ";", "warning", "(", "false", ",", "'Render methods should be a pure function of props and state; '", "+", "'triggering nested component updates from render is not allowed. '", "+", "'If necessary, trigger nested updates in componentDidUpdate.\\n\\n'", "+", "'Check the render method of %s.'", ",", "getComponentName", "(", "ReactDebugCurrentFiber", ".", "current", ")", "||", "'Unknown'", ")", ";", "}", "}", "callback", "=", "callback", "===", "undefined", "?", "null", ":", "callback", ";", "{", "warning", "(", "callback", "===", "null", "||", "typeof", "callback", "===", "'function'", ",", "'render(...): Expected the last optional `callback` argument to be a '", "+", "'function. Instead received: %s.'", ",", "callback", ")", ";", "}", "var", "update", "=", "{", "expirationTime", ":", "expirationTime", ",", "partialState", ":", "{", "element", ":", "element", "}", ",", "callback", ":", "callback", ",", "isReplace", ":", "false", ",", "isForced", ":", "false", ",", "capturedValue", ":", "null", ",", "next", ":", "null", "}", ";", "insertUpdateIntoFiber", "(", "current", ",", "update", ")", ";", "scheduleWork", "(", "current", ",", "expirationTime", ")", ";", "return", "expirationTime", ";", "}", "function", "updateContainerAtExpirationTime", "(", "element", ",", "container", ",", "parentComponent", ",", "currentTime", ",", "expirationTime", ",", "callback", ")", "{", "// TODO: If this is a nested container, this won't be the root.", "var", "current", "=", "container", ".", "current", ";", "{", "if", "(", "ReactFiberInstrumentation_1", ".", "debugTool", ")", "{", "if", "(", "current", ".", "alternate", "===", "null", ")", "{", "ReactFiberInstrumentation_1", ".", "debugTool", ".", "onMountContainer", "(", "container", ")", ";", "}", "else", "if", "(", "element", "===", "null", ")", "{", "ReactFiberInstrumentation_1", ".", "debugTool", ".", "onUnmountContainer", "(", "container", ")", ";", "}", "else", "{", "ReactFiberInstrumentation_1", ".", "debugTool", ".", "onUpdateContainer", "(", "container", ")", ";", "}", "}", "}", "var", "context", "=", "getContextForSubtree", "(", "parentComponent", ")", ";", "if", "(", "container", ".", "context", "===", "null", ")", "{", "container", ".", "context", "=", "context", ";", "}", "else", "{", "container", ".", "pendingContext", "=", "context", ";", "}", "return", "scheduleRootUpdate", "(", "current", ",", "element", ",", "currentTime", ",", "expirationTime", ",", "callback", ")", ";", "}", "function", "findHostInstance", "(", "fiber", ")", "{", "var", "hostFiber", "=", "findCurrentHostFiber", "(", "fiber", ")", ";", "if", "(", "hostFiber", "===", "null", ")", "{", "return", "null", ";", "}", "return", "hostFiber", ".", "stateNode", ";", "}", "return", "{", "createContainer", ":", "function", "(", "containerInfo", ",", "isAsync", ",", "hydrate", ")", "{", "return", "createFiberRoot", "(", "containerInfo", ",", "isAsync", ",", "hydrate", ")", ";", "}", ",", "updateContainer", ":", "function", "(", "element", ",", "container", ",", "parentComponent", ",", "callback", ")", "{", "var", "current", "=", "container", ".", "current", ";", "var", "currentTime", "=", "recalculateCurrentTime", "(", ")", ";", "var", "expirationTime", "=", "computeExpirationForFiber", "(", "current", ")", ";", "return", "updateContainerAtExpirationTime", "(", "element", ",", "container", ",", "parentComponent", ",", "currentTime", ",", "expirationTime", ",", "callback", ")", ";", "}", ",", "updateContainerAtExpirationTime", ":", "function", "(", "element", ",", "container", ",", "parentComponent", ",", "expirationTime", ",", "callback", ")", "{", "var", "currentTime", "=", "recalculateCurrentTime", "(", ")", ";", "return", "updateContainerAtExpirationTime", "(", "element", ",", "container", ",", "parentComponent", ",", "currentTime", ",", "expirationTime", ",", "callback", ")", ";", "}", ",", "flushRoot", ":", "flushRoot", ",", "requestWork", ":", "requestWork", ",", "computeUniqueAsyncExpiration", ":", "computeUniqueAsyncExpiration", ",", "batchedUpdates", ":", "batchedUpdates", ",", "unbatchedUpdates", ":", "unbatchedUpdates", ",", "deferredUpdates", ":", "deferredUpdates", ",", "syncUpdates", ":", "syncUpdates", ",", "interactiveUpdates", ":", "interactiveUpdates", ",", "flushInteractiveUpdates", ":", "flushInteractiveUpdates", ",", "flushControlled", ":", "flushControlled", ",", "flushSync", ":", "flushSync", ",", "getPublicRootInstance", ":", "function", "(", "container", ")", "{", "var", "containerFiber", "=", "container", ".", "current", ";", "if", "(", "!", "containerFiber", ".", "child", ")", "{", "return", "null", ";", "}", "switch", "(", "containerFiber", ".", "child", ".", "tag", ")", "{", "case", "HostComponent", ":", "return", "getPublicInstance", "(", "containerFiber", ".", "child", ".", "stateNode", ")", ";", "default", ":", "return", "containerFiber", ".", "child", ".", "stateNode", ";", "}", "}", ",", "findHostInstance", ":", "findHostInstance", ",", "findHostInstanceWithNoPortals", ":", "function", "(", "fiber", ")", "{", "var", "hostFiber", "=", "findCurrentHostFiberWithNoPortals", "(", "fiber", ")", ";", "if", "(", "hostFiber", "===", "null", ")", "{", "return", "null", ";", "}", "return", "hostFiber", ".", "stateNode", ";", "}", ",", "injectIntoDevTools", ":", "function", "(", "devToolsConfig", ")", "{", "var", "findFiberByHostInstance", "=", "devToolsConfig", ".", "findFiberByHostInstance", ";", "return", "injectInternals", "(", "_assign", "(", "{", "}", ",", "devToolsConfig", ",", "{", "findHostInstanceByFiber", ":", "function", "(", "fiber", ")", "{", "return", "findHostInstance", "(", "fiber", ")", ";", "}", ",", "findFiberByHostInstance", ":", "function", "(", "instance", ")", "{", "if", "(", "!", "findFiberByHostInstance", ")", "{", "// Might not be implemented by the renderer.", "return", "null", ";", "}", "return", "findFiberByHostInstance", "(", "instance", ")", ";", "}", "}", ")", ")", ";", "}", "}", ";", "}" ]
0 is PROD, 1 is DEV. Might add PROFILE later.
[ "0", "is", "PROD", "1", "is", "DEV", ".", "Might", "add", "PROFILE", "later", "." ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L15011-L15186
16,269
JedWatson/react-tappable
dist/react-tappable.js
validateFragmentProps
function validateFragmentProps(fragment) { currentlyValidatingElement = fragment; var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!VALID_FRAGMENT_PROPS.has(key)) { warning(false, 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.%s', key, getStackAddendum()); break; } } if (fragment.ref !== null) { warning(false, 'Invalid attribute `ref` supplied to `React.Fragment`.%s', getStackAddendum()); } currentlyValidatingElement = null; }
javascript
function validateFragmentProps(fragment) { currentlyValidatingElement = fragment; var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!VALID_FRAGMENT_PROPS.has(key)) { warning(false, 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.%s', key, getStackAddendum()); break; } } if (fragment.ref !== null) { warning(false, 'Invalid attribute `ref` supplied to `React.Fragment`.%s', getStackAddendum()); } currentlyValidatingElement = null; }
[ "function", "validateFragmentProps", "(", "fragment", ")", "{", "currentlyValidatingElement", "=", "fragment", ";", "var", "keys", "=", "Object", ".", "keys", "(", "fragment", ".", "props", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "!", "VALID_FRAGMENT_PROPS", ".", "has", "(", "key", ")", ")", "{", "warning", "(", "false", ",", "'Invalid prop `%s` supplied to `React.Fragment`. '", "+", "'React.Fragment can only have `key` and `children` props.%s'", ",", "key", ",", "getStackAddendum", "(", ")", ")", ";", "break", ";", "}", "}", "if", "(", "fragment", ".", "ref", "!==", "null", ")", "{", "warning", "(", "false", ",", "'Invalid attribute `ref` supplied to `React.Fragment`.%s'", ",", "getStackAddendum", "(", ")", ")", ";", "}", "currentlyValidatingElement", "=", "null", ";", "}" ]
Given a fragment, validate that it can only be provided with fragment props @param {ReactElement} fragment
[ "Given", "a", "fragment", "validate", "that", "it", "can", "only", "be", "provided", "with", "fragment", "props" ]
c7a05f03f354c7556a413a6d270544629fd50ab7
https://github.com/JedWatson/react-tappable/blob/c7a05f03f354c7556a413a6d270544629fd50ab7/dist/react-tappable.js#L20550-L20567
16,270
codex-team/js-notifier
src/notifier.js
show
function show(options) { if (!options.message) { return; } prepare_(); let notify = null; const time = options.time || 8000; switch (options.type) { case 'confirm': notify = draw.confirm(options); break; case 'prompt': notify = draw.prompt(options); break; default: notify = draw.alert(options); window.setTimeout(function () { notify.remove(); }, time); } wrapper_.appendChild(notify); notify.classList.add(bounceInClass); }
javascript
function show(options) { if (!options.message) { return; } prepare_(); let notify = null; const time = options.time || 8000; switch (options.type) { case 'confirm': notify = draw.confirm(options); break; case 'prompt': notify = draw.prompt(options); break; default: notify = draw.alert(options); window.setTimeout(function () { notify.remove(); }, time); } wrapper_.appendChild(notify); notify.classList.add(bounceInClass); }
[ "function", "show", "(", "options", ")", "{", "if", "(", "!", "options", ".", "message", ")", "{", "return", ";", "}", "prepare_", "(", ")", ";", "let", "notify", "=", "null", ";", "const", "time", "=", "options", ".", "time", "||", "8000", ";", "switch", "(", "options", ".", "type", ")", "{", "case", "'confirm'", ":", "notify", "=", "draw", ".", "confirm", "(", "options", ")", ";", "break", ";", "case", "'prompt'", ":", "notify", "=", "draw", ".", "prompt", "(", "options", ")", ";", "break", ";", "default", ":", "notify", "=", "draw", ".", "alert", "(", "options", ")", ";", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "notify", ".", "remove", "(", ")", ";", "}", ",", "time", ")", ";", "}", "wrapper_", ".", "appendChild", "(", "notify", ")", ";", "notify", ".", "classList", ".", "add", "(", "bounceInClass", ")", ";", "}" ]
Show new notification @param {NotificationOptions | ConfirmNotificationOptions | PromptNotificationOptions} options
[ "Show", "new", "notification" ]
d000792c90bbde682d438b3554f3b9c8f6ddcb95
https://github.com/codex-team/js-notifier/blob/d000792c90bbde682d438b3554f3b9c8f6ddcb95/src/notifier.js#L35-L65
16,271
KhaledMohamedP/translate-json-object
lib/translate-json-object.js
init
function init(options) { setting = options || {}; if (!setting.googleApiKey && !setting.yandexApiKey) { console.warn(constant.ERROR.MISSING_TOKEN); return false; } else if (setting.yandexApiKey) { serviceType = constant.YANDEX_NAME; translateSrv = require('./service/yandex.js'); } else { serviceType = constant.GOOGLE_NAME; translateSrv = require('./service/google.js'); } translateSrv.init(setting); return true; }
javascript
function init(options) { setting = options || {}; if (!setting.googleApiKey && !setting.yandexApiKey) { console.warn(constant.ERROR.MISSING_TOKEN); return false; } else if (setting.yandexApiKey) { serviceType = constant.YANDEX_NAME; translateSrv = require('./service/yandex.js'); } else { serviceType = constant.GOOGLE_NAME; translateSrv = require('./service/google.js'); } translateSrv.init(setting); return true; }
[ "function", "init", "(", "options", ")", "{", "setting", "=", "options", "||", "{", "}", ";", "if", "(", "!", "setting", ".", "googleApiKey", "&&", "!", "setting", ".", "yandexApiKey", ")", "{", "console", ".", "warn", "(", "constant", ".", "ERROR", ".", "MISSING_TOKEN", ")", ";", "return", "false", ";", "}", "else", "if", "(", "setting", ".", "yandexApiKey", ")", "{", "serviceType", "=", "constant", ".", "YANDEX_NAME", ";", "translateSrv", "=", "require", "(", "'./service/yandex.js'", ")", ";", "}", "else", "{", "serviceType", "=", "constant", ".", "GOOGLE_NAME", ";", "translateSrv", "=", "require", "(", "'./service/google.js'", ")", ";", "}", "translateSrv", ".", "init", "(", "setting", ")", ";", "return", "true", ";", "}" ]
init - Initialize the setting of your module instance, it takes a setting object @param {Object} options @return {boolean} indicate if the module is configured properly
[ "init", "-", "Initialize", "the", "setting", "of", "your", "module", "instance", "it", "takes", "a", "setting", "object" ]
f1f0297614ed0f942921ab66ea788d6602e14b60
https://github.com/KhaledMohamedP/translate-json-object/blob/f1f0297614ed0f942921ab66ea788d6602e14b60/lib/translate-json-object.js#L26-L42
16,272
redhivesoftware/math-expression-evaluator
src/math_function.js
function (x) { return (Mexp.math.isDegree ? 180 / Math.PI * Math.acos(x) : Math.acos(x)) }
javascript
function (x) { return (Mexp.math.isDegree ? 180 / Math.PI * Math.acos(x) : Math.acos(x)) }
[ "function", "(", "x", ")", "{", "return", "(", "Mexp", ".", "math", ".", "isDegree", "?", "180", "/", "Math", ".", "PI", "*", "Math", ".", "acos", "(", "x", ")", ":", "Math", ".", "acos", "(", "x", ")", ")", "}" ]
mode of calculator
[ "mode", "of", "calculator" ]
8a12b393714235f8826376b958edade7c6965bb7
https://github.com/redhivesoftware/math-expression-evaluator/blob/8a12b393714235f8826376b958edade7c6965bb7/src/math_function.js#L7-L9
16,273
TheCocoaProject/cordova-plugin-nativestorage
www/mainHandle.js
StorageHandle
function StorageHandle() { this.storageSupport = storageSupportAnalyse(); switch (this.storageSupport) { case 0: var exec = require('cordova/exec'); this.storageHandlerDelegate = exec; break; case 1: var localStorageHandle = require('./LocalStorageHandle'); this.storageHandlerDelegate = localStorageHandle; break; case 2: console.log("ALERT! localstorage isn't supported"); break; default: console.log("StorageSupport Error"); break; } }
javascript
function StorageHandle() { this.storageSupport = storageSupportAnalyse(); switch (this.storageSupport) { case 0: var exec = require('cordova/exec'); this.storageHandlerDelegate = exec; break; case 1: var localStorageHandle = require('./LocalStorageHandle'); this.storageHandlerDelegate = localStorageHandle; break; case 2: console.log("ALERT! localstorage isn't supported"); break; default: console.log("StorageSupport Error"); break; } }
[ "function", "StorageHandle", "(", ")", "{", "this", ".", "storageSupport", "=", "storageSupportAnalyse", "(", ")", ";", "switch", "(", "this", ".", "storageSupport", ")", "{", "case", "0", ":", "var", "exec", "=", "require", "(", "'cordova/exec'", ")", ";", "this", ".", "storageHandlerDelegate", "=", "exec", ";", "break", ";", "case", "1", ":", "var", "localStorageHandle", "=", "require", "(", "'./LocalStorageHandle'", ")", ";", "this", ".", "storageHandlerDelegate", "=", "localStorageHandle", ";", "break", ";", "case", "2", ":", "console", ".", "log", "(", "\"ALERT! localstorage isn't supported\"", ")", ";", "break", ";", "default", ":", "console", ".", "log", "(", "\"StorageSupport Error\"", ")", ";", "break", ";", "}", "}" ]
if storage not available gracefully fails, no error message for now
[ "if", "storage", "not", "available", "gracefully", "fails", "no", "error", "message", "for", "now" ]
12aea3dfe4976c2ecb3e91dc951bd5af0cdd90df
https://github.com/TheCocoaProject/cordova-plugin-nativestorage/blob/12aea3dfe4976c2ecb3e91dc951bd5af0cdd90df/www/mainHandle.js#L26-L44
16,274
mapbox/timespace
index.js
getFuzzyLocalTimeFromPoint
function getFuzzyLocalTimeFromPoint(timestamp, point) { var tile = tilebelt.pointToTile(point[0], point[1], z).join('/'); var locale = tiles[tile]; if (locale) return moment.tz(new Date(timestamp), locale); else return undefined; }
javascript
function getFuzzyLocalTimeFromPoint(timestamp, point) { var tile = tilebelt.pointToTile(point[0], point[1], z).join('/'); var locale = tiles[tile]; if (locale) return moment.tz(new Date(timestamp), locale); else return undefined; }
[ "function", "getFuzzyLocalTimeFromPoint", "(", "timestamp", ",", "point", ")", "{", "var", "tile", "=", "tilebelt", ".", "pointToTile", "(", "point", "[", "0", "]", ",", "point", "[", "1", "]", ",", "z", ")", ".", "join", "(", "'/'", ")", ";", "var", "locale", "=", "tiles", "[", "tile", "]", ";", "if", "(", "locale", ")", "return", "moment", ".", "tz", "(", "new", "Date", "(", "timestamp", ")", ",", "locale", ")", ";", "else", "return", "undefined", ";", "}" ]
Returns the local time at the point of interest. @param {Integer} timestamp a unix timestamp @param {Array} point a [lng, lat] point of interest @return {Object} a moment-timezone object
[ "Returns", "the", "local", "time", "at", "the", "point", "of", "interest", "." ]
dab5368face8c355debff951bfbfd8d2b55b6686
https://github.com/mapbox/timespace/blob/dab5368face8c355debff951bfbfd8d2b55b6686/index.js#L22-L28
16,275
mapbox/timespace
index.js
getFuzzyTimezoneFromTile
function getFuzzyTimezoneFromTile(tile) { if (tile[2] === z) { var key = tile.join('/'); if (key in tiles) return tiles[key]; else throw new Error('tile not found'); } else if (tile[2] > z) { // higher zoom level (9, 10, 11, ...) key = _getParent(tile).join('/'); if (key in tiles) return tiles[key]; else throw new Error('tile not found'); } else { // lower zoom level (..., 5, 6, 7) var children = _getChildren(tile); var votes = []; // list of timezone abbrevations var abbrs = {}; // abbrevation to full name lookup table children.forEach(function(child) { key = child.join('/'); if (key in tiles) { var tz = tiles[key]; // timezone name // Need to use timezone abbreviation becuase e.g. America/Los_Angeles // and America/Vancouver are the same. Use a time to determine the // abbreviation, in case two similar tz have slightly different // daylight savings schedule. var abbr = moment.tz(Date.now(), tz)._z.abbrs[0]; votes.push(abbr); abbrs[abbr] = tz; } }); if (votes.length > 1) return abbrs[ss.mode(votes)]; else throw new Error('tile not found'); } }
javascript
function getFuzzyTimezoneFromTile(tile) { if (tile[2] === z) { var key = tile.join('/'); if (key in tiles) return tiles[key]; else throw new Error('tile not found'); } else if (tile[2] > z) { // higher zoom level (9, 10, 11, ...) key = _getParent(tile).join('/'); if (key in tiles) return tiles[key]; else throw new Error('tile not found'); } else { // lower zoom level (..., 5, 6, 7) var children = _getChildren(tile); var votes = []; // list of timezone abbrevations var abbrs = {}; // abbrevation to full name lookup table children.forEach(function(child) { key = child.join('/'); if (key in tiles) { var tz = tiles[key]; // timezone name // Need to use timezone abbreviation becuase e.g. America/Los_Angeles // and America/Vancouver are the same. Use a time to determine the // abbreviation, in case two similar tz have slightly different // daylight savings schedule. var abbr = moment.tz(Date.now(), tz)._z.abbrs[0]; votes.push(abbr); abbrs[abbr] = tz; } }); if (votes.length > 1) return abbrs[ss.mode(votes)]; else throw new Error('tile not found'); } }
[ "function", "getFuzzyTimezoneFromTile", "(", "tile", ")", "{", "if", "(", "tile", "[", "2", "]", "===", "z", ")", "{", "var", "key", "=", "tile", ".", "join", "(", "'/'", ")", ";", "if", "(", "key", "in", "tiles", ")", "return", "tiles", "[", "key", "]", ";", "else", "throw", "new", "Error", "(", "'tile not found'", ")", ";", "}", "else", "if", "(", "tile", "[", "2", "]", ">", "z", ")", "{", "// higher zoom level (9, 10, 11, ...)", "key", "=", "_getParent", "(", "tile", ")", ".", "join", "(", "'/'", ")", ";", "if", "(", "key", "in", "tiles", ")", "return", "tiles", "[", "key", "]", ";", "else", "throw", "new", "Error", "(", "'tile not found'", ")", ";", "}", "else", "{", "// lower zoom level (..., 5, 6, 7)", "var", "children", "=", "_getChildren", "(", "tile", ")", ";", "var", "votes", "=", "[", "]", ";", "// list of timezone abbrevations", "var", "abbrs", "=", "{", "}", ";", "// abbrevation to full name lookup table", "children", ".", "forEach", "(", "function", "(", "child", ")", "{", "key", "=", "child", ".", "join", "(", "'/'", ")", ";", "if", "(", "key", "in", "tiles", ")", "{", "var", "tz", "=", "tiles", "[", "key", "]", ";", "// timezone name", "// Need to use timezone abbreviation becuase e.g. America/Los_Angeles", "// and America/Vancouver are the same. Use a time to determine the", "// abbreviation, in case two similar tz have slightly different", "// daylight savings schedule.", "var", "abbr", "=", "moment", ".", "tz", "(", "Date", ".", "now", "(", ")", ",", "tz", ")", ".", "_z", ".", "abbrs", "[", "0", "]", ";", "votes", ".", "push", "(", "abbr", ")", ";", "abbrs", "[", "abbr", "]", "=", "tz", ";", "}", "}", ")", ";", "if", "(", "votes", ".", "length", ">", "1", ")", "return", "abbrs", "[", "ss", ".", "mode", "(", "votes", ")", "]", ";", "else", "throw", "new", "Error", "(", "'tile not found'", ")", ";", "}", "}" ]
Retrieves the timezone of the tile of interest at z8-level accuracy. @param {Array} tile [x, y, z] coordinate of a tile @return {String} timezone for the tile
[ "Retrieves", "the", "timezone", "of", "the", "tile", "of", "interest", "at", "z8", "-", "level", "accuracy", "." ]
dab5368face8c355debff951bfbfd8d2b55b6686
https://github.com/mapbox/timespace/blob/dab5368face8c355debff951bfbfd8d2b55b6686/index.js#L35-L70
16,276
Slynova-Org/flydrive
src/Drivers/LocalFileSystem.js
isReadableStream
function isReadableStream (stream) { return stream !== null && typeof (stream) === 'object' && typeof (stream.pipe) === 'function' && typeof (stream._read) === 'function' && typeof (stream._readableState) === 'object' && stream.readable !== false }
javascript
function isReadableStream (stream) { return stream !== null && typeof (stream) === 'object' && typeof (stream.pipe) === 'function' && typeof (stream._read) === 'function' && typeof (stream._readableState) === 'object' && stream.readable !== false }
[ "function", "isReadableStream", "(", "stream", ")", "{", "return", "stream", "!==", "null", "&&", "typeof", "(", "stream", ")", "===", "'object'", "&&", "typeof", "(", "stream", ".", "pipe", ")", "===", "'function'", "&&", "typeof", "(", "stream", ".", "_read", ")", "===", "'function'", "&&", "typeof", "(", "stream", ".", "_readableState", ")", "===", "'object'", "&&", "stream", ".", "readable", "!==", "false", "}" ]
Returns a boolean indication if stream param is a readable stream or not. @param {*} stream @return {Boolean}
[ "Returns", "a", "boolean", "indication", "if", "stream", "param", "is", "a", "readable", "stream", "or", "not", "." ]
c1025a1b285efc9b879952a63fb8ec9bce7ac36b
https://github.com/Slynova-Org/flydrive/blob/c1025a1b285efc9b879952a63fb8ec9bce7ac36b/src/Drivers/LocalFileSystem.js#L23-L30
16,277
oxygenhq/oxygen
ox_modules/module-mailinator.js
wait
function wait() { var isDone = false; var start = new Date().getTime(); var interval = setInterval(() => { var now = new Date().getTime(); if ((now - start) >= _retryInterval){ clearInterval(interval); isDone = true; } }, 50); deasync.loopWhile(() => !isDone); }
javascript
function wait() { var isDone = false; var start = new Date().getTime(); var interval = setInterval(() => { var now = new Date().getTime(); if ((now - start) >= _retryInterval){ clearInterval(interval); isDone = true; } }, 50); deasync.loopWhile(() => !isDone); }
[ "function", "wait", "(", ")", "{", "var", "isDone", "=", "false", ";", "var", "start", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "var", "interval", "=", "setInterval", "(", "(", ")", "=>", "{", "var", "now", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "if", "(", "(", "now", "-", "start", ")", ">=", "_retryInterval", ")", "{", "clearInterval", "(", "interval", ")", ";", "isDone", "=", "true", ";", "}", "}", ",", "50", ")", ";", "deasync", ".", "loopWhile", "(", "(", ")", "=>", "!", "isDone", ")", ";", "}" ]
wait synchronously in a non-blocking manner
[ "wait", "synchronously", "in", "a", "non", "-", "blocking", "manner" ]
b1c4be3360363091df89558dbbfb7f6d9d8efd71
https://github.com/oxygenhq/oxygen/blob/b1c4be3360363091df89558dbbfb7f6d9d8efd71/ox_modules/module-mailinator.js#L33-L46
16,278
oxygenhq/oxygen
ox_modules/module-mob/commands/clickHidden.js
function(elms, clickParent) { var elm = elms && elms.length > 0 ? elms[0] : null; if (!elm) { return; } /*global document*/ var clck_ev = document.createEvent('MouseEvent'); clck_ev.initEvent('click', true, true); if (clickParent) { elm.parentElement.dispatchEvent(clck_ev); } else { elm.dispatchEvent(clck_ev); } }
javascript
function(elms, clickParent) { var elm = elms && elms.length > 0 ? elms[0] : null; if (!elm) { return; } /*global document*/ var clck_ev = document.createEvent('MouseEvent'); clck_ev.initEvent('click', true, true); if (clickParent) { elm.parentElement.dispatchEvent(clck_ev); } else { elm.dispatchEvent(clck_ev); } }
[ "function", "(", "elms", ",", "clickParent", ")", "{", "var", "elm", "=", "elms", "&&", "elms", ".", "length", ">", "0", "?", "elms", "[", "0", "]", ":", "null", ";", "if", "(", "!", "elm", ")", "{", "return", ";", "}", "/*global document*/", "var", "clck_ev", "=", "document", ".", "createEvent", "(", "'MouseEvent'", ")", ";", "clck_ev", ".", "initEvent", "(", "'click'", ",", "true", ",", "true", ")", ";", "if", "(", "clickParent", ")", "{", "elm", ".", "parentElement", ".", "dispatchEvent", "(", "clck_ev", ")", ";", "}", "else", "{", "elm", ".", "dispatchEvent", "(", "clck_ev", ")", ";", "}", "}" ]
click hidden function
[ "click", "hidden", "function" ]
b1c4be3360363091df89558dbbfb7f6d9d8efd71
https://github.com/oxygenhq/oxygen/blob/b1c4be3360363091df89558dbbfb7f6d9d8efd71/ox_modules/module-mob/commands/clickHidden.js#L24-L37
16,279
AleksandrRogov/DynamicsWebApi
lib/utilities/RequestConverter.js
convertRequest
function convertRequest(request, functionName, config) { var url = ''; var result; if (!request.url) { if (!request._unboundRequest && !request.collection) { ErrorHelper.parameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection"); } if (request.collection) { ErrorHelper.stringParameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection"); url = request.collection; //add alternate key feature if (request.key) { request.key = ErrorHelper.keyParameterCheck(request.key, 'DynamicsWebApi.' + functionName, "request.key"); } else if (request.id) { request.key = ErrorHelper.guidParameterCheck(request.id, 'DynamicsWebApi.' + functionName, "request.id"); } if (request.key) { url += "(" + request.key + ")"; } } if (request._additionalUrl) { if (url) { url += '/'; } url += request._additionalUrl; } result = convertRequestOptions(request, functionName, url, '&', config); if (request.fetchXml) { ErrorHelper.stringParameterCheck(request.fetchXml, 'DynamicsWebApi.' + functionName, "request.fetchXml"); result.url += "?fetchXml=" + encodeURIComponent(request.fetchXml); } else if (result.query) { result.url += "?" + result.query; } } else { ErrorHelper.stringParameterCheck(request.url, 'DynamicsWebApi.' + functionName, "request.url"); url = request.url.replace(config.webApiUrl, ''); result = convertRequestOptions(request, functionName, url, '&', config); } if (request.hasOwnProperty('async') && request.async != null) { ErrorHelper.boolParameterCheck(request.async, 'DynamicsWebApi.' + functionName, "request.async"); result.async = request.async; } else { result.async = true; } return { url: result.url, headers: result.headers, async: result.async }; }
javascript
function convertRequest(request, functionName, config) { var url = ''; var result; if (!request.url) { if (!request._unboundRequest && !request.collection) { ErrorHelper.parameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection"); } if (request.collection) { ErrorHelper.stringParameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection"); url = request.collection; //add alternate key feature if (request.key) { request.key = ErrorHelper.keyParameterCheck(request.key, 'DynamicsWebApi.' + functionName, "request.key"); } else if (request.id) { request.key = ErrorHelper.guidParameterCheck(request.id, 'DynamicsWebApi.' + functionName, "request.id"); } if (request.key) { url += "(" + request.key + ")"; } } if (request._additionalUrl) { if (url) { url += '/'; } url += request._additionalUrl; } result = convertRequestOptions(request, functionName, url, '&', config); if (request.fetchXml) { ErrorHelper.stringParameterCheck(request.fetchXml, 'DynamicsWebApi.' + functionName, "request.fetchXml"); result.url += "?fetchXml=" + encodeURIComponent(request.fetchXml); } else if (result.query) { result.url += "?" + result.query; } } else { ErrorHelper.stringParameterCheck(request.url, 'DynamicsWebApi.' + functionName, "request.url"); url = request.url.replace(config.webApiUrl, ''); result = convertRequestOptions(request, functionName, url, '&', config); } if (request.hasOwnProperty('async') && request.async != null) { ErrorHelper.boolParameterCheck(request.async, 'DynamicsWebApi.' + functionName, "request.async"); result.async = request.async; } else { result.async = true; } return { url: result.url, headers: result.headers, async: result.async }; }
[ "function", "convertRequest", "(", "request", ",", "functionName", ",", "config", ")", "{", "var", "url", "=", "''", ";", "var", "result", ";", "if", "(", "!", "request", ".", "url", ")", "{", "if", "(", "!", "request", ".", "_unboundRequest", "&&", "!", "request", ".", "collection", ")", "{", "ErrorHelper", ".", "parameterCheck", "(", "request", ".", "collection", ",", "'DynamicsWebApi.'", "+", "functionName", ",", "\"request.collection\"", ")", ";", "}", "if", "(", "request", ".", "collection", ")", "{", "ErrorHelper", ".", "stringParameterCheck", "(", "request", ".", "collection", ",", "'DynamicsWebApi.'", "+", "functionName", ",", "\"request.collection\"", ")", ";", "url", "=", "request", ".", "collection", ";", "//add alternate key feature", "if", "(", "request", ".", "key", ")", "{", "request", ".", "key", "=", "ErrorHelper", ".", "keyParameterCheck", "(", "request", ".", "key", ",", "'DynamicsWebApi.'", "+", "functionName", ",", "\"request.key\"", ")", ";", "}", "else", "if", "(", "request", ".", "id", ")", "{", "request", ".", "key", "=", "ErrorHelper", ".", "guidParameterCheck", "(", "request", ".", "id", ",", "'DynamicsWebApi.'", "+", "functionName", ",", "\"request.id\"", ")", ";", "}", "if", "(", "request", ".", "key", ")", "{", "url", "+=", "\"(\"", "+", "request", ".", "key", "+", "\")\"", ";", "}", "}", "if", "(", "request", ".", "_additionalUrl", ")", "{", "if", "(", "url", ")", "{", "url", "+=", "'/'", ";", "}", "url", "+=", "request", ".", "_additionalUrl", ";", "}", "result", "=", "convertRequestOptions", "(", "request", ",", "functionName", ",", "url", ",", "'&'", ",", "config", ")", ";", "if", "(", "request", ".", "fetchXml", ")", "{", "ErrorHelper", ".", "stringParameterCheck", "(", "request", ".", "fetchXml", ",", "'DynamicsWebApi.'", "+", "functionName", ",", "\"request.fetchXml\"", ")", ";", "result", ".", "url", "+=", "\"?fetchXml=\"", "+", "encodeURIComponent", "(", "request", ".", "fetchXml", ")", ";", "}", "else", "if", "(", "result", ".", "query", ")", "{", "result", ".", "url", "+=", "\"?\"", "+", "result", ".", "query", ";", "}", "}", "else", "{", "ErrorHelper", ".", "stringParameterCheck", "(", "request", ".", "url", ",", "'DynamicsWebApi.'", "+", "functionName", ",", "\"request.url\"", ")", ";", "url", "=", "request", ".", "url", ".", "replace", "(", "config", ".", "webApiUrl", ",", "''", ")", ";", "result", "=", "convertRequestOptions", "(", "request", ",", "functionName", ",", "url", ",", "'&'", ",", "config", ")", ";", "}", "if", "(", "request", ".", "hasOwnProperty", "(", "'async'", ")", "&&", "request", ".", "async", "!=", "null", ")", "{", "ErrorHelper", ".", "boolParameterCheck", "(", "request", ".", "async", ",", "'DynamicsWebApi.'", "+", "functionName", ",", "\"request.async\"", ")", ";", "result", ".", "async", "=", "request", ".", "async", ";", "}", "else", "{", "result", ".", "async", "=", "true", ";", "}", "return", "{", "url", ":", "result", ".", "url", ",", "headers", ":", "result", ".", "headers", ",", "async", ":", "result", ".", "async", "}", ";", "}" ]
Converts a request object to URL link @param {Object} request - Request object @param {string} [functionName] - Name of the function that converts a request (for Error Handling only) @param {Object} [config] - DynamicsWebApi config @returns {ConvertedRequest} Converted request
[ "Converts", "a", "request", "object", "to", "URL", "link" ]
3ef9e2a010bafe439d71774325adc0b317024e5a
https://github.com/AleksandrRogov/DynamicsWebApi/blob/3ef9e2a010bafe439d71774325adc0b317024e5a/lib/utilities/RequestConverter.js#L208-L264
16,280
AleksandrRogov/DynamicsWebApi
lib/requests/sendRequest.js
findCollectionName
function findCollectionName(entityName) { var xrmInternal = Utility.getXrmInternal(); if (!Utility.isNull(xrmInternal)) { return xrmInternal.getEntitySetName(entityName) || entityName; } var collectionName = null; if (!Utility.isNull(_entityNames)) { collectionName = _entityNames[entityName]; if (Utility.isNull(collectionName)) { for (var key in _entityNames) { if (_entityNames[key] == entityName) { return entityName; } } } } return collectionName; }
javascript
function findCollectionName(entityName) { var xrmInternal = Utility.getXrmInternal(); if (!Utility.isNull(xrmInternal)) { return xrmInternal.getEntitySetName(entityName) || entityName; } var collectionName = null; if (!Utility.isNull(_entityNames)) { collectionName = _entityNames[entityName]; if (Utility.isNull(collectionName)) { for (var key in _entityNames) { if (_entityNames[key] == entityName) { return entityName; } } } } return collectionName; }
[ "function", "findCollectionName", "(", "entityName", ")", "{", "var", "xrmInternal", "=", "Utility", ".", "getXrmInternal", "(", ")", ";", "if", "(", "!", "Utility", ".", "isNull", "(", "xrmInternal", ")", ")", "{", "return", "xrmInternal", ".", "getEntitySetName", "(", "entityName", ")", "||", "entityName", ";", "}", "var", "collectionName", "=", "null", ";", "if", "(", "!", "Utility", ".", "isNull", "(", "_entityNames", ")", ")", "{", "collectionName", "=", "_entityNames", "[", "entityName", "]", ";", "if", "(", "Utility", ".", "isNull", "(", "collectionName", ")", ")", "{", "for", "(", "var", "key", "in", "_entityNames", ")", "{", "if", "(", "_entityNames", "[", "key", "]", "==", "entityName", ")", "{", "return", "entityName", ";", "}", "}", "}", "}", "return", "collectionName", ";", "}" ]
Searches for a collection name by provided entity name in a cached entity metadata. The returned collection name can be null. @param {string} entityName - entity name @returns {string} - a collection name
[ "Searches", "for", "a", "collection", "name", "by", "provided", "entity", "name", "in", "a", "cached", "entity", "metadata", ".", "The", "returned", "collection", "name", "can", "be", "null", "." ]
3ef9e2a010bafe439d71774325adc0b317024e5a
https://github.com/AleksandrRogov/DynamicsWebApi/blob/3ef9e2a010bafe439d71774325adc0b317024e5a/lib/requests/sendRequest.js#L14-L34
16,281
AleksandrRogov/DynamicsWebApi
lib/requests/sendRequest.js
sendRequest
function sendRequest(method, path, config, data, additionalHeaders, responseParams, successCallback, errorCallback, isBatch, isAsync) { additionalHeaders = additionalHeaders || {}; responseParams = responseParams || {}; //add response parameters to parse responseParseParams.push(responseParams); //stringify passed data var stringifiedData = stringifyData(data, config); if (isBatch) { batchRequestCollection.push({ method: method, path: path, config: config, data: stringifiedData, headers: additionalHeaders }); return; } if (path === '$batch') { var batchResult = BatchConverter.convertToBatch(batchRequestCollection); stringifiedData = batchResult.body; //clear an array of requests batchRequestCollection.length = 0; additionalHeaders = setStandardHeaders(additionalHeaders); additionalHeaders['Content-Type'] = 'multipart/mixed;boundary=' + batchResult.boundary; } else { additionalHeaders = setStandardHeaders(additionalHeaders); } responseParams.convertedToBatch = false; //if the URL contains more characters than max possible limit, convert the request to a batch request if (path.length > 2000) { var batchBoundary = 'dwa_batch_' + Utility.generateUUID(); var batchBody = []; batchBody.push('--' + batchBoundary); batchBody.push('Content-Type: application/http'); batchBody.push('Content-Transfer-Encoding: binary\n'); batchBody.push(method + ' ' + config.webApiUrl + path + ' HTTP/1.1'); for (var key in additionalHeaders) { if (key === 'Authorization') continue; batchBody.push(key + ': ' + additionalHeaders[key]); //authorization header is an exception. bug #27 delete additionalHeaders[key]; } batchBody.push('\n--' + batchBoundary + '--'); stringifiedData = batchBody.join('\n'); additionalHeaders = setStandardHeaders(additionalHeaders); additionalHeaders['Content-Type'] = 'multipart/mixed;boundary=' + batchBoundary; path = '$batch'; method = 'POST'; responseParams.convertedToBatch = true; } if (config.impersonate && !additionalHeaders['MSCRMCallerID']) { additionalHeaders['MSCRMCallerID'] = config.impersonate; } var executeRequest; /* develblock:start */ if (typeof XMLHttpRequest !== 'undefined') { /* develblock:end */ executeRequest = require('./xhr'); /* develblock:start */ } else if (typeof process !== 'undefined') { executeRequest = require('./http'); } /* develblock:end */ var sendInternalRequest = function (token) { if (token) { if (!additionalHeaders) { additionalHeaders = {}; } additionalHeaders['Authorization'] = 'Bearer ' + (token.hasOwnProperty('accessToken') ? token.accessToken : token); } executeRequest({ method: method, uri: config.webApiUrl + path, data: stringifiedData, additionalHeaders: additionalHeaders, responseParams: responseParseParams, successCallback: successCallback, errorCallback: errorCallback, isAsync: isAsync, timeout: config.timeout }); }; //call a token refresh callback only if it is set and there is no "Authorization" header set yet if (config.onTokenRefresh && (!additionalHeaders || (additionalHeaders && !additionalHeaders['Authorization']))) { config.onTokenRefresh(sendInternalRequest); } else { sendInternalRequest(); } }
javascript
function sendRequest(method, path, config, data, additionalHeaders, responseParams, successCallback, errorCallback, isBatch, isAsync) { additionalHeaders = additionalHeaders || {}; responseParams = responseParams || {}; //add response parameters to parse responseParseParams.push(responseParams); //stringify passed data var stringifiedData = stringifyData(data, config); if (isBatch) { batchRequestCollection.push({ method: method, path: path, config: config, data: stringifiedData, headers: additionalHeaders }); return; } if (path === '$batch') { var batchResult = BatchConverter.convertToBatch(batchRequestCollection); stringifiedData = batchResult.body; //clear an array of requests batchRequestCollection.length = 0; additionalHeaders = setStandardHeaders(additionalHeaders); additionalHeaders['Content-Type'] = 'multipart/mixed;boundary=' + batchResult.boundary; } else { additionalHeaders = setStandardHeaders(additionalHeaders); } responseParams.convertedToBatch = false; //if the URL contains more characters than max possible limit, convert the request to a batch request if (path.length > 2000) { var batchBoundary = 'dwa_batch_' + Utility.generateUUID(); var batchBody = []; batchBody.push('--' + batchBoundary); batchBody.push('Content-Type: application/http'); batchBody.push('Content-Transfer-Encoding: binary\n'); batchBody.push(method + ' ' + config.webApiUrl + path + ' HTTP/1.1'); for (var key in additionalHeaders) { if (key === 'Authorization') continue; batchBody.push(key + ': ' + additionalHeaders[key]); //authorization header is an exception. bug #27 delete additionalHeaders[key]; } batchBody.push('\n--' + batchBoundary + '--'); stringifiedData = batchBody.join('\n'); additionalHeaders = setStandardHeaders(additionalHeaders); additionalHeaders['Content-Type'] = 'multipart/mixed;boundary=' + batchBoundary; path = '$batch'; method = 'POST'; responseParams.convertedToBatch = true; } if (config.impersonate && !additionalHeaders['MSCRMCallerID']) { additionalHeaders['MSCRMCallerID'] = config.impersonate; } var executeRequest; /* develblock:start */ if (typeof XMLHttpRequest !== 'undefined') { /* develblock:end */ executeRequest = require('./xhr'); /* develblock:start */ } else if (typeof process !== 'undefined') { executeRequest = require('./http'); } /* develblock:end */ var sendInternalRequest = function (token) { if (token) { if (!additionalHeaders) { additionalHeaders = {}; } additionalHeaders['Authorization'] = 'Bearer ' + (token.hasOwnProperty('accessToken') ? token.accessToken : token); } executeRequest({ method: method, uri: config.webApiUrl + path, data: stringifiedData, additionalHeaders: additionalHeaders, responseParams: responseParseParams, successCallback: successCallback, errorCallback: errorCallback, isAsync: isAsync, timeout: config.timeout }); }; //call a token refresh callback only if it is set and there is no "Authorization" header set yet if (config.onTokenRefresh && (!additionalHeaders || (additionalHeaders && !additionalHeaders['Authorization']))) { config.onTokenRefresh(sendInternalRequest); } else { sendInternalRequest(); } }
[ "function", "sendRequest", "(", "method", ",", "path", ",", "config", ",", "data", ",", "additionalHeaders", ",", "responseParams", ",", "successCallback", ",", "errorCallback", ",", "isBatch", ",", "isAsync", ")", "{", "additionalHeaders", "=", "additionalHeaders", "||", "{", "}", ";", "responseParams", "=", "responseParams", "||", "{", "}", ";", "//add response parameters to parse", "responseParseParams", ".", "push", "(", "responseParams", ")", ";", "//stringify passed data", "var", "stringifiedData", "=", "stringifyData", "(", "data", ",", "config", ")", ";", "if", "(", "isBatch", ")", "{", "batchRequestCollection", ".", "push", "(", "{", "method", ":", "method", ",", "path", ":", "path", ",", "config", ":", "config", ",", "data", ":", "stringifiedData", ",", "headers", ":", "additionalHeaders", "}", ")", ";", "return", ";", "}", "if", "(", "path", "===", "'$batch'", ")", "{", "var", "batchResult", "=", "BatchConverter", ".", "convertToBatch", "(", "batchRequestCollection", ")", ";", "stringifiedData", "=", "batchResult", ".", "body", ";", "//clear an array of requests", "batchRequestCollection", ".", "length", "=", "0", ";", "additionalHeaders", "=", "setStandardHeaders", "(", "additionalHeaders", ")", ";", "additionalHeaders", "[", "'Content-Type'", "]", "=", "'multipart/mixed;boundary='", "+", "batchResult", ".", "boundary", ";", "}", "else", "{", "additionalHeaders", "=", "setStandardHeaders", "(", "additionalHeaders", ")", ";", "}", "responseParams", ".", "convertedToBatch", "=", "false", ";", "//if the URL contains more characters than max possible limit, convert the request to a batch request", "if", "(", "path", ".", "length", ">", "2000", ")", "{", "var", "batchBoundary", "=", "'dwa_batch_'", "+", "Utility", ".", "generateUUID", "(", ")", ";", "var", "batchBody", "=", "[", "]", ";", "batchBody", ".", "push", "(", "'--'", "+", "batchBoundary", ")", ";", "batchBody", ".", "push", "(", "'Content-Type: application/http'", ")", ";", "batchBody", ".", "push", "(", "'Content-Transfer-Encoding: binary\\n'", ")", ";", "batchBody", ".", "push", "(", "method", "+", "' '", "+", "config", ".", "webApiUrl", "+", "path", "+", "' HTTP/1.1'", ")", ";", "for", "(", "var", "key", "in", "additionalHeaders", ")", "{", "if", "(", "key", "===", "'Authorization'", ")", "continue", ";", "batchBody", ".", "push", "(", "key", "+", "': '", "+", "additionalHeaders", "[", "key", "]", ")", ";", "//authorization header is an exception. bug #27", "delete", "additionalHeaders", "[", "key", "]", ";", "}", "batchBody", ".", "push", "(", "'\\n--'", "+", "batchBoundary", "+", "'--'", ")", ";", "stringifiedData", "=", "batchBody", ".", "join", "(", "'\\n'", ")", ";", "additionalHeaders", "=", "setStandardHeaders", "(", "additionalHeaders", ")", ";", "additionalHeaders", "[", "'Content-Type'", "]", "=", "'multipart/mixed;boundary='", "+", "batchBoundary", ";", "path", "=", "'$batch'", ";", "method", "=", "'POST'", ";", "responseParams", ".", "convertedToBatch", "=", "true", ";", "}", "if", "(", "config", ".", "impersonate", "&&", "!", "additionalHeaders", "[", "'MSCRMCallerID'", "]", ")", "{", "additionalHeaders", "[", "'MSCRMCallerID'", "]", "=", "config", ".", "impersonate", ";", "}", "var", "executeRequest", ";", "/* develblock:start */", "if", "(", "typeof", "XMLHttpRequest", "!==", "'undefined'", ")", "{", "/* develblock:end */", "executeRequest", "=", "require", "(", "'./xhr'", ")", ";", "/* develblock:start */", "}", "else", "if", "(", "typeof", "process", "!==", "'undefined'", ")", "{", "executeRequest", "=", "require", "(", "'./http'", ")", ";", "}", "/* develblock:end */", "var", "sendInternalRequest", "=", "function", "(", "token", ")", "{", "if", "(", "token", ")", "{", "if", "(", "!", "additionalHeaders", ")", "{", "additionalHeaders", "=", "{", "}", ";", "}", "additionalHeaders", "[", "'Authorization'", "]", "=", "'Bearer '", "+", "(", "token", ".", "hasOwnProperty", "(", "'accessToken'", ")", "?", "token", ".", "accessToken", ":", "token", ")", ";", "}", "executeRequest", "(", "{", "method", ":", "method", ",", "uri", ":", "config", ".", "webApiUrl", "+", "path", ",", "data", ":", "stringifiedData", ",", "additionalHeaders", ":", "additionalHeaders", ",", "responseParams", ":", "responseParseParams", ",", "successCallback", ":", "successCallback", ",", "errorCallback", ":", "errorCallback", ",", "isAsync", ":", "isAsync", ",", "timeout", ":", "config", ".", "timeout", "}", ")", ";", "}", ";", "//call a token refresh callback only if it is set and there is no \"Authorization\" header set yet", "if", "(", "config", ".", "onTokenRefresh", "&&", "(", "!", "additionalHeaders", "||", "(", "additionalHeaders", "&&", "!", "additionalHeaders", "[", "'Authorization'", "]", ")", ")", ")", "{", "config", ".", "onTokenRefresh", "(", "sendInternalRequest", ")", ";", "}", "else", "{", "sendInternalRequest", "(", ")", ";", "}", "}" ]
Sends a request to given URL with given parameters @param {string} method - Method of the request. @param {string} path - Request path. @param {Object} config - DynamicsWebApi config. @param {Object} [data] - Data to send in the request. @param {Object} [additionalHeaders] - Object with additional headers. IMPORTANT! This object does not contain default headers needed for every request. @param {any} [responseParams] - parameters for parsing the response @param {Function} successCallback - A callback called on success of the request. @param {Function} errorCallback - A callback called when a request failed. @param {boolean} [isBatch] - Indicates whether the request is a Batch request or not. Default: false @param {boolean} [isAsync] - Indicates whether the request should be made synchronously or asynchronously.
[ "Sends", "a", "request", "to", "given", "URL", "with", "given", "parameters" ]
3ef9e2a010bafe439d71774325adc0b317024e5a
https://github.com/AleksandrRogov/DynamicsWebApi/blob/3ef9e2a010bafe439d71774325adc0b317024e5a/lib/requests/sendRequest.js#L112-L226
16,282
nikku/camunda-worker-node
lib/engine/api.js
getSerializedType
function getSerializedType(value, descriptor) { if (value instanceof SerializedVariable) { return 'SerializedVariable'; } else if (descriptor) { return descriptor.type; } else if (value instanceof Date) { return 'Date'; } else if (typeof value === 'object') { return 'Json'; } else if (typeof value === 'boolean') { return 'Boolean'; } else if (typeof value === 'number') { return 'Double'; } else { return 'String'; } }
javascript
function getSerializedType(value, descriptor) { if (value instanceof SerializedVariable) { return 'SerializedVariable'; } else if (descriptor) { return descriptor.type; } else if (value instanceof Date) { return 'Date'; } else if (typeof value === 'object') { return 'Json'; } else if (typeof value === 'boolean') { return 'Boolean'; } else if (typeof value === 'number') { return 'Double'; } else { return 'String'; } }
[ "function", "getSerializedType", "(", "value", ",", "descriptor", ")", "{", "if", "(", "value", "instanceof", "SerializedVariable", ")", "{", "return", "'SerializedVariable'", ";", "}", "else", "if", "(", "descriptor", ")", "{", "return", "descriptor", ".", "type", ";", "}", "else", "if", "(", "value", "instanceof", "Date", ")", "{", "return", "'Date'", ";", "}", "else", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "return", "'Json'", ";", "}", "else", "if", "(", "typeof", "value", "===", "'boolean'", ")", "{", "return", "'Boolean'", ";", "}", "else", "if", "(", "typeof", "value", "===", "'number'", ")", "{", "return", "'Double'", ";", "}", "else", "{", "return", "'String'", ";", "}", "}" ]
Get serialized type for given value
[ "Get", "serialized", "type", "for", "given", "value" ]
705b105e99ed6bcff873b0f1bcc42bf11664c459
https://github.com/nikku/camunda-worker-node/blob/705b105e99ed6bcff873b0f1bcc42bf11664c459/lib/engine/api.js#L79-L106
16,283
nikku/camunda-worker-node
lib/auth.js
createAuth
function createAuth(type, token) { if (!type) { throw new Error('<type> required'); } if (!token) { throw new Error('<token> required'); } /** * Actual middleware that appends a `Authorization: "${type} ${token}"` * header to the request options. */ return function(worker) { const workerOptions = worker.options; const requestOptions = workerOptions.requestOptions || {}; const headers = requestOptions.headers || {}; worker.options = { ...workerOptions, requestOptions: { ...requestOptions, headers: { ...headers, Authorization: `${type} ${token}` } } }; }; }
javascript
function createAuth(type, token) { if (!type) { throw new Error('<type> required'); } if (!token) { throw new Error('<token> required'); } /** * Actual middleware that appends a `Authorization: "${type} ${token}"` * header to the request options. */ return function(worker) { const workerOptions = worker.options; const requestOptions = workerOptions.requestOptions || {}; const headers = requestOptions.headers || {}; worker.options = { ...workerOptions, requestOptions: { ...requestOptions, headers: { ...headers, Authorization: `${type} ${token}` } } }; }; }
[ "function", "createAuth", "(", "type", ",", "token", ")", "{", "if", "(", "!", "type", ")", "{", "throw", "new", "Error", "(", "'<type> required'", ")", ";", "}", "if", "(", "!", "token", ")", "{", "throw", "new", "Error", "(", "'<token> required'", ")", ";", "}", "/**\n * Actual middleware that appends a `Authorization: \"${type} ${token}\"`\n * header to the request options.\n */", "return", "function", "(", "worker", ")", "{", "const", "workerOptions", "=", "worker", ".", "options", ";", "const", "requestOptions", "=", "workerOptions", ".", "requestOptions", "||", "{", "}", ";", "const", "headers", "=", "requestOptions", ".", "headers", "||", "{", "}", ";", "worker", ".", "options", "=", "{", "...", "workerOptions", ",", "requestOptions", ":", "{", "...", "requestOptions", ",", "headers", ":", "{", "...", "headers", ",", "Authorization", ":", "`", "${", "type", "}", "${", "token", "}", "`", "}", "}", "}", ";", "}", ";", "}" ]
Set arbitrary authorization tokens on Engine API requests. @example Worker(engineEndpoint, { use: [ Auth('Bearer', 'BEARER_TOKEN') ] });
[ "Set", "arbitrary", "authorization", "tokens", "on", "Engine", "API", "requests", "." ]
705b105e99ed6bcff873b0f1bcc42bf11664c459
https://github.com/nikku/camunda-worker-node/blob/705b105e99ed6bcff873b0f1bcc42bf11664c459/lib/auth.js#L14-L45
16,284
nikku/camunda-worker-node
lib/worker.js
Worker
function Worker(baseUrl, opts = {}) { if (!(this instanceof Worker)) { return new Worker(baseUrl, opts); } // inheritance Emitter.call(this); this.options = extend({ workerId: uuid.v4() }, defaultOptions, opts); this.subscriptions = {}; this.state = STATE_NEW; // apply extensions if (this.options.use) { this.extend(this.options.use); } // local variables this.engineApi = new EngineApi( baseUrl, this.options.requestOptions, this.options.apiVersion ); if (this.options.pollingDelay) { throw new Error('options.pollingDelay got replaced with options.autoPoll'); } // start if (this.options.autoPoll) { this.start(); } }
javascript
function Worker(baseUrl, opts = {}) { if (!(this instanceof Worker)) { return new Worker(baseUrl, opts); } // inheritance Emitter.call(this); this.options = extend({ workerId: uuid.v4() }, defaultOptions, opts); this.subscriptions = {}; this.state = STATE_NEW; // apply extensions if (this.options.use) { this.extend(this.options.use); } // local variables this.engineApi = new EngineApi( baseUrl, this.options.requestOptions, this.options.apiVersion ); if (this.options.pollingDelay) { throw new Error('options.pollingDelay got replaced with options.autoPoll'); } // start if (this.options.autoPoll) { this.start(); } }
[ "function", "Worker", "(", "baseUrl", ",", "opts", "=", "{", "}", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Worker", ")", ")", "{", "return", "new", "Worker", "(", "baseUrl", ",", "opts", ")", ";", "}", "// inheritance", "Emitter", ".", "call", "(", "this", ")", ";", "this", ".", "options", "=", "extend", "(", "{", "workerId", ":", "uuid", ".", "v4", "(", ")", "}", ",", "defaultOptions", ",", "opts", ")", ";", "this", ".", "subscriptions", "=", "{", "}", ";", "this", ".", "state", "=", "STATE_NEW", ";", "// apply extensions", "if", "(", "this", ".", "options", ".", "use", ")", "{", "this", ".", "extend", "(", "this", ".", "options", ".", "use", ")", ";", "}", "// local variables", "this", ".", "engineApi", "=", "new", "EngineApi", "(", "baseUrl", ",", "this", ".", "options", ".", "requestOptions", ",", "this", ".", "options", ".", "apiVersion", ")", ";", "if", "(", "this", ".", "options", ".", "pollingDelay", ")", "{", "throw", "new", "Error", "(", "'options.pollingDelay got replaced with options.autoPoll'", ")", ";", "}", "// start", "if", "(", "this", ".", "options", ".", "autoPoll", ")", "{", "this", ".", "start", "(", ")", ";", "}", "}" ]
Instantiate a worker. @param {String} baseUrl @param {Object} [opts={}]
[ "Instantiate", "a", "worker", "." ]
705b105e99ed6bcff873b0f1bcc42bf11664c459
https://github.com/nikku/camunda-worker-node/blob/705b105e99ed6bcff873b0f1bcc42bf11664c459/lib/worker.js#L41-L78
16,285
nikku/camunda-worker-node
lib/basic-auth.js
createBasicAuth
function createBasicAuth(username, password) { if (!username) { throw new Error('<username> required'); } if (typeof password === 'undefined') { throw new Error('<password> required'); } const token = base64encode(`${username}:${password}`); return auth('Basic', token); }
javascript
function createBasicAuth(username, password) { if (!username) { throw new Error('<username> required'); } if (typeof password === 'undefined') { throw new Error('<password> required'); } const token = base64encode(`${username}:${password}`); return auth('Basic', token); }
[ "function", "createBasicAuth", "(", "username", ",", "password", ")", "{", "if", "(", "!", "username", ")", "{", "throw", "new", "Error", "(", "'<username> required'", ")", ";", "}", "if", "(", "typeof", "password", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'<password> required'", ")", ";", "}", "const", "token", "=", "base64encode", "(", "`", "${", "username", "}", "${", "password", "}", "`", ")", ";", "return", "auth", "(", "'Basic'", ",", "token", ")", ";", "}" ]
Set username + password credentials on Engine API requests. @example Worker(engineEndpoint, { use: [ BasicAuth('Walt', 'SECRET_PASSWORD') ] });
[ "Set", "username", "+", "password", "credentials", "on", "Engine", "API", "requests", "." ]
705b105e99ed6bcff873b0f1bcc42bf11664c459
https://github.com/nikku/camunda-worker-node/blob/705b105e99ed6bcff873b0f1bcc42bf11664c459/lib/basic-auth.js#L16-L29
16,286
nikku/camunda-worker-node
lib/logger.js
Logger
function Logger(worker) { forEach([ 'start', 'stop', 'reschedule', 'error', 'poll', 'poll:done', 'poll:error', 'fetchTasks', 'fetchTasks:failed', 'fetchTasks:success', 'worker:register', 'worker:remove', 'executeTask', 'executeTask:complete', 'executeTask:complete:sent', 'executeTask:failed', 'executeTask:failed:sent', 'executeTask:done', 'executeTask:skip', 'executeTasks', 'executeTasks:done', 'extendLock', 'extendLock:success', 'extendLock:failed', ], function(event) { worker.on(event, function(...args) { debug(event, ...args); }); }); }
javascript
function Logger(worker) { forEach([ 'start', 'stop', 'reschedule', 'error', 'poll', 'poll:done', 'poll:error', 'fetchTasks', 'fetchTasks:failed', 'fetchTasks:success', 'worker:register', 'worker:remove', 'executeTask', 'executeTask:complete', 'executeTask:complete:sent', 'executeTask:failed', 'executeTask:failed:sent', 'executeTask:done', 'executeTask:skip', 'executeTasks', 'executeTasks:done', 'extendLock', 'extendLock:success', 'extendLock:failed', ], function(event) { worker.on(event, function(...args) { debug(event, ...args); }); }); }
[ "function", "Logger", "(", "worker", ")", "{", "forEach", "(", "[", "'start'", ",", "'stop'", ",", "'reschedule'", ",", "'error'", ",", "'poll'", ",", "'poll:done'", ",", "'poll:error'", ",", "'fetchTasks'", ",", "'fetchTasks:failed'", ",", "'fetchTasks:success'", ",", "'worker:register'", ",", "'worker:remove'", ",", "'executeTask'", ",", "'executeTask:complete'", ",", "'executeTask:complete:sent'", ",", "'executeTask:failed'", ",", "'executeTask:failed:sent'", ",", "'executeTask:done'", ",", "'executeTask:skip'", ",", "'executeTasks'", ",", "'executeTasks:done'", ",", "'extendLock'", ",", "'extendLock:success'", ",", "'extendLock:failed'", ",", "]", ",", "function", "(", "event", ")", "{", "worker", ".", "on", "(", "event", ",", "function", "(", "...", "args", ")", "{", "debug", "(", "event", ",", "...", "args", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Enable detailed task worker logging. @example var worker = Worker(engineEndpoint, { use: [ Logger ] });
[ "Enable", "detailed", "task", "worker", "logging", "." ]
705b105e99ed6bcff873b0f1bcc42bf11664c459
https://github.com/nikku/camunda-worker-node/blob/705b105e99ed6bcff873b0f1bcc42bf11664c459/lib/logger.js#L18-L52
16,287
nikku/camunda-worker-node
lib/metrics.js
Metric
function Metric(worker) { var tasksExecutedCount = 0; var pollCount = 0; var executionTime = 0; var pollTime = 0; var idleTime = 0; var activeTasks = 0; worker.on('executeTask', function() { activeTasks++; }); worker.on('executeTask:done', function(task, durationMs) { tasksExecutedCount++; activeTasks--; executionTime += durationMs; }); worker.on('poll', function() { pollCount++; }); worker.on('poll:done', function(reason, durationMs) { pollTime += durationMs; }); worker.on('reschedule', function(waitMs) { idleTime += waitMs; }); function printStats() { debug('stats', { executionTime, pollTime, idleTime, pollCount, tasksExecutedCount, activeTasks }); executionTime = 0; pollTime = 0; idleTime = 0; pollCount = 0; tasksExecutedCount = 0; } var timer; worker.on('start', () => { printStats(); timer = setInterval(printStats, 5000); }); worker.on('stop', () => { if (timer) { clearInterval(timer); } timer = null; }); }
javascript
function Metric(worker) { var tasksExecutedCount = 0; var pollCount = 0; var executionTime = 0; var pollTime = 0; var idleTime = 0; var activeTasks = 0; worker.on('executeTask', function() { activeTasks++; }); worker.on('executeTask:done', function(task, durationMs) { tasksExecutedCount++; activeTasks--; executionTime += durationMs; }); worker.on('poll', function() { pollCount++; }); worker.on('poll:done', function(reason, durationMs) { pollTime += durationMs; }); worker.on('reschedule', function(waitMs) { idleTime += waitMs; }); function printStats() { debug('stats', { executionTime, pollTime, idleTime, pollCount, tasksExecutedCount, activeTasks }); executionTime = 0; pollTime = 0; idleTime = 0; pollCount = 0; tasksExecutedCount = 0; } var timer; worker.on('start', () => { printStats(); timer = setInterval(printStats, 5000); }); worker.on('stop', () => { if (timer) { clearInterval(timer); } timer = null; }); }
[ "function", "Metric", "(", "worker", ")", "{", "var", "tasksExecutedCount", "=", "0", ";", "var", "pollCount", "=", "0", ";", "var", "executionTime", "=", "0", ";", "var", "pollTime", "=", "0", ";", "var", "idleTime", "=", "0", ";", "var", "activeTasks", "=", "0", ";", "worker", ".", "on", "(", "'executeTask'", ",", "function", "(", ")", "{", "activeTasks", "++", ";", "}", ")", ";", "worker", ".", "on", "(", "'executeTask:done'", ",", "function", "(", "task", ",", "durationMs", ")", "{", "tasksExecutedCount", "++", ";", "activeTasks", "--", ";", "executionTime", "+=", "durationMs", ";", "}", ")", ";", "worker", ".", "on", "(", "'poll'", ",", "function", "(", ")", "{", "pollCount", "++", ";", "}", ")", ";", "worker", ".", "on", "(", "'poll:done'", ",", "function", "(", "reason", ",", "durationMs", ")", "{", "pollTime", "+=", "durationMs", ";", "}", ")", ";", "worker", ".", "on", "(", "'reschedule'", ",", "function", "(", "waitMs", ")", "{", "idleTime", "+=", "waitMs", ";", "}", ")", ";", "function", "printStats", "(", ")", "{", "debug", "(", "'stats'", ",", "{", "executionTime", ",", "pollTime", ",", "idleTime", ",", "pollCount", ",", "tasksExecutedCount", ",", "activeTasks", "}", ")", ";", "executionTime", "=", "0", ";", "pollTime", "=", "0", ";", "idleTime", "=", "0", ";", "pollCount", "=", "0", ";", "tasksExecutedCount", "=", "0", ";", "}", "var", "timer", ";", "worker", ".", "on", "(", "'start'", ",", "(", ")", "=>", "{", "printStats", "(", ")", ";", "timer", "=", "setInterval", "(", "printStats", ",", "5000", ")", ";", "}", ")", ";", "worker", ".", "on", "(", "'stop'", ",", "(", ")", "=>", "{", "if", "(", "timer", ")", "{", "clearInterval", "(", "timer", ")", ";", "}", "timer", "=", "null", ";", "}", ")", ";", "}" ]
Periodically log worker utilization metrics. @example worker(engineEndpoint, { use: [ Metrics ] });
[ "Periodically", "log", "worker", "utilization", "metrics", "." ]
705b105e99ed6bcff873b0f1bcc42bf11664c459
https://github.com/nikku/camunda-worker-node/blob/705b105e99ed6bcff873b0f1bcc42bf11664c459/lib/metrics.js#L16-L82
16,288
Streampunk/macadam
index.js
Capture
function Capture (deviceIndex, displayMode, pixelFormat) { this.deviceIndex = deviceIndex; this.displayMode = displayMode; this.pixelFormat = pixelFormat; this.emergencyBrake = null; if (arguments.length !== 3 || typeof deviceIndex !== 'number' || typeof displayMode !== 'number' || typeof pixelFormat !== 'number' ) { this.emit('error', new Error('Capture requires three number arguments: ' + 'device index, display mode and pixel format')); } else { this.capture = macadamNative.capture({ deviceIndex: deviceIndex, displayMode: displayMode, pixelFormat: pixelFormat });//.catch(err => { this.emit('error', err); }); this.capture.then(x => { this.emergencyBrake = x; }); this.running = true; /* process.on('exit', function () { console.log('Exiting node.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.emergencyBrake = null; process.exit(0); }); */ process.on('SIGINT', () => { console.log('Received SIGINT.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.emergencyBrake = null; this.running = false; process.exit(); }); EventEmitter.call(this); } }
javascript
function Capture (deviceIndex, displayMode, pixelFormat) { this.deviceIndex = deviceIndex; this.displayMode = displayMode; this.pixelFormat = pixelFormat; this.emergencyBrake = null; if (arguments.length !== 3 || typeof deviceIndex !== 'number' || typeof displayMode !== 'number' || typeof pixelFormat !== 'number' ) { this.emit('error', new Error('Capture requires three number arguments: ' + 'device index, display mode and pixel format')); } else { this.capture = macadamNative.capture({ deviceIndex: deviceIndex, displayMode: displayMode, pixelFormat: pixelFormat });//.catch(err => { this.emit('error', err); }); this.capture.then(x => { this.emergencyBrake = x; }); this.running = true; /* process.on('exit', function () { console.log('Exiting node.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.emergencyBrake = null; process.exit(0); }); */ process.on('SIGINT', () => { console.log('Received SIGINT.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.emergencyBrake = null; this.running = false; process.exit(); }); EventEmitter.call(this); } }
[ "function", "Capture", "(", "deviceIndex", ",", "displayMode", ",", "pixelFormat", ")", "{", "this", ".", "deviceIndex", "=", "deviceIndex", ";", "this", ".", "displayMode", "=", "displayMode", ";", "this", ".", "pixelFormat", "=", "pixelFormat", ";", "this", ".", "emergencyBrake", "=", "null", ";", "if", "(", "arguments", ".", "length", "!==", "3", "||", "typeof", "deviceIndex", "!==", "'number'", "||", "typeof", "displayMode", "!==", "'number'", "||", "typeof", "pixelFormat", "!==", "'number'", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "Error", "(", "'Capture requires three number arguments: '", "+", "'device index, display mode and pixel format'", ")", ")", ";", "}", "else", "{", "this", ".", "capture", "=", "macadamNative", ".", "capture", "(", "{", "deviceIndex", ":", "deviceIndex", ",", "displayMode", ":", "displayMode", ",", "pixelFormat", ":", "pixelFormat", "}", ")", ";", "//.catch(err => { this.emit('error', err); });", "this", ".", "capture", ".", "then", "(", "x", "=>", "{", "this", ".", "emergencyBrake", "=", "x", ";", "}", ")", ";", "this", ".", "running", "=", "true", ";", "/* process.on('exit', function () {\n console.log('Exiting node.');\n if (this.emergencyBrake) this.emergencyBrake.stop();\n this.emergencyBrake = null;\n process.exit(0);\n }); */", "process", ".", "on", "(", "'SIGINT'", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "'Received SIGINT.'", ")", ";", "if", "(", "this", ".", "emergencyBrake", ")", "this", ".", "emergencyBrake", ".", "stop", "(", ")", ";", "this", ".", "emergencyBrake", "=", "null", ";", "this", ".", "running", "=", "false", ";", "process", ".", "exit", "(", ")", ";", "}", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "}", "}" ]
Capture class is deprecated
[ "Capture", "class", "is", "deprecated" ]
b85b7b9b06415aeb896009fa05194c1dc1ce8616
https://github.com/Streampunk/macadam/blob/b85b7b9b06415aeb896009fa05194c1dc1ce8616/index.js#L57-L89
16,289
Streampunk/macadam
index.js
Playback
function Playback (deviceIndex, displayMode, pixelFormat) { this.index = 0; this.deviceIndex = deviceIndex; this.displayMode = displayMode; this.pixelFormat = pixelFormat; this.running = true; this.emergencyBrake = null; if (arguments.length !== 3 || typeof deviceIndex !== 'number' || typeof displayMode !== 'number' || typeof pixelFormat !== 'number' ) { this.emit('error', new Error('Playback requires three number arguments: ' + 'index, display mode and pixel format')); } else { this.playback = macadamNative.playback({ deviceIndex: deviceIndex, displayMode: displayMode, pixelFormat: pixelFormat }).catch(err => { this.emit('error', err); }); /* process.on('exit', function () { console.log('Exiting node.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.running = false; process.exit(0); }); */ process.on('SIGINT', () => { console.log('Received SIGINT.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.running = false; process.exit(); }); } EventEmitter.call(this); }
javascript
function Playback (deviceIndex, displayMode, pixelFormat) { this.index = 0; this.deviceIndex = deviceIndex; this.displayMode = displayMode; this.pixelFormat = pixelFormat; this.running = true; this.emergencyBrake = null; if (arguments.length !== 3 || typeof deviceIndex !== 'number' || typeof displayMode !== 'number' || typeof pixelFormat !== 'number' ) { this.emit('error', new Error('Playback requires three number arguments: ' + 'index, display mode and pixel format')); } else { this.playback = macadamNative.playback({ deviceIndex: deviceIndex, displayMode: displayMode, pixelFormat: pixelFormat }).catch(err => { this.emit('error', err); }); /* process.on('exit', function () { console.log('Exiting node.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.running = false; process.exit(0); }); */ process.on('SIGINT', () => { console.log('Received SIGINT.'); if (this.emergencyBrake) this.emergencyBrake.stop(); this.running = false; process.exit(); }); } EventEmitter.call(this); }
[ "function", "Playback", "(", "deviceIndex", ",", "displayMode", ",", "pixelFormat", ")", "{", "this", ".", "index", "=", "0", ";", "this", ".", "deviceIndex", "=", "deviceIndex", ";", "this", ".", "displayMode", "=", "displayMode", ";", "this", ".", "pixelFormat", "=", "pixelFormat", ";", "this", ".", "running", "=", "true", ";", "this", ".", "emergencyBrake", "=", "null", ";", "if", "(", "arguments", ".", "length", "!==", "3", "||", "typeof", "deviceIndex", "!==", "'number'", "||", "typeof", "displayMode", "!==", "'number'", "||", "typeof", "pixelFormat", "!==", "'number'", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "Error", "(", "'Playback requires three number arguments: '", "+", "'index, display mode and pixel format'", ")", ")", ";", "}", "else", "{", "this", ".", "playback", "=", "macadamNative", ".", "playback", "(", "{", "deviceIndex", ":", "deviceIndex", ",", "displayMode", ":", "displayMode", ",", "pixelFormat", ":", "pixelFormat", "}", ")", ".", "catch", "(", "err", "=>", "{", "this", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "/* process.on('exit', function () {\n console.log('Exiting node.');\n if (this.emergencyBrake) this.emergencyBrake.stop();\n this.running = false;\n process.exit(0);\n }); */", "process", ".", "on", "(", "'SIGINT'", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "'Received SIGINT.'", ")", ";", "if", "(", "this", ".", "emergencyBrake", ")", "this", ".", "emergencyBrake", ".", "stop", "(", ")", ";", "this", ".", "running", "=", "false", ";", "process", ".", "exit", "(", ")", ";", "}", ")", ";", "}", "EventEmitter", ".", "call", "(", "this", ")", ";", "}" ]
Playback class is deprecated
[ "Playback", "class", "is", "deprecated" ]
b85b7b9b06415aeb896009fa05194c1dc1ce8616
https://github.com/Streampunk/macadam/blob/b85b7b9b06415aeb896009fa05194c1dc1ce8616/index.js#L130-L162
16,290
projectatomic/dockerfile_lint
lib/parser.js
parseJSON
function parseJSON(cmd) { try { var json = JSON.parse(cmd.rest); } catch (e) { return false; } // Ensure it's an array. if (!Array.isArray(json)) { return false; } // Ensure every entry in the array is a string. if (!json.every(function (entry) { return typeof(entry) === 'string'; })) { return false; } cmd.args = json; return true; }
javascript
function parseJSON(cmd) { try { var json = JSON.parse(cmd.rest); } catch (e) { return false; } // Ensure it's an array. if (!Array.isArray(json)) { return false; } // Ensure every entry in the array is a string. if (!json.every(function (entry) { return typeof(entry) === 'string'; })) { return false; } cmd.args = json; return true; }
[ "function", "parseJSON", "(", "cmd", ")", "{", "try", "{", "var", "json", "=", "JSON", ".", "parse", "(", "cmd", ".", "rest", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "// Ensure it's an array.", "if", "(", "!", "Array", ".", "isArray", "(", "json", ")", ")", "{", "return", "false", ";", "}", "// Ensure every entry in the array is a string.", "if", "(", "!", "json", ".", "every", "(", "function", "(", "entry", ")", "{", "return", "typeof", "(", "entry", ")", "===", "'string'", ";", "}", ")", ")", "{", "return", "false", ";", "}", "cmd", ".", "args", "=", "json", ";", "return", "true", ";", "}" ]
Converts to JSON array, returns true on success, false otherwise.
[ "Converts", "to", "JSON", "array", "returns", "true", "on", "success", "false", "otherwise", "." ]
625f957af62c5184423cbc017fdbc8e4a7383543
https://github.com/projectatomic/dockerfile_lint/blob/625f957af62c5184423cbc017fdbc8e4a7383543/lib/parser.js#L267-L288
16,291
projectatomic/dockerfile_lint
lib/parser.js
splitCommand
function splitCommand(line) { // Make sure we get the same results irrespective of leading/trailing spaces var match = line.match(TOKEN_WHITESPACE); if (!match) { return { name: line.toUpperCase(), rest: '' }; } var name = line.substr(0, match.index).toUpperCase(); var rest = line.substr(match.index + match[0].length); return { name: name, rest: rest }; }
javascript
function splitCommand(line) { // Make sure we get the same results irrespective of leading/trailing spaces var match = line.match(TOKEN_WHITESPACE); if (!match) { return { name: line.toUpperCase(), rest: '' }; } var name = line.substr(0, match.index).toUpperCase(); var rest = line.substr(match.index + match[0].length); return { name: name, rest: rest }; }
[ "function", "splitCommand", "(", "line", ")", "{", "// Make sure we get the same results irrespective of leading/trailing spaces", "var", "match", "=", "line", ".", "match", "(", "TOKEN_WHITESPACE", ")", ";", "if", "(", "!", "match", ")", "{", "return", "{", "name", ":", "line", ".", "toUpperCase", "(", ")", ",", "rest", ":", "''", "}", ";", "}", "var", "name", "=", "line", ".", "substr", "(", "0", ",", "match", ".", "index", ")", ".", "toUpperCase", "(", ")", ";", "var", "rest", "=", "line", ".", "substr", "(", "match", ".", "index", "+", "match", "[", "0", "]", ".", "length", ")", ";", "return", "{", "name", ":", "name", ",", "rest", ":", "rest", "}", ";", "}" ]
Takes a single line of text and parses out the cmd and rest, which are used for dispatching to more exact parsing functions.
[ "Takes", "a", "single", "line", "of", "text", "and", "parses", "out", "the", "cmd", "and", "rest", "which", "are", "used", "for", "dispatching", "to", "more", "exact", "parsing", "functions", "." ]
625f957af62c5184423cbc017fdbc8e4a7383543
https://github.com/projectatomic/dockerfile_lint/blob/625f957af62c5184423cbc017fdbc8e4a7383543/lib/parser.js#L341-L357
16,292
node-red/node-red-node-test-helper
index.js
findRuntimePath
function findRuntimePath() { const upPkg = readPkgUp.sync(); // case 1: we're in NR itself if (upPkg.pkg.name === 'node-red') { if (checkSemver(upPkg.pkg.version,"<0.20.0")) { return path.join(path.dirname(upPkg.path), upPkg.pkg.main); } else { return path.join(path.dirname(upPkg.path),"packages","node_modules","node-red"); } } // case 2: NR is resolvable from here try { return require.resolve('node-red'); } catch (ignored) {} // case 3: NR is installed alongside node-red-node-test-helper if ((upPkg.pkg.dependencies && upPkg.pkg.dependencies['node-red']) || (upPkg.pkg.devDependencies && upPkg.pkg.devDependencies['node-red'])) { const dirpath = path.join(path.dirname(upPkg.path), 'node_modules', 'node-red'); try { const pkg = require(path.join(dirpath, 'package.json')); return path.join(dirpath, pkg.main); } catch (ignored) {} } }
javascript
function findRuntimePath() { const upPkg = readPkgUp.sync(); // case 1: we're in NR itself if (upPkg.pkg.name === 'node-red') { if (checkSemver(upPkg.pkg.version,"<0.20.0")) { return path.join(path.dirname(upPkg.path), upPkg.pkg.main); } else { return path.join(path.dirname(upPkg.path),"packages","node_modules","node-red"); } } // case 2: NR is resolvable from here try { return require.resolve('node-red'); } catch (ignored) {} // case 3: NR is installed alongside node-red-node-test-helper if ((upPkg.pkg.dependencies && upPkg.pkg.dependencies['node-red']) || (upPkg.pkg.devDependencies && upPkg.pkg.devDependencies['node-red'])) { const dirpath = path.join(path.dirname(upPkg.path), 'node_modules', 'node-red'); try { const pkg = require(path.join(dirpath, 'package.json')); return path.join(dirpath, pkg.main); } catch (ignored) {} } }
[ "function", "findRuntimePath", "(", ")", "{", "const", "upPkg", "=", "readPkgUp", ".", "sync", "(", ")", ";", "// case 1: we're in NR itself", "if", "(", "upPkg", ".", "pkg", ".", "name", "===", "'node-red'", ")", "{", "if", "(", "checkSemver", "(", "upPkg", ".", "pkg", ".", "version", ",", "\"<0.20.0\"", ")", ")", "{", "return", "path", ".", "join", "(", "path", ".", "dirname", "(", "upPkg", ".", "path", ")", ",", "upPkg", ".", "pkg", ".", "main", ")", ";", "}", "else", "{", "return", "path", ".", "join", "(", "path", ".", "dirname", "(", "upPkg", ".", "path", ")", ",", "\"packages\"", ",", "\"node_modules\"", ",", "\"node-red\"", ")", ";", "}", "}", "// case 2: NR is resolvable from here", "try", "{", "return", "require", ".", "resolve", "(", "'node-red'", ")", ";", "}", "catch", "(", "ignored", ")", "{", "}", "// case 3: NR is installed alongside node-red-node-test-helper", "if", "(", "(", "upPkg", ".", "pkg", ".", "dependencies", "&&", "upPkg", ".", "pkg", ".", "dependencies", "[", "'node-red'", "]", ")", "||", "(", "upPkg", ".", "pkg", ".", "devDependencies", "&&", "upPkg", ".", "pkg", ".", "devDependencies", "[", "'node-red'", "]", ")", ")", "{", "const", "dirpath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "upPkg", ".", "path", ")", ",", "'node_modules'", ",", "'node-red'", ")", ";", "try", "{", "const", "pkg", "=", "require", "(", "path", ".", "join", "(", "dirpath", ",", "'package.json'", ")", ")", ";", "return", "path", ".", "join", "(", "dirpath", ",", "pkg", ".", "main", ")", ";", "}", "catch", "(", "ignored", ")", "{", "}", "}", "}" ]
Finds the NR runtime path by inspecting environment
[ "Finds", "the", "NR", "runtime", "path", "by", "inspecting", "environment" ]
d6695c2de7968364c624f743ca38b13a0b859558
https://github.com/node-red/node-red-node-test-helper/blob/d6695c2de7968364c624f743ca38b13a0b859558/index.js#L36-L59
16,293
node-red/node-red-node-test-helper
index.js
checkSemver
function checkSemver(localVersion,testRange) { var parts = localVersion.split("-"); return semver.satisfies(parts[0],testRange); }
javascript
function checkSemver(localVersion,testRange) { var parts = localVersion.split("-"); return semver.satisfies(parts[0],testRange); }
[ "function", "checkSemver", "(", "localVersion", ",", "testRange", ")", "{", "var", "parts", "=", "localVersion", ".", "split", "(", "\"-\"", ")", ";", "return", "semver", ".", "satisfies", "(", "parts", "[", "0", "]", ",", "testRange", ")", ";", "}" ]
As we have prerelease tags in development version, they need stripping off before semver will do a sensible comparison with a range.
[ "As", "we", "have", "prerelease", "tags", "in", "development", "version", "they", "need", "stripping", "off", "before", "semver", "will", "do", "a", "sensible", "comparison", "with", "a", "range", "." ]
d6695c2de7968364c624f743ca38b13a0b859558
https://github.com/node-red/node-red-node-test-helper/blob/d6695c2de7968364c624f743ca38b13a0b859558/index.js#L64-L67
16,294
graphology/graphology
src/iteration/neighbors.js
createNeighborArrayForNode
function createNeighborArrayForNode(type, direction, nodeData) { // If we want only undirected or in or out, we can roll some optimizations if (type !== 'mixed') { if (type === 'undirected') return Object.keys(nodeData.undirected); if (typeof direction === 'string') return Object.keys(nodeData[direction]); } // Else we need to keep a set of neighbors not to return duplicates const neighbors = new Set(); if (type !== 'undirected') { if (direction !== 'out') { merge(neighbors, nodeData.in); } if (direction !== 'in') { merge(neighbors, nodeData.out); } } if (type !== 'directed') { merge(neighbors, nodeData.undirected); } return take(neighbors.values(), neighbors.size); }
javascript
function createNeighborArrayForNode(type, direction, nodeData) { // If we want only undirected or in or out, we can roll some optimizations if (type !== 'mixed') { if (type === 'undirected') return Object.keys(nodeData.undirected); if (typeof direction === 'string') return Object.keys(nodeData[direction]); } // Else we need to keep a set of neighbors not to return duplicates const neighbors = new Set(); if (type !== 'undirected') { if (direction !== 'out') { merge(neighbors, nodeData.in); } if (direction !== 'in') { merge(neighbors, nodeData.out); } } if (type !== 'directed') { merge(neighbors, nodeData.undirected); } return take(neighbors.values(), neighbors.size); }
[ "function", "createNeighborArrayForNode", "(", "type", ",", "direction", ",", "nodeData", ")", "{", "// If we want only undirected or in or out, we can roll some optimizations", "if", "(", "type", "!==", "'mixed'", ")", "{", "if", "(", "type", "===", "'undirected'", ")", "return", "Object", ".", "keys", "(", "nodeData", ".", "undirected", ")", ";", "if", "(", "typeof", "direction", "===", "'string'", ")", "return", "Object", ".", "keys", "(", "nodeData", "[", "direction", "]", ")", ";", "}", "// Else we need to keep a set of neighbors not to return duplicates", "const", "neighbors", "=", "new", "Set", "(", ")", ";", "if", "(", "type", "!==", "'undirected'", ")", "{", "if", "(", "direction", "!==", "'out'", ")", "{", "merge", "(", "neighbors", ",", "nodeData", ".", "in", ")", ";", "}", "if", "(", "direction", "!==", "'in'", ")", "{", "merge", "(", "neighbors", ",", "nodeData", ".", "out", ")", ";", "}", "}", "if", "(", "type", "!==", "'directed'", ")", "{", "merge", "(", "neighbors", ",", "nodeData", ".", "undirected", ")", ";", "}", "return", "take", "(", "neighbors", ".", "values", "(", ")", ",", "neighbors", ".", "size", ")", ";", "}" ]
Function creating an array of relevant neighbors for the given node. @param {string} type - Type of neighbors. @param {string} direction - Direction. @param {any} nodeData - Target node's data. @return {Array} - The list of neighbors.
[ "Function", "creating", "an", "array", "of", "relevant", "neighbors", "for", "the", "given", "node", "." ]
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/neighbors.js#L77-L106
16,295
graphology/graphology
src/iteration/neighbors.js
forEachInObject
function forEachInObject(nodeData, object, callback) { for (const k in object) { let edgeData = object[k]; if (edgeData instanceof Set) edgeData = edgeData.values().next().value; const sourceData = edgeData.source, targetData = edgeData.target; const neighborData = sourceData === nodeData ? targetData : sourceData; callback( neighborData.key, neighborData.attributes ); } }
javascript
function forEachInObject(nodeData, object, callback) { for (const k in object) { let edgeData = object[k]; if (edgeData instanceof Set) edgeData = edgeData.values().next().value; const sourceData = edgeData.source, targetData = edgeData.target; const neighborData = sourceData === nodeData ? targetData : sourceData; callback( neighborData.key, neighborData.attributes ); } }
[ "function", "forEachInObject", "(", "nodeData", ",", "object", ",", "callback", ")", "{", "for", "(", "const", "k", "in", "object", ")", "{", "let", "edgeData", "=", "object", "[", "k", "]", ";", "if", "(", "edgeData", "instanceof", "Set", ")", "edgeData", "=", "edgeData", ".", "values", "(", ")", ".", "next", "(", ")", ".", "value", ";", "const", "sourceData", "=", "edgeData", ".", "source", ",", "targetData", "=", "edgeData", ".", "target", ";", "const", "neighborData", "=", "sourceData", "===", "nodeData", "?", "targetData", ":", "sourceData", ";", "callback", "(", "neighborData", ".", "key", ",", "neighborData", ".", "attributes", ")", ";", "}", "}" ]
Function iterating over the given node's relevant neighbors using a callback. @param {string} type - Type of neighbors. @param {string} direction - Direction. @param {any} nodeData - Target node's data. @param {function} callback - Callback to use.
[ "Function", "iterating", "over", "the", "given", "node", "s", "relevant", "neighbors", "using", "a", "callback", "." ]
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/neighbors.js#L117-L134
16,296
graphology/graphology
src/iteration/neighbors.js
nodeHasNeighbor
function nodeHasNeighbor(graph, type, direction, node, neighbor) { const nodeData = graph._nodes.get(node); if (type !== 'undirected') { if (direction !== 'out' && typeof nodeData.in !== 'undefined') { for (const k in nodeData.in) if (k === neighbor) return true; } if (direction !== 'in' && typeof nodeData.out !== 'undefined') { for (const k in nodeData.out) if (k === neighbor) return true; } } if (type !== 'directed' && typeof nodeData.undirected !== 'undefined') { for (const k in nodeData.undirected) if (k === neighbor) return true; } return false; }
javascript
function nodeHasNeighbor(graph, type, direction, node, neighbor) { const nodeData = graph._nodes.get(node); if (type !== 'undirected') { if (direction !== 'out' && typeof nodeData.in !== 'undefined') { for (const k in nodeData.in) if (k === neighbor) return true; } if (direction !== 'in' && typeof nodeData.out !== 'undefined') { for (const k in nodeData.out) if (k === neighbor) return true; } } if (type !== 'directed' && typeof nodeData.undirected !== 'undefined') { for (const k in nodeData.undirected) if (k === neighbor) return true; } return false; }
[ "function", "nodeHasNeighbor", "(", "graph", ",", "type", ",", "direction", ",", "node", ",", "neighbor", ")", "{", "const", "nodeData", "=", "graph", ".", "_nodes", ".", "get", "(", "node", ")", ";", "if", "(", "type", "!==", "'undirected'", ")", "{", "if", "(", "direction", "!==", "'out'", "&&", "typeof", "nodeData", ".", "in", "!==", "'undefined'", ")", "{", "for", "(", "const", "k", "in", "nodeData", ".", "in", ")", "if", "(", "k", "===", "neighbor", ")", "return", "true", ";", "}", "if", "(", "direction", "!==", "'in'", "&&", "typeof", "nodeData", ".", "out", "!==", "'undefined'", ")", "{", "for", "(", "const", "k", "in", "nodeData", ".", "out", ")", "if", "(", "k", "===", "neighbor", ")", "return", "true", ";", "}", "}", "if", "(", "type", "!==", "'directed'", "&&", "typeof", "nodeData", ".", "undirected", "!==", "'undefined'", ")", "{", "for", "(", "const", "k", "in", "nodeData", ".", "undirected", ")", "if", "(", "k", "===", "neighbor", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Function returning whether the given node has target neighbor. @param {Graph} graph - Target graph. @param {string} type - Type of neighbor. @param {string} direction - Direction. @param {any} node - Target node. @param {any} neighbor - Target neighbor. @return {boolean}
[ "Function", "returning", "whether", "the", "given", "node", "has", "target", "neighbor", "." ]
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/neighbors.js#L299-L324
16,297
graphology/graphology
src/iteration/neighbors.js
attachNeighborArrayCreator
function attachNeighborArrayCreator(Class, description) { const { name, type, direction } = description; /** * Function returning an array or the count of certain neighbors. * * Arity 1: Return all of a node's relevant neighbors. * @param {any} node - Target node. * * Arity 2: Return whether the two nodes are indeed neighbors. * @param {any} source - Source node. * @param {any} target - Target node. * * @return {array|number} - The neighbors or the number of neighbors. * * @throws {Error} - Will throw if there are too many arguments. */ Class.prototype[name] = function(node) { // Early termination if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type) return []; if (arguments.length === 2) { const node1 = '' + arguments[0], node2 = '' + arguments[1]; if (!this._nodes.has(node1)) throw new NotFoundGraphError(`Graph.${name}: could not find the "${node1}" node in the graph.`); if (!this._nodes.has(node2)) throw new NotFoundGraphError(`Graph.${name}: could not find the "${node2}" node in the graph.`); // Here, we want to assess whether the two given nodes are neighbors return nodeHasNeighbor( this, type, direction, node1, node2 ); } else if (arguments.length === 1) { node = '' + node; const nodeData = this._nodes.get(node); if (typeof nodeData === 'undefined') throw new NotFoundGraphError(`Graph.${name}: could not find the "${node}" node in the graph.`); // Here, we want to iterate over a node's relevant neighbors const neighbors = createNeighborArrayForNode( type === 'mixed' ? this.type : type, direction, nodeData ); return neighbors; } throw new InvalidArgumentsGraphError(`Graph.${name}: invalid number of arguments (expecting 1 or 2 and got ${arguments.length}).`); }; }
javascript
function attachNeighborArrayCreator(Class, description) { const { name, type, direction } = description; /** * Function returning an array or the count of certain neighbors. * * Arity 1: Return all of a node's relevant neighbors. * @param {any} node - Target node. * * Arity 2: Return whether the two nodes are indeed neighbors. * @param {any} source - Source node. * @param {any} target - Target node. * * @return {array|number} - The neighbors or the number of neighbors. * * @throws {Error} - Will throw if there are too many arguments. */ Class.prototype[name] = function(node) { // Early termination if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type) return []; if (arguments.length === 2) { const node1 = '' + arguments[0], node2 = '' + arguments[1]; if (!this._nodes.has(node1)) throw new NotFoundGraphError(`Graph.${name}: could not find the "${node1}" node in the graph.`); if (!this._nodes.has(node2)) throw new NotFoundGraphError(`Graph.${name}: could not find the "${node2}" node in the graph.`); // Here, we want to assess whether the two given nodes are neighbors return nodeHasNeighbor( this, type, direction, node1, node2 ); } else if (arguments.length === 1) { node = '' + node; const nodeData = this._nodes.get(node); if (typeof nodeData === 'undefined') throw new NotFoundGraphError(`Graph.${name}: could not find the "${node}" node in the graph.`); // Here, we want to iterate over a node's relevant neighbors const neighbors = createNeighborArrayForNode( type === 'mixed' ? this.type : type, direction, nodeData ); return neighbors; } throw new InvalidArgumentsGraphError(`Graph.${name}: invalid number of arguments (expecting 1 or 2 and got ${arguments.length}).`); }; }
[ "function", "attachNeighborArrayCreator", "(", "Class", ",", "description", ")", "{", "const", "{", "name", ",", "type", ",", "direction", "}", "=", "description", ";", "/**\n * Function returning an array or the count of certain neighbors.\n *\n * Arity 1: Return all of a node's relevant neighbors.\n * @param {any} node - Target node.\n *\n * Arity 2: Return whether the two nodes are indeed neighbors.\n * @param {any} source - Source node.\n * @param {any} target - Target node.\n *\n * @return {array|number} - The neighbors or the number of neighbors.\n *\n * @throws {Error} - Will throw if there are too many arguments.\n */", "Class", ".", "prototype", "[", "name", "]", "=", "function", "(", "node", ")", "{", "// Early termination", "if", "(", "type", "!==", "'mixed'", "&&", "this", ".", "type", "!==", "'mixed'", "&&", "type", "!==", "this", ".", "type", ")", "return", "[", "]", ";", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "const", "node1", "=", "''", "+", "arguments", "[", "0", "]", ",", "node2", "=", "''", "+", "arguments", "[", "1", "]", ";", "if", "(", "!", "this", ".", "_nodes", ".", "has", "(", "node1", ")", ")", "throw", "new", "NotFoundGraphError", "(", "`", "${", "name", "}", "${", "node1", "}", "`", ")", ";", "if", "(", "!", "this", ".", "_nodes", ".", "has", "(", "node2", ")", ")", "throw", "new", "NotFoundGraphError", "(", "`", "${", "name", "}", "${", "node2", "}", "`", ")", ";", "// Here, we want to assess whether the two given nodes are neighbors", "return", "nodeHasNeighbor", "(", "this", ",", "type", ",", "direction", ",", "node1", ",", "node2", ")", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "node", "=", "''", "+", "node", ";", "const", "nodeData", "=", "this", ".", "_nodes", ".", "get", "(", "node", ")", ";", "if", "(", "typeof", "nodeData", "===", "'undefined'", ")", "throw", "new", "NotFoundGraphError", "(", "`", "${", "name", "}", "${", "node", "}", "`", ")", ";", "// Here, we want to iterate over a node's relevant neighbors", "const", "neighbors", "=", "createNeighborArrayForNode", "(", "type", "===", "'mixed'", "?", "this", ".", "type", ":", "type", ",", "direction", ",", "nodeData", ")", ";", "return", "neighbors", ";", "}", "throw", "new", "InvalidArgumentsGraphError", "(", "`", "${", "name", "}", "${", "arguments", ".", "length", "}", "`", ")", ";", "}", ";", "}" ]
Function attaching a neighbors array creator method to the Graph prototype. @param {function} Class - Target class. @param {object} description - Method description.
[ "Function", "attaching", "a", "neighbors", "array", "creator", "method", "to", "the", "Graph", "prototype", "." ]
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/neighbors.js#L332-L398
16,298
graphology/graphology
src/iteration/edges.js
collectForKey
function collectForKey(edges, object, k) { if (!(k in object)) return; if (object[k] instanceof Set) object[k].forEach(edgeData => edges.push(edgeData.key)); else edges.push(object[k].key); return; }
javascript
function collectForKey(edges, object, k) { if (!(k in object)) return; if (object[k] instanceof Set) object[k].forEach(edgeData => edges.push(edgeData.key)); else edges.push(object[k].key); return; }
[ "function", "collectForKey", "(", "edges", ",", "object", ",", "k", ")", "{", "if", "(", "!", "(", "k", "in", "object", ")", ")", "return", ";", "if", "(", "object", "[", "k", "]", "instanceof", "Set", ")", "object", "[", "k", "]", ".", "forEach", "(", "edgeData", "=>", "edges", ".", "push", "(", "edgeData", ".", "key", ")", ")", ";", "else", "edges", ".", "push", "(", "object", "[", "k", "]", ".", "key", ")", ";", "return", ";", "}" ]
Function collecting edges from the given object at given key. @param {array} edges - Edges array to populate. @param {object} object - Target object. @param {mixed} k - Neighbor key. @return {array} - The found edges.
[ "Function", "collecting", "edges", "from", "the", "given", "object", "at", "given", "key", "." ]
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L170-L181
16,299
graphology/graphology
src/iteration/edges.js
forEachForKey
function forEachForKey(object, k, callback) { if (!(k in object)) return; if (object[k] instanceof Set) object[k].forEach(edgeData => callback( edgeData.key, edgeData.attributes, edgeData.source.key, edgeData.target.key, edgeData.source.attributes, edgeData.target.attributes )); else { const edgeData = object[k]; callback( edgeData.key, edgeData.attributes, edgeData.source.key, edgeData.target.key, edgeData.source.attributes, edgeData.target.attributes ); } return; }
javascript
function forEachForKey(object, k, callback) { if (!(k in object)) return; if (object[k] instanceof Set) object[k].forEach(edgeData => callback( edgeData.key, edgeData.attributes, edgeData.source.key, edgeData.target.key, edgeData.source.attributes, edgeData.target.attributes )); else { const edgeData = object[k]; callback( edgeData.key, edgeData.attributes, edgeData.source.key, edgeData.target.key, edgeData.source.attributes, edgeData.target.attributes ); } return; }
[ "function", "forEachForKey", "(", "object", ",", "k", ",", "callback", ")", "{", "if", "(", "!", "(", "k", "in", "object", ")", ")", "return", ";", "if", "(", "object", "[", "k", "]", "instanceof", "Set", ")", "object", "[", "k", "]", ".", "forEach", "(", "edgeData", "=>", "callback", "(", "edgeData", ".", "key", ",", "edgeData", ".", "attributes", ",", "edgeData", ".", "source", ".", "key", ",", "edgeData", ".", "target", ".", "key", ",", "edgeData", ".", "source", ".", "attributes", ",", "edgeData", ".", "target", ".", "attributes", ")", ")", ";", "else", "{", "const", "edgeData", "=", "object", "[", "k", "]", ";", "callback", "(", "edgeData", ".", "key", ",", "edgeData", ".", "attributes", ",", "edgeData", ".", "source", ".", "key", ",", "edgeData", ".", "target", ".", "key", ",", "edgeData", ".", "source", ".", "attributes", ",", "edgeData", ".", "target", ".", "attributes", ")", ";", "}", "return", ";", "}" ]
Function iterating over the egdes from the object at given key using a callback. @param {object} object - Target object. @param {mixed} k - Neighbor key. @param {function} callback - Callback to use.
[ "Function", "iterating", "over", "the", "egdes", "from", "the", "object", "at", "given", "key", "using", "a", "callback", "." ]
f99681435ecd2d5b9d0a8e0d0d10f794817f417e
https://github.com/graphology/graphology/blob/f99681435ecd2d5b9d0a8e0d0d10f794817f417e/src/iteration/edges.js#L191-L219