_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3900
|
getOperationForUpdatingLog
|
train
|
function getOperationForUpdatingLog(operationId, tableName, action, item) {
return api.getMetadata(tableName, action, item).then(function(metadata) {
return {
tableName: operationTableName,
action: 'upsert',
data: {
|
javascript
|
{
"resource": ""
}
|
q3901
|
getMetadata
|
train
|
function getMetadata(tableName, action, item) {
return Platform.async(function(callback) {
callback();
})().then(function() {
var metadata = {};
// If action is update and item defines version property OR if action is insert / update,
// define metadata.version to be the item's version property
if (action === 'upsert' ||
action === 'insert' ||
(action === 'update' && item.hasOwnProperty(versionColumnName))) {
metadata[versionColumnName] = item[versionColumnName];
return metadata;
} else if (action == 'update' || action === 'delete') { // Read item's version property from the table
|
javascript
|
{
"resource": ""
}
|
q3902
|
getMaxOperationId
|
train
|
function getMaxOperationId() {
var query = new Query(operationTableName);
return store.read(query.orderByDescending('id').take(1)).then(function(result) {
Validate.isArray(result);
|
javascript
|
{
"resource": ""
}
|
q3903
|
push
|
train
|
function push(handler) {
return pushTaskRunner.run(function() {
reset();
pushHandler = handler;
return
|
javascript
|
{
"resource": ""
}
|
q3904
|
pushAllOperations
|
train
|
function pushAllOperations() {
var currentOperation,
pushError;
return readAndLockFirstPendingOperation().then(function(pendingOperation) {
if (!pendingOperation) {
return; // No more pending operations. Push is complete
}
var currentOperation = pendingOperation;
return pushOperation(currentOperation).then(function() {
return removeLockedOperation();
}, function(error) {
// failed to push
return unlockPendingOperation().then(function() {
pushError = createPushError(store, operationTableManager, storeTaskRunner, currentOperation, error);
//TODO: If the conflict isn't resolved but the error is marked as handled by the user,
//we can end up in an infinite loop. Guard against this by capping the max number of
//times handlePushError can be called for the same record.
// We want to reset the retryCount when we move on to the next record
if (lastFailedOperationId !== currentOperation.logRecord.id) {
lastFailedOperationId = currentOperation.logRecord.id;
retryCount = 0;
}
// Cap the number of times error handling logic is invoked for the same record
if (retryCount < maxRetryCount) {
++retryCount;
return handlePushError(pushError, pushHandler);
}
});
}).then(function() {
if (!pushError) { // no push error
lastProcessedOperationId = currentOperation.logRecord.id;
} else if (pushError && !pushError.isHandled) { // push failed and not handled
|
javascript
|
{
"resource": ""
}
|
q3905
|
train
|
function (err) {
if (_.isNull(err)) {
// Call complete with all the args except for err
|
javascript
|
{
"resource": ""
}
|
|
q3906
|
handlePushError
|
train
|
function handlePushError(pushError, pushHandler) {
return Platform.async(function(callback) {
callback();
})().then(function() {
if (pushError.isConflict()) {
if (pushHandler && pushHandler.onConflict) {
// NOTE: value of server record will not be
|
javascript
|
{
"resource": ""
}
|
q3907
|
removeSystemProperties
|
train
|
function removeSystemProperties(instance) {
var copy = {};
for (var property in instance) {
if ((property != MobileServiceSystemColumns.Version) &&
(property != MobileServiceSystemColumns.UpdatedAt)
|
javascript
|
{
"resource": ""
}
|
q3908
|
getItemFromResponse
|
train
|
function getItemFromResponse(response) {
var result = _.fromJson(response.responseText);
if (response.getResponseHeader) {
var eTag = response.getResponseHeader('ETag');
if (!_.isNullOrEmpty(eTag)) {
|
javascript
|
{
"resource": ""
}
|
q3909
|
setServerItemIfPreconditionFailed
|
train
|
function setServerItemIfPreconditionFailed(error) {
if (error.request && error.request.status === 412) {
|
javascript
|
{
"resource": ""
}
|
q3910
|
getVersionFromEtag
|
train
|
function getVersionFromEtag(etag) {
var len = etag.length,
result = etag;
if (len > 1 && etag[0] === '"' && etag[len - 1] === '"') {
|
javascript
|
{
"resource": ""
}
|
q3911
|
addQueryParametersFeaturesIfApplicable
|
train
|
function addQueryParametersFeaturesIfApplicable(features, userQueryParameters) {
var hasQueryParameters = false;
if (userQueryParameters) {
if (Array.isArray(userQueryParameters)) {
hasQueryParameters = userQueryParameters.length > 0;
} else if (_.isObject(userQueryParameters)) {
for (var k in userQueryParameters) {
|
javascript
|
{
"resource": ""
}
|
q3912
|
train
|
function(gpsRefPos) {
if(gpsRefPos === undefined ||
gpsRefPos.length < 4) {
this._gpsRefPos = undefined;
}
else if(gpsRefPos[0] === 0 &&
gpsRefPos[1] === 0 &&
gpsRefPos[2] === 0 &&
|
javascript
|
{
"resource": ""
}
|
|
q3913
|
train
|
function () {
var lngSize = this._getLngSize() / 2.0;
var latSize = this._getLatSize() / 2.0;
var latlng = this._latlng;
return new L.LatLngBounds(
|
javascript
|
{
"resource": ""
}
|
|
q3914
|
train
|
function(point, angle) {
var x = point[0];
var y = point[1];
var si_z = Math.sin(angle);
var co_z = Math.cos(angle);
var newX = x * co_z
|
javascript
|
{
"resource": ""
}
|
|
q3915
|
train
|
function(points, angle) {
var result = [];
for(var i=0;i<points.length;i+=2) {
var x = points[i + 0] * this._size;
var y = points[i + 1] * this._size;
|
javascript
|
{
"resource": ""
}
|
|
q3916
|
train
|
function () {
if(this._heading === undefined) {
return this._createNoHeadingSymbolPathString();
}
else {
if(this._gpsRefPos ===
|
javascript
|
{
"resource": ""
}
|
|
q3917
|
train
|
function(message, originalError) {
var stack;
this.message = message;
this.originalError = originalError;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
stack = this.stack;
} else {
stack = new Error(message).stack;
}
if (Object.defineProperty) {
Object.defineProperty(this, "stack", {
configurable: true, // required for Bluebird long stack traces
|
javascript
|
{
"resource": ""
}
|
|
q3918
|
getInternetExplorerExe
|
train
|
function getInternetExplorerExe () {
var suffix = path.join('Internet Explorer', PROCESS_NAME)
var locations = _.map(_.compact([
process.env['PROGRAMW6432'],
process.env['PROGRAMFILES(X86)'],
process.env['PROGRAMFILES']
]), function (prefix) {
|
javascript
|
{
"resource": ""
}
|
q3919
|
merge
|
train
|
function merge( a, l, m, r ) {
const n1 = m - l + 1;
const n2 = r - m;
const L = a.slice( l, m + 1 );
const R = a.slice( m + 1, 1 + r );
let i = 0, j = 0, k = l;
while( i < n1 && j < n2 ) {
if( L[ i ][ 0 ] <= R[ j ][ 0 ] ) {
a[ k ] = L[ i ];
i++;
} else {
a[ k ] =
|
javascript
|
{
"resource": ""
}
|
q3920
|
findHost
|
train
|
function findHost() {
var current = this;
var app;
// Keep iterating upward until we don't have a grandparent.
// Has to do this grandparent check because at some point we hit the project.
// Stop at lazy engine boundaries.
do {
|
javascript
|
{
"resource": ""
}
|
q3921
|
train
|
function(path) {
return (path && path.match(/^[a-z]:\\/i))
|
javascript
|
{
"resource": ""
}
|
|
q3922
|
Player
|
train
|
function Player(opts) {
if (!(this instanceof Player)) {
return new Player(opts);
}
events.EventEmitter.call(this);
this.name = opts.name;
this.supportedInterfaces =
|
javascript
|
{
"resource": ""
}
|
q3923
|
TokenRequest
|
train
|
function TokenRequest(authenticate, options) {
var self = this;
this.status = 'expired';
this.pendingCallbacks = [];
// execute accumulated callbacks during the 'pending' state
function fireCallbacks(err, token) {
self.pendingCallbacks.forEach(function (callback) {
callback(err, token);
});
self.pendingCallbacks = [];
}
TokenRequest.prototype.get = function (callback) {
if (this.status == 'expired') {
this.status = 'pending';
this.pendingCallbacks.push(callback);
authenticate(options, function (err, token) {
if (err) {
self.status = 'expired';
return fireCallbacks(err, null);
}
self.issued = Date.now();
self.duration = options.expiration || 60 * 60 * 1000;
self.token = token;
self.status = 'completed';
|
javascript
|
{
"resource": ""
}
|
q3924
|
fireCallbacks
|
train
|
function fireCallbacks(err, token) {
self.pendingCallbacks.forEach(function (callback) {
|
javascript
|
{
"resource": ""
}
|
q3925
|
parseLines
|
train
|
function parseLines (src) {
const lines = []
for (i = 0; i < src.length; ++i) {
if (src[i] === '\n' && src[i - 1] === '\r') i += 1
if (!src[i]) break
const keyStart = endOfIndent(src, i)
if (atLineEnd(src, keyStart)) {
lines.push('')
i = keyStart
continue
}
if (atComment(src, keyStart)) {
const commentEnd = endOfComment(src, keyStart)
lines.push(src.slice(keyStart, commentEnd))
i = commentEnd
continue
}
const keyEnd
|
javascript
|
{
"resource": ""
}
|
q3926
|
parse
|
train
|
function parse (src, path) {
const pathSep = typeof path === 'string' ? path : '.'
return parseLines(src).reduce((res, line) => {
if (Array.isArray(line)) {
const [key, value] = line
if (path) {
const keyPath = key.split(pathSep)
let parent = res
while (keyPath.length >= 2) {
const p = keyPath.shift()
if (!parent[p]) {
parent[p] = {}
} else if (typeof parent[p] !== 'object') {
parent[p] = { '': parent[p]
|
javascript
|
{
"resource": ""
}
|
q3927
|
stringify
|
train
|
function stringify (input, {
commentPrefix = '# ',
defaultKey = '',
indent = ' ',
keySep = ' = ',
latin1 = true,
lineWidth = 80,
newline = '\n',
pathSep = '.'
} = {}) {
if (!input) return ''
if (!Array.isArray(input)) input = toLines(input, pathSep, defaultKey)
const foldLine = getFold({ indent, latin1, lineWidth, newline: '\\' + newline })
const foldComment = getFold({ indent: commentPrefix, latin1, lineWidth, newline })
return input
.map(line => {
switch (true) {
case !line:
return ''
case Array.isArray(line):
|
javascript
|
{
"resource": ""
}
|
q3928
|
mapVariablesToObject
|
train
|
function mapVariablesToObject(variables) {
var plugmanConsumableVariables = {};
for (var i in variables) {
var t = variables[i].split('=');
if (t[0] && t[1]) {
|
javascript
|
{
"resource": ""
}
|
q3929
|
TidalAPI
|
train
|
function TidalAPI(authData) {
if(typeof authData !== 'object')
{
throw new Error('You must pass auth data into the TidalAPI object correctly');
} else {
if(typeof authData.username !== 'string') {
throw new Error('Username invalid or missing');
}
if(typeof authData.password !== 'string') {
throw new Error('Password invalid or missing');
}
if(typeof authData.token !== 'string') {
|
javascript
|
{
"resource": ""
}
|
q3930
|
tryLogin
|
train
|
function tryLogin(authInfo, cb) {
/**
* Logging?
* @type {boolean}
*/
var loggingIn = true;
request({
method: 'POST',
uri: '/login/username',
headers: {
'X-Tidal-Token': authInfo.token
},
form: {
username: authInfo.username,
password: authInfo.password,
clientUniqueKey: "vjknfvjbnjhbgjhbbg"
}
}, function(err, res, data) {
if(!err){
if (data && res && res.statusCode !== 200 || err) {
throw new Error(data)
}
data = JSON.parse(data);
|
javascript
|
{
"resource": ""
}
|
q3931
|
resize
|
train
|
function resize () {
if (!running) {
running = true
if (window.requestAnimationFrame) {
|
javascript
|
{
"resource": ""
}
|
q3932
|
train
|
function (value) {
assertErr(value instanceof Date, TypeError, 'Field error: value is not an instance of Date')
assertErr(!isNaN(value.getTime()), TypeError,
|
javascript
|
{
"resource": ""
}
|
|
q3933
|
train
|
function (value) {
var date = new Date(value)
assertErr(!isNaN(date.getTime()), TypeError, 'Field
|
javascript
|
{
"resource": ""
}
|
|
q3934
|
train
|
function (ast) {
assertErr(ast.kind === Kind.STRING,
GraphQLError, 'Query error: Can only parse strings to dates but got a: ' + ast.kind, [ast])
var result = new Date(ast.value)
assertErr(!isNaN(result.getTime()),
GraphQLError, 'Query error: Invalid date', [ast])
|
javascript
|
{
"resource": ""
}
|
|
q3935
|
push
|
train
|
function push (chunk) {
if (!isAudioBuffer(chunk)) {
chunk = util.create(chunk, channels)
}
|
javascript
|
{
"resource": ""
}
|
q3936
|
createNodeUI
|
train
|
function createNodeUI(node) {
var nodeMaterial = new THREE.MeshBasicMaterial({ color: 0xfefefe
|
javascript
|
{
"resource": ""
}
|
q3937
|
train
|
function () {
$('<table class="jqs-table"><tr></tr></table>').appendTo($(this.element));
for (var i = 0; i < this.settings.days; i++) {
$('<td><div class="jqs-day"></div></td>').
appendTo($('.jqs-table tr', this.element));
}
$('<div class="jqs-grid"><div class="jqs-grid-head"></div></div>').appendTo($(this.element));
for (var j = 0; j < 25; j++) {
$('<div class="jqs-grid-line"><div class="jqs-grid-hour">' + this.formatHour(j) + '</div></div>').
appendTo($('.jqs-grid', this.element));
}
var dayRemove = '';
var dayDuplicate = '';
if (this.settings.mode === 'edit') {
dayRemove = '<div class="jqs-day-remove" title="' + this.settings.periodRemoveButton + '"></div>';
|
javascript
|
{
"resource": ""
}
|
|
q3938
|
train
|
function (period) {
if (!this.settings.onDuplicatePeriod.call(this, period, this.element)) {
var options = this.periodData(period);
var position = Math.round(period.position().top / this.periodPosition);
var height = Math.round(period.height() / this.periodPosition);
var $this = this;
|
javascript
|
{
"resource": ""
}
|
|
q3939
|
train
|
function (ui) {
var start = Math.round(ui.position.top / this.periodPosition);
var end = Math.round(($(ui.helper).height() + ui.position.top) / this.periodPosition);
|
javascript
|
{
"resource": ""
}
|
|
q3940
|
train
|
function (period) {
var start = Math.round(period.position().top / this.periodPosition);
var end = Math.round((period.height() + period.position().top) / this.periodPosition);
return {
start: this.periodFormat(start),
|
javascript
|
{
"resource": ""
}
|
|
q3941
|
train
|
function (position) {
if (position >= this.periodHeight) {
position = 0;
}
if (position < 0) {
position = 0;
}
var hour = Math.floor(position / this.periodInterval);
var mn = (position / this.periodInterval - hour) * 60;
if (this.settings.hour === 12) {
var time = hour;
|
javascript
|
{
"resource": ""
}
|
|
q3942
|
train
|
function (time) {
var split = time.split(':');
var hour = parseInt(split[0]);
var mn = parseInt(split[1]);
if (this.settings.hour === 12) {
var matches = time.match(/([0-1]?[0-9]):?([0-5][0-9])?\s?(am|pm|p)?/);
var ind = matches[3];
if (!ind) {
ind = 'am';
}
hour = parseInt(matches[1]);
mn = parseInt(matches[2]);
|
javascript
|
{
"resource": ""
}
|
|
q3943
|
train
|
function (current) {
var currentStart = Math.round(current.position().top);
var currentEnd = Math.round(current.position().top + current.height());
var start = 0;
var end = 0;
var check = true;
$('.jqs-period', $(current).parent()).each(function (index, period) {
if (current.attr('id') !== $(period).attr('id')) {
start = Math.round($(period).position().top);
end = Math.round($(period).position().top + $(period).height());
if (start > currentStart && start < currentEnd) {
check = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q3944
|
train
|
function () {
var $this = this;
var data = [];
$('.jqs-day', $this.element).each(function (index, day) {
var periods = [];
$('.jqs-period', day).each(function (index,
|
javascript
|
{
"resource": ""
}
|
|
q3945
|
train
|
function (args) {
var $this = this;
var dataImport = args[1];
var ret = [];
$.each(dataImport, function (index, data) {
$.each(data.periods, function (index, period) {
var parent = $('.jqs-day', $this.element).eq(data.day);
var options = {};
var height, position;
if ($.isArray(period)) {
position = $this.positionFormat(period[0]);
height = $this.positionFormat(period[1]);
|
javascript
|
{
"resource": ""
}
|
|
q3946
|
train
|
function (d, msgctxt, msgid, msgid_plural, n, category) {
if (! msgid) {
return '';
}
var msg_ctxt_id = msgctxt ? msgctxt + this.context_glue + msgid : msgid;
var domainname = d || this.domain || 'messages';
var lang = this.lang;
// category is always LC_MESSAGES. We ignore all else
var category_name = 'LC_MESSAGES';
category = 5;
var locale_data = [];
if (typeof(this.data[lang]) != 'undefined' &&
this.data[lang][domainname]) {
locale_data.push(this.data[lang][domainname] );
} else if (typeof(this.data[lang]) != 'undefined') {
// didn't find domain we're looking for. Search all of them.
for (var dom in this.data[lang]) {
locale_data.push(this.data[lang][dom] );
}
}
var trans = [];
var found = false;
var domain_used; // so we can find plural-forms if needed
if (locale_data.length) {
for (var i=0; i<locale_data.length; i++) {
var locale = locale_data[i];
if (locale.msgs[msg_ctxt_id]) {
var msg_ctxt_str = locale.msgs[msg_ctxt_id].msgstr;
trans = msg_ctxt_str.concat(trans.slice(msg_ctxt_str.length));
domain_used = locale;
found = true;
// only break if found translation actually has a translation.
if ( trans.length > 0 && trans[0].length !== 0 ) {
break;
}
}
}
}
// default to
|
javascript
|
{
"resource": ""
}
|
|
q3947
|
train
|
function(mustache, program, inverse) {
var params = mustache.params;
this.pushParams(params);
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
if(mustache.hash) {
|
javascript
|
{
"resource": ""
}
|
|
q3948
|
parseCoffeeDocs
|
train
|
function parseCoffeeDocs(file, fn) {
fs.readFile(file, function(err, data) {
if (err) {
fn(err);
}
var js = coffee.compile(data.toString());
var regex = /\/\**([\s\S]*?)\*\//gm;
var fragments = js.match(regex);
var docs = [];
for (var i = 0; i < fragments.length; i++) {
var
|
javascript
|
{
"resource": ""
}
|
q3949
|
getSwagger
|
train
|
function getSwagger(fragment, fn) {
for (var i = 0; i < fragment.tags.length; i++) {
var tag = fragment.tags[i];
if ('swagger' === tag.title) {
return
|
javascript
|
{
"resource": ""
}
|
q3950
|
readApi
|
train
|
function readApi(file, fn) {
var ext = path.extname(file);
if ('.js' === ext || '.ts' === ext) {
readJsDoc(file, fn);
} else if ('.yml' === ext) {
readYml(file, fn);
} else if
|
javascript
|
{
"resource": ""
}
|
q3951
|
train
|
function(x){
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Only try to use the proxyquireify version if it has been `require`d
if (pqify && pqify.exports._proxy) {
|
javascript
|
{
"resource": ""
}
|
|
q3952
|
pointIsInsideBounds
|
train
|
function pointIsInsideBounds(x, y, bounds) {
return x >= bounds.left &&
y >= bounds.top &&
|
javascript
|
{
"resource": ""
}
|
q3953
|
add
|
train
|
function add(scope, element) {
updateDelayed();
items.push({
element:
|
javascript
|
{
"resource": ""
}
|
q3954
|
_fnCheck
|
train
|
function _fnCheck(callback, data) {
if (angular.isUndefinedOrNull(data) || angular.isArray(data)) {
return; // jmp out
}
if (angular.isFunction(callback)) {
return callback(data, $filter);
} else {
if (typeof callback === 'boolean') {
data = !!data;
return data === callback;
} else if (angular.isDefined(callback)) {
try {
var _regex = new RegExp(callback);
return _regex.test(data);
}
|
javascript
|
{
"resource": ""
}
|
q3955
|
_fnAfter
|
train
|
function _fnAfter(options, node, isNodePassed, isChildPassed, isParentPassed) {
if (isNodePassed === true) {
node.__filtered__ = true;
node.__filtered_visible__ = true;
node.__filtered_index__ = options.filter_index++;
return; //jmp
} else if (isChildPassed === true && options.showParent === true
|| isParentPassed === true && options.showChild === true) {
node.__filtered__ = false;
|
javascript
|
{
"resource": ""
}
|
q3956
|
_fnConvert
|
train
|
function _fnConvert(filters) {
var _iF, _lenF, _keysF,
_filter,
_state;
// convert filter object to array filter
if (angular.isObject(filters) && !angular.isArray(filters)) {
_keysF = Object.keys(filters);
_lenF = _keysF.length;
_filter = [];
if (_lenF > 0) {
for (_iF = 0; _iF < _lenF; _iF++) {
if (typeof filters[_keysF[_iF]] === 'string' && filters[_keysF[_iF]].length === 0) {
continue;
} else if (angular.isArray(filters[_keysF[_iF]])) {
_state = filters[_keysF[_iF]];
} else if (angular.isObject(filters[_keysF[_iF]])) {
|
javascript
|
{
"resource": ""
}
|
q3957
|
train
|
function (e) {
var patternName;
var state = e.state;
if (state === null) {
this.skipBack = false;
return;
} else if (state !== null) {
patternName = state.pattern;
}
var iFramePath = "";
iFramePath = this.getFileName(patternName);
if (iFramePath === "") {
iFramePath = "styleguide/html/styleguide.html";
}
var obj = JSON.stringify({
"event": "patternLab.updatePath",
|
javascript
|
{
"resource": ""
}
|
|
q3958
|
train
|
function () {
// make sure the listener for checkpanels is set-up
Dispatcher.addListener('insertPanels', modalViewer.insert);
// add the info/code panel onclick handler
$('.pl-js-pattern-info-toggle').click(function (e) {
modalViewer.toggle();
});
// make sure the close button handles the click
$('.pl-js-modal-close-btn').on('click', function (e) {
// hide any open annotations
obj = JSON.stringify({
'event': 'patternLab.annotationsHighlightHide'
});
document.querySelector('.pl-js-iframe').contentWindow.postMessage(obj, modalViewer.targetOrigin);
// hide the viewer
modalViewer.close();
});
// see if the modal is already active, if so update attributes as appropriate
if (DataSaver.findValue('modalActive') === 'true') {
modalViewer.active = true;
$('.pl-js-pattern-info-toggle').html("Hide Pattern Info");
}
// make sure the modal viewer is not viewable, it's always hidden by default. the pageLoad event determines when it actually opens
modalViewer.hide();
// review the query strings in case there is something
|
javascript
|
{
"resource": ""
}
|
|
q3959
|
train
|
function (templateRendered, patternPartial, iframePassback, switchText) {
if (iframePassback) {
// send a message to the pattern
var obj = JSON.stringify({
'event': 'patternLab.patternModalInsert',
'patternPartial': patternPartial,
'modalContent': templateRendered.outerHTML
});
document.querySelector('.pl-js-iframe').contentWindow.postMessage(obj, modalViewer.targetOrigin);
} else {
|
javascript
|
{
"resource": ""
}
|
|
q3960
|
train
|
function (patternPartial, panelID) {
var els;
// turn off all of the active tabs
els = document.querySelectorAll('#pl-' + patternPartial + '-tabs .pl-js-tab-link');
for (i = 0; i < els.length; ++i) {
els[i].classList.remove('pl-is-active-tab');
}
// hide all of the panels
els = document.querySelectorAll('#pl-'
|
javascript
|
{
"resource": ""
}
|
|
q3961
|
train
|
function (patternData, iframePassback, switchText) {
Dispatcher.addListener('checkPanels', panelsViewer.checkPanels);
// set-up defaults
var template, templateCompiled, templateRendered, panel;
// get the base panels
var panels = Panels.get();
// evaluate panels array and create content
for (var i = 0; i < panels.length; ++i) {
panel = panels[i];
// catch pattern panel since it doesn't have a name defined by default
if (panel.name === undefined) {
panel.name = patternData.patternEngineName || patternData.patternExtension;
panel.language = patternData.patternExtension;
}
// if httpRequestReplace has not been set, use the extension. this is likely for the raw template
if (panel.httpRequestReplace === '') {
panel.httpRequestReplace = panel.httpRequestReplace + '.' + patternData.patternExtension;
}
if ((panel.templateID !== undefined) && (panel.templateID)) {
if ((panel.httpRequest
|
javascript
|
{
"resource": ""
}
|
|
q3962
|
goMedium
|
train
|
function goMedium() {
killDisco();
killHay();
fullMode = false;
sizeiframe(getRandom(
minViewportWidth,
config.ishViewportRange !==
|
javascript
|
{
"resource": ""
}
|
q3963
|
goLarge
|
train
|
function goLarge() {
killDisco();
killHay();
fullMode = false;
sizeiframe(getRandom(
config.ishViewportRange !== undefined ? parseInt(config.ishViewportRange.l[0]) : 800,
|
javascript
|
{
"resource": ""
}
|
q3964
|
killHay
|
train
|
function killHay() {
var currentWidth = $sgIframe.width();
hayMode = false;
$sgIframe.removeClass('hay-mode');
|
javascript
|
{
"resource": ""
}
|
q3965
|
startHay
|
train
|
function startHay() {
hayMode = true;
$('.pl-js-vp-iframe-container').removeClass("vp-animate").width(minViewportWidth + viewportResizeHandleWidth);
$sgIframe.removeClass("vp-animate").width(minViewportWidth);
var timeoutID = window.setTimeout(function () {
$('.pl-js-vp-iframe-container').addClass('hay-mode').width(maxViewportWidth
|
javascript
|
{
"resource": ""
}
|
q3966
|
create_hint
|
train
|
function create_hint(value, match, type, title, description, link) {
var $hint = $(document.createElement('span'));
$hint.addClass('brackets-js-hints brackets-js-hints-with-type-details');
$hint.attr('title', title);
if (match) {
value = value.replace(match, '');
$hint.append($(document.createElement('span')).text(match).addClass('matched-hint'));
$hint.append($(document.createElement('span')).text(value).addClass('require-hint-value'));
}
else {
$hint.append($(document.createElement('span')).text(value).addClass('require-hint-value'));
}
if (link) {
$hint.append($(document.createElement('a')).addClass('jshint-link').attr('href', link));
|
javascript
|
{
"resource": ""
}
|
q3967
|
findExecutable
|
train
|
function findExecutable(opt_exe) {
var exe = opt_exe || io.findInPath(PHANTOMJS_EXE, true);
if (!exe) {
throw Error(
'The PhantomJS executable could not be found on the current PATH. ' +
'Please download the latest version from ' +
'http://phantomjs.org/download.html and ensure it can be found on ' +
'your PATH. For
|
javascript
|
{
"resource": ""
}
|
q3968
|
train
|
function(opt_capabilities, opt_flow) {
var capabilities = opt_capabilities || webdriver.Capabilities.phantomjs();
var exe = findExecutable(capabilities.get(BINARY_PATH_CAPABILITY));
var args = ['--webdriver-logfile=' + DEFAULT_LOG_FILE];
var logPrefs = capabilities.get(webdriver.Capability.LOGGING_PREFS);
if (logPrefs instanceof webdriver.logging.Preferences) {
logPrefs = logPrefs.toJSON();
}
if (logPrefs && logPrefs[webdriver.logging.Type.DRIVER]) {
var level = WEBDRIVER_TO_PHANTOMJS_LEVEL[
logPrefs[webdriver.logging.Type.DRIVER]];
if (level) {
args.push('--webdriver-loglevel=' + level);
}
}
var proxy = capabilities.get(webdriver.Capability.PROXY);
if (proxy) {
switch (proxy.proxyType) {
case 'manual':
if (proxy.httpProxy) {
args.push(
'--proxy-type=http',
'--proxy=http://' + proxy.httpProxy);
}
break;
case 'pac':
throw Error('PhantomJS does not support Proxy PAC files');
case 'system':
args.push('--proxy-type=system');
break;
case 'direct':
args.push('--proxy-type=none');
|
javascript
|
{
"resource": ""
}
|
|
q3969
|
train
|
function(opt_config, opt_flow) {
var caps;
if (opt_config instanceof Options) {
caps = opt_config.toCapabilities();
} else {
caps = new webdriver.Capabilities(opt_config);
}
var binary = caps.get('firefox_binary') || new Binary();
if (typeof binary === 'string') {
binary = new Binary(binary);
}
var profile = caps.get('firefox_profile') || new Profile();
caps.set('firefox_binary', null);
caps.set('firefox_profile', null);
var serverUrl = portprober.findFreePort().then(function(port) {
var prepareProfile;
if (typeof profile === 'string') {
prepareProfile = decodeProfile(profile).then(function(dir) {
var profile = new Profile(dir);
profile.setPreference('webdriver_firefox_port', port);
return profile.writeToDisk();
});
} else {
profile.setPreference('webdriver_firefox_port', port);
prepareProfile = profile.writeToDisk();
}
|
javascript
|
{
"resource": ""
}
|
|
q3970
|
DriverService
|
train
|
function DriverService(executable, options) {
/** @private {string} */
this.executable_ = executable;
/** @private {boolean} */
this.loopbackOnly_ = !!options.loopback;
/** @private {(number|!webdriver.promise.Promise.<number>)} */
this.port_ = options.port;
/**
* @private {!(Array.<string>|webdriver.promise.Promise.<!Array.<string>>)}
*/
this.args_ = options.args;
/** @private {string} */
this.path_ = options.path || '/';
/** @private {!Object.<string, string>} */
|
javascript
|
{
"resource": ""
}
|
q3971
|
defaultWindowsLocation
|
train
|
function defaultWindowsLocation() {
var files = [
process.env['PROGRAMFILES'] || 'C:\\Program Files',
process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)'
].map(function(prefix) {
|
javascript
|
{
"resource": ""
}
|
q3972
|
findFirefox
|
train
|
function findFirefox() {
if (foundBinary) {
return foundBinary;
}
if (process.platform === 'darwin') {
var osxExe = '/Applications/Firefox.app/Contents/MacOS/firefox-bin';
foundBinary = io.exists(osxExe).then(function(exists) {
return exists ? osxExe : null;
});
} else if (process.platform === 'win32') {
foundBinary = defaultWindowsLocation();
} else {
foundBinary
|
javascript
|
{
"resource": ""
}
|
q3973
|
installNoFocusLibs
|
train
|
function installNoFocusLibs(profileDir) {
var x86 = path.join(profileDir, 'x86');
var amd64 = path.join(profileDir, 'amd64');
return mkdir(x86)
.then(copyLib.bind(null, NO_FOCUS_LIB_X86, x86))
.then(mkdir.bind(null, amd64))
.then(copyLib.bind(null, NO_FOCUS_LIB_AMD64, amd64))
.then(function() {
return x86 + ':' + amd64;
});
function mkdir(dir)
|
javascript
|
{
"resource": ""
}
|
q3974
|
train
|
function(opt_exe) {
/** @private {(string|undefined)} */
this.exe_ = opt_exe;
/** @private {!Array.<string>} */
this.args_ = [];
/** @private {!Object.<string, string>} */
this.env_ = {};
|
javascript
|
{
"resource": ""
}
|
|
q3975
|
getDefaultPreferences
|
train
|
function getDefaultPreferences() {
if (!defaultPreferences) {
var contents = fs.readFileSync(WEBDRIVER_PREFERENCES_PATH, 'utf8');
|
javascript
|
{
"resource": ""
}
|
q3976
|
loadUserPrefs
|
train
|
function loadUserPrefs(f) {
var done = promise.defer();
fs.readFile(f, function(err, contents) {
if (err && err.code === 'ENOENT') {
done.fulfill({});
return;
}
if (err) {
done.reject(err);
return;
}
var prefs = {};
var context =
|
javascript
|
{
"resource": ""
}
|
q3977
|
mixin
|
train
|
function mixin(a, b) {
Object.keys(b).forEach(function(key) {
|
javascript
|
{
"resource": ""
}
|
q3978
|
installExtensions
|
train
|
function installExtensions(extensions, dir, opt_excludeWebDriverExt) {
var hasWebDriver = !!opt_excludeWebDriverExt;
var next = 0;
var extensionDir = path.join(dir, 'extensions');
var done = promise.defer();
return io.exists(extensionDir).then(function(exists) {
if (!exists) {
return promise.checkedNodeCall(fs.mkdir, extensionDir);
}
}).then(function() {
installNext();
return done.promise;
});
function installNext() {
if (!done.isPending()) {
return;
}
if (next >= extensions.length) {
if (hasWebDriver) {
done.fulfill(dir);
|
javascript
|
{
"resource": ""
}
|
q3979
|
decode
|
train
|
function decode(data) {
return io.tmpFile().then(function(file) {
var buf = new Buffer(data, 'base64');
return promise.checkedNodeCall(fs.writeFile, file, buf).then(function() {
return io.tmpDir();
}).then(function(dir) {
|
javascript
|
{
"resource": ""
}
|
q3980
|
Context
|
train
|
function Context(opt_configureForTesting) {
var closure = this.closure = vm.createContext({
console: console,
setTimeout: setTimeout,
setInterval: setInterval,
clearTimeout: clearTimeout,
clearInterval: clearInterval,
process: process,
require: require,
Buffer: Buffer,
Error: Error,
CLOSURE_BASE_PATH: path.dirname(CLOSURE_BASE_FILE_PATH) + '/',
CLOSURE_IMPORT_SCRIPT: function(src) {
loadScript(src);
return true;
},
CLOSURE_NO_DEPS: !isDevMode(),
goog: {}
});
closure.window = closure.top = closure;
if (opt_configureForTesting) {
closure.document = {
body: {},
createElement: function() { return {}; },
getElementsByTagName: function() { return []; }
|
javascript
|
{
"resource": ""
}
|
q3981
|
loadScript
|
train
|
function loadScript(src) {
src = path.normalize(src);
var contents = fs.readFileSync(src, 'utf8');
|
javascript
|
{
"resource": ""
}
|
q3982
|
train
|
function(result, onKill) {
/** @return {boolean} Whether this command is still running. */
this.isRunning = function() {
return result.isPending();
};
/**
* @return {!promise.Promise.<!Result>} A promise for the result of this
* command.
*/
this.result = function() {
return result;
};
/**
|
javascript
|
{
"resource": ""
}
|
|
q3983
|
resolve
|
train
|
function resolve(newState, newValue) {
if (webdriver.promise.Deferred.State_.PENDING !== state) {
return;
}
if (newValue === self) {
// See promise a+, 2.3.1
// http://promises-aplus.github.io/promises-spec/#point-48
throw TypeError('A promise may not resolve to itself');
}
state = webdriver.promise.Deferred.State_.BLOCKED;
if (webdriver.promise.isPromise(newValue)) {
var onFulfill = goog.partial(notifyAll, newState);
var onReject = goog.partial(
|
javascript
|
{
"resource": ""
}
|
q3984
|
notify
|
train
|
function notify(listener) {
var func = state == webdriver.promise.Deferred.State_.RESOLVED ?
listener.callback : listener.errback;
if (func) {
flow.runInNewFrame_(goog.partial(func, value),
listener.fulfill, listener.reject);
|
javascript
|
{
"resource": ""
}
|
q3985
|
cancel
|
train
|
function cancel(opt_reason) {
if (!isPending()) {
return;
}
if (opt_canceller) {
|
javascript
|
{
"resource": ""
}
|
q3986
|
AddonFormatError
|
train
|
function AddonFormatError(msg) {
Error.call(this);
Error.captureStackTrace(this, AddonFormatError);
/** @override */
|
javascript
|
{
"resource": ""
}
|
q3987
|
getDetails
|
train
|
function getDetails(addonPath) {
return readManifest(addonPath).then(function(doc) {
var em = getNamespaceId(doc, 'http://www.mozilla.org/2004/em-rdf#');
var rdf = getNamespaceId(
doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
var description = doc[rdf + 'RDF'][rdf + 'Description'][0];
var details = {
id: getNodeText(description, em + 'id'),
name: getNodeText(description, em + 'name'),
version: getNodeText(description, em + 'version'),
unpack: getNodeText(description, em + 'unpack') || false
};
if (typeof details.unpack === 'string') {
details.unpack = details.unpack.toLowerCase() === 'true';
}
if (!details.id) {
throw new AddonFormatError('Could not find add-on ID for ' + addonPath);
}
return details;
});
|
javascript
|
{
"resource": ""
}
|
q3988
|
readManifest
|
train
|
function readManifest(addonPath) {
var manifest;
if (addonPath.slice(-4) === '.xpi') {
manifest = checkedCall(fs.readFile, addonPath).then(function(buff) {
var zip = new AdmZip(buff);
if (!zip.getEntry('install.rdf')) {
throw new AddonFormatError(
'Could not find install.rdf in ' + addonPath);
}
var done = promise.defer();
|
javascript
|
{
"resource": ""
}
|
q3989
|
train
|
function(opt_config, opt_service, opt_flow) {
var service = opt_service || getDefaultService();
var executor = executors.createExecutor(service.start());
var capabilities =
opt_config instanceof Options ? opt_config.toCapabilities() :
(opt_config || webdriver.Capabilities.chrome());
var
|
javascript
|
{
"resource": ""
}
|
|
q3990
|
findUnixPortRange
|
train
|
function findUnixPortRange() {
var cmd;
if (process.platform === 'sunos') {
cmd =
'/usr/sbin/ndd /dev/tcp tcp_smallest_anon_port tcp_largest_anon_port';
} else if (fs.existsSync('/proc/sys/net/ipv4/ip_local_port_range')) {
// Linux
cmd = 'cat /proc/sys/net/ipv4/ip_local_port_range';
} else {
cmd = 'sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last' +
' | sed -e "s/.*:\\s*//"';
}
return execute(cmd).then(function(stdout)
|
javascript
|
{
"resource": ""
}
|
q3991
|
train
|
function (fontName) {
var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS';
var $tester = $('<div>').css({
position: 'absolute',
left: '-9999px',
top: '-9999px',
fontSize: '200px'
}).text('mmmmmmmmmwwwwwww').appendTo(document.body);
|
javascript
|
{
"resource": ""
}
|
|
q3992
|
train
|
function (sc, so, ec, eo) {
if (arguments.length === 4) {
return new WrappedRange(sc, so, ec, eo);
} else if (arguments.length === 2) { //collapsed
ec = sc;
eo = so;
return new WrappedRange(sc, so, ec, eo);
} else {
var wrappedRange = this.createFromSelection();
if (!wrappedRange && arguments.length === 1) {
|
javascript
|
{
"resource": ""
}
|
|
q3993
|
returnToOriginal
|
train
|
function returnToOriginal() {
doneAnimating = false;
var placeholder = origin.parent('.material-placeholder');
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var originalWidth = origin.data('width');
var originalHeight = origin.data('height');
origin.velocity("stop", true);
$('#materialbox-overlay').velocity("stop", true);
$('.materialbox-caption').velocity("stop", true);
$('#materialbox-overlay').velocity({opacity: 0}, {
duration: outDuration, // Delay prevents animation overlapping
queue: false, easing: 'easeOutQuad',
complete: function(){
// Remove Overlay
overlayActive = false;
$(this).remove();
}
});
// Resize Image
origin.velocity(
{
width: originalWidth,
height: originalHeight,
left: 0,
top: 0
},
{
duration: outDuration,
queue: false, easing: 'easeOutQuad',
complete: function() {
placeholder.css({
height: '',
width: '',
position: '',
top: '',
left: ''
});
origin.removeAttr('style');
|
javascript
|
{
"resource": ""
}
|
q3994
|
train
|
function(string, $el) {
var img = $el.find('img');
var matchStart = $el.text().toLowerCase().indexOf("" + string.toLowerCase() + ""),
matchEnd = matchStart + string.length - 1,
beforeMatch = $el.text().slice(0, matchStart),
matchText = $el.text().slice(matchStart, matchEnd + 1),
|
javascript
|
{
"resource": ""
}
|
|
q3995
|
train
|
function(collection, newOption, firstActivation) {
if (newOption) {
collection.find('li.selected').removeClass('selected');
var option = $(newOption);
option.addClass('selected');
if
|
javascript
|
{
"resource": ""
}
|
|
q3996
|
train
|
function(btn) {
if (btn.attr('data-open') === "true") {
return;
}
var offsetX, offsetY, scaleFactor;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var btnRect = btn[0].getBoundingClientRect();
var anchor = btn.find('> a').first();
var menu = btn.find('> ul').first();
var backdrop = $('<div class="fab-backdrop"></div>');
var fabColor = anchor.css('background-color');
anchor.append(backdrop);
offsetX = btnRect.left - (windowWidth / 2) + (btnRect.width / 2);
offsetY = windowHeight - btnRect.bottom;
scaleFactor = windowWidth / backdrop.width();
btn.attr('data-origin-bottom', btnRect.bottom);
btn.attr('data-origin-left', btnRect.left);
btn.attr('data-origin-width', btnRect.width);
// Set initial state
btn.addClass('active');
btn.attr('data-open', true);
btn.css({
'text-align': 'center',
width: '100%',
bottom: 0,
left: 0,
transform: 'translateX(' + offsetX + 'px)',
transition: 'none'
});
anchor.css({
transform: 'translateY(' + -offsetY + 'px)',
transition: 'none'
});
backdrop.css({
'background-color': fabColor
});
setTimeout(function() {
btn.css({
transform: '',
transition: 'transform .2s cubic-bezier(0.550, 0.085, 0.680, 0.530), background-color 0s linear .2s'
});
anchor.css({
overflow: 'visible',
|
javascript
|
{
"resource": ""
}
|
|
q3997
|
train
|
function(btn) {
if (btn.attr('data-open') !== "true") {
return;
}
var offsetX, offsetY, scaleFactor;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var btnWidth = btn.attr('data-origin-width');
var btnBottom = btn.attr('data-origin-bottom');
var btnLeft = btn.attr('data-origin-left');
var anchor = btn.find('> .btn-floating').first();
var menu = btn.find('> ul').first();
var backdrop = btn.find('.fab-backdrop');
var fabColor = anchor.css('background-color');
offsetX = btnLeft - (windowWidth / 2) + (btnWidth / 2);
offsetY = windowHeight - btnBottom;
scaleFactor = windowWidth / backdrop.width();
// Hide backdrop
btn.removeClass('active');
btn.attr('data-open', false);
btn.css({
'background-color': 'transparent',
transition: 'none'
});
anchor.css({
transition: 'none'
});
backdrop.css({
transform: 'scale(0)',
'background-color': fabColor
});
menu.find('> li > a').css({
opacity: ''
});
setTimeout(function() {
backdrop.remove();
// Set initial state.
btn.css({
'text-align': '',
|
javascript
|
{
"resource": ""
}
|
|
q3998
|
train
|
function( giveFocus ) {
// If we need to give focus, do it before changing states.
if ( giveFocus ) {
// ....ah yes! It would’ve been incomplete without a crazy workaround for IE :|
// The focus is triggered *after* the close has completed - causing it
// to open again. So unbind and rebind the event at the next tick.
P.$root.off( 'focus.toOpen' ).eq(0).focus()
setTimeout( function() {
P.$root.on( 'focus.toOpen', handleFocusToOpenEvent )
}, 0 )
}
// Remove the “active” class.
$ELEMENT.removeClass( CLASSES.active )
aria( ELEMENT, 'expanded', false )
// * A Firefox bug, when `html` has `overflow:hidden`, results in
// killing transitions :(. So remove the “opened” state on the next tick.
// Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
setTimeout( function() {
// Remove the “opened” and “focused” class from the picker root.
|
javascript
|
{
"resource": ""
}
|
|
q3999
|
train
|
function (obj) {
var inverted = {};
for (var key in obj) {
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.