_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7800 | __expand | train | function __expand(bytes) {
// Resize buffer if more space needed
if (length+bytes >= buffer.length) {
var new_buffer = new Uint8Array((length+bytes)*2);
new_buffer.set(buffer);
buffer = new_buffer;
}
length += bytes;
} | javascript | {
"resource": ""
} |
q7801 | __append_utf8 | train | function __append_utf8(codepoint) {
var mask;
var bytes;
// 1 byte
if (codepoint <= 0x7F) {
mask = 0x00;
bytes = 1;
}
// 2 byte
else if (codepoint <= 0x7FF) {
mask = 0xC0;
bytes = 2;
}
// 3 byte
else if (codepoint <= 0xFFFF) {
mask = 0xE0;
bytes = 3;
}
// 4 byte
else if (codepoint <= 0x1FFFFF) {
mask = 0xF0;
bytes = 4;
}
// If invalid codepoint, append replacement character
else {
__append_utf8(0xFFFD);
return;
}
// Offset buffer by size
__expand(bytes);
var offset = length - 1;
// Add trailing bytes, if any
for (var i=1; i<bytes; i++) {
buffer[offset--] = 0x80 | (codepoint & 0x3F);
codepoint >>= 6;
}
// Set initial byte
buffer[offset] = mask | codepoint;
} | javascript | {
"resource": ""
} |
q7802 | __encode_utf8 | train | function __encode_utf8(text) {
// Fill buffer with UTF-8
for (var i=0; i<text.length; i++) {
var codepoint = text.charCodeAt(i);
__append_utf8(codepoint);
}
// Flush buffer
if (length > 0) {
var out_buffer = buffer.subarray(0, length);
length = 0;
return out_buffer;
}
} | javascript | {
"resource": ""
} |
q7803 | set | train | function set(prefix, value) {
for (const key of keys(value)) {
const name = prefix ? `${prefix}[${key}]` : key
const field = value[key]
if (isArray(field) || isPlainObject(field)) {
set(name, field)
} else {
if (options.strict && (isBoolean(field) && field === false)) {
continue
}
fd[method](name, field)
}
}
} | javascript | {
"resource": ""
} |
q7804 | getValueAt | train | function getValueAt(audioData, t) {
// Convert [0, 1] range to [0, audioData.length - 1]
var index = (audioData.length - 1) * t;
// Determine the start and end points for the summation used by the
// Lanczos interpolation algorithm (see: https://en.wikipedia.org/wiki/Lanczos_resampling)
var start = Math.floor(index) - LANCZOS_WINDOW_SIZE + 1;
var end = Math.floor(index) + LANCZOS_WINDOW_SIZE;
// Calculate the value of the Lanczos interpolation function for the
// required range
var sum = 0;
for (var i = start; i <= end; i++) {
sum += (audioData[i] || 0) * lanczos(index - i, LANCZOS_WINDOW_SIZE);
}
return sum;
} | javascript | {
"resource": ""
} |
q7805 | toSampleArray | train | function toSampleArray(audioBuffer) {
// Track overall amount of data read
var inSamples = audioBuffer.length;
readSamples += inSamples;
// Calculate the total number of samples that should be written as of
// the audio data just received and adjust the size of the output
// packet accordingly
var expectedWrittenSamples = Math.round(readSamples * format.rate / audioBuffer.sampleRate);
var outSamples = expectedWrittenSamples - writtenSamples;
// Update number of samples written
writtenSamples += outSamples;
// Get array for raw PCM storage
var data = new SampleArray(outSamples * format.channels);
// Convert each channel
for (var channel = 0; channel < format.channels; channel++) {
var audioData = audioBuffer.getChannelData(channel);
// Fill array with data from audio buffer channel
var offset = channel;
for (var i = 0; i < outSamples; i++) {
data[offset] = interpolateSample(audioData, i / (outSamples - 1)) * maxSampleValue;
offset += format.channels;
}
}
return data;
} | javascript | {
"resource": ""
} |
q7806 | beginAudioCapture | train | function beginAudioCapture() {
// Attempt to retrieve an audio input stream from the browser
navigator.mediaDevices.getUserMedia({ 'audio' : true }, function streamReceived(stream) {
// Create processing node which receives appropriately-sized audio buffers
processor = context.createScriptProcessor(BUFFER_SIZE, format.channels, format.channels);
processor.connect(context.destination);
// Send blobs when audio buffers are received
processor.onaudioprocess = function processAudio(e) {
writer.sendData(toSampleArray(e.inputBuffer).buffer);
};
// Connect processing node to user's audio input source
source = context.createMediaStreamSource(stream);
source.connect(processor);
// Save stream for later cleanup
mediaStream = stream;
}, function streamDenied() {
// Simply end stream if audio access is not allowed
writer.sendEnd();
// Notify of closure
if (recorder.onerror)
recorder.onerror();
});
} | javascript | {
"resource": ""
} |
q7807 | stopAudioCapture | train | function stopAudioCapture() {
// Disconnect media source node from script processor
if (source)
source.disconnect();
// Disconnect associated script processor node
if (processor)
processor.disconnect();
// Stop capture
if (mediaStream) {
var tracks = mediaStream.getTracks();
for (var i = 0; i < tracks.length; i++)
tracks[i].stop();
}
// Remove references to now-unneeded components
processor = null;
source = null;
mediaStream = null;
// End stream
writer.sendEnd();
} | javascript | {
"resource": ""
} |
q7808 | __decode_utf8 | train | function __decode_utf8(buffer) {
var text = "";
var bytes = new Uint8Array(buffer);
for (var i=0; i<bytes.length; i++) {
// Get current byte
var value = bytes[i];
// Start new codepoint if nothing yet read
if (bytes_remaining === 0) {
// 1 byte (0xxxxxxx)
if ((value | 0x7F) === 0x7F)
text += String.fromCharCode(value);
// 2 byte (110xxxxx)
else if ((value | 0x1F) === 0xDF) {
codepoint = value & 0x1F;
bytes_remaining = 1;
}
// 3 byte (1110xxxx)
else if ((value | 0x0F )=== 0xEF) {
codepoint = value & 0x0F;
bytes_remaining = 2;
}
// 4 byte (11110xxx)
else if ((value | 0x07) === 0xF7) {
codepoint = value & 0x07;
bytes_remaining = 3;
}
// Invalid byte
else
text += "\uFFFD";
}
// Continue existing codepoint (10xxxxxx)
else if ((value | 0x3F) === 0xBF) {
codepoint = (codepoint << 6) | (value & 0x3F);
bytes_remaining--;
// Write codepoint if finished
if (bytes_remaining === 0)
text += String.fromCharCode(codepoint);
}
// Invalid byte
else {
bytes_remaining = 0;
text += "\uFFFD";
}
}
return text;
} | javascript | {
"resource": ""
} |
q7809 | extractMediaQuery | train | function extractMediaQuery(props){
var mediaValue = props.length && props[0];
if(Object.keys(fucss.media).indexOf(mediaValue) !== -1){
return props.shift();
}
} | javascript | {
"resource": ""
} |
q7810 | include | train | function include(ckey, file) {
var
match = file.match(INCNAME)
file = match && match[1]
if (file) {
var ch = file[0]
if ((ch === '"' || ch === "'") && ch === file.slice(-1))
file = file.slice(1, -1).trim()
}
if (file) {
result.insert = file
result.once = !!ckey[8]
}
else
emitError('Expected filename for #' + ckey + ' in @')
} | javascript | {
"resource": ""
} |
q7811 | normalize | train | function normalize(key, expr) {
if (key.slice(0, 4) !== 'incl') {
expr = expr.replace(/[/\*]\/.*/, '').trim()
// all keywords must have an expression, except `#else/#endif`
if (!expr && key !== 'else' && key !== 'endif') {
emitError('Expected expression for #' + key + ' in @')
return false
}
}
return expr
} | javascript | {
"resource": ""
} |
q7812 | checkInBlock | train | function checkInBlock(mask) {
var block = cc.block[last]
if (block && block === (block & mask))
return true
emitError('Unexpected #' + key + ' in @')
return false
} | javascript | {
"resource": ""
} |
q7813 | _repeat | train | function _repeat (source, times) {
var result = "";
for (var i = 0; i < times; i++) {
result += source;
}
return result;
} | javascript | {
"resource": ""
} |
q7814 | unsignEncryptedContent | train | function unsignEncryptedContent(content) {
const newIndex = content.indexOf(SIGNING_KEY);
const oldIndex = content.indexOf(SIGNING_KEY_OLD);
if (newIndex === -1 && oldIndex === -1) {
throw new Error("Invalid credentials content (unknown signature)");
}
return newIndex >= 0
? content.substr(SIGNING_KEY.length)
: content.substr(SIGNING_KEY_OLD.length);
} | javascript | {
"resource": ""
} |
q7815 | compileCss | train | function compileCss(src, dest) {
gulp
.src(src)
.pipe(plumber(config.plumberOptions))
.pipe(gulpif(!config.production, sourcemaps.init()))
.pipe(sass({
outputStyle: config.production ? 'compressed' : 'expanded',
precision: 5
}))
.pipe(postcss(processors))
.pipe(gulpif(config.production, rename({
suffix: '.min',
extname: '.css'
})))
.pipe(gulpif(!config.production, sourcemaps.write()))
.pipe(gulp.dest(dest));
} | javascript | {
"resource": ""
} |
q7816 | setEnabledStateOfLed | train | function setEnabledStateOfLed(callback) {
var index = 0;
var setEnabledStateOfLedInterval = setInterval(function() {
if (index <= 5) {
dothat.barGraph.setEnabledStateOfLed(index, false);
index++;
} else {
clearInterval(setEnabledStateOfLedInterval);
if (callback) {
callback();
}
}
}, 500);
} | javascript | {
"resource": ""
} |
q7817 | _setIn | train | function _setIn (source, key, value) {
var result = {};
for (var prop in source) {
result[prop] = source[prop];
}
result[key] = value;
return result;
} | javascript | {
"resource": ""
} |
q7818 | getInterceptedXHR | train | function getInterceptedXHR(req) {
var requestPath = req.requestPath;
var interceptedXHRs = interceptXHRMap[requestPath];
var interceptedXHRsObj = {};
var counter = 1;
if (interceptedXHRs != undefined) {
for (var i = 0; i < interceptedXHRs.length; i++) {
interceptedXHRsObj["xhr_" + counter] = interceptedXHRs[i];
counter++;
}
}
return interceptedXHRsObj;
} | javascript | {
"resource": ""
} |
q7819 | isFakeRespond | train | function isFakeRespond(req) {
var temp = req.url.toString();
var uniqueID = md5(JSON.stringify(req.body));
if (temp.indexOf("?") >= 0)
req.url = reparsePath(temp);
if (req.method === 'POST' && ((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) &&
((!((req.url + uniqueID) in mockReqRespMap)) && (mockReqRespMap[req.url + uniqueID] === undefined))) {
mockReqRespMap[req.url + uniqueID] = mockReqRespMap[req.url];
delete mockReqRespMap[req.url];
console.log('This is POST call, but we are mocking it as a GET method, please use setMockPOSTRespond function to mock the data!!');
}
if (((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) ||
((req._parsedUrl.pathname in mockReqRespMap) && (mockReqRespMap[req._parsedUrl.pathname] !== undefined)) ||
(((req.url + uniqueID) in mockReqRespMap) && (mockReqRespMap[req.url + uniqueID] !== undefined))) {
return true;
} else {
return false;
}
} | javascript | {
"resource": ""
} |
q7820 | isInterceptXHR | train | function isInterceptXHR(req) {
if (((req.url in interceptXHRMap) && (interceptXHRMap[req.url] !== undefined)) ||
((req._parsedUrl.pathname in interceptXHRMap) && (interceptXHRMap[req._parsedUrl.pathname] !== undefined))) {
return true;
} else {
return false;
}
} | javascript | {
"resource": ""
} |
q7821 | reparsePath | train | function reparsePath(oldpath) {
if (oldpath.indexOf("?") >= 0) {
var vars = oldpath.split("?")[1].split("&");
var result = oldpath.split("?")[0] + '?';
var firstFlag = 0;
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (ignoredParams.search(pair[0]) < 0) {
if (firstFlag === 0) {
result = result + pair[0] + '=' + pair[1];
firstFlag = 1;
}
else {
result = result + '&' + pair[0] + '=' + pair[1];
}
}
}
return result;
}
else {
return oldpath;
}
} | javascript | {
"resource": ""
} |
q7822 | modelMethod | train | function modelMethod(model, method, data, done) {
model[method](data).then(function(results) {
done(null, results);
})
.catch(function(error) {
// Try again on timeout
if (error.message == "connect ETIMEDOUT") {
modelMethod(model, method, data, done);
return;
}
done(error);
});
} | javascript | {
"resource": ""
} |
q7823 | runQuery | train | function runQuery(connection, query, options, done) {
options = _.isObject(options) ? options :
connection.QueryTypes[options] ? { type: connection.QueryTypes[options] } : {};
connection.query(query, options)
.then(function(results) {
done(null, results);
})
.catch(function(error) {
if (error) {
output.error("Query error. SQL has been written to .tables.debug. Use a smaller batchSize to more easily find the issue.");
output.error(error);
fs.writeFileSync(".tables.debug", query);
}
done(error);
});
} | javascript | {
"resource": ""
} |
q7824 | mysqlBulkUpsert | train | function mysqlBulkUpsert(model, data) {
var mysql = require("mysql");
var queries = ["SET AUTOCOMMIT = 0"];
// Transform data
_.each(data, function(d) {
var query = "REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES (?)";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
query = mysql.format(query, [ _.values(d) ]);
queries.push(query);
});
// Create final output and format
queries.push("COMMIT");
queries.push("SET AUTOCOMMIT = 1");
return queries.join("; ");
} | javascript | {
"resource": ""
} |
q7825 | sqliteBulkUpsert | train | function sqliteBulkUpsert(model, data) {
var queries = ["BEGIN"];
var values = [];
// Transform data
_.each(data, function(d) {
var query = "INSERT OR REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
// Put in ?'s
query = query.replace("[[VALUES]]", _.map(d, function(v) {
return "?";
}).join(", "));
// Get values
values = values.concat(_.values(d));
queries.push(query);
});
// Create final output and format
queries.push("COMMIT");
return {
query: queries.join("; "),
replacements: values
};
} | javascript | {
"resource": ""
} |
q7826 | pgsqlBulkUpsert | train | function pgsqlBulkUpsert(model, data) {
var queries = [];
// Transform data
_.each(data, function(d) {
// TODO: Postgres does not have easy UPSERT syntax, the ON CONFLICT UPDATE requires specific columns
var query = "INSERT INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
query = query.replace("[[VALUES]]", _.map(d, function(v) {
return sequelizeSS.escape(v, undefined, "postgres");
}).join(", "));
queries.push(query);
});
// Create final output and format
return queries.join("; ");
} | javascript | {
"resource": ""
} |
q7827 | vacuum | train | function vacuum(connection, done) {
var n = connection.connectionManager.dialectName;
var query;
// Make query based on dialiect
if (n === "mysql" || n === "mariadb" || n === "mysqli") {
query = "SELECT 1";
}
else if (n === "sqlite") {
query = "VACUUM";
}
else if (n === "pgsql" || n === "postgres") {
query = "VACUUM";
}
runQuery(connection, query, { type: connection.QueryTypes.UPSERT, raw: true }, done);
} | javascript | {
"resource": ""
} |
q7828 | getUriMappers | train | function getUriMappers (serviceLocator) {
var routeDefinitions;
try {
routeDefinitions = serviceLocator.resolveAll('routeDefinition');
} catch (e) {
routeDefinitions = [];
}
return routeDefinitions
.map(route => {
var mapper = routeHelper.compileRoute(route.expression);
return {
expression: mapper.expression,
map: route.map || noop,
argsMap: uri => {
var args = mapper.map(uri);
Object.assign(args, route.args);
return args;
}
};
});
} | javascript | {
"resource": ""
} |
q7829 | runPostMapping | train | function runPostMapping (args, uriMappers, location) {
uriMappers.some(mapper => {
if (mapper.expression.test(location.path)) {
args = mapper.map(args);
return true;
}
return false;
});
return args;
} | javascript | {
"resource": ""
} |
q7830 | dotNotation | train | function dotNotation(path) {
if (path instanceof Array) {
return {
path: path,
str: path.join('.')
}
}
if (typeof path !== 'string') {
return;
}
return {
path: path.split('\.'),
str: path
}
} | javascript | {
"resource": ""
} |
q7831 | getPropertyValue | train | function getPropertyValue(obj, path) {
if (path.length === 0 || obj === undefined) {
return undefined;
}
var notation = dotNotation(path);
if (!notation) {
return;
}
path = notation.path;
for (var i = 0; i < path.length; i++) {
obj = obj[path[i]];
if (obj === undefined) {
return undefined;
}
}
return obj;
} | javascript | {
"resource": ""
} |
q7832 | setHiddenProperty | train | function setHiddenProperty(obj, key, value) {
Object.defineProperty(obj, key, {
enumerable: false,
value: value
});
return value;
} | javascript | {
"resource": ""
} |
q7833 | tryToCoverWindow | train | function tryToCoverWindow(code) {
if (typeof window === "object") {
var variables = Object.getOwnPropertyNames(window);
if (!window.hasOwnProperty('window')) {
variables.push('window');
}
var stubDeclarations = '';
variables.forEach(function(name) {
// If the name really can be the name of variable.
if (lodash.isString(name)) {
var stub = 'var ' + name + '; \n';
stubDeclarations = stubDeclarations + stub;
}
});
code = stubDeclarations + code;
}
return code;
} | javascript | {
"resource": ""
} |
q7834 | createCORSRequest | train | function createCORSRequest (method, url) {
var xhr;
xhr = new window.XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (window.XDomainRequest) {
// XDomainRequest for IE.
if (_allowInsecureSubmissions) {
// remove 'https:' and use relative protocol
// this allows IE8 to post messages when running
// on http
url = url.slice(6);
}
xhr = new window.XDomainRequest();
xhr.open(method, url);
}
xhr.timeout = 10000;
return xhr;
} | javascript | {
"resource": ""
} |
q7835 | makePostCorsRequest | train | function makePostCorsRequest (url, data) {
var xhr = createCORSRequest('POST', url, data);
if (typeof _beforeXHRCallback === 'function') {
_beforeXHRCallback(xhr);
}
if ('withCredentials' in xhr) {
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 202) {
sendSavedErrors();
} else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400 && xhr.status !== 429) {
offlineSave(url, data);
}
};
xhr.onload = function() {
_private.log('posted to Raygun');
callAfterSend(this);
};
} else if (window.XDomainRequest) {
xhr.ontimeout = function() {
if (_enableOfflineSave) {
_private.log('Raygun: saved locally');
offlineSave(url, data);
}
};
xhr.onload = function() {
_private.log('posted to Raygun');
sendSavedErrors();
callAfterSend(this);
};
}
xhr.onerror = function() {
_private.log('failed to post to Raygun');
callAfterSend(this);
};
if (!xhr) {
_private.log('CORS not supported');
return;
}
xhr.send(data);
} | javascript | {
"resource": ""
} |
q7836 | createUriPathMapper | train | function createUriPathMapper (expression, parameters) {
return (uriPath, args) => {
var matches = uriPath.match(expression);
if (!matches || matches.length < 2) {
return args;
}
// start with second match because first match is always
// the whole URI path
matches = matches.splice(1);
parameters.forEach((parameter, index) => {
var value = matches[index];
try {
value = decodeURIComponent(value);
} catch (e) {
// nothing to do
}
args[parameter.name] = value;
});
};
} | javascript | {
"resource": ""
} |
q7837 | createUriQueryMapper | train | function createUriQueryMapper (query) {
var parameters = extractQueryParameters(query);
return (queryValues, args) => {
queryValues = queryValues || Object.create(null);
Object.keys(queryValues)
.forEach(queryKey => {
var parameter = parameters[queryKey];
if (!parameter) {
return;
}
var value = util.isArray(queryValues[queryKey]) ?
queryValues[queryKey]
.map(parameter.map)
.filter(value => value !== null) :
parameter.map(queryValues[queryKey]);
if (value === null) {
return;
}
args[parameter.name] = value;
});
};
} | javascript | {
"resource": ""
} |
q7838 | createUriQueryValueMapper | train | function createUriQueryValueMapper (expression) {
return value => {
value = value.toString();
var matches = value.match(expression);
if (!matches || matches.length === 0) {
return null;
}
// the value is the second item, the first is a whole string
var mappedValue = matches[matches.length - 1];
try {
mappedValue = decodeURIComponent(mappedValue);
} catch (e) {
// nothing to do
}
return mappedValue;
};
} | javascript | {
"resource": ""
} |
q7839 | getParameterDescriptor | train | function getParameterDescriptor (parameter) {
var parts = parameter.split(SLASHED_BRACKETS_REG_EXP);
return {
name: parts[0].trim().substring(1)
};
} | javascript | {
"resource": ""
} |
q7840 | extractQueryParameters | train | function extractQueryParameters (query) {
return Object.keys(query.values)
.reduce((queryParameters, name) => {
// arrays in routing definitions are not supported
if (util.isArray(query.values[name])) {
return queryParameters;
}
// escape regular expression characters
var escaped = query.values[name].replace(EXPRESSION_ESCAPE_REG_EXP, '\\$&');
// get all occurrences of routing parameters in URI path
var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_QUERY_REPLACEMENT_REG_EXP_SOURCE) + '$';
var queryParameterMatches = escaped.match(PARAMETER_REG_EXP);
if (!queryParameterMatches ||
queryParameterMatches.length === 0) {
return;
}
var parameter = getParameterDescriptor(queryParameterMatches[queryParameterMatches.length - 1]);
var expression = new RegExp(regExpSource, 'i');
parameter.map = createUriQueryValueMapper(expression);
queryParameters[name] = parameter;
return queryParameters;
}, Object.create(null));
} | javascript | {
"resource": ""
} |
q7841 | compileStringRouteExpression | train | function compileStringRouteExpression (routeExpression) {
var routeUri = new URI(routeExpression);
routeUri.path = module.exports.removeEndSlash(routeUri.path);
if (!routeUri) {
return null;
}
// escape regular expression characters
var escaped = routeUri.path.replace(
EXPRESSION_ESCAPE_REG_EXP, '\\$&'
);
// get all occurrences of routing parameters in URI path
var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_PATH_REPLACEMENT_REG_EXP_SOURCE) + '$';
var expression = new RegExp(regExpSource, 'i');
var pathParameterMatches = escaped.match(PARAMETER_REG_EXP);
var pathParameters = pathParameterMatches ? pathParameterMatches.map(getParameterDescriptor) : null;
var pathMapper = pathParameters ? createUriPathMapper(expression, pathParameters) : null;
var queryMapper = routeUri.query ? createUriQueryMapper(routeUri.query) : null;
return {
expression: expression,
map: uri => {
var args = Object.create(null);
if (pathMapper) {
pathMapper(uri.path, args);
}
if (queryMapper && uri.query) {
queryMapper(uri.query.values, args);
}
return args;
}
};
} | javascript | {
"resource": ""
} |
q7842 | toSQLName | train | function toSQLName(input) {
return !input || _.isObject(input) || _.isArray(input) || _.isNaN(input) ? undefined :
input.toString().toLowerCase()
.replace(/\W+/g, " ")
.trim()
.replace(/\s+/g, "_")
.replace(/_+/g, "_")
.substring(0, 64);
} | javascript | {
"resource": ""
} |
q7843 | standardizeInput | train | function standardizeInput(input) {
if ([undefined, null].indexOf(input) !== -1) {
input = null;
}
else if (_.isNaN(input)) {
input = null;
}
else if (_.isString(input)) {
input = input.trim();
// Written empty values
if (["unspecified", "unknown", "none", "null", "empty", ""].indexOf(input.toLowerCase()) !== -1) {
input = null;
}
}
return input;
} | javascript | {
"resource": ""
} |
q7844 | suit | train | function suit(options) {
options = options || {};
// for backwards compatibility with rework-npm < 1.0.0
options.root = options.root || options.dir;
return function (ast, reworkObj) {
reworkObj
// inline imports
.use(inliner({
alias: options.alias,
prefilter: function (css) {
// per-file conformance checks
return rework(css).use(conformance).toString();
},
root: options.root,
shim: options.shim,
}))
// check if the number of selectors exceeds the IE limit
.use(limits)
// custom media queries
.use(customMedia)
// variables
.use(vars())
// calc
.use(calc);
};
} | javascript | {
"resource": ""
} |
q7845 | train | function(leaveState, event, data) {
// If `data` is a string, it is the destination state of the transition
if (_.isString(data)) data = {enterState: data}
else data = _.clone(data)
if (leaveState !== ANY_STATE && !this._states.hasOwnProperty(leaveState))
this.state(leaveState, {})
if (!this._states.hasOwnProperty(data.enterState))
this.state(data.enterState, {})
if (!this._transitions.hasOwnProperty(leaveState))
this._transitions[leaveState] = {}
data.callbacks = this._collectMethods((data.callbacks || []))
this._transitions[leaveState][event] = data
} | javascript | {
"resource": ""
} | |
q7846 | train | function(name, data) {
if (name === ANY_STATE)
throw new Error('state name "' + ANY_STATE + '" is forbidden')
data = _.clone(data)
data.enter = this._collectMethods((data.enter || []))
data.leave = this._collectMethods((data.leave || []))
this._states[name] = data
} | javascript | {
"resource": ""
} | |
q7847 | train | function() {
var events = _.reduce(_.values(this._transitions), function(memo, transitions) {
return memo.concat(_.keys(transitions))
}, [])
return _.uniq(events)
} | javascript | {
"resource": ""
} | |
q7848 | train | function(event) {
var data, extraArgs, key, transitions = this._transitions
if (transitions.hasOwnProperty((key = this.currentState)) &&
transitions[key].hasOwnProperty(event)) {
data = transitions[key][event]
} else if (transitions.hasOwnProperty(ANY_STATE) &&
transitions[ANY_STATE].hasOwnProperty(event)) {
data = transitions[ANY_STATE][event]
} else return
extraArgs = _.toArray(arguments).slice(1)
this._doTransition.apply(this, [data, event].concat(extraArgs))
} | javascript | {
"resource": ""
} | |
q7849 | train | function(data, event) {
var extraArgs = _.toArray(arguments).slice(2),
leaveState = this.currentState,
enterState = data.enterState,
triggers = data.triggers
if (!this.silent)
this.trigger.apply(this, ['leaveState:' + leaveState].concat(extraArgs))
this._callCallbacks(this._states[leaveState].leave, extraArgs)
if (!this.silent) {
this.trigger.apply(this, ['transition', leaveState, enterState].concat(extraArgs))
if (triggers)
this.trigger.apply(this, [triggers].concat(extraArgs))
}
this._callCallbacks(data.callbacks, extraArgs)
if (!this.silent)
this.trigger.apply(this, ['enterState:' + enterState].concat(extraArgs))
this.toState.apply(this, [enterState].concat(extraArgs))
} | javascript | {
"resource": ""
} | |
q7850 | train | function(methodNames) {
var methods = [], i, length, method
for (i = 0, length = methodNames.length; i < length; i++) {
// first, check if this is an anonymous function
if (_.isFunction(methodNames[i]))
method = methodNames[i]
else {
// else, get the function from the View
method = this[methodNames[i]]
if (!method)
throw new Error('Method "' + methodNames[i] + '" does not exist')
}
methods.push(method)
}
return methods
} | javascript | {
"resource": ""
} | |
q7851 | train | function(cbArray, extraArgs) {
var i, length
for (i = 0, length = cbArray.length; i < length; i++)
cbArray[i].apply(this, extraArgs)
} | javascript | {
"resource": ""
} | |
q7852 | train | function(instance) {
// If this is the first state machine registered in the debugger,
// we create the debugger's html.
if (this.viewsArray.length === 0) {
var container = this.el = $('<div id="backbone-statemachine-debug-container">'+
'<h3>backbone.statemachine: DEBUGGER</h3>'+
'<a id="backbone-statemachine-debug-hideshow">hide</a>'+
'<style>'+
'#backbone-statemachine-debug-container{background-color:rgba(0,0,0,0.5);position:absolute;height:300px;width:300px;right:0;top:0;padding:10px;z-index:10;-moz-border-radius-bottomleft:30px;-webkit-border-radius-bottomleft:30px;border-bottom-left-radius:30px;}'+
'#backbone-statemachine-debug-container.collapsed{height:20px;width:60px;}'+
'#backbone-statemachine-debug-container a{color:blue;cursor:pointer;}'+
'#backbone-statemachine-debug-container h3{margin:0;text-align:center;color:white;margin-bottom:0.5em;}'+
'.backbone-statemachine-debug{width:60px;height:60px;-moz-border-radius:30px;-webkit-border-radius:30px;border-radius:30px;text-align:center;}'+
'.backbone-statemachine-debug .state{font-weight:bold;}'+
'a#backbone-statemachine-debug-hideshow{position:absolute;bottom:12px;left:12px;font-weight:bold;color:white;}'+
'</style></div>'
).appendTo($('body'))
$('#backbone-statemachine-debug-hideshow', this.el).click(function(event){
event.preventDefault()
if (this.collapsed) {
$(container).removeClass('collapsed').children().show()
$(this).html('hide')
this.collapsed = false
} else {
$(container).addClass('collapsed').children().hide()
$(this).html('show').show()
this.collapsed = true
}
})
}
// create the debug view, pick a random color for it, and add it to the debugger.
var debugView = new this({model: instance})
var bgColor = this.pickColor()
$(debugView.el).appendTo(this.el).css({'background-color': bgColor})
debugView.render()
if (this.collapsed) $(debugView.el).hide()
this.viewsArray.push(debugView)
} | javascript | {
"resource": ""
} | |
q7853 | basic_medium | train | function basic_medium(req, res, next) {
var auth = basic_small(req);
if (auth !== '') {
if (check(auth, my.hash, my.file) === true) { // check if different
return setHeader(res, 'WWW-Authenticate', my.realms) === true
? end_work(err, next, 401) : null;
}
if (my.agent === '' || my.agent === req.headers['user-agent']) { // check UA
return end_work(err, next);
}
return end_work(err, next, 403);
}
// first attempt
res.writeHead(401, my.realm);
res.end();
} | javascript | {
"resource": ""
} |
q7854 | pad | train | function pad(number, size) {
var stringNum = String(number);
while (stringNum.length < (size || 2)) {
stringNum = '0' + stringNum;
}
return stringNum;
} | javascript | {
"resource": ""
} |
q7855 | strCompact | train | function strCompact(str) {
return this.trim(str).replace(/([\r\n\s])+/g, function (match, whitespace) {
return whitespace === ' ' ? whitespace : ' ';
});
} | javascript | {
"resource": ""
} |
q7856 | strReplace | train | function strReplace(search, replace, subject) {
var regex = void 0;
if (validateHelpers.isArray(search)) {
for (var i = 0; i < search.length; i++) {
search[i] = search[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
regex = new RegExp(search[i], 'g');
subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[i] : replace);
}
} else {
search = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
regex = new RegExp(search, 'g');
subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[0] : replace);
}
return subject;
} | javascript | {
"resource": ""
} |
q7857 | underscore | train | function underscore(str) {
return str.replace(/[-\s]+/g, '_').replace(/([A-Z\d]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase();
} | javascript | {
"resource": ""
} |
q7858 | camelize | train | function camelize(obj) {
var _this = this;
var _camelize = function _camelize(str) {
str = stringHelpers.underscore(str);
str = stringHelpers.slugifyText(str);
return str.replace(/[_.-\s](\w|$)/g, function (_, x) {
return x.toUpperCase();
});
};
if (validateHelpers.isDate(obj) || validateHelpers.isRegExp(obj)) {
return obj;
}
if (validateHelpers.isArray(obj)) {
return obj.map(function (item, index) {
if (validateHelpers.isObject(item)) {
return _this.camelize(item);
}
return item;
});
}
if (validateHelpers.isString(obj)) {
return _camelize(obj);
}
return Object.keys(obj).reduce(function (acc, key) {
var camel = _camelize(key);
acc[camel] = obj[key];
if (validateHelpers.isObject(obj[key])) {
acc[camel] = _this.camelize(obj[key]);
}
return acc;
}, {});
} | javascript | {
"resource": ""
} |
q7859 | contains | train | function contains(value, elem) {
if (validateHelpers.isArray(elem)) {
for (var i = 0, len = elem.length; i < len; i += 1) {
if (elem[i] === value) {
return true;
}
}
}
if (validateHelpers.isString(elem)) {
return elem.indexOf(value) >= 0;
}
return false;
} | javascript | {
"resource": ""
} |
q7860 | getUrlParameter | train | function getUrlParameter(name, entryPoint) {
entryPoint = !validateHelpers.isString(entryPoint) ? window.location.href : entryPoint.substring(0, 1) === '?' ? entryPoint : '?' + entryPoint;
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(entryPoint);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
} | javascript | {
"resource": ""
} |
q7861 | resizeImageByRatio | train | function resizeImageByRatio(type, newSize, aspectRatio, decimal) {
if (!validateHelpers.isNumber(newSize) || !validateHelpers.isNumber(aspectRatio)) {
newSize = parseFloat(newSize, 10);
aspectRatio = parseFloat(aspectRatio, 10);
}
var dimensions = {};
decimal = decimal || 4;
switch (type) {
case 'width':
dimensions.width = parseFloat(newSize, 10);
dimensions.height = parseFloat((newSize / aspectRatio).toFixed(decimal), 10);
break;
case 'height':
dimensions.width = parseFloat((newSize * aspectRatio).toFixed(decimal), 10);
dimensions.height = parseFloat(newSize, 10);
break;
default:
throw new Error('\'type\' needs to be \'width\' or \'height\'');
}
return dimensions;
} | javascript | {
"resource": ""
} |
q7862 | semverCompare | train | function semverCompare(v1, v2) {
var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
var validate = function validate(version) {
if (!validateHelpers.isString(version)) {
throw new TypeError('Invalid argument: expected string');
}
if (!semver.test(version)) {
throw new Error('Invalid argument: not valid semver');
}
};
[v1, v2].forEach(validate);
var pa = v1.split('.');
var pb = v2.split('.');
for (var i = 0; i < 3; i++) {
var na = Number(pa[i]);
var nb = Number(pb[i]);
if (na > nb) {
return 1;
}
if (nb > na) {
return -1;
}
if (!isNaN(na) && isNaN(nb)) {
return 1;
}
if (isNaN(na) && !isNaN(nb)) {
return -1;
}
}
return 0;
} | javascript | {
"resource": ""
} |
q7863 | stripTags | train | function stripTags(input, allowed) {
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // Making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return stringHelpers.strCompact(input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ' ';
}));
} | javascript | {
"resource": ""
} |
q7864 | times | train | function times(n, iteratee) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = -1;
var length = Math.min(n, MAX_ARRAY_LENGTH);
var result = new Array(length);
while (++index < length) {
result[index] = iteratee(index);
}
index = MAX_ARRAY_LENGTH;
n -= MAX_ARRAY_LENGTH;
while (++index < n) {
iteratee(index);
}
return result;
} | javascript | {
"resource": ""
} |
q7865 | unserialize | train | function unserialize(str) {
str = !validateHelpers.isString(str) ? window.location.href : str;
if (str.indexOf('?') < 0) {
return {};
}
str = str.indexOf('?') === 0 ? str.substr(1) : str.slice(str.indexOf('?') + 1);
var query = {};
var parts = str.split('&');
for (var i = 0, len = parts.length; i < len; i += 1) {
var part = parts[i].split('=');
query[decodeURIComponent(part[0])] = decodeURIComponent(part[1] || '');
}
return query;
} | javascript | {
"resource": ""
} |
q7866 | isArguments | train | function isArguments(value) {
// fallback check is for IE
return toString.call(value) === '[object Arguments]' || value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && 'callee' in value;
} | javascript | {
"resource": ""
} |
q7867 | isArray | train | function isArray(value) {
// check native isArray first
if (Array.isArray) {
return Array.isArray(value);
}
return toString.call(value) === '[object Array]';
} | javascript | {
"resource": ""
} |
q7868 | isEmpty | train | function isEmpty(variable) {
var emptyVariables = {
'undefined': true,
'null': true,
'number': false,
'boolean': false,
'function': false,
'regexp': false,
'date': false,
'error': false
};
var strType = globalHelpers.getType(variable);
var boolReturn = void 0;
if (emptyVariables.hasOwnProperty(strType)) {
boolReturn = emptyVariables[strType];
} else {
switch (strType) {
case 'object':
boolReturn = this.isObjectEmpty(variable);
break;
case 'string':
boolReturn = variable ? false : true;
break;
case 'array':
boolReturn = variable.length ? false : true;
break;
}
}
return boolReturn;
} | javascript | {
"resource": ""
} |
q7869 | isJson | train | function isJson(str) {
try {
var obj = JSON.parse(str);
return this.isObject(obj);
} catch (e) {/* ignore */}
return false;
} | javascript | {
"resource": ""
} |
q7870 | isNumber | train | function isNumber(value) {
var isNaN = Number.isNaN || window.isNaN;
return typeof value === 'number' && !isNaN(value);
} | javascript | {
"resource": ""
} |
q7871 | isObjectEmpty | train | function isObjectEmpty(obj) {
if (!this.isObject(obj)) {
return false;
}
for (var x in obj) {
if ({}.hasOwnProperty.call(obj, x)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q7872 | isSameType | train | function isSameType(value, other) {
var tag = toString.call(value);
if (tag !== toString.call(other)) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q7873 | arrayClone | train | function arrayClone(arr) {
var clone = new Array(arr.length);
this._forEach(arr, function (el, i) {
clone[i] = el;
});
return clone;
} | javascript | {
"resource": ""
} |
q7874 | arrayFlatten | train | function arrayFlatten(arr, level) {
var self = this;
var result = [];
var current = 0;
level = level || Infinity;
self._forEach(arr, function (el) {
if (validateHelpers.isArray(el) && current < level) {
result = result.concat(self.arrayFlatten(el, level, current + 1));
} else {
result.push(el);
}
});
return result;
} | javascript | {
"resource": ""
} |
q7875 | arraySample | train | function arraySample(arr, num, remove) {
var result = [];
var _num = void 0;
var _remove = void 0;
var single = void 0;
if (validateHelpers.isBoolean(num)) {
_remove = num;
} else {
_num = num;
_remove = remove;
}
if (validateHelpers.isUndefined(_num)) {
_num = 1;
single = true;
}
if (!_remove) {
arr = this.arrayClone(arr);
}
_num = Math.min(_num, arr.length);
for (var i = 0, index; i < _num; i += 1) {
index = Math.trunc(Math.random() * arr.length);
result.push(arr[index]);
arr.splice(index, 1);
}
return single ? result[0] : result;
} | javascript | {
"resource": ""
} |
q7876 | chunk | train | function chunk(array, size) {
size = Math.max(size, 0);
var length = array === null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0;
var resIndex = 0;
var result = new Array(Math.ceil(length / size));
while (index < length) {
result[resIndex++] = this.slice(array, index, index += size);
}
return result;
} | javascript | {
"resource": ""
} |
q7877 | cleanArray | train | function cleanArray(array) {
var newArray = [];
for (var i = 0, len = array.length; i < len; i += 1) {
if (array[i]) {
newArray.push(array[i]);
}
}
return newArray;
} | javascript | {
"resource": ""
} |
q7878 | explode | train | function explode(str, separator, limit) {
if (!validateHelpers.isString(str)) {
throw new Error('\'str\' must be a String');
}
var arr = str.split(separator);
if (limit !== undefined && arr.length >= limit) {
arr.push(arr.splice(limit - 1).join(separator));
}
return arr;
} | javascript | {
"resource": ""
} |
q7879 | implode | train | function implode(pieces, glue) {
if (validateHelpers.isArray(pieces)) {
return pieces.join(glue || ',');
} else if (validateHelpers.isObject(pieces)) {
var arr = [];
for (var o in pieces) {
if (object.hasOwnProperty(o)) {
arr.push(pieces[o]);
}
}
return arr.join(glue || ',');
}
return '';
} | javascript | {
"resource": ""
} |
q7880 | toNumber | train | function toNumber(value) {
var _this = this;
if (validateHelpers.isArray(value)) {
return value.map(function (a) {
return _this.toNumber(a);
});
}
var number = parseFloat(value);
if (number === undefined) {
return value;
}
if (number.toString().length !== value.toString().length && !validateHelpers.isNumeric(value)) {
return value;
}
return validateHelpers.isNumber(number) ? value : number;
} | javascript | {
"resource": ""
} |
q7881 | extend | train | function extend(obj) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (validateHelpers.isObject(obj) && args.length > 0) {
if (Object.assign) {
return Object.assign.apply(Object, [obj].concat(toConsumableArray(args)));
}
args.forEach(function (arg) {
if (validateHelpers.isObject(arg)) {
Object.keys(arg).forEach(function (key) {
obj[key] = arg[key];
});
}
});
}
return obj;
} | javascript | {
"resource": ""
} |
q7882 | getDescendantProp | train | function getDescendantProp(obj, path) {
if (!validateHelpers.isPlainObject(obj)) {
throw new TypeError('\'obj\' param must be an plain object');
}
return path.split('.').reduce(function (acc, part) {
return acc && acc[part];
}, obj);
} | javascript | {
"resource": ""
} |
q7883 | groupObjectByValue | train | function groupObjectByValue(item, key) {
var camelize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!validateHelpers.isArray(item)) {
throw new Error('\'item\' must be an array of objects');
}
var grouped = item.reduce(function (r, a) {
r[a[key]] = r[a[key]] || [];
r[a[key]].push(a);
return r;
}, Object.create(null));
return camelize ? globalHelpers.camelize(grouped) : grouped;
} | javascript | {
"resource": ""
} |
q7884 | objectArraySortByValue | train | function objectArraySortByValue(arr, map, key) {
var _this2 = this;
var reverse = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (!validateHelpers.isArray(map) || map.length < 1) {
var compare = function compare(a, b, n) {
return _this2.getDescendantProp(a, n).toString().localeCompare(_this2.getDescendantProp(b, n).toString(), undefined, { numeric: true });
};
return arr.slice().sort(function (a, b) {
return reverse ? -compare(a, b, key) : compare(a, b, key);
});
}
return arr.slice().sort(function (a, b) {
var ordered = map.indexOf(_this2.getDescendantProp(a, key).toString()) - map.indexOf(_this2.getDescendantProp(b, key).toString());
return reverse ? ordered * -1 : ordered;
});
} | javascript | {
"resource": ""
} |
q7885 | objectToArray | train | function objectToArray(obj) {
if (!validateHelpers.isPlainObject(obj)) {
throw new Error('\'obj\' must be a plain object');
}
return Object.keys(obj).map(function (key) {
return obj[key];
});
} | javascript | {
"resource": ""
} |
q7886 | renameKeys | train | function renameKeys(obj, keysMap) {
if (!validateHelpers.isPlainObject(obj)) {
throw new Error('\'obj\' must be an plain object');
}
return Object.keys(obj).reduce(function (acc, key) {
return _extends({}, acc, defineProperty({}, keysMap[key] || key, obj[key]));
}, {});
} | javascript | {
"resource": ""
} |
q7887 | getUserLocation | train | function getUserLocation(cache, storage) {
var _this = this;
if (cache) {
this._initLocationStorage(storage);
}
var store = storage.session.get(CONSTANTS.STORAGE_NAME);
/* eslint-disable */
return $.Deferred(function (def) {
/* eslint-enable */
if (!validateHelpers.isObjectEmpty(store)) {
def.resolve(store);
} else {
if (window.navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
if (!window.google) {
return def.reject('Google Maps Javascript API not found. Follow tutorial: https://developers.google.com/maps/documentation/javascript');
}
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
for (var i = 0, len = results.length; i < len; i += 1) {
if (results[i].types[0] === 'locality') {
var city = results[i].address_components[0].short_name;
var state = results[i].address_components[2].short_name;
var storeLocation = {
coords: { lat: lat, lng: lng },
city: city,
state: state,
region: _this.filteredRegion(state)
};
if (cache) {
storage.session.set(CONSTANTS.STORAGE_NAME, storeLocation, CONSTANTS.EXPIRE_TIME);
}
def.resolve(storeLocation);
}
}
} else {
def.reject('No reverse geocode results.');
}
} else {
def.reject('Geocoder failed: ' + status);
}
});
}, function (err) {
def.reject('Geolocation not available.');
});
} else {
def.reject('Geolocation isn\'t available');
}
}
}).promise();
} | javascript | {
"resource": ""
} |
q7888 | filteredRegion | train | function filteredRegion(state) {
var _this2 = this;
var filteredRegion = '';
var _loop = function _loop(region) {
if ({}.hasOwnProperty.call(_this2._regionMap, region)) {
_this2._regionMap[region].some(function (el, i, arr) {
if (stringHelpers.removeAccent(el.toLowerCase()) === stringHelpers.removeAccent(state.toLowerCase())) {
filteredRegion = region;
}
});
}
};
for (var region in this._regionMap) {
_loop(region);
}
return filteredRegion;
} | javascript | {
"resource": ""
} |
q7889 | Utilify | train | function Utilify() {
classCallCheck(this, Utilify);
/**
* Version
* @type {String}
*/
this.version = '0.10.1';
/**
* Package name
* @type {String}
*/
this.name = '@UtilifyJS';
/**
* Global Helpers instance
* @type {GlobalHelpers}
*/
this.globalHelpers = new GlobalHelpers();
/**
* Location Helpers instance
* @type {LocationHelpers}
*/
this.locationHelpers = new LocationHelpers(store);
/**
* Local/Session Storage
* @type {Object}
*/
this.storage = store;
/**
* JS Cookies
* @type {Object}
*/
this.cookies = initCookies(function () {});
} | javascript | {
"resource": ""
} |
q7890 | train | function ( target, store, template, options ) {
var ref = [store],
obj, instance;
if ( !( target instanceof Element ) || typeof store !== "object" || !regex.string_object.test( typeof template ) ) {
throw new Error( label.error.invalidArguments );
}
obj = element.create( "ul", {"class": "list", id: store.parentNode.id + "-datalist"}, target );
// Creating instance
instance = new DataList( obj, ref[0], template );
if ( options instanceof Object) {
utility.merge( instance, options );
}
instance.store.datalists.push( instance );
// Rendering if not tied to an API or data is ready
if ( instance.store.uri === null || instance.store.loaded ) {
instance.refresh();
}
return instance;
} | javascript | {
"resource": ""
} | |
q7891 | train | function () {
if ( isNaN( this.pageSize ) ) {
throw new Error( label.error.invalidArguments );
}
return number.round( ( !this.filter ? this.total : this.filtered.length ) / this.pageSize, "up" );
} | javascript | {
"resource": ""
} | |
q7892 | train | function (fileName) {
fileName = (fileName || "").toLowerCase();
var validExtensions = ["svg", "cdr", "eps", "ai"],
fileExtension = fileName.substr(fileName.lastIndexOf('.') + 1);
return validExtensions.indexOf(fileExtension) != -1;
} | javascript | {
"resource": ""
} | |
q7893 | train | function(pluginOptions, options) {
options.isFactoryFunctionRun = true;
return new GrawlixPlugin({
name: 'blank-plugin-2',
init: function(opts) {
opts.isLoaded = true;
}
});
} | javascript | {
"resource": ""
} | |
q7894 | train | function(ed25519Sk, callback){
if (typeof callback != 'function') throw new TypeError('callback must be a function');
try {
isValidInput(ed25519Sk, 'ed25519Sk', MiniSodium.crypto_sign_SECRETKEYBYTES);
} catch (e){
callback(e);
return;
}
ed25519Sk = to_hex(ed25519Sk);
var params = [ed25519Sk];
cordova.exec(resultHandlerFactory(callback), callback, 'MiniSodium', 'crypto_sign_ed25519_sk_to_curve25519', params);
} | javascript | {
"resource": ""
} | |
q7895 | train | function(str) {
if (str instanceof Uint8Array) return str;
if (!is_hex(str)) {
throw new TypeError("The provided string doesn't look like hex data");
}
var result = new Uint8Array(str.length / 2);
for (var i = 0; i < str.length; i += 2) {
result[i >>> 1] = parseInt(str.substr(i, 2), 16);
}
return result;
} | javascript | {
"resource": ""
} | |
q7896 | buildRouterPath | train | function buildRouterPath(path, prefix) {
if (!prefix) {
prefix = '';
}
if (prefix.length && path === '/') {
return prefix;
}
return prefix + path;
} | javascript | {
"resource": ""
} |
q7897 | compareRouteAndApplyArgs | train | function compareRouteAndApplyArgs (route, request_url, request_method) {
if (route.method !== request_method) {
return false;
}
let template = route.path.split('/');
if (template[0] === '') {
template = template.slice(1); // Slice kills the emptystring before the leading slash
}
let actual = request_url.pathname.split('/');
if (actual[0] === '') {
actual = actual.slice(1); // Slice kills the emptystring before the leading slash
}
if (template.length != actual.length) {
return false;
}
for (let i = 0; i < template.length; i++) {
let actual_part = actual[i];
let template_part = template[i];
// Process variables first
if (template_part[0] === '#') {
// # templates only accept numbers
if (isNaN(Number(actual_part))) {
return false;
}
applyArg(request_url, template_part.substring(1), Number(actual_part));
continue;
}
if (template_part[0] === '$') {
// $ templates accept any non-slash alphanumeric character
applyArg(request_url, template_part.substring(1), String(actual_part));
// Continue so that
continue;
}
// Process exact matches second
if (actual_part === template_part) {
continue;
}
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q7898 | applyArg | train | function applyArg(request_url, template_part, actual_part) {
if (typeof(request_url.args) === "undefined") {
request_url.args = {};
}
if (typeof request_url.args !== "object") {
throw new Error("The request url's args have already been defined as a " + typeof request_url.args + " and we expected an object. For safety we are throwing this error instead of overwriting your existing data. Please use a different field name in your code");
}
request_url.args[template_part] = actual_part;
} | javascript | {
"resource": ""
} |
q7899 | getNotificationState | train | function getNotificationState () {
if (process.platform !== 'win32') {
throw new Error('windows-notification-state only works on windows')
}
const QUERY_USER_NOTIFICATION_STATE = [
'',
'QUNS_NOT_PRESENT',
'QUNS_BUSY',
'QUNS_RUNNING_D3D_FULL_SCREEN',
'QUNS_PRESENTATION_MODE',
'QUNS_ACCEPTS_NOTIFICATIONS',
'QUNS_QUIET_TIME',
'QUNS_APP'
]
const result = addon.getNotificationState()
if (QUERY_USER_NOTIFICATION_STATE[result]) {
return QUERY_USER_NOTIFICATION_STATE[result]
} else {
return 'UNKNOWN_ERROR'
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.