_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q28600 | getForwardedAttributes | train | function getForwardedAttributes( section ) {
var attributes = section.attributes;
var result = [];
for( var i = 0, len = attributes.length; i < len; i++ ) {
var name = attributes[i].name,
value = attributes[i].value;
// disregard attributes that are used for markdown loading/parsing
if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
if( value ) {
result.push( name + '="' + value + '"' );
}
else {
result.push( name );
}
}
return result.join( ' ' );
} | javascript | {
"resource": ""
} |
q28601 | getSlidifyOptions | train | function getSlidifyOptions( options ) {
options = options || {};
options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
options.attributes = options.attributes || '';
return options;
} | javascript | {
"resource": ""
} |
q28602 | slidify | train | function slidify( markdown, options ) {
options = getSlidifyOptions( options );
var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
horizontalSeparatorRegex = new RegExp( options.separator );
var matches,
lastIndex = 0,
isHorizontal,
wasHorizontal = true,
content,
sectionStack = [];
// iterate until all blocks between separators are stacked up
while( matches = separatorRegex.exec( markdown ) ) {
notes = null;
// determine direction (horizontal by default)
isHorizontal = horizontalSeparatorRegex.test( matches[0] );
if( !isHorizontal && wasHorizontal ) {
// create vertical stack
sectionStack.push( [] );
}
// pluck slide content from markdown input
content = markdown.substring( lastIndex, matches.index );
if( isHorizontal && wasHorizontal ) {
// add to horizontal stack
sectionStack.push( content );
}
else {
// add to vertical stack
sectionStack[sectionStack.length-1].push( content );
}
lastIndex = separatorRegex.lastIndex;
wasHorizontal = isHorizontal;
}
// add the remaining slide
( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
var markdownSections = '';
// flatten the hierarchical stack, and insert <section data-markdown> tags
for( var i = 0, len = sectionStack.length; i < len; i++ ) {
// vertical
if( sectionStack[i] instanceof Array ) {
markdownSections += '<section '+ options.attributes +'>';
sectionStack[i].forEach( function( child ) {
markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
} );
markdownSections += '</section>';
}
else {
markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
}
}
return markdownSections;
} | javascript | {
"resource": ""
} |
q28603 | addAttributeInElement | train | function addAttributeInElement( node, elementTarget, separator ) {
var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
var nodeValue = node.nodeValue;
if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
var classes = matches[1];
nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
node.nodeValue = nodeValue;
while( matchesClass = mardownClassRegex.exec( classes ) ) {
elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
}
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q28604 | addAttributes | train | function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
previousParentElement = element;
for( var i = 0; i < element.childNodes.length; i++ ) {
childElement = element.childNodes[i];
if ( i > 0 ) {
j = i - 1;
while ( j >= 0 ) {
aPreviousChildElement = element.childNodes[j];
if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
previousParentElement = aPreviousChildElement;
break;
}
j = j - 1;
}
}
parentSection = section;
if( childElement.nodeName == "section" ) {
parentSection = childElement ;
previousParentElement = childElement ;
}
if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
}
}
}
if ( element.nodeType == Node.COMMENT_NODE ) {
if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
addAttributeInElement( element, section, separatorSectionAttributes );
}
}
} | javascript | {
"resource": ""
} |
q28605 | convertSlides | train | function convertSlides() {
var sections = document.querySelectorAll( '[data-markdown]');
for( var i = 0, len = sections.length; i < len; i++ ) {
var section = sections[i];
// Only parse the same slide once
if( !section.getAttribute( 'data-markdown-parsed' ) ) {
section.setAttribute( 'data-markdown-parsed', true )
var notes = section.querySelector( 'aside.notes' );
var markdown = getMarkdownFromSlide( section );
section.innerHTML = marked( markdown );
addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
section.parentNode.getAttribute( 'data-element-attributes' ) ||
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
section.getAttribute( 'data-attributes' ) ||
section.parentNode.getAttribute( 'data-attributes' ) ||
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
// If there were notes, we need to re-add them after
// having overwritten the section's HTML
if( notes ) {
section.appendChild( notes );
}
}
}
} | javascript | {
"resource": ""
} |
q28606 | runExecutable | train | function runExecutable(args, cwd, logLevel) {
const logger = require('./logger')(logLevel);
return new Promise((resolve, reject) => {
logger.silly('Theme Kit command starting');
let errors = '';
const pathToExecutable = path.join(config.destination, config.binName);
fs.statSync(pathToExecutable);
const childProcess = spawn(pathToExecutable, args, {
cwd,
stdio: ['inherit', 'inherit', 'pipe']
});
childProcess.on('error', (err) => {
errors += err;
});
childProcess.stderr.on('data', (err) => {
errors += err;
});
childProcess.on('close', () => {
logger.silly('Theme Kit command finished');
if (errors) {
reject(errors);
}
resolve();
});
});
} | javascript | {
"resource": ""
} |
q28607 | cleanFile | train | function cleanFile(pathToFile) {
try {
fs.unlinkSync(pathToFile);
} catch (err) {
switch (err.code) {
case 'ENOENT':
return;
default:
throw new Error(err);
}
}
} | javascript | {
"resource": ""
} |
q28608 | train | function () {
var module = "Global";
for(var i = 0; i < doc.tags.length; i++) {
var tag = doc.tags[i];
if (tag.type === "method") {
module = tag.content;
}
else if (tag.type === "function") {
module = tag.content;
}
}
return module.trim();
} | javascript | {
"resource": ""
} | |
q28609 | train | function() {
// We perform the bindings so that every function works
// properly when it is passed as a callback.
this.get = utils.bind(this, this.get);
this.del = utils.bind(this, this.del);
this.post = utils.bind(this, this.post);
this.request = utils.bind(this, this.request);
this._buildResponse = utils.bind(this, this._buildResponse);
// Set our default version to "none"
this._setSplunkVersion("none");
// Cookie store for cookie based authentication.
this._cookieStore = {};
} | javascript | {
"resource": ""
} | |
q28610 | train | function() {
var cookieString = "";
utils.forEach(this._cookieStore, function (cookieValue, cookieKey) {
cookieString += cookieKey;
cookieString += '=';
cookieString += cookieValue;
cookieString += '; ';
});
return cookieString;
} | javascript | {
"resource": ""
} | |
q28611 | train | function(url, headers, params, timeout, callback) {
var message = {
method: "GET",
headers: headers,
timeout: timeout,
query: params
};
return this.request(url, message, callback);
} | javascript | {
"resource": ""
} | |
q28612 | train | function(url, message, callback) {
var that = this;
var wrappedCallback = function(response) {
callback = callback || function() {};
// Handle cookies if 'set-cookie' header is in the response
var cookieHeaders = response.response.headers['set-cookie'];
if (cookieHeaders) {
utils.forEach(cookieHeaders, function (cookieHeader) {
var cookie = that._parseCookieHeader(cookieHeader);
that._cookieStore[cookie.key] = cookie.value;
});
}
// Handle callback
if (response.status < 400 && response.status !== "abort") {
callback(null, response);
}
else {
callback(response);
}
};
var query = utils.getWithVersion(this.version, queryBuilderMap)(message);
var post = message.post || {};
var encodedUrl = url + "?" + Http.encode(query);
var body = message.body ? message.body : Http.encode(post);
var cookieString = that._getCookieString();
if (cookieString.length !== 0) {
message.headers["Cookie"] = cookieString;
// Remove Authorization header
// Splunk will use Authorization header and ignore Cookies if Authorization header is sent
delete message.headers["Authorization"];
}
var options = {
method: message.method,
headers: message.headers,
timeout: message.timeout,
body: body
};
// Now we can invoke the user-provided HTTP class,
// passing in our "wrapped" callback
return this.makeRequest(encodedUrl, options, wrappedCallback);
} | javascript | {
"resource": ""
} | |
q28613 | train | function(error, response, data) {
var complete_response, json = {};
var contentType = null;
if (response && response.headers) {
contentType = utils.trim(response.headers["content-type"] || response.headers["Content-Type"] || response.headers["Content-type"] || response.headers["contentType"]);
}
if (utils.startsWith(contentType, "application/json") && data) {
try {
json = this.parseJson(data) || {};
}
catch(e) {
logger.error("Error in parsing JSON:", data, e);
json = data;
}
}
else {
json = data;
}
if (json) {
logger.printMessages(json.messages);
}
complete_response = {
response: response,
status: (response ? response.statusCode : 0),
data: json,
error: error
};
return complete_response;
} | javascript | {
"resource": ""
} | |
q28614 | train | function(results, done) {
// Find the index of the fields we want
var rawIndex = results.fields.indexOf("_raw");
var sourcetypeIndex = results.fields.indexOf("sourcetype");
var userIndex = results.fields.indexOf("user");
// Print out each result and the key-value pairs we want
console.log("Results: ");
for(var i = 0; i < results.rows.length; i++) {
console.log(" Result " + i + ": ");
console.log(" sourcetype: " + results.rows[i][sourcetypeIndex]);
console.log(" user: " + results.rows[i][userIndex]);
console.log(" _raw: " + results.rows[i][rawIndex]);
}
done();
} | javascript | {
"resource": ""
} | |
q28615 | train | function(job, done) {
var MAX_COUNT = 5;
var count = 0;
Async.whilst(
// Loop for N times
function() { return MAX_COUNT > count; },
// Every second, ask for preview results
function(iterationDone) {
Async.sleep(1000, function() {
job.preview({}, function(err, results) {
if (err) {
iterationDone(err);
return;
}
// Only do something if we have results
if (results && results.rows) {
// Up the iteration counter
count++;
console.log("========== Iteration " + count + " ==========");
var sourcetypeIndex = results.fields.indexOf("sourcetype");
var countIndex = results.fields.indexOf("count");
for(var i = 0; i < results.rows.length; i++) {
var row = results.rows[i];
// This is a hacky "padding" solution
var stat = (" " + row[sourcetypeIndex] + " ").slice(0, 30);
// Print out the sourcetype and the count of the sourcetype so far
console.log(stat + row[countIndex]);
}
console.log("=================================");
}
// And we're done with this iteration
iterationDone();
});
});
},
// When we're done looping, just cancel the job
function(err) {
job.cancel(done);
}
);
} | javascript | {
"resource": ""
} | |
q28616 | train | function(script)
{
// create local undefined vars so that script cannot access private vars
var _namespaces = undefined;
var _imported = undefined;
var _loading = undefined;
var _classPaths = undefined;
var _classInfo = undefined;
var _classDependencyList = undefined;
var _mixinCount = undefined;
var _mixinDependencies = undefined;
var _evalScript = undefined;
var _appendConstructor = undefined;
// set arguments to undefined so that script cannot access
arguments = undefined;
// eval script in context of window
eval.call(window, script);
} | javascript | {
"resource": ""
} | |
q28617 | ungettext | train | function ungettext(msgid1, msgid2, n) {
if (_i18n_locale.locale_name == 'en_DEBUG') return __debug_trans_str(msgid1);
var id = ''+_i18n_plural(n)+'-'+msgid1;
var entry = _i18n_catalog[id];
return entry == undefined ? (n==1 ? msgid1 : msgid2) : entry;
} | javascript | {
"resource": ""
} |
q28618 | Time | train | function Time(hour, minute, second, microsecond) {
if (_i18n_locale.locale_name == 'en_DEBUG') {
this.hour = 11;
this.minute = 22;
this.second = 33;
this.microsecond = 123000;
} else {
this.hour = hour;
this.minute = minute;
this.second = second;
this.microsecond = microsecond ? microsecond : 0;
}
} | javascript | {
"resource": ""
} |
q28619 | DateTime | train | function DateTime(date) {
if (date instanceof DateTime)
return date;
if (_i18n_locale.locale_name == 'en_DEBUG')
date = new Date(3333, 10, 22, 11, 22, 33, 123);
if (date instanceof Date) {
this.date = date;
this.hour = date.getHours();
this.minute = date.getMinutes();
this.second = date.getSeconds();
this.microsecond = 0;
this.year = date.getFullYear();
this.month = date.getMonth()+1;
this.day = date.getDate();
} else {
for(var k in date) {
this[k] = date[k];
}
}
} | javascript | {
"resource": ""
} |
q28620 | train | function(firedAlertGroups, done) {
// Get the list of all fired alert groups, including the all group (represented by "-").
var groups = firedAlertGroups.list();
console.log("Fired alert groups:");
Async.seriesEach(
groups,
function(firedAlertGroup, index, seriescallback) {
firedAlertGroup.list(function(err, firedAlerts){
// How many times was this alert fired?
console.log(firedAlertGroup.name, "(Count:", firedAlertGroup.count(), ")");
// Print the properties for each fired alert (default of 30 per alert group).
for(var i = 0; i < firedAlerts.length; i++) {
var firedAlert = firedAlerts[i];
for (var key in firedAlert.properties()) {
if (firedAlert.properties().hasOwnProperty(key)) {
console.log("\t", key, ":", firedAlert.properties()[key]);
}
}
console.log();
}
console.log("======================================");
});
seriescallback();
},
function(err) {
if (err) {
done(err);
}
done();
}
);
} | javascript | {
"resource": ""
} | |
q28621 | camelcase | train | function camelcase(flag) {
return flag.split('-').reduce(function(str, word){
return str + word[0].toUpperCase() + word.slice(1);
});
} | javascript | {
"resource": ""
} |
q28622 | pad | train | function pad(str, width) {
var len = Math.max(0, width - str.length);
return str + Array(len + 1).join(' ');
} | javascript | {
"resource": ""
} |
q28623 | train | function(sids, options, callback) {
_check_sids('cancel', sids);
// For each of the supplied sids, cancel the job.
this._foreach(sids, function(job, idx, done) {
job.cancel(function (err) {
if (err) {
done(err);
return;
}
console.log(" Job " + job.sid + " cancelled");
done();
});
}, callback);
} | javascript | {
"resource": ""
} | |
q28624 | train | function(args, options, callback) {
// Get the query and parameters, and remove the extraneous
// search parameter
var query = options.search;
var params = options;
delete params.search;
// Create the job
this.service.jobs().create(query, params, function(err, job) {
if (err) {
callback(err);
return;
}
console.log("Created job " + job.sid);
callback(null, job);
});
} | javascript | {
"resource": ""
} | |
q28625 | train | function(sids, options, callback) {
sids = sids || [];
if (sids.length === 0) {
// If no job SIDs are provided, we list all jobs.
var jobs = this.service.jobs();
jobs.fetch(function(err, jobs) {
if (err) {
callback(err);
return;
}
var list = jobs.list() || [];
for(var i = 0; i < list.length; i++) {
console.log(" Job " + (i + 1) + " sid: "+ list[i].sid);
}
callback(null, list);
});
}
else {
// If certain job SIDs are provided,
// then we simply read the properties of those jobs
this._foreach(sids, function(job, idx, done) {
job.fetch(function(err, job) {
if (err) {
done(err);
return;
}
console.log("Job " + job.sid + ": ");
var properties = job.properties();
for(var key in properties) {
// Skip some keys that make the output hard to read
if (utils.contains(["performance"], key)) {
continue;
}
console.log(" " + key + ": ", properties[key]);
}
done(null, properties);
});
}, callback);
}
} | javascript | {
"resource": ""
} | |
q28626 | getDisplayDate | train | function getDisplayDate(date) {
var monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
date = new Date(date);
var hours = date.getHours();
if (hours < 10) {
hours = "0" + hours.toString();
}
var mins = date.getMinutes();
if (mins < 10) {
mins = "0" + mins.toString();
}
return monthStrings[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear() +
" - " + hours + ":" + mins + " " + (date.getUTCHours() < 12 ? "AM" : "PM");
} | javascript | {
"resource": ""
} |
q28627 | train | function(allMessages) {
allMessages = allMessages || [];
for(var i = 0; i < allMessages.length; i++) {
var message = allMessages[i];
var type = message["type"];
var text = message["text"];
var msg = '[SPLUNKD] ' + text;
switch (type) {
case 'HTTP':
case 'FATAL':
case 'ERROR':
this.error(msg);
break;
case 'WARN':
this.warn(msg);
break;
case 'INFO':
this.info(msg);
break;
case 'HTTP':
this.error(msg);
break;
default:
this.info(msg);
break;
}
}
} | javascript | {
"resource": ""
} | |
q28628 | train | function(name, properties) {
// first respect the field hide list that came from the parent module
if(properties.fieldHideList && $.inArray(name, properties.fieldHideList) > -1) {
return false;
}
// next process the field visibility lists from the xml
if(this.fieldListMode === 'show_hide') {
if($.inArray(name, this.fieldHideList) > -1 && $.inArray(name, this.fieldShowList) < 0) {
return false;
}
}
else {
// assumes 'hide_show' mode
if($.inArray(name, this.fieldHideList) > -1) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} | |
q28629 | train | function($super, key, value, properties) {
var keysToIgnore = {
'chart.nullValueMode': true
};
if(key in keysToIgnore) {
return;
}
$super(key, value, properties);
} | javascript | {
"resource": ""
} | |
q28630 | train | function(point, series) {
if(!point || !point.graphic) {
return;
}
point.graphic.attr({'fill': this.fadedElementColor, 'stroke-width': 1, 'stroke': this.fadedElementBorderColor});
} | javascript | {
"resource": ""
} | |
q28631 | train | function(properties, data) {
var axisProperties = this.parseUtils.getXAxisProperties(properties),
orientation = (this.axesAreInverted) ? 'vertical' : 'horizontal',
colorScheme = this.getAxisColorScheme();
// add some extra info to the axisProperties as needed
if(axisProperties.hasOwnProperty('axisTitle.text')){
axisProperties['axisTitle.text'] = Splunk.JSCharting.ParsingUtils.escapeHtml(axisProperties['axisTitle.text']);
}
axisProperties.chartType = properties.chart;
axisProperties.axisLength = $(this.renderTo).width();
this.xAxis = new Splunk.JSCharting.NumericAxis(axisProperties, data, orientation, colorScheme);
this.hcConfig.xAxis = $.extend(true, this.xAxis.getConfig(), {
startOnTick: true,
endOnTick: true,
minPadding: 0,
maxPadding: 0
});
} | javascript | {
"resource": ""
} | |
q28632 | train | function($super) {
if(!this.hasSVG) {
$super();
return;
}
var i, loopSplit, loopKeyName, loopKeyElem, loopValElem,
$tooltip = $('.highcharts-tooltip', $(this.renderTo)),
tooltipElements = (this.hasSVG) ? $('tspan', $tooltip) :
$('span > span', $tooltip);
for(i = 0; i < tooltipElements.length; i += 3) {
loopKeyElem =tooltipElements[i];
if(tooltipElements.length < i + 2) {
break;
}
loopValElem = tooltipElements[i + 1];
loopSplit = (this.hasSVG) ? loopKeyElem.textContent.split(':') :
$(loopKeyElem).html().split(':');
loopKeyName = loopSplit[0];
this.addClassToElement(loopKeyElem, 'key');
this.addClassToElement(loopKeyElem, loopKeyName + '-key');
this.addClassToElement(loopValElem, 'value');
this.addClassToElement(loopValElem, loopKeyName + '-value');
}
} | javascript | {
"resource": ""
} | |
q28633 | train | function(properties, data) {
var useTimeNames = (this.processedData.xAxisType === 'time'),
resolveLabel = this.getLabel.bind(this);
this.formatTooltip(properties, data);
$.extend(true, this.hcConfig, {
plotOptions: {
pie: {
dataLabels: {
formatter: function() {
return Splunk.JSCharting.ParsingUtils.escapeHtml(resolveLabel(this, useTimeNames));
}
}
}
}
});
} | javascript | {
"resource": ""
} | |
q28634 | train | function(list, map, legendSize) {
var hexColor;
this.colorList = [];
this.hcConfig.colors = [];
for(i = 0; i < list.length; i++) {
hexColor = this.colorPalette.getColor(list[i], map[list[i]], legendSize);
this.colorList.push(hexColor);
this.hcConfig.colors.push(this.colorUtils.addAlphaToColor(hexColor, 1.0));
}
} | javascript | {
"resource": ""
} | |
q28635 | train | function(ticks) {
var key,
tickArray = [];
for(key in ticks) {
if(ticks.hasOwnProperty(key)) {
tickArray.push(ticks[key]);
}
}
tickArray.sort(function(t1, t2) {
return (t1.pos - t2.pos);
});
return tickArray;
} | javascript | {
"resource": ""
} | |
q28636 | train | function(options, extremes) {
// if there are no extremes (i.e. no meaningful data was extracted), go with 0 to 100
if(!extremes.min && !extremes.max) {
options.min = 0;
options.max = 100;
return;
}
// if the min or max is such that no data makes it onto the chart, we hard-code some reasonable extremes
if(extremes.min > extremes.dataMax && extremes.min > 0 && this.userMax === Infinity) {
options.max = (this.logScale) ? extremes.min + 2 : extremes.min * 2;
return;
}
if(extremes.max < extremes.dataMin && extremes.max < 0 && this.userMin === -Infinity) {
options.min = (this.logScale) ? extremes.max - 2 : extremes.max * 2;
return;
}
// if either data extreme is exactly zero, remove the padding on that side so the axis doesn't extend beyond zero
if(extremes.dataMin === 0 && this.userMin === -Infinity) {
options.min = 0;
options.minPadding = 0;
}
if(extremes.dataMax === 0 && this.userMax === Infinity) {
options.max = 0;
options.maxPadding = 0;
}
} | javascript | {
"resource": ""
} | |
q28637 | train | function(startVal, endVal, drawFn, finishCallback) {
var animationRange = endVal - startVal,
duration = 500,
animationProperties = {
duration: duration,
step: function(now, fx) {
drawFn(startVal + now);
this.nudgeChart();
}.bind(this)
};
if(finishCallback) {
animationProperties.complete = function() {
finishCallback(endVal);
};
}
// for the animation start and end values, use 0 and animationRange for consistency with the way jQuery handles
// css properties that it doesn't recognize
$(this.renderTo)
.stop(true, true)
.css({'animation-progress': 0})
.animate({'animation-progress': animationRange}, animationProperties);
} | javascript | {
"resource": ""
} | |
q28638 | train | function($super, oldValue, newValue) {
var oldPrecision = this.mathUtils.getDecimalPrecision(oldValue, 3),
newPrecision = this.mathUtils.getDecimalPrecision(newValue, 3);
this.valueAnimationPrecision = Math.max(oldPrecision, newPrecision);
$super(oldValue, newValue);
} | javascript | {
"resource": ""
} | |
q28639 | train | function(fillColor) {
var fillColorHex = this.colorUtils.hexFromColor(fillColor),
luminanceThreshold = 128,
darkColor = 'black',
lightColor = 'white',
fillLuminance = this.colorUtils.getLuminance(fillColorHex);
return (fillLuminance < luminanceThreshold) ? lightColor : darkColor;
} | javascript | {
"resource": ""
} | |
q28640 | train | function(num) {
var result = Math.log(num) / Math.LN10;
return (Math.round(result * 10000) / 10000);
} | javascript | {
"resource": ""
} | |
q28641 | train | function(num) {
if(typeof num !== "number") {
return NaN;
}
var isNegative = (num < 0),
result;
if(isNegative) {
num = -num;
}
if(num < 10) {
num += (10 - num) / 10;
}
result = this.logBaseTen(num);
return (isNegative) ? -result : result;
} | javascript | {
"resource": ""
} | |
q28642 | train | function(num) {
if(typeof num !== "number") {
return NaN;
}
var isNegative = (num < 0),
result;
if(isNegative) {
num = -num;
}
result = Math.pow(10, num);
if(result < 10) {
result = 10 * (result - 1) / (10 - 1);
}
result = (isNegative) ? -result : result;
return (Math.round(result * 1000) / 1000);
} | javascript | {
"resource": ""
} | |
q28643 | train | function(num) {
if(typeof num !== "number") {
return NaN;
}
var isNegative = num < 0;
num = (isNegative) ? -num : num;
var log = this.logBaseTen(num),
result = Math.pow(10, Math.floor(log));
return (isNegative) ? -result: result;
} | javascript | {
"resource": ""
} | |
q28644 | train | function(num, max) {
max = max || Infinity;
var precision = 0;
while(precision < max && num.toFixed(precision) !== num.toString()) {
precision += 1;
}
return precision;
} | javascript | {
"resource": ""
} | |
q28645 | train | function(isoString, pointSpan) {
var i18n = Splunk.JSCharting.i18nUtils,
bdTime = this.extractBdTime(isoString),
dateObject;
if(bdTime.isInvalid) {
return null;
}
dateObject = this.bdTimeToDateObject(bdTime);
if (pointSpan >= this.MIN_SECS_PER_DAY) { // day or larger
return i18n.format_date(dateObject);
}
else if (pointSpan >= this.SECS_PER_MIN) { // minute or longer
return format_datetime(dateObject, 'medium', 'short');
}
return format_datetime(dateObject);
} | javascript | {
"resource": ""
} | |
q28646 | train | function(hexNum, alpha) {
if(typeof hexNum !== "number") {
hexNum = parseInt(hexNum, 16);
}
if(isNaN(hexNum) || hexNum < 0x000000 || hexNum > 0xffffff) {
return undefined;
}
var r = (hexNum & 0xff0000) >> 16,
g = (hexNum & 0x00ff00) >> 8,
b = hexNum & 0x0000ff;
return ((alpha === undefined) ? ("rgb(" + r + "," + g + "," + b + ")") : ("rgba(" + r + "," + g + "," + b + "," + alpha + ")"));
} | javascript | {
"resource": ""
} | |
q28647 | train | function(color) {
var normalizedColor = Splunk.util.normalizeColor(color);
return (normalizedColor) ? parseInt(normalizedColor.replace("#", "0x"), 16) : 0;
} | javascript | {
"resource": ""
} | |
q28648 | train | function(rgbaStr) {
// lazy create the regex
if(!this.rgbaRegex) {
this.rgbaRegex = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,[\s\d.]+\)\s*$/;
}
var colorComponents = this.rgbaRegex.exec(rgbaStr);
if(!colorComponents) {
return rgbaStr;
}
return ("rgb(" + colorComponents[1] + ", " + colorComponents[2] + ", " + colorComponents[3] + ")");
} | javascript | {
"resource": ""
} | |
q28649 | train | function(properties) {
var key, newKey,
remapped = {},
axisProps = this.filterPropsByRegex(properties, /(axisX|primaryAxis|axisLabelsX|axisTitleX|gridLinesX)/);
for(key in axisProps) {
if(axisProps.hasOwnProperty(key)) {
if(!this.xAxisKeyIsTrumped(key, properties)) {
newKey = key.replace(/(axisX|primaryAxis)/, "axis");
newKey = newKey.replace(/axisLabelsX/, "axisLabels");
newKey = newKey.replace(/axisTitleX/, "axisTitle");
newKey = newKey.replace(/gridLinesX/, "gridLines");
remapped[newKey] = axisProps[key];
}
}
}
return remapped;
} | javascript | {
"resource": ""
} | |
q28650 | train | function(key, properties) {
if(!(/primaryAxis/.test(key))) {
return false;
}
if(/primaryAxisTitle/.test(key)) {
return properties[key.replace(/primaryAxisTitle/, "axisTitleX")];
}
return properties[key.replace(/primaryAxis/, "axisX")];
} | javascript | {
"resource": ""
} | |
q28651 | train | function(properties) {
var key, newKey,
remapped = {},
axisProps = this.filterPropsByRegex(properties, /(axisY|secondaryAxis|axisLabelsY|axisTitleY|gridLinesY)/);
for(key in axisProps) {
if(axisProps.hasOwnProperty(key)) {
if(!this.yAxisKeyIsTrumped(key, properties)) {
newKey = key.replace(/(axisY|secondaryAxis)/, "axis");
newKey = newKey.replace(/axisLabelsY/, "axisLabels");
newKey = newKey.replace(/axisTitleY/, "axisTitle");
newKey = newKey.replace(/gridLinesY/, "gridLines");
remapped[newKey] = axisProps[key];
}
}
}
return remapped;
} | javascript | {
"resource": ""
} | |
q28652 | train | function(key, properties) {
if(!(/secondaryAxis/.test(key))) {
return false;
}
if(/secondaryAxisTitle/.test(key)) {
return properties[key.replace(/secondaryAxisTitle/, "axisTitleY")];
}
return properties[key.replace(/secondaryAxis/, "axisY")];
} | javascript | {
"resource": ""
} | |
q28653 | train | function(props, regex) {
if(!(regex instanceof RegExp)) {
return props;
}
var key,
filtered = {};
for(key in props) {
if(props.hasOwnProperty(key) && regex.test(key)) {
filtered[key] = props[key];
}
}
return filtered;
} | javascript | {
"resource": ""
} | |
q28654 | train | function(array1, array2) {
// make sure these are actually arrays
if(!(array1 instanceof Array) || !(array2 instanceof Array)) {
return false;
}
if(array1 === array2) {
// true if they are the same object
return true;
}
if(array1.length !== array2.length) {
// false if they are different lengths
return false;
}
// false if any of their elements don't match
for(var i = 0; i < array1.length; i++) {
if(array1[i] !== array2[i]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} | |
q28655 | train | function(date, format) {
var i, replacements,
locale = locale_name();
if(format && locale_uses_day_before_month()) {
replacements = this.DAY_FIRST_FORMATS;
for(i = 0; i < replacements.length; i++) {
format = format.replace(replacements[i][0], replacements[i][1]);
}
}
if(format && locale in this.CUSTOM_LOCALE_FORMATS) {
replacements = this.CUSTOM_LOCALE_FORMATS[locale];
for(i = 0; i < replacements.length; i++) {
format = format.replace(replacements[i][0], replacements[i][1]);
}
}
return format_date(date, format);
} | javascript | {
"resource": ""
} | |
q28656 | train | function(args) {
args = this.trim(args, '&\?#');
var parts = args.split('&');
var output = {};
var key;
var value;
var equalsSegments;
var lim = parts.length;
for (var i=0,l=lim; i<l; i++) {
equalsSegments = parts[i].split('=');
key = decodeURIComponent(equalsSegments.shift());
value = equalsSegments.join("=");
output[key] = decodeURIComponent(value);
}
return output;
} | javascript | {
"resource": ""
} | |
q28657 | train | function(){
var hashPos = window.location.href.indexOf('#');
if (hashPos == -1) {
return "";
}
var qPos = window.location.href.indexOf('?', hashPos);
if (qPos != -1)
return window.location.href.substr(qPos);
return window.location.href.substr(hashPos);
} | javascript | {
"resource": ""
} | |
q28658 | train | function(serverOffsetThen, d) {
if (!Splunk.util.isInt(serverOffsetThen)) {
return 0;
}
// what JS thinks the timezone offset is at the time given by d. This WILL INCLUDE DST
var clientOffsetThen = d.getTimezoneOffset() * 60;
// what splunkd told is the actual timezone offset.
serverOffsetThen = serverOffsetThen * -60;
return 1000 * (serverOffsetThen - clientOffsetThen);
} | javascript | {
"resource": ""
} | |
q28659 | train | function() {
var output = '', seg, len;
for (var i=0,l=arguments.length; i<l; i++) {
seg = arguments[i].toString();
len = seg.length;
if (len > 1 && seg.charAt(len-1) == '/') {
seg = seg.substring(0, len-1);
}
if (seg.charAt(0) != '/') {
output += '/' + seg;
} else {
output += seg;
}
}
// augment static dirs with build number
if (output!='/') {
var segments = output.split('/');
var firstseg = segments[1];
if (firstseg=='static' || firstseg=='modules') {
var postfix = output.substring(firstseg.length+2, output.length);
output = '/'+firstseg+'/@' + window.$C['BUILD_NUMBER'];
if (window.$C['BUILD_PUSH_NUMBER']) output += '.' + window.$C['BUILD_PUSH_NUMBER'];
if (segments[2] == 'app')
output += ':'+this.getConfigValue('APP_BUILD', 0);
output += '/' + postfix;
}
}
var root = Splunk.util.getConfigValue('MRSPARKLE_ROOT_PATH', '/');
var locale = Splunk.util.getConfigValue('LOCALE', 'en-US');
if (root == '' || root == '/') {
return '/' + locale + output;
} else {
return root + '/' + locale + output;
}
} | javascript | {
"resource": ""
} | |
q28660 | train | function(url, options) {
url = this.make_url(url);
if (options) url = url + '?' + this.propToQueryString(options);
return url;
} | javascript | {
"resource": ""
} | |
q28661 | train | function(uri, options, windowObj, focus) {
uri = this.make_full_url(uri, options);
if (!windowObj) windowObj = window;
windowObj.document.location = uri;
if (focus && windowObj.focus) windowObj.focus();
return;
} | javascript | {
"resource": ""
} | |
q28662 | train | function(path) {
if (path === undefined) {
path = document.location.pathname;
}
var locale = this.getConfigValue('LOCALE').toString();
// if there is no way to figure out the locale, just return pathname
if (!this.getConfigValue('LOCALE') || path.indexOf(locale) == -1) {
return path;
}
var start = locale.length + path.indexOf(locale);
return path.slice(start);
} | javascript | {
"resource": ""
} | |
q28663 | train | function(){
var pageYOffset = 0;
if(window.pageYOffset){
pageYOffset = window.pageYOffset;
}else if(document.documentElement && document.documentElement.scrollTop){
pageYOffset = document.documentElement.scrollTop;
}
return pageYOffset;
} | javascript | {
"resource": ""
} | |
q28664 | train | function(){
return {
width:(!isNaN(window.innerWidth))?window.innerWidth:document.documentElement.clientWidth||0,
height:(!isNaN(window.innerHeight))?window.innerHeight:document.documentElement.clientHeight||0
};
} | javascript | {
"resource": ""
} | |
q28665 | train | function(el, styleProperty){
if(el.currentStyle){
return el.currentStyle[styleProperty];
}else if(window.getComputedStyle){
var cssProperty = styleProperty.replace(/([A-Z])/g, "-$1").toLowerCase();
var computedStyle = window.getComputedStyle(el, "");
return computedStyle.getPropertyValue(cssProperty);
}else{
return "";
}
} | javascript | {
"resource": ""
} | |
q28666 | train | function(p, s){
s = s || window.location.search;
if(!s){
return null;
}
if(!(s.indexOf(p+'=')+1)){
return null;
}
return s.split(p+'=')[1].split('&')[0];
} | javascript | {
"resource": ""
} | |
q28667 | train | function(rgb){
var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var hex = (parts[1]<<16|parts[2]<<8|parts[3]).toString(16);
return "#"+Array(6-hex.length).concat([hex]).toString().replace(/,/g, 0);
} | javascript | {
"resource": ""
} | |
q28668 | train | function(target, innerHTML) {
/*@cc_on //innerHTML is faster for IE
target.innerHTML = innerHTML;
return target;
@*/
var targetClone = target.cloneNode(false);
targetClone.innerHTML = innerHTML;
target.parentNode.replaceChild(targetClone, target);
return targetClone;
} | javascript | {
"resource": ""
} | |
q28669 | train | function(q, isUserEntered) {
var workingQ = '' + q;
workingQ = workingQ.replace(this.reLTrim, '').replace(this.reRNormalize, ' ');
if (workingQ.substring(0, 1) == '|') {
return q;
}
// this is specific to the case where searchstring = 'search ',
// which we conservatively assume does not constitute a search command
if (!isUserEntered
&& (workingQ.substring(0, 7) == 'search ' && workingQ.length > 7))
{
return q;
}
return 'search ' + workingQ;
} | javascript | {
"resource": ""
} | |
q28670 | train | function(q) {
var workingQ = '' + q;
workingQ = workingQ.replace(this.reLTrimCommand, '');
if (workingQ.substring(0, 7) == 'search ') {
return workingQ.substring(7).replace(this.reLTrimCommand, '');
}
return q;
} | javascript | {
"resource": ""
} | |
q28671 | train | function(strList) {
if (typeof(strList) != 'string' || !strList) return [];
var items = [];
var field_name_buffer = [];
var inquote = false;
var str = $.trim(strList);
for (var i=0,j=str.length; i<j; i++) {
if (str.charAt(i) == '\\') {
var nextidx = i+1;
if (j > nextidx && (str.charAt(nextidx) == '\\' || str.charAt(nextidx) == '"')) {
field_name_buffer.push(str.charAt(nextidx));
i++;
continue;
} else {
field_name_buffer.push(str.charAt(i));
continue;
}
}
if (str.charAt(i) == '"') {
if (!inquote) {
inquote = true;
continue;
} else {
inquote = false;
items.push(field_name_buffer.join(''));
field_name_buffer = [];
continue;
}
}
if ((str.charAt(i) == ' ' || str.charAt(i) == ',') && !inquote) {
if (field_name_buffer.length > 0) {
items.push(field_name_buffer.join(''));
}
field_name_buffer = [];
continue;
}
field_name_buffer.push(str.charAt(i));
}
if (field_name_buffer.length > 0) items.push(field_name_buffer.join(''));
return items;
} | javascript | {
"resource": ""
} | |
q28672 | train | function(obj1, obj2){
if(obj1 instanceof Array && obj2 instanceof Array){
if(obj1.length!==obj2.length){
return false;
}else{
for(var i=0; i<obj1.length; i++){
if(!this.objectSimilarity(obj1[i], obj2[i])){
return false;
}
}
}
}else if(obj1 instanceof Object && obj2 instanceof Object){
if(obj1!=obj2){
for(var j in obj2){
if(!obj1.hasOwnProperty(j)){
return false;
}
}
for(var k in obj1){
if(obj1.hasOwnProperty(k)){
if(obj2.hasOwnProperty(k)){
if(!this.objectSimilarity(obj1[k], obj2[k])){
return false;
}
}else{
return false;
}
}
}
}
}else if(typeof(obj1)==="function" && typeof(obj2)==="function"){
if(obj1.toString()!==obj2.toString()){
return false;
}
}else if(obj1!==obj2){
return false;
}
return true;
} | javascript | {
"resource": ""
} | |
q28673 | train | function(){
var self = this,
startTime = null,
stopTime = null,
times = [];
var isSet = function(prop){
return (prop==null)?false:true;
};
var isStarted = function(){
return isSet(startTime);
};
var isStopped = function(){
return isSet(stopTime);
};
var softReset = function(){
startTime = null;
stopTime = null;
};
self.start = function(){
if(isStarted()){
throw new Error("cannot call start, start already invoked.");
}
startTime = new Date();
};
self.stop = function(){
if(!isStarted()){
throw new Error("cannot call stop, start not invoked.");
}
if(isStopped()){
throw new Error("cannot call stop, stop already invoked.");
}
stopTime = new Date();
time = stopTime - startTime;
times.push(time);
};
self.pause = function(){
if(!isStarted()){
throw new Error("cannot call pause, start not invoked.");
}
if(isStopped()){
throw new Error("cannot call pause, stop already invoked.");
}
self.stop();
softReset();
};
self.reset = function(){
softReset();
times = [];
};
self.time = function(){
var total = 0;
for(i=0; i<times.length; i++){
total += times[i];
}
if(isStarted() && !isStopped()){
total += (new Date() - startTime);
}
return total/1000;
};
} | javascript | {
"resource": ""
} | |
q28674 | train | function(string, maxLength) {
if (!string) return string;
if (maxLength < 1) return string;
if (string.length <= maxLength) return string;
if (maxLength == 1) return string.substring(0,1) + '...';
var midpoint = Math.ceil(string.length / 2);
var toremove = string.length - maxLength;
var lstrip = Math.ceil(toremove/2);
var rstrip = toremove - lstrip;
return string.substring(0, midpoint-lstrip) + '...' + string.substring(midpoint+rstrip);
} | javascript | {
"resource": ""
} | |
q28675 | train | function(fragment, reg, value) {
if (typeof fragment == 'string') {
if (fragment.match(reg)) {
fragment = fragment.replace(reg, value);
}
return fragment;
}
else if (typeof fragment == "function") {
return fragment;
}
// watch out for infinite loops. We make all changes to the array after iteration.
var keysToRename = {};
for (var key in fragment) {
// recurse
if (typeof fragment[key] == 'object') {
Splunk.util.replaceTokens(fragment[key], reg, value);
}
// we have hit a string value.
else if (typeof fragment[key] == 'string' && fragment[key].match(reg)) {
fragment[key] = fragment[key].replace(reg, value);
}
// now that the value is changed we check the key itself
if (key.match(reg)) {
// mark this to be changed after we're out of the iterator
keysToRename[key] = key.replace(reg, value);
}
}
for (oldKey in keysToRename) {
var newKey = keysToRename[oldKey];
fragment[newKey] = fragment[oldKey];
delete(fragment[oldKey]);
}
return fragment;
} | javascript | {
"resource": ""
} | |
q28676 | extend | train | function extend(a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
} | javascript | {
"resource": ""
} |
q28677 | erase | train | function erase(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
} | javascript | {
"resource": ""
} |
q28678 | attr | train | function attr(elem, prop, value) {
var key,
setAttribute = 'setAttribute',
ret;
// if the prop is a string
if (isString(prop)) {
// set the value
if (defined(value)) {
elem[setAttribute](prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (defined(prop) && isObject(prop)) {
for (key in prop) {
elem[setAttribute](key, prop[key]);
}
}
return ret;
} | javascript | {
"resource": ""
} |
q28679 | css | train | function css(el, styles) {
if (isIE) {
if (styles && styles.opacity !== UNDEFINED) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
extend(el.style, styles);
} | javascript | {
"resource": ""
} |
q28680 | createElement | train | function createElement(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag);
if (attribs) {
extend(el, attribs);
}
if (nopad) {
css(el, {padding: 0, border: NONE, margin: 0});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
} | javascript | {
"resource": ""
} |
q28681 | getPosition | train | function getPosition(el) {
var p = { left: el.offsetLeft, top: el.offsetTop };
el = el.offsetParent;
while (el) {
p.left += el.offsetLeft;
p.top += el.offsetTop;
if (el !== doc.body && el !== doc.documentElement) {
p.left -= el.scrollLeft;
p.top -= el.scrollTop;
}
el = el.offsetParent;
}
return p;
} | javascript | {
"resource": ""
} |
q28682 | placeBox | train | function placeBox(boxWidth, boxHeight, outerLeft, outerTop, outerWidth, outerHeight, point) {
// keep the box within the chart area
var pointX = point.x,
pointY = point.y,
x = pointX - boxWidth + outerLeft - 25,
y = pointY - boxHeight + outerTop + 10,
alignedRight;
// it is too far to the left, adjust it
if (x < 7) {
x = outerLeft + pointX + 15;
}
// Test to see if the tooltip is to far to the right,
// if it is, move it back to be inside and then up to not cover the point.
if ((x + boxWidth) > (outerLeft + outerWidth)) {
// PATCH by Simon Fishel
//
// if the tooltip is too wide for the plot area, clip it left not right
//
// - x -= (x + boxWidth) - (outerLeft + outerWidth);
// + if(boxWidth > outerWidth) {
// + x = 7;
// + }
// + else {
// + x -= (x + boxWidth) - (outerLeft + outerWidth);
// + }
if(boxWidth > outerWidth) {
x = 7;
}
else {
x -= (x + boxWidth) - (outerLeft + outerWidth);
}
y -= boxHeight;
alignedRight = true;
}
if (y < 5) {
y = 5; // above
// If the tooltip is still covering the point, move it below instead
if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) {
y = pointY + boxHeight - 5; // below
}
} else if (y + boxHeight > outerTop + outerHeight) {
y = outerTop + outerHeight - boxHeight - 5; // below
}
return {x: x, y: y};
} | javascript | {
"resource": ""
} |
q28683 | stableSort | train | function stableSort(arr, sortFunction) {
var length = arr.length,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].ss_i = i; // stable sort index
}
arr.sort(function (a, b) {
var sortValue = sortFunction(a, b);
return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].ss_i; // stable sort index
}
} | javascript | {
"resource": ""
} |
q28684 | train | function (start, end, pos, complete) {
var ret = [],
i = start.length,
startVal;
if (pos === 1) { // land on the final path without adjustment points appended in the ends
ret = complete;
} else if (i === end.length && pos < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
pos * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
return ret;
} | javascript | {
"resource": ""
} | |
q28685 | train | function () {
var element = this.element,
childNodes = element.childNodes,
i = childNodes.length;
while (i--) {
element.removeChild(childNodes[i]);
}
} | javascript | {
"resource": ""
} | |
q28686 | train | function (points, width) {
// points format: [M, 0, 0, L, 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
points[1] = points[4] = mathRound(points[1]) + (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
}
return points;
} | javascript | {
"resource": ""
} | |
q28687 | train | function (x, y, r, innerR, start, end) {
// arcs are defined as symbols for the ability to set
// attributes in attr and animate
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
return this.symbol('arc', x || 0, y || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
} | javascript | {
"resource": ""
} | |
q28688 | train | function (name) {
var elem = this.createElement('g');
return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
} | javascript | {
"resource": ""
} | |
q28689 | train | function (x, y, width, height) {
var wrapper,
id = PREFIX + idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
return wrapper;
} | javascript | {
"resource": ""
} | |
q28690 | train | function (color, elem, prop) {
var colorObject,
regexRgba = /^rgba/;
if (color && color.linearGradient) {
var renderer = this,
strLinearGradient = 'linearGradient',
linearGradient = color[strLinearGradient],
id = PREFIX + idCounter++,
gradientObject,
stopColor,
stopOpacity;
gradientObject = renderer.createElement(strLinearGradient).attr({
id: id,
gradientUnits: 'userSpaceOnUse',
x1: linearGradient[0],
y1: linearGradient[1],
x2: linearGradient[2],
y2: linearGradient[3]
}).add(renderer.defs);
// Keep a reference to the gradient object so it is possible to destroy it later
renderer.gradients.push(gradientObject);
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(color.stops, function (stop) {
var stopObject;
if (regexRgba.test(stop[1])) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
return 'url(' + this.url + '#' + id + ')';
// Webkit and Batik can't show rgba.
} else if (regexRgba.test(color)) {
colorObject = Color(color);
attr(elem, prop + '-opacity', colorObject.get('a'));
return colorObject.get('rgb');
} else {
// Remove the opacity attribute added above. Does not throw if the attribute is not there.
elem.removeAttribute(prop + '-opacity');
return color;
}
} | javascript | {
"resource": ""
} | |
q28691 | train | function (renderer, nodeName) {
var markup = ['<', nodeName, ' filled="f" stroked="f"'],
style = ['position: ', ABSOLUTE, ';'];
// divs and shapes need size
if (nodeName === 'shape' || nodeName === DIV) {
style.push('left:0;top:0;width:10px;height:10px;');
}
if (docMode8) {
style.push('visibility: ', nodeName === DIV ? HIDDEN : VISIBLE);
}
markup.push(' style="', style.join(''), '"/>');
// create element with default attributes and style
if (nodeName) {
markup = nodeName === DIV || nodeName === 'span' || nodeName === 'img' ?
markup.join('')
: renderer.prepVML(markup);
this.element = createElement(markup);
}
this.renderer = renderer;
} | javascript | {
"resource": ""
} | |
q28692 | train | function () {
var wrapper = this;
if (wrapper.destroyClip) {
wrapper.destroyClip();
}
return SVGElement.prototype.destroy.apply(wrapper);
} | javascript | {
"resource": ""
} | |
q28693 | train | function (eventType, handler) {
// simplest possible event model for internal use
this.element['on' + eventType] = function () {
var evt = win.event;
evt.target = evt.srcElement;
handler(evt);
};
return this;
} | javascript | {
"resource": ""
} | |
q28694 | train | function (str, x, y) {
var defaultChartStyle = defaultOptions.chart.style;
return this.createElement('span')
.attr({
text: str,
x: mathRound(x),
y: mathRound(y)
})
.css({
whiteSpace: 'nowrap',
fontFamily: defaultChartStyle.fontFamily,
fontSize: defaultChartStyle.fontSize
});
} | javascript | {
"resource": ""
} | |
q28695 | train | function () {
var value = this.value,
ret;
if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (tickInterval % 1000000 === 0) { // use M abbreviation
ret = (value / 1000000) + 'M';
} else if (tickInterval % 1000 === 0) { // use k abbreviation
ret = (value / 1000) + 'k';
} else if (!categories && value >= 1000) { // add thousands separators
ret = numberFormat(value, 0);
} else { // strings (categories) and small numbers
ret = value;
}
return ret;
} | javascript | {
"resource": ""
} | |
q28696 | Tick | train | function Tick(pos, minor) {
var tick = this;
tick.pos = pos;
tick.minor = minor;
tick.isNew = true;
if (!minor) {
tick.addLabel();
}
} | javascript | {
"resource": ""
} |
q28697 | StackItem | train | function StackItem(options, isNegative, x, stackOption) {
var stackItem = this;
// Tells if the stack is negative
stackItem.isNegative = isNegative;
// Save the options to be able to style the label
stackItem.options = options;
// Save the x value to be able to position the label later
stackItem.x = x;
// Save the stack option on the series configuration object
stackItem.stack = stackOption;
// The align options and text align varies on whether the stack is negative and
// if the chart is inverted or not.
// First test the user supplied value, then use the dynamic.
stackItem.alignOptions = {
align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
};
stackItem.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
} | javascript | {
"resource": ""
} |
q28698 | correctFloat | train | function correctFloat(num) {
var invMag, ret = num;
magnitude = pick(magnitude, math.pow(10, mathFloor(math.log(tickInterval) / math.LN10)));
if (magnitude < 1) {
invMag = mathRound(1 / magnitude) * 10;
ret = mathRound(num * invMag) / invMag;
}
return ret;
} | javascript | {
"resource": ""
} |
q28699 | setCategories | train | function setCategories(newCategories, doRedraw) {
// set the categories
axis.categories = userOptions.categories = categories = newCategories;
// force reindexing tooltips
each(associatedSeries, function (series) {
series.translate();
series.setTooltipPoints(true);
});
// optionally redraw
axis.isDirty = true;
if (pick(doRedraw, true)) {
chart.redraw();
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.