_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q12400
|
lowerCSSInfo
|
train
|
function lowerCSSInfo(docDom) {
// read index file, and getting target ts files.
var $scripts = $(docDom).find('link[rel="stylesheet"][href]');
$scripts.each(function () {
$(this).attr('href', function (idx, path) {
return path.toLowerCase();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q12401
|
sanitize
|
train
|
function sanitize(uri, options) {
options = extend({}, this.options, options);
return new Promise(function(accept, reject) {
var result = {href: null},
isFile, hasProtocol, loadFile, base;
if (uri == null || typeof uri !== 'string') {
reject('Sanitize failure, invalid URI: ' + stringValue(uri));
return;
}
hasProtocol = protocol_re.test(uri);
// if relative url (no protocol/host), prepend baseURL
if ((base = options.baseURL) && !hasProtocol) {
// Ensure that there is a slash between the baseURL (e.g. hostname) and url
if (!startsWith(uri, '/') && base[base.length-1] !== '/') {
uri = '/' + uri;
}
uri = base + uri;
}
// should we load from file system?
loadFile = (isFile = startsWith(uri, fileProtocol))
|| options.mode === 'file'
|| options.mode !== 'http' && !hasProtocol && fs();
if (isFile) {
// strip file protocol
uri = uri.slice(fileProtocol.length);
} else if (startsWith(uri, '//')) {
if (options.defaultProtocol === 'file') {
// if is file, strip protocol and set loadFile flag
uri = uri.slice(2);
loadFile = true;
} else {
// if relative protocol (starts with '//'), prepend default protocol
uri = (options.defaultProtocol || 'http') + ':' + uri;
}
}
// set non-enumerable mode flag to indicate local file load
Object.defineProperty(result, 'localFile', {value: !!loadFile});
// set uri
result.href = uri;
// set default result target, if specified
if (options.target) {
result.target = options.target + '';
}
// return
accept(result);
});
}
|
javascript
|
{
"resource": ""
}
|
q12402
|
http
|
train
|
function http(url, options) {
return request(url, extend({}, this.options.http, options))
.then(function(response) {
if (!response.ok) throw response.status + '' + response.statusText;
return response.text();
});
}
|
javascript
|
{
"resource": ""
}
|
q12403
|
compile
|
train
|
function compile(path, callback) {
if (/\.luax/.test(path)) {
// Load already compiled bytecode
loadBytecode(path);
}
if (/\.lua$/.test(path)) {
luaToBytecode(path, function (err, newpath) {
if (err) return callback(err);
loadBytecode(newpath);
});
}
function loadBytecode(path) {
readFile(path, function (err, buffer) {
if (err) return callback(err);
generate(buffer);
});
}
function generate(buffer) {
var program;
try {
program = parse(buffer);
}
catch (err) {
return callback(err);
}
callback(null, program);
}
}
|
javascript
|
{
"resource": ""
}
|
q12404
|
Electronify
|
train
|
function Electronify(path, options) {
if (!_isReady) {
app.on("ready", () => Electronify(path, options));
return app;
}
// Defaults
var bwOpts = ul.merge(options, {
width: 800
, height: 600
, _path: path
});
_opts = bwOpts;
createWindow(_opts);
return app;
}
|
javascript
|
{
"resource": ""
}
|
q12405
|
_createFPS
|
train
|
function _createFPS(context) {
// Render FPS in right-top
var modifier = new Modifier({
align: [1, 0],
origin: [1, 0],
size: [100, 50]
});
var surface = new Surface({
content: 'fps',
classes: ['fps']
});
context.add(modifier).add(surface);
// Update every 5 ticks
Timer.every(function () {
surface.setContent(Math.round(Engine.getFPS()) + ' fps');
}, 2);
}
|
javascript
|
{
"resource": ""
}
|
q12406
|
isJSON
|
train
|
function isJSON(body) {
if (!body) return false;
if ('string' == typeof body) return false;
if ('function' == typeof body.pipe) return false;
if (Buffer.isBuffer(body)) return false;
return true;
}
|
javascript
|
{
"resource": ""
}
|
q12407
|
_createPhotoMarker
|
train
|
function _createPhotoMarker(photo) {
var randomAngle = (Math.PI / 180) * (10 - (Math.random() * 20));
var marker = {
mapModifier: new MapModifier({
mapView: mapView,
position: photo.loc
}),
modifier: new StateModifier({
align: [0, 0],
origin: [0.5, 0.5]
}),
content: {
modifier: new Modifier({
size: [36, 26],
transform: Transform.rotateZ(randomAngle)
}),
back: new Surface({
classes: ['photo-frame']
}),
photoModifier: new Modifier({
origin: [0.5, 0.5],
align: [0.5, 0.5],
transform: Transform.scale(0.86, 0.78, 1)
}),
photo: new ImageSurface({
classes: ['photo']
})
}
};
marker.renderable = new RenderNode(marker.mapModifier);
var renderable = marker.renderable.add(marker.modifier).add(marker.content.modifier);
renderable.add(marker.content.back);
renderable.add(marker.content.photoModifier).add(marker.content.photo);
return marker;
}
|
javascript
|
{
"resource": ""
}
|
q12408
|
_elementIsChildOfMapView
|
train
|
function _elementIsChildOfMapView(element) {
if (element.className.indexOf('fm-mapview') >= 0) {
return true;
}
return element.parentElement ? _elementIsChildOfMapView(element.parentElement) : false;
}
|
javascript
|
{
"resource": ""
}
|
q12409
|
TabDirectiveController
|
train
|
function TabDirectiveController ($scope) {
var ctrl = this;
ctrl.isActive = function isActive () {
return !!$scope.isActive;
};
ctrl.activate = function activate () {
$scope.tabsCtrl.activate($scope);
};
$scope.internalControl = {
activate: ctrl.activate,
isActive: ctrl.isActive
};
}
|
javascript
|
{
"resource": ""
}
|
q12410
|
init
|
train
|
function init() {
require('dotenv').load();
app.port = process.env.PORT || 3002;
// Default route
app.get('/', function (req, res) {
res.json({
name: 'League of Legends eSports API',
version: "0.9.0",
author: "Robert Manolea <manolea.robert@gmail.com>",
repository: "https://github.com/Pupix/lol-esports-api"
});
});
// Dynamic API routes
XP.forEach(routes, function (func, route) {
app.get(route, requestHandler);
});
//Error Handling
app.use(function (req, res) { res.status(404).json({error: 404, message: "Not Found"}); });
app.use(function (req, res) { res.status(500).json({error: 500, message: 'Internal Server Error'}); });
// Listening
app.listen(app.port, function () { console.log('League of Legends eSports API is listening on port ' + app.port); });
}
|
javascript
|
{
"resource": ""
}
|
q12411
|
vPagesDirectiveController
|
train
|
function vPagesDirectiveController ($scope) {
var ctrl = this;
$scope.pages = [];
ctrl.getPagesId = function getPagesId () {
return $scope.id;
};
ctrl.getPageByIndex = function (index) {
return $scope.pages[index];
};
ctrl.getPageIndex = function (page) {
return $scope.pages.indexOf(page);
};
ctrl.getPageIndexById = function getPageIndexById (id) {
var length = $scope.pages.length,
index = null;
for (var i = 0; i < length; i++) {
var iteratedPage = $scope.pages[i];
if (iteratedPage.id && iteratedPage.id === id) { index = i; }
}
return index;
};
ctrl.addPage = function (page) {
$scope.pages.push(page);
if ($scope.activeIndex === ctrl.getPageIndex(page)) {
ctrl.activate(page);
}
};
ctrl.next = function () {
var newActiveIndex = $scope.activeIndex + 1;
if (newActiveIndex > $scope.pages.length - 1) {
newActiveIndex = 0;
}
$scope.activeIndex = newActiveIndex;
};
ctrl.previous = function () {
var newActiveIndex = $scope.activeIndex - 1;
if (newActiveIndex < 0) {
newActiveIndex = $scope.pages.length - 1;
}
$scope.activeIndex = newActiveIndex;
};
ctrl.activate = function (pageToActivate) {
if (!pageToActivate) { return; }
if (!pageToActivate.isActive) {
pageToActivate.isActive = true;
angular.forEach($scope.pages, function (iteratedPage) {
if (iteratedPage !== pageToActivate && iteratedPage.isActive) {
iteratedPage.isActive = false;
}
});
}
};
$scope.$watch('activeIndex', function (newValue, oldValue) {
if (newValue === oldValue) { return; }
var pageToActivate = ctrl.getPageByIndex(newValue);
if (pageToActivate.isDisabled) {
$scope.activeIndex = (angular.isDefined(oldValue)) ? oldValue : 0;
return false;
}
ctrl.activate(pageToActivate);
});
// API
$scope.internalControl = {
next: function () {
ctrl.next();
},
previous: function () {
ctrl.previous();
},
activate: function (indexOrId) {
if (angular.isString(indexOrId)) {
$scope.activeIndex = ctrl.getPageIndexById(indexOrId);
} else {
$scope.activeIndex = indexOrId;
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q12412
|
parseOutput
|
train
|
function parseOutput(str, callback) {
var blocks = str.split('\n\n');
var wifis = [];
var err = null;
try {
if (blocks.length < 2) {
// 2nd try, with \r\n
blocks = str.split('\r\n\r\n')
}
if (!blocks || blocks.length === 1) {
// No WiFis found
return callback(null, []);
}
// Each block has the same structure, while some parts might be available and others
// not. A sample structure:
// SSID 1 : AP-Test1
// Network type : Infrastructure
// Authentication : WPA2-Personal
// Encryption : CCMP
// BSSID 1 : 00:aa:f2:77:a5:53
// Signal : 46%
// Radio type : 802.11n
// Channel : 6
// Basic rates (MBit/s) : 1 2 5.5 11
// Other rates (MBit/s) : 6 9 12 18 24 36 48 54
for (var i = 1, l = blocks.length; i < l; i++) {
var network = {};
var lines = blocks[i].split('\n');
var regexChannel = /[a-zA-Z0-9()\s]+:[\s]*[0-9]+$/g;
if (!lines || lines.length < 2) {
continue;
}
// First line is always the SSID (which can be empty)
var ssid = lines[0].substring(lines[0].indexOf(':') + 1).trim();
for (var t = 1, n = lines.length; t < n; t++) {
if (lines[t].split(':').length === 7) {
// This is the mac address, use this one as trigger for a new network
if (network.mac) {
wifis.push(network);
}
network = {
ssid: ssid,
mac : lines[t].substring(lines[t].indexOf(':') + 1).trim()
};
}
else if (lines[t].indexOf('%') > 0) {
// Network signal strength, identified by '%'
var level = parseInt(lines[t].split(':')[1].split('%')[0].trim(), 10);
network.rssi = (level / 2) - 100;
}
else if (!network.channel) {
// A tricky one: the channel is the first one having just ONE number. Set only
// if the channel is not already set ("Basic Rates" can be a single number also)
if (regexChannel.exec(lines[t].trim())) {
network.channel = parseInt(lines[t].split(':')[1].trim(), 10);
}
}
}
if (network) {
wifis.push(network);
}
}
}
catch (ex) {
err = ex;
}
callback(err, wifis);
}
|
javascript
|
{
"resource": ""
}
|
q12413
|
PageDirectiveController
|
train
|
function PageDirectiveController ($scope) {
var ctrl = this;
ctrl.isActive = function isActive () {
return !!$scope.isActive;
};
ctrl.activate = function activate () {
$scope.pagesCtrl.activate($scope);
};
$scope.internalControl = {
activate: ctrl.activate,
isActive: ctrl.isActive
};
}
|
javascript
|
{
"resource": ""
}
|
q12414
|
initTools
|
train
|
function initTools(callback) {
// When a command is not found, an error is issued and async would finish. Therefore we pack
// the error into the result and check it later on.
async.parallel([
function (cb) {
exec(airport.detector, function (err) {
cb(null, {err: err, scanner: airport}
)
}
);
},
function (cb) {
exec(iwlist.detector, function (err) {
cb(null, {err: err, scanner: iwlist}
)
}
);
},
function (cb) {
exec(netsh.detector, function (err) {
cb(null, {err: err, scanner: netsh}
)
}
);
}
],
function (err, results) {
var res = _.find(results,
function (f) {
return !f.err
});
if (res) {
return callback(null, res.scanner);
}
callback(new Error('No scanner found'));
}
);
}
|
javascript
|
{
"resource": ""
}
|
q12415
|
scanNetworks
|
train
|
function scanNetworks(callback) {
exec(scanner.cmdLine, function (err, stdout) {
if (err) {
callback(err, null);
return;
}
scanner.parseOutput(stdout, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q12416
|
train
|
function (callback) {
if (!scanner) {
initTools(function (err, s) {
if (err) {
return callback(err);
}
scanner = s;
scanNetworks(callback);
});
return;
}
scanNetworks(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q12417
|
TOC
|
train
|
function TOC(enabled){
if (!(this instanceof TOC)) return new TOC(enabled);
this.enabled = !!enabled;
this._items = {all:[],h1:[],h2:[],h3:[],h4:[]};
this._last = {h1:null,h2:null,h3:null,h4:null};
}
|
javascript
|
{
"resource": ""
}
|
q12418
|
Strategy
|
train
|
function Strategy(options, verifyPublic) {
if (typeof options == 'function') {
verifyPublic = options;
options = {};
}
if (!verifyPublic) throw new Error('OAuth 2.0 public client strategy requires a verifyPublic function');
passport.Strategy.call(this);
this.name = 'oauth2-public-client';
this._verifyPublic = verifyPublic;
this._passReqToCallback = options.passReqToCallback;
}
|
javascript
|
{
"resource": ""
}
|
q12419
|
newToken
|
train
|
function newToken(){ // check if the client has all the tokens
var allRetrieved = true;
var tokens = client.getTokens();
['auth', 'gvx', 'rnr'].forEach(function(type){
if(!tokens.hasOwnProperty(type)){
allRetrieved = false;
}
});
if(allRetrieved){ // save tokens once all have been retrieved
fs.writeFileSync('./tokens.json', JSON.stringify(tokens));
console.log('\n\nALL TOKENS SAVED TO tokens.json')
}
}
|
javascript
|
{
"resource": ""
}
|
q12420
|
getConfigFromBabel
|
train
|
function getConfigFromBabel(start, babelrc = '.babelrc') {
if (start === '/') return [];
const packageJSONPath = path.join(start, 'package.json');
const packageJSON = require(packageJSONPath);
const babelConfig = packageJSON.babel;
if (babelConfig) {
const pluginConfig = babelConfig.plugins.find(p => (
p[0] === 'babel-root-import'
));
process.chdir(path.dirname(packageJSONPath));
return pluginConfig[1];
}
const babelrcPath = path.join(start, babelrc);
if (fs.existsSync(babelrcPath)) {
const babelrcJson = JSON5.parse(fs.readFileSync(babelrcPath, 'utf8'));
if (babelrcJson && Array.isArray(babelrcJson.plugins)) {
const pluginConfig = babelrcJson.plugins.find(p => (
p[0] === 'babel-plugin-root-import'
));
// The src path inside babelrc are from the root so we have
// to change the working directory for the same directory
// to make the mapping to work properly
process.chdir(path.dirname(babelrcPath));
return pluginConfig[1];
}
}
return getConfigFromBabel(path.dirname(start));
}
|
javascript
|
{
"resource": ""
}
|
q12421
|
train
|
function($scope, element, attrs, ctrl) {
$scope.popoverClass = attrs.popoverClass;
$scope.dropDirection = attrs.direction || 'bottom';
var left, top;
var trigger = document.querySelector('#'+$scope.trigger);
var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]');
// Add click event listener to trigger
trigger.addEventListener('click', function(ev){
var left, top;
var trigger = this; //get trigger element
var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]'); //get triger's target popover
ev.preventDefault();
calcPopoverPosition(trigger, target); //calculate the position of the popover
hideAllPopovers(trigger);
target.classList.toggle('hide'); //toggle display of target popover
// if target popover is visible then add click listener to body and call the open popover callback
if(!target.classList.contains('hide')){
ctrl.registerBodyListener();
$scope.onOpen();
$scope.$apply();
}
//else remove click listener from body and call close popover callback
else{
ctrl.unregisterBodyListener();
$scope.onClose();
$scope.$apply();
}
});
var getTriggerOffset = function(){
var triggerRect = trigger.getBoundingClientRect();
var bodyRect = document.body.getBoundingClientRect();
return {
top: triggerRect.top + document.body.scrollTop,
left: triggerRect.left + document.body.scrollLeft
}
};
// calculates the position of the popover
var calcPopoverPosition = function(trigger, target){
target.classList.toggle('hide');
var targetWidth = target.offsetWidth;
var targetHeight = target.offsetHeight;
target.classList.toggle('hide');
var triggerWidth = trigger.offsetWidth;
var triggerHeight = trigger.offsetHeight;
switch($scope.dropDirection){
case 'left': {
left = getTriggerOffset().left - targetWidth - 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case 'right':{
left = getTriggerOffset().left + triggerWidth + 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case'top':{
left = getTriggerOffset().left + 'px';
top = getTriggerOffset().top - targetHeight - 10 + 'px';
break;
}
default:{
left = getTriggerOffset().left +'px';
top = getTriggerOffset().top + triggerHeight + 10 + 'px'
}
}
target.style.position = 'absolute';
target.style.left = left;
target.style.top = top;
}
calcPopoverPosition(trigger, target);
}
|
javascript
|
{
"resource": ""
}
|
|
q12422
|
train
|
function(trigger, target){
target.classList.toggle('hide');
var targetWidth = target.offsetWidth;
var targetHeight = target.offsetHeight;
target.classList.toggle('hide');
var triggerWidth = trigger.offsetWidth;
var triggerHeight = trigger.offsetHeight;
switch($scope.dropDirection){
case 'left': {
left = getTriggerOffset().left - targetWidth - 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case 'right':{
left = getTriggerOffset().left + triggerWidth + 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case'top':{
left = getTriggerOffset().left + 'px';
top = getTriggerOffset().top - targetHeight - 10 + 'px';
break;
}
default:{
left = getTriggerOffset().left +'px';
top = getTriggerOffset().top + triggerHeight + 10 + 'px'
}
}
target.style.position = 'absolute';
target.style.left = left;
target.style.top = top;
}
|
javascript
|
{
"resource": ""
}
|
|
q12423
|
train
|
function(trigger){
var triggerId;
if(trigger)
triggerId = trigger.getAttribute('id');
var allPopovers = trigger != undefined ? document.querySelectorAll('.ng-popover:not([trigger="'+triggerId+'"])') : document.querySelectorAll('.ng-popover');
for(var i =0; i<allPopovers.length; i++){
var popover = allPopovers[i];
if(!popover.classList.contains('hide'))
popover.classList.add('hide')
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12424
|
heapify
|
train
|
function heapify(heap, i) {
var l = getLeft(i);
var r = getRight(i);
var smallest = i;
if (l < heap.list.length &&
heap.compare(heap.list[l], heap.list[i]) < 0) {
smallest = l;
}
if (r < heap.list.length &&
heap.compare(heap.list[r], heap.list[smallest]) < 0) {
smallest = r;
}
if (smallest !== i) {
swap(heap.list, i, smallest);
heapify(heap, smallest);
}
}
|
javascript
|
{
"resource": ""
}
|
q12425
|
buildHeapFromNodeArray
|
train
|
function buildHeapFromNodeArray(heap, nodeArray) {
heap.list = nodeArray;
for (var i = Math.floor(heap.list.length / 2); i >= 0; i--) {
heapify(heap, i);
}
}
|
javascript
|
{
"resource": ""
}
|
q12426
|
train
|
function() {
var this_ = this;
this.msg = (typeof this.options.select_message == 'string'?
document.getElementById(this.options.select_message):
this.options.select_message);
this.close_button = this.get_close_button();
this.msg_autoclose = null;
addEvent(this.close_button, 'click', function(e){
preventDefault(e);
this_.hide_message();
this_.save_message_closed();
clearTimeout(this_.msg_autoclose);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12427
|
train
|
function () {
var body = this.body;
var el = this.el;
el.setAttribute('position', body.position);
el.setAttribute('rotation', {
x: deg(body.quaternion.x),
y: deg(body.quaternion.y),
z: deg(body.quaternion.z)
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12428
|
train
|
function(numclasses) {
for (var i = numclasses.length; i--;) {
var numclass = numclasses[i];
var spans = byClassName(this.selectable, numclass);
var closewrap = firstWithClass(spans[spans.length - 1], 'closewrap');
closewrap.parentNode.removeChild(closewrap);
this.removeTextSelection(spans);
delete this.ranges[numclass];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12429
|
create
|
train
|
function create(type, constructor) {
return function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? invertRange(s)
: s.invertExtent ? invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
}
|
javascript
|
{
"resource": ""
}
|
q12430
|
parserFabric
|
train
|
function parserFabric(mode, format) {
return function (value, parseFn) {
parseFn = parseFn || moment_1.utc;
if (value === null || value === undefined || value === "") {
return null;
}
var formatsToParse = parseFormat[mode || "date"];
return parseFn(value, [format].concat(formatsToParse), true);
};
}
|
javascript
|
{
"resource": ""
}
|
q12431
|
runAndWatch
|
train
|
function runAndWatch(watchPattern, initialValue, task) {
gulp.watch(watchPattern, event => {
task(event.path, event);
});
return task(initialValue);
}
|
javascript
|
{
"resource": ""
}
|
q12432
|
lintFiles
|
train
|
function lintFiles(pattern, strict, configs) {
const linter = new eslint.CLIEngine(configs);
const report = linter.executeOnFiles([pattern]);
const formatter = linter.getFormatter();
console.log(formatter(report.results));
if (0 < report.errorCount || (strict && 0 < report.warningCount)) {
throw new Error('eslint reports some problems.');
}
}
|
javascript
|
{
"resource": ""
}
|
q12433
|
forEach
|
train
|
function forEach(parameters, dIt = global.it, dDescribe = global.describe) {
const it = makeTestCaseDefiner(parameters, dIt);
it.skip = makeParameterizedSkip(parameters, dIt);
it.only = makeParameterizedOnly(parameters, dIt);
const describe = makeTestCaseDefiner(parameters, dDescribe);
describe.skip = makeParameterizedSkip(parameters, dDescribe);
describe.only = makeParameterizedOnly(parameters, dDescribe);
return { it, describe };
}
|
javascript
|
{
"resource": ""
}
|
q12434
|
makeParameterizedOnly
|
train
|
function makeParameterizedOnly(parameters, defaultIt) {
return function(title, test) {
const it = makeTestCaseDefiner(parameters, defaultIt);
global.describe.only('', () => it(title, test));
};
}
|
javascript
|
{
"resource": ""
}
|
q12435
|
monthCalendar
|
train
|
function monthCalendar(date) {
var start = date.clone().startOf("month").startOf("week").startOf("day");
var end = date.clone().endOf("month").endOf("week").startOf("day");
var result = [];
var current = start.weekday(0).subtract(1, "d");
while (true) {
current = current.clone().add(1, "d");
result.push(current);
if (areDatesEqual(current, end)) {
break;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q12436
|
daysOfWeek
|
train
|
function daysOfWeek() {
var result = [];
for (var weekday = 0; weekday < 7; weekday++) {
result.push(moment_1.utc().weekday(weekday).format("dd"));
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q12437
|
assignDeclarationToGlobal
|
train
|
function assignDeclarationToGlobal(state, nodes, declaration) {
var filenameNoExt = getFilenameNoExt(state.file.opts.filename);
var expr = getGlobalExpression(state, filenameNoExt, declaration.id.name);
assignToGlobal(expr, nodes, declaration.id);
}
|
javascript
|
{
"resource": ""
}
|
q12438
|
assignToGlobal
|
train
|
function assignToGlobal(expr, nodes, expression) {
createGlobal(expr, nodes);
if (!t.isExpression(expression)) {
expression = t.toExpression(expression);
}
nodes.push(t.expressionStatement(t.assignmentExpression('=', expr, expression)));
}
|
javascript
|
{
"resource": ""
}
|
q12439
|
createGlobal
|
train
|
function createGlobal(expr, nodes, opt_namedPartial) {
var exprs = [];
while (t.isMemberExpression(expr)) {
exprs.push(expr);
expr = expr.object;
}
var currGlobalName = '';
for (var i = exprs.length - 2; opt_namedPartial ? i >= 0 : i > 0; i--) {
currGlobalName += '.' + exprs[i].property.value;
if (!createdGlobals[currGlobalName]) {
createdGlobals[currGlobalName] = true;
nodes.push(t.expressionStatement(
t.assignmentExpression('=', exprs[i], t.logicalExpression(
'||',
exprs[i],
t.objectExpression([])
))
));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q12440
|
getGlobalExpression
|
train
|
function getGlobalExpression(state, filePath, name, opt_isWildcard) {
assertFilenameRequired(state.file.opts.filename);
var globalName = state.opts.globalName;
var id;
if (typeof globalName === 'function') {
id = globalName(state, filePath, name, opt_isWildcard);
}
else {
if (name || opt_isWildcard) {
globalName += 'Named';
}
filePath = path.resolve(path.dirname(state.file.opts.filename), filePath);
var splitPath = filePath.split(path.sep);
var moduleName = splitPath[splitPath.length - 1];
id = 'this.' + globalName + '.' + moduleName + (name && name !== true ? '.' + name : '');
}
var parts = id.split('.');
var expr = t.identifier(parts[0]);
for (var i = 1; i < parts.length; i++) {
expr = t.memberExpression(expr, t.stringLiteral(parts[i]), true);
}
return expr;
}
|
javascript
|
{
"resource": ""
}
|
q12441
|
removeExtensions
|
train
|
function removeExtensions(filename) {
var extension = path.extname(filename);
while (extension !== '') {
filename = path.basename(filename, extension);
extension = path.extname(filename);
}
return filename;
}
|
javascript
|
{
"resource": ""
}
|
q12442
|
train
|
function(nodePath) {
createdGlobals = {};
filenameNoExtCache = null;
var node = nodePath.node;
var contents = node.body;
node.body = [t.expressionStatement(t.callExpression(
t.memberExpression(
t.functionExpression(null, [], t.blockStatement(contents)),
t.identifier('call'),
false
),
[t.identifier('this')]
))];
}
|
javascript
|
{
"resource": ""
}
|
|
q12443
|
train
|
function(nodePath, state) {
var replacements = [];
if ( nodePath.node.source.value.match(/^[\./]/) ) {
nodePath.node.specifiers.forEach(function(specifier) {
var expr = getGlobalExpression(
state,
removeExtensions(nodePath.node.source.value),
specifier.imported ? specifier.imported.name : null,
t.isImportNamespaceSpecifier(specifier)
);
replacements.push(t.variableDeclaration('var', [
t.variableDeclarator(specifier.local, expr)
]));
});
}
nodePath.replaceWithMultiple(replacements);
}
|
javascript
|
{
"resource": ""
}
|
|
q12444
|
train
|
function(nodePath, state) {
var replacements = [];
var expr = getGlobalExpression(state, getFilenameNoExt(state.file.opts.filename));
var expression = nodePath.node.declaration;
if (expression.id &&
(t.isFunctionDeclaration(expression) || t.isClassDeclaration(expression))) {
replacements.push(expression);
expression = expression.id;
}
assignToGlobal(expr, replacements, expression);
nodePath.replaceWithMultiple(replacements);
}
|
javascript
|
{
"resource": ""
}
|
|
q12445
|
train
|
function(nodePath, state) {
var replacements = [];
var node = nodePath.node;
if (node.declaration) {
replacements.push(node.declaration);
if (t.isVariableDeclaration(node.declaration)) {
node.declaration.declarations.forEach(assignDeclarationToGlobal.bind(null, state, replacements));
} else {
assignDeclarationToGlobal(state, replacements, node.declaration);
}
} else {
node.specifiers.forEach(function(specifier) {
var exprToAssign = specifier.local;
if (node.source) {
var specifierName = specifier.local ? specifier.local.name : null;
exprToAssign = getGlobalExpression(state, node.source.value, specifierName);
}
var filenameNoExt = getFilenameNoExt(state.file.opts.filename);
var expr = getGlobalExpression(state, filenameNoExt, specifier.exported.name);
assignToGlobal(expr, replacements, exprToAssign);
});
}
nodePath.replaceWithMultiple(replacements);
}
|
javascript
|
{
"resource": ""
}
|
|
q12446
|
defineAttributes
|
train
|
function defineAttributes(object, attributes) {
if (object instanceof Parse.Object) {
if (!(attributes instanceof Array)) attributes = Array.prototype.slice.call(arguments, 1);
attributes.forEach(function (attribute) {
Object.defineProperty(object, attribute, {
get: function () {
return this.get(attribute);
},
set: function (value) {
this.set(attribute, value);
},
configurable: true,
enumerable: true
});
});
} else if (typeof object == 'function') {
return defineAttributes(object.prototype, attributes)
} else {
if (object instanceof Array) attributes = object;
else attributes = Array.prototype.slice.call(arguments, 0);
return function defineAttributesDecorator(target) {
defineAttributes(target, attributes);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q12447
|
wrapParsePromise
|
train
|
function wrapParsePromise(promise, parsePromise) {
['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve']
.forEach(function (prop) {
promise[prop] = parsePromise[prop];
});
['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) {
promise[method] = wrap(parsePromise[method]);
});
['then', 'catch'].forEach(function (method) {
var func = promise[method];
promise[method] = function wrappedAngularPromise() {
var args = Array.prototype.slice.call(arguments, 0);
var promise = func.apply(this, args);
wrapParsePromise(promise, parsePromise);
return promise;
};
});
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q12448
|
wrap
|
train
|
function wrap(func) {
return function wrappedParsePromise() {
var args = Array.prototype.slice.call(arguments, 0);
var parsePromise = func.apply(this, args);
var promise = $q(parsePromise.then.bind(parsePromise));
wrapParsePromise(promise, parsePromise);
return promise;
};
}
|
javascript
|
{
"resource": ""
}
|
q12449
|
wrapObject
|
train
|
function wrapObject(object, methods) {
if (!(methods instanceof Array)) methods = Array.prototype.slice.call(arguments, 1);
methods.forEach(function (method) {
object[method] = wrap(object[method]);
});
}
|
javascript
|
{
"resource": ""
}
|
q12450
|
eatUnquoted
|
train
|
function eatUnquoted(stream) {
const start = stream.pos;
if (stream.eatWhile(isUnquoted)) {
stream.start = start;
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
q12451
|
doSubmit
|
train
|
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n])
.appendTo(form)[0]);
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
|
javascript
|
{
"resource": ""
}
|
q12452
|
checkState
|
train
|
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q12453
|
doAjaxSubmit
|
train
|
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}
|
javascript
|
{
"resource": ""
}
|
q12454
|
train
|
function (properties, rule, options) {
var signature = rule.selector || rule.params;
var name = signature.match(customPropertyPattern).shift().replace(propertyKeyDelimiter, '').trim();
var parameters = signature.replace(customPropertyPattern, '').match(parametersPattern).map(function (parameter) {
return parameter.replace(options.syntax.parameter, options.syntax.variable);
});
var property = {
name: name,
parameters: parameters,
declarations: rule.nodes.map(function (node) {
return {
property: node.prop,
value: node.value,
// Parses variables that are also parameters. Ignores other variables for compatability with Sass variables.
// We only need the index of each parameter
variables: (node.value.match(variablesPattern) || [])
.filter(function (variable) {
return node.value.indexOf(variable) !== -1;
}).map(function (variable) {
return parameters.indexOf(variable);
})
};
})
};
properties[options.syntax.property + property.name + signatureSeparator + parameters.length] = property;
rule.remove();
}
|
javascript
|
{
"resource": ""
}
|
|
q12455
|
train
|
function (customProperty, declaration) {
customProperty.declarations.forEach(function (customDeclaration) {
// No need to copy value here as replace will copy value
var value = customDeclaration.value;
// Replace parameter variables with user given values
customDeclaration.variables.forEach(function (variable) {
value = value.replace(customProperty.parameters[variable],
declaration.values[variable]);
});
// Using cloneBefore to insert declaration provides sourcemap support
declaration.cloneBefore({
prop: customDeclaration.property,
value: value
});
});
declaration.remove();
}
|
javascript
|
{
"resource": ""
}
|
|
q12456
|
abort
|
train
|
function abort(options = {}) {
if (process.platform !== 'win32' && process.platform !== 'linux') {
throw new Error('Unsupported OS (only Windows and Linux are supported)!');
}
let cmdarguments = ['shutdown'];
if (process.platform === 'win32') {
cmdarguments.push('-a'); // abort
} else {
// linux
cmdarguments.push('-c'); // cancel a pending shutdown
}
executeCmd(cmdarguments, options.debug, options.quitapp);
}
|
javascript
|
{
"resource": ""
}
|
q12457
|
setTimer
|
train
|
function setTimer(timervalue) {
let cmdarguments = [];
if (process.platform === 'linux' ) {
if (timervalue) {
cmdarguments.push(timervalue.toString());
} else {
cmdarguments.push('now');
}
}
if (process.platform === 'darwin') {
if (timervalue) {
let timeinminutes = Math.round(Number(timervalue) / 60);
if (timeinminutes === 0) {
timeinminutes = 1; // min 1 minute
}
cmdarguments.push('-t ' + timeinminutes.toString());
} else {
cmdarguments.push('now');
}
}
if (process.platform === 'win32') {
if (timervalue) {
cmdarguments.push('-t ' + timervalue.toString());
} else {
cmdarguments.push('-t 0'); // set to 0 because default is 20 seconds
}
}
return cmdarguments;
}
|
javascript
|
{
"resource": ""
}
|
q12458
|
getActualTarget
|
train
|
function getActualTarget() {
var scrollX = window.scrollX,
scrollY = window.scrollY;
// IE is stupid and doesn't support scrollX/Y
if(scrollX === undefined){
scrollX = d.body.scrollLeft;
scrollY = d.body.scrollTop;
}
return d.elementFromPoint(this.pageX - window.scrollX, this.pageY - window.scrollY);
}
|
javascript
|
{
"resource": ""
}
|
q12459
|
defaultLogger
|
train
|
function defaultLogger() {
if(!_defaultLogger) {
var prefix = 'master';
if(cluster.worker) {
prefix = 'work ' + cluster.worker.id;
}
_defaultLogger = new Logger(process.stdout, prefix, utils.LogLevel.INFO, []);
}
return _defaultLogger;
}
|
javascript
|
{
"resource": ""
}
|
q12460
|
typeOf
|
train
|
function typeOf(value) {
var s = typeof value;
if(s === 'object') {
if(value) {
if(value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
q12461
|
treatAs
|
train
|
function treatAs(value) {
var s = typeof value;
if(s === 'object') {
if(value) {
return Object.prototype.toString.call(value).match(/^\[object\s(.*)\]$/)[1];
} else {
s = 'null';
}
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
q12462
|
toInteger
|
train
|
function toInteger(val) {
var v = +val;// toNumber conversion
if(isNaN(v)) {
return 0;
}
if(v === 0 || v === Infinity || v == -Infinity) {
return v;
}
if(v < 0) {
return -1 * Math.floor(-v);
} else {
return Math.floor(v);
}
}
|
javascript
|
{
"resource": ""
}
|
q12463
|
UnknownReference
|
train
|
function UnknownReference(id, prop, missing) {
this._id = id;
this._prop = prop;
this._missing = missing;
}
|
javascript
|
{
"resource": ""
}
|
q12464
|
train
|
function (obj, prop, value) {
shared.utils.dassert(getTracker(obj) === this);
this._lastTx = this.tc().addNew(obj, prop, value, this._lastTx);
}
|
javascript
|
{
"resource": ""
}
|
|
q12465
|
train
|
function (obj) {
shared.utils.dassert(getTracker(obj) === this);
this._rev += 1;
this._type = shared.types.TypeStore.instance().type(obj);
}
|
javascript
|
{
"resource": ""
}
|
|
q12466
|
MongoStore
|
train
|
function MongoStore(options) {
if (typeof options === "undefined") { options = {
}; }
_super.call(this);
this._logger = shared.utils.defaultLogger();
// Database stuff
this._collection = null;
this._pending = [];
// Outstanding work queue
this._root = null;
// Root object
this._cache = new shared.mtx.ObjectCache();
this._host = options.host || 'localhost';
this._port = options.port || 27017;
this._dbName = options.db || 'shared';
this._collectionName = options.collection || 'shared';
this._safe = options.safe || 'false';
this._logger.debug('STORE', '%s: Store created', this.id());
}
|
javascript
|
{
"resource": ""
}
|
q12467
|
saveFile
|
train
|
function saveFile(html) {
fs.outputFile(options.outputFile, html, function(err, data) {
if (err) {
console.log(error('ERROR!'));
console.dir(err);
process.exit(1);
}
console.log(good('\n\nAll done!'));
console.log('Created file: ' + good(options.outputFile));
});
}
|
javascript
|
{
"resource": ""
}
|
q12468
|
doTemplating
|
train
|
function doTemplating(json) {
// Adding '#styleguide .hljs pre' to highlight css, to override common used styling for 'pre'
highlightSource = highlightSource.replace('.hljs {', '#styleguide .hljs pre, .hljs {');
handlebars.registerPartial("jquery", '<script>\n' + jqSource+ '\n</script>');
handlebars.registerPartial("theme", '<style>\n' + themeSource + '\n</style>');
handlebars.registerPartial("highlight", '<style>\n' + highlightSource + '\n</style>');
var template = handlebars.compile(templateSource);
return template(json);
}
|
javascript
|
{
"resource": ""
}
|
q12469
|
Seeker
|
train
|
function Seeker(cron, now) {
if (cron.parts === null) {
throw new Error('No schedule found');
}
var date;
if (cron.options.timezone) {
date = moment.tz(now, cron.options.timezone);
} else {
date = moment(now);
}
if (!date.isValid()) {
throw new Error('Invalid date provided');
}
if (date.seconds() > 0) {
// Add a minute to the date to prevent returning dates in the past
date.add(1, 'minute');
}
this.cron = cron;
this.now = date;
this.date = date;
this.pristine = true;
}
|
javascript
|
{
"resource": ""
}
|
q12470
|
train
|
function(parts, date, reverse) {
var operation = 'add';
var reset = 'startOf';
if (reverse) {
operation = 'subtract';
reset = 'endOf';
date.subtract(1, 'minute'); // Ensure prev and next cannot be same time
}
var retry = 24;
while (--retry) {
shiftMonth(parts, date, operation, reset);
var monthChanged = shiftDay(parts, date, operation, reset);
if (!monthChanged) {
var dayChanged = shiftHour(parts, date, operation, reset);
if (!dayChanged) {
var hourChanged = shiftMinute(parts, date, operation, reset);
if (!hourChanged) {
break;
}
}
}
}
if (!retry) {
throw new Error('Unable to find execution time for schedule');
}
date.seconds(0).milliseconds(0);
// Return new moment object
return moment(date);
}
|
javascript
|
{
"resource": ""
}
|
|
q12471
|
DebugLog
|
train
|
function DebugLog(msg)
{
console.log("[PSN] :: " + ((typeof msg == "object") ? JSON.stringify(msg, null, 2) : msg));
}
|
javascript
|
{
"resource": ""
}
|
q12472
|
GetHeaders
|
train
|
function GetHeaders(additional_headers)
{
var ret_headers = {};
// clone default headers into our return object (parsed)
for(var key in headers)
{
ret_headers[key] = ParseStaches(headers[key]);
}
// add accept-language header based on our language
ret_headers['Accept-Language'] = auth_obj.npLanguage + "," + languages.join(',');
// add access token (if we have one)
if (auth_obj.access_token)
{
ret_headers['Authorization'] = 'Bearer ' + auth_obj.access_token;
}
// add additional headers (if supplied) (parsed)
if (additional_headers) for(var key in additional_headers)
{
ret_headers[key] = ParseStaches(additional_headers[key]);
}
return ret_headers;
}
|
javascript
|
{
"resource": ""
}
|
q12473
|
GetOAuthData
|
train
|
function GetOAuthData(additional_fields)
{
var ret_fields = {};
// clone base oauth settings
for(var key in oauth_settings)
{
ret_fields[key] = ParseStaches(oauth_settings[key]);
}
// add additional fields (if supplied)
if (additional_fields) for(var key in additional_fields)
{
ret_fields[key] = ParseStaches(additional_fields[key]);
}
return ret_fields;
}
|
javascript
|
{
"resource": ""
}
|
q12474
|
URLGET
|
train
|
function URLGET(url, fields, method, callback)
{
// method variable is optional
if (typeof method == "function")
{
callback = method;
method = "GET";
}
_URLGET(url, fields, GetHeaders({"Access-Control-Request-Method": method}), method, function(err, body) {
if (err)
{
// got error, bounce it up
if (callback) callback(err);
return;
}
else
{
var JSONBody;
if (typeof body == "object")
{
// already a JSON object?
JSONBody = body;
}
else
{
// try to parse JSON body
if (!body || !/\S/.test(body))
{
// string is empty, return empty object
if (callback) callback(false, {});
return;
}
else
{
try
{
JSONBody = JSON.parse(body);
}
catch(parse_err)
{
// error parsing JSON result
Log("Parse JSON error: " + parse_err + "\r\nURL:\r\n" + url + "\r\nBody:\r\n" + body);
if (callback) callback("Parse JSON error: " + parse_err);
return;
}
}
}
// success! return JSON object
if (callback) callback(false, JSONBody);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12475
|
Login
|
train
|
function Login(callback)
{
Log("Making OAuth Request...");
// start OAuth request (use our internal GET function as this is different!)
_URLGET(
// URL
urls.login_base + "/2.0/oauth/authorize",
// query string
GetOAuthData({
response_type: "code",
service_entity: "urn:service-entity:psn",
returnAuthCode: true,
state: "1156936032"
}),
// headers
{
'User-Agent': ParseStaches(useragent)
},
function(err, body, response)
{
if (err)
{
// return login error
if (callback) callback(err);
return;
}
else
{
// get the login path
var login_referrer = response.req.path;
Log("Logging in...");
// now actually login using the previous URL as the referrer
request(
{
url: urls.login_base + "/login.do",
method: "POST",
headers:
{
'User-Agent': ParseStaches(useragent),
'X-Requested-With': headers["X-Requested-With"],
'Origin': 'https://auth.api.sonyentertainmentnetwork.com',
'Referer': login_referrer,
},
form:
{
'params': new Buffer(login_params).toString('base64'),
'j_username': login_details.email,
'j_password': login_details.password
}
},
function (err, response, body)
{
if (err)
{
// login failed
Log("Failed to make login request");
if (callback) callback(err);
return;
}
else
{
Log("Following login...");
request.get(response.headers.location, function (err, response, body)
{
if (!err)
{
// parse URL
var result = url.parse(response.req.path, true);
if (result.query.authentication_error)
{
// try to extract login error from website
var error_message = /errorDivMessage\"\>\s*(.*)\<br \/\>/.exec(body);
if (error_message && error_message[1])
{
Log("Login failed! Error from Sony: " + error_message[1]);
if (callback) callback(error_message[1]);
}
else
{
Log("Login failed!");
if (callback) callback("Login failed!");
}
return;
}
else
{
// no auth error!
var auth_result = url.parse(result.query.targetUrl, true);
if (auth_result.query.authCode)
{
Log("Got auth code: " + auth_result.query.authCode);
auth_obj.auth_code = auth_result.query.authCode;
if (callback) callback(false);
return;
}
else
{
Log("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
if (callback) callback("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
return;
}
}
}
else
{
Log("Auth code fetch error: " + err);
if (callback) callback(err);
return;
}
});
}
}
);
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
q12476
|
GetAccessToken
|
train
|
function GetAccessToken(callback)
{
// do we have a refresh token? Or do we need to login from scratch?
if (auth_obj.refresh_token)
{
// we have a refresh token!
Log("Refreshing session...");
if (!auth_obj.refresh_token)
{
if (callback) callback("No refresh token found!");
return;
}
// request new access_token
request.post(
{
url: urls.oauth,
form: GetOAuthData({
"grant_type": "refresh_token",
"refresh_token": auth_obj.refresh_token
})
},
function(err, response, body)
{
_ParseTokenResponse(err, body, callback);
}
);
}
else
{
// no refresh token, sign-in from scratch
Log("Signing in with OAuth...");
// make sure we have an authcode
if (!auth_obj.auth_code)
{
if (callback) callback("No authcode available for OAuth!");
return;
}
// request initial access_token
request.post(
{
url: urls.oauth,
form: GetOAuthData({
"grant_type": "authorization_code",
"code": auth_obj.auth_code
})
},
function(err, response, body)
{
_ParseTokenResponse(err, body, callback);
}
);
}
}
|
javascript
|
{
"resource": ""
}
|
q12477
|
GetUserData
|
train
|
function GetUserData(callback)
{
Log("Fetching user profile data");
// get the current user's data
parent.Get("https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info", {}, function(error, data)
{
if (error)
{
Log("Error fetching user profile: " + error);
if (callback) callback("Error fetching user profile: " + error);
return;
}
if (!data.onlineId)
{
Log("Missing PSNId from profile result: " + JSON.stringify(data, null, 2));
if (callback) callback("Missing PSNId from profile result: " + JSON.stringify(data, null, 2));
return;
}
// store user ID
Log("We're logged in as " + data.onlineId);
auth_obj.username = data.onlineId;
// store user's region too
auth_obj.region = data.region;
// save updated data object
DoSave(function()
{
// return no error
if (callback) callback(false);
}
);
// supply self to let API know we are a token fetch function
}, GetUserData);
}
|
javascript
|
{
"resource": ""
}
|
q12478
|
CheckTokens
|
train
|
function CheckTokens(callback, token_fetch)
{
// build list of tokens we're missing
var todo = [];
// force token_fetch to an array
token_fetch = [].concat(token_fetch);
// make sure we're actually logged in first
if (!auth_obj.auth_code)
{
Log("Need to login - no auth token found");
todo.push({name: "Login", func: Login});
}
if (!auth_obj.expire_time || auth_obj.expire_time < new Date().getTime())
{
// token has expired! Fetch access_token again
Log("Need to fetch access tokens - tokens expired");
todo.push({name: "GetAccessToken", func: GetAccessToken});
}
else if (!auth_obj.access_token)
{
// we have no access token (?!)
Log("Need to fetch access tokens - no token available");
todo.push({name: "GetAccessToken", func: GetAccessToken});
}
if (!auth_obj.username || !auth_obj.region)
{
// missing player username/region
Log("Need to fetch userdata - no region or username available");
todo.push({name: "GetUserData", func: GetUserData});
}
if (todo.length == 0)
{
// everything is fine
if (callback) callback(false);
}
else
{
// work through our list of tokens we need to update
var step = function()
{
var func = todo.shift();
if (!func)
{
// all done!
if (callback) callback(false);
return;
}
if (token_fetch.indexOf(func.func) >= 0)
{
// if we're actually calling a token fetch function, skip!
process.nextTick(step);
}
else
{
func.func(function(error) {
if (error)
{
// token fetching error!
if (callback) callback(func.name + " :: " + error);
return;
}
// do next step
process.nextTick(step);
});
}
};
// start updating tokens
process.nextTick(step);
}
}
|
javascript
|
{
"resource": ""
}
|
q12479
|
train
|
function()
{
var func = todo.shift();
if (!func)
{
// all done!
if (callback) callback(false);
return;
}
if (token_fetch.indexOf(func.func) >= 0)
{
// if we're actually calling a token fetch function, skip!
process.nextTick(step);
}
else
{
func.func(function(error) {
if (error)
{
// token fetching error!
if (callback) callback(func.name + " :: " + error);
return;
}
// do next step
process.nextTick(step);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12480
|
MakePSNRequest
|
train
|
function MakePSNRequest(method, url, fields, callback, token_fetch)
{
// use fields var as callback if it's missed out
if (typeof fields == "function")
{
token_fetch = false;
callback = fields;
fields = {};
}
else if (typeof method == "function")
{
token_fetch = false;
callback = method;
}
// parse stache fields in fields list
for(var field_key in fields)
{
fields[field_key] = ParseStaches(fields[field_key]);
}
CheckTokens(function(error)
{
// check our tokens are fine
if (!error)
{
// make PSN GET request
URLGET(
// parse URL for region etc.
ParseStaches(url),
fields,
method,
function(error, data)
{
if (error)
{
Log("PSN " + method + " Error: " + error);
if (callback) callback(error);
return;
}
if (data.error && (data.error.code === 2105858 || data.error.code === 2138626))
{
// access token has expired/failed/borked
// login again!
Log("Access token failure, try to login again.");
Login(function(error) {
if (error)
{
if (callback) callback(error);
return;
}
// call ourselves
parent.Get(url, fields, callback, token_fetch);
});
}
if (data.error && data.error.message)
{
// server error
if (callback) callback(data.error.code + ": " + data.error.message, data.error);
return;
}
// everything is fine! return data
if (callback) callback(false, data);
}
);
}
else
{
Log("Token error: " + error);
if (callback) callback(error);
return;
}
}, token_fetch);
}
|
javascript
|
{
"resource": ""
}
|
q12481
|
Ready
|
train
|
function Ready()
{
if (options.autoconnect)
{
// make a connection request immediately (optional)
parent.GetPSN(true, function() {
if (options.onReady) options.onReady();
return;
});
}
else
{
// just callback that we're ready (if anyone is listening)
if (options.onReady) options.onReady();
return;
}
}
|
javascript
|
{
"resource": ""
}
|
q12482
|
squaredEuclideanDistance
|
train
|
function squaredEuclideanDistance (point1, point2) {
var result = 0,
i = 0;
for (; i < point1.length; i++) {
result += Math.pow(point1[i] - point2[i], 2);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q12483
|
getNeighbourhood
|
train
|
function getNeighbourhood (dimensionNumber) {
var neighbourhood = moore(2, dimensionNumber),
origin = [],
dimension;
for (dimension = 0; dimension < dimensionNumber; dimension++) {
origin.push(0);
}
neighbourhood.push(origin);
// sort by ascending distance to optimize proximity checks
// see point 5.1 in Parallel Poisson Disk Sampling by Li-Yi Wei, 2008
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.460.3061&rank=1
neighbourhood.sort(function (n1, n2) {
var squareDist1 = 0,
squareDist2 = 0;
for (var dimension = 0; dimension < dimensionNumber; dimension++) {
squareDist1 += Math.pow(n1[dimension], 2);
squareDist2 += Math.pow(n2[dimension], 2);
}
if (squareDist1 < squareDist2) {
return -1;
} else if(squareDist1 > squareDist2) {
return 1;
} else {
return 0;
}
});
return neighbourhood;
}
|
javascript
|
{
"resource": ""
}
|
q12484
|
provide
|
train
|
function provide() {
if (console) console.warn('@provide is now deprecated. Use @connect instead');
return composeWithContext(Array.prototype.slice.call(arguments))
}
|
javascript
|
{
"resource": ""
}
|
q12485
|
parseNodeValue
|
train
|
function parseNodeValue(node) {
const childNodes = node && node.childNodes && [...node.childNodes];
if (!childNodes) {
return {};
}
// Trying to find and parse CDATA as JSON
const cdatas = childNodes.filter((childNode) => childNode.nodeName === '#cdata-section');
if (cdatas && cdatas.length > 0) {
try {
return JSON.parse(cdatas[0].data);
} catch (e) {}
}
// Didn't find any CDATA or failed to parse it as JSON
return childNodes.reduce((previousText, childNode) => {
let nodeText = '';
switch (childNode.nodeName) {
case '#text':
nodeText = childNode.textContent.trim();
break;
case '#cdata-section':
nodeText = childNode.data;
break;
}
return previousText + nodeText;
}, '');
}
|
javascript
|
{
"resource": ""
}
|
q12486
|
parseXMLNode
|
train
|
function parseXMLNode(node) {
const parsedNode = {
attributes: {},
children: {},
value: {},
};
parsedNode.value = parseNodeValue(node);
if (node.attributes) {
[...node.attributes].forEach((nodeAttr) => {
if (nodeAttr.nodeName && nodeAttr.nodeValue !== undefined && nodeAttr.nodeValue !== null) {
parsedNode.attributes[nodeAttr.nodeName] = nodeAttr.nodeValue;
}
});
}
if (node.childNodes) {
[...node.childNodes]
.filter((childNode) => childNode.nodeName.substring(0, 1) !== '#')
.forEach((childNode) => {
parsedNode.children[childNode.nodeName] = parseXMLNode(childNode);
});
}
return parsedNode;
}
|
javascript
|
{
"resource": ""
}
|
q12487
|
async
|
train
|
function async(makeGenerator) {
return () => {
const generator = makeGenerator(...arguments);
function handle(result) {
// result => { done: [Boolean], value: [Object] }
if (result.done) {
return Promise.resolve(result.value);
}
return Promise.resolve(result.value).then(res => {
return handle(generator.next(res));
}, err => {
return handle(generator.throw(err));
});
}
try {
return handle(generator.next());
} catch (ex) {
return Promise.reject(ex);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q12488
|
runMultiple
|
train
|
function runMultiple(input, options) {
return new Promise((resolve, reject) => {
let commands = input;
// set default options
const defaultOpts = {
cwd: process.cwd(),
verbose: DEFAULT_VERBOSE,
mode: SEQUENTIAL,
logger: console.log,
};
// set global options
const globalOpts = Object.assign({}, defaultOpts, options);
// resolve string to proper input type
if (typeof commands === 'string') {
commands = [{ command: commands }];
}
// start execution
if (commands && typeof commands === 'object') {
if (Object.prototype.toString.call(commands) !== '[object Array]') {
// not array
commands = [commands];
}
else {
// is array, check type of children
commands = commands.map(cmd => typeof cmd === 'object' ? cmd : { command: cmd });
}
// run commands in parallel
if (globalOpts.mode === PARALLEL) {
const promises = commands.map(cmd => {
const resolvedOpts = Object.assign({}, globalOpts, cmd);
return run(resolvedOpts);
});
Promise.all(promises).then(resolve, reject);
}
else { // run commands in sequence (default)
async(function* () {
try {
const results = [];
for (const i in commands) {
const cmd = commands[i];
const resolvedOpts = Object.assign({}, globalOpts, cmd);
const result = yield run(resolvedOpts);
results.push(result);
}
if (results) {
resolve(results);
}
else {
reject('Falsy value in results');
}
}
catch (e) {
reject(e);
}
})();
}
}
else {
reject('Invalid input');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12489
|
itemsForCounter
|
train
|
function itemsForCounter(flushInterval, host, key, value) {
const avg = value / (flushInterval / 1000); // calculate "per second" rate
return [
{
host,
key: `${key}[total]`,
value,
},
{
host,
key: `${key}[avg]`,
value: avg,
},
];
}
|
javascript
|
{
"resource": ""
}
|
q12490
|
itemsForTimer
|
train
|
function itemsForTimer(percentiles, host, key, data) {
const values = data.sort((a, b) => (a - b));
const count = values.length;
const min = values[0];
const max = values[count - 1];
let mean = min;
let maxAtThreshold = max;
const items = [
{
host,
key: `${key}[lower]`,
value: min || 0,
},
{
host,
key: `${key}[upper]`,
value: max || 0,
},
{
host,
key: `${key}[count]`,
value: count,
},
];
percentiles.forEach((percentile) => {
const strPercentile = percentile.toString().replace('.', '_');
if (count > 1) {
const thresholdIndex = Math.round(((100 - percentile) / 100) * count);
const numInThreshold = count - thresholdIndex;
const percentValues = values.slice(0, numInThreshold);
maxAtThreshold = percentValues[numInThreshold - 1];
// Average the remaining timings
let sum = 0;
for (let i = 0; i < numInThreshold; i += 1) {
sum += percentValues[i];
}
mean = sum / numInThreshold;
}
items.push({
host,
key: `${key}[mean][${strPercentile}]`,
value: mean || 0,
});
items.push({
host,
key: `${key}[upper][${strPercentile}]`,
value: maxAtThreshold || 0,
});
});
return items;
}
|
javascript
|
{
"resource": ""
}
|
q12491
|
flush
|
train
|
function flush(targetBuilder, sender, flushInterval, timestamp, metrics) {
debug(`starting flush for timestamp ${timestamp}`);
const flushStart = tsNow();
const handle = (processor, stat, value) => {
try {
const { host, key } = targetBuilder(stat);
processor(host, key, value).forEach((item) => {
sender.addItem(item.host, item.key, item.value);
debug(`${item.host} -> ${item.key} -> ${item.value}`);
});
} catch (err) {
stats.last_exception = tsNow();
error(err);
}
};
const counterProcessor = itemsForCounter.bind(undefined, flushInterval);
Object.keys(metrics.counters).forEach((stat) => {
handle(counterProcessor, stat, metrics.counters[stat]);
});
const timerProcessor = itemsForTimer.bind(undefined, metrics.pctThreshold);
Object.keys(metrics.timers).forEach((stat) => {
handle(timerProcessor, stat, metrics.timers[stat]);
});
Object.keys(metrics.gauges).forEach((stat) => {
handle(itemsForGauge, stat, metrics.gauges[stat]);
});
stats.flush_length = sender.items.length;
debug(`flushing ${stats.flush_length} items to zabbix`);
// Send the items to Zabbix
sender.send((err, res) => {
if (err) {
stats.last_exception = tsNow();
error(err);
// eslint-disable-next-line no-param-reassign
sender.items = [];
} else {
stats.last_flush = timestamp;
stats.flush_time = flushStart - stats.last_flush;
debug(`flush completed in ${stats.flush_time} seconds`);
}
if (res.info) {
info(res.info);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12492
|
status
|
train
|
function status(writeCb) {
Object.keys(stats).forEach((stat) => {
writeCb(null, 'zabbix', stat, stats[stat]);
});
}
|
javascript
|
{
"resource": ""
}
|
q12493
|
init
|
train
|
function init(startupTime, config, events, l) {
logger = l;
let targetBuilder;
if (config.zabbixTargetHostname) {
targetBuilder = targetStatic.bind(undefined, config.zabbixTargetHostname);
} else {
targetBuilder = targetDecode;
}
const sender = new ZabbixSender({
host: config.zabbixHost || 'localhost',
port: config.zabbixPort || '10051',
with_timestamps: config.zabbixSendTimestamps || false,
});
stats.last_flush = 0;
stats.last_exception = 0;
stats.flush_time = 0;
stats.flush_length = 0;
events.on('flush', flush.bind(undefined, targetBuilder, sender, config.flushInterval));
events.on('status', status);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q12494
|
collectProperties
|
train
|
function collectProperties(groups, properties) {
var collection = {};
for (var key in groups) {
if (Array.isArray(groups[key])) {
collection[key] = groups[key].reduce(function(coll, item) {
properties.forEach(function(prop) {
if (!coll[prop]) coll[prop] = [];
coll[prop] = coll[prop].concat(propertyAt(item,prop));
})
return coll;
}, {})
} else {
collection[key] = collectProperties(groups[key], properties);
}
}
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q12495
|
fileUriToPath
|
train
|
function fileUriToPath (uri) {
if ('string' != typeof uri ||
uri.length <= 7 ||
'file://' != uri.substring(0, 7)) {
throw new TypeError('must pass in a file:// URI to convert to a file path');
}
var rest = decodeURI(uri.substring(7));
var firstSlash = rest.indexOf('/');
var host = rest.substring(0, firstSlash);
var path = rest.substring(firstSlash + 1);
// 2. Scheme Definition
// As a special case, <host> can be the string "localhost" or the empty
// string; this is interpreted as "the machine from which the URL is
// being interpreted".
if ('localhost' == host) host = '';
if (host) {
host = sep + sep + host;
}
// 3.2 Drives, drive letters, mount points, file system root
// Drive letters are mapped into the top of a file URI in various ways,
// depending on the implementation; some applications substitute
// vertical bar ("|") for the colon after the drive letter, yielding
// "file:///c|/tmp/test.txt". In some cases, the colon is left
// unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
// colon is simply omitted, as in "file:///c/tmp/test.txt".
path = path.replace(/^(.+)\|/, '$1:');
// for Windows, we need to invert the path separators from what a URI uses
if (sep == '\\') {
path = path.replace(/\//g, '\\');
}
if (/^.+\:/.test(path)) {
// has Windows drive at beginning of path
} else {
// unix path…
path = sep + path;
}
return host + path;
}
|
javascript
|
{
"resource": ""
}
|
q12496
|
parseHeaders
|
train
|
function parseHeaders() {
var str = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var lines = str.split(/\r?\n/);
var fields = {};
var index = undefined;
var line = undefined;
var field = undefined;
var val = undefined;
lines.pop(); // trailing CRLF
for (var i = 0, len = lines.length; i < len; i += 1) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
}
|
javascript
|
{
"resource": ""
}
|
q12497
|
buildHashTimeLockContract
|
train
|
function buildHashTimeLockContract(network, xHash, destH160Addr, revokerH160Addr, lockTime) {
const bitcoinNetwork = bitcoin.networks[network];
const redeemScript = bitcoin.script.compile([
bitcoin.opcodes.OP_IF,
bitcoin.opcodes.OP_SHA256,
Buffer.from(xHash, 'hex'),
bitcoin.opcodes.OP_EQUALVERIFY,
bitcoin.opcodes.OP_DUP,
bitcoin.opcodes.OP_HASH160,
Buffer.from(hex.stripPrefix(destH160Addr), 'hex'),
bitcoin.opcodes.OP_ELSE,
bitcoin.script.number.encode(lockTime),
bitcoin.opcodes.OP_CHECKLOCKTIMEVERIFY,
bitcoin.opcodes.OP_DROP,
bitcoin.opcodes.OP_DUP,
bitcoin.opcodes.OP_HASH160,
Buffer.from(hex.stripPrefix(revokerH160Addr), 'hex'),
bitcoin.opcodes.OP_ENDIF,
bitcoin.opcodes.OP_EQUALVERIFY,
bitcoin.opcodes.OP_CHECKSIG,
]);
const addressPay = bitcoin.payments.p2sh({
redeem: { output: redeemScript, network: bitcoinNetwork },
network: bitcoinNetwork,
});
const { address } = addressPay;
return {
// contract
address,
redeemScript: redeemScript.toString('hex'),
// params
xHash,
lockTime,
redeemer: hex.ensurePrefix(destH160Addr),
revoker: hex.ensurePrefix(revokerH160Addr),
};
}
|
javascript
|
{
"resource": ""
}
|
q12498
|
hashForRedeemSig
|
train
|
function hashForRedeemSig(network, txid, address, value, redeemScript) {
const tx = btcUtil.buildIncompleteRedeem(network, txid, address, value);
const sigHash = tx.hashForSignature(
0,
new Buffer.from(redeemScript, 'hex'),
bitcoin.Transaction.SIGHASH_ALL
);
return sigHash.toString('hex');
}
|
javascript
|
{
"resource": ""
}
|
q12499
|
hashForRevokeSig
|
train
|
function hashForRevokeSig(network, txid, address, value, lockTime, redeemScript) {
const tx = btcUtil.buildIncompleteRevoke(network, txid, address, value, lockTime);
const sigHash = tx.hashForSignature(
0,
new Buffer.from(redeemScript, 'hex'),
bitcoin.Transaction.SIGHASH_ALL
);
return sigHash.toString('hex');
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.