Dataset Viewer
code
stringlengths 28
313k
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
74
| language
stringclasses 1
value | repo
stringlengths 5
60
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
async function getCLS(url) {
const browser = await puppeteer.launch({
args: ['--no-sandbox'],
timeout: 10000,
});
try {
const page = await browser.newPage();
const client = await page.target().createCDPSession();
await client.send('Network.enable');
await client.send('ServiceWorker.enable');
await page.emulateNetworkConditions(puppeteer.networkConditions['Good 3G']);
await page.emulateCPUThrottling(4);
await page.emulate(phone);
// inject a function with the code from
// https://web.dev/cls/#measure-cls-in-javascript
await page.evaluateOnNewDocument(calculateShifts);
await page.goto(url, {waitUntil: 'load', timeout: 60000});
const cls = await page.evaluate(() => {
return window.cumulativeLayoutShiftScore;
});
browser.close();
return cls;
} catch (error) {
console.log(error);
browser.close();
}
}
|
Get cumulative layout shift for a URL
@param {String} url - url to measure
@return {Number} - cumulative layout shift
|
getCLS
|
javascript
|
addyosmani/puppeteer-webperf
|
cumulative-layout-shift.js
|
https://github.com/addyosmani/puppeteer-webperf/blob/master/cumulative-layout-shift.js
|
Apache-2.0
|
async function getLCP(url) {
const browser = await puppeteer.launch({
args: ['--no-sandbox'],
timeout: 10000,
});
try {
const page = await browser.newPage();
const client = await page.target().createCDPSession();
await client.send('Network.enable');
await client.send('ServiceWorker.enable');
await page.emulateNetworkConditions(puppeteer.networkConditions['Good 3G']);
await page.emulateCPUThrottling(4);
await page.emulate(phone);
await page.evaluateOnNewDocument(calculateLCP);
await page.goto(url, {waitUntil: 'load', timeout: 60000});
const lcp = await page.evaluate(() => {
return window.largestContentfulPaint;
});
browser.close();
return lcp;
} catch (error) {
console.log(error);
browser.close();
}
}
|
Get LCP for a provided URL
@param {*} url
@return {Number} lcp
|
getLCP
|
javascript
|
addyosmani/puppeteer-webperf
|
largest-contentful-paint.js
|
https://github.com/addyosmani/puppeteer-webperf/blob/master/largest-contentful-paint.js
|
Apache-2.0
|
async function lighthouseFromPuppeteer(url, options, config = null) {
// Launch chrome using chrome-launcher
const chrome = await chromeLauncher.launch(options);
options.port = chrome.port;
// Connect chrome-launcher to puppeteer
const resp = await util.promisify(request)(`http://localhost:${options.port}/json/version`);
const {webSocketDebuggerUrl} = JSON.parse(resp.body);
const browser = await puppeteer.connect({
browserWSEndpoint: webSocketDebuggerUrl,
});
// Run Lighthouse
const {lhr} = await lighthouse(url, options, config);
await browser.disconnect();
await chrome.kill();
const html = reportGenerator.generateReport(lhr, 'html');
fs.writeFile('report.html', html, function(err) {
if (err) throw err;
});
}
|
Perform a Lighthouse run
@param {String} url - url The URL to test
@param {Object} options - Optional settings for the Lighthouse run
@param {Object} [config=null] - Configuration for the Lighthouse run. If
not present, the default config is used.
|
lighthouseFromPuppeteer
|
javascript
|
addyosmani/puppeteer-webperf
|
lighthouse-report.js
|
https://github.com/addyosmani/puppeteer-webperf/blob/master/lighthouse-report.js
|
Apache-2.0
|
constructor (name, cpus) {
this.name = name || 'HTTP';
this._watchers = null;
this._error = null;
this._server = null;
this._port = null;
this._paused = false;
this.cpus = parseInt(cpus) || os.cpus().length;
this.children = [];
process.on('exit', (code) => {
console.log(`[${this.name}.Daemon] Shutdown: Exited with code ${code}`);
});
}
|
Multi-process HTTP Daemon that resets when files changed (in development)
@class
|
constructor
|
javascript
|
acode/FunctionScript
|
lib/daemon.js
|
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
|
MIT
|
start(port) {
this._port = port || 3000;
console.log(`[${this.name}.Daemon] Startup: Initializing`);
if ((process.env.NODE_ENV || 'development') === 'development') {
this.watch('', (changes) => {
changes.forEach(change => {
console.log(`[${this.name}.Daemon] ${change.event[0].toUpperCase()}${change.event.substr(1)}: ${change.path}`);
});
this.children.forEach(child => child.send({invalidate: true}));
this.children = [];
!this.children.length && this.unwatch() && this.start();
});
}
this._server && this._server.close();
this._server = null;
for (var i = 0; i < this.cpus; i++) {
let child = cluster.fork();
this.children.push(child);
child.on('message', this.message.bind(this));
child.on('exit', this.exit.bind(this, child));
}
console.log(`[${this.name}.Daemon] Startup: Spawning HTTP Workers`);
}
|
Starts the Daemon. If all application services fail, will launch a
dummy error app on the port provided.
@param {Number} port
|
start
|
javascript
|
acode/FunctionScript
|
lib/daemon.js
|
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
|
MIT
|
idle() {
let port = this._port || 3000;
this._server = http
.createServer((req, res) => {
this.error(req, res, this._error);
req.connection.destroy();
})
.listen(port);
console.log(`[${this.name}.Daemon] Idle: Unable to spawn HTTP Workers, listening on port ${port}`);
}
|
Daemon failed to load, set it in idle state (accept connections, give dummy response)
|
idle
|
javascript
|
acode/FunctionScript
|
lib/daemon.js
|
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
|
MIT
|
exit(child, code) {
let index = this.children.indexOf(child);
if (index === -1) {
return;
}
this.children.splice(index, 1);
if (code === 0) {
child = cluster.fork();
this.children.push(child);
child.on('message', this.message.bind(this));
child.on('exit', this.exit.bind(this, child));
}
if (this.children.length === 0) {
this.idle();
}
}
|
Shut down a child process given a specific exit code. (Reboot if clean shutdown.)
@param {child_process} child
@param {Number} code Exit status codes
|
exit
|
javascript
|
acode/FunctionScript
|
lib/daemon.js
|
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
|
MIT
|
logError(error) {
this._error = error;
this._server = null;
console.log(`[${this.name}.Daemon] ${error.name}: ${error.message}`);
console.log(error.stack);
}
|
Log an error on the Daemon
@param {Error} error
|
logError
|
javascript
|
acode/FunctionScript
|
lib/daemon.js
|
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
|
MIT
|
unwatch() {
clearInterval(this._watchers.interval);
this._watchers = null;
return true;
}
|
Stops watching a directory tree for changes
|
unwatch
|
javascript
|
acode/FunctionScript
|
lib/daemon.js
|
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
|
MIT
|
watch (root, onChange) {
let cwd = process.cwd();
function watchDir (dirname, watchers) {
if (!watchers) {
watchers = Object.create(null);
watchers.directories = Object.create(null);
watchers.interval = null;
}
let pathname = path.join(cwd, dirname);
let files = fs.readdirSync(pathname);
watchers.directories[dirname] = Object.create(null);
files.forEach(function (name) {
if (name === 'node_modules' || name.indexOf('.') === 0) {
return;
}
let filename = path.join(dirname, name);
let fullPath = path.join(cwd, filename);
let stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
watchDir(filename, watchers);
return;
}
watchers.directories[dirname][name] = stat;
});
return watchers;
}
let watchers = watchDir(root || '');
let self = this;
watchers.iterate = function (changes) {
if (!fs.existsSync(path.join(process.cwd(), '.daemon.pause'))) {
// Skip a cycle if just unpaused...
if (!this._paused) {
if (changes.length) {
onChange.call(self, changes);
}
} else {
this._paused = false;
}
} else {
this._paused = true;
}
};
watchers.interval = setInterval(function() {
let changes = [];
Object.keys(watchers.directories).forEach(function (dirname) {
let dir = watchers.directories[dirname];
let dirPath = path.join(cwd, dirname);
if (!fs.existsSync(dirPath)) {
delete watchers.directories[dirname];
changes.push({event: 'removed', path: dirPath});
} else {
let files = fs.readdirSync(dirPath);
let added = [];
let contents = Object.create(null);
files.forEach(function (filename) {
if (filename === 'node_modules' || filename.indexOf('.') === 0) {
return;
}
let fullPath = path.join(dirPath, filename);
let stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
let checkPath = path.join(dirname, filename);
if (!watchers.directories[checkPath]) {
watchDir(checkPath, watchers);
}
} else {
if (!dir[filename]) {
added.push([filename, stat]);
changes.push({event: 'added', path: fullPath});
return;
}
if (stat.mtime.toString() !== dir[filename].mtime.toString()) {
dir[filename] = stat;
changes.push({event: 'modified', path: fullPath});
}
contents[filename] = true;
}
});
Object.keys(dir).forEach(function (filename) {
let fullPath = path.join(cwd, dirname, filename);
if (!contents[filename]) {
delete dir[filename];
changes.push({event: 'removed', path: fullPath});
}
});
added.forEach(function (change) {
let [filename, stat] = change;
dir[filename] = stat;
});
}
});
watchers.iterate(changes);
}, 1000);
return this._watchers = watchers;
}
|
Watches a directory tree for changes
@param {string} root Directory tree to watch
@param {function} onChange Method to be executed when a change is detected
|
watch
|
javascript
|
acode/FunctionScript
|
lib/daemon.js
|
https://github.com/acode/FunctionScript/blob/master/lib/daemon.js
|
MIT
|
renderComponent = (jsx, renderToDOM) => {
if (renderToDOM) {
const testDiv = document.createElement('div');
document.body.appendChild(testDiv);
return render(jsx, testDiv);
}
return ReactTestUtils.renderIntoDocument(jsx);
}
|
getBoundingClientRect() does not work correctly with ReactTestUtils.renderIntoDocument().
So for testing resizing we need ReactDOM.render()
|
renderComponent
|
javascript
|
tomkp/react-split-pane
|
test/assertions/Asserter.js
|
https://github.com/tomkp/react-split-pane/blob/master/test/assertions/Asserter.js
|
MIT
|
renderChunk(code, chunk, opts) {
if (opts.format === 'umd') {
// Can swap this out with MagicString.replace() when we bump it:
// https://github.com/developit/microbundle/blob/f815a01cb63d90b9f847a4dcad2a64e6b2f8596f/src/index.js#L657-L671
const s = new MagicString(code);
const minified = code.match(
/([a-zA-Z$_]+)="undefined"!=typeof globalThis\?globalThis:(\1\|\|self)/,
);
if (minified) {
s.overwrite(
minified.index,
minified.index + minified[0].length,
minified[2],
);
}
const unminified = code.match(
/(global *= *)typeof +globalThis *!== *['"]undefined['"] *\? *globalThis *: *(global *\|\| *self)/,
);
if (unminified) {
s.overwrite(
unminified.index,
unminified.index + unminified[0].length,
unminified[1] + unminified[2],
);
}
return {
code: s.toString(),
map: s.generateMap({ hires: true }),
};
}
}
|
',
plugins: [
[
require.resolve('babel-plugin-transform-replace-expressions'),
{ replace: defines },
],
],
}),
customBabel()({
babelHelpers: 'bundled',
extensions: EXTENSIONS,
// use a regex to make sure to exclude eventual hoisted packages
exclude: /\/node_modules\//,
passPerPreset: true, // @see https://babeljs.io/docs/en/options#passperpreset
custom: {
defines,
modern,
compress: options.compress !== false,
targets: options.target === 'node' ? { node: '12' } : undefined,
pragma: options.jsx,
pragmaFrag: options.jsxFragment,
typescript: !!useTypescript,
jsxImportSource: options.jsxImportSource || false,
},
}),
options.compress !== false && [
terser({
compress: Object.assign(
{
keep_infinity: true,
pure_getters: true,
// Ideally we'd just get Terser to respect existing Arrow functions...
// unsafe_arrows: true,
passes: 10,
},
typeof minifyOptions.compress === 'boolean'
? minifyOptions.compress
: minifyOptions.compress || {},
),
format: {
// By default, Terser wraps function arguments in extra parens to trigger eager parsing.
// Whether this is a good idea is way too specific to guess, so we optimize for size by default:
wrap_func_args: false,
comments: /^\s*([@#]__[A-Z]+__\s*$|@cc_on)/,
preserve_annotations: true,
},
module: modern,
ecma: modern ? 2017 : 5,
toplevel: modern || format === 'cjs' || format === 'es',
mangle:
typeof minifyOptions.mangle === 'boolean'
? minifyOptions.mangle
: Object.assign({}, minifyOptions.mangle || {}),
nameCache,
}),
nameCache && {
// before hook
options: loadNameCache,
// after hook
writeBundle() {
if (writeMeta && nameCache) {
let filename = getNameCachePath();
let json = JSON.stringify(
nameCache,
null,
nameCacheIndentTabs ? '\t' : 2,
);
if (endsWithNewLine) json += EOL;
fs.writeFile(filename, json, () => {});
}
},
},
],
options.visualize && visualizer(),
// NOTE: OMT only works with amd and esm
// Source: https://github.com/surma/rollup-plugin-off-main-thread#config
useWorkerLoader && (format === 'es' || modern) && OMT(),
/** @type {import('rollup').Plugin}
|
renderChunk
|
javascript
|
developit/microbundle
|
src/index.js
|
https://github.com/developit/microbundle/blob/master/src/index.js
|
MIT
|
function safeVariableName(name) {
const normalized = removeScope(name).toLowerCase();
const identifier = normalized.replace(INVALID_ES3_IDENT, '');
return camelCase(identifier);
}
|
Turn a package name into a valid reasonably-unique variable name
@param {string} name
|
safeVariableName
|
javascript
|
developit/microbundle
|
src/utils.js
|
https://github.com/developit/microbundle/blob/master/src/utils.js
|
MIT
|
function toReplacementExpression(value, name) {
// --define A="1",B='true' produces string:
const matches = value.match(/^(['"])(.+)\1$/);
if (matches) {
return [JSON.stringify(matches[2]), name];
}
// --define @assign=Object.assign replaces expressions with expressions:
if (name[0] === '@') {
return [value, name.substring(1)];
}
// --define A=1,B=true produces int/boolean literal:
if (/^(true|false|\d+)$/i.test(value)) {
return [value, name];
}
// default: string literal
return [JSON.stringify(value), name];
}
|
Convert booleans and int define= values to literals.
This is more intuitive than `microbundle --define A=1` producing A="1".
|
toReplacementExpression
|
javascript
|
developit/microbundle
|
src/lib/option-normalization.js
|
https://github.com/developit/microbundle/blob/master/src/lib/option-normalization.js
|
MIT
|
function parseMappingArgument(globalStrings, processValue) {
const globals = {};
globalStrings.split(',').forEach(globalString => {
let [key, value] = globalString.split('=');
if (processValue) {
const r = processValue(value, key);
if (r !== undefined) {
if (Array.isArray(r)) {
[value, key] = r;
} else {
value = r;
}
}
}
globals[key] = value;
});
return globals;
}
|
Parses values of the form "$=jQuery,React=react" into key-value object pairs.
|
parseMappingArgument
|
javascript
|
developit/microbundle
|
src/lib/option-normalization.js
|
https://github.com/developit/microbundle/blob/master/src/lib/option-normalization.js
|
MIT
|
function fastRestTransform({ template, types: t }) {
const slice = template`var IDENT = Array.prototype.slice;`;
const VISITOR = {
RestElement(path, state) {
if (path.parentKey !== 'params') return;
// Create a global _slice alias
let slice = state.get('slice');
if (!slice) {
slice = path.scope.generateUidIdentifier('slice');
state.set('slice', slice);
}
// _slice.call(arguments) or _slice.call(arguments, 1)
const args = [t.identifier('arguments')];
if (path.key) args.push(t.numericLiteral(path.key));
const sliced = t.callExpression(
t.memberExpression(t.clone(slice), t.identifier('call')),
args,
);
const ident = path.node.argument;
const binding = path.scope.getBinding(ident.name);
if (binding.referencePaths.length !== 0) {
// arguments access requires a non-Arrow function:
const func = path.parentPath;
if (t.isArrowFunctionExpression(func)) {
func.arrowFunctionToExpression();
}
if (
binding.constant &&
binding.referencePaths.length === 1 &&
sameArgumentsObject(binding.referencePaths[0], func, t)
) {
// one usage, never assigned - replace usage inline
binding.referencePaths[0].replaceWith(sliced);
} else {
// unknown usage, create a binding
const decl = t.variableDeclaration('var', [
t.variableDeclarator(t.clone(ident), sliced),
]);
func.get('body').unshiftContainer('body', decl);
}
}
path.remove();
},
};
return {
name: 'transform-fast-rest',
visitor: {
Program(path, state) {
const childState = new Map();
const useHelper = state.opts.helper === true; // defaults to false
if (!useHelper) {
let inlineHelper;
if (state.opts.literal === false) {
inlineHelper = template.expression.ast`Array.prototype.slice`;
} else {
inlineHelper = template.expression.ast`[].slice`;
}
childState.set('slice', inlineHelper);
}
path.traverse(VISITOR, childState);
const name = childState.get('slice');
if (name && useHelper) {
const helper = slice({ IDENT: name });
t.addComment(helper.declarations[0].init, 'leading', '#__PURE__');
path.unshiftContainer('body', helper);
}
},
},
};
}
|
Transform ...rest parameters to [].slice.call(arguments,offset).
Demo: https://astexplorer.net/#/gist/70aaa0306db9a642171ef3e2f35df2e0/576c150f647e4936fa6960e0453a11cdc5d81f21
Benchmark: https://jsperf.com/rest-arguments-babel-pr-9152/4
@param {object} opts
@param {babel.template} opts.template
@param {babel.types} opts.types
@returns {babel.PluginObj}
|
fastRestTransform
|
javascript
|
developit/microbundle
|
src/lib/transform-fast-rest.js
|
https://github.com/developit/microbundle/blob/master/src/lib/transform-fast-rest.js
|
MIT
|
function Assertion (obj, msg, stack) {
flag(this, 'ssfi', stack || arguments.callee);
flag(this, 'object', obj);
flag(this, 'message', msg);
}
|
# .use(function)
Provides a way to extend the internals of Chai
@param {Function}
@returns {this} for chaining
@api public
|
Assertion
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function an (type, msg) {
if (msg) flag(this, 'message', msg);
type = type.toLowerCase();
var obj = flag(this, 'object')
, article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a ';
this.assert(
type === _.type(obj)
, 'expected #{this} to be ' + article + type
, 'expected #{this} not to be ' + article + type
);
}
|
### .a(type)
The `a` and `an` assertions are aliases that can be
used either as language chains or to assert a value's
type.
// typeof
expect('test').to.be.a('string');
expect({ foo: 'bar' }).to.be.an('object');
expect(null).to.be.a('null');
expect(undefined).to.be.an('undefined');
// language chain
expect(foo).to.be.an.instanceof(Foo);
@name a
@alias an
@param {String} type
@param {String} message _optional_
@api public
|
an
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function includeChainingBehavior () {
flag(this, 'contains', true);
}
|
### .include(value)
The `include` and `contain` assertions can be used as either property
based language chains or as methods to assert the inclusion of an object
in an array or a substring in a string. When used as language chains,
they toggle the `contain` flag for the `keys` assertion.
expect([1,2,3]).to.include(2);
expect('foobar').to.contain('foo');
expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
@name include
@alias contain
@param {Object|String|Number} obj
@param {String} message _optional_
@api public
|
includeChainingBehavior
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function checkArguments () {
var obj = flag(this, 'object')
, type = Object.prototype.toString.call(obj);
this.assert(
'[object Arguments]' === type
, 'expected #{this} to be arguments but got ' + type
, 'expected #{this} to not be arguments'
);
}
|
### .arguments
Asserts that the target is an arguments object.
function test () {
expect(arguments).to.be.arguments;
}
@name arguments
@alias Arguments
@api public
|
checkArguments
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertEqual (val, msg) {
if (msg) flag(this, 'message', msg);
var obj = flag(this, 'object');
if (flag(this, 'deep')) {
return this.eql(val);
} else {
this.assert(
val === obj
, 'expected #{this} to equal #{exp}'
, 'expected #{this} to not equal #{exp}'
, val
, this._obj
, true
);
}
}
|
### .equal(value)
Asserts that the target is strictly equal (`===`) to `value`.
Alternately, if the `deep` flag is set, asserts that
the target is deeply equal to `value`.
expect('hello').to.equal('hello');
expect(42).to.equal(42);
expect(1).to.not.equal(true);
expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' });
expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
@name equal
@alias equals
@alias eq
@alias deep.equal
@param {Mixed} value
@param {String} message _optional_
@api public
|
assertEqual
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertEql(obj, msg) {
if (msg) flag(this, 'message', msg);
this.assert(
_.eql(obj, flag(this, 'object'))
, 'expected #{this} to deeply equal #{exp}'
, 'expected #{this} to not deeply equal #{exp}'
, obj
, this._obj
, true
);
}
|
### .eql(value)
Asserts that the target is deeply equal to `value`.
expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]);
@name eql
@alias eqls
@param {Mixed} value
@param {String} message _optional_
@api public
|
assertEql
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertAbove (n, msg) {
if (msg) flag(this, 'message', msg);
var obj = flag(this, 'object');
if (flag(this, 'doLength')) {
new Assertion(obj, msg).to.have.property('length');
var len = obj.length;
this.assert(
len > n
, 'expected #{this} to have a length above #{exp} but got #{act}'
, 'expected #{this} to not have a length above #{exp}'
, n
, len
);
} else {
this.assert(
obj > n
, 'expected #{this} to be above ' + n
, 'expected #{this} to be at most ' + n
);
}
}
|
### .above(value)
Asserts that the target is greater than `value`.
expect(10).to.be.above(5);
Can also be used in conjunction with `length` to
assert a minimum length. The benefit being a
more informative error message than if the length
was supplied directly.
expect('foo').to.have.length.above(2);
expect([ 1, 2, 3 ]).to.have.length.above(2);
@name above
@alias gt
@alias greaterThan
@param {Number} value
@param {String} message _optional_
@api public
|
assertAbove
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertLeast (n, msg) {
if (msg) flag(this, 'message', msg);
var obj = flag(this, 'object');
if (flag(this, 'doLength')) {
new Assertion(obj, msg).to.have.property('length');
var len = obj.length;
this.assert(
len >= n
, 'expected #{this} to have a length at least #{exp} but got #{act}'
, 'expected #{this} to have a length below #{exp}'
, n
, len
);
} else {
this.assert(
obj >= n
, 'expected #{this} to be at least ' + n
, 'expected #{this} to be below ' + n
);
}
}
|
### .least(value)
Asserts that the target is greater than or equal to `value`.
expect(10).to.be.at.least(10);
Can also be used in conjunction with `length` to
assert a minimum length. The benefit being a
more informative error message than if the length
was supplied directly.
expect('foo').to.have.length.of.at.least(2);
expect([ 1, 2, 3 ]).to.have.length.of.at.least(3);
@name least
@alias gte
@param {Number} value
@param {String} message _optional_
@api public
|
assertLeast
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertBelow (n, msg) {
if (msg) flag(this, 'message', msg);
var obj = flag(this, 'object');
if (flag(this, 'doLength')) {
new Assertion(obj, msg).to.have.property('length');
var len = obj.length;
this.assert(
len < n
, 'expected #{this} to have a length below #{exp} but got #{act}'
, 'expected #{this} to not have a length below #{exp}'
, n
, len
);
} else {
this.assert(
obj < n
, 'expected #{this} to be below ' + n
, 'expected #{this} to be at least ' + n
);
}
}
|
### .below(value)
Asserts that the target is less than `value`.
expect(5).to.be.below(10);
Can also be used in conjunction with `length` to
assert a maximum length. The benefit being a
more informative error message than if the length
was supplied directly.
expect('foo').to.have.length.below(4);
expect([ 1, 2, 3 ]).to.have.length.below(4);
@name below
@alias lt
@alias lessThan
@param {Number} value
@param {String} message _optional_
@api public
|
assertBelow
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertMost (n, msg) {
if (msg) flag(this, 'message', msg);
var obj = flag(this, 'object');
if (flag(this, 'doLength')) {
new Assertion(obj, msg).to.have.property('length');
var len = obj.length;
this.assert(
len <= n
, 'expected #{this} to have a length at most #{exp} but got #{act}'
, 'expected #{this} to have a length above #{exp}'
, n
, len
);
} else {
this.assert(
obj <= n
, 'expected #{this} to be at most ' + n
, 'expected #{this} to be above ' + n
);
}
}
|
### .most(value)
Asserts that the target is less than or equal to `value`.
expect(5).to.be.at.most(5);
Can also be used in conjunction with `length` to
assert a maximum length. The benefit being a
more informative error message than if the length
was supplied directly.
expect('foo').to.have.length.of.at.most(4);
expect([ 1, 2, 3 ]).to.have.length.of.at.most(3);
@name most
@alias lte
@param {Number} value
@param {String} message _optional_
@api public
|
assertMost
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertInstanceOf (constructor, msg) {
if (msg) flag(this, 'message', msg);
var name = _.getName(constructor);
this.assert(
flag(this, 'object') instanceof constructor
, 'expected #{this} to be an instance of ' + name
, 'expected #{this} to not be an instance of ' + name
);
}
|
### .instanceof(constructor)
Asserts that the target is an instance of `constructor`.
var Tea = function (name) { this.name = name; }
, Chai = new Tea('chai');
expect(Chai).to.be.an.instanceof(Tea);
expect([ 1, 2, 3 ]).to.be.instanceof(Array);
@name instanceof
@param {Constructor} constructor
@param {String} message _optional_
@alias instanceOf
@api public
|
assertInstanceOf
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertOwnProperty (name, msg) {
if (msg) flag(this, 'message', msg);
var obj = flag(this, 'object');
this.assert(
obj.hasOwnProperty(name)
, 'expected #{this} to have own property ' + _.inspect(name)
, 'expected #{this} to not have own property ' + _.inspect(name)
);
}
|
### .ownProperty(name)
Asserts that the target has an own property `name`.
expect('test').to.have.ownProperty('length');
@name ownProperty
@alias haveOwnProperty
@param {String} name
@param {String} message _optional_
@api public
|
assertOwnProperty
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertLengthChain () {
flag(this, 'doLength', true);
}
|
### .length(value)
Asserts that the target's `length` property has
the expected value.
expect([ 1, 2, 3]).to.have.length(3);
expect('foobar').to.have.length(6);
Can also be used as a chain precursor to a value
comparison for the length property.
expect('foo').to.have.length.above(2);
expect([ 1, 2, 3 ]).to.have.length.above(2);
expect('foo').to.have.length.below(4);
expect([ 1, 2, 3 ]).to.have.length.below(4);
expect('foo').to.have.length.within(2,4);
expect([ 1, 2, 3 ]).to.have.length.within(2,4);
@name length
@alias lengthOf
@param {Number} length
@param {String} message _optional_
@api public
|
assertLengthChain
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function assertKeys (keys) {
var obj = flag(this, 'object')
, str
, ok = true;
keys = keys instanceof Array
? keys
: Array.prototype.slice.call(arguments);
if (!keys.length) throw new Error('keys required');
var actual = Object.keys(obj)
, len = keys.length;
// Inclusion
ok = keys.every(function(key){
return ~actual.indexOf(key);
});
// Strict
if (!flag(this, 'negate') && !flag(this, 'contains')) {
ok = ok && keys.length == actual.length;
}
// Key string
if (len > 1) {
keys = keys.map(function(key){
return _.inspect(key);
});
var last = keys.pop();
str = keys.join(', ') + ', and ' + last;
} else {
str = _.inspect(keys[0]);
}
// Form
str = (len > 1 ? 'keys ' : 'key ') + str;
// Have / include
str = (flag(this, 'contains') ? 'contain ' : 'have ') + str;
// Assertion
this.assert(
ok
, 'expected #{this} to ' + str
, 'expected #{this} to not ' + str
);
}
|
### .keys(key1, [key2], [...])
Asserts that the target has exactly the given keys, or
asserts the inclusion of some keys when using the
`include` or `contain` modifiers.
expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']);
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar');
@name keys
@alias key
@param {String...|Array} keys
@api public
|
assertKeys
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function AssertionError (options) {
options = options || {};
this.message = options.message;
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
this.showDiff = options.showDiff;
if (options.stackStartFunction && Error.captureStackTrace) {
var stackStartFunction = options.stackStartFunction;
Error.captureStackTrace(this, stackStartFunction);
}
}
|
# AssertionError (constructor)
Create a new assertion error based on the Javascript
`Error` prototype.
**Options**
- message
- actual
- expected
- operator
- startStackFunction
@param {Object} options
@api public
|
AssertionError
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function loadShould () {
// modify Object.prototype to have `should`
Object.defineProperty(Object.prototype, 'should',
{
set: function (value) {
// See https://github.com/chaijs/chai/issues/86: this makes
// `whatever.should = someValue` actually set `someValue`, which is
// especially useful for `global.should = require('chai').should()`.
//
// Note that we have to use [[DefineProperty]] instead of [[Put]]
// since otherwise we would trigger this very setter!
Object.defineProperty(this, 'should', {
value: value,
enumerable: true,
configurable: true,
writable: true
});
}
, get: function(){
if (this instanceof String || this instanceof Number) {
return new Assertion(this.constructor(this));
} else if (this instanceof Boolean) {
return new Assertion(this == true);
}
return new Assertion(this);
}
, configurable: true
});
var should = {};
should.equal = function (val1, val2, msg) {
new Assertion(val1, msg).to.equal(val2);
};
should.Throw = function (fn, errt, errs, msg) {
new Assertion(fn, msg).to.Throw(errt, errs);
};
should.exist = function (val, msg) {
new Assertion(val, msg).to.exist;
}
// negation
should.not = {}
should.not.equal = function (val1, val2, msg) {
new Assertion(val1, msg).to.not.equal(val2);
};
should.not.Throw = function (fn, errt, errs, msg) {
new Assertion(fn, msg).to.not.Throw(errt, errs);
};
should.not.exist = function (val, msg) {
new Assertion(val, msg).to.not.exist;
}
should['throw'] = should['Throw'];
should.not['throw'] = should.not['Throw'];
return should;
}
|
### .closeTo(actual, expected, delta, [message])
Asserts that the target is equal `expected`, to within a +/- `delta` range.
assert.closeTo(1.5, 1, 0.5, 'numbers are close');
@name closeTo
@param {Number} actual
@param {Number} expected
@param {Number} delta
@param {String} message
@api public
|
loadShould
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
assert = function () {
var result = method.apply(this, arguments);
return result === undefined ? this : result;
}
|
### addChainableMethod (ctx, name, method, chainingBehavior)
Adds a method to an object, such that the method can also be chained.
utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) {
var obj = utils.flag(this, 'object');
new chai.Assertion(obj).to.be.equal(str);
});
Can also be accessed directly from `chai.Assertion`.
chai.Assertion.addChainableMethod('foo', fn, chainingBehavior);
The result can then be used as both a method assertion, executing both `method` and
`chainingBehavior`, or as a language chain, which only executes `chainingBehavior`.
expect(fooStr).to.be.foo('bar');
expect(fooStr).to.be.foo.equal('foo');
@param {Object} ctx object to which the method is added
@param {String} name of method to add
@param {Function} method function to be used for `name`, when called
@param {Function} chainingBehavior function to be called every time the property is accessed
@name addChainableMethod
@api public
|
assert
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function _deepEqual(actual, expected, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return actual === expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, memos);
}
}
|
### addProperty (ctx, name, getter)
Adds a property to the prototype of an object.
utils.addProperty(chai.Assertion.prototype, 'foo', function () {
var obj = utils.flag(this, 'object');
new chai.Assertion(obj).to.be.instanceof(Foo);
});
Can also be accessed directly from `chai.Assertion`.
chai.Assertion.addProperty('foo', fn);
Then can be used as any other assertion.
expect(myFoo).to.be.foo;
@param {Object} ctx object to which the property is added
@param {String} name of property to add
@param {Function} getter function to be used for name
@name addProperty
@api public
|
_deepEqual
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function parsePath (path) {
var str = path.replace(/\[/g, '.[')
, parts = str.match(/(\\\.|[^.]+?)+/g);
return parts.map(function (value) {
var re = /\[(\d+)\]$/
, mArr = re.exec(value)
if (mArr) return { i: parseFloat(mArr[1]) };
else return { p: value };
});
}
|
### .getPathValue(path, object)
This allows the retrieval of values in an
object given a string path.
var obj = {
prop1: {
arr: ['a', 'b', 'c']
, str: 'Hello'
}
, prop2: {
arr: [ { nested: 'Universe' } ]
, str: 'Hello again!'
}
}
The following would be the results.
getPathValue('prop1.str', obj); // Hello
getPathValue('prop1.att[2]', obj); // b
getPathValue('prop2.arr[0].nested', obj); // Universe
@param {String} path
@param {Object} object
@returns {Object} value or `undefined`
@name getPathValue
@api public
|
parsePath
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function addProperty(property) {
if (result.indexOf(property) === -1) {
result.push(property);
}
}
|
### .getProperties(object)
This allows the retrieval of property names of an object, enumerable or not,
inherited or not.
@param {Object} object
@returns {Array}
@name getProperties
@api public
|
addProperty
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function inspect(obj, showHidden, depth, colors) {
var ctx = {
showHidden: showHidden,
seen: [],
stylize: function (str) { return str; }
};
return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth));
}
|
Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Boolean} showHidden Flag that shows hidden (not enumerable)
properties of objects.
@param {Number} depth Depth in which to descend in object. Default is 2.
@param {Boolean} colors Flag to turn on ANSI escape codes to color the
output. Default is false (no coloring).
|
inspect
|
javascript
|
dobtco/formbuilder
|
test/vendor/js/chai.js
|
https://github.com/dobtco/formbuilder/blob/master/test/vendor/js/chai.js
|
MIT
|
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
|
Mark a function for special use by Sizzle
@param {Function} fn The function to mark
|
markFunction
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
|
Support testing using an element
@param {Function} fn Passed the created div and expects a boolean result
|
assert
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
|
Adds the same handler for all of the specified attrs
@param {String} attrs Pipe-separated list of attributes
@param {Function} handler The method that will be applied
|
addHandle
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
|
Checks document order of two siblings
@param {Element} a
@param {Element} b
@returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
|
siblingCheck
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
|
Returns a function to use in pseudos for input types
@param {String} type
|
createInputPseudo
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
|
Returns a function to use in pseudos for buttons
@param {String} type
|
createButtonPseudo
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
|
Returns a function to use in pseudos for positionals
@param {Function} fn
|
createPositionalPseudo
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
|
Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem
|
tokenize
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function objToPaths(obj) {
var ret = {},
separator = DeepModel.keyPathSeparator;
for (var key in obj) {
var val = obj[key];
if (val && val.constructor === Object && !_.isEmpty(val)) {
//Recursion for embedded objects
var obj2 = objToPaths(val);
for (var key2 in obj2) {
var val2 = obj2[key2];
ret[key + separator + key2] = val2;
}
} else {
ret[key] = val;
}
}
return ret;
}
|
Takes a nested object and returns a shallow object keyed with the path names
e.g. { "level1.level2": "value" }
@param {Object} Nested object e.g. { level1: { level2: 'value' } }
@return {Object} Shallow object with path names e.g. { 'level1.level2': 'value' }
|
objToPaths
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function getNested(obj, path, return_exists) {
var separator = DeepModel.keyPathSeparator;
var fields = path.split(separator);
var result = obj;
return_exists || (return_exists === false);
for (var i = 0, n = fields.length; i < n; i++) {
if (return_exists && !_.has(result, fields[i])) {
return false;
}
result = result[fields[i]];
if (result == null && i < n - 1) {
result = {};
}
if (typeof result === 'undefined') {
if (return_exists)
{
return true;
}
return result;
}
}
if (return_exists)
{
return true;
}
return result;
}
|
@param {Object} Object to fetch attribute from
@param {String} Object path e.g. 'user.name'
@return {Mixed}
|
getNested
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
function setNested(obj, path, val, options) {
options = options || {};
var separator = DeepModel.keyPathSeparator;
var fields = path.split(separator);
var result = obj;
for (var i = 0, n = fields.length; i < n && result !== undefined ; i++) {
var field = fields[i];
//If the last in the path, set the value
if (i === n - 1) {
options.unset ? delete result[field] : result[field] = val;
} else {
//Create the child object if it doesn't exist, or isn't an object
if (typeof result[field] === 'undefined' || ! _.isObject(result[field])) {
result[field] = {};
}
//Move onto the next part of the path
result = result[field];
}
}
}
|
@param {Object} obj Object to fetch attribute from
@param {String} path Object path e.g. 'user.name'
@param {Object} [options] Options
@param {Boolean} [options.unset] Whether to delete the value
@param {Mixed} Value to set
|
setNested
|
javascript
|
dobtco/formbuilder
|
vendor/js/vendor.js
|
https://github.com/dobtco/formbuilder/blob/master/vendor/js/vendor.js
|
MIT
|
filterFn = function(fn) {
return fn.type === event;
}
|
mui delegate events
@param {type} event
@param {type} selector
@param {type} callback
@returns {undefined}
|
filterFn
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
function update(fn) {
return function(value) {
var classes = self.className.split(/\s+/),
index = classes.indexOf(value);
fn(classes, index, value);
self.className = classes.join(" ");
};
}
|
mui fixed classList
@param {type} document
@returns {undefined}
|
update
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
getDistance = function(p1, p2, props) {
if(!props) {
props = ['x', 'y'];
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return sqrt((x * x) + (y * y));
}
|
angle
@param {type} p1
@param {type} p2
@returns {Number}
|
getDistance
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
getAngle = function(p1, p2, props) {
if(!props) {
props = ['x', 'y'];
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return atan2(y, x) * 180 / Math.PI;
}
|
rotation
@param {Object} start
@param {Object} end
|
getAngle
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
getDirection = function(x, y) {
if(x === y) {
return '';
}
if(abs(x) >= abs(y)) {
return x > 0 ? 'left' : 'right';
}
return y > 0 ? 'up' : 'down';
}
|
detect gestures
@param {type} event
@param {type} touch
@returns {undefined}
|
getDirection
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
handle = function(event, touch) {
var session = $.gestures.session;
var options = this.options;
var now = $.now();
switch (event.type) {
case $.EVENT_MOVE:
if (now - flickStartTime > 300) {
flickStartTime = now;
session.flickStart = touch.center;
}
break;
case $.EVENT_END:
case $.EVENT_CANCEL:
touch.flick = false;
if (session.flickStart && options.flickMaxTime > (now - flickStartTime) && touch.distance > options.flickMinDistince) {
touch.flick = true;
touch.flickTime = now - flickStartTime;
touch.flickDistanceX = touch.center.x - session.flickStart.x;
touch.flickDistanceY = touch.center.y - session.flickStart.y;
$.trigger(session.target, name, touch);
$.trigger(session.target, name + touch.direction, touch);
}
break;
}
}
|
mui gesture flick[left|right|up|down]
@param {type} $
@param {type} name
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
handle = function(event, touch) {
var session = $.gestures.session;
var options = this.options;
switch (event.type) {
case $.EVENT_END:
if (!touch.isFinal) {
return;
}
var target = session.target;
if (!target || (target.disabled || (target.classList && target.classList.contains('mui-disabled')))) {
return;
}
if (touch.distance < options.tapMaxDistance && touch.deltaTime < options.tapMaxTime) {
if ($.options.gestureConfig.doubletap && lastTarget && (lastTarget === target)) { //same target
if (lastTapTime && (touch.timestamp - lastTapTime) < options.tapMaxInterval) {
$.trigger(target, 'doubletap', touch);
lastTapTime = $.now();
lastTarget = target;
return;
}
}
$.trigger(target, name, touch);
lastTapTime = $.now();
lastTarget = target;
}
break;
}
}
|
mui gesture tap and doubleTap
@param {type} $
@param {type} name
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
handle = function(event, touch) {
var session = $.gestures.session;
var options = this.options;
switch (event.type) {
case $.EVENT_START:
clearTimeout(timer);
timer = setTimeout(function() {
$.trigger(session.target, name, touch);
}, options.holdTimeout);
break;
case $.EVENT_MOVE:
if (touch.distance > options.holdThreshold) {
clearTimeout(timer);
}
break;
case $.EVENT_END:
case $.EVENT_CANCEL:
clearTimeout(timer);
break;
}
}
|
mui gesture hold
@param {type} $
@param {type} name
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
handle = function(event, touch) {
var session = $.gestures.session;
var options = this.options;
switch (event.type) {
case $.EVENT_START:
if ($.options.gestureConfig.hold) {
timer && clearTimeout(timer);
timer = setTimeout(function() {
touch.hold = true;
$.trigger(session.target, name, touch);
}, options.holdTimeout);
}
break;
case $.EVENT_MOVE:
break;
case $.EVENT_END:
case $.EVENT_CANCEL:
if (timer) {
clearTimeout(timer) && (timer = null);
$.trigger(session.target, 'release', touch);
}
break;
}
}
|
mui gesture pinch
@param {type} $
@param {type} name
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
ajaxBeforeSend = function(xhr, settings) {
var context = settings.context
if(settings.beforeSend.call(context, xhr, settings) === false) {
return false;
}
}
|
mui ajax
@param {type} $
@returns {undefined}
|
ajaxBeforeSend
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
findOffCanvasContainer = function(target) {
parentNode = target.parentNode;
if (parentNode) {
if (parentNode.classList.contains(CLASS_OFF_CANVAS_WRAP)) {
return parentNode;
} else {
parentNode = parentNode.parentNode;
if (parentNode.classList.contains(CLASS_OFF_CANVAS_WRAP)) {
return parentNode;
}
}
}
}
|
Popovers
@param {type} $
@param {type} window
@param {type} document
@param {type} name
@param {type} undefined
@returns {undefined}
|
findOffCanvasContainer
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
setStyle = function(popover, display, top, left) {
var style = popover.style;
if (typeof display !== 'undefined')
style.display = display;
if (typeof top !== 'undefined')
style.top = top + 'px';
if (typeof left !== 'undefined')
style.left = left + 'px';
}
|
segmented-controllers
@param {type} $
@param {type} window
@param {type} document
@param {type} undefined
@returns {undefined}
|
setStyle
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
handle = function(event, target) {
if (target.classList && target.classList.contains(CLASS_SWITCH)) {
return target;
}
return false;
}
|
Tableviews
@param {type} $
@param {type} window
@param {type} document
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
radioOrCheckboxClick = function(event) {
var type = event.target && event.target.type || '';
if (type === 'radio' || type === 'checkbox') {
return;
}
var classList = cell.classList;
if (classList.contains('mui-radio')) {
var input = cell.querySelector('input[type=radio]');
if (input) {
// input.click();
if (!input.disabled && !input.readOnly) {
input.checked = !input.checked;
$.trigger(input, 'change');
}
}
} else if (classList.contains('mui-checkbox')) {
var input = cell.querySelector('input[type=checkbox]');
if (input) {
// input.click();
if (!input.disabled && !input.readOnly) {
input.checked = !input.checked;
$.trigger(input, 'change');
}
}
}
}
|
Popup(alert,confirm,prompt)
@param {Object} $
@param {Object} window
@param {Object} document
|
radioOrCheckboxClick
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
closePopup = function() {
if (popupStack.length) {
popupStack[popupStack.length - 1]['close']();
return true;
} else {
return false;
}
}
|
Input(TODO resize)
@param {type} $
@param {type} window
@param {type} document
@returns {undefined}
|
closePopup
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
Button = function(element, options) {
this.element = element;
this.options = $.extend({}, defaultOptions, options);
if (!this.options.loadingText) {
this.options.loadingText = defaultOptions.loadingText;
}
if (this.options.loadingIcon === null) {
this.options.loadingIcon = 'mui-spinner';
if ($.getStyles(this.element, 'color') === 'rgb(255, 255, 255)') {
this.options.loadingIcon += ' ' + 'mui-spinner-white';
}
}
this.isInput = this.element.tagName === 'INPUT';
this.resetHTML = this.isInput ? this.element.value : this.element.innerHTML;
this.state = '';
}
|
Button
@param {type} $
@param {type} window
@param {type} document
@returns {undefined}
|
Button
|
javascript
|
dcloudio/mui
|
dist/js/mui.js
|
https://github.com/dcloudio/mui/blob/master/dist/js/mui.js
|
MIT
|
webviewGroupContext = function(id, webviewOptions, groupContext) {
this.id = id;
this.url = webviewOptions.url;
this.options = webviewOptions;
this.groupContext = groupContext;
this.webview = false;
this.inited = false;
}
|
@param {Object} id
@param {Object} webviewOptions
|
webviewGroupContext
|
javascript
|
dcloudio/mui
|
examples/hello-mui/js/webviewGroup.js
|
https://github.com/dcloudio/mui/blob/master/examples/hello-mui/js/webviewGroup.js
|
MIT
|
createStandardXHR = function () {
try {
return new window.XMLHttpRequest();
} catch( e ) {
return false;
}
}
|
Decodes a base64 string.
@param {String}
input The string to decode.
|
createStandardXHR
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/easemob.im-1.0.5.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/easemob.im-1.0.5.js
|
MIT
|
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
|
Checks a node for validity as a Sizzle context
@param {Element|Object=} context
@returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
|
testContext
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
MIT
|
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
|
A low-level selection function that works with Sizzle's compiled
selector functions
@param {String|Function} selector A selector or a pre-compiled
selector function built with Sizzle.compile
@param {Element} context
@param {Array} [results]
@param {Array} [seed] A set of elements to match against
|
winnow
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
MIT
|
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
|
Clean-up method for dom ready events
|
detach
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
MIT
|
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
|
The ready event handler and self cleanup method
|
completed
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
MIT
|
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
|
Determines whether an object can have data
|
dataAttr
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
MIT
|
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
|
Retrieve the actual display of a element
@param {String} name nodeName of the element
@param {Object} doc Document object
|
actualDisplay
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
MIT
|
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
|
Try to determine the default display value of an element
@param {String} nodeName
|
defaultDisplay
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/jquery-1.11.1.js
|
MIT
|
function core_sha1(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = new Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
var i, j, t, olda, oldb, oldc, oldd, olde;
for (i = 0; i < x.length; i += 16)
{
olda = a;
oldb = b;
oldc = c;
oldd = d;
olde = e;
for (j = 0; j < 80; j++)
{
if (j < 16) { w[j] = x[i + j]; }
else { w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); }
t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return [a, b, c, d, e];
}
|
Decodes a base64 string.
@param {String} input The string to decode.
|
core_sha1
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/strophe-custom-2.0.0.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/strophe-custom-2.0.0.js
|
MIT
|
wrapper = function(handlers, elem) {
while (handlers.length) {
this.deleteHandler(handlers.pop());
}
this._sasl_auth1_cb.bind(this)(elem);
return false;
}
|
PrivateFunction: _sasl_success_cb
_Private_ handler for succesful SASL authentication.
Parameters:
(XMLElement) elem - The matching stanza.
Returns:
false to remove the handler.
|
wrapper
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/strophe-custom-2.0.0.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/strophe-custom-2.0.0.js
|
MIT
|
sendFunc = function () {
req.date = new Date();
if (self._conn.options.customHeaders){
var headers = self._conn.options.customHeaders;
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
req.xhr.setRequestHeader(header, headers[header]);
}
}
}
req.xhr.send(req.data);
}
|
PrivateFunction: _processRequest
_Private_ function to process a request in the queue.
This function takes requests off the queue and sends them and
restarts dead requests.
Parameters:
(Integer) i - The index of the request in the queue.
|
sendFunc
|
javascript
|
dcloudio/mui
|
examples/login/libs/easymob-webim-sdk/strophe-custom-2.0.0.js
|
https://github.com/dcloudio/mui/blob/master/examples/login/libs/easymob-webim-sdk/strophe-custom-2.0.0.js
|
MIT
|
handle = function(event, target) {
var className = target.className || '';
if (typeof className !== 'string') { //svg className(SVGAnimatedString)
className = '';
}
if (className && ~className.indexOf(CLASS_ACTION)) {
if (target.classList.contains($.className('action-back'))) {
event.preventDefault();
}
return target;
}
return false;
}
|
actions
@param {type} $
@param {type} name
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
js/actions.js
|
https://github.com/dcloudio/mui/blob/master/js/actions.js
|
MIT
|
handle = function(event, target) {
if (target.tagName === 'A' && target.hash) {
var modal = document.getElementById(target.hash.replace('#', ''));
if (modal && modal.classList.contains(CLASS_MODAL)) {
return modal;
}
}
return false;
}
|
Modals
@param {type} $
@param {type} window
@param {type} document
@param {type} name
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
js/modals.js
|
https://github.com/dcloudio/mui/blob/master/js/modals.js
|
MIT
|
getScale = function(starts, moves) {
if(starts.length >= 2 && moves.length >= 2) {
var props = ['pageX', 'pageY'];
return getDistance(moves[1], moves[0], props) / getDistance(starts[1], starts[0], props);
}
return 1;
}
|
scale
@param {Object} starts
@param {Object} moves
|
getScale
|
javascript
|
dcloudio/mui
|
js/mui.gestures.js
|
https://github.com/dcloudio/mui/blob/master/js/mui.gestures.js
|
MIT
|
getVelocity = function(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
|
px per ms
@param {Object} deltaTime
@param {Object} x
@param {Object} y
|
getVelocity
|
javascript
|
dcloudio/mui
|
js/mui.gestures.js
|
https://github.com/dcloudio/mui/blob/master/js/mui.gestures.js
|
MIT
|
createCallbackName = function() {
return 'mui_jsonp_callback_' + (callbackIndex++);
}
|
MUI JSONP
varstion 1.0.0
by Houfeng
[email protected]
|
createCallbackName
|
javascript
|
dcloudio/mui
|
js/mui.jsonp.js
|
https://github.com/dcloudio/mui/blob/master/js/mui.jsonp.js
|
MIT
|
handle = function(event, target) {
if (target.tagName === 'A' && target.hash) {
var offcanvas = document.getElementById(target.hash.replace('#', ''));
if (offcanvas) {
var container = findOffCanvasContainer(offcanvas);
if (container) {
$.targets._container = container;
return offcanvas;
}
}
}
return false;
}
|
off-canvas
@param {type} $
@param {type} window
@param {type} document
@param {type} action
@returns {undefined}
|
handle
|
javascript
|
dcloudio/mui
|
js/mui.offcanvas.js
|
https://github.com/dcloudio/mui/blob/master/js/mui.offcanvas.js
|
MIT
|
Toggle = function(element) {
this.element = element;
this.classList = this.element.classList;
this.handle = this.element.querySelector(SELECTOR_SWITCH_HANDLE);
this.init();
this.initEvent();
}
|
Toggles switch
@param {type} $
@param {type} window
@param {type} name
@returns {undefined}
|
Toggle
|
javascript
|
dcloudio/mui
|
js/switches.js
|
https://github.com/dcloudio/mui/blob/master/js/switches.js
|
MIT
|
query = (q, data) => {
return new Promise((resolve, reject) => {
db.query(q, data, (err, res) => (err ? reject(err) : resolve(res)))
})
}
|
Query MySQL as a promise
@param {String} q MySQL Query
@param {Object} data Data needed by the query
@returns {<Promise>} Promise
|
query
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/db.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/db.js
|
MIT
|
c_validator = (field, req) => {
let i = field.charAt(0).toUpperCase() + field.substr(1)
req.checkBody(field, `${i} is empty!!`).notEmpty()
req.checkBody(field, `${i} must be greater than 4`).isLength({ min: 4 })
req.checkBody(field, `${i} must be less than 32`).isLength({ max: 32 })
}
|
Common validators esp. in signup, edit-profile
@param {String} field
@param {Object} req
|
c_validator
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/db.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/db.js
|
MIT
|
toHashtag = async (str, user, post) => {
let hashtags = str.match(/[^|\s]?#[\d\w]+/g)
if (hashtags) {
for (let h of hashtags) {
let hash = h.slice(1)
if (hash.substr(0, 1) !== '#') {
let newHashtag = {
hashtag: h,
post_id: post,
user: user,
hashtag_time: new Date().getTime(),
}
await query('INSERT INTO hashtags SET ?', newHashtag)
}
}
}
}
|
Insert hashtags when post is created
@param {String} str Text which will be used to get hashtags
@param {Number} user UserID
@param {Number} post PostID
|
toHashtag
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/db.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/db.js
|
MIT
|
catchError = (error, res) => {
console.log(error)
res.json({ mssg: 'An error occured!!' })
}
|
Function for outputting error created by try-catch block on express routes
@param {Error} error Error object
@param {Object} res Response object
|
catchError
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/db.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/db.js
|
MIT
|
getWhatOfGrp = async (what, group) => {
let s = await db.query(`SELECT ${what} FROM groups WHERE group_id=?`, [group])
return s.length == 0 ? '' : s[0][what]
}
|
Returns what of a group
@param {String} what Get what eg. name
@param {Number} group Group ID
|
getWhatOfGrp
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Group.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Group.js
|
MIT
|
deleteGroup = async group => {
let posts = await db.query('SELECT post_id FROM posts WHERE group_id=?', [
group,
]),
dltDir = promisify(rmdir)
for (let p of posts) {
await deletePost({ post: p.post_id, when: 'group' })
}
await db.query('DELETE FROM notifications WHERE group_id=?', [group])
await db.query('DELETE FROM group_members WHERE group_id=?', [group])
await db.query('DELETE FROM groups WHERE group_id=?', [group])
DeleteAllOfFolder(`${root}/dist/groups/${group}/`)
await dltDir(`${root}/dist/groups/${group}`)
}
|
Deletes group
@param {Number} group GroupID
|
deleteGroup
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Group.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Group.js
|
MIT
|
joinedGroup = async (user, group) => {
let is = await db.query(
'SELECT COUNT(grp_member_id) AS joined FROM group_members WHERE member=? AND group_id=? LIMIT 1',
[user, group]
)
return db.tf(is[0].joined)
}
|
Returns whether user joined group
@param {Number} user UserID
@param {Number} group GroupID
|
joinedGroup
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Group.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Group.js
|
MIT
|
mutualGroupMembers = async (user, group) => {
let myFollowings = await db.query(
'SELECT follow_system.follow_to AS user, follow_system.follow_to_username AS username FROM follow_system WHERE follow_system.follow_by=?',
[user]
),
grpMembers = await db.query(
'SELECT group_members.member AS user, users.username AS username FROM group_members, users WHERE group_id = ? AND group_members.member = users.id ORDER BY group_members.joined_group DESC',
[group]
),
mutuals = intersectionBy(myFollowings, grpMembers, 'user')
return mutuals
}
|
Returns mutual users of group members and user
@param {Number} user UserID
@param {Number} group GroupID
|
mutualGroupMembers
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Group.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Group.js
|
MIT
|
mail = options =>
new Promise((resolve, reject) => {
let o = {
from: `Instagram <${MAIL}>`,
...options,
}
transporter.sendMail(o, err => {
err ? reject(err) : resolve('Mail Sent!!')
})
})
|
Mails to specified eMail address
@param {Object} options
@param {String} options.to
@param {String} options.subject
@param {String} options.html
@returns {<Promise>} Promise
|
mail
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Mail.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Mail.js
|
MIT
|
getLastMssgTime = async con_id => {
let s = await db.query(
'SELECT MAX(message_time) AS ti FROM messages WHERE con_id = ?',
[con_id]
)
return s[0].ti
}
|
Returns last message time of a comversation
@param {Number} con_id Conversation ID
|
getLastMssgTime
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Message.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Message.js
|
MIT
|
getLastMssg = async con_id => {
let [{ last }] = await db.query(
'SELECT MAX(message_id) AS last FROM messages WHERE con_id = ?',
[con_id]
)
let l = await db.query(
'SELECT message, type, mssg_by FROM messages WHERE message_id=?',
[last]
)
return l[0]
}
|
Returns last message of a comversation
@param {Number} con_id Conversation ID
|
getLastMssg
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Message.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Message.js
|
MIT
|
deleteCon = async con_id => {
try {
let messages = await db.query(
'SELECT message, type FROM messages WHERE con_id=?',
[con_id]
),
deleteMessageFile = promisify(unlink)
for (let m of messages) {
if (m.type != 'text') {
await deleteMessageFile(`${root}/dist/messages/${m.message}`)
}
}
await db.query('DELETE FROM messages WHERE con_id=?', [con_id])
await db.query('DELETE FROM conversations WHERE con_id=?', [con_id])
} catch (error) {
console.log(error)
}
}
|
Deletes a conversation
@param {Number} con_id Conversation ID
|
deleteCon
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Message.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Message.js
|
MIT
|
NotLoggedIn = (req, res, next) => {
req.session.id ? res.redirect('/') : next()
}
|
FOR NOT-LOGGED IN USERS ONLY
|
NotLoggedIn
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Middlewares.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Middlewares.js
|
MIT
|
likedOrNot = async (user, post) => {
let s = await db.query(
'SELECT COUNT(like_id) AS l FROM likes WHERE like_by=? AND post_id=?',
[user, post]
)
return db.tf(s[0].l)
}
|
Returns whther user liked the post
@param {Number} user User ID
@param {Number} post Post ID
@returns {Boolean} Boolean
|
likedOrNot
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Post.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Post.js
|
MIT
|
bookmarkedOrNot = async (user, post) => {
let s = await db.query(
'SELECT COUNT(bkmrk_id) AS b FROM bookmarks WHERE bkmrk_by=? AND post_id=?',
[user, post]
)
return db.tf(s[0].b)
}
|
Returns whether user bookmarked the post
@param {Number} user User ID
@param {Number} post Post ID
@returns {Boolean} Boolean
|
bookmarkedOrNot
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Post.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Post.js
|
MIT
|
isPostMine = async (session, post) => {
let s = await db.query('SELECT user FROM posts WHERE post_id=?', [post])
return s[0].user == session ? true : false
}
|
Returns whether session is the owner of post
@param {Number} session Session ID
@param {Number} post Post ID
@returns {Boolean} Boolean
|
isPostMine
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Post.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Post.js
|
MIT
|
didIShare = async (post, session, user) => {
let s = await db.query(
'SELECT COUNT(share_id) AS post_share FROM shares WHERE share_by=? AND share_to=? AND post_id=?',
[session, user, post]
)
return db.tf(s[0].post_share)
}
|
Returns whether session shares post to user
@param {Number} post Post ID
@param {Number} session Session ID [share_by]
@param {User} user User ID [share_to]
@returns {Boolean} Boolean
|
didIShare
|
javascript
|
yTakkar/React-Instagram-Clone-2.0
|
config/Post.js
|
https://github.com/yTakkar/React-Instagram-Clone-2.0/blob/master/config/Post.js
|
MIT
|
End of preview. Expand
in Data Studio
Javascript CodeSearch Dataset (Shuu12121/javascript-treesitter-dedupe-filtered-datasetsV2)
Dataset Description
This dataset contains JavaScript functions and methods paired with their JSDoc comments, extracted from open-source JavaScript repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.
Each entry includes:
code: The source code of a javascript function or method.docstring: The docstring or Javadoc associated with the function/method.func_name: The name of the function/method.language: The programming language (always "javascript").repo: The GitHub repository from which the code was sourced (e.g., "owner/repo").path: The file path within the repository where the function/method is located.url: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).license: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0"). Additional metrics if available (from Lizard tool):ccn: Cyclomatic Complexity Number.params: Number of parameters of the function/method.nloc: Non-commenting lines of code.token_count: Number of tokens in the function/method.
Dataset Structure
The dataset is divided into the following splits:
train: 129,007 examplesvalidation: 11,797 examplestest: 6,738 examples
Data Collection
The data was collected by:
- Identifying popular and relevant Javascript repositories on GitHub.
- Cloning these repositories.
- Parsing Javascript files (
.js) using tree-sitter to extract functions/methods and their docstrings/Javadoc. - Filtering functions/methods based on code length and presence of a non-empty docstring/Javadoc.
- Using the
lizardtool to calculate code metrics (CCN, NLOC, params). - Storing the extracted data in JSONL format, including repository and license information.
- Splitting the data by repository to ensure no data leakage between train, validation, and test sets.
Intended Use
This dataset can be used for tasks such as:
- Training and evaluating models for code search (natural language to code).
- Code summarization / docstring generation (code to natural language).
- Studies on Javascript code practices and documentation habits.
Licensing
The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD).
Each sample includes its original license information in the license field.
The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0),
but users should respect the original licenses of the underlying code.
Example Usage
from datasets import load_dataset
# Load the dataset
dataset = load_dataset("Shuu12121/javascript-treesitter-dedupe-filtered-datasetsV2")
# Access a split (e.g., train)
train_data = dataset["train"]
# Print the first example
print(train_data[0])
- Downloads last month
- 7