text
stringlengths 2
6.14k
|
|---|
#!/usr/bin/env node
import _ from 'lodash';
import fs from 'fs';
import program from 'commander';
import path from 'path';
import checkEnv from 'check-env';
import stripJsonComments from 'strip-json-comments';
import * as helpers from './helpers';
import { ConfigurationError } from './errors';
import { version } from '../package.json';
function readJSONConfig(filePath) {
const configFile = fs.readFileSync(filePath, { encoding: 'utf8' });
try {
return JSON.parse(stripJsonComments(configFile));
} catch (err) {
if (err instanceof SyntaxError) {
throw new ConfigurationError('The configuration file contains invalid JSON');
} else {
throw err;
}
}
}
function run() {
program
.version(version)
.option('-c, --config <path>',
'Sets the path to the config file, otherwise read from the env variable CONFIG_FILE.'
)
.parse(process.argv);
// If no config option is given, try to use the env variable:
if (!program.config) checkEnv(['CONFIG_FILE']);
else process.env.CONFIG_FILE = program.config;
const completePath = path.resolve(process.cwd(), process.env.CONFIG_FILE);
const config = _.endsWith(process.env.CONFIG_FILE, '.js') ?
require(completePath) : readJSONConfig(completePath);
helpers.createBots(config);
}
export default run;
|
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
/* eslint-env node */
/* eslint-disable no-console */
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const rename = require('gulp-rename');
const rollup = require('rollup-stream');
const source = require('vinyl-source-stream');
const del = require('del');
const runseq = require('run-sequence');
const closure = require('google-closure-compiler').gulp();
const babel = require('rollup-plugin-babel');
function debugify(sourceName, fileName, extraRollupOptions) {
if (!fileName)
fileName = sourceName;
const options = {
entry: `./entrypoints/${sourceName}-index.js`,
format: 'iife',
moduleName: 'webcomponentsjs'
};
Object.assign(options, extraRollupOptions);
return rollup(options)
.pipe(source(`${sourceName}-index.js`), 'entrypoints')
.pipe(rename(fileName + '.js'))
.pipe(gulp.dest('./'))
}
function closurify(sourceName, fileName) {
if (!fileName) {
fileName = sourceName;
}
const closureOptions = {
new_type_inf: true,
compilation_level: 'ADVANCED',
language_in: 'ES6_STRICT',
language_out: 'ES5_STRICT',
isolation_mode: 'IIFE',
assume_function_wrapper: true,
js_output_file: `${fileName}.js`,
warning_level: 'VERBOSE',
rewrite_polyfills: false,
module_resolution: 'NODE',
entry_point: `entrypoints/${sourceName}-index.js`,
dependency_mode: 'STRICT',
externs: [
'externs/webcomponents.js',
'node_modules/@webcomponents/custom-elements/externs/custom-elements.js',
'node_modules/@webcomponents/html-imports/externs/html-imports.js',
'node_modules/@webcomponents/shadycss/externs/shadycss-externs.js',
'node_modules/@webcomponents/shadydom/externs/shadydom.js'
]
};
return gulp.src([
'entrypoints/*.js',
'src/*.js',
'node_modules/es6-promise/lib/es6-promise/**/*.js',
'node_modules/@webcomponents/**/*.js',
'!node_modules/@webcomponents/*/externs/*.js',
'!node_modules/@webcomponents/*/node_modules/**',
'!**/bower_components/**'
], {base: './', follow: true})
.pipe(sourcemaps.init())
.pipe(closure(closureOptions))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('.'));
}
gulp.task('debugify-hi', () => {
return debugify('webcomponents-hi')
});
gulp.task('debugify-hi-ce', () => {
return debugify('webcomponents-hi-ce')
});
gulp.task('debugify-hi-sd-ce', () => {
return debugify('webcomponents-hi-sd-ce')
});
gulp.task('debugify-hi-sd-ce-pf', () => {
// The es6-promise polyfill needs to set the correct context.
// See https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined
const extraOptions = {context: 'window'};
return debugify('webcomponents-hi-sd-ce-pf', 'webcomponents-lite', extraOptions)
});
gulp.task('debugify-sd-ce', () => {
return debugify('webcomponents-sd-ce')
});
gulp.task('closurify-hi', () => {
return closurify('webcomponents-hi')
});
gulp.task('closurify-hi-ce', () => {
return closurify('webcomponents-hi-ce')
});
gulp.task('closurify-hi-sd-ce', () => {
return closurify('webcomponents-hi-sd-ce')
});
gulp.task('closurify-hi-sd-ce-pf', () => {
return closurify('webcomponents-hi-sd-ce-pf', 'webcomponents-lite')
});
gulp.task('closurify-sd-ce', () => {
return closurify('webcomponents-sd-ce')
});
function singleLicenseComment() {
let hasLicense = false;
return (comment) => {
if (hasLicense) {
return false;
}
return hasLicense = /@license/.test(comment);
}
}
const babelOptions = {
presets: 'minify',
shouldPrintComment: singleLicenseComment()
};
gulp.task('debugify-ce-es5-adapter', () => {
return debugify('custom-elements-es5-adapter', '', {plugins: [babel(babelOptions)]});
});
gulp.task('default', ['closure']);
gulp.task('clean-builds', () => {
return del(['custom-elements-es5-adapter.js{,.map}', 'webcomponents*.js{,.map}', '!webcomponents-loader.js']);
});
gulp.task('debug', (cb) => {
const tasks = [
'debugify-hi',
'debugify-hi-ce',
'debugify-hi-sd-ce',
'debugify-hi-sd-ce-pf',
'debugify-sd-ce',
'debugify-ce-es5-adapter'
];
runseq('clean-builds', tasks, cb);
});
gulp.task('closure', (cb) => {
const tasks = [
'closurify-hi',
'closurify-hi-ce',
'closurify-hi-sd-ce',
'closurify-hi-sd-ce-pf',
'closurify-sd-ce',
'debugify-ce-es5-adapter'
];
runseq('clean-builds', ...tasks, cb);
});
|
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function isAlpha(c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
exports_1("isAlpha", isAlpha);
return {
setters: [],
execute: function () {
}
};
});
|
import AnnotationCommand from '../../ui/AnnotationCommand'
class LinkCommand extends AnnotationCommand {
canFuse() { return false }
/*
On link creation we collapse the selection, as this is a condition for the
EditLinkTool to be shown (see EditAnnotationCommand)
*/
executeCreate(params) {
let result = super.executeCreate(params)
let editorSession = this._getEditorSession(params)
editorSession.transaction((tx) => {
tx.setSelection(tx.selection.collapse())
})
return result
}
}
export default LinkCommand
|
'use strict';
/**
* This test is only run when the --with-docs flag is active : `npm run test-e2e -- --with-docs`
* or when WITH_DOCS env variable is declared at true
*
* It's only meant to be run against a built version (also built with the flag --with-docs or WITH_DOCS env variable declared)
*
* This is not a documented feature. This is more to ensure on travis that not only:
* - the doc generates correctly without failing
* - but it also generates a correct output
*/
// before each 'it' of the following describe:
describe('Docs home page /docs', () => {
beforeEach(() => {
//go to page (if not yet)
goToUrl('/docs');
});
it('should have a title', () => {
expect(browser.getTitle()).toEqual('vanilla-es6-jspm');
});
it('should have a title in the header', () => {
expect(element(by.css('h1.blue-main-title')).getText()).toEqual('vanilla-es6-jspm');
});
});
|
import yamljs from "yamljs";
const yaml = `
---
receipt: Oz-Ware Purchase Invoice
date: 2012-08-06
customer:
first_name: Dorothy
family_name: Gale
items:
- part_no: A4786
descrip: Water Bucket (Filled)
price: 1.47
quantity: 4
- part_no: E1628
descrip: High Heeled "Ruby" Slippers
size: 8
price: 133.7
quantity: 1
`;
const parsed = yamljs.parse(yaml);
const generatedString = yamljs.stringify(parsed, 4, 4);
// $ExpectError
yamljs.stringify(parsed, "");
|
import ReactionsController from 'app/controllers/reactions';
class AdminReactionsController extends ReactionsController {
}
export default AdminReactionsController;
|
// Copyright 2012 Mark Cavage, Inc. All rights reserved.
var socketio = require('socket.io');
var restify = require('../../lib');
///--- Globals
var HTML =
'<script src="/socket.io/socket.io.js"></script>\n' +
'<script>\n' +
'var socket = io("http://localhost:8080");\n' +
'socket.on("news", function (data) {\n' +
'console.log(data);\n' +
'socket.emit("my other event", { my: "data" });\n' +
'});\n' +
'</script>';
///--- Mainline
var server = restify.createServer();
var io = socketio(server.server);
server.get('/', function indexHTML(req, res, next) {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(HTML));
res.writeHead(200);
res.write(HTML);
res.end();
next();
});
io.on('connection', function(socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function(data) {
console.log(data);
});
});
server.listen(8080, function() {
console.log('socket.io server listening at %s', server.url);
});
|
/**
* @class Admin_Page_Venues
* @extends Admin_Page_Abstract
*/
var Admin_Page_Venues = Admin_Page_Abstract.extend({
/** @type String */
_class: 'Admin_Page_Venues'
});
|
"use strict";
const path = require("path");
const pMap = require("p-map");
const { Command } = require("@lerna/command");
const { rimrafDir } = require("@lerna/rimraf-dir");
const { promptConfirmation } = require("@lerna/prompt");
const { getFilteredPackages } = require("@lerna/filter-options");
const { pulseTillDone } = require("@lerna/pulse-till-done");
module.exports = factory;
function factory(argv) {
return new CleanCommand(argv);
}
class CleanCommand extends Command {
get requiresGit() {
return false;
}
initialize() {
let chain = Promise.resolve();
chain = chain.then(() => getFilteredPackages(this.packageGraph, this.execOpts, this.options));
chain = chain.then((filteredPackages) => {
this.directoriesToDelete = filteredPackages.map((pkg) => pkg.nodeModulesLocation);
});
return chain.then(() => {
if (this.options.yes) {
return true;
}
this.logger.info("", "Removing the following directories:");
this.logger.info(
"clean",
this.directoriesToDelete.map((dir) => path.relative(this.project.rootPath, dir)).join("\n")
);
return promptConfirmation("Proceed?");
});
}
execute() {
this.enableProgressBar();
const tracker = this.logger.newItem("clean");
const mapper = (dirPath) => {
tracker.info("clean", "removing", dirPath);
return pulseTillDone(rimrafDir(dirPath)).then(() => {
tracker.completeWork(1);
});
};
tracker.addWork(this.directoriesToDelete.length);
return pMap(this.directoriesToDelete, mapper, { concurrency: this.concurrency }).then(() => {
tracker.finish();
this.logger.success("clean", "finished");
});
}
}
module.exports.CleanCommand = CleanCommand;
|
/**
* The StoriesKeep view.
*/
define([
'jquery',
'backbone',
'underscore',
'handlebars',
'mps',
'simplePagination',
'text!static/templates/storiesKeep.handlebars',
], function($,Backbone,underscore,Handlebars,mps,simplePagination, storiesTPL) {
'use strict';
var StoriesKeepModel = Backbone.Model.extend({
defaults: {
total: null,
perpage: null,
page: null
},
})
var StoriesKeepView = Backbone.View.extend({
el: '#storiesKeepView',
template: Handlebars.compile(storiesTPL),
initialize: function() {
if (!this.$el.length) {
return
}
//CACHE
this.$htmlbody = $('html, body');
this.$sideBar = $('#sidebarNavView');
this.$sourcesBox = $('#sources-box');
this.$container = $('#crowdsourced-stories');
this.$spinner = $('#sources-spinner');
this.$listContainer = $('#storiesKeepList');
this.$paginationContainer = $('#pagination-container');
//VARS
this.model = new StoriesKeepModel({
total: this.$paginationContainer.data('total'),
perpage: this.$paginationContainer.data('perpage'),
page: this.$paginationContainer.data('page')
});
this.initPaginate();
},
initPaginate: function(){
// pagination
this.$paginationContainer.pagination({
items: this.model.get('total'),
itemsOnPage : this.model.get('perpage'),
currentPage : this.model.get('page'),
displayedPages: 3,
selectOnClick: false,
prevText: ' ',
nextText: ' ',
onPageClick: _.bind(function(pageNumber, event){
event.preventDefault();
this.$paginationContainer.pagination('drawPage', pageNumber);
this.$spinner.addClass('start');
this.$container.addClass('start');
($(window).width() >= 850 ) ? this.$htmlbody.animate({ scrollTop: this.$sideBar.offset().top }, 500) : this.$sourcesBox.animate({ scrollTop: 0 }, 500);
this.loadAjaxStories(pageNumber);
mps.publish('SourceStatic/Silentupdate',[{section: 'crowdsourced-stories', page: pageNumber}]);
}, this )
});
},
loadAjaxStories: function(page){
$.ajax({
url: '/stayinformed-stories.json',
type: 'GET',
dataType: 'json',
data: {
for_stay: true,
page: page,
perpage: this.model.get('perpage')
},
success: _.bind(function(data){
this.parse(data);
}, this ),
error: function(err){
console.log(err);
}
})
},
parse: function(data){
this.data = _.map(data, _.bind(function(item){
var img = (! item.media.length) ? null : item.media[item.media.length -1].preview_url;
var detail = (item.details.length > 295) ? item.details.substr(0, 295)+'...' : item.details;
return {
id: item.id,
title: item.title,
details: detail,
link: '/stories/'+item.id,
map: (img) ? 'http://gfw2stories.s3.amazonaws.com/uploads/' + img : 'https://maps.googleapis.com/maps/api/staticmap?center=' + item.lat + ',' + item.lng + '&zoom=2&size=80x80',
}
}, this ));
this.render();
},
render: function(){
this.$spinner.removeClass('start');
this.$container.removeClass('start');
this.$listContainer.html(this.template({ stories : this.data }));
mps.publish('SubItem/change');
}
});
return StoriesKeepView;
});
|
/*global describeComponent, setupComponent*/
define(function (require) {
'use strict';
var defineComponent = require('flight/lib/component');
var Example = require('mock/example');
describeMixin('mock/example_mixin', function () {
describe('defineComponent.teardownAll()', function () {
var result = [];
beforeEach(function () {
spyOn(defineComponent, 'teardownAll').and.callFake(function () {
result.push('call');
});
});
describe('automatically calls after each test', function () {
it('dummy', function () {
// do nothing
});
it('first call', function () {
expect(result.length).toEqual(1);
});
it('second call', function () {
expect(result.length).toEqual(2);
});
it('third call', function () {
expect(result.length).toEqual(3);
});
});
});
describe('this.component.teardown()', function () {
var result = [];
beforeEach(function () {
spyOn(this.Component.prototype, 'teardown').and.callFake(function () {
result.push('call');
});
});
it('should automatically call before this.setupComponent() if component exists', function () {
expect(this.component).toBeNull();
this.setupComponent();
expect(result.length).toEqual(0);
this.setupComponent();
expect(result.length).toEqual(1);
});
it('should be called by afterEach of before `it`', function () {
expect(result.length).toEqual(3);
});
});
describe('this.setupComponent()', function () {
it('provides the correct $node attribute', function () {
expect(this.$node).toBeNull();
this.setupComponent();
expect(this.$node instanceof jQuery).toBe(true);
expect(this.$node).toHaveClass('component-root');
});
it('sets the fixture if string given to first argument', function () {
this.setupComponent('<div id="test_fixture1"/>');
expect(this.$node).toHaveId('test_fixture1');
});
it('adds component-root class to fixture root', function () {
this.setupComponent('<div id="test_fixture1"/>');
expect(this.$node).toHaveClass('component-root');
});
it('sets the fixture if jQuery object given to first argument', function () {
this.setupComponent($('<div id="test_fixture2"/>'));
expect(this.$node).toHaveId('test_fixture2');
});
it('removes $node by afterEach', function () {
expect(this.$node).toBeNull();
expect($('.component-root').length).toEqual(0);
});
it('passes options to component if object givent to first argument', function () {
this.setupComponent();
expect(this.component.attr.param).toEqual('defaultParam');
this.setupComponent({
param: 'testParam'
});
expect(this.component.attr.param).toEqual('testParam');
});
it('sets the fixture and passed options to component if both arguments given', function () {
this.setupComponent('<div id="test_fixture_both"/>', {
param: 'testFixtureParam'
});
expect(this.component.attr.param).toEqual('testFixtureParam');
expect(this.$node).toHaveId('test_fixture_both');
});
it('resets a fixture if multiple calls', function () {
this.setupComponent('<div id="fixture1"/>');
expect(this.$node).toHaveId('fixture1');
this.setupComponent('<div id="fixture2"/>');
expect(this.$node).toHaveId('fixture2');
});
it('calls this.component.teardown() if multiple calls', function () {
spyOn(this.Component.prototype, 'teardown');
try {
this.setupComponent();
expect(this.component.teardown.calls.count()).toEqual(0);
this.setupComponent();
expect(this.component.teardown.calls.count()).toEqual(1);
} catch (e) {
}
});
});
});
});
|
System.register(["github:aurelia/dependency-injection@0.6.0/index"], function($__export) {
return { setters: [function(m) { for (var p in m) $__export(p, m[p]); }], execute: function() {} };
});
|
import Subscriber from '../Subscriber';
import Observable from '../Observable';
import Subject from '../Subject';
import Map from '../util/Map';
import FastMap from '../util/FastMap';
import { RefCountSubscription, GroupedObservable } from './groupBy-support';
import tryCatch from '../util/tryCatch';
import { errorObject } from '../util/errorObject';
export function groupBy(keySelector, elementSelector, durationSelector) {
return new GroupByObservable(this, keySelector, elementSelector, durationSelector);
}
export class GroupByObservable extends Observable {
constructor(source, keySelector, elementSelector, durationSelector) {
super();
this.source = source;
this.keySelector = keySelector;
this.elementSelector = elementSelector;
this.durationSelector = durationSelector;
}
_subscribe(subscriber) {
const refCountSubscription = new RefCountSubscription();
const groupBySubscriber = new GroupBySubscriber(subscriber, refCountSubscription, this.keySelector, this.elementSelector, this.durationSelector);
refCountSubscription.setPrimary(this.source.subscribe(groupBySubscriber));
return refCountSubscription;
}
}
class GroupBySubscriber extends Subscriber {
constructor(destination, refCountSubscription, keySelector, elementSelector, durationSelector) {
super();
this.refCountSubscription = refCountSubscription;
this.keySelector = keySelector;
this.elementSelector = elementSelector;
this.durationSelector = durationSelector;
this.groups = null;
this.destination = destination;
this.add(destination);
}
_next(x) {
let key = tryCatch(this.keySelector)(x);
if (key === errorObject) {
this.error(key.e);
}
else {
let groups = this.groups;
const elementSelector = this.elementSelector;
const durationSelector = this.durationSelector;
if (!groups) {
groups = this.groups = typeof key === 'string' ? new FastMap() : new Map();
}
let group = groups.get(key);
if (!group) {
groups.set(key, group = new Subject());
let groupedObservable = new GroupedObservable(key, group, this.refCountSubscription);
if (durationSelector) {
let duration = tryCatch(durationSelector)(new GroupedObservable(key, group));
if (duration === errorObject) {
this.error(duration.e);
}
else {
this.add(duration._subscribe(new GroupDurationSubscriber(key, group, this)));
}
}
this.destination.next(groupedObservable);
}
if (elementSelector) {
let value = tryCatch(elementSelector)(x);
if (value === errorObject) {
this.error(value.e);
}
else {
group.next(value);
}
}
else {
group.next(x);
}
}
}
_error(err) {
const groups = this.groups;
if (groups) {
groups.forEach((group, key) => {
group.error(err);
this.removeGroup(key);
});
}
this.destination.error(err);
}
_complete() {
const groups = this.groups;
if (groups) {
groups.forEach((group, key) => {
group.complete();
this.removeGroup(group);
});
}
this.destination.complete();
}
removeGroup(key) {
this.groups.delete(key);
}
}
class GroupDurationSubscriber extends Subscriber {
constructor(key, group, parent) {
super(null);
this.key = key;
this.group = group;
this.parent = parent;
}
_next(value) {
this.group.complete();
this.parent.removeGroup(this.key);
}
_error(err) {
this.group.error(err);
this.parent.removeGroup(this.key);
}
_complete() {
this.group.complete();
this.parent.removeGroup(this.key);
}
}
//# sourceMappingURL=groupBy.js.map
|
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
// there should be more tests here, but SQL tests can be fragile
// full coverage should be provided by integration tests
var expect = require('chai').use(require('chai-subset')).expect,
mssql = require('mssql'),
statements = require('../../../../src/data/mssql/statements'),
queries = require('../../../../src/query');
describe('azure-mobile-apps.data.mssql.statements', function () {
describe('delete', function () {
var del = statements.delete;
it('generates simple statement and parameters', function () {
var statement = del({ name: 'table' }, queries.create('table').where({ id: 'id' }));
expect(statement.sql).to.equal('SELECT * FROM [dbo].[table] WHERE ([id] = @p1);DELETE FROM [dbo].[table] WHERE ([id] = @p1);SELECT @@rowcount AS recordsAffected;');
expect(statement.parameters).to.containSubset([{ name: 'p1', value: 'id' }]);
});
it('generates soft delete statement and params', function () {
var statement = del({ name: 'table', softDelete: true }, queries.create('table').where({ id: 'id' }));
expect(statement.sql).to.equal('UPDATE [dbo].[table] SET [deleted] = 1 WHERE ([id] = @p1) AND [deleted] = 0;SELECT @@rowcount AS recordsAffected;SELECT * FROM [dbo].[table] WHERE ([id] = @p1);');
expect(statement.parameters).to.containSubset([{ name: 'p1', value: 'id' }]);
});
});
});
|
import { ActionHandler, Evented, FrameworkObject } from '@ember/-internals/runtime';
import { initViewElement } from '../system/utils';
import { cloneStates, states } from './states';
/**
`Ember.CoreView` is an abstract class that exists to give view-like behavior
to both Ember's main view class `Component` and other classes that don't need
the full functionality of `Component`.
Unless you have specific needs for `CoreView`, you will use `Component`
in your applications.
@class CoreView
@namespace Ember
@extends EmberObject
@deprecated Use `Component` instead.
@uses Evented
@uses Ember.ActionHandler
@private
*/
const CoreView = FrameworkObject.extend(Evented, ActionHandler, {
isView: true,
_states: cloneStates(states),
init() {
this._super(...arguments);
this._state = 'preRender';
this._currentState = this._states.preRender;
initViewElement(this);
if (!this.renderer) {
throw new Error(
`Cannot instantiate a component without a renderer. Please ensure that you are creating ${this} with a proper container/registry.`
);
}
},
/**
If the view is currently inserted into the DOM of a parent view, this
property will point to the parent of the view.
@property parentView
@type Ember.View
@default null
@private
*/
parentView: null,
instrumentDetails(hash) {
hash.object = this.toString();
hash.containerKey = this._debugContainerKey;
hash.view = this;
return hash;
},
/**
Override the default event firing from `Evented` to
also call methods with the given name.
@method trigger
@param name {String}
@private
*/
trigger(name, ...args) {
this._super(...arguments);
let method = this[name];
if (typeof method === 'function') {
return method.apply(this, args);
}
},
has(name) {
return typeof this[name] === 'function' || this._super(name);
},
});
CoreView.reopenClass({
isViewFactory: true,
});
export default CoreView;
|
var cfg = require('../../config');
var path = require('path');
var gulp = require('gulp');
var util = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
//-- Minify and mangle scripts
gulp.task('optimize:scripts', function() {
return gulp.src(cfg.resources.build.scripts)
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.on('error', function(e) {
util.log(e);
})
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(path.join(cfg.paths.site, cfg.paths.scripts)));
});
/* Refs:
https://www.npmjs.com/package/gulp-sourcemaps
https://www.npmjs.com/package/gulp-uglify
*/
|
// routes/say.js
var mongoose = require('mongoose');
exports.get_url = '/say/:id';
exports.get = function(req, res) {
var Say = mongoose.model('Say');
var id = req.params.id;
Say.find({_id: id}).populate('user').exec(function(err, says) {
if (err !== null) {
res.send('404', 404);
}
else if (says === null || says.length === 0) {
res.send('404', 404);
}
else {
var say = says[0];
var user_id = null;
if (req.isAuthenticated()) {
user_id = req.user._id;
}
say.renderMarkdown(user_id)
.then(function(rendered_html) {
res.render('say', {
logged_in: req.isAuthenticated(),
user_id: user_id,
nickname: (req.user || {}).nickname,
title: process.env.MD_TITLE || 'Markdown Chat',
date: say.date,
html: rendered_html,
date_str: say.readableDateStr(),
_id: say._id,
raw_markdown: (say.raw_markdown || '')
.replace(/(^\s+)|(\s+$)/g, '')
});
});
}
});
};
|
/*!
* VisualEditor UserInterface language tool class.
*
* @copyright 2011-2015 VisualEditor Team and others; see http://ve.mit-license.org
*/
/**
* UserInterface language tool.
*
* @class
* @extends ve.ui.InspectorTool
* @constructor
* @param {OO.ui.ToolGroup} toolGroup
* @param {Object} [config] Configuration options
*/
ve.ui.LanguageInspectorTool = function VeUiLanguageInspectorTool( toolGroup, config ) {
ve.ui.InspectorTool.call( this, toolGroup, config );
};
OO.inheritClass( ve.ui.LanguageInspectorTool, ve.ui.InspectorTool );
ve.ui.LanguageInspectorTool.static.name = 'language';
ve.ui.LanguageInspectorTool.static.group = 'meta';
ve.ui.LanguageInspectorTool.static.icon = 'language';
ve.ui.LanguageInspectorTool.static.title =
OO.ui.deferMsg( 'visualeditor-annotationbutton-language-tooltip' );
ve.ui.LanguageInspectorTool.static.modelClasses = [ ve.dm.LanguageAnnotation ];
ve.ui.LanguageInspectorTool.static.commandName = 'language';
ve.ui.toolFactory.register( ve.ui.LanguageInspectorTool );
|
// FROM http://stackoverflow.com/questions/814613/how-to-read-get-data-from-a-url-using-javascript
_f4u$t.parseURLParams = function(url) {
//var queryStart = url.indexOf("?") + 1;
//var queryEnd = url.indexOf("#") + 1 || url.length + 1;
var queryStart = url.indexOf("#") + 1;
var queryEnd = url.length + 1;
var query = url.slice(queryStart, queryEnd - 1);
var params = {};
if (query === url || query === "")
return params;
var nvPairs = query.replace(/\+/g, " ").split("&");
for (var i=0; i<nvPairs.length; i++) {
var nv = nvPairs[i].split("=");
var n = decodeURIComponent(nv[0]);
var v = decodeURIComponent(nv[1]);
if (!(n in params)) {
params[n] = [];
}
params[n].push(nv.length === 2 ? v : null);
}
return params;
}
_f4u$t.load_css_and_then_js = function(css, js) {
if (!css || (css.length == 0)) {
_f4u$t.load_js(js);
}
else {
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = css[0];
cssNode.media = 'screen';
headID.appendChild(cssNode);
_f4u$t.load_css_and_then_js(css.slice(1), js);
}
}
_f4u$t.load_js = function(js) {
if (!js || (js.length == 0)) {
return;
}
else {
$.getScript(js[0], function () {
_f4u$t.load_js(js.slice(1));
});
}
}
|
function showHideHelp(butt) {
butt.className = ( butt.className == 'on' ) ? 'off' : 'on';
document.body.className = ( butt.className == 'on' ) ? 'show-help' : '';
}
function xoopsExternalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href")) {
// Check rel value with extra rels, like "external noflow". No test for performance yet
$pattern = new RegExp("external", "i");
if ($pattern.test(anchor.getAttribute("rel"))) {
anchor.target = "_blank";
}
}
}
}
function xoopsGetElementById(id) {
return $(id);
}
function selectModule(id, button) {
element = xoopsGetElementById(id);
if (button.value == 1) {
element.style.background = '#E6EFC2';
} else {
element.style.background = 'transparent';
}
}
function showThemeSelected(element) {
if (!document.getElementsByTagName) return;
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
divname = div.getAttribute("id");
if (div.getAttribute("rel")) {
$(divname).hide();
if (divname == element.value) {
$(divname).show();
}
}
}
}
function passwordStrength(password) {
if (password.length == 0) {
var score = 0;
} else {
var score = 1;
//if password bigger than 6 give 1 point
if (password.length > 6) score++;
//if password has both lower and uppercase characters give 1 point
if (( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) )) score++;
//if password has at least one number give 1 point
if (password.match(/\d+/)) score++;
//if password has at least one special character give 1 point
if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) score++;
//if password bigger than 12 give another 1 point
if (password.length > 12) score++;
}
document.getElementById("passwordDescription").innerHTML = desc[score];
document.getElementById("passwordStrength").className = "strength" + score;
}
function suggestPassword(passwordlength) {
var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ.,:";
var pwchars = "abcdefhjmnpqrstuvwxyz1234567890,?;.:!$=+@_-&|#ABCDEFGHJKLMNPQRSTUVWYXZ";
var passwd = document.getElementById('generated_pw');
passwd.value = '';
for (i = 0; i < passwordlength; i++) {
passwd.value += pwchars.charAt(Math.floor(Math.random() * pwchars.length))
}
return passwd.value;
}
/**
* Copy the generated password (or anything in the field) to the form
*
* @param string the form name
*
* @return boolean always true
*/
function suggestPasswordCopy(id) {
generated_pw = xoopsGetElementById('generated_pw');
adminpass = xoopsGetElementById('adminpass')
adminpass.value = generated_pw.value;
adminpass2 = xoopsGetElementById('adminpass2')
adminpass2.value = generated_pw.value;
passwordStrength(adminpass.value)
return true;
}
function selectAll() {
// alert('You are clicking on me');
var radios = document.getElementsByTagName("input");
var modules = document.getElementsByTagName("input");
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === "radio" && radios[i].id.slice(-1) === "1") {
radios[i].checked = true;
radios[i].parentNode.parentNode.style.background = '#E6EFC2';
} else {
radios[i].checked = false;
}
}
}
function unselectAll() {
// alert('You are clicking on me');
var radios = document.getElementsByTagName("input");
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === "radio" && radios[i].id.slice(-1) === "2") {
radios[i].checked = true;
radios[i].parentNode.parentNode.style.background = 'transparent';
} else {
radios[i].checked = false;
}
}
}
window.onload = xoopsExternalLinks;
|
// $Id: ckeditor.config.js,v 1.2.2.9.2.3 2010/12/06 13:44:37 dczepierga Exp $
/*
WARNING: clear browser's cache after you modify this file.
If you don't do this, you may notice that browser is ignoring all your changes.
*/
CKEDITOR.editorConfig = function(config) {
config.indentClasses = [ 'rteindent1', 'rteindent2', 'rteindent3', 'rteindent4' ];
// [ Left, Center, Right, Justified ]
config.justifyClasses = [ 'rteleft', 'rtecenter', 'rteright', 'rtejustify' ];
// The minimum editor width, in pixels, when resizing it with the resize handle.
config.resize_minWidth = 450;
// Protect PHP code tags (<?...?>) so CKEditor will not break them when
// switching from Source to WYSIWYG.
// Uncommenting this line doesn't mean the user will not be able to type PHP
// code in the source. This kind of prevention must be done in the server
// side
// (as does Drupal), so just leave this line as is.
config.protectedSource.push(/<\?[\s\S]*?\?>/g); // PHP Code
config.extraPlugins = '';
if (Drupal.ckeditorCompareVersion('3.1')) {
config.extraPlugins += (config.extraPlugins ? ',drupalbreaks' : 'drupalbreaks' );
}
/*
* Append here extra CSS rules that should be applied into the editing area.
* Example:
* config.extraCss = 'body {color:#FF0000;}';
*/
config.extraCss = '';
/**
* Sample extraCss code for the "marinelli" theme.
*/
if (Drupal.settings.ckeditor.theme == "marinelli") {
config.extraCss += "body{background:#FFF;text-align:left;font-size:0.8em;}";
config.extraCss += "#primary ol, #primary ul{margin:10px 0 10px 25px;}";
}
if (Drupal.settings.ckeditor.theme == "newsflash") {
config.extraCss = "body{min-width:400px}";
}
/**
* CKEditor's editing area body ID & class.
* See http://drupal.ckeditor.com/tricks
* This setting can be used if CKEditor does not work well with your theme by default.
*/
config.bodyClass = '';
config.bodyId = '';
/**
* Sample bodyClass and BodyId for the "marinelli" theme.
*/
if (Drupal.settings.ckeditor.theme == "marinelli") {
config.bodyClass = 'singlepage';
config.bodyId = 'primary';
}
if (Drupal.ckeditorCompareVersion('3.1')) {
CKEDITOR.plugins.addExternal('drupalbreaks', Drupal.settings.ckeditor.module_path + '/plugins/drupalbreaks/');
}
// 'MediaEmbed' plugin. To enable it, uncomment lines below and add 'MediaEmbed' button to selected toolbars.
//config.extraPlugins += (config.extraPlugins ? ',mediaembed' : 'mediaembed' );
//CKEDITOR.plugins.addExternal('mediaembed', Drupal.settings.ckeditor.module_path + '/plugins/mediaembed/');
// 'IMCE' plugin. If IMCE module is enabled, you may uncomment lines below and add an 'IMCE' button to selected toolbar.
//config.extraPlugins += (config.extraPlugins ? ',imce' : 'imce' );
//CKEDITOR.plugins.addExternal('imce', Drupal.settings.ckeditor.module_path + '/plugins/imce/');
};
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'stylescombo', 'sr-latn', {
label: 'Stil',
panelTitle: 'Formatting Styles', // MISSING
panelTitle1: 'Block Styles', // MISSING
panelTitle2: 'Inline Styles', // MISSING
panelTitle3: 'Object Styles' // MISSING
} );
|
define("dojox/mvc/Group", ["dojo/_base/declare", "dijit/_WidgetBase", "dojo/_base/lang"], function(declare, _WidgetBase, lang){
return declare("dojox.mvc.Group", _WidgetBase, {
// summary:
// A simple model-bound container widget with single-node binding to a data model.
//
// description:
// A group is usually bound to an intermediate dojo/Stateful node in the data model.
// Child dijits or custom view components inside a group inherit their parent
// data binding context from it.
// target: dojo/Stateful
// The data model used for relative data binding.
target: null,
startup: function(){
// This code needed for ticket 14423 is using removeRepeatNode on a repeat to work with mobile.lists
// this.select and this.onCheckStateChanged are called by ListItem so they need to be set
// but it seems like a bit of a hack.
var parent = null;
if(lang.isFunction(this.getParent)){
if(this.getParent() && this.getParent().removeRepeatNode){
this.select = this.getParent().select;
this.onCheckStateChanged = this.getParent().onCheckStateChanged;
}
}
this.inherited(arguments);
},
_setTargetAttr: function(/*dojo/Stateful*/ value){
// summary:
// Handler for calls to set("target", val).
// description:
// Sets target and "ref" property so that child widgets can refer to.
this._set("target", value);
if(this.binding != value){
// The new value not matching to this.binding means that the change is not initiated by ref change.
this.set("ref", value);
}
}
});
});
|
// JavaScript Document
jQuery(document).ready(function(){
// Hide all of manual link field
jQuery('.manual_link').hide();
// Check which slide is using manual link
jQuery('.slide_link').each(function(index){
if(jQuery(this).val()=='manual'){
jQuery('.manual_link').eq(index).show();
}
});
// Slide link change to manual link
jQuery('.slide_link').change(function(e){
var index = jQuery('.slide_link').index(jQuery(this));
if(jQuery(this).val()=='manual'){
jQuery('.manual_link').eq(index).show();
}else{
jQuery('.manual_link').eq(index).hide();
}
});
// Add new slide
jQuery('#add_sh_slide').click(function(){
$index = jQuery('#shslides tr:last').index();
window.wordpress_send_to_editor = window.send_to_editor;
var l = jQuery('#shslides tr:last td select').val();
jQuery('#shslides tr:last').clone().appendTo('tbody#slides');
jQuery('#shslides span.sort-icon').eq($index+1).text('#'+($index+2));
jQuery('#shslides input.shslideshow_slide').eq($index+1).val('');
jQuery('#shslides .slide_link:eq('+($index+1)+') option:selected').removeAttr('selected');
jQuery('#shslides .slide_link:eq('+($index+1)+') option[value=0]').attr('selected','selected');
jQuery('.shslideshow_upload').eq($index+1).bind('click',upload);
if(l == 'manual'){
jQuery('input.manual_link').eq($index+1).val('');
}
jQuery('input.manual_link').eq($index+1).hide();
jQuery('.del_sh_slide').eq($index+1).removeAttr('onclick');
jQuery('.del_sh_slide').eq($index+1).bind('click',function(){
jQuery(this).parents('tr').remove();
});
jQuery('.slide_link').eq($index+1).bind('change',function(e){
var index = jQuery('.slide_link').index(jQuery(this));
if(jQuery(this).val()=='manual'){
jQuery('.manual_link').eq(index).show();
}else{
jQuery('.manual_link').eq(index).hide();
}
});
});
// Delete slide
jQuery('.del_sh_slide').click(function(){
if(jQuery(this).attr('onclick')==''){
jQuery(this).parents('tr').remove();
}
});
});
function upload() {
var i = jQuery('.shslideshow_upload').index(this);
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
window.send_to_editor = function(html) {
imgurl = jQuery(html).attr('href');
jQuery('.shslideshow_slide').eq(i).val(imgurl);
tb_remove();
window.send_to_editor = window.wordpress_send_to_editor;
}
}
function del_slide(sid,index){
if(confirm('Are you sure to delete #'+index)){
jQuery.ajax({
type: 'POST',
url: path+'ajax.php',
dataType: 'json',
data: {
id: sid
},
success:function(data){
if(data.msg == 'Success'){
jQuery('.del_sh_slide[onclick="del_slide('+sid+','+index+')"]').parents('tr').remove();
}else{
window.alert(data.msg);
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){
window.alert('error');
}
});
}
}
|
// $Id: explorer.selection.js,v 1.2 2009/07/17 15:38:28 gnindl Exp $
/**
* @file explorer.selection.js
* This behavior synchronizes the selections in the view with the stored value
* that will be sent back to the autocomplete widget when the dialog is closed.
*/
/**
* Behavior concering the choise of a view item
* @param
* DOM context
*/
Drupal.behaviors.NodereferenceExplorerSelection = function(context) {
//fix for hover over active table cell (column sorted)
$('.views-item-selectable', context).mouseover(function() {
var background = $(this).css('background-color');
$('td', this).css('background-color', background);
}).mouseout(function() {
$('td', this).css('background-color', '');
});
//select view item logically and visually
$('.views-item-selectable', context).click(function(eventObject) {
if (eventObject.target.type !== 'radio') {
$(':radio', this).trigger('click');
}
});
//hide underlying radion button and process click behavior
$('.views-item-selectable input:radio', context).hide().click(function (eventObject) {
var title = $(this).val();
$('#edit-selection').val(title);
//selected item is marked and attached by a class
$(this).parents('.view-content').find('.views-item-selectable').each(function () {
$(this).removeClass('viewItemSelected');
});
$(this).parents('.views-item-selectable').addClass('viewItemSelected');
});
//cache selected value in form
var selected = $('#edit-selection').val();
$('input:radio[value="'+selected+'"]', context).click();
};
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'fakeobjects', 'en-gb', {
anchor: 'Anchor',
flash: 'Flash Animation',
hiddenfield: 'Hidden Field',
iframe: 'IFrame',
unknown: 'Unknown Object'
} );
|
$ = jQuery.noConflict();
/* Add class for user image */
$('.user-profile-image').find('img').addClass('img-circle').attr("","");
$('#myTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
jQuery(document).ready(function() {
jQuery('.btn-btt').smoothScroll({speed: 1000});
jQuery(window).scroll(function() {
if(jQuery(window).scrollTop() > 200) {
jQuery('.btn-btt').show();
}
else {
jQuery('.btn-btt').hide();
}
}).resize(function(){
if(jQuery(window).scrollTop() > 200) {
jQuery('.btn-btt').show();
}
else {
jQuery('.btn-btt').hide();
}
});
});
|
jQuery(document).ready(function($) {
jQuery('#ewic-aff').bind('click', function () {
var email = jQuery('#ewic_aff_email').val();
var sec = jQuery(this).data('nonce');
var cmd = jQuery(this).data('cmd');
var elmt = jQuery(this);
if ( email != '' ) {
get_aff_ajax( cmd, email, sec, elmt );
} else {
alert('Please input your Account Email or Payment Email!');
return false;
}
return false;
});
function get_aff_ajax( cmd, email, sec, elmt ) {
jQuery('#loader').addClass('button_loading');
jQuery(elmt).attr('disabled','disabled');
dat = {};
dat['eml'] = email;
dat['security'] = sec;
dat['command'] = cmd;
dat['action'] = 'ewic_get_aff_data';
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: dat,
success: function(response) {
if (response.status == true ) {
restore_registered(elmt, response.aff_name, email);
}
else if (response.status == 'disconnected' ) {
jQuery('#ewic_aff_email').val('');
restore_not_reg(elmt);
} else {
restore_not_reg(elmt);
alert('Oops. You are not registered yet to our Affiliate program!');
}
// end success-
}
// end ajax
});
}
function restore_registered(elmt, affname, affemail ) {
jQuery(elmt).removeAttr('disabled');
jQuery('#loader').removeClass('button_loading');
jQuery('#is-status').text('Connected');
jQuery(elmt).data('cmd', 'ewic_affiliate_dis').val('Disconnect');
jQuery('#ewic-not-yet').hide();
jQuery('#ewic-aff-registered').fadeIn(1000);
jQuery('#ewic-aff-holder').text('Hi, '+affname+' ( '+affemail+' )');
}
function restore_not_reg(elmt) {
jQuery(elmt).removeAttr('disabled');
jQuery('#loader').removeClass('button_loading');
jQuery('#is-status').text('');
jQuery(elmt).data('cmd', 'ewic_affiliate_con').val('Connect');
jQuery('#ewic-not-yet').show();
jQuery('#ewic-aff-holder').text('');
jQuery('#ewic-aff-registered').hide();
}
});
|
var zoom_in_active = base_url + '/img/button-zoom-in-on.png',
zoom_in_inactive = base_url + '/img/button-zoom-in-off.png',
zoom_out_active = base_url + '/img/button-zoom-out-on.png',
zoom_out_inactive = base_url + '/img/button-zoom-out-off.png';
var map,
MM;
MM = com.modestmaps;
var hashStr = (location.hash.charAt(0) == '#') ? location.hash.substr(1) : location.hash;
var incomingCoords = MM.Hash.prototype.parseHash(hashStr) || null;
var provider = base_provider + '/{Z}/{X}/{Y}.jpg';
var template = new MM.Template(provider);
var layer = new MM.Layer(template);
map = new MM.Map("map", layer, null, [new MM.DragHandler(), new MM.DoubleClickHandler()]);
var bounds = geojpeg_bounds.split(','),
north = parseFloat(bounds[0]),
west = parseFloat(bounds[1]),
south = parseFloat(bounds[2]),
east = parseFloat(bounds[3]),
extents = [new MM.Location(north, west), new MM.Location(south, east)];
var hash = new MM.Hash(map);
if(!incomingCoords){
map.setExtent(extents);
map.zoomIn();
map.panBy(0,40);
}else{
map.setCenterZoom(incomingCoords.center,incomingCoords.zoom);
}
|
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file httpprovider.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com>
* Fabian Vogelsteller <fabian@ethdev.com>
* @date 2014
*/
"use strict";
// resolves the problem for electron/atom shell environments, which use node integration, but have no process variable available
var XMLHttpRequest = (typeof window !== 'undefined' && window.XMLHttpRequest) ? window.XMLHttpRequest : require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line
var errors = require('./errors');
var HttpProvider = function (host) {
this.host = host || 'http://localhost:8545';
};
HttpProvider.prototype.send = function (payload) {
var request = new XMLHttpRequest();
request.open('POST', this.host, false);
request.setRequestHeader('Content-type','application/json');
try {
request.send(JSON.stringify(payload));
} catch(error) {
throw errors.InvalidConnection(this.host);
}
// check request.status
// TODO: throw an error here! it cannot silently fail!!!
//if (request.status !== 200) {
//return;
//}
var result = request.responseText;
try {
result = JSON.parse(result);
} catch(e) {
throw errors.InvalidResponse(result);
}
return result;
};
HttpProvider.prototype.sendAsync = function (payload, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
var result = request.responseText;
var error = null;
try {
result = JSON.parse(result);
} catch(e) {
error = errors.InvalidResponse(result);
}
callback(error, result);
}
};
request.open('POST', this.host, true);
request.setRequestHeader('Content-type','application/json');
try {
request.send(JSON.stringify(payload));
} catch(error) {
callback(errors.InvalidConnection(this.host));
}
};
module.exports = HttpProvider;
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
// This JavaScript file is a single, large, imported script.
// It imports other large scripts which are deeply nested.
// It is imported by another script.
.import "msdsi7.js" as Msdsi7
function testFunc(seedValue) {
var retn = 0.65;
var firstFactor = calculateFirstFactor(seedValue);
var secondFactor = calculateSecondFactor(seedValue);
var modificationTerm = calculateModificationTerm(seedValue);
// do some regexp matching
var someString = "This is a random string which we'll perform regular expression matching on to reduce considerably. This is meant to be part of a complex javascript expression whose evaluation takes considerably longer than the creation cost of QScriptValue.";
var regexpPattern = new RegExp("is", "i");
var regexpOutputLength = 0;
var temp = regexpPattern.exec(someString);
while (temp == "is") {
regexpOutputLength += 4;
regexpOutputLength *= 2;
temp = regexpPattern.exec(someString);
if (regexpOutputLength > (seedValue * 3)) {
temp = "break";
}
}
// spin in a for loop for a while
var i = 0;
var j = 0;
var cumulativeTotal = 3;
for (i = 20; i > 1; i--) {
for (j = 31; j > 5; j--) {
var branchVariable = i + j;
if (branchVariable % 3 == 0) {
cumulativeTotal -= secondFactor;
} else {
cumulativeTotal += firstFactor;
}
if (cumulativeTotal > (seedValue * 50)) {
break;
}
}
}
retn *= (1 + (cumulativeTotal * 0.001));
retn *= Msdsi7.testFunc(seedValue + retn);
return retn;
}
function calculateFirstFactor(seedValue) {
var firstFactor = (0.45 * (9.3 / 3.1) - 0.90);
firstFactor *= (1 + (0.00006 / seedValue));
return firstFactor;
}
function calculateSecondFactor(seedValue) {
var secondFactor = 0.78 * (6.3 / 2.1) - (0.39 * 4);
secondFactor *= (1 + (0.00006 / seedValue));
return secondFactor;
}
function calculateModificationTerm(seedValue) {
var modificationTerm = (12 + (9*7) - 54 + 16 - ((calculateFirstFactor(seedValue) * seedValue) / 3) + (4*calculateSecondFactor(seedValue) * seedValue * 1.33)) + (calculateSecondFactor(seedValue) * seedValue);
modificationTerm = modificationTerm + (33/2) + 19 - (9*2) - (61*3) + 177;
return modificationTerm;
}
|
import React from 'react'
const TransactionIoListItem = props => {
const item = props.io[props.index]
return (
<div className={'list-item-plain' + (props.index % 2 === 0 ? ' even' : '')}>
<div className="flex-sb">
<p className="mono">{item.address}</p>
<p className={item.color || ''}>
{new Intl.NumberFormat(props.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(item.amount)}
</p>
</div>
</div>
)
}
export default TransactionIoListItem
|
/* @flow */
import React, { PureComponent } from 'react';
import propTypes from 'prop-types';
import type {
NavigationScreenProp,
NavigationRoute,
NavigationAction,
NavigationNavigatorProps,
} from '../TypeDefinition';
type Props<O> = {
screenProps?: {},
navigation: NavigationScreenProp<NavigationRoute, NavigationAction>,
component: ReactClass<NavigationNavigatorProps<O, NavigationRoute>>,
};
export default class SceneView<O> extends PureComponent<void, Props<O>, void> {
static childContextTypes = {
navigation: propTypes.object.isRequired,
};
props: Props<O>;
getChildContext() {
return {
navigation: this.props.navigation,
};
}
render() {
const { screenProps, navigation, component: Component } = this.props;
return <Component screenProps={screenProps} navigation={navigation} />;
}
}
|
/** @odoo-module **/
import { getMessagingComponent } from "@mail/utils/messaging_component";
import AbstractAction from 'web.AbstractAction';
const { Component } = owl;
export const DiscussWidget = AbstractAction.extend({
template: 'mail.widgets.Discuss',
/**
* @override {web.AbstractAction}
* @param {web.ActionManager} parent
* @param {Object} action
* @param {Object} [action.context]
* @param {string} [action.context.active_id]
* @param {Object} [action.params]
* @param {string} [action.params.default_active_id]
* @param {Object} [options={}]
*/
init(parent, action, options={}) {
this._super(...arguments);
// control panel attributes
this.action = action;
this.actionManager = parent;
this.discuss = undefined;
this.options = options;
this.component = undefined;
this._lastPushStateActiveThread = null;
this.env = Component.env;
Component.env.services.messaging.modelManager.messagingCreatedPromise.then(() => {
const messaging = Component.env.services.messaging.modelManager.messaging;
const initActiveId = this.options.active_id ||
(this.action.context && this.action.context.active_id) ||
(this.action.params && this.action.params.default_active_id) ||
'mail.box_inbox';
this.discuss = messaging.discuss;
this.discuss.update({ initActiveId });
});
},
/**
* @override {web.AbstractAction}
*/
destroy() {
if (this.component) {
this.component.destroy();
this.component = undefined;
}
if (this.$buttons) {
this.$buttons.off().remove();
}
this._super(...arguments);
},
/**
* @override {web.AbstractAction}
*/
on_attach_callback() {
this._super(...arguments);
if (this.component) {
// prevent twice call to on_attach_callback (FIXME)
return;
}
const DiscussComponent = getMessagingComponent("Discuss");
this.component = new DiscussComponent();
this._pushStateActionManagerEventListener = ev => {
ev.stopPropagation();
if (this._lastPushStateActiveThread === this.discuss.thread) {
return;
}
this._pushStateActionManager();
this._lastPushStateActiveThread = this.discuss.thread;
};
this._showRainbowManEventListener = ev => {
ev.stopPropagation();
this._showRainbowMan();
};
this.el.addEventListener(
'o-push-state-action-manager',
this._pushStateActionManagerEventListener
);
this.el.addEventListener(
'o-show-rainbow-man',
this._showRainbowManEventListener
);
return this.component.mount(this.el);
},
/**
* @override {web.AbstractAction}
*/
on_detach_callback() {
this._super(...arguments);
if (this.component) {
this.component.destroy();
}
this.component = undefined;
this.el.removeEventListener(
'o-push-state-action-manager',
this._pushStateActionManagerEventListener
);
this.el.removeEventListener(
'o-show-rainbow-man',
this._showRainbowManEventListener
);
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
*/
_pushStateActionManager() {
this.actionManager.do_push_state({
action: this.action.id,
active_id: this.discuss.activeId,
});
},
/**
* @private
*/
_showRainbowMan() {
this.trigger_up('show_effect', {
message: this.env._t("Congratulations, your inbox is empty!"),
type: 'rainbow_man',
});
},
});
|
// |reftest| pref(javascript.options.xml.content,true)
/* -*- Mode: java; tab-width:8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var BUGNUMBER = 374160;
var summary = 'Do not assert with <a><b c="1"></b><b c="2"></b></a>..@c[0]=3';
var actual = 'No Crash';
var expect = 'No Crash';
printBugNumber(BUGNUMBER);
START(summary);
<a><b c="1"></b><b c="2"></b></a>..@c[0] = 3;
TEST(1, expect, actual);
END();
|
/**
* This file is part of Shuup.
*
* Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
*
* This source code is licensed under the OSL-3.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
function adjustStock(event, button) {
event.preventDefault();
var stockAdjustDiv = button.parent("div.form");
var url = stockAdjustDiv.data("url");
var data = stockAdjustDiv.find(":input").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(msg) {
$(msg.stockInformationDiv).html(msg.updatedStockInformation);
window.Messages.enqueue({tags: "info", text: msg.message});
},
error: function(response) {
window.Messages.enqueue({tags: "error", text: response.responseJSON.message});
}
});
}
|
'use strict';
const expect = require('chai').expect,
FormatUtils = require('../../../lib/utils/format_utils'),
formatComment = FormatUtils.formatComment,
dateFormatForLiquibase = FormatUtils.dateFormatForLiquibase;
describe('FormatUtils', () => {
describe('::formatComment', () => {
describe('when the comment is in the one-line form', () => {
const oneLineComment1 = ' comment ';
const oneLineComment2 = 'comment';
const oneLineComment3 = ' * a one line comment. ';
const oneLineComment4 = ' multi word\tcomment ';
const oneLineComment5 = 'multi word\tcomment';
const expectedResult1 = 'comment';
const expectedResult2 = 'a one line comment.';
const expectedResult3 = 'multi word\tcomment';
describe(buildTestTitle(oneLineComment1), () => {
it('returns ' + buildTestTitle(expectedResult1), () => {
expect(formatComment(oneLineComment1)).to.eq(expectedResult1);
});
});
describe(buildTestTitle(oneLineComment2), () => {
it('returns ' + buildTestTitle(expectedResult1), () => {
expect(formatComment(oneLineComment2)).to.eq(expectedResult1);
});
});
describe(buildTestTitle(oneLineComment3), () => {
it('returns ' + buildTestTitle(expectedResult2), () => {
expect(formatComment(oneLineComment3)).to.eq(expectedResult2);
});
});
describe(buildTestTitle(oneLineComment4), () => {
it('returns ' + buildTestTitle(expectedResult3), () => {
expect(formatComment(oneLineComment4)).to.eq(expectedResult3);
});
});
describe(buildTestTitle(oneLineComment5), () => {
it('returns ' + buildTestTitle(expectedResult3), () => {
expect(formatComment(oneLineComment5)).to.eq(expectedResult3);
});
});
});
describe('when the comment is in the multi-line form', () => {
const multiLineComment1 = '\n* <p>first line of comment</p><br/>\n*<p>second line</p>\n';
const multiLineComment2 = '*** <p>first line of comment</p><br/>\n* *<p>second line</p>\n\n';
const multiLineComment3 = '\n * abcde\n * fghij\n * nothing\n';
const expectedResult1 = '<p>first line of comment</p><br/>\n<p>second line</p>';
const expectedResult2 = '<p>first line of comment</p><br/>\n*<p>second line</p>';
const expectedResult3 = 'abcde\nfghij\nnothing';
describe(buildTestTitle(multiLineComment1), () => {
it('returns ' + buildTestTitle(expectedResult1), () => {
expect(formatComment(multiLineComment1)).to.eq(expectedResult1);
});
});
describe(buildTestTitle(multiLineComment2), () => {
it('returns ' + buildTestTitle(expectedResult2), () => {
expect(formatComment(multiLineComment2)).to.eq(expectedResult2);
});
});
describe(buildTestTitle(multiLineComment3), () => {
it('returns ' + buildTestTitle(expectedResult3), () => {
expect(formatComment(multiLineComment3)).to.eq(expectedResult3);
});
});
});
});
describe('::dateFormatForLiquibase', () => {
describe('when passing both arguments', () => {
it('uses the increment with the passed date', () => {
const now = new Date();
const increment = 1000042;
const result =
dateFormatForLiquibase({date: now, increment: increment});
now.setSeconds(now.getUTCSeconds() + increment);
const now_utc = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds());
const year = `${now_utc.getFullYear()}`;
let month = `${now_utc.getMonth() + 1}`;
if (month.length === 1) {
month = `0${month}`;
}
let day = `${now_utc.getDate()}`;
if (day.length === 1) {
day = `0${day}`;
}
let hour = `${now_utc.getHours()}`;
if (hour.length === 1) {
hour = `0${hour}`;
}
let minute = `${now_utc.getMinutes()}`;
if (minute.length === 1) {
minute = `0${minute}`;
}
let second = `${now_utc.getSeconds()}`;
if (second.length === 1) {
second = `0${second}`;
}
expect(
result
).to.equal(`${year}${month}${day}${hour}${minute}${second}`);
});
});
describe('when not passing the date', () => {
it('does not fail', () => {
expect(dateFormatForLiquibase().length).to.equal(14);
});
});
describe('when not passing the increment', () => {
it('formats the current time for liquibase with no increment', () => {
const now = new Date();
const result = dateFormatForLiquibase({date: now});
const now_utc = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds());
const year = `${now_utc.getFullYear()}`;
let month = `${now_utc.getMonth() + 1}`;
if (month.length === 1) {
month = `0${month}`;
}
let day = `${now_utc.getDate()}`;
if (day.length === 1) {
day = `0${day}`;
}
let hour = `${now_utc.getHours()}`;
if (hour.length === 1) {
hour = `0${hour}`;
}
let minute = `${now_utc.getMinutes()}`;
if (minute.length === 1) {
minute = `0${minute}`;
}
let second = `${(now_utc.getSeconds()) % 60}`;
if (second.length === 1) {
second = `0${second}`;
}
expect(
result
).to.equal(`${year}${month}${day}${hour}${minute}${second}`);
});
});
});
});
function buildTestTitle(comment) {
return `'${comment}'`;
}
|
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview This file implements the `amp test-report-upload` task, which POSTs test result reports
* to an API endpoint that stores them in the database.
*/
'use strict';
const fetch = require('node-fetch');
const fs = require('fs').promises;
const path = require('path');
const {
ciBuildId,
ciBuildUrl,
ciJobId,
ciJobUrl,
ciCommitSha,
ciRepoSlug,
} = require('../common/ci');
const {log} = require('../common/logging');
const {cyan, green, red, yellow} = require('kleur/colors');
const REPORTING_API_URL = 'https://amp-test-cases.appspot.com/report';
/**
* Parses a test report file and adds build & job info to it.
* @param {('unit' | 'integration' | 'e2e')} testType The type of the tests whose result we want to report.
* @return {Promise<Object.<string,Object>|null>} Object containing the build, job, and test results.
*/
async function getReport(testType) {
try {
const report = JSON.parse(
await fs.readFile(`result-reports/${testType}.json`, 'utf-8')
);
return addJobAndBuildInfo(testType, report);
} catch (e) {
log(red('ERROR:'), 'Error getting test result report.\n', e.toString());
return null;
}
}
/**
* Adds job and build info to a report.
* @param {('unit' | 'integration' | 'e2e')} testType The type of the tests whose result we want to report.
* @param {Object} reportJson The Json report generated by Karma.
* @return {Object.<string,Object>} Object containing the build, job, and test results.
*/
function addJobAndBuildInfo(testType, reportJson) {
const buildId = ciBuildId();
const commitSha = ciCommitSha();
const jobId = ciJobId();
if (!buildId || !commitSha || !jobId) {
throw new ReferenceError('CI fields are not defined.');
}
// (TODO ampproject/amp-github-apps/pull:1194) Update field names in database.
return {
repository: ciRepoSlug(),
results: reportJson,
build: {
buildId,
commitSha,
url: ciBuildUrl(),
},
job: {
jobId,
testSuiteType: testType,
url: ciJobUrl(),
},
};
}
/**
* Sends a single report to the API endpoint for storage.
* @param {('unit' | 'integration' | 'e2e')} testType The type of the tests whose result we want to report.
*/
async function sendCiKarmaReport(testType) {
const body = await getReport(testType);
if (!body) {
return;
}
const response = await fetch(REPORTING_API_URL, {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'},
});
if (response.ok) {
log(
green('INFO:'),
`Test results of type`,
cyan(testType),
'reported to',
cyan(REPORTING_API_URL)
);
} else {
log(
yellow('WARNING:'),
'failed to report results of type',
cyan(testType),
': \n',
yellow(await response.text())
);
}
}
/**
* Uploads every report to the API endpoint for storage.
*/
async function testReportUpload() {
const filenames = await fs.readdir('result-reports/');
const testTypes = filenames.map((filename) => path.parse(filename).name);
await Promise.all(testTypes.map(sendCiKarmaReport));
}
module.exports = {
testReportUpload,
};
testReportUpload.description = 'Sends test results to test result database';
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// When the assessment page loads, activity-generic.js will render the contents
// of the 'assessment' variable into the enclosing HTML webpage.
// For information on modifying this page, see
// https://code.google.com/p/course-builder/wiki/CreateAssessments.
var assessment = {
// HTML to display at the start of the page
preamble: '<br><b>GPI Database, Multiple-choice Questions / Module 6</b><br><br>Please answer <b>all</b> questions below:<br><br>',
// An ordered list of questions, with each question's type implicitly determined by the fields it possesses:
// choices - multiple choice question (with exactly one correct answer)
// correctAnswerString - case-insensitive string match
// correctAnswerRegex - freetext regular expression match
// correctAnswerNumeric - freetext numeric match
questionsList: [
{questionHTML: 'What is purpose of gpidatabase.com?',
choices: ['Control activities and avoid access to non authorized users',
correct('Is the system we have to track and share information, monitor activity, evaluate and have statistics on propagation and potential'),
'It is a Catalog for Materials available',
'Is the system we use to send emails to each other, make calls and see news on WOPG'],
lesson: '7.1'},
{questionHTML: "How do you know what TV Initiatives are present in South America?", // question can be plain text or arbitrary HTML
choices: ['Under Assessments tab do a Find and enter SAM% under Region and then click on Search to see the results',
'Send email to help@gpidatabase.com asking for the report',
'Under Cities Profiles tab do a Find and enter SAM% under Region and then click on Search to see the results',
correct('Under View Projects tab do a Find and enter TV% under Project and SAM% under Region and then click on Search to see the results')],
// the (optional) lesson associated with this question, which is displayed as a suggestion
// for further study if the student answers this question incorrectly.
lesson: '7.1'},
{questionHTML: 'Where do you enter your Assessments?',
choices: [correct('Under Assessments tab'),
'Under View Assessments tab',
'On Google Docs',
'Under GPI-EA Events tab'],
lesson: '7.1'},
{questionHTML: 'How do you know what projects/initiatives have reached more than 250.000 people?',
choices: ['Under View Projects tab, view the details of every project, one by one, go to the Status tab and see the reached people',
'Under Potential tab, enter 250000 and click Update',
'It is impossible to get that information inside gpidatabase.com',
correct('Under Proj/City tab enter 250000 and click on Show')],
lesson: '7.1'},
{questionHTML: 'How do you know the planned GPI Events in your region?',
choices: ['Ask Karthik by email to be sure you have the latest information',
correct('Under GPI-EA Events click on Find, enter your Region and then click on Search to see the results'),
'Under View Projects tab click on Find, enter your Region and then click on Search to see the results',
'Check on Google Document'],
lesson: '7.1'},
],
assessmentName: 'a6course', // unique name submitted along with all of the answers
checkAnswers:false // render a "Check your Answers" button to allow students to check answers prior to submitting?
}
|
$(document).ready(function () {
// when a hanburger menu is clicked
let $ul = $(".nav__list"),
$menu = $(".nav__menu");
$($menu).click(function () {
// toggle menu-click Class
$ul.toggleClass("menu-click");
}); // end click event handler
});
|
/**
Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
**/
require("./source_info.js");
'use strict';
global.tr.exportTo('tr.model.source_info', function() {
function JSSourceInfo(file, line, column, isNative, scriptId, state) {
tr.model.source_info.SourceInfo.call(this, file, line, column);
this.isNative_ = isNative;
this.scriptId_ = scriptId;
this.state_ = state;
}
JSSourceInfo.prototype = {
__proto__: tr.model.source_info.SourceInfo.prototype,
get state() {
return this.state_;
},
get isNative() {
return this.isNative_;
},
get scriptId() {
return this.scriptId_;
},
toString: function() {
var str = this.isNative_ ? '[native v8] ' : '';
return str +
tr.model.source_info.SourceInfo.prototype.toString.call(this);
}
};
return {
JSSourceInfo: JSSourceInfo,
JSSourceState: {
COMPILED: 'compiled',
OPTIMIZABLE: 'optimizable',
OPTIMIZED: 'optimized',
UNKNOWN: 'unknown'
}
};
});
|
/**
* Grays + HSV color spectrum
*
* @class Widgets.nlFokkezbColor.lib.ghsv
* @xtype spectrum
*/
/**
* The image displaying the spectrum.
*
* @property {String}
*/
exports.image = 'images/ghsv.png';
/**
* Convert percentage x and y to HSV
*
* @param {Object} pc Coordinates in percentages
* @param {Number} pc.x X-coordinate
* @param {Number} pc.y Y-coordinate
*
* @return {Object} Color in HSV
* @return {Number} return.h Hue (0 - 359)
* @return {Number} return.s Saturation (0 - 100)
* @return {Number} return.v Value (0 - 100)
*/
exports.pc2hsv = function pc2hsv(pc) {
var third = 100 / 3;
if (pc.y < third) {
s = 0;
v = Math.round(100 - (pc.y * 3));
} else if (pc.y < (2 * third)) {
s = 100;
v = Math.round((pc.y - third) * 3);
} else {
s = Math.round(100 - ((pc.y - third - third) * 3));
v = 100;
}
return {
h: Math.round((pc.x / 100) * 359),
s: s,
v: v
};
};
/**
* Convert percentage x and y to HSV
*
* @param {Object} hsv Color in HSV
* @param {Number} hsv.h Hue (0 - 359)
* @param {Number} hsv.s Saturation (0 - 100)
* @param {Number} hsv.v Value (0 - 100)
*
* @return {Object} Coordinates in percentages
* @return {Number} return.x X-coordinate
* @return {Number} return.y Y-coordinate
*/
exports.hsv2pc = function hsv2pc(hsv) {
var y3p;
if (hsv.s > 0) {
if (hsv.b < 100) {
y3p = 100 + hsv.b;
} else {
y3p = 300 - hsv.s;
}
} else {
y3p = 100 - hsv.b;
}
return {
x: Math.round((hsv.h * 100) / 359),
y: Math.round((y3p * 100) / 300)
};
};
|
/**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.crunch',
name: 'CapabilityCategoryCapabilityJunctionRefine',
refines: 'foam.nanos.crunch.CapabilityCategoryCapabilityJunction',
documentation: `
Refine capabilitycategorycapabilityjunction to add tablecellformatters for source and target id
`,
properties: [
{
class: 'Reference',
of: 'foam.nanos.crunch.Capability',
name: 'targetId',
tableCellFormatter: function(value, obj, axiom) {
this.__subSubContext__.capabilityDAO
.find(value)
.then((capability) => this.add(capability.name))
.catch((error) => {
this.add(value);
});
}
}
]
});
|
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const globby = require('globby');
const path = require('path');
const prettier = require('prettier');
const toc = require('markdown-toc');
const {getStdout} = require('../../common/exec');
const {green} = require('kleur/colors');
const {logOnSameLineLocalDev} = require('../../common/logging');
const {readFile} = require('fs-extra');
const {writeDiffOrFail} = require('../../common/diff');
const task = 'markdown-toc';
const header = `<!--
(Do not remove or edit this comment.)
This table-of-contents is automatically generated. To generate it, run:
amp markdown-toc --fix
-->`;
// Case-insensitive, allows multiple newlines and arbitrary indentation.
const headerRegexp = new RegExp(
header
.split(/\n+/g)
.map(
(line) =>
`\\s*${line.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/^\s+/, '')}`
)
.join('\n+'),
'im'
);
/**
* @param {string} content
* @return {?string}
*/
function getFrontmatter(content) {
const end = content.search(/(\n-|\n#)/m);
if (end < 0) {
return null;
}
const withWhitespace = content.substr(0, end);
if (withWhitespace.trim().length < 1) {
return null;
}
return withWhitespace;
}
/**
* @param {?string} maybeComment
* @return {?Object}
*/
function isolateCommentJson(maybeComment) {
if (!maybeComment) {
return null;
}
const json = maybeComment.replace('<!--', '').replace('-->', '').trim();
if (!json) {
return null;
}
try {
const options = JSON.parse(json);
return options;
} catch (_) {
return null;
}
}
/**
* @param {string} content
* @return {Promise<string|null>}
*/
async function overrideToc(content) {
const headerMatch = content.match(headerRegexp);
if (!headerMatch || !headerMatch.length || headerMatch.index === undefined) {
return null;
}
const headerEnd = headerMatch.index + headerMatch[0].length;
const afterHeader = content.substr(headerEnd);
const frontmatter = getFrontmatter(afterHeader);
const frontmatterOptions = isolateCommentJson(frontmatter);
const afterFrontmatter = frontmatter
? afterHeader.substr(afterHeader.indexOf(frontmatter) + frontmatter.length)
: afterHeader;
const listEnd = afterFrontmatter.search(/\n[^-\s]/m);
if (listEnd < 0) {
return null;
}
// https://github.com/jonschlinkert/markdown-toc#options
const options = {
firsth1: false,
...frontmatterOptions,
// Don't allow to override `bullets` because it breaks assumptions.
bullets: '-',
};
const overridden = [
content.substr(0, headerEnd),
frontmatter,
toc(content, options).content,
afterFrontmatter.substr(listEnd),
].join('\n');
return prettier.format(overridden, {
...(await prettier.resolveConfig('_.md')),
parser: 'markdown',
});
}
/**
* @param {string} cwd
* @return {Promise<Object<string, ?string>>}
*/
async function overrideTocGlob(cwd) {
const glob = [
'**/*.md',
'!**/{node_modules,build,dist,dist.3p,dist.tools,.karma-cache}/**',
];
const files = globby.sync(glob, {cwd}).map((file) => path.join(cwd, file));
const filesIncludingString = getStdout(
[`grep -irl "${task}"`, ...files].join(' ')
)
.trim()
.split('\n');
/** @type {Object<string, ?string>} */
const result = {};
for (const filename of filesIncludingString) {
const content = await readFile(filename, 'utf-8');
const tentative = await overrideToc(content);
if (!tentative) {
continue;
}
result[filename] = tentative === content ? null : tentative;
}
return result;
}
async function markdownToc() {
const result = await overrideTocGlob('.');
let errored = false;
for (const filename in result) {
if (filename.indexOf('markdown-toc/') >= 0) {
continue;
}
const tentative = result[filename];
if (!tentative) {
logOnSameLineLocalDev(green('Checked: ') + filename);
} else {
try {
writeDiffOrFail('markdown-toc', filename, tentative);
} catch (_) {
errored = true;
}
}
}
if (errored) {
throw new Error('Files are outdated');
}
}
module.exports = {
headerRegExpForTesting: headerRegexp,
markdownToc,
overrideTocGlob,
overrideToc,
};
markdownToc.description =
'Finds Markdown files that contain table of contents and updates them.';
markdownToc.flags = {
'fix': 'Write to file',
};
|
var stream_data = (function () {
var exports = {};
// The stream_info variable maps stream names to stream properties objects
// Call clear_subscriptions() to initialize it.
var stream_info;
var subs_by_stream_id;
exports.clear_subscriptions = function () {
stream_info = new Dict({fold_case: true});
subs_by_stream_id = new Dict();
};
exports.recent_subjects = new Dict({fold_case: true});
exports.clear_subscriptions();
exports.add_sub = function (stream_name, sub) {
stream_info.set(stream_name, sub);
subs_by_stream_id.set(sub.stream_id, sub);
};
exports.get_sub = function (stream_name) {
return stream_info.get(stream_name);
};
exports.get_sub_by_id = function (stream_id) {
return subs_by_stream_id.get(stream_id);
};
exports.delete_sub = function (stream_name) {
stream_info.del(stream_name);
};
exports.subscribed_subs = function () {
return _.where(stream_info.values(), {subscribed: true});
};
exports.subscribed_streams = function () {
return _.pluck(exports.subscribed_subs(), 'name');
};
exports.get_colors = function () {
return _.pluck(exports.subscribed_subs(), 'color');
};
exports.all_subscribed_streams_are_in_home_view = function () {
return _.every(exports.subscribed_subs(), function (sub) {
return sub.in_home_view; }
);
};
exports.home_view_stream_names = function () {
var home_view_subs = _.filter(exports.subscribed_subs(), function (sub) {
return sub.in_home_view;
}
);
return _.map(home_view_subs, function (sub) {
return sub.name;
});
};
exports.canonicalized_name = function (stream_name) {
return stream_name.toString().toLowerCase();
};
exports.get_color = function (stream_name) {
var sub = exports.get_sub(stream_name);
if (sub === undefined) {
return stream_color.default_color;
}
return sub.color;
};
exports.in_home_view = function (stream_name) {
var sub = exports.get_sub(stream_name);
return sub !== undefined && sub.in_home_view;
};
exports.is_subscribed = function (stream_name) {
var sub = exports.get_sub(stream_name);
return sub !== undefined && sub.subscribed;
};
exports.get_invite_only = function (stream_name) {
var sub = exports.get_sub(stream_name);
if (sub === undefined) {
return false;
}
return sub.invite_only;
};
exports.get_name = function (stream_name) {
// This returns the actual name of a stream if we are subscribed to
// it (i.e "Denmark" vs. "denmark"), while falling thru to
// stream_name if we don't have a subscription. (Stream names
// are case-insensitive, but we try to display the actual name
// when we know it.)
var sub = exports.get_sub(stream_name);
if (sub === undefined) {
return stream_name;
}
return sub.name;
};
exports.set_subscribers = function (sub, emails) {
sub.subscribers = Dict.from_array(emails || [], {fold_case: true});
};
// NOTE: If you do anything with the `subscribers` attribute on the stream
// properties object, first make sure `is_subscribed` is true (i.e., the local
// user is subscribed). Otherwise we don't and can't update the subscribers
// list.
//
// The accessor functions below know to check for that case.
exports.add_subscriber = function (stream_name, user_email) {
var sub = exports.get_sub(stream_name);
if (typeof sub === 'undefined' || !sub.subscribed) {
// If we're not subscribed, we don't track this, and shouldn't
// get these events. Likewise, if we don't know about the stream,
// we don't want to track this.
blueslip.warn("We got an add_subscriber call for a non-existent or unsubscribed stream.");
return;
}
sub.subscribers.set(user_email, true);
};
exports.remove_subscriber = function (stream_name, user_email) {
var sub = exports.get_sub(stream_name);
if (typeof sub === 'undefined' || !sub.subscribed) {
// If we're not subscribed, we don't track this, and shouldn't
// get these events. Likewise, if we don't know about the stream,
// we don't want to track this.
blueslip.warn("We got a remove_subscriber call for a non-existent or unsubscribed stream.");
return;
}
sub.subscribers.del(user_email);
};
exports.user_is_subscribed = function (stream_name, user_email) {
var sub = exports.get_sub(stream_name);
if (typeof sub === 'undefined' || !sub.subscribed) {
// If we don't know about the stream, or we ourselves are not
// subscribed, we can't keep track of the subscriber list in general,
// so we return undefined (treated as falsy if not explicitly handled).
blueslip.warn("We got a user_is_subscribed call for a non-existent or unsubscribed stream.");
return undefined;
}
return sub.subscribers.has(user_email);
};
return exports;
}());
if (typeof module !== 'undefined') {
module.exports = stream_data;
}
|
var equal = require('assert').equal;
var camelize = require('../camelize');
test('#camelize', function(){
equal(camelize('the_camelize_string_method'), 'theCamelizeStringMethod');
equal(camelize('webkit-transform'), 'webkitTransform');
equal(camelize('-the-camelize-string-method'), 'TheCamelizeStringMethod');
equal(camelize('_the_camelize_string_method'), 'TheCamelizeStringMethod');
equal(camelize('The-camelize-string-method'), 'TheCamelizeStringMethod');
equal(camelize('the camelize string method'), 'theCamelizeStringMethod');
equal(camelize(' the camelize string method'), 'theCamelizeStringMethod');
equal(camelize('the camelize string method'), 'theCamelizeStringMethod');
equal(camelize(' with spaces'), 'withSpaces');
equal(camelize('_som eWeird---name-'), 'SomEWeirdName');
equal(camelize(''), '', 'Camelize empty string returns empty string');
equal(camelize(null), '', 'Camelize null returns empty string');
equal(camelize(undefined), '', 'Camelize undefined returns empty string');
equal(camelize(123), '123');
equal(camelize('the_camelize_string_method', true), 'theCamelizeStringMethod');
equal(camelize('webkit-transform', true), 'webkitTransform');
equal(camelize('-the-camelize-string-method', true), 'theCamelizeStringMethod');
equal(camelize('_the_camelize_string_method', true), 'theCamelizeStringMethod');
equal(camelize('The-camelize-string-method', true), 'theCamelizeStringMethod');
equal(camelize('the camelize string method', true), 'theCamelizeStringMethod');
equal(camelize(' the camelize string method', true), 'theCamelizeStringMethod');
equal(camelize('the camelize string method', true), 'theCamelizeStringMethod');
equal(camelize(' with spaces', true), 'withSpaces');
equal(camelize('_som eWeird---name-', true), 'somEWeirdName');
equal(camelize('', true), '', 'Camelize empty string returns empty string');
equal(camelize(null, true), '', 'Camelize null returns empty string');
equal(camelize(undefined, true), '', 'Camelize undefined returns empty string');
equal(camelize(123, true), '123');
});
|
module.exports = require('./domainRouter');
|
'use strict'
var XMPP = require('../index')
var prebind = new XMPP({
jid: 'me@example.com',
password: 'secret',
preferred: 'PLAIN',
bosh: {
url: 'http://example.com/http-bind',
wait: 60,
prebind: function (error, data) {
if (error) throw new Error(error)
return data
/*
data.sid
data.rid
*/
}
}
})
prebind.on('online', function () { console.log('Connected') })
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.5-4-246
description: >
Object.create - one property in 'Properties' is a String object
that uses Object's [[Get]] method to access the 'get' property
(8.10.5 step 7.a)
---*/
var strObj = new String("abc");
strObj.get = function () {
return "VerifyStringObject";
};
var newObj = Object.create({}, {
prop: strObj
});
assert.sameValue(newObj.prop, "VerifyStringObject", 'newObj.prop');
|
$(document).ready(function() {
var loggedIn = false;
$('#loginBtn').click(function() {
// Show Loading
$.mobile.loading("show", {
text: "Signing In...",
textVisible: true,
theme: "b",
});
var username = $("#sid").val();
var password = $("#password").val();
var dataString = 'sid=' + username + '&password=' + password;
var wrongInput = '<p class="invalid-password">Invalid username or password</p>';
$.ajax({
method: "POST",
type: "json",
url: "http://5.196.109.144/index.php",
data: dataString,
cache: false,
success: function(response) {
if (response.status == "success") {
loggedIn = true;
$('.student-name').text(response.name);
getData();
$.mobile.loading("hide"); // Hide loading if success
$.mobile.changePage('#user-profile'); // Go to user-profile page if succeed
} else {
$('.invalid-password').remove();
// navigator.notification.vibrate(3000);
$('.loginform').append(wrongInput);
$('.invalid-password').slideDown();
$.mobile.loading("hide"); // Hide loading if failed
}
}
});
function getData() {
$.ajax({
type: "POST",
dataType: "json",
url: "http://5.196.109.144/student.php",
data: dataString,
cache: false,
success: function(response) {
var htmlData = '<ul class="student-data">'
if (loggedIn = true) {
for (var i = 0; i < response.length; i += 1) {
var row = '<ul class="table-row">';
htmlData += row;
htmlData += ' <li> Module: ' + response[i].moduleName;
htmlData += ' <li> Grade: ' + response[i].grade;
htmlData += ' <li> Teacher: ' + response[i].teacherName;
htmlData += ' <li> Start Date: ' + response[i].startDate;
htmlData += '</ul>';
}
htmlData += '</li>'
$('.user-profile').append(htmlData);
} else {
alert("A problem occured, Please login again.");
}
}
});
}
return false;
});
$('#logoutBtn').click(function() {
loggedIn = false;
$('.student-data').remove();
});
});
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.5-4-155
description: >
Object.create - 'value' property of one property in 'Properties'
is an inherited data property (8.10.5 step 5.a)
---*/
var proto = {
value: "inheritedDataProperty"
};
var ConstructFun = function () { };
ConstructFun.prototype = proto;
var descObj = new ConstructFun();
var newObj = Object.create({}, {
prop: descObj
});
assert.sameValue(newObj.prop, "inheritedDataProperty", 'newObj.prop');
|
angular.module('ec2016App', [])
.controller('PizzaCtrl', function($scope){
$scope.pizzas = [];
$scope.addPizza = function(paramId, paramName, paramPrice) {
$scope.pizzas.push( { id: paramId, name: paramName, price: paramPrice });
};
$scope.submit = function(){
var id = $scope.newpizza.id;
var name = $scope.newpizza.name;
var price = $scope.newpizza.price;
$scope.addPizza( id, name, price );
app.savePizza( id, name, price );
}
});
function addPizzaToScope(id, name, price) {
var scope = angular.element(
document.getElementById("Pizzas")).scope();
scope.$apply(function () {
scope.addPizza(id, name, price);
});
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var ybase64 = require('../../../src/util/YBase64');
var sinon = require('sinon');
var expect = require('chai').expect;
var sandbox;
var testMessage = 'testMessageToEncodeWithYBase64\n';
describe('YBase64 util', function() {
beforeEach(function() {
sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});
it('should ybase64 string eqals test data', function() {
expect(ybase64.ybase64Encode(testMessage)).to.equal('dGVzdE1lc3NhZ2VUb0VuY29kZVdpdGhZQmFzZTY0Cg--');
expect(Buffer.from(testMessage).toString('base64').replace(/\+/g, '.').replace(/\//g, '_').replace(/=/g, '-')).to
.equal('dGVzdE1lc3NhZ2VUb0VuY29kZVdpdGhZQmFzZTY0Cg--');
});
it('should string eqals ybase64 decoded test data', function() {
expect(ybase64.ybase64Decode('dGVzdE1lc3NhZ2VUb0VuY29kZVdpdGhZQmFzZTY0Cg--').toString('UTF-8')).to.equal(testMessage);
expect(ybase64.ybase64Decode('dGVzdE1lc3NhZ2VUb0VuY29kZVdpdGhZQmFzZTY0Cg--').toString('UTF-8')).to
.equal(Buffer.from(ybase64.ybase64Encode(testMessage).replace(/\./g, '+').replace(/_/g, '/').replace(/-/g, '='), 'base64').toString());
});
it('should test ybase64Decode: invalid input: result error', function() {
try {
ybase64.ybase64Decode(123456789);
} catch (e) {
expect(e.message).to.be.contain('is not string');
return;
}
expect(1).to.be.false;
});
});
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Ember from 'ember';
export default Ember.Controller.extend({
queryParams: ["service"],
service: undefined,
isLoading: false,
actionResponse: null,
actions: {
showStopServiceConfirm() {
this.set('actionResponse', null);
Ember.$("#stopServiceConfirmDialog").modal('show');
},
stopService() {
var self = this;
Ember.$("#stopServiceConfirmDialog").modal('hide');
var adapter = this.store.adapterFor('yarn-servicedef');
self.set('isLoading', true);
adapter.stopService(this.get('service'), this.get('model.app.user')).then(function() {
self.set('actionResponse', {msg: 'Service stopped successfully. Auto refreshing in 5 seconds.', type: 'success'});
Ember.run.later(self, function() {
this.set('actionResponse', null);
this.send("refresh");
}, 5000);
}, function(errr) {
let messg = errr.diagnostics || 'Error: Stop service failed!';
self.set('actionResponse', {msg: messg, type: 'error'});
}).finally(function() {
self.set('isLoading', false);
});
},
showDeleteServiceConfirm() {
this.set('actionResponse', null);
Ember.$("#deleteServiceConfirmDialog").modal('show');
},
deleteService() {
var self = this;
Ember.$("#deleteServiceConfirmDialog").modal('hide');
var adapter = this.store.adapterFor('yarn-servicedef');
self.set('isLoading', true);
adapter.deleteService(this.get('service'), this.get('model.app.user')).then(function() {
self.set('actionResponse', {msg: 'Service deleted successfully. Redirecting to services in 5 seconds.', type: 'success'});
Ember.run.later(self, function() {
this.set('actionResponse', null);
this.transitionToRoute("yarn-services");
}, 5000);
}, function(errr) {
let messg = errr.diagnostics || 'Error: Delete service failed!';
self.set('actionResponse', {msg: messg, type: 'error'});
}).finally(function() {
self.set('isLoading', false);
});
},
resetActionResponse() {
this.set('actionResponse', null);
}
},
isRunningService: Ember.computed('model.serviceName', 'model.app.state', function() {
return this.get('service') !== undefined && this.get('model.app.state') === 'RUNNING';
}),
amHostHttpAddressFormatted: Ember.computed('model.app.amHostHttpAddress', function() {
var amHostAddress = this.get('model.app.amHostHttpAddress');
if (amHostAddress && amHostAddress.indexOf('://') < 0) {
amHostAddress = 'http://' + amHostAddress;
}
return amHostAddress;
})
});
|
// Copyright 2014 Samsung Electronics Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var a = null;
assert(--a === -1);
|
define(function (require) {
const _ = require('lodash');
const moment = require('moment');
// gets parsed value if given arg is a moment object
function timeValue(val) {
return moment.isMoment(val) ? val.valueOf() : val;
}
// returns a properly formatted millisecond timestamp index constraint
function msConstraint(comparison, value) {
return {
[comparison]: timeValue(value),
format: 'epoch_millis'
};
}
// returns a new object with any indexes removed that do not include the
// time field
//
// fixme: this really seems like a bug that needs to be fixed in
// elasticsearch itself, but this workaround will do for now
function omitIndicesWithoutTimeField(indices, timeFieldName) {
return _.pick(indices, index => index.fields[timeFieldName]);
}
return function CalculateIndicesFactory(Promise, es) {
// Uses the field stats api to determine the names of indices that need to
// be queried against that match the given pattern and fall within the
// given time range
function calculateIndices(pattern, timeFieldName, start, stop, sortDirection) {
return getFieldStats(pattern, timeFieldName, start, stop)
.then(resp => omitIndicesWithoutTimeField(resp.indices, timeFieldName))
.then(indices => sortIndexStats(indices, timeFieldName, sortDirection));
};
// creates the configuration hash that must be passed to the elasticsearch
// client
function getFieldStats(pattern, timeFieldName, start, stop) {
const constraints = {};
if (start) {
constraints.max_value = msConstraint('gte', start);
}
if (stop) {
constraints.min_value = msConstraint('lte', stop);
}
return es.fieldStats({
index: pattern,
level: 'indices',
body: {
fields: [ timeFieldName ],
index_constraints: {
[timeFieldName]: constraints
}
}
});
}
function sortIndexStats(indices, timeFieldName, sortDirection) {
const desc = sortDirection === 'desc';
const leader = desc ? 'max' : 'min';
let indexDetails = _(indices).map((stats, index) => {
const field = stats.fields[timeFieldName];
// TODO: remove when we get to es 2.2, see elastic/elasticsearch#14404
let min = field.min_value;
if (typeof min === 'string') min = moment(min).valueOf();
let max = field.max_value;
if (typeof max === 'string') max = moment(max).valueOf();
return { index, min, max };
});
if (sortDirection) {
indexDetails = indexDetails.sortByOrder([leader], [sortDirection]);
}
return indexDetails.value();
}
return calculateIndices;
};
});
|
Jsonix.Schema = {};
|
/* Module to be used by other web driver runners like protractor*/
var Metrics = require('./metrics'),
options = require('./options'),
helpers = require('./helpers'),
Q = require('q'),
debug = require('debug')('bp:selenium:runner'),
wd = require('wd');
var metrics = null;
function Runner(opts) {
this.opts = options.scrub(opts);
this.metrics = null;
this.browser = null;
};
Runner.prototype.setupMetrics_ = function() {
var me = this;
if (this.metrics === null) {
this.metrics = new Metrics(this.opts.metrics);
return this.metrics.setup(this.opts);
} else {
return Q();
}
};
Runner.prototype.attachBrowser_ = function(sessionId) {
if (this.browser === null) {
this.browser = wd.promiseRemote(this.opts.selenium);
this.browser.on('status', function(data) {
//log.debug(data);
});
this.browser.on('command', function(meth, path, data) {
if (data && typeof data === 'object') {
var data = JSON.stringify(data);
}
debug(meth, (path || '').substr(0, 70), (data || '').substr(0, 70));
});
return this.browser.attach(sessionId);
} else {
return Q();
}
};
Runner.prototype.config = function(cb) {
var me = this;
this.setupMetrics_().then(function() {
cb(null, me.opts);
}, function(err) {
cb(err);
});
}
Runner.prototype.start = function(sessionId, cb) {
var me = this;
if (typeof cb !== 'function') {
cb = function() {};
}
this.setupMetrics_().then(function() {
return me.attachBrowser_(sessionId);
}).then(function() {
me.metrics.start(me.browser).then(cb, cb);
});
};
Runner.prototype.stop = function(cb) {
var me = this;
this.metrics.teardown(this.browser).then(function() {
return me.metrics.getResults();
}).then(function(data) {
cb(undefined, data);
}, function(err) {
cb(err, null);
});
};
module.exports = Runner;
|
/**
* Data can often be a complicated mix of numbers and letters (file names
* are a common example) and sorting them in a natural manner is quite a
* difficult problem.
*
* Fortunately a deal of work has already been done in this area by other
* authors - the following plug-in uses the [naturalSort() function by Jim
* Palmer](http://www.overset.com/2008/09/01/javascript-natural-sort-algorithm-with-unicode-support) to provide natural sorting in DataTables.
*
* @name Natural sorting
* @summary Sort data with a mix of numbers and letters _naturally_.
* @author [Jim Palmer](http://www.overset.com/2008/09/01/javascript-natural-sort-algorithm-with-unicode-support)
*
* @example
* $('#example').dataTable( {
* columnDefs: [
* { type: 'natural', targets: 0 }
* ]
* } );
*/
(function() {
/*
* Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
* Author: Jim Palmer (based on chunking idea from Dave Koelle)
* Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
* See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
*/
function naturalSort (a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
hre = /^0x[0-9a-f]+$/i,
ore = /^0/,
// convert all to strings and trim()
x = a.toString().replace(sre, '') || '',
y = b.toString().replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
// numeric, hex or date detection
xD = parseInt(x.match(hre), 10) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),
yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
// first try and sort Hex codes or Dates
if (yD) {
if ( xD < yD ) {
return -1;
}
else if ( xD > yD ) {
return 1;
}
}
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc], 10) || xN[cLoc] || 0;
var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc], 10) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
return (isNaN(oFxNcL)) ? 1 : -1;
}
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL) {
return -1;
}
if (oFxNcL > oFyNcL) {
return 1;
}
}
return 0;
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"natural-asc": function ( a, b ) {
return naturalSort(a,b);
},
"natural-desc": function ( a, b ) {
return naturalSort(a,b) * -1;
}
} );
}());
|
const sql = require('sql-ringojs-client');
const fs = require('fs');
exports.app = function(req) {
const path = req.pathInfo;
let connection, body;
if (path === '/json') {
const helloObject = { message: "Hello, World!" };
// JSON Response Test
return {
status: 200,
headers: { "Content-Type": "application/json" },
body: [JSON.stringify(helloObject)]
}
}
if (path === '/db') {
let queryCount = req.env.servletRequest.getParameter('queries');
try {
connection = datasource.getConnection();
let randId, world;
if (!queryCount || isNaN(queryCount) || queryCount < 1) {
randId = ((Math.random() * 10000) | 0) + 1;
world = sql.query(connection, 'select * from World where World.id = ' + randId)[0];
return {
status: 200,
headers: { "Content-Type": "application/json" },
body: [JSON.stringify(world)]
}
} else {
queryCount = parseInt(queryCount, 10);
body = [];
for (let i = 0; i < queryCount; i++) {
randId = ((Math.random() * 10000) | 0) + 1;
world = sql.query(connection, 'select * from World where World.id = ' + randId)[0];
body.push(world);
}
return {
status: 200,
headers: {"Content-Type": "application/json"},
body: [JSON.stringify(body)]
}
}
} catch (e) {
connection.close();
connection = null;
} finally {
if (connection !== null) {
connection.close();
}
}
}
if (path === '/plaintext') {
return {
status: 200,
headers: {"Content-Type": 'text/plain'},
body: ['Hello, World!']
};
}
if (path === '/updates') {
let queryCount = parseInt(req.env.servletRequest.getParameter('queries'), 10);
if (isNaN(queryCount) || queryCount < 1) {
queryCount = 1;
} else if (queryCount > 500) {
queryCount = 500;
}
try {
connection = datasource.getConnection();
body = [];
for (let i = 0; i < queryCount; i++) {
let randId = ((Math.random() * 10000) | 0) + 1;
world = sql.query(connection, 'select * from World where World.id = ' + randId)[0];
world.randomNumber = ((Math.random() * 10000) | 0) + 1;
sql.execute(connection, 'UPDATE World SET randomNumber = ' + world.randomNumber + ' WHERE id = ' + world.id);
body.push(world);
}
} catch (e) {
connection.close();
connection = null;
} finally {
if (connection !== null) {
connection.close();
}
}
return {
status: 200,
headers: {"Content-Type": "application/json; charset=UTF-8"},
body: [JSON.stringify(body)]
}
}
};
const datasource = module.singleton('pooling-datasource', function() {
const mysqlConnectionProperties = "?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useServerPrepStmts&enableQueryTimeouts=false&useUnbufferedIO=false&useReadAheadInput=false&maintainTimeStats=false&cacheRSMetadata=true&useSSL=false";
return sql.connect("jdbc:mysql://TFB-database/hello_world" + mysqlConnectionProperties, 'benchmarkdbuser', 'benchmarkdbpass');
});
if (require.main == module) {
require("ringo/httpserver").main(module.id);
}
|
(function ($, window) {
window.MyBB = window.MyBB || {};
window.MyBB.Cookie = {
cookiePrefix: '',
cookiePath: '/',
cookieDomain: '',
init: function () {
MyBB.Settings = MyBB.Settings || {};
if (typeof MyBB.Settings.cookiePrefix != 'undefined') {
this.cookiePrefix = MyBB.Settings.cookiePrefix;
}
if (typeof MyBB.Settings.cookiePath != 'undefined') {
this.cookiePath = MyBB.Settings.cookiePath;
}
if (typeof MyBB.Settings.cookieDomain != 'undefined') {
this.cookieDomain = MyBB.Settings.cookieDomain;
}
},
get: function (name) {
this.init();
name = this.cookiePrefix + name;
return $.cookie(name);
},
set: function (name, value, expires) {
this.init();
name = this.cookiePrefix + name;
if (!expires) {
expires = 157680000; // 5*365*24*60*60 => 5 years
}
expire = new Date();
expire.setTime(expire.getTime() + (expires * 1000));
options = {
expires: expire,
path: this.cookiePath,
domain: this.cookieDomain
};
return $.cookie(name, value, options);
},
unset: function (name) {
this.init();
name = this.cookiePrefix + name;
options = {
path: this.cookiePath,
domain: this.cookieDomain
};
return $.removeCookie(name, options);
}
}
})
(jQuery, window);
|
Ext.define('Ozone.components.admin.group.GroupEditPanel', {
extend: 'Ext.panel.Panel',
alias: ['widget.groupedit','widget.groupeditpanel','widget.Ozone.components.admin.group.GroupEditPanel'],
mixins: ['Ozone.components.WidgetAlerts'],
cls: 'groupeditpanel',
initComponent: function () {
var self = this;
Ext.applyIf(this,{
layout: 'fit',
items: [{
xtype: 'editwidgetpanel',
cls: 'adminEditor',
bodyCls: 'adminEditor-body',
dragAndDrop: false,
launchesWidgets: false,
domain: 'Group',
channel: 'AdminChannel',
store: Ext.create('Ozone.data.GroupStore', {}),
items: [
{
xtype: 'groupeditproperties',
itemId: 'groupeditproperties',
editPanel: self
},
{
xtype: 'groupeditusers',
itemId: 'groupeditusers',
editPanel: self
},
{
xtype: 'groupeditwidgets',
itemId: 'groupeditwidgets',
editPanel: self
},
{
xtype: 'groupeditdashboards',
itemId: 'groupeditdashboards',
editPanel: self
},
{
xtype: 'groupeditstacks',
itemId: 'groupeditstacks',
editPanel: self
}
]
}]
});
this.callParent(arguments);
}
});
|
// load('jquery/build.js')
load('steal/rhino/steal.js')
var i, fileName, cmd,
plugins = [
"class" ,
"controller",
{
plugin: "controller/subscribe",
exclude: ["jquery/controller/controller.js",
"jquery/class/class.js",
"jquery/lang/lang.js",
"jquery/event/destroyed/destroyed.js",
"jquery/controller/controller.js"]},
"event/default",
"event/destroyed",
"event/drag",
"event/pause",
"event/resize",
{
plugin: "event/drag/limit",
exclude: ["jquery/lang/vector/vector.js", "jquery/event/livehack/livehack.js", "jquery/event/drag/drag.js"]},
{
plugin: "event/drag/scroll",
exclude: ["jquery/dom/within/within.js", "jquery/dom/compare/compare.js", "jquery/event/drop/drop.js","jquery/lang/vector/vector.js", "jquery/event/livehack/livehack.js", "jquery/event/drag/drag.js"]},
{
plugin: "event/drop",
exclude: ["jquery/lang/vector/vector.js", "jquery/event/livehack/livehack.js", "jquery/event/drag/drag.js"]},
"event/hover",
"view/ejs",
"dom/closest",
"dom/compare",
{
plugin: "dom/dimensions",
fileName: "jquery.dimensions.etc.js"
},
"dom/fixture",
"dom/form_params",
"dom/within",
"dom/cur_styles",
"model",
{
plugin: "model/associations",
exclude: ["jquery/class/class.js",
"jquery/lang/lang.js",
"jquery/event/destroyed/destroyed.js",
"jquery/lang/openajax/openajax.js",
"jquery/model/model.js"]
},
{
plugin: "model/backup",
exclude: ["jquery/class/class.js",
"jquery/lang/lang.js",
"jquery/event/destroyed/destroyed.js",
"jquery/lang/openajax/openajax.js",
"jquery/model/model.js"]
},
{
plugin: "model/list",
exclude: ["jquery/class/class.js",
"jquery/lang/lang.js",
"jquery/event/destroyed/destroyed.js",
"jquery/lang/openajax/openajax.js",
"jquery/model/model.js"]
},
{
plugin: "model/list/cookie",
exclude: ["jquery/class/class.js",
"jquery/lang/lang.js",
"jquery/event/destroyed/destroyed.js",
"jquery/lang/openajax/openajax.js",
"jquery/model/model.js",
"jquery/model/list/list.js"]
},
{
plugin: "model/list/local",
exclude: ["jquery/class/class.js",
"jquery/lang/lang.js",
"jquery/event/destroyed/destroyed.js",
"jquery/lang/openajax/openajax.js",
"jquery/model/model.js",
"jquery/model/list/list.js"]
},
{
plugin: "model/validations",
exclude: ["jquery/class/class.js",
"jquery/lang/lang.js",
"jquery/event/destroyed/destroyed.js",
"jquery/lang/openajax/openajax.js",
"jquery/model/model.js"]
},
"view",
"view/ejs",
"view/jaml",
"view/micro",
"view/tmpl"
]
steal.plugins('steal/build/pluginify').then( function(s){
var plugin, exclude, fileDest, fileName;
for(i=0; i<plugins.length; i++){
plugin = plugins[i];
exclude = [];
fileName = null;
if (typeof plugin != "string") {
fileName = plugin.fileName;
exclude = plugin.exclude || [];
plugin = plugin.plugin;
}
fileName = fileName || "jquery."+plugin.replace(/\//g, ".").replace(/dom\./, "").replace(/\_/, "")+".js";
fileDest = "jquery/dist/"+fileName
s.build.pluginify("jquery/"+plugin,{
nojquery: true,
destination: fileDest,
exclude: exclude.length? exclude: false
})
var outBaos = new java.io.ByteArrayOutputStream();
var output = new java.io.PrintStream(outBaos);
runCommand("java", "-jar", "steal/build/scripts/compiler.jar", "--compilation_level", "SIMPLE_OPTIMIZATIONS", "--warning_level", "QUIET", "--js", fileDest, {
output: output
});
var minFileDest = fileDest.replace(".js", ".min.js")
new steal.File(minFileDest).save(outBaos.toString());
}
})
/*
for (i = 0; i < plugins.length; i++) {
plugin = plugins[i];
exclude = [];
fileName = null;
if (typeof plugin != "string") {
fileName = plugin.fileName;
exclude = plugin.exclude || [];
plugin = plugin.plugin;
}
fileName = fileName || "jquery." + plugin.replace(/\//g, ".").replace(/dom\./, "").replace(/\_/, "") + ".js";
fileDest = "jquery/dist/" + fileName
// compress
var outBaos = new java.io.ByteArrayOutputStream();
var output = new java.io.PrintStream(outBaos);
runCommand("java", "-jar", "steal/build/scripts/compiler.jar", "--compilation_level", "SIMPLE_OPTIMIZATIONS", "--warning_level", "QUIET", "--js", fileDest, {
output: output
});
var minFileDest = fileDest.replace(".js", ".min.js")
new steal.File(minFileDest).save(outBaos.toString());
print("***" + fileName + " pluginified and compressed")
}*/
|
/* @flow */
import type { L10nsStrings } from "../formatters/buildFormatter";
const strings: L10nsStrings = {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "əvvəl",
suffixFromNow: "sonra",
seconds: "saniyələr",
minute: "1 dəqiqə",
minutes: "%d dəqiqə",
hour: "1 saat",
hours: "%d saat",
day: "1 gün",
days: "%d gün",
month: "1 ay",
months: "%d ay",
year: "1 il",
years: "%d il",
wordSeparator: ""
};
export default strings;
|
Object(exports).value = 123;
Object(exports).value2 = 42;
|
/**
* Copyright 2010 Ajax.org B.V.
*
* This product includes software developed by
* Ajax.org B.V. (http://www.ajax.org/).
*
* Author: Fabian Jaokbs <fabian@ajax.org>
*/
var assert = require("assert");
var BitBucket = require("./index").BitBucket;
module.exports = {
setUp: function() {
this.bitbucket = new BitBucket(true);
this.repoApi = this.bitbucket.getRepoApi();
},
// "test: search repos" : function(finished) {
// this.repoApi.search("php github api", function(err, repos) {
// assert.ok(repos.length > 0);
// assert.ok(repos[0].name !== undefined);
// finished();
// });
// },
//
// "test: show repository" : function(finished) {
// this.repoApi.show("fjakobs", "qxoo", function(err, repo) {
// assert.equal(repo.name, "qxoo");
// finished();
// });
// },
"test: get user repos" : function(finished) {
this.repoApi.getUserRepos("c9test01", function(err, repos) {
assert.equal(err, null);
assert.ok(repos.length > 0);
assert.ok(repos[0].name !== undefined);
finished();
});
},
//
// "test: get repo tags" : function(finished) {
// this.repoApi.getRepoTags("fjakobs", "node", function(err, tags) {
// assert.ok(tags["v0.1.0"] == "813b53938b40484f63e7324c030e33711f26a149");
// finished();
// });
// },
//
// "test: get repo languages" : function(finished) {
// this.repoApi.getRepoLanguages("fjakobs", "node", function(err, languages) {
// assert.ok(languages['C++'] != undefined);
// finished();
// });
// },
//
// "test: get repo branches" : function(finished) {
// this.repoApi.getRepoBranches("fjakobs", "node", function(err, branches) {
// assert.ok(branches["master"] !== undefined);
// finished();
// });
// },
//
// "test: get repo collaborators" : function(finished) {
// this.repoApi.getRepoCollaborators("fjakobs", "node", function(err, collaborators) {
// assert.ok(collaborators.length > 0);
// assert.ok(!!~collaborators.toString().split(",").indexOf("fjakobs"));
// finished();
// });
// },
//
// "test: get repo contributors" : function(finished) {
// this.repoApi.getRepoContributors("fjakobs", "node", function(err, contributors) {
// assert.ok(contributors.length > 0);
// assert.ok(contributors[0].login == "ry");
// finished();
// });
// },
//
// "test: get repo non-github contributors" : function(finished) {
// this.repoApi.getRepoContributors("fjakobs", "node", true, function(err, contributors) {
// assert.ok(contributors.length > 0);
// assert.ok(contributors[0].login == "ry");
// finished();
// });
// },
//
// "test: get repo watchers" : function(finished) {
// this.repoApi.getRepoWatchers("fjakobs", "node", function(err, watchers) {
// assert.ok(watchers.length > 0);
// assert.ok(!!~watchers.toString().split(",").indexOf("fjakobs"));
// finished();
// });
// }
};
!module.parent && require("asyncjs").test.testcase(module.exports).exec();
|
/**
* JavaScript library to deal with file uploads
* @author Yannick Warnier <yannick.warnier@chamilo.org>
*/
/**
* Upload class. Used to pack functions into one practical object.
* Call like this: var myUpload = new upload(5);
*/
function upload(latency){
/**
* Starts the timer
* Call like this:
* @param string Name of the DOM element we need to update
* @param string Loading image to display
* @return true
*/
function start(domid,img,text,formid){
__progress_bar_domid = domid;
__progress_bar_img = img;
__progress_bar_text = text;
__progress_bar_interval = setTimeout(__display_progress_bar,latency);
//__display_progress_bar()
__upload_form_domid = formid;
}
/**
* Displays the progress bar in the given DOM element
*/
function __display_progress_bar(){
var my_html ='<span style="font-style:italic;">'+ __progress_bar_text+'</span><br/><img src="'+__progress_bar_img+'" alt="Progress bar"/>';
document.getElementById(__progress_bar_domid).innerHTML = my_html;
if(__upload_form_domid != ''){
document.getElementById(__upload_form_domid).style.display = 'none';
}
}
function stop()
{
//clearTimeout(__progress_bar_interval);
document.getElementById(__progress_bar_domid).innerHTML = null;
document.getElementById(__progress_bar_domid).style.display = 'none';
}
this.start = start;
this.stop = stop;
var __progress_bar_domid = '';
var __progress_bar_img = getPath('WEB_PATH') + '/configuration/resources/images/' + getTheme() + '/action_progress_bar.gif';
var __progress_bar_text = getTranslation('Uploading', 'libraries');
var __upload_form_domid = '';
}
|
/**
* @class CM_Janus_Server
* @extends CM_Frontend_JsonSerializable
*/
var CM_Janus_Server = CM_Frontend_JsonSerializable.extend({
_class: 'CM_Janus_Server',
/**
* @returns {String}
*/
getWebSocketAddress: function() {
return this.get('webSocketAddress');
},
/**
* @param {String} webSocketAddress
*/
setWebSocketAddress: function(webSocketAddress) {
this.set('webSocketAddress', webSocketAddress);
},
/**
* @returns {String}
*/
getWebSocketAddressSubscribeOnly: function() {
return this.get('webSocketAddressSubscribeOnly');
},
/**
* @param {String} webSocketAddressSubscribeOnly
*/
setWebSocketAddressSubscribeOnly: function(webSocketAddressSubscribeOnly) {
this.set('webSocketAddressSubscribeOnly', webSocketAddressSubscribeOnly);
},
/**
* @returns {String[]}
*/
getIceServerList: function() {
return this.get('iceServerList');
},
/**
* @param {String[]} iceServerList
*/
setIceServerList: function(iceServerList) {
this.set('iceServerList', iceServerList);
}
});
|
import React from 'react'
import d3 from 'd3'
import ReactDOM from 'react-dom'
export default class TimeScaleBrush extends React.Component {
constructor(props) {
super(props)
this.chart = null
this.chart_id = "chart_" + props.id
this.svg = null
this.brush = null
this.intervals = {}
this.updateBrush.bind(this)
}
updateBrush(new_extent) {
this.svg.select(".brush").transition()
.duration(250)
.call(this.brush.extent(new_extent))
.call(this.brush.event);
this.props.onBrush(new_extent);
}
updateNamedBrush(name) {
this.updateBrush(this.intervals[name])
}
componentDidMount() {
let el = ReactDOM.findDOMNode(this)
let margin = {top: 5, right: 20, bottom: 20, left: 0},
width = el.offsetWidth - margin.left - margin.right,
height = 80 - margin.top - margin.bottom;
let svg = d3.select(el).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
this.svg = svg
svg.append("rect")
.attr("class", "grid-background")
.attr("width", width)
.attr("height", height)
let small_interval = d3.time.month,
large_interval = d3.time.year
if(this.props.timescale.length < 52 * 7) {
small_interval = d3.time.week
large_interval = d3.time.month
}
let timescale_by_chunk = this.props.timescale.map(small_interval)
let min_max = d3.extent(timescale_by_chunk) // First and last
this.intervals = {
'all': [null, null],
'last_week': [d3.time.week.offset(min_max[1], -1), min_max[1]],
'last_month': [d3.time.month.offset(min_max[1], -1), min_max[1]]
}
let x = d3.time.scale()
.domain(min_max)
.range([0, width])
let brush = d3.svg.brush()
.x(x)
.extent([null, null])
.on("brushend", brushended)
this.brush = brush
let onBrush = this.props.onBrush
function brushended() {
if (!d3.event.sourceEvent) return; // only transition after input
let extent0 = brush.extent(),
extent1 = extent0.map(small_interval.round);
// if empty when rounded, use floor & ceil instead
if (extent1[0] >= extent1[1]) {
extent1[0] = small_interval.floor(extent0[0]);
extent1[1] = small_interval.ceil(extent0[1]);
}
d3.select(this).transition()
.duration(250)
.call(brush.extent(extent1))
.call(brush.event);
if(onBrush) onBrush(extent1)
}
// Ticks by week
svg.append("g")
.attr("class", "x grid")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(small_interval)
.tickSize(-height)
.tickFormat(""))
// X axis with months
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(large_interval)
.tickPadding(0))
.selectAll("text")
.attr("x", 6)
.style("text-anchor", null);
// Selector brush
svg.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.event)
.selectAll("rect")
.attr("height", height)
}
render() {
return (<div id={this.chart_id}></div>);
}
}
|
importScripts('https://cdn.pushcrew.com/sw/ffsw-ea8fbd93b3ff72545ab791ee2cd999e9.js');
|
var webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
output: {
path: "dist/assets",
filename: "bundle.js",
publicPath: "assets"
},
devServer: {
inline: true,
contentBase: './dist',
port: 3000
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: ["babel-loader"],
query: {
presets: ["latest", "stage-0", "react"]
}
},
{
test: /\.json$/,
exclude: /(node_modules)/,
loader: "json-loader"
}
]
}
}
|
const {resolve} = require('path');
const {DefinePlugin} = require('webpack');
const {
GITHUB_URL,
getVersionString,
} = require('react-devtools-extensions/utils');
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
console.error('NODE_ENV not set');
process.exit(1);
}
const builtModulesDir = resolve(__dirname, '..', '..', 'build', 'node_modules');
const __DEV__ = NODE_ENV === 'development';
const DEVTOOLS_VERSION = getVersionString();
module.exports = {
mode: __DEV__ ? 'development' : 'production',
devtool: __DEV__ ? 'cheap-module-eval-source-map' : false,
target: 'electron-main',
entry: {
standalone: './src/standalone.js',
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
library: '[name]',
libraryTarget: 'commonjs2',
},
resolve: {
alias: {
react: resolve(builtModulesDir, 'react'),
'react-dom': resolve(builtModulesDir, 'react-dom'),
'react-debug-tools': resolve(builtModulesDir, 'react-debug-tools'),
'react-is': resolve(builtModulesDir, 'react-is'),
scheduler: resolve(builtModulesDir, 'scheduler'),
},
},
node: {
// Don't replace __dirname!
// This would break the standalone DevTools ability to load the backend.
// see https://github.com/facebook/react-devtools/issues/1269
__dirname: false,
},
plugins: [
new DefinePlugin({
__DEV__: false,
__PROFILE__: false,
__EXPERIMENTAL__: true,
'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
}),
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
configFile: resolve(
__dirname,
'..',
'react-devtools-shared',
'babel.config.js',
),
},
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
// WARNING It's important that we disable CSS source maps for production builds.
// This causes style-loader to insert styles via a <style> tag rather than URL.createObjectURL,
// which in turn avoids a nasty Electron/Chromium bug that breaks DevTools in Nuclide.
// (Calls to URL.createObjectURL seem to crash the webview process.)
sourceMap: __DEV__,
modules: true,
localIdentName: '[local]___[hash:base64:5]',
},
},
],
},
],
},
};
|
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax --turbo --turbo-escape
function f(str) {
var s = "We turn {" + str + "} into a ConsString now";
return s.length;
}
assertEquals(33, f("a"));
assertEquals(33, f("b"));
%OptimizeFunctionOnNextCall(f);
assertEquals(33, f("c"));
function g(str) {
var s = "We also try to materalize {" + str + "} when deopting";
%DeoptimizeNow();
return s.length;
}
assertEquals(43, g("a"));
assertEquals(43, g("b"));
%OptimizeFunctionOnNextCall(g);
assertEquals(43, g("c"));
|
define([], function() {
'use strict';
return ['$scope', 'Restangular', '$filter', function($scope, Restangular, $filter) {
var controller = this;
$scope.company = {};
$scope.address = {};
controller.onFail = function(response) {
if (response.status === 409) {
$scope.errors = [
{
entity: 'company',
message: $filter('translate')('COMPANY.COMPANY_ID_CONFLICT'),
property: 'companyId'
}
];
} else {
$scope.errors = response.data.errors;
}
};
$scope.saveEntity = function() {
// TODO: address exists now even if the company does not!
Restangular.all('addresses')
.post($scope.address)
.then(function(address) {
$scope.company.address = address._links.self.href;
return Restangular.all('companies').post($scope.company);
})
.then(function(company) {
return $scope.closeModal(company);
})
.catch(controller.onFail);
};
}];
});
|
#!/usr/bin/env node
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var suman = require("suman");
var Test = suman.init(module, {
ioc: {
b: 'far',
a: 'foo',
c: 'charge'
},
pre: ['three', 'two']
});
Test.create(function (assert, before, beforeEach, it, after, afterEach) {
before(function (h) {
});
console.log('yolo');
it('is great', function (t) {
});
it('is great', function (t) {
throw new Error('fml');
});
});
|
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CourseTeachersSchema = new Schema({
teacher: { type: Schema.Types.ObjectId, ref: 'b_using_options'},
room: Number
});
var ExamsSchema = new Schema({
subject: { type: String},
examDate: Date,
score: Number,
result: {type: String, enum: ['distinction', 'merit', 'pass', 'fail']},
grader: { type: Schema.Types.ObjectId, ref: 'b_using_options'}
});
var CourseSchema = new Schema({
subject: String,
grade: {type: String},
teachers: [CourseTeachersSchema]
});
var HSchema = new Schema({
surname: {type: String, list: {}, index: true},
forename: {type: String, list: true},
address: {
street: String,
town: String
},
studies: {
courses: {type: [CourseSchema], form: {noRemove: true}},
exams: [ExamsSchema]
},
assistants: [
{ type: Schema.Types.ObjectId, ref: 'b_using_options'}
]
});
var H;
try {
H = mongoose.model('H');
} catch (e) {
H = mongoose.model('H', HSchema);
}
module.exports = H;
|
/**
* Created by c0645457 on 7/08/15.
*/
'use strict';
var contactListApp = angular.module('contactListApp', [
'ngRoute',
'contactControllers',
'contactListFilters',
'contactListServices'
]);
contactListApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/contacts', {
templateUrl: ' partials/contact-list.html',
controller: 'ContactListCtrl'
}).
when('/contacts/:contactId', {
templateUrl: ' partials/contact-detail.html',
controller: 'ContactDetailCtrl'
}).
otherwise({
redirectTo: '/contacts'
});
}]);
|
define('models/<%= collection.name %>-revision', [], function () {
Backbone.Model.<%= collection.name.toCamelCase() %>Revision = Backbone.DeepModel.extend({
idAttribute: '_id',
urlRoot: '/api/<%= collection.name %>/:objectId/revisions',
toString: function () {
<% if (collection.toStringField) { %>
return this.get('snapshot.<%= collection.toStringField %>');
<% } else { %>
return 'Missing config setting: collection.toStringField must be set';
<% } %>
}
});
return Backbone.Model.<%= collection.name.toCamelCase() %>Revision;
});
|
if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {
module.exports = 'pouchdb';
}
(function(window, angular, undefined) {
|
/**
*
* a basic Tiled loader
*/
var game = {
/**
* initlization
*/
onload: function() {
// init the video
if (!me.video.init(800, 480, {wrapper : "jsapp", scale : me.device.getPixelRatio()})) {
alert("Your browser does not support HTML5 canvas.");
return;
}
// set all ressources to be loaded
me.loader.onload = this.loaded.bind(this);
// set all ressources to be loaded
me.loader.preload(g_ressources);
// load everything & display a loading screen
me.state.change(me.state.LOADING);
},
/**
* callback when everything is loaded
*/
loaded: function () {
// set the "Play/Ingame" Screen Object
me.state.set(me.state.PLAY, new game.PlayScreen());
// enable the keyboard (to navigate in the map)
me.input.bindKey(me.input.KEY.LEFT, "left");
me.input.bindKey(me.input.KEY.RIGHT, "right");
me.input.bindKey(me.input.KEY.UP, "up");
me.input.bindKey(me.input.KEY.DOWN, "down");
me.input.bindKey(me.input.KEY.ENTER, "enter");
// start the game
me.state.change(me.state.PLAY);
},
/**
*
* change the current level
* using the listbox current value in the HTML file
*/
changelevel: function() {
var level = "";
var level_id = document.getElementById("level_name").value;
switch (level_id) {
case "1":
level = "village";
break;
case "2":
level = "desert";
break;
case "3":
level = "sewers";
break;
case "4":
level = "cute";
break;
case "5":
level = "isometric";
break;
case "6":
level = "perspective";
break;
default:
return;
};
// load the new level
me.levelDirector.loadLevel(level);
}
}; // game
//bootstrap :)
window.onReady(function() {
game.onload();
});
|
import { Resource } from 'kolibri.lib.apiResource';
export default new Resource({
name: 'contentnode_search',
});
|
angular.module('ionicApp',['ionic','ionic.contrib.drawer'])
.config(function($stateProvider,$urlRouterProvider){
$stateProvider.state('main',{
url : '/main',
templateUrl: 'templates/main.html',
})
$urlRouterProvider.otherwise('/main');
})
|
'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var karma = require('gulp-karma');
var config = require('../config');
function runTestsTask() {
return gulp.src([].concat(
config.test.runtimeFiles,
[ config.test.bundle.dir + '/' + config.test.bundle.name ]
))
.pipe(karma({
configFile: config.test.runnerConfig,
action: 'run'
}))
.on('error', function(err) {
gutil.log('Karma error:', err.message);
});
};
module.exports = runTestsTask;
|
(function () {
"use strict";
function PartialViewMacrosCreateController($scope, codefileResource, $location, navigationService, formHelper, appState) {
var vm = this;
var node = $scope.currentNode;
vm.snippets = [];
vm.createFolderError = "";
vm.folderName = "";
vm.fileName = "";
vm.showSnippets = false;
vm.creatingFolder = false;
vm.showCreateFolder = showCreateFolder;
vm.createFolder = createFolder;
vm.createFile = createFile;
vm.createFileWithoutMacro = createFileWithoutMacro;
vm.showCreateFromSnippet = showCreateFromSnippet;
vm.createFileFromSnippet = createFileFromSnippet;
vm.close = close;
function onInit() {
codefileResource.getSnippets('partialViewMacros')
.then(function (snippets) {
vm.snippets = snippets;
});
}
function showCreateFolder() {
vm.creatingFolder = true;
}
function createFolder(form) {
if (formHelper.submitForm({ scope: $scope, formCtrl: form })) {
codefileResource.createContainer("partialViewMacros", node.id, vm.folderName).then(function (saved) {
navigationService.hideMenu();
navigationService.syncTree({
tree: "partialViewMacros",
path: saved.path,
forceReload: true,
activate: true
});
formHelper.resetForm({ scope: $scope, formCtrl: form });
var section = appState.getSectionState("currentSection");
}, function (err) {
formHelper.resetForm({ scope: $scope, formCtrl: form, hasErrors: true });
vm.createFolderError = err;
});
}
}
function createFile() {
$location.path("/settings/partialViewMacros/edit/" + node.id).search("create", "true");
navigationService.hideMenu();
}
function createFileWithoutMacro() {
$location.path("/settings/partialViewMacros/edit/" + node.id).search("create", "true").search("nomacro", "true");
navigationService.hideMenu();
}
function createFileFromSnippet(snippet) {
$location.path("/settings/partialViewMacros/edit/" + node.id).search("create", "true").search("snippet", snippet.fileName);
navigationService.hideMenu();
}
function showCreateFromSnippet() {
vm.showSnippets = true;
}
function close() {
const showMenu = true;
navigationService.hideDialog(showMenu);
}
onInit();
}
angular.module("umbraco").controller("Umbraco.Editors.PartialViewMacros.CreateController", PartialViewMacrosCreateController);
})();
|
export default (title) => {
return title.toLowerCase().replace(new RegExp(' ', 'gi'), '-')
};
|
import _curry2 from './internal/_curry2.js';
import curryN from './curryN.js';
/**
* Returns a function of arity `n` from a (manually) curried function.
* Note that, the returned function is actually a ramda style
* curryied function, which can accept one or more arguments in each
* function calling.
*
* @func
* @memberOf R
* @since v0.14.0
* @category Function
* @sig Number -> (a -> b -> c ... -> z) -> ((a -> b -> c ...) -> z)
* @param {Number} length The arity for the returned function.
* @param {Function} fn The function to uncurry.
* @return {Function} A new function.
* @see R.curry, R.curryN
* @example
*
* const addFour = a => b => c => d => a + b + c + d;
*
* const uncurriedAddFour = R.uncurryN(4, addFour);
* uncurriedAddFour(1, 2, 3, 4); //=> 10
*/
var uncurryN = _curry2(function uncurryN(depth, fn) {
return curryN(depth, function() {
var currentDepth = 1;
var value = fn;
var idx = 0;
var endIdx;
while (currentDepth <= depth && typeof value === 'function') {
endIdx = currentDepth === depth ? arguments.length : idx + value.length;
value = value.apply(this, Array.prototype.slice.call(arguments, idx, endIdx));
currentDepth += 1;
idx = endIdx;
}
return value;
});
});
export default uncurryN;
|
/*!
* Ext JS Library
* Copyright(c) 2006-2014 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
var windowIndex = 0;
Ext.define('Desktop.BogusModule', {
extend: 'Ext.ux.desktop.Module',
init : function(){
this.launcher = {
text: 'Window '+(++windowIndex),
iconCls:'bogus',
handler : this.createWindow,
scope: this,
windowId:windowIndex
}
},
createWindow : function(src){
var desktop = this.app.getDesktop();
var win = desktop.getWindow('bogus'+src.windowId);
if(!win){
win = desktop.createWindow({
id: 'bogus'+src.windowId,
title:src.text,
width:640,
height:480,
html : '<p>Something useful would be in here.</p>',
iconCls: 'bogus',
animCollapse:false,
constrainHeader:true
});
}
win.show();
return win;
}
});
|
/* To avoid CSS expressions while still supporting IE 7 and IE 6, use this script */
/* The script tag referring to this file must be placed before the ending body tag. */
/* Use conditional comments in order to target IE 7 and older:
<!--[if lt IE 8]><!-->
<script src="ie7/ie7.js"></script>
<!--<![endif]-->
*/
(function() {
function addIcon(el, entity) {
var html = el.innerHTML;
el.innerHTML = '<span style="font-family: \'fileaplay\'">' + entity + '</span>' + html;
}
var icons = {
'ssfa-fileaplay-arrow-down-alt1': '!',
'ssfa-fileaplay-arrow-down-alt2': '"',
'ssfa-fileaplay-play': '#',
'ssfa-fileaplay-pause': '$',
'ssfa-fileaplay-download': '%',
'ssfa-fileaplay-play2': '&',
'ssfa-fileaplay-pause2': ''',
'ssfa-fileaplay-box-add': '(',
'ssfa-fileaplay-download2': ')',
'ssfa-fileaplay-play3': '*',
'ssfa-fileaplay-pause3': '+',
'ssfa-fileaplay-play22': ',',
'ssfa-fileaplay-pause22': '-',
'ssfa-fileaplay-in': '.',
'ssfa-fileaplay-play4': '/',
'ssfa-fileaplay-pause4': '0',
'ssfa-fileaplay-play32': '1',
'ssfa-fileaplay-pause32': '2',
'0': 0
},
els = document.getElementsByTagName('*'),
i, c, el;
for (i = 0; ; i += 1) {
el = els[i];
if(!el) {
break;
}
c = el.className;
c = c.match(/ssfa-fileaplay-[^\s'"]+/);
if (c && icons[c[0]]) {
addIcon(el, icons[c[0]]);
}
}
}());
|
import React from "react";
import Tile from "grommet/components/Tile";
import Heading from "grommet/components/Heading";
import PropTypes from "prop-types";
const CustomTile = props => {
return (
<Tile basis={props.basis || "1/2"} pad="large">
<Heading tag="h5">{props.header}</Heading>
<code style={{ color: "#C094bf" }}>
<span>{props.code}</span>
</code>
</Tile>
);
};
CustomTile.propTypes = {
basis: PropTypes.string,
header: PropTypes.node,
code: PropTypes.string
};
export default CustomTile;
|
define(["Tone/core/Tone", "Tone/component/LowpassCombFilter", "Tone/effect/StereoEffect",
"Tone/signal/Signal", "Tone/component/Split", "Tone/component/Merge", "Tone/signal/ScaleExp"],
function(Tone){
"use strict";
/**
* an array of comb filter delay values from Freeverb implementation
* @static
* @private
* @type {Array}
*/
var combFilterTunings = [1557 / 44100, 1617 / 44100, 1491 / 44100, 1422 / 44100, 1277 / 44100, 1356 / 44100, 1188 / 44100, 1116 / 44100];
/**
* an array of allpass filter frequency values from Freeverb implementation
* @private
* @static
* @type {Array}
*/
var allpassFilterFrequencies = [225, 556, 441, 341];
/**
* @class Tone.Freeverb is a reverb based on [Freeverb](https://ccrma.stanford.edu/~jos/pasp/Freeverb.html).
* Read more on reverb on [SoundOnSound](http://www.soundonsound.com/sos/may00/articles/reverb.htm).
*
* @extends {Tone.Effect}
* @constructor
* @param {NormalRange|Object} [roomSize] Correlated to the decay time.
* @param {Frequency} [dampening] The cutoff frequency of a lowpass filter as part
* of the reverb.
* @example
* var freeverb = new Tone.Freeverb().toMaster();
* freeverb.dampening.value = 1000;
* //routing synth through the reverb
* var synth = new Tone.AMSynth().connect(freeverb);
*/
Tone.Freeverb = function(){
var options = this.optionsObject(arguments, ["roomSize", "dampening"], Tone.Freeverb.defaults);
Tone.StereoEffect.call(this, options);
/**
* The roomSize value between. A larger roomSize
* will result in a longer decay.
* @type {NormalRange}
* @signal
*/
this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange);
/**
* The amount of dampening of the reverberant signal.
* @type {Frequency}
* @signal
*/
this.dampening = new Tone.Signal(options.dampening, Tone.Type.Frequency);
/**
* scale the dampening
* @type {Tone.ScaleExp}
* @private
*/
this._dampeningScale = new Tone.ScaleExp(100, 8000, 0.5)
/**
* the comb filters
* @type {Array}
* @private
*/
this._combFilters = [];
/**
* the allpass filters on the left
* @type {Array}
* @private
*/
this._allpassFiltersL = [];
/**
* the allpass filters on the right
* @type {Array}
* @private
*/
this._allpassFiltersR = [];
//make the allpass filters on teh right
for (var l = 0; l < allpassFilterFrequencies.length; l++){
var allpassL = this.context.createBiquadFilter();
allpassL.type = "allpass";
allpassL.frequency.value = allpassFilterFrequencies[l];
this._allpassFiltersL.push(allpassL);
}
//make the allpass filters on the left
for (var r = 0; r < allpassFilterFrequencies.length; r++){
var allpassR = this.context.createBiquadFilter();
allpassR.type = "allpass";
allpassR.frequency.value = allpassFilterFrequencies[r];
this._allpassFiltersR.push(allpassR);
}
//make the comb filters
for (var c = 0; c < combFilterTunings.length; c++){
var lfpf = new Tone.LowpassCombFilter(combFilterTunings[c]);
if (c < combFilterTunings.length / 2){
this.effectSendL.chain(lfpf, this._allpassFiltersL[0]);
} else {
this.effectSendR.chain(lfpf, this._allpassFiltersR[0]);
}
this.roomSize.connect(lfpf.resonance);
this._dampeningScale.connect(lfpf.dampening);
this._combFilters.push(lfpf);
}
//chain the allpass filters togetehr
this.connectSeries.apply(this, this._allpassFiltersL);
this.connectSeries.apply(this, this._allpassFiltersR);
this._allpassFiltersL[this._allpassFiltersL.length - 1].connect(this.effectReturnL);
this._allpassFiltersR[this._allpassFiltersR.length - 1].connect(this.effectReturnR);
this.dampening.connect(this._dampeningScale);
this._readOnly(["roomSize", "dampening"]);
};
Tone.extend(Tone.Freeverb, Tone.StereoEffect);
/**
* @static
* @type {Object}
*/
Tone.Freeverb.defaults = {
"roomSize" : 0.7,
"dampening" : 0.5
};
/**
* Clean up.
* @returns {Tone.Freeverb} this
*/
Tone.Freeverb.prototype.dispose = function(){
Tone.StereoEffect.prototype.dispose.call(this);
for (var al = 0; al < this._allpassFiltersL.length; al++) {
this._allpassFiltersL[al].disconnect();
this._allpassFiltersL[al] = null;
}
this._allpassFiltersL = null;
for (var ar = 0; ar < this._allpassFiltersR.length; ar++) {
this._allpassFiltersR[ar].disconnect();
this._allpassFiltersR[ar] = null;
}
this._allpassFiltersR = null;
for (var cf = 0; cf < this._combFilters.length; cf++) {
this._combFilters[cf].dispose();
this._combFilters[cf] = null;
}
this._combFilters = null;
this._writable(["roomSize", "dampening"]);
this.roomSize.dispose();
this.roomSize = null;
this.dampening.dispose();
this.dampening = null;
return this;
};
return Tone.Freeverb;
});
|
var rampResources = require("ramp-resources");
function createLogger(verbosity) {
var level = verbosity ? verbosity.slice(1).length : 0;
var logger = {};
var levels = ["debug", "info", "log", "warn", "error"]
var minLevel = (2 - level);
for (var i = 0, ii = levels.length; i < ii; i++) {
var level = levels[i];
if (i < minLevel) {
logger[level] = function(){};
} else {
logger[level] = console.log
}
}
return logger;
};
function createHeaderResourceSet() {
var rs = rampResources.createResourceSet();
rs.addResource({
path: "/",
content: "<p>This is the slave header.</p>"
});
rs.addResource({
path: "/status.js",
content: "buster.onConnectionStatusChange(function (status) { document.body.className = status ? 'connected' : 'disconnected' })"
});
rs.loadPath.append("/status.js");
rs.addResource({
path: "/status.css",
content: "body { background-color: #336699; color: #fff; text-align: center; } body.disconnected { background-color: red; }"
});
rs.loadPath.append("/status.css");
return rs;
};
module.exports.createLogger = createLogger;
module.exports.createHeaderResourceSet = createHeaderResourceSet;
|
// moment.js locale configuration
// locale : portuguese (pt)
// author : Jefferson : https://github.com/jalex79
(function (factory) {
// Comment out broken wrapper, see T145382
/*if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
}*/
factory(this.moment);
}(function (moment) {
return moment.defineLocale('pt', {
months : 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'),
monthsShort : 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'),
weekdays : 'domingo_segunda-feira_terça-feira_quarta-feira_quinta-feira_sexta-feira_sábado'.split('_'),
weekdaysShort : 'dom_seg_ter_qua_qui_sex_sáb'.split('_'),
weekdaysMin : 'dom_2ª_3ª_4ª_5ª_6ª_sáb'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'LT:ss',
L : 'DD/MM/YYYY',
LL : 'D [de] MMMM [de] YYYY',
LLL : 'D [de] MMMM [de] YYYY LT',
LLLL : 'dddd, D [de] MMMM [de] YYYY LT'
},
calendar : {
sameDay: '[Hoje às] LT',
nextDay: '[Amanhã às] LT',
nextWeek: 'dddd [às] LT',
lastDay: '[Ontem às] LT',
lastWeek: function () {
return (this.day() === 0 || this.day() === 6) ?
'[Último] dddd [às] LT' : // Saturday + Sunday
'[Última] dddd [às] LT'; // Monday - Friday
},
sameElse: 'L'
},
relativeTime : {
future : 'em %s',
past : 'há %s',
s : 'segundos',
m : 'um minuto',
mm : '%d minutos',
h : 'uma hora',
hh : '%d horas',
d : 'um dia',
dd : '%d dias',
M : 'um mês',
MM : '%d meses',
y : 'um ano',
yy : '%d anos'
},
ordinalParse: /\d{1,2}º/,
ordinal : '%dº',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
}));
|
import { connect } from 'react-redux';
import AppUpdatedModal from './AppUpdatedModal';
function createMapDispatchToProps(dispatch, props) {
return {
onModalClose() {
location.reload();
}
};
}
export default connect(null, createMapDispatchToProps)(AppUpdatedModal);
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright (c) 2014, Joyent, Inc.
*/
var parser = require('./parser');
var signer = require('./signer');
var verify = require('./verify');
var util = require('./util');
///--- API
module.exports = {
parse: parser.parseRequest,
parseRequest: parser.parseRequest,
sign: signer.signRequest,
signRequest: signer.signRequest,
sshKeyToPEM: util.sshKeyToPEM,
sshKeyFingerprint: util.fingerprint,
verify: verify.verifySignature,
verifySignature: verify.verifySignature
};
|
var glob = require("glob");
var entries = {};
var bundlesPattern = __dirname + "/../app/coffeescripts/bundles/**/*.coffee";
var pluginBundlesPattern = __dirname + "/../gems/plugins/*/app/coffeescripts/bundles/*.coffee";
var bundleNameRegexp = /\/coffeescripts\/bundles\/(.*).coffee/;
var fileNameRegexp = /\/([^/]+)\.coffee/;
var pluginNameRegexp = /plugins\/([^/]+)\/app/;
var appBundles = glob.sync(bundlesPattern, []);
var pluginBundles = glob.sync(pluginBundlesPattern, []);
// these are bundles that are dependencies, and therefore should not be compiled
// as entry points (webpack won't allow that).
// TODO: Ultimately we should move them to other directories.
var nonEntryPoints = ['common', 'modules/account_quota_settings', 'modules/content_migration_setup'];
appBundles.forEach(function(entryFilepath){
var entryBundlePath = entryFilepath.replace(/^.*app\/coffeescripts\/bundles/, "./app/coffeescripts/bundles")
var entryName = bundleNameRegexp.exec(entryBundlePath)[1];
if(nonEntryPoints.indexOf(entryName) < 0){
entries[entryName] = entryBundlePath;
}
});
// TODO: Include this from source rather than after the ember app compilation step.
// This whole "compiled" folder should eventually go away
entries['screenreader_gradebook'] = "./public/javascripts/compiled/bundles/screenreader_gradebook.js";
pluginBundles.forEach(function(entryFilepath){
var pluginName = pluginNameRegexp.exec(entryFilepath)[1];
var fileName = fileNameRegexp.exec(entryFilepath)[1];
var bundleName = pluginName + "-" + fileName;
entries[bundleName] = entryFilepath;
});
entries['instructure-common'] = [
'ajax_errors',
'coffeescripts/bundles/common',
'classnames',
'compiled/helpDialog',
'compiled/badge_counts',
'compiled/behaviors/activate',
'compiled/behaviors/admin-links',
'compiled/behaviors/authenticity_token',
'compiled/behaviors/elementToggler',
'compiled/behaviors/instructure_inline_media_comment',
'compiled/behaviors/ping',
'compiled/behaviors/tooltip',
'compiled/behaviors/ujsLinks',
'compiled/collections/AssignmentOverrideCollection',
'compiled/collections/DateGroupCollection',
'compiled/collections/GroupUserCollection',
'compiled/editor/stocktiny',
'compiled/grade_calculator',
'compiled/jquery/ModuleSequenceFooter',
'compiled/jquery/serializeForm',
'compiled/models/Assignment',
'compiled/models/grade_summary/CalculationMethodContent',
'compiled/models/AssignmentOverride',
'compiled/models/DateGroup',
'compiled/models/Group',
'compiled/models/Outcome',
'compiled/models/Progress',
'compiled/models/Pseudonym',
'compiled/models/Section',
'compiled/models/TurnitinSettings',
'compiled/models/User',
'compiled/PandaPub',
'compiled/registration/incompleteRegistrationWarning',
'compiled/util/brandableCss',
'compiled/util/DateValidator',
'compiled/util/PandaPubPoller',
'compiled/util/Popover',
'compiled/util/round',
'compiled/views/CollectionView',
'compiled/views/DialogBaseView',
'compiled/views/DialogFormView',
'compiled/views/editor/KeyboardShortcuts',
'compiled/views/MessageStudentsDialog',
'compiled/views/PaginatedCollectionView',
'compiled/views/PaginatedView',
'compiled/views/PublishButtonView',
'compiled/views/PublishIconView',
'compiled/views/TreeBrowserView',
'compiled/views/ValidatedFormView',
'compiled/views/ValidatedMixin',
'i18nObj',
'instructure',
'jquery.instructure_forms',
'jquery.toJSON',
'jst/_avatar',
'jst/collectionView',
'jst/DialogFormWrapper',
'jst/editor/KeyboardShortcuts',
'jst/EmptyDialogFormWrapper',
'jst/ExternalTools/_external_tool_menuitem',
'jst/messageStudentsDialog',
'jst/outcomes/_calculationMethodExample',
'jst/paginatedCollection',
'jst/PaginatedView',
'jsx/shared/helpers/createStore',
'link_enrollment',
'LtiThumbnailLauncher',
'media_comments',
'page_views',
'reminders'
];
entries['vendor'] = [
'Backbone',
'bower/classnames/index',
'bower/handlebars/handlebars.runtime',
'handlebars',
'jquery',
'jquery.ajaxJSON',
'jquery.fancyplaceholder',
'jquery.google-analytics',
'jqueryui/autocomplete',
'jqueryui/effects/drop',
'jqueryui/progressbar',
'jqueryui/tabs',
'moment',
'react',
'react-modal',
'underscore',
'vendor/backbone-identity-map',
'vendor/backbone',
'vendor/date',
'vendor/d3.v3',
'vendor/graphael',
'vendor/i18n',
'vendor/i18n_js_extension',
'vendor/jquery-1.7.2',
'vendor/jquery.ba-hashchange',
'vendor/jquery.ba-tinypubsub',
'vendor/jquery.cookie',
'vendor/jquery.pageless',
'vendor/jquery.scrollTo',
'vendor/mediaelement-and-player',
'vendor/raphael',
'vendor/redux',
'vendor/slickgrid/slick.grid',
'vendor/slickgrid/slick.editors',
'vendor/slickgrid/plugins/slick.rowselectionmodel',
'vendor/swfobject/swfobject'
];
module.exports = entries;
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'basicstyles', 'bg', {
bold: 'Удебелен',
italic: 'Наклонен',
strike: 'Зачертан текст',
subscript: 'Индексиран текст',
superscript: 'Суперскрипт',
underline: 'Подчертан'
} );
|
'use strict';
var p5 = require('../core/core');
/**
* [normal description]
* @return {[type]} [description]
*/
p5.prototype.normalMaterial = function(){
var mId = 'normalVert|normalFrag';
if(!this._graphics.materialInHash(mId)){
this._graphics.initShaders('normalVert', 'normalFrag');
}
if(mId !== this._graphics.getCurShaderId()){
this._graphics.saveShaders(mId);
}
return this;
};
/**
* [basic description]
* @param {[type]} r [description]
* @param {[type]} g [description]
* @param {[type]} b [description]
* @param {[type]} a [description]
* @return {[type]} [description]
*/
p5.prototype.basicMaterial = function(r, g, b, a){
var mId = 'normalVert|basicFrag';
var gl = this._graphics.GL;
var shaderProgram;
if(!this._graphics.materialInHash(mId)){
shaderProgram =
this._graphics.initShaders('normalVert', 'basicFrag');
}else{
shaderProgram = this._graphics.mHash[mId];
}
gl.useProgram(shaderProgram);
shaderProgram.uMaterialColor = gl.getUniformLocation(
shaderProgram, 'uMaterialColor' );
var color = this._graphics._pInst.color.apply(
this._graphics._pInst, arguments);
var colors = _normalizeColor(color.rgba);
gl.uniform4f( shaderProgram.uMaterialColor,
colors[0], colors[1], colors[2], colors[3]);
if(mId !== this._graphics.getCurShaderId()){
this._graphics.saveShaders(mId);
}
return this;
};
function _normalizeColor(_arr){
var arr = [];
_arr.forEach(function(val){
arr.push(val/255);
});
return arr;
}
module.exports = p5;
|
import $ from 'jquery';
import Marionette from 'backbone.marionette';
import ActionView from './action-view';
export default Marionette.CollectionView.extend({
childView: ActionView,
childViewOptions: function () {
return {
state: this.options.state
};
},
scrollToTop: function () {
var parent = this.$el.scrollParent();
if (parent.is(document)) {
parent = $(window);
}
parent.scrollTop(0);
},
scrollToAction: function (action) {
var model = this.collection.findWhere({ key: action });
if (model != null) {
var view = this.children.findByModel(model);
if (view != null) {
this.scrollToView(view);
}
}
},
scrollToView: function (view) {
var el = view.$el,
parent = el.scrollParent();
var elOffset = el.offset(),
parentOffset = parent.offset();
if (parent.is(document)) {
parentOffset = { top: 0 };
}
if (elOffset != null && parentOffset != null) {
var scrollTop = elOffset.top - parentOffset.top - 70;
parent.scrollTop(scrollTop);
}
}
});
|
'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var $ = require('../internals/export');
var iterate = require('../internals/iterate');
var aCallable = require('../internals/a-callable');
var anObject = require('../internals/an-object');
$({ target: 'Iterator', proto: true, real: true }, {
every: function every(fn) {
anObject(this);
aCallable(fn);
return !iterate(this, function (value, stop) {
if (!fn(value)) return stop();
}, { IS_ITERATOR: true, INTERRUPTED: true }).stopped;
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.