_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q47700
|
train
|
function ( geometry, n ) {
var face, i,
faces = geometry.faces,
vertices = geometry.vertices,
il = faces.length,
totalArea = 0,
cumulativeAreas = [],
vA, vB, vC, vD;
// precompute face areas
for ( i = 0; i < il; i ++ ) {
face = faces[ i ];
if ( face instanceof THREE.Face3 ) {
vA = vertices[ face.a ];
vB = vertices[ face.b ];
vC = vertices[ face.c ];
face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
} else if ( face instanceof THREE.Face4 ) {
vA = vertices[ face.a ];
vB = vertices[ face.b ];
vC = vertices[ face.c ];
vD = vertices[ face.d ];
face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
face._area = face._area1 + face._area2;
}
totalArea += face._area;
cumulativeAreas[ i ] = totalArea;
}
// binary search cumulative areas array
function binarySearchIndices( value ) {
function binarySearch( start, end ) {
// return closest larger index
// if exact number is not found
if ( end < start )
return start;
var mid = start + Math.floor( ( end - start ) / 2 );
if ( cumulativeAreas[ mid ] > value ) {
return binarySearch( start, mid - 1 );
} else if ( cumulativeAreas[ mid ] < value ) {
return binarySearch( mid + 1, end );
} else {
return mid;
}
}
var result = binarySearch( 0, cumulativeAreas.length - 1 )
return result;
}
// pick random face weighted by face area
var r, index,
result = [];
var stats = {};
for ( i = 0; i < n; i ++ ) {
r = THREE.GeometryUtils.random() * totalArea;
index = binarySearchIndices( r );
result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
if ( ! stats[ index ] ) {
stats[ index ] = 1;
} else {
stats[ index ] += 1;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q47701
|
train
|
function( geometry ) {
var vertices = [];
for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
var n = vertices.length;
var face = geometry.faces[ i ];
if ( face instanceof THREE.Face4 ) {
var a = face.a;
var b = face.b;
var c = face.c;
var d = face.d;
var va = geometry.vertices[ a ];
var vb = geometry.vertices[ b ];
var vc = geometry.vertices[ c ];
var vd = geometry.vertices[ d ];
vertices.push( va.clone() );
vertices.push( vb.clone() );
vertices.push( vc.clone() );
vertices.push( vd.clone() );
face.a = n;
face.b = n + 1;
face.c = n + 2;
face.d = n + 3;
} else {
var a = face.a;
var b = face.b;
var c = face.c;
var va = geometry.vertices[ a ];
var vb = geometry.vertices[ b ];
var vc = geometry.vertices[ c ];
vertices.push( va.clone() );
vertices.push( vb.clone() );
vertices.push( vc.clone() );
face.a = n;
face.b = n + 1;
face.c = n + 2;
}
}
geometry.vertices = vertices;
delete geometry.__tmpVertices;
}
|
javascript
|
{
"resource": ""
}
|
|
q47702
|
train
|
function( ax, ay,
bx, by,
cx, cy,
px, py ) {
var aX, aY, bX, bY;
var cX, cY, apx, apy;
var bpx, bpy, cpx, cpy;
var cCROSSap, bCROSScp, aCROSSbp;
aX = cx - bx; aY = cy - by;
bX = ax - cx; bY = ay - cy;
cX = bx - ax; cY = by - ay;
apx= px -ax; apy= py - ay;
bpx= px - bx; bpy= py - by;
cpx= px - cx; cpy= py - cy;
aCROSSbp = aX*bpy - aY*bpx;
cCROSSap = cX*apy - cY*apx;
bCROSScp = bX*cpy - bY*cpx;
return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
}
|
javascript
|
{
"resource": ""
}
|
|
q47703
|
addVertexEdgeMap
|
train
|
function addVertexEdgeMap(vertex, edge) {
if (vertexEdgeMap[vertex]===undefined) {
vertexEdgeMap[vertex] = [];
}
vertexEdgeMap[vertex].push(edge);
}
|
javascript
|
{
"resource": ""
}
|
q47704
|
levenshteinForStrings
|
train
|
function levenshteinForStrings(a, b) {
if (a === b)
return 0;
const tmp = a;
// Swapping the strings so that the shorter string is the first one.
if (a.length > b.length) {
a = b;
b = tmp;
}
let la = a.length,
lb = b.length;
if (!la)
return lb;
if (!lb)
return la;
// Ignoring common suffix
// NOTE: ~- is a fast - 1 operation, it does not work on big number though
while (la > 0 && (a.charCodeAt(~-la) === b.charCodeAt(~-lb))) {
la--;
lb--;
}
if (!la)
return lb;
let start = 0;
// Ignoring common prefix
while (start < la && (a.charCodeAt(start) === b.charCodeAt(start)))
start++;
la -= start;
lb -= start;
if (!la)
return lb;
const v0 = VECTOR;
let i = 0;
while (i < lb) {
CODES[i] = b.charCodeAt(start + i);
v0[i] = ++i;
}
let current = 0,
left,
above,
charA,
j;
// Starting the nested loops
for (i = 0; i < la; i++) {
left = i;
current = i + 1;
charA = a.charCodeAt(start + i);
for (j = 0; j < lb; j++) {
above = current;
current = left;
left = v0[j];
if (charA !== CODES[j]) {
// Insertion
if (left < current)
current = left;
// Deletion
if (above < current)
current = above;
current++;
}
v0[j] = current;
}
}
return current;
}
|
javascript
|
{
"resource": ""
}
|
q47705
|
caverphone
|
train
|
function caverphone(rules, name) {
if (typeof name !== 'string')
throw Error('talisman/phonetics/caverphone: the given name is not a string.');
// Preparing the name
name = deburr(name)
.toLowerCase()
.replace(/[^a-z]/g, '');
// Applying the rules
for (let i = 0, l = rules.length; i < l; i++) {
const [match, replacement] = rules[i];
name = name.replace(match, replacement);
}
// Returning the padded code
return pad(name);
}
|
javascript
|
{
"resource": ""
}
|
q47706
|
indexOf
|
train
|
function indexOf(haystack, needle) {
if (typeof haystack === 'string')
return haystack.indexOf(needle);
for (let i = 0, j = 0, l = haystack.length, n = needle.length; i < l; i++) {
if (haystack[i] === needle[j]) {
j++;
if (j === n)
return i - j + 1;
}
else {
j = 0;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q47707
|
matches
|
train
|
function matches(a, b) {
const stack = [a, b];
let m = 0;
while (stack.length) {
a = stack.pop();
b = stack.pop();
if (!a.length || !b.length)
continue;
const lcs = (new GeneralizedSuffixArray([a, b]).longestCommonSubsequence()),
length = lcs.length;
if (!length)
continue;
// Increasing matches
m += length;
// Add to the stack
const aStart = indexOf(a, lcs),
bStart = indexOf(b, lcs);
stack.push(a.slice(0, aStart), b.slice(0, bStart));
stack.push(a.slice(aStart + length), b.slice(bStart + length));
}
return m;
}
|
javascript
|
{
"resource": ""
}
|
q47708
|
customJaroWinkler
|
train
|
function customJaroWinkler(options, a, b) {
options = options || {};
const {
boostThreshold = 0.7,
scalingFactor = 0.1
} = options;
if (scalingFactor > 0.25)
throw Error('talisman/metrics/distance/jaro-winkler: the scaling factor should not exceed 0.25.');
if (boostThreshold < 0 || boostThreshold > 1)
throw Error('talisman/metrics/distance/jaro-winkler: the boost threshold should be comprised between 0 and 1.');
// Fast break
if (a === b)
return 1;
// Computing Jaro-Winkler score
const dj = jaro(a, b);
if (dj < boostThreshold)
return dj;
const p = scalingFactor;
let l = 0;
const prefixLimit = Math.min(a.length, b.length, 4);
// Common prefix (up to 4 characters)
for (let i = 0; i < prefixLimit; i++) {
if (a[i] === b[i])
l++;
else
break;
}
return dj + (l * p * (1 - dj));
}
|
javascript
|
{
"resource": ""
}
|
q47709
|
applyRules
|
train
|
function applyRules(rules, stem) {
for (let i = 0, l = rules.length; i < l; i++) {
const [min, pattern, replacement = ''] = rules[i];
if (stem.slice(-pattern.length) === pattern) {
const newStem = stem.slice(0, -pattern.length) + replacement,
m = computeM(newStem);
if (m <= min)
continue;
return newStem;
}
}
return stem;
}
|
javascript
|
{
"resource": ""
}
|
q47710
|
genericVariance
|
train
|
function genericVariance(ddof, sequence) {
const length = sequence.length;
if (!length)
throw Error('talisman/stats/inferential#variance: the given list is empty.');
// Returning 0 if the denominator would be <= 0
const denominator = length - ddof;
if (denominator <= 0)
return 0;
const m = mean(sequence);
let s = 0;
for (let i = 0; i < length; i++)
s += Math.pow(sequence[i] - m, 2);
return s / denominator;
}
|
javascript
|
{
"resource": ""
}
|
q47711
|
genericStdev
|
train
|
function genericStdev(ddof, sequence) {
const v = genericVariance(ddof, sequence);
return Math.sqrt(v);
}
|
javascript
|
{
"resource": ""
}
|
q47712
|
withoutTranspositions
|
train
|
function withoutTranspositions(maxOffset, maxDistance, a, b) {
// Early termination
if (a === b)
return 0;
const la = a.length,
lb = b.length;
if (!la || !lb)
return Math.max(la, lb);
let cursorA = 0,
cursorB = 0,
longestCommonSubsequence = 0,
localCommonSubstring = 0;
while (cursorA < la && cursorB < lb) {
if (a[cursorA] === b[cursorB]) {
localCommonSubstring++;
}
else {
longestCommonSubsequence += localCommonSubstring;
localCommonSubstring = 0;
if (cursorA !== cursorB)
cursorA = cursorB = Math.max(cursorA, cursorB);
for (let i = 0; i < maxOffset && (cursorA + i < la || cursorB + i < lb); i++) {
if (cursorA + i < la && a[cursorA + i] === b[cursorB]) {
cursorA += i;
localCommonSubstring++;
break;
}
if (cursorB + i < lb && a[cursorA] === b[cursorB + i]) {
cursorB += i;
localCommonSubstring++;
break;
}
}
}
cursorA++;
cursorB++;
if (maxDistance) {
const tempDistance = Math.max(cursorA, cursorB) - longestCommonSubsequence;
if (tempDistance === maxDistance)
return maxDistance;
if (tempDistance > maxDistance)
return Infinity;
}
}
longestCommonSubsequence += localCommonSubstring;
return Math.max(la, lb) - longestCommonSubsequence;
}
|
javascript
|
{
"resource": ""
}
|
q47713
|
withTranspositions
|
train
|
function withTranspositions(maxOffset, maxDistance, a, b) {
// Early termination
if (a === b)
return 0;
const la = a.length,
lb = b.length;
if (!la || !lb)
return Math.max(la, lb);
let cursorA = 0,
cursorB = 0,
longestCommonSubsequence = 0,
localCommonSubstring = 0,
transpositions = 0;
const offsetArray = [];
while (cursorA < la && cursorB < lb) {
if (a[cursorA] === b[cursorB]) {
localCommonSubstring++;
let isTransposition = false,
i = 0;
while (i < offsetArray.length) {
const offset = offsetArray[i];
if (cursorA <= offset.cursorA || cursorB <= offset.cursorB) {
isTransposition = Math.abs(cursorB - cursorA) >= Math.abs(offset.cursorB - offset.cursorA);
if (isTransposition) {
transpositions++;
}
else {
if (!offset.isTransposition) {
offset.isTransposition = true;
transpositions++;
}
}
break;
}
else {
// NOTE: we could marginally enhance the performance of the algo
// by using an object rather than splicing the array
if (cursorA > offset.cursorB && cursorB > offset.cursorA)
offsetArray.splice(i, 1);
else
i++;
}
}
offsetArray.push({
cursorA,
cursorB,
isTransposition
});
}
else {
longestCommonSubsequence += localCommonSubstring;
localCommonSubstring = 0;
if (cursorA !== cursorB)
cursorA = cursorB = Math.min(cursorA, cursorB);
for (let i = 0; i < maxOffset && (cursorA + i < la || cursorB + i < lb); i++) {
if ((cursorA + i < la) && a[cursorA + i] === b[cursorB]) {
cursorA += i - 1;
cursorB--;
break;
}
if ((cursorB + i < lb) && a[cursorA] === b[cursorB + i]) {
cursorA--;
cursorB += i - 1;
break;
}
}
}
cursorA++;
cursorB++;
// NOTE: this was below maxDistance check in original implemenation but
// this looked suspicious
if (cursorA >= la || cursorB >= lb) {
longestCommonSubsequence += localCommonSubstring;
localCommonSubstring = 0;
cursorA = cursorB = Math.min(cursorA, cursorB);
}
if (maxDistance) {
const tempDistance = (
Math.max(cursorA, cursorB) -
longestCommonSubsequence +
transpositions
);
if (tempDistance === maxDistance)
return maxDistance;
if (tempDistance > maxDistance)
return Infinity;
}
}
longestCommonSubsequence += localCommonSubstring;
return Math.max(la, lb) - longestCommonSubsequence + transpositions;
}
|
javascript
|
{
"resource": ""
}
|
q47714
|
createContext
|
train
|
function createContext(sentence) {
const context = new Array(sentence.length + 4);
context[0] = START[0];
context[1] = START[1];
for (let j = 0, m = sentence.length; j < m; j++)
context[j + 2] = normalize(sentence[j][0]);
context[context.length - 2] = END[0];
context[context.length - 1] = END[1];
return context;
}
|
javascript
|
{
"resource": ""
}
|
q47715
|
transferCase
|
train
|
function transferCase(source, target) {
let cased = '';
for (let i = 0, l = target.length; i < l; i++) {
const c = source[i].toLowerCase() === source[i] ?
'toLowerCase' :
'toUpperCase';
cased += target[i][c]();
}
return cased;
}
|
javascript
|
{
"resource": ""
}
|
q47716
|
nysiis
|
train
|
function nysiis(type, name) {
if (typeof name !== 'string')
throw Error('talisman/phonetics/nysiis: the given name is not a string.');
// Preparing the string
name = deburr(name)
.toUpperCase()
.trim()
.replace(/[^A-Z]/g, '');
// Getting the proper patterns
const patterns = PATTERNS[type];
// Applying the first substitutions
for (let i = 0, l = patterns.first.length; i < l; i++) {
const [match, replacement] = patterns.first[i];
name = name.replace(match, replacement);
}
// Storing the first letter
const firstLetter = name.charAt(0);
// Eating the first letter if applying the original algorithm
if (type === 'original')
name = name.slice(1);
// Applying the second substitutions
for (let i = 0, l = patterns.second.length; i < l; i++) {
const [match, replacement] = patterns.second[i];
name = name.replace(match, replacement);
}
// Returning the squeezed code
return firstLetter + squeeze(name);
}
|
javascript
|
{
"resource": ""
}
|
q47717
|
frequencies
|
train
|
function frequencies(sequence) {
const index = {};
// Handling strings
sequence = seq(sequence);
for (let i = 0, l = sequence.length; i < l; i++) {
const element = sequence[i];
if (!index[element])
index[element] = 0;
index[element]++;
}
return index;
}
|
javascript
|
{
"resource": ""
}
|
q47718
|
relativeFrequencies
|
train
|
function relativeFrequencies(sequence) {
let index,
length;
// Handling the object polymorphism
if (typeof sequence === 'object' && !Array.isArray(sequence)) {
index = sequence;
length = 0;
for (const k in index)
length += index[k];
}
else {
length = sequence.length;
index = frequencies(sequence);
}
const relativeIndex = {};
for (const k in index)
relativeIndex[k] = index[k] / length;
return relativeIndex;
}
|
javascript
|
{
"resource": ""
}
|
q47719
|
dunningLogLikelihood
|
train
|
function dunningLogLikelihood(a, b, ab, N) {
const p1 = b / N,
p2 = 0.99;
const nullHypothesis = ab * Math.log(p1) + (a - ab) * Math.log(1 - p1),
alternativeHyphothesis = ab * Math.log(p2) + (a - ab) * Math.log(1 - p2);
const likelihood = nullHypothesis - alternativeHyphothesis;
return (-2 * likelihood);
}
|
javascript
|
{
"resource": ""
}
|
q47720
|
colLogLikelihood
|
train
|
function colLogLikelihood(a, b, ab, N) {
const p = b / N,
p1 = ab / a,
p2 = (b - ab) / (N - a);
const summand1 = ab * Math.log(p) + (a - ab) * Math.log(1 - p),
summand2 = (b - ab) * Math.log(p) + (N - a - b + ab) * Math.log(1 - p);
let summand3 = 0;
if (a !== ab)
summand3 = ab * Math.log(p1) + (a - ab) * Math.log(1 - p1);
let summand4 = 0;
if (b !== ab)
summand4 = (b - ab) * Math.log(p2) + (N - a - b + ab) * Math.log(1 - p2);
const likelihood = summand1 + summand2 - summand3 - summand4;
return (-2 * likelihood);
}
|
javascript
|
{
"resource": ""
}
|
q47721
|
train
|
function( name, value ) {
if ( completed == null ) {
name = requestHeadersNames[ name.toLowerCase() ] =
requestHeadersNames[ name.toLowerCase() ] || name;
requestHeaders[ name ] = value;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q47722
|
reflowText
|
train
|
function reflowText (text, width, gfm) {
// Hard break was inserted by Renderer.prototype.br or is
// <br /> when gfm is true
var splitRe = gfm ? HARD_RETURN_GFM_RE : HARD_RETURN_RE,
sections = text.split(splitRe),
reflowed = [];
sections.forEach(function (section) {
// Split the section by escape codes so that we can
// deal with them separately.
var fragments = section.split(/(\u001b\[(?:\d{1,3})(?:;\d{1,3})*m)/g);
var column = 0;
var currentLine = '';
var lastWasEscapeChar = false;
while (fragments.length) {
var fragment = fragments[0];
if (fragment === '') {
fragments.splice(0, 1);
lastWasEscapeChar = false;
continue;
}
// This is an escape code - leave it whole and
// move to the next fragment.
if (!textLength(fragment)) {
currentLine += fragment;
fragments.splice(0, 1);
lastWasEscapeChar = true;
continue;
}
var words = fragment.split(/[ \t\n]+/);
for (var i = 0; i < words.length; i++) {
var word = words[i];
var addSpace = column != 0;
if (lastWasEscapeChar) addSpace = false;
// If adding the new word overflows the required width
if (column + word.length + addSpace > width) {
if (word.length <= width) {
// If the new word is smaller than the required width
// just add it at the beginning of a new line
reflowed.push(currentLine);
currentLine = word;
column = word.length;
} else {
// If the new word is longer than the required width
// split this word into smaller parts.
var w = word.substr(0, width - column - addSpace);
if (addSpace) currentLine += ' ';
currentLine += w;
reflowed.push(currentLine);
currentLine = '';
column = 0;
word = word.substr(w.length);
while (word.length) {
var w = word.substr(0, width);
if (!w.length) break;
if (w.length < width) {
currentLine = w;
column = w.length;
break;
} else {
reflowed.push(w);
word = word.substr(width);
}
}
}
} else {
if (addSpace) {
currentLine += ' ';
column++;
}
currentLine += word;
column += word.length;
}
lastWasEscapeChar = false;
}
fragments.splice(0, 1);
}
if (textLength(currentLine)) reflowed.push(currentLine);
});
return reflowed.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q47723
|
fixNestedLists
|
train
|
function fixNestedLists (body, indent) {
var regex = new RegExp('' +
'(\\S(?: | )?)' + // Last char of current point, plus one or two spaces
// to allow trailing spaces
'((?:' + indent + ')+)' + // Indentation of sub point
'(' + POINT_REGEX + '(?:.*)+)$', 'gm'); // Body of subpoint
return body.replace(regex, '$1\n' + indent + '$2$3');
}
|
javascript
|
{
"resource": ""
}
|
q47724
|
map
|
train
|
function map(tree, method, args) {
return tree.model[method].apply(tree.model, args);
}
|
javascript
|
{
"resource": ""
}
|
q47725
|
getPredicateFunction
|
train
|
function getPredicateFunction(predicate) {
let fn = predicate;
if (_.isString(predicate)) {
fn = node => (_.isFunction(node[predicate]) ? node[predicate]() : node[predicate]);
}
return fn;
}
|
javascript
|
{
"resource": ""
}
|
q47726
|
baseStatePredicate
|
train
|
function baseStatePredicate(state, full) {
if (full) {
return this.extract(state);
}
// Cache a state predicate function
const fn = getPredicateFunction(state);
return this.flatten(node => {
// Never include removed nodes unless specifically requested
if (state !== 'removed' && node.removed()) {
return false;
}
return fn(node);
});
}
|
javascript
|
{
"resource": ""
}
|
q47727
|
cloneItree
|
train
|
function cloneItree(itree, excludeKeys) {
const clone = {};
excludeKeys = _.castArray(excludeKeys);
excludeKeys.push('ref');
_.each(itree, (v, k) => {
if (!_.includes(excludeKeys, k)) {
clone[k] = _.cloneDeep(v);
}
});
return clone;
}
|
javascript
|
{
"resource": ""
}
|
q47728
|
baseState
|
train
|
function baseState(node, property, val) {
const currentVal = node.itree.state[property];
if (typeof val !== 'undefined' && currentVal !== val) {
// Update values
node.itree.state[property] = val;
if (property !== 'rendered') {
node.markDirty();
}
// Emit an event
node._tree.emit('node.state.changed', node, property, currentVal, val);
}
return currentVal;
}
|
javascript
|
{
"resource": ""
}
|
q47729
|
resetState
|
train
|
function resetState(node) {
_.each(node._tree.defaultState, (val, prop) => {
node.state(prop, val);
});
return node;
}
|
javascript
|
{
"resource": ""
}
|
q47730
|
run
|
train
|
async function run() {
const fetcher = new ChangelogFetcher({ base, futureRelease, futureReleaseTag, labels, owner, repo, token });
const releases = await fetcher.fetchChangelog();
formatChangelog(releases).forEach(line => process.stdout.write(line));
}
|
javascript
|
{
"resource": ""
}
|
q47731
|
train
|
function (element, event) {
var pageX = (event.changedTouches) ? event.changedTouches[0].pageX : event.pageX;
var offsetx = pageX - $(element).offset().left;
if (!ltr) { offsetx = range.width() - offsetx };
if (offsetx > range.width()) { offsetx = range.width(); }
if (offsetx < 0) { offsetx = 0; }
return score = Math.ceil(offsetx / itemdata('starwidth') * (1 / itemdata('step')));
}
|
javascript
|
{
"resource": ""
}
|
|
q47732
|
train
|
function (score) {
var w = score * itemdata('starwidth') * itemdata('step');
var h = range.find('.rateit-hover');
if (h.data('width') != w) {
range.find('.rateit-selected').hide();
h.width(w).show().data('width', w);
var data = [(score * itemdata('step')) + itemdata('min')];
item.trigger('hover', data).trigger('over', data);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47733
|
getRenderedCenter
|
train
|
function getRenderedCenter(target, renderedDimensions){
let pos = target.renderedPosition();
let dimensions = renderedDimensions(target);
let offsetX = dimensions.w / 2;
let offsetY = dimensions.h / 2;
return {
x : (pos.x - offsetX),
y : (pos.y - offsetY)
};
}
|
javascript
|
{
"resource": ""
}
|
q47734
|
getRenderedMidpoint
|
train
|
function getRenderedMidpoint(target){
let p = target.midpoint();
let pan = target.cy().pan();
let zoom = target.cy().zoom();
return {
x: p.x * zoom + pan.x,
y: p.y * zoom + pan.y
};
}
|
javascript
|
{
"resource": ""
}
|
q47735
|
getPopper
|
train
|
function getPopper(target, opts) {
let refObject = getRef(target, opts);
let content = getContent(target, opts.content);
let popperOpts = assign({}, popperDefaults, opts.popper);
return new Popper(refObject, content, popperOpts);
}
|
javascript
|
{
"resource": ""
}
|
q47736
|
createOptionsObject
|
train
|
function createOptionsObject(target, opts) {
let defaults = {
boundingBox : {
top: 0,
left: 0,
right: 0,
bottom: 0,
w: 3,
h: 3,
},
renderedDimensions : () => ({w: 3, h: 3}),
redneredPosition : () => ({x : 0, y : 0}),
popper : {},
cy : target
};
return assign( {}, defaults, opts );
}
|
javascript
|
{
"resource": ""
}
|
q47737
|
ensureWindows
|
train
|
function ensureWindows () {
if (process.platform !== 'win32') {
log('This tool requires Windows 10.\n')
log('You can run a virtual machine using the free VirtualBox and')
log('the free Windows Virtual Machines found at http://modern.ie.\n')
log('For more information, please see the readme.')
process.exit(1)
}
let release = require('os').release()
let major = parseInt(release.slice(0, 2), 10)
let minor = parseInt(release.slice(3, 4), 10)
let build = parseInt(release.slice(5), 10)
if (major < 10 || (minor === 0 && build < 14316)) {
log(`You are running Windows ${release}. You need at least Windows 10.0.14316.`)
log('We can\'t confirm that you\'re running the right version, but we won\'t stop')
log('this process - should things fail though, you might have to update your')
log('Windows.')
}
}
|
javascript
|
{
"resource": ""
}
|
q47738
|
hasVariableResources
|
train
|
function hasVariableResources (assetsDirectory) {
const files = require('fs-extra').readdirSync(assetsDirectory)
const hasScale = files.find(file => /\.scale-...\./g.test(file))
return (!!hasScale)
}
|
javascript
|
{
"resource": ""
}
|
q47739
|
executeChildProcess
|
train
|
function executeChildProcess (fileName, args, options) {
return new Promise((resolve, reject) => {
const child = require('child_process').spawn(fileName, args, options)
child.stdout.on('data', (data) => log(data.toString()))
child.stderr.on('data', (data) => log(data.toString()))
child.on('exit', (code) => {
if (code !== 0) {
return reject(new Error(fileName + ' exited with code: ' + code))
}
return resolve()
})
child.stdin.end()
})
}
|
javascript
|
{
"resource": ""
}
|
q47740
|
isSetupRequired
|
train
|
function isSetupRequired (program) {
const config = dotfile.get() || {}
const hasPublisher = (config.publisher || program.publisher)
const hasDevCert = (config.devCert || program.devCert)
const hasWindowsKit = (config.windowsKit || program.windowsKit)
const hasBaseImage = (config.expandedBaseImage || program.expandedBaseImage)
const hasConverterTools = (config.desktopConverter || program.desktopConverter)
if (!program.containerVirtualization) {
return (hasPublisher && hasDevCert && hasWindowsKit)
} else {
return (hasPublisher && hasDevCert && hasWindowsKit && hasBaseImage && hasConverterTools)
}
}
|
javascript
|
{
"resource": ""
}
|
q47741
|
wizardSetup
|
train
|
function wizardSetup (program) {
const welcome = multiline.stripIndent(function () { /*
Welcome to the Electron-Windows-Store tool!
This tool will assist you with turning your Electron app into
a swanky Windows Store app.
We need to know some settings. We will ask you only once and store
your answers in your profile folder in a .electron-windows-store
file.
*/
})
const complete = multiline.stripIndent(function () { /*
Setup complete, moving on to package your app!
*/
})
let questions = [
{
name: 'desktopConverter',
type: 'input',
message: 'Please enter the path to your Desktop App Converter (DesktopAppConverter.ps1): ',
validate: (input) => pathExists.sync(input),
when: () => (!program.desktopConverter)
},
{
name: 'expandedBaseImage',
type: 'input',
message: 'Please enter the path to your Expanded Base Image: ',
default: 'C:\\ProgramData\\Microsoft\\Windows\\Images\\BaseImage-14316\\',
validate: (input) => pathExists.sync(input),
when: () => (!program.expandedBaseImage)
},
{
name: 'devCert',
type: 'input',
message: 'Please enter the path to your development PFX certficate: ',
default: null,
when: () => (!dotfile.get().makeCertificate || !program.devCert)
},
{
name: 'publisher',
type: 'input',
message: 'Please enter your publisher identity: ',
default: 'CN=developmentca',
when: () => (!program.publisher)
},
{
name: 'windowsKit',
type: 'input',
message: "Please enter the location of your Windows Kit's bin folder: ",
default: utils.getDefaultWindowsKitLocation(),
when: () => (!program.windowsKit)
}
]
if (!program.isModuleUse) {
utils.log(welcome)
}
// Remove the Desktop Converter Questions if not installed
if (program.didInstallDesktopAppConverter === false) {
questions = questions.slice(3)
}
if (program.isModuleUse) {
program.windowsKit = program.windowsKit || utils.getDefaultWindowsKitLocation()
return Promise.resolve(program)
}
return inquirer.prompt(questions)
.then((answers) => {
dotfile.set({
desktopConverter: answers.desktopConverter || false,
expandedBaseImage: answers.expandedBaseImage || false,
devCert: answers.devCert,
publisher: answers.publisher,
windowsKit: answers.windowsKit,
makeCertificate: dotfile.get().makeCertificate
})
program.desktopConverter = answers.desktopConverter
program.expandedBaseImage = answers.expandedBaseImage
program.devCert = answers.devCert
program.publisher = answers.publisher
program.windowsKit = answers.windowsKit
if (program.makeCertificate) {
utils.log(chalk.bold.green('Creating Certficate'))
let publisher = dotfile.get().publisher.split('=')[1]
let certFolder = path.join(process.env.APPDATA, 'electron-windows-store', publisher)
return sign.makeCert({ publisherName: publisher, certFilePath: certFolder, program: program })
.then(pfxFile => {
utils.log('Created and installed certificate:')
utils.log(pfxFile)
dotfile.set({ devCert: pfxFile })
})
}
utils.log(complete)
})
}
|
javascript
|
{
"resource": ""
}
|
q47742
|
logConfiguration
|
train
|
function logConfiguration (program) {
utils.log(chalk.bold.green.underline('\nConfiguration: '))
utils.log(`Desktop Converter Location: ${program.desktopConverter}`)
utils.log(`Expanded Base Image: ${program.expandedBaseImage}`)
utils.log(`Publisher: ${program.publisher}`)
utils.log(`Dev Certificate: ${program.devCert}`)
utils.log(`Windows Kit Location: ${program.windowsKit}
`)
}
|
javascript
|
{
"resource": ""
}
|
q47743
|
setup
|
train
|
function setup (program) {
return new Promise((resolve, reject) => {
if (isSetupRequired(program)) {
// If we're setup, merge the dotfile configuration into the program
defaults(program, dotfile.get())
logConfiguration(program)
resolve()
} else {
// We're not setup, let's do that now
askForDependencies(program)
.then(() => wizardSetup(program))
.then(() => logConfiguration(program))
.then(() => resolve())
.catch((e) => reject(e))
}
})
}
|
javascript
|
{
"resource": ""
}
|
q47744
|
convertWithContainer
|
train
|
function convertWithContainer (program) {
return new Promise((resolve, reject) => {
if (!program.desktopConverter) {
utils.log('Could not find the Project Centennial Desktop App Converter, which is required to')
utils.log('run the conversion to appx using a Windows Container.\n')
utils.log('Consult the documentation at https://aka.ms/electron-windows-store for a tutorial.\n')
utils.log('You can find the Desktop App Converter at https://www.microsoft.com/en-us/download/details.aspx?id=51691\n')
utils.log('Exiting now - restart when you downloaded and unpacked the Desktop App Converter!')
process.exit(0)
}
let preAppx = path.join(program.outputDirectory, 'pre-appx')
let installer = path.join(program.outputDirectory, 'ElectronInstaller.exe')
let logfile = path.join(program.outputDirectory, 'logs', 'conversion.log')
let converterArgs = [
`-LogFile ${logfile}`,
`-Installer '${installer}'`,
`-Converter '${path.join(program.desktopConverter, 'DesktopAppConverter.ps1')}'`,
`-ExpandedBaseImage ${program.expandedBaseImage}`,
`-Destination '${preAppx}'`,
`-PackageName "${program.packageName}"`,
`-Version ${program.packageVersion}`,
`-Publisher "${program.publisher}"`,
`-AppExecutable '${program.packageExecutable}'`
]
let args = `& {& '${path.resolve(__dirname, '..', 'ps1', 'convert.ps1')}' ${converterArgs.join(' ')}}`
let child, tail
utils.log(chalk.green.bold('Starting Conversion...'))
utils.debug(`Conversion parameters used: ${JSON.stringify(converterArgs)}`)
try {
child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', args])
} catch (error) {
reject(error)
}
child.stdout.on('data', (data) => utils.debug(data.toString()))
child.stderr.on('data', (data) => utils.debug(data.toString()))
child.on('exit', () => {
// The conversion process exited, let's look for a log file
// However, give the PS process a 3s headstart, since we'll
// crash if the logfile does not exist yet
setTimeout(() => {
tail = new Tail(logfile, {
fromBeginning: true
})
tail.on('line', (data) => {
utils.log(data)
if (data.indexOf('Conversion complete') > -1) {
utils.log('')
tail.unwatch()
resolve()
} else if (data.indexOf('An error occurred') > -1) {
tail.unwatch()
reject(new Error('Detected error in conversion log'))
}
})
tail.on('error', (err) => utils.log(err))
}, 3000)
})
child.stdin.end()
})
}
|
javascript
|
{
"resource": ""
}
|
q47745
|
specialRequire
|
train
|
function specialRequire(name, fromDir) {
if (!fromDir) fromDir = process.cwd();
var paths = Module._nodeModulePaths(fromDir);
var path = Module._findPath(name, paths);
return path ? require(path) : require(name);
}
|
javascript
|
{
"resource": ""
}
|
q47746
|
_transform
|
train
|
function _transform() {
var codeIn = $('#codeIn').val();
try {
var codeOut = Streamline.transform(codeIn, {
runtime: _generators ? "generators" : "callbacks",
});
$('#codeOut').val(codeOut);
info("ready");
} catch (ex) {
console.error(ex);
error(ex.message);
}
}
|
javascript
|
{
"resource": ""
}
|
q47747
|
onFinished
|
train
|
function onFinished (msg, listener) {
if (isFinished(msg) !== false) {
defer(listener, null, msg)
return msg
}
// attach the listener to the message
attachListener(msg, listener)
return msg
}
|
javascript
|
{
"resource": ""
}
|
q47748
|
isFinished
|
train
|
function isFinished (msg) {
var socket = msg.socket
if (typeof msg.finished === 'boolean') {
// OutgoingMessage
return Boolean(msg.finished || (socket && !socket.writable))
}
if (typeof msg.complete === 'boolean') {
// IncomingMessage
return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
}
// don't know
return undefined
}
|
javascript
|
{
"resource": ""
}
|
q47749
|
attachFinishedListener
|
train
|
function attachFinishedListener (msg, callback) {
var eeMsg
var eeSocket
var finished = false
function onFinish (error) {
eeMsg.cancel()
eeSocket.cancel()
finished = true
callback(error)
}
// finished on first message event
eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish)
function onSocket (socket) {
// remove listener
msg.removeListener('socket', onSocket)
if (finished) return
if (eeMsg !== eeSocket) return
// finished on first socket event
eeSocket = first([[socket, 'error', 'close']], onFinish)
}
if (msg.socket) {
// socket already assigned
onSocket(msg.socket)
return
}
// wait for socket to be assigned
msg.on('socket', onSocket)
if (msg.socket === undefined) {
// istanbul ignore next: node.js 0.8 patch
patchAssignSocket(msg, onSocket)
}
}
|
javascript
|
{
"resource": ""
}
|
q47750
|
attachListener
|
train
|
function attachListener (msg, listener) {
var attached = msg.__onFinished
// create a private single listener with queue
if (!attached || !attached.queue) {
attached = msg.__onFinished = createListener(msg)
attachFinishedListener(msg, attached)
}
attached.queue.push(listener)
}
|
javascript
|
{
"resource": ""
}
|
q47751
|
createListener
|
train
|
function createListener (msg) {
function listener (err) {
if (msg.__onFinished === listener) msg.__onFinished = null
if (!listener.queue) return
var queue = listener.queue
listener.queue = null
for (var i = 0; i < queue.length; i++) {
queue[i](err, msg)
}
}
listener.queue = []
return listener
}
|
javascript
|
{
"resource": ""
}
|
q47752
|
patchAssignSocket
|
train
|
function patchAssignSocket (res, callback) {
var assignSocket = res.assignSocket
if (typeof assignSocket !== 'function') return
// res.on('socket', callback) is broken in 0.8
res.assignSocket = function _assignSocket (socket) {
assignSocket.call(this, socket)
callback(socket)
}
}
|
javascript
|
{
"resource": ""
}
|
q47753
|
parseLdOutput
|
train
|
function parseLdOutput(output) {
const libraryList = output.split('\n').filter(ln => ln.includes('=>'));
const result = {};
libraryList.forEach(s => {
const [name, _, libPath] = s.trim().split(' ');
result[name] = libPath;
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47754
|
BaseNode
|
train
|
function BaseNode (nodeId, log, connection, options) {
/**
* Unique current machine name.
* @type {string}
*
* @example
* console.log(node.localNodeId + ' is started')
*/
this.localNodeId = nodeId
/**
* Log for synchronization.
* @type {Log}
*/
this.log = log
/**
* Connection used to communicate to remote node.
* @type {Connection}
*/
this.connection = connection
/**
* Synchronization options.
* @type {object}
*/
this.options = options || { }
if (this.options.ping && !this.options.timeout) {
throw new Error('You must set timeout option to use ping')
}
/**
* Is synchronization in process.
* @type {boolean}
*
* @example
* node.on('disconnect', () => {
* node.connected //=> false
* })
*/
this.connected = false
/**
* Did we finish remote node authentication.
* @type {boolean}
*/
this.authenticated = false
this.unauthenticated = []
this.timeFix = 0
this.syncing = 0
this.received = { }
/**
* Latest current log `added` time, which was successfully synchronized.
* It will be saves in log store.
* @type {number}
*/
this.lastSent = 0
/**
* Latest remote node’s log `added` time, which was successfully synchronized.
* It will be saves in log store.
* @type {number}
*/
this.lastReceived = 0
/**
* Current synchronization state.
*
* * `disconnected`: no connection, but no new actions to synchronization.
* * `connecting`: connection was started and we wait for node answer.
* * `sending`: new actions was sent, waiting for answer.
* * `synchronized`: all actions was synchronized and we keep connection.
*
* @type {"disconnected"|"connecting"|"sending"|"synchronized"}
*
* @example
* node.on('state', () => {
* if (node.state === 'sending') {
* console.log('Do not close browser')
* }
* })
*/
this.state = 'disconnected'
this.emitter = new NanoEvents()
this.timeouts = []
this.throwsError = true
this.unbind = []
var node = this
this.unbind.push(log.on('add', function (action, meta) {
node.onAdd(action, meta)
}))
this.unbind.push(connection.on('connecting', function () {
node.onConnecting()
}))
this.unbind.push(connection.on('connect', function () {
node.onConnect()
}))
this.unbind.push(connection.on('message', function (message) {
node.onMessage(message)
}))
this.unbind.push(connection.on('error', function (error) {
if (error.message === 'Wrong message format') {
node.sendError(new LoguxError('wrong-format', error.received))
node.connection.disconnect('error')
} else {
node.error(error)
}
}))
this.unbind.push(connection.on('disconnect', function () {
node.onDisconnect()
}))
this.initialized = false
this.lastAddedCache = 0
this.initializing = this.initialize()
}
|
javascript
|
{
"resource": ""
}
|
q47755
|
destroy
|
train
|
function destroy () {
if (this.connection.destroy) {
this.connection.destroy()
} else if (this.connected) {
this.connection.disconnect('destroy')
}
for (var i = 0; i < this.unbind.length; i++) {
this.unbind[i]()
}
clearTimeout(this.pingTimeout)
this.endTimeout()
}
|
javascript
|
{
"resource": ""
}
|
q47756
|
ServerNode
|
train
|
function ServerNode (nodeId, log, connection, options) {
options = merge(options, DEFAULT_OPTIONS)
BaseNode.call(this, nodeId, log, connection, options)
if (this.options.fixTime) {
throw new Error(
'Logux Server could not fix time. Set opts.fixTime for Client node.')
}
this.state = 'connecting'
}
|
javascript
|
{
"resource": ""
}
|
q47757
|
ClientNode
|
train
|
function ClientNode (nodeId, log, connection, options) {
options = merge(options, DEFAULT_OPTIONS)
BaseNode.call(this, nodeId, log, connection, options)
}
|
javascript
|
{
"resource": ""
}
|
q47758
|
Log
|
train
|
function Log (opts) {
if (!opts) opts = { }
if (typeof opts.nodeId === 'undefined') {
throw new Error('Expected node ID')
}
if (typeof opts.store !== 'object') {
throw new Error('Expected store')
}
if (opts.nodeId.indexOf(' ') !== -1) {
throw new Error('Space is prohibited in node ID')
}
/**
* Unique node ID. It is used in action IDs.
* @type {string|number}
*/
this.nodeId = opts.nodeId
this.lastTime = 0
this.sequence = 0
this.store = opts.store
this.emitter = new NanoEvents()
}
|
javascript
|
{
"resource": ""
}
|
q47759
|
add
|
train
|
function add (action, meta) {
if (typeof action.type === 'undefined') {
throw new Error('Expected "type" in action')
}
if (!meta) meta = { }
var newId = false
if (typeof meta.id === 'undefined') {
newId = true
meta.id = this.generateId()
}
if (typeof meta.time === 'undefined') {
meta.time = parseInt(meta.id)
}
if (typeof meta.reasons === 'undefined') {
meta.reasons = []
} else if (!Array.isArray(meta.reasons)) {
meta.reasons = [meta.reasons]
}
meta.reasons.forEach(function (reason) {
if (typeof reason !== 'string') {
throw new Error('Expected "reasons" to be strings')
}
})
var log = this
this.emitter.emit('preadd', action, meta)
if (meta.keepLast) {
this.removeReason(meta.keepLast, { olderThan: meta })
meta.reasons.push(meta.keepLast)
}
if (meta.reasons.length === 0 && newId) {
this.emitter.emit('add', action, meta)
this.emitter.emit('clean', action, meta)
return Promise.resolve(meta)
} else if (meta.reasons.length === 0) {
return this.store.byId(meta.id).then(function (result) {
if (result[0]) {
return false
} else {
log.emitter.emit('add', action, meta)
log.emitter.emit('clean', action, meta)
return meta
}
})
} else {
return this.store.add(action, meta).then(function (addedMeta) {
if (addedMeta === false) {
return false
} else {
log.emitter.emit('add', action, addedMeta)
return addedMeta
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
q47760
|
generateId
|
train
|
function generateId () {
var now = Date.now()
if (now <= this.lastTime) {
now = this.lastTime
this.sequence += 1
} else {
this.lastTime = now
this.sequence = 0
}
return now + ' ' + this.nodeId + ' ' + this.sequence
}
|
javascript
|
{
"resource": ""
}
|
q47761
|
each
|
train
|
function each (opts, callback) {
if (!callback) {
callback = opts
opts = { order: 'created' }
}
var store = this.store
return new Promise(function (resolve) {
function nextPage (get) {
get().then(function (page) {
var result
for (var i = page.entries.length - 1; i >= 0; i--) {
var entry = page.entries[i]
result = callback(entry[0], entry[1])
if (result === false) break
}
if (result === false || !page.next) {
resolve()
} else {
nextPage(page.next)
}
})
}
nextPage(store.get.bind(store, opts))
})
}
|
javascript
|
{
"resource": ""
}
|
q47762
|
WsConnection
|
train
|
function WsConnection (url, WS, opts) {
this.connected = false
this.emitter = new NanoEvents()
if (WS) {
this.WS = WS
} else if (typeof WebSocket !== 'undefined') {
this.WS = WebSocket
} else {
throw new Error('No WebSocket support')
}
this.url = url
this.opts = opts
}
|
javascript
|
{
"resource": ""
}
|
q47763
|
isFirstOlder
|
train
|
function isFirstOlder (firstMeta, secondMeta) {
if (firstMeta && !secondMeta) {
return false
} else if (!firstMeta && secondMeta) {
return true
}
if (firstMeta.time > secondMeta.time) {
return false
} else if (firstMeta.time < secondMeta.time) {
return true
}
var first = split(firstMeta.id)
var second = split(secondMeta.id)
if (first[1] > second[1]) {
return false
} else if (first[1] < second[1]) {
return true
}
if (first[0] > second[0]) {
return false
} else if (first[0] < second[0]) {
return true
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q47764
|
LoguxError
|
train
|
function LoguxError (type, options, received) {
Error.call(this, type)
/**
* Always equal to `LoguxError`. The best way to check error class.
* @type {string}
*
* @example
* if (error.name === 'LoguxError') { }
*/
this.name = 'LoguxError'
/**
* The error code.
* @type {string}
*
* @example
* if (error.type === 'timeout') {
* fixNetwork()
* }
*/
this.type = type
/**
* Error options depends on error type.
* @type {any}
*
* @example
* if (error.type === 'timeout') {
* console.error('A timeout was reached (' + error.options + ' ms)')
* }
*/
this.options = options
/**
* Human-readable error description.
* @type {string}
*
* @example
* console.log('Server throws: ' + error.description)
*/
this.description = LoguxError.describe(type, options)
/**
* Was error received from remote client.
* @type {boolean}
*/
this.received = !!received
this.message = ''
if (received) {
this.message += 'Logux received ' + this.type + ' error'
if (this.description !== this.type) {
this.message += ' (' + this.description + ')'
}
} else {
this.message = this.description
}
if (Error.captureStackTrace) {
Error.captureStackTrace(this, LoguxError)
}
}
|
javascript
|
{
"resource": ""
}
|
q47765
|
_getStrategyGrouping
|
train
|
function _getStrategyGrouping(_class) {
return function () {
var replicationParams = _.toArray(arguments)
, replication = {"class": _class};
if (_class === methods.withSimpleStrategy.name) {
if (typeof replicationParams[0] === "undefined")
throw new Error("SimpleStrategy requires replication parameters.");
replication.replication_factor = replicationParams[0];
}
else if (_class === methods.withNetworkTopologyStrategy.name) {
var filter = function (param) {
return typeof param === "object" && Object.keys(param).length >= 1;
};
var dataCenterParams = _.filter(arguments, filter);
if (!dataCenterParams.length)
throw new Error("NetworkTopologyStrategy requires a variable length argument list of data center param objecs => '{ dataCenterName: dataCenterReplicationFactor }'.");
_.each(dataCenterParams, function (dataCenterParam) {
_.each(Object.keys(dataCenterParam), function (k) {
replication[k] = dataCenterParam[k];
});
});
}
this._statements.push({
grouping: "strategy",
type: methods[nameToCallMap[_class]].name,
value: replication
});
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
q47766
|
_getAndGrouping
|
train
|
function _getAndGrouping(type) {
return function () {
var boolean = _.toArray(arguments);
this._statements.push({
grouping: "and",
type: type,
value: arguments[0] ? arguments[0] : false
});
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
q47767
|
_attachExecMethod
|
train
|
function _attachExecMethod(qb) {
/**
* Create the exec function for a pass through to the datastax driver.
*
* @param `{Object} options` optional argument passed to datastax driver upon query execution
* @param `{Function} cb` => function(err, result) {}
* @returns {Client|exports|module.exports}
*/
qb.exec = function (options, cb) {
var _options = typeof options !== "undefined" && _.isFunction(options) ? {} : options
, _cb;
if (!_.has(_options, "prepare")) {
_options.prepare = qb._execPrepare;
}
if (_.isFunction(options)) {
_cb = options;
}
else if (_.isFunction(cb)) {
_cb = cb;
}
else {
_cb = _.noop;
}
if (cassandra !== null && cassandra.connected) {
var cql = qb.cql();
cassandra.execute(cql, qb.bindings(), _options, _cb);
}
else {
_cb(new Error("Cassandra client is not initialized."));
}
// maintain chain
return qb;
};
}
|
javascript
|
{
"resource": ""
}
|
q47768
|
_attachStreamMethod
|
train
|
function _attachStreamMethod(qb) {
/**
* Create the stream function for a pass through to the datastax driver,
* all callbacks are defaulted to lodash#noop if not declared.
*
* @param `{Object} options` optional argument passed to datastax driver upon query execution
* @param `{Object} cbs` =>
* {
* readable: function() {},
* end: function() {},
* error: function(err) {}
* }
* @returns {Client|exports|module.exports}
*/
qb.stream = function (options, cbs) {
var _options = _.isObject(cbs) ? options : {}
, _cbs = _.isObject(cbs) ? cbs : options
, onReadable = _cbs.readable || _.noop
, onEnd = _cbs.end || _.noop
, onError = _cbs.error || _.noop;
if (cassandra !== null && cassandra.connected) {
var cql = qb.cql();
cassandra.stream(cql, qb.bindings(), _options)
.on("readable", onReadable)
.on("end", onEnd)
.on("error", onError);
}
else {
console.error("Cassandra client is not initialized.");
onError(new Error("Cassandra client is not initialized."));
}
// maintain chain
return qb;
};
}
|
javascript
|
{
"resource": ""
}
|
q47769
|
_attachEachRowMethod
|
train
|
function _attachEachRowMethod(qb) {
/**
* Create the eachRow function for a pass through to the datastax driver.
*
* @param `{Object} options` optional argument passed to datastax driver upon query execution
* @param `{Function} rowCb` => function(row) {}
* @param `{Function} errorCb` => function(err) {}
* @returns {Client|exports|module.exports}
*/
qb.eachRow = function (options, rowCb, errorCb) {
// options is really rowCB
if (_.isFunction(options)) {
errorCb = rowCb;
rowCb = options;
}
var _options = _.isObject(options) ? options : {};
if (!_.isFunction(rowCb)) {
rowCb = _.noop;
}
if (!_.isFunction(errorCb)) {
errorCb = _.noop;
}
if (cassandra !== null && cassandra.connected) {
var cql = qb.cql();
cassandra.eachRow(cql, qb.bindings(), _options, rowCb, errorCb);
}
else {
errorCb(new Error("Cassandra client is not initialized."));
}
// maintain chain
return qb;
};
}
|
javascript
|
{
"resource": ""
}
|
q47770
|
_attachBatchMethod
|
train
|
function _attachBatchMethod(qb) {
/**
*
* @param options
* @param cassakni
* @param cb
* @returns {Client|exports|module.exports}
*/
qb.batch = function (options, cassakni, cb) {
var _options
, _cassakni
, _cb;
// options is really cassakni, cassakni is cb
if (_.isArray(options)) {
_options = {};
_cassakni = options;
_cb = cassakni;
}
// standard order
else {
_options = options;
_cassakni = cassakni;
_cb = cb;
}
if (!_.isFunction(_cb)) {
_cb = _.noop;
}
if (cassandra !== null && cassandra.connected) {
var error = null
, statements = _.map(_cassakni, function (qb) {
if (!qb.toString || qb.toString() !== duckType) {
error = new Error("Invalid input to CassanKnex#batch.");
return {};
}
else {
return {query: qb.cql(), params: qb.bindings()};
}
});
if (error) {
return _cb(error);
}
cassandra.batch(statements, _options, _cb);
}
else {
_cb(new Error("Cassandra client is not initialized."));
}
// maintain chain
return qb;
};
}
|
javascript
|
{
"resource": ""
}
|
q47771
|
startWatch
|
train
|
function startWatch() {
var rp = path.join(rootPath, '/**/*.md')
watcher = gulp.watch([rp, '!' + rp + '/_book/'], function() {
rebuildBook(reload)
})
return watcher
}
|
javascript
|
{
"resource": ""
}
|
q47772
|
train
|
function (format) {
return function (data) {
var el = makeElement("img", [ "image-output" ]);
el.src = "data:image/" + format + ";base64," + joinText(data).replace(/\n/g, "");
return el;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q47773
|
resolveExecutablePath
|
train
|
async function resolveExecutablePath (cmd) {
let executablePath;
try {
executablePath = await fs.which(cmd);
if (executablePath && await fs.exists(executablePath)) {
return executablePath;
}
} catch (err) {
if ((/not found/gi).test(err.message)) {
log.debug(err);
} else {
log.warn(err);
}
}
log.debug(`No executable path of '${cmd}'.`);
if (executablePath) {
log.debug(`Does '${executablePath}' exist?`);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q47774
|
tick
|
train
|
function tick() {
var moment = (new Date().getTime() - startDate)/1000;
x = Math.round(150 * Math.sin(moment));
y = Math.round(150 * Math.cos(moment));
requestAnimationFrame(tick);
}
|
javascript
|
{
"resource": ""
}
|
q47775
|
train
|
function (todo) {
model.remove(todo.id, function () {
todos.splice(todos.indexOf(todo), 1);
if (todo.completed) {
completedCount--;
} else {
itemsLeft--;
checkedAll = completedCount === todos.length;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q47776
|
train
|
function (query, callback) {
if (!callback) {
return;
}
var todos = data.todos;
callback.call(undefined, todos.filter(function (todo) {
for (var q in query) {
if (query[q] !== todo[q]) {
return false;
}
}
return true;
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q47777
|
train
|
function (updateData, callback, id) {
var todos = data.todos;
callback = callback || function () { };
// If an ID was actually given, find the item and update each property
if (id) {
for (var i = 0; i < todos.length; i++) {
if (todos[i].id === id) {
for (var key in updateData) {
todos[i][key] = updateData[key];
}
break;
}
}
flush();
callback.call(undefined, data.todos);
} else {
// Generate an ID
updateData.id = new Date().getTime();
todos.push(updateData);
flush();
callback.call(undefined, [updateData]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47778
|
train
|
function (id, callback) {
var todos = data.todos;
for (var i = 0; i < todos.length; i++) {
if (todos[i].id == id) {
todos.splice(i, 1);
break;
}
}
flush();
callback.call(undefined, data.todos);
}
|
javascript
|
{
"resource": ""
}
|
|
q47779
|
render
|
train
|
function render() {
return h('div', [
h('input', {
type: 'text', placeholder: 'What is your name?',
value: yourName, oninput: handleNameInput
}),
h('p.output', ['Hello ' + (yourName || 'you') + '!'])
]);
}
|
javascript
|
{
"resource": ""
}
|
q47780
|
train
|
function (title, callback) {
title = title || '';
callback = callback || function () { };
var newItem = {
title: title.trim(),
completed: false
};
storage.save(newItem, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q47781
|
train
|
function (query, callback) {
var queryType = typeof query;
callback = callback || function () { };
if (queryType === 'function') {
callback = query;
storage.findAll(callback);
} else if (queryType === 'string' || queryType === 'number') {
query = parseInt(query, 10);
storage.find({ id: query }, callback);
} else {
storage.find(query, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47782
|
train
|
function (callback) {
var todos = {
active: 0,
completed: 0,
total: 0
};
storage.findAll(function (data) {
data.forEach(function (todo) {
if (todo.completed) {
todos.completed++;
} else {
todos.active++;
}
todos.total++;
});
callback(todos);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q47783
|
isFileProcessable
|
train
|
function isFileProcessable(filepath) {
if (options.fileFilterRegex.length === 0) {
return true;
}
return options.fileFilterRegex.some((regex) => filepath.match(regex) !== null);
}
|
javascript
|
{
"resource": ""
}
|
q47784
|
session
|
train
|
async function session(ctx, next) {
ctx.sessionStore = store
if (ctx.session || ctx._session) {
return next()
}
const result = await getSession(ctx)
if (!result) {
return next()
}
addCommonAPI(ctx)
ctx._session = result.session
// more flexible
Object.defineProperty(ctx, 'session', {
get() {
return this._session
},
set(sess) {
this._session = sess
}
})
ctx.regenerateSession = async function regenerateSession() {
debug('regenerating session')
if (!result.isNew) {
// destroy the old session
debug('destroying previous session')
await store.destroy(ctx.sessionId)
}
ctx.session = generateSession()
ctx.sessionId = genSid.call(ctx, 24)
sessionIdStore.reset.call(ctx)
debug('created new session: %s', ctx.sessionId)
result.isNew = true
}
// make sure `refreshSession` always called
let firstError = null
try {
await next()
} catch (err) {
debug('next logic error: %s', err.message)
firstError = err
}
// can't use finally because `refreshSession` is async
try {
await refreshSession(ctx, ctx.session, result.originalHash, result.isNew)
} catch (err) {
debug('refresh session error: %s', err.message)
if (firstError) ctx.app.emit('error', err, ctx)
firstError = firstError || err
}
if (firstError) throw firstError
}
|
javascript
|
{
"resource": ""
}
|
q47785
|
deferSession
|
train
|
async function deferSession(ctx, next) {
ctx.sessionStore = store
// TODO:
// Accessing ctx.session when it's defined is causing problems
// because it has side effect. So, here we use a flag to determine
// that session property is already defined.
if (ctx.__isSessionDefined) {
return next()
}
let isNew = false
let originalHash = null
let touchSession = false
let getter = false
// if path not match
if (!matchPath(ctx)) {
return next()
}
addCommonAPI(ctx)
Object.defineProperty(ctx, 'session', {
async get() {
if (touchSession) {
return this._session
}
touchSession = true
getter = true
const result = await getSession(this)
// if cookie path not match
// this route's controller should never use session
if (!result) return
originalHash = result.originalHash
isNew = result.isNew
this._session = result.session
return this._session
},
set(value) {
touchSession = true
this._session = value
}
})
// internal flag to determine that session is already defined
ctx.__isSessionDefined = true
ctx.regenerateSession = async function regenerateSession() {
debug('regenerating session')
// make sure that the session has been loaded
await ctx.session
if (!isNew) {
// destroy the old session
debug('destroying previous session')
await store.destroy(ctx.sessionId)
}
ctx._session = generateSession()
ctx.sessionId = genSid.call(ctx, 24)
sessionIdStore.reset.call(ctx)
debug('created new session: %s', ctx.sessionId)
isNew = true
return ctx._session
}
await next()
if (touchSession) {
// if only this.session=, need try to decode and get the sessionID
if (!getter) {
ctx.sessionId = sessionIdStore.get.call(ctx)
}
await refreshSession(ctx, ctx._session, originalHash, isNew)
}
}
|
javascript
|
{
"resource": ""
}
|
q47786
|
getScriptData
|
train
|
function getScriptData(evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
var node = evt.currentTarget || evt.srcElement;
//Remove the listeners once here.
removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
removeListener(node, context.onScriptError, 'error');
return {
node: node,
id: node && node.getAttribute('data-requiremodule')
};
}
|
javascript
|
{
"resource": ""
}
|
q47787
|
completed
|
train
|
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
|
javascript
|
{
"resource": ""
}
|
q47788
|
computePixelPositionAndBoxSizingReliable
|
train
|
function computePixelPositionAndBoxSizingReliable() {
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;" +
"position:absolute;top:1%";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
|
javascript
|
{
"resource": ""
}
|
q47789
|
compareAscending
|
train
|
function compareAscending(a, b) {
return baseCompareAscending(a.criteria, b.criteria) || a.index - b.index;
}
|
javascript
|
{
"resource": ""
}
|
q47790
|
compareMultipleAscending
|
train
|
function compareMultipleAscending(a, b) {
var ac = a.criteria,
bc = b.criteria,
index = -1,
length = ac.length;
while (++index < length) {
var result = baseCompareAscending(ac[index], bc[index]);
if (result) {
return result;
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provided the same value
// for `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
//
// This also ensures a stable sort in V8 and other engines.
// See https://code.google.com/p/v8/issues/detail?id=90
return a.index - b.index;
}
|
javascript
|
{
"resource": ""
}
|
q47791
|
releaseArray
|
train
|
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < MAX_POOL_SIZE) {
arrayPool.push(array);
}
}
|
javascript
|
{
"resource": ""
}
|
q47792
|
releaseObject
|
train
|
function releaseObject(object) {
object.criteria = object.value = null;
if (objectPool.length < MAX_POOL_SIZE) {
objectPool.push(object);
}
}
|
javascript
|
{
"resource": ""
}
|
q47793
|
shimTrimLeft
|
train
|
function shimTrimLeft(string, chars) {
string = string == null ? '' : String(string);
if (!string) {
return string;
}
if (chars == null) {
return string.slice(trimmedLeftIndex(string))
}
chars = String(chars);
return string.slice(charsLeftIndex(string, chars));
}
|
javascript
|
{
"resource": ""
}
|
q47794
|
shimTrimRight
|
train
|
function shimTrimRight(string, chars) {
string = string == null ? '' : String(string);
if (!string) {
return string;
}
if (chars == null) {
return string.slice(0, trimmedRightIndex(string) + 1)
}
chars = String(chars);
return string.slice(0, charsRightIndex(string, chars) + 1);
}
|
javascript
|
{
"resource": ""
}
|
q47795
|
trimmedLeftIndex
|
train
|
function trimmedLeftIndex(string) {
var index = -1,
length = string.length;
while (++index < length) {
var c = string.charCodeAt(index);
if (!((c <= 160 && (c >= 9 && c <= 13) || c == 32 || c == 160) || c == 5760 || c == 6158 ||
(c >= 8192 && (c <= 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)))) {
break;
}
}
return index;
}
|
javascript
|
{
"resource": ""
}
|
q47796
|
trimmedRightIndex
|
train
|
function trimmedRightIndex(string) {
var index = string.length;
while (index--) {
var c = string.charCodeAt(index);
if (!((c <= 160 && (c >= 9 && c <= 13) || c == 32 || c == 160) || c == 5760 || c == 6158 ||
(c >= 8192 && (c <= 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)))) {
break;
}
}
return index;
}
|
javascript
|
{
"resource": ""
}
|
q47797
|
baseEach
|
train
|
function baseEach(collection, callback) {
var index = -1,
iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number') {
if (support.unindexedChars && isString(iterable)) {
iterable = iterable.split('');
}
while (++index < length) {
if (callback(iterable[index], index, collection) === false) {
break;
}
}
} else {
baseForOwn(collection, callback);
}
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q47798
|
baseEachRight
|
train
|
function baseEachRight(collection, callback) {
var iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number') {
if (support.unindexedChars && isString(iterable)) {
iterable = iterable.split('');
}
while (length--) {
if (callback(iterable[length], length, collection) === false) {
break;
}
}
} else {
baseForOwnRight(collection, callback);
}
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q47799
|
baseForOwn
|
train
|
function baseForOwn(object, callback) {
var index = -1,
props = keys(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.