_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3100
|
_suspendBeforeObserver
|
train
|
function _suspendBeforeObserver(obj, path, target, method, callback) {
return suspendListener(obj,
|
javascript
|
{
"resource": ""
}
|
q3101
|
set
|
train
|
function set(obj, keyName, value, tolerant) {
if (typeof obj === 'string') {
Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj));
value = keyName;
keyName = obj;
obj = null;
}
Ember.assert("Cannot call set with "+ keyName +" key.", !!keyName);
if (!obj) {
return setPath(obj, keyName, value, tolerant);
}
var meta = obj['__ember_meta__'];
var desc = meta && meta.descs[keyName];
var isUnknown, currentValue;
if (desc === undefined && isPath(keyName)) {
return setPath(obj, keyName, value, tolerant);
}
Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined);
Ember.assert('calling set on destroyed object', !obj.isDestroyed);
if (desc !== undefined) {
desc.set(obj, keyName, value);
} else {
if (typeof obj === 'object' && obj !== null && value !== undefined && obj[keyName] === value) {
return
|
javascript
|
{
"resource": ""
}
|
q3102
|
intern
|
train
|
function intern(str) {
var obj = {};
obj[str] = 1;
for (var key in obj) {
|
javascript
|
{
"resource": ""
}
|
q3103
|
makeArray
|
train
|
function makeArray(obj) {
if (obj === null || obj === undefined) { return []; }
|
javascript
|
{
"resource": ""
}
|
q3104
|
typeOf
|
train
|
function typeOf(item) {
var ret, modulePath;
// ES6TODO: Depends on Ember.Object which is defined in runtime.
if (typeof EmberObject === "undefined") {
modulePath = 'ember-runtime/system/object';
if (Ember.__loader.registry[modulePath]) {
EmberObject = Ember.__loader.require(modulePath)['default'];
|
javascript
|
{
"resource": ""
}
|
q3105
|
watchKey
|
train
|
function watchKey(obj, keyName, meta) {
// can't watch length on Array - it is special...
if (keyName === 'length' && typeOf(obj) === 'array') { return; }
var m = meta || metaFor(obj), watching = m.watching;
// activate watching first time
if (!watching[keyName]) {
watching[keyName] = 1;
var desc = m.descs[keyName];
if (desc && desc.willWatch) { desc.willWatch(obj, keyName); }
|
javascript
|
{
"resource": ""
}
|
q3106
|
train
|
function() {
this._super.apply(this, arguments);
Ember.deprecate('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.', !this.currentWhen);
// Map desired event name to
|
javascript
|
{
"resource": ""
}
|
|
q3107
|
train
|
function(){
var helperParameters = this.parameters;
var linkTextPath = helperParameters.options.linkTextPath;
var paths = getResolvedPaths(helperParameters);
var length = paths.length;
var path, i, normalizedPath;
if (linkTextPath) {
normalizedPath = getNormalizedPath(linkTextPath, helperParameters);
this.registerObserver(normalizedPath.root, normalizedPath.path, this, this.rerender);
}
for(i=0; i < length; i++) {
path = paths[i];
if (null === path) {
// A literal value was provided, not a path, so nothing to observe.
continue;
}
normalizedPath = getNormalizedPath(path, helperParameters);
this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged);
}
|
javascript
|
{
"resource": ""
}
|
|
q3108
|
train
|
function(params, transition) {
var match, name, sawParams, value;
var queryParams = get(this, '_qp.map');
for (var prop in params) {
if (prop === 'queryParams' || (queryParams && prop in queryParams)) {
continue;
}
if (match = prop.match(/^(.*)_id$/)) {
name = match[1];
value = params[prop];
}
sawParams = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q3109
|
train
|
function(name, model) {
var container = this.container;
|
javascript
|
{
"resource": ""
}
|
|
q3110
|
train
|
function(infos) {
updatePaths(this);
this._cancelLoadingEvent();
this.notifyPropertyChange('url');
// Put this in the runloop so url will be accurate. Seems
// less surprising than didTransition being out of sync.
run.once(this, this.trigger, 'didTransition');
|
javascript
|
{
"resource": ""
}
|
|
q3111
|
train
|
function(routeName, models, queryParams) {
var router = this.router;
|
javascript
|
{
"resource": ""
}
|
|
q3112
|
train
|
function(callback) {
var router = this.router;
if (!router) {
router = new Router();
router._triggerWillChangeContext = Ember.K;
router._triggerWillLeave = Ember.K;
router.callbacks = [];
router.triggerEvent = triggerEvent;
|
javascript
|
{
"resource": ""
}
|
|
q3113
|
map
|
train
|
function map(dependentKey, callback) {
var options = {
addedItem: function(array, item, changeMeta, instanceMeta) {
var mapped = callback.call(this, item, changeMeta.index);
array.insertAt(changeMeta.index, mapped);
return array;
},
|
javascript
|
{
"resource": ""
}
|
q3114
|
sort
|
train
|
function sort(itemsKey, sortDefinition) {
Ember.assert('Ember.computed.sort requires two arguments: an array key to sort and ' +
'either a sort properties key or sort function', arguments.length === 2);
if (typeof sortDefinition ===
|
javascript
|
{
"resource": ""
}
|
q3115
|
train
|
function(actionName) {
var args = [].slice.call(arguments, 1);
var target;
if (this._actions && this._actions[actionName]) {
if (this._actions[actionName].apply(this, args) === true) {
// handler returned true, so this action will bubble
} else {
return;
}
}
if (target = get(this, 'target')) {
|
javascript
|
{
"resource": ""
}
|
|
q3116
|
train
|
function(removing, adding) {
var removeCnt, addCnt, hasDelta;
if ('number' === typeof removing) removeCnt = removing;
else if (removing) removeCnt = get(removing, 'length');
else removeCnt = removing = -1;
if ('number' === typeof adding) addCnt = adding;
|
javascript
|
{
"resource": ""
}
|
|
q3117
|
train
|
function(name, target, method) {
if (!method) {
method = target;
|
javascript
|
{
"resource": ""
}
|
|
q3118
|
train
|
function(name) {
var length = arguments.length;
var args = new Array(length - 1);
|
javascript
|
{
"resource": ""
}
|
|
q3119
|
train
|
function(objects) {
if (!(Enumerable.detect(objects) || isArray(objects))) {
throw new TypeError("Must pass
|
javascript
|
{
"resource": ""
}
|
|
q3120
|
train
|
function(objects) {
beginPropertyChanges(this);
for (var i = objects.length - 1; i >= 0; i--) {
this.removeObject(objects[i]);
|
javascript
|
{
"resource": ""
}
|
|
q3121
|
train
|
function() {
var C = this;
var l = arguments.length;
if (l > 0) {
var args = new Array(l);
for (var i = 0; i < l; i++) {
args[i] = arguments[i];
|
javascript
|
{
"resource": ""
}
|
|
q3122
|
train
|
function(obj) {
// fail fast
if (!Enumerable.detect(obj)) return false;
var loc = get(this, 'length');
if (get(obj, 'length') !== loc) return false;
|
javascript
|
{
"resource": ""
}
|
|
q3123
|
train
|
function() {
if (get(this, 'isFrozen')) throw new EmberError(FROZEN_ERROR);
|
javascript
|
{
"resource": ""
}
|
|
q3124
|
train
|
function (index) {
var split = false;
var arrayOperationIndex, arrayOperation,
arrayOperationRangeStart, arrayOperationRangeEnd,
len;
// OPTIMIZE: we could search these faster if we kept a balanced tree.
// find leftmost arrayOperation to the right of `index`
for (arrayOperationIndex = arrayOperationRangeStart = 0, len = this._operations.length; arrayOperationIndex < len; ++arrayOperationIndex) {
arrayOperation = this._operations[arrayOperationIndex];
if (arrayOperation.type === DELETE) { continue; }
arrayOperationRangeEnd = arrayOperationRangeStart + arrayOperation.count - 1;
if (index === arrayOperationRangeStart) {
|
javascript
|
{
"resource": ""
}
|
|
q3125
|
train
|
function(rootElement, event, eventName) {
var self = this;
rootElement.on(event + '.ember', '.ember-view', function(evt, triggeringManager) {
var view = View.views[this.id];
var result = true;
var manager = self.canDispatchToEventManager ? self._findNearestEventManager(view, eventName) : null;
if (manager && manager !== triggeringManager) {
result = self._dispatchEvent(manager, evt, eventName, view);
} else if (view) {
result = self._bubbleEvent(view, evt, eventName);
}
return result;
});
rootElement.on(event
|
javascript
|
{
"resource": ""
}
|
|
q3126
|
train
|
function(content, start, removedCount) {
// If the contents were empty before and this template collection has an
// empty view remove it now.
var emptyView = get(this, 'emptyView');
if (emptyView && emptyView instanceof View) {
emptyView.removeFromParent();
}
// Loop through child views that correspond with the removed items.
// Note that we loop from the end of the array to the beginning because
// we are mutating it as we go.
|
javascript
|
{
"resource": ""
}
|
|
q3127
|
train
|
function(content, start, removed, added) {
var addedViews = [];
var view, item, idx, len, itemViewClass, emptyView;
len = content ? get(content, 'length') : 0;
if (len) {
itemViewClass = get(this, 'itemViewClass');
itemViewClass = handlebarsGetView(content, itemViewClass, this.container);
for (idx = start; idx < start+added; idx++) {
item = content.objectAt(idx);
view = this.createChildView(itemViewClass, {
|
javascript
|
{
"resource": ""
}
|
|
q3128
|
train
|
function(classBindings) {
var classNames = this.classNames;
var elem, newClass, dasherizedClass;
// Loop through all of the configured bindings. These will be either
// property names ('isUrgent') or property paths relative to the view
// ('content.isUrgent')
forEach(classBindings, function(binding) {
Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1);
// Variable in which the old class value is saved. The observer function
// closes over this variable, so it knows which string to remove when
// the property changes.
var oldClass;
// Extract just the property name from bindings like 'foo:bar'
var parsedPath = View._parsePropertyPath(binding);
// Set up an observer on the context. If the property changes, toggle the
// class name.
var observer = function() {
// Get the current value of the property
newClass = this._classStringForProperty(binding);
elem = this.$();
// If we had previously added a class to the element, remove it.
if (oldClass) {
elem.removeClass(oldClass);
// Also remove from classNames so that if the view gets rerendered,
// the class doesn't get added back to the DOM.
classNames.removeObject(oldClass);
}
// If necessary, add a new class. Make sure we keep track of it so
// it can be removed in the future.
if (newClass) {
elem.addClass(newClass);
oldClass = newClass;
} else {
oldClass = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q3129
|
train
|
function(property) {
var parsedPath = View._parsePropertyPath(property);
var path = parsedPath.path;
var val = get(this, path);
if (val === undefined && isGlobalPath(path)) {
val = get(Ember.lookup, path);
|
javascript
|
{
"resource": ""
}
|
|
q3130
|
interiorNamespace
|
train
|
function interiorNamespace(element){
if (
element &&
element.namespaceURI === svgNamespace &&
!svgHTMLIntegrationPoints[element.tagName]
) {
|
javascript
|
{
"resource": ""
}
|
q3131
|
buildSafeDOM
|
train
|
function buildSafeDOM(html, contextualElement, dom) {
var childNodes = buildIESafeDOM(html, contextualElement, dom);
if (contextualElement.tagName === 'SELECT') {
// Walk child nodes
for (var i = 0; childNodes[i]; i++) {
// Find and process the first option child node
if (childNodes[i].tagName === 'OPTION') {
if (detectAutoSelectedOption(childNodes[i].parentNode, childNodes[i], html)) {
|
javascript
|
{
"resource": ""
}
|
q3132
|
filterArguments
|
train
|
function filterArguments(args, params, inject) {
var newArgs = ['node', '_mocha'].concat(inject || []),
param, i, len,
type;
for (i = 2, len = args.length; i < len; i++) {
if ((i < args.length - 1) && (args[i].length > 2) && (args[i].substr(0, 2) === '--')) {
// Get parameter without '--'
param = args[i].substr(2);
// Is parameter used?
if (params.hasOwnProperty(param)) {
// Remember what the type was
type = typeof params[param];
// Overwrite value with next value in arguments
if (type === 'boolean') {
params[param] = true;
} else {
params[param] = args[i + 1];
i++;
// Convert back to
|
javascript
|
{
"resource": ""
}
|
q3133
|
prepareEnvironment
|
train
|
function prepareEnvironment (argv) {
var params, args;
// Define default values
params = {
'approved-folder': 'approved',
'build-folder': 'build',
'highlight-folder': 'highlight',
'config-folder': 'config',
'fail-orphans': false,
'fail-additions': false,
'test-path': null,
'config': null
};
// Filter arguments
args = filterArguments(argv, params, [
'--slow', '5000',
'--no-timeouts'
]);
if (!fs.existsSync(params['test-path'])) {
throw new Error('Cannot find path to ' + params['test-path']);
} else {
params['test-path'] = path.resolve(params['test-path']);
}
// Load global config
if (typeof params['config'] === 'string') {
params['config'] = require(path.resolve(params['config']));
} else {
params['config'] = params['config'] || {};
}
|
javascript
|
{
"resource": ""
}
|
q3134
|
makeBarsChartPath
|
train
|
function makeBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, isRange) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
let xSpacing = width / pointsOnScreen;
let barWidth = xSpacing - paddingLeft;
let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth;
let pathStr = []
let barCords = [];
let x1, y1, y2;
chart.data.some((d, idx) => {
x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx;
if (x1 > fullWidth * t && chart.drawChart) {
return true;
}
if (chart.stretchChart) {
x1 = x1 * t;
}
y1 = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1);
y2 = isRange ? (chartHeight+chartHeightOffset) - d.valueLow * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) :
|
javascript
|
{
"resource": ""
}
|
q3135
|
makeStackedBarsChartPath
|
train
|
function makeStackedBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, yAxisWidth, isRange) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
width = width - yAxisWidth;
let xSpacing = width / pointsOnScreen;
let barWidth = xSpacing - paddingLeft;
let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth;
let paths = []
let barCords = [];
let x1, y1, y2;
chart.data.some((d, idx) => {
x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx + yAxisWidth;
if (x1 > fullWidth * t && chart.drawChart) {
return true;
}
if (chart.stretchChart) {
x1 = x1 * t;
}
let prevY = 0;
d.forEach((stack) => {
y1 = (chartHeight+chartHeightOffset) - (stack.value+prevY) * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1);
|
javascript
|
{
"resource": ""
}
|
q3136
|
makeAreaChartPath
|
train
|
function makeAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) {
return makeLineOrAreaChartPath(chart, width, t,
|
javascript
|
{
"resource": ""
}
|
q3137
|
makeLineChartPath
|
train
|
function makeLineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) {
return makeLineOrAreaChartPath(chart, width, t,
|
javascript
|
{
"resource": ""
}
|
q3138
|
makeLineOrAreaChartPath
|
train
|
function makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, makeArea, isRange) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
let xSpacing = width / pointsOnScreen;
let centeriser = xSpacing / 2 - markerRadius;
let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser;
let lineStrArray = makeArea && !isRange ? ['M' + markerRadius, chartHeight+chartHeightOffset] : [];
if (isRange) {
lineStrArray.push('M');
lineStrArray.push(makeXcord(chart, fullWidth, t, centeriser, markerRadius));
lineStrArray.push((chartHeight+chartHeightOffset) - chart.data[0].value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[0 % chart.timingFunctions.length](t) : 1));
}
let xCord;
let lowCords = [];
chart.data.some((d, idx) => {
let spacing = idx*xSpacing + centeriser;
if (spacing > fullWidth * t && chart.drawChart) {
return true;
}
xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius);
// Move line to to next x-coordinate:
lineStrArray.push((idx > 0 || makeArea ? 'L' : 'M') + xCord);
// And y-cordinate:
let yCord = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1);
lineStrArray.push(yCord);
if (isRange) {
let
|
javascript
|
{
"resource": ""
}
|
q3139
|
makeSplineChartPath
|
train
|
function makeSplineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, closePath) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
let xSpacing = width / pointsOnScreen;
let centeriser = xSpacing / 2 - markerRadius;
let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser;
let xCord;
let xCords = [];
let yCords = [];
chart.data.forEach((d, idx) => {
let spacing = idx*xSpacing + centeriser;
if (spacing > fullWidth * t && chart.drawChart) {
return true;
}
xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius);
xCords.push(xCord);
yCords.push((chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1));
});
let px = computeSplineControlPoints(xCords);
let py = computeSplineControlPoints(yCords);
|
javascript
|
{
"resource": ""
}
|
q3140
|
rgbaToHsla
|
train
|
function rgbaToHsla(h, s, l, a) {
|
javascript
|
{
"resource": ""
}
|
q3141
|
inerpolateColorsFixedAlpha
|
train
|
function inerpolateColorsFixedAlpha(col1, col2, amount, alpha) {
let col1rgb = parseColor(col1);
let col2rgb = parseColor(col2);
return RGBobj2string({
r: Math.min(255, col1rgb.r * amount + col2rgb.r * Math.max(0,1-amount)),
g: Math.min(255, col1rgb.g * amount +
|
javascript
|
{
"resource": ""
}
|
q3142
|
shadeColor
|
train
|
function shadeColor(col, amount) {
let col1rgb = parseColor(col);
return RGBobj2string({
r: Math.min(255, col1rgb.r * amount +
|
javascript
|
{
"resource": ""
}
|
q3143
|
lightenColor
|
train
|
function lightenColor(col, amount) {
let colRgba = parseColor(col);
let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a);
colRgba = hslaToRgba(colHsla[0],colHsla[1],Math.min(Math.max(colHsla[2]+amount, 0), 1),colHsla[3]);
|
javascript
|
{
"resource": ""
}
|
q3144
|
hueshiftColor
|
train
|
function hueshiftColor(col, amount) {
let colRgba = parseColor(col);
let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a);
colRgba = hslaToRgba((hsl[0] + amount) % 1,
|
javascript
|
{
"resource": ""
}
|
q3145
|
getMaxSumStack
|
train
|
function getMaxSumStack(arr) { //here!!!
let maxValue = Number.MIN_VALUE;
arr
.forEach((d) => {
let stackSum = computeArrayValueSum(d);
|
javascript
|
{
"resource": ""
}
|
q3146
|
getMinMaxValuesXY
|
train
|
function getMinMaxValuesXY(arr) {
let maxValueX = Number.MIN_VALUE;
let maxValueY = Number.MIN_VALUE;
let minValueX = Number.MAX_VALUE;
let minValueY = Number.MAX_VALUE;
arr
.forEach((d) => {
if (d.x > maxValueX) {
maxValueX = d.x;
}
if (d.x < minValueX) {
minValueX = d.x;
}
if (d.y
|
javascript
|
{
"resource": ""
}
|
q3147
|
getMinMaxValuesCandlestick
|
train
|
function getMinMaxValuesCandlestick(arr) {
let maxValue = Number.MIN_VALUE;
let minValue = Number.MAX_VALUE;
arr
.forEach((d) => {
if (d.high > maxValue) {
maxValue = d.high;
|
javascript
|
{
"resource": ""
}
|
q3148
|
findRectangleIndexContainingPoint
|
train
|
function findRectangleIndexContainingPoint(rectangles, x, y) {
let closestIdx;
rectangles.some((d, idx) => {
|
javascript
|
{
"resource": ""
}
|
q3149
|
findClosestPointIndexWithinRadius
|
train
|
function findClosestPointIndexWithinRadius(points, x, y, radiusThreshold) {
let closestIdx;
let closestDist = Number.MAX_VALUE;
points.forEach((d, idx) => {
let distSqrd = Math.pow(d.x - x, 2) + Math.pow(d.y - y, 2); // changeto: (d.x - x)**2 + (d.y
|
javascript
|
{
"resource": ""
}
|
q3150
|
train
|
function (fieldDefinition) {
let type = fieldDefinition.fieldType;
if (typeof type === 'object') {
|
javascript
|
{
"resource": ""
}
|
|
q3151
|
buildConfig
|
train
|
function buildConfig( wantedEnv )
{
const isValid = wantedEnv &&
wantedEnv.length > 0 && allowedEnvs.indexOf( wantedEnv ) !== -1;
|
javascript
|
{
"resource": ""
}
|
q3152
|
generate
|
train
|
function generate (projectPatch, source, done) {
shell.mkdir('-p',
|
javascript
|
{
"resource": ""
}
|
q3153
|
getCacheRefreshInterval
|
train
|
function getCacheRefreshInterval() {
var value = parseInt(process.env[CACHE_REFRESH_KEY]);
// Should we 0
|
javascript
|
{
"resource": ""
}
|
q3154
|
createLocal
|
train
|
function createLocal(id) {
var nstr = prefix
|
javascript
|
{
"resource": ""
}
|
q3155
|
createThisVar
|
train
|
function createThisVar(id) {
var nstr = "this_"
|
javascript
|
{
"resource": ""
}
|
q3156
|
rewrite
|
train
|
function rewrite(node, nstr) {
var lo = node.range[0], hi = node.range[1]
|
javascript
|
{
"resource": ""
}
|
q3157
|
CacheClient
|
train
|
function CacheClient(store, config) {
EventEmitter.call(this);
this._store = store;
this._config = config || {};
|
javascript
|
{
"resource": ""
}
|
q3158
|
timeit
|
train
|
async function timeit(fun, context={}, args=[]) {
const start = now();
await fun.call(context, ...args);
|
javascript
|
{
"resource": ""
}
|
q3159
|
getCache
|
train
|
function getCache() {
return new Promise(function(resolve, reject) {
// create and fetch the cache key
get(getKey(), function(err, data) {
if (err) {
|
javascript
|
{
"resource": ""
}
|
q3160
|
putCache
|
train
|
function putCache() {
return new Promise(function(resolve, reject) {
// make the cache key
let key = getKey();
// adapt the image
adapt(function(err, stdout, stderr) {
if (err) {
return reject(err);
}
// convert the new image stream to buffer
stream2buffer(stdout, function(err, buffer) {
|
javascript
|
{
"resource": ""
}
|
q3161
|
getKey
|
train
|
function getKey() {
let paramString =
width + 'x' + height + '-'
+ path
+ (is2x ? '-@2x' : '')
+ (bg ? `_${bg}` : '')
+ (crop ? '_crop' : '')
+ (mode ? `_${mode}` : '')
|
javascript
|
{
"resource": ""
}
|
q3162
|
train
|
function(type, resStr, resArr, resObj) {
switch(type){
case 'css':
var css = resObj;
for (var res in resArr) {
//means that you will find options.
if (typeof(resArr[res]) == "object") {
//console.info('found object ', resArr[res]);
css.media = (resArr[res].options.media) ? resArr[res].options.media : css.media;
css.rel = (resArr[res].options.rel) ? resArr[res].options.rel : css.rel;
css.type = (resArr[res].options.type) ? resArr[res].options.type : css.type;
if (!css.content[resArr[res]._]) {
css.content[resArr[res]._] = '<link href="'+ resArr[res]._ +'" media="'+ css.media +'" rel="'+ css.rel +'" type="'+ css.type +'">';
resStr += '\n\t' + css.content[resArr[res]._]
}
} else {
css.content[resArr[res]] = '<link href="'+ resArr[res] +'" media="screen" rel="'+ css.rel +'" type="'+ css.type +'">';
resStr += '\n\t' + css.content[resArr[res]]
}
}
return { css : css, cssStr : resStr }
break;
case 'js':
var js = resObj;
for (var res in resArr) {
//means that you will find options
|
javascript
|
{
"resource": ""
}
|
|
q3163
|
train
|
function (i, res, files, cb) {
if (!files.length || files.length == 0) {
cb(false)
} else {
if ( fs.existsSync(files[i].target) ) new _(files[i].target).rmSync();
var sourceStream = fs.createReadStream(files[i].source);
var destinationStream = fs.createWriteStream(files[i].target);
sourceStream
.pipe(destinationStream)
.on('error', function () {
var err = 'Error on SuperController::copyFile(...): Not found ' + files[i].source + ' or ' + files[i].target;
|
javascript
|
{
"resource": ""
}
|
|
q3164
|
train
|
function(req) {
req.getParams = function() {
// copy
var params = JSON.parse(JSON.stringify(req.params));
switch( req.method.toLowerCase() ) {
case 'get':
params = merge(params, req.get, true);
break;
case 'post':
params = merge(params, req.post, true);
break;
case 'put':
params = merge(params, req.put, true);
break;
case 'delete':
params = merge(params, req.delete, true);
break;
}
return params
}
req.getParam = function(name) {
// copy
var param = null, params = JSON.parse(JSON.stringify(req.params));
|
javascript
|
{
"resource": ""
}
|
|
q3165
|
train
|
function (code) {
var list = {}, cde = 'short', name = null;
if ( typeof(code) != 'undefined' && typeof(userLocales[0][code]) == 'string' ) {
cde = code
} else if ( typeof(code) != 'undefined' ) (
console.warn('`'+ code +'` not supported : sticking with `short` code')
)
for ( var i = 0, len = userLocales.length; i< len; ++i ) {
if (userLocales[i][cde]) {
|
javascript
|
{
"resource": ""
}
|
|
q3166
|
train
|
function (arr){
var tmp = null,
curObj = {},
obj = {},
count = 0,
data = {},
last = null;
for (var r in arr) {
tmp = r.split(".");
//Creating structure - Adding sub levels
for (var o in tmp) {
count++;
if (last && typeof(obj[last]) == "undefined") {
curObj[last] = {};
if (count >= tmp.length) {
// assigning.
// !!! if null or undefined, it will be ignored while extending.
curObj[last][tmp[o]] = (arr[r]) ? arr[r] : "undefined";
last = null;
count = 0;
break
|
javascript
|
{
"resource": ""
}
|
|
q3167
|
assertSameObjectIdArray
|
train
|
function assertSameObjectIdArray(actual, expected, msg) {
assert(Array.isArray(actual), 'assertSameObjectIdArray: First argument is not an Array.')
assert(Array.isArray(expected), 'assertSameObjectIdArray: Second argument is not an Array.')
assert(size(actual) > 0 || size(expected) > 0, 'assertSameObjectIdArray: Received two empty Arrays.')
assert.strictEqual(size(actual), size(expected), 'assertSameObjectIdArray: arrays different sizes')
const parseIds = flow(map(stringifyObjectId), sortBy(identity))
|
javascript
|
{
"resource": ""
}
|
q3168
|
PreInstall
|
train
|
function PreInstall() {
var self = this;
var init = function() {
self.isWin32 = ( os.platform() == 'win32' ) ? true : false;
self.path = __dirname.substring(0, (__dirname.length - 'script'.length));
console.debug('paths -> '+ self.path);
if ( hasNodeModulesSync() ) { // cleaining old
var target = new _(self.path + '/node_modules');
console.debug('replacing: ', target.toString() );
var err = target.rmSync();
|
javascript
|
{
"resource": ""
}
|
q3169
|
train
|
function($form) {
var $form = $form, _id = null;
if ( typeof($form) == 'undefined' ) {
if ( typeof(this.target) != 'undefined' ) {
_id = this.target.getAttribute('id');
} else {
_id = this.getAttribute('id');
}
$form = instance.$forms[_id]
} else if ( typeof($form) == 'string' ) {
_id = $form;
_id = _id.replace(/\#/, '');
if ( typeof(instance.$forms[_id]) == 'undefined') {
|
javascript
|
{
"resource": ""
}
|
|
q3170
|
train
|
function(rules, tmp) {
var _r = null;
for (var r in rules) {
if ( typeof(rules[r]) == 'object' && typeof(instance.rules[tmp + r]) == 'undefined' ) {
_r = r;
if (/\[|\]/.test(r) ) { // must be a real path
_r = r.replace(/\[/g, '.').replace(/\]/g, '');
}
|
javascript
|
{
"resource": ""
}
|
|
q3171
|
createSplitterForField
|
train
|
function createSplitterForField(multiFieldDefinitionPart, fieldName) {
if (multiFieldDefinitionPart === undefined) {
throw ("'multiFieldDefinitionPart' must not be undefined");
}
if (fieldName === undefined) {
throw ("'fieldName' must not be undefined");
}
const delimiter = multiFieldDefinitionPart.delimiter;
let escapeChar = multiFieldDefinitionPart.escapeChar;
let removeWhiteSpace = true;
let uniqueFields = true;
let sortFields = true;
let removeEmpty = true;
// set default values
if (multiFieldDefinitionPart.removeWhiteSpace !== undefined) {
// remove leading and trailing whitespaces
removeWhiteSpace = multiFieldDefinitionPart.removeWhiteSpace;
}
if (multiFieldDefinitionPart.uniqueFields !== undefined) {
// remove duplicates from the list
uniqueFields = multiFieldDefinitionPart.uniqueFields;
}
if (multiFieldDefinitionPart.sortFields !== undefined) {
// sort the fields
sortFields = multiFieldDefinitionPart.sortFields;
}
if (multiFieldDefinitionPart.removeEmpty !== undefined) {
// Empty fields will be deleted
removeEmpty = multiFieldDefinitionPart.removeEmpty;
}
return function (content) {
if (content.hasOwnProperty(fieldName)) {
// the field exists in the content record
let fieldValue = content[fieldName];
if (fieldValue) {
// ------------------------------------------------
// escape delimiter
// ------------------------------------------------
if (escapeChar) {
escapeChar = escapeChar.replace(/\\/, "\\\\");
escapeChar = escapeChar.replace(/\//, "\\/");
// The escaped delimiter will be replaced by the string '<--DIVIDER-->'
let re = new RegExp(escapeChar + delimiter, 'g');
fieldValue = fieldValue.replace(re, TMP_DEVIDER);
}
// ------------------------------------------------
// split the string
// ------------------------------------------------
let values = fieldValue.split(delimiter);
if (escapeChar) {
// remove the escape char
let re = new RegExp(TMP_DEVIDER, 'g');
for (let i = 0; i < values.length; i++) {
|
javascript
|
{
"resource": ""
}
|
q3172
|
findPrevNode
|
train
|
function findPrevNode(firstNode, item, comparer) {
let ret;
let prevNode = firstNode;
// while item > prevNode.value
while (prevNode != undefined
|
javascript
|
{
"resource": ""
}
|
q3173
|
findNode
|
train
|
function findNode(firstNode, predicate) {
let curNode = firstNode;
while (curNode != null) {
if (predicate(curNode.value))
|
javascript
|
{
"resource": ""
}
|
q3174
|
createCheckEmail
|
train
|
function createCheckEmail(fieldDefinition, fieldName) {
const severity = propertyHelper.getSeverity(fieldDefinition);
// return getIteratorFunction: function (fieldName, defaultValue, checkProperties, checkFunction, getErrorFunction,
// getValueIfErrorFunction, getValueIfOkFunction) {
let errorInfo = {
|
javascript
|
{
"resource": ""
}
|
q3175
|
createCheckDefaultValue
|
train
|
function createCheckDefaultValue(fieldDefinition, fieldName) {
const defaultValue = fieldDefinition.defaultValue;
// -----------------------------------------------------------------------
// Set default value
// -----------------------------------------------------------------------
return function (content) {
const valueToCheck = content[fieldName];
// If the value is defined, we need to check it
if (valueToCheck === undefined || valueToCheck === null) {
|
javascript
|
{
"resource": ""
}
|
q3176
|
train
|
function (format) {
var name = "default";
for (var f in self.masks) {
if ( self.masks[f] === format
|
javascript
|
{
"resource": ""
}
|
|
q3177
|
train
|
function(date, dateTo) {
if ( dateTo instanceof Date) {
// The number of milliseconds in one day
var oneDay = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1Ms = date.getTime()
|
javascript
|
{
"resource": ""
}
|
|
q3178
|
train
|
function(date, dateTo, mask) {
if ( dateTo instanceof Date) {
var count = countDaysTo(date, dateTo)
, month = date.getMonth()
, year = date.getFullYear()
, day = date.getDate() + 1
, dateObj = new Date(year, month, day)
,
|
javascript
|
{
"resource": ""
}
|
|
q3179
|
BaseDecorator
|
train
|
function BaseDecorator(cache, config, configSchema) {
this._cache = cache;
if (config) {
this._configSchema = configSchema;
this._config = this._humanTimeIntervalToMs(config);
this._config = this._validateConfig(configSchema, this._config);
}
// substitute cb, for
|
javascript
|
{
"resource": ""
}
|
q3180
|
train
|
function (obj) {
if (
!obj
|| {}.toString.call(obj) !== '[object Object]'
|| obj.nodeType
|| obj.setInterval
) {
return false
}
var hasOwn = {}.hasOwnProperty;
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
// added test for node > v6
var hasMethodPrototyped = ( typeof(obj.constructor) != 'undefined' ) ? hasOwn.call(obj.constructor.prototype, 'isPrototypeOf') : false;
|
javascript
|
{
"resource": ""
}
|
|
q3181
|
doCallback
|
train
|
function doCallback(callback, reason, value) {
// Note: Could delay callback call until later, as When.js does, but this
// loses the stack (particularly for bluebird long traces) and causes
// unnecessary delay in the non-exception (common) case.
try {
// Match argument length to resolve/reject in case callback cares.
// Note: bluebird has argument length 1 if value === undefined due to
// https://github.com/petkaantonov/bluebird/issues/170
//
|
javascript
|
{
"resource": ""
}
|
q3182
|
promiseNodeify
|
train
|
function promiseNodeify(promise, callback) {
if (typeof callback !== 'function') {
return promise;
}
function onRejected(reason) {
// callback is unlikely to recognize or expect a falsey error.
// (we also rely on truthyness for arguments.length in doCallback)
// Convert it to something truthy
let truthyReason = reason;
if (!truthyReason) {
// Note: unthenify converts falsey rejections to TypeError:
// https://github.com/blakeembrey/unthenify/blob/v1.0.0/src/index.ts#L32
|
javascript
|
{
"resource": ""
}
|
q3183
|
getBinaryCase
|
train
|
function getBinaryCase (str, val) {
let res = '';
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code >= 65 && code <= 90) {
res += val & 1 ? String.fromCharCode(code + 32) : String.fromCharCode(code);
|
javascript
|
{
"resource": ""
}
|
q3184
|
resolvePermission
|
train
|
function resolvePermission(params) {
var dbPermissions = mBaaS.permission_map.db;
if (params.act && dbPermissions && dbPermissions[params.act]) {
|
javascript
|
{
"resource": ""
}
|
q3185
|
getFilterMethods
|
train
|
function getFilterMethods(type, controller, action) {
// Get all filters for the action.
let filters = getFilters(type, controller, action)
// Get filter method names to be skipped.
type = `skip${type[0].toUpperCase() + type.slice(1)}`
let skipFilterMethods = _.map(getFilters(type, controller, action), 'action')
// Remove filters that should be skipped.
filters = _.filter(filters, f => {
for(let method of skipFilterMethods)
if(method
|
javascript
|
{
"resource": ""
}
|
q3186
|
getFilters
|
train
|
function getFilters(type, controller, action) {
// User can set 'only' and 'except' rules on filters to be used on one
// or many action methods.
let useOptions = { only: true, except: false }
// Only return action filter methods that apply.
return _.filter(controller[`__${type}Filters`], filter => {
// An action must be defined in each filter.
if(!('action' in filter) || !filter.action)
throw new Error(`No action defined in filter for [${controller.constructor.name}.${type}: ${JSON.stringify(filter)}].`)
|
javascript
|
{
"resource": ""
}
|
q3187
|
charlike
|
train
|
async function charlike(settings = {}) {
const proj = settings.project;
if (!proj || (proj && typeof proj !== 'object')) {
throw new TypeError('expect `settings.project` to be an object');
}
const options = await makeDefaults(settings);
const { project, templates } = options;
const cfgDir = path.join(os.homedir(), '.config', 'charlike');
const tplDir = path.join(cfgDir, 'templates');
const templatesDir = templates ? path.resolve(templates) : null;
if (templatesDir && fs.existsSync(templatesDir)) {
project.templates = templatesDir;
} else if (fs.existsSync(cfgDir) && fs.existsSync(tplDir)) {
project.templates = tplDir;
} else {
project.templates = path.join(path.dirname(__dirname), 'templates');
}
if (!fs.existsSync(project.templates)) {
throw new Error(`source templates folder not exist: ${project.templates}`);
}
const locals = objectAssign({}, options.locals, { project });
const stream = fastGlob.stream('**/*', {
cwd: project.templates,
ignore: arrayify(null),
});
return new Promise((resolve, reject) => {
stream.on('error', reject);
stream.on('end', () => {
// Note: Seems to be called before really write to the optionsination directory.
// Stream are still fucking shit even in Node v10.
// Feels like nothing happend since v0.10.
// For proof, `process.exit` from inside the `.then` in the CLI,
// it will end/close the program before even create the options folder.
// One more proof: put one console.log in stream.on('data')
// and you will see that it still outputs even after calling the resolve()
|
javascript
|
{
"resource": ""
}
|
q3188
|
train
|
function(request, params, route) {
var uRe = params.url.split(/\//)
, uRo = route.split(/\//)
, maxLen = uRo.length
, score = 0
, r = {}
, i = 0;
//attaching routing description for this request
request.routing = params; // can be retried in controller with: req.routing
if (uRe.length === uRo.length) {
for (; i<maxLen; ++i) {
if (uRe[i] === uRo[i]) {
|
javascript
|
{
"resource": ""
}
|
|
q3189
|
wrapFn
|
train
|
function wrapFn (gen) {
if (!is.function(gen)) throw new Error('Middleware must be a function')
if (!is.generator(gen)) return
|
javascript
|
{
"resource": ""
}
|
q3190
|
use
|
train
|
function use () {
// init hooks
if (!this.hasOwnProperty('_hooks')) {
this._hooks = {}
}
var args = Array.prototype.slice.call(arguments)
var i, j, l, m
var name = null
if (is.array(args[0])) {
// use(['a','b','c'], ...)
var arr = args.shift()
for (i = 0, l = arr.length; i < l; i++) {
use.apply(this, [arr[i]].concat(args))
}
return this
} else if (is.object(args[0]) && args[0]._hooks) {
// use(ginga)
var key
// concat hooks
for (key in args[0]._hooks) {
use.call(this, key, args[0]._hooks[key])
}
return this
}
// method name
if (is.string(args[0])) name = args.shift()
if (!name) throw new Error('Method name is not defined.')
if (!this._hooks[name]) this._hooks[name] = []
for (i =
|
javascript
|
{
"resource": ""
}
|
q3191
|
define
|
train
|
function define () {
var args = Array.prototype.slice.call(arguments)
var i, l
var name = args.shift()
if (is.array(name)) {
name = args.shift()
for (i = 0, l = name.length; i < l; i++) {
define.apply(this, [name[i]].concat(args))
}
return this
}
if (!is.string(name)) throw new Error('Method name is not defined')
var invoke = is.function(args[args.length - 1]) ? wrapFn(args.pop()) : null
var pre = args.map(wrapFn)
// define scope method
this[name] = function () {
var args = Array.prototype.slice.call(arguments)
var self = this
var callback
if (is.function(args[args.length - 1])) callback = args.pop()
// init pipeline
var pipe = []
var obj = this
// prototype chain
while (obj) {
if (obj.hasOwnProperty('_hooks') && obj._hooks[name]) {
pipe.unshift(obj._hooks[name])
}
obj = Object.getPrototypeOf(obj)
}
// pre middlewares
pipe.unshift(pre)
// invoke middleware
if (invoke) pipe.push(invoke)
pipe = flatten(pipe)
// context object and next triggerer
var ctx = new EventEmitter()
ctx.method = name
ctx.args = args
var index = 0
var size = pipe.length
function next (err, res) {
if (err || index === size) {
var args = Array.prototype.slice.call(arguments)
// callback when err or end of pipeline
|
javascript
|
{
"resource": ""
}
|
q3192
|
train
|
function(callback) {
self.configureDatabases(function(err) {
if (err) {
process.exit(111);
|
javascript
|
{
"resource": ""
}
|
|
q3193
|
train
|
function (fieldDefinition, fieldName) {
const severity = propertyHelper.getSeverity(fieldDefinition, undefined, 'mandatory');
const isMandatoy = propertyHelper.getProperty(fieldDefinition, undefined, 'mandatory');
// const severity = fieldDefinition.severity;
// const isMandatoy = fieldDefinition.mandatory;
if (isMandatoy === true) {
|
javascript
|
{
"resource": ""
}
|
|
q3194
|
train
|
function (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.
if (
evt.type === "load" ||
|
javascript
|
{
"resource": ""
}
|
|
q3195
|
train
|
function (attrName, oldVal, newVal) {
var property = vcomet.util.hyphenToCamelCase(attrName);
// The onAttributeChanged callback is triggered whether its observed or as a reflection of a property
if (el.__observeAttributes[attrName] || el.__reflectProperties[property]) {
vcomet.triggerAllCallbackEvents(el, config, "onAttributeChanged", [attrName, oldVal, newVal]);
}
|
javascript
|
{
"resource": ""
}
|
|
q3196
|
createAccessPolicy
|
train
|
function createAccessPolicy(thingId) {
const thingPolicy = {
id: thingId + "-" + thingId + "-cru-policy",
effect: "allow",
actions: ["dcd:actions:create", "dcd:actions:read", "dcd:actions:update"],
subjects: ["dcd:things:" + thingId],
resources: [
"dcd:things:" + thingId,
"dcd:things:" + thingId + ":properties",
|
javascript
|
{
"resource": ""
}
|
q3197
|
createOwnerAccessPolicy
|
train
|
function createOwnerAccessPolicy(thingId, subject) {
const thingOwnerPolicy = {
id: thingId + "-" + subject + "-clrud-policy",
effect: "allow",
actions: [
"dcd:actions:create",
"dcd:actions:list",
"dcd:actions:read",
"dcd:actions:update",
"dcd:actions:delete"
],
subjects: [subject],
|
javascript
|
{
"resource": ""
}
|
q3198
|
PopulateInDecorator
|
train
|
function PopulateInDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
populateIn: joi.number().integer().min(500).required(),
populateInAttempts: joi.number().integer().default(5),
pausePopulateIn: joi.number().integer().required(),
accessedAtThrottle: joi.number().integer().default(1000)
}));
this._store = this._getStore();
this._timer
|
javascript
|
{
"resource": ""
}
|
q3199
|
concatenateFile
|
train
|
function concatenateFile(file, done) {
// Append the concat file itself to the end of the concatenation.
files[file].files.push(file)
// Make sure the output is defined.
if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) {
// Output the file to the destination, without the ".concat".
const dir = path.dirname(file)
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.