_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q28400 | train | function (callback) {
IdentityCounter.findOneAndUpdate(
{ model: settings.model, field: settings.field },
{ count: settings.startAt - settings.incrementBy },
{ new: true }, // new: true specifies that the callback should get the updated counter.
function (err) {
if (err) return callback(err);
callback(null, settings.startAt);
}
);
} | javascript | {
"resource": ""
} | |
q28401 | train | function (err, updatedIdentityCounter) {
if (err) return next(err);
// If there are no errors then go ahead and set the document's field to the current count.
doc[settings.field] = updatedIdentityCounter.count;
// Continue with default document save functionality.
next();
} | javascript | {
"resource": ""
} | |
q28402 | addUnscrollClassName | train | function addUnscrollClassName() {
if (document.getElementById('unscroll-class-name')) {
return;
}
var css = '.unscrollable { overflow-y: hidden !important; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
style.setAttribute('id', 'unscroll-class-name');
style.appendChild(document.createTextNode(css));
head.appendChild(style);
} | javascript | {
"resource": ""
} |
q28403 | train | function (el)
{
// Extract the href or the onclick event if no submit event is passed
if (!this.options.confirm) {
var submit = el.attr('onclick') ? el.attr('onclick') : (el.attr('href') ? (el.attr('target') ? 'window.open("' + el.attr('href') + '", "' + el.attr('target') + '");' : 'window.location.href = "' + el.attr('href') + '";') : '');
el.prop('onclick', null).data('jBox-Confirm-submit', submit);
}
} | javascript | {
"resource": ""
} | |
q28404 | train | function ()
{
// Set the new action for the submit button
this.submitButton.off('click.jBox-Confirm' + this.id).on('click.jBox-Confirm' + this.id, function () { this.options.confirm ? this.options.confirm() : eval(this.source.data('jBox-Confirm-submit')); this.options.closeOnConfirm && this.close(); }.bind(this));
} | javascript | {
"resource": ""
} | |
q28405 | train | function ()
{
// Append image label containers
this.imageLabel = jQuery('<div/>', {'class': 'jBox-image-label-container'}).appendTo(this.wrapper);
this.imageLabel.append(jQuery('<div/>', {'class': 'jBox-image-pointer-prev', click: function () { this.showImage('prev'); }.bind(this)})).append(jQuery('<div/>', {'class': 'jBox-image-pointer-next', click: function () { this.showImage('next'); }.bind(this)}));
// Append the download button
if (this.options.downloadButton) {
this.downloadButton = jQuery('<div/>', {'class': 'jBox-image-download-button-wrapper'})
.appendTo(this.wrapper)
.append(
this.options.downloadButtonText ? jQuery('<div/>', {'class': 'jBox-image-download-button-text'}).html(this.options.downloadButtonText) : null
)
.append(
jQuery('<div/>', {'class': 'jBox-image-download-button-icon'})
).on('click touchdown', function () {
if (this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl) {
var currentImageUrl = this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl;
} else {
var currentImage = this.wrapper.find('.jBox-image-default-current');
var currentImageStyle = currentImage[0].style.backgroundImage;
var currentImageUrl = currentImageStyle.slice(4, -1).replace(/["']/g, '');
}
this.downloadImage(currentImageUrl);
}.bind(this));
}
// Creating the image counter containers
if (this.options.imageCounter) {
this.imageCounter = jQuery('<div/>', {'class': 'jBox-image-counter-container'}).appendTo(this.wrapper);
this.imageCounter.append(jQuery('<span/>', {'class': 'jBox-image-counter-current'})).append(jQuery('<span/>').html(this.options.imageCounterSeparator)).append(jQuery('<span/>', {'class': 'jBox-image-counter-all'}));
}
} | javascript | {
"resource": ""
} | |
q28406 | train | function ()
{
// Add key events
jQuery(document).on('keyup.jBox-Image-' + this.id, function (ev) {
(ev.keyCode == 37) && this.showImage('prev');
(ev.keyCode == 39) && this.showImage('next');
}.bind(this));
// Load the image from the attached element
this.showImage('open');
} | javascript | {
"resource": ""
} | |
q28407 | train | function ()
{
// Cache position values
this.defaultNoticePosition = jQuery.extend({}, this.options.position);
// Type Notice has its own adjust position function
this._adjustNoticePositon = function () {
var win = jQuery(window);
var windowDimensions = {
x: win.width(),
y: win.height()
};
// Reset default position
this.options.position = jQuery.extend({}, this.defaultNoticePosition);
// Adjust depending on viewport
jQuery.each(this.options.responsivePositions, function (viewport, position) {
if (windowDimensions.x <= viewport) {
this.options.position = position;
return false;
}
}.bind(this));
// Set new padding options
this.options.adjustDistance = {
top: this.options.position.y,
right: this.options.position.x,
bottom: this.options.position.y,
left: this.options.position.x
};
};
// If jBox grabs an element as content, crab a clone instead
this.options.content instanceof jQuery && (this.options.content = this.options.content.clone().attr('id', ''));
// Adjust paddings when window resizes
jQuery(window).on('resize.responsivejBoxNotice-' + this.id, function (ev) { if (this.isOpen) { this._adjustNoticePositon(); } }.bind(this));
this.open();
} | javascript | {
"resource": ""
} | |
q28408 | train | function ()
{
// Bail if we're stacking
if (this.options.stack) {
return;
}
// Adjust position when opening
this._adjustNoticePositon();
// Loop through notices at same window corner destroy them
jQuery.each(jQuery('.jBox-Notice'), function (index, el)
{
el = jQuery(el);
// Abort if the element is this notice or when it's not at the same position
if (el.attr('id') == this.id || el.data('jBox-Notice-position') != this.options.attributes.x + '-' + this.options.attributes.y) {
return;
}
// Remove notice when we don't wont to stack them
if (!this.options.stack) {
el.data('jBox').close({ignoreDelay: true});
return;
}
}.bind(this));
} | javascript | {
"resource": ""
} | |
q28409 | train | function ()
{
var stacks = {};
jQuery.each(jQuery('.jBox-Notice'), function (index, el)
{
el = jQuery(el);
var pos = el.data('jBox-Notice-position');
if (!stacks[pos]) {
stacks[pos] = [];
}
stacks[pos].push(el);
});
for (var pos in stacks) {
var position = pos.split('-');
var direction = position[1];
stacks[pos].reverse();
var margin = 0;
for (var i in stacks[pos]) {
el = stacks[pos][i];
el.css('margin-' + direction, margin);
margin += el.outerHeight() + this.options.stackSpacing;
}
}
} | javascript | {
"resource": ""
} | |
q28410 | train | function () {
// Create the containers for the liked or disliked avatars
if (initial) {
$('<div id="LikedAvatars" class="AvatarsCollection"/>').appendTo($('body'));
$('<div id="DislikedAvatars" class="AvatarsCollection"/>').appendTo($('body'));
}
$.each(this.footer.find('button'), function (index, el) {
// Adding the click events for the buttons in the footer
$(el).on('click', function () {
// Storing a global var that the user clicked on a button
DemoAvatars.clicked = true;
// When a user clicks a button close the tooltips
DemoAvatars.AvatarsTooltipLike && DemoAvatars.AvatarsTooltipLike.close();
DemoAvatars.AvatarsTooltipDislike && DemoAvatars.AvatarsTooltipDislike.close();
// When we click a button, the jBox disappears, let's tell this jBox that we removed it
this.AvatarRemoved = true;
// Did we like or dislike the avatar?
var liked = $(el).hasClass('button-heart');
// Slide the jBox to the left or right depending on which button the user clicked
this.animate('slide' + (liked ? 'Right' : 'Left'), {
// Once the jBox is removed, hide it and show the avatar in the collection
complete: function () {
this.wrapper.css('display', 'none');
// Which container to use
var collectionContainer = liked ? $('#LikedAvatars') : $('#DislikedAvatars');
// If there if not enough space for the avatars to show in one line remove the first one
if (collectionContainer.find('div[data-avatar-tooltip]').length && ((collectionContainer.find('div[data-avatar-tooltip]').length + 1) * $(collectionContainer.find('div[data-avatar-tooltip]')[0]).outerWidth(true) > collectionContainer.outerWidth())) {
$(collectionContainer.find('div[data-avatar-tooltip]')[0]).remove();
}
// Add the avatar to the collection
this.animate('popIn', {
element: $('<div data-avatar-tooltip="You ' + (liked ? 'liked' : 'disliked') + ' ' + DemoAvatars.Avatars[this.AvatarIndex] + '"/>').append($('<div/>').html('<img src="https://stephanwagner.me/img/jBox/avatar/' + DemoAvatars.Avatars[this.AvatarIndex] + '.svg"/>')).appendTo(collectionContainer)
});
// Attach the avatar tooltip
DemoAvatars.AvatarsTooltip && DemoAvatars.AvatarsTooltip.attach();
}.bind(this)
});
// Open another Avatar jBox
generateAvatarJBox();
}.bind(this));
}.bind(this));
} | javascript | {
"resource": ""
} | |
q28411 | train | function () {
// Set title and content depending on current index
this.setTitle(DemoAvatars.Avatars[DemoAvatars.current]);
this.content.css({backgroundImage: 'url(https://stephanwagner.me/img/jBox/avatar/' + DemoAvatars.Avatars[DemoAvatars.current] + '.svg)'});
// If it's the inital jBox, show the tooltips after a short delay
initial && setTimeout(function () {
// We are creating the two tooltips in a loop as they are very similar
$.each(['Dislike', 'Like'], function (index, item) {
// We store the tooltips in the global var so we can refer to them later
DemoAvatars['AvatarsTooltip' + item] = new jBox('Tooltip', {
theme: 'TooltipBorder',
addClass: 'AvatarsTooltip AvatarsTooltip' + item,
minWidth: 110,
content: item,
position: {
y: 'bottom'
},
offset: {
y: 5
},
target: '#AvatarsInitial .jBox-footer .button-' + (item == 'Like' ? 'heart' : 'cross'),
animation: 'move',
zIndex: 11000,
// Abort opening the tooltips when we clicked on a like or dislike button already
onOpen: function () {
DemoAvatars.clicked && this.close();
}
}).open();
});
}, 500);
} | javascript | {
"resource": ""
} | |
q28412 | getCredential | train | function getCredential(accessKey, region, requestDate) {
if (!isString(accessKey)) {
throw new TypeError('accessKey should be of type "string"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"')
}
return `${accessKey}/${getScope(region, requestDate)}`
} | javascript | {
"resource": ""
} |
q28413 | getSignedHeaders | train | function getSignedHeaders(headers) {
if (!isObject(headers)) {
throw new TypeError('request should be of type "object"')
}
// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
//
// User-Agent:
//
// This is ignored from signing because signing this causes problems with generating pre-signed URLs
// (that are executed by other agents) or when customers pass requests through proxies, which may
// modify the user-agent.
//
// Content-Length:
//
// This is ignored from signing because generating a pre-signed URL should not provide a content-length
// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when
// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which
// implicitly validates the payload length (since changing the number of bytes would change the checksum)
// and therefore this header is not valuable in the signature.
//
// Content-Type:
//
// Signing this header causes quite a number of problems in browser environments, where browsers
// like to modify and normalize the content-type header in different ways. There is more information
// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic
// and reduces the possibility of future bugs
//
// Authorization:
//
// Is skipped for obvious reasons
var ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent']
return _.map(headers, (v, header) => header)
.filter(header => ignoredHeaders.indexOf(header) === -1)
.sort()
} | javascript | {
"resource": ""
} |
q28414 | getSigningKey | train | function getSigningKey(date, region, secretKey) {
if (!isObject(date)) {
throw new TypeError('date should be of type "object"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isString(secretKey)) {
throw new TypeError('secretKey should be of type "string"')
}
var dateLine = makeDateShort(date),
hmac1 = Crypto.createHmac('sha256', 'AWS4' + secretKey).update(dateLine).digest(),
hmac2 = Crypto.createHmac('sha256', hmac1).update(region).digest(),
hmac3 = Crypto.createHmac('sha256', hmac2).update('s3').digest()
return Crypto.createHmac('sha256', hmac3).update('aws4_request').digest()
} | javascript | {
"resource": ""
} |
q28415 | getStringToSign | train | function getStringToSign(canonicalRequest, requestDate, region) {
if (!isString(canonicalRequest)) {
throw new TypeError('canonicalRequest should be of type "string"')
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
var hash = Crypto.createHash('sha256').update(canonicalRequest).digest('hex')
var scope = getScope(region, requestDate)
var stringToSign = []
stringToSign.push(signV4Algorithm)
stringToSign.push(makeDateLong(requestDate))
stringToSign.push(scope)
stringToSign.push(hash)
return stringToSign.join('\n')
} | javascript | {
"resource": ""
} |
q28416 | probe | train | function probe (mdns, service, cb) {
var sent = false
var retries = 0
var timer
mdns.on('response', onresponse)
setTimeout(send, Math.random() * 250)
function send () {
// abort if the service have or is being stopped in the meantime
if (!service._activated || service._destroyed) return
mdns.query(service.fqdn, 'ANY', function () {
// This function will optionally be called with an error object. We'll
// just silently ignore it and retry as we normally would
sent = true
timer = setTimeout(++retries < 3 ? send : done, 250)
timer.unref()
})
}
function onresponse (packet) {
// Apparently conflicting Multicast DNS responses received *before*
// the first probe packet is sent MUST be silently ignored (see
// discussion of stale probe packets in RFC 6762 Section 8.2,
// "Simultaneous Probe Tiebreaking" at
// https://tools.ietf.org/html/rfc6762#section-8.2
if (!sent) return
if (packet.answers.some(matchRR) || packet.additionals.some(matchRR)) done(true)
}
function matchRR (rr) {
return dnsEqual(rr.name, service.fqdn)
}
function done (exists) {
mdns.removeListener('response', onresponse)
clearTimeout(timer)
cb(!!exists)
}
} | javascript | {
"resource": ""
} |
q28417 | announce | train | function announce (server, service) {
var delay = 1000
var packet = service._records()
server.register(packet)
;(function broadcast () {
// abort if the service have or is being stopped in the meantime
if (!service._activated || service._destroyed) return
server.mdns.respond(packet, function () {
// This function will optionally be called with an error object. We'll
// just silently ignore it and retry as we normally would
if (!service.published) {
service._activated = true
service.published = true
service.emit('up')
}
delay = delay * REANNOUNCE_FACTOR
if (delay < REANNOUNCE_MAX_MS && !service._destroyed) {
setTimeout(broadcast, delay).unref()
}
})
})()
} | javascript | {
"resource": ""
} |
q28418 | teardown | train | function teardown (server, services, cb) {
if (!Array.isArray(services)) services = [services]
services = services.filter(function (service) {
return service._activated // ignore services not currently starting or started
})
var records = flatten.depth(services.map(function (service) {
service._activated = false
var records = service._records()
records.forEach(function (record) {
record.ttl = 0 // prepare goodbye message
})
return records
}), 1)
if (records.length === 0) return cb && cb()
server.unregister(records)
// send goodbye message
server.mdns.respond(records, function () {
services.forEach(function (service) {
service.published = false
})
if (cb) cb.apply(null, arguments)
})
} | javascript | {
"resource": ""
} |
q28419 | Browser | train | function Browser (mdns, opts, onup) {
if (typeof opts === 'function') return new Browser(mdns, null, opts)
EventEmitter.call(this)
this._mdns = mdns
this._onresponse = null
this._serviceMap = {}
this._txt = dnsTxt(opts.txt)
if (!opts || !opts.type) {
this._name = WILDCARD
this._wildcard = true
} else {
this._name = serviceName.stringify(opts.type, opts.protocol || 'tcp') + TLD
if (opts.name) this._name = opts.name + '.' + this._name
this._wildcard = false
}
this.services = []
if (onup) this.on('up', onup)
this.start()
} | javascript | {
"resource": ""
} |
q28420 | train | function (obj, columnName) {
if (typeof obj !== "object" || typeof columnName !== "string") {
return obj;
}
var args = columnName.split('.');
var cObj = obj;
if (args.length > 1) {
for (var i = 1, len = args.length; i < len; i++) {
cObj = cObj[args[i]];
if (!cObj) {
return obj;
}
}
return cObj;
}
return obj;
} | javascript | {
"resource": ""
} | |
q28421 | stringify | train | function stringify(obj) {
try {
return JSON.stringify(obj);
} catch (e) {
var cache = [];
return JSON.stringify(obj, function (key, value) {
if (angular.isObject(value) && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
}
} | javascript | {
"resource": ""
} |
q28422 | getModuleConfig | train | function getModuleConfig(moduleName) {
if (!angular.isString(moduleName)) {
throw new Error('You need to give the name of the module to get');
}
if (!modules[moduleName]) {
return null;
}
return angular.copy(modules[moduleName]);
} | javascript | {
"resource": ""
} |
q28423 | setModuleConfig | train | function setModuleConfig(moduleConfig) {
if (!angular.isObject(moduleConfig)) {
throw new Error('You need to give the module config object to set');
}
modules[moduleConfig.name] = moduleConfig;
return moduleConfig;
} | javascript | {
"resource": ""
} |
q28424 | isLoaded | train | function isLoaded(modulesNames) {
var moduleLoaded = function moduleLoaded(module) {
var isLoaded = regModules.indexOf(module) > -1;
if (!isLoaded) {
isLoaded = !!moduleExists(module);
}
return isLoaded;
};
if (angular.isString(modulesNames)) {
modulesNames = [modulesNames];
}
if (angular.isArray(modulesNames)) {
var i, len;
for (i = 0, len = modulesNames.length; i < len; i++) {
if (!moduleLoaded(modulesNames[i])) {
return false;
}
}
return true;
} else {
throw new Error('You need to define the module(s) name(s)');
}
} | javascript | {
"resource": ""
} |
q28425 | getModule | train | function getModule(moduleName) {
try {
return ngModuleFct(moduleName);
} catch (e) {
// this error message really suxx
if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
e.message = 'The module "' + stringify(moduleName) + '" that you are trying to load does not exist. ' + e.message;
}
throw e;
}
} | javascript | {
"resource": ""
} |
q28426 | inject | train | function inject(moduleName) {
var localParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var real = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
var self = this,
deferred = $q.defer();
if (angular.isDefined(moduleName) && moduleName !== null) {
if (angular.isArray(moduleName)) {
var promisesList = [];
angular.forEach(moduleName, function (module) {
promisesList.push(self.inject(module, localParams, real));
});
return $q.all(promisesList);
} else {
self._addToLoadList(self._getModuleName(moduleName), true, real);
}
}
if (modulesToLoad.length > 0) {
var res = modulesToLoad.slice(); // clean copy
var loadNext = function loadNext(moduleName) {
moduleCache.push(moduleName);
modulePromises[moduleName] = deferred.promise;
self._loadDependencies(moduleName, localParams).then(function success() {
try {
justLoaded = [];
_register(providers, moduleCache, localParams);
} catch (e) {
self._$log.error(e.message);
deferred.reject(e);
return;
}
if (modulesToLoad.length > 0) {
loadNext(modulesToLoad.shift()); // load the next in list
} else {
deferred.resolve(res); // everything has been loaded, resolve
}
}, function error(err) {
deferred.reject(err);
});
};
// load the first in list
loadNext(modulesToLoad.shift());
} else if (localParams && localParams.name && modulePromises[localParams.name]) {
return modulePromises[localParams.name];
} else {
deferred.resolve();
}
return deferred.promise;
} | javascript | {
"resource": ""
} |
q28427 | getOptions | train | function getOptions(loaderContext) {
const options = {
plugins: [],
relativeUrls: true,
...clone(loaderUtils.getOptions(loaderContext)),
};
// We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
options.filename = loaderContext.resource;
// When no paths are given, we use the webpack resolver
if ('paths' in options === false) {
// It's safe to mutate the array now because it has already been cloned
options.plugins.push(createWebpackLessPlugin(loaderContext));
}
if (options.sourceMap) {
if (typeof options.sourceMap === 'boolean') {
options.sourceMap = {};
}
if ('outputSourceFiles' in options.sourceMap === false) {
// Include source files as `sourceContents` as sane default since this makes source maps "just work" in most cases
options.sourceMap.outputSourceFiles = true;
}
}
return options;
} | javascript | {
"resource": ""
} |
q28428 | createWebpackLessPlugin | train | function createWebpackLessPlugin(loaderContext) {
const { fs } = loaderContext;
const resolve = pify(loaderContext.resolve.bind(loaderContext));
const loadModule = pify(loaderContext.loadModule.bind(loaderContext));
const readFile = pify(fs.readFile.bind(fs));
class WebpackFileManager extends less.FileManager {
supports() {
// Our WebpackFileManager handles all the files
return true;
}
// Sync resolving is used at least by the `data-uri` function.
// This file manager doesn't know how to do it, so let's delegate it
// to the default file manager of Less.
// We could probably use loaderContext.resolveSync, but it's deprecated,
// see https://webpack.js.org/api/loaders/#this-resolvesync
supportsSync() {
return false;
}
loadFile(filename, currentDirectory, options) {
let url;
if (less.version[0] >= 3) {
if (options.ext && !isModuleName.test(filename)) {
url = this.tryAppendExtension(filename, options.ext);
} else {
url = filename;
}
} else {
url = filename.replace(matchMalformedModuleFilename, '$1');
}
const moduleRequest = loaderUtils.urlToRequest(
url,
url.charAt(0) === '/' ? '' : null
);
// Less is giving us trailing slashes, but the context should have no trailing slash
const context = currentDirectory.replace(trailingSlash, '');
let resolvedFilename;
return resolve(context, moduleRequest)
.then((f) => {
resolvedFilename = f;
loaderContext.addDependency(resolvedFilename);
if (isLessCompatible.test(resolvedFilename)) {
return readFile(resolvedFilename).then((contents) =>
contents.toString('utf8')
);
}
return loadModule([stringifyLoader, resolvedFilename].join('!')).then(
JSON.parse
);
})
.then((contents) => {
return {
contents,
filename: resolvedFilename,
};
});
}
}
return {
install(lessInstance, pluginManager) {
pluginManager.addFileManager(new WebpackFileManager());
},
minVersion: [2, 1, 1],
};
} | javascript | {
"resource": ""
} |
q28429 | processResult | train | function processResult(loaderContext, resultPromise) {
const { callback } = loaderContext;
resultPromise
.then(
({ css, map, imports }) => {
imports.forEach(loaderContext.addDependency, loaderContext);
return {
// Removing the sourceMappingURL comment.
// See removeSourceMappingUrl.js for the reasoning behind this.
css: removeSourceMappingUrl(css),
map: typeof map === 'string' ? JSON.parse(map) : map,
};
},
(lessError) => {
if (lessError.filename) {
loaderContext.addDependency(lessError.filename);
}
throw formatLessError(lessError);
}
)
.then(({ css, map }) => {
callback(null, css, map);
}, callback);
} | javascript | {
"resource": ""
} |
q28430 | formatLessError | train | function formatLessError(err) {
/* eslint-disable no-param-reassign */
const msg = err.message;
// Instruct webpack to hide the JS stack from the console
// Usually you're only interested in the SASS stack in this case.
err.hideStack = true;
err.message = [
os.EOL,
...getFileExcerptIfPossible(err),
msg.charAt(0).toUpperCase() + msg.slice(1),
` in ${err.filename} (line ${err.line}, column ${err.column})`,
].join(os.EOL);
return err;
} | javascript | {
"resource": ""
} |
q28431 | getColumnPropertiesFromColumnArray | train | function getColumnPropertiesFromColumnArray(columnProperties, columns) {
return columns.reduce((previous, current, i) => {
previous[current] = { id: current, order: offset + i };
return previous;
},
columnProperties);
} | javascript | {
"resource": ""
} |
q28432 | buildGriddleReducerObject | train | function buildGriddleReducerObject(reducerObjects) {
let reducerMethodsWithoutHooks = [];
let beforeHooks = [];
let afterHooks = [];
let beforeReduceAll = [];
let afterReduceAll = [];
if (reducerObjects.length > 0) {
// remove the hooks and extend the object
for(const key in reducerObjects) {
const reducer = reducerObjects[key];
reducerMethodsWithoutHooks.push(removeHooksFromObject(reducer));
beforeHooks.push(getBeforeHooksFromObject(reducer));
afterHooks.push(getAfterHooksFromObject(reducer));
beforeReduceAll.push(getBeforeReduceHooksFromObject(reducer));
afterReduceAll.push(getAfterReduceHooksFromObject(reducer));
}
}
const composedBeforeHooks = composeReducerObjects(beforeHooks);
const composedAfterHooks = composeReducerObjects(afterHooks);
const composedBeforeReduceAll = composeReducerObjects(beforeReduceAll);
const composedAfterReduceAll = composeReducerObjects(afterReduceAll);
// combine the reducers without hooks
const combinedReducer = extendArray(reducerMethodsWithoutHooks);
const composed = composeReducerObjects([
composedBeforeReduceAll,
composedBeforeHooks,
combinedReducer,
composedAfterHooks,
composedAfterReduceAll
]);
return composed;
} | javascript | {
"resource": ""
} |
q28433 | train | function(name, fullPath, fileSystem, nativeURL) {
// remove trailing slash if it is present
if (fullPath && /\/$/.test(fullPath)) {
fullPath = fullPath.substring(0, fullPath.length - 1);
}
if (nativeURL && /\/$/.test(nativeURL)) {
nativeURL = nativeURL.substring(0, nativeURL.length - 1);
}
FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);
} | javascript | {
"resource": ""
} | |
q28434 | run | train | function run(context) {
const preferences = configPreferences.read(context);
const platforms = context.opts.cordova.platforms;
platforms.forEach(platform => {
if (platform === ANDROID) {
androidManifest.writePreferences(context, preferences);
}
if (platform === IOS) {
iosDevelopmentTeam.addDevelopmentTeam(preferences);
}
});
} | javascript | {
"resource": ""
} |
q28435 | execute | train | function execute(method, params) {
var output = !params ? [] : params;
if (method == "getStandardEvents") {
return new Promise(function promise(resolve, reject) {
resolve(standardEvent);
});
}
return new Promise(function promise(resolve, reject) {
exec(
function success(res) {
resolve(res);
},
function failure(err) {
reject(err);
},
API_CLASS,
method,
output
);
});
} | javascript | {
"resource": ""
} |
q28436 | train | function() {
this._readyState = 0;
this._error = null;
this._result = null;
this._progress = null;
this._localURL = '';
this._realReader = origFileReader ? new origFileReader() : {};
} | javascript | {
"resource": ""
} | |
q28437 | addDevelopmentTeam | train | function addDevelopmentTeam(preferences) {
const file = path.join(preferences.projectRoot, FILENAME);
let content = getBuildJson(file);
content = convertStringToJson(content);
createDefaultBuildJson(content);
updateDevelopmentTeam(content, preferences);
content = convertJsonToString(content);
setBuildJson(file, content);
} | javascript | {
"resource": ""
} |
q28438 | updateDevelopmentTeam | train | function updateDevelopmentTeam(content, preferences) {
const release = preferences.iosTeamRelease;
const debug = preferences.iosTeamDebug
? preferences.iosTeamDebug
: preferences.iosTeamRelease;
if (release === null) {
throw new Error(
'BRANCH SDK: Invalid "ios-team-release" in <branch-config> in your config.xml. Docs https://goo.gl/GijGKP'
);
}
content.ios.release.developmentTeam = release;
content.ios.debug.developmentTeam = debug;
} | javascript | {
"resource": ""
} |
q28439 | train | function (successCB, failureCB, args, env) {
var result = new PluginResult(args, env);
var response = g11n.getInstance().InvokeMethod('getPreferredLanguage', args);
var data = JSON.parse(response);
console.log('getPreferredLanguage: ' + JSON.stringify(response));
if (data.error !== undefined) {
result.error({
code: data.error.code,
message: data.error.message
});
} else {
result.ok({
value: data.result
});
}
} | javascript | {
"resource": ""
} | |
q28440 | train | function (successCB, failureCB, args, env) {
var result = new PluginResult(args, env);
var response = g11n.getInstance().InvokeMethod('getNumberPattern', args);
var data = JSON.parse(response);
console.log('getNumberPattern: ' + JSON.stringify(response));
if (data.error !== undefined) {
result.error({
code: data.error.code,
message: data.error.message
});
} else {
result.ok({
pattern: data.result.pattern,
symbol: data.result.symbol,
fraction: data.result.fraction,
rounding: data.result.rounding,
positive: data.result.positive,
negative: data.result.negative,
decimal: data.result.decimal,
grouping: data.result.grouping
});
}
} | javascript | {
"resource": ""
} | |
q28441 | train | function (date, successCB, failureCB, options) {
argscheck.checkArgs('dfFO', 'Globalization.dateToString', arguments);
var dateValue = date.valueOf();
exec(successCB, failureCB, 'Globalization', 'dateToString', [{'date': dateValue, 'options': options}]);
} | javascript | {
"resource": ""
} | |
q28442 | train | function (currencyCode, successCB, failureCB) {
argscheck.checkArgs('sfF', 'Globalization.getCurrencyPattern', arguments);
exec(successCB, failureCB, 'Globalization', 'getCurrencyPattern', [{'currencyCode': currencyCode}]);
} | javascript | {
"resource": ""
} | |
q28443 | train | function(name, localURL, type, lastModifiedDate, size){
MediaFile.__super__.constructor.apply(this, arguments);
} | javascript | {
"resource": ""
} | |
q28444 | collectEventData | train | function collectEventData(element, eventType, touches, ev) {
// find out pointerType
var pointerType = ionic.Gestures.POINTER_TOUCH;
if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) {
pointerType = ionic.Gestures.POINTER_MOUSE;
}
return {
center: ionic.Gestures.utils.getCenter(touches),
timeStamp: new Date().getTime(),
target: ev.target,
touches: touches,
eventType: eventType,
pointerType: pointerType,
srcEvent: ev,
/**
* prevent the browser default actions
* mostly used to disable scrolling of the browser
*/
preventDefault: function() {
if(this.srcEvent.preventManipulation) {
this.srcEvent.preventManipulation();
}
if(this.srcEvent.preventDefault) {
// this.srcEvent.preventDefault();
}
},
/**
* stop bubbling the event up to its parents
*/
stopPropagation: function() {
this.srcEvent.stopPropagation();
},
/**
* immediately stop gesture detection
* might be useful after a swipe was detected
* @return {*}
*/
stopDetect: function() {
return ionic.Gestures.detection.stopDetect();
}
};
} | javascript | {
"resource": ""
} |
q28445 | train | function() {
if (keyboardHasPlugin()) {
window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow );
window.removeEventListener('native.keyboardhide', keyboardFocusOut);
} else {
document.body.removeEventListener('focusout', keyboardFocusOut);
}
document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn);
document.body.removeEventListener('focusin', debouncedKeyboardFocusIn);
window.removeEventListener('orientationchange', keyboardOrientationChange);
if ( window.navigator.msPointerEnabled ) {
document.removeEventListener("MSPointerDown", keyboardInit);
} else {
document.removeEventListener('touchstart', keyboardInit);
}
ionic.keyboard.isInitialized = false;
} | javascript | {
"resource": ""
} | |
q28446 | keyboardNativeShow | train | function keyboardNativeShow(e) {
clearTimeout(keyboardFocusOutTimer);
//console.log("keyboardNativeShow fired at: " + Date.now());
//console.log("keyboardNativeshow window.innerHeight: " + window.innerHeight);
if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {
ionic.keyboard.isOpening = true;
ionic.keyboard.isClosing = false;
}
ionic.keyboard.height = e.keyboardHeight;
//console.log('nativeshow keyboard height:' + e.keyboardHeight);
if (wasOrientationChange) {
keyboardWaitForResize(keyboardUpdateViewportHeight, true);
} else {
keyboardWaitForResize(keyboardShow, true);
}
} | javascript | {
"resource": ""
} |
q28447 | keyboardFocusOut | train | function keyboardFocusOut() {
clearTimeout(keyboardFocusOutTimer);
//console.log("keyboardFocusOut fired at: " + Date.now());
//console.log("keyboardFocusOut event type: " + e.type);
if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) {
ionic.keyboard.isClosing = true;
ionic.keyboard.isOpening = false;
}
// Call keyboardHide with a slight delay because sometimes on focus or
// orientation change focusin is called immediately after, so we give it time
// to cancel keyboardHide
keyboardFocusOutTimer = setTimeout(function() {
ionic.requestAnimationFrame(function() {
// focusOut during or right after an orientationchange, so we didn't get
// a chance to update the viewport height yet, do it and keyboardHide
//console.log("focusOut, wasOrientationChange: " + wasOrientationChange);
if (wasOrientationChange) {
keyboardWaitForResize(function(){
keyboardUpdateViewportHeight();
keyboardHide();
}, false);
} else {
keyboardWaitForResize(keyboardHide, false);
}
});
}, 50);
} | javascript | {
"resource": ""
} |
q28448 | keyboardOrientationChange | train | function keyboardOrientationChange() {
//console.log("orientationchange fired at: " + Date.now());
//console.log("orientation was: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
// toggle orientation
ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape;
// //console.log("now orientation is: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
// no need to wait for resizing on iOS, and orientationchange always fires
// after the keyboard has opened, so it doesn't matter if it's open or not
if (ionic.Platform.isIOS()) {
keyboardUpdateViewportHeight();
}
// On Android, if the keyboard isn't open or we aren't using the keyboard
// plugin, update the viewport height once everything has resized. If the
// keyboard is open and we are using the keyboard plugin do nothing and let
// nativeShow handle it using an accurate keyboard height.
if ( ionic.Platform.isAndroid()) {
if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) {
keyboardWaitForResize(keyboardUpdateViewportHeight, false);
} else {
wasOrientationChange = true;
}
}
} | javascript | {
"resource": ""
} |
q28449 | keyboardShow | train | function keyboardShow() {
ionic.keyboard.isOpen = true;
ionic.keyboard.isOpening = false;
var details = {
keyboardHeight: keyboardGetHeight(),
viewportHeight: keyboardCurrentViewportHeight
};
if (keyboardActiveElement) {
details.target = keyboardActiveElement;
var elementBounds = keyboardActiveElement.getBoundingClientRect();
details.elementTop = Math.round(elementBounds.top);
details.elementBottom = Math.round(elementBounds.bottom);
details.windowHeight = details.viewportHeight - details.keyboardHeight;
//console.log("keyboardShow viewportHeight: " + details.viewportHeight +
//", windowHeight: " + details.windowHeight +
//", keyboardHeight: " + details.keyboardHeight);
// figure out if the element is under the keyboard
details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight);
//console.log("isUnderKeyboard: " + details.isElementUnderKeyboard);
//console.log("elementBottom: " + details.elementBottom);
// send event so the scroll view adjusts
ionic.trigger('scrollChildIntoView', details, true);
}
setTimeout(function(){
document.body.classList.add(KEYBOARD_OPEN_CSS);
}, 400);
return details; //for testing
} | javascript | {
"resource": ""
} |
q28450 | train | function(touches, timeStamp) {
var self = this;
// remember if the deceleration was just stopped
self.__decStopped = !!(self.__isDecelerating || self.__isAnimating);
self.hintResize();
if (timeStamp instanceof Date) {
timeStamp = timeStamp.valueOf();
}
if (typeof timeStamp !== "number") {
timeStamp = Date.now();
}
// Reset interruptedAnimation flag
self.__interruptedAnimation = true;
// Stop deceleration
if (self.__isDecelerating) {
zyngaCore.effect.Animate.stop(self.__isDecelerating);
self.__isDecelerating = false;
self.__interruptedAnimation = true;
}
// Stop animation
if (self.__isAnimating) {
zyngaCore.effect.Animate.stop(self.__isAnimating);
self.__isAnimating = false;
self.__interruptedAnimation = true;
}
// Use center point when dealing with two fingers
var currentTouchLeft, currentTouchTop;
var isSingleTouch = touches.length === 1;
if (isSingleTouch) {
currentTouchLeft = touches[0].pageX;
currentTouchTop = touches[0].pageY;
} else {
currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
}
// Store initial positions
self.__initialTouchLeft = currentTouchLeft;
self.__initialTouchTop = currentTouchTop;
// Store initial touchList for scale calculation
self.__initialTouches = touches;
// Store current zoom level
self.__zoomLevelStart = self.__zoomLevel;
// Store initial touch positions
self.__lastTouchLeft = currentTouchLeft;
self.__lastTouchTop = currentTouchTop;
// Store initial move time stamp
self.__lastTouchMove = timeStamp;
// Reset initial scale
self.__lastScale = 1;
// Reset locking flags
self.__enableScrollX = !isSingleTouch && self.options.scrollingX;
self.__enableScrollY = !isSingleTouch && self.options.scrollingY;
// Reset tracking flag
self.__isTracking = true;
// Reset deceleration complete flag
self.__didDecelerationComplete = false;
// Dragging starts directly with two fingers, otherwise lazy with an offset
self.__isDragging = !isSingleTouch;
// Some features are disabled in multi touch scenarios
self.__isSingleTouch = isSingleTouch;
// Clearing data structure
self.__positions = [];
} | javascript | {
"resource": ""
} | |
q28451 | train | function(left, top, animate) {
var self = this;
if (!animate) {
self.el.scrollTop = top;
self.el.scrollLeft = left;
self.resize();
return;
}
var oldOverflowX = self.el.style.overflowX;
var oldOverflowY = self.el.style.overflowY;
clearTimeout(self.__scrollToCleanupTimeout);
self.__scrollToCleanupTimeout = setTimeout(function() {
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
}, 500);
self.el.style.overflowY = 'hidden';
self.el.style.overflowX = 'hidden';
animateScroll(top, left);
function animateScroll(Y, X) {
// scroll animation loop w/ easing
// credit https://gist.github.com/dezinezync/5487119
var start = Date.now(),
duration = 250, //milliseconds
fromY = self.el.scrollTop,
fromX = self.el.scrollLeft;
if (fromY === Y && fromX === X) {
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
self.resize();
return; /* Prevent scrolling to the Y point if already there */
}
// decelerating to zero velocity
function easeOutCubic(t) {
return (--t) * t * t + 1;
}
// scroll loop
function animateScrollStep() {
var currentTime = Date.now(),
time = Math.min(1, ((currentTime - start) / duration)),
// where .5 would be 50% of time on a linear scale easedT gives a
// fraction based on the easing method
easedT = easeOutCubic(time);
if (fromY != Y) {
self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10);
}
if (fromX != X) {
self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10);
}
if (time < 1) {
ionic.requestAnimationFrame(animateScrollStep);
} else {
// done
ionic.tap.removeClonedInputs(self.__container, self);
self.el.style.overflowX = oldOverflowX;
self.el.style.overflowY = oldOverflowY;
self.resize();
}
}
// start scroll loop
ionic.requestAnimationFrame(animateScrollStep);
}
} | javascript | {
"resource": ""
} | |
q28452 | train | function() {
this.el = this.listEl = this.scrollEl = this.scrollView = null;
// ensure no scrolls have been left frozen
if (this.isScrollFreeze) {
self.scrollView.freeze(false);
}
} | javascript | {
"resource": ""
} | |
q28453 | train | function(isInstant) {
if (this._lastDragOp) {
this._lastDragOp.clean && this._lastDragOp.clean(isInstant);
this._lastDragOp.deregister && this._lastDragOp.deregister();
this._lastDragOp = null;
}
} | javascript | {
"resource": ""
} | |
q28454 | compilationGenerator | train | function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
var compiled;
if (eager) {
return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
}
return function lazyCompilation() {
if (!compiled) {
compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
// Null out all of these references in order to make them eligible for garbage collection
// since this is a potentially long lived closure
$compileNodes = transcludeFn = previousCompileContext = null;
}
return compiled.apply(this, arguments);
};
} | javascript | {
"resource": ""
} |
q28455 | roundNumber | train | function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
var digits = parsedNumber.d;
var fractionLen = digits.length - parsedNumber.i;
// determine fractionSize if it is not specified; `+fractionSize` converts it to a number
fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
// The index of the digit to where rounding is to occur
var roundAt = fractionSize + parsedNumber.i;
var digit = digits[roundAt];
if (roundAt > 0) {
// Drop fractional digits beyond `roundAt`
digits.splice(Math.max(parsedNumber.i, roundAt));
// Set non-fractional digits beyond `roundAt` to 0
for (var j = roundAt; j < digits.length; j++) {
digits[j] = 0;
}
} else {
// We rounded to zero so reset the parsedNumber
fractionLen = Math.max(0, fractionLen);
parsedNumber.i = 1;
digits.length = Math.max(1, roundAt = fractionSize + 1);
digits[0] = 0;
for (var i = 1; i < roundAt; i++) digits[i] = 0;
}
if (digit >= 5) {
if (roundAt - 1 < 0) {
for (var k = 0; k > roundAt; k--) {
digits.unshift(0);
parsedNumber.i++;
}
digits.unshift(1);
parsedNumber.i++;
} else {
digits[roundAt - 1]++;
}
}
// Pad out with zeros to get the required fraction length
for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
// Do any carrying, e.g. a digit was rounded up to 10
var carry = digits.reduceRight(function(carry, d, i, digits) {
d = d + carry;
digits[i] = d % 10;
return Math.floor(d / 10);
}, 0);
if (carry) {
digits.unshift(carry);
parsedNumber.i++;
}
} | javascript | {
"resource": ""
} |
q28456 | train | function(scope, $element, attrs, ctrl, $transclude) {
var previousElement, previousScope;
scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
if (previousElement) {
$animate.leave(previousElement);
}
if (previousScope) {
previousScope.$destroy();
previousScope = null;
}
if (value || value === 0) {
previousScope = scope.$new();
$transclude(previousScope, function(element) {
previousElement = element;
$animate.enter(element, null, $element);
});
}
});
} | javascript | {
"resource": ""
} | |
q28457 | run | train | function run() {
var template;
$ionicTemplateCache._runCount++;
hasRun = true;
// ignore if race condition already zeroed out array
if (toCache.length === 0) return;
var i = 0;
while (i < 4 && (template = toCache.pop())) {
// note that inline templates are ignored by this request
if (isString(template)) $http.get(template, { cache: $templateCache });
i++;
}
// only preload 3 templates a second
if (toCache.length) {
$timeout(run, 1000);
}
} | javascript | {
"resource": ""
} |
q28458 | checkInfiniteBounds | train | function checkInfiniteBounds() {
if (self.isLoading) return;
var maxScroll = {};
if (self.jsScrolling) {
maxScroll = self.getJSMaxScroll();
var scrollValues = self.scrollView.getValues();
if ((maxScroll.left !== -1 && scrollValues.left >= maxScroll.left) ||
(maxScroll.top !== -1 && scrollValues.top >= maxScroll.top)) {
onInfinite();
}
} else {
maxScroll = self.getNativeMaxScroll();
if ((
maxScroll.left !== -1 &&
self.scrollEl.scrollLeft >= maxScroll.left - self.scrollEl.clientWidth
) || (
maxScroll.top !== -1 &&
self.scrollEl.scrollTop >= maxScroll.top - self.scrollEl.clientHeight
)) {
onInfinite();
}
}
} | javascript | {
"resource": ""
} |
q28459 | calculateMaxValue | train | function calculateMaxValue(maximum) {
var distance = ($attrs.distance || '2.5%').trim();
var isPercent = distance.indexOf('%') !== -1;
return isPercent ?
maximum * (1 - parseFloat(distance) / 100) :
maximum - parseFloat(distance);
} | javascript | {
"resource": ""
} |
q28460 | train | function(newWidth, newHeight) {
var requiresRefresh = self.dataLength && newWidth && newHeight &&
(newWidth !== self.width || newHeight !== self.height);
self.width = newWidth;
self.height = newHeight;
return !!requiresRefresh;
} | javascript | {
"resource": ""
} | |
q28461 | train | function(newData) {
var requiresRefresh = newData.length > 0 || newData.length < self.dataLength;
self.dataLength = newData.length;
return !!requiresRefresh;
} | javascript | {
"resource": ""
} | |
q28462 | toggleElements | train | function toggleElements() {
// convert arguments to array
var args = Array.prototype.slice.call(arguments);
args.forEach(function(buttonId) {
var buttonEl = document.getElementById(buttonId);
if (buttonEl) {
var curDisplayStyle = buttonEl.style.display;
buttonEl.style.display = curDisplayStyle === 'none' ? 'block' : 'none';
}
});
} | javascript | {
"resource": ""
} |
q28463 | startCameraPreview | train | function startCameraPreview(takeCallback, errorCallback, selectCallback, retakeCallback) {
// try to select appropriate device for capture
// rear camera is preferred option
var expectedPanel = Windows.Devices.Enumeration.Panel.back;
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) {
if (devices.length > 0) {
devices.forEach(function (currDev) {
if (currDev.enclosureLocation && currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
captureSettings.videoDeviceId = currDev.id;
}
});
capture.initializeAsync(captureSettings).done(function () {
// This is necessary since WP8.1 MediaCapture outputs video stream rotated 90 degrees CCW
// TODO: This can be not consistent across devices, need additional testing on various devices
// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
capture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
capturePreview.msZoom = true;
capturePreview.src = URL.createObjectURL(capture);
capturePreview.play();
previewContainer.style.display = 'block';
// Bind events to controls
capturePreview.onclick = takeCallback;
document.getElementById('takePicture').onclick = takeCallback;
document.getElementById('cancelCapture').onclick = function () {
errorCallback(CaptureError.CAPTURE_NO_MEDIA_FILES);
};
document.getElementById('selectPicture').onclick = selectCallback;
document.getElementById('retakePicture').onclick = retakeCallback;
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
} else {
// no appropriate devices found
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR);
}
});
} | javascript | {
"resource": ""
} |
q28464 | destroyCameraPreview | train | function destroyCameraPreview() {
capturePreview.pause();
capturePreview.src = null;
if (previewContainer) {
document.body.removeChild(previewContainer);
}
if (capture) {
capture.stopRecordAsync();
capture = null;
}
} | javascript | {
"resource": ""
} |
q28465 | train | function (successCallback, errorCallback) {
try {
createCameraUI();
startCameraPreview(function () {
// This callback called twice: whem video capture started and when it ended
// so we need to check capture status
if (!captureStarted) {
// remove cancel button and rename 'Take' button to 'Stop'
toggleElements('cancelCapture');
document.getElementById('takePicture').text = 'Stop';
var encodingProperties = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(Windows.Media.MediaProperties.VideoEncodingQuality.auto),
generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
localFolder.createFileAsync("cameraCaptureVideo.mp4", generateUniqueCollisionOption).done(function(capturedFile) {
capture.startRecordToStorageFileAsync(encodingProperties, capturedFile).done(function() {
capturedVideoFile = capturedFile;
captureStarted = true;
}, function(err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function(err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
} else {
capture.stopRecordAsync().done(function () {
destroyCameraPreview();
successCallback(capturedVideoFile);
});
}
}, errorCallback);
} catch (ex) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
}
} | javascript | {
"resource": ""
} | |
q28466 | train | function (successCallback, errorCallback) {
try {
createCameraUI();
startCameraPreview(
// Callback for Take button - captures intermediate image file.
function () {
var encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(),
overwriteCollisionOption = Windows.Storage.CreationCollisionOption.replaceExisting,
tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
tempFolder.createFileAsync("cameraCaptureImage.jpg", overwriteCollisionOption).done(function (capturedFile) {
capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () {
// store intermediate result in object's global variable
capturedPictureFile = capturedFile;
// show pre-captured image and toggle visibility of all buttons
previewContainer.style.backgroundImage = 'url("' + 'ms-appdata:///temp/' + capturedFile.name + '")';
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
},
// error + cancel callback
function (err) {
destroyCameraPreview();
errorCallback(err);
},
// Callback for Select button - copies intermediate file into persistent application's storage
function () {
var generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
capturedPictureFile.copyAsync(localFolder, capturedPictureFile.name, generateUniqueCollisionOption).done(function (copiedFile) {
destroyCameraPreview();
successCallback(copiedFile);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
},
// Callback for retake button - just toggles visibility of necessary elements
function () {
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}
);
} catch (ex) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
}
} | javascript | {
"resource": ""
} | |
q28467 | train | function () {
var encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(),
overwriteCollisionOption = Windows.Storage.CreationCollisionOption.replaceExisting,
tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
tempFolder.createFileAsync("cameraCaptureImage.jpg", overwriteCollisionOption).done(function (capturedFile) {
capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () {
// store intermediate result in object's global variable
capturedPictureFile = capturedFile;
// show pre-captured image and toggle visibility of all buttons
previewContainer.style.backgroundImage = 'url("' + 'ms-appdata:///temp/' + capturedFile.name + '")';
toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
}, function (err) {
destroyCameraPreview();
errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
});
} | javascript | {
"resource": ""
} | |
q28468 | train | function () {
var generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
localFolder = Windows.Storage.ApplicationData.current.localFolder;
capturedPictureFile.copyAsync(localFolder, capturedPictureFile.name, generateUniqueCollisionOption).done(function (copiedFile) {
destroyCameraPreview();
successCallback(copiedFile);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
} | javascript | {
"resource": ""
} | |
q28469 | run | train | function run(context) {
const preferences = configPreferences.read(context);
const platforms = context.opts.cordova.platforms;
platforms.forEach(platform => {
if (platform === IOS) {
iosPlist.addBranchSettings(preferences);
iosCapabilities.enableAssociatedDomains(preferences);
iosAssociatedDomains.addAssociatedDomains(preferences);
}
});
} | javascript | {
"resource": ""
} |
q28470 | writePreferences | train | function writePreferences(context, preferences) {
// read manifest
const manifest = getManifest(context);
// update manifest
manifest.file = updateBranchMetaData(manifest.file, preferences);
manifest.file = updateBranchReferrerTracking(manifest.file);
manifest.file = updateLaunchOptionToSingleTask(
manifest.file,
manifest.mainActivityIndex
);
manifest.file = updateBranchURIScheme(
manifest.file,
manifest.mainActivityIndex,
preferences
);
manifest.file = updateBranchAppLinks(
manifest.file,
manifest.mainActivityIndex,
preferences,
manifest.targetSdk
);
// save manifest
xmlHelper.writeJsonAsXml(manifest.path, manifest.file);
} | javascript | {
"resource": ""
} |
q28471 | getManifest | train | function getManifest(context) {
let pathToManifest;
let manifest;
try {
// cordova platform add android@6.0.0
pathToManifest = path.join(
context.opts.projectRoot,
"platforms",
"android",
"AndroidManifest.xml"
);
manifest = xmlHelper.readXmlAsJson(pathToManifest);
} catch (e) {
try {
// cordova platform add android@7.0.0
pathToManifest = path.join(
context.opts.projectRoot,
"platforms",
"android",
"app",
"src",
"main",
"AndroidManifest.xml"
);
manifest = xmlHelper.readXmlAsJson(pathToManifest);
} catch (e) {
throw new Error(`BRANCH SDK: Cannot read AndroidManfiest.xml ${e}`);
}
}
const mainActivityIndex = getMainLaunchActivityIndex(
manifest.manifest.application[0].activity
);
const targetSdk =
manifest.manifest["uses-sdk"][0].$["android:targetSdkVersion"];
return {
file: manifest,
path: pathToManifest,
mainActivityIndex: mainActivityIndex,
targetSdk: targetSdk
};
} | javascript | {
"resource": ""
} |
q28472 | train | function(file) {
this.fileName = "";
this.length = 0;
if (file) {
this.localURL = file.localURL || file;
this.length = file.size || 0;
}
// default is to write at the beginning of the file
this.position = 0;
this.readyState = 0; // EMPTY
this.result = null;
// Error
this.error = null;
// Event handlers
this.onwritestart = null; // When writing starts
this.onprogress = null; // While writing the file, and reporting partial file data
this.onwrite = null; // When the write has successfully completed.
this.onwriteend = null; // When the request has completed (either in success or failure).
this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
this.onerror = null; // When the write has failed (see errors).
} | javascript | {
"resource": ""
} | |
q28473 | makeCallbackButton | train | function makeCallbackButton (labelIndex) {
return function () {
if (modalWindow) {
modalWindow.removeEventListener('unload', onUnload, false);
modalWindow.close();
}
// checking if prompt
var promptInput = modalDocument.getElementById('prompt-input');
var response;
if (promptInput) {
response = {
input1: promptInput.value,
buttonIndex: labelIndex
};
}
response = response || labelIndex;
callback(response);
};
} | javascript | {
"resource": ""
} |
q28474 | enableAssociatedDomains | train | function enableAssociatedDomains(preferences) {
const entitlementsFile = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
"Resources",
`${preferences.projectName}.entitlements`
);
activateAssociativeDomains(
preferences.iosProjectModule.xcode,
entitlementsFile
);
addPbxReference(preferences.iosProjectModule.xcode, entitlementsFile);
preferences.iosProjectModule.write();
} | javascript | {
"resource": ""
} |
q28475 | activateAssociativeDomains | train | function activateAssociativeDomains(xcodeProject, entitlementsFile) {
const configurations = removeComments(
xcodeProject.pbxXCBuildConfigurationSection()
);
let config;
let buildSettings;
for (config in configurations) {
buildSettings = configurations[config].buildSettings;
buildSettings.CODE_SIGN_IDENTITY = `"${CODESIGNIDENTITY}"`;
buildSettings.CODE_SIGN_ENTITLEMENTS = `"${entitlementsFile}"`;
// if deployment target is less then the required one - increase it
if (buildSettings.IPHONEOS_DEPLOYMENT_TARGET) {
const buildDeploymentTarget = buildSettings.IPHONEOS_DEPLOYMENT_TARGET.toString();
if (compare(buildDeploymentTarget, IOS_DEPLOYMENT_TARGET) === -1) {
buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IOS_DEPLOYMENT_TARGET;
}
} else {
buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IOS_DEPLOYMENT_TARGET;
}
}
} | javascript | {
"resource": ""
} |
q28476 | removeComments | train | function removeComments(obj) {
const keys = Object.keys(obj);
const newObj = {};
for (let i = 0, len = keys.length; i < len; i++) {
if (!COMMENT_KEY.test(keys[i])) {
newObj[keys[i]] = obj[keys[i]];
}
}
return newObj;
} | javascript | {
"resource": ""
} |
q28477 | install | train | function install(context) {
// set properties
const q = context.requireCordovaModule("q");
var async = new q.defer(); // eslint-disable-line
const installFlagLocation = path.join(
context.opts.projectRoot,
"plugins",
context.opts.plugin.id,
INSTALLFLAGNAME
);
const dependencies = require(path.join(
context.opts.projectRoot,
"plugins",
context.opts.plugin.id,
"package.json"
)).dependencies;
// only run once
if (getPackageInstalled(installFlagLocation)) return;
// install node modules
const modules = getNodeModulesToInstall(dependencies);
if (modules.length === 0) return async.promise;
installNodeModules(modules, () => {
// only run once
setPackageInstalled(installFlagLocation);
removeEtcDirectory();
async.resolve();
});
// wait until callbacks from the all the npm install complete
return async.promise;
} | javascript | {
"resource": ""
} |
q28478 | installNodeModules | train | function installNodeModules(modules, callback) {
// base case
if (modules.length <= 0) {
return callback();
}
// install one at a time
const module = modules.pop();
console.log(`BRANCH SDK: Installing node dependency ${module}`);
const install = `npm install --prefix ./plugins/${SDK} -D ${module}`;
exec(install, (err, stdout, stderr) => {
// handle error
if (err) {
throw new Error(
`BRANCH SDK: Failed to install Branch node dependency ${module}. Docs https://goo.gl/GijGKP`
);
} else {
// next module
installNodeModules(modules, callback);
}
});
} | javascript | {
"resource": ""
} |
q28479 | getNodeModulesToInstall | train | function getNodeModulesToInstall(dependencies) {
const modules = [];
for (const module in dependencies) {
if (dependencies.hasOwnProperty(module)) {
try {
require(module);
} catch (err) {
modules.push(module);
}
}
}
return modules;
} | javascript | {
"resource": ""
} |
q28480 | showCameraDialog | train | function showCameraDialog (done, cancel, fail) {
var wv = qnx.webplatform.createWebView(function () {
wv.url = 'local:///chrome/camera.html';
wv.allowQnxObject = true;
wv.allowRpc = true;
wv.zOrder = 1;
wv.setGeometry(0, 0, screen.width, screen.height);
wv.backgroundColor = 0x00000000;
wv.active = true;
wv.visible = true;
wv.on('UserMediaRequest', function (evt, args) {
wv.allowUserMedia(JSON.parse(args).id, 'CAMERA_UNIT_REAR');
});
wv.on('JavaScriptCallback', function (evt, data) {
var args = JSON.parse(data).args;
if (args[0] === 'cordova-plugin-camera') {
if (args[1] === 'cancel') {
cancel('User canceled');
} else if (args[1] === 'error') {
fail(args[2]);
} else {
saveImage(args[1], done, fail);
}
wv.un('JavaScriptCallback', arguments.callee);
wv.visible = false;
wv.destroy();
qnx.webplatform.getApplication().unlockRotation();
}
});
wv.on('Destroyed', function () {
wv.delete();
});
qnx.webplatform.getApplication().lockRotation();
qnx.webplatform.getController().dispatchEvent('webview.initialized', [wv]);
});
} | javascript | {
"resource": ""
} |
q28481 | saveImage | train | function saveImage(data, success, fail) {
var name = savePath + imgName();
require('lib/webview').setSandbox(false);
window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) {
fs.root.getFile(name, { create: true }, function (entry) {
entry.createWriter(function (writer) {
writer.onwriteend = function () {
success(name);
};
writer.onerror = fail;
writer.write(dataURItoBlob(data));
});
}, fail);
}, fail);
} | javascript | {
"resource": ""
} |
q28482 | addAssociatedDomains | train | function addAssociatedDomains(preferences) {
const files = getEntitlementFiles(preferences);
for (let i = 0; i < files.length; i++) {
const file = files[i];
let entitlements = getEntitlements(file);
entitlements = updateEntitlements(entitlements, preferences);
setEntitlements(file, entitlements);
}
} | javascript | {
"resource": ""
} |
q28483 | getEntitlementFiles | train | function getEntitlementFiles(preferences) {
const files = [];
const entitlements = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
"Resources",
`${preferences.projectName}.entitlements`
);
files.push(
path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
`${preferences.projectName}.entitlements`
)
);
files.push(entitlements);
for (let i = 0; i < BUILD_TYPES.length; i++) {
const buildType = BUILD_TYPES[i];
const plist = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
`Entitlements-${buildType}.plist`
);
files.push(plist);
}
return files;
} | javascript | {
"resource": ""
} |
q28484 | updateAssociatedDomains | train | function updateAssociatedDomains(preferences) {
const domainList = [];
const prefix = "applinks:";
const linkDomains = preferences.linkDomain;
for (let i = 0; i < linkDomains.length; i++) {
const linkDomain = linkDomains[i];
// add link domain to associated domain
domainList.push(prefix + linkDomain);
// app.link link domains need -alternate associated domains as well (for Deep Views)
if (linkDomain.indexOf("app.link") !== -1) {
const first = linkDomain.split(".")[0];
const second = linkDomain.split(".")[1];
const rest = linkDomain
.split(".")
.slice(2)
.join(".");
const alternate = `${first}-alternate`;
domainList.push(`${prefix + alternate}.${second}.${rest}`);
}
}
return domainList;
} | javascript | {
"resource": ""
} |
q28485 | train | function () {
window.removeEventListener("focus", savePhotoOnFocus);
// call only when the app is in focus again
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
} | javascript | {
"resource": ""
} | |
q28486 | train | function (id, name, version, installed) {
this.id = id;
this.name = name;
this.installed = installed || false;
this.metadata = {
version: version
};
} | javascript | {
"resource": ""
} | |
q28487 | train | function (type, data, bNoDetach) {
var evt = createEvent(type, data);
if (typeof documentEventHandlers[type] !== 'undefined') {
if (bNoDetach) {
documentEventHandlers[type].fire(evt);
} else {
setTimeout(function () {
// Fire deviceready on listeners that were registered before cordova.js was loaded.
if (type === 'deviceready') {
document.dispatchEvent(evt);
}
documentEventHandlers[type].fire(evt);
}, 0);
}
} else {
document.dispatchEvent(evt);
}
} | javascript | {
"resource": ""
} | |
q28488 | train | function (callbackId, args) {
cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
} | javascript | {
"resource": ""
} | |
q28489 | train | function (callbackId, args) {
// TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
// Derive success from status.
cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
} | javascript | {
"resource": ""
} | |
q28490 | recursiveMerge | train | function recursiveMerge (target, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
if (target.prototype && target.prototype.constructor === target) {
// If the target object is a constructor override off prototype.
clobber(target.prototype, prop, src[prop]);
} else {
if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
recursiveMerge(target[prop], src[prop]);
} else {
clobber(target, prop, src[prop]);
}
}
}
}
} | javascript | {
"resource": ""
} |
q28491 | train | function (type, sticky) {
this.type = type;
// Map of guid -> function.
this.handlers = {};
// 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
this.state = sticky ? 1 : 0;
// Used in sticky mode to remember args passed to fire().
this.fireArgs = null;
// Used by onHasSubscribersChange to know if there are any listeners.
this.numHandlers = 0;
// Function that is called when the first listener is subscribed, or when
// the last listener is unsubscribed.
this.onHasSubscribersChange = null;
} | javascript | {
"resource": ""
} | |
q28492 | train | function (h, c) {
var len = c.length;
var i = len;
var f = function () {
if (!(--i)) h();
};
for (var j = 0; j < len; j++) {
if (c[j].state === 0) {
throw Error('Can only use join with sticky channels.');
}
c[j].subscribe(f);
}
if (!len) h();
} | javascript | {
"resource": ""
} | |
q28493 | handlePluginsObject | train | function handlePluginsObject (moduleList) {
// if moduleList is not defined or empty, we've nothing to do
if (!moduleList || !moduleList.length) {
return;
}
// Loop through all the modules and then through their clobbers and merges.
for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign
if (module.clobbers && module.clobbers.length) {
for (var j = 0; j < module.clobbers.length; j++) {
modulemapper.clobbers(module.id, module.clobbers[j]);
}
}
if (module.merges && module.merges.length) {
for (var k = 0; k < module.merges.length; k++) {
modulemapper.merges(module.id, module.merges[k]);
}
}
// Finally, if runs is truthy we want to simply require() the module.
if (module.runs) {
modulemapper.runs(module.id);
}
}
} | javascript | {
"resource": ""
} |
q28494 | createPromptDialog | train | function createPromptDialog (title, message, buttons, defaultText, callback) {
var isPhone = cordova.platformId === 'windows' && WinJS.Utilities.isPhone;
var isWindows = !!cordova.platformId.match(/windows/);
createCSSElem('notification.css');
var dlgWrap = document.createElement('div');
dlgWrap.className = 'dlgWrap';
var dlg = document.createElement('div');
dlg.className = 'dlgContainer';
if (isWindows) {
dlg.className += ' dlgContainer-windows';
} else if (isPhone) {
dlg.className += ' dlgContainer-phone';
}
// dialog layout template
dlg.innerHTML = _cleanHtml("<span id='lbl-title'></span><br/>" + // title
"<span id='lbl-message'></span><br/>" + // message
"<input id='prompt-input'/><br/>"); // input fields
dlg.querySelector('#lbl-title').appendChild(document.createTextNode(title));
dlg.querySelector('#lbl-message').appendChild(document.createTextNode(message));
dlg.querySelector('#prompt-input').setAttribute('placeholder', defaultText);
dlg.querySelector('#prompt-input').setAttribute('value', defaultText);
function makeButtonCallback (idx) {
return function () {
var value = dlg.querySelector('#prompt-input').value || defaultText;
dlgWrap.parentNode.removeChild(dlgWrap);
if (callback) {
callback({ input1: value, buttonIndex: idx }); // eslint-disable-line standard/no-callback-literal
}
};
}
function addButton (idx, label) {
var button = document.createElement('button');
button.className = 'dlgButton';
button.tabIndex = idx;
button.onclick = makeButtonCallback(idx + 1);
if (idx === 0) {
button.className += ' dlgButtonFirst';
}
button.appendChild(document.createTextNode(label));
dlg.appendChild(button);
}
// reverse order is used since we align buttons to the right
for (var idx = buttons.length - 1; idx >= 0; idx--) {
addButton(idx, buttons[idx]);
}
dlgWrap.appendChild(dlg);
document.body.appendChild(dlgWrap);
// make sure input field is under focus
dlg.querySelector('#prompt-input').select();
// add Enter/Return key handling
var defaultButton = dlg.querySelector('.dlgButtonFirst');
dlg.addEventListener('keypress', function (e) {
if (e.keyCode === 13) { // enter key
if (defaultButton) {
defaultButton.click();
}
}
});
return dlgWrap;
} | javascript | {
"resource": ""
} |
q28495 | readXmlAsJson | train | function readXmlAsJson(file) {
let xmlData;
let xmlParser;
let parsedData;
try {
xmlData = fs.readFileSync(file);
xmlParser = new xml2js.Parser();
xmlParser.parseString(xmlData, (err, data) => {
if (!err && data) {
parsedData = data;
}
});
} catch (err) {
throw new Error(`BRANCH SDK: Cannot write file ${file}`);
}
return parsedData;
} | javascript | {
"resource": ""
} |
q28496 | writeJsonAsXml | train | function writeJsonAsXml(file, content, options) {
const xmlBuilder = new xml2js.Builder(options);
const changedXmlData = xmlBuilder.buildObject(content);
let isSaved = true;
try {
fs.writeFileSync(file, changedXmlData);
} catch (err) {
isSaved = false;
throw new Error(`BRANCH SDK: Cannot write file ${file}`);
}
return isSaved;
} | javascript | {
"resource": ""
} |
q28497 | relativeParts | train | function relativeParts (seconds) {
seconds = Math.abs(seconds);
var descriptors = {};
var units = [
'years', 86400 * 365,
'months', 86400 * 30,
'weeks', 86400 * 7,
'days', 86400,
'hours', 3600,
'minutes', 60
];
if (seconds < 60) {
return {
minutes: Math.round(seconds / 60)
};
}
for (var i = 0, uLen = units.length; i < uLen; i += 2) {
var value = units[i + 1];
if (seconds >= value) {
descriptors[units[i]] = Math.floor(seconds / value);
seconds -= descriptors[units[i]] * value;
}
}
return descriptors;
} | javascript | {
"resource": ""
} |
q28498 | prettyDate | train | function prettyDate (time, useCompactFormat, maxDiff) {
maxDiff = maxDiff || 86400 * 10; // default = 10 days
switch (time.constructor) {
case String: // timestamp
time = parseInt(time);
break;
case Date:
time = time.getTime();
break;
}
var secDiff = (Date.now() - time) / 1000;
if (isNaN(secDiff)) {
return _('incorrectDate');
}
if (Math.abs(secDiff) > 60) {
// round milliseconds up if difference is over 1 minute so the result is
// closer to what the user would expect (1h59m59s300ms diff should return
// "in 2 hours" instead of "in an hour")
secDiff = secDiff > 0 ? Math.ceil(secDiff) : Math.floor(secDiff);
}
if (secDiff > maxDiff) {
return localeFormat(new Date(time), '%x');
}
var f = useCompactFormat ? '-short' : '-long';
var parts = relativeParts(secDiff);
var affix = secDiff >= 0 ? '-ago' : '-until';
for (var i in parts) {
return _(i + affix + f, { value: parts[i] });
}
} | javascript | {
"resource": ""
} |
q28499 | resolve | train | function resolve(success, fail, path, fsType, sandbox, options, size) {
options = options || { create: false };
size = size || info.MAX_SIZE;
if (size > info.MAX_SIZE) {
//bb10 does not respect quota; fail at unreasonably large size
fail(FileError.QUOTA_EXCEEDED_ERR);
} else if (path.indexOf(':') > -1) {
//files with : character are not valid in Cordova apps
fail(FileError.ENCODING_ERR);
} else {
requestAnimationFrame(function () {
cordova.exec(function () {
requestAnimationFrame(function () {
resolveNative(success, fail, path, fsType, options, size);
});
}, fail, 'File', 'setSandbox', [sandbox], false);
});
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.