_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q200 | extendedCallback | train | function extendedCallback(res) {
timeline.mark(`end:${id}`);
// add full response data
moduleData[id].response = getResDataObject(res);
// flatten object for easy transformation/filtering later
moduleData[id] = flatten(moduleData[id], { maxDepth: 5 });
moduleData[id] = filterData(config, moduleData[id]);
// if filter function returns falsey value, drop all data completely
if (typeof moduleData[id] !== 'object') {
timeline.data = timeline.data.filter(
d => !new RegExp(id).test(d.name)
);
delete moduleData[id];
}
if (typeof originalCallback === 'function') {
return originalCallback.apply(this, [res]);
}
return true;
} | javascript | {
"resource": ""
} |
q201 | train | function(func, scope, args)
{
var fixedArgs = Array.prototype.slice.call(arguments, 2);
return function()
{
var args = fixedArgs.concat(Array.prototype.slice.call(arguments, 0));
(/** @type {Function} */ func).apply(scope, args);
};
} | javascript | {
"resource": ""
} |
|
q202 | train | function(args)
{
var i, max, match, log;
// Convert argument list to real array
args = Array.prototype.slice.call(arguments, 0);
// First argument is the log method to call
log = args.shift();
max = args.length;
if (max > 1 && window["__consoleShimTest__"] !== false)
{
// When first parameter is not a string then add a format string to
// the argument list so we are able to modify it in the next stop
if (typeof(args[0]) != "string")
{
args.unshift("%o");
max += 1;
}
// For each additional parameter which has no placeholder in the
// format string we add another placeholder separated with a
// space character.
match = args[0].match(/%[a-z]/g);
for (i = match ? match.length + 1 : 1; i < max; i += 1)
{
args[0] += " %o";
}
}
Function.apply.call(log, console, args);
} | javascript | {
"resource": ""
} |
|
q203 | parseOptions | train | function parseOptions(options) {
let separator
let transformer
if (2 === options.length) {
[separator, transformer] = options
if (defaultTransformers[transformer]) {
transformer = defaultTransformers[transformer] /* Don't validate */
validate({ separator })
} else {
validate({ separator, transformer })
}
} else if (1 === options.length) {
const option = options[0]
if (false === option || 'function' === typeof option) {
transformer = option /* Don't validate */
} else if (defaultTransformers[option]) {
transformer = defaultTransformers[option] /* Don't validate */
} else {
separator = option
validate({ separator })
}
}
return { separator, transformer }
} | javascript | {
"resource": ""
} |
q204 | getWeight | train | function getWeight(labels, labelWeight) {
const places = labels.map(label => labelWeight.indexOf(label.name));
let binary = '';
for (let i = 0; i < labelWeight.length; i++) {
binary += places.includes(i) ? '1' : '0';
}
return parseInt(binary, 2);
} | javascript | {
"resource": ""
} |
q205 | getReleaseInfo | train | async function getReleaseInfo(context, childTags) {
const tagShas = [];
const releasesBySha = await fetchAllReleases(context, release => {
if (childTags.has(release.tag_name)) {
// put in reverse order
// later releases come first,
// but we want to iterate beginning oldest releases first
tagShas.unshift(release.target_commitish);
// tagSha.push(release.target_commitish);
}
});
return {releasesBySha, tagShas};
} | javascript | {
"resource": ""
} |
q206 | getType | train | function getType(value) {
// inspired by http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/
// handle null in old IE
if (value === null) {
return 'null';
}
// handle DOM elements
if (value && (value.nodeType === 1 || value.nodeType === 9)) {
return 'element';
}
var s = Object.prototype.toString.call(value);
var type = s.match(/\[object (.*?)\]/)[1].toLowerCase();
// handle NaN and Infinity
if (type === 'number') {
if (isNaN(value)) {
return 'nan';
}
if (!isFinite(value)) {
return 'infinity';
}
}
return type;
} | javascript | {
"resource": ""
} |
q207 | extendFormatExtensions | train | function extendFormatExtensions (extensionName, extensionValue) {
if (typeof extensionName !== 'string' || !(extensionValue instanceof RegExp)) {
throw new Error('extensionName or extensionValue undefined or not correct type');
}
if (revalidator.validate.formats.hasOwnProperty(extensionName) ||
revalidator.validate.formats.hasOwnProperty(extensionName)) {
var msg = 'extensionName: ' + extensionName + ' already exists in formatExtensions.';
throw new Error(msg);
}
revalidator.validate.formatExtensions[extensionName] = extensionValue;
} | javascript | {
"resource": ""
} |
q208 | getError | train | function getError (type, expected, actual) {
return {
attribute: type,
expected: expected,
actual: actual,
message: getMsg(type, expected)
};
} | javascript | {
"resource": ""
} |
q209 | getResult | train | function getResult (err) {
var res = {
valid: true,
errors: []
};
if (err !== null) {
res.valid = false;
res.errors.push(err);
}
return res;
} | javascript | {
"resource": ""
} |
q210 | uniqueArrayHelper | train | function uniqueArrayHelper (val) {
var h = {};
for (var i = 0, l = val.length; i < l; i++) {
var key = JSON.stringify(val[i]);
if (h[key]) {
return false;
}
h[key] = true;
}
return true;
} | javascript | {
"resource": ""
} |
q211 | getValidationFunction | train | function getValidationFunction (validationOptions) {
validationOptions = validationOptions || {};
return function (doc, schema, options) {
doc = doc || {};
options = options || {};
options.isUpdate = options.isUpdate || false;
// check is update
if (options.isUpdate) {
var i,
keys = Object.keys(schema.properties),
length = keys.length;
for (i = 0; i < length; i++) {
if (!doc.hasOwnProperty(keys[i])) {
// set property required to false
schema.properties[keys[i]].required = false;
// remove property from required array
if (Array.isArray(schema.required) && schema.required.indexOf(keys[i]) > -1) {
schema.required.splice(schema.required.indexOf(keys[i]), 1);
}
}
}
}
// add default validation options to options object
for (var key in validationOptions) {
// only add options, do not override
if (validationOptions.hasOwnProperty(key) && !options.hasOwnProperty(key)) {
options[key] = validationOptions[key];
}
}
// json schema validate
return exports.validate(doc, schema, options);
};
} | javascript | {
"resource": ""
} |
q212 | componentExists | train | function componentExists(componentPath) {
const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath));
const existsInWidgets = fs.existsSync(path.resolve(themes.getPath(), 'widgets', componentPath));
return !(!existsInExtensions && !existsInWidgets);
} | javascript | {
"resource": ""
} |
q213 | readConfig | train | function readConfig(options) {
return new Promise((resolve, reject) => {
const {
type,
config,
importsStart = null,
importsEnd = null,
exportsStart = 'export default {',
exportsEnd = '};',
isArray = false,
} = options;
if (!config || !isPlainObject(config)) {
return reject(new TypeError(t('SUPPLIED_CONFIG_IS_NOT_AN_OBJECT', {
typeofConfig: typeof config,
})));
}
const imports = importsStart ? [importsStart] : []; // Holds the import strings.
const exports = [exportsStart]; // Holds the export strings.
// eslint-disable-next-line global-require, import/no-dynamic-require
const themePackage = require(`${themes.getPath()}/package.json`);
if (
(type === TYPE_PORTALS || type === TYPE_WIDGETS) &&
has(themePackage.dependencies, 'react-loadable')
) {
imports.push('import Loadable from \'react-loadable\';');
imports.push('import Loading from \'@shopgate/pwa-common/components/Loading\';');
imports.push('');
}
try {
Object.keys(config).forEach((id) => {
const component = config[id];
const componentPath = isDev ? component.path.replace('/dist/', '/src/') : component.path;
if (!componentExists(componentPath)) {
return;
}
const variableName = getVariableName(id);
const isPortalsOrWidgets = (
(type === TYPE_PORTALS && component.target !== 'app.routes')
|| type === TYPE_WIDGETS
);
if (isPortalsOrWidgets && has(themePackage.dependencies, 'react-loadable')) {
imports.push(`const ${variableName} = Loadable({\n loader: () => import('${componentPath}'),\n loading: Loading,\n});\n`);
} else {
imports.push(`import ${variableName} from '${componentPath}';`);
}
if (isArray) {
exports.push(` ${variableName},`);
return;
}
exports.push(` '${id}': ${variableName},`);
});
} catch (e) {
return reject(e);
}
if (importsEnd) {
imports.push(importsEnd);
}
exports.push(exportsEnd);
return resolve({
imports,
exports,
});
});
} | javascript | {
"resource": ""
} |
q214 | getIndexLogTranslations | train | function getIndexLogTranslations(type = TYPE_WIDGETS) {
const params = { type: t(`TYPE_${type}`) };
return {
logStart: ` ${t('INDEXING_TYPE', params)}`,
logEnd: ` ${t('INDEXED_TYPE', params)}`,
logNotFound: ` ${t('NO_EXTENSIONS_FOUND_FOR_TYPE', params)}`,
};
} | javascript | {
"resource": ""
} |
q215 | validateExtensions | train | function validateExtensions(input) {
return new Promise((resolve, reject) => {
try {
const extensionPath = getExtensionsPath();
if (!fs.existsSync(extensionPath)) {
fs.mkdirSync(extensionPath);
}
if (!input.imports.length) {
return resolve(null);
}
return resolve(input);
} catch (e) {
return reject(new Error(t('EXTENSION_COULD_NOT_BE_VALIDATED')));
}
});
} | javascript | {
"resource": ""
} |
q216 | createStrings | train | function createStrings(input) {
return new Promise((resolve, reject) => {
try {
if (!input) {
return resolve(null);
}
const importsString = input.imports.length ? `${input.imports.join('\n')}\n\n` : '';
const exportsString = input.exports.length ? `${input.exports.join('\n')}\n` : '';
const indexString = `${importsString}${exportsString}`.replace('\n\n\n', '\n\n');
return resolve(indexString.length ? indexString : null);
} catch (e) {
return reject(new Error(t('STRINGS_COULD_NOT_BE_CREATED')));
}
});
} | javascript | {
"resource": ""
} |
q217 | writeExtensionFile | train | function writeExtensionFile(options) {
return new Promise((resolve, reject) => {
try {
const {
file,
input,
defaultContent,
logNotFound,
logEnd,
} = options;
const filePath = path.resolve(getExtensionsPath(), file);
if (!input) {
logger.warn(logNotFound);
fs.writeFileSync(filePath, defaultContent, { flag: 'w+' });
return resolve();
}
fs.writeFileSync(filePath, input, { flag: 'w+' });
logger.log(logEnd);
return resolve();
} catch (e) {
return reject(e);
}
});
} | javascript | {
"resource": ""
} |
q218 | index | train | function index(options) {
const {
file,
config,
logStart,
logNotFound,
logEnd,
defaultContent = defaultFileContent,
} = options;
logger.log(logStart);
return readConfig(config)
.then(input => validateExtensions(input))
.then(input => createStrings(input))
.then(input => writeExtensionFile({
input,
file,
defaultContent,
logNotFound,
logEnd,
}));
} | javascript | {
"resource": ""
} |
q219 | indexWidgets | train | function indexWidgets() {
const { widgets = {} } = getComponentsSettings();
return index({
file: 'widgets.js',
config: {
type: TYPE_WIDGETS,
config: widgets,
},
...getIndexLogTranslations(TYPE_WIDGETS),
});
} | javascript | {
"resource": ""
} |
q220 | indexTracking | train | function indexTracking() {
const { tracking = {} } = getComponentsSettings();
return index({
file: 'tracking.js',
config: {
type: TYPE_TRACKERS,
config: tracking,
},
...getIndexLogTranslations(TYPE_TRACKERS),
});
} | javascript | {
"resource": ""
} |
q221 | indexPortals | train | function indexPortals() {
const { portals = {} } = getComponentsSettings();
return index({
file: 'portals.js',
config: {
type: TYPE_PORTALS,
config: portals,
importsStart: 'import portalCollection from \'@shopgate/pwa-common/helpers/portals/portalCollection\';',
exportsStart: 'portalCollection.registerPortals({',
exportsEnd: '});',
},
...getIndexLogTranslations(TYPE_PORTALS),
});
} | javascript | {
"resource": ""
} |
q222 | indexReducers | train | function indexReducers() {
const { reducers = {} } = getComponentsSettings();
return index({
file: 'reducers.js',
config: {
type: TYPE_REDUCERS,
config: reducers,
},
defaultContent: 'export default null;\n',
...getIndexLogTranslations(TYPE_REDUCERS),
});
} | javascript | {
"resource": ""
} |
q223 | indexSubscribers | train | function indexSubscribers() {
const { subscribers = {} } = getComponentsSettings();
return index({
file: 'subscribers.js',
config: {
type: TYPE_SUBSCRIBERS,
config: subscribers,
exportsStart: 'export default [',
exportsEnd: '];',
isArray: true,
},
defaultContent: 'export default [];\n',
...getIndexLogTranslations(TYPE_SUBSCRIBERS),
});
} | javascript | {
"resource": ""
} |
q224 | indexTranslations | train | function indexTranslations() {
const { translations = {} } = getComponentsSettings();
return index({
file: 'translations.js',
config: {
type: TYPE_TRANSLATIONS,
config: translations,
},
defaultContent: 'export default null;\n',
...getIndexLogTranslations(TYPE_TRANSLATIONS),
});
} | javascript | {
"resource": ""
} |
q225 | search | train | function search(query, options = {}) {
const {
format = 'idCode',
mode = 'substructure',
flattenResult = true,
keepMolecule = false,
limit = Number.MAX_SAFE_INTEGER
} = options;
if (typeof query === 'string') {
const getMoleculeCreators = require('./moleculeCreators');
const moleculeCreators = getMoleculeCreators(this.OCL.Molecule);
query = moleculeCreators.get(format.toLowerCase())(query);
} else if (!(query instanceof this.OCL.Molecule)) {
throw new TypeError('toSearch must be a Molecule or string');
}
let result;
switch (mode.toLowerCase()) {
case 'exact':
result = exactSearch(this.moleculeDB.db, query, limit);
break;
case 'substructure':
result = subStructureSearch(this.moleculeDB, query, limit);
break;
case 'similarity':
result = similaritySearch(this.moleculeDB, this.OCL, query, limit);
break;
default:
throw new Error(`unknown search mode: ${options.mode}`);
}
return processResult(result, { flattenResult, keepMolecule, limit });
} | javascript | {
"resource": ""
} |
q226 | maybeApi | train | async function maybeApi ({ apiAddress, apiOpts, ipfsConnectionTest, IpfsApi }) {
try {
const ipfs = new IpfsApi(apiAddress, apiOpts)
await ipfsConnectionTest(ipfs)
return { ipfs, provider, apiAddress }
} catch (error) {
console.log('Failed to connect to ipfs-api', apiAddress)
}
} | javascript | {
"resource": ""
} |
q227 | addMissingChirality | train | function addMissingChirality(molecule, esrType = Molecule.cESRTypeAnd) {
for (let iAtom = 0; iAtom < molecule.getAllAtoms(); iAtom++) {
let tempMolecule = molecule.getCompactCopy();
changeAtomForStereo(tempMolecule, iAtom);
// After copy, helpers must be recalculated
tempMolecule.ensureHelperArrays(Molecule.cHelperParities);
// We need to have >0 and not >1 because there could be unspecified chirality in racemate
for (let i = 0; i < tempMolecule.getAtoms(); i++) {
// changed from from handling below; TLS 9.Nov.2015
if (
tempMolecule.isAtomStereoCenter(i) &&
tempMolecule.getStereoBond(i) === -1
) {
let stereoBond = tempMolecule.getAtomPreferredStereoBond(i);
if (stereoBond !== -1) {
molecule.setBondType(stereoBond, Molecule.cBondTypeUp);
if (molecule.getBondAtom(1, stereoBond) === i) {
let connAtom = molecule.getBondAtom(0, stereoBond);
molecule.setBondAtom(0, stereoBond, i);
molecule.setBondAtom(1, stereoBond, connAtom);
}
// To me it seems that we have to add all stereo centers into AND group 0. TLS 9.Nov.2015
molecule.setAtomESR(i, esrType, 0);
}
}
}
}
} | javascript | {
"resource": ""
} |
q228 | markDiastereotopicAtoms | train | function markDiastereotopicAtoms(molecule) {
// changed from markDiastereo(); TLS 9.Nov.2015
let ids = getAtomIDs(molecule);
let analyzed = {};
let group = 0;
for (let id of ids) {
console.log(`${id} - ${group}`);
if (!analyzed.contains(id)) {
analyzed[id] = true;
for (let iAtom = 0; iAtom < ids.length; iAtom++) {
if (id.equals(ids[iAtom])) {
molecule.setAtomCustomLabel(iAtom, group);
}
}
group++;
}
}
} | javascript | {
"resource": ""
} |
q229 | getContrastColor | train | function getContrastColor(bgColor, colors) {
// We set a rather high cutoff to prefer light text if possible.
const cutoff = 0.74;
// Calculate the perceived luminosity (relative brightness) of the color.
const perceivedLuminosity = Color(bgColor).luminosity();
return perceivedLuminosity >= cutoff ? colors.dark : colors.light;
} | javascript | {
"resource": ""
} |
q230 | getFocusColor | train | function getFocusColor(colors) {
if (Color(colors.primary).luminosity() >= 0.8) {
return colors.accent;
}
return colors.primary;
} | javascript | {
"resource": ""
} |
q231 | applyContrastColors | train | function applyContrastColors(config) {
const { colors } = config;
return {
...config,
colors: {
...colors,
primaryContrast: getContrastColor(colors.primary, colors),
accentContrast: getContrastColor(colors.accent, colors),
focus: getFocusColor(colors),
},
};
} | javascript | {
"resource": ""
} |
q232 | applyCustomColors | train | function applyCustomColors(config) {
const { colors } = getAppSettings();
if (!config.hasOwnProperty('colors')) {
return {
...config,
colors,
};
}
return {
...config,
colors: {
...config.colors,
...colors,
},
};
} | javascript | {
"resource": ""
} |
q233 | module | train | function module(filename) {
return function () {
if (verbose.local) console.log(filename);
response.write(fs.readFileSync(filename) + '\n/*:oxsep:*/\n');
};
} | javascript | {
"resource": ""
} |
q234 | collecticonsBundle | train | async function collecticonsBundle (params) {
const {
dirPath,
destFile
} = params;
await validateDirPath(dirPath);
const resultFiles = await collecticonsCompile({
dirPath,
styleFormats: ['css'],
styleDest: './styles',
fontDest: './',
fontTypes: ['woff', 'woff2'],
previewDest: './',
noFileOutput: true
});
if (resultFiles === null) return;
// Create zip.
let zip = new JSZip();
// Add generated files.
resultFiles.forEach(file => {
zip.file(file.path, file.contents);
});
// Add the icons.
const dir = await fs.readdir(dirPath);
const svgs = await Promise.all(dir.map(async file => {
return file.endsWith('.svg')
? (
{
path: `icons/${file}`,
contents: await fs.readFile(path.resolve(dirPath, file))
}
)
: null;
}));
svgs.forEach(file => {
zip.file(file.path, file.contents);
});
await fs.ensureDir(path.dirname(destFile));
await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary');
} | javascript | {
"resource": ""
} |
q235 | train | function(errors) {
//!steal-remove-start
if (process.env.NODE_ENV !== 'production') {
clearTimeout(asyncTimer);
}
//!steal-remove-end
var stub = error && error.call(self, errors);
// if 'validations' is on the page it will trigger
// the error itself and we dont want to trigger
// the event twice. :)
if (stub !== false) {
mapEventsMixin.dispatch.call(self, 'error', [ prop, errors ], true);
}
return false;
} | javascript | {
"resource": ""
} |
|
q236 | train | function(map, attr, val) {
var serializer = attr === "*" ? false : getPropDefineBehavior("serialize", attr, map.define);
if (serializer === undefined) {
return oldSingleSerialize.call(map, attr, val);
} else if (serializer !== false) {
return typeof serializer === "function" ? serializer.call(map, val, attr) : oldSingleSerialize.call(map, attr, val);
}
} | javascript | {
"resource": ""
} |
|
q237 | generateFonts | train | async function generateFonts (options = {}) {
if (!options.fontName) throw new TypeError('Missing fontName argument');
if (!options.icons || !Array.isArray(options.icons) || !options.icons.length) { throw new TypeError('Invalid or empty icons argument'); }
// Store created tasks to match dependencies.
let genTasks = {};
/**
* First, creates tasks for dependent font types.
* Then creates task for specified font type and chains it to dependencies promises.
* If some task already exists, it reuses it.
*/
const makeGenTask = type => {
// If already defined return.
if (genTasks[type]) return genTasks[type];
// Get generator function.
const gen = generators[type];
// Create dependent functions
const depsTasks = (gen.deps || []).map(depType => makeGenTask(depType));
const task = Promise.all(depsTasks).then(results =>
gen.fn(options, results)
);
genTasks[type] = task;
return task;
};
// Make a gen task for each type.
const types = ['svg', 'ttf', 'woff', 'woff2'];
const tasks = types.map(type => {
return makeGenTask(type);
});
const results = await Promise.all(tasks);
return zipObject(types, results);
} | javascript | {
"resource": ""
} |
q238 | renderSass | train | async function renderSass (opts = {}) {
const tpl = await fs.readFile(path.resolve(__dirname, 'sass.ejs'), 'utf8');
return ejs.render(tpl, opts);
} | javascript | {
"resource": ""
} |
q239 | renderCatalog | train | async function renderCatalog (opts = {}) {
if (!opts.fontName) throw new ReferenceError('fontName is undefined');
if (!opts.className) throw new ReferenceError('className is undefined');
if (!opts.icons || !opts.icons.length) throw new ReferenceError('icons is undefined or empty');
const fonts = opts.fonts
? Object.keys(opts.fonts).reduce((acc, name) => {
return {
...acc,
[name]: opts.fonts[name].contents.toString('base64')
};
}, {})
: undefined;
return JSON.stringify({
name: opts.fontName,
className: opts.className,
fonts,
icons: opts.icons.map(i => ({
icon: `${opts.className}-${i.name}`,
charCode: `${i.codepoint.toString(16).toUpperCase()}`
}))
});
} | javascript | {
"resource": ""
} |
q240 | Logger | train | function Logger () {
const levels = [
'fatal', // 1
'error', // 2
'warn', // 3
'info', // 4
'debug' // 5
];
let verbosity = 3;
levels.forEach((level, idx) => {
this[level] = (...params) => {
if (idx + 1 <= verbosity) console.log(...params); // eslint-disable-line
};
});
this.setLevel = (_) => {
verbosity = _;
};
return this;
} | javascript | {
"resource": ""
} |
q241 | userError | train | function userError (details = [], code) {
const err = new Error('User error');
err.userError = true;
err.code = code;
err.details = details;
return err;
} | javascript | {
"resource": ""
} |
q242 | time | train | function time (name) {
const t = timers[name];
if (t) {
let elapsed = Date.now() - t;
if (elapsed < 1000) return `${elapsed}ms`;
if (elapsed < 60 * 1000) return `${elapsed / 1000}s`;
elapsed /= 1000;
const h = Math.floor(elapsed / 3600);
const m = Math.floor((elapsed % 3600) / 60);
const s = Math.floor((elapsed % 3600) % 60);
delete timers[name];
return `${h}h ${m}m ${s}s`;
} else {
timers[name] = Date.now();
}
} | javascript | {
"resource": ""
} |
q243 | validateDirPath | train | async function validateDirPath (dirPath) {
try {
const stats = await fs.lstat(dirPath);
if (!stats.isDirectory()) {
throw userError([
'Source path must be a directory',
''
]);
}
} catch (error) {
if (error.code === 'ENOENT') {
throw userError([
'No files or directories found at ' + dirPath,
''
]);
}
throw error;
}
} | javascript | {
"resource": ""
} |
q244 | validateDirPathForCLI | train | async function validateDirPathForCLI (dirPath) {
try {
await validateDirPath(dirPath);
} catch (error) {
if (!error.userError) throw error;
if (error.details[0].startsWith('Source path must be a directory')) {
const args = process.argv.reduce((acc, o, idx) => {
// Discard the first 2 arguments.
if (idx < 1) return acc;
if (o === dirPath) return acc.concat(path.dirname(dirPath));
return acc.concat(o);
}, []);
throw userError([
'Source path must be a directory. Try running with the following instead:',
'',
` node ${args.join(' ')}`,
''
]);
}
throw error;
}
} | javascript | {
"resource": ""
} |
q245 | compileProgram | train | async function compileProgram (dirPath, command) {
await validateDirPathForCLI(dirPath);
const params = pick(command, [
'fontName',
'sassPlaceholder',
'cssClass',
'fontTypes',
'styleFormats',
'styleDest',
'styleName',
'fontDest',
'authorName',
'authorUrl',
'className',
'previewDest',
'preview',
'catalogDest',
'experimentalFontOnCatalog',
'experimentalDisableStyles'
]);
try {
return collecticonsCompile({
dirPath,
...params
});
} catch (error) {
if (!error.userError) throw error;
// Capture some errors and convert to their command line alternative.
const code = error.code;
if (code === 'PLC_CLASS_EXC') {
error.details = ['Error: --no-sass-placeholder and --no-css-class are mutually exclusive'];
} else if (code === 'FONT_TYPE') {
error.details = ['Error: invalid font type value passed to --font-types'];
} else if (code === 'CLASS_CSS_FORMAT') {
error.details = ['Error: "--no-css-class" and "--style-formats css" are not compatible'];
} else if (code === 'STYLE_TYPE') {
error.details = ['Error: invalid style format value passed to --style-format'];
}
throw error;
}
} | javascript | {
"resource": ""
} |
q246 | bundleProgram | train | async function bundleProgram (dirPath, destFile) {
await validateDirPathForCLI(dirPath);
return collecticonsBundle({
dirPath,
destFile
});
} | javascript | {
"resource": ""
} |
q247 | Connection | train | function Connection (options, clientOptions, label) {
this.options = options;
this.clientOptions = clientOptions;
this.label = label;
this.initialConnection = false;
this.initialConnectionRetries = 0;
this.maxConnectionRetries = 60;
Object.defineProperty(this, 'exchanges', {
get: function () {
if (this.connection) {
return this.connection.exchanges;
}
}
});
Object.defineProperty(this, 'connected', {
get: function () {
return this.connection !== undefined;
}
});
} | javascript | {
"resource": ""
} |
q248 | resolveRef | train | function resolveRef(schemaObj, resolvedValues) {
// the array store referenced value
var refVal = schemaObj.refVal;
// the map store full ref id and index of the referenced value in refVal
// example: { 'test#definitions/option' : 1, 'test#definitions/repo' : 2 }
var refs = schemaObj.refs;
// the map to store schema value with sub reference
var subRefs = {};
_.forEach(refs, function (index, refId) {
// if reference id already resolved then continue the loop
if (refId in resolvedValues) {
return true; // continue
}
var refValue = refVal[index];
// if no further nested reference, add to resolved map
if (_.isEmpty(refValue.refs)) {
resolvedValues[refId] = refValue;
return true;
}
// add schema value with sub reference to map to resolve later
subRefs[refId] = refValue;
});
// resolve sub reference recursively
_.forEach(subRefs, function (subRef, refId) {
resolvedValues[refId] = 1;
resolvedValues[refId] = resolveRef(subRef, resolvedValues);
});
return schemaObj.schema;
} | javascript | {
"resource": ""
} |
q249 | assetFingerprint | train | function assetFingerprint(label, fingerprint, cacheInfo) {
if(arguments.length > 1)
{
//Add a label
var labelInfo = labels[label] = {"fingerprint": fingerprint};
if(cacheInfo)
for(var i in cacheInfo)
labelInfo[i] = cacheInfo[i];
}
else
{
//Try to get a fingerprint from a registered label
var info = labels[label];
if(info)
{
fingerprints[info.fingerprint] = info;
return info.fingerprint;
}
else
{
info = {};
//Try to get a fingerprint using the specified cache strategy
var fullPath = path.resolve(rootPath + "/" + (label || this.url) );
//Use the "cache strategy" to get a fingerprint
//Prefer the use of etag over lastModified when generating fingerprints
if(!fs.existsSync(fullPath) )
return label;
if(strategy.lastModified)
{
var mdate = info.lastModified = strategy.lastModified(fullPath);
mdate.setMilliseconds(0);
}
if(strategy.etag)
info.etag = strategy.etag(fullPath);
if(strategy.expires)
info.expires = strategy.expires(fullPath);
if(strategy.fileFingerprint)
{
var fingerprint = strategy.fileFingerprint(label, fullPath);
fingerprints[fingerprint] = info;
return fingerprint;
}
else
return label; //Do not generate a fingerprint
}
}
} | javascript | {
"resource": ""
} |
q250 | train | function() {
var self = this;
return waterline.catalogs.findOne({"node": self.id})
.then(function(catalog) {
return !_.isEmpty(catalog);
});
} | javascript | {
"resource": ""
} |
|
q251 | train | function () {
var waterline = this.injector.get('Services.Waterline');
return bluebird.all(
_.map(waterline, function (collection) {
if (typeof collection.destroy === 'function') {
return bluebird.fromNode(collection.destroy.bind(collection)).then(function () {
if (collection.adapterDictionary.define !== 'mongo') {
return bluebird.fromNode(
collection.adapter.define.bind(collection.adapter)
);
}
});
}
})
);
} | javascript | {
"resource": ""
} |
|
q252 | ChildProcess | train | function ChildProcess (command, args, env, code, maxBuffer) {
var self = this;
assert.string(command);
assert.optionalArrayOfNumber(code);
self.command = command;
self.file = self._parseCommandPath(self.command);
self.args = args;
self.environment = env || {};
self.exitCode = code || [0];
self.maxBuffer = maxBuffer || Constants.ChildProcess.MaxBuffer;
if (!self.file) {
throw new Error('Unable to locate command file (' + self.command +').');
}
if (!_.isEmpty(self.args)) {
try {
assert.arrayOfString(self.args, 'ChildProcess command arguments');
} catch (e) {
throw new Error('args must be an array of strings');
}
}
self.hasBeenKilled = false;
self.hasBeenCancelled = false;
self.spawnInstance = undefined;
} | javascript | {
"resource": ""
} |
q253 | provideName | train | function provideName(obj, token){
if(!isString(token)) {
throw new Error('Must provide string as name of module');
}
di.annotate(obj, new di.Provide(token));
} | javascript | {
"resource": ""
} |
q254 | providePromise | train | function providePromise(obj, providePromiseName) {
if(!isString(providePromiseName)) {
throw new Error('Must provide string as name of promised module');
}
di.annotate(obj, new di.ProvidePromise(providePromiseName));
} | javascript | {
"resource": ""
} |
q255 | resolveProvide | train | function resolveProvide(obj, override) {
var provide = override || obj.$provide;
if(isString(provide)) {
return provideName(obj, provide);
}
if(isObject(provide)) {
if (isString(provide.promise)) {
return providePromise(obj, provide.promise);
} else if (isString(provide.provide)) {
return provideName(obj, provide.provide);
}
}
} | javascript | {
"resource": ""
} |
q256 | addInject | train | function addInject(obj, inject) {
if(!exists(inject)) {
return;
}
var injectMe;
if (inject === '$injector') {
injectMe = new di.Inject(di.Injector);
} else if (isObject(inject)) {
if(isString(inject.inject)){
injectMe = new di.Inject(inject.inject);
} else if(isString(inject.promise)) {
injectMe = new di.InjectPromise(inject.promise);
} else if(isString(inject.lazy)) {
injectMe = new di.InjectLazy(inject.lazy);
}
} else {
injectMe = new di.Inject(inject);
}
di.annotate(obj, injectMe);
} | javascript | {
"resource": ""
} |
q257 | resolveInjects | train | function resolveInjects(obj, override){
var injects = obj.$inject || override;
if (exists(injects)) {
if (!Array.isArray(injects)) {
injects = [injects];
}
injects.forEach(function addInjects(element) {
addInject(obj, element);
});
}
} | javascript | {
"resource": ""
} |
q258 | injectableWrapper | train | function injectableWrapper(obj, provide, injects, isTransientScope) {
// TODO(@davequick): discuss with @halfspiral whether isTransientScope might just better
// be an array of Annotations
var wrappedObject = function wrapOrCreateObject() {
if(isFunction(obj) && (exists(obj.$provide) || exists(obj.$inject) || provide || injects)){
var instance = Object.create(obj.prototype);
return obj.apply(instance,arguments) || instance;
}
return obj;
};
return _wrapper(obj, wrappedObject, provide, injects, isTransientScope);
} | javascript | {
"resource": ""
} |
q259 | _requireFile | train | function _requireFile(requirable, directory) {
var required;
try{
var res = resolve.sync(requirable, { basedir: directory});
required = require(res);
}
catch(err) {
required = (void 0);
}
return required;
} | javascript | {
"resource": ""
} |
q260 | _require | train | function _require(requireMe, provides, injects, currentDirectory, next) {
var requireResult = _requireFile (requireMe, currentDirectory) ||
_requireFile (requireMe, defaultDirectory) ||
_requireFile (requireMe, __dirname) ||
_requireFile (requireMe, process.cwd()) ||
_requireFile (requireMe, (void 0));
if(!exists(requireResult)) {
var directories = 'directories:(';
directories += exists(currentDirectory) ? currentDirectory + ', ' : '';
directories += exists(defaultDirectory) ? defaultDirectory + ', ' : '';
directories += __dirname + ')';
throw new Error('dihelper incapable of finding specified file for require filename:' +
requireMe + ', ' + directories);
}
if (typeof provides === 'undefined' && !exists(requireResult.$provide)) {
//TODO(@davequick): also look for annotations once ES6, for now can't because you would
// receive a different di instance if you did require('di/dist/cjs/annotations') so class
// equalities would not work. Once all is ES6, then instanceof for the classes should work
// and add it here. For now you have to have a string or object on yourmodule.$provide or
// it will be overwritten.
provides = requireMe;
}
return next(requireResult, provides, injects);
} | javascript | {
"resource": ""
} |
q261 | requireWrapper | train | function requireWrapper(requireMe, provides, injects, directory) {
return _require(requireMe, provides, injects, directory, simpleWrapper);
} | javascript | {
"resource": ""
} |
q262 | requireGlob | train | function requireGlob(pattern) {
return _.map(glob.sync(pattern), function (file) {
var required = require(file);
resolveProvide(required);
resolveInjects(required);
return required;
});
} | javascript | {
"resource": ""
} |
q263 | injectableFromFile | train | function injectableFromFile(requireMe, provides, injects, directory) {
return _require(requireMe, provides, injects, directory, injectableWrapper);
} | javascript | {
"resource": ""
} |
q264 | requireOverrideInjection | train | function requireOverrideInjection(requireMe, provides, injects, directory) {
return _require(requireMe, provides, injects, directory, overrideInjection);
} | javascript | {
"resource": ""
} |
q265 | env | train | function env(environment) {
environment = environment || {};
if ('object' === typeof process && 'object' === typeof process.env) {
env.merge(environment, process.env);
}
if ('undefined' !== typeof window) {
if ('string' === window.name && window.name.length) {
env.merge(environment, env.parse(window.name));
}
if (window.localStorage) {
try { env.merge(environment, env.parse(window.localStorage.env || window.localStorage.debug)); }
catch (e) {}
}
if (
'object' === typeof window.location
&& 'string' === typeof window.location.hash
&& window.location.hash.length
) {
env.merge(environment, env.parse(window.location.hash.charAt(0) === '#'
? window.location.hash.slice(1)
: window.location.hash
));
}
}
//
// Also add lower case variants to the object for easy access.
//
var key, lower;
for (key in environment) {
lower = key.toLowerCase();
if (!(lower in environment)) {
environment[lower] = environment[key];
}
}
return environment;
} | javascript | {
"resource": ""
} |
q266 | moveToDest | train | function moveToDest(srcDir, destDir) {
if (!this.options.cleanOutput) {
return srcDir;
}
var content, cssDir, src;
var copiedCache = this.copiedCache || {};
var copied = {};
var options = this.options;
var tree = this.walkDir(srcDir, {cache: this.cache});
var cache = tree.paths;
var generated = tree.changed;
var linkedFiles = [];
for (var i = 0; i < generated.length; i += 1) {
file = generated[i];
if (cache[file].isDirectory || copiedCache[file] === cache[file].statsHash) {
continue;
}
src = srcDir + '/' + file;
if (file.substr(-4) === '.css') {
content = fs.readFileSync(src);
cssDir = path.dirname(file);
while ((linkedFile = urlRe.exec(content))) {
linkedFile = (linkedFile[1][0] === '/') ? linkedFile[1].substr(1) : path.normalize(cssDir + '/' + linkedFile[1]);
linkedFiles.push(linkedFile);
}
}
mkdirp(destDir + '/' + path.dirname(file));
symlinkOrCopy(src, destDir + '/' + file);
copied[file] = cache[file].statsHash;
}
for (i = 0; i < linkedFiles.length; i += 1) {
file = linkedFiles[i];
if (file in copied) { continue; }
if (!cache[file] || copiedCache[file] !== cache[file].statsHash) {
copied[file] = cache[file] && cache[file].statsHash;
mkdirp(destDir + '/' + path.dirname(file));
symlinkOrCopy(srcDir + '/' + file, destDir + '/' + file);
}
}
this.copiedCache = copied;
return destDir;
} | javascript | {
"resource": ""
} |
q267 | CompassCompiler | train | function CompassCompiler(inputTree, files, options) {
options = arguments.length > 2 ? (options || {}) : (files || {});
if (arguments.length > 2) {
console.log('[broccoli-compass] DEPRECATION: passing files to broccoli-compass constructor as second parameter is deprecated, ' +
'use options.files instead');
options.files = files;
}
if (!(this instanceof CompassCompiler)) {
return new CompassCompiler(inputTree, options);
}
if (options.exclude) {
console.log('[broccoli-compass] DEPRECATION: The exclude option has been deprecated in favour of the `cleanOutput` option');
}
this.options = merge(true, this.defaultOptions);
merge(this.options, options);
options = this.options;
options.files = (options.files instanceof Array) ? options.files : [];
this.generateCmdLine();
this.inputTree = inputTree;
} | javascript | {
"resource": ""
} |
q268 | addToCache | train | function addToCache(filename, obj) {
if(cacheOn)
{
var x = cache[filename];
if(!x)
x = cache[filename] = {};
x.mtime = obj.mtime || x.mtime;
x.etag = obj.etag || x.etag;
x.size = obj.size || x.size;
}
} | javascript | {
"resource": ""
} |
q269 | train | function () {
var self = this;
var indexes = self.$indexes || [];
return Promise.try (function() {
assert.arrayOfObject(indexes, '$indexes should be an array of object');
//validate and assign default arguments before creating indexes
//if necessary, convert the indexes format to fit for different database
_.forEach(indexes, function(indexItem) {
assert.object(indexItem.keys, 'Database index keys should be object');
if (indexItem.options) {
assert.object(indexItem.options, 'Database index options should be object');
}
else {
indexItem.options = {};
}
});
return indexes;
})
.then(function(indexes) {
if (_.isEmpty(indexes)) {
return;
}
switch(self.connection.toString()) {
case 'mongo':
return Promise.map(indexes, function(indexItem) {
return self.createMongoIndexes([indexItem.keys, indexItem.options]);
});
default:
break;
}
});
} | javascript | {
"resource": ""
} |
|
q270 | train | function (criteria) {
var identity = this.identity;
return this.findOne(criteria).then(function (record) {
if (!record) {
throw new Errors.NotFoundError(
'Could not find %s with criteria %j.'.format(
pluralize.singular(identity),
criteria
), {
criteria: criteria,
collection: identity
});
}
return record;
});
} | javascript | {
"resource": ""
} |
|
q271 | train | function (criteria, document) {
var self = this;
return this.needOne(criteria).then(function (target) {
return self.update(target.id, document).then(function (documents) {
return documents[0];
});
});
} | javascript | {
"resource": ""
} |
|
q272 | train | function (criteria) {
var self = this;
return this.needOne(criteria).then(function (target) {
return self.destroy(target.id).then(function (documents) {
return documents[0];
});
});
} | javascript | {
"resource": ""
} |
|
q273 | BaseError | train | function BaseError(message, context) {
this.message = message;
this.name = this.constructor.name;
this.context = context || {};
Error.captureStackTrace(this, BaseError);
} | javascript | {
"resource": ""
} |
q274 | Subscription | train | function Subscription (queue, options) {
assert.object(queue, 'queue');
assert.object(options, 'options');
this.MAX_DISPOSE_RETRIES = 3;
this.retryDelay = 1000;
this.queue = queue;
this.options = options;
this._disposed = false;
} | javascript | {
"resource": ""
} |
q275 | Perf | train | function Perf (stats, name, filter, rename) {
this.stats = stats
this.name = name
this.filter = filter || function () { return true }
this.rename = rename || function (name) { return name }
} | javascript | {
"resource": ""
} |
q276 | getMedian | train | function getMedian (args) {
if (!args.length) return 0
var numbers = args.slice(0).sort(function (a, b) { return a - b })
var middle = Math.floor(numbers.length / 2)
var isEven = numbers.length % 2 === 0
var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle]
return Number(res.toFixed(2))
} | javascript | {
"resource": ""
} |
q277 | Message | train | function Message (data, headers, deliveryInfo) {
assert.object(data);
assert.object(headers);
assert.object(deliveryInfo);
this.data = Message.factory(data, deliveryInfo.type);
this.headers = headers;
this.deliveryInfo = deliveryInfo;
} | javascript | {
"resource": ""
} |
q278 | profileServiceFactory | train | function profileServiceFactory(
Constants,
Promise,
_,
DbRenderable,
Util )
{
Util.inherits(ProfileService, DbRenderable);
/**
* ProfileService is a singleton object which provides key/value store
* access to profile files loaded from disk via FileLoader.
* @constructor
* @extends {FileLoader}
*/
function ProfileService () {
DbRenderable.call(this, {
directory: Constants.Profiles.Directory,
collectionName: 'profiles'
});
}
ProfileService.prototype.get = function (name, raw, scope ) {
return ProfileService.super_.prototype.get.call(this, name, scope)
.then(function(profile) {
if (profile && raw) {
return profile.contents;
} else {
return profile;
}
});
};
return new ProfileService();
} | javascript | {
"resource": ""
} |
q279 | loggerFactory | train | function loggerFactory(
events,
Constants,
assert,
_,
util,
stack,
nconf
) {
var levels = _.keys(Constants.Logging.Levels);
function getCaller (depth) {
var current = stack.get()[depth];
var file = current.getFileName().replace(
Constants.WorkingDirectory,
''
) + ':' + current.getLineNumber();
return file.replace(/^node_modules/, '');
}
function Logger (module) {
var provides = util.provides(module);
if (provides !== undefined) {
this.module = provides;
} else {
if (_.isFunction(module)) {
this.module = module.name;
} else {
this.module = module || 'No Module';
}
}
}
Logger.prototype.log = function (level, message, context) {
assert.isIn(level, levels);
assert.string(message, 'message');
// Exit if the log level of this message is less than the minimum log level.
var minLogLevel = nconf.get('minLogLevel');
if ((minLogLevel === undefined) || (typeof minLogLevel !== 'number')) {
minLogLevel = 0;
}
if (Constants.Logging.Levels[level] < minLogLevel) {
return;
}
events.log({
name: Constants.Name,
host: Constants.Host,
module: this.module,
level: level,
message: message,
context: context,
timestamp: new Date().toISOString(),
caller: getCaller(3),
subject: 'Server'
});
};
_.forEach(levels, function(level) {
Logger.prototype[level] = function (message, context) {
this.log(level, message, context);
};
});
Logger.prototype.deprecate = function (message, frames) {
console.error([
'DEPRECATION:',
this.module,
'-',
message,
getCaller(frames || 2)
].join(' '));
};
Logger.initialize = function (module) {
return new Logger(module);
};
return Logger;
} | javascript | {
"resource": ""
} |
q280 | GraphProgress | train | function GraphProgress(graph, graphDescription) {
assert.object(graph, 'graph');
assert.string(graphDescription, 'graphDescription');
this.graph = graph;
this.data = {
graphId: graph.instanceId,
nodeId: graph.node,
graphName: graph.name || 'Not available',
status: graph._status,
progress: {
description: graphDescription || 'Not available',
}
};
this._calculateGraphProgress();
} | javascript | {
"resource": ""
} |
q281 | HttpTool | train | function HttpTool(){
this.settings = {};
this.urlObject = {};
this.dataToWrite = '';
// ********** Helper Functions/Members **********
var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'];
/**
* Make sure that settings has at least property of url and method.
* @return {boolean} whether settings is valid.
*/
this.isSettingValid = function(settings){
if (_.isEmpty(settings)) {
return false;
}
if ( ! (settings.hasOwnProperty('url') && settings.hasOwnProperty('method'))) {
return false;
}
if (_.isEmpty(settings.url) || _.isEmpty(settings.method)) {
return false;
}
if (_.indexOf(validMethods, settings.method) === -1) {
return false;
}
return true;
};
/**
* Parse and convert setting into a urlObject that suitable for
* http/https module in NodeJs.
* @return {object} - the object that suitable for Node http/https module.
*/
this.setupUrlOptions = function(settings) {
var urlTool = require('url');
var urlObject = {};
// Parse the string into url options
if (typeof (settings.url) === 'string') {
urlObject = urlTool.parse(settings.url);
}
else {
urlObject = settings.url;
}
// set the REST options
urlObject.method = settings.method;
// set up the REST headers
if (! _.isEmpty(settings.headers)){
urlObject.headers = settings.headers;
}
else {
urlObject.headers = {};
}
urlObject.headers['Content-Length'] = 0;
if (settings.hasOwnProperty('data')){
switch (typeof settings.data) {
case 'object':
this.dataToWrite = JSON.stringify(settings.data);
urlObject.headers['Content-Type'] = 'application/json';
break;
case 'string':
this.dataToWrite = settings.data;
break;
default:
throw new TypeError("Data field can only be object or string," +
" but got " + (typeof settings.data));
}
urlObject.headers['Content-Length'] = Buffer.byteLength(this.dataToWrite);
}
if (! _.isEmpty(settings.credential)){
if (!_.isEmpty(settings.credential.password) &&
_.isEmpty(settings.credential.username)) {
throw new Error('Please provide username and password '+
'for basic authentication.');
}
else {
urlObject.auth = settings.credential.username +':'+
settings.credential.password;
}
}
// set the protolcol paramter
if (urlObject.protocol.substr(-1) !== ':') {
urlObject.protocol = urlObject.protocol + ':';
}
urlObject.rejectUnauthorized = settings.verifySSL || false;
urlObject.recvTimeoutMs = settings.recvTimeoutMs;
return urlObject;
};
} | javascript | {
"resource": ""
} |
q282 | templateServiceFactory | train | function templateServiceFactory(
Constants,
Promise,
_,
DbRenderable,
Util )
{
Util.inherits(TemplateService, DbRenderable);
/**
* TemplateService is a singleton object which provides key/value store
* access to template files loaded from disk via FileLoader.
* @constructor
* @extends {FileLoader}
*/
function TemplateService () {
DbRenderable.call(this, {
directory: Constants.Templates.Directory,
collectionName: 'templates'
});
}
return new TemplateService();
} | javascript | {
"resource": ""
} |
q283 | normalizeFgArgs | train | function normalizeFgArgs(fgArgs) {
var program, args, cb;
var processArgsEnd = fgArgs.length;
var lastFgArg = fgArgs[fgArgs.length - 1];
if (typeof lastFgArg === "function") {
cb = lastFgArg;
processArgsEnd -= 1;
} else {
cb = function(done) { done(); };
}
if (Array.isArray(fgArgs[0])) {
program = fgArgs[0][0];
args = fgArgs[0].slice(1);
} else {
program = fgArgs[0];
args = Array.isArray(fgArgs[1]) ? fgArgs[1] : fgArgs.slice(1, processArgsEnd);
}
return {program: program, args: args, cb: cb};
} | javascript | {
"resource": ""
} |
q284 | Conrec | train | function Conrec(drawContour) {
if (!drawContour) {
var c = this;
c.contours = {};
/**
* drawContour - interface for implementing the user supplied method to
* render the countours.
*
* Draws a line between the start and end coordinates.
*
* @param startX - start coordinate for X
* @param startY - start coordinate for Y
* @param endX - end coordinate for X
* @param endY - end coordinate for Y
* @param contourLevel - Contour level for line.
*/
this.drawContour = function(startX, startY, endX, endY, contourLevel, k) {
var cb = c.contours[k];
if (!cb) {
cb = c.contours[k] = new ContourBuilder(contourLevel);
}
cb.addSegment({x: startX, y: startY}, {x: endX, y: endY});
}
this.contourList = function() {
var l = [];
var a = c.contours;
for (var k in a) {
var s = a[k].s;
var level = a[k].level;
while (s) {
var h = s.head;
var l2 = [];
l2.level = level;
l2.k = k;
while (h && h.p) {
l2.push(h.p);
h = h.next;
}
l.push(l2);
s = s.next;
}
}
l.sort(function(a, b) { return a.k - b.k });
return l;
}
} else {
this.drawContour = drawContour;
}
this.h = new Array(5);
this.sh = new Array(5);
this.xh = new Array(5);
this.yh = new Array(5);
} | javascript | {
"resource": ""
} |
q285 | failFirstRequest | train | function failFirstRequest(server) {
var listeners = server.listeners("request"),
existingListeners = [];
for (var i = 0, l = listeners.length; i < l; i++) {
existingListeners[i] = listeners[i];
}
server.removeAllListeners("request");
server.on("request", function (req, res) {
var fireExisting = true;
if (/^\/transport\/server\//.test(req.url)) {
fireExisting = onTransportRequest(req, res);
}
if (fireExisting) {
for (var i = 0, l = existingListeners.length; i < l; i++) {
existingListeners[i].call(server, req, res);
}
}
});
var count = 0;
function onTransportRequest(req, res) {
count += 1;
console.log("REQUEST", req.url, count);
if (count === 1) {
console.log(" Fail request");
res.end("<An unparsable response>");
return false;
}
return true;
}
} | javascript | {
"resource": ""
} |
q286 | instrumental_send | train | function instrumental_send(payload) {
var state = "cold";
var tlsOptionsVariation = selectTlsOptionsVariation();
var client = instrumental_connection(host, port, tlsOptionsVariation, function(_client){
state = "connected";
var cleanString = function(value) {
return String(value).replace(/\s+/g, "_");
}
// Write the authentication header
_client.write(
"hello version node/statsd-instrumental-backend/" + cleanString(package.version) +
" hostname " + cleanString(hostname) +
" pid " + cleanString(process.pid) +
" runtime " + cleanString("node/" + process.versions.node) +
" platform " + cleanString(process.platform + "-" + process.arch) + "\n" +
"authenticate " + key + "\n"
);
});
// We need to handle the timeout. I think we should only care about read
// timeouts. That is we write out data, if we don't hear back in timeout
// seconds then the data probably hasn't reached the server.
client.setTimeout(timeout, function() {
// ZOMG FAILED WRITING WE ARE BAD AT COMPUTER SCIENCE
if(state == "connected") {
// We're waiting to hear back from the server and it has timed out. It's
// unlikely that the server will suddenly wake up and send us our data so
// lets disconnect and go shopping.
client.end();
}
});
// HOW WE HANDLE ERRORS. We should probably reconnect, maybe retry.
client.addListener("error", function(exception){
if(debug) {
log("Client error:", exception);
}
instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000);
});
// What do we do when instrumental talks to us
var totalBuffer = "";
client.on("data", function(buffer) {
totalBuffer = totalBuffer + buffer;
if(debug) {
log("Received:", buffer);
}
// Authorization success
if(totalBuffer == "ok\nok\n") {
error = false;
if(debug) {
log("Sending:", payload.join("\n"));
}
client.end(payload.join("\n") + "\n", function() {
tlsOptionsVariation.lastSuccessAt = new Date();
if (debug) log("payload sent, tlsOptionsVariation: ", tlsOptionsVariation);
state = "sent";
});
instrumentalStats.last_flush = Math.round(new Date().getTime() / 1000);
// Authorization failure
} else if(totalBuffer.length >= "ok\nok\n".length) {
// TODO: Actually do something with this
error = true;
instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000);
}
});
} | javascript | {
"resource": ""
} |
q287 | getRoutes | train | function getRoutes(feature) {
const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js');
if (vio.fileNotExists(targetPath)) return [];
const theAst = ast.getAst(targetPath);
const arr = [];
let rootPath = '';
let indexRoute = null;
traverse(theAst, {
ObjectExpression(path) {
const node = path.node;
const props = node.properties;
if (!props.length) return;
const obj = {};
props.forEach(p => {
if (_.has(p, 'key.name') && !p.computed) {
obj[p.key.name] = p;
}
});
if (obj.path && obj.component) {
// in a route config, if an object expression has both 'path' and 'component' property, then it's a route config
arr.push({
path: _.get(obj.path, 'value.value'), // only string literal supported
component: _.get(obj.component, 'value.name'), // only identifier supported
isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean
node: {
start: node.start,
end: node.end,
},
});
}
if (obj.isIndex && obj.component && !indexRoute) {
// only find the first index route
indexRoute = {
component: _.get(obj.component, 'value.name'),
};
}
if (obj.path && obj.childRoutes && !rootPath) {
rootPath = _.get(obj.path, 'value.value');
if (!rootPath) rootPath = '$none'; // only find the first rootPath
}
},
});
const prjRootPath = getRootRoutePath();
if (rootPath === '$none') rootPath = prjRootPath;
else if (!/^\//.test(rootPath)) rootPath = prjRootPath + '/' + rootPath;
rootPath = rootPath.replace(/\/+/, '/');
arr.forEach(item => {
if (!/^\//.test(item.path)) {
item.path = (rootPath + '/' + item.path).replace(/\/+/, '/');
}
});
if (indexRoute) {
indexRoute.path = rootPath;
arr.unshift(indexRoute);
}
return arr;
} | javascript | {
"resource": ""
} |
q288 | getKey | train | function getKey(context) {
if (context.getModelKey) {
return context.getModelKey();
}
return context.props.name || context.props.key || context.props.ref;
} | javascript | {
"resource": ""
} |
q289 | modelOrCollectionOnOrOnce | train | function modelOrCollectionOnOrOnce(modelType, type, args, _this, _modelOrCollection) {
var modelEvents = getModelAndCollectionEvents(modelType, _this);
var ev = args[0];
var cb = args[1];
var ctx = args[2];
modelEvents[ev] = {
type: type,
ev: ev,
cb: cb,
ctx: ctx
};
function _on(modelOrCollection) {
_this[type === 'on' ? 'listenTo' : 'listenToOnce'](modelOrCollection, ev, cb, ctx);
}
if (modelEvents.__bound) {
if (_modelOrCollection) {
_on(_modelOrCollection);
} else {
getModelOrCollections(modelType, _this, _on);
}
}
} | javascript | {
"resource": ""
} |
q290 | getModelAndCollectionEvents | train | function getModelAndCollectionEvents(type, context) {
var key = '__' + type + CAP_EVENTS,
modelEvents = getState(key, context);
if (!modelEvents) {
modelEvents = {};
var stateVar = {};
stateVar[key] = modelEvents;
setState(stateVar, context, false);
}
return modelEvents;
} | javascript | {
"resource": ""
} |
q291 | pushLoadingState | train | function pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force) {
var currentLoads = getState(stateName, context),
currentlyLoading = currentLoads && currentLoads.length;
if (!currentLoads) {
currentLoads = [];
}
if (_.isArray(currentLoads)) {
if (_.indexOf(currentLoads, xhrEvent) >= 0) {
if (!force) {
return;
}
} else {
currentLoads.push(xhrEvent);
}
if (!currentlyLoading) {
var toSet = {};
toSet[stateName] = currentLoads;
setState(toSet, context);
}
xhrEvent.on('complete', function() {
popLoadingState(xhrEvent, stateName, modelOrCollection, context);
});
}
} | javascript | {
"resource": ""
} |
q292 | popLoadingState | train | function popLoadingState(xhrEvent, stateName, modelOrCollection, context) {
var currentLoads = getState(stateName, context);
if (_.isArray(currentLoads)) {
var i = currentLoads.indexOf(xhrEvent);
while (i >= 0) {
currentLoads.splice(i, 1);
i = currentLoads.indexOf(xhrEvent);
}
if (!currentLoads.length) {
var toSet = {};
toSet[stateName] = undefined;
setState(toSet, context);
}
}
} | javascript | {
"resource": ""
} |
q293 | joinCurrentModelActivity | train | function joinCurrentModelActivity(method, stateName, modelOrCollection, context, force) {
var xhrActivity = modelOrCollection[xhrModelLoadingAttribute];
if (xhrActivity) {
_.each(xhrActivity, function(xhrEvent) {
if (!method || method === ALL_XHR_ACTIVITY || xhrEvent.method === method) {
// this is one that is applicable
pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force);
}
});
}
} | javascript | {
"resource": ""
} |
q294 | train | function() {
var keys = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : undefined;
return {
getInitialState: function() {
var self = this;
modelOrCollectionEventHandler(typeData.type, keys || 'updateOn', this, '{key}', function() {
self.deferUpdate();
});
}
};
} | javascript | {
"resource": ""
} |
|
q295 | train | function(type, attributes, isCheckable, classAttributes) {
return React.createClass(_.extend({
mixins: ['modelAware'],
render: function() {
var props = {};
var defaultValue = getModelValue(this);
if (isCheckable) {
props.defaultChecked = defaultValue;
} else {
props.defaultValue = defaultValue;
}
return React.DOM[type](_.extend(props, attributes, this.props,
{onChange: twoWayBinding(this)}), this.props.children);
},
getValue: function() {
if (this.isMounted()) {
if (isCheckable) {
var el = this.getDOMNode();
return el.checked ? true : false;
} else {
return getElementValue(this);
}
}
},
getDOMValue: function() {
if (this.isMounted()) {
return getElementValue(this);
}
}
}, classAttributes));
} | javascript | {
"resource": ""
} |
|
q296 | loadPlugin | train | function loadPlugin(pluginRoot, noUI) {
// noUI flag is used for loading dev plugins whose ui is from webpack dev server
try {
// const pkgJson = require(paths.join(pluginRoot, 'package.json'));
const pluginInstance = {};
// Core part
const coreIndex = paths.join(pluginRoot, 'core/index.js');
if (fs.existsSync(coreIndex)) {
Object.assign(pluginInstance, require(coreIndex));
}
// UI part
if (!noUI && fs.existsSync(path.join(pluginRoot, 'build/main.js'))) {
pluginInstance.ui = {
root: path.join(pluginRoot, 'build'),
};
}
// Plugin meta defined in package.json
const pkgJsonPath = path.join(pluginRoot, 'package.json');
let pkgJson = null;
if (fs.existsSync(pkgJsonPath)) {
pkgJson = fs.readJsonSync(pkgJsonPath);
['appType', 'name', 'featureFiles'].forEach(key => {
if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) {
if (key === 'name') {
let name = pkgJson.name;
if (name.startsWith('rekit-plugin')) name = name.replace('rekit-plugin-', '');
pluginInstance.name = name;
} else {
pluginInstance[key] = pkgJson[key] || null;
}
}
});
if (pkgJson.rekitPlugin) {
Object.keys(pkgJson.rekitPlugin).forEach(key => {
if (!pluginInstance.hasOwnProperty(key)) {
pluginInstance[key] = pkgJson.rekitPlugin[key];
}
});
}
}
return pluginInstance;
} catch (e) {
logger.warn(`Failed to load plugin: ${pluginRoot}`, e);
}
return null;
} | javascript | {
"resource": ""
} |
q297 | addPlugin | train | function addPlugin(plugin) {
if (!plugin) {
return;
}
if (!needFilterPlugin) {
console.warn('You are adding a plugin after getPlugins is called.');
}
needFilterPlugin = true;
if (!plugin.name) {
console.log('plugin: ', plugin);
throw new Error('Each plugin should have a name.');
}
if (_.find(allPlugins, { name: plugin.name })) {
console.warn('You should not add a plugin with same name: ' + plugin.name);
return;
}
allPlugins.push(plugin);
} | javascript | {
"resource": ""
} |
q298 | generate | train | function generate(targetPath, args) {
if (
!args.template &&
(!args.templateFile || (args.templateFile && !vio.fileExists(args.templateFile)))
) {
const err = new Error(`No template file found: ${args.templateFile}`);
err.code = 'TEMPLATE_FILE_NOT_FOUND';
throw err;
}
const tpl = args.template || vio.getContent(args.templateFile);
const compiled = _.template(tpl, args.templateOptions || {});
const result = compiled(args.context || {});
vio.save(targetPath, result);
} | javascript | {
"resource": ""
} |
q299 | train | function() {
var data = {};
if (this.data && !isObject(this.data)) {
return this.data;
}
// TODO - don't do this yet until virt properties are checked
// var keys = Object.keys(this);
var keys = Object.keys(this.data ? this.data : this);
for (var i = 0, n = keys.length; i < n; i++) {
var key = keys[i];
if (key in this.constructor.prototype || key.charCodeAt(0) === 95) {
continue;
}
data[key] = this[key];
}
return data;
} | javascript | {
"resource": ""
} |