_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q47300
|
ConstructorComponent
|
train
|
function ConstructorComponent(id, ctor, hs) {
Component.call(this, id, ctor, hs);
this._ctor = ctor;
}
|
javascript
|
{
"resource": ""
}
|
q47301
|
Component
|
train
|
function Component(id, mod, asm) {
var keys, i, len;
this.id = id;
this.dependencies = mod['@require'] || [];
this.singleton = mod['@singleton'];
this.implements = mod['@implements'] || [];
if (typeof this.implements == 'string') {
this.implements = [ this.implements ]
}
this.a = {};
if (typeof mod === 'object' || typeof mod === 'function') {
keys = Object.keys(mod);
for (i = 0, len = keys.length; i < len; ++i) {
if (keys[i].indexOf('@') == 0) {
this.a[keys[i]] = mod[keys[i]];
}
}
}
this._assembly = asm;
}
|
javascript
|
{
"resource": ""
}
|
q47302
|
onWritten
|
train
|
function onWritten(writeErr) {
var flags = fo.getFlags({
overwrite: optResolver.resolve('overwrite', file),
append: optResolver.resolve('append', file),
});
if (fo.isFatalOverwriteError(writeErr, flags)) {
return callback(writeErr);
}
callback(null, file);
}
|
javascript
|
{
"resource": ""
}
|
q47303
|
defaultHandler
|
train
|
function defaultHandler() {
let containerBottom;
let elementBottom;
if (container === windowElement) {
containerBottom = height(container) + pageYOffset(container[0].document.documentElement);
elementBottom = offsetTop(elem) + height(elem);
} else {
containerBottom = height(container);
let containerTopOffset = 0;
if (offsetTop(container) !== undefined) {
containerTopOffset = offsetTop(container);
}
elementBottom = (offsetTop(elem) - containerTopOffset) + height(elem);
}
if (useDocumentBottom) {
elementBottom = height((elem[0].ownerDocument || elem[0].document).documentElement);
}
const remaining = elementBottom - containerBottom;
const shouldScroll = remaining <= (height(container) * scrollDistance) + 1;
if (shouldScroll) {
checkWhenEnabled = true;
if (scrollEnabled) {
if (scope.$$phase || $rootScope.$$phase) {
scope.infiniteScroll();
} else {
scope.$apply(scope.infiniteScroll);
}
}
} else {
if (checkInterval) { $interval.cancel(checkInterval); }
checkWhenEnabled = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q47304
|
throttle
|
train
|
function throttle(func, wait) {
let timeout = null;
let previous = 0;
function later() {
previous = new Date().getTime();
$interval.cancel(timeout);
timeout = null;
return func.call();
}
function throttled() {
const now = new Date().getTime();
const remaining = wait - (now - previous);
if (remaining <= 0) {
$interval.cancel(timeout);
timeout = null;
previous = now;
func.call();
} else if (!timeout) {
timeout = $interval(later, remaining, 1);
}
}
return throttled;
}
|
javascript
|
{
"resource": ""
}
|
q47305
|
changeContainer
|
train
|
function changeContainer(newContainer) {
if (container != null) {
container.unbind('scroll', handler);
}
container = newContainer;
if (newContainer != null) {
container.bind('scroll', handler);
}
}
|
javascript
|
{
"resource": ""
}
|
q47306
|
train
|
function () {
NAF.log.setDebug(this.data.debug);
NAF.log.write('Networked-Aframe Connecting...');
this.checkDeprecatedProperties();
this.setupNetworkAdapter();
if (this.hasOnConnectFunction()) {
this.callOnConnect();
}
return NAF.connection.connect(this.data.serverURL, this.data.app, this.data.room, this.data.audio);
}
|
javascript
|
{
"resource": ""
}
|
|
q47307
|
SimpsonDef
|
train
|
function SimpsonDef(func, a, b) {
var c = (a + b) / 2;
var d = Math.abs(b - a) / 6;
return d * (func(a) + 4 * func(c) + func(b));
}
|
javascript
|
{
"resource": ""
}
|
q47308
|
SimpsonRecursive
|
train
|
function SimpsonRecursive(func, a, b, whole, eps) {
var c = a + b;
var left = SimpsonDef(func, a, c);
var right = SimpsonDef(func, c, b);
if (Math.abs(left + right - whole) <= 15 * eps) {
return left + right + (left + right - whole) / 15;
} else {
return SimpsonRecursive(func, a, c, eps / 2, left) + SimpsonRecursive(func, c, b, eps / 2, right);
}
}
|
javascript
|
{
"resource": ""
}
|
q47309
|
train
|
function (M) { //starting at bottom right, moving horizontally
var jump = false,
tl = n * n,
br = 1,
inc = 1,
row, col, val, i, j;
M[0][0] = tl;
M[n - 1][n - 1] = br;
for (i = 1; i < n; i++) {
//generate top/bottom row
if (jump) {
tl -= 4 * inc;
br += 4 * inc;
inc++;
} else {
tl--;
br++;
}
M[0][i] = tl;
M[n - 1][n - 1 - i] = br;
jump = !jump;
}
var dec = true;
for (i = 1; i < n; i++) {
//iterate diagonally from top row
row = 0;
col = i;
val = M[row][col];
for (j = 1; j < i + 1; j++) {
if (dec) {
val -= 1;
} else {
val += 1;
}
row++;
col--;
M[row][col] = val;
}
dec = !dec;
}
if (n % 2 === 0) {
dec = true;
} else {
dec = false;
}
for (i = 1; i < n - 1; i++) {
//iterate diagonally from bottom row
row = n - 1;
col = i;
val = M[row][col];
for (j = 1; j < n - i; j++) {
if (dec) {
val--;
} else {
val++;
}
row--;
col++;
M[row][col] = val;
}
dec = !dec;
}
return M;
}
|
javascript
|
{
"resource": ""
}
|
|
q47310
|
gulpSVGSprite
|
train
|
function gulpSVGSprite(config) {
// Extend plugin error
function extendError(pError, error) {
if (error && (typeof error === 'object')) {
['name', 'errno'].forEach(function(property) {
if (property in error) {
this[property] = error[property];
}
}, pError);
}
return pError;
}
// Instanciate spriter instance
var spriter = new SVGSpriter(config);
var shapes = 0;
// Intercept error log and convert to plugin errors
spriter.config.log.error = function(message, error) {
this.emit('error', extendError(new PluginError(PLUGIN_NAME, message), error));
};
return through2.obj(function (file, enc, cb) {
var error = null;
try {
spriter.add(file);
++shapes;
} catch(e) {
error = (!e.plugin || (e.plugin !== PLUGIN_NAME)) ? extendError(new PluginError(PLUGIN_NAME, e.message), e) : e;
}
return cb(error);
}, function(cb) {
var stream = this;
spriter.compile(function(error, result /*, data*/){
if (error) {
stream.emit('error', new PluginError(PLUGIN_NAME, error));
} else if (shapes > 0) {
for (var mode in result) {
for (var resource in result[mode]) {
stream.push(result[mode][resource]);
}
}
}
cb();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q47311
|
extendError
|
train
|
function extendError(pError, error) {
if (error && (typeof error === 'object')) {
['name', 'errno'].forEach(function(property) {
if (property in error) {
this[property] = error[property];
}
}, pError);
}
return pError;
}
|
javascript
|
{
"resource": ""
}
|
q47312
|
stringify
|
train
|
function stringify (val) {
var stack = val.stack
if (stack) {
return String(stack)
}
var str = String(val)
return str === toString.call(val)
? inspect(val)
: str
}
|
javascript
|
{
"resource": ""
}
|
q47313
|
train
|
function(event) {
var input = event.target,
datalist = input.list,
keyOpen = event.keyCode === keyUP || event.keyCode === keyDOWN;
// Check for whether the events target was an input and still check for an existing instance of the datalist and polyfilling select
if (input.tagName.toLowerCase() !== 'input' || datalist === null) {
return;
}
// Handling IE10+ & EDGE
if (isGteIE10 || isEDGE) {
// On keypress check for value
if (
getInputValue(input) !== '' &&
!keyOpen &&
event.keyCode !== keyENTER &&
event.keyCode !== keyESC &&
// As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here
(isGteIE10 || input.type === 'text')
) {
updateIEOptions(input, datalist);
// TODO: Check whether this update is necessary depending on the options values
input.focus();
}
return;
}
var visible = false,
// Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted)
datalistSelect =
datalist.getElementsByClassName(classNamePolyfillingSelect)[0] ||
setUpPolyfillingSelect(input, datalist);
// On an ESC or ENTER key press within the input, let's break here and afterwards hide the datalist select, but if the input contains a value or one of the opening keys have been pressed ...
if (
event.keyCode !== keyESC &&
event.keyCode !== keyENTER &&
(getInputValue(input) !== '' || keyOpen) &&
datalistSelect !== undefined
) {
// ... prepare the options
if (prepOptions(datalist, input).length > 0) {
visible = true;
}
var firstEntry = 0,
lastEntry = datalistSelect.options.length - 1;
// ... preselect best fitting index
if (touched) {
datalistSelect.selectedIndex = firstEntry;
} else if (keyOpen && input.getAttribute('type') !== 'number') {
datalistSelect.selectedIndex =
event.keyCode === keyUP ? lastEntry : firstEntry;
// ... and on arrow up or down keys, focus the select
datalistSelect.focus();
}
}
// Toggle the visibility of the datalist select according to previous checks
toggleVisibility(visible, datalistSelect);
}
|
javascript
|
{
"resource": ""
}
|
|
q47314
|
train
|
function(event) {
var input = event.target,
datalist = input.list;
if (
!input.matches('input[list]') ||
!input.matches('.' + classNameInput) ||
!datalist
) {
return;
}
// Query for related option - and escaping the value as doublequotes wouldn't work
var option = datalist.querySelector(
'option[value="' +
getInputValue(input).replace(/\\([\s\S])|(")/g, '\\$1$2') +
'"]'
);
// We're using .getAttribute instead of .dataset here for IE10
if (option && option.getAttribute('data-originalvalue')) {
setInputValue(input, option.getAttribute('data-originalvalue'));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47315
|
train
|
function(option, inputValue) {
var optVal = option.value.toLowerCase(),
inptVal = inputValue.toLowerCase(),
label = option.getAttribute('label'),
text = option.text.toLowerCase();
/*
"Each option element that is a descendant of the datalist element, that is not disabled, and whose value is a string that isn't the empty string, represents a suggestion. Each suggestion has a value and a label."
"If appropriate, the user agent should use the suggestion's label and value to identify the suggestion to the user."
*/
return Boolean(
option.disabled === false &&
((optVal !== '' && optVal.indexOf(inptVal) !== -1) ||
(label && label.toLowerCase().indexOf(inptVal) !== -1) ||
(text !== '' && text.indexOf(inptVal) !== -1))
);
}
|
javascript
|
{
"resource": ""
}
|
|
q47316
|
train
|
function(event) {
// Check for correct element on this event delegation
if (!event.target.matches('input[list]')) {
return;
}
var input = event.target,
datalist = input.list;
// Check for whether the events target was an input and still check for an existing instance of the datalist
if (input.tagName.toLowerCase() !== 'input' || datalist === null) {
return;
}
// Test for whether this input has already been enhanced by the polyfill
if (!input.matches('.' + classNameInput)) {
prepareInput(input, event.type);
}
// #GH-49: Microsoft EDGE / datalist popups get "emptied" when receiving focus via tabbing
if (isEDGE && event.type === 'focusin') {
// Set the value of the first option to it's value - this actually triggers a redraw of the complete list
var firstOption = input.list.options[0];
firstOption.value = firstOption.value;
}
// Break here for IE10+ & EDGE
if (isGteIE10 || isEDGE) {
return;
}
var // Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted)
datalistSelect =
datalist.getElementsByClassName(classNamePolyfillingSelect)[0] ||
setUpPolyfillingSelect(input, datalist),
// Either have the select set to the state to get displayed in case of that it would have been focused or because it's the target on the inputs blur - and check for general existance of any option as suggestions
visible =
datalistSelect &&
datalistSelect.querySelector('option:not(:disabled)') &&
((event.type === 'focusin' && getInputValue(input) !== '') ||
(event.relatedTarget && event.relatedTarget === datalistSelect));
// Toggle the visibility of the datalist select according to previous checks
toggleVisibility(visible, datalistSelect);
}
|
javascript
|
{
"resource": ""
}
|
|
q47317
|
train
|
function(input, eventType) {
// We'd like to prevent autocomplete on the input datalist field
input.setAttribute('autocomplete', 'off');
// WAI ARIA attributes
input.setAttribute('role', 'textbox');
input.setAttribute('aria-haspopup', 'true');
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-owns', input.getAttribute('list'));
// Bind the keyup event on the related datalists input
if (eventType === 'focusin') {
input.addEventListener('keyup', inputInputList);
input.addEventListener('focusout', changesInputList, true);
// As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here
if (isGteIE10 || (isEDGE && input.type === 'text')) {
input.addEventListener('input', inputInputListIE);
}
} else if (eventType === 'blur') {
input.removeEventListener('keyup', inputInputList);
input.removeEventListener('focusout', changesInputList, true);
// As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here
if (isGteIE10 || (isEDGE && input.type === 'text')) {
input.removeEventListener('input', inputInputListIE);
}
}
// Add class for identifying that this input is even already being polyfilled
input.className += ' ' + classNameInput;
}
|
javascript
|
{
"resource": ""
}
|
|
q47318
|
train
|
function(input) {
// In case of type=email and multiple attribute, we would need to grab the last piece
// Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly
return input.getAttribute('type') === 'email' &&
input.getAttribute('multiple') !== null
? input.value.substring(input.value.lastIndexOf(',') + 1)
: input.value;
}
|
javascript
|
{
"resource": ""
}
|
|
q47319
|
train
|
function(input, datalistSelectValue) {
var lastSeperator;
// In case of type=email and multiple attribute, we need to set up the resulting inputs value differently
input.value =
// Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly
input.getAttribute('type') === 'email' &&
input.getAttribute('multiple') !== null &&
(lastSeperator = input.value.lastIndexOf(',')) > -1
? input.value.slice(0, lastSeperator) + ',' + datalistSelectValue
: datalistSelectValue;
}
|
javascript
|
{
"resource": ""
}
|
|
q47320
|
train
|
function(input, datalist) {
// Check for whether it's of one of the supported input types defined at the beginning
// Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly
// and still check for an existing instance
if (
(input.getAttribute('type') &&
supportedTypes.indexOf(input.getAttribute('type')) === -1) ||
datalist === null
) {
return;
}
var rects = input.getClientRects(),
// Measurements
inputStyles = window.getComputedStyle(input),
datalistSelect = dcmnt.createElement('select');
// Setting a class for easier identifying that select afterwards
datalistSelect.setAttribute('class', classNamePolyfillingSelect);
// Set general styling related definitions
datalistSelect.style.position = 'absolute';
// Initially hiding the datalist select
toggleVisibility(false, datalistSelect);
// The select itself shouldn't be a possible target for tabbing
datalistSelect.setAttribute('tabindex', '-1');
// WAI ARIA attributes
datalistSelect.setAttribute('aria-live', 'polite');
datalistSelect.setAttribute('role', 'listbox');
if (!touched) {
datalistSelect.setAttribute('aria-multiselectable', 'false');
}
// The select should get positioned underneath the input field ...
if (inputStyles.getPropertyValue('display') === 'block') {
datalistSelect.style.marginTop =
'-' + inputStyles.getPropertyValue('margin-bottom');
} else {
var direction =
inputStyles.getPropertyValue('direction') === 'rtl' ? 'right' : 'left';
datalistSelect.style.setProperty(
'margin-' + direction,
'-' +
(rects[0].width +
parseFloat(inputStyles.getPropertyValue('margin-' + direction))) +
'px'
);
datalistSelect.style.marginTop =
parseInt(rects[0].height + (input.offsetTop - datalist.offsetTop), 10) +
'px';
}
// Set the polyfilling selects border-radius equally to the one by the polyfilled input
datalistSelect.style.borderRadius = inputStyles.getPropertyValue(
'border-radius'
);
datalistSelect.style.minWidth = rects[0].width + 'px';
if (touched) {
var messageElement = dcmnt.createElement('option');
// ... and it's first entry should contain the localized message to select an entry
messageElement.innerText = datalist.title;
// ... and disable this option, as it shouldn't get selected by the user
messageElement.disabled = true;
// ... and assign a dividable class to it
messageElement.setAttribute('class', 'message');
// ... and finally insert it into the select
datalistSelect.appendChild(messageElement);
}
// Add select to datalist element ...
datalist.appendChild(datalistSelect);
// ... and our upfollowing functions to the related event
if (touched) {
datalistSelect.addEventListener('change', changeDataListSelect);
} else {
datalistSelect.addEventListener('click', changeDataListSelect);
}
datalistSelect.addEventListener('blur', changeDataListSelect);
datalistSelect.addEventListener('keydown', changeDataListSelect);
datalistSelect.addEventListener('keypress', datalistSelectKeyPress);
return datalistSelect;
}
|
javascript
|
{
"resource": ""
}
|
|
q47321
|
train
|
function(event) {
var datalistSelect = event.target,
datalist = datalistSelect.parentNode,
input = dcmnt.querySelector('input[list="' + datalist.id + '"]');
// Check for whether the events target was a select or whether the input doesn't exist
if (datalistSelect.tagName.toLowerCase() !== 'select' || input === null) {
return;
}
// Determine a relevant key - either printable characters (that would have a length of 1) or controlling like Backspace
if (event.key && (event.key === 'Backspace' || event.key.length === 1)) {
input.focus();
if (event.key === 'Backspace') {
input.value = input.value.substr(0, input.value.length - 1);
// Dispatch the input event on the related input[list]
dispatchInputEvent(input);
} else {
input.value += event.key;
}
prepOptions(datalist, input);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47322
|
train
|
function(event) {
var datalistSelect = event.currentTarget,
datalist = datalistSelect.parentNode,
input = dcmnt.querySelector('input[list="' + datalist.id + '"]');
// Check for whether the events target was a select or whether the input doesn't exist
if (datalistSelect.tagName.toLowerCase() !== 'select' || input === null) {
return;
}
var eventType = event.type,
// ENTER and ESC
visible =
eventType === 'keydown' &&
(event.keyCode !== keyENTER && event.keyCode !== keyESC);
// On change, click or after pressing ENTER or TAB key, input the selects value into the input on a change within the list
if (
(eventType === 'change' ||
eventType === 'click' ||
(eventType === 'keydown' &&
(event.keyCode === keyENTER || event.key === 'Tab'))) &&
datalistSelect.value.length > 0 &&
datalistSelect.value !== datalist.title
) {
setInputValue(input, datalistSelect.value);
// Dispatch the input event on the related input[list]
dispatchInputEvent(input);
// Finally focusing the input, as other browser do this as well
if (event.key !== 'Tab') {
input.focus();
}
// #GH-51 / Prevent the form to be submitted on selecting a value via ENTER key within the select
if (event.keyCode === keyENTER) {
event.preventDefault();
}
// Set the visibility to false afterwards, as we're done here
visible = false;
} else if (eventType === 'keydown' && event.keyCode === keyESC) {
// In case of the ESC key being pressed, we still want to focus the input[list]
input.focus();
}
// Toggle the visibility of the datalist select according to previous checks
toggleVisibility(visible, datalistSelect);
}
|
javascript
|
{
"resource": ""
}
|
|
q47323
|
train
|
function(input) {
var evt;
if (typeof Event === 'function') {
evt = new Event('input', {
bubbles: true
});
} else {
evt = dcmnt.createEvent('Event');
evt.initEvent('input', true, false);
}
input.dispatchEvent(evt);
}
|
javascript
|
{
"resource": ""
}
|
|
q47324
|
train
|
function(visible, datalistSelect) {
if (visible) {
datalistSelect.removeAttribute('hidden');
} else {
datalistSelect.setAttributeNode(dcmnt.createAttribute('hidden'));
}
datalistSelect.setAttribute('aria-hidden', (!visible).toString());
}
|
javascript
|
{
"resource": ""
}
|
|
q47325
|
makeRecencyFilter
|
train
|
function makeRecencyFilter(timeFn) {
var lastTime = 0;
return function(items) {
var out = [];
items.forEach(function(item) {
if (timeFn(item) > lastTime) {
out.push(item);
}
});
out.forEach(function(item) {
lastTime = Math.max(lastTime, timeFn(item));
});
return out;
};
}
|
javascript
|
{
"resource": ""
}
|
q47326
|
getBaseDir
|
train
|
function getBaseDir(configFilePath) {
// calculates the path of the project including Wist as dependency
const projectPath = path.resolve(__dirname, '../../../');
if (configFilePath && pathIsInside(configFilePath, projectPath)) {
// be careful of https://github.com/substack/node-resolve/issues/78
return path.join(path.resolve(configFilePath));
}
/*
* default to Wist project path since it's unlikely that plugins will be
* in this directory
*/
return path.join(projectPath);
}
|
javascript
|
{
"resource": ""
}
|
q47327
|
handleInitialize
|
train
|
function handleInitialize(currentOptions) {
const recommendedFilePath = path.resolve(__dirname, '../../config/wist-recommended.json');
let result = 0;
if (currentOptions.config) {
result = handleConfiguration(currentOptions.config);
} else {
result = handleConfiguration(recommendedFilePath);
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q47328
|
handleConfiguration
|
train
|
function handleConfiguration(filePath) {
if (fs.existsSync(filePath)) {
filePath = path.resolve(filePath);
}
else {
console.error('Invalid path to configuration file.');
return 1;
}
return setupConfigurationFile(filePath);
}
|
javascript
|
{
"resource": ""
}
|
q47329
|
setupConfigurationFile
|
train
|
function setupConfigurationFile(configFilePath) {
const fileName = '.wistrc.json';
try {
let contents = require(configFilePath);
fs.writeFileSync(fileName, JSON.stringify(contents, null, 2));
log.info(`Initialized directory with a ${fileName}`)
} catch (e) {
console.error(e.message);
return 1;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q47330
|
deepmerge
|
train
|
function deepmerge(target, src, combine, isRule) {
/*
The MIT License (MIT)
Copyright (c) 2012 Nicholas Fisher
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
* This code is taken from deepmerge repo
* (https://github.com/KyleAMathews/deepmerge)
* and modified to meet our needs.
*/
const array = Array.isArray(src) || Array.isArray(target);
let dst = array && [] || {};
combine = !!combine;
isRule = !!isRule;
if (array) {
target = target || [];
// src could be a string, so check for array
if (isRule && Array.isArray(src) && src.length > 1) {
dst = dst.concat(src);
}
else {
dst = dst.concat(target);
}
if (typeof src !== 'object' && !Array.isArray(src)) {
src = [src];
}
Object.keys(src).forEach((e, i) => {
e = src[i];
if (typeof dst[i] === 'undefined') {
dst[i] = e;
}
else if (typeof e === 'object') {
if (isRule) {
dst[i] = e;
}
else {
dst[i] = deepmerge(target[i], e, combine, isRule);
}
}
else {
if (!combine) {
dst[i] = e;
}
else {
if (dst.indexOf(e) === -1) {
dst.push(e);
}
}
}
});
}
else {
if (target && typeof target === 'object') {
Object.keys(target).forEach(key => {
dst[key] = target[key];
});
}
Object.keys(src).forEach(key => {
if (key === 'overrides') {
dst[key] = (target[key] || []).concat(src[key] || []);
}
else if (Array.isArray(src[key]) || Array.isArray(target[key])) {
dst[key] = deepmerge(target[key], src[key], key === 'plugins' || key === 'extends', isRule);
}
else if (typeof src[key] !== 'object' || !src[key] || key === 'exported' || key === 'astGlobals') {
dst[key] = src[key];
}
else {
dst[key] = deepmerge(target[key] || {}, src[key], combine, key === 'rules');
}
});
}
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q47331
|
createAsync
|
train
|
function createAsync() {
var
wired = new Async,
wire = render.bind(wired),
chunksReceiver
;
wired.update = function () {
this.callback = chunksReceiver;
return chunks.apply(this, arguments);
};
return function (callback) {
chunksReceiver = callback || String;
return wire;
};
}
|
javascript
|
{
"resource": ""
}
|
q47332
|
fixUpdates
|
train
|
function fixUpdates(updates) {
for (var
update,
i = 0,
length = updates.length,
out = [];
i < length; i++
) {
update = updates[i];
out.push(update === getUpdateForHTML ? update.call(this) : update);
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
q47333
|
invokeAtDistance
|
train
|
function invokeAtDistance(value, asTPV) {
var after = asTPV ? asTemplateValue : identity;
if ('text' in value) {
return Promise.resolve(value.text).then(String).then(after);
} else if ('any' in value) {
return Promise.resolve(value.any).then(after);
} else if ('html' in value) {
return Promise.resolve(value.html).then(asHTML).then(after);
} else {
return Promise.resolve(invokeTransformer(value)).then(after);
}
}
|
javascript
|
{
"resource": ""
}
|
q47334
|
invokeTransformer
|
train
|
function invokeTransformer(object) {
for (var key, i = 0, length = transformersKeys.length; i < length; i++) {
key = transformersKeys[i];
if (object.hasOwnProperty(key)) {
// noop is passed to respect hyperHTML API but it won't have
// any effect at distance for the time being
return transformers[key](object[key], noop);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47335
|
asTemplateValue
|
train
|
function asTemplateValue(value, isAttribute) {
var presuf = isAttribute ? '' : createHyperComment();
switch(typeof value) {
case 'string': return presuf + escape(value) + presuf;
case 'boolean':
case 'number': return presuf + value + presuf;
case 'function': return asTemplateValue(value({}), isAttribute);
case 'object':
if (value instanceof Buffer) return presuf + value + presuf;
if (value instanceof Component) return asTemplateValue(value.render(), isAttribute);
case 'undefined':
if (value == null) return presuf + '' + presuf;
default:
if (isArray(value)) {
for (var i = 0, length = value.length; i < length; i++) {
if (value[i] instanceof Component) {
value[i] = value[i].render();
}
}
return presuf + value.join('') + presuf;
}
if ('placeholder' in value) return invokeAtDistance(value, true);
if ('text' in value) return presuf + escape(value.text) + presuf;
if ('any' in value) return asTemplateValue(value.any, isAttribute);
if ('html' in value) return presuf + [].concat(value.html).join('') + presuf;
return asTemplateValue(invokeTransformer(value), isAttribute);
}
}
|
javascript
|
{
"resource": ""
}
|
q47336
|
updateBoolean
|
train
|
function updateBoolean(name) {
name = ' ' + name;
function update(value) {
switch (value) {
case true:
case 'true':
return name;
}
return '';
}
update[UID] = true;
return update;
}
|
javascript
|
{
"resource": ""
}
|
q47337
|
updateEvent
|
train
|
function updateEvent(value) {
switch (typeof value) {
case 'function': return 'return (' + escape(
JS_SHORTCUT.test(value) && !JS_FUNCTION.test(value) ?
('function ' + value) :
value
) + ').call(this, event)';
case 'object': return '';
default: return escape(value || '');
}
}
|
javascript
|
{
"resource": ""
}
|
q47338
|
chunks
|
train
|
function chunks() {
for (var
update,
out = [],
updates = this.updates,
template = this.chunks,
callback = this.callback,
all = Promise.resolve(template[0]),
chain = function (after) {
return all.then(function (through) {
notify(through);
return after;
});
},
getSubValue = function (value) {
if (isArray(value)) {
value.forEach(getSubValue);
} else {
all = chain(
Promise.resolve(value)
.then(resolveArray)
);
}
},
getValue = function (value) {
if (isArray(value)) {
var hc = Promise.resolve(createHyperComment());
all = chain(hc);
value.forEach(getSubValue);
all = chain(hc);
} else {
all = chain(
Promise.resolve(value)
.then(resolveAsTemplateValue(update))
.then(update === asTemplateValue ? identity : update)
);
}
},
notify = function (chunk) {
out.push(chunk);
callback(chunk);
},
i = 1,
length = arguments.length; i < length; i++
) {
update = updates[i - 1];
getValue(arguments[i]);
all = chain(template[i]);
}
return all.then(notify).then(function () { return out; });
}
|
javascript
|
{
"resource": ""
}
|
q47339
|
resolveAsTemplateValue
|
train
|
function resolveAsTemplateValue(update) {
return function (value) {
return asTemplateValue(
value,
update === updateAttribute ||
update === updateEvent ||
UID in update
);
};
}
|
javascript
|
{
"resource": ""
}
|
q47340
|
update
|
train
|
function update() {
for (var
tmp,
promise = false,
updates = this.updates,
template = this.chunks,
out = [template[0]],
i = 1,
length = arguments.length;
i < length; i++
) {
tmp = arguments[i];
if (
(typeof tmp === 'object' && tmp !== null)
&&
(typeof tmp.then === 'function' || 'placeholder' in tmp)
) {
promise = true;
out.push(
('placeholder' in tmp ? invokeAtDistance(tmp, false) : tmp)
.then(updates[i - 1]),
template[i]
);
} else {
out.push(updates[i - 1](tmp), template[i]);
}
}
return promise ? Promise.all(out).then(asBuffer) : asBuffer(out);
}
|
javascript
|
{
"resource": ""
}
|
q47341
|
checkAttributes
|
train
|
function checkAttributes (priority, element, ignore, path, parent = element.parentNode) {
const pattern = findAttributesPattern(priority, element, ignore)
if (pattern) {
const matches = parent.querySelectorAll(pattern)
if (matches.length === 1) {
path.unshift(pattern)
return true
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q47342
|
findAttributesPattern
|
train
|
function findAttributesPattern (priority, element, ignore) {
const attributes = element.attributes
const sortedKeys = Object.keys(attributes).sort((curr, next) => {
const currPos = priority.indexOf(attributes[curr].name)
const nextPos = priority.indexOf(attributes[next].name)
if (nextPos === -1) {
if (currPos === -1) {
return 0
}
return -1
}
return currPos - nextPos
})
for (var i = 0, l = sortedKeys.length; i < l; i++) {
const key = sortedKeys[i]
const attribute = attributes[key]
const attributeName = attribute.name
const attributeValue = escapeValue(attribute.value)
const currentIgnore = ignore[attributeName] || ignore.attribute
const currentDefaultIgnore = defaultIgnore[attributeName] || defaultIgnore.attribute
if (checkIgnore(currentIgnore, attributeName, attributeValue, currentDefaultIgnore)) {
continue
}
var pattern = `[${attributeName}="${attributeValue}"]`
if ((/\b\d/).test(attributeValue) === false) {
if (attributeName === 'id') {
pattern = `#${attributeValue}`
}
if (attributeName === 'class') {
const className = attributeValue.trim().replace(/\s+/g, '.')
pattern = `.${className}`
}
}
return pattern
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q47343
|
checkTag
|
train
|
function checkTag (element, ignore, path, parent = element.parentNode) {
const pattern = findTagPattern(element, ignore)
if (pattern) {
const matches = parent.getElementsByTagName(pattern)
if (matches.length === 1) {
path.unshift(pattern)
return true
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q47344
|
findTagPattern
|
train
|
function findTagPattern (element, ignore) {
const tagName = element.tagName.toLowerCase()
if (checkIgnore(ignore.tag, null, tagName)) {
return null
}
return tagName
}
|
javascript
|
{
"resource": ""
}
|
q47345
|
checkChilds
|
train
|
function checkChilds (priority, element, ignore, path) {
const parent = element.parentNode
const children = parent.childTags || parent.children
for (var i = 0, l = children.length; i < l; i++) {
const child = children[i]
if (child === element) {
const childPattern = findPattern(priority, child, ignore)
if (!childPattern) {
return console.warn(`
Element couldn\'t be matched through strict ignore pattern!
`, child, ignore, childPattern)
}
const pattern = `> ${childPattern}:nth-child(${i+1})`
path.unshift(pattern)
return true
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q47346
|
checkIgnore
|
train
|
function checkIgnore (predicate, name, value, defaultPredicate) {
if (!value) {
return true
}
const check = predicate || defaultPredicate
if (!check) {
return false
}
return check(name, value, defaultPredicate)
}
|
javascript
|
{
"resource": ""
}
|
q47347
|
getCommonSelectors
|
train
|
function getCommonSelectors (elements) {
const { classes, attributes, tag } = getCommonProperties(elements)
const selectorPath = []
if (tag) {
selectorPath.push(tag)
}
if (classes) {
const classSelector = classes.map((name) => `.${name}`).join('')
selectorPath.push(classSelector)
}
if (attributes) {
const attributeSelector = Object.keys(attributes).reduce((parts, name) => {
parts.push(`[${name}="${attributes[name]}"]`)
return parts
}, []).join('')
selectorPath.push(attributeSelector)
}
if (selectorPath.length) {
// TODO: check for parent-child relation
}
return [
selectorPath.join('')
]
}
|
javascript
|
{
"resource": ""
}
|
q47348
|
traverseDescendants
|
train
|
function traverseDescendants (nodes, handler) {
nodes.forEach((node) => {
var progress = true
handler(node, () => progress = false)
if (node.childTags && progress) {
traverseDescendants(node.childTags, handler)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q47349
|
getAncestor
|
train
|
function getAncestor (node, root, validate) {
while (node.parent) {
node = node.parent
if (validate(node)) {
return node
}
if (node === root) {
break
}
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q47350
|
compareResults
|
train
|
function compareResults (matches, elements) {
const { length } = matches
return length === elements.length && elements.every((element) => {
for (var i = 0; i < length; i++) {
if (matches[i] === element) {
return true
}
}
return false
})
}
|
javascript
|
{
"resource": ""
}
|
q47351
|
$isInInvisibleState
|
train
|
function $isInInvisibleState(c) {
if (c.isVisible === false ||
c.$container.parentNode === null ||
c.width <= 0 ||
c.height <= 0 ||
c.parent === null ||
zebkit.web.$contains(c.$container) === false)
{
return true;
}
var p = c.parent;
while (p !== null && p.isVisible === true && p.width > 0 && p.height > 0) {
p = p.parent;
}
return p !== null || ui.$cvp(c) === null;
}
|
javascript
|
{
"resource": ""
}
|
q47352
|
$resolveDOMParent
|
train
|
function $resolveDOMParent(c) {
// try to find an HTML element in zebkit (pay attention, in zebkit hierarchy !)
// hierarchy that has to be a DOM parent for the given component
var parentElement = null;
for(var p = c.parent; p !== null; p = p.parent) {
if (p.isDOMElement === true) {
parentElement = p.$container;
break;
}
}
// parentElement is null means the component has
// not been inserted into DOM hierarchy
if (parentElement !== null && c.$container.parentNode === null) {
// parent DOM element of the component is null, but a DOM container
// for the element has been detected. We need to add it to DOM
// than we have to add the DOM to the found DOM parent element
parentElement.appendChild(c.$container);
// adjust location of just attached DOM component
$adjustLocation(c);
} else {
// test consistency whether the DOM element already has
// parent node that doesn't match the discovered
if (parentElement !== null &&
c.$container.parentNode !== null &&
c.$container.parentNode !== parentElement)
{
throw new Error("DOM parent inconsistent state ");
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47353
|
setParent
|
train
|
function setParent(p) {
this.$super(p);
if (p !== null && p.noSubIfEmpty === true) {
this.getSub().setVisible(false);
}
}
|
javascript
|
{
"resource": ""
}
|
q47354
|
keyPressed
|
train
|
function keyPressed(e){
if (e.code === "Escape") {
if (this.parent !== null) {
var p = this.$parentMenu;
this.$canceled(this);
this.$hideMenu();
if (p !== null) {
p.requestFocus();
}
}
} else {
this.$super(e);
}
}
|
javascript
|
{
"resource": ""
}
|
q47355
|
addDecorative
|
train
|
function addDecorative(c) {
if (c.$isDecorative !== true) {
c.$$isDecorative = true;
}
this.$getSuper("insert").call(this, this.kids.length, null, c);
}
|
javascript
|
{
"resource": ""
}
|
q47356
|
setValue
|
train
|
function setValue(s) {
var txt = this.getValue();
if (txt !== s){
if (this.position !== null) {
this.position.setOffset(0);
}
this.scrollManager.scrollTo(0, 0);
this.$super(s);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q47357
|
train
|
function(e, pr) {
if (arguments.length === 0) {
if (this.$error !== null) {
this.dumpError(e);
}
} else {
if (this.$error === null) {
if (this.$ignoreError) {
this.$ignored(e);
} else {
this.$taskCounter = this.$level = this.$busy = 0;
this.$error = e;
this.$results = [];
}
this.$schedule();
} else if (arguments.length < 2 || pr === true) {
this.dumpError(e);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q47358
|
train
|
function(body) {
var level = this.$level; // store level then was executed for the given task
// to be used to compute correct the level inside the
// method below
var task = function() {
// clean results of execution of a previous task
this.$busy = 0;
var pc = this.$taskCounter;
if (this.$error !== null) {
this.$taskCounter = 0; // we have to count the tasks on this level
this.$level = level + 1;
try {
if (typeof body === 'function') {
body.call(this, this.$error);
} else if (body === null) {
} else {
this.dumpError(this.$error);
}
} catch(e) {
this.$level = level; // restore level
this.$taskCounter = pc; // restore counter
throw e;
}
}
if (level === 0) {
try {
this.$schedule();
} catch(e) {
this.error(e);
}
} else {
this.$schedule();
}
this.$level = level; // restore level
this.$taskCounter = pc; // restore counter
};
if (this.$level > 0) {
this.$tasks.splice(this.$taskCounter++, 0, task);
} else {
this.$tasks.push(task);
}
if (this.$level === 0) {
this.$schedule();
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q47359
|
train
|
function() {
// clean results of execution of a previous task
this.$busy = 0;
var pc = this.$taskCounter;
if (this.$error !== null) {
this.$taskCounter = 0; // we have to count the tasks on this level
this.$level = level + 1;
try {
if (typeof body === 'function') {
body.call(this, this.$error);
} else if (body === null) {
} else {
this.dumpError(this.$error);
}
} catch(e) {
this.$level = level; // restore level
this.$taskCounter = pc; // restore counter
throw e;
}
}
if (level === 0) {
try {
this.$schedule();
} catch(e) {
this.error(e);
}
} else {
this.$schedule();
}
this.$level = level; // restore level
this.$taskCounter = pc; // restore counter
}
|
javascript
|
{
"resource": ""
}
|
|
q47360
|
getView
|
train
|
function getView(t, v) {
if (v !== null && v !== undefined && this.numPrecision !== -1 && zebkit.isNumber(v)) {
v = v.toFixed(this.numPrecision);
}
return this.$super(t, v);
}
|
javascript
|
{
"resource": ""
}
|
q47361
|
setViewProvider
|
train
|
function setViewProvider(p){
if (this.provider != p) {
this.stopEditing(false);
this.provider = p;
delete this.nodes;
this.nodes = {};
this.vrp();
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q47362
|
dumpError
|
train
|
function dumpError(e) {
if (typeof console !== "undefined" && typeof console.log !== "undefined") {
var msg = "zebkit.err [";
if (typeof Date !== 'undefined') {
var date = new Date();
msg = msg + date.getDate() + "/" +
(date.getMonth() + 1) + "/" +
date.getFullYear() + " " +
date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}
if (e === null || e === undefined) {
console.log("Unknown error");
} else {
console.log(msg + " : " + e);
console.log((e.stack ? e.stack : e));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47363
|
image
|
train
|
function image(ph, fireErr) {
if (arguments.length < 2) {
fireErr = false;
}
var doit = new DoIt(),
jn = doit.join(),
marker = "data:image";
if (isString(ph) && ph.length > marker.length) {
// use "for" instead of "indexOf === 0"
var i = 0;
for(; i < marker.length && marker[i] === ph[i]; i++) {}
if (i < marker.length) {
var file = ZFS.read(ph);
if (file !== null) {
ph = "data:image/" + file.ext + ";base64," + file.data;
}
}
}
$zenv.loadImage(ph,
function(img) {
jn(img);
},
function(img, e) {
if (fireErr === true) {
doit.error(e);
} else {
jn(img);
}
}
);
return doit;
}
|
javascript
|
{
"resource": ""
}
|
q47364
|
isNumber
|
train
|
function isNumber(o) {
return o !== undefined && o !== null &&
(typeof o === "number" || o.constructor === Number);
}
|
javascript
|
{
"resource": ""
}
|
q47365
|
isBoolean
|
train
|
function isBoolean(o) {
return o !== undefined && o !== null &&
(typeof o === "boolean" || o.constructor === Boolean);
}
|
javascript
|
{
"resource": ""
}
|
q47366
|
getPropertyValue
|
train
|
function getPropertyValue(obj, path, useGetter) {
// if (arguments.length < 3) {
// useGetter = false;
// }
path = path.trim();
if (path === undefined || path.length === 0) {
throw new Error("Invalid field path: '" + path + "'");
}
// if (obj === undefined || obj === null) {
// throw new Error("Undefined target object");
// }
var paths = null,
m = null,
p = null;
if (path.indexOf('.') > 0) {
paths = path.split('.');
for(var i = 0; i < paths.length; i++) {
p = paths[i];
if (obj !== undefined && obj !== null &&
((useGetter === true && (m = getPropertyGetter(obj, p))) || obj.hasOwnProperty(p)))
{
if (useGetter === true && m !== null) {
obj = m.call(obj);
} else {
obj = obj[p];
}
} else {
return undefined;
}
}
} else if (path === '*') {
var res = {};
for (var k in obj) {
if (k[0] !== '$' && obj.hasOwnProperty(k)) {
res[k] = getPropertyValue(obj, k, useGetter === true);
}
}
return res;
} else {
if (useGetter === true) {
m = getPropertyGetter(obj, path);
if (m !== null) {
return m.call(obj);
}
}
if (obj.hasOwnProperty(path) === true) {
obj = obj[path];
} else {
return undefined;
}
}
// detect object value factory
if (obj !== null && obj !== undefined && obj.$new !== undefined) {
return obj.$new();
} else {
return obj;
}
}
|
javascript
|
{
"resource": ""
}
|
q47367
|
train
|
function() {
return (this.scheme !== null ? this.scheme + "://" : '') +
(this.host !== null ? this.host : '' ) +
(this.port !== -1 ? ":" + this.port : '' ) +
(this.path !== null ? this.path : '' ) +
(this.qs !== null ? "?" + this.qs : '' );
}
|
javascript
|
{
"resource": ""
}
|
|
q47368
|
train
|
function() {
if (this.path === null) {
return null;
} else {
var i = this.path.lastIndexOf('/');
return (i < 0 || this.path === '/') ? null
: new URI(this.scheme,
this.host,
this.port,
this.path.substring(0, i),
this.qs);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47369
|
train
|
function(obj) {
if (obj !== null) {
if (this.qs === null) {
this.qs = '';
}
if (this.qs.length > 0) {
this.qs = this.qs + "&" + URI.toQS(obj);
} else {
this.qs = URI.toQS(obj);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47370
|
train
|
function() {
var args = Array.prototype.slice.call(arguments);
args.splice(0, 0, this.toString());
return URI.join.apply(URI, args);
}
|
javascript
|
{
"resource": ""
}
|
|
q47371
|
train
|
function(to) {
if ((to instanceof URI) === false) {
to = new URI(to);
}
if (this.isAbsolute() &&
to.isAbsolute() &&
this.host === to.host &&
this.port === to.port &&
(this.scheme === to.scheme || (this.isFilePath() && to.isFilePath()) ) &&
(this.path.indexOf(to.path) === 0 && (to.path.length === this.path.length ||
(to.path.length === 1 && to.path[0] === '/') ||
this.path[to.path.length] === '/' )))
{
return (to.path.length === 1 && to.path[0] === '/') ? this.path.substring(to.path.length)
: this.path.substring(to.path.length + 1);
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47372
|
$initializeCodesMap
|
train
|
function $initializeCodesMap() {
var k = null,
code = null;
// validate codes mapping
for(k in CODES) {
code = CODES[k];
if (code.map !== undefined) {
if (CODES[code.map] === undefined) {
throw new Error("Invalid mapping for code = '" + k + "'");
}
} else if (code.keyCode === undefined) {
throw new Error("unknown keyCode for code = '" + k + "'");
}
}
// build codes map table for the cases when "code" property
CODES_MAP = {};
for(k in CODES) {
code = CODES[k];
if (code.map !== undefined) {
if (code.keyCode !== undefined) {
CODES_MAP[code.keyCode] = code.map;
}
} else {
CODES_MAP[code.keyCode] = k;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47373
|
setFormat
|
train
|
function setFormat(format) {
if (format === null || format === undefined) {
throw new Error("Format is not defined " + this.clazz.$name);
}
if (this.format !== format) {
this.format = format;
this.$getSuper("setValue").call(this, this.$format(this.date));
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q47374
|
getCalendar
|
train
|
function getCalendar() {
if (this.clazz.$name === undefined) {
throw new Error();
}
if (this.calendar === undefined || this.calendar === null) {
var $this = this;
this.$freezeCalendar = false;
this.calendar = new pkg.Calendar([
function $clazz() {
this.MonthsCombo.$name = "INNER";
},
function winActivated(e) {
if (e.isActive === false) {
$this.hideCalendar();
}
},
function childKeyPressed(e){
if (e.code === "Escape") {
$this.hideCalendar();
}
},
function dateSelected(date, b) {
this.$super(date, b);
if (date !== null && b) {
if ($this.$freezeCalendar === false) {
if ($this.dateSelected !== undefined) {
$this.dateSelected.call($this, date, b);
}
$this.hideCalendar();
}
}
}
]);
}
return this.calendar;
}
|
javascript
|
{
"resource": ""
}
|
q47375
|
showCalendar
|
train
|
function showCalendar(anchor) {
try {
this.$freezeCalendar = true;
this.hideCalendar();
var calendar = this.getCalendar();
this.$anchor = anchor;
var c = this.getCanvas(),
w = c.getLayer("win"),
p = zebkit.layout.toParentOrigin(0, 0, anchor, c);
calendar.toPreferredSize();
p.y = p.y + anchor.height;
if (p.y + calendar.height > w.height - w.getBottom()) {
p.y = p.y - calendar.height - anchor.height - 1;
}
if (p.x + calendar.width > w.width - w.getRight()) {
p.x -= (p.x + calendar.width - w.width + w.getRight());
}
calendar.setLocation(p.x, p.y);
ui.showWindow(this, "mdi", calendar);
ui.activateWindow(calendar);
calendar.monthDays.requestFocus();
if (this.calendarShown !== undefined) {
this.calendarShown(this.calendar);
}
} finally {
this.$freezeCalendar = false;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q47376
|
hideCalendar
|
train
|
function hideCalendar() {
if (this.calendar !== undefined && this.calendar !== null) {
var calendar = this.getCalendar();
if (calendar.parent !== null) {
calendar.removeMe();
if (this.calendarHidden !== undefined) {
this.calendarHidden();
}
this.$anchor.requestFocus();
this.$anchor = null;
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q47377
|
setValue
|
train
|
function setValue(d1, d2) {
if (compareDates(d1, d2) === 1) {
throw new RangeError();
}
if (compareDates(d1, this.minDateField.date) !== 0 ||
compareDates(d2, this.maxDateField.date) !== 0 )
{
var prev = this.getValue();
this.minDateField.setValue(d1);
this.maxDateField.setValue(d2);
this.getCalendar().monthDays.retagModel();
this.fire("dateRangeSelected", [this, prev]);
if (this.dateRangeSelected !== undefined) {
this.dateRangeSelected(prev);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47378
|
$cpMethods
|
train
|
function $cpMethods(src, dest, clazz) {
var overriddenAbstractMethods = 0;
for(var name in src) {
if (name !== CNAME &&
name !== "clazz" &&
src.hasOwnProperty(name) )
{
var method = src[name];
if (typeof method === "function" && method !== $toString) {
if (name === "$prototype") {
method.call(dest, clazz);
} else {
// TODO analyze if we overwrite existent field
if (dest[name] !== undefined) {
// abstract method is overridden, let's skip abstract method
// stub implementation
if (method.$isAbstract === true) {
overriddenAbstractMethods++;
continue;
}
if (dest[name].boundTo === clazz) {
throw new Error("Method '" + name + "(...)'' bound to this class already exists");
}
}
if (method.methodBody !== undefined) {
dest[name] = $ProxyMethod(name, method.methodBody, clazz);
} else {
dest[name] = $ProxyMethod(name, method, clazz);
}
// save information about abstract method
if (method.$isAbstract === true) {
dest[name].$isAbstract = true;
}
}
}
}
}
return overriddenAbstractMethods;
}
|
javascript
|
{
"resource": ""
}
|
q47379
|
newInstance
|
train
|
function newInstance(clazz, args) {
if (arguments.length > 1 && args.length > 0) {
var f = function () {};
f.prototype = clazz.prototype;
var o = new f();
clazz.apply(o, args);
return o;
}
return new clazz();
}
|
javascript
|
{
"resource": ""
}
|
q47380
|
train
|
function() {
var methods = arguments[arguments.length - 1],
hasMethod = Array.isArray(methods);
// inject class
if (hasMethod && this.$isExtended !== true) {
// create intermediate class
var A = this.$parent !== null ? Class(this.$parent, [])
: Class([]);
// copy this class prototypes methods to intermediate class A and re-define
// boundTo to the intermediate class A if they were bound to source class
// methods that have been moved from source class to class have to be re-bound
// to A class
for(var name in this.prototype) {
if (name !== "clazz" && this.prototype.hasOwnProperty(name) ) {
var f = this.prototype[name];
if (typeof f === 'function') {
A.prototype[name] = f.methodBody !== undefined ? $ProxyMethod(name, f.methodBody, f.boundTo)
: f;
if (A.prototype[name].boundTo === this) {
A.prototype[name].boundTo = A;
if (f.boundTo === this) {
f.boundTo = A;
}
}
}
}
}
this.$parent = A;
this.$isExtended = true;
}
if (hasMethod) {
$mixing(this, methods);
}
// add passed interfaces
for(var i = 0; i < arguments.length - (hasMethod ? 1 : 0); i++) {
var I = arguments[i];
if (I === null || I === undefined || I.clazz !== Interface) {
throw new Error("Interface is expected");
}
if (this.$parents[I.$hash$] !== undefined) {
throw new Error("Interface has been already inherited");
}
$cpMethods(I.prototype, this.prototype, this);
this.$parents[I.$hash$] = I;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q47381
|
train
|
function(clazz) {
if (this !== clazz) {
// detect class
if (clazz.clazz === this.clazz) {
for (var p = this.$parent; p !== null; p = p.$parent) {
if (p === clazz) {
return true;
}
}
} else { // detect interface
if (this.$parents[clazz.$hash$] === clazz) {
return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q47382
|
train
|
function(name) {
if ($caller !== null) {
for(var $s = $caller.boundTo.$parent; $s !== null; $s = $s.$parent) {
var m = $s.prototype[name];
if (typeof m === 'function') {
return m;
}
}
return null;
}
throw new Error("$super is called outside of class context");
}
|
javascript
|
{
"resource": ""
}
|
|
q47383
|
instanceOf
|
train
|
function instanceOf(obj, clazz) {
if (clazz !== null && clazz !== undefined) {
if (obj === null || obj === undefined) {
return false;
} else if (obj.clazz === undefined) {
return (obj instanceof clazz);
} else {
return obj.clazz !== null &&
(obj.clazz === clazz ||
obj.clazz.$parents[clazz.$hash$] !== undefined);
}
}
throw new Error("instanceOf(): null class");
}
|
javascript
|
{
"resource": ""
}
|
q47384
|
validateArguments
|
train
|
function validateArguments (targets, callback) {
const nodes = Object.prototype.toString.call(targets)
const targetsValid = typeof targets === 'string' || ((nodes === '[object NodeList]' || nodes === '[object HTMLCollection]') || targets.nodeType === 1)
const callbackValid = typeof callback === 'function'
if (!targetsValid) console.error('Countable: Not a valid target')
if (!callbackValid) console.error('Countable: Not a valid callback function')
return targetsValid && callbackValid
}
|
javascript
|
{
"resource": ""
}
|
q47385
|
train
|
function (elements, callback, options) {
if (!validateArguments(elements, callback)) return
if (!Array.isArray(elements)) {
elements = [ elements ]
}
each.call(elements, function (e) {
const handler = function () {
callback.call(e, count(e, options))
}
liveElements.push({ element: e, handler: handler })
handler()
e.addEventListener('input', handler)
})
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q47386
|
train
|
function (elements) {
if (!validateArguments(elements, function () {})) return
if (!Array.isArray(elements)) {
elements = [ elements ]
}
liveElements.filter(function (e) {
return elements.indexOf(e.element) !== -1
}).forEach(function (e) {
e.element.removeEventListener('input', e.handler)
})
liveElements = liveElements.filter(function (e) {
return elements.indexOf(e.element) === -1
})
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q47387
|
train
|
function (targets, callback, options) {
if (!validateArguments(targets, callback)) return
if (!Array.isArray(targets)) {
targets = [ targets ]
}
each.call(targets, function (e) {
callback.call(e, count(e, options))
})
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q47388
|
train
|
function (elements) {
if (elements.length === undefined) {
elements = [ elements ]
}
return liveElements.filter(function (e) {
return elements.indexOf(e.element) !== -1
}).length === elements.length
}
|
javascript
|
{
"resource": ""
}
|
|
q47389
|
Run
|
train
|
function Run(path, options, callback) {
var p = Spawn(path, options.args),
err = "",
data = "";
if (options.remove !== false) {
Fs.unlink(path, () => {});
}
if (options.stdin) {
options.stdin.pipe(p.stdin);
}
if (options.stdout) {
p.stdout.pipe(options.stdout);
} else {
p.stdout.on("data", function (chunk) {
data += chunk.toString();
});
}
if (options.stderr) {
p.stderr.pipe(options.stderr);
} else {
p.stderr.on("data", function (err) {
err += err.toString();
});
}
p.on("close", function () {
callback([null, err][Number(!!err)], data.slice(0, -1));
});
}
|
javascript
|
{
"resource": ""
}
|
q47390
|
Move
|
train
|
function Move(old, cwd, callback) {
var n = Path.join(cwd, Path.basename(old));
Fs.rename(old, n, function (err) {
callback(null, [old, n][Number(!err)]);
});
}
|
javascript
|
{
"resource": ""
}
|
q47391
|
Compile
|
train
|
function Compile(input, options, callback) {
var output = Path.join(options.cwd, Path.basename(input).slice(0, -4));
if (options.precompiled) {
callback(null, output);
} else {
CheckCobc(function (exists) {
if (!exists) {
return callback(new Error("Couldn't find the cobc executable in the PATH. Make sure you installed Open Cobol."));
}
var args = {
x: true,
_: input
};
Object.assign(args, options.compileargs);
Exec(OArgv(args, "cobc"), {
cwd: options.cwd
}, function (err, stdout, stderr) {
if (stderr || err) {
return callback(stderr || err);
}
callback(null, output);
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q47392
|
Cobol
|
train
|
function Cobol(input, options, callback) {
var args = Sliced(arguments);
if (typeof options === "function") {
callback = options;
options = {};
}
callback = callback || function () {};
// Merge the defaults
options = Ul.merge(options, {
cwd: process.cwd(),
compileargs: {},
args: []
});
if (_typeof(args[1]) === "object") {}
// options = Ul.merge(options, {
// stdout: process.stdout
// , stderr: process.stderr
// , stdin: process.stdin
// });
// File
if (typeof input === "string" && input.split("\n").length === 1) {
return OneByOne([Compile.bind(this, input, options), function (next, path) {
Run(path, options, next);
}], function (err, data) {
callback(err, data && data.slice(-1)[0]);
});
}
// Comment
// TODO We should improve this.
if (typeof input === "function") {
input = input.toString();
input = input.slice(input.indexOf("/*") + 2, input.indexOf("*/"));
}
// Code
if (typeof input === "string") {
return OneByOne([Tmp.file.bind(Tmp), function (next, path) {
Fs.writeFile(path, input, function (err) {
next(err, path);
});
}, function (next, path) {
if (_typeof(args[1]) !== "object") {
return Cobol(path, next);
}
Cobol(path, options, next);
}], function (err, data) {
//if (options.autoclose !== false) {
// process.nextTick(function () {
// process.exit();
// });
//}
callback(err, data && data.slice(-1)[0]);
});
}
callback(new Error("Incorrect usage."));
}
|
javascript
|
{
"resource": ""
}
|
q47393
|
loadJSON
|
train
|
function loadJSON (path, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType('application/json');
xobj.open('GET', path, true);
xobj.onreadystatechange = function () {
if (xobj.readyState === 4 && xobj.status === 200) {
callback(xobj.responseText);
}
};
xobj.send(null);
}
|
javascript
|
{
"resource": ""
}
|
q47394
|
destroyMap
|
train
|
function destroyMap (map) {
var el = map.getContainer();
map.remove();
document.body.removeChild(el);
}
|
javascript
|
{
"resource": ""
}
|
q47395
|
startDrag
|
train
|
function startDrag(e) {
// Preventing the event's default action stops text being
// selectable during the drag.
e.preventDefault();
var self = $(this);
self.trigger('startDrag');
// Measure how far the user's mouse is from the top of the scrollbar drag handle.
var eventOffset = e.pageY;
if (scrollDirection === 'horiz') {
eventOffset = e.pageX;
}
dragOffset = eventOffset - $dragHandleEl.offset()[offsetAttr];
$(document).on('mousemove', drag);
$(document).on('mouseup', function() {
endDrag.call(self);
});
}
|
javascript
|
{
"resource": ""
}
|
q47396
|
drag
|
train
|
function drag(e) {
e.preventDefault();
// Calculate how far the user's mouse is from the top/left of the scrollbar (minus the dragOffset).
var eventOffset = e.pageY;
if (scrollDirection === 'horiz') {
eventOffset = e.pageX;
}
var dragPos = eventOffset - $scrollbarEl.offset()[offsetAttr] - dragOffset;
// Convert the mouse position into a percentage of the scrollbar height/width.
var dragPerc = dragPos / $scrollbarEl[sizeAttr]();
// Scroll the content by the same percentage.
var scrollPos = dragPerc * $contentEl[sizeAttr]();
$scrollContentEl[scrollOffsetAttr](scrollPos);
}
|
javascript
|
{
"resource": ""
}
|
q47397
|
resizeScrollContent
|
train
|
function resizeScrollContent() {
if (scrollDirection === 'vert'){
$scrollContentEl.width($el.width()+scrollbarWidth());
$scrollContentEl.height($el.height());
} else {
$scrollContentEl.width($el.width());
$scrollContentEl.height($el.height()+scrollbarWidth());
$contentEl.height($el.height());
}
}
|
javascript
|
{
"resource": ""
}
|
q47398
|
scrollbarWidth
|
train
|
function scrollbarWidth() {
// Append a temporary scrolling element to the DOM, then measure
// the difference between between its outer and inner elements.
var tempEl = $('<div class="scrollbar-width-tester" style="width:50px;height:50px;overflow-y:scroll;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
$('body').append(tempEl);
var width = $(tempEl).innerWidth();
var widthMinusScrollbars = $('div', tempEl).innerWidth();
tempEl.remove();
// On OS X if the scrollbar is set to auto hide it will have zero width. On webkit we can still
// hide it using ::-webkit-scrollbar { width:0; height:0; } but there is no moz equivalent. So we're
// forced to sniff Firefox and return a hard-coded scrollbar width. I know, I know...
if (width === widthMinusScrollbars && navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
return 17;
}
return (width - widthMinusScrollbars);
}
|
javascript
|
{
"resource": ""
}
|
q47399
|
train
|
function(imageElement) {
_readyCb = function() {
try {
var w = imageElement.width;
var h = imageElement.height;
var newImg = document.createElement('img');
var ratio = (w / _w < h / _h) ? (w / _w) : (h / _h);
newImg.setAttribute('src', imageElement.getAttribute('src'));
newImg.height = (h / ratio);
newImg.width = (w / ratio);
_context.clearRect(0, 0, _w, _h);
_context.drawImage(newImg, 0, 0, _w, _h);
link.setIcon(_canvas);
} catch(e) {
throw 'Error setting image. Message: ' + e.message;
}
};
if (_ready) {
_readyCb();
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.