_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q20000 | createDatepickerInstance | train | function createDatepickerInstance(template) {
var outputElement = $compile(template)(pageScope);
pageScope.$apply();
ngElement = outputElement[0].tagName == 'MD-DATEPICKER' ?
outputElement : outputElement.find('md-datepicker');
element = ngElement[0];
scope = ngElement.isolateScope();
c... | javascript | {
"resource": ""
} |
q20001 | buildJs | train | function buildJs() {
const jsFiles = config.jsCoreFiles;
config.componentPaths.forEach(component => {
jsFiles.push(path.join(component, '*.js'));
jsFiles.push(path.join(component, '**/*.js'));
});
gutil.log("building js files...");
const jsBuildStream = gulp.src(jsFiles)
.pipe(filterNonCodeFiles()... | javascript | {
"resource": ""
} |
q20002 | deployMaterialMocks | train | function deployMaterialMocks() {
return gulp.src(config.mockFiles)
.pipe(gulp.dest(config.outputDir));
} | javascript | {
"resource": ""
} |
q20003 | themeBuildStream | train | function themeBuildStream() {
// Make a copy so that we don't modify the actual config that is used by other functions
var paths = config.themeBaseFiles.slice(0);
config.componentPaths.forEach(component => paths.push(path.join(component, '*-theme.scss')));
paths.push(config.themeCore);
return gulp.src(paths)... | javascript | {
"resource": ""
} |
q20004 | dedupeCss | train | function dedupeCss() {
const prefixRegex = /-(webkit|moz|ms|o)-.+/;
return insert.transform(function(contents) {
// Parse the CSS into an AST.
const parsed = postcss.parse(contents);
// Walk through all the rules, skipping comments, media queries etc.
parsed.walk(function(rule) {
// Skip ove... | javascript | {
"resource": ""
} |
q20005 | validateProp | train | function validateProp(prop) {
return prop && prop.type === 'decl' && ![prop.prop, prop.value].some(function(value) {
return value.indexOf('-') > -1 && prefixRegex.test(value);
});
} | javascript | {
"resource": ""
} |
q20006 | add | train | function add(item, index) {
if (!item) return -1;
if (!angular.isNumber(index)) {
index = _items.length;
}
_items.splice(index, 0, item);
return indexOf(item);
} | javascript | {
"resource": ""
} |
q20007 | findSubsequentItem | train | function findSubsequentItem(backwards, item, validate, limit) {
validate = validate || trueFn;
var curIndex = indexOf(item);
while (true) {
if (!inRange(curIndex)) return null;
var nextIndex = curIndex + (backwards ? -1 : 1);
var foundItem = null;
if (inRange(nextInde... | javascript | {
"resource": ""
} |
q20008 | preLink | train | function preLink(scope, element, attr, ctrls) {
var selectCtrl = ctrls[0];
element.addClass('_md'); // private md component indicator for styling
$mdTheming(element);
element.on('click', clickListener);
element.on('keypress', keyListener);
function keyListener(e) {
if (e.keyCode == ... | javascript | {
"resource": ""
} |
q20009 | cleanElement | train | function cleanElement() {
destroyListener();
element
.removeClass('md-active')
.attr('aria-hidden', 'true')
.css({
'display': 'none',
'top': '',
'right': '',
'bottom': '',
'left': '',
'font-size': '',
... | javascript | {
"resource": ""
} |
q20010 | mouseOnScrollbar | train | function mouseOnScrollbar() {
var clickOnScrollbar = false;
if (ev && (ev.currentTarget.children.length > 0)) {
var child = ev.currentTarget.children[0];
var hasScrollbar = child.scrollHeight > child.clientHeight;
if (hasScrollbar && child.children.lengt... | javascript | {
"resource": ""
} |
q20011 | register | train | function register(element, handlerName, options) {
var handler = HANDLERS[handlerName.replace(/^\$md./, '')];
if (!handler) {
throw new Error('Failed to register element with handler ' + handlerName + '. ' +
'Available handlers: ' + Object.keys(HANDLERS).join(', '));
}
return handler.registe... | javascript | {
"resource": ""
} |
q20012 | train | function (ev, pointer) {
if (this.state.isRunning) return;
var parentTarget = this.getNearestParent(ev.target);
// Get the options from the nearest registered parent
var parentTargetOptions = parentTarget && parentTarget.$mdGesture[this.name] || {};
this.state = {
isRunning: true,... | javascript | {
"resource": ""
} | |
q20013 | isInputEventFromLabelClick | train | function isInputEventFromLabelClick(event) {
return lastLabelClickPos
&& lastLabelClickPos.x == event.x
&& lastLabelClickPos.y == event.y;
} | javascript | {
"resource": ""
} |
q20014 | getEventPoint | train | function getEventPoint(ev) {
ev = ev.originalEvent || ev; // support jQuery events
return (ev.touches && ev.touches[0]) ||
(ev.changedTouches && ev.changedTouches[0]) ||
ev;
} | javascript | {
"resource": ""
} |
q20015 | canFocus | train | function canFocus(element) {
return (
!!element &&
element.getAttribute('tabindex') !== '-1' &&
!element.hasAttribute('disabled') &&
(
element.hasAttribute('tabindex') ||
element.hasAttribute('href') ||
element.isContentEditable ||
['INPUT', 'SELECT', 'BUTTON', 'TEXTAREA', 'VID... | javascript | {
"resource": ""
} |
q20016 | handleDemoIndexFile | train | function handleDemoIndexFile() {
files.index.contentsPromise.then(function(contents) {
demoContainer = angular.element(
'<div class="demo-content ' + ngModule + '">'
);
var isStandalone = !!ngModule;
var demoScope;
var demoCompileService;
if (isStandalone... | javascript | {
"resource": ""
} |
q20017 | handleDemoStyles | train | function handleDemoStyles() {
return $q.all(files.css.map(function(file) {
return file.contentsPromise;
}))
.then(function(styles) {
styles = styles.join('\n'); // join styles as one string
var styleElement = angular.element('<style>' + styles + '</style>');
document.b... | javascript | {
"resource": ""
} |
q20018 | handleDemoTemplates | train | function handleDemoTemplates() {
return $q.all(files.html.map(function(file) {
return file.contentsPromise.then(function(contents) {
// Get the $templateCache instance that goes with the demo's specific ng-app.
var demoTemplateCache = demoContainer.injector().get('$templateCache');
... | javascript | {
"resource": ""
} |
q20019 | findInstance | train | function findInstance(handle, shouldWait) {
var instance = $mdComponentRegistry.get(handle);
if (!instance && !shouldWait) {
// Report missing instance
$log.error($mdUtil.supplant(errorMsg, [handle || ""]));
// The component has not registered itself... most like NOT yet created
// ret... | javascript | {
"resource": ""
} |
q20020 | toggleOpen | train | function toggleOpen(isOpen) {
if (scope.isOpen === isOpen) {
return $q.when(true);
} else {
if (scope.isOpen && sidenavCtrl.onCloseCb) sidenavCtrl.onCloseCb();
return $q(function(resolve) {
// Toggle value to force an async `updateIsOpen()` to run
scope.isOpen = ... | javascript | {
"resource": ""
} |
q20021 | onKeyDown | train | function onKeyDown(ev) {
var isEscape = (ev.keyCode === $mdConstant.KEY_CODE.ESCAPE);
return isEscape ? close(ev) : $q.when(true);
} | javascript | {
"resource": ""
} |
q20022 | mdCalendarMonthBodyDirective | train | function mdCalendarMonthBodyDirective($compile, $$mdSvgRegistry) {
var ARROW_ICON = $compile('<md-icon md-svg-src="' +
$$mdSvgRegistry.mdTabsArrow + '"></md-icon>')({})[0];
return {
require: ['^^mdCalendar', '^^mdCalendarMonth', 'mdCalendarMonthBody'],
scope: { offset: '=mdMonthOffset' },
... | javascript | {
"resource": ""
} |
q20023 | CalendarMonthBodyCtrl | train | function CalendarMonthBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @type {Object} Reference to the month view. */
this.monthCtr... | javascript | {
"resource": ""
} |
q20024 | mdCalendarYearDirective | train | function mdCalendarYearDirective() {
return {
require: ['^^mdCalendar', '^^mdCalendarYear', 'mdCalendarYearBody'],
scope: { offset: '=mdYearOffset' },
controller: CalendarYearBodyCtrl,
controllerAs: 'mdYearBodyCtrl',
bindToController: true,
link: function(scope, element, attrs, c... | javascript | {
"resource": ""
} |
q20025 | CalendarYearBodyCtrl | train | function CalendarYearBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @type {Object} Reference to the calendar. */
this.calendarCtr... | javascript | {
"resource": ""
} |
q20026 | setDefaults | train | function setDefaults(definition) {
providerConfig.optionsFactory = definition.options;
providerConfig.methods = (definition.methods || []).concat(EXPOSED_METHODS);
return provider;
} | javascript | {
"resource": ""
} |
q20027 | addPreset | train | function addPreset(name, definition) {
definition = definition || {};
definition.methods = definition.methods || [];
definition.options = definition.options || function() { return {}; };
if (/^cancel|hide|show$/.test(name)) {
throw new Error("Preset '" + name + "' in " + interimFactoryN... | javascript | {
"resource": ""
} |
q20028 | waitForInterim | train | function waitForInterim(callbackFn) {
return function() {
var fnArguments = arguments;
if (!showingInterims.length) {
// When there are still interim's opening, then wait for the first interim element to
// finish its open animation.
if (showPromises.leng... | javascript | {
"resource": ""
} |
q20029 | createAndTransitionIn | train | function createAndTransitionIn() {
return $q(function(resolve, reject) {
// Trigger onCompiling callback before the compilation starts.
// This is useful, when modifying options, which can be influenced by developers.
options.onCompiling && options.onCompiling(options);
... | javascript | {
"resource": ""
} |
q20030 | compileElement | train | function compileElement(options) {
var compiled = !options.skipCompile ? $mdCompiler.compile(options) : null;
return compiled || $q(function (resolve) {
resolve({
locals: {},
link: function () {
return options.element;
... | javascript | {
"resource": ""
} |
q20031 | linkElement | train | function linkElement(compileData, options){
angular.extend(compileData.locals, options);
var element = compileData.link(options.scope);
// Search for parent at insertion time, if not specified
options.element = element;
options.parent = findParent(element, options);
... | javascript | {
"resource": ""
} |
q20032 | findParent | train | function findParent(element, options) {
var parent = options.parent;
// Search for parent at insertion time, if not specified
if (angular.isFunction(parent)) {
parent = parent(options.scope, element, options);
} else if (angular.isString(parent)) {
parent... | javascript | {
"resource": ""
} |
q20033 | startAutoHide | train | function startAutoHide() {
var autoHideTimer, cancelAutoHide = angular.noop;
if (options.hideDelay) {
autoHideTimer = $timeout(service.hide, options.hideDelay) ;
cancelAutoHide = function() {
$timeout.cancel(autoHideTimer);
};
}
... | javascript | {
"resource": ""
} |
q20034 | changeSelectedButton | train | function changeSelectedButton(parent, increment) {
// Coerce all child radio buttons into an array, then wrap then in an iterator
var buttons = $mdUtil.iterator(parent[0].querySelectorAll('md-radio-button'), true);
if (buttons.count()) {
var validate = function (button) {
// If disabled, then... | javascript | {
"resource": ""
} |
q20035 | initialize | train | function initialize() {
if (!rgCtrl) {
throw 'RadioButton: No RadioGroupController could be found.';
}
rgCtrl.add(render);
attr.$observe('value', render);
element
.on('click', listener)
.on('$destroy', function() {
rgCtrl.remove(render);
});
... | javascript | {
"resource": ""
} |
q20036 | listener | train | function listener(ev) {
if (element[0].hasAttribute('disabled') || rgCtrl.isDisabled()) return;
scope.$apply(function() {
rgCtrl.setViewValue(attr.value, ev && ev.type);
});
} | javascript | {
"resource": ""
} |
q20037 | configureAria | train | function configureAria(element, scope){
element.attr({
id: attr.id || 'radio_' + $mdUtil.nextUid(),
role: 'radio',
'aria-checked': 'false'
});
$mdAria.expectWithText(element, 'aria-label');
} | javascript | {
"resource": ""
} |
q20038 | fontSet | train | function fontSet(alias, className) {
config.fontSets.push({
alias: alias,
fontSet: className || alias
});
return this;
} | javascript | {
"resource": ""
} |
q20039 | findRegisteredFontSet | train | function findRegisteredFontSet(alias) {
var useDefault = angular.isUndefined(alias) || !(alias && alias.length);
if (useDefault) {
return config.defaultFontSet;
}
var result = alias;
angular.forEach(config.fontSets, function(fontSet) {
if (fontSet.alias === alias) {
result = fon... | javascript | {
"resource": ""
} |
q20040 | isIcon | train | function isIcon(target) {
return angular.isDefined(target.element) && angular.isDefined(target.config);
} | javascript | {
"resource": ""
} |
q20041 | Icon | train | function Icon(el, config) {
// If the node is a <symbol>, it won't be rendered so we have to convert it into <svg>.
if (el && el.tagName.toLowerCase() === 'symbol') {
var viewbox = el.getAttribute('viewBox');
// // Check if innerHTML is supported as IE11 does not support innerHTML on SVG elements.
... | javascript | {
"resource": ""
} |
q20042 | prepareAndStyle | train | function prepareAndStyle() {
var viewBoxSize = this.config ? this.config.viewBoxSize : config.defaultViewBoxSize;
angular.forEach({
'fit': '',
'height': '100%',
'width': '100%',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox': this.element.getAttribute('viewBox') || ('0 0 ' + vie... | javascript | {
"resource": ""
} |
q20043 | watchMedia | train | function watchMedia() {
for (var mediaName in $mdConstant.MEDIA) {
$mdMedia(mediaName); // initialize
$mdMedia.getQuery($mdConstant.MEDIA[mediaName])
.addListener(invalidateLayout);
}
return $mdMedia.watchResponsiveAttributes(
['md-cols', 'md-row-height', 'md-gutt... | javascript | {
"resource": ""
} |
q20044 | layoutDelegate | train | function layoutDelegate(tilesInvalidated) {
var tiles = getTileElements();
var props = {
tileSpans: getTileSpans(tiles),
colCount: getColumnCount(),
rowMode: getRowMode(),
rowHeight: getRowHeight(),
gutter: getGutter()
};
if (!tilesInvalidated && angular.... | javascript | {
"resource": ""
} |
q20045 | getTileStyle | train | function getTileStyle(position, spans, colCount, rowCount, gutter, rowMode, rowHeight) {
// TODO(shyndman): There are style caching opportunities here.
// Percent of the available horizontal space that one column takes up.
var hShare = (1 / colCount) * 100;
// Fraction of the gutter size that ... | javascript | {
"resource": ""
} |
q20046 | getTileSpans | train | function getTileSpans(tileElements) {
return [].map.call(tileElements, function(ele) {
var ctrl = angular.element(ele).controller('mdGridTile');
return {
row: parseInt(
$mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-rowspan'), 10) || 1,
col: parseInt(
... | javascript | {
"resource": ""
} |
q20047 | GridLayout | train | function GridLayout(colCount, tileSpans) {
var self, layoutInfo, gridStyles, layoutTime, mapTime, reflowTime;
layoutTime = $mdUtil.time(function() {
layoutInfo = calculateGridFor(colCount, tileSpans);
});
return self = {
/**
* An array of objects describing each tile'... | javascript | {
"resource": ""
} |
q20048 | train | function(updateFn) {
mapTime = $mdUtil.time(function() {
var info = self.layoutInfo();
gridStyles = updateFn(info.positioning, info.rowCount);
});
return self;
} | javascript | {
"resource": ""
} | |
q20049 | train | function() {
return {
tileCount: tileSpans.length,
layoutTime: layoutTime,
mapTime: mapTime,
reflowTime: reflowTime,
totalTime: layoutTime + mapTime + reflowTime
};
} | javascript | {
"resource": ""
} | |
q20050 | calculateGridFor | train | function calculateGridFor(colCount, tileSpans) {
var curCol = 0,
curRow = 0,
spaceTracker = newSpaceTracker();
return {
positioning: tileSpans.map(function(spans, i) {
return {
spans: spans,
position: reserveSpace(spans, i)
};
}),
rowCount: ... | javascript | {
"resource": ""
} |
q20051 | validate | train | function validate () {
if (exec('npm whoami') !== 'angular') {
err('You must be authenticated with npm as "angular" to perform a release.');
} else if (exec('git rev-parse --abbrev-ref HEAD') !== 'staging') {
err('Releases can only performed from "staging" at this time.');
} else {
return ... | javascript | {
"resource": ""
} |
q20052 | checkoutVersionBranch | train | function checkoutVersionBranch () {
exec(`git branch -q -D release/${newVersion}`);
exec(`git checkout -q -b release/${newVersion}`);
abortCmds.push('git checkout master');
abortCmds.push(`git branch -D release/${newVersion}`);
} | javascript | {
"resource": ""
} |
q20053 | updateVersion | train | function updateVersion () {
start(`Updating ${"package.json".cyan} version from ${oldVersion.cyan} to ${newVersion.cyan}...`);
pkg.version = newVersion;
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
done();
abortCmds.push('git checkout package.json');
pushCmds.push('git add p... | javascript | {
"resource": ""
} |
q20054 | createChangelog | train | function createChangelog () {
start(`Generating changelog from ${oldVersion.cyan} to ${newVersion.cyan}...`);
exec(`git fetch --tags ${origin}`);
exec(`git checkout CHANGELOG.md`);
exec(`gulp changelog --sha=$(git merge-base v${lastMajorVer} HEAD)`);
done();
abortCmds.push('git checkout CHANG... | javascript | {
"resource": ""
} |
q20055 | getNewVersion | train | function getNewVersion () {
header();
const options = getVersionOptions(oldVersion);
let key, version;
log(`The current version is ${oldVersion.cyan}.`);
log('');
log('What should the next version be?');
for (key in options) { log((+key + 1) + ') ' + options[ key ].cyan); }
log('');
... | javascript | {
"resource": ""
} |
q20056 | cloneRepo | train | function cloneRepo (repo) {
start(`Cloning ${repo.cyan} from Github...`);
exec(`rm -rf ${repo}`);
exec(`git clone git@github.com:angular/${repo}.git --depth=1`);
done();
cleanupCmds.push(`rm -rf ${repo}`);
} | javascript | {
"resource": ""
} |
q20057 | writeScript | train | function writeScript (name, cmds) {
fs.writeFileSync(name, '#!/usr/bin/env bash\n\n' + cmds.join('\n'));
exec('chmod +x ' + name);
} | javascript | {
"resource": ""
} |
q20058 | updateBowerVersion | train | function updateBowerVersion () {
start('Updating bower version...');
const options = { cwd: './bower-material' };
const bower = require(options.cwd + '/bower.json'),
pkg = require(options.cwd + '/package.json');
// update versions in config files
bower.version = pkg.version = newVers... | javascript | {
"resource": ""
} |
q20059 | updateSite | train | function updateSite () {
start('Adding new version of the docs site...');
const options = { cwd: './code.material.angularjs.org' };
writeDocsJson();
// build files for bower
exec([
'rm -rf dist',
'gulp docs'
]);
replaceFilePaths();
// copy files over to site repo
ex... | javascript | {
"resource": ""
} |
q20060 | replaceFilePaths | train | function replaceFilePaths () {
// handle docs.js
const filePath = path.join(__dirname, '/dist/docs/docs.js');
const file = fs.readFileSync(filePath);
const contents = file.toString()
.replace(/http:\/\/localhost:8080\/angular-material/g, 'https://gitcdn.xyz/cdn/angular/bower-material/v' + newVer... | javascript | {
"resource": ""
} |
q20061 | replaceBaseHref | train | function replaceBaseHref (folder) {
// handle index.html
const filePath = path.join(__dirname, '/code.material.angularjs.org/', folder, '/index.html');
const file = fs.readFileSync(filePath);
const contents = file.toString().replace(/base href="\//g, 'base href="/' + folder + '/');
fs.writeFileSync(... | javascript | {
"resource": ""
} |
q20062 | updateMaster | train | function updateMaster () {
pushCmds.push(
comment('update package.json in master'),
'git checkout master',
`git pull --rebase ${origin} master --strategy=theirs`,
`git checkout release/${newVersion} -- CHANGELOG.md`,
`node -e "const newVersion = '${newVersion}'; ${stringifyFu... | javascript | {
"resource": ""
} |
q20063 | center | train | function center (msg) {
msg = ' ' + msg.trim() + ' ';
const length = msg.length;
const spaces = Math.floor((lineWidth - length) / 2);
return Array(spaces + 1).join('-') + msg.green + Array(lineWidth - msg.length - spaces + 1).join('-');
} | javascript | {
"resource": ""
} |
q20064 | start | train | function start (msg) {
const msgLength = strip(msg).length,
diff = lineWidth - 4 - msgLength;
write(msg + Array(diff + 1).join(' '));
} | javascript | {
"resource": ""
} |
q20065 | reverseTranslate | train | function reverseTranslate (newFrom) {
return $animateCss(target, {
to: newFrom || from,
addClass: options.transitionOutClass,
removeClass: options.transitionInClass,
duration: options.duration
}).start();
} | javascript | {
"resource": ""
} |
q20066 | noTransitionFound | train | function noTransitionFound(styles) {
styles = styles || window.getComputedStyle(element[0]);
return styles.transitionDuration == '0s' || (!styles.transition && !styles.transitionProperty);
} | javascript | {
"resource": ""
} |
q20067 | currentBounds | train | function currentBounds() {
var cntr = element ? element.parent() : null;
var parent = cntr ? cntr.parent() : null;
return parent ? self.clientRect(parent) : null;
} | javascript | {
"resource": ""
} |
q20068 | train | function (element, originator) {
var zoomTemplate = "translate3d( {centerX}px, {centerY}px, 0 ) scale( {scaleX}, {scaleY} )";
var buildZoom = angular.bind(null, $mdUtil.supplant, zoomTemplate);
return buildZoom(self.calculateTransformValues(element, originator));
} | javascript | {
"resource": ""
} | |
q20069 | train | function(raw) {
var css = { };
var lookups = 'left top right bottom width height x y min-width min-height max-width max-height';
angular.forEach(raw, function(value,key) {
if (angular.isUndefined(value)) return;
if (lookups.indexOf(key) >= 0) {
css[key] = value + 'px';
... | javascript | {
"resource": ""
} | |
q20070 | train | function (element) {
var bounds = angular.element(element)[0].getBoundingClientRect();
var isPositiveSizeClientRect = function (rect) {
return rect && (rect.width > 0) && (rect.height > 0);
};
// If the event origin element has zero size, it has probably been hidden.
return isPosi... | javascript | {
"resource": ""
} | |
q20071 | train | function (targetRect) {
return targetRect ? {
x: Math.round(targetRect.left + (targetRect.width / 2)),
y: Math.round(targetRect.top + (targetRect.height / 2))
} : { x : 0, y : 0 };
} | javascript | {
"resource": ""
} | |
q20072 | MdToastController | train | function MdToastController($mdToast, $scope, $log) {
// For compatibility with AngularJS 1.6+, we should always use the $onInit hook in
// interimElements. The $mdCompiler simulates the $onInit hook for all versions.
this.$onInit = function() {
var self = this;
if (self.highlightAction) {
... | javascript | {
"resource": ""
} |
q20073 | attachToBody | train | function attachToBody(el) {
var element = angular.element(el);
angular.element(document.body).append(element);
attachedElements.push(element);
} | javascript | {
"resource": ""
} |
q20074 | hexToRgba | train | function hexToRgba (color) {
var hex = color[ 0 ] === '#' ? color.substr(1) : color,
dig = hex.length / 3,
red = hex.substr(0, dig),
green = hex.substr(dig, dig),
blue = hex.substr(dig * 2);
if (dig === 1) {
red += red;
green += green;
blue += blue;
}
ret... | javascript | {
"resource": ""
} |
q20075 | rgbaToHex | train | function rgbaToHex(color) {
color = color.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
var hex = (color && color.length === 4) ? "#" +
("0" + parseInt(color[1],10).toString(16)).slice(-2) +
("0" + parseInt(color[2],10).toString(16)).slice(-2) +
("0" + parseInt(colo... | javascript | {
"resource": ""
} |
q20076 | isSameMonthAndYear | train | function isSameMonthAndYear(d1, d2) {
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
} | javascript | {
"resource": ""
} |
q20077 | getWeekOfMonth | train | function getWeekOfMonth(date) {
var firstDayOfMonth = getFirstDateOfMonth(date);
return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
} | javascript | {
"resource": ""
} |
q20078 | incrementDays | train | function incrementDays(date, numberOfDays) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
} | javascript | {
"resource": ""
} |
q20079 | incrementMonths | train | function incrementMonths(date, numberOfMonths) {
// If the same date in the target month does not actually exist, the Date object will
// automatically advance *another* month by the number of missing days.
// For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
// So... | javascript | {
"resource": ""
} |
q20080 | isDateWithinRange | train | function isDateWithinRange(date, minDate, maxDate) {
var dateAtMidnight = createDateAtMidnight(date);
var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
return (!minDateAtMi... | javascript | {
"resource": ""
} |
q20081 | clampDate | train | function clampDate(date, minDate, maxDate) {
var boundDate = date;
if (minDate && date < minDate) {
boundDate = new Date(minDate.getTime());
}
if (maxDate && date > maxDate) {
boundDate = new Date(maxDate.getTime());
}
return boundDate;
} | javascript | {
"resource": ""
} |
q20082 | isMonthWithinRange | train | function isMonthWithinRange(date, minDate, maxDate) {
var month = date.getMonth();
var year = date.getFullYear();
return (!minDate || minDate.getFullYear() < year || minDate.getMonth() <= month) &&
(!maxDate || maxDate.getFullYear() > year || maxDate.getMonth() >= month);
} | javascript | {
"resource": ""
} |
q20083 | onScroll | train | function onScroll() {
var scrollTop = contentEl.prop('scrollTop');
var isScrollingDown = scrollTop > (onScroll.prevScrollTop || 0);
// Store the previous scroll so we know which direction we are scrolling
onScroll.prevScrollTop = scrollTop;
//
// AT TOP (not scrolling)
//
... | javascript | {
"resource": ""
} |
q20084 | onRemove | train | function onRemove(scope, element, opts) {
opts.cleanupInteraction();
opts.cleanupBackdrop();
opts.cleanupResizing();
opts.hideBackdrop();
// Before the menu is closing remove the clickable class.
element.removeClass('md-clickable');
// For navigation $destroy events, do a qui... | javascript | {
"resource": ""
} |
q20085 | showMenu | train | function showMenu() {
opts.parent.append(element);
element[0].style.display = '';
return $q(function(resolve) {
var position = calculateMenuPosition(element, opts);
element.removeClass('md-leave');
// Animate the menu scaling, and opacity [from its position origi... | javascript | {
"resource": ""
} |
q20086 | sanitizeAndConfigure | train | function sanitizeAndConfigure() {
if (!opts.target) {
throw Error(
'$mdMenu.show() expected a target to animate from in options.target'
);
}
angular.extend(opts, {
alreadyOpen: false,
isRemoved: false,
target: angular.element(opts.tar... | javascript | {
"resource": ""
} |
q20087 | setupBackdrop | train | function setupBackdrop() {
if (!opts.backdrop) return angular.noop;
opts.backdrop.on('click', onBackdropClick);
return function() {
opts.backdrop.off('click', onBackdropClick);
};
} | javascript | {
"resource": ""
} |
q20088 | onBackdropClick | train | function onBackdropClick(event) {
event.preventDefault();
event.stopPropagation();
scope.$apply(function() {
opts.mdMenuCtrl.close(true, { closeAll: true });
});
} | javascript | {
"resource": ""
} |
q20089 | captureClickListener | train | function captureClickListener(e) {
var target = e.target;
// Traverse up the event until we get to the menuContentEl to see if
// there is an ng-click and that the ng-click is not disabled
do {
if (target == opts.menuContentEl[0]) return;
if ((hasAnyAttrib... | javascript | {
"resource": ""
} |
q20090 | firstVisibleChild | train | function firstVisibleChild() {
for (var i = 0; i < openMenuNode.children.length; ++i) {
if ($window.getComputedStyle(openMenuNode.children[i]).display != 'none') {
return openMenuNode.children[i];
}
}
} | javascript | {
"resource": ""
} |
q20091 | publicDocData | train | function publicDocData(doc, extraData) {
const options = _.assign(extraData || {}, { hasDemo: (doc.docType === 'directive') });
// This RegEx always retrieves the last source descriptor.
// For example it retrieves from `/opt/material/src/core/services/ripple/ripple.js` the following
// source descriptor: `src... | javascript | {
"resource": ""
} |
q20092 | registerGestures | train | function registerGestures(element, parent) {
var deregister = $mdGesture.register(parent, 'drag', { horizontal: false });
parent.on('$md.dragstart', onDragStart)
.on('$md.drag', onDrag)
.on('$md.dragend', onDragEnd);
return function cleanupGestures() {
deregister();
pa... | javascript | {
"resource": ""
} |
q20093 | MdDialogController | train | function MdDialogController($mdDialog, $mdConstant) {
// For compatibility with AngularJS 1.6+, we should always use the $onInit hook in
// interimElements. The $mdCompiler simulates the $onInit hook for all versions.
this.$onInit = function() {
var isPrompt = this.$type == 'prompt';
if (isProm... | javascript | {
"resource": ""
} |
q20094 | onShow | train | function onShow(scope, element, options, controller) {
angular.element($document[0].body).addClass('md-dialog-is-showing');
var dialogElement = element.find('md-dialog');
// Once a dialog has `ng-cloak` applied on his template the dialog animation will not work properly.
// This is a very comm... | javascript | {
"resource": ""
} |
q20095 | onRemove | train | function onRemove(scope, element, options) {
options.deactivateListeners();
options.unlockScreenReader();
options.hideBackdrop(options.$destroy);
// Remove the focus traps that we added earlier for keeping focus within the dialog.
if (topFocusTrap && topFocusTrap.parentNode) {
top... | javascript | {
"resource": ""
} |
q20096 | detachAndClean | train | function detachAndClean() {
angular.element($document[0].body).removeClass('md-dialog-is-showing');
// Reverse the container stretch if using a content element.
if (options.contentElement) {
options.reverseContainerStretch();
}
// Exposed cleanup function from the $md... | javascript | {
"resource": ""
} |
q20097 | getBoundingClientRect | train | function getBoundingClientRect (element, orig) {
var source = angular.element((element || {}));
if (source && source.length) {
// Compute and save the target element's bounding rect, so that if the
// element is hidden when the dialog closes, we can shrink the dialog
... | javascript | {
"resource": ""
} |
q20098 | getDomElement | train | function getDomElement(element, defaultElement) {
if (angular.isString(element)) {
element = $document[0].querySelector(element);
}
// If we have a reference to a raw dom element, always wrap it in jqLite
return angular.element(element || defaultElement);
... | javascript | {
"resource": ""
} |
q20099 | activateListeners | train | function activateListeners(element, options) {
var window = angular.element($window);
var onWindowResize = $mdUtil.debounce(function() {
stretchDialogContainerToViewport(element, options);
}, 60);
var removeListeners = [];
var smartClose = function() {
// Only 'confirm' di... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.