_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q54400
|
hasPipeDataListeners
|
train
|
function hasPipeDataListeners (stream) {
var listeners = stream.listeners('data')
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].name === 'ondata') {
return true
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q54401
|
unpipe
|
train
|
function unpipe (stream) {
if (!stream) {
throw new TypeError('argument stream is required')
}
if (typeof stream.unpipe === 'function') {
// new-style
stream.unpipe()
return
}
// Node.js 0.8 hack
if (!hasPipeDataListeners(stream)) {
return
}
var listener
var listeners = stream.listeners('close')
for (var i = 0; i < listeners.length; i++) {
listener = listeners[i]
if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
continue
}
// invoke the listener
listener.call(stream)
}
}
|
javascript
|
{
"resource": ""
}
|
q54402
|
makeStatsD
|
train
|
function makeStatsD(options, logger) {
let statsd;
const srvName = options._prefix ? options._prefix : normalizeName(options.name);
const statsdOptions = {
host: options.host,
port: options.port,
prefix: `${srvName}.`,
suffix: '',
globalize: false,
cacheDns: false,
mock: false
};
// Batch metrics unless `batch` option is `false`
if (typeof options.batch !== 'boolean' || options.batch) {
options.batch = options.batch || {};
statsdOptions.maxBufferSize = options.batch.max_size || DEFAULT_MAX_BATCH_SIZE;
statsdOptions.bufferFlushInterval = options.batch.max_delay || 1000;
}
if (options.type === 'log') {
statsd = new LogStatsD(logger, srvName);
} else {
statsd = new StatsD(statsdOptions);
}
// Support creating sub-metric clients with a fixed prefix. This is useful
// for systematically categorizing metrics per-request, by using a
// specific logger.
statsd.makeChild = (name) => {
const child = statsd.childClient();
// We can't use the prefix in clientOptions,
// because it will be prepended to existing prefix.
child.prefix = statsd.prefix + normalizeName(name) + '.';
// Attach normalizeName to make the childClient instance backwards-compatible
// with the previously used StatsD instance
child.normalizeName = normalizeName;
return child;
};
// Add a static utility method for stat name normalization
statsd.normalizeName = normalizeName;
return statsd;
}
|
javascript
|
{
"resource": ""
}
|
q54403
|
promisedSpawn
|
train
|
function promisedSpawn(args, options) {
options = options || {};
let promise = new P((resolve, reject) => {
const argOpts = options.capture ? undefined : { stdio: 'inherit' };
let ret = '';
let err = '';
if (opts.verbose) {
console.log(`# RUNNING: ${args.join(' ')}\n (in ${process.cwd()})`);
}
child = spawn('/usr/bin/env', args, argOpts);
if (options.capture) {
child.stdout.on('data', (data) => {
ret += data.toString();
});
child.stderr.on('data', (data) => {
err += data.toString();
});
}
child.on('close', (code) => {
child = undefined;
ret = ret.trim();
if (ret === '') {
ret = undefined;
}
if (code) {
if (options.ignoreErr) {
resolve(ret);
} else {
reject(new SpawnError(code, err.trim()));
}
} else {
resolve(ret);
}
});
});
if (options.useErrHandler || options.errMessage) {
promise = promise.catch((err) => {
if (options.errMessage) {
console.error(`ERROR: ${options.errMessage.split('\n').join('\nERROR: ')}`);
}
let msg = `ERROR: ${args.slice(0, 2).join(' ')} exited with code ${err.code}`;
if (err.message) {
msg += ` and message ${err.message}`;
}
console.error(msg);
process.exit(err.code);
});
}
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q54404
|
startContainer
|
train
|
function startContainer(args, hidePorts) {
const cmd = ['docker', 'run', '--name', name, '--rm'];
// add the extra args as well
if (args && Array.isArray(args)) {
Array.prototype.push.apply(cmd, args);
}
if (!hidePorts) {
// list all of the ports defined in the config file
config.services.forEach((srv) => {
srv.conf = srv.conf || {};
srv.conf.port = srv.conf.port || 8888;
cmd.push('-p', `${srv.conf.port}:${srv.conf.port}`);
});
}
// append the image name to create a container from
cmd.push(imgName);
// ok, start the container
return promisedSpawn(cmd, { useErrHandler: true });
}
|
javascript
|
{
"resource": ""
}
|
q54405
|
getUid
|
train
|
function getUid() {
if (opts.deploy) {
// get the deploy repo location
return promisedSpawn(
['git', 'config', 'deploy.dir'],
{
capture: true,
errMessage: 'You must set the location of the deploy repo!\n' +
'Use git config deploy.dir /full/path/to/deploy/dir'
}
).then((dir) => {
opts.dir = dir;
// make sure that the dir exists and it is a git repo
return fs.statAsync(`${dir}/.git`);
}).then((stat) => {
opts.uid = stat.uid;
opts.gid = stat.gid;
}).catch(() => {
console.error(`ERROR: The deploy repo dir ${opts.dir} does not exist or is not a git repo!`);
process.exit(3);
});
}
// get the uid/gid from statting package.json
return fs.statAsync('package.json')
.then((stat) => {
opts.uid = stat.uid;
opts.gid = stat.gid;
}).catch(() => {
console.error('ERROR: package.json does not exist!');
process.exit(4);
});
}
|
javascript
|
{
"resource": ""
}
|
q54406
|
setLocalStorage
|
train
|
function setLocalStorage(optOutState) {
if (!(localStorage && localStorage.setItem)) {
return null;
}
if (typeof optOutState !== 'boolean') {
console.warn('setCookie for outOut invalid param optOutState. Param must be boolean');
return null;
}
try {
localStorage.setItem(disableStr, optOutState);
} catch (e) {
return null;
}
return optOutState;
}
|
javascript
|
{
"resource": ""
}
|
q54407
|
getLocalStorage
|
train
|
function getLocalStorage() {
if (!(localStorage && localStorage.getItem)) {
return null;
}
let state = localStorage.getItem(disableStr);
if (state === 'false') {
state = false;
} else if (state === 'true') {
state = true;
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q54408
|
setCookie
|
train
|
function setCookie(optOutState) {
switch (optOutState) {
case true:
document.cookie = `${disableStr}=true; expires=Thu, 18 Jan 2038 03:13:59 UTC; path=/`;
window[disableStr] = true;
break;
case false:
document.cookie = `${disableStr}=false; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=/`;
window[disableStr] = false;
break;
default:
console.warn('setCookie for outOut invalid param optOutState. Param must be boolean');
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54409
|
setOptOut
|
train
|
function setOptOut(optOutParam) {
window[disableStr] = optOutParam;
setCookie(optOutParam);
setLocalStorage(optOutParam);
return optOutParam;
}
|
javascript
|
{
"resource": ""
}
|
q54410
|
getCookie
|
train
|
function getCookie() {
if (document.cookie.indexOf(`${disableStr}=true`) > -1) {
return true;
} else if (document.cookie.indexOf(`${disableStr}=false`) > -1) {
return false;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q54411
|
isOptOut
|
train
|
function isOptOut() {
// Check cookie first
let optOutState = getCookie();
// No cookie info, check localStorage
if (optOutState === null) {
optOutState = getLocalStorage();
}
// No localStorage, we get default value
if (optOutState === null || typeof optOutState === 'undefined') {
optOutState = false;
}
// Set global for the environment
window[disableStr] = optOutState;
return optOutState;
}
|
javascript
|
{
"resource": ""
}
|
q54412
|
getInitialState
|
train
|
function getInitialState() {
if (!window.localStorage) {
return undefined;
}
const storedState = window.localStorage.getItem(storeKey);
if (!storedState) {
return undefined;
}
const normalisedState = storedState.replace(new RegExp('"isFetching":true', 'g'), '"isFetching":false');
return JSON.parse(normalisedState);
}
|
javascript
|
{
"resource": ""
}
|
q54413
|
parseVersion
|
train
|
function parseVersion(v) {
const [
, // Full match of no interest.
major = null,
sub = null,
minor = null,
] = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-.*)?$/.exec(v);
if (major === null || sub === null || minor === null) {
const err = new Error(`Invalid version string (${v})!`);
logger.error(err);
throw err;
}
return {
major,
sub,
minor,
};
}
|
javascript
|
{
"resource": ""
}
|
q54414
|
run
|
train
|
async function run() {
try {
// Find last release: Get tags, filter out wrong tags and pre-releases, then take last one.
const { stdout } = // get last filtered tag, sorted by version numbers in ascending order
await exec(`git tag | grep '${tagFrom}' | grep -Ev '-' | sort -V | tail -1`);
const prevTag = stdout.trim();
const nextVersion = parseVersion(argv[releaseNameParam]);
// Normalize the given "release-name" for the tile (strip out pre-release information).
const nextVersionString = `v${nextVersion.major}.${nextVersion.sub}.${nextVersion.minor}`;
// Read previous changelog to extend it (remove ending line feeds -> added back in later)
const changelogContent = fs.readFileSync('CHANGELOG.md', { encoding: 'utf8' }).trimRight();
const config = lernaConfiguration.load();
// This causes the "Unreleased" title to be replaced by a version that links to a github diff.
config.nextVersion = `[${
nextVersionString
}](https://github.com/shopgate/pwa/compare/${prevTag}...${nextVersionString})`;
// Skip creation if the "nextVersion" title is already present.
if (changelogContent.includes(config.nextVersion)) {
// Output the already existing data when already is there already.
logger.log(changelogContent);
return;
}
const changelog = new Changelog(config);
// The "release-name" param is not supposed to be used here. Instead use "HEAD".
const latestChanges = await changelog.createMarkdown({
tagFrom: prevTag,
tagTo,
});
// Add changes to the top of the main changelog
let newChangelog = '# Changelog\n';
if (appendPreviousChangelog) {
newChangelog = changelogContent;
}
if (latestChanges.trim().length > 0) {
newChangelog = newChangelog.replace(
'# Changelog\n',
`# Changelog\n\n${latestChanges.trim()}\n`
);
if (tagTo !== 'HEAD') {
newChangelog = newChangelog.replace(
`## ${tagTo} `,
`## ${config.nextVersion} `
);
}
}
// Print the output for the bash/makefile to read
logger.log(newChangelog);
} catch (error) {
throw error;
}
}
|
javascript
|
{
"resource": ""
}
|
q54415
|
synchRepo
|
train
|
async function synchRepo(remote, pathname) {
const cmd = `git subtree push --prefix=${pathname} ${remote} master`;
try {
await exec(cmd);
logger.log(`Synched master of ${pathname}`);
} catch (error) {
throw error;
}
}
|
javascript
|
{
"resource": ""
}
|
q54416
|
product
|
train
|
function product(subscribe) {
const processProduct$ = productReceived$.merge(cachedProductReceived$);
subscribe(productWillEnter$, ({ action, dispatch }) => {
const { productId } = action.route.params;
const { productId: variantId } = action.route.state;
const id = variantId || hex2bin(productId);
dispatch(fetchProduct(id));
dispatch(fetchProductDescription(id));
dispatch(fetchProductProperties(id));
dispatch(fetchProductImages(id, productImageFormats.getAllUniqueFormats()));
dispatch(fetchProductShipping(id));
});
subscribe(processProduct$, ({ action, dispatch }) => {
const {
id,
flags = {
hasVariants: false,
hasOptions: false,
},
baseProductId,
} = action.productData;
if (baseProductId) {
dispatch(fetchProduct(baseProductId));
dispatch(fetchProductImages(baseProductId, productImageFormats.getAllUniqueFormats()));
}
if (flags.hasVariants) {
dispatch(fetchProductVariants(id));
}
if (flags.hasOptions) {
dispatch(fetchProductOptions(id));
}
});
const receivedVisibleProductDebounced$ = receivedVisibleProduct$.debounceTime(500);
/** Refresh product data after getting cache version for PDP */
subscribe(receivedVisibleProductDebounced$, ({ action, dispatch }) => {
const { id } = action.productData;
dispatch(fetchProduct(id, true));
});
/** Visible product is no more available */
subscribe(visibleProductNotFound$, ({ action, dispatch }) => {
dispatch(showModal({
confirm: null,
dismiss: 'modal.ok',
title: 'modal.title_error',
message: 'product.no_more_found',
params: {
name: action.productData.name,
},
}));
dispatch(historyPop());
dispatch(expireProductById(action.productData.id));
});
subscribe(productRelationsReceived$, ({ dispatch, getState, action }) => {
const { hash } = action;
const productIds = getProductRelationsByHash(hash)(getState());
dispatch(fetchProductsById(productIds));
});
/**
* Expire products after checkout, fetch updated data
*/
subscribe(checkoutSucceeded$, ({ dispatch, action }) => {
const { products } = action;
const productIds = products.map(p => p.product.id);
productIds.forEach(id => dispatch(expireProductById(id)));
dispatch(fetchProductsById(productIds));
});
}
|
javascript
|
{
"resource": ""
}
|
q54417
|
sgTrackingUrlMapper
|
train
|
function sgTrackingUrlMapper(url, data) {
// In our development system urls start with /php/shopgate/ always
const developmentPath = '/php/shopgate/';
const appRegex = /sg_app_resources\/[0-9]*\//;
// Build regex that will remove all blacklisted paramters
let regex = '';
urlParameterBlacklist.forEach((entry) => {
regex += `((\\?|^){0,1}(${entry}=.*?(&|$)))`;
regex += '|';
});
const params = url.indexOf('?') !== -1 ? url.split('?')[1] : '';
let urlParams = params.replace(new RegExp(regex, 'g'), '');
urlParams = urlParams === '' ? '' : `?${urlParams.replace(/&$/, '')}`;
// Get rid of hash and app urls
let urlPath = url.split('?')[0].split('#')[0].replace(appRegex, '');
// Get path from url
if (url.indexOf(developmentPath) !== -1) {
urlPath = urlPath.substring(urlPath.indexOf(developmentPath) + developmentPath.length);
} else if (urlPath.indexOf('http') !== -1) {
urlPath = urlPath.substring(urlPath.indexOf('/', urlPath.indexOf('//') + 2) + 1);
} else {
urlPath = urlPath.substring(1);
}
// Get action from path
const action = urlPath.substring(
0,
((urlPath.indexOf('/') !== -1) ? (urlPath.indexOf('/')) : undefined)
);
// If no mapping function is available for the action, continue
if (typeof mapping[action] === 'undefined') {
return {
public: urlPath + urlParams,
private: action,
};
}
// Call mapping function and return its result
const pathWithoutAction = urlPath.substring(action.length + 1);
let pathWithoutActionArray = [];
if (pathWithoutAction.length !== 0) {
pathWithoutActionArray = pathWithoutAction.split('/');
}
const mappedUrls = mapping[action](pathWithoutActionArray, data || {});
if (Array.isArray(mappedUrls)) {
return {
public: mappedUrls[1] + urlParams,
private: mappedUrls[0],
};
}
return {
public: mappedUrls + urlParams,
private: mappedUrls,
};
}
|
javascript
|
{
"resource": ""
}
|
q54418
|
get
|
train
|
function get(object, path, defaultValue) {
// Initialize the parameters
const data = object || {};
const dataPath = path || '';
const defaultReturnValue = defaultValue;
// Get the segments of the path
const pathSegments = dataPath.split('.');
if (!dataPath || !pathSegments.length) {
// No path or path segments where determinable - return the default value
return defaultReturnValue;
}
/**
* Recursive callable function to traverse through a complex object
*
* @param {Object} currentData The current data that shall be investigated
* @param {number} currentPathSegmentIndex The current index within the path segment list
* @returns {*} The value at the end of the path or the default one
*/
function checkPathSegment(currentData, currentPathSegmentIndex) {
// Get the current segment within the path
const currentPathSegment = pathSegments[currentPathSegmentIndex];
const nextPathSegmentIndex = currentPathSegmentIndex + 1;
/**
* Prepare the default value as return value for the case that no matching property was
* found for the current path segment. In that case the path must be wrong.
*/
let result = defaultReturnValue;
if (currentData && currentData.hasOwnProperty(currentPathSegment)) {
if (
typeof currentData[currentPathSegment] !== 'object' ||
pathSegments.length === nextPathSegmentIndex
) {
// A final value was found
result = currentData[currentPathSegment];
} else {
// The value at the current step within the path is another object. Traverse through it
result = checkPathSegment(currentData[currentPathSegment], nextPathSegmentIndex);
}
}
return result;
}
// Start traversing the path within the data object
return checkPathSegment(data, 0);
}
|
javascript
|
{
"resource": ""
}
|
q54419
|
checkPathSegment
|
train
|
function checkPathSegment(currentData, currentPathSegmentIndex) {
// Get the current segment within the path
const currentPathSegment = pathSegments[currentPathSegmentIndex];
const nextPathSegmentIndex = currentPathSegmentIndex + 1;
/**
* Prepare the default value as return value for the case that no matching property was
* found for the current path segment. In that case the path must be wrong.
*/
let result = defaultReturnValue;
if (currentData && currentData.hasOwnProperty(currentPathSegment)) {
if (
typeof currentData[currentPathSegment] !== 'object' ||
pathSegments.length === nextPathSegmentIndex
) {
// A final value was found
result = currentData[currentPathSegment];
} else {
// The value at the current step within the path is another object. Traverse through it
result = checkPathSegment(currentData[currentPathSegment], nextPathSegmentIndex);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q54420
|
sanitizeTitle
|
train
|
function sanitizeTitle(title, shopName) {
// Take care that the parameters don't contain leading or trailing spaces
let trimmedTitle = title.trim();
const trimmedShopName = shopName.trim();
if (!trimmedShopName) {
/**
* If no shop name is available, it doesn't make sense to replace it.
* So we return the the trimmed title directly.
*/
return trimmedTitle;
}
/**
* Setup the RegExp. It matches leading and trailing occurrences
* of known patterns for generically added shop names within page title
*/
const shopNameRegExp = new RegExp(`((^${trimmedShopName}:)|(- ${trimmedShopName}$))+`, 'ig');
if (trimmedTitle === trimmedShopName) {
// Clear the page title if it only contains the shop name
trimmedTitle = '';
}
// Remove the shop name from the page title
return trimmedTitle.replace(shopNameRegExp, '').trim();
}
|
javascript
|
{
"resource": ""
}
|
q54421
|
formatSgDataProduct
|
train
|
function formatSgDataProduct(product) {
return {
id: getProductIdentifier(product),
type: 'product',
name: get(product, 'name'),
priceNet: getUnifiedNumber(get(product, 'amount.net')),
priceGross: getUnifiedNumber(get(product, 'amount.gross')),
quantity: getUnifiedNumber(get(product, 'quantity')),
currency: get(product, 'amount.currency'),
};
}
|
javascript
|
{
"resource": ""
}
|
q54422
|
formatFavouriteListItems
|
train
|
function formatFavouriteListItems(products) {
if (!products || !Array.isArray(products)) {
return [];
}
return products.map(product => ({
id: get(product, 'product_number_public') || get(product, 'product_number') || get(product, 'uid'),
type: 'product',
name: get(product, 'name'),
priceNet: getUnifiedNumber(get(product, 'unit_amount_net')) / 100,
priceGross: getUnifiedNumber(get(product, 'unit_amount_with_tax')) / 100,
currency: get(product, 'currency_id'),
}));
}
|
javascript
|
{
"resource": ""
}
|
q54423
|
executeCommand
|
train
|
function executeCommand(name = '', params = {}) {
const command = new AppCommand();
command
.setCommandName(name)
.dispatch(params);
}
|
javascript
|
{
"resource": ""
}
|
q54424
|
widgetCell
|
train
|
function widgetCell({
col,
row,
width,
height,
}) {
return css({
gridColumnStart: col + 1,
gridColumnEnd: col + width + 1,
gridRowStart: row + 1,
gridRowEnd: row + height + 1,
}).toString();
}
|
javascript
|
{
"resource": ""
}
|
q54425
|
fetchClientInformation
|
train
|
function fetchClientInformation() {
return (dispatch) => {
dispatch(requestClientInformation());
if (!hasSGJavaScriptBridge()) {
dispatch(receiveClientInformation(defaultClientInformation));
return;
}
getWebStorageEntry({ name: 'clientInformation' })
.then(response => dispatch(receiveClientInformation(response.value)))
.catch((error) => {
logger.error(error);
dispatch(errorClientInformation());
});
};
}
|
javascript
|
{
"resource": ""
}
|
q54426
|
shouldShowWidget
|
train
|
function shouldShowWidget(settings = {}) {
const nowDate = new Date();
// Show widget if flag does not exist (old widgets)
if (!settings.hasOwnProperty('published')) {
return true;
}
if (settings.published === false) {
return false;
}
// Defensive here since this data comes from the pipeline, it might be invalid for some reasons.
if (settings.hasOwnProperty('plan') && settings.plan) {
let startDate = null;
let endDate = null;
let notStartedYet = false;
let finishedAlready = false;
if (settings.planDate.valid_from) {
startDate = new Date(settings.planDate.valid_from);
notStartedYet = nowDate <= startDate;
}
if (settings.planDate.valid_to) {
endDate = new Date(settings.planDate.valid_to);
finishedAlready = nowDate >= endDate;
}
// Don't hide if no dates found
if (!startDate && !endDate) {
return true;
}
// Hide if some wrong dates are passed
if (startDate && endDate && (startDate >= endDate)) {
return false;
}
// Hide if start date is set but it is not there yet
// Hide if end date is reached
if ((startDate && notStartedYet) || (endDate && finishedAlready)) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54427
|
hasAnyTerms
|
train
|
function hasAnyTerms(file) {
var pathname = file.path;
var hasTerms = false;
var hasSrcInclusiveTerms = false;
hasTerms = matchTerms(file, forbiddenTerms);
if (!isTestFile(file)) {
hasSrcInclusiveTerms = matchTerms(file, forbiddenTermsSrcInclusive);
}
return hasTerms || hasSrcInclusiveTerms;
}
|
javascript
|
{
"resource": ""
}
|
q54428
|
isMissingTerms
|
train
|
function isMissingTerms(file) {
var contents = file.contents.toString();
return Object.keys(requiredTerms).map(function(term) {
var filter = requiredTerms[term];
if (!filter.test(file.path)) {
return false;
}
var matches = contents.match(new RegExp(term));
if (!matches) {
util.log(util.colors.red('Did not find required: "' + term +
'" in ' + file.relative));
util.log(util.colors.blue('=========='));
return true;
}
return false;
}).some(function(hasMissingTerm) {
return hasMissingTerm;
});
}
|
javascript
|
{
"resource": ""
}
|
q54429
|
checkForbiddenAndRequiredTerms
|
train
|
function checkForbiddenAndRequiredTerms() {
var forbiddenFound = false;
var missingRequirements = false;
return gulp.src(srcGlobs)
.pipe(through2.obj(function(file, enc, cb) {
forbiddenFound = hasAnyTerms(file) || forbiddenFound;
missingRequirements = isMissingTerms(file) || missingRequirements;
cb();
}))
.on('end', function() {
if (forbiddenFound) {
util.log(util.colors.blue(
'Please remove these usages or consult with the Web Activities team.'));
}
if (missingRequirements) {
util.log(util.colors.blue(
'Adding these terms (e.g. by adding a required LICENSE ' +
'to the file)'));
}
if (forbiddenFound || missingRequirements) {
process.exit(1);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q54430
|
parseQueryString
|
train
|
function parseQueryString(query) {
if (!query) {
return {};
}
return (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
const item = param.split('=');
const key = decodeURIComponent(item[0] || '');
const value = decodeURIComponent(item[1] || '');
if (key) {
params[key] = value;
}
return params;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q54431
|
addFragmentParam
|
train
|
function addFragmentParam(url, param, value) {
return url +
(url.indexOf('#') == -1 ? '#' : '&') +
encodeURIComponent(param) + '=' + encodeURIComponent(value);
}
|
javascript
|
{
"resource": ""
}
|
q54432
|
train
|
function (str) {
return str.split(';').map(function (e, i) {
return plugs[i].parse(e)
})
}
|
javascript
|
{
"resource": ""
}
|
|
q54433
|
lint
|
train
|
function lint() {
var errorsFound = false;
var stream = gulp.src(config.lintGlobs);
if (isWatching) {
stream = stream.pipe(watcher());
}
if (argv.fix) {
options.fix = true;
}
return stream.pipe(eslint(options))
.pipe(eslint.formatEach('stylish', function(msg) {
errorsFound = true;
util.log(util.colors.red(msg));
}))
.pipe(gulpIf(isFixed, gulp.dest('.')))
.pipe(eslint.failAfterError())
.on('end', function() {
if (errorsFound && !options.fix) {
util.log(util.colors.blue('Run `gulp lint --fix` to automatically ' +
'fix some of these lint warnings/errors. This is a destructive ' +
'operation (operates on the file system) so please make sure ' +
'you commit before running.'));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q54434
|
compileJs
|
train
|
function compileJs(srcDir, srcFilename, destDir, options) {
options = options || {};
if (options.minify) {
const startTime = Date.now();
return closureCompile(
srcDir + srcFilename + '.js', destDir, options.minifiedName, options)
.then(function() {
fs.writeFileSync(destDir + '/version.txt', internalRuntimeVersion);
if (options.latestName) {
fs.copySync(
destDir + '/' + options.minifiedName,
destDir + '/' + options.latestName);
}
})
.then(() => {
endBuildStep('Minified', srcFilename + '.js', startTime);
});
}
var bundler = browserify(srcDir + srcFilename + '-babel.js', {debug: true})
.transform(babel, {loose: 'all'});
if (options.watch) {
bundler = watchify(bundler);
}
var wrapper = options.wrapper || '<%= contents %>';
var lazybuild = lazypipe()
.pipe(source, srcFilename + '-babel.js')
.pipe(buffer)
.pipe($$.replace, /\$internalRuntimeVersion\$/g, internalRuntimeVersion)
.pipe($$.wrap, wrapper)
.pipe($$.sourcemaps.init.bind($$.sourcemaps), {loadMaps: true});
var lazywrite = lazypipe()
.pipe($$.sourcemaps.write.bind($$.sourcemaps), './')
.pipe(gulp.dest.bind(gulp), destDir);
var destFilename = options.toName || srcFilename + '.js';
function rebundle() {
const startTime = Date.now();
return toPromise(bundler.bundle()
.on('error', function(err) {
if (err instanceof SyntaxError) {
console.error($$.util.colors.red('Syntax error:', err.message));
} else {
console.error($$.util.colors.red(err.message));
}
})
.pipe(lazybuild())
.pipe($$.rename(destFilename))
.pipe(lazywrite())
.on('end', function() {
})).then(() => {
endBuildStep('Compiled', srcFilename, startTime);
});
}
if (options.watch) {
bundler.on('update', function() {
rebundle();
// Touch file in unit test set. This triggers rebundling of tests because
// karma only considers changes to tests files themselves re-bundle
// worthy.
touch('test/_init_tests.js');
});
}
if (options.watch === false) {
// Due to the two step build process, compileJs() is called twice, once with
// options.watch set to true and, once with it set to false. However, we do
// not need to call rebundle() twice. This avoids the duplicate compile seen
// when you run `gulp watch` and touch a file.
return Promise.resolve();
} else {
// This is the default options.watch === true case, and also covers the
// `gulp build` / `gulp dist` cases where options.watch is undefined.
return rebundle();
}
}
|
javascript
|
{
"resource": ""
}
|
q54435
|
endBuildStep
|
train
|
function endBuildStep(stepName, targetName, startTime) {
const endTime = Date.now();
const executionTime = new Date(endTime - startTime);
const secs = executionTime.getSeconds();
const ms = executionTime.getMilliseconds().toString();
var timeString = '(';
if (secs === 0) {
timeString += ms + ' ms)';
} else {
timeString += secs + '.' + ms + ' s)';
}
if (!process.env.TRAVIS) {
$$.util.log(
stepName,
$$.util.colors.cyan(targetName),
$$.util.colors.green(timeString));
}
}
|
javascript
|
{
"resource": ""
}
|
q54436
|
serve
|
train
|
function serve() {
util.log(util.colors.green('Serving unminified js'));
nodemon({
script: require.resolve('../server/server.js'),
watch: [
require.resolve('../server/server.js')
],
env: {
'NODE_ENV': 'development',
'SERVE_PORT': port,
'SERVE_HOST': host,
'SERVE_USEHTTPS': useHttps,
'SERVE_PROCESS_ID': process.pid,
'SERVE_QUIET': quiet
},
})
.once('quit', function () {
util.log(util.colors.green('Shutting down server'));
});
if (!quiet) {
util.log(util.colors.yellow('Run `gulp build` then go to ' + getHost()));
}
}
|
javascript
|
{
"resource": ""
}
|
q54437
|
dist
|
train
|
function dist() {
process.env.NODE_ENV = 'production';
return clean().then(() => {
return Promise.all([
compile({minify: true, checkTypes: false, isProdBuild: true}),
]).then(() => {
// Push main "min" files to root to make them available to npm package.
fs.copySync('./dist/activities.min.js', './activities.min.js');
fs.copySync('./dist/activities.min.js.map', './activities.min.js.map');
// Check types now.
return compile({minify: true, checkTypes: true});
}).then(() => {
return rollupActivities('./index.js', 'activities.js');
}).then(() => {
return rollupActivities('./index-ports.js', 'activity-ports.js');
}).then(() => {
return rollupActivities('./index-hosts.js', 'activity-hosts.js');
});
});
}
|
javascript
|
{
"resource": ""
}
|
q54438
|
buildBinaryString
|
train
|
function buildBinaryString (arrayBuffer) {
var binaryString = "";
const utf8Array = new Uint8Array(arrayBuffer);
const blockSize = 16384;
for (var i = 0; i < utf8Array.length; i = i + blockSize) {
const binarySubString = String.fromCharCode.apply(null, utf8Array.subarray(i, i + blockSize));
binaryString = binaryString + binarySubString;
}
return binaryString;
}
|
javascript
|
{
"resource": ""
}
|
q54439
|
getEntryIconHtml
|
train
|
function getEntryIconHtml(shape) {
var html = '',
name = shape.name,
x = shape.xPos,
y = shape.yPos,
fill = shape.fillColor,
stroke = shape.strokeColor,
width = shape.strokeWidth;
switch (name) {
case 'circle':
html = '<use xlink:href="#circle" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
'fill="' + fill + '" ' +
'stroke="' + stroke + '" ' +
'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
case 'diamond':
html = '<use xlink:href="#diamond" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
'fill="' + fill + '" ' +
'stroke="' + stroke + '" ' +
'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
case 'cross':
html = '<use xlink:href="#cross" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
// 'fill="' + fill + '" ' +
'stroke="' + stroke + '" ' +
'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
case 'rectangle':
html = '<use xlink:href="#rectangle" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
'fill="' + fill + '" ' +
'stroke="' + stroke + '" ' +
'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
case 'plus':
html = '<use xlink:href="#plus" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
// 'fill="' + fill + '" ' +
'stroke="' + stroke + '" ' +
'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
case 'bar':
html = '<use xlink:href="#bars" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
'fill="' + fill + '" ' +
// 'stroke="' + stroke + '" ' +
// 'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
case 'area':
html = '<use xlink:href="#area" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
'fill="' + fill + '" ' +
// 'stroke="' + stroke + '" ' +
// 'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
case 'line':
html = '<use xlink:href="#line" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
// 'fill="' + fill + '" ' +
'stroke="' + stroke + '" ' +
'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
break;
default:
// default is circle
html = '<use xlink:href="#circle" class="legendIcon" ' +
'x="' + x + '" ' +
'y="' + y + '" ' +
'fill="' + fill + '" ' +
'stroke="' + stroke + '" ' +
'stroke-width="' + width + '" ' +
'width="1.5em" height="1.5em"' +
'/>';
}
return html;
}
|
javascript
|
{
"resource": ""
}
|
q54440
|
getLegendEntries
|
train
|
function getLegendEntries(series, labelFormatter, sorted) {
var lf = labelFormatter,
legendEntries = series.map(function(s, i) {
return {
label: (lf ? lf(s.label, s) : s.label) || 'Plot ' + (i + 1),
color: s.color,
options: {
lines: s.lines,
points: s.points,
bars: s.bars
}
};
});
// Sort the legend using either the default or a custom comparator
if (sorted) {
if ($.isFunction(sorted)) {
legendEntries.sort(sorted);
} else if (sorted === 'reverse') {
legendEntries.reverse();
} else {
var ascending = (sorted !== 'descending');
legendEntries.sort(function(a, b) {
return a.label === b.label
? 0
: ((a.label < b.label) !== ascending ? 1 : -1 // Logical XOR
);
});
}
}
return legendEntries;
}
|
javascript
|
{
"resource": ""
}
|
q54441
|
checkOptions
|
train
|
function checkOptions(opts1, opts2) {
for (var prop in opts1) {
if (opts1.hasOwnProperty(prop)) {
if (opts1[prop] !== opts2[prop]) {
return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q54442
|
shouldRedraw
|
train
|
function shouldRedraw(oldEntries, newEntries) {
if (!oldEntries || !newEntries) {
return true;
}
if (oldEntries.length !== newEntries.length) {
return true;
}
var i, newEntry, oldEntry, newOpts, oldOpts;
for (i = 0; i < newEntries.length; i++) {
newEntry = newEntries[i];
oldEntry = oldEntries[i];
if (newEntry.label !== oldEntry.label) {
return true;
}
if (newEntry.color !== oldEntry.color) {
return true;
}
// check for changes in lines options
newOpts = newEntry.options.lines;
oldOpts = oldEntry.options.lines;
if (checkOptions(newOpts, oldOpts)) {
return true;
}
// check for changes in points options
newOpts = newEntry.options.points;
oldOpts = oldEntry.options.points;
if (checkOptions(newOpts, oldOpts)) {
return true;
}
// check for changes in bars options
newOpts = newEntry.options.bars;
oldOpts = oldEntry.options.bars;
if (checkOptions(newOpts, oldOpts)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q54443
|
train
|
function (value) {
var bw = options.grid.borderWidth;
return (((typeof bw === "object" && bw[axis.position] > 0) || bw > 0) && (value === axis.min || value === axis.max));
}
|
javascript
|
{
"resource": ""
}
|
|
q54444
|
train
|
function( data ){
data = $.extend({
distance: drag.distance,
which: drag.which,
not: drag.not,
drop: drag.drop
}, data || {});
data.distance = squared( data.distance ); // x² + y² = distance²
$event.add( this, "mousedown", handler, data );
if ( this.attachEvent ) this.attachEvent("ondragstart", dontStart ); // prevent image dragging in IE...
}
|
javascript
|
{
"resource": ""
}
|
|
q54445
|
hijack
|
train
|
function hijack ( event, type, elem ){
event.type = type; // force the event type
var result = ($.event.dispatch || $.event.handle).call( elem, event );
return result===false ? false : result || event.result;
}
|
javascript
|
{
"resource": ""
}
|
q54446
|
selectable
|
train
|
function selectable ( elem, bool ){
if ( !elem ) return; // maybe element was removed ?
elem = elem.ownerDocument ? elem.ownerDocument : elem;
elem.unselectable = bool ? "off" : "on"; // IE
if ( elem.style ) elem.style.MozUserSelect = bool ? "" : "none"; // FF
$.event[ bool ? "remove" : "add" ]( elem, "selectstart mousedown", dontStart ); // IE/Opera
}
|
javascript
|
{
"resource": ""
}
|
q54447
|
train
|
function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Safari 3.0+ "[object HTMLElementConstructor]"
return /constructor/i.test(window.top.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.top['safari'] || (typeof window.top.safari !== 'undefined' && window.top.safari.pushNotification));
}
|
javascript
|
{
"resource": ""
}
|
|
q54448
|
isExtJsReady
|
train
|
function isExtJsReady() {
return !(typeof Ext === 'undefined' || !Ext.isReady || typeof Ext.onReady === 'undefined' ||
typeof Ext.Ajax === 'undefined' || typeof Ext.Ajax.on === 'undefined');
}
|
javascript
|
{
"resource": ""
}
|
q54449
|
getStoreData
|
train
|
function getStoreData(storeId, field) {
var arr = Ext.StoreManager.get(storeId).getRange();
var res = arr.map(function (elem) {
return elem[field];
});
return res;
}
|
javascript
|
{
"resource": ""
}
|
q54450
|
replaceLocKeys
|
train
|
function replaceLocKeys(str) {
var reExtra = /el"(.*?)"/g;
var result = str.replace(reExtra, function (m, key) {
return '"' + tiaEJ.getLocaleValue(key, true) + '"';
});
var re = /l"(.*?)"/g;
result = result.replace(re, function (m, key) {
return '"' + tiaEJ.getLocaleValue(key) + '"';
});
result = result.replace(/,/g, '\\,');
return result;
}
|
javascript
|
{
"resource": ""
}
|
q54451
|
handleDirConfig
|
train
|
function handleDirConfig(dir, files, parentDirConfig) {
let config;
if (files.includes(gT.engineConsts.dirConfigName)) {
config = nodeUtils.requireEx(path.join(dir, gT.engineConsts.dirConfigName), true).result;
} else {
config = {};
}
// TODO: some error when suite configs or root configs is met in wrong places.
_.pullAll(files, [
gT.engineConsts.suiteConfigName,
gT.engineConsts.dirConfigName,
gT.engineConsts.suiteResDirName,
gT.engineConsts.rootResDirName,
gT.engineConsts.dirRootConfigName,
gT.engineConsts.suiteRootConfigName,
]);
if (config.require) {
nodeUtils.requireArray(config.require);
}
const dirCfg = _.merge(_.cloneDeep(parentDirConfig), config);
if (dirCfg.ignoreNames) {
_.pullAll(files, dirCfg.ignoreNames);
}
if (config.browserProfileDir) {
dirCfg.browserProfilePath = path.join(gIn.suite.browserProfilesPath, config.browserProfileDir);
} else {
dirCfg.browserProfilePath = gT.defaultRootProfile;
}
gIn.tracer.msg2(`Profile path: ${dirCfg.browserProfilePath}`);
return dirCfg;
}
|
javascript
|
{
"resource": ""
}
|
q54452
|
getSmtpTransporter
|
train
|
function getSmtpTransporter() {
return nodemailer.createTransport(
smtpTransport({
// service: 'tia',
host: gT.suiteConfig.mailSmtpHost,
secure: true,
// secure : false,
// port: 25,
auth: {
user: gT.suiteConfig.mailUser,
pass: gT.suiteConfig.mailPassword,
},
// , tls: {
// rejectUnauthorized: false
// }
})
);
}
|
javascript
|
{
"resource": ""
}
|
q54453
|
trackEOL
|
train
|
function trackEOL(msg) {
if (msg === true || Boolean(msg.match(/(\n|\r)$/))) {
gIn.tracePrefix = '';
} else {
gIn.tracePrefix = '\n';
}
}
|
javascript
|
{
"resource": ""
}
|
q54454
|
failWrapper
|
train
|
function failWrapper(msg, mode) {
gT.l.fail(msg);
if (mode && mode.accName) {
mode.accName = false; // eslint-disable-line no-param-reassign
}
}
|
javascript
|
{
"resource": ""
}
|
q54455
|
doesStoreContainField
|
train
|
function doesStoreContainField(store, fieldName) {
var model = store.first();
if (typeof model.get(fieldName) !== 'undefined') {
return true;
}
return model.getField(fieldName) != null;
}
|
javascript
|
{
"resource": ""
}
|
q54456
|
getCols
|
train
|
function getCols(table) {
var panel = tiaEJ.search.parentPanel(table);
var columns = panel.getVisibleColumns();
return columns;
}
|
javascript
|
{
"resource": ""
}
|
q54457
|
getColSelectors
|
train
|
function getColSelectors(table) {
var cols = this.getCols(table);
var selectors = cols.map(function (col) {
return table.getCellSelector(col);
});
return selectors;
}
|
javascript
|
{
"resource": ""
}
|
q54458
|
getColHeaderInfos
|
train
|
function getColHeaderInfos(table) {
var cols = this.getCols(table);
var arr = cols.map(function (col) {
// col.textEl.dom.textContent // slower but more honest.
// TODO: getConfig().tooltip - проверить.
var text = tiaEJ.convertTextToFirstLocKey(col.text);
if (text === col.emptyCellText) {
text = ''; // <emptyCell>
}
var info = col.getConfig('xtype') + ': "' + text + '"';
var toolTip = col.getConfig().toolTip;
if (toolTip) {
info += ', toolTip: ' + tiaEJ.convertTextToFirstLocKey(toolTip);
}
// if (col.items) {
// info += ', items: ' + JSON.stringify(col.items);
// }
// if (col.getConfig('xtype') === 'actioncolumn') { //
// console.dir(col);
// window.c2 = col;
// }
return info;
});
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q54459
|
getCB
|
train
|
function getCB(cb) {
var str = '';
// str += this.getIdItemIdReference(cb) + '\n';
str += this.getCompDispIdProps(cb) + '\n';
str += 'Selected vals: \'' + this.getCBSelectedVals(cb) + '\'\n';
var displayField = this.safeGetConfig(cb, 'displayField');
// str += 'displayField: ' + displayField + '\n';
str += tiaEJ.ctMisc.stringifyStoreField(cb.getStore(), displayField).join('\n') + '\n';
return tia.cC.content.wrap(str);
}
|
javascript
|
{
"resource": ""
}
|
q54460
|
getFormSubmitValues
|
train
|
function getFormSubmitValues(form) {
var fields = form.getValues(false, false, false, false);
return fields; // O
}
|
javascript
|
{
"resource": ""
}
|
q54461
|
getTree
|
train
|
function getTree(table, options) {
if (table.isPanel) {
table = table.getView();
}
function getDefOpts() {
return {
throwIfInvisible: false,
allFields: false
};
}
var isVisible = table.isVisible(true);
options = tiaEJ.ctMisc.checkVisibilityAndFillOptions(isVisible, options, getDefOpts);
var panel = tiaEJ.search.parentPanel(table);
var root = panel.getRootNode();
var res = [];
function traverseSubTree(node, indent) {
var fieldsToPrint = ['text', 'checked', 'id'];
if (tia.debugMode) {
fieldsToPrint = [
'text',
'checked',
'id',
'visible',
'expanded',
'leaf',
'expandable',
'index',
'depth',
'qtip',
'qtitle',
'cls'
];
}
if (options.allFields) {
res.push(indent + tiaEJ.ctMisc.stringifyAllRecord(node, fieldsToPrint, true));
} else {
res.push(indent + tiaEJ.ctMisc.stringifyRecord(node, fieldsToPrint, true));
}
if (node.hasChildNodes()) {
indent += tia.cC.content.indent;
node.eachChild(function (curNode) {
traverseSubTree(curNode, indent);
});
}
}
traverseSubTree(root, '');
return tia.cC.content.wrap('Tree content: \n' + res.join('\n') + '\n');
}
|
javascript
|
{
"resource": ""
}
|
q54462
|
getControllerInfo
|
train
|
function getControllerInfo(controller, msg) {
var res = ['++++++++++',
'CONTROLLER INFO (' + msg + '):',
];
if (!controller) {
res.push('N/A');
return res;
}
var modelStr = '';
var refsObj = controller.getReferences();
var refsStr = Ext.Object.getKeys(refsObj).join(', ');
var routesObj = controller.getRoutes();
var routesStr = Ext.Object.getKeys(routesObj).join(', ');
// TODO: getStore ?? или это есть во ViewModel?
var viewModel = controller.getViewModel();
if (viewModel) {
modelStr += 'viewModel.$className: ' + viewModel.$className;
}
var view = controller.getView();
var viewStr = '';
if (view) {
viewStr += 'view.$className: ' + view.$className +
', getConfig("xtype"): ' + view.getConfig('xtype') + ' ' +
this.formGetIdStr(view, '18px');
var itemId = view.getConfig('itemId');
if (!autoGenRE.test(itemId)) {
viewStr += ', itemId: ' + itemId;
}
var reference = view.getConfig('reference');
if (reference) {
viewStr += ', reference: ' + reference;
}
}
this.pushTextProp(controller, 'alias', res);
return res.concat([
'controller: isViewController: ' + controller.isViewController,
'clName: ' + controller.$className,
'getId(): ' + controller.getId(),
'getReferences(): ' + refsStr,
'routes: ' + routesStr,
modelStr,
viewStr,
'++++++++++',
]);
}
|
javascript
|
{
"resource": ""
}
|
q54463
|
getFormFieldInfo
|
train
|
function getFormFieldInfo(field) {
var formFieldArr = [
this.consts.avgSep,
'Form Field Info: ',
];
var name = field.getName() || '';
if (!Boolean(autoGenRE.test(name))) {
formFieldArr.push('getName(): ' + this.boldIf(name, name, 'darkgreen'));
}
tia.cU.dumpObj(field, [
'getValue()',
'getRawValue()',
'getSubmitValue()',
'getModelData()',
'getSubmitData()',
'getInputId()',
'initialConfig.inputType',
'initialConfig.boxLabel',
'boxLabel',
'inputType',
'getFieldLabel()',
'getActiveError()',
'getErrors()',
], formFieldArr);
var store;
if (field.isPickerField) {
var pickerComp = field.getPicker();
formFieldArr = formFieldArr.concat([
this.consts.tinySep,
'Picker field info:']);
tia.cU.dumpObj(pickerComp, ['$className'], formFieldArr);
tia.cU.dumpObj(field, [
'getConfig().displayField',
'initialConfig.hiddenName',
], formFieldArr);
formFieldArr.push(this.consts.tinySep);
if (field.getStore) {
store = field.getStore();
formFieldArr = formFieldArr.concat(this.getStoreContent(store));
}
} else if (field.displayField) {
formFieldArr = formFieldArr.concat([
this.consts.tinySep,
'Form field containing "displayField" info:']);
tia.cU.dumpObj(field, ['$className'], formFieldArr);
tia.cU.dumpObj(field, [
'getConfig().displayField',
'initialConfig.hiddenName',
], formFieldArr);
formFieldArr.push(this.consts.tinySep);
if (field.getStore) {
store = field.getStore();
formFieldArr = formFieldArr.concat(this.getStoreContent(store));
}
}
formFieldArr.push(this.consts.avgSep);
return formFieldArr;
}
|
javascript
|
{
"resource": ""
}
|
q54464
|
parseSearchString
|
train
|
function parseSearchString(str) {
str = tia.cU.replaceXTypesInTeq(str);
var re = /&(\w|\d|_|-)+/g;
var searchData = [];
var prevLastIndex = 0;
var query;
while (true) {
var reResult = re.exec(str);
if (reResult === null) {
// Only query string.
query = str.slice(prevLastIndex).trim();
if (query) {
searchData.push({
query: query,
});
}
return searchData;
}
query = str.slice(prevLastIndex, reResult.index).trim();
var reference = str.slice(reResult.index + 1, re.lastIndex).trim();
prevLastIndex = re.lastIndex;
if (query) {
searchData.push({
query: query,
});
}
searchData.push({
reference: reference,
});
}
}
|
javascript
|
{
"resource": ""
}
|
q54465
|
byIdRef
|
train
|
function byIdRef(id, ref) {
var cmp = this.byId(id).lookupReferenceHolder(false).lookupReference(ref);
if (!cmp) {
throw new Error('Component not found for container id: ' + id + ', reference: ' + ref);
}
return cmp;
}
|
javascript
|
{
"resource": ""
}
|
q54466
|
byIdRefKey
|
train
|
function byIdRefKey(id, ref, key, extra) {
var text = tiaEJ.getTextByLocKey(key, extra);
var cmp = this.search.byIdRef(id, ref);
var resItem = this.search.byText(cmp, text, 'container id: ' + id + ', reference: ' + ref);
return resItem;
}
|
javascript
|
{
"resource": ""
}
|
q54467
|
stopTimer
|
train
|
function stopTimer(startTime) {
if (gT.config.enableTimings) {
const dif = process.hrtime(startTime);
return ` (${dif[0] * 1000 + dif[1] / 1e6} ms)`;
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q54468
|
pause
|
train
|
async function pause() {
if (gT.cLParams.selActsDelay) {
await gT.u.promise.delayed(gT.cLParams.selActsDelay);
}
}
|
javascript
|
{
"resource": ""
}
|
q54469
|
handleErrorWhenDriverExistsAndRecCountZero
|
train
|
async function handleErrorWhenDriverExistsAndRecCountZero() {
gIn.errRecursionCount = 1; // To prevent recursive error report on error report.
/* Here we use selenium GUI stuff when there was gT.s.driver.init call */
gIn.tracer.msg1('A.W.: Error report: printSelDriverLogs');
await gT.s.driver.printSelDriverLogs(900).catch(() => {
gIn.tracer.msg1(
`Error at printSelDriverLogs at error handling, driver exists: ${Boolean(gT.sOrig.driver)}`
);
});
if (!gIn.brHelpersInitiated) {
gIn.tracer.msg1('A.W.: Error report: initTiaBrHelpers');
await gT.s.browser.initTiaBrHelpers(true).catch(() => {
gIn.tracer.msg1(
`Error at initTiaBrHelpers at error handling, driver exists: ${Boolean(gT.sOrig.driver)}`
);
});
}
gIn.tracer.msg1('A.W.: Error report: printCaughtExceptions');
await gT.s.browser.printCaughtExceptions(true).catch(() => {
gIn.tracer.msg1(
`Error at logExceptions at error handling, driver exists: ${Boolean(gT.sOrig.driver)}`
);
});
gIn.tracer.msg1('A.W.: Error report: printSelBrowserLogs');
await gT.s.browser.printSelBrowserLogs().catch(() => {
gIn.tracer.msg1(
`Error at logConsoleContent at error handling, driver exists: ${Boolean(gT.sOrig.driver)}`
);
});
gIn.tracer.msg1('A.W.: Error report: screenshot');
await gT.s.browser.screenshot().catch(() => {
gIn.tracer.msg1(
`Error at screenshot at error handling, driver exists: ${Boolean(gT.sOrig.driver)}`
);
});
await quitDriver();
throw new Error(gT.engineConsts.CANCELLING_THE_TEST);
}
|
javascript
|
{
"resource": ""
}
|
q54470
|
getTableItemByIndex
|
train
|
function getTableItemByIndex(table, index) {
if (table.isPanel) {
table = table.getView();
}
var el = table.getRow(index);
return el;
}
|
javascript
|
{
"resource": ""
}
|
q54471
|
findRecordIds
|
train
|
function findRecordIds(store, rowData) {
var internalIds = [];
store.each(function (m) {
for (var i = 0; i < rowData.length; i++) {
var item = rowData[i];
var dataIndex = item[0];
var value = item[1];
var fieldValue = m.get(dataIndex);
if (fieldValue !== value) {
return true; // To next record.
}
}
internalIds.push(m.internalId);
return true;
});
if (!internalIds.length) {
throw new Error('Record not found for ' + JSON.stringify(rowData));
}
return internalIds;
}
|
javascript
|
{
"resource": ""
}
|
q54472
|
findRecord
|
train
|
function findRecord(store, fieldName, text) {
var index = store.find(fieldName, text);
if (index === -1) {
throw new Error('Text: ' + text + ' not found for fieldName: ' + fieldName);
}
return index;
}
|
javascript
|
{
"resource": ""
}
|
q54473
|
findRecords
|
train
|
function findRecords(store, fieldName, texts) {
var records = [];
texts.forEach(function (text) {
var index = store.find(fieldName, text);
if (index === -1) {
throw new Error('Text: ' + text + ' not found for fieldName: ' + fieldName);
}
records.push(index);
});
return records;
}
|
javascript
|
{
"resource": ""
}
|
q54474
|
setTableSelection
|
train
|
function setTableSelection(table, rowData) {
if (table.isPanel) {
table = table.getView();
}
var model = this.findRecord(table.getStore(), rowData);
table.setSelection(model);
}
|
javascript
|
{
"resource": ""
}
|
q54475
|
getRowDomId
|
train
|
function getRowDomId(table, internalId) {
if (table.isPanel) {
table = table.getView();
}
var tableId = table.getId();
var gridRowid = tableId + '-record-' + internalId;
return gridRowid;
}
|
javascript
|
{
"resource": ""
}
|
q54476
|
getTableCellByColumnTexts
|
train
|
function getTableCellByColumnTexts(table, cellData) {
if (table.isPanel) {
table = table.getView();
}
if (typeof cellData.one === 'undefined') {
cellData.one = true;
}
if (typeof cellData.index === 'undefined') {
cellData.index = 0;
}
var panel = table.ownerGrid;
var visColumns = panel.getVisibleColumns();
var text2DataIndex = {};
var cellSelector = null;
visColumns.forEach(function (col) {
var key = col.text || col.tooltip;
text2DataIndex[key] = col.dataIndex;
if (key === cellData.column) {
cellSelector = table.getCellSelector(col);
}
});
if (!cellSelector) {
throw new Error('Column ' + cellData.column + ' not found in visible columns');
}
var row = cellData.row.slice(0);
row = row.map(function (tup) {
var tmpTup = tup.slice(0);
tmpTup[0] = text2DataIndex[tup[0]];
if (!tmpTup[0]) {
throw new Error('getTableCellByColumnTexts: No such column text: ' + tup[0]);
}
return tmpTup;
});
var internalIds = this.findRecordIds(table.getStore(), row);
console.log(internalIds);
if (cellData.one && (internalIds.length > 1)) {
throw new Error('getTableCellByColumnTexts: one is true, but found ' + internalIds.length + ' records.');
}
var internalId = (cellData.index < 0) ? internalIds[internalIds.length + cellData.index] :
internalIds[cellData.index];
var rowDomId = this.getRowDomId(table, internalId);
var rowDom = document.getElementById(rowDomId);
var cellDom = rowDom.querySelector(cellSelector);
return cellDom;
}
|
javascript
|
{
"resource": ""
}
|
q54477
|
parseMwsResponse
|
train
|
function parseMwsResponse(method, headers, response, callback) {
// if it's XML, then we an parse correctly
if (headers && headers['content-type'] == 'text/xml') {
xml2js.parseString(response, {explicitArray: false}, function(err, result) {
if (err) {
return callback(err);
}
if (result.ErrorResponse) {
err = {
Code: 'Unknown',
Message: 'Unknown MWS error'
};
if (result.ErrorResponse.Error) {
err = result.ErrorResponse.Error;
}
return callback(error.apiError(err.Code, err.Message, result));
} else {
callback(null, new Response(method, result));
}
});
} else {
callback(null, new Response(method, { "Response": response }));
}
}
|
javascript
|
{
"resource": ""
}
|
q54478
|
write
|
train
|
function write(arr, str, range) {
const offset = range[0];
arr[offset] = str;
for (let i = offset + 1; i < range[1]; i++) {
arr[i] = undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q54479
|
replaceRequireAndDefine
|
train
|
function replaceRequireAndDefine(code, amdPackages, amdModules) {
// Parse the code as an AST
const ast = esprima.parseScript(code, {
range: true
});
// Split the code into an array for easier substitutions
const buffer = code.split('');
// Walk thru the tree, find and replace our targets
eswalk(ast, function(node) {
if (!node) {
return;
}
switch (node.type) {
case 'CallExpression':
if (!amdPackages || !amdModules) {
// If not provided then we don't need to track them
break;
}
// Collect the AMD modules
// Looking for something like define(<name>, [<module1>, <module2>, ...], <function>)
// This is the way ember defines a module
if (node.callee.name === 'define') {
if (node.arguments.length < 2 || node.arguments[1].type !== 'ArrayExpression' || !node.arguments[1].elements) {
return;
}
node.arguments[1].elements.forEach(function(element) {
if (element.type !== 'Literal') {
return;
}
const isAMD = amdPackages.some(function(amdPackage) {
if (typeof element.value !== 'string') {
return false;
}
return element.value.indexOf(amdPackage + '/') === 0 || element.value === amdPackage;
});
if (!isAMD) {
return;
}
amdModules.add(element.value);
});
return;
}
// Dealing with ember-auto-import eval
if (node.callee.name === 'eval' && node.arguments[0].type === 'Literal' && typeof node.arguments[0].value === 'string') {
const evalCode = node.arguments[0].value;
const evalCodeAfter = replaceRequireAndDefine(evalCode, amdPackages, amdModules);
if (evalCode !== evalCodeAfter) {
write(buffer, "eval(" + JSON.stringify(evalCodeAfter) + ");", node.range);
}
}
return;
case 'Identifier':
{
// We are dealing with code, make sure the node.name is not inherited from object
if (!identifiers.hasOwnProperty(node.name)) {
return;
}
const identifier = identifiers[node.name];
if (!identifier) {
return;
}
write(buffer, identifier, node.range);
}
return;
case 'Literal':
{
// We are dealing with code, make sure the node.name is not inherited from object
if (!literals.hasOwnProperty(node.value)) {
return;
}
const literal = literals[node.value];
if (!literal) {
return;
}
write(buffer, literal, node.range);
}
return;
}
});
// Return the new code
return buffer.join('');
}
|
javascript
|
{
"resource": ""
}
|
q54480
|
getStartEnvOptions
|
train
|
function getStartEnvOptions() {
var options = {};
for (var k in args) {
switch (k) {
case 'daemon':
case 'robust':
options[k] = args[k] === true ? '1' : '0';
break;
case 'cluster':
options[k] = args[k] ? args[k] : os.cpus().length;
break;
case 'port':
options[k] = args[k];
break;
}
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q54481
|
train
|
function(value, field) {
if(field.parser) {
var parser = (isFunction(field.parser)) ?
field.parser : null;//Y.Parsers[field.parser+''];
if(parser) {
value = parser.call(this, value);
}
else {
//Y.log("Could not find parser for field " + Y.dump(field), "warn", "dataschema-json");
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q54482
|
train
|
function (path, data) {
var i = 0,
len = path.length;
for (;i<len;i++) {
if (isObject(data) && (path[i] in data)) {
data = data[path[i]];
} else {
data = undefined;
break;
}
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
|
q54483
|
train
|
function(schema, data) {
var data_in = data,
data_out = { results: [], meta: {} };
// Convert incoming JSON strings
if (!isObject(data)) {
try {
data_in = JSON.parse(data);
}
catch(e) {
data_out.error = e;
return data_out;
}
}
if (isObject(data_in) && schema) {
// Parse results data
data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out);
// Parse meta data
if (schema.metaFields !== undefined) {
data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out);
}
}
else {
//Y.log("JSON data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-json");
data_out.error = new Error("JSON schema parse failure");
}
return data_out;
}
|
javascript
|
{
"resource": ""
}
|
|
q54484
|
train
|
function(schema, json_in, data_out) {
var getPath = SchemaJSON.getPath,
getValue = SchemaJSON.getLocationValue,
path = getPath(schema.resultListLocator),
results = path ?
(getValue(path, json_in) ||
// Fall back to treat resultListLocator as a simple key
json_in[schema.resultListLocator]) :
// Or if no resultListLocator is supplied, use the input
json_in;
if (isArray(results)) {
// if no result fields are passed in, then just take
// the results array whole-hog Sometimes you're getting
// an array of strings, or want the whole object, so
// resultFields don't make sense.
if (isArray(schema.resultFields)) {
data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out);
} else {
data_out.results = results;
}
} else if (!results) { //else if (schema.resultListLocator) {
data_out.results = [];
data_out.error = new Error("JSON results retrieval failure");
//Y.log("JSON data could not be parsed: " + Y.dump(json_in), "error", "dataschema-json");
}
else {
data_out.results = results;
}
return data_out;
}
|
javascript
|
{
"resource": ""
}
|
|
q54485
|
train
|
function(metaFields, json_in, data_out) {
if (isObject(metaFields)) {
var key, path;
for(key in metaFields) {
if (metaFields.hasOwnProperty(key)) {
path = SchemaJSON.getPath(metaFields[key]);
if (path && json_in) {
data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in);
}
}
}
}
else {
data_out.error = new Error("JSON meta data retrieval failure");
}
return data_out;
}
|
javascript
|
{
"resource": ""
}
|
|
q54486
|
train
|
function (rootNode, viewKey) {
var views = this.getList('view', rootNode);
var self = this;
_.each(views, function (view) {
view.remove();
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q54487
|
onLinksDone
|
train
|
function onLinksDone(loaded) {
if (loaded === 2) {
if (hasLayoutChanged) {
$target.find('[lazo-cmp-name]').remove();
$target.append(html);
} else {
$target.html(html);
}
setTimeout(function () {
LAZO.error.clear();
$target.css({ 'visibility': 'visible'} );
viewManager.attachViews(ctl, function (err, success) {
if (err) {
LAZO.logger.error('[LAZO.navigate] Error attaching views', err);
}
doc.updatePageTags(LAZO.ctl.ctx, function (err) {
if (err) {
LAZO.logger.error('[LAZO.navigate] Error updating page tags', err);
}
doc.setTitle(LAZO.ctl.ctx._rootCtx.pageTitle);
LAZO.app.trigger('navigate:application:complete', eventData);
});
});
}, 0);
}
}
|
javascript
|
{
"resource": ""
}
|
q54488
|
train
|
function(attrs, options) {
// begin lazo specific overrides
var modelName = null;
if (this.modelName) {
if (_.isFunction(this.modelName)) {
modelName = this.modelName(attrs, options);
}
else {
modelName = this.modelName;
}
}
// end lazo specific overrides
if (attrs instanceof Backbone.Model) {
if (!attrs.collection) attrs.collection = this;
if (!attrs.name && modelName) attrs.name = modelName; // lazo specific
return attrs;
}
options || (options = {});
options.collection = this;
// begin lazo specific overrides
if (modelName) {
options.name = modelName;
}
options.ctx = this.ctx;
// end lazo specific overrides
var model = new this.model(attrs, options);
if (!model._validate(attrs, options)) {
this.trigger('invalid', this, attrs, options);
return false;
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q54489
|
train
|
function (svc, attributes, options) {
options = options || {};
if (!options.success) {
throw new Error('Success callback undefined for service call svc: ' + svc);
}
var error = options.error;
options.error = function (err) {
if (error) {
error(err);
}
};
// use the backbone verbs
return this.sync(
'update',
{
name: svc,
url: svc,
params: options.params,
ctx: this.ctx,
toJSON: function () {
return attributes;
}
},
options);
}
|
javascript
|
{
"resource": ""
}
|
|
q54490
|
setTags
|
train
|
function setTags(routeDefs) {
for (var k in routeDefs) {
if (_.isObject(routeDefs[k])) {
if (!_.isArray(routeDefs[k].servers)) {
routeDefs[k].servers = ['primary'];
}
} else {
routeDefs[k] = {
component: routeDefs[k],
servers: ['primary']
};
}
}
return routeDefs;
}
|
javascript
|
{
"resource": ""
}
|
q54491
|
train
|
function (component) {
var pathParts = component === 'app' ? ['app'] : ['components'];
if (component !== 'app') {
pathParts.push(component);
}
pathParts.push('assets');
return path.resolve(LAZO.FILE_REPO_PATH + path.sep + path.join.apply(this, pathParts));
}
|
javascript
|
{
"resource": ""
}
|
|
q54492
|
train
|
function (map, ctx) {
for (var k in map) {
map[k] = this.resolveAssets(map[k], ctx);
}
return map;
}
|
javascript
|
{
"resource": ""
}
|
|
q54493
|
train
|
function (key, options) {
var ret;
if (this.data && key in this.data) {
ret = this.data[key];
try {
ret = JSON.parse(ret);
} catch (e) {} // ignore JSON parse errors since we only want to parse it if it is JSON
}
if (options && _.isFunction(options.success)) {
options.success(ret);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q54494
|
train
|
function(elem, listener) {
var normalizedListener = function(e) {
listener(normalizeWheelEvent(e));
};
EVENT_NAMES.forEach(function(name) {
elem.addEventListener(name, normalizedListener);
});
return function() {
EVENT_NAMES.forEach(function(name) {
elem.removeEventListener(name, normalizedListener);
});
};
}
|
javascript
|
{
"resource": ""
}
|
|
q54495
|
train
|
function(r1, c1, r2, c2) {
var range = {};
if (r1 < r2) {
range.top = r1;
range.height = r2 - r1 + 1;
} else {
range.top = r2;
range.height = r1 - r2 + 1;
}
if (c1 < c2) {
range.left = c1;
range.width = c2 - c1 + 1;
} else {
range.left = c2;
range.width = c1 - c2 + 1;
}
return range;
}
|
javascript
|
{
"resource": ""
}
|
|
q54496
|
handleRowColSelectionChange
|
train
|
function handleRowColSelectionChange(rowOrCol) {
var decoratorsField = ('_' + rowOrCol + 'SelectionClasses');
model[decoratorsField].forEach(function (selectionDecorator) {
grid.cellClasses.remove(selectionDecorator);
});
model[decoratorsField] = [];
if (grid[rowOrCol + 'Model'].allSelected()) {
var top = rowOrCol === 'row' ? Infinity : 0;
var left = rowOrCol === 'col' ? Infinity : 0;
var decorator = grid.cellClasses.create(top, left, 'selected', 1, 1, 'virtual');
grid.cellClasses.add(decorator);
model[decoratorsField].push(decorator);
} else {
grid[rowOrCol + 'Model'].getSelected().forEach(function (index) {
var virtualIndex = grid[rowOrCol + 'Model'].toVirtual(index);
var top = rowOrCol === 'row' ? virtualIndex : 0;
var left = rowOrCol === 'col' ? virtualIndex : 0;
var decorator = grid.cellClasses.create(top, left, 'selected', 1, 1, 'virtual');
grid.cellClasses.add(decorator);
model[decoratorsField].push(decorator);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q54497
|
createCategorizer
|
train
|
async function createCategorizer() {
const classifierOptions = { tokenizer }
// We can't initialize the model in parallel using `Promise.all` because with
// it is not possible to manage errors separately
let globalModel, localModel
try {
globalModel = await createGlobalModel(classifierOptions)
} catch (e) {
log('info', 'Failed to create global model:')
log('info', e.message)
}
try {
localModel = await createLocalModel(classifierOptions)
} catch (e) {
log('info', 'Failed to create local model:')
log('info', e.message)
}
const modelsToApply = [globalModel, localModel].filter(Boolean)
const categorize = transactions => {
modelsToApply.forEach(model => model.categorize(transactions))
return transactions
}
return { categorize }
}
|
javascript
|
{
"resource": ""
}
|
q54498
|
onRegistered
|
train
|
function onRegistered(client, url) {
let server
return new Promise(resolve => {
server = http.createServer((request, response) => {
if (request.url.indexOf('/do_access') === 0) {
log('debug', request.url, 'url received')
resolve(request.url)
response.end(
'Authorization registered, you can close this page and go back to the cli'
)
}
})
server.listen(3333, () => {
require('opn')(url, { wait: false })
console.log(
'A new tab just opened in your browser to require the right authorizations for this connector in your cozy. Waiting for it...'
)
console.log(
'If your browser does not open (maybe your are in a headless virtual machine...), then paste this url in your browser'
)
console.log(url)
})
}).then(
url => {
server.close()
return url
},
err => {
server.close()
log('error', err, 'registration error')
throw err
}
)
}
|
javascript
|
{
"resource": ""
}
|
q54499
|
log
|
train
|
function log(type, message, label, namespace) {
if (filterOut(level, type, message, label, namespace)) {
return
}
// eslint-disable-next-line no-console
console.log(format(type, message, label, namespace))
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.