_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1900
|
QueryLogic
|
train
|
function QueryLogic(Type, options){
Type = Type || {};
var passedHydrator = options && options.toQuery;
var passedSerializer = options && options.toParams;
var schema;
if(Type[schemaSymbol]) {
schema = Type[schemaSymbol]();
} else {
schema = Type;
}
// check that the basics are here
var id = schema.identity && schema.identity[0];
if(!id) {
//console.warn("can-query given a type without an identity schema. Using `id` as the identity id.");
schema.identity = ["id"];
}
var converter = makeBasicQueryConvert(schema),
hydrate,
serialize;
if(passedHydrator) {
hydrate = function(query){
|
javascript
|
{
"resource": ""
}
|
q1901
|
generateApplicationCode
|
train
|
function generateApplicationCode(swagger, codegenOptions) {
debug('Generating application code.');
// Build up the execution parameters for the templates.
const templateFunc = codegenOptions.templateSet;
const outputDirectory = codegenOptions.temporaryDirectory;
const codegenSettings = defaults(
templateFunc(codegenOptions.templateSettings),
{
output: (name, content) => {
const fullName = path.join(outputDirectory, name);
|
javascript
|
{
"resource": ""
}
|
q1902
|
startSkeletonApplication
|
train
|
function startSkeletonApplication(options) {
debug('Starting to create application skeleton');
const configWithDefaults = defaults(
options, {
redirects: {
'documentation-from-root': {
match: /^\/$/,
target: '/docs',
},
},
ioc: {
},
customMiddleware: {
beforeSwagger: [],
afterSwagger: [],
beforeController: [],
},
codegen: {
controllerStubFolder: 'controllers',
temporaryDirectory: './.temp',
templateSet: templates,
},
service: {
listenPort: 10010,
},
cors: {
},
});
// If the swagger input is a string, then load it as a filename
const swaggerFile = configWithDefaults.service.swagger;
const swagger = typeof swaggerFile === 'string' ?
yamljs.load(swaggerFile) : swaggerFile;
// Create service instances
const app = connect();
const ioc = connectIoc(configWithDefaults.ioc);
// Generate custom application code
generateApplicationCode(
swagger,
configWithDefaults.codegen);
initializeSwagger(swagger, (middleware) => {
// Pre-request handling middleware
app.use(query()); // Query-string parsing
app.use(fiddleware.respondJson()); // res.json(data, status) support.
app.use(ioc.middleware); // Somersault IoC for controllers.
app.use(cors(configWithDefaults.cors));
|
javascript
|
{
"resource": ""
}
|
q1903
|
getRoutes
|
train
|
function getRoutes(req, res) {
var index = {
name: about.name,
version: about.version,
description: about.description,
|
javascript
|
{
"resource": ""
}
|
q1904
|
train
|
function(Type){
return Type && canReflect.isConstructorLike(Type) &&
!set.hasComparisons(Type) &&
!Type[canSymbol.for("can.SetType")] &&
|
javascript
|
{
"resource": ""
}
|
|
q1905
|
isCollection
|
train
|
function isCollection(object) {
if (!object || typeof object !== 'object') {
return false;
}
else if ('isCollection' in object) {
diag.debug.assert(function () { return object.isCollection === Collection.prototype.isPrototypeOf(object);
|
javascript
|
{
"resource": ""
}
|
q1906
|
jsonCompare
|
train
|
function jsonCompare(arg, options) {
var sortOrder;
if (typeof arg === 'string') {
sortOrder = new SortOrder_1.SortOrder();
sortOrder.fromJSON([arg]);
}
else if (_.isArray(arg)) {
sortOrder = new SortOrder_1.SortOrder();
sortOrder.fromJSON(arg);
}
else {
|
javascript
|
{
"resource": ""
}
|
q1907
|
SortOrderComparator
|
train
|
function SortOrderComparator(sortOrder, options) {
this.sortOrder = sortOrder;
this.options = {
casesensitive: false
};
if (options) {
_.extend(this.options, options);
}
this.expressions = new Array(sortOrder.sortFields.length);
for
|
javascript
|
{
"resource": ""
}
|
q1908
|
apiAuthorizer
|
train
|
function apiAuthorizer (args, ctx, acl) {
const { token = {}, groups } = ctx;
const { groups: tokenGroups = [] } = token;
if (typeof acl ===
|
javascript
|
{
"resource": ""
}
|
q1909
|
globify
|
train
|
function globify (args) {
let parsed = new ParsedArgs(args);
let expandGlob = parsed.args[parsed.globIndex];
let renameOutfile = parsed.args[parsed.outfileIndex];
let files = expandGlob && expandGlob(parsed.globOptions);
if (!expandGlob) {
// No glob patterns were found, so just run browserify as-is
if (renameOutfile) {
parsed.args[parsed.outfileIndex] = renameOutfile();
}
browserify(parsed.cmd, parsed.args);
}
else if (!renameOutfile) {
// Run browserify with the expanded list of file names
|
javascript
|
{
"resource": ""
}
|
q1910
|
areTermsMatching
|
train
|
function areTermsMatching (buyerTerms, sellerTerms) {
if (buyerTerms.maxPrice >= sellerTerms.minPrice &&
buyerTerms.maxLock >= sellerTerms.minLock &&
|
javascript
|
{
"resource": ""
}
|
q1911
|
onPushNotificationError
|
train
|
function onPushNotificationError(error) {
Q(pushCallback(error)).done(undefined, function (e) {
|
javascript
|
{
"resource": ""
}
|
q1912
|
onPushNotificationRegistration
|
train
|
function onPushNotificationRegistration(response) {
if (resolveRegistrationEventResponse) {
diag.debug.assert(!!rejectRegistrationEventResponse);
resolveRegistrationEventResponse(response);
resolveRegistrationEventResponse = undefined;
|
javascript
|
{
"resource": ""
}
|
q1913
|
onPushNotificationNotification
|
train
|
function onPushNotificationNotification(response) {
// assignments avoiding changes of implementation state during promise chain
var plugin = pushPlugin;
var callback = pushCallback;
return Q(response).then(function (r) {
diag.debug.assert(r === response, 'just begins promise chain avoiding explicit try-catch');
return callback(undefined, response) || response;
}).then(function (r) {
diag.debug.assert(r === response, 'push callback must respond same object');
return Q.Promise(function (resolve, reject) {
try {
if ('notId' in response.additionalData) {
plugin.finish(resolve, reject, response.additionalData.notId);
}
else {
plugin.finish(resolve, reject);
|
javascript
|
{
"resource": ""
}
|
q1914
|
defaultPushCallback
|
train
|
function defaultPushCallback(error, pushMessage) {
if (error) {
diag.debug.error('push failure', error);
}
else if (pushMessage && pushMessage.message) {
|
javascript
|
{
"resource": ""
}
|
q1915
|
listenPushNotification
|
train
|
function listenPushNotification(callback) {
if (callback === void 0) { callback = defaultPushCallback; }
if (resolveRegistrationEventResponse) {
diag.debug.assert(!!rejectRegistrationEventResponse);
resolveRegistrationEventResponse(undefined);
resolveRegistrationEventResponse = undefined;
rejectRegistrationEventResponse = undefined;
}
if (callback) {
// perform registration
promiseRegistrationEventResponse = device.ready.then(function (info) {
var pushInitOptions = init.initOptions.push;
var pushPlatform = info.platform.id;
if (pushPlatform === 'windowsphone') {
pushPlatform = 'windows';
}
if (!pushInitOptions || !pushPlatform || !(pushPlatform in pushInitOptions)) {
// no push configuration for current platform
promiseRegistrationEventResponse = Q.resolve(undefined);
return promiseRegistrationEventResponse;
}
// init or reinit push
var pushStatic = global['PushNotification'];
var pushImpl = pushStatic.init(pushInitOptions);
if (pushPlugin !== pushImpl) {
if (pushPlugin) {
// turn off existing event handlers (in reverse order of registration)
pushPlugin.off('notification', onPushNotificationNotification);
pushPlugin.off('registration', onPushNotificationRegistration);
pushPlugin.off('error', onPushNotificationError);
}
// set up new registration results
promiseRegistrationEventResponse = Q.Promise(function (resolve, reject) {
resolveRegistrationEventResponse = resolve;
rejectRegistrationEventResponse = reject;
});
// activation of new implementation
|
javascript
|
{
"resource": ""
}
|
q1916
|
configurePushDevice
|
train
|
function configurePushDevice(options) {
return Q.when(promiseRegistrationEventResponse, function (registrationEventResponse) {
if (!registrationEventResponse) {
// either there is no configuration or since this method was called,
// registration was canceled
return Q.resolve(undefined);
|
javascript
|
{
"resource": ""
}
|
q1917
|
train
|
function (k, v) {
checkJobs.push(function (checkDone) {
api.elasticsearch.search(self.alias, [k], [v], 0, 2, null, 1, function (error, results) {
if (error) { return checkDone(error) }
if (results.length === 0) { return checkDone() }
if (results.length ===
|
javascript
|
{
"resource": ""
}
|
|
q1918
|
train
|
function(opts) {
this._emitter = new events.EventEmitter();
this._libpath = opts.path;
this._tox = opts.tox;
|
javascript
|
{
"resource": ""
}
|
|
q1919
|
setCallback
|
train
|
function setCallback (action, callbackContext = null, callbackText = null) {
const callbackAction = this.toAbsoluteAction(action);
this.setState({
[ACTION]: callbackAction,
|
javascript
|
{
"resource": ""
}
|
q1920
|
hasCallback
|
train
|
function hasCallback (callbackContext = null) {
if (!this.state[ACTION]
|| callbackContext
|
javascript
|
{
"resource": ""
}
|
q1921
|
renameFilesIOS
|
train
|
function renameFilesIOS (oldPackageName, newPackageName) {
const filesAndFolders = [
`ios/${oldPackageName}.xcodeproj/xcshareddata/xcschemes/<?>-tvOS.xcscheme`,
`ios/${oldPackageName}.xcodeproj/xcshareddata/xcschemes/<?>.xcscheme`,
'ios/<?>.xcodeproj',
`ios/${oldPackageName}/<?>.entitlements`,
'ios/<?>',
'ios/<?>-tvOS',
'ios/<?>-tvOSTests',
`ios/${oldPackageName}Tests/<?>Tests.m`,
'ios/<?>Tests',
'ios/<?>.xcworkspace',
]
for (let i = 0; i < filesAndFolders.length; i++) {
const element = filesAndFolders[i]
|
javascript
|
{
"resource": ""
}
|
q1922
|
updatePackageID
|
train
|
function updatePackageID () {
return new Promise((resolve) => {
const oldPackageID = oldInfo.packageID
const newPackageID = newInfo.packageID
const androidPath = newInfo.androidPathToModule
console.log(`Changing package ID from "${oldPackageID}" to "${newPackageID}"...`)
|
javascript
|
{
"resource": ""
}
|
q1923
|
train
|
function(tox, opts) {
if(!opts) opts = {};
var libpath = opts['path'];
this._tox = tox;
|
javascript
|
{
"resource": ""
}
|
|
q1924
|
OpenEventObserver
|
train
|
function OpenEventObserver(clientPort, serverPort) {
events.EventEmitter.call(this);
this.isClientPortOpen =
|
javascript
|
{
"resource": ""
}
|
q1925
|
chainSerialPorts
|
train
|
function chainSerialPorts(clientPort, serverPort) {
var observer = new OpenEventObserver(clientPort, serverPort);
function serverPortWrite(data) {
try {
debug('writing to serverPort', data);
if (! Buffer.isBuffer(data)) {
data = new Buffer(data);
}
serverPort.write(data);
}
catch (ex) {
debug('error reading message', ex);
|
javascript
|
{
"resource": ""
}
|
q1926
|
logout
|
train
|
function logout(logoutOptions) {
if (logoutOptions === void 0) { logoutOptions = {}; }
var serverUrl = urls.resolveServer('/', logoutOptions);
var serverObj = server.Server.getInstance(serverUrl);
// process options
var currentOptions = serverObj.applyOptions({
serverUrl: serverUrl,
agentOptions: logoutOptions.agentOptions || init.initOptions.agentOptions,
agentClass: logoutOptions.agentClass || init.initOptions.agentClass,
});
return ajax(_.defaults({
serverUrl: serverUrl,
method: 'POST',
url: '/gofer/security/rest/auth/logout',
body: {}
}, currentOptions)).catch(function (error) {
if (error.statusCode === 422) {
// REST-based logout URL currently is broken reporting a 422 in all cases
return ajax(_.defaults({
serverUrl: serverUrl,
method: 'GET',
url: '/gofer/security-logout'
}, currentOptions)).then(function (result) {
diag.debug.warn('BUG: resorted to classic PATH-based logout as REST-based logout failed:', error);
return result;
}, function (error2) {
return Q.reject(error2.statusCode === 422 ? error : error2);
});
}
return Q.reject(error);
|
javascript
|
{
"resource": ""
}
|
q1927
|
registerPushDevice
|
train
|
function registerPushDevice(registrationId, options) {
if (options === void 0) { options = {}; }
var user = server.getCurrentAuthorization().name;
var pushInitOptions = init.initOptions.push;
return device.ready.then(function (info) {
var providerType;
switch (info.platform.id) {
case 'android':
providerType = 'GCM';
break;
case 'ios':
// when a senderID is configured,
// iOS device is registered at APNS which generates a token registered in turn at GCM,
// so that pushes are send using GCM to either type of device.
providerType = pushInitOptions.ios.senderID ? 'GCM' : 'APNS';
break;
case 'windowsphone':
providerType = 'WNS';
break;
|
javascript
|
{
"resource": ""
}
|
q1928
|
pushDeviceFilterByUsers
|
train
|
function pushDeviceFilterByUsers() {
var users = [];
for (var _i = 0; _i < arguments.length; _i++) {
users[_i - 0] = arguments[_i];
}
if (users.length <= 0) {
return {
type: 'null',
fieldName: 'user',
isNull: true
};
}
else if (users.length === 1) {
return {
type: 'string',
fieldName: 'user',
|
javascript
|
{
"resource": ""
}
|
q1929
|
train
|
function(opts) {
if(!opts) opts = {};
var libpath = opts['path'];
this._emitter = new events.EventEmitter();
this._library = this.createLibrary(libpath);
this._initCrypto(opts);
this._options = this._createToxOptions(opts);
this._initNew(this._options);
this._initCallbacks();
// Create a child
|
javascript
|
{
"resource": ""
}
|
|
q1930
|
bufferloader
|
train
|
function bufferloader (url, limit = 0, limitJustByBody = false, redirCount = 3) {
return new Promise((resolve, reject) => {
if (redirCount <= 0) {
reject(new Error('Too many redirects'));
}
let totalLength = 0;
let buf = Buffer.alloc(0);
const req = https.get(url, (res) => {
if (res.statusCode === 301 && res.headers && res.headers.location) {
// redirect
req.removeAllListeners();
resolve(bufferloader(res.headers.location, limit, limitJustByBody, redirCount - 1));
return;
}
if (res.statusCode !== 200) {
req.removeAllListeners();
reject(new Error(res.statusMessage || 'Cant load'));
return;
}
|
javascript
|
{
"resource": ""
}
|
q1931
|
train
|
function () {
if (options['offline']) {
options.drupalDistroRelease = '0.0.0';
}
else {
// Find the latest stable release for the Drupal distro version.
var done = this.async();
options.drupalDistro.releaseVersion(options.drupalDistroVersion, done, function(err,
|
javascript
|
{
"resource": ""
}
|
|
q1932
|
train
|
function () {
var srcFiles = path.resolve(
this.templatePath('drupal'),
options.drupalDistro.id,
options.drupalDistroVersion
);
if (gadget.fsExistsSync(srcFiles)) {
this.fs.copy(
path.resolve(srcFiles),
this.destinationRoot(),
|
javascript
|
{
"resource": ""
}
|
|
q1933
|
train
|
function () {
var isNewProject = (this.composerOrig == undefined);
if (!isNewProject) {
// Use original composer file if project already generated.
this.composer = this.composerOrig;
}
this.composer.name = 'organization/' + options.projectName;
this.composer.description = options.projectDescription;
// Allow distros to modify the composer.json.
if (typeof options.drupalDistro.modifyComposer == 'function') {
var done = this.async();
|
javascript
|
{
"resource": ""
}
|
|
q1934
|
runCall
|
train
|
function runCall(name, call, input) {
return web.post(connectorsUrl +
|
javascript
|
{
"resource": ""
}
|
q1935
|
validateBotApi
|
train
|
function validateBotApi (botFactory, postBackTest, textTest, acl) {
/** @deprecated way to validate bot */
if (postBackTest && typeof postBackTest === 'object') {
// @ts-ignore
return validate(botFactory, postBackTest, textTest, acl)
.then((res) => {
if (!res.ok) {
throw new Error(res.error);
}
});
}
return {
|
javascript
|
{
"resource": ""
}
|
q1936
|
clearOfflineLogin
|
train
|
function clearOfflineLogin(credentials, serverOptions) {
// simultaneous logins using different credentials is not realized so far,
// so that the credentials parameter is irrelevant, but provided for the
// sake of completeness...
|
javascript
|
{
"resource": ""
}
|
q1937
|
storeOfflineLogin
|
train
|
function storeOfflineLogin(credentials, serverOptions, loginResponse) {
return cipher.encryptJson(credentials['password'], loginResponse).then(function (value) {
|
javascript
|
{
"resource": ""
}
|
q1938
|
fetchOfflineLogin
|
train
|
function fetchOfflineLogin(credentials, serverOptions) {
try {
var value = localStorage().getItem(computeLocalStorageKey(serverOptions));
if (!value) {
return Q.resolve(undefined);
}
|
javascript
|
{
"resource": ""
}
|
q1939
|
train
|
function(opts) {
// If opts is a string, assume libpath
if(_.isString(opts)) {
opts = { path: opts }
}
if(!opts) opts = {};
|
javascript
|
{
"resource": ""
}
|
|
q1940
|
KeysAnd
|
train
|
function KeysAnd(values) {
var vals = this.values = {};
canReflect.eachKey(values, function(value, key) {
if (canReflect.isPlainObject(value) && !set.isSpecial(value)) {
|
javascript
|
{
"resource": ""
}
|
q1941
|
resolveAppBuild
|
train
|
function resolveAppBuild(appTsConfigPath) {
const outDir = getAppBuildFolder(appTsConfigPath);
const buildPath
|
javascript
|
{
"resource": ""
}
|
q1942
|
initBLModel
|
train
|
function initBLModel(soajs, cb) {
let modelName = driverConfig.model;
if (soajs.servicesConfig && soajs.servicesConfig.model) {
modelName = soajs.servicesConfig.model;
}
if (process.env.SOAJS_TEST && soajs.inputmaskData && soajs.inputmaskData.model) {
modelName = soajs.inputmaskData.model;
}
let modelPath = __dirname + "/model/" + modelName + ".js";
return requireModel(modelPath, cb);
/**
* checks if model file exists, requires it and returns it.
* @param filePath
* @param cb
*/
function requireModel(filePath, cb) {
//check if
|
javascript
|
{
"resource": ""
}
|
q1943
|
requireModel
|
train
|
function requireModel(filePath, cb) {
//check if file exist. if not return error
fs.exists(filePath, function (exists) {
if (!exists) {
soajs.log.error('Requested Model Not Found!');
|
javascript
|
{
"resource": ""
}
|
q1944
|
train
|
function (req, res, passport, cb) {
let authentication = req.soajs.inputmaskData.strategy;
passportLib.getDriver(req, false, function (err, passportDriver) {
passportDriver.preAuthenticate(req, function () {
passport.authenticate(authentication, {session: false}, function (err, user) {
if (err) {
req.soajs.log.error(err);
return cb({"code": 499, "msg": err.toString()});
}
if (!user) {
cb({"code": 403, "msg": req.soajs.config.errors[403]});
}
req.soajs.inputmaskData.user = user;
initBLModel(req.soajs, function (err) {
|
javascript
|
{
"resource": ""
}
|
|
q1945
|
train
|
function (soajs, data, cb) {
initBLModel(soajs, function (err) {
if (err) {
return cb(err);
}
driver.model.initConnection(soajs);
let criteria = null;
if (!(data.username || data.id)) {
return cb(411);
}
if (data.username) {
criteria = {
'username': data.username
};
}
else {
let id = null;
try {
id = driver.model.validateId(soajs, data.id);
criteria = {
'_id': id
};
}
catch (e) {
return cb(411);
}
}
if (!criteria)
return cb(403);
utilities.findRecord(soajs, driver.model, criteria, cb, function (record) {
delete record.password;
let groupInfo = checkUserTenantAccess(record, soajs.tenant);
|
javascript
|
{
"resource": ""
}
|
|
q1946
|
train
|
function (soajs, data, cb) {
let token = data.token;
let openam;
if (soajs.servicesConfig.urac && soajs.servicesConfig.urac.openam) {
openam = soajs.servicesConfig.urac.openam;
}
else {
return cb({"code": 712, "msg": soajs.config.errors[712]});
}
let openamAttributesURL = openam.attributesURL;
let openamAttributesMap = openam.attributesMap;
let openamTimeout = openam.timeout || 10000;
request.post(openamAttributesURL, {
form: {subjectid: token},
timeout: openamTimeout
}, function (error, response, body) {
let userRecord;
if (error) {
soajs.log.error(error);
return cb({"code": 710, "msg": soajs.config.errors[710]});
}
if (!response || response.statusCode !== 200) {
soajs.log.error("OpenAM token invalid!");
return cb({"code": 711, "msg": soajs.config.errors[711]});
}
try {
|
javascript
|
{
"resource": ""
}
|
|
q1947
|
train
|
function (soajs) {
if (soajs.inputmaskData && soajs.inputmaskData.isOwner) {
soajs.mongoDb = new Mongo(soajs.meta.tenantDB(soajs.registry.tenantMetaDB, 'urac', soajs.inputmaskData.tCode));
}
else {
let tcode = soajs.tenant.code;
if (soajs.tenant.roaming && soajs.tenant.roaming.code) {
|
javascript
|
{
"resource": ""
}
|
|
q1948
|
train
|
function (soajs, id) {
let id1;
try {
id1 = soajs.mongoDb.ObjectId(id.toString());
|
javascript
|
{
"resource": ""
}
|
|
q1949
|
train
|
function (soajs, combo, cb) {
soajs.mongoDb.find(combo.collection,
|
javascript
|
{
"resource": ""
}
|
|
q1950
|
train
|
function (soajs, combo, cb) {
soajs.mongoDb.insert
|
javascript
|
{
"resource": ""
}
|
|
q1951
|
configFromRFC2822
|
train
|
function configFromRFC2822(config) {
var string, match, dayFormat,
dateFormat, timeFormat, tzFormat;
var timezones = {
' GMT': ' +0000',
' EDT': ' -0400',
' EST': ' -0500',
' CDT': ' -0500',
' CST': ' -0600',
' MDT': ' -0600',
' MST': ' -0700',
' PDT': ' -0700',
' PST': ' -0800'
};
var military = 'YXWVUTSRQPONZABCDEFGHIKLM';
var timezone, timezoneIndex;
string = config._i
.replace(/\([^\)]*\)|[\n\t]/g, ' ') // Remove comments and folding whitespace
.replace(/(\s\s+)/g, ' ') // Replace multiple-spaces with a single space
.replace(/^\s|\s$/g, ''); // Remove leading and trailing spaces
match = basicRfcRegex.exec(string);
if (match) {
dayFormat = match[1] ? 'ddd' + ((match[1].length === 5) ? ', ' : ' ') : '';
dateFormat = 'D MMM ' + ((match[2].length > 10) ? 'YYYY ' : 'YY ');
timeFormat = 'HH:mm' + (match[4] ? ':ss' : '');
// TODO: Replace the vanilla
|
javascript
|
{
"resource": ""
}
|
q1952
|
matchDetails
|
train
|
function matchDetails(m, isSearch) {
var id, regexp, segment, type, cfg, arrayMode;
id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
cfg = config.params[id];
segment = pattern.substring(last, m.index);
regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
if (regexp) {
|
javascript
|
{
"resource": ""
}
|
q1953
|
update
|
train
|
function update() {
for (var i = 0; i < states.length; i++) {
if (anyMatch(states[i].state, states[i].params)) {
addClass($element, activeClasses[states[i].hash]);
} else {
removeClass($element, activeClasses[states[i].hash]);
}
|
javascript
|
{
"resource": ""
}
|
q1954
|
extendClass
|
train
|
function extendClass(parent, members) {
var object = function () { return UNDEFINED; };
object.prototype = new parent();
|
javascript
|
{
"resource": ""
}
|
q1955
|
numberFormat
|
train
|
function numberFormat(number, decimals, decPoint, thousandsSep) {
var externalFn = Highcharts.numberFormat,
lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = +number || 0,
c = decimals === -1 ?
(n.toString().split('.')[1] || '').length : // preserve decimals
(isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
s = n < 0 ? "-" : "",
|
javascript
|
{
"resource": ""
}
|
q1956
|
formatSingle
|
train
|
function formatSingle(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = numberFormat(
val,
|
javascript
|
{
"resource": ""
}
|
q1957
|
train
|
function (prop, setter) {
// jQuery 1.8 style
if ($.Tween) {
$.Tween.propHooks[prop] = {
set: setter
};
|
javascript
|
{
"resource": ""
}
|
|
q1958
|
train
|
function (inherit) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881)
if (inherit && this.element.namespaceURI === SVG_NS) {
this.element.removeAttribute('visibility');
} else {
|
javascript
|
{
"resource": ""
}
|
|
q1959
|
train
|
function (parent) {
var renderer = this.renderer,
parentWrapper = parent || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
element = this.element,
zIndex = this.zIndex,
otherElement,
otherZIndex,
i,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// mark the container as having z indexed children
if (zIndex) {
parentWrapper.handleZ = true;
zIndex = pInt(zIndex);
}
// insert according
|
javascript
|
{
"resource": ""
}
|
|
q1960
|
train
|
function (key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { //
|
javascript
|
{
"resource": ""
}
|
|
q1961
|
train
|
function (x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = mathMin((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path,
normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors;
x += normalizer;
y += normalizer;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33,
|
javascript
|
{
"resource": ""
}
|
|
q1962
|
train
|
function () {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
|
javascript
|
{
"resource": ""
}
|
|
q1963
|
train
|
function (width, baseline, alignCorrection, rotation, align) {
var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
height = pick(this.elemHeight, this.element.offsetHeight),
quad,
nonLeft = align && align !== 'left';
// correct x and y
this.xCorr = costheta < 0 && -width;
this.yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
|
javascript
|
{
"resource": ""
}
|
|
q1964
|
train
|
function (key, value) {
if (docMode8) { // IE8 setAttribute bug
this.element[key] = value;
} else {
|
javascript
|
{
"resource": ""
}
|
|
q1965
|
train
|
function (value, key, element) {
var style = element.style;
this[key] = style[key] = value; // style is for #1873
|
javascript
|
{
"resource": ""
}
|
|
q1966
|
train
|
function (x, y, w, h, options) {
return SVGRenderer.prototype.symbols[
!defined(options)
|
javascript
|
{
"resource": ""
}
|
|
q1967
|
train
|
function () {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
|
javascript
|
{
"resource": ""
}
|
|
q1968
|
train
|
function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this,
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
|
javascript
|
{
"resource": ""
}
|
|
q1969
|
train
|
function (value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB;
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = mathRound(translatedValue + transB);
y1 = y2 = mathRound(cHeight - translatedValue - transB);
if (isNaN(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
|
javascript
|
{
"resource": ""
}
|
|
q1970
|
train
|
function () {
var chart = this.chart,
maxTicks = chart.maxTicks || {},
tickPositions = this.tickPositions,
key = this._maxTicksKey = [this.coll, this.pos, this.len].join('-');
if (!this.isLinked && !this.isDatetimeAxis
|
javascript
|
{
"resource": ""
}
|
|
q1971
|
train
|
function (e, point) {
if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too.
if ((defined(point) || !pick(this.crosshair.snap, true)) === false) {
this.hideCrosshair();
return;
}
var path,
options = this.crosshair,
animation = options.animation,
pos;
// Get the path
if (!pick(options.snap, true)) {
pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
/*jslint eqeq: true*/
pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY;
|
javascript
|
{
"resource": ""
}
|
|
q1972
|
train
|
function (tooltip) {
var items = this.points || splat(this),
series = items[0].series,
s;
// build the header
s = [tooltip.tooltipHeaderFormatter(items[0])];
// build the values
|
javascript
|
{
"resource": ""
}
|
|
q1973
|
train
|
function (e) {
var chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: [],
originalEvent: e.originalEvent || e
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
selectionData[axis.coll].push({
axis: axis,
min: mathMin(selectionMin, selectionMax), // for reversed axes,
max: mathMax(selectionMin, selectionMax)
|
javascript
|
{
"resource": ""
}
|
|
q1974
|
train
|
function () {
var chart = charts[hoverChartIndex];
if (chart) {
chart.pointer.reset();
|
javascript
|
{
"resource": ""
}
|
|
q1975
|
train
|
function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
|
javascript
|
{
"resource": ""
}
|
|
q1976
|
train
|
function (fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove'
|
javascript
|
{
"resource": ""
}
|
|
q1977
|
train
|
function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
|
javascript
|
{
"resource": ""
}
|
|
q1978
|
train
|
function () {
var allItems = [];
each(this.chart.series, function (series) {
var seriesOptions = series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
|
javascript
|
{
"resource": ""
}
|
|
q1979
|
train
|
function (scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + pageCount
});
|
javascript
|
{
"resource": ""
}
|
|
q1980
|
train
|
function (titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function (arr) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
|
javascript
|
{
"resource": ""
}
|
|
q1981
|
train
|
function (width, height, animation) {
var chart = this,
chartWidth,
chartHeight,
fireEndResize;
// Handle the isResizing counter
chart.isResizing += 1;
fireEndResize = function () {
if (chart) {
fireEvent(chart, 'endResize', null, function () {
chart.isResizing -= 1;
});
}
};
// set the animation for the current process
setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (defined(width)) {
chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
chart.hasUserSize = !!chartWidth;
}
if (defined(height)) {
chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
}
|
javascript
|
{
"resource": ""
}
|
|
q1982
|
train
|
function () {
each(this.series, function (serie) {
serie.translate();
if (serie.setTooltipPoints) {
|
javascript
|
{
"resource": ""
}
|
|
q1983
|
train
|
function (credits) {
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text,
0,
0
)
.on('click', function () {
|
javascript
|
{
"resource": ""
}
|
|
q1984
|
train
|
function (chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function (a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: NORMAL_STATE,
pointAttr: {},
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// special
if (useCanVG) {
options.animation = false;
}
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function (key) {
series[key + 'Data'] = [];
|
javascript
|
{
"resource": ""
}
|
|
q1985
|
train
|
function () {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function (axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
|
javascript
|
{
"resource": ""
}
|
|
q1986
|
train
|
function (point, i) {
var series = point.series,
args = arguments,
fn = typeof i === 'number' ?
// Insert the value in the given position
function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with
|
javascript
|
{
"resource": ""
}
|
|
q1987
|
train
|
function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
|
javascript
|
{
"resource": ""
}
|
|
q1988
|
train
|
function (key) {
Array.prototype[i].apply(series[key + 'Data'],
|
javascript
|
{
"resource": ""
}
|
|
q1989
|
train
|
function (force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
activePointCount = 0,
isCartesian = series.isCartesian,
xExtremes,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
activePointCount = processedXData.length;
}
|
javascript
|
{
"resource": ""
}
|
|
q1990
|
train
|
function () {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
pointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
|
javascript
|
{
"resource": ""
}
|
|
q1991
|
StackItem
|
train
|
function StackItem(axis, options, isNegative, x, stackOption) {
var inverted = axis.chart.inverted;
this.axis = axis;
// Tells if the stack is negative
this.isNegative = isNegative;
// Save the options to be able to style the label
this.options = options;
// Save the x value to be able to position the label later
this.x = x;
// Initialize total value
this.total = null;
// This will keep each points' extremes stored by series.index and point index
this.points = {};
// Save the stack option on the series configuration object, and whether to treat it as percent
this.stack = stackOption;
// The align options and text align varies on whether the stack is negative and
// if
|
javascript
|
{
"resource": ""
}
|
q1992
|
train
|
function (newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// Make sure groups are not destroyed (#3094)
each(preserve, function (prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, { data: this.options.data }, newOptions);
// Destroy the series and reinsert methods from the type prototype
this.remove(false);
|
javascript
|
{
"resource": ""
}
|
|
q1993
|
train
|
function () {
var series = this,
segments = [],
segment = [],
keys = [],
xAxis = this.xAxis,
yAxis = this.yAxis,
stack = yAxis.stacks[this.stackKey],
pointMap = {},
plotX,
plotY,
points = this.points,
connectNulls = this.options.connectNulls,
i,
x;
if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
// Create a map where we can quickly look up the points by their X value.
for (i = 0; i < points.length; i++) {
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
for (x in stack) {
if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
keys.push(+x);
}
}
keys.sort(function (a, b) {
return a - b;
});
each(keys, function (x) {
var y = 0,
stackPoint;
if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
return;
// The point exists, push it to the segment
} else if (pointMap[x]) {
segment.push(pointMap[x]);
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
} else
|
javascript
|
{
"resource": ""
}
|
|
q1994
|
train
|
function (segment) {
var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
i,
options = this.options,
segLength = segmentPath.length,
translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
yBottom;
if (segLength === 3) { // for animation from 1 to two points
areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
}
if (options.stacking && !this.closedStacks) {
// Follow stack back. Todo: implement areaspline. A general solution could be to
// reverse the entire graphPath of the previous series, though may be hard with
// splines and with series with different extremes
for (i = segment.length - 1; i >= 0; i--) {
yBottom = pick(segment[i].yBottom, translatedThreshold);
|
javascript
|
{
"resource": ""
}
|
|
q1995
|
train
|
function () {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints)
|
javascript
|
{
"resource": ""
}
|
|
q1996
|
onScroll
|
train
|
function onScroll() {
// unique tick id
++ticks;
// viewport rectangle
var top = jWindow.scrollTop(),
left = jWindow.scrollLeft(),
right = left + jWindow.width(),
bottom = top + jWindow.height();
// determine which elements are in view
// + 60 accounts for fixed nav
var intersections = findElements(top+offset.top + 200, right+offset.right, bottom+offset.bottom, left+offset.left);
$.each(intersections, function(i, element) {
|
javascript
|
{
"resource": ""
}
|
q1997
|
train
|
function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
if (!multiple) {
$newSelect.trigger('close');
}
}
}
// ARROW DOWN - move to next not disabled option
|
javascript
|
{
"resource": ""
}
|
|
q1998
|
captionTransition
|
train
|
function captionTransition(caption, duration) {
if (caption.hasClass("center-align")) {
caption.velocity({opacity: 0, translateY: -100}, {duration: duration, queue: false});
}
else if (caption.hasClass("right-align")) {
caption.velocity({opacity: 0, translateX: 100}, {duration: duration, queue: false});
}
|
javascript
|
{
"resource": ""
}
|
q1999
|
moveToSlide
|
train
|
function moveToSlide(index) {
// Wrap around indices.
if (index >= $slides.length) index = 0;
else if (index < 0) index = $slides.length -1;
$active_index = $slider.find('.active').index();
// Only do if index changes
if ($active_index != index) {
$active = $slides.eq($active_index);
$caption = $active.find('.caption');
$active.removeClass('active');
$active.velocity({opacity: 0}, {duration: options.transition, queue: false, easing: 'easeOutQuad',
complete: function() {
$slides.not('.active').velocity({opacity: 0, translateX: 0, translateY: 0}, {duration: 0, queue: false});
} });
captionTransition($caption, options.transition);
// Update indicators
if (options.indicators) {
$indicators.eq($active_index).removeClass('active');
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.