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
|
---|---|---|---|---|---|---|---|---|---|---|---|
43,600 | robinpowered/robin-js-sdk-public | lib/api/modules/locations.js | function (locationIdentifier, spaceIdentifier, params) {
var path;
if (locationIdentifier) {
path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.SPACES, spaceIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A location identifier is required.');
}
} | javascript | function (locationIdentifier, spaceIdentifier, params) {
var path;
if (locationIdentifier) {
path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.SPACES, spaceIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A location identifier is required.');
}
} | [
"function",
"(",
"locationIdentifier",
",",
"spaceIdentifier",
",",
"params",
")",
"{",
"var",
"path",
";",
"if",
"(",
"locationIdentifier",
")",
"{",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"LOCATIONS",
",",
"locationIdentifier",
",",
"constants",
".",
"SPACES",
",",
"spaceIdentifier",
")",
";",
"return",
"this",
".",
"Core",
".",
"GET",
"(",
"path",
",",
"params",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"rejectRequest",
"(",
"'Bad Request: A location identifier is required.'",
")",
";",
"}",
"}"
]
| Get all the spaces in a location or a particular space in a location identified by `spaceIdentifier`
@param {String|Integer} locationIdentifier A Robin channel identifier
@param {String|Integer|undefined} spaceIdentifier A Robin channel data point identifier
@param {Object|undefined} params A querystring object
@return {Function} A Promise | [
"Get",
"all",
"the",
"spaces",
"in",
"a",
"location",
"or",
"a",
"particular",
"space",
"in",
"a",
"location",
"identified",
"by",
"spaceIdentifier"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/locations.js#L68-L76 |
|
43,601 | robinpowered/robin-js-sdk-public | lib/api/modules/locations.js | function (locationIdentifier, data) {
var path;
if (locationIdentifier) {
path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.SPACES);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A location identifier is required.');
}
} | javascript | function (locationIdentifier, data) {
var path;
if (locationIdentifier) {
path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.SPACES);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A location identifier is required.');
}
} | [
"function",
"(",
"locationIdentifier",
",",
"data",
")",
"{",
"var",
"path",
";",
"if",
"(",
"locationIdentifier",
")",
"{",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"LOCATIONS",
",",
"locationIdentifier",
",",
"constants",
".",
"SPACES",
")",
";",
"return",
"this",
".",
"Core",
".",
"POST",
"(",
"path",
",",
"data",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"rejectRequest",
"(",
"'Bad Request: A location identifier is required.'",
")",
";",
"}",
"}"
]
| Add space to a location
@param {String|Integer} locationIdentifier A Robin location identifier
@param {Object} data A querystring object
@return {Function} A Promise | [
"Add",
"space",
"to",
"a",
"location"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/locations.js#L84-L92 |
|
43,602 | robinpowered/robin-js-sdk-public | lib/api/modules/locations.js | function (locationIdentifier, params) {
var path;
if (locationIdentifier) {
path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.PRESENCE);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A location identifier is required.');
}
} | javascript | function (locationIdentifier, params) {
var path;
if (locationIdentifier) {
path = this.constructPath(constants.LOCATIONS, locationIdentifier, constants.PRESENCE);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A location identifier is required.');
}
} | [
"function",
"(",
"locationIdentifier",
",",
"params",
")",
"{",
"var",
"path",
";",
"if",
"(",
"locationIdentifier",
")",
"{",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"LOCATIONS",
",",
"locationIdentifier",
",",
"constants",
".",
"PRESENCE",
")",
";",
"return",
"this",
".",
"Core",
".",
"GET",
"(",
"path",
",",
"params",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"rejectRequest",
"(",
"'Bad Request: A location identifier is required.'",
")",
";",
"}",
"}"
]
| Get all the current presence for all the spaces in a location
@param {String|Integer} locationIdentifier A Robin channel identifier
@param {Object|undefined} params A querystring object
@return {Function} A Promise | [
"Get",
"all",
"the",
"current",
"presence",
"for",
"all",
"the",
"spaces",
"in",
"a",
"location"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/locations.js#L106-L114 |
|
43,603 | evansiroky/gtfs-sequelize | lib/operations.js | updateInterpolatedTimes | function updateInterpolatedTimes (cfg, callback) {
const db = cfg.db
const lastTimepoint = cfg.lastTimepoint
const nextTimepoint = cfg.nextTimepoint
const timeDiff = nextTimepoint.arrival_time - lastTimepoint.departure_time
let literal
// sqlite null is a string
if (nextTimepoint.shape_dist_traveled && nextTimepoint.shape_dist_traveled !== 'NULL') {
// calculate interpolation based off of distance ratios
const distanceTraveled = nextTimepoint.shape_dist_traveled - lastTimepoint.shape_dist_traveled
literal = `${lastTimepoint.departure_time} +
${timeDiff} *
(shape_dist_traveled - ${lastTimepoint.shape_dist_traveled}) /
${distanceTraveled}`
} else {
// calculate interpolation based off of stop sequence ratios
const numStopsPassed = nextTimepoint.stop_sequence - lastTimepoint.stop_sequence
literal = `${lastTimepoint.departure_time} +
${timeDiff} *
(stop_sequence - ${lastTimepoint.stop_sequence}) /
${numStopsPassed}`
}
const updateLiteral = db.sequelize.literal(literal)
db.stop_time
.update(
{
arrival_time: updateLiteral,
departure_time: updateLiteral
},
{
where: {
trip_id: lastTimepoint.trip_id,
stop_sequence: {
$gt: lastTimepoint.stop_sequence,
$lt: nextTimepoint.stop_sequence
}
}
}
)
.then(() => {
callback()
})
.catch(callback)
} | javascript | function updateInterpolatedTimes (cfg, callback) {
const db = cfg.db
const lastTimepoint = cfg.lastTimepoint
const nextTimepoint = cfg.nextTimepoint
const timeDiff = nextTimepoint.arrival_time - lastTimepoint.departure_time
let literal
// sqlite null is a string
if (nextTimepoint.shape_dist_traveled && nextTimepoint.shape_dist_traveled !== 'NULL') {
// calculate interpolation based off of distance ratios
const distanceTraveled = nextTimepoint.shape_dist_traveled - lastTimepoint.shape_dist_traveled
literal = `${lastTimepoint.departure_time} +
${timeDiff} *
(shape_dist_traveled - ${lastTimepoint.shape_dist_traveled}) /
${distanceTraveled}`
} else {
// calculate interpolation based off of stop sequence ratios
const numStopsPassed = nextTimepoint.stop_sequence - lastTimepoint.stop_sequence
literal = `${lastTimepoint.departure_time} +
${timeDiff} *
(stop_sequence - ${lastTimepoint.stop_sequence}) /
${numStopsPassed}`
}
const updateLiteral = db.sequelize.literal(literal)
db.stop_time
.update(
{
arrival_time: updateLiteral,
departure_time: updateLiteral
},
{
where: {
trip_id: lastTimepoint.trip_id,
stop_sequence: {
$gt: lastTimepoint.stop_sequence,
$lt: nextTimepoint.stop_sequence
}
}
}
)
.then(() => {
callback()
})
.catch(callback)
} | [
"function",
"updateInterpolatedTimes",
"(",
"cfg",
",",
"callback",
")",
"{",
"const",
"db",
"=",
"cfg",
".",
"db",
"const",
"lastTimepoint",
"=",
"cfg",
".",
"lastTimepoint",
"const",
"nextTimepoint",
"=",
"cfg",
".",
"nextTimepoint",
"const",
"timeDiff",
"=",
"nextTimepoint",
".",
"arrival_time",
"-",
"lastTimepoint",
".",
"departure_time",
"let",
"literal",
"// sqlite null is a string",
"if",
"(",
"nextTimepoint",
".",
"shape_dist_traveled",
"&&",
"nextTimepoint",
".",
"shape_dist_traveled",
"!==",
"'NULL'",
")",
"{",
"// calculate interpolation based off of distance ratios",
"const",
"distanceTraveled",
"=",
"nextTimepoint",
".",
"shape_dist_traveled",
"-",
"lastTimepoint",
".",
"shape_dist_traveled",
"literal",
"=",
"`",
"${",
"lastTimepoint",
".",
"departure_time",
"}",
"${",
"timeDiff",
"}",
"${",
"lastTimepoint",
".",
"shape_dist_traveled",
"}",
"${",
"distanceTraveled",
"}",
"`",
"}",
"else",
"{",
"// calculate interpolation based off of stop sequence ratios",
"const",
"numStopsPassed",
"=",
"nextTimepoint",
".",
"stop_sequence",
"-",
"lastTimepoint",
".",
"stop_sequence",
"literal",
"=",
"`",
"${",
"lastTimepoint",
".",
"departure_time",
"}",
"${",
"timeDiff",
"}",
"${",
"lastTimepoint",
".",
"stop_sequence",
"}",
"${",
"numStopsPassed",
"}",
"`",
"}",
"const",
"updateLiteral",
"=",
"db",
".",
"sequelize",
".",
"literal",
"(",
"literal",
")",
"db",
".",
"stop_time",
".",
"update",
"(",
"{",
"arrival_time",
":",
"updateLiteral",
",",
"departure_time",
":",
"updateLiteral",
"}",
",",
"{",
"where",
":",
"{",
"trip_id",
":",
"lastTimepoint",
".",
"trip_id",
",",
"stop_sequence",
":",
"{",
"$gt",
":",
"lastTimepoint",
".",
"stop_sequence",
",",
"$lt",
":",
"nextTimepoint",
".",
"stop_sequence",
"}",
"}",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"callback",
"(",
")",
"}",
")",
".",
"catch",
"(",
"callback",
")",
"}"
]
| Make an update query to the db to set the interpolated times in
a particular range of a particular trip | [
"Make",
"an",
"update",
"query",
"to",
"the",
"db",
"to",
"set",
"the",
"interpolated",
"times",
"in",
"a",
"particular",
"range",
"of",
"a",
"particular",
"trip"
]
| ba101fa82e730694c536c43e615ff38fd264a65b | https://github.com/evansiroky/gtfs-sequelize/blob/ba101fa82e730694c536c43e615ff38fd264a65b/lib/operations.js#L10-L53 |
43,604 | evansiroky/gtfs-sequelize | lib/operations.js | interpolateStopTimes | function interpolateStopTimes (db, callback) {
console.log('interpolating stop times')
const streamerConfig = util.makeStreamerConfig(db.trip)
const querier = dbStreamer.getQuerier(streamerConfig)
const maxUpdateConcurrency = db.trip.sequelize.getDialect() === 'sqlite' ? 1 : 100
const updateQueue = async.queue(updateInterpolatedTimes, maxUpdateConcurrency)
let isComplete = false
let numUpdates = 0
/**
* Helper function to call upon completion of interpolation
*/
function onComplete (err) {
if (err) {
console.log('interpolation encountered an error: ', err)
return callback(err)
}
// set is complete and create a queue drain function
// however, a feed may not have any interpolated times, so
// `isComplete` is set in case nothing is pushed to the queue
isComplete = true
updateQueue.drain = () => {
console.log('interpolation completed successfully')
callback(err)
}
}
let rowTimeout
/**
* Helper function to account for stop_times that are completely interpolated
*/
function onRowComplete () {
if (rowTimeout) {
clearTimeout(rowTimeout)
}
if (isComplete && numUpdates === 0) {
rowTimeout = setTimeout(() => {
// check yet again, because interpolated times could've appeared since setting timeout
if (numUpdates === 0) {
console.log('interpolation completed successfully (no interpolations needed)')
callback()
}
}, 10000)
}
}
// TODO: fix this cause it doesn't work w/ sqlite with a schema for some reason
const statement = `SELECT trip_id FROM ${streamerConfig.tableName}`
querier.execute(
statement,
row => {
// get all stop_times for trip
db.stop_time
.findAll({
where: {
trip_id: row.trip_id
}
})
// iterate through stop times to determine null arrival or departure times
.then(stopTimes => {
let lastStopTime
let lastTimepoint
let lookingForNextTimepoint = false
stopTimes.forEach(stopTime => {
if (lookingForNextTimepoint) {
// check if current stop time has a time
// mysql null stop times are showin up as 0, which might be bug elsewhere
// sqlite null shows up as 'NULL'
if (
stopTime.arrival_time !== null &&
stopTime.arrival_time !== 'NULL' &&
stopTime.arrival_time >= lastTimepoint.departure_time
) {
// found next timepoint
// make update query to set interpolated times
updateQueue.push({
db: db,
lastTimepoint: lastTimepoint,
nextTimepoint: stopTime
})
numUpdates++
lookingForNextTimepoint = false
}
} else {
// sqlite uninterpolated shows up ass 'NULL'
if (stopTime.arrival_time === null || stopTime.arrival_time === 'NULL') {
lastTimepoint = lastStopTime
lookingForNextTimepoint = true
}
}
lastStopTime = stopTime
})
onRowComplete()
})
.catch(onComplete)
},
onComplete
)
} | javascript | function interpolateStopTimes (db, callback) {
console.log('interpolating stop times')
const streamerConfig = util.makeStreamerConfig(db.trip)
const querier = dbStreamer.getQuerier(streamerConfig)
const maxUpdateConcurrency = db.trip.sequelize.getDialect() === 'sqlite' ? 1 : 100
const updateQueue = async.queue(updateInterpolatedTimes, maxUpdateConcurrency)
let isComplete = false
let numUpdates = 0
/**
* Helper function to call upon completion of interpolation
*/
function onComplete (err) {
if (err) {
console.log('interpolation encountered an error: ', err)
return callback(err)
}
// set is complete and create a queue drain function
// however, a feed may not have any interpolated times, so
// `isComplete` is set in case nothing is pushed to the queue
isComplete = true
updateQueue.drain = () => {
console.log('interpolation completed successfully')
callback(err)
}
}
let rowTimeout
/**
* Helper function to account for stop_times that are completely interpolated
*/
function onRowComplete () {
if (rowTimeout) {
clearTimeout(rowTimeout)
}
if (isComplete && numUpdates === 0) {
rowTimeout = setTimeout(() => {
// check yet again, because interpolated times could've appeared since setting timeout
if (numUpdates === 0) {
console.log('interpolation completed successfully (no interpolations needed)')
callback()
}
}, 10000)
}
}
// TODO: fix this cause it doesn't work w/ sqlite with a schema for some reason
const statement = `SELECT trip_id FROM ${streamerConfig.tableName}`
querier.execute(
statement,
row => {
// get all stop_times for trip
db.stop_time
.findAll({
where: {
trip_id: row.trip_id
}
})
// iterate through stop times to determine null arrival or departure times
.then(stopTimes => {
let lastStopTime
let lastTimepoint
let lookingForNextTimepoint = false
stopTimes.forEach(stopTime => {
if (lookingForNextTimepoint) {
// check if current stop time has a time
// mysql null stop times are showin up as 0, which might be bug elsewhere
// sqlite null shows up as 'NULL'
if (
stopTime.arrival_time !== null &&
stopTime.arrival_time !== 'NULL' &&
stopTime.arrival_time >= lastTimepoint.departure_time
) {
// found next timepoint
// make update query to set interpolated times
updateQueue.push({
db: db,
lastTimepoint: lastTimepoint,
nextTimepoint: stopTime
})
numUpdates++
lookingForNextTimepoint = false
}
} else {
// sqlite uninterpolated shows up ass 'NULL'
if (stopTime.arrival_time === null || stopTime.arrival_time === 'NULL') {
lastTimepoint = lastStopTime
lookingForNextTimepoint = true
}
}
lastStopTime = stopTime
})
onRowComplete()
})
.catch(onComplete)
},
onComplete
)
} | [
"function",
"interpolateStopTimes",
"(",
"db",
",",
"callback",
")",
"{",
"console",
".",
"log",
"(",
"'interpolating stop times'",
")",
"const",
"streamerConfig",
"=",
"util",
".",
"makeStreamerConfig",
"(",
"db",
".",
"trip",
")",
"const",
"querier",
"=",
"dbStreamer",
".",
"getQuerier",
"(",
"streamerConfig",
")",
"const",
"maxUpdateConcurrency",
"=",
"db",
".",
"trip",
".",
"sequelize",
".",
"getDialect",
"(",
")",
"===",
"'sqlite'",
"?",
"1",
":",
"100",
"const",
"updateQueue",
"=",
"async",
".",
"queue",
"(",
"updateInterpolatedTimes",
",",
"maxUpdateConcurrency",
")",
"let",
"isComplete",
"=",
"false",
"let",
"numUpdates",
"=",
"0",
"/**\n * Helper function to call upon completion of interpolation\n */",
"function",
"onComplete",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'interpolation encountered an error: '",
",",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"}",
"// set is complete and create a queue drain function",
"// however, a feed may not have any interpolated times, so",
"// `isComplete` is set in case nothing is pushed to the queue",
"isComplete",
"=",
"true",
"updateQueue",
".",
"drain",
"=",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"'interpolation completed successfully'",
")",
"callback",
"(",
"err",
")",
"}",
"}",
"let",
"rowTimeout",
"/**\n * Helper function to account for stop_times that are completely interpolated\n */",
"function",
"onRowComplete",
"(",
")",
"{",
"if",
"(",
"rowTimeout",
")",
"{",
"clearTimeout",
"(",
"rowTimeout",
")",
"}",
"if",
"(",
"isComplete",
"&&",
"numUpdates",
"===",
"0",
")",
"{",
"rowTimeout",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"// check yet again, because interpolated times could've appeared since setting timeout",
"if",
"(",
"numUpdates",
"===",
"0",
")",
"{",
"console",
".",
"log",
"(",
"'interpolation completed successfully (no interpolations needed)'",
")",
"callback",
"(",
")",
"}",
"}",
",",
"10000",
")",
"}",
"}",
"// TODO: fix this cause it doesn't work w/ sqlite with a schema for some reason",
"const",
"statement",
"=",
"`",
"${",
"streamerConfig",
".",
"tableName",
"}",
"`",
"querier",
".",
"execute",
"(",
"statement",
",",
"row",
"=>",
"{",
"// get all stop_times for trip",
"db",
".",
"stop_time",
".",
"findAll",
"(",
"{",
"where",
":",
"{",
"trip_id",
":",
"row",
".",
"trip_id",
"}",
"}",
")",
"// iterate through stop times to determine null arrival or departure times",
".",
"then",
"(",
"stopTimes",
"=>",
"{",
"let",
"lastStopTime",
"let",
"lastTimepoint",
"let",
"lookingForNextTimepoint",
"=",
"false",
"stopTimes",
".",
"forEach",
"(",
"stopTime",
"=>",
"{",
"if",
"(",
"lookingForNextTimepoint",
")",
"{",
"// check if current stop time has a time",
"// mysql null stop times are showin up as 0, which might be bug elsewhere",
"// sqlite null shows up as 'NULL'",
"if",
"(",
"stopTime",
".",
"arrival_time",
"!==",
"null",
"&&",
"stopTime",
".",
"arrival_time",
"!==",
"'NULL'",
"&&",
"stopTime",
".",
"arrival_time",
">=",
"lastTimepoint",
".",
"departure_time",
")",
"{",
"// found next timepoint",
"// make update query to set interpolated times",
"updateQueue",
".",
"push",
"(",
"{",
"db",
":",
"db",
",",
"lastTimepoint",
":",
"lastTimepoint",
",",
"nextTimepoint",
":",
"stopTime",
"}",
")",
"numUpdates",
"++",
"lookingForNextTimepoint",
"=",
"false",
"}",
"}",
"else",
"{",
"// sqlite uninterpolated shows up ass 'NULL'",
"if",
"(",
"stopTime",
".",
"arrival_time",
"===",
"null",
"||",
"stopTime",
".",
"arrival_time",
"===",
"'NULL'",
")",
"{",
"lastTimepoint",
"=",
"lastStopTime",
"lookingForNextTimepoint",
"=",
"true",
"}",
"}",
"lastStopTime",
"=",
"stopTime",
"}",
")",
"onRowComplete",
"(",
")",
"}",
")",
".",
"catch",
"(",
"onComplete",
")",
"}",
",",
"onComplete",
")",
"}"
]
| Calculate and assign an approximate arrival and departure time
at all stop_times that have an undefined arrival and departure time | [
"Calculate",
"and",
"assign",
"an",
"approximate",
"arrival",
"and",
"departure",
"time",
"at",
"all",
"stop_times",
"that",
"have",
"an",
"undefined",
"arrival",
"and",
"departure",
"time"
]
| ba101fa82e730694c536c43e615ff38fd264a65b | https://github.com/evansiroky/gtfs-sequelize/blob/ba101fa82e730694c536c43e615ff38fd264a65b/lib/operations.js#L59-L159 |
43,605 | evansiroky/gtfs-sequelize | lib/operations.js | onComplete | function onComplete (err) {
if (err) {
console.log('interpolation encountered an error: ', err)
return callback(err)
}
// set is complete and create a queue drain function
// however, a feed may not have any interpolated times, so
// `isComplete` is set in case nothing is pushed to the queue
isComplete = true
updateQueue.drain = () => {
console.log('interpolation completed successfully')
callback(err)
}
} | javascript | function onComplete (err) {
if (err) {
console.log('interpolation encountered an error: ', err)
return callback(err)
}
// set is complete and create a queue drain function
// however, a feed may not have any interpolated times, so
// `isComplete` is set in case nothing is pushed to the queue
isComplete = true
updateQueue.drain = () => {
console.log('interpolation completed successfully')
callback(err)
}
} | [
"function",
"onComplete",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'interpolation encountered an error: '",
",",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"}",
"// set is complete and create a queue drain function",
"// however, a feed may not have any interpolated times, so",
"// `isComplete` is set in case nothing is pushed to the queue",
"isComplete",
"=",
"true",
"updateQueue",
".",
"drain",
"=",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"'interpolation completed successfully'",
")",
"callback",
"(",
"err",
")",
"}",
"}"
]
| Helper function to call upon completion of interpolation | [
"Helper",
"function",
"to",
"call",
"upon",
"completion",
"of",
"interpolation"
]
| ba101fa82e730694c536c43e615ff38fd264a65b | https://github.com/evansiroky/gtfs-sequelize/blob/ba101fa82e730694c536c43e615ff38fd264a65b/lib/operations.js#L71-L84 |
43,606 | evansiroky/gtfs-sequelize | lib/operations.js | onRowComplete | function onRowComplete () {
if (rowTimeout) {
clearTimeout(rowTimeout)
}
if (isComplete && numUpdates === 0) {
rowTimeout = setTimeout(() => {
// check yet again, because interpolated times could've appeared since setting timeout
if (numUpdates === 0) {
console.log('interpolation completed successfully (no interpolations needed)')
callback()
}
}, 10000)
}
} | javascript | function onRowComplete () {
if (rowTimeout) {
clearTimeout(rowTimeout)
}
if (isComplete && numUpdates === 0) {
rowTimeout = setTimeout(() => {
// check yet again, because interpolated times could've appeared since setting timeout
if (numUpdates === 0) {
console.log('interpolation completed successfully (no interpolations needed)')
callback()
}
}, 10000)
}
} | [
"function",
"onRowComplete",
"(",
")",
"{",
"if",
"(",
"rowTimeout",
")",
"{",
"clearTimeout",
"(",
"rowTimeout",
")",
"}",
"if",
"(",
"isComplete",
"&&",
"numUpdates",
"===",
"0",
")",
"{",
"rowTimeout",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"// check yet again, because interpolated times could've appeared since setting timeout",
"if",
"(",
"numUpdates",
"===",
"0",
")",
"{",
"console",
".",
"log",
"(",
"'interpolation completed successfully (no interpolations needed)'",
")",
"callback",
"(",
")",
"}",
"}",
",",
"10000",
")",
"}",
"}"
]
| Helper function to account for stop_times that are completely interpolated | [
"Helper",
"function",
"to",
"account",
"for",
"stop_times",
"that",
"are",
"completely",
"interpolated"
]
| ba101fa82e730694c536c43e615ff38fd264a65b | https://github.com/evansiroky/gtfs-sequelize/blob/ba101fa82e730694c536c43e615ff38fd264a65b/lib/operations.js#L91-L104 |
43,607 | hello-js/hello | lib/middleware/request-id.js | requestId | function requestId (ctx, next) {
let requestId = uuid.v4()
ctx.id = requestId
ctx.request.id = requestId
ctx.state.requestId = requestId
ctx.set('X-Request-Id', requestId)
return next()
} | javascript | function requestId (ctx, next) {
let requestId = uuid.v4()
ctx.id = requestId
ctx.request.id = requestId
ctx.state.requestId = requestId
ctx.set('X-Request-Id', requestId)
return next()
} | [
"function",
"requestId",
"(",
"ctx",
",",
"next",
")",
"{",
"let",
"requestId",
"=",
"uuid",
".",
"v4",
"(",
")",
"ctx",
".",
"id",
"=",
"requestId",
"ctx",
".",
"request",
".",
"id",
"=",
"requestId",
"ctx",
".",
"state",
".",
"requestId",
"=",
"requestId",
"ctx",
".",
"set",
"(",
"'X-Request-Id'",
",",
"requestId",
")",
"return",
"next",
"(",
")",
"}"
]
| Generates a unique request ID for all requests, setting it as `ctx.id`, `ctx.request.id` and
`ctx.state.requestId`. It will also set the `X-Request-Id` header to aid clients with debugging.
@example
ctx.headers
// { `x-request-id`: '72243aca-e4bb-4a3a-a2e7-ed380c256826' }
ctx.state
// { requestId: '72243aca-e4bb-4a3a-a2e7-ed380c256826' }
@returns {Promise} | [
"Generates",
"a",
"unique",
"request",
"ID",
"for",
"all",
"requests",
"setting",
"it",
"as",
"ctx",
".",
"id",
"ctx",
".",
"request",
".",
"id",
"and",
"ctx",
".",
"state",
".",
"requestId",
".",
"It",
"will",
"also",
"set",
"the",
"X",
"-",
"Request",
"-",
"Id",
"header",
"to",
"aid",
"clients",
"with",
"debugging",
"."
]
| 72a0d2c87817921fba15c2d2567b8f0abc62c3e5 | https://github.com/hello-js/hello/blob/72a0d2c87817921fba15c2d2567b8f0abc62c3e5/lib/middleware/request-id.js#L18-L27 |
43,608 | aurelia/ssr-engine | dist/commonjs/cleanup.js | rdelete | function rdelete(m, key) {
if (m.parent && m.parent.filename === require.resolve(key)) {
delete m.parent;
}
for (var i = m.children.length - 1; i >= 0; i--) {
if (m.children[i].filename === require.resolve(key)) {
m.children.splice(i, 1);
}
else {
rdelete(m.children[i], key);
}
}
} | javascript | function rdelete(m, key) {
if (m.parent && m.parent.filename === require.resolve(key)) {
delete m.parent;
}
for (var i = m.children.length - 1; i >= 0; i--) {
if (m.children[i].filename === require.resolve(key)) {
m.children.splice(i, 1);
}
else {
rdelete(m.children[i], key);
}
}
} | [
"function",
"rdelete",
"(",
"m",
",",
"key",
")",
"{",
"if",
"(",
"m",
".",
"parent",
"&&",
"m",
".",
"parent",
".",
"filename",
"===",
"require",
".",
"resolve",
"(",
"key",
")",
")",
"{",
"delete",
"m",
".",
"parent",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"m",
".",
"children",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"m",
".",
"children",
"[",
"i",
"]",
".",
"filename",
"===",
"require",
".",
"resolve",
"(",
"key",
")",
")",
"{",
"m",
".",
"children",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"else",
"{",
"rdelete",
"(",
"m",
".",
"children",
"[",
"i",
"]",
",",
"key",
")",
";",
"}",
"}",
"}"
]
| Recursively go over all node modules and delete a specific module
so it can be garbage collected
@param m
@param key | [
"Recursively",
"go",
"over",
"all",
"node",
"modules",
"and",
"delete",
"a",
"specific",
"module",
"so",
"it",
"can",
"be",
"garbage",
"collected"
]
| 5394083a067136364d58650a78f9200b18033bd8 | https://github.com/aurelia/ssr-engine/blob/5394083a067136364d58650a78f9200b18033bd8/dist/commonjs/cleanup.js#L34-L46 |
43,609 | dbtek/bootswatch-dist | build.js | getNewVersions | function getNewVersions() {
return getTags()
.then(tags => {
var newVersions = []
for(tag of tags) {
if (semver.gt(tag.name, update.latest) || (
semver.eq(tag.name, update.latest) && (semver(tag.name).build[0] || 0) > (semver(update.latest).build[0] || 0)
)) {
newVersions.push(tag)
}
}
newVersions.reverse()
// order versions from lower to greater
console.log(chalk.blue('New versions available: ' + (newVersions.map(v => v.name).join(', ') || 'none') + '.'))
return newVersions
})
.catch(e => console.log(e.stack))
} | javascript | function getNewVersions() {
return getTags()
.then(tags => {
var newVersions = []
for(tag of tags) {
if (semver.gt(tag.name, update.latest) || (
semver.eq(tag.name, update.latest) && (semver(tag.name).build[0] || 0) > (semver(update.latest).build[0] || 0)
)) {
newVersions.push(tag)
}
}
newVersions.reverse()
// order versions from lower to greater
console.log(chalk.blue('New versions available: ' + (newVersions.map(v => v.name).join(', ') || 'none') + '.'))
return newVersions
})
.catch(e => console.log(e.stack))
} | [
"function",
"getNewVersions",
"(",
")",
"{",
"return",
"getTags",
"(",
")",
".",
"then",
"(",
"tags",
"=>",
"{",
"var",
"newVersions",
"=",
"[",
"]",
"for",
"(",
"tag",
"of",
"tags",
")",
"{",
"if",
"(",
"semver",
".",
"gt",
"(",
"tag",
".",
"name",
",",
"update",
".",
"latest",
")",
"||",
"(",
"semver",
".",
"eq",
"(",
"tag",
".",
"name",
",",
"update",
".",
"latest",
")",
"&&",
"(",
"semver",
"(",
"tag",
".",
"name",
")",
".",
"build",
"[",
"0",
"]",
"||",
"0",
")",
">",
"(",
"semver",
"(",
"update",
".",
"latest",
")",
".",
"build",
"[",
"0",
"]",
"||",
"0",
")",
")",
")",
"{",
"newVersions",
".",
"push",
"(",
"tag",
")",
"}",
"}",
"newVersions",
".",
"reverse",
"(",
")",
"// order versions from lower to greater",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'New versions available: '",
"+",
"(",
"newVersions",
".",
"map",
"(",
"v",
"=>",
"v",
".",
"name",
")",
".",
"join",
"(",
"', '",
")",
"||",
"'none'",
")",
"+",
"'.'",
")",
")",
"return",
"newVersions",
"}",
")",
".",
"catch",
"(",
"e",
"=>",
"console",
".",
"log",
"(",
"e",
".",
"stack",
")",
")",
"}"
]
| Filters bootswatch versions greater than latest update defined in update.json.
@return {Promise} Promise to be resolved with new versions. | [
"Filters",
"bootswatch",
"versions",
"greater",
"than",
"latest",
"update",
"defined",
"in",
"update",
".",
"json",
"."
]
| c087ae53cf83ff7714dff7d470c12d2da1e44fd1 | https://github.com/dbtek/bootswatch-dist/blob/c087ae53cf83ff7714dff7d470c12d2da1e44fd1/build.js#L60-L77 |
43,610 | dbtek/bootswatch-dist | build.js | cloneRepo | function cloneRepo() {
return new Promise((resolve, reject) => {
git.clone(`https://${GH_TOKEN}@github.com/dbtek/bootswatch-dist.git`, '.tmp/repo', (err, result) => {
if (err) {
return reject(err)
}
resolve(result)
})
})
} | javascript | function cloneRepo() {
return new Promise((resolve, reject) => {
git.clone(`https://${GH_TOKEN}@github.com/dbtek/bootswatch-dist.git`, '.tmp/repo', (err, result) => {
if (err) {
return reject(err)
}
resolve(result)
})
})
} | [
"function",
"cloneRepo",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"git",
".",
"clone",
"(",
"`",
"${",
"GH_TOKEN",
"}",
"`",
",",
"'.tmp/repo'",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
"}",
"resolve",
"(",
"result",
")",
"}",
")",
"}",
")",
"}"
]
| Clones release repository
@return {Promise} | [
"Clones",
"release",
"repository"
]
| c087ae53cf83ff7714dff7d470c12d2da1e44fd1 | https://github.com/dbtek/bootswatch-dist/blob/c087ae53cf83ff7714dff7d470c12d2da1e44fd1/build.js#L97-L106 |
43,611 | dbtek/bootswatch-dist | build.js | copyRepo | function copyRepo(dest) {
return new Promise((resolve, reject) => {
ncp('.tmp/repo', dest, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
} | javascript | function copyRepo(dest) {
return new Promise((resolve, reject) => {
ncp('.tmp/repo', dest, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
} | [
"function",
"copyRepo",
"(",
"dest",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"ncp",
"(",
"'.tmp/repo'",
",",
"dest",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
"return",
"}",
"resolve",
"(",
")",
"}",
")",
"}",
")",
"}"
]
| Copies repository folder to given destination
@param {String} dest
@return {Promise} | [
"Copies",
"repository",
"folder",
"to",
"given",
"destination"
]
| c087ae53cf83ff7714dff7d470c12d2da1e44fd1 | https://github.com/dbtek/bootswatch-dist/blob/c087ae53cf83ff7714dff7d470c12d2da1e44fd1/build.js#L113-L123 |
43,612 | dbtek/bootswatch-dist | build.js | downloadBootstrapAssets | function downloadBootstrapAssets(version, path) {
console.log(chalk.blue((`Downloading Bootstrap assets to ${path}`)))
version = semver.clean(version)
const url = 'https://maxcdn.bootstrapcdn.com/bootstrap'
var proms = [
'fonts/glyphicons-halflings-regular.eot',
'fonts/glyphicons-halflings-regular.woff',
'fonts/glyphicons-halflings-regular.woff2',
'fonts/glyphicons-halflings-regular.ttf',
'fonts/glyphicons-halflings-regular.svg'
].map(f => {
return download(`${url}/${version}/${f}`, `${path}/fonts`)
.catch(e => {
console.log(chalk.red(`Downloading ${version}/${f} failed.`))
return Promise.resolve()
})
})
proms = proms.concat([
'js/bootstrap.js',
'js/bootstrap.min.js'
].map(f => {
return download(`${url}/${version}/${f}`, `${path}/js`)
.catch(e => {
console.log(chalk.red(`Downloading ${version}/${f} failed.`))
return Promise.resolve()
})
})
)
return Promise.all(proms)
} | javascript | function downloadBootstrapAssets(version, path) {
console.log(chalk.blue((`Downloading Bootstrap assets to ${path}`)))
version = semver.clean(version)
const url = 'https://maxcdn.bootstrapcdn.com/bootstrap'
var proms = [
'fonts/glyphicons-halflings-regular.eot',
'fonts/glyphicons-halflings-regular.woff',
'fonts/glyphicons-halflings-regular.woff2',
'fonts/glyphicons-halflings-regular.ttf',
'fonts/glyphicons-halflings-regular.svg'
].map(f => {
return download(`${url}/${version}/${f}`, `${path}/fonts`)
.catch(e => {
console.log(chalk.red(`Downloading ${version}/${f} failed.`))
return Promise.resolve()
})
})
proms = proms.concat([
'js/bootstrap.js',
'js/bootstrap.min.js'
].map(f => {
return download(`${url}/${version}/${f}`, `${path}/js`)
.catch(e => {
console.log(chalk.red(`Downloading ${version}/${f} failed.`))
return Promise.resolve()
})
})
)
return Promise.all(proms)
} | [
"function",
"downloadBootstrapAssets",
"(",
"version",
",",
"path",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"(",
"`",
"${",
"path",
"}",
"`",
")",
")",
")",
"version",
"=",
"semver",
".",
"clean",
"(",
"version",
")",
"const",
"url",
"=",
"'https://maxcdn.bootstrapcdn.com/bootstrap'",
"var",
"proms",
"=",
"[",
"'fonts/glyphicons-halflings-regular.eot'",
",",
"'fonts/glyphicons-halflings-regular.woff'",
",",
"'fonts/glyphicons-halflings-regular.woff2'",
",",
"'fonts/glyphicons-halflings-regular.ttf'",
",",
"'fonts/glyphicons-halflings-regular.svg'",
"]",
".",
"map",
"(",
"f",
"=>",
"{",
"return",
"download",
"(",
"`",
"${",
"url",
"}",
"${",
"version",
"}",
"${",
"f",
"}",
"`",
",",
"`",
"${",
"path",
"}",
"`",
")",
".",
"catch",
"(",
"e",
"=>",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"`",
"${",
"version",
"}",
"${",
"f",
"}",
"`",
")",
")",
"return",
"Promise",
".",
"resolve",
"(",
")",
"}",
")",
"}",
")",
"proms",
"=",
"proms",
".",
"concat",
"(",
"[",
"'js/bootstrap.js'",
",",
"'js/bootstrap.min.js'",
"]",
".",
"map",
"(",
"f",
"=>",
"{",
"return",
"download",
"(",
"`",
"${",
"url",
"}",
"${",
"version",
"}",
"${",
"f",
"}",
"`",
",",
"`",
"${",
"path",
"}",
"`",
")",
".",
"catch",
"(",
"e",
"=>",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"`",
"${",
"version",
"}",
"${",
"f",
"}",
"`",
")",
")",
"return",
"Promise",
".",
"resolve",
"(",
")",
"}",
")",
"}",
")",
")",
"return",
"Promise",
".",
"all",
"(",
"proms",
")",
"}"
]
| Downloads bootstrap js and font files by given version to destination path.
@param {String} version Semver
@param {String} path Save destination
@return {Promise} | [
"Downloads",
"bootstrap",
"js",
"and",
"font",
"files",
"by",
"given",
"version",
"to",
"destination",
"path",
"."
]
| c087ae53cf83ff7714dff7d470c12d2da1e44fd1 | https://github.com/dbtek/bootswatch-dist/blob/c087ae53cf83ff7714dff7d470c12d2da1e44fd1/build.js#L131-L161 |
43,613 | dbtek/bootswatch-dist | build.js | updatePackageInfo | function updatePackageInfo(theme, version) {
const cwd = `.tmp/${version}/${theme}/publish`
bower.version = `${version}-${theme}`
pkg.version = `${version}-${theme}`
return Promise.all([
fs.writeFile(`${cwd}/bower.json`, JSON.stringify(bower, null, 4)),
fs.writeFile(`${cwd}/package.json`, JSON.stringify(pkg, null, 4))
])
} | javascript | function updatePackageInfo(theme, version) {
const cwd = `.tmp/${version}/${theme}/publish`
bower.version = `${version}-${theme}`
pkg.version = `${version}-${theme}`
return Promise.all([
fs.writeFile(`${cwd}/bower.json`, JSON.stringify(bower, null, 4)),
fs.writeFile(`${cwd}/package.json`, JSON.stringify(pkg, null, 4))
])
} | [
"function",
"updatePackageInfo",
"(",
"theme",
",",
"version",
")",
"{",
"const",
"cwd",
"=",
"`",
"${",
"version",
"}",
"${",
"theme",
"}",
"`",
"bower",
".",
"version",
"=",
"`",
"${",
"version",
"}",
"${",
"theme",
"}",
"`",
"pkg",
".",
"version",
"=",
"`",
"${",
"version",
"}",
"${",
"theme",
"}",
"`",
"return",
"Promise",
".",
"all",
"(",
"[",
"fs",
".",
"writeFile",
"(",
"`",
"${",
"cwd",
"}",
"`",
",",
"JSON",
".",
"stringify",
"(",
"bower",
",",
"null",
",",
"4",
")",
")",
",",
"fs",
".",
"writeFile",
"(",
"`",
"${",
"cwd",
"}",
"`",
",",
"JSON",
".",
"stringify",
"(",
"pkg",
",",
"null",
",",
"4",
")",
")",
"]",
")",
"}"
]
| Creates bower.json and package.json with content relevant to theme.
@param {String} theme Theme name
@param {String} version Semver
@return {Promise} | [
"Creates",
"bower",
".",
"json",
"and",
"package",
".",
"json",
"with",
"content",
"relevant",
"to",
"theme",
"."
]
| c087ae53cf83ff7714dff7d470c12d2da1e44fd1 | https://github.com/dbtek/bootswatch-dist/blob/c087ae53cf83ff7714dff7d470c12d2da1e44fd1/build.js#L211-L219 |
43,614 | dbtek/bootswatch-dist | build.js | releaseTheme | function releaseTheme(theme, version) {
const repoPath = `.tmp/${version}/${theme}/publish`
return setupThemeRepo(theme, version)
.then(() => {
console.log(chalk.blue('Committing changes...'))
return new Promise((resolve, reject) => {
// commit changes
git.add(['css', 'js', 'fonts', 'bower.json', 'package.json'], (err) =>{
if (err) return reject(err)
git.commit(`${version} upgrade :arrow_up:`, ['.'], (err, res) => {
if (err) return reject(err)
// tag current version (3.3.7-cerulean)
git.addTag(cleanVersion(version) + '-' + theme, (err) => {
if (err) return reject(err)
console.log(chalk.blue('Pushing commit...'))
// push commit
git.push('origin', theme, (err) => {
if (err) return reject(err)
console.log(chalk.blue('Pushing tag...'))
// push new tag
git.pushTags('origin', (err) => {
if (err) return reject(err)
console.log(chalk.green(`${theme} published.`))
resolve()
})
})
})
})
})
})
})
} | javascript | function releaseTheme(theme, version) {
const repoPath = `.tmp/${version}/${theme}/publish`
return setupThemeRepo(theme, version)
.then(() => {
console.log(chalk.blue('Committing changes...'))
return new Promise((resolve, reject) => {
// commit changes
git.add(['css', 'js', 'fonts', 'bower.json', 'package.json'], (err) =>{
if (err) return reject(err)
git.commit(`${version} upgrade :arrow_up:`, ['.'], (err, res) => {
if (err) return reject(err)
// tag current version (3.3.7-cerulean)
git.addTag(cleanVersion(version) + '-' + theme, (err) => {
if (err) return reject(err)
console.log(chalk.blue('Pushing commit...'))
// push commit
git.push('origin', theme, (err) => {
if (err) return reject(err)
console.log(chalk.blue('Pushing tag...'))
// push new tag
git.pushTags('origin', (err) => {
if (err) return reject(err)
console.log(chalk.green(`${theme} published.`))
resolve()
})
})
})
})
})
})
})
} | [
"function",
"releaseTheme",
"(",
"theme",
",",
"version",
")",
"{",
"const",
"repoPath",
"=",
"`",
"${",
"version",
"}",
"${",
"theme",
"}",
"`",
"return",
"setupThemeRepo",
"(",
"theme",
",",
"version",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'Committing changes...'",
")",
")",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"// commit changes",
"git",
".",
"add",
"(",
"[",
"'css'",
",",
"'js'",
",",
"'fonts'",
",",
"'bower.json'",
",",
"'package.json'",
"]",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"git",
".",
"commit",
"(",
"`",
"${",
"version",
"}",
"`",
",",
"[",
"'.'",
"]",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"// tag current version (3.3.7-cerulean)",
"git",
".",
"addTag",
"(",
"cleanVersion",
"(",
"version",
")",
"+",
"'-'",
"+",
"theme",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'Pushing commit...'",
")",
")",
"// push commit",
"git",
".",
"push",
"(",
"'origin'",
",",
"theme",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'Pushing tag...'",
")",
")",
"// push new tag",
"git",
".",
"pushTags",
"(",
"'origin'",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"console",
".",
"log",
"(",
"chalk",
".",
"green",
"(",
"`",
"${",
"theme",
"}",
"`",
")",
")",
"resolve",
"(",
")",
"}",
")",
"}",
")",
"}",
")",
"}",
")",
"}",
")",
"}",
")",
"}",
")",
"}"
]
| Releases new theme version
@param {String} theme Theme name
@param {String} version Semver
@return {Promise} | [
"Releases",
"new",
"theme",
"version"
]
| c087ae53cf83ff7714dff7d470c12d2da1e44fd1 | https://github.com/dbtek/bootswatch-dist/blob/c087ae53cf83ff7714dff7d470c12d2da1e44fd1/build.js#L227-L258 |
43,615 | happilymarrieddad/puglatizer | puglatizer.js | function(callback) {
fs.stat(outputFile,function(err,stat) {
if (err) { return callback(null) }
console.log('Found old ' + outputFile + ' so now removing')
fs.unlinkSync(outputFile)
return callback(null)
})
} | javascript | function(callback) {
fs.stat(outputFile,function(err,stat) {
if (err) { return callback(null) }
console.log('Found old ' + outputFile + ' so now removing')
fs.unlinkSync(outputFile)
return callback(null)
})
} | [
"function",
"(",
"callback",
")",
"{",
"fs",
".",
"stat",
"(",
"outputFile",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"null",
")",
"}",
"console",
".",
"log",
"(",
"'Found old '",
"+",
"outputFile",
"+",
"' so now removing'",
")",
"fs",
".",
"unlinkSync",
"(",
"outputFile",
")",
"return",
"callback",
"(",
"null",
")",
"}",
")",
"}"
]
| Unbuild old template file if exists | [
"Unbuild",
"old",
"template",
"file",
"if",
"exists"
]
| 59678b13021c697b822bb45f9eb3ffc6a071c2ad | https://github.com/happilymarrieddad/puglatizer/blob/59678b13021c697b822bb45f9eb3ffc6a071c2ad/puglatizer.js#L46-L53 |
|
43,616 | happilymarrieddad/puglatizer | puglatizer.js | function(callback) {
fs.appendFileSync(outputFile,";(function(root,factory){\r\n")
fs.appendFileSync(outputFile," if (typeof define === 'function' && define.amd) {\r\n")
fs.appendFileSync(outputFile," define([], factory);\r\n")
fs.appendFileSync(outputFile," } else if (typeof exports === 'object') {\r\n")
fs.appendFileSync(outputFile," module.exports = factory();\r\n")
fs.appendFileSync(outputFile," } else {\r\n")
fs.appendFileSync(outputFile," if (typeof root === 'undefined' || root !== Object(root)) {\r\n")
fs.appendFileSync(outputFile," throw new Error('puglatizer: window does not exist or is not an object');\r\n")
fs.appendFileSync(outputFile," }\r\n")
fs.appendFileSync(outputFile," root.puglatizer = factory();\r\n")
fs.appendFileSync(outputFile," }\r\n")
fs.appendFileSync(outputFile,"}(this, function () {\r\n")
fs.appendFileSync(outputFile," function pug_classes_object(val) { var classString = '', padding = ''; for (var key in val) { if (key && val[key] && pug_has_own_property.call(val, key)) { var classString = classString + padding + key; var padding = ' '; } } return classString; }")
fs.appendFileSync(outputFile," function pug_classes_array(val, escaping) { var classString = '', className, padding = '', escapeEnabled = Array.isArray(escaping); for (var i = 0; i < val.length; i++) { var className = pug_classes(val[i]); if (!className) continue; escapeEnabled && escaping[i] && (className = pug_escape(className)); var classString = classString + padding + className; var padding = ' '; } return classString; }")
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.merge.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.classes.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.style.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.attr.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.attrs.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.escape.toString()).replace('pug_match_html','(/[\"&<>]/)') + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.rethrow.toString()) + '\r\n')
fs.appendFileSync(outputFile," var pug = {\r\n")
fs.appendFileSync(outputFile," merge:" + minify.js(pug.runtime.merge.toString()) + ',\r\n')
fs.appendFileSync(outputFile," classes:" + minify.js(pug.runtime.classes.toString()) + ',\r\n')
fs.appendFileSync(outputFile," style:" + minify.js(pug.runtime.style.toString()) + ',\r\n')
fs.appendFileSync(outputFile," attr:" + minify.js(pug.runtime.attr.toString()) + ',\r\n')
fs.appendFileSync(outputFile," attrs:" + minify.js(pug.runtime.attrs.toString()) + ',\r\n')
fs.appendFileSync(outputFile," escape:" + minify.js(pug.runtime.escape.toString()).replace('pug_match_html','(/[\"&<>]/)') + ',\r\n')
fs.appendFileSync(outputFile," rethrow:" + minify.js(pug.runtime.rethrow.toString()) + '\r\n')
fs.appendFileSync(outputFile," }\r\n")
fs.appendFileSync(outputFile,"\r\n")
fs.appendFileSync(outputFile,' var puglatizer = {}')
fs.appendFileSync(outputFile,"\r\n")
return callback()
} | javascript | function(callback) {
fs.appendFileSync(outputFile,";(function(root,factory){\r\n")
fs.appendFileSync(outputFile," if (typeof define === 'function' && define.amd) {\r\n")
fs.appendFileSync(outputFile," define([], factory);\r\n")
fs.appendFileSync(outputFile," } else if (typeof exports === 'object') {\r\n")
fs.appendFileSync(outputFile," module.exports = factory();\r\n")
fs.appendFileSync(outputFile," } else {\r\n")
fs.appendFileSync(outputFile," if (typeof root === 'undefined' || root !== Object(root)) {\r\n")
fs.appendFileSync(outputFile," throw new Error('puglatizer: window does not exist or is not an object');\r\n")
fs.appendFileSync(outputFile," }\r\n")
fs.appendFileSync(outputFile," root.puglatizer = factory();\r\n")
fs.appendFileSync(outputFile," }\r\n")
fs.appendFileSync(outputFile,"}(this, function () {\r\n")
fs.appendFileSync(outputFile," function pug_classes_object(val) { var classString = '', padding = ''; for (var key in val) { if (key && val[key] && pug_has_own_property.call(val, key)) { var classString = classString + padding + key; var padding = ' '; } } return classString; }")
fs.appendFileSync(outputFile," function pug_classes_array(val, escaping) { var classString = '', className, padding = '', escapeEnabled = Array.isArray(escaping); for (var i = 0; i < val.length; i++) { var className = pug_classes(val[i]); if (!className) continue; escapeEnabled && escaping[i] && (className = pug_escape(className)); var classString = classString + padding + className; var padding = ' '; } return classString; }")
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.merge.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.classes.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.style.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.attr.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.attrs.toString()) + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.escape.toString()).replace('pug_match_html','(/[\"&<>]/)') + '\r\n')
fs.appendFileSync(outputFile," " + minify.js(pug.runtime.rethrow.toString()) + '\r\n')
fs.appendFileSync(outputFile," var pug = {\r\n")
fs.appendFileSync(outputFile," merge:" + minify.js(pug.runtime.merge.toString()) + ',\r\n')
fs.appendFileSync(outputFile," classes:" + minify.js(pug.runtime.classes.toString()) + ',\r\n')
fs.appendFileSync(outputFile," style:" + minify.js(pug.runtime.style.toString()) + ',\r\n')
fs.appendFileSync(outputFile," attr:" + minify.js(pug.runtime.attr.toString()) + ',\r\n')
fs.appendFileSync(outputFile," attrs:" + minify.js(pug.runtime.attrs.toString()) + ',\r\n')
fs.appendFileSync(outputFile," escape:" + minify.js(pug.runtime.escape.toString()).replace('pug_match_html','(/[\"&<>]/)') + ',\r\n')
fs.appendFileSync(outputFile," rethrow:" + minify.js(pug.runtime.rethrow.toString()) + '\r\n')
fs.appendFileSync(outputFile," }\r\n")
fs.appendFileSync(outputFile,"\r\n")
fs.appendFileSync(outputFile,' var puglatizer = {}')
fs.appendFileSync(outputFile,"\r\n")
return callback()
} | [
"function",
"(",
"callback",
")",
"{",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\";(function(root,factory){\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" if (typeof define === 'function' && define.amd) {\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" define([], factory);\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" } else if (typeof exports === 'object') {\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" module.exports = factory();\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" } else {\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" if (typeof root === 'undefined' || root !== Object(root)) {\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" throw new Error('puglatizer: window does not exist or is not an object');\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" }\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" root.puglatizer = factory();\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" }\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\"}(this, function () {\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" function pug_classes_object(val) { var classString = '', padding = ''; for (var key in val) { if (key && val[key] && pug_has_own_property.call(val, key)) { var classString = classString + padding + key; var padding = ' '; } } return classString; }\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" function pug_classes_array(val, escaping) { var classString = '', className, padding = '', escapeEnabled = Array.isArray(escaping); for (var i = 0; i < val.length; i++) { var className = pug_classes(val[i]); if (!className) continue; escapeEnabled && escaping[i] && (className = pug_escape(className)); var classString = classString + padding + className; var padding = ' '; } return classString; }\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"merge",
".",
"toString",
"(",
")",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"classes",
".",
"toString",
"(",
")",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"style",
".",
"toString",
"(",
")",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"attr",
".",
"toString",
"(",
")",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"attrs",
".",
"toString",
"(",
")",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"escape",
".",
"toString",
"(",
")",
")",
".",
"replace",
"(",
"'pug_match_html'",
",",
"'(/[\\\"&<>]/)'",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"rethrow",
".",
"toString",
"(",
")",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" var pug = {\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \tmerge:\"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"merge",
".",
"toString",
"(",
")",
")",
"+",
"',\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \tclasses:\"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"classes",
".",
"toString",
"(",
")",
")",
"+",
"',\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \tstyle:\"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"style",
".",
"toString",
"(",
")",
")",
"+",
"',\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \tattr:\"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"attr",
".",
"toString",
"(",
")",
")",
"+",
"',\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \tattrs:\"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"attrs",
".",
"toString",
"(",
")",
")",
"+",
"',\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \tescape:\"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"escape",
".",
"toString",
"(",
")",
")",
".",
"replace",
"(",
"'pug_match_html'",
",",
"'(/[\\\"&<>]/)'",
")",
"+",
"',\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" \trethrow:\"",
"+",
"minify",
".",
"js",
"(",
"pug",
".",
"runtime",
".",
"rethrow",
".",
"toString",
"(",
")",
")",
"+",
"'\\r\\n'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" }\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\"\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"' var puglatizer = {}'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\"\\r\\n\"",
")",
"return",
"callback",
"(",
")",
"}"
]
| Create the initial file | [
"Create",
"the",
"initial",
"file"
]
| 59678b13021c697b822bb45f9eb3ffc6a071c2ad | https://github.com/happilymarrieddad/puglatizer/blob/59678b13021c697b822bb45f9eb3ffc6a071c2ad/puglatizer.js#L55-L90 |
|
43,617 | happilymarrieddad/puglatizer | puglatizer.js | function(callback) {
var fileLoop = function(currentDir,templateDirectories,cb) {
var callback_has_been_called = false
fs.readdir(currentDir,function(err,files) {
if (err) {
return console.log('Unable to find files in path',currentDir)
}
var num = files.length
var finishFile = function(i) {
if (!(--num)) {
if (!callback_has_been_called) {
callback_has_been_called = true
return cb()
}
} else {
buildFileData(i+1)
}
}
var buildFileData = function(i) {
var file = files[i]
var filepath = currentDir + '/' + file
fs.stat(filepath,function(err2,stats) {
if (err2) {
return console.log('Unable to find file',filepath)
}
if (stats && stats.isDirectory()) {
var pugatizerPath = ' puglatizer' + currentDir.replace(templateDirectories,'').replace(/\//g,'"]["') + '"]["' + file.replace('.pug','') + '"] = {}\r\n'
pugatizerPath = pugatizerPath.replace('puglatizer"]','puglatizer')
fs.appendFileSync(outputFile,pugatizerPath)
fileLoop(filepath,templateDirectories,function() {
finishFile(i)
})
} else if (stats && stats.isFile()) {
var ext = path.extname(filepath)
if (ext == '.pug') {
var pugatizerPath = ' puglatizer' + currentDir.replace(templateDirectories,'').replace(/\//g,'"]["') + '"]["' + file.replace('.pug','') + '"] = '
pugatizerPath = pugatizerPath.replace('puglatizer"]','puglatizer')
buildTemplateFromFile(filepath,options,function(err,template) {
pugatizerPath += minify.js(template.toString()) + ';\r\n\r\n'
fs.appendFileSync(outputFile,pugatizerPath)
finishFile(i)
})
} else {
finishFile(i)
}
} else {
finishFile(i)
}
})
}
if (!num) {
return console.log('Unable to find files in path',currentDir)
} else {
buildFileData(0)
}
})
}
fileLoop(templateDirectories,templateDirectories,function() {
return callback()
})
} | javascript | function(callback) {
var fileLoop = function(currentDir,templateDirectories,cb) {
var callback_has_been_called = false
fs.readdir(currentDir,function(err,files) {
if (err) {
return console.log('Unable to find files in path',currentDir)
}
var num = files.length
var finishFile = function(i) {
if (!(--num)) {
if (!callback_has_been_called) {
callback_has_been_called = true
return cb()
}
} else {
buildFileData(i+1)
}
}
var buildFileData = function(i) {
var file = files[i]
var filepath = currentDir + '/' + file
fs.stat(filepath,function(err2,stats) {
if (err2) {
return console.log('Unable to find file',filepath)
}
if (stats && stats.isDirectory()) {
var pugatizerPath = ' puglatizer' + currentDir.replace(templateDirectories,'').replace(/\//g,'"]["') + '"]["' + file.replace('.pug','') + '"] = {}\r\n'
pugatizerPath = pugatizerPath.replace('puglatizer"]','puglatizer')
fs.appendFileSync(outputFile,pugatizerPath)
fileLoop(filepath,templateDirectories,function() {
finishFile(i)
})
} else if (stats && stats.isFile()) {
var ext = path.extname(filepath)
if (ext == '.pug') {
var pugatizerPath = ' puglatizer' + currentDir.replace(templateDirectories,'').replace(/\//g,'"]["') + '"]["' + file.replace('.pug','') + '"] = '
pugatizerPath = pugatizerPath.replace('puglatizer"]','puglatizer')
buildTemplateFromFile(filepath,options,function(err,template) {
pugatizerPath += minify.js(template.toString()) + ';\r\n\r\n'
fs.appendFileSync(outputFile,pugatizerPath)
finishFile(i)
})
} else {
finishFile(i)
}
} else {
finishFile(i)
}
})
}
if (!num) {
return console.log('Unable to find files in path',currentDir)
} else {
buildFileData(0)
}
})
}
fileLoop(templateDirectories,templateDirectories,function() {
return callback()
})
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"fileLoop",
"=",
"function",
"(",
"currentDir",
",",
"templateDirectories",
",",
"cb",
")",
"{",
"var",
"callback_has_been_called",
"=",
"false",
"fs",
".",
"readdir",
"(",
"currentDir",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"console",
".",
"log",
"(",
"'Unable to find files in path'",
",",
"currentDir",
")",
"}",
"var",
"num",
"=",
"files",
".",
"length",
"var",
"finishFile",
"=",
"function",
"(",
"i",
")",
"{",
"if",
"(",
"!",
"(",
"--",
"num",
")",
")",
"{",
"if",
"(",
"!",
"callback_has_been_called",
")",
"{",
"callback_has_been_called",
"=",
"true",
"return",
"cb",
"(",
")",
"}",
"}",
"else",
"{",
"buildFileData",
"(",
"i",
"+",
"1",
")",
"}",
"}",
"var",
"buildFileData",
"=",
"function",
"(",
"i",
")",
"{",
"var",
"file",
"=",
"files",
"[",
"i",
"]",
"var",
"filepath",
"=",
"currentDir",
"+",
"'/'",
"+",
"file",
"fs",
".",
"stat",
"(",
"filepath",
",",
"function",
"(",
"err2",
",",
"stats",
")",
"{",
"if",
"(",
"err2",
")",
"{",
"return",
"console",
".",
"log",
"(",
"'Unable to find file'",
",",
"filepath",
")",
"}",
"if",
"(",
"stats",
"&&",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"var",
"pugatizerPath",
"=",
"' puglatizer'",
"+",
"currentDir",
".",
"replace",
"(",
"templateDirectories",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'\"][\"'",
")",
"+",
"'\"][\"'",
"+",
"file",
".",
"replace",
"(",
"'.pug'",
",",
"''",
")",
"+",
"'\"] = {}\\r\\n'",
"pugatizerPath",
"=",
"pugatizerPath",
".",
"replace",
"(",
"'puglatizer\"]'",
",",
"'puglatizer'",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"pugatizerPath",
")",
"fileLoop",
"(",
"filepath",
",",
"templateDirectories",
",",
"function",
"(",
")",
"{",
"finishFile",
"(",
"i",
")",
"}",
")",
"}",
"else",
"if",
"(",
"stats",
"&&",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"var",
"ext",
"=",
"path",
".",
"extname",
"(",
"filepath",
")",
"if",
"(",
"ext",
"==",
"'.pug'",
")",
"{",
"var",
"pugatizerPath",
"=",
"' puglatizer'",
"+",
"currentDir",
".",
"replace",
"(",
"templateDirectories",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'\"][\"'",
")",
"+",
"'\"][\"'",
"+",
"file",
".",
"replace",
"(",
"'.pug'",
",",
"''",
")",
"+",
"'\"] = '",
"pugatizerPath",
"=",
"pugatizerPath",
".",
"replace",
"(",
"'puglatizer\"]'",
",",
"'puglatizer'",
")",
"buildTemplateFromFile",
"(",
"filepath",
",",
"options",
",",
"function",
"(",
"err",
",",
"template",
")",
"{",
"pugatizerPath",
"+=",
"minify",
".",
"js",
"(",
"template",
".",
"toString",
"(",
")",
")",
"+",
"';\\r\\n\\r\\n'",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"pugatizerPath",
")",
"finishFile",
"(",
"i",
")",
"}",
")",
"}",
"else",
"{",
"finishFile",
"(",
"i",
")",
"}",
"}",
"else",
"{",
"finishFile",
"(",
"i",
")",
"}",
"}",
")",
"}",
"if",
"(",
"!",
"num",
")",
"{",
"return",
"console",
".",
"log",
"(",
"'Unable to find files in path'",
",",
"currentDir",
")",
"}",
"else",
"{",
"buildFileData",
"(",
"0",
")",
"}",
"}",
")",
"}",
"fileLoop",
"(",
"templateDirectories",
",",
"templateDirectories",
",",
"function",
"(",
")",
"{",
"return",
"callback",
"(",
")",
"}",
")",
"}"
]
| Here we build all the pug functions | [
"Here",
"we",
"build",
"all",
"the",
"pug",
"functions"
]
| 59678b13021c697b822bb45f9eb3ffc6a071c2ad | https://github.com/happilymarrieddad/puglatizer/blob/59678b13021c697b822bb45f9eb3ffc6a071c2ad/puglatizer.js#L92-L161 |
|
43,618 | happilymarrieddad/puglatizer | puglatizer.js | function(callback) {
fs.appendFileSync(outputFile,"\r\n")
fs.appendFileSync(outputFile," return puglatizer;\r\n")
fs.appendFileSync(outputFile,"}));\r\n")
return callback()
} | javascript | function(callback) {
fs.appendFileSync(outputFile,"\r\n")
fs.appendFileSync(outputFile," return puglatizer;\r\n")
fs.appendFileSync(outputFile,"}));\r\n")
return callback()
} | [
"function",
"(",
"callback",
")",
"{",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\"\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\" return puglatizer;\\r\\n\"",
")",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"\"}));\\r\\n\"",
")",
"return",
"callback",
"(",
")",
"}"
]
| Finalize the file | [
"Finalize",
"the",
"file"
]
| 59678b13021c697b822bb45f9eb3ffc6a071c2ad | https://github.com/happilymarrieddad/puglatizer/blob/59678b13021c697b822bb45f9eb3ffc6a071c2ad/puglatizer.js#L163-L169 |
|
43,619 | jasonslyvia/redux-composable-fetch | lib/index.js | resolveHandler | function resolveHandler(_ref4) {
var action = _ref4.action;
var type = _ref4.type;
var payload = _ref4.payload;
var error = _ref4.error;
return _extends({}, action, { type: type, payload: payload, error: error });
} | javascript | function resolveHandler(_ref4) {
var action = _ref4.action;
var type = _ref4.type;
var payload = _ref4.payload;
var error = _ref4.error;
return _extends({}, action, { type: type, payload: payload, error: error });
} | [
"function",
"resolveHandler",
"(",
"_ref4",
")",
"{",
"var",
"action",
"=",
"_ref4",
".",
"action",
";",
"var",
"type",
"=",
"_ref4",
".",
"type",
";",
"var",
"payload",
"=",
"_ref4",
".",
"payload",
";",
"var",
"error",
"=",
"_ref4",
".",
"error",
";",
"return",
"_extends",
"(",
"{",
"}",
",",
"action",
",",
"{",
"type",
":",
"type",
",",
"payload",
":",
"payload",
",",
"error",
":",
"error",
"}",
")",
";",
"}"
]
| For unify the action being dispatched, you might NOT need it! `result` might be the payload or the error, depending how the request end up | [
"For",
"unify",
"the",
"action",
"being",
"dispatched",
"you",
"might",
"NOT",
"need",
"it!",
"result",
"might",
"be",
"the",
"payload",
"or",
"the",
"error",
"depending",
"how",
"the",
"request",
"end",
"up"
]
| eb4676077747692092d7ee1d2d63be16e455e662 | https://github.com/jasonslyvia/redux-composable-fetch/blob/eb4676077747692092d7ee1d2d63be16e455e662/lib/index.js#L49-L55 |
43,620 | jasonslyvia/redux-composable-fetch | lib/index.js | createFetchMiddleware | function createFetchMiddleware() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var finalConfig = _extends({}, config);
// Be compatible with previous API
if (typeof config === 'boolean') {
finalConfig.promiseMode = config;
}
var _finalConfig$promiseM = finalConfig.promiseMode;
var promiseMode = _finalConfig$promiseM === undefined ? false : _finalConfig$promiseM;
var _finalConfig$rejectHa = finalConfig.rejectHard;
var rejectHard = _finalConfig$rejectHa === undefined ? false : _finalConfig$rejectHa;
var _options$beforeFetch = options.beforeFetch;
var beforeFetch = _options$beforeFetch === undefined ? defaultBeforeFetch : _options$beforeFetch;
var _options$afterFetch = options.afterFetch;
var afterFetch = _options$afterFetch === undefined ? defaultAfterFetch : _options$afterFetch;
var _options$onReject = options.onReject;
var onReject = _options$onReject === undefined ? rejectHandler : _options$onReject;
var _options$onResolve = options.onResolve;
var onResolve = _options$onResolve === undefined ? resolveHandler : _options$onResolve;
return function () {
return function () {
var next = arguments.length <= 0 || arguments[0] === undefined ? noop : arguments[0];
return function (action) {
if (!promiseMode && (!action.url || !action.types)) {
return next(action);
}
if (promiseMode && !action.url) {
throw new Error('[fetch-middleware] Missing required key: `url`');
}
var loadingType = void 0;
var successType = void 0;
var failureType = void 0;
if (!promiseMode) {
var _action$types = _slicedToArray(action.types, 3);
loadingType = _action$types[0];
successType = _action$types[1];
failureType = _action$types[2];
}
if (loadingType) {
try {
next(_extends({}, action, {
type: loadingType
}));
} catch (err) {
console.error('[fetch-middleware] Uncaught error while dispatching `' + loadingType + '`\n', err.stack);
}
}
var beforeFetchResult = void 0;
try {
beforeFetchResult = beforeFetch({ action: action });
} catch (err) {
throw new Error('[fetch-middleware] Uncaught error in `beforeFetch` middleware', err.stack);
}
if (!(beforeFetchResult instanceof Promise)) {
throw new TypeError('[fetch-middleware] `beforeFetch` middleware returned a non-Promise object, instead got:', beforeFetchResult);
}
return beforeFetchResult.then(function (args) {
if (!args || (typeof args === 'undefined' ? 'undefined' : _typeof(args)) !== 'object' || !hasOwn(args, 'action')) {
console.error('[fetch-middleware] `beforeFetch` should resolve an object containing `action` key, instead got:', args);
return Promise.reject(args);
}
return args;
}).then(function (_ref5) {
var action = _ref5.action;
var url = action.url;
var types = action.types;
var useJsonp = action.useJsonp;
var options = _objectWithoutProperties(action, ['url', 'types', 'useJsonp']); // eslint-disable-line
return (useJsonp ? (0, _jsonpFetch2.default)(url, options) : fetch(url, options)).then(function (result) {
return Promise.resolve({
action: action,
result: result
});
}, function (err) {
return Promise.reject({
action: action,
error: err
});
});
}).then(function (_ref6) {
var action = _ref6.action;
var result = _ref6.result;
var afterFetchResult = void 0;
try {
afterFetchResult = afterFetch({ action: action, result: result });
} catch (err) {
console.error('[fetch-middleware] Uncaught error in `afterFetch` middleware\n', err.stack);
}
if (!(afterFetchResult instanceof Promise)) {
console.error('[fetch-middleware] `afterFetch` middleware returned a non-Promise object');
return Promise.reject();
}
return afterFetchResult;
}).then(function (args) {
if (!args || (typeof args === 'undefined' ? 'undefined' : _typeof(args)) !== 'object' || !hasOwn(args, 'action', 'result')) {
console.error('[fetch-middleware] `afterFetch` should resolve an object ' + 'containing `action` and `result` key, instead got', args);
return Promise.reject(args);
}
return args;
}).catch(function (err) {
if (err instanceof Error || (typeof err === 'undefined' ? 'undefined' : _typeof(err)) !== 'object' || !hasOwn(err, 'action', 'error')) {
return onReject({
action: action,
error: err
});
}
return onReject(err);
}).then(function (_ref7) {
var action = _ref7.action;
var result = _ref7.result;
if (successType) {
try {
next(onResolve({
action: action,
type: successType,
payload: result,
error: false
}));
} catch (err) {
console.error('[fetch-middleware] Uncaught error while dispatching `' + successType + '`\n', err.stack);
}
}
return Promise.resolve(result);
}).catch(function (_ref8) {
var action = _ref8.action;
var error = _ref8.error;
// By default, final `catch` will resolve silently with `undefiend`
// since we assume all related logoic has been taken care of in reducers
if (failureType) {
try {
next(onResolve({
action: action,
type: failureType,
payload: error,
error: true
}));
} catch (err) {
console.error('[fetch-middleware] Uncaught error while dispatching `' + failureType + '`\n', err.stack);
}
}
// But you can force reject by setting `config.rejectHard` to true,
// if you'd like to make use of this promise directly
if (!failureType || rejectHard) {
return Promise.reject(error);
}
});
};
};
};
} | javascript | function createFetchMiddleware() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var finalConfig = _extends({}, config);
// Be compatible with previous API
if (typeof config === 'boolean') {
finalConfig.promiseMode = config;
}
var _finalConfig$promiseM = finalConfig.promiseMode;
var promiseMode = _finalConfig$promiseM === undefined ? false : _finalConfig$promiseM;
var _finalConfig$rejectHa = finalConfig.rejectHard;
var rejectHard = _finalConfig$rejectHa === undefined ? false : _finalConfig$rejectHa;
var _options$beforeFetch = options.beforeFetch;
var beforeFetch = _options$beforeFetch === undefined ? defaultBeforeFetch : _options$beforeFetch;
var _options$afterFetch = options.afterFetch;
var afterFetch = _options$afterFetch === undefined ? defaultAfterFetch : _options$afterFetch;
var _options$onReject = options.onReject;
var onReject = _options$onReject === undefined ? rejectHandler : _options$onReject;
var _options$onResolve = options.onResolve;
var onResolve = _options$onResolve === undefined ? resolveHandler : _options$onResolve;
return function () {
return function () {
var next = arguments.length <= 0 || arguments[0] === undefined ? noop : arguments[0];
return function (action) {
if (!promiseMode && (!action.url || !action.types)) {
return next(action);
}
if (promiseMode && !action.url) {
throw new Error('[fetch-middleware] Missing required key: `url`');
}
var loadingType = void 0;
var successType = void 0;
var failureType = void 0;
if (!promiseMode) {
var _action$types = _slicedToArray(action.types, 3);
loadingType = _action$types[0];
successType = _action$types[1];
failureType = _action$types[2];
}
if (loadingType) {
try {
next(_extends({}, action, {
type: loadingType
}));
} catch (err) {
console.error('[fetch-middleware] Uncaught error while dispatching `' + loadingType + '`\n', err.stack);
}
}
var beforeFetchResult = void 0;
try {
beforeFetchResult = beforeFetch({ action: action });
} catch (err) {
throw new Error('[fetch-middleware] Uncaught error in `beforeFetch` middleware', err.stack);
}
if (!(beforeFetchResult instanceof Promise)) {
throw new TypeError('[fetch-middleware] `beforeFetch` middleware returned a non-Promise object, instead got:', beforeFetchResult);
}
return beforeFetchResult.then(function (args) {
if (!args || (typeof args === 'undefined' ? 'undefined' : _typeof(args)) !== 'object' || !hasOwn(args, 'action')) {
console.error('[fetch-middleware] `beforeFetch` should resolve an object containing `action` key, instead got:', args);
return Promise.reject(args);
}
return args;
}).then(function (_ref5) {
var action = _ref5.action;
var url = action.url;
var types = action.types;
var useJsonp = action.useJsonp;
var options = _objectWithoutProperties(action, ['url', 'types', 'useJsonp']); // eslint-disable-line
return (useJsonp ? (0, _jsonpFetch2.default)(url, options) : fetch(url, options)).then(function (result) {
return Promise.resolve({
action: action,
result: result
});
}, function (err) {
return Promise.reject({
action: action,
error: err
});
});
}).then(function (_ref6) {
var action = _ref6.action;
var result = _ref6.result;
var afterFetchResult = void 0;
try {
afterFetchResult = afterFetch({ action: action, result: result });
} catch (err) {
console.error('[fetch-middleware] Uncaught error in `afterFetch` middleware\n', err.stack);
}
if (!(afterFetchResult instanceof Promise)) {
console.error('[fetch-middleware] `afterFetch` middleware returned a non-Promise object');
return Promise.reject();
}
return afterFetchResult;
}).then(function (args) {
if (!args || (typeof args === 'undefined' ? 'undefined' : _typeof(args)) !== 'object' || !hasOwn(args, 'action', 'result')) {
console.error('[fetch-middleware] `afterFetch` should resolve an object ' + 'containing `action` and `result` key, instead got', args);
return Promise.reject(args);
}
return args;
}).catch(function (err) {
if (err instanceof Error || (typeof err === 'undefined' ? 'undefined' : _typeof(err)) !== 'object' || !hasOwn(err, 'action', 'error')) {
return onReject({
action: action,
error: err
});
}
return onReject(err);
}).then(function (_ref7) {
var action = _ref7.action;
var result = _ref7.result;
if (successType) {
try {
next(onResolve({
action: action,
type: successType,
payload: result,
error: false
}));
} catch (err) {
console.error('[fetch-middleware] Uncaught error while dispatching `' + successType + '`\n', err.stack);
}
}
return Promise.resolve(result);
}).catch(function (_ref8) {
var action = _ref8.action;
var error = _ref8.error;
// By default, final `catch` will resolve silently with `undefiend`
// since we assume all related logoic has been taken care of in reducers
if (failureType) {
try {
next(onResolve({
action: action,
type: failureType,
payload: error,
error: true
}));
} catch (err) {
console.error('[fetch-middleware] Uncaught error while dispatching `' + failureType + '`\n', err.stack);
}
}
// But you can force reject by setting `config.rejectHard` to true,
// if you'd like to make use of this promise directly
if (!failureType || rejectHard) {
return Promise.reject(error);
}
});
};
};
};
} | [
"function",
"createFetchMiddleware",
"(",
")",
"{",
"var",
"options",
"=",
"arguments",
".",
"length",
"<=",
"0",
"||",
"arguments",
"[",
"0",
"]",
"===",
"undefined",
"?",
"{",
"}",
":",
"arguments",
"[",
"0",
"]",
";",
"var",
"config",
"=",
"arguments",
".",
"length",
"<=",
"1",
"||",
"arguments",
"[",
"1",
"]",
"===",
"undefined",
"?",
"{",
"}",
":",
"arguments",
"[",
"1",
"]",
";",
"var",
"finalConfig",
"=",
"_extends",
"(",
"{",
"}",
",",
"config",
")",
";",
"// Be compatible with previous API",
"if",
"(",
"typeof",
"config",
"===",
"'boolean'",
")",
"{",
"finalConfig",
".",
"promiseMode",
"=",
"config",
";",
"}",
"var",
"_finalConfig$promiseM",
"=",
"finalConfig",
".",
"promiseMode",
";",
"var",
"promiseMode",
"=",
"_finalConfig$promiseM",
"===",
"undefined",
"?",
"false",
":",
"_finalConfig$promiseM",
";",
"var",
"_finalConfig$rejectHa",
"=",
"finalConfig",
".",
"rejectHard",
";",
"var",
"rejectHard",
"=",
"_finalConfig$rejectHa",
"===",
"undefined",
"?",
"false",
":",
"_finalConfig$rejectHa",
";",
"var",
"_options$beforeFetch",
"=",
"options",
".",
"beforeFetch",
";",
"var",
"beforeFetch",
"=",
"_options$beforeFetch",
"===",
"undefined",
"?",
"defaultBeforeFetch",
":",
"_options$beforeFetch",
";",
"var",
"_options$afterFetch",
"=",
"options",
".",
"afterFetch",
";",
"var",
"afterFetch",
"=",
"_options$afterFetch",
"===",
"undefined",
"?",
"defaultAfterFetch",
":",
"_options$afterFetch",
";",
"var",
"_options$onReject",
"=",
"options",
".",
"onReject",
";",
"var",
"onReject",
"=",
"_options$onReject",
"===",
"undefined",
"?",
"rejectHandler",
":",
"_options$onReject",
";",
"var",
"_options$onResolve",
"=",
"options",
".",
"onResolve",
";",
"var",
"onResolve",
"=",
"_options$onResolve",
"===",
"undefined",
"?",
"resolveHandler",
":",
"_options$onResolve",
";",
"return",
"function",
"(",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"next",
"=",
"arguments",
".",
"length",
"<=",
"0",
"||",
"arguments",
"[",
"0",
"]",
"===",
"undefined",
"?",
"noop",
":",
"arguments",
"[",
"0",
"]",
";",
"return",
"function",
"(",
"action",
")",
"{",
"if",
"(",
"!",
"promiseMode",
"&&",
"(",
"!",
"action",
".",
"url",
"||",
"!",
"action",
".",
"types",
")",
")",
"{",
"return",
"next",
"(",
"action",
")",
";",
"}",
"if",
"(",
"promiseMode",
"&&",
"!",
"action",
".",
"url",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[fetch-middleware] Missing required key: `url`'",
")",
";",
"}",
"var",
"loadingType",
"=",
"void",
"0",
";",
"var",
"successType",
"=",
"void",
"0",
";",
"var",
"failureType",
"=",
"void",
"0",
";",
"if",
"(",
"!",
"promiseMode",
")",
"{",
"var",
"_action$types",
"=",
"_slicedToArray",
"(",
"action",
".",
"types",
",",
"3",
")",
";",
"loadingType",
"=",
"_action$types",
"[",
"0",
"]",
";",
"successType",
"=",
"_action$types",
"[",
"1",
"]",
";",
"failureType",
"=",
"_action$types",
"[",
"2",
"]",
";",
"}",
"if",
"(",
"loadingType",
")",
"{",
"try",
"{",
"next",
"(",
"_extends",
"(",
"{",
"}",
",",
"action",
",",
"{",
"type",
":",
"loadingType",
"}",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'[fetch-middleware] Uncaught error while dispatching `'",
"+",
"loadingType",
"+",
"'`\\n'",
",",
"err",
".",
"stack",
")",
";",
"}",
"}",
"var",
"beforeFetchResult",
"=",
"void",
"0",
";",
"try",
"{",
"beforeFetchResult",
"=",
"beforeFetch",
"(",
"{",
"action",
":",
"action",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[fetch-middleware] Uncaught error in `beforeFetch` middleware'",
",",
"err",
".",
"stack",
")",
";",
"}",
"if",
"(",
"!",
"(",
"beforeFetchResult",
"instanceof",
"Promise",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'[fetch-middleware] `beforeFetch` middleware returned a non-Promise object, instead got:'",
",",
"beforeFetchResult",
")",
";",
"}",
"return",
"beforeFetchResult",
".",
"then",
"(",
"function",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"args",
"||",
"(",
"typeof",
"args",
"===",
"'undefined'",
"?",
"'undefined'",
":",
"_typeof",
"(",
"args",
")",
")",
"!==",
"'object'",
"||",
"!",
"hasOwn",
"(",
"args",
",",
"'action'",
")",
")",
"{",
"console",
".",
"error",
"(",
"'[fetch-middleware] `beforeFetch` should resolve an object containing `action` key, instead got:'",
",",
"args",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"args",
")",
";",
"}",
"return",
"args",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"_ref5",
")",
"{",
"var",
"action",
"=",
"_ref5",
".",
"action",
";",
"var",
"url",
"=",
"action",
".",
"url",
";",
"var",
"types",
"=",
"action",
".",
"types",
";",
"var",
"useJsonp",
"=",
"action",
".",
"useJsonp",
";",
"var",
"options",
"=",
"_objectWithoutProperties",
"(",
"action",
",",
"[",
"'url'",
",",
"'types'",
",",
"'useJsonp'",
"]",
")",
";",
"// eslint-disable-line",
"return",
"(",
"useJsonp",
"?",
"(",
"0",
",",
"_jsonpFetch2",
".",
"default",
")",
"(",
"url",
",",
"options",
")",
":",
"fetch",
"(",
"url",
",",
"options",
")",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"{",
"action",
":",
"action",
",",
"result",
":",
"result",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"{",
"action",
":",
"action",
",",
"error",
":",
"err",
"}",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"_ref6",
")",
"{",
"var",
"action",
"=",
"_ref6",
".",
"action",
";",
"var",
"result",
"=",
"_ref6",
".",
"result",
";",
"var",
"afterFetchResult",
"=",
"void",
"0",
";",
"try",
"{",
"afterFetchResult",
"=",
"afterFetch",
"(",
"{",
"action",
":",
"action",
",",
"result",
":",
"result",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'[fetch-middleware] Uncaught error in `afterFetch` middleware\\n'",
",",
"err",
".",
"stack",
")",
";",
"}",
"if",
"(",
"!",
"(",
"afterFetchResult",
"instanceof",
"Promise",
")",
")",
"{",
"console",
".",
"error",
"(",
"'[fetch-middleware] `afterFetch` middleware returned a non-Promise object'",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
")",
";",
"}",
"return",
"afterFetchResult",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"args",
"||",
"(",
"typeof",
"args",
"===",
"'undefined'",
"?",
"'undefined'",
":",
"_typeof",
"(",
"args",
")",
")",
"!==",
"'object'",
"||",
"!",
"hasOwn",
"(",
"args",
",",
"'action'",
",",
"'result'",
")",
")",
"{",
"console",
".",
"error",
"(",
"'[fetch-middleware] `afterFetch` should resolve an object '",
"+",
"'containing `action` and `result` key, instead got'",
",",
"args",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"args",
")",
";",
"}",
"return",
"args",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"instanceof",
"Error",
"||",
"(",
"typeof",
"err",
"===",
"'undefined'",
"?",
"'undefined'",
":",
"_typeof",
"(",
"err",
")",
")",
"!==",
"'object'",
"||",
"!",
"hasOwn",
"(",
"err",
",",
"'action'",
",",
"'error'",
")",
")",
"{",
"return",
"onReject",
"(",
"{",
"action",
":",
"action",
",",
"error",
":",
"err",
"}",
")",
";",
"}",
"return",
"onReject",
"(",
"err",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"_ref7",
")",
"{",
"var",
"action",
"=",
"_ref7",
".",
"action",
";",
"var",
"result",
"=",
"_ref7",
".",
"result",
";",
"if",
"(",
"successType",
")",
"{",
"try",
"{",
"next",
"(",
"onResolve",
"(",
"{",
"action",
":",
"action",
",",
"type",
":",
"successType",
",",
"payload",
":",
"result",
",",
"error",
":",
"false",
"}",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'[fetch-middleware] Uncaught error while dispatching `'",
"+",
"successType",
"+",
"'`\\n'",
",",
"err",
".",
"stack",
")",
";",
"}",
"}",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"_ref8",
")",
"{",
"var",
"action",
"=",
"_ref8",
".",
"action",
";",
"var",
"error",
"=",
"_ref8",
".",
"error",
";",
"// By default, final `catch` will resolve silently with `undefiend`",
"// since we assume all related logoic has been taken care of in reducers",
"if",
"(",
"failureType",
")",
"{",
"try",
"{",
"next",
"(",
"onResolve",
"(",
"{",
"action",
":",
"action",
",",
"type",
":",
"failureType",
",",
"payload",
":",
"error",
",",
"error",
":",
"true",
"}",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'[fetch-middleware] Uncaught error while dispatching `'",
"+",
"failureType",
"+",
"'`\\n'",
",",
"err",
".",
"stack",
")",
";",
"}",
"}",
"// But you can force reject by setting `config.rejectHard` to true,",
"// if you'd like to make use of this promise directly",
"if",
"(",
"!",
"failureType",
"||",
"rejectHard",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}",
";",
"}",
";",
"}"
]
| Create a fetch middleware
@param {object} options Options for creating fetch middleware
@param {function} beforeFetch Injection point before sending request, it should return a Promise
@param {function} afterFetch Injection point after receive response, it should return a Promise
@param {function} onReject Injection point when anything goes wrong, it should return a Promise
@param {object} config Miscellaneous configuration
@return {function} | [
"Create",
"a",
"fetch",
"middleware"
]
| eb4676077747692092d7ee1d2d63be16e455e662 | https://github.com/jasonslyvia/redux-composable-fetch/blob/eb4676077747692092d7ee1d2d63be16e455e662/lib/index.js#L79-L252 |
43,621 | Robert-W/react-prerender | samples/amd/js/utils/params.js | getUrlParams | function getUrlParams(path) {
if (!path) {
return {};
}
var bits = path.split('?');
var querystring = bits.length > 1 ? bits[1] : '';
return toObject(querystring);
} | javascript | function getUrlParams(path) {
if (!path) {
return {};
}
var bits = path.split('?');
var querystring = bits.length > 1 ? bits[1] : '';
return toObject(querystring);
} | [
"function",
"getUrlParams",
"(",
"path",
")",
"{",
"if",
"(",
"!",
"path",
")",
"{",
"return",
"{",
"}",
";",
"}",
"var",
"bits",
"=",
"path",
".",
"split",
"(",
"'?'",
")",
";",
"var",
"querystring",
"=",
"bits",
".",
"length",
">",
"1",
"?",
"bits",
"[",
"1",
"]",
":",
"''",
";",
"return",
"toObject",
"(",
"querystring",
")",
";",
"}"
]
| Return the query parameters from the provided string
@param {string} path - Path to pull querystring from, should be location.href
@return {object} - Dictionary containiner the url parameters | [
"Return",
"the",
"query",
"parameters",
"from",
"the",
"provided",
"string"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/samples/amd/js/utils/params.js#L63-L70 |
43,622 | hello-js/hello | lib/app.js | _defaults | function _defaults (config) {
let values = require('./defaults/default')
try {
values = merge(values, require(`./defaults/${process.env.NODE_ENV}`))
} catch (e) { }
return defaultsDeep(config, values)
} | javascript | function _defaults (config) {
let values = require('./defaults/default')
try {
values = merge(values, require(`./defaults/${process.env.NODE_ENV}`))
} catch (e) { }
return defaultsDeep(config, values)
} | [
"function",
"_defaults",
"(",
"config",
")",
"{",
"let",
"values",
"=",
"require",
"(",
"'./defaults/default'",
")",
"try",
"{",
"values",
"=",
"merge",
"(",
"values",
",",
"require",
"(",
"`",
"${",
"process",
".",
"env",
".",
"NODE_ENV",
"}",
"`",
")",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"defaultsDeep",
"(",
"config",
",",
"values",
")",
"}"
]
| Set default values for the `config` param if not set
@private
@param {Object} [config] - The config to use (optional)
@returns {Object} - The config object with default values | [
"Set",
"default",
"values",
"for",
"the",
"config",
"param",
"if",
"not",
"set"
]
| 72a0d2c87817921fba15c2d2567b8f0abc62c3e5 | https://github.com/hello-js/hello/blob/72a0d2c87817921fba15c2d2567b8f0abc62c3e5/lib/app.js#L154-L162 |
43,623 | PunchThrough/bean-sdk-node | src/util/intelhex.js | extractDataFromIntelHexLine | function extractDataFromIntelHexLine(intelHexLine) {
if (!intelHexLine.startsWith(':')) {
throw new Error(`Intel hex lines need to start with ':'`)
}
let asciiHex = intelHexLine.slice(1, intelHexLine.length)
if (asciiHex.length === 0) {
throw new Error(`Length of ascii hex string needs to be greater than 0`)
}
if (asciiHex.length % 2 !== 0) {
throw new Error(`Length of ascii hex string needs to be even`)
}
let rawBytes = []
for (let i = 0; i < asciiHex.length; i += 2) {
let asciiByte = asciiHex.slice(i, i + 2)
rawBytes.push(parseInt(asciiByte, 16))
}
if (rawBytes[3] === INTEL_HEX_DATA) {
let dataBytes = rawBytes.slice(4, rawBytes.length - 1)
let bytes = new buffer.Buffer(dataBytes.length)
for (let i = 0; i < dataBytes.length; i++) {
bytes.writeUInt8(dataBytes[i], i)
}
return bytes
} else {
return null
}
} | javascript | function extractDataFromIntelHexLine(intelHexLine) {
if (!intelHexLine.startsWith(':')) {
throw new Error(`Intel hex lines need to start with ':'`)
}
let asciiHex = intelHexLine.slice(1, intelHexLine.length)
if (asciiHex.length === 0) {
throw new Error(`Length of ascii hex string needs to be greater than 0`)
}
if (asciiHex.length % 2 !== 0) {
throw new Error(`Length of ascii hex string needs to be even`)
}
let rawBytes = []
for (let i = 0; i < asciiHex.length; i += 2) {
let asciiByte = asciiHex.slice(i, i + 2)
rawBytes.push(parseInt(asciiByte, 16))
}
if (rawBytes[3] === INTEL_HEX_DATA) {
let dataBytes = rawBytes.slice(4, rawBytes.length - 1)
let bytes = new buffer.Buffer(dataBytes.length)
for (let i = 0; i < dataBytes.length; i++) {
bytes.writeUInt8(dataBytes[i], i)
}
return bytes
} else {
return null
}
} | [
"function",
"extractDataFromIntelHexLine",
"(",
"intelHexLine",
")",
"{",
"if",
"(",
"!",
"intelHexLine",
".",
"startsWith",
"(",
"':'",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"`",
")",
"}",
"let",
"asciiHex",
"=",
"intelHexLine",
".",
"slice",
"(",
"1",
",",
"intelHexLine",
".",
"length",
")",
"if",
"(",
"asciiHex",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"`",
")",
"}",
"if",
"(",
"asciiHex",
".",
"length",
"%",
"2",
"!==",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"`",
")",
"}",
"let",
"rawBytes",
"=",
"[",
"]",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"asciiHex",
".",
"length",
";",
"i",
"+=",
"2",
")",
"{",
"let",
"asciiByte",
"=",
"asciiHex",
".",
"slice",
"(",
"i",
",",
"i",
"+",
"2",
")",
"rawBytes",
".",
"push",
"(",
"parseInt",
"(",
"asciiByte",
",",
"16",
")",
")",
"}",
"if",
"(",
"rawBytes",
"[",
"3",
"]",
"===",
"INTEL_HEX_DATA",
")",
"{",
"let",
"dataBytes",
"=",
"rawBytes",
".",
"slice",
"(",
"4",
",",
"rawBytes",
".",
"length",
"-",
"1",
")",
"let",
"bytes",
"=",
"new",
"buffer",
".",
"Buffer",
"(",
"dataBytes",
".",
"length",
")",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"dataBytes",
".",
"length",
";",
"i",
"++",
")",
"{",
"bytes",
".",
"writeUInt8",
"(",
"dataBytes",
"[",
"i",
"]",
",",
"i",
")",
"}",
"return",
"bytes",
"}",
"else",
"{",
"return",
"null",
"}",
"}"
]
| Extract the "data" from an Intel hex line
An Intel hex line looks like this
:100000005CC000000C9450080C947D087EC0000079
Once the ':' character is removed, each set of two characters represent a
Hexadecimal octet, or byte. However, not every byte in the string is considered
data, here is what the bytes mean:
Byte(s) [ 0] = Byte count
Byte(s) [1:2] = Address
Byte(s) [ 3] = Record type
Byte(s) [ n] = Data
Byte(s) [n+1] = Checksum
@param intelHexLine Ascii Intel hex line
@returns | [
"Extract",
"the",
"data",
"from",
"an",
"Intel",
"hex",
"line"
]
| b58342043c832f2e3b12cfb55a0fec603aab38d8 | https://github.com/PunchThrough/bean-sdk-node/blob/b58342043c832f2e3b12cfb55a0fec603aab38d8/src/util/intelhex.js#L31-L64 |
43,624 | jhermsmeier/node-mbr | lib/mbr.js | function() {
var i = 0
var part = null
for( var i = 0; i < this.partitions.length; i++ ) {
part = this.partitions[i]
if( part.type === 0xEE || part.type === 0xEF ) {
return part
}
}
return null
} | javascript | function() {
var i = 0
var part = null
for( var i = 0; i < this.partitions.length; i++ ) {
part = this.partitions[i]
if( part.type === 0xEE || part.type === 0xEF ) {
return part
}
}
return null
} | [
"function",
"(",
")",
"{",
"var",
"i",
"=",
"0",
"var",
"part",
"=",
"null",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"partitions",
".",
"length",
";",
"i",
"++",
")",
"{",
"part",
"=",
"this",
".",
"partitions",
"[",
"i",
"]",
"if",
"(",
"part",
".",
"type",
"===",
"0xEE",
"||",
"part",
".",
"type",
"===",
"0xEF",
")",
"{",
"return",
"part",
"}",
"}",
"return",
"null",
"}"
]
| Get the EFI system partition if available
@returns {MBR.Partition|null} | [
"Get",
"the",
"EFI",
"system",
"partition",
"if",
"available"
]
| a3ebdeb56fc3ce12a89e965c7127f6fe9547470a | https://github.com/jhermsmeier/node-mbr/blob/a3ebdeb56fc3ce12a89e965c7127f6fe9547470a/lib/mbr.js#L179-L193 |
|
43,625 | sapegin/proselint | src/worker.js | replaceCodeBlocks | function replaceCodeBlocks(contents) {
function processCode() {
return ast => {
visit(ast, 'code', node => {
const start = node.position.start.line;
const end = node.position.end.line;
for (let line = start; line < end - 1; line++) {
lines[line] = '';
}
});
};
}
const lines = splitLines(contents);
remark()
.use(processCode)
.process(contents)
;
return lines.join('\n');
} | javascript | function replaceCodeBlocks(contents) {
function processCode() {
return ast => {
visit(ast, 'code', node => {
const start = node.position.start.line;
const end = node.position.end.line;
for (let line = start; line < end - 1; line++) {
lines[line] = '';
}
});
};
}
const lines = splitLines(contents);
remark()
.use(processCode)
.process(contents)
;
return lines.join('\n');
} | [
"function",
"replaceCodeBlocks",
"(",
"contents",
")",
"{",
"function",
"processCode",
"(",
")",
"{",
"return",
"ast",
"=>",
"{",
"visit",
"(",
"ast",
",",
"'code'",
",",
"node",
"=>",
"{",
"const",
"start",
"=",
"node",
".",
"position",
".",
"start",
".",
"line",
";",
"const",
"end",
"=",
"node",
".",
"position",
".",
"end",
".",
"line",
";",
"for",
"(",
"let",
"line",
"=",
"start",
";",
"line",
"<",
"end",
"-",
"1",
";",
"line",
"++",
")",
"{",
"lines",
"[",
"line",
"]",
"=",
"''",
";",
"}",
"}",
")",
";",
"}",
";",
"}",
"const",
"lines",
"=",
"splitLines",
"(",
"contents",
")",
";",
"remark",
"(",
")",
".",
"use",
"(",
"processCode",
")",
".",
"process",
"(",
"contents",
")",
";",
"return",
"lines",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
]
| Replace all lines inside code blocks with empty lines becase proselint validates code by default. We use empty lines instead of just code removal to keep correct line numbers. Work with the original document because Remark changes formatting which makes error positions incorrect | [
"Replace",
"all",
"lines",
"inside",
"code",
"blocks",
"with",
"empty",
"lines",
"becase",
"proselint",
"validates",
"code",
"by",
"default",
".",
"We",
"use",
"empty",
"lines",
"instead",
"of",
"just",
"code",
"removal",
"to",
"keep",
"correct",
"line",
"numbers",
".",
"Work",
"with",
"the",
"original",
"document",
"because",
"Remark",
"changes",
"formatting",
"which",
"makes",
"error",
"positions",
"incorrect"
]
| 2564fbbf493dc0660045fc01c357383699d3722f | https://github.com/sapegin/proselint/blob/2564fbbf493dc0660045fc01c357383699d3722f/src/worker.js#L98-L117 |
43,626 | hello-js/hello | lib/router.js | controllerMethod | function controllerMethod (controller, method) {
if (controller && controller[method]) {
return controller[method]
}
// Handle hello-based Controller classes
if (isClass(controller) && controller.action) {
return controller.action(method)
}
return notImplemented
} | javascript | function controllerMethod (controller, method) {
if (controller && controller[method]) {
return controller[method]
}
// Handle hello-based Controller classes
if (isClass(controller) && controller.action) {
return controller.action(method)
}
return notImplemented
} | [
"function",
"controllerMethod",
"(",
"controller",
",",
"method",
")",
"{",
"if",
"(",
"controller",
"&&",
"controller",
"[",
"method",
"]",
")",
"{",
"return",
"controller",
"[",
"method",
"]",
"}",
"// Handle hello-based Controller classes",
"if",
"(",
"isClass",
"(",
"controller",
")",
"&&",
"controller",
".",
"action",
")",
"{",
"return",
"controller",
".",
"action",
"(",
"method",
")",
"}",
"return",
"notImplemented",
"}"
]
| Returns a wrapper to be used in the router for calling a given controller method.
@param {Object|Controller} controller - The controller
@param {String} method - The method on the controller to call
@returns {Function} The controller method to call | [
"Returns",
"a",
"wrapper",
"to",
"be",
"used",
"in",
"the",
"router",
"for",
"calling",
"a",
"given",
"controller",
"method",
"."
]
| 72a0d2c87817921fba15c2d2567b8f0abc62c3e5 | https://github.com/hello-js/hello/blob/72a0d2c87817921fba15c2d2567b8f0abc62c3e5/lib/router.js#L177-L188 |
43,627 | jasonslyvia/redux-composable-fetch | lib/applyFetchMiddleware.js | applyFetchMiddleware | function applyFetchMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
var middlewaresWithOnResolve = middlewares.filter(function (m) {
return typeof m.onResolve === 'function';
});
if (middlewaresWithOnResolve.length > 1) {
console.warn('[fetch-middleware] Only one single `onResolve` handler is supported, but you provided %d', middlewaresWithOnResolve.length);
}
return {
beforeFetch: function beforeFetch(_ref) {
var action = _ref.action;
return middlewares.reduce(function (chain, middleware) {
if (typeof middleware.beforeFetch === 'function') {
return chain.then(function (_ref2) {
var action = _ref2.action;
return middleware.beforeFetch({ action: action });
});
}
return chain;
}, Promise.resolve({ action: action }));
},
afterFetch: function afterFetch(_ref3) {
var action = _ref3.action;
var result = _ref3.result;
return middlewares.reduce(function (chain, middleware) {
if (typeof middleware.afterFetch === 'function') {
return chain.then(function (_ref4) {
var action = _ref4.action;
var result = _ref4.result;
return middleware.afterFetch({ action: action, result: result });
});
}
return chain;
}, Promise.resolve({ action: action, result: result }));
},
onReject: function onReject(_ref5) {
var action = _ref5.action;
var error = _ref5.error;
return middlewares.reduce(function (chain, middleware) {
if (typeof middleware.onReject === 'function') {
return chain.catch(function (_ref6) {
var action = _ref6.action;
var error = _ref6.error;
return middleware.onReject({ action: action, error: error });
});
}
return chain;
}, Promise.reject({ action: action, error: error }));
},
onResolve: middlewaresWithOnResolve[0] ? middlewaresWithOnResolve[0].onResolve : undefined
};
} | javascript | function applyFetchMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
var middlewaresWithOnResolve = middlewares.filter(function (m) {
return typeof m.onResolve === 'function';
});
if (middlewaresWithOnResolve.length > 1) {
console.warn('[fetch-middleware] Only one single `onResolve` handler is supported, but you provided %d', middlewaresWithOnResolve.length);
}
return {
beforeFetch: function beforeFetch(_ref) {
var action = _ref.action;
return middlewares.reduce(function (chain, middleware) {
if (typeof middleware.beforeFetch === 'function') {
return chain.then(function (_ref2) {
var action = _ref2.action;
return middleware.beforeFetch({ action: action });
});
}
return chain;
}, Promise.resolve({ action: action }));
},
afterFetch: function afterFetch(_ref3) {
var action = _ref3.action;
var result = _ref3.result;
return middlewares.reduce(function (chain, middleware) {
if (typeof middleware.afterFetch === 'function') {
return chain.then(function (_ref4) {
var action = _ref4.action;
var result = _ref4.result;
return middleware.afterFetch({ action: action, result: result });
});
}
return chain;
}, Promise.resolve({ action: action, result: result }));
},
onReject: function onReject(_ref5) {
var action = _ref5.action;
var error = _ref5.error;
return middlewares.reduce(function (chain, middleware) {
if (typeof middleware.onReject === 'function') {
return chain.catch(function (_ref6) {
var action = _ref6.action;
var error = _ref6.error;
return middleware.onReject({ action: action, error: error });
});
}
return chain;
}, Promise.reject({ action: action, error: error }));
},
onResolve: middlewaresWithOnResolve[0] ? middlewaresWithOnResolve[0].onResolve : undefined
};
} | [
"function",
"applyFetchMiddleware",
"(",
")",
"{",
"for",
"(",
"var",
"_len",
"=",
"arguments",
".",
"length",
",",
"middlewares",
"=",
"Array",
"(",
"_len",
")",
",",
"_key",
"=",
"0",
";",
"_key",
"<",
"_len",
";",
"_key",
"++",
")",
"{",
"middlewares",
"[",
"_key",
"]",
"=",
"arguments",
"[",
"_key",
"]",
";",
"}",
"var",
"middlewaresWithOnResolve",
"=",
"middlewares",
".",
"filter",
"(",
"function",
"(",
"m",
")",
"{",
"return",
"typeof",
"m",
".",
"onResolve",
"===",
"'function'",
";",
"}",
")",
";",
"if",
"(",
"middlewaresWithOnResolve",
".",
"length",
">",
"1",
")",
"{",
"console",
".",
"warn",
"(",
"'[fetch-middleware] Only one single `onResolve` handler is supported, but you provided %d'",
",",
"middlewaresWithOnResolve",
".",
"length",
")",
";",
"}",
"return",
"{",
"beforeFetch",
":",
"function",
"beforeFetch",
"(",
"_ref",
")",
"{",
"var",
"action",
"=",
"_ref",
".",
"action",
";",
"return",
"middlewares",
".",
"reduce",
"(",
"function",
"(",
"chain",
",",
"middleware",
")",
"{",
"if",
"(",
"typeof",
"middleware",
".",
"beforeFetch",
"===",
"'function'",
")",
"{",
"return",
"chain",
".",
"then",
"(",
"function",
"(",
"_ref2",
")",
"{",
"var",
"action",
"=",
"_ref2",
".",
"action",
";",
"return",
"middleware",
".",
"beforeFetch",
"(",
"{",
"action",
":",
"action",
"}",
")",
";",
"}",
")",
";",
"}",
"return",
"chain",
";",
"}",
",",
"Promise",
".",
"resolve",
"(",
"{",
"action",
":",
"action",
"}",
")",
")",
";",
"}",
",",
"afterFetch",
":",
"function",
"afterFetch",
"(",
"_ref3",
")",
"{",
"var",
"action",
"=",
"_ref3",
".",
"action",
";",
"var",
"result",
"=",
"_ref3",
".",
"result",
";",
"return",
"middlewares",
".",
"reduce",
"(",
"function",
"(",
"chain",
",",
"middleware",
")",
"{",
"if",
"(",
"typeof",
"middleware",
".",
"afterFetch",
"===",
"'function'",
")",
"{",
"return",
"chain",
".",
"then",
"(",
"function",
"(",
"_ref4",
")",
"{",
"var",
"action",
"=",
"_ref4",
".",
"action",
";",
"var",
"result",
"=",
"_ref4",
".",
"result",
";",
"return",
"middleware",
".",
"afterFetch",
"(",
"{",
"action",
":",
"action",
",",
"result",
":",
"result",
"}",
")",
";",
"}",
")",
";",
"}",
"return",
"chain",
";",
"}",
",",
"Promise",
".",
"resolve",
"(",
"{",
"action",
":",
"action",
",",
"result",
":",
"result",
"}",
")",
")",
";",
"}",
",",
"onReject",
":",
"function",
"onReject",
"(",
"_ref5",
")",
"{",
"var",
"action",
"=",
"_ref5",
".",
"action",
";",
"var",
"error",
"=",
"_ref5",
".",
"error",
";",
"return",
"middlewares",
".",
"reduce",
"(",
"function",
"(",
"chain",
",",
"middleware",
")",
"{",
"if",
"(",
"typeof",
"middleware",
".",
"onReject",
"===",
"'function'",
")",
"{",
"return",
"chain",
".",
"catch",
"(",
"function",
"(",
"_ref6",
")",
"{",
"var",
"action",
"=",
"_ref6",
".",
"action",
";",
"var",
"error",
"=",
"_ref6",
".",
"error",
";",
"return",
"middleware",
".",
"onReject",
"(",
"{",
"action",
":",
"action",
",",
"error",
":",
"error",
"}",
")",
";",
"}",
")",
";",
"}",
"return",
"chain",
";",
"}",
",",
"Promise",
".",
"reject",
"(",
"{",
"action",
":",
"action",
",",
"error",
":",
"error",
"}",
")",
")",
";",
"}",
",",
"onResolve",
":",
"middlewaresWithOnResolve",
"[",
"0",
"]",
"?",
"middlewaresWithOnResolve",
"[",
"0",
"]",
".",
"onResolve",
":",
"undefined",
"}",
";",
"}"
]
| Utility function, chain multiple middlewares of `redux-composable-fetch` into one
@param {...object} middlewares
@return {object} | [
"Utility",
"function",
"chain",
"multiple",
"middlewares",
"of",
"redux",
"-",
"composable",
"-",
"fetch",
"into",
"one"
]
| eb4676077747692092d7ee1d2d63be16e455e662 | https://github.com/jasonslyvia/redux-composable-fetch/blob/eb4676077747692092d7ee1d2d63be16e455e662/lib/applyFetchMiddleware.js#L12-L72 |
43,628 | hello-js/hello | cli/index.js | run | function run (action, command, name, flags) {
switch (action) {
case 'new':
case 'generate':
case 'g':
generate(command, name, flags)
break
case 'migrate':
migrate(command || 'up')
break
case 'up':
migrate('up')
break
case 'down':
case 'rollback':
migrate('down')
break
default:
run('new', action, command, flags)
}
} | javascript | function run (action, command, name, flags) {
switch (action) {
case 'new':
case 'generate':
case 'g':
generate(command, name, flags)
break
case 'migrate':
migrate(command || 'up')
break
case 'up':
migrate('up')
break
case 'down':
case 'rollback':
migrate('down')
break
default:
run('new', action, command, flags)
}
} | [
"function",
"run",
"(",
"action",
",",
"command",
",",
"name",
",",
"flags",
")",
"{",
"switch",
"(",
"action",
")",
"{",
"case",
"'new'",
":",
"case",
"'generate'",
":",
"case",
"'g'",
":",
"generate",
"(",
"command",
",",
"name",
",",
"flags",
")",
"break",
"case",
"'migrate'",
":",
"migrate",
"(",
"command",
"||",
"'up'",
")",
"break",
"case",
"'up'",
":",
"migrate",
"(",
"'up'",
")",
"break",
"case",
"'down'",
":",
"case",
"'rollback'",
":",
"migrate",
"(",
"'down'",
")",
"break",
"default",
":",
"run",
"(",
"'new'",
",",
"action",
",",
"command",
",",
"flags",
")",
"}",
"}"
]
| Handle the cli input
@param {String} action - The action to perform (new, generate)
@param {String} command - The command to pass to the generator or migrator
@param {String} name - The name of the item to create, if any
@param {Object} flags - The flags/options passed to the command line | [
"Handle",
"the",
"cli",
"input"
]
| 72a0d2c87817921fba15c2d2567b8f0abc62c3e5 | https://github.com/hello-js/hello/blob/72a0d2c87817921fba15c2d2567b8f0abc62c3e5/cli/index.js#L44-L64 |
43,629 | hello-js/hello | cli/index.js | generate | function generate (generatorName, name, flags) {
let generator
switch (generatorName) {
case 'app':
generator = new generators.App(name)
break
case 'controller':
generator = new generators.Controller(name, flags)
break
case 'model':
generator = new generators.Model(name, flags)
break
case 'view':
console.log(`generating view ${name} ...`)
console.log('NotImplemented. View generation not yet available')
break
case 'migration':
generator = new generators.Migration(name, flags)
break
case 'scaffold':
console.log(`generating scaffold ${name} ...`)
console.log('NotImplemented. Scaffold generation not yet available')
break
case 'user':
console.log(`generating user ${name} ...`)
console.log('NotImplemented. User generation not yet available')
break
default:
if (!name) {
return generate('app', generatorName)
}
}
if (!generator) {
return cli.showHelp(0)
}
return generator.run()
} | javascript | function generate (generatorName, name, flags) {
let generator
switch (generatorName) {
case 'app':
generator = new generators.App(name)
break
case 'controller':
generator = new generators.Controller(name, flags)
break
case 'model':
generator = new generators.Model(name, flags)
break
case 'view':
console.log(`generating view ${name} ...`)
console.log('NotImplemented. View generation not yet available')
break
case 'migration':
generator = new generators.Migration(name, flags)
break
case 'scaffold':
console.log(`generating scaffold ${name} ...`)
console.log('NotImplemented. Scaffold generation not yet available')
break
case 'user':
console.log(`generating user ${name} ...`)
console.log('NotImplemented. User generation not yet available')
break
default:
if (!name) {
return generate('app', generatorName)
}
}
if (!generator) {
return cli.showHelp(0)
}
return generator.run()
} | [
"function",
"generate",
"(",
"generatorName",
",",
"name",
",",
"flags",
")",
"{",
"let",
"generator",
"switch",
"(",
"generatorName",
")",
"{",
"case",
"'app'",
":",
"generator",
"=",
"new",
"generators",
".",
"App",
"(",
"name",
")",
"break",
"case",
"'controller'",
":",
"generator",
"=",
"new",
"generators",
".",
"Controller",
"(",
"name",
",",
"flags",
")",
"break",
"case",
"'model'",
":",
"generator",
"=",
"new",
"generators",
".",
"Model",
"(",
"name",
",",
"flags",
")",
"break",
"case",
"'view'",
":",
"console",
".",
"log",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"console",
".",
"log",
"(",
"'NotImplemented. View generation not yet available'",
")",
"break",
"case",
"'migration'",
":",
"generator",
"=",
"new",
"generators",
".",
"Migration",
"(",
"name",
",",
"flags",
")",
"break",
"case",
"'scaffold'",
":",
"console",
".",
"log",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"console",
".",
"log",
"(",
"'NotImplemented. Scaffold generation not yet available'",
")",
"break",
"case",
"'user'",
":",
"console",
".",
"log",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"console",
".",
"log",
"(",
"'NotImplemented. User generation not yet available'",
")",
"break",
"default",
":",
"if",
"(",
"!",
"name",
")",
"{",
"return",
"generate",
"(",
"'app'",
",",
"generatorName",
")",
"}",
"}",
"if",
"(",
"!",
"generator",
")",
"{",
"return",
"cli",
".",
"showHelp",
"(",
"0",
")",
"}",
"return",
"generator",
".",
"run",
"(",
")",
"}"
]
| Run a given generator
@param {String} generatorName - The name of the generator to run
@param {String} name - The name of the generated item
@param {Object} flags - The flags passed to the generator | [
"Run",
"a",
"given",
"generator"
]
| 72a0d2c87817921fba15c2d2567b8f0abc62c3e5 | https://github.com/hello-js/hello/blob/72a0d2c87817921fba15c2d2567b8f0abc62c3e5/cli/index.js#L73-L112 |
43,630 | hello-js/hello | cli/index.js | migrate | async function migrate (direction) {
let config = require(path.join(process.cwd(), '.', 'config'))
let db = require(path.join(process.cwd(), '.', 'db'))
if (direction === 'up') {
await db.migrate.latest(config.db)
} else if (direction === 'down') {
await db.migrate.rollback(config.db)
} else {
cli.showHelp(0)
}
process.exit(0)
} | javascript | async function migrate (direction) {
let config = require(path.join(process.cwd(), '.', 'config'))
let db = require(path.join(process.cwd(), '.', 'db'))
if (direction === 'up') {
await db.migrate.latest(config.db)
} else if (direction === 'down') {
await db.migrate.rollback(config.db)
} else {
cli.showHelp(0)
}
process.exit(0)
} | [
"async",
"function",
"migrate",
"(",
"direction",
")",
"{",
"let",
"config",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'.'",
",",
"'config'",
")",
")",
"let",
"db",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'.'",
",",
"'db'",
")",
")",
"if",
"(",
"direction",
"===",
"'up'",
")",
"{",
"await",
"db",
".",
"migrate",
".",
"latest",
"(",
"config",
".",
"db",
")",
"}",
"else",
"if",
"(",
"direction",
"===",
"'down'",
")",
"{",
"await",
"db",
".",
"migrate",
".",
"rollback",
"(",
"config",
".",
"db",
")",
"}",
"else",
"{",
"cli",
".",
"showHelp",
"(",
"0",
")",
"}",
"process",
".",
"exit",
"(",
"0",
")",
"}"
]
| Run the migrations in a given direction.
@param {String} direction - The direcation to run, can be 'up' or 'down' | [
"Run",
"the",
"migrations",
"in",
"a",
"given",
"direction",
"."
]
| 72a0d2c87817921fba15c2d2567b8f0abc62c3e5 | https://github.com/hello-js/hello/blob/72a0d2c87817921fba15c2d2567b8f0abc62c3e5/cli/index.js#L119-L132 |
43,631 | Robert-W/react-prerender | lib/utils.js | function (options) {
return options.mount && options.target && options.component
&& type(options.component) === TYPES.STRING
&& type(options.target) === TYPES.STRING
&& type(options.mount) === TYPES.STRING;
} | javascript | function (options) {
return options.mount && options.target && options.component
&& type(options.component) === TYPES.STRING
&& type(options.target) === TYPES.STRING
&& type(options.mount) === TYPES.STRING;
} | [
"function",
"(",
"options",
")",
"{",
"return",
"options",
".",
"mount",
"&&",
"options",
".",
"target",
"&&",
"options",
".",
"component",
"&&",
"type",
"(",
"options",
".",
"component",
")",
"===",
"TYPES",
".",
"STRING",
"&&",
"type",
"(",
"options",
".",
"target",
")",
"===",
"TYPES",
".",
"STRING",
"&&",
"type",
"(",
"options",
".",
"mount",
")",
"===",
"TYPES",
".",
"STRING",
";",
"}"
]
| Checks for mount, target, and component since they are the minimum required options
Also checks to make sure they are the correct type
@param {object} options
@return {bool} | [
"Checks",
"for",
"mount",
"target",
"and",
"component",
"since",
"they",
"are",
"the",
"minimum",
"required",
"options",
"Also",
"checks",
"to",
"make",
"sure",
"they",
"are",
"the",
"correct",
"type"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/lib/utils.js#L34-L39 |
|
43,632 | Robert-W/react-prerender | lib/utils.js | function (options) {
return (
options.paths
&& options.baseUrl
&& type(options.paths) === TYPES.OBJECT
&& type(options.baseUrl) === TYPES.STRING
) || (
options.buildProfile
&& type(options.buildProfile) === TYPES.STRING
);
} | javascript | function (options) {
return (
options.paths
&& options.baseUrl
&& type(options.paths) === TYPES.OBJECT
&& type(options.baseUrl) === TYPES.STRING
) || (
options.buildProfile
&& type(options.buildProfile) === TYPES.STRING
);
} | [
"function",
"(",
"options",
")",
"{",
"return",
"(",
"options",
".",
"paths",
"&&",
"options",
".",
"baseUrl",
"&&",
"type",
"(",
"options",
".",
"paths",
")",
"===",
"TYPES",
".",
"OBJECT",
"&&",
"type",
"(",
"options",
".",
"baseUrl",
")",
"===",
"TYPES",
".",
"STRING",
")",
"||",
"(",
"options",
".",
"buildProfile",
"&&",
"type",
"(",
"options",
".",
"buildProfile",
")",
"===",
"TYPES",
".",
"STRING",
")",
";",
"}"
]
| Checks for baseUrl and paths or a build profile at minimum
Also checks to make sure they are the correct type
@param {object} options
@return {bool} | [
"Checks",
"for",
"baseUrl",
"and",
"paths",
"or",
"a",
"build",
"profile",
"at",
"minimum",
"Also",
"checks",
"to",
"make",
"sure",
"they",
"are",
"the",
"correct",
"type"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/lib/utils.js#L47-L57 |
|
43,633 | Robert-W/react-prerender | lib/utils.js | function (options) {
return options.moduleRoot && options.remapModule && options.ignorePatterns
&& type(options.moduleRoot) === TYPES.STRING
&& type(options.remapModule) === TYPES.STRING
&& (
(type(options.ignorePatterns) === TYPES.STRING || type(options.ignorePatterns) === TYPES.REGEXP)
||
(
type(options.ignorePatterns) === TYPES.ARRAY
&& options.ignorePatterns.every(function (pattern) {
return type(pattern) === TYPES.STRING || type(pattern) === TYPES.REGEXP;
})
)
);
} | javascript | function (options) {
return options.moduleRoot && options.remapModule && options.ignorePatterns
&& type(options.moduleRoot) === TYPES.STRING
&& type(options.remapModule) === TYPES.STRING
&& (
(type(options.ignorePatterns) === TYPES.STRING || type(options.ignorePatterns) === TYPES.REGEXP)
||
(
type(options.ignorePatterns) === TYPES.ARRAY
&& options.ignorePatterns.every(function (pattern) {
return type(pattern) === TYPES.STRING || type(pattern) === TYPES.REGEXP;
})
)
);
} | [
"function",
"(",
"options",
")",
"{",
"return",
"options",
".",
"moduleRoot",
"&&",
"options",
".",
"remapModule",
"&&",
"options",
".",
"ignorePatterns",
"&&",
"type",
"(",
"options",
".",
"moduleRoot",
")",
"===",
"TYPES",
".",
"STRING",
"&&",
"type",
"(",
"options",
".",
"remapModule",
")",
"===",
"TYPES",
".",
"STRING",
"&&",
"(",
"(",
"type",
"(",
"options",
".",
"ignorePatterns",
")",
"===",
"TYPES",
".",
"STRING",
"||",
"type",
"(",
"options",
".",
"ignorePatterns",
")",
"===",
"TYPES",
".",
"REGEXP",
")",
"||",
"(",
"type",
"(",
"options",
".",
"ignorePatterns",
")",
"===",
"TYPES",
".",
"ARRAY",
"&&",
"options",
".",
"ignorePatterns",
".",
"every",
"(",
"function",
"(",
"pattern",
")",
"{",
"return",
"type",
"(",
"pattern",
")",
"===",
"TYPES",
".",
"STRING",
"||",
"type",
"(",
"pattern",
")",
"===",
"TYPES",
".",
"REGEXP",
";",
"}",
")",
")",
")",
";",
"}"
]
| Checks for moduleRoot, remapModule, and ignorePatterns at minimum
Also checks to make sure they are the correct type
@param {object} options
@return {bool} | [
"Checks",
"for",
"moduleRoot",
"remapModule",
"and",
"ignorePatterns",
"at",
"minimum",
"Also",
"checks",
"to",
"make",
"sure",
"they",
"are",
"the",
"correct",
"type"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/lib/utils.js#L65-L79 |
|
43,634 | Robert-W/react-prerender | lib/utils.js | function (path) {
var profile;
try {
profile = eval(fs.readFileSync(path, 'utf-8'));
} catch (err) {
// set profile to empty, check in prerender will throw an error
// if no path or baseUrl is present
profile = {};
}
return profile;
} | javascript | function (path) {
var profile;
try {
profile = eval(fs.readFileSync(path, 'utf-8'));
} catch (err) {
// set profile to empty, check in prerender will throw an error
// if no path or baseUrl is present
profile = {};
}
return profile;
} | [
"function",
"(",
"path",
")",
"{",
"var",
"profile",
";",
"try",
"{",
"profile",
"=",
"eval",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
",",
"'utf-8'",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"// set profile to empty, check in prerender will throw an error",
"// if no path or baseUrl is present",
"profile",
"=",
"{",
"}",
";",
"}",
"return",
"profile",
";",
"}"
]
| Load and attempt to evaluate a requirejs build profile
@param {string} path path to a requirejs build profile
@return {object} requirejsConfig | [
"Load",
"and",
"attempt",
"to",
"evaluate",
"a",
"requirejs",
"build",
"profile"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/lib/utils.js#L86-L96 |
|
43,635 | Robert-W/react-prerender | lib/utils.js | function (moduleRoot, remapModule, ignores) {
var tree = madge(moduleRoot, { format: 'amd' }).tree,
paths = [],
map = {};
/**
* Filter function to test module paths, ignores can be array[string|regexp]|string|regexp
* @param {string} path - module path
*/
var matches = function matches (path) {
if (type(ignores) === TYPES.STRING) {
return path.search(ignores) > -1;
} else if (type(ignores) === TYPES.REGEXP) {
return ignores.test(path);
} else {
return ignores.some(function (ignore) {
return type(ignore) === TYPES.STRING ? (path.search(ignore) > -1) : ignore.test(path);
});
}
};
//- Generate an array of paths to ignore
for (var dependency in tree) {
paths = paths.concat(tree[dependency].filter(matches));
}
if (paths.length === 0) {
console.warn(messages.moduleRemapFoundNone);
}
//- Put in a format requirejs can understand
paths.forEach(function (path) {
map[path] = remapModule;
});
return map;
} | javascript | function (moduleRoot, remapModule, ignores) {
var tree = madge(moduleRoot, { format: 'amd' }).tree,
paths = [],
map = {};
/**
* Filter function to test module paths, ignores can be array[string|regexp]|string|regexp
* @param {string} path - module path
*/
var matches = function matches (path) {
if (type(ignores) === TYPES.STRING) {
return path.search(ignores) > -1;
} else if (type(ignores) === TYPES.REGEXP) {
return ignores.test(path);
} else {
return ignores.some(function (ignore) {
return type(ignore) === TYPES.STRING ? (path.search(ignore) > -1) : ignore.test(path);
});
}
};
//- Generate an array of paths to ignore
for (var dependency in tree) {
paths = paths.concat(tree[dependency].filter(matches));
}
if (paths.length === 0) {
console.warn(messages.moduleRemapFoundNone);
}
//- Put in a format requirejs can understand
paths.forEach(function (path) {
map[path] = remapModule;
});
return map;
} | [
"function",
"(",
"moduleRoot",
",",
"remapModule",
",",
"ignores",
")",
"{",
"var",
"tree",
"=",
"madge",
"(",
"moduleRoot",
",",
"{",
"format",
":",
"'amd'",
"}",
")",
".",
"tree",
",",
"paths",
"=",
"[",
"]",
",",
"map",
"=",
"{",
"}",
";",
"/**\n * Filter function to test module paths, ignores can be array[string|regexp]|string|regexp\n * @param {string} path - module path\n */",
"var",
"matches",
"=",
"function",
"matches",
"(",
"path",
")",
"{",
"if",
"(",
"type",
"(",
"ignores",
")",
"===",
"TYPES",
".",
"STRING",
")",
"{",
"return",
"path",
".",
"search",
"(",
"ignores",
")",
">",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"type",
"(",
"ignores",
")",
"===",
"TYPES",
".",
"REGEXP",
")",
"{",
"return",
"ignores",
".",
"test",
"(",
"path",
")",
";",
"}",
"else",
"{",
"return",
"ignores",
".",
"some",
"(",
"function",
"(",
"ignore",
")",
"{",
"return",
"type",
"(",
"ignore",
")",
"===",
"TYPES",
".",
"STRING",
"?",
"(",
"path",
".",
"search",
"(",
"ignore",
")",
">",
"-",
"1",
")",
":",
"ignore",
".",
"test",
"(",
"path",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"//- Generate an array of paths to ignore",
"for",
"(",
"var",
"dependency",
"in",
"tree",
")",
"{",
"paths",
"=",
"paths",
".",
"concat",
"(",
"tree",
"[",
"dependency",
"]",
".",
"filter",
"(",
"matches",
")",
")",
";",
"}",
"if",
"(",
"paths",
".",
"length",
"===",
"0",
")",
"{",
"console",
".",
"warn",
"(",
"messages",
".",
"moduleRemapFoundNone",
")",
";",
"}",
"//- Put in a format requirejs can understand",
"paths",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"map",
"[",
"path",
"]",
"=",
"remapModule",
";",
"}",
")",
";",
"return",
"map",
";",
"}"
]
| Generate a map object that maps all modules matching the ignores pattern to the emptyModule
@param {string} moduleRoot - base dir of your modules
@param {string} remapModule - path to empty module (by empty module I mean a dependency free module)
@param {string|array} ignores - RegEx patterns or basic strings to include in the map
@return {object} map | [
"Generate",
"a",
"map",
"object",
"that",
"maps",
"all",
"modules",
"matching",
"the",
"ignores",
"pattern",
"to",
"the",
"emptyModule"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/lib/utils.js#L105-L141 |
|
43,636 | Robert-W/react-prerender | lib/utils.js | function (component, props) {
var Component = React.createFactory(component);
return ReactDomServer.renderToString(Component(props));
} | javascript | function (component, props) {
var Component = React.createFactory(component);
return ReactDomServer.renderToString(Component(props));
} | [
"function",
"(",
"component",
",",
"props",
")",
"{",
"var",
"Component",
"=",
"React",
".",
"createFactory",
"(",
"component",
")",
";",
"return",
"ReactDomServer",
".",
"renderToString",
"(",
"Component",
"(",
"props",
")",
")",
";",
"}"
]
| Generate a string representation of a react component
@param {function} component - react component
@param {object} props - default props to pass in to the component
@return {string} string representation of your component | [
"Generate",
"a",
"string",
"representation",
"of",
"a",
"react",
"component"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/lib/utils.js#L149-L152 |
|
43,637 | Robert-W/react-prerender | lib/utils.js | function (target, mount, component) {
var file = fs.readFileSync(target, 'utf-8');
var $ = cheerio.load(file);
//- returns true if any of the elements match mount, so throw if false
if (!$(mount).is(mount)) { throw messages.errors.domNodeNotFound(mount); }
//- write to html
$(mount).append(component);
fs.writeFileSync(target, $.html());
} | javascript | function (target, mount, component) {
var file = fs.readFileSync(target, 'utf-8');
var $ = cheerio.load(file);
//- returns true if any of the elements match mount, so throw if false
if (!$(mount).is(mount)) { throw messages.errors.domNodeNotFound(mount); }
//- write to html
$(mount).append(component);
fs.writeFileSync(target, $.html());
} | [
"function",
"(",
"target",
",",
"mount",
",",
"component",
")",
"{",
"var",
"file",
"=",
"fs",
".",
"readFileSync",
"(",
"target",
",",
"'utf-8'",
")",
";",
"var",
"$",
"=",
"cheerio",
".",
"load",
"(",
"file",
")",
";",
"//- returns true if any of the elements match mount, so throw if false",
"if",
"(",
"!",
"$",
"(",
"mount",
")",
".",
"is",
"(",
"mount",
")",
")",
"{",
"throw",
"messages",
".",
"errors",
".",
"domNodeNotFound",
"(",
"mount",
")",
";",
"}",
"//- write to html",
"$",
"(",
"mount",
")",
".",
"append",
"(",
"component",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"target",
",",
"$",
".",
"html",
"(",
")",
")",
";",
"}"
]
| Insert the string into the target html file at the mount point
@param {string} target - path to html file
@param {string} mount - query for a dom node that the component will be injected into
@param {string} component - string representation of a react component | [
"Insert",
"the",
"string",
"into",
"the",
"target",
"html",
"file",
"at",
"the",
"mount",
"point"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/lib/utils.js#L160-L168 |
|
43,638 | ahomu/rx.observable.combinetemplate | index.js | collectTargetObservablesAndContext | function collectTargetObservablesAndContext(templateObject) {
var targets = [];
var contexts = [];
/**
*
* ```
* // context index sample (`x` == Observable)
* {
* foo: x, // => ['foo']
* bar: {
* foo: x, // => ['bar', 'foo']
* bar: [_, _, x] // => ['bar', 'bar', 2]
* },
* baz: [_, x, _], // => ['baz', 1]
* qux: {
* foo: {
* foo: x // => ['qux', 'foo', 'foo']
* }
* }
* }
* ```
*
* @param {Array<*>|Object<*>} list
* @param {Array<Array<number|string>>} parentContext like [0, 3, 2...]
*/
function walker(list, parentContext) {
if (Array.isArray(list)) {
list.forEach(evaluator);
} else {
Object.keys(list).forEach(function(key) {
evaluator(list[key], key);
});
}
function evaluator(value, key) {
var context = parentContext.slice();
context.push(key);
// maybe isObservable
if (value != null && value.subscribe != null && value.publish != null) {
targets.push(value);
contexts.push(context);
// isArray || isObject
} else if (Array.isArray(value) || (!!value && typeof value === 'object')) {
walker(value, context);
}
}
}
walker(templateObject, []);
return {
targets : targets,
contexts : contexts
};
} | javascript | function collectTargetObservablesAndContext(templateObject) {
var targets = [];
var contexts = [];
/**
*
* ```
* // context index sample (`x` == Observable)
* {
* foo: x, // => ['foo']
* bar: {
* foo: x, // => ['bar', 'foo']
* bar: [_, _, x] // => ['bar', 'bar', 2]
* },
* baz: [_, x, _], // => ['baz', 1]
* qux: {
* foo: {
* foo: x // => ['qux', 'foo', 'foo']
* }
* }
* }
* ```
*
* @param {Array<*>|Object<*>} list
* @param {Array<Array<number|string>>} parentContext like [0, 3, 2...]
*/
function walker(list, parentContext) {
if (Array.isArray(list)) {
list.forEach(evaluator);
} else {
Object.keys(list).forEach(function(key) {
evaluator(list[key], key);
});
}
function evaluator(value, key) {
var context = parentContext.slice();
context.push(key);
// maybe isObservable
if (value != null && value.subscribe != null && value.publish != null) {
targets.push(value);
contexts.push(context);
// isArray || isObject
} else if (Array.isArray(value) || (!!value && typeof value === 'object')) {
walker(value, context);
}
}
}
walker(templateObject, []);
return {
targets : targets,
contexts : contexts
};
} | [
"function",
"collectTargetObservablesAndContext",
"(",
"templateObject",
")",
"{",
"var",
"targets",
"=",
"[",
"]",
";",
"var",
"contexts",
"=",
"[",
"]",
";",
"/**\n *\n * ```\n * // context index sample (`x` == Observable)\n * {\n * foo: x, // => ['foo']\n * bar: {\n * foo: x, // => ['bar', 'foo']\n * bar: [_, _, x] // => ['bar', 'bar', 2]\n * },\n * baz: [_, x, _], // => ['baz', 1]\n * qux: {\n * foo: {\n * foo: x // => ['qux', 'foo', 'foo']\n * }\n * }\n * }\n * ```\n *\n * @param {Array<*>|Object<*>} list\n * @param {Array<Array<number|string>>} parentContext like [0, 3, 2...]\n */",
"function",
"walker",
"(",
"list",
",",
"parentContext",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"list",
")",
")",
"{",
"list",
".",
"forEach",
"(",
"evaluator",
")",
";",
"}",
"else",
"{",
"Object",
".",
"keys",
"(",
"list",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"evaluator",
"(",
"list",
"[",
"key",
"]",
",",
"key",
")",
";",
"}",
")",
";",
"}",
"function",
"evaluator",
"(",
"value",
",",
"key",
")",
"{",
"var",
"context",
"=",
"parentContext",
".",
"slice",
"(",
")",
";",
"context",
".",
"push",
"(",
"key",
")",
";",
"// maybe isObservable",
"if",
"(",
"value",
"!=",
"null",
"&&",
"value",
".",
"subscribe",
"!=",
"null",
"&&",
"value",
".",
"publish",
"!=",
"null",
")",
"{",
"targets",
".",
"push",
"(",
"value",
")",
";",
"contexts",
".",
"push",
"(",
"context",
")",
";",
"// isArray || isObject",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
"||",
"(",
"!",
"!",
"value",
"&&",
"typeof",
"value",
"===",
"'object'",
")",
")",
"{",
"walker",
"(",
"value",
",",
"context",
")",
";",
"}",
"}",
"}",
"walker",
"(",
"templateObject",
",",
"[",
"]",
")",
";",
"return",
"{",
"targets",
":",
"targets",
",",
"contexts",
":",
"contexts",
"}",
";",
"}"
]
| Log target observable & context that indicates the position in the object.
@param {Object} templateObject
@returns {{targets: Array, contexts: Array}} | [
"Log",
"target",
"observable",
"&",
"context",
"that",
"indicates",
"the",
"position",
"in",
"the",
"object",
"."
]
| 1c2204b6b26fb2c1ea0452c18191cb3c248522d5 | https://github.com/ahomu/rx.observable.combinetemplate/blob/1c2204b6b26fb2c1ea0452c18191cb3c248522d5/index.js#L92-L150 |
43,639 | jhermsmeier/node-mbr | lib/code.js | Code | function Code( buffer, start, end ) {
if( !(this instanceof Code) )
return new Code( buffer, start, end )
this.offset = start || 0x00
if( Buffer.isBuffer( buffer ) ) {
this.data = buffer.slice( start, end )
} else {
this.data = Buffer.alloc( 446 )
}
} | javascript | function Code( buffer, start, end ) {
if( !(this instanceof Code) )
return new Code( buffer, start, end )
this.offset = start || 0x00
if( Buffer.isBuffer( buffer ) ) {
this.data = buffer.slice( start, end )
} else {
this.data = Buffer.alloc( 446 )
}
} | [
"function",
"Code",
"(",
"buffer",
",",
"start",
",",
"end",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Code",
")",
")",
"return",
"new",
"Code",
"(",
"buffer",
",",
"start",
",",
"end",
")",
"this",
".",
"offset",
"=",
"start",
"||",
"x00",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"buffer",
")",
")",
"{",
"this",
".",
"data",
"=",
"buffer",
".",
"slice",
"(",
"start",
",",
"end",
")",
"}",
"else",
"{",
"this",
".",
"data",
"=",
"Buffer",
".",
"alloc",
"(",
"446",
")",
"}",
"}"
]
| Code section structure
@class
@memberOf MBR
@param {Buffer} buffer
@param {Number} [start]
@param {Number} [end] | [
"Code",
"section",
"structure"
]
| a3ebdeb56fc3ce12a89e965c7127f6fe9547470a | https://github.com/jhermsmeier/node-mbr/blob/a3ebdeb56fc3ce12a89e965c7127f6fe9547470a/lib/code.js#L9-L22 |
43,640 | mjohnsullivan/axiscam | lib/axis.js | function(options) {
var that = this
this.name = options.name
// Record the url and protocol, ignore SSL certs
this.url = url.parse(options.url)
if (this.url.protocol.indexOf('https') === 0) {
this.protocol = https
this.url.rejectUnauthorized = false
}
else
this.protocol = http
// Set the size
imageSize = imageSizes[options.size] || imageSize
// Initialise the jpg stream
this.jpgStream = createJPGStream()
// Start the MJPEG stream
this._createVideoStream()
} | javascript | function(options) {
var that = this
this.name = options.name
// Record the url and protocol, ignore SSL certs
this.url = url.parse(options.url)
if (this.url.protocol.indexOf('https') === 0) {
this.protocol = https
this.url.rejectUnauthorized = false
}
else
this.protocol = http
// Set the size
imageSize = imageSizes[options.size] || imageSize
// Initialise the jpg stream
this.jpgStream = createJPGStream()
// Start the MJPEG stream
this._createVideoStream()
} | [
"function",
"(",
"options",
")",
"{",
"var",
"that",
"=",
"this",
"this",
".",
"name",
"=",
"options",
".",
"name",
"// Record the url and protocol, ignore SSL certs",
"this",
".",
"url",
"=",
"url",
".",
"parse",
"(",
"options",
".",
"url",
")",
"if",
"(",
"this",
".",
"url",
".",
"protocol",
".",
"indexOf",
"(",
"'https'",
")",
"===",
"0",
")",
"{",
"this",
".",
"protocol",
"=",
"https",
"this",
".",
"url",
".",
"rejectUnauthorized",
"=",
"false",
"}",
"else",
"this",
".",
"protocol",
"=",
"http",
"// Set the size",
"imageSize",
"=",
"imageSizes",
"[",
"options",
".",
"size",
"]",
"||",
"imageSize",
"// Initialise the jpg stream",
"this",
".",
"jpgStream",
"=",
"createJPGStream",
"(",
")",
"// Start the MJPEG stream",
"this",
".",
"_createVideoStream",
"(",
")",
"}"
]
| Wrapper for Axis camera VAPIX API
url: the base URL for the camera
name: a name that's associated with the camera | [
"Wrapper",
"for",
"Axis",
"camera",
"VAPIX",
"API"
]
| 1bbdedb3a41a8caa0d748392bfecf9d15ce42ef1 | https://github.com/mjohnsullivan/axiscam/blob/1bbdedb3a41a8caa0d748392bfecf9d15ce42ef1/lib/axis.js#L22-L43 |
|
43,641 | francejs/effroi | src/utils.js | function(element) {
var c={};
try {
var rect = element.getBoundingClientRect();
c.x = Math.floor((rect.left + rect.right) / 2);
c.y = Math.floor((rect.top + rect.bottom) / 2);
} catch(e) {
c.x = 1;
c.y = 1;
}
return c;
} | javascript | function(element) {
var c={};
try {
var rect = element.getBoundingClientRect();
c.x = Math.floor((rect.left + rect.right) / 2);
c.y = Math.floor((rect.top + rect.bottom) / 2);
} catch(e) {
c.x = 1;
c.y = 1;
}
return c;
} | [
"function",
"(",
"element",
")",
"{",
"var",
"c",
"=",
"{",
"}",
";",
"try",
"{",
"var",
"rect",
"=",
"element",
".",
"getBoundingClientRect",
"(",
")",
";",
"c",
".",
"x",
"=",
"Math",
".",
"floor",
"(",
"(",
"rect",
".",
"left",
"+",
"rect",
".",
"right",
")",
"/",
"2",
")",
";",
"c",
".",
"y",
"=",
"Math",
".",
"floor",
"(",
"(",
"rect",
".",
"top",
"+",
"rect",
".",
"bottom",
")",
"/",
"2",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"c",
".",
"x",
"=",
"1",
";",
"c",
".",
"y",
"=",
"1",
";",
"}",
"return",
"c",
";",
"}"
]
| Find the center of an element | [
"Find",
"the",
"center",
"of",
"an",
"element"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/utils.js#L11-L22 |
|
43,642 | francejs/effroi | src/utils.js | function(event, property, value) {
try {
Object.defineProperty(event, property, {
get : function() {
return value;
}
});
} catch(e) {
event[property] = value;
}
} | javascript | function(event, property, value) {
try {
Object.defineProperty(event, property, {
get : function() {
return value;
}
});
} catch(e) {
event[property] = value;
}
} | [
"function",
"(",
"event",
",",
"property",
",",
"value",
")",
"{",
"try",
"{",
"Object",
".",
"defineProperty",
"(",
"event",
",",
"property",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"value",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"event",
"[",
"property",
"]",
"=",
"value",
";",
"}",
"}"
]
| Set event property with a Chromium specific hack | [
"Set",
"event",
"property",
"with",
"a",
"Chromium",
"specific",
"hack"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/utils.js#L49-L59 |
|
43,643 | francejs/effroi | src/utils.js | function(element, content) {
var nodeName = element.nodeName.toLowerCase(),
type = element.hasAttribute('type') ? element.getAttribute('type') : null;
if (nodeName === 'textarea') {
return true;
}
if (nodeName === 'input'
&& ['text', 'password', 'number', 'date'].indexOf(type) !== -1) {
return true;
}
return false;
} | javascript | function(element, content) {
var nodeName = element.nodeName.toLowerCase(),
type = element.hasAttribute('type') ? element.getAttribute('type') : null;
if (nodeName === 'textarea') {
return true;
}
if (nodeName === 'input'
&& ['text', 'password', 'number', 'date'].indexOf(type) !== -1) {
return true;
}
return false;
} | [
"function",
"(",
"element",
",",
"content",
")",
"{",
"var",
"nodeName",
"=",
"element",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
",",
"type",
"=",
"element",
".",
"hasAttribute",
"(",
"'type'",
")",
"?",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
":",
"null",
";",
"if",
"(",
"nodeName",
"===",
"'textarea'",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"nodeName",
"===",
"'input'",
"&&",
"[",
"'text'",
",",
"'password'",
",",
"'number'",
",",
"'date'",
"]",
".",
"indexOf",
"(",
"type",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Tell if the element can accept the given content | [
"Tell",
"if",
"the",
"element",
"can",
"accept",
"the",
"given",
"content"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/utils.js#L62-L74 |
|
43,644 | francejs/effroi | src/utils.js | function(element) {
if('TEXTAREA'===element.nodeName
||('INPUT'===element.nodeName&&element.hasAttribute('type')
&&('text'===element.getAttribute('type')
||'number'===element.getAttribute('type'))
)
) {
return true;
}
return false;
} | javascript | function(element) {
if('TEXTAREA'===element.nodeName
||('INPUT'===element.nodeName&&element.hasAttribute('type')
&&('text'===element.getAttribute('type')
||'number'===element.getAttribute('type'))
)
) {
return true;
}
return false;
} | [
"function",
"(",
"element",
")",
"{",
"if",
"(",
"'TEXTAREA'",
"===",
"element",
".",
"nodeName",
"||",
"(",
"'INPUT'",
"===",
"element",
".",
"nodeName",
"&&",
"element",
".",
"hasAttribute",
"(",
"'type'",
")",
"&&",
"(",
"'text'",
"===",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
"||",
"'number'",
"===",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Tell if the element content can be partially selected | [
"Tell",
"if",
"the",
"element",
"content",
"can",
"be",
"partially",
"selected"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/utils.js#L77-L87 |
|
43,645 | francejs/effroi | src/utils.js | function(element) {
if('TEXTAREA'===element.nodeName || 'SELECT'===element.nodeName
|| ('INPUT'===element.nodeName&&element.hasAttribute('type')
&&('text'===element.getAttribute('type')
|| 'number'===element.getAttribute('type')
|| 'password'===element.getAttribute('type')
|| 'file'===element.getAttribute('type')
|| 'date'===element.getAttribute('type'))
)
) {
return true;
}
return false;
} | javascript | function(element) {
if('TEXTAREA'===element.nodeName || 'SELECT'===element.nodeName
|| ('INPUT'===element.nodeName&&element.hasAttribute('type')
&&('text'===element.getAttribute('type')
|| 'number'===element.getAttribute('type')
|| 'password'===element.getAttribute('type')
|| 'file'===element.getAttribute('type')
|| 'date'===element.getAttribute('type'))
)
) {
return true;
}
return false;
} | [
"function",
"(",
"element",
")",
"{",
"if",
"(",
"'TEXTAREA'",
"===",
"element",
".",
"nodeName",
"||",
"'SELECT'",
"===",
"element",
".",
"nodeName",
"||",
"(",
"'INPUT'",
"===",
"element",
".",
"nodeName",
"&&",
"element",
".",
"hasAttribute",
"(",
"'type'",
")",
"&&",
"(",
"'text'",
"===",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
"||",
"'number'",
"===",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
"||",
"'password'",
"===",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
"||",
"'file'",
"===",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
"||",
"'date'",
"===",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Tell if the element is a form element that can contain a value | [
"Tell",
"if",
"the",
"element",
"is",
"a",
"form",
"element",
"that",
"can",
"contain",
"a",
"value"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/utils.js#L90-L103 |
|
43,646 | jasonslyvia/redux-composable-fetch | lib/jsonpFetch.js | removeElement | function removeElement(elem) {
var parent = elem.parentNode;
if (parent && parent.nodeType !== 11) {
parent.removeChild(elem);
}
} | javascript | function removeElement(elem) {
var parent = elem.parentNode;
if (parent && parent.nodeType !== 11) {
parent.removeChild(elem);
}
} | [
"function",
"removeElement",
"(",
"elem",
")",
"{",
"var",
"parent",
"=",
"elem",
".",
"parentNode",
";",
"if",
"(",
"parent",
"&&",
"parent",
".",
"nodeType",
"!==",
"11",
")",
"{",
"parent",
".",
"removeChild",
"(",
"elem",
")",
";",
"}",
"}"
]
| remove dom node | [
"remove",
"dom",
"node"
]
| eb4676077747692092d7ee1d2d63be16e455e662 | https://github.com/jasonslyvia/redux-composable-fetch/blob/eb4676077747692092d7ee1d2d63be16e455e662/lib/jsonpFetch.js#L18-L24 |
43,647 | jasonslyvia/redux-composable-fetch | lib/jsonpFetch.js | parseUrl | function parseUrl(url, params) {
var paramsStr = '';
if (typeof params === 'string') {
paramsStr = params;
} else if ((typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') {
Object.keys(params).forEach(function (key) {
if (url.indexOf(key + '=') < 0) {
paramsStr += '&' + key + '=' + encodeURIComponent(params[key]);
}
});
}
// add a timestampe to remove cache
paramsStr += '&_time=' + getNow();
if (paramsStr[0] === '&') {
paramsStr = paramsStr.substr(1);
}
return url + (url.indexOf('?') === -1 ? '?' : '&') + paramsStr;
} | javascript | function parseUrl(url, params) {
var paramsStr = '';
if (typeof params === 'string') {
paramsStr = params;
} else if ((typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') {
Object.keys(params).forEach(function (key) {
if (url.indexOf(key + '=') < 0) {
paramsStr += '&' + key + '=' + encodeURIComponent(params[key]);
}
});
}
// add a timestampe to remove cache
paramsStr += '&_time=' + getNow();
if (paramsStr[0] === '&') {
paramsStr = paramsStr.substr(1);
}
return url + (url.indexOf('?') === -1 ? '?' : '&') + paramsStr;
} | [
"function",
"parseUrl",
"(",
"url",
",",
"params",
")",
"{",
"var",
"paramsStr",
"=",
"''",
";",
"if",
"(",
"typeof",
"params",
"===",
"'string'",
")",
"{",
"paramsStr",
"=",
"params",
";",
"}",
"else",
"if",
"(",
"(",
"typeof",
"params",
"===",
"'undefined'",
"?",
"'undefined'",
":",
"_typeof",
"(",
"params",
")",
")",
"===",
"'object'",
")",
"{",
"Object",
".",
"keys",
"(",
"params",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"url",
".",
"indexOf",
"(",
"key",
"+",
"'='",
")",
"<",
"0",
")",
"{",
"paramsStr",
"+=",
"'&'",
"+",
"key",
"+",
"'='",
"+",
"encodeURIComponent",
"(",
"params",
"[",
"key",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"// add a timestampe to remove cache",
"paramsStr",
"+=",
"'&_time='",
"+",
"getNow",
"(",
")",
";",
"if",
"(",
"paramsStr",
"[",
"0",
"]",
"===",
"'&'",
")",
"{",
"paramsStr",
"=",
"paramsStr",
".",
"substr",
"(",
"1",
")",
";",
"}",
"return",
"url",
"+",
"(",
"url",
".",
"indexOf",
"(",
"'?'",
")",
"===",
"-",
"1",
"?",
"'?'",
":",
"'&'",
")",
"+",
"paramsStr",
";",
"}"
]
| parse the final url of request | [
"parse",
"the",
"final",
"url",
"of",
"request"
]
| eb4676077747692092d7ee1d2d63be16e455e662 | https://github.com/jasonslyvia/redux-composable-fetch/blob/eb4676077747692092d7ee1d2d63be16e455e662/lib/jsonpFetch.js#L26-L46 |
43,648 | Robert-W/react-prerender | samples/amd/js/actions/MapActions.js | createMap | function createMap(mapConfig) {
app.debug('MapActions >>> createMap');
var basemap = (0, _jsUtilsParams.getUrlParams)(location.href)[_jsConstantsAppConstants.MAP.basemap];
if (basemap) {
mapConfig.options.basemap = basemap;
}
var deferred = new Promise(function (resolve) {
app.map = new _EsriMap['default'](mapConfig.id, mapConfig.options);
app.map.on('load', function () {
resolve();
});
});
return deferred;
} | javascript | function createMap(mapConfig) {
app.debug('MapActions >>> createMap');
var basemap = (0, _jsUtilsParams.getUrlParams)(location.href)[_jsConstantsAppConstants.MAP.basemap];
if (basemap) {
mapConfig.options.basemap = basemap;
}
var deferred = new Promise(function (resolve) {
app.map = new _EsriMap['default'](mapConfig.id, mapConfig.options);
app.map.on('load', function () {
resolve();
});
});
return deferred;
} | [
"function",
"createMap",
"(",
"mapConfig",
")",
"{",
"app",
".",
"debug",
"(",
"'MapActions >>> createMap'",
")",
";",
"var",
"basemap",
"=",
"(",
"0",
",",
"_jsUtilsParams",
".",
"getUrlParams",
")",
"(",
"location",
".",
"href",
")",
"[",
"_jsConstantsAppConstants",
".",
"MAP",
".",
"basemap",
"]",
";",
"if",
"(",
"basemap",
")",
"{",
"mapConfig",
".",
"options",
".",
"basemap",
"=",
"basemap",
";",
"}",
"var",
"deferred",
"=",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"app",
".",
"map",
"=",
"new",
"_EsriMap",
"[",
"'default'",
"]",
"(",
"mapConfig",
".",
"id",
",",
"mapConfig",
".",
"options",
")",
";",
"app",
".",
"map",
".",
"on",
"(",
"'load'",
",",
"function",
"(",
")",
"{",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"deferred",
";",
"}"
]
| Simple method to create a new Map
@param {object} mapConfig - config object containing id and options
@return {Promise} deferred - Promise that resolves on map load event | [
"Simple",
"method",
"to",
"create",
"a",
"new",
"Map"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/samples/amd/js/actions/MapActions.js#L18-L32 |
43,649 | Robert-W/react-prerender | samples/amd/js/actions/MapActions.js | setBasemap | function setBasemap(basemap) {
app.debug('MapActions >>> setBasemap');
app.map.setBasemap(basemap);
_jsDispatcher.Dispatcher.dispatch({
actionType: _jsConstantsAppConstants.MAP.basemap,
data: basemap
});
} | javascript | function setBasemap(basemap) {
app.debug('MapActions >>> setBasemap');
app.map.setBasemap(basemap);
_jsDispatcher.Dispatcher.dispatch({
actionType: _jsConstantsAppConstants.MAP.basemap,
data: basemap
});
} | [
"function",
"setBasemap",
"(",
"basemap",
")",
"{",
"app",
".",
"debug",
"(",
"'MapActions >>> setBasemap'",
")",
";",
"app",
".",
"map",
".",
"setBasemap",
"(",
"basemap",
")",
";",
"_jsDispatcher",
".",
"Dispatcher",
".",
"dispatch",
"(",
"{",
"actionType",
":",
"_jsConstantsAppConstants",
".",
"MAP",
".",
"basemap",
",",
"data",
":",
"basemap",
"}",
")",
";",
"}"
]
| Method to update the basemap
@param {string} basemap - the value of the basemap to be updated, should come from config.js basemaps | [
"Method",
"to",
"update",
"the",
"basemap"
]
| 0499603b0fa56679abaea323d92ac7be530921f0 | https://github.com/Robert-W/react-prerender/blob/0499603b0fa56679abaea323d92ac7be530921f0/samples/amd/js/actions/MapActions.js#L38-L45 |
43,650 | francejs/effroi | src/devices/keyboard.js | _charIsPrintable | function _charIsPrintable(charCode) {
// C0 control characters
if((charCode >=0 && charCode <= 0x1F) || 0x7F === charCode) {
return false;
}
// C1 control characters
if(charCode >= 0x80 && charCode <= 0x9F) {
return false;
}
if(-1 !== _downKeys.indexOf(this.CTRL)) {
return false;
}
return true;
} | javascript | function _charIsPrintable(charCode) {
// C0 control characters
if((charCode >=0 && charCode <= 0x1F) || 0x7F === charCode) {
return false;
}
// C1 control characters
if(charCode >= 0x80 && charCode <= 0x9F) {
return false;
}
if(-1 !== _downKeys.indexOf(this.CTRL)) {
return false;
}
return true;
} | [
"function",
"_charIsPrintable",
"(",
"charCode",
")",
"{",
"// C0 control characters",
"if",
"(",
"(",
"charCode",
">=",
"0",
"&&",
"charCode",
"<=",
"0x1F",
")",
"||",
"0x7F",
"===",
"charCode",
")",
"{",
"return",
"false",
";",
"}",
"// C1 control characters",
"if",
"(",
"charCode",
">=",
"0x80",
"&&",
"charCode",
"<=",
"0x9F",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"-",
"1",
"!==",
"_downKeys",
".",
"indexOf",
"(",
"this",
".",
"CTRL",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Private functions Return the char corresponding to the key if any | [
"Private",
"functions",
"Return",
"the",
"char",
"corresponding",
"to",
"the",
"key",
"if",
"any"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/devices/keyboard.js#L176-L189 |
43,651 | francejs/effroi | src/devices/keyboard.js | _inputChar | function _inputChar(char) {
if(_charIsPrintable(char.charCodeAt(0))
&&utils.isSelectable(document.activeElement)) {
// add the char
// FIXME: put at caretPosition/replace selected content
document.activeElement.value += char;
// fire an input event
utils.dispatch(document.activeElement, {type: 'input'});
}
} | javascript | function _inputChar(char) {
if(_charIsPrintable(char.charCodeAt(0))
&&utils.isSelectable(document.activeElement)) {
// add the char
// FIXME: put at caretPosition/replace selected content
document.activeElement.value += char;
// fire an input event
utils.dispatch(document.activeElement, {type: 'input'});
}
} | [
"function",
"_inputChar",
"(",
"char",
")",
"{",
"if",
"(",
"_charIsPrintable",
"(",
"char",
".",
"charCodeAt",
"(",
"0",
")",
")",
"&&",
"utils",
".",
"isSelectable",
"(",
"document",
".",
"activeElement",
")",
")",
"{",
"// add the char",
"// FIXME: put at caretPosition/replace selected content",
"document",
".",
"activeElement",
".",
"value",
"+=",
"char",
";",
"// fire an input event",
"utils",
".",
"dispatch",
"(",
"document",
".",
"activeElement",
",",
"{",
"type",
":",
"'input'",
"}",
")",
";",
"}",
"}"
]
| Try to add the char corresponding to the key to the activeElement | [
"Try",
"to",
"add",
"the",
"char",
"corresponding",
"to",
"the",
"key",
"to",
"the",
"activeElement"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/devices/keyboard.js#L192-L201 |
43,652 | francejs/effroi | src/devices/keyboard.js | _getModifiers | function _getModifiers() {
var modifiers = '';
if(_downKeys.length) {
for(var i=_downKeys.length-1; i>=0; i--) {
if(-1 !== _that.MODIFIERS.indexOf(_downKeys[i])) {
modifiers += (modifiers ? ' ' : '') + _downKeys[i];
}
}
}
return modifiers;
} | javascript | function _getModifiers() {
var modifiers = '';
if(_downKeys.length) {
for(var i=_downKeys.length-1; i>=0; i--) {
if(-1 !== _that.MODIFIERS.indexOf(_downKeys[i])) {
modifiers += (modifiers ? ' ' : '') + _downKeys[i];
}
}
}
return modifiers;
} | [
"function",
"_getModifiers",
"(",
")",
"{",
"var",
"modifiers",
"=",
"''",
";",
"if",
"(",
"_downKeys",
".",
"length",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"_downKeys",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"-",
"1",
"!==",
"_that",
".",
"MODIFIERS",
".",
"indexOf",
"(",
"_downKeys",
"[",
"i",
"]",
")",
")",
"{",
"modifiers",
"+=",
"(",
"modifiers",
"?",
"' '",
":",
"''",
")",
"+",
"_downKeys",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"return",
"modifiers",
";",
"}"
]
| Compute current modifiers | [
"Compute",
"current",
"modifiers"
]
| 4313d8597cb31df8e7fa002a4abbd73e7f722640 | https://github.com/francejs/effroi/blob/4313d8597cb31df8e7fa002a4abbd73e7f722640/src/devices/keyboard.js#L204-L214 |
43,653 | john-doherty/jsdoc-to-json-schema | lib/jsdoc-to-json-schema.js | getInputAsStream | function getInputAsStream(input) {
return new Promise(function(resolve, reject) {
if (input.write) {
// already a stream
resolve(input);
}
else {
// read from file
fs.readFileAsync(input, 'utf-8').then(function(data) {
// convert file string into stream and pipe into jsdoc-parse
var stream = string2stream(data);
// return stream
resolve(stream);
})
.catch(function(err) {
reject(err);
});
}
});
} | javascript | function getInputAsStream(input) {
return new Promise(function(resolve, reject) {
if (input.write) {
// already a stream
resolve(input);
}
else {
// read from file
fs.readFileAsync(input, 'utf-8').then(function(data) {
// convert file string into stream and pipe into jsdoc-parse
var stream = string2stream(data);
// return stream
resolve(stream);
})
.catch(function(err) {
reject(err);
});
}
});
} | [
"function",
"getInputAsStream",
"(",
"input",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"input",
".",
"write",
")",
"{",
"// already a stream",
"resolve",
"(",
"input",
")",
";",
"}",
"else",
"{",
"// read from file",
"fs",
".",
"readFileAsync",
"(",
"input",
",",
"'utf-8'",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"// convert file string into stream and pipe into jsdoc-parse",
"var",
"stream",
"=",
"string2stream",
"(",
"data",
")",
";",
"// return stream",
"resolve",
"(",
"stream",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Returns a file as a stream
@param {string} input - path to json/js file containing JSDoc comments
@returns {Promise} promise to return a stream if the file exists | [
"Returns",
"a",
"file",
"as",
"a",
"stream"
]
| be44c57c6b820b2f1133bd0d900df308e462de23 | https://github.com/john-doherty/jsdoc-to-json-schema/blob/be44c57c6b820b2f1133bd0d900df308e462de23/lib/jsdoc-to-json-schema.js#L56-L83 |
43,654 | john-doherty/jsdoc-to-json-schema | lib/jsdoc-to-json-schema.js | buildJsonSchema | function buildJsonSchema(comments) {
// skeleton schema object
var schema = {
properties: {
}
};
// go through each comment block
(comments || []).forEach(function(block) {
// we're only interested in customTags (none standard jsDoc comments i.e. @schema.)
(block.customTags || []).forEach(function(item) {
var tag = item.tag.replace('schema.', '');
var value = item.value || '';
// skip properties with no value
if (value === '') return;
if (block.scope === 'global') {
schema[tag] = value;
}
else {
// item is a property
schema.properties[block.name] = schema.properties[block.name] || {};
// jsdoc-parse lowercase tag names, so we need more case blocks to correct this
switch (tag) {
/* integers */
case 'minimum':
case 'maximum': {
schema.properties[block.name][tag] = parseInt(value, 10);
} break;
case 'minitems': {
schema.properties[block.name].minItems = parseInt(value, 10);
} break;
case 'maxitems': {
schema.properties[block.name].maxItems = parseInt(value, 10);
} break;
case 'minlength': {
schema.properties[block.name].minLength = parseInt(value, 10);
} break;
case 'maxlength': {
schema.properties[block.name].maxLength = parseInt(value, 10);
} break;
case 'exclusiveminimum': {
schema.properties[block.name].exclusiveMinimum = parseInt(value, 10);
} break;
case 'exclusivemaximum': {
schema.properties[block.name].exclusiveMaximum = parseInt(value, 10);
} break;
case 'divisibleby': {
schema.properties[block.name].divisibleBy = parseInt(value, 10);
} break;
/* boolean's */
case 'required': {
schema.properties[block.name][tag] = (value === 'true');
} break;
case 'uniqueitems': {
schema.properties[block.name].uniqueItems = (value === 'true');
} break;
/* strings */
case 'extends':
case 'id':
case 'type':
case 'pattern':
case 'title':
case 'format':
case 'disallow':
case 'extends':
case 'enum':
case 'description':
case 'name':
case 'default':
default: {
schema.properties[block.name][tag] = value;
} break;
}
}
});
});
return schema;
} | javascript | function buildJsonSchema(comments) {
// skeleton schema object
var schema = {
properties: {
}
};
// go through each comment block
(comments || []).forEach(function(block) {
// we're only interested in customTags (none standard jsDoc comments i.e. @schema.)
(block.customTags || []).forEach(function(item) {
var tag = item.tag.replace('schema.', '');
var value = item.value || '';
// skip properties with no value
if (value === '') return;
if (block.scope === 'global') {
schema[tag] = value;
}
else {
// item is a property
schema.properties[block.name] = schema.properties[block.name] || {};
// jsdoc-parse lowercase tag names, so we need more case blocks to correct this
switch (tag) {
/* integers */
case 'minimum':
case 'maximum': {
schema.properties[block.name][tag] = parseInt(value, 10);
} break;
case 'minitems': {
schema.properties[block.name].minItems = parseInt(value, 10);
} break;
case 'maxitems': {
schema.properties[block.name].maxItems = parseInt(value, 10);
} break;
case 'minlength': {
schema.properties[block.name].minLength = parseInt(value, 10);
} break;
case 'maxlength': {
schema.properties[block.name].maxLength = parseInt(value, 10);
} break;
case 'exclusiveminimum': {
schema.properties[block.name].exclusiveMinimum = parseInt(value, 10);
} break;
case 'exclusivemaximum': {
schema.properties[block.name].exclusiveMaximum = parseInt(value, 10);
} break;
case 'divisibleby': {
schema.properties[block.name].divisibleBy = parseInt(value, 10);
} break;
/* boolean's */
case 'required': {
schema.properties[block.name][tag] = (value === 'true');
} break;
case 'uniqueitems': {
schema.properties[block.name].uniqueItems = (value === 'true');
} break;
/* strings */
case 'extends':
case 'id':
case 'type':
case 'pattern':
case 'title':
case 'format':
case 'disallow':
case 'extends':
case 'enum':
case 'description':
case 'name':
case 'default':
default: {
schema.properties[block.name][tag] = value;
} break;
}
}
});
});
return schema;
} | [
"function",
"buildJsonSchema",
"(",
"comments",
")",
"{",
"// skeleton schema object",
"var",
"schema",
"=",
"{",
"properties",
":",
"{",
"}",
"}",
";",
"// go through each comment block",
"(",
"comments",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"block",
")",
"{",
"// we're only interested in customTags (none standard jsDoc comments i.e. @schema.)",
"(",
"block",
".",
"customTags",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"var",
"tag",
"=",
"item",
".",
"tag",
".",
"replace",
"(",
"'schema.'",
",",
"''",
")",
";",
"var",
"value",
"=",
"item",
".",
"value",
"||",
"''",
";",
"// skip properties with no value",
"if",
"(",
"value",
"===",
"''",
")",
"return",
";",
"if",
"(",
"block",
".",
"scope",
"===",
"'global'",
")",
"{",
"schema",
"[",
"tag",
"]",
"=",
"value",
";",
"}",
"else",
"{",
"// item is a property",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
"=",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
"||",
"{",
"}",
";",
"// jsdoc-parse lowercase tag names, so we need more case blocks to correct this",
"switch",
"(",
"tag",
")",
"{",
"/* integers */",
"case",
"'minimum'",
":",
"case",
"'maximum'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
"[",
"tag",
"]",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"case",
"'minitems'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"minItems",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"case",
"'maxitems'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"maxItems",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"case",
"'minlength'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"minLength",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"case",
"'maxlength'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"maxLength",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"case",
"'exclusiveminimum'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"exclusiveMinimum",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"case",
"'exclusivemaximum'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"exclusiveMaximum",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"case",
"'divisibleby'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"divisibleBy",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
";",
"}",
"break",
";",
"/* boolean's */",
"case",
"'required'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
"[",
"tag",
"]",
"=",
"(",
"value",
"===",
"'true'",
")",
";",
"}",
"break",
";",
"case",
"'uniqueitems'",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
".",
"uniqueItems",
"=",
"(",
"value",
"===",
"'true'",
")",
";",
"}",
"break",
";",
"/* strings */",
"case",
"'extends'",
":",
"case",
"'id'",
":",
"case",
"'type'",
":",
"case",
"'pattern'",
":",
"case",
"'title'",
":",
"case",
"'format'",
":",
"case",
"'disallow'",
":",
"case",
"'extends'",
":",
"case",
"'enum'",
":",
"case",
"'description'",
":",
"case",
"'name'",
":",
"case",
"'default'",
":",
"default",
":",
"{",
"schema",
".",
"properties",
"[",
"block",
".",
"name",
"]",
"[",
"tag",
"]",
"=",
"value",
";",
"}",
"break",
";",
"}",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"schema",
";",
"}"
]
| Builds a JSON v3 schema based on schema tags found
@param {array} comments - array of jsdoc comment blocks with scope information
@returns {object} JSON Schema object | [
"Builds",
"a",
"JSON",
"v3",
"schema",
"based",
"on",
"schema",
"tags",
"found"
]
| be44c57c6b820b2f1133bd0d900df308e462de23 | https://github.com/john-doherty/jsdoc-to-json-schema/blob/be44c57c6b820b2f1133bd0d900df308e462de23/lib/jsdoc-to-json-schema.js#L90-L190 |
43,655 | blueapron/grunt-phantomjs-basil | phantomjs/main.js | function(arg) {
var args = Array.isArray(arg) ? arg : Array.apply(null, arguments);
lastMsgDate = new Date();
fs.write(tempFile, JSON.stringify(args) + '\n', 'a');
} | javascript | function(arg) {
var args = Array.isArray(arg) ? arg : Array.apply(null, arguments);
lastMsgDate = new Date();
fs.write(tempFile, JSON.stringify(args) + '\n', 'a');
} | [
"function",
"(",
"arg",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"isArray",
"(",
"arg",
")",
"?",
"arg",
":",
"Array",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"lastMsgDate",
"=",
"new",
"Date",
"(",
")",
";",
"fs",
".",
"write",
"(",
"tempFile",
",",
"JSON",
".",
"stringify",
"(",
"args",
")",
"+",
"'\\n'",
",",
"'a'",
")",
";",
"}"
]
| Send messages to the parent by appending to temp file | [
"Send",
"messages",
"to",
"the",
"parent",
"by",
"appending",
"to",
"temp",
"file"
]
| ecb547ff4063bc04c992ecb1e996f2ad33a9f6ec | https://github.com/blueapron/grunt-phantomjs-basil/blob/ecb547ff4063bc04c992ecb1e996f2ad33a9f6ec/phantomjs/main.js#L49-L53 |
|
43,656 | blueapron/grunt-phantomjs-basil | phantomjs/main.js | function(option) {
var opt = {
name: option.name || Date.now().toString(),
path: option.path ? option.path + '/' : '',
rect: option.rect || webpage.viewportSize
};
// use clipRect to capture only the area of the specified position
webpage.clipRect = opt.rect;
webpage.render([options.screenshotPath, opt.path, opt.name, '.png'].join(''), {format: 'png'});
return option;
} | javascript | function(option) {
var opt = {
name: option.name || Date.now().toString(),
path: option.path ? option.path + '/' : '',
rect: option.rect || webpage.viewportSize
};
// use clipRect to capture only the area of the specified position
webpage.clipRect = opt.rect;
webpage.render([options.screenshotPath, opt.path, opt.name, '.png'].join(''), {format: 'png'});
return option;
} | [
"function",
"(",
"option",
")",
"{",
"var",
"opt",
"=",
"{",
"name",
":",
"option",
".",
"name",
"||",
"Date",
".",
"now",
"(",
")",
".",
"toString",
"(",
")",
",",
"path",
":",
"option",
".",
"path",
"?",
"option",
".",
"path",
"+",
"'/'",
":",
"''",
",",
"rect",
":",
"option",
".",
"rect",
"||",
"webpage",
".",
"viewportSize",
"}",
";",
"// use clipRect to capture only the area of the specified position",
"webpage",
".",
"clipRect",
"=",
"opt",
".",
"rect",
";",
"webpage",
".",
"render",
"(",
"[",
"options",
".",
"screenshotPath",
",",
"opt",
".",
"path",
",",
"opt",
".",
"name",
",",
"'.png'",
"]",
".",
"join",
"(",
"''",
")",
",",
"{",
"format",
":",
"'png'",
"}",
")",
";",
"return",
"option",
";",
"}"
]
| Take screenshot of current page | [
"Take",
"screenshot",
"of",
"current",
"page"
]
| ecb547ff4063bc04c992ecb1e996f2ad33a9f6ec | https://github.com/blueapron/grunt-phantomjs-basil/blob/ecb547ff4063bc04c992ecb1e996f2ad33a9f6ec/phantomjs/main.js#L97-L109 |
|
43,657 | CarbonLighthouse/svc-client | lib/fetchUtil.js | defaultExtractor | function defaultExtractor(response) {
// 204 NO CONTENT
if (response.status === 204) {
return undefined;
}
const contentTypeHeader = response.headers.get('Content-Type');
if (!contentTypeHeader) {
// This is the correct thing to do based on my interpretation of the HTTP specification:
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1
// return arrayBufferExtractor(response);
// But, not supported by fetch polyfill so I just send as text.
return textExtractor(response);
}
const type = contentType.parse(contentTypeHeader).type;
if (type.match(/^application\/json/)) {
return jsonExtractor(response);
}
if (type.match(/^image\//)) {
return blobExtractor(response);
}
// By default try to extract as text?
return textExtractor(response);
} | javascript | function defaultExtractor(response) {
// 204 NO CONTENT
if (response.status === 204) {
return undefined;
}
const contentTypeHeader = response.headers.get('Content-Type');
if (!contentTypeHeader) {
// This is the correct thing to do based on my interpretation of the HTTP specification:
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1
// return arrayBufferExtractor(response);
// But, not supported by fetch polyfill so I just send as text.
return textExtractor(response);
}
const type = contentType.parse(contentTypeHeader).type;
if (type.match(/^application\/json/)) {
return jsonExtractor(response);
}
if (type.match(/^image\//)) {
return blobExtractor(response);
}
// By default try to extract as text?
return textExtractor(response);
} | [
"function",
"defaultExtractor",
"(",
"response",
")",
"{",
"// 204 NO CONTENT",
"if",
"(",
"response",
".",
"status",
"===",
"204",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"contentTypeHeader",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
";",
"if",
"(",
"!",
"contentTypeHeader",
")",
"{",
"// This is the correct thing to do based on my interpretation of the HTTP specification:",
"// https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1",
"// return arrayBufferExtractor(response);",
"// But, not supported by fetch polyfill so I just send as text.",
"return",
"textExtractor",
"(",
"response",
")",
";",
"}",
"const",
"type",
"=",
"contentType",
".",
"parse",
"(",
"contentTypeHeader",
")",
".",
"type",
";",
"if",
"(",
"type",
".",
"match",
"(",
"/",
"^application\\/json",
"/",
")",
")",
"{",
"return",
"jsonExtractor",
"(",
"response",
")",
";",
"}",
"if",
"(",
"type",
".",
"match",
"(",
"/",
"^image\\/",
"/",
")",
")",
"{",
"return",
"blobExtractor",
"(",
"response",
")",
";",
"}",
"// By default try to extract as text?",
"return",
"textExtractor",
"(",
"response",
")",
";",
"}"
]
| I am covering some basics, but honestly there's like a billion mime-types I don't know what the rules are for when to use which extraction method. It should be up to people to use the exported extractors themselves, or provide their own custom extractors in their method description. | [
"I",
"am",
"covering",
"some",
"basics",
"but",
"honestly",
"there",
"s",
"like",
"a",
"billion",
"mime",
"-",
"types",
"I",
"don",
"t",
"know",
"what",
"the",
"rules",
"are",
"for",
"when",
"to",
"use",
"which",
"extraction",
"method",
".",
"It",
"should",
"be",
"up",
"to",
"people",
"to",
"use",
"the",
"exported",
"extractors",
"themselves",
"or",
"provide",
"their",
"own",
"custom",
"extractors",
"in",
"their",
"method",
"description",
"."
]
| 8efa97046c25eee2bc0f959ae98fb44acbcb6c54 | https://github.com/CarbonLighthouse/svc-client/blob/8efa97046c25eee2bc0f959ae98fb44acbcb6c54/lib/fetchUtil.js#L13-L41 |
43,658 | CarbonLighthouse/svc-client | lib/fetchUtil.js | handleErrors | function handleErrors(errorFormatter, response) {
if (!response.ok) {
if (errorFormatter) {
return errorFormatter(response);
}
return defaultErrorFormatter(response);
}
return response;
} | javascript | function handleErrors(errorFormatter, response) {
if (!response.ok) {
if (errorFormatter) {
return errorFormatter(response);
}
return defaultErrorFormatter(response);
}
return response;
} | [
"function",
"handleErrors",
"(",
"errorFormatter",
",",
"response",
")",
"{",
"if",
"(",
"!",
"response",
".",
"ok",
")",
"{",
"if",
"(",
"errorFormatter",
")",
"{",
"return",
"errorFormatter",
"(",
"response",
")",
";",
"}",
"return",
"defaultErrorFormatter",
"(",
"response",
")",
";",
"}",
"return",
"response",
";",
"}"
]
| If there is a custom errorFormatter use it, otherwise use the default
@param errorFormatter
@param response
@returns {*} | [
"If",
"there",
"is",
"a",
"custom",
"errorFormatter",
"use",
"it",
"otherwise",
"use",
"the",
"default"
]
| 8efa97046c25eee2bc0f959ae98fb44acbcb6c54 | https://github.com/CarbonLighthouse/svc-client/blob/8efa97046c25eee2bc0f959ae98fb44acbcb6c54/lib/fetchUtil.js#L61-L70 |
43,659 | blueapron/grunt-qunit-kimchi | qunit/phantom_screenshot.js | getOffset | function getOffset(selector) {
var rect, doc, docElem;
var elem = document.querySelector(selector);
if(!elem) { return false; }
if(!elem.getClientRects().length) {
return { top: 0, left: 0, width: 0, height: 0};
}
rect = elem.getBoundingClientRect();
if(rect.width || rect.height) {
doc = elem.ownerDocument;
docElem = doc.documentElement;
}
return {
top: rect.top + window.pageYOffset - docElem.clientTop,
left: rect.left + window.pageXOffset - docElem.clientLeft,
width: elem.offsetWidth,
height: elem.offsetHeight
}
} | javascript | function getOffset(selector) {
var rect, doc, docElem;
var elem = document.querySelector(selector);
if(!elem) { return false; }
if(!elem.getClientRects().length) {
return { top: 0, left: 0, width: 0, height: 0};
}
rect = elem.getBoundingClientRect();
if(rect.width || rect.height) {
doc = elem.ownerDocument;
docElem = doc.documentElement;
}
return {
top: rect.top + window.pageYOffset - docElem.clientTop,
left: rect.left + window.pageXOffset - docElem.clientLeft,
width: elem.offsetWidth,
height: elem.offsetHeight
}
} | [
"function",
"getOffset",
"(",
"selector",
")",
"{",
"var",
"rect",
",",
"doc",
",",
"docElem",
";",
"var",
"elem",
"=",
"document",
".",
"querySelector",
"(",
"selector",
")",
";",
"if",
"(",
"!",
"elem",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"elem",
".",
"getClientRects",
"(",
")",
".",
"length",
")",
"{",
"return",
"{",
"top",
":",
"0",
",",
"left",
":",
"0",
",",
"width",
":",
"0",
",",
"height",
":",
"0",
"}",
";",
"}",
"rect",
"=",
"elem",
".",
"getBoundingClientRect",
"(",
")",
";",
"if",
"(",
"rect",
".",
"width",
"||",
"rect",
".",
"height",
")",
"{",
"doc",
"=",
"elem",
".",
"ownerDocument",
";",
"docElem",
"=",
"doc",
".",
"documentElement",
";",
"}",
"return",
"{",
"top",
":",
"rect",
".",
"top",
"+",
"window",
".",
"pageYOffset",
"-",
"docElem",
".",
"clientTop",
",",
"left",
":",
"rect",
".",
"left",
"+",
"window",
".",
"pageXOffset",
"-",
"docElem",
".",
"clientLeft",
",",
"width",
":",
"elem",
".",
"offsetWidth",
",",
"height",
":",
"elem",
".",
"offsetHeight",
"}",
"}"
]
| Get offset information with native methods
Because not everyone uses jQuery and QUnit does not depend on jQuery
@param {String} selector (.test, #test)
@return {Object} position of the selector dom | [
"Get",
"offset",
"information",
"with",
"native",
"methods",
"Because",
"not",
"everyone",
"uses",
"jQuery",
"and",
"QUnit",
"does",
"not",
"depend",
"on",
"jQuery"
]
| 594450211b0de3175501e39836cf63e7a12f6504 | https://github.com/blueapron/grunt-qunit-kimchi/blob/594450211b0de3175501e39836cf63e7a12f6504/qunit/phantom_screenshot.js#L53-L75 |
43,660 | blueapron/grunt-qunit-kimchi | qunit/phantom_screenshot.js | excludeElements | function excludeElements(exclude) {
return Array.isArray(exclude) ? exclude.forEach(function(selector) {
// Use querySelectorAll to hide all dom element with the specified selector
var selectorAll = document.querySelectorAll(selector);
if(selectorAll.length) {
// Interate through NodeList
for(var i = 0; i < selectorAll.length; i++) {
selectorAll.item(i).style.visibility = 'hidden';
}
}
}) : false;
} | javascript | function excludeElements(exclude) {
return Array.isArray(exclude) ? exclude.forEach(function(selector) {
// Use querySelectorAll to hide all dom element with the specified selector
var selectorAll = document.querySelectorAll(selector);
if(selectorAll.length) {
// Interate through NodeList
for(var i = 0; i < selectorAll.length; i++) {
selectorAll.item(i).style.visibility = 'hidden';
}
}
}) : false;
} | [
"function",
"excludeElements",
"(",
"exclude",
")",
"{",
"return",
"Array",
".",
"isArray",
"(",
"exclude",
")",
"?",
"exclude",
".",
"forEach",
"(",
"function",
"(",
"selector",
")",
"{",
"// Use querySelectorAll to hide all dom element with the specified selector",
"var",
"selectorAll",
"=",
"document",
".",
"querySelectorAll",
"(",
"selector",
")",
";",
"if",
"(",
"selectorAll",
".",
"length",
")",
"{",
"// Interate through NodeList",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"selectorAll",
".",
"length",
";",
"i",
"++",
")",
"{",
"selectorAll",
".",
"item",
"(",
"i",
")",
".",
"style",
".",
"visibility",
"=",
"'hidden'",
";",
"}",
"}",
"}",
")",
":",
"false",
";",
"}"
]
| Loop through the exlude array and
find the dom of the selector and hide it
@param {Array} exclude - each item in the array should contain selector string | [
"Loop",
"through",
"the",
"exlude",
"array",
"and",
"find",
"the",
"dom",
"of",
"the",
"selector",
"and",
"hide",
"it"
]
| 594450211b0de3175501e39836cf63e7a12f6504 | https://github.com/blueapron/grunt-qunit-kimchi/blob/594450211b0de3175501e39836cf63e7a12f6504/qunit/phantom_screenshot.js#L83-L95 |
43,661 | blueapron/grunt-qunit-kimchi | qunit/phantom_screenshot.js | screenshot | function screenshot(name, options) {
var options = options || {};
var newPath = path;
// options to override
if(options.selector) { selector = options.selector; }
if(options.path) { newPath = path + '/' + options.path; }
if(Array.isArray(options.exclude)) { exclude = exclude.concat(options.exclude); }
// Check if in phantomjs browser and PhantomScreenshot exists
if(window.callPhantom && window.PhantomScreenshot) {
asyncScreenshot(name, newPath);
}
} | javascript | function screenshot(name, options) {
var options = options || {};
var newPath = path;
// options to override
if(options.selector) { selector = options.selector; }
if(options.path) { newPath = path + '/' + options.path; }
if(Array.isArray(options.exclude)) { exclude = exclude.concat(options.exclude); }
// Check if in phantomjs browser and PhantomScreenshot exists
if(window.callPhantom && window.PhantomScreenshot) {
asyncScreenshot(name, newPath);
}
} | [
"function",
"screenshot",
"(",
"name",
",",
"options",
")",
"{",
"var",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"newPath",
"=",
"path",
";",
"// options to override",
"if",
"(",
"options",
".",
"selector",
")",
"{",
"selector",
"=",
"options",
".",
"selector",
";",
"}",
"if",
"(",
"options",
".",
"path",
")",
"{",
"newPath",
"=",
"path",
"+",
"'/'",
"+",
"options",
".",
"path",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
".",
"exclude",
")",
")",
"{",
"exclude",
"=",
"exclude",
".",
"concat",
"(",
"options",
".",
"exclude",
")",
";",
"}",
"// Check if in phantomjs browser and PhantomScreenshot exists",
"if",
"(",
"window",
".",
"callPhantom",
"&&",
"window",
".",
"PhantomScreenshot",
")",
"{",
"asyncScreenshot",
"(",
"name",
",",
"newPath",
")",
";",
"}",
"}"
]
| Helper function to take screenshot if in phantomjs environment
@param {String} name - Name of the image to be saved
@param {Object} options - selector[String], path[String], exclude[Array] | [
"Helper",
"function",
"to",
"take",
"screenshot",
"if",
"in",
"phantomjs",
"environment"
]
| 594450211b0de3175501e39836cf63e7a12f6504 | https://github.com/blueapron/grunt-qunit-kimchi/blob/594450211b0de3175501e39836cf63e7a12f6504/qunit/phantom_screenshot.js#L131-L144 |
43,662 | bjoerge/route-pattern | route-pattern.js | PathPattern | function PathPattern(options) {
// The route string are compiled to a regexp (if it isn't already)
this.regexp = options.regexp;
// The query parameters specified in the path part of the route
this.params = options.params;
// The original routestring (optional)
this.routeString = options.routeString;
} | javascript | function PathPattern(options) {
// The route string are compiled to a regexp (if it isn't already)
this.regexp = options.regexp;
// The query parameters specified in the path part of the route
this.params = options.params;
// The original routestring (optional)
this.routeString = options.routeString;
} | [
"function",
"PathPattern",
"(",
"options",
")",
"{",
"// The route string are compiled to a regexp (if it isn't already)",
"this",
".",
"regexp",
"=",
"options",
".",
"regexp",
";",
"// The query parameters specified in the path part of the route",
"this",
".",
"params",
"=",
"options",
".",
"params",
";",
"// The original routestring (optional)",
"this",
".",
"routeString",
"=",
"options",
".",
"routeString",
";",
"}"
]
| The PathPattern constructor Takes a route string or regexp as parameter and provides a set of utility functions for matching against a location path | [
"The",
"PathPattern",
"constructor",
"Takes",
"a",
"route",
"string",
"or",
"regexp",
"as",
"parameter",
"and",
"provides",
"a",
"set",
"of",
"utility",
"functions",
"for",
"matching",
"against",
"a",
"location",
"path"
]
| 460f59e3ecb1f9601f45c9cd93952df39c29d08a | https://github.com/bjoerge/route-pattern/blob/460f59e3ecb1f9601f45c9cd93952df39c29d08a/route-pattern.js#L164-L173 |
43,663 | harishanchu/nodejs-config | lib/config/environmentDetector.js | detectWebEnvironment | function detectWebEnvironment(environments) {
// If the given environment is just a Closure, we will defer the environment check
// to the Closure the developer has provided, which allows them to totally swap
// the webs environment detection logic with their own custom Closure's code.
if (typeof environments === 'function') {
return environments()
}
var hosts;
for (var environment in environments) {
hosts = environments[environment];
// To determine the current environment, we'll simply iterate through the possible
// environments and look for the host that matches the host for this request we
// are currently processing here, then return back these environment's names.
hosts = helper.parseObject(hosts);
var k, host;
for (k in hosts) {
host = hosts[k];
if (isMachine(host)) return environment;
}
}
return 'production';
} | javascript | function detectWebEnvironment(environments) {
// If the given environment is just a Closure, we will defer the environment check
// to the Closure the developer has provided, which allows them to totally swap
// the webs environment detection logic with their own custom Closure's code.
if (typeof environments === 'function') {
return environments()
}
var hosts;
for (var environment in environments) {
hosts = environments[environment];
// To determine the current environment, we'll simply iterate through the possible
// environments and look for the host that matches the host for this request we
// are currently processing here, then return back these environment's names.
hosts = helper.parseObject(hosts);
var k, host;
for (k in hosts) {
host = hosts[k];
if (isMachine(host)) return environment;
}
}
return 'production';
} | [
"function",
"detectWebEnvironment",
"(",
"environments",
")",
"{",
"// If the given environment is just a Closure, we will defer the environment check",
"// to the Closure the developer has provided, which allows them to totally swap",
"// the webs environment detection logic with their own custom Closure's code.",
"if",
"(",
"typeof",
"environments",
"===",
"'function'",
")",
"{",
"return",
"environments",
"(",
")",
"}",
"var",
"hosts",
";",
"for",
"(",
"var",
"environment",
"in",
"environments",
")",
"{",
"hosts",
"=",
"environments",
"[",
"environment",
"]",
";",
"// To determine the current environment, we'll simply iterate through the possible",
"// environments and look for the host that matches the host for this request we",
"// are currently processing here, then return back these environment's names.",
"hosts",
"=",
"helper",
".",
"parseObject",
"(",
"hosts",
")",
";",
"var",
"k",
",",
"host",
";",
"for",
"(",
"k",
"in",
"hosts",
")",
"{",
"host",
"=",
"hosts",
"[",
"k",
"]",
";",
"if",
"(",
"isMachine",
"(",
"host",
")",
")",
"return",
"environment",
";",
"}",
"}",
"return",
"'production'",
";",
"}"
]
| Set the application environment for a web request.
@param {Object|function} environments
@return string | [
"Set",
"the",
"application",
"environment",
"for",
"a",
"web",
"request",
"."
]
| 47c0d057913c6aaf361afb667b2141906d15c088 | https://github.com/harishanchu/nodejs-config/blob/47c0d057913c6aaf361afb667b2141906d15c088/lib/config/environmentDetector.js#L30-L54 |
43,664 | pablolb/promise-circuitbreaker | doc/scripts/toc.js | function(ul) {
var prevLevel = {level: -1, index: -1, parent: -1, val: ''};
var levelParent = {0: -1};
tocList = ul.children("li");
tocList.each(function(i) {
var me = $(this).removeClass("toc-active");
var currentLevel = parseInt(me.attr('class').trim().slice(-1));
if (currentLevel > prevLevel.level) {
currentParent = prevLevel.index;
} else if (currentLevel == prevLevel.level) {
currentParent = prevLevel.parent;
} else if (currentLevel < prevLevel.level) {
currentParent = levelParent[currentLevel] || prevLevel.parent;
}
levelParent[currentLevel] = currentParent;
var currentVal = $('a', this).text().trim().toLowerCase();
treeObject[i] = {
val: currentVal,
level: currentLevel,
parent: currentParent
}
prevLevel = {index: i, val: currentVal, level: currentLevel, parent: currentParent};
});
} | javascript | function(ul) {
var prevLevel = {level: -1, index: -1, parent: -1, val: ''};
var levelParent = {0: -1};
tocList = ul.children("li");
tocList.each(function(i) {
var me = $(this).removeClass("toc-active");
var currentLevel = parseInt(me.attr('class').trim().slice(-1));
if (currentLevel > prevLevel.level) {
currentParent = prevLevel.index;
} else if (currentLevel == prevLevel.level) {
currentParent = prevLevel.parent;
} else if (currentLevel < prevLevel.level) {
currentParent = levelParent[currentLevel] || prevLevel.parent;
}
levelParent[currentLevel] = currentParent;
var currentVal = $('a', this).text().trim().toLowerCase();
treeObject[i] = {
val: currentVal,
level: currentLevel,
parent: currentParent
}
prevLevel = {index: i, val: currentVal, level: currentLevel, parent: currentParent};
});
} | [
"function",
"(",
"ul",
")",
"{",
"var",
"prevLevel",
"=",
"{",
"level",
":",
"-",
"1",
",",
"index",
":",
"-",
"1",
",",
"parent",
":",
"-",
"1",
",",
"val",
":",
"''",
"}",
";",
"var",
"levelParent",
"=",
"{",
"0",
":",
"-",
"1",
"}",
";",
"tocList",
"=",
"ul",
".",
"children",
"(",
"\"li\"",
")",
";",
"tocList",
".",
"each",
"(",
"function",
"(",
"i",
")",
"{",
"var",
"me",
"=",
"$",
"(",
"this",
")",
".",
"removeClass",
"(",
"\"toc-active\"",
")",
";",
"var",
"currentLevel",
"=",
"parseInt",
"(",
"me",
".",
"attr",
"(",
"'class'",
")",
".",
"trim",
"(",
")",
".",
"slice",
"(",
"-",
"1",
")",
")",
";",
"if",
"(",
"currentLevel",
">",
"prevLevel",
".",
"level",
")",
"{",
"currentParent",
"=",
"prevLevel",
".",
"index",
";",
"}",
"else",
"if",
"(",
"currentLevel",
"==",
"prevLevel",
".",
"level",
")",
"{",
"currentParent",
"=",
"prevLevel",
".",
"parent",
";",
"}",
"else",
"if",
"(",
"currentLevel",
"<",
"prevLevel",
".",
"level",
")",
"{",
"currentParent",
"=",
"levelParent",
"[",
"currentLevel",
"]",
"||",
"prevLevel",
".",
"parent",
";",
"}",
"levelParent",
"[",
"currentLevel",
"]",
"=",
"currentParent",
";",
"var",
"currentVal",
"=",
"$",
"(",
"'a'",
",",
"this",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"treeObject",
"[",
"i",
"]",
"=",
"{",
"val",
":",
"currentVal",
",",
"level",
":",
"currentLevel",
",",
"parent",
":",
"currentParent",
"}",
"prevLevel",
"=",
"{",
"index",
":",
"i",
",",
"val",
":",
"currentVal",
",",
"level",
":",
"currentLevel",
",",
"parent",
":",
"currentParent",
"}",
";",
"}",
")",
";",
"}"
]
| Create the tree | [
"Create",
"the",
"tree"
]
| cfc27daf6f6477c680c8225ba806751f1838b12b | https://github.com/pablolb/promise-circuitbreaker/blob/cfc27daf6f6477c680c8225ba806751f1838b12b/doc/scripts/toc.js#L54-L77 |
|
43,665 | pablolb/promise-circuitbreaker | doc/scripts/toc.js | function(key) {
var me = treeObject[key];
if (me.parent > -1) {
$(tocList[me.parent]).show();
showParents(me.parent);
}
} | javascript | function(key) {
var me = treeObject[key];
if (me.parent > -1) {
$(tocList[me.parent]).show();
showParents(me.parent);
}
} | [
"function",
"(",
"key",
")",
"{",
"var",
"me",
"=",
"treeObject",
"[",
"key",
"]",
";",
"if",
"(",
"me",
".",
"parent",
">",
"-",
"1",
")",
"{",
"$",
"(",
"tocList",
"[",
"me",
".",
"parent",
"]",
")",
".",
"show",
"(",
")",
";",
"showParents",
"(",
"me",
".",
"parent",
")",
";",
"}",
"}"
]
| Show the parents recursively | [
"Show",
"the",
"parents",
"recursively"
]
| cfc27daf6f6477c680c8225ba806751f1838b12b | https://github.com/pablolb/promise-circuitbreaker/blob/cfc27daf6f6477c680c8225ba806751f1838b12b/doc/scripts/toc.js#L80-L86 |
|
43,666 | pablolb/promise-circuitbreaker | doc/scripts/toc.js | function(searchVal) {
searchVal = searchVal.trim().toLowerCase();
for (var key in treeObject) {
var me = treeObject[key];
if (me.val.indexOf(searchVal) !== -1 || searchVal.length == 0) {
$(tocList[key]).show();
if ($(tocList[me.parent]).is(":hidden")) {
showParents(key);
}
} else {
$(tocList[key]).hide();
}
}
} | javascript | function(searchVal) {
searchVal = searchVal.trim().toLowerCase();
for (var key in treeObject) {
var me = treeObject[key];
if (me.val.indexOf(searchVal) !== -1 || searchVal.length == 0) {
$(tocList[key]).show();
if ($(tocList[me.parent]).is(":hidden")) {
showParents(key);
}
} else {
$(tocList[key]).hide();
}
}
} | [
"function",
"(",
"searchVal",
")",
"{",
"searchVal",
"=",
"searchVal",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"for",
"(",
"var",
"key",
"in",
"treeObject",
")",
"{",
"var",
"me",
"=",
"treeObject",
"[",
"key",
"]",
";",
"if",
"(",
"me",
".",
"val",
".",
"indexOf",
"(",
"searchVal",
")",
"!==",
"-",
"1",
"||",
"searchVal",
".",
"length",
"==",
"0",
")",
"{",
"$",
"(",
"tocList",
"[",
"key",
"]",
")",
".",
"show",
"(",
")",
";",
"if",
"(",
"$",
"(",
"tocList",
"[",
"me",
".",
"parent",
"]",
")",
".",
"is",
"(",
"\":hidden\"",
")",
")",
"{",
"showParents",
"(",
"key",
")",
";",
"}",
"}",
"else",
"{",
"$",
"(",
"tocList",
"[",
"key",
"]",
")",
".",
"hide",
"(",
")",
";",
"}",
"}",
"}"
]
| Perform the search | [
"Perform",
"the",
"search"
]
| cfc27daf6f6477c680c8225ba806751f1838b12b | https://github.com/pablolb/promise-circuitbreaker/blob/cfc27daf6f6477c680c8225ba806751f1838b12b/doc/scripts/toc.js#L89-L102 |
|
43,667 | reklatsmasters/pem-file | index.js | encode | function encode(source, label) {
if (!Buffer.isBuffer(source)) {
throw new TypeError('Argument `source` should be a Buffer.')
}
if (typeof label !== 'string') {
throw new TypeError('Argument `label` should be a string in upper case.')
}
const prefix = before + ' ' + label + endline
const suffix = after + ' ' + label + endline
const body = source.toString('base64').replace(/(.{64})/g, '$1\r\n')
return [prefix, body, suffix].join('\r\n')
} | javascript | function encode(source, label) {
if (!Buffer.isBuffer(source)) {
throw new TypeError('Argument `source` should be a Buffer.')
}
if (typeof label !== 'string') {
throw new TypeError('Argument `label` should be a string in upper case.')
}
const prefix = before + ' ' + label + endline
const suffix = after + ' ' + label + endline
const body = source.toString('base64').replace(/(.{64})/g, '$1\r\n')
return [prefix, body, suffix].join('\r\n')
} | [
"function",
"encode",
"(",
"source",
",",
"label",
")",
"{",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"source",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument `source` should be a Buffer.'",
")",
"}",
"if",
"(",
"typeof",
"label",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument `label` should be a string in upper case.'",
")",
"}",
"const",
"prefix",
"=",
"before",
"+",
"' '",
"+",
"label",
"+",
"endline",
"const",
"suffix",
"=",
"after",
"+",
"' '",
"+",
"label",
"+",
"endline",
"const",
"body",
"=",
"source",
".",
"toString",
"(",
"'base64'",
")",
".",
"replace",
"(",
"/",
"(.{64})",
"/",
"g",
",",
"'$1\\r\\n'",
")",
"return",
"[",
"prefix",
",",
"body",
",",
"suffix",
"]",
".",
"join",
"(",
"'\\r\\n'",
")",
"}"
]
| Convert data to PEM format.
@param {Buffer} source
@param {string} label
@returns {String} | [
"Convert",
"data",
"to",
"PEM",
"format",
"."
]
| ac192c8edd4ad310400c34691ab2f04042b0bdec | https://github.com/reklatsmasters/pem-file/blob/ac192c8edd4ad310400c34691ab2f04042b0bdec/index.js#L26-L41 |
43,668 | reklatsmasters/pem-file | index.js | decode | function decode(pem) {
if (Buffer.isBuffer(pem)) {
pem = pem.toString('ascii')
}
const lines = pem.trim().split('\n')
if (lines.length < 3) {
throw new Error('Invalid PEM data.')
}
const match = header.exec(lines[0])
if (match === null) {
throw new Error('Invalid label.')
}
const label = match[1]
let i = 1
for (; i < lines.length; ++i) {
if (lines[i].startsWith(after)) {
break
}
}
const footer = new RegExp(`^${after} ${label}${endline}\r?\n?$`)
if (footer.exec(lines[i]) === null) {
throw new Error('Invalid end of file.')
}
const body = lines.slice(1, i).join('\n').replace(/\r?\n/g, '')
return Buffer.from(body, 'base64')
} | javascript | function decode(pem) {
if (Buffer.isBuffer(pem)) {
pem = pem.toString('ascii')
}
const lines = pem.trim().split('\n')
if (lines.length < 3) {
throw new Error('Invalid PEM data.')
}
const match = header.exec(lines[0])
if (match === null) {
throw new Error('Invalid label.')
}
const label = match[1]
let i = 1
for (; i < lines.length; ++i) {
if (lines[i].startsWith(after)) {
break
}
}
const footer = new RegExp(`^${after} ${label}${endline}\r?\n?$`)
if (footer.exec(lines[i]) === null) {
throw new Error('Invalid end of file.')
}
const body = lines.slice(1, i).join('\n').replace(/\r?\n/g, '')
return Buffer.from(body, 'base64')
} | [
"function",
"decode",
"(",
"pem",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"pem",
")",
")",
"{",
"pem",
"=",
"pem",
".",
"toString",
"(",
"'ascii'",
")",
"}",
"const",
"lines",
"=",
"pem",
".",
"trim",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"lines",
".",
"length",
"<",
"3",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid PEM data.'",
")",
"}",
"const",
"match",
"=",
"header",
".",
"exec",
"(",
"lines",
"[",
"0",
"]",
")",
"if",
"(",
"match",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid label.'",
")",
"}",
"const",
"label",
"=",
"match",
"[",
"1",
"]",
"let",
"i",
"=",
"1",
"for",
"(",
";",
"i",
"<",
"lines",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"lines",
"[",
"i",
"]",
".",
"startsWith",
"(",
"after",
")",
")",
"{",
"break",
"}",
"}",
"const",
"footer",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"after",
"}",
"${",
"label",
"}",
"${",
"endline",
"}",
"\\r",
"\\n",
"`",
")",
"if",
"(",
"footer",
".",
"exec",
"(",
"lines",
"[",
"i",
"]",
")",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid end of file.'",
")",
"}",
"const",
"body",
"=",
"lines",
".",
"slice",
"(",
"1",
",",
"i",
")",
".",
"join",
"(",
"'\\n'",
")",
".",
"replace",
"(",
"/",
"\\r?\\n",
"/",
"g",
",",
"''",
")",
"return",
"Buffer",
".",
"from",
"(",
"body",
",",
"'base64'",
")",
"}"
]
| Convert PEM formatted data to raw buffer.
@param {Buffer|String} pem
@returns {Buffer} | [
"Convert",
"PEM",
"formatted",
"data",
"to",
"raw",
"buffer",
"."
]
| ac192c8edd4ad310400c34691ab2f04042b0bdec | https://github.com/reklatsmasters/pem-file/blob/ac192c8edd4ad310400c34691ab2f04042b0bdec/index.js#L48-L82 |
43,669 | harish2704/html-scrapper | lib/Browser.js | Browser | function Browser ( opts ){
opts = opts || {};
// Members
this.headers = _.defaults({}, headers, opts.headers );
this.proxy = opts.proxy;
this.jar = opts.jar || request.jar();
} | javascript | function Browser ( opts ){
opts = opts || {};
// Members
this.headers = _.defaults({}, headers, opts.headers );
this.proxy = opts.proxy;
this.jar = opts.jar || request.jar();
} | [
"function",
"Browser",
"(",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"// Members",
"this",
".",
"headers",
"=",
"_",
".",
"defaults",
"(",
"{",
"}",
",",
"headers",
",",
"opts",
".",
"headers",
")",
";",
"this",
".",
"proxy",
"=",
"opts",
".",
"proxy",
";",
"this",
".",
"jar",
"=",
"opts",
".",
"jar",
"||",
"request",
".",
"jar",
"(",
")",
";",
"}"
]
| A simple class imitating a web-browser. It can be considered as a wrapper around famous 'request' module.
Current implementation is very limited .
Only get method is implemented. It can be done very easily.
@param {Object} opts - Option object.
@param {Object} opts.headers - [optional] additional headers used for all requests.
default:
```js
var headers = {
'User-Argent' :'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36'
};
```
@param {String} opts.proxy - [optional] proxy parameter that will be passed to request module.
default: null
@param {tough.CookieJar} opts.jar - [optional] Cookie.jar instance used for for the Browser. default ```request.jar()```
It should be an instance of 'tough-cookie' jar;
@return {undefined}
@class | [
"A",
"simple",
"class",
"imitating",
"a",
"web",
"-",
"browser",
".",
"It",
"can",
"be",
"considered",
"as",
"a",
"wrapper",
"around",
"famous",
"request",
"module",
".",
"Current",
"implementation",
"is",
"very",
"limited",
".",
"Only",
"get",
"method",
"is",
"implemented",
".",
"It",
"can",
"be",
"done",
"very",
"easily",
"."
]
| 1515a295bb41d3bdecf8e497d2c0b678854d77a1 | https://github.com/harish2704/html-scrapper/blob/1515a295bb41d3bdecf8e497d2c0b678854d77a1/lib/Browser.js#L39-L45 |
43,670 | vicanso/koa-log | lib/dev.js | dev | function dev() {
return function logger(ctx, next) {
// request
const start = new Date();
/* eslint no-console: 0 */
console.log(` ${chalk.gray('<--')} ${chalk.bold(ctx.method)} ${chalk.gray(ctx.originalUrl)}`);
// calculate the length of a streaming response
// by intercepting the stream with a counter.
// only necessary if a content-length header is currently not set.
const length = ctx.response.length;
const body = ctx.body;
let counter;
if ((length === null || length === undefined) && body && body.readable) {
/* eslint no-param-reassign: 0 */
ctx.body = body
.pipe(counter = new Counter())
.on('error', ctx.onerror);
}
// log when the response is finished or closed,
// whichever happens first.
const res = ctx.res;
const onfinish = done.bind(null, 'finish');
const onclose = done.bind(null, 'close');
/* eslint no-use-before-define: 0 */
function done(event) {
res.removeListener('finish', onfinish);
res.removeListener('close', onclose);
log(ctx, start, counter ? counter.length : length, null, event);
}
res.once('finish', onfinish);
res.once('close', onclose);
return next();
};
} | javascript | function dev() {
return function logger(ctx, next) {
// request
const start = new Date();
/* eslint no-console: 0 */
console.log(` ${chalk.gray('<--')} ${chalk.bold(ctx.method)} ${chalk.gray(ctx.originalUrl)}`);
// calculate the length of a streaming response
// by intercepting the stream with a counter.
// only necessary if a content-length header is currently not set.
const length = ctx.response.length;
const body = ctx.body;
let counter;
if ((length === null || length === undefined) && body && body.readable) {
/* eslint no-param-reassign: 0 */
ctx.body = body
.pipe(counter = new Counter())
.on('error', ctx.onerror);
}
// log when the response is finished or closed,
// whichever happens first.
const res = ctx.res;
const onfinish = done.bind(null, 'finish');
const onclose = done.bind(null, 'close');
/* eslint no-use-before-define: 0 */
function done(event) {
res.removeListener('finish', onfinish);
res.removeListener('close', onclose);
log(ctx, start, counter ? counter.length : length, null, event);
}
res.once('finish', onfinish);
res.once('close', onclose);
return next();
};
} | [
"function",
"dev",
"(",
")",
"{",
"return",
"function",
"logger",
"(",
"ctx",
",",
"next",
")",
"{",
"// request",
"const",
"start",
"=",
"new",
"Date",
"(",
")",
";",
"/* eslint no-console: 0 */",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"gray",
"(",
"'<--'",
")",
"}",
"${",
"chalk",
".",
"bold",
"(",
"ctx",
".",
"method",
")",
"}",
"${",
"chalk",
".",
"gray",
"(",
"ctx",
".",
"originalUrl",
")",
"}",
"`",
")",
";",
"// calculate the length of a streaming response",
"// by intercepting the stream with a counter.",
"// only necessary if a content-length header is currently not set.",
"const",
"length",
"=",
"ctx",
".",
"response",
".",
"length",
";",
"const",
"body",
"=",
"ctx",
".",
"body",
";",
"let",
"counter",
";",
"if",
"(",
"(",
"length",
"===",
"null",
"||",
"length",
"===",
"undefined",
")",
"&&",
"body",
"&&",
"body",
".",
"readable",
")",
"{",
"/* eslint no-param-reassign: 0 */",
"ctx",
".",
"body",
"=",
"body",
".",
"pipe",
"(",
"counter",
"=",
"new",
"Counter",
"(",
")",
")",
".",
"on",
"(",
"'error'",
",",
"ctx",
".",
"onerror",
")",
";",
"}",
"// log when the response is finished or closed,",
"// whichever happens first.",
"const",
"res",
"=",
"ctx",
".",
"res",
";",
"const",
"onfinish",
"=",
"done",
".",
"bind",
"(",
"null",
",",
"'finish'",
")",
";",
"const",
"onclose",
"=",
"done",
".",
"bind",
"(",
"null",
",",
"'close'",
")",
";",
"/* eslint no-use-before-define: 0 */",
"function",
"done",
"(",
"event",
")",
"{",
"res",
".",
"removeListener",
"(",
"'finish'",
",",
"onfinish",
")",
";",
"res",
".",
"removeListener",
"(",
"'close'",
",",
"onclose",
")",
";",
"log",
"(",
"ctx",
",",
"start",
",",
"counter",
"?",
"counter",
".",
"length",
":",
"length",
",",
"null",
",",
"event",
")",
";",
"}",
"res",
".",
"once",
"(",
"'finish'",
",",
"onfinish",
")",
";",
"res",
".",
"once",
"(",
"'close'",
",",
"onclose",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
";",
"}"
]
| Development logger. | [
"Development",
"logger",
"."
]
| 881c093ba4d4fc8cc01d05c274efeedd32db98fb | https://github.com/vicanso/koa-log/blob/881c093ba4d4fc8cc01d05c274efeedd32db98fb/lib/dev.js#L28-L65 |
43,671 | vicanso/koa-log | lib/dev.js | time | function time(start) {
let delta = new Date() - start;
delta = delta < 10000 ? `${delta}ms` : `${Math.round(delta / 1000)}s`;
return humanize(delta);
} | javascript | function time(start) {
let delta = new Date() - start;
delta = delta < 10000 ? `${delta}ms` : `${Math.round(delta / 1000)}s`;
return humanize(delta);
} | [
"function",
"time",
"(",
"start",
")",
"{",
"let",
"delta",
"=",
"new",
"Date",
"(",
")",
"-",
"start",
";",
"delta",
"=",
"delta",
"<",
"10000",
"?",
"`",
"${",
"delta",
"}",
"`",
":",
"`",
"${",
"Math",
".",
"round",
"(",
"delta",
"/",
"1000",
")",
"}",
"`",
";",
"return",
"humanize",
"(",
"delta",
")",
";",
"}"
]
| Show the response time in a human readable format.
In milliseconds if less than 10 seconds,
in seconds otherwise. | [
"Show",
"the",
"response",
"time",
"in",
"a",
"human",
"readable",
"format",
".",
"In",
"milliseconds",
"if",
"less",
"than",
"10",
"seconds",
"in",
"seconds",
"otherwise",
"."
]
| 881c093ba4d4fc8cc01d05c274efeedd32db98fb | https://github.com/vicanso/koa-log/blob/881c093ba4d4fc8cc01d05c274efeedd32db98fb/lib/dev.js#L108-L112 |
43,672 | simonepri/is-sea | index.js | isSea | function isSea(lat, lng) {
if (landLookup === null) {
const map = getMap();
landLookup = new GeoJsonLookup(map);
}
return landLookup.hasContainers({type: 'Point', coordinates: [lng, lat]});
} | javascript | function isSea(lat, lng) {
if (landLookup === null) {
const map = getMap();
landLookup = new GeoJsonLookup(map);
}
return landLookup.hasContainers({type: 'Point', coordinates: [lng, lat]});
} | [
"function",
"isSea",
"(",
"lat",
",",
"lng",
")",
"{",
"if",
"(",
"landLookup",
"===",
"null",
")",
"{",
"const",
"map",
"=",
"getMap",
"(",
")",
";",
"landLookup",
"=",
"new",
"GeoJsonLookup",
"(",
"map",
")",
";",
"}",
"return",
"landLookup",
".",
"hasContainers",
"(",
"{",
"type",
":",
"'Point'",
",",
"coordinates",
":",
"[",
"lng",
",",
"lat",
"]",
"}",
")",
";",
"}"
]
| Returns wheather the given point is in the sea or not.
@public
@param {number} lat The latitude of the point.
@param {number} lng The longitude of the point.
@return {boolean} True if the point is in the sea, false otherwise. | [
"Returns",
"wheather",
"the",
"given",
"point",
"is",
"in",
"the",
"sea",
"or",
"not",
"."
]
| e437c849942b4600599d3e16a592ca87bf7ee582 | https://github.com/simonepri/is-sea/blob/e437c849942b4600599d3e16a592ca87bf7ee582/index.js#L15-L22 |
43,673 | Justineo/postcss-sort-style-rules | index.js | getRange | function getRange(node) {
if (isScope(node)) {
return node.nodes
.map(getRange)
.reduce(reduceRanges);
} else if (node.type === 'rule') {
return specificity.calculate(node.selector)
.map(result => {
return result.specificity.split(',').map(v => Number(v));
})
.reduce(reduceRange, Object.assign({}, DEFAULT_RANGE));
}
return null;
} | javascript | function getRange(node) {
if (isScope(node)) {
return node.nodes
.map(getRange)
.reduce(reduceRanges);
} else if (node.type === 'rule') {
return specificity.calculate(node.selector)
.map(result => {
return result.specificity.split(',').map(v => Number(v));
})
.reduce(reduceRange, Object.assign({}, DEFAULT_RANGE));
}
return null;
} | [
"function",
"getRange",
"(",
"node",
")",
"{",
"if",
"(",
"isScope",
"(",
"node",
")",
")",
"{",
"return",
"node",
".",
"nodes",
".",
"map",
"(",
"getRange",
")",
".",
"reduce",
"(",
"reduceRanges",
")",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"'rule'",
")",
"{",
"return",
"specificity",
".",
"calculate",
"(",
"node",
".",
"selector",
")",
".",
"map",
"(",
"result",
"=>",
"{",
"return",
"result",
".",
"specificity",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"v",
"=>",
"Number",
"(",
"v",
")",
")",
";",
"}",
")",
".",
"reduce",
"(",
"reduceRange",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"DEFAULT_RANGE",
")",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Get specificity range of a style rule or a scope | [
"Get",
"specificity",
"range",
"of",
"a",
"style",
"rule",
"or",
"a",
"scope"
]
| 11d28ee3595c9c37003f69d78657605234fe817e | https://github.com/Justineo/postcss-sort-style-rules/blob/11d28ee3595c9c37003f69d78657605234fe817e/index.js#L63-L76 |
43,674 | discolabs/shopify.i18n.js | dist/shopify.i18n.js | init | function init(defaultLocale, defaultLocaleAssetUrl, defaultCurrency) {
// Store default/initial settings.
_defaultLocale = defaultLocale;
_defaultLocaleAssetUrl = defaultLocaleAssetUrl;
_defaultCurrency = defaultCurrency;
// Store default currency against the Currency object.
Currency.currentCurrency = _defaultCurrency;
// See if we have a saved locale in our cookie that's different to our current one. If so, translate to it.
var cookieLocale = localeCookie.read();
if(cookieLocale && cookieLocale.length && (cookieLocale != _defaultLocale)) {
translate(cookieLocale);
}
// See if we have a saved currency in our cookie that's different to our current one. If so, convert to it.
var cookieCurrency = Currency.cookie.read();
if(cookieCurrency && cookieCurrency.length && (cookieCurrency != _defaultCurrency)) {
convert(cookieCurrency);
}
// Create event listeners.
$(document).on('change', '[data-change="locale"]', localeChangedHandler);
$(document).on('change', '[data-change="currency"]', currencyChangedHandler);
$(document).on('click', '[data-toggle="currency"]', currencyToggledHandler);
} | javascript | function init(defaultLocale, defaultLocaleAssetUrl, defaultCurrency) {
// Store default/initial settings.
_defaultLocale = defaultLocale;
_defaultLocaleAssetUrl = defaultLocaleAssetUrl;
_defaultCurrency = defaultCurrency;
// Store default currency against the Currency object.
Currency.currentCurrency = _defaultCurrency;
// See if we have a saved locale in our cookie that's different to our current one. If so, translate to it.
var cookieLocale = localeCookie.read();
if(cookieLocale && cookieLocale.length && (cookieLocale != _defaultLocale)) {
translate(cookieLocale);
}
// See if we have a saved currency in our cookie that's different to our current one. If so, convert to it.
var cookieCurrency = Currency.cookie.read();
if(cookieCurrency && cookieCurrency.length && (cookieCurrency != _defaultCurrency)) {
convert(cookieCurrency);
}
// Create event listeners.
$(document).on('change', '[data-change="locale"]', localeChangedHandler);
$(document).on('change', '[data-change="currency"]', currencyChangedHandler);
$(document).on('click', '[data-toggle="currency"]', currencyToggledHandler);
} | [
"function",
"init",
"(",
"defaultLocale",
",",
"defaultLocaleAssetUrl",
",",
"defaultCurrency",
")",
"{",
"// Store default/initial settings.",
"_defaultLocale",
"=",
"defaultLocale",
";",
"_defaultLocaleAssetUrl",
"=",
"defaultLocaleAssetUrl",
";",
"_defaultCurrency",
"=",
"defaultCurrency",
";",
"// Store default currency against the Currency object.",
"Currency",
".",
"currentCurrency",
"=",
"_defaultCurrency",
";",
"// See if we have a saved locale in our cookie that's different to our current one. If so, translate to it.",
"var",
"cookieLocale",
"=",
"localeCookie",
".",
"read",
"(",
")",
";",
"if",
"(",
"cookieLocale",
"&&",
"cookieLocale",
".",
"length",
"&&",
"(",
"cookieLocale",
"!=",
"_defaultLocale",
")",
")",
"{",
"translate",
"(",
"cookieLocale",
")",
";",
"}",
"// See if we have a saved currency in our cookie that's different to our current one. If so, convert to it.",
"var",
"cookieCurrency",
"=",
"Currency",
".",
"cookie",
".",
"read",
"(",
")",
";",
"if",
"(",
"cookieCurrency",
"&&",
"cookieCurrency",
".",
"length",
"&&",
"(",
"cookieCurrency",
"!=",
"_defaultCurrency",
")",
")",
"{",
"convert",
"(",
"cookieCurrency",
")",
";",
"}",
"// Create event listeners.",
"$",
"(",
"document",
")",
".",
"on",
"(",
"'change'",
",",
"'[data-change=\"locale\"]'",
",",
"localeChangedHandler",
")",
";",
"$",
"(",
"document",
")",
".",
"on",
"(",
"'change'",
",",
"'[data-change=\"currency\"]'",
",",
"currencyChangedHandler",
")",
";",
"$",
"(",
"document",
")",
".",
"on",
"(",
"'click'",
",",
"'[data-toggle=\"currency\"]'",
",",
"currencyToggledHandler",
")",
";",
"}"
]
| Initialise the i18n module.
@param defaultLocale
@param defaultLocaleAssetUrl
@param defaultCurrency | [
"Initialise",
"the",
"i18n",
"module",
"."
]
| aefa0999b9dece6e4fa74df29b50c0a543608049 | https://github.com/discolabs/shopify.i18n.js/blob/aefa0999b9dece6e4fa74df29b50c0a543608049/dist/shopify.i18n.js#L672-L697 |
43,675 | discolabs/shopify.i18n.js | dist/shopify.i18n.js | translateElement | function translateElement(element, locale) {
var $element = $(element),
keyPath = $element.data('translate');
var translation = getTranslation(keyPath, locale);
if(translation) {
$(element).text(translation);
}
} | javascript | function translateElement(element, locale) {
var $element = $(element),
keyPath = $element.data('translate');
var translation = getTranslation(keyPath, locale);
if(translation) {
$(element).text(translation);
}
} | [
"function",
"translateElement",
"(",
"element",
",",
"locale",
")",
"{",
"var",
"$element",
"=",
"$",
"(",
"element",
")",
",",
"keyPath",
"=",
"$element",
".",
"data",
"(",
"'translate'",
")",
";",
"var",
"translation",
"=",
"getTranslation",
"(",
"keyPath",
",",
"locale",
")",
";",
"if",
"(",
"translation",
")",
"{",
"$",
"(",
"element",
")",
".",
"text",
"(",
"translation",
")",
";",
"}",
"}"
]
| Translate a specific element to the given locale.
@param element
@param locale | [
"Translate",
"a",
"specific",
"element",
"to",
"the",
"given",
"locale",
"."
]
| aefa0999b9dece6e4fa74df29b50c0a543608049 | https://github.com/discolabs/shopify.i18n.js/blob/aefa0999b9dece6e4fa74df29b50c0a543608049/dist/shopify.i18n.js#L733-L741 |
43,676 | discolabs/shopify.i18n.js | dist/shopify.i18n.js | translate | function translate(locale) {
// Check to see if we have the locale translation data available. If not, fetch it via Ajax.
if(_locales[locale] === undefined) {
$.getJSON(getLocaleAssetUrl(locale), function (localeData) {
// Store the returned locale data.
_locales[locale] = localeData;
// Try to perform translation again.
translate(locale);
});
return;
}
// Translate elements to the given locale.
$('[data-translate]').each(function(i, element) {
translateElement(element, locale);
});
// Save the chosen locale in a cookie.
localeCookie.write(locale);
} | javascript | function translate(locale) {
// Check to see if we have the locale translation data available. If not, fetch it via Ajax.
if(_locales[locale] === undefined) {
$.getJSON(getLocaleAssetUrl(locale), function (localeData) {
// Store the returned locale data.
_locales[locale] = localeData;
// Try to perform translation again.
translate(locale);
});
return;
}
// Translate elements to the given locale.
$('[data-translate]').each(function(i, element) {
translateElement(element, locale);
});
// Save the chosen locale in a cookie.
localeCookie.write(locale);
} | [
"function",
"translate",
"(",
"locale",
")",
"{",
"// Check to see if we have the locale translation data available. If not, fetch it via Ajax.",
"if",
"(",
"_locales",
"[",
"locale",
"]",
"===",
"undefined",
")",
"{",
"$",
".",
"getJSON",
"(",
"getLocaleAssetUrl",
"(",
"locale",
")",
",",
"function",
"(",
"localeData",
")",
"{",
"// Store the returned locale data.",
"_locales",
"[",
"locale",
"]",
"=",
"localeData",
";",
"// Try to perform translation again.",
"translate",
"(",
"locale",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"// Translate elements to the given locale.",
"$",
"(",
"'[data-translate]'",
")",
".",
"each",
"(",
"function",
"(",
"i",
",",
"element",
")",
"{",
"translateElement",
"(",
"element",
",",
"locale",
")",
";",
"}",
")",
";",
"// Save the chosen locale in a cookie.",
"localeCookie",
".",
"write",
"(",
"locale",
")",
";",
"}"
]
| Translate all elements on the page marked up with data-translate attributes to the given locale.
@param locale | [
"Translate",
"all",
"elements",
"on",
"the",
"page",
"marked",
"up",
"with",
"data",
"-",
"translate",
"attributes",
"to",
"the",
"given",
"locale",
"."
]
| aefa0999b9dece6e4fa74df29b50c0a543608049 | https://github.com/discolabs/shopify.i18n.js/blob/aefa0999b9dece6e4fa74df29b50c0a543608049/dist/shopify.i18n.js#L748-L767 |
43,677 | discolabs/shopify.i18n.js | dist/shopify.i18n.js | convert | function convert(currency) {
// Store the current currency.
var oldCurrency = Currency.currentCurrency;
// Call convertAll with all possible formats. Currency.currentCurrency will be set as a side effect.
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money"]', 'money_format');
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money_with_currency"]', 'money_with_currency_format');
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money_without_currency"]', 'money_without_currency_format');
// Save the chosen currency in a cookie.
Currency.cookie.write(currency);
// If there was a change in currency, fire the currency changed event.
if(oldCurrency != currency) {
$(document).trigger('currency.changed', [oldCurrency, currency]);
}
} | javascript | function convert(currency) {
// Store the current currency.
var oldCurrency = Currency.currentCurrency;
// Call convertAll with all possible formats. Currency.currentCurrency will be set as a side effect.
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money"]', 'money_format');
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money_with_currency"]', 'money_with_currency_format');
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money_without_currency"]', 'money_without_currency_format');
// Save the chosen currency in a cookie.
Currency.cookie.write(currency);
// If there was a change in currency, fire the currency changed event.
if(oldCurrency != currency) {
$(document).trigger('currency.changed', [oldCurrency, currency]);
}
} | [
"function",
"convert",
"(",
"currency",
")",
"{",
"// Store the current currency.",
"var",
"oldCurrency",
"=",
"Currency",
".",
"currentCurrency",
";",
"// Call convertAll with all possible formats. Currency.currentCurrency will be set as a side effect.",
"Currency",
".",
"convertAll",
"(",
"Currency",
".",
"currentCurrency",
",",
"currency",
",",
"'[data-convert=\"money\"]'",
",",
"'money_format'",
")",
";",
"Currency",
".",
"convertAll",
"(",
"Currency",
".",
"currentCurrency",
",",
"currency",
",",
"'[data-convert=\"money_with_currency\"]'",
",",
"'money_with_currency_format'",
")",
";",
"Currency",
".",
"convertAll",
"(",
"Currency",
".",
"currentCurrency",
",",
"currency",
",",
"'[data-convert=\"money_without_currency\"]'",
",",
"'money_without_currency_format'",
")",
";",
"// Save the chosen currency in a cookie.",
"Currency",
".",
"cookie",
".",
"write",
"(",
"currency",
")",
";",
"// If there was a change in currency, fire the currency changed event.",
"if",
"(",
"oldCurrency",
"!=",
"currency",
")",
"{",
"$",
"(",
"document",
")",
".",
"trigger",
"(",
"'currency.changed'",
",",
"[",
"oldCurrency",
",",
"currency",
"]",
")",
";",
"}",
"}"
]
| Convert all elements on the page marked up with data-convert attributes to the given currency.
@param currency | [
"Convert",
"all",
"elements",
"on",
"the",
"page",
"marked",
"up",
"with",
"data",
"-",
"convert",
"attributes",
"to",
"the",
"given",
"currency",
"."
]
| aefa0999b9dece6e4fa74df29b50c0a543608049 | https://github.com/discolabs/shopify.i18n.js/blob/aefa0999b9dece6e4fa74df29b50c0a543608049/dist/shopify.i18n.js#L796-L812 |
43,678 | alexmic/mongoose-fakery | lib/fakery.js | Factory | function Factory(name, model, attributes) {
this.name = name;
this.model = model;
this.attributes = attributes;
} | javascript | function Factory(name, model, attributes) {
this.name = name;
this.model = model;
this.attributes = attributes;
} | [
"function",
"Factory",
"(",
"name",
",",
"model",
",",
"attributes",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"model",
"=",
"model",
";",
"this",
".",
"attributes",
"=",
"attributes",
";",
"}"
]
| Helper Factory class. Mainly acts as a 'mark' that this is a Factory. For
now this does not play an active role in anything. | [
"Helper",
"Factory",
"class",
".",
"Mainly",
"acts",
"as",
"a",
"mark",
"that",
"this",
"is",
"a",
"Factory",
".",
"For",
"now",
"this",
"does",
"not",
"play",
"an",
"active",
"role",
"in",
"anything",
"."
]
| 98a7357e08d48c785c804dab350e77eb420d3d91 | https://github.com/alexmic/mongoose-fakery/blob/98a7357e08d48c785c804dab350e77eb420d3d91/lib/fakery.js#L14-L18 |
43,679 | alexmic/mongoose-fakery | lib/fakery.js | function(name, model, attributes) {
if (name != null && model == null && attributes == null) return factories[name];
if (model == null) return;
if (attributes == null) attributes = {};
factories[name] = new Factory(name, model, attributes);
} | javascript | function(name, model, attributes) {
if (name != null && model == null && attributes == null) return factories[name];
if (model == null) return;
if (attributes == null) attributes = {};
factories[name] = new Factory(name, model, attributes);
} | [
"function",
"(",
"name",
",",
"model",
",",
"attributes",
")",
"{",
"if",
"(",
"name",
"!=",
"null",
"&&",
"model",
"==",
"null",
"&&",
"attributes",
"==",
"null",
")",
"return",
"factories",
"[",
"name",
"]",
";",
"if",
"(",
"model",
"==",
"null",
")",
"return",
";",
"if",
"(",
"attributes",
"==",
"null",
")",
"attributes",
"=",
"{",
"}",
";",
"factories",
"[",
"name",
"]",
"=",
"new",
"Factory",
"(",
"name",
",",
"model",
",",
"attributes",
")",
";",
"}"
]
| Adds a factory object in `factories`. If a factory with the given name
is already defined, it will get overriden. If only `name` is provided
then it acts as a getter for the named factory.
Params:
- name: the name of the factory, as a string
- model: the mongoose model class
- attributes: hash with model attributes
Examples:
>>> fakery.fake('test', TestModel, {name: fakery.g.name()});
// => undefined
>>> fakery.fake('test');
// => {name: 'test', model: TestModel, attributes: {name: ...}}; | [
"Adds",
"a",
"factory",
"object",
"in",
"factories",
".",
"If",
"a",
"factory",
"with",
"the",
"given",
"name",
"is",
"already",
"defined",
"it",
"will",
"get",
"overriden",
".",
"If",
"only",
"name",
"is",
"provided",
"then",
"it",
"acts",
"as",
"a",
"getter",
"for",
"the",
"named",
"factory",
"."
]
| 98a7357e08d48c785c804dab350e77eb420d3d91 | https://github.com/alexmic/mongoose-fakery/blob/98a7357e08d48c785c804dab350e77eb420d3d91/lib/fakery.js#L46-L51 |
|
43,680 | alexmic/mongoose-fakery | lib/fakery.js | function(attr, lazyContext) {
var resolved;
if (helpers.isArray(attr)) {
resolved = helpers.map(attr, function(item) {
return resolve(item, lazyContext);
});
} else if (helpers.isFunction(attr)) {
if (attr._lazy === true) {
if (lazyContext != null) resolved = attr(lazyContext);
} else {
resolved = attr();
}
} else if (helpers.isObject(attr)) {
resolved = {};
helpers.each(attr, function(value, key) {
resolved[key] = resolve(value, lazyContext);
});
} else {
resolved = attr;
}
return resolved;
} | javascript | function(attr, lazyContext) {
var resolved;
if (helpers.isArray(attr)) {
resolved = helpers.map(attr, function(item) {
return resolve(item, lazyContext);
});
} else if (helpers.isFunction(attr)) {
if (attr._lazy === true) {
if (lazyContext != null) resolved = attr(lazyContext);
} else {
resolved = attr();
}
} else if (helpers.isObject(attr)) {
resolved = {};
helpers.each(attr, function(value, key) {
resolved[key] = resolve(value, lazyContext);
});
} else {
resolved = attr;
}
return resolved;
} | [
"function",
"(",
"attr",
",",
"lazyContext",
")",
"{",
"var",
"resolved",
";",
"if",
"(",
"helpers",
".",
"isArray",
"(",
"attr",
")",
")",
"{",
"resolved",
"=",
"helpers",
".",
"map",
"(",
"attr",
",",
"function",
"(",
"item",
")",
"{",
"return",
"resolve",
"(",
"item",
",",
"lazyContext",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"helpers",
".",
"isFunction",
"(",
"attr",
")",
")",
"{",
"if",
"(",
"attr",
".",
"_lazy",
"===",
"true",
")",
"{",
"if",
"(",
"lazyContext",
"!=",
"null",
")",
"resolved",
"=",
"attr",
"(",
"lazyContext",
")",
";",
"}",
"else",
"{",
"resolved",
"=",
"attr",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"helpers",
".",
"isObject",
"(",
"attr",
")",
")",
"{",
"resolved",
"=",
"{",
"}",
";",
"helpers",
".",
"each",
"(",
"attr",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"resolved",
"[",
"key",
"]",
"=",
"resolve",
"(",
"value",
",",
"lazyContext",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"resolved",
"=",
"attr",
";",
"}",
"return",
"resolved",
";",
"}"
]
| Resolves an attribute to a value, depending on its type.
`lazyContext` is passed to this method during the second pass where
lazy attributes are supposed to get resolved.
This is a private method.
Params
- attr: the factory attribute to resolve
- lazyContext: the context for lazy attributes, which is a hash of all
resolved attributes during the first run | [
"Resolves",
"an",
"attribute",
"to",
"a",
"value",
"depending",
"on",
"its",
"type",
"."
]
| 98a7357e08d48c785c804dab350e77eb420d3d91 | https://github.com/alexmic/mongoose-fakery/blob/98a7357e08d48c785c804dab350e77eb420d3d91/lib/fakery.js#L67-L90 |
|
43,681 | alexmic/mongoose-fakery | lib/fakery.js | function(name, overrides) {
var factory = factories[name], resolved;
if (overrides == null) overrides = {};
if (factory == null) return;
// resolve "eager" properties first and leave lazy ones for a second pass
var resolved = resolve(factory.attributes);
// pass already resolved attributes as context to the second pass
resolved = resolve(factory.attributes, resolved);
// apply overrides
helpers.each(overrides, function(value, key) {
resolved[key] = value;
});
return new factory.model(resolved);
} | javascript | function(name, overrides) {
var factory = factories[name], resolved;
if (overrides == null) overrides = {};
if (factory == null) return;
// resolve "eager" properties first and leave lazy ones for a second pass
var resolved = resolve(factory.attributes);
// pass already resolved attributes as context to the second pass
resolved = resolve(factory.attributes, resolved);
// apply overrides
helpers.each(overrides, function(value, key) {
resolved[key] = value;
});
return new factory.model(resolved);
} | [
"function",
"(",
"name",
",",
"overrides",
")",
"{",
"var",
"factory",
"=",
"factories",
"[",
"name",
"]",
",",
"resolved",
";",
"if",
"(",
"overrides",
"==",
"null",
")",
"overrides",
"=",
"{",
"}",
";",
"if",
"(",
"factory",
"==",
"null",
")",
"return",
";",
"// resolve \"eager\" properties first and leave lazy ones for a second pass",
"var",
"resolved",
"=",
"resolve",
"(",
"factory",
".",
"attributes",
")",
";",
"// pass already resolved attributes as context to the second pass",
"resolved",
"=",
"resolve",
"(",
"factory",
".",
"attributes",
",",
"resolved",
")",
";",
"// apply overrides",
"helpers",
".",
"each",
"(",
"overrides",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"resolved",
"[",
"key",
"]",
"=",
"value",
";",
"}",
")",
";",
"return",
"new",
"factory",
".",
"model",
"(",
"resolved",
")",
";",
"}"
]
| Makes a model from the factory with the given `name`.
Params
- name: the name of the factory, as a string
- overrides: a hash of attributes to override factory attributes passed
in `fake()` call.
Examples:
>>> fakery.make('test', {name: 'test'});
// => {name: 'test', ...} | [
"Makes",
"a",
"model",
"from",
"the",
"factory",
"with",
"the",
"given",
"name",
"."
]
| 98a7357e08d48c785c804dab350e77eb420d3d91 | https://github.com/alexmic/mongoose-fakery/blob/98a7357e08d48c785c804dab350e77eb420d3d91/lib/fakery.js#L104-L117 |
|
43,682 | alexmic/mongoose-fakery | lib/fakery.js | function(name, arg1, arg2) {
var overrides, done, model;
if (helpers.isObject(arg1)) {
overrides = arg1;
done = arg2;
}
if (helpers.isFunction(arg1)) {
overrides = {};
done = arg1;
}
model = make(name, overrides);
if (model != null) model.save(done);
return model;
} | javascript | function(name, arg1, arg2) {
var overrides, done, model;
if (helpers.isObject(arg1)) {
overrides = arg1;
done = arg2;
}
if (helpers.isFunction(arg1)) {
overrides = {};
done = arg1;
}
model = make(name, overrides);
if (model != null) model.save(done);
return model;
} | [
"function",
"(",
"name",
",",
"arg1",
",",
"arg2",
")",
"{",
"var",
"overrides",
",",
"done",
",",
"model",
";",
"if",
"(",
"helpers",
".",
"isObject",
"(",
"arg1",
")",
")",
"{",
"overrides",
"=",
"arg1",
";",
"done",
"=",
"arg2",
";",
"}",
"if",
"(",
"helpers",
".",
"isFunction",
"(",
"arg1",
")",
")",
"{",
"overrides",
"=",
"{",
"}",
";",
"done",
"=",
"arg1",
";",
"}",
"model",
"=",
"make",
"(",
"name",
",",
"overrides",
")",
";",
"if",
"(",
"model",
"!=",
"null",
")",
"model",
".",
"save",
"(",
"done",
")",
";",
"return",
"model",
";",
"}"
]
| Makes a model and persists it in the database.
Params
- name: the name of the factory, as a string
- arg1: either a mongoose callback or an override hash
- arg2: if arg1 is an override hash, then arg2 is the mongoose callback
Examples:
>>> fakery.makeAndSave('test', function(err, test) {
console.log(test);
})
// => TestUser | [
"Makes",
"a",
"model",
"and",
"persists",
"it",
"in",
"the",
"database",
"."
]
| 98a7357e08d48c785c804dab350e77eb420d3d91 | https://github.com/alexmic/mongoose-fakery/blob/98a7357e08d48c785c804dab350e77eb420d3d91/lib/fakery.js#L133-L146 |
|
43,683 | alexmic/mongoose-fakery | lib/fakery.js | function(name, fn) {
if (name == null || fn == null) return;
generatorStore[name] = function() {
var args = [].slice.call(arguments);
return function() {
return fn.apply(fn, args);
};
};
} | javascript | function(name, fn) {
if (name == null || fn == null) return;
generatorStore[name] = function() {
var args = [].slice.call(arguments);
return function() {
return fn.apply(fn, args);
};
};
} | [
"function",
"(",
"name",
",",
"fn",
")",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"fn",
"==",
"null",
")",
"return",
";",
"generatorStore",
"[",
"name",
"]",
"=",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"return",
"function",
"(",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"fn",
",",
"args",
")",
";",
"}",
";",
"}",
";",
"}"
]
| Creates and stores a new generator function from a data provider. A data
provider is basically a function that returns some data. Generators wrap
data providers and pass any parameters they receive.
Params:
- name: the name of the generator, as a string
- fn: the provider function
Examples:
>>> fakery.generator('now', function() {
return new Date();
});
// => undefined | [
"Creates",
"and",
"stores",
"a",
"new",
"generator",
"function",
"from",
"a",
"data",
"provider",
".",
"A",
"data",
"provider",
"is",
"basically",
"a",
"function",
"that",
"returns",
"some",
"data",
".",
"Generators",
"wrap",
"data",
"providers",
"and",
"pass",
"any",
"parameters",
"they",
"receive",
"."
]
| 98a7357e08d48c785c804dab350e77eb420d3d91 | https://github.com/alexmic/mongoose-fakery/blob/98a7357e08d48c785c804dab350e77eb420d3d91/lib/fakery.js#L163-L171 |
|
43,684 | azu/babel-plugin-jsdoc-to-assert | src/index.js | maybeSkip | function maybeSkip(path) {
if(path.__jsdoc_to_assert_checked__) {
return true;
}
const {node} = path;
if (node.leadingComments != null && node.leadingComments.length > 0) {
return false;
}
return true;
} | javascript | function maybeSkip(path) {
if(path.__jsdoc_to_assert_checked__) {
return true;
}
const {node} = path;
if (node.leadingComments != null && node.leadingComments.length > 0) {
return false;
}
return true;
} | [
"function",
"maybeSkip",
"(",
"path",
")",
"{",
"if",
"(",
"path",
".",
"__jsdoc_to_assert_checked__",
")",
"{",
"return",
"true",
";",
"}",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"node",
".",
"leadingComments",
"!=",
"null",
"&&",
"node",
".",
"leadingComments",
".",
"length",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| if the `path` have not comments, return true
@param {Object} path
@returns {boolean} | [
"if",
"the",
"path",
"have",
"not",
"comments",
"return",
"true"
]
| 1b001e993a6086ec01305fc310283ddf3273c92b | https://github.com/azu/babel-plugin-jsdoc-to-assert/blob/1b001e993a6086ec01305fc310283ddf3273c92b/src/index.js#L23-L32 |
43,685 | emmetio/html-transform | lib/addons/bem.js | getBlockName | function getBlockName(node, lookup, prefix) {
let depth = prefix.length > 1 ? prefix.length : 0;
// NB don’t walk up to root node, stay at first root child in case of
// too deep prefix
while (node.parent && node.parent.parent && depth--) {
node = node.parent;
}
return lookup.get(node) || '';
} | javascript | function getBlockName(node, lookup, prefix) {
let depth = prefix.length > 1 ? prefix.length : 0;
// NB don’t walk up to root node, stay at first root child in case of
// too deep prefix
while (node.parent && node.parent.parent && depth--) {
node = node.parent;
}
return lookup.get(node) || '';
} | [
"function",
"getBlockName",
"(",
"node",
",",
"lookup",
",",
"prefix",
")",
"{",
"let",
"depth",
"=",
"prefix",
".",
"length",
">",
"1",
"?",
"prefix",
".",
"length",
":",
"0",
";",
"// NB don’t walk up to root node, stay at first root child in case of",
"// too deep prefix",
"while",
"(",
"node",
".",
"parent",
"&&",
"node",
".",
"parent",
".",
"parent",
"&&",
"depth",
"--",
")",
"{",
"node",
"=",
"node",
".",
"parent",
";",
"}",
"return",
"lookup",
".",
"get",
"(",
"node",
")",
"||",
"''",
";",
"}"
]
| Returns block name for given `node` by `prefix`, which tells the depth of
of parent node lookup
@param {Node} node
@param {Map} lookup
@param {String} prefix
@return {String} | [
"Returns",
"block",
"name",
"for",
"given",
"node",
"by",
"prefix",
"which",
"tells",
"the",
"depth",
"of",
"of",
"parent",
"node",
"lookup"
]
| 61774dba583f811f910f7b031743289b87cab98f | https://github.com/emmetio/html-transform/blob/61774dba583f811f910f7b031743289b87cab98f/lib/addons/bem.js#L132-L142 |
43,686 | julianburr/sketchtool-cli | index.js | pluginFolder | function pluginFolder () {
const path = sketchtoolExec('show plugins');
invariant(path, 'Plugin folder not found!');
invariant(fs.existsSync(path), `Plugin folder does not exist at ${path}!`);
return path;
} | javascript | function pluginFolder () {
const path = sketchtoolExec('show plugins');
invariant(path, 'Plugin folder not found!');
invariant(fs.existsSync(path), `Plugin folder does not exist at ${path}!`);
return path;
} | [
"function",
"pluginFolder",
"(",
")",
"{",
"const",
"path",
"=",
"sketchtoolExec",
"(",
"'show plugins'",
")",
";",
"invariant",
"(",
"path",
",",
"'Plugin folder not found!'",
")",
";",
"invariant",
"(",
"fs",
".",
"existsSync",
"(",
"path",
")",
",",
"`",
"${",
"path",
"}",
"`",
")",
";",
"return",
"path",
";",
"}"
]
| Receive plugin folder path from current Sketch installation
@return {string} | [
"Receive",
"plugin",
"folder",
"path",
"from",
"current",
"Sketch",
"installation"
]
| 9609acf4ef234507eef32151f93e892243437124 | https://github.com/julianburr/sketchtool-cli/blob/9609acf4ef234507eef32151f93e892243437124/index.js#L71-L76 |
43,687 | julianburr/sketchtool-cli | index.js | runPluginWithIdentifier | function runPluginWithIdentifier (pluginName, identifier, options = {}) {
const pluginFolderPath = options.dir || pluginFolder();
// Append `.sketchplugin` if not passed in with the plugin name
if (!pluginName.endsWith('.sketchplugin')) {
pluginName += '.sketchplugin';
}
const pluginPath = `${pluginFolderPath}/${pluginName}`;
// Check if the plugin actually exists before running anything!
const exists = fs.existsSync(pluginPath);
invariant(
exists,
`Plugin '${pluginPath}' not found! Cannot run plugin command!`
);
let args = '';
if (options.context) {
args += `--context='${JSON.stringify(options.context)}' `;
}
sketchtoolExec(`run ${escape(pluginPath)} ${identifier} ${args}`);
} | javascript | function runPluginWithIdentifier (pluginName, identifier, options = {}) {
const pluginFolderPath = options.dir || pluginFolder();
// Append `.sketchplugin` if not passed in with the plugin name
if (!pluginName.endsWith('.sketchplugin')) {
pluginName += '.sketchplugin';
}
const pluginPath = `${pluginFolderPath}/${pluginName}`;
// Check if the plugin actually exists before running anything!
const exists = fs.existsSync(pluginPath);
invariant(
exists,
`Plugin '${pluginPath}' not found! Cannot run plugin command!`
);
let args = '';
if (options.context) {
args += `--context='${JSON.stringify(options.context)}' `;
}
sketchtoolExec(`run ${escape(pluginPath)} ${identifier} ${args}`);
} | [
"function",
"runPluginWithIdentifier",
"(",
"pluginName",
",",
"identifier",
",",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"pluginFolderPath",
"=",
"options",
".",
"dir",
"||",
"pluginFolder",
"(",
")",
";",
"// Append `.sketchplugin` if not passed in with the plugin name",
"if",
"(",
"!",
"pluginName",
".",
"endsWith",
"(",
"'.sketchplugin'",
")",
")",
"{",
"pluginName",
"+=",
"'.sketchplugin'",
";",
"}",
"const",
"pluginPath",
"=",
"`",
"${",
"pluginFolderPath",
"}",
"${",
"pluginName",
"}",
"`",
";",
"// Check if the plugin actually exists before running anything!",
"const",
"exists",
"=",
"fs",
".",
"existsSync",
"(",
"pluginPath",
")",
";",
"invariant",
"(",
"exists",
",",
"`",
"${",
"pluginPath",
"}",
"`",
")",
";",
"let",
"args",
"=",
"''",
";",
"if",
"(",
"options",
".",
"context",
")",
"{",
"args",
"+=",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"options",
".",
"context",
")",
"}",
"`",
";",
"}",
"sketchtoolExec",
"(",
"`",
"${",
"escape",
"(",
"pluginPath",
")",
"}",
"${",
"identifier",
"}",
"${",
"args",
"}",
"`",
")",
";",
"}"
]
| Run given plugin command of given plugin name
@param {string} pluginName
@param {string} identifier
@param {Object} options | [
"Run",
"given",
"plugin",
"command",
"of",
"given",
"plugin",
"name"
]
| 9609acf4ef234507eef32151f93e892243437124 | https://github.com/julianburr/sketchtool-cli/blob/9609acf4ef234507eef32151f93e892243437124/index.js#L84-L107 |
43,688 | julianburr/sketchtool-cli | index.js | list | function list (type, filePath) {
invariant(
ALLOWED_LIST_TYPES.includes(type),
`Type '${type}' is not supported by sketchtool`
);
return JSON.parse(sketchtoolExec(`list ${type} ${escape(filePath)}`));
} | javascript | function list (type, filePath) {
invariant(
ALLOWED_LIST_TYPES.includes(type),
`Type '${type}' is not supported by sketchtool`
);
return JSON.parse(sketchtoolExec(`list ${type} ${escape(filePath)}`));
} | [
"function",
"list",
"(",
"type",
",",
"filePath",
")",
"{",
"invariant",
"(",
"ALLOWED_LIST_TYPES",
".",
"includes",
"(",
"type",
")",
",",
"`",
"${",
"type",
"}",
"`",
")",
";",
"return",
"JSON",
".",
"parse",
"(",
"sketchtoolExec",
"(",
"`",
"${",
"type",
"}",
"${",
"escape",
"(",
"filePath",
")",
"}",
"`",
")",
")",
";",
"}"
]
| List specific element type from given file
@param {string} type
@param {string} filePath
@return {Object} | [
"List",
"specific",
"element",
"type",
"from",
"given",
"file"
]
| 9609acf4ef234507eef32151f93e892243437124 | https://github.com/julianburr/sketchtool-cli/blob/9609acf4ef234507eef32151f93e892243437124/index.js#L124-L130 |
43,689 | amida-tech/withings-lib | lib/withings.js | function (options) {
this._oauth = new OAuth.OAuth(
endpoints.requestToken,
endpoints.accessToken,
options.consumerKey,
options.consumerSecret,
'1.0',
options.callbackUrl,
'HMAC-SHA1'
);
// Store authenticated access if it exists
if (options.accessToken) {
this.accessToken = options.accessToken;
this.accessTokenSecret = options.accessTokenSecret;
}
// Store a user ID if it exists
if (options.userID) {
this.userID = options.userID;
}
} | javascript | function (options) {
this._oauth = new OAuth.OAuth(
endpoints.requestToken,
endpoints.accessToken,
options.consumerKey,
options.consumerSecret,
'1.0',
options.callbackUrl,
'HMAC-SHA1'
);
// Store authenticated access if it exists
if (options.accessToken) {
this.accessToken = options.accessToken;
this.accessTokenSecret = options.accessTokenSecret;
}
// Store a user ID if it exists
if (options.userID) {
this.userID = options.userID;
}
} | [
"function",
"(",
"options",
")",
"{",
"this",
".",
"_oauth",
"=",
"new",
"OAuth",
".",
"OAuth",
"(",
"endpoints",
".",
"requestToken",
",",
"endpoints",
".",
"accessToken",
",",
"options",
".",
"consumerKey",
",",
"options",
".",
"consumerSecret",
",",
"'1.0'",
",",
"options",
".",
"callbackUrl",
",",
"'HMAC-SHA1'",
")",
";",
"// Store authenticated access if it exists",
"if",
"(",
"options",
".",
"accessToken",
")",
"{",
"this",
".",
"accessToken",
"=",
"options",
".",
"accessToken",
";",
"this",
".",
"accessTokenSecret",
"=",
"options",
".",
"accessTokenSecret",
";",
"}",
"// Store a user ID if it exists",
"if",
"(",
"options",
".",
"userID",
")",
"{",
"this",
".",
"userID",
"=",
"options",
".",
"userID",
";",
"}",
"}"
]
| OAuth API Client | [
"OAuth",
"API",
"Client"
]
| e82ad901f1642f276dcfcceb3ac93edd9027cd2f | https://github.com/amida-tech/withings-lib/blob/e82ad901f1642f276dcfcceb3ac93edd9027cd2f/lib/withings.js#L35-L58 |
|
43,690 | pablolb/promise-circuitbreaker | lib/observer.js | CBObserver | function CBObserver() {
var EVENT = 'interval',
watched = [],
listeners = [],
intervals = {},
self = this;
/**
* Watch a circuit breaker
*
* @param {CircuitBreaker} cb - The circuit breaker on which we'll listen the 'interval' event.
*/
this.watch = function(cb) {
if (watched.indexOf(cb) > -1) {
return;
}
watched.push(cb);
var name = cb.getName();
if (!(name in intervals)) {
intervals[name] = [];
}
var listener = buildOnInterval(name);
listeners.push(listener);
cb.on(EVENT, listener);
};
/**
* Stop watching this circuit breaker
*
* @param {CircuitBreaker} cb
*/
this.unwatch = function(cb) {
var index = watched.indexOf(cb);
if (index > -1) {
watched.splice(index, 1);
var arr = listeners.splice(index, 1);
cb.removeListener(EVENT, arr[0]);
}
};
function buildOnInterval(cb) {
return function(interval) {
intervals[cb].push(interval);
emitIfNecessary();
};
}
function emitIfNecessary() {
for (var name in intervals) {
var cnt = intervals[name].length;
if (cnt > 1) {
doEmit();
return;
} else if (cnt === 0) {
return false;
}
}
doEmit();
}
function doEmit() {
var data = intervals;
intervals = {};
for (var name in data) {
intervals[name] = [];
}
/**
* Batch event. The keys of the object are the names of the circuit breakers.
* The values of the object are arrays of {@link CircuitBreaker#event:interval}.
*
* @event CBObserver#batch
* @type object
*/
self.emit('batch', data);
}
} | javascript | function CBObserver() {
var EVENT = 'interval',
watched = [],
listeners = [],
intervals = {},
self = this;
/**
* Watch a circuit breaker
*
* @param {CircuitBreaker} cb - The circuit breaker on which we'll listen the 'interval' event.
*/
this.watch = function(cb) {
if (watched.indexOf(cb) > -1) {
return;
}
watched.push(cb);
var name = cb.getName();
if (!(name in intervals)) {
intervals[name] = [];
}
var listener = buildOnInterval(name);
listeners.push(listener);
cb.on(EVENT, listener);
};
/**
* Stop watching this circuit breaker
*
* @param {CircuitBreaker} cb
*/
this.unwatch = function(cb) {
var index = watched.indexOf(cb);
if (index > -1) {
watched.splice(index, 1);
var arr = listeners.splice(index, 1);
cb.removeListener(EVENT, arr[0]);
}
};
function buildOnInterval(cb) {
return function(interval) {
intervals[cb].push(interval);
emitIfNecessary();
};
}
function emitIfNecessary() {
for (var name in intervals) {
var cnt = intervals[name].length;
if (cnt > 1) {
doEmit();
return;
} else if (cnt === 0) {
return false;
}
}
doEmit();
}
function doEmit() {
var data = intervals;
intervals = {};
for (var name in data) {
intervals[name] = [];
}
/**
* Batch event. The keys of the object are the names of the circuit breakers.
* The values of the object are arrays of {@link CircuitBreaker#event:interval}.
*
* @event CBObserver#batch
* @type object
*/
self.emit('batch', data);
}
} | [
"function",
"CBObserver",
"(",
")",
"{",
"var",
"EVENT",
"=",
"'interval'",
",",
"watched",
"=",
"[",
"]",
",",
"listeners",
"=",
"[",
"]",
",",
"intervals",
"=",
"{",
"}",
",",
"self",
"=",
"this",
";",
"/**\n * Watch a circuit breaker\n *\n * @param {CircuitBreaker} cb - The circuit breaker on which we'll listen the 'interval' event.\n */",
"this",
".",
"watch",
"=",
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"watched",
".",
"indexOf",
"(",
"cb",
")",
">",
"-",
"1",
")",
"{",
"return",
";",
"}",
"watched",
".",
"push",
"(",
"cb",
")",
";",
"var",
"name",
"=",
"cb",
".",
"getName",
"(",
")",
";",
"if",
"(",
"!",
"(",
"name",
"in",
"intervals",
")",
")",
"{",
"intervals",
"[",
"name",
"]",
"=",
"[",
"]",
";",
"}",
"var",
"listener",
"=",
"buildOnInterval",
"(",
"name",
")",
";",
"listeners",
".",
"push",
"(",
"listener",
")",
";",
"cb",
".",
"on",
"(",
"EVENT",
",",
"listener",
")",
";",
"}",
";",
"/**\n * Stop watching this circuit breaker\n *\n * @param {CircuitBreaker} cb\n */",
"this",
".",
"unwatch",
"=",
"function",
"(",
"cb",
")",
"{",
"var",
"index",
"=",
"watched",
".",
"indexOf",
"(",
"cb",
")",
";",
"if",
"(",
"index",
">",
"-",
"1",
")",
"{",
"watched",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"var",
"arr",
"=",
"listeners",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"cb",
".",
"removeListener",
"(",
"EVENT",
",",
"arr",
"[",
"0",
"]",
")",
";",
"}",
"}",
";",
"function",
"buildOnInterval",
"(",
"cb",
")",
"{",
"return",
"function",
"(",
"interval",
")",
"{",
"intervals",
"[",
"cb",
"]",
".",
"push",
"(",
"interval",
")",
";",
"emitIfNecessary",
"(",
")",
";",
"}",
";",
"}",
"function",
"emitIfNecessary",
"(",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"intervals",
")",
"{",
"var",
"cnt",
"=",
"intervals",
"[",
"name",
"]",
".",
"length",
";",
"if",
"(",
"cnt",
">",
"1",
")",
"{",
"doEmit",
"(",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"cnt",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"}",
"doEmit",
"(",
")",
";",
"}",
"function",
"doEmit",
"(",
")",
"{",
"var",
"data",
"=",
"intervals",
";",
"intervals",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"name",
"in",
"data",
")",
"{",
"intervals",
"[",
"name",
"]",
"=",
"[",
"]",
";",
"}",
"/**\n * Batch event. The keys of the object are the names of the circuit breakers.\n * The values of the object are arrays of {@link CircuitBreaker#event:interval}.\n *\n * @event CBObserver#batch\n * @type object\n */",
"self",
".",
"emit",
"(",
"'batch'",
",",
"data",
")",
";",
"}",
"}"
]
| An observer that watches one or more circuit breakers. It will
group their 'interval' event by name, and emit a single 'batch'
event with their combined data.
@fires CBObserver#batch
@constructor | [
"An",
"observer",
"that",
"watches",
"one",
"or",
"more",
"circuit",
"breakers",
".",
"It",
"will",
"group",
"their",
"interval",
"event",
"by",
"name",
"and",
"emit",
"a",
"single",
"batch",
"event",
"with",
"their",
"combined",
"data",
"."
]
| cfc27daf6f6477c680c8225ba806751f1838b12b | https://github.com/pablolb/promise-circuitbreaker/blob/cfc27daf6f6477c680c8225ba806751f1838b12b/lib/observer.js#L14-L92 |
43,691 | emmetio/html-transform | lib/numbering.js | findRepeater | function findRepeater(node) {
while (node) {
if (node.repeat) {
return node.repeat;
}
node = node.parent;
}
} | javascript | function findRepeater(node) {
while (node) {
if (node.repeat) {
return node.repeat;
}
node = node.parent;
}
} | [
"function",
"findRepeater",
"(",
"node",
")",
"{",
"while",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"repeat",
")",
"{",
"return",
"node",
".",
"repeat",
";",
"}",
"node",
"=",
"node",
".",
"parent",
";",
"}",
"}"
]
| Returns repeater object for given node
@param {Node} node
@return {Object} | [
"Returns",
"repeater",
"object",
"for",
"given",
"node"
]
| 61774dba583f811f910f7b031743289b87cab98f | https://github.com/emmetio/html-transform/blob/61774dba583f811f910f7b031743289b87cab98f/lib/numbering.js#L50-L58 |
43,692 | emmetio/html-transform | lib/numbering.js | replaceNumbering | function replaceNumbering(str, value, count) {
// replace numbering in strings only: skip explicit wrappers that could
// contain unescaped numbering tokens
if (typeof str === 'string') {
const ranges = getNumberingRanges(str);
return replaceNumberingRanges(str, ranges, value, count);
}
return str;
} | javascript | function replaceNumbering(str, value, count) {
// replace numbering in strings only: skip explicit wrappers that could
// contain unescaped numbering tokens
if (typeof str === 'string') {
const ranges = getNumberingRanges(str);
return replaceNumberingRanges(str, ranges, value, count);
}
return str;
} | [
"function",
"replaceNumbering",
"(",
"str",
",",
"value",
",",
"count",
")",
"{",
"// replace numbering in strings only: skip explicit wrappers that could",
"// contain unescaped numbering tokens",
"if",
"(",
"typeof",
"str",
"===",
"'string'",
")",
"{",
"const",
"ranges",
"=",
"getNumberingRanges",
"(",
"str",
")",
";",
"return",
"replaceNumberingRanges",
"(",
"str",
",",
"ranges",
",",
"value",
",",
"count",
")",
";",
"}",
"return",
"str",
";",
"}"
]
| Replaces numbering in given string
@param {String} str
@param {Number} value
@return {String} | [
"Replaces",
"numbering",
"in",
"given",
"string"
]
| 61774dba583f811f910f7b031743289b87cab98f | https://github.com/emmetio/html-transform/blob/61774dba583f811f910f7b031743289b87cab98f/lib/numbering.js#L66-L75 |
43,693 | emmetio/html-transform | lib/numbering.js | unescapeString | function unescapeString(str) {
let i = 0, result = '';
const len = str.length;
while (i < len) {
const ch = str[i++];
result += (ch === '\\') ? (str[i++] || '') : ch;
}
return result;
} | javascript | function unescapeString(str) {
let i = 0, result = '';
const len = str.length;
while (i < len) {
const ch = str[i++];
result += (ch === '\\') ? (str[i++] || '') : ch;
}
return result;
} | [
"function",
"unescapeString",
"(",
"str",
")",
"{",
"let",
"i",
"=",
"0",
",",
"result",
"=",
"''",
";",
"const",
"len",
"=",
"str",
".",
"length",
";",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"const",
"ch",
"=",
"str",
"[",
"i",
"++",
"]",
";",
"result",
"+=",
"(",
"ch",
"===",
"'\\\\'",
")",
"?",
"(",
"str",
"[",
"i",
"++",
"]",
"||",
"''",
")",
":",
"ch",
";",
"}",
"return",
"result",
";",
"}"
]
| Unescapes characters, screened with `\`, in given string
@param {String} str
@return {String} | [
"Unescapes",
"characters",
"screened",
"with",
"\\",
"in",
"given",
"string"
]
| 61774dba583f811f910f7b031743289b87cab98f | https://github.com/emmetio/html-transform/blob/61774dba583f811f910f7b031743289b87cab98f/lib/numbering.js#L125-L135 |
43,694 | emmetio/html-transform | lib/repeater-content.js | insertContentIntoPlaceholder | function insertContentIntoPlaceholder(node, content) {
const state = {replaced: false};
node.value = replacePlaceholder(node.value, content, state);
node.attributes.forEach(attr => {
if (attr.value) {
node.setAttribute(attr.name, replacePlaceholder(attr.value, content, state));
}
});
return state.replaced;
} | javascript | function insertContentIntoPlaceholder(node, content) {
const state = {replaced: false};
node.value = replacePlaceholder(node.value, content, state);
node.attributes.forEach(attr => {
if (attr.value) {
node.setAttribute(attr.name, replacePlaceholder(attr.value, content, state));
}
});
return state.replaced;
} | [
"function",
"insertContentIntoPlaceholder",
"(",
"node",
",",
"content",
")",
"{",
"const",
"state",
"=",
"{",
"replaced",
":",
"false",
"}",
";",
"node",
".",
"value",
"=",
"replacePlaceholder",
"(",
"node",
".",
"value",
",",
"content",
",",
"state",
")",
";",
"node",
".",
"attributes",
".",
"forEach",
"(",
"attr",
"=>",
"{",
"if",
"(",
"attr",
".",
"value",
")",
"{",
"node",
".",
"setAttribute",
"(",
"attr",
".",
"name",
",",
"replacePlaceholder",
"(",
"attr",
".",
"value",
",",
"content",
",",
"state",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"state",
".",
"replaced",
";",
"}"
]
| Inserts given `content` into placeholders for given `node`. Placeholders
might be available in attribute values and node content
@param {Node} node
@param {String} content
@return {Boolean} Returns `true` if placeholders were found and replaced in node | [
"Inserts",
"given",
"content",
"into",
"placeholders",
"for",
"given",
"node",
".",
"Placeholders",
"might",
"be",
"available",
"in",
"attribute",
"values",
"and",
"node",
"content"
]
| 61774dba583f811f910f7b031743289b87cab98f | https://github.com/emmetio/html-transform/blob/61774dba583f811f910f7b031743289b87cab98f/lib/repeater-content.js#L118-L129 |
43,695 | emmetio/html-transform | lib/repeater-content.js | replacePlaceholder | function replacePlaceholder(str, value, _state) {
if (typeof str === 'string') {
const ranges = findUnescapedTokens(str, placeholder);
if (ranges.length) {
if (_state) {
_state.replaced = true;
}
str = replaceRanges(str, ranges, value);
}
}
return str;
} | javascript | function replacePlaceholder(str, value, _state) {
if (typeof str === 'string') {
const ranges = findUnescapedTokens(str, placeholder);
if (ranges.length) {
if (_state) {
_state.replaced = true;
}
str = replaceRanges(str, ranges, value);
}
}
return str;
} | [
"function",
"replacePlaceholder",
"(",
"str",
",",
"value",
",",
"_state",
")",
"{",
"if",
"(",
"typeof",
"str",
"===",
"'string'",
")",
"{",
"const",
"ranges",
"=",
"findUnescapedTokens",
"(",
"str",
",",
"placeholder",
")",
";",
"if",
"(",
"ranges",
".",
"length",
")",
"{",
"if",
"(",
"_state",
")",
"{",
"_state",
".",
"replaced",
"=",
"true",
";",
"}",
"str",
"=",
"replaceRanges",
"(",
"str",
",",
"ranges",
",",
"value",
")",
";",
"}",
"}",
"return",
"str",
";",
"}"
]
| Replaces all placeholder occurances in given `str` with `value`
@param {String} str
@param {String} value
@param {Object} [_state] If provided, set `replaced` property of given
object to `true` if placeholder was found and replaced
@return {String} | [
"Replaces",
"all",
"placeholder",
"occurances",
"in",
"given",
"str",
"with",
"value"
]
| 61774dba583f811f910f7b031743289b87cab98f | https://github.com/emmetio/html-transform/blob/61774dba583f811f910f7b031743289b87cab98f/lib/repeater-content.js#L139-L152 |
43,696 | emmetio/html-transform | lib/repeater-content.js | setNodeContent | function setNodeContent(node, content) {
// find caret position and replace it with content, if possible
if (node.value) {
const ranges = findUnescapedTokens(node.value, caret);
if (ranges.length) {
node.value = replaceRanges(node.value, ranges, content);
return;
}
}
if ((node.name && node.name.toLowerCase() === 'a') || node.hasAttribute('href')) {
// special case: inserting content into `<a>` tag
if (reUrl.test(content)) {
node.setAttribute('href', (reProto.test(content) ? '' : 'http://') + content);
} else if (reEmail.test(content)) {
node.setAttribute('href', 'mailto:' + content);
}
}
node.value = content;
} | javascript | function setNodeContent(node, content) {
// find caret position and replace it with content, if possible
if (node.value) {
const ranges = findUnescapedTokens(node.value, caret);
if (ranges.length) {
node.value = replaceRanges(node.value, ranges, content);
return;
}
}
if ((node.name && node.name.toLowerCase() === 'a') || node.hasAttribute('href')) {
// special case: inserting content into `<a>` tag
if (reUrl.test(content)) {
node.setAttribute('href', (reProto.test(content) ? '' : 'http://') + content);
} else if (reEmail.test(content)) {
node.setAttribute('href', 'mailto:' + content);
}
}
node.value = content;
} | [
"function",
"setNodeContent",
"(",
"node",
",",
"content",
")",
"{",
"// find caret position and replace it with content, if possible",
"if",
"(",
"node",
".",
"value",
")",
"{",
"const",
"ranges",
"=",
"findUnescapedTokens",
"(",
"node",
".",
"value",
",",
"caret",
")",
";",
"if",
"(",
"ranges",
".",
"length",
")",
"{",
"node",
".",
"value",
"=",
"replaceRanges",
"(",
"node",
".",
"value",
",",
"ranges",
",",
"content",
")",
";",
"return",
";",
"}",
"}",
"if",
"(",
"(",
"node",
".",
"name",
"&&",
"node",
".",
"name",
".",
"toLowerCase",
"(",
")",
"===",
"'a'",
")",
"||",
"node",
".",
"hasAttribute",
"(",
"'href'",
")",
")",
"{",
"// special case: inserting content into `<a>` tag",
"if",
"(",
"reUrl",
".",
"test",
"(",
"content",
")",
")",
"{",
"node",
".",
"setAttribute",
"(",
"'href'",
",",
"(",
"reProto",
".",
"test",
"(",
"content",
")",
"?",
"''",
":",
"'http://'",
")",
"+",
"content",
")",
";",
"}",
"else",
"if",
"(",
"reEmail",
".",
"test",
"(",
"content",
")",
")",
"{",
"node",
".",
"setAttribute",
"(",
"'href'",
",",
"'mailto:'",
"+",
"content",
")",
";",
"}",
"}",
"node",
".",
"value",
"=",
"content",
";",
"}"
]
| Updates content of given node
@param {Node} node
@param {String} content | [
"Updates",
"content",
"of",
"given",
"node"
]
| 61774dba583f811f910f7b031743289b87cab98f | https://github.com/emmetio/html-transform/blob/61774dba583f811f910f7b031743289b87cab98f/lib/repeater-content.js#L172-L192 |
43,697 | mikcsabee/npm-submodule-webpack-plugin | src/plugin.js | NpmSubmodulePlugin | function NpmSubmodulePlugin(options) {
// initialize instance variables
this.commands = options.commands ? options.commands : [];
this.autoInstall = options.autoInstall ? options.autoInstall : false;
this.logger = options.logger ? options.logger : console.log;
this.path = 'node_modules' + path.sep + options.module;
this.spawnSyncOptions = {
stdio: ['ignore', 'pipe', 'inherit'],
cwd: this.path
};
} | javascript | function NpmSubmodulePlugin(options) {
// initialize instance variables
this.commands = options.commands ? options.commands : [];
this.autoInstall = options.autoInstall ? options.autoInstall : false;
this.logger = options.logger ? options.logger : console.log;
this.path = 'node_modules' + path.sep + options.module;
this.spawnSyncOptions = {
stdio: ['ignore', 'pipe', 'inherit'],
cwd: this.path
};
} | [
"function",
"NpmSubmodulePlugin",
"(",
"options",
")",
"{",
"// initialize instance variables",
"this",
".",
"commands",
"=",
"options",
".",
"commands",
"?",
"options",
".",
"commands",
":",
"[",
"]",
";",
"this",
".",
"autoInstall",
"=",
"options",
".",
"autoInstall",
"?",
"options",
".",
"autoInstall",
":",
"false",
";",
"this",
".",
"logger",
"=",
"options",
".",
"logger",
"?",
"options",
".",
"logger",
":",
"console",
".",
"log",
";",
"this",
".",
"path",
"=",
"'node_modules'",
"+",
"path",
".",
"sep",
"+",
"options",
".",
"module",
";",
"this",
".",
"spawnSyncOptions",
"=",
"{",
"stdio",
":",
"[",
"'ignore'",
",",
"'pipe'",
",",
"'inherit'",
"]",
",",
"cwd",
":",
"this",
".",
"path",
"}",
";",
"}"
]
| Logger to caputer the command output.
@callback Logger
@param {string} message - message to log.
The mandatory named JavaScript function which represents a Webpack plugin.
@example
new NpmSubmodulePlugin({
module: 'isObject',
autoInstall: false,
commands: [
'install',
'install --save react'
],
logger: console.log
});
@param {Object} options - The plugin options
@param {string} options.module - The node module to operate on.
@param {boolean} [options.autoInstall=false] - Adds `npm install` to the commands if the `node_modules` folder is not exists.
@param {string[]} [options.commands=[]] - The commands to execute.
@param {Logger} [options.logger=console.log] - The logger.
@class | [
"Logger",
"to",
"caputer",
"the",
"command",
"output",
"."
]
| 1eee09d129b480e3aa1fcf5f786cee9a13464181 | https://github.com/mikcsabee/npm-submodule-webpack-plugin/blob/1eee09d129b480e3aa1fcf5f786cee9a13464181/src/plugin.js#L56-L66 |
43,698 | simonguo/hbook | lib/utils/git.js | parseGitUrl | function parseGitUrl(giturl) {
var ref, uri, fileParts, filepath;
if (!checkGitUrl(giturl)) return null;
giturl = giturl.slice(GIT_PREFIX.length);
uri = new URI(giturl);
ref = uri.fragment() || 'master';
uri.fragment(null);
// Extract file inside the repo (after the .git)
fileParts =uri.path().split('.git');
filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
if (filepath[0] == '/') filepath = filepath.slice(1);
// Recreate pathname without the real filename
uri.path(_.first(fileParts)+'.git');
return {
host: uri.toString(),
ref: ref || 'master',
filepath: filepath
};
} | javascript | function parseGitUrl(giturl) {
var ref, uri, fileParts, filepath;
if (!checkGitUrl(giturl)) return null;
giturl = giturl.slice(GIT_PREFIX.length);
uri = new URI(giturl);
ref = uri.fragment() || 'master';
uri.fragment(null);
// Extract file inside the repo (after the .git)
fileParts =uri.path().split('.git');
filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
if (filepath[0] == '/') filepath = filepath.slice(1);
// Recreate pathname without the real filename
uri.path(_.first(fileParts)+'.git');
return {
host: uri.toString(),
ref: ref || 'master',
filepath: filepath
};
} | [
"function",
"parseGitUrl",
"(",
"giturl",
")",
"{",
"var",
"ref",
",",
"uri",
",",
"fileParts",
",",
"filepath",
";",
"if",
"(",
"!",
"checkGitUrl",
"(",
"giturl",
")",
")",
"return",
"null",
";",
"giturl",
"=",
"giturl",
".",
"slice",
"(",
"GIT_PREFIX",
".",
"length",
")",
";",
"uri",
"=",
"new",
"URI",
"(",
"giturl",
")",
";",
"ref",
"=",
"uri",
".",
"fragment",
"(",
")",
"||",
"'master'",
";",
"uri",
".",
"fragment",
"(",
"null",
")",
";",
"// Extract file inside the repo (after the .git)",
"fileParts",
"=",
"uri",
".",
"path",
"(",
")",
".",
"split",
"(",
"'.git'",
")",
";",
"filepath",
"=",
"fileParts",
".",
"length",
">",
"1",
"?",
"fileParts",
".",
"slice",
"(",
"1",
")",
".",
"join",
"(",
"'.git'",
")",
":",
"''",
";",
"if",
"(",
"filepath",
"[",
"0",
"]",
"==",
"'/'",
")",
"filepath",
"=",
"filepath",
".",
"slice",
"(",
"1",
")",
";",
"// Recreate pathname without the real filename",
"uri",
".",
"path",
"(",
"_",
".",
"first",
"(",
"fileParts",
")",
"+",
"'.git'",
")",
";",
"return",
"{",
"host",
":",
"uri",
".",
"toString",
"(",
")",
",",
"ref",
":",
"ref",
"||",
"'master'",
",",
"filepath",
":",
"filepath",
"}",
";",
"}"
]
| Parse and extract infos | [
"Parse",
"and",
"extract",
"infos"
]
| 5ea071130cc418fccd97a3e7e9a285c1d756b80b | https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/git.js#L26-L49 |
43,699 | simonguo/hbook | lib/utils/git.js | cloneGitRepo | function cloneGitRepo(host, ref) {
var isBranch = false;
ref = ref || 'master';
if (!validateSha(ref)) isBranch = true;
return Q()
// Create temporary folder to store git repos
.then(function() {
if (GIT_TMP) return;
return fs.tmp.dir()
.then(function(_tmp) {
GIT_TMP = _tmp;
});
})
// Return or clone the git repo
.then(function() {
// Unique ID for repo/ref combinaison
var repoId = crc.crc32(host+'#'+ref).toString(16);
// Absolute path to the folder
var repoPath = path.resolve(GIT_TMP, repoId);
return fs.exists(repoPath)
.then(function(doExists) {
if (doExists) return;
// Clone repo
return exec('git clone '+host+' '+repoPath)
.then(function() {
return exec('git checkout '+ref, { cwd: repoPath });
});
})
.thenResolve(repoPath);
});
} | javascript | function cloneGitRepo(host, ref) {
var isBranch = false;
ref = ref || 'master';
if (!validateSha(ref)) isBranch = true;
return Q()
// Create temporary folder to store git repos
.then(function() {
if (GIT_TMP) return;
return fs.tmp.dir()
.then(function(_tmp) {
GIT_TMP = _tmp;
});
})
// Return or clone the git repo
.then(function() {
// Unique ID for repo/ref combinaison
var repoId = crc.crc32(host+'#'+ref).toString(16);
// Absolute path to the folder
var repoPath = path.resolve(GIT_TMP, repoId);
return fs.exists(repoPath)
.then(function(doExists) {
if (doExists) return;
// Clone repo
return exec('git clone '+host+' '+repoPath)
.then(function() {
return exec('git checkout '+ref, { cwd: repoPath });
});
})
.thenResolve(repoPath);
});
} | [
"function",
"cloneGitRepo",
"(",
"host",
",",
"ref",
")",
"{",
"var",
"isBranch",
"=",
"false",
";",
"ref",
"=",
"ref",
"||",
"'master'",
";",
"if",
"(",
"!",
"validateSha",
"(",
"ref",
")",
")",
"isBranch",
"=",
"true",
";",
"return",
"Q",
"(",
")",
"// Create temporary folder to store git repos",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"GIT_TMP",
")",
"return",
";",
"return",
"fs",
".",
"tmp",
".",
"dir",
"(",
")",
".",
"then",
"(",
"function",
"(",
"_tmp",
")",
"{",
"GIT_TMP",
"=",
"_tmp",
";",
"}",
")",
";",
"}",
")",
"// Return or clone the git repo",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Unique ID for repo/ref combinaison",
"var",
"repoId",
"=",
"crc",
".",
"crc32",
"(",
"host",
"+",
"'#'",
"+",
"ref",
")",
".",
"toString",
"(",
"16",
")",
";",
"// Absolute path to the folder",
"var",
"repoPath",
"=",
"path",
".",
"resolve",
"(",
"GIT_TMP",
",",
"repoId",
")",
";",
"return",
"fs",
".",
"exists",
"(",
"repoPath",
")",
".",
"then",
"(",
"function",
"(",
"doExists",
")",
"{",
"if",
"(",
"doExists",
")",
"return",
";",
"// Clone repo",
"return",
"exec",
"(",
"'git clone '",
"+",
"host",
"+",
"' '",
"+",
"repoPath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"exec",
"(",
"'git checkout '",
"+",
"ref",
",",
"{",
"cwd",
":",
"repoPath",
"}",
")",
";",
"}",
")",
";",
"}",
")",
".",
"thenResolve",
"(",
"repoPath",
")",
";",
"}",
")",
";",
"}"
]
| Clone a git repo from a specific ref | [
"Clone",
"a",
"git",
"repo",
"from",
"a",
"specific",
"ref"
]
| 5ea071130cc418fccd97a3e7e9a285c1d756b80b | https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/git.js#L52-L89 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.