text
stringlengths
2
6.14k
var vertx = require('vertx'); vertx.createHttpServer().requestHandler(function(req) { req.response.end('Hello World\n'); }).listen(8080)
Template['signup'].helpers({ }); Template['signup'].events({ });
$ = jQuery = require('jquery'); require('./picker.js'); require('./picker.date.js'); require('./picker.time.js'); require('./legacy.js');
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _ = require('lodash'); var async = require('async'); /** * Helper class that triggers execution for components */ var Executor = /** @class */ (function () { function Executor() { } /** * Triggers execution for component that implement IExecutable and IParamExecutable interfaces * and passes to IParamExecutable them set of parameters. * @param correlationId a unique transaction id to trace calls across components * @param component a components to be executed * @param args a set of parameters to pass to executed components * @param callback a function to call back with results when execution is complete */ Executor.executeOne = function (correlationId, component, args, callback) { if (_.isFunction(component.execute)) { try { return component.execute(correlationId, args, callback); } catch (err) { callback(err, null); } } else callback(null, null); }; /** * Triggers execution for components that implement IExecutable and IParamExecutable interfaces * and passes to IParamExecutable them set of parameters. * @param correlationId a unique transaction id to trace calls across components * @param components a list of components to be executed * @param args a set of parameters to pass to executed components * @param callback a function to call back with results when execution is complete */ Executor.execute = function (correlationId, components, args, callback) { var results = []; async.eachSeries(components, function (component, callback) { Executor.executeOne(correlationId, component, args, function (err, result) { results.push(result); callback(err); }); }, function (err) { callback(err, results); }); }; return Executor; }()); exports.Executor = Executor; //# sourceMappingURL=Executor.js.map
// ==UserScript== // @name Kingsage Enhancement Suite // @version 1.3.1.0 // @author grafilicious // @include http://*.kingsage.*game.php* // @include http://*.kingsage.*redir.php* // @include https://*.kingsage.*game.php* // @include https://*.kingsage.*redir.php* // @exclude http://support.*/* // @grant none // ==/UserScript==
import React, { Component, PropTypes } from 'react'; import { TextInput, ScrollView, Text, View, TouchableHighlight } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import DropdownAlert from 'react-native-dropdownalert'; import Swipeout from 'react-native-swipe-out'; import Modal from 'react-native-root-modal'; import Button from 'react-native-button'; import { Actions } from 'react-native-router-flux'; import styles from '../styles/styles.js'; export default class Tasks extends Component { static propTypes = { addTask: PropTypes.func.isRequired, removeTask: PropTypes.func.isRequired, tasks: PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { formOpen: false, formTaskTitle: '', } } componentDidMount() { Actions.refresh({ renderRightButton: this.renderRightButton }); } renderRightButton = () => { return ( <TouchableHighlight onPress={() => this.openForm()}> <Text style={styles.navbarRightButton}>+</Text> </TouchableHighlight> ); } tasksDone() { return [].concat(this.props.tasks.tasks.filter((ele) => ele.status == 'done')); } tasksOpen() { return [].concat(this.props.tasks.tasks.filter((ele) => ele.status == 'open')); } listDoneTasks() { if(this.props.showtabs == 'open') { return; } const list = this.tasksDone(); return list.map((task) => { const swipeButtons = [ { text: 'Delete', backgroundColor: 'red', color: 'white', onPress: () => this.deleteTask(task), }, { text: 'Undone', type: 'primary', onPress: () => this.undoTask(task), } ]; return ( <View key={task.id} style={styles.taskrow}> <Swipeout left={swipeButtons} style={styles.taskswipe}> <View style={styles.taskdescription}> <Text>{task.title}</Text> </View> </Swipeout> </View> ) }); } listOpenTasks() { if(this.props.showtabs == 'done') { return; } const list = this.tasksOpen(); return list.map((task) => { const swipeButtons = [ { text: 'Delete', backgroundColor: 'red', color: 'white', onPress: () => this.deleteTask(task), }, { text: 'Done', type: 'primary', onPress: () => this.completeTask(task), } ]; return ( <View key={task.id} style={styles.taskrow}> <Swipeout left={swipeButtons} style={styles.taskswipe}> <View style={styles.taskdescription}> <Text>{task.title}</Text> </View> </Swipeout> </View> ) }); } deleteTask(task) { this.props.removeTask(task); } completeTask(task) { this.props.markTaskComplete(task); } undoTask(task) { this.props.markTaskIncomplete(task); } saveTask() { const taskTitle = this.state.formTaskTitle; this.setState({formTaskTitle: ''}); this.props.addTask(taskTitle); this.closeForm(); } _titleOnChange(text) { this.setState({formTaskTitle: text}); } openForm() { this.setState({formOpen: true}); } closeForm() { this.setState({formOpen: false}); } formTask() { return ( <Modal visible={this.state.formOpen}> <View style={styles.inputmodalroot} onPress={() => this.closeForm()}> <View style={styles.inputmodalrow}> <Text style={styles.inputmodalhead}>New Task</Text> </View> <View style={styles.inputmodalrow}> <TextInput style={styles.inputmodalinput} placeholder="Task Description" onChangeText={(text) => this._titleOnChange(text)} onSubmitEditing={() => {this.saveTask()}} autoCorrect={false} value={this.state.formName} /> </View> <View style={styles.inputmodalrow}> <TouchableHighlight style={styles.inputmodalcancel} onPress={() => this.closeForm()}> <View> <Text>Cancel</Text> </View> </TouchableHighlight> <TouchableHighlight style={styles.inputmodalsave} onPress={() => this.saveTask()}> <View> <Text>Save</Text> </View> </TouchableHighlight> </View> </View> </Modal> ); } titleStats() { const open = this.props.tasks.tasks.filter((el) => el.status == 'open').length; const done = this.props.tasks.tasks.length - open; return ( <View style={styles.header}> <Text style={styles.headertext}>Open: {open}</Text> <Text style={styles.headertext}>Done: {done}</Text> </View> ) } render() { return ( <ScrollView style={styles.tasksscrollview}> {this.formTask()} {this.titleStats()} {this.listOpenTasks()} {this.listDoneTasks()} <DropdownAlert ref={(ref) => this.dropdown = ref} /> </ScrollView> ); } } /* */
module.exports = [ { output: { filename: "commonjs.js", libraryTarget: "commonjs-module" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "umd.js", libraryTarget: "umd" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "umd-default.js", libraryTarget: "umd", libraryExport: "default" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "this.js", libraryTarget: "this" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "global.js", library: "globalName" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "commonjs2-external.js", libraryTarget: "commonjs2" }, externals: ["external"] } ];
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the CustomParameterGroup class. * @constructor * Additional parameters for a set of operations, such as: * Paging_getMultiplePagesFragmentWithGroupingNextLink, * Paging_nextFragmentWithGrouping. * * @member {string} apiVersion Sets the api version to use. * * @member {string} tenant Sets the tenant to use. * */ function CustomParameterGroup() { } /** * Defines the metadata of CustomParameterGroup * * @returns {object} metadata of CustomParameterGroup * */ CustomParameterGroup.prototype.mapper = function () { return { required: false, type: { name: 'Composite', className: 'CustomParameterGroup', modelProperties: { apiVersion: { required: true, type: { name: 'String' } }, tenant: { required: true, type: { name: 'String' } } } } }; }; module.exports = CustomParameterGroup;
var app = app || {} app.TaskCollection = Backbone.Collection.extend({ model: app.SharedTaskModel, url: "/tasks", // will be overwritten to be `tasks-unassigned`, `task-user/<username>`, or `tasks-completed` collectionKind: null, initialize: function(models, options) { this.masterTaskCollection = app.allTasks; this.collectionKind = options.collectionKind; this.url = options.url; this.listenTo(this.masterTaskCollection, "add", this.taskAdded); this.listenTo(this.masterTaskCollection, "change", this.taskChanged); this.listenTo(this.masterTaskCollection, "remove", this.taskRemoved); this.fetch(); // returns and array of object. each obj is passed to new SharedTaskModel(obj) }, taskAdded: function(e) { console.log(Date.now() + " : " + this.collectionKind + " added ", e); var status = e.get("status"); var creator = e.get("creator"); var assignee = e.get("assignee"); var currentUser = app.currentUser.get("username"); switch (this.collectionKind) { case "unassigned": if (status === "unassigned") { this.add(e); } break; case "user": if (creator === currentUser || assignee === currentUser) { this.add(e); } break; case "completed": if (status === "completed") { this.add(e); } break; } }, taskChanged: function(e) { console.log(Date.now() + " : " + this.collectionKind + " changed ", e); var status = e.get("status"); var creator = e.get("creator"); var assignee = e.get("assignee"); var currentUser = app.currentUser.get("username"); switch (this.collectionKind) { case "unassigned": if (status !== "unassigned") { this.remove(e); } else if (status === "unassigned") { this.add(e); } break; case "user": if ((creator === currentUser || assignee === currentUser) && status !== "completed") { this.add(e); } else { this.remove(e); } break; case "completed": if (status === "completed") { this.add(e); } break; } }, taskRemoved: function(e) { this.remove(e); } })
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.3-3-1 description: Object.getOwnPropertyDescriptor - 'P' is own data property includes: [runTestCase.js] ---*/ function testcase() { var obj = { property: "ownDataProperty" }; var desc = Object.getOwnPropertyDescriptor(obj, "property"); return desc.value === "ownDataProperty"; } runTestCase(testcase);
var path = require('path'); var gulp = require('gulp'); var args = require('yargs').argv; var colors = require('colors'); var spawn = require('child_process').spawn; var fs = require('fs'); const mappings = require('./api-specs.json'); const defaultSpecRoot = "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master"; gulp.task('default', function () { console.log("Usage: gulp codegen " + "[--spec-root <swagger specs root>] " + "[--projects <project names>] " + "[--autorest <autorest info>] " + "[--autorest-csharp <autorest.csharp info>] " + "[--debug] " + "[--autorest-args <AutoRest arguments>]\n"); console.log("--spec-root"); console.log(`\tRoot location of Swagger API specs, default value is "${defaultSpecRoot}"`); console.log("--projects"); console.log("\tComma separated projects to regenerate, default is all. List of available project names:"); Object.keys(mappings).forEach(function(i) { console.log('\t' + i.magenta); }); console.log("--autorest"); console.log("\tThe version of AutoRest. E.g. 2.0.9, or the location of AutoRest repo, e.g. E:\\repo\\autorest"); console.log("--autorest-csharp"); console.log("\tThe NPM version number for the autorest.csharp generator, e.g. @2.1.28 or @preview, or a file path to a local autorest.csharp generator."); console.log("\tUsually you'll only need to provide this and not a --autorest argument in order to work on C# code generation."); console.log("\tSee https://github.com/Azure/autorest/blob/master/docs/developer/autorest-extension.md"); console.log("--debug"); console.log("\tFlag that allows you to attach a debugger to the autorest.csharp generator."); console.log("--autorest-args"); console.log("\tPasses additional argument to AutoRest generator"); }); var specRoot = args['spec-root'] || defaultSpecRoot; var projects = args['projects']; var autoRestVersion = 'latest'; // default if (args['autorest'] !== undefined) { autoRestVersion = args['autorest']; } var debug = args['debug']; var autoRestArgs = args['autorest-args'] || ''; var autoRestExe; gulp.task('codegen', function (cb) { if (autoRestVersion.match(/[0-9]+\.[0-9]+\.[0-9]+.*/) || autoRestVersion == 'latest' || autoRestVersion == 'preview') { autoRestExe = 'autorest ---version=' + autoRestVersion; handleInput(projects, cb); } else { autoRestExe = "node " + path.join(autoRestVersion, "src/autorest-core/dist/app.js"); handleInput(projects, cb); } }); var handleInput = function (projects, cb) { if (projects === undefined) { Object.keys(mappings).forEach(function (proj) { codegen(proj, cb); }); } else { projects.split(",").forEach(function (proj) { proj = proj.replace(/\ /g, ''); if (mappings[proj] === undefined) { console.error('Invalid project name "' + proj + '"!'); process.exit(1); } codegen(proj, cb); }); } } var codegen = function (project, cb) { const regenManager = args['regenerate-manager'] ? ' --regenerate-manager=true ' : ''; var outputDir = path.resolve(mappings[project].dir); if (!args['preserve']) { deleteFolderRecursive(outputDir); } console.log('Generating "' + project + '" from spec file ' + specRoot + '/' + mappings[project].source); var generator = '--fluent'; if (mappings[project].fluent !== null && mappings[project].fluent === false) { generator = ''; } const autorestCSArg = args['autorest-csharp'] || "@latest"; const generatorPath = autorestCSArg.startsWith("@") ? "@microsoft.azure/autorest.csharp" + autorestCSArg : path.resolve(autorestCSArg); const autorestUseArg = `--use=${generatorPath}`; cmd = autoRestExe + ' ' + specRoot + "/" + mappings[project].source + ' --csharp ' + ' --azure-arm ' + generator + ' --csharp.sync-methods=none ' + ` --csharp.namespace=${mappings[project].package} ` + ` --csharp.output-folder=${outputDir} ` + ` --csharp.license-header=MICROSOFT_MIT_NO_CODEGEN ` + ` --csharp.clear-output-folder=false ` + autorestUseArg + regenManager + ' --use=@microsoft.azure/autorest.csharp@preview' + ' --package-version=1.3.0 ' + ' --runtime-version=3.3.10 ' + autoRestArgs; if (mappings[project].args !== undefined) { cmd = cmd + ' ' + mappings[project].args; } if (debug) { cmd += ' --csharp.debugger'; } console.log('Command: ' + cmd); spawn(cmd, [], { shell: true, stdio: "inherit" }); }; var deleteFolderRecursive = function(path) { var header = "Code generated by Microsoft (R) AutoRest Code Generator"; if(fs.existsSync(path)) { fs.readdirSync(path).forEach(function(file, index) { var curPath = path + "/" + file; if(fs.lstatSync(curPath).isDirectory()) { // recurse deleteFolderRecursive(curPath); } else { // delete file var content = fs.readFileSync(curPath).toString('utf8'); if (content.indexOf(header) > -1) { fs.unlinkSync(curPath); } } }); } };
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require react //= require react_ujs //= require components //= require_tree . //= require bootstrap-sprockets //= require bootstrap //= require tether
/* * Report container widget * * Data attributes: * - data-control="report-container" - enables the report container plugin * * JavaScript API: * $('#container').reportContainer() * * Dependancies: * - Isotope (isotope.js) */ +function ($) { "use strict"; // REPORTCONTAINER CLASS DEFINITION // ============================ var ReportContainer = function(element, options) { this.options = options this.$el= $(element) this.$form = this.$el.closest('form') this.$toolbar = $('[data-container-toolbar]', this.$form) this.alias = $('[data-container-alias]', this.$form).val() this.init(); } ReportContainer.DEFAULTS = { breakpoint: 768, columns: 10 } ReportContainer.prototype.init = function (){ var self = this this.$el.isotope({ itemSelector: '.item', resizable: false }) $(window).resize($.proxy(this.updateWidth, this)) this.updateWidth() if (!Modernizr.touch) { this.$el.sortable({ vertical: false, handle: '.drag-handle', onDrop: function($item, container, _super) { $item.removeClass("dragged") $("body").removeClass("dragging") self.updateSeparators() self.redraw() self.postSortOrders() } }) } this.$el.on('hidden.oc.inspector', '[data-inspectable]', function() { var values = $('[data-inspector-values]', this).val(), parsedValues = $.parseJSON(values), li = $(this).closest('li').get(0) self.$form.request(self.alias + '::onUpdateWidget', { data: { 'fields': values, 'alias': $('[data-widget-alias]', $(this).closest('div.content')).val() }, success: function(data) { this.success(data).done(function(){ li.className = li.className.replace(/width\-[0-9]+/g, '') $(li).addClass('width-'+parsedValues['ocWidgetWidth']) $(li).toggleClass('new-line', parsedValues['ocWidgetNewRow'] == 1) self.updateSeparators() self.redraw() }) } }) }) this.$el.on('click', '.content > button.close', function() { var $btn = $(this) $.oc.confirm('Remove this widget?', function() { self.$form.request(self.alias + '::onRemoveWidget', { data: { 'alias': $('[data-widget-alias]', $btn.closest('div.content')).val() } }) $btn.closest('li').remove() self.redraw() self.setSortOrders() }) }) $(window).on('oc.reportWidgetAdded', function(){ self.redraw() self.setSortOrders() }) $(window).on('oc.reportWidgetRefresh', function(){ self.redraw() }) window.setTimeout(function(){ self.updateWidth() self.redraw() }, 200) this.setSortOrders() } ReportContainer.prototype.updateWidth = function(){ var width = this.$el.width(), wrapped = width <= this.options.breakpoint, columnWidth = wrapped ? width : width / this.options.columns this.$el.isotope({ masonry: { columnWidth: columnWidth } }) this.$el.toggleClass('wrapped', wrapped) } ReportContainer.prototype.redraw = function() { this.$el .isotope('reloadItems') .isotope({ sortBy: 'original-order' }) var $items = $('li.item', this.$el) $items.css({'width': '', 'height': ''}) $('> .dropdown', this.$toolbar).toggleClass('dropup', !!$items.length) } ReportContainer.prototype.setSortOrders = function() { this.sortOrders = [] var self = this $('[data-widget-order]', this.$el).each(function(){ self.sortOrders.push($(this).val()) }) } ReportContainer.prototype.postSortOrders = function() { var aliases = [], self = this $('[data-widget-alias]', this.$el).each(function(){ aliases.push($(this).val()) }) this.$form.request(self.alias + '::onSetWidgetOrders', { data: { 'aliases': aliases.join(','), 'orders': self.sortOrders.join(',') } }) } ReportContainer.prototype.updateSeparators = function() { $('li.item.separator', this.$el).remove() $('li.item.new-line', this.$el).each(function(){ $(this).before('<li class="item separator"></li>') }) } // REPORTCONTAINER PLUGIN DEFINITION // ============================ var old = $.fn.reportContainer $.fn.reportContainer = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('oc.reportContainer') var options = $.extend({}, ReportContainer.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('oc.reportContainer', (data = new ReportContainer(this, options))) if (typeof option == 'string') data[option].call($this) }) } $.fn.reportContainer.Constructor = ReportContainer // REPORTCONTAINER NO CONFLICT // ================= $.fn.reportContainer.noConflict = function () { $.fn.reportContainer = old return this } // REPORTCONTAINER DATA-API // =============== $(document).render(function () { $('[data-control="report-container"]').reportContainer() }) }(window.jQuery);
import React, {Component} from 'react'; import SelectField from 'material-ui/SelectField'; class TeamMatch extends Component { render() { const style = { h1: { fontFamily: "Roboto", fontSize: 22, fontWeight: 500, marginTop: 15, marginBottom: 0, }, matchContainer: { width: "80%", margin: "auto", }, }; return ( <div style={style.matchContainer}> <h1 style={style.h1}> Match {this.props.matchNumber} </h1> <SelectField value={this.props.player1} fullWidth={true} onChange={this.props.selectPlayer1} maxHeight={200} > {this.props.players} </SelectField> <div> <span>and</span> </div> <SelectField value={this.props.player2} fullWidth={true} onChange={this.props.selectPlayer2} maxHeight={200} > {this.props.players} </SelectField> </div> ) } } export default TeamMatch;
AwsApplicationModel = AwsDeploy.Model.extend({ idAttribute: "application_name" }); AwsApplicationCollection = AwsDeploy.Collection.extend({ model: AwsApplicationModel, url: "/aws/apps" }); AwsEnvironmentModel = AwsDeploy.Model.extend({ idAttribute: "environment_id" }); AwsEnvironmentCollection = AwsDeploy.Collection.extend({ model: AwsEnvironmentModel, url: function () { return "/aws/apps/" + this.application_name + "/environments"; } }); AwsApplicationVersionModel = AwsDeploy.Model.extend({ idAttribute: "version_label" }); AwsApplicationVersionCollection = AwsDeploy.Collection.extend({ model: AwsApplicationVersionModel, url: function () { return "/aws/apps/" + this.application_name + "/versions"; } }); AwsS3BucketModel = AwsDeploy.Model.extend({ idAttribute: "bucket_name" }); AwsS3BucketCollection = AwsDeploy.Collection.extend({ model: AwsS3BucketModel, url: function () { return "/aws/s3/buckets"; } });
version https://git-lfs.github.com/spec/v1 oid sha256:4cf204823e3498eff3398eefe0ba3895ba2ec12a24deeb0ff1ae3f01c5ce5f2d size 129
var fs = require('fs'); var path = require('path'); var glob = require('glob'); var prettyjson = require('prettyjson'); var _ = require('lodash'); var config = require('../src/utils/config'); function processComponent(filepath) { var examplesFile = config.getExampleFilename(filepath); var hasExamples = !!fs.existsSync(examplesFile); return '{' + [ 'filepath: ' + JSON.stringify(filepath), 'relativePath: ' + JSON.stringify(path.relative(config.rootDir, filepath)), 'module: ' + requireIt(filepath), 'examples: ' + (hasExamples ? requireIt('examples!' + examplesFile) : null) ].join(',') + '}'; } function requireIt(filepath) { return 'require(' + JSON.stringify(filepath) + ')'; } module.exports = function() {}; module.exports.pitch = function() { this.cacheable && this.cacheable(); var componentSources; if (typeof config.components === 'function') { componentSources = config.components(config, glob); } else { componentSources = glob.sync(path.join(config.rootDir, config.components)); } if (config.verbose) { console.log(); console.log('Loading components:'); console.log(prettyjson.render(componentSources)); console.log(); } var specPath; var specId; var components = componentSources.map(function(item){ specPath = config.getExampleFilename(item); specId = path.dirname(specPath.replace(global.userPath, '')).replace(/\\/g, '/'); specId = specId.replace(/^\//, '').toLowerCase(); return '"' + specId + '":' + processComponent(item); }); var simplifiedConfig = _.pick(config, [ 'title', 'highlightTheme' ]); return [ 'module.exports = {', ' config: ' + JSON.stringify(simplifiedConfig) + ',', ' components: {' + components.join(',') + '}', '};' ].join('\n'); };
exports.BattleMovedex = { "waterpulse": { inherit: true, basePower: 80 }, "paleowave": { inherit: true, isNonstandard: false }, "submission": { inherit: true, accuracy: 100, basePower: 120, category: "Physical", secondary: { chance: 10, volatileStatus: 'flinch' } }, "lunardance": { num: 461, accuracy: true, basePower: 0, category: "Status", desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.", shortDesc: "User faints. Replacement is fully healed, with PP.", id: "lunardance", isViable: true, name: "Lunar Dance", pp: 20, priority: 0, isSnatchable: true, boosts: { spa: 1, spe: 1 }, target: "self", type: "Psychic" }, "airslash": { inherit: true, basePower: 90 }, "psyshock": { inherit: true, basePower: 90 }, "icywind": { inherit: true, accuracy: 100, basePower: 90, category: "Physical", defensiveCategory: "Special", desc: "Physical But Deals Special Damage.", shortDesc: "Physical but hits on special defense.", secondary: false }, "moonblast": { num: 1000, accuracy: 90, basePower: 130, category: "Special", desc: "Surronds the user with moonlight energy and releases all of that energy in one blast using up all the energy making the attacks Special Attack go down.", shortDesc: "Deals damage and lowers the attacker's SpA.", id: "moonblast", isViable: true, name: "Moonblast", pp: 5, priority: 0, self: { boosts: { spa: -2 } }, secondary: false, target: "normal", type: "Fairy" }, "fairywind": { num: 1001, accuracy: 100, basePower: 85, category: "Special", desc: "Deals damage to one adjacent target by summoning a mystical wind that has a chance to encloak the user with mystical energy that boosts speed.", shortDesc: "Deals damage and has 10% chance to raise speed.", id: "fairywind", isViable: true, name: "Fairy Wind", pp: 15, priority: 0, secondary: { chance: 10, self: { boosts: { spd: 1 } } }, target: "normal", type: "Fairy" }, "mysticcrash": { num: 1002, accuracy: 100, basePower: 120, category: "Physical", desc: "Deals damage to one adjacent target by crashing into the target with a cloak of mystical energy.", shortDesc: "Deals damage and has recoil Basically Double Edge for faries.", id: "mysticcrash", isViable: true, name: "Mystic Crash", pp: 15, priority: 0, isContact: true, recoil: [22,100], secondary: false, target: "normal", type: "Fairy" } };
import sum from './index'; test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
function Player(options){ var options = options || {}; this.position = options.position || { i:-1, j:0 }; this.name = options.name || 'Mario'; this.img = options.img || 'mario.png'; this.dir = 's'; };
/* TODO: This is the primary part of this game. - It setups the game with initial options and create setup data. - It receives and run user's operation. - It keeps sending game data to renderer, server and clients. - It monitors game process and decides the next status of the game. */ var CharacterManager = require('./CharacterManager.js'); var PhaseManager = require('./PhaseManager.js'); var Player = require('./Player.js'); var Core = function(opts) { "use strick"; // property ----------------------------------------------- var that = this, start = false, _players = null; var _msg; var _send; var phaseManager = null; var characterManager = null; var _onEnd = null; // message ----------------------------------------------- this.send = null; /* TODO: this.send(code, content): This function should be set by Host-Manager, it is used to send message out */ this.handler = { nextPhase: function() { phaseManager.nextPhase(0); }, setAlive: function(playerIdx, isAlive) { characterManager.list[playerIdx].setAlive(isAlive); }, setStatus: function(role, status) { }, win: function(isVillager) { win(isVillager); } }; /* TODO: this is a package of hander for Render.Main */ this.receive = function(msg) { /* TODO: receive unordinary message. you can use this port to handle customized message format */ }; this.action = function(clientId, dat) { /* TODO: will be fired when a client takes a move. analysis the action data and handle this change. */ console.log(clientId, dat); if (dat == null || _players[clientId] == null) return; _players[clientId].receiveAction(dat); }; // callback ------------------------------------------ this.onUpdated = null; // (gameData): becalled when game updates this.onSetuped = null; // (setupData): be called when game setups this.clientSetup = null; // (target, clientData) setup client, be called when game setups this.clientUpdate = null; // (target, clientData) update client side, be called when anything related to that client updates // update --------------------------------------------- this.reset = function(setupData, gameData) { /* TODO: reset game with given data. the game will be recovered if gameData provided */ if (setupData != null) { const playerSetupData = setupData[0]; const characterCode = setupData[1]; phaseManager = _createPhase(); characterManager = new CharacterManager(); _players = _createPlayer(playerSetupData); characterManager.setup(_players, characterCode, phaseManager); phaseManager.setup(characterManager.list); } if (gameData != null) { var phaseData = gameData[0]; var characterData = gameData[1]; phaseManager.reset(phaseData); characterManager.reset(characterData); } }; this.setup = function(playerData, para) { /* TODO: setup the game with player data and initial options. then send the setup data out */ console.log("playerdata"); console.log(playerData); console.log("para"); console.log(para); var characterCode = _shuffle(para.characterList); var clientNumber = para.clientNumber; var playerSetupData = []; for (var i = 0, count = playerData.length; i < count; i++) { if (playerData[i] == null) continue; const id = playerData[i].id; const number = clientNumber[id]; const name = playerData[i].name; const idx = i; playerSetupData.push([id, number, name, idx]); } phaseManager = _createPhase(); characterManager = new CharacterManager(); _players = _createPlayer(playerSetupData); characterManager.setup(_players, characterCode, phaseManager); phaseManager.setup(characterManager.list); that.onSetuped([playerSetupData, characterCode]); for (var i = 0; i < characterManager.list.length; i++) { const c = characterManager.list[i]; that.clientSetup([playerSetupData[i][0]], [ playerSetupData[i][3], c.getMetadata().Code, playerSetupData ]); } this.onUpdated([ phaseManager.getGameData(), characterManager.getGameData(), ]); }; var _createPlayer = function(playerSetupData) { let playerMap = {}; for (var i = 0, count = playerSetupData.length; i < count; i++) { const id = playerSetupData[i][0]; const number = playerSetupData[i][1]; const name = playerSetupData[i][2]; const idx = playerSetupData[i][3]; var p = new Player(id, number, name, idx); p.onUpdate = this.clientUpdate.bind(this); playerMap[id] = p; } return playerMap; }.bind(this); var _createPhase = function() { const phaseManager = new PhaseManager(); phaseManager.onPhaseEnd = function() { this.onUpdated([ phaseManager.getGameData(), characterManager.getGameData(), ]); }.bind(this); return phaseManager; }.bind(this); var _shuffle = function(input) { var output = []; var copy = input.slice(); for (var i = input.length; i > 0; i--) { var k = ~~(Math.random() * i); output.push(copy[k]); copy[k] = copy[i - 1]; } return output; }.bind(this); var win = function(isVillager) { that.onUpdated([ phaseManager.getGameData(), characterManager.getGameData(), isVillager ? 1 : 0, ]); _onEnd && _onEnd(); start = false; }; // game ------------------------------------------------ this.start = function() { /* TODO: game start */ start = true; }; this.end = function() { /* TODO: game end */ start = false; }; this.renew = function() { /* TODO: game renew */ start = false; _players = null; }; this.pause = function() { /* TODO: game parse */ }; this.continue = function() { /* TODO: game continue */ }; var _init = function(opts) { _onEnd = opts && opts.onEnd; }(opts); }; module.exports = Core;
let config = require("../config"); let chalk = require("chalk"); let mongoose = require("mongoose"); let autoIncrement = require("mongoose-auto-increment"); module.exports = function () { let db; // logger.info(); mongoose.Promise = global.Promise; db = mongoose.createConnection(config.db.uri, config.db.options, function mongoAfterConnect(err) { if (err) { } }); return db; };
import {StyleSheet} from 'react-native'; export default StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', paddingTop: 10 }, drawerAndroid: { backgroundColor: '#fff', paddingBottom: 260 }, title: { flexDirection: 'row', paddingLeft: 10, paddingRight: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' }, image: { width: 30, height: 40 }, archive:{ flex: 1, marginLeft: 20 , flexDirection:'row', alignItems:'center' }, archiveText:{ fontSize: 18, color: 'black' }, iconPlus: { flex: 1, alignItems: 'center', justifyContent: 'center', marginRight: 7, width: 30 }, searchContainer:{ flexDirection: 'row', backgroundColor: '#ccc', height: 24, borderRadius: 12, marginLeft: 10, marginRight: 10, marginTop: 6 }, searchView: { flexDirection: 'row', flex: 3, alignItems: 'center', justifyContent: 'center' }, searchTextInput:{ flex: 10, padding: 0, paddingLeft: 10, color: 'black' }, swipeListViewContainer: { paddingTop: 10, flex: 1 }, loadMoreText: { fontSize:16, color: '#2A83F2', fontFamily: 'sans-serif-condensed' }, loadMoreContainer: { justifyContent: 'center', alignItems: 'center' , height: 46 }, noMoreMessage: { color: '#F05D5D', fontSize:16 , fontFamily: 'sans-serif-condensed' }, rowBack: { alignItems: 'center', backgroundColor: '#DDD', flex: 1, flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 15, }, backRightBtn: { alignItems: 'center', bottom: 0, justifyContent: 'center', position: 'absolute', top: 0, width: 75 }, backRightBtnRight: { backgroundColor: '#F5F5F5', right: 0 }, backRightBtnLeft: { backgroundColor: '#F5F5F5', right: 75 }, backRightBtnRightDelete: { color: '#EE3B3B', marginTop: 5, fontSize: 12 }, backRightBtnRightMark: { marginTop: 5, fontSize: 12, color: '#33373D' } });
$(document).ready(function () { $('form').bootstrapValidator({}); });
var Backbone = require('backbone'); module.exports = Backbone.View.extend({ initialize(o) { this.opts = o || {}; this.config = o.config || {}; this.listenTo( this.collection, 'add', this.addTo ); this.listenTo( this.collection, 'reset', this.render ); }, /** * Add to collection * @param {Object} Model * * @return void * @private * */ addTo(model) { var i = this.collection.indexOf(model); this.addToCollection(model, null, i); var em = this.config.em; if(em) { // OLD em.trigger('add:component', model); em.trigger('component:add', model); } }, /** * Add new object to collection * @param {Object} Model * @param {Object} Fragment collection * @param {Integer} Index of append * * @return {Object} Object rendered * @private * */ addToCollection(model, fragmentEl, index) { if(!this.compView) this.compView = require('./ComponentView'); var fragment = fragmentEl || null, viewObject = this.compView; //console.log('Add to collection', model, 'Index',i); var dt = this.opts.componentTypes; var type = model.get('type'); for (var it = 0; it < dt.length; it++) { var dtId = dt[it].id; if(dtId == type) { viewObject = dt[it].view; break; } } //viewObject = dt[type] ? dt[type].view : dt.default.view; var view = new viewObject({ model, config: this.config, componentTypes: dt, }); var rendered = view.render().el; if(view.model.get('type') == 'textnode') rendered = document.createTextNode(view.model.get('content')); if(fragment){ fragment.appendChild(rendered); }else{ var p = this.$parent; var pc = p.children; if(typeof index != 'undefined'){ var method = 'before'; // If the added model is the last of collection // need to change the logic of append if(pc && p.children().length == index){ index--; method = 'after'; } // In case the added is new in the collection index will be -1 if(index < 0) { p.append(rendered); }else { if(pc) { p.children().eq(index)[method](rendered); } } }else{ p.append(rendered); } } return rendered; }, render($p) { var fragment = document.createDocumentFragment(); this.$parent = $p || this.$el; this.$el.empty(); this.collection.each(function(model){ this.addToCollection(model, fragment); },this); this.$el.append(fragment); return this; } });
"use strict"; var Q = require('q'); var HTTPError = require('nor-errors').HTTPError; var debug = require('nor-debug'); var is = require('nor-is'); var _cookies = require('./cookies.js'); var FUNCTION = require('nor-function'); /** Parse arguments */ function do_args(url, opts) { // url if(is.string(url)) { url = require('url').parse(url, true); } debug.assert(url).is('object'); // opts opts = opts || {}; debug.assert(opts).is('object'); opts.url = url; opts.body = opts.body ? opts.body : undefined; //debug.log('opts.body = ' , opts.body); debug.assert(opts.body).ignore(undefined).is('string'); url.method = opts.method || 'GET'; url.headers = opts.headers || {}; if(opts.body && (url.method === 'POST')) { url.headers['Content-Type'] = url.headers['Content-Type'] || 'text/plain;charset=utf8'; url.headers['Content-Length'] = new Buffer(opts.body, 'utf8').length; } url.agent = opts.agent; if(is.object(opts.params)) { url.path += '?' + require('querystring').stringify(opts.params); } opts.protocol = (''+url.protocol).split(':').shift() || 'http'; var cookies = _cookies.get(url); if(cookies && (cookies.length >= 1)) { url.headers.cookie = cookies.join(';'); } return opts; } /** Performs generic request */ function do_plain(url, opts) { opts = do_args(url, opts); if(opts.redirect_loop_counter === undefined) { opts.redirect_loop_counter = 10; } var buffer; var d = Q.defer(); var req = require(opts.protocol).request(opts.url, function(res) { var buffer = ""; res.setEncoding('utf8'); function collect_chunks(chunk) { buffer += chunk; } res.on('data', collect_chunks); res.once('end', function() { res.removeListener('data', collect_chunks); var content_type = res.headers['content-type'] || undefined; //debug.log('content_type = ' , content_type); d.resolve( Q.fcall(function() { //debug.log('buffer = ', buffer); //debug.log('res.headers = ', res.headers); if(res.headers && res.headers['set-cookie']) { _cookies.set(opts.url, res.headers['set-cookie']); } if( (res.statusCode >= 301) && (res.statusCode <= 303) ) { if(opts.redirect_loop_counter < 0) { throw new Error('Redirect loop detected'); } opts.redirect_loop_counter -= 1; //debug.log('res.statusCode = ', res.statusCode); //debug.log('res.headers.location = ', res.headers.location); return do_plain(res.headers.location, { 'method': 'GET', 'headers': { 'accept': opts.url.headers && opts.url.headers.accept } }); } if(!((res.statusCode >= 200) && (res.statusCode < 400))) { throw new HTTPError(res.statusCode, ((content_type === 'application/json') ? JSON.parse(buffer) : buffer) ); } return buffer; }) ); }); }).once('error', function(e) { d.reject(new TypeError(''+e)); }); if(opts.body && (url.method !== 'GET')) { buffer = is.string(opts.body) ? opts.body : JSON.stringify(opts.body); //debug.log('Writing buffer = ', buffer); req.end( buffer, 'utf8' ); } else { req.end(); } return d.promise; } /** JSON request */ function do_json(url, opts) { opts = opts || {}; if(is.object(opts) && is.defined(opts.body)) { opts.body = JSON.stringify(opts.body); } opts.headers = opts.headers || {}; if(opts.body) { opts.headers['Content-Type'] = 'application/json;charset=utf8'; } opts.headers.Accept = 'application/json'; return do_plain(url, opts).then(function(buffer) { return JSON.parse(buffer); }); } /** JavaScript function request */ function do_js(url, opts) { opts = opts || {}; if(is.object(opts) && is['function'](opts.body)) { opts.body = FUNCTION(opts.body).stringify(); } else if(is.object(opts) && is.string(opts.body)) { } else { throw new TypeError('opts.body is not function nor string'); } opts.headers = opts.headers || {}; if(opts.body) { opts.headers['Content-Type'] = 'application/javascript;charset=utf8'; } // Default method should be POST since JavaScript code usually might change something. if(!opts.method) { opts.method = 'post'; } opts.headers.Accept = 'application/json'; return do_plain(url, opts).then(function(buffer) { return JSON.parse(buffer); }); } /** Generic HTTP/HTTPS request */ var mod = module.exports = {}; mod.plain = do_plain; mod.json = do_json; mod.js = do_js; /* EOF */
var _ = require('lodash'); var async = require('async'); var path = require('path'); var Registry = function() { this.order = []; }; Registry.prototype = { add: function(label, fn) { this.order.push({ name: label, fn: fn }); }, before: function(beforeLabel, label, fn) { var beforeIndex = _.findIndex(this.order, function(o) { return o.name == beforeLabel; }); if (beforeIndex === -1) { return console.log( 'Cannot register', label, '.', beforeLabel, 'not found' ); } this.order.splice(beforeIndex, 0, { name: label, fn: fn }); }, after: function(afterLabel, label, fn) { var afterIndex = _.findIndex(this.order, function(o) { return o.name == afterLabel; }); if (afterIndex === -1) { return console.log( 'Cannot register', label, '.', afterLabel, 'not found' ); } this.order.splice(afterIndex + 1, 0, { name: label, fn: fn }); } }; var Executer = function(verbose) { this.plugins = {}; this.verbose = verbose; }; Executer.prototype = { execute: function(plugins, disablePlugins, args, cb) { // require all plugins. Plugin functions are cached // across builds. this.requirePlugins(plugins); // create new registry object that each plugin calls // to register itself. var registry = new Registry(); // loop through and instantiate each plugin, passing in // the registry object. _.each( plugins, _.bind(function(plugin) { if (this.plugins[plugin]) { new this.plugins[plugin](registry); } }, this) ); // remove disabled plugins by removing all labels that start // with the plugin name. var enabled = _.filter(registry.order, function(o) { return _.indexOf(disablePlugins, o.name.split(':')[0]) == -1; }); // log the order of all plugins. if (this.verbose) { console.log('Plugin order:'); _.each(enabled, function(o, i) { console.log(i + 1 + '. ' + o.name); }); } // create an async waterfall chain from the registry order. var chain = _.map(enabled, function(o) { return o.fn; }); // add a function to kick off the chain, passing the args chain.unshift(function(callback) { args.unshift(null); callback.apply(this, args); }); // run the all functions, one after the other. async.waterfall(chain, function(err, config, stream, extras) { cb(config, stream, extras); }); }, // File loading // ------------------------------------------------ requirePlugins: function(plugins) { _.each( plugins, _.bind(function(plugin) { if (!this.plugins[plugin]) { this.plugins[plugin] = this.requirePlugin(plugin); } }, this) ); }, requirePlugin: function(file) { var loadedFile; // try to load the file as a local file try { loadedFile = require(path.join(__dirname, 'plugins', file)); } catch (e1) { if (e1 instanceof SyntaxError) { console.log( 'Plugin file: ' + file + ' has syntax errors. ' + e1.toString() ); } else { // try to load the file as a file in the book try { loadedFile = require(path.join(process.cwd(), file)); } catch (e2) { if (e2 instanceof SyntaxError) { console.log( 'Plugin file: ' + file + ' has syntax errors. ' + e2.toString() ); } else { // try to load the file as a node module installed in book folder try { loadedFile = require(path.join( process.cwd(), 'node_modules', file )); } catch (e3) { console.log(e3); if (e3 instanceof SyntaxError) { console.log( 'Plugin file: ' + file + ' has syntax errors. ' + e3.toString() ); } else { console.log('Required file: ' + file + ' cannot be found'); } } } } } } return loadedFile; } }; module.exports = Executer;
///<reference path="../typings/node/node.d.ts"/> ///<reference path="../typings/express/express.d.ts"/> ///<reference path="../typings/body-parser/body-parser.d.ts"/> ///<reference path="../typings/firebase/firebase.d.ts"/> "use strict"; var secrets_1 = require('./config/secrets'); var express = require('express'); var bodyParser = require('body-parser'); var Firebase = require('firebase'); var FbService = require('./firebase.service'); var server = express(); var DB; server.use(bodyParser.urlencoded({ extended: false })); var twilio = require('twilio'); var fbInit = function () { var _a = secrets_1["default"].firebase, url = _a.url, key = _a.key; DB = new Firebase(url); DB.authWithCustomToken(key, function (error, authData) { error ? console.log('Firebase FAILED to connect') : FbService.init(DB, authData); }); }; fbInit(); var keys; (function (keys) { keys[keys['up'] = 2] = 'up'; keys[keys['left'] = 4] = 'left'; keys[keys['right'] = 6] = 'right'; keys[keys['down'] = 8] = 'down'; })(keys || (keys = {})); server.get('/', function (req, res) { res.send('App running on port 3000!'); }); server.post('/keyPress', function (req, res) { console.log('req.body ', req.body.Digits); var key = req.body.Digits; if (keys[key]) { console.log("IS KEY:", keys[key]); FbService.moveCirlce(keys[key]); } else { console.log("NOT KEY"); } var twiml = new twilio.TwimlResponse(); twiml.gather({ numDigits: '1', action: '/keyPress', method: 'POST', timeout: '1000' }); res.send(twiml.toString()); }); server.post('/voice', function (req, res) { console.log('req.body ', req.body); var twiml = new twilio.TwimlResponse(); twiml.gather({ numDigits: '1', action: '/keyPress', method: 'POST', timeout: '1000' }); res.send(twiml.toString()); }); server.listen(3000, function () { return console.log('Server on port 3000'); }); //# sourceMappingURL=index.js.map
'use strict'; import '../../assets/webgl-debug'; import WebGLUtils from '../../assets/webgl-utils'; let canvas = document.querySelector('canvas'); let gl = WebGLUtils.setupWebGL(canvas); let theta = 0.0; const VERTICES_1 = [ 0.0, 0.5, 0.5, 0.0, -0.5, 0.0, 0.0, -0.5 ]; const TRANSLATION_1 = -.3; const TRANSLATION_2 = .3; // specifies the affine transformation of x and // y from normalized device coordinates to // window coordinates. gl.viewport(0, 0, canvas.width, canvas.height); // specifying the clear color for a drawing area gl.clearColor(.0, .0, .0, 1.); if (!WebGLUtils.Shaders.initFromElems(gl, document.getElementById('vshader'), document.getElementById('fshader'))) { throw new Error('Failed to initialize shaders'); } let bufferId = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, bufferId); let a_Position = gl.getAttribLocation(gl.program, 'a_Position'); gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(a_Position); let a_Translation = gl.getAttribLocation(gl.program, 'a_Translation'); if (!~a_Translation) throw new Error('Couldn\'t retrieve a_Translation attrib.'); let u_theta = gl.getUniformLocation(gl.program, 'u_theta'); if (!~u_theta) throw new Error('Couldn\'t retrieve a_Translation attrib.'); function render () { // non-specific preparation gl.clear(gl.COLOR_BUFFER_BIT); theta += 0.1; gl.uniform1f(u_theta, theta); // first rectangle gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(VERTICES_1), gl.STATIC_DRAW); gl.vertexAttrib1f(a_Translation, TRANSLATION_1); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); // second rectangle gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(VERTICES_1), gl.STATIC_DRAW); gl.vertexAttrib1f(a_Translation, TRANSLATION_2); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } (function loop () { window.requestAnimationFrame(loop); render(); })();
import React from 'react'; export default (props) => { const itemHtml = props.items.map((item, index) => { return <li key={index}>{item}</li> }); return ( <div> <ul>{itemHtml}</ul> <button onClick={props.onClick}>New Item</button> </div> ) }
/* globals $*/ (function () { let sessionStorageAuthtoken = sessionStorage.getItem('authtoken'); if (sessionStorageAuthtoken === null) { $('#buttonLogin').removeClass('hidden'); $('#buttonRegister').removeClass('hidden'); } else { $('#buttonLogin').addClass('hidden'); $('#buttonRegister').addClass('hidden'); $('#buttonLogout').removeClass('hidden'); $('#buttonCreateNewAd').removeClass('hidden'); $('#buttonMyAd').removeClass('hidden'); $('#buttonUserProfile').removeClass('hidden'); } })();
var $ = require('jquery'); var tpl = require('child.njk'); $(function(){ $('body') .html( tpl.render({ message: 'Hello!'}) ) ; });
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ const minDiffInBST = function (root) { let status = { minDiff: Number.POSITIVE_INFINITY, lastValue: Number.NEGATIVE_INFINITY }; traverse(root, status); return status.minDiff; }; function traverse(node, status) { if (!node) { return; } traverse(node.left, status); let diff = node.val - status.lastValue; if (diff < status.minDiff) { status.minDiff = diff; } status.lastValue = node.val; traverse(node.right, status); } module.exports = minDiffInBST;
function(doc) { if (doc.class == 'job' && doc.state == 'error') { emit(doc.errored_at, doc); } }
import React, {useState, useEffect} from 'react' import {Text, Container, Flex, Spinner, Stack} from '@sanity/ui' import {versionedClient} from './versionedClient' const checkCors = () => Promise.all([ versionedClient.request({uri: '/ping', withCredentials: false}).then(() => true), versionedClient .request({uri: '/users/me', withCredentials: false}) .then(() => true) .catch(() => false), ]) .then((res) => ({ isCorsError: res[0] && !res[1], pingResponded: res[0], })) .catch((error) => ({error})) function CorsWrapper({result, children}) { const response = result && result.error && result.error.response const message = response && response.body && response.body.message if (!message) { return <>{children}</> } return ( <div> <Text>Error message:</Text> <pre> <code>{response.body.message}</code> </pre> {children} </div> ) } export default function CorsCheck() { const [state, setState] = useState({isLoading: true}) useEffect(() => { checkCors().then((res) => setState({ result: res, isLoading: false, }) ) }, []) const {isLoading, result} = state const origin = window.location.origin || window.location.href.replace(new RegExp(`${window.location.pathname}$`), '') if (isLoading) { return ( <Container width={4} padding={4} height="fill"> <Flex align="center" justify="center" height="fill"> <Text> <Spinner /> </Text> </Flex> </Container> ) } const tld = versionedClient.config().apiHost.replace(/.*?sanity\.([a-z]+).*/, '$1') const projectId = versionedClient.config().projectId const corsUrl = `https://manage.sanity.${tld}/projects/${projectId}/settings/api` const response = result.error && result.error.response if (response) { const is404 = response.statusCode === 404 const errType = response.body.attributes && response.body.attributes.type if (is404 && errType === 'project') { return ( <Stack space={4}> <Text accent>{response.body.message || response.statusCode}</Text> <Text accent> Double-check that your <code>sanity.json</code> points to the right project ID! </Text> </Stack> ) } } if (result.isCorsError) { return ( <CorsWrapper result={state.result}> <Text accent> It looks like the error is being caused by the current origin (<code>{origin}</code>) not being allowed for this project. If you are a project administrator or developer, you can head to{' '} <a rel="noopener noreferrer" target="_blank" href={corsUrl}> the project management </a>{' '} interface. Add the origin under the{' '} <a href="https://www.sanity.io/docs/front-ends/cors" target="_blank" rel="noopener noreferrer" > <em>CORS Origins</em> </a>{' '} section. Do remember to <code>allow credentials</code>! </Text> </CorsWrapper> ) } if (result.pingResponded) { return ( <CorsWrapper result={state.result}> <Text accent> Our diagnostics cannot quite determine why this happened. If it was a network glitch you could try hitting the <strong>Retry</strong> button below. If you are working as a developer on this project, you could also have a look at the browser's dev console and see if any issues are listed there. </Text> </CorsWrapper> ) } return ( <CorsWrapper result={state.result}> <Text accent> It might be that your internet connection is unstable or down. You could try hitting the{' '} <strong>Retry</strong> button to see if it was just a temporary glitch. </Text> </CorsWrapper> ) }
'use strict'; //Setting up route angular.module('phi.projects') .config(['crudRouteProvider', 'securityAuthorizationProvider', function (crudRouteProvider, securityAuthorizationProvider) { crudRouteProvider.routesFor('Projects') .whenList({ projects: ['Projects', function(Projects) { return Projects.all(); }] }) .whenNew({ currentUser: securityAuthorizationProvider.requireAuthenticatedUser, project: ['Projects', function(Projects) { return new Projects(); }] }) .whenEdit({ currentUser: securityAuthorizationProvider.requireAuthenticatedUser, project: ['$route', 'Projects', function($route, Projects) { return Projects.getById($route.current.params.itemId); }] }) .whenShow({ currentUser: securityAuthorizationProvider.requireAuthenticatedUser, project: ['$route', 'Projects', function($route, Projects) { return Projects.getById($route.current.params.itemId); }] }); } ]);
/** * <%= ComponentName %> Component Style for tingle * @author <%- props.authorName %> * * Copyright 2014-2015, Tingle Team, Alinw. * All rights reserved. */ import <%= ComponentName %> from './<%= ComponentName %>'; module.exports = <%= ComponentName %>;
var args = require('yargs'); const dest = './dist'; const src = './src'; const port = 3000; const shouldWatch = args.watch; module.exports = { watch: shouldWatch, src: src, dest: dest, webpack: { entry: { bundle: src + '/bundles/bundle.js' }, output: { filename: '[name].js', path: dest + '/bundles' } }, browserSync: { server: { baseDir: dest, port: port }//, //files: [dest + '/dist/**'] }, sass: { settings: { sourceComments: 'map', imagePath: '/img' // Used by the image-url helper } }, appx: { src: src + '/AppxManifest.xml' }, ngrok: { port: port }, production: { cssSrc: dest + '/**/*.css', jsSrc: dest + '/**/*.js', dest: dest }, clean: { src: dest }, deploy: { src: dest + '/**/*' } };
import hbs from 'htmlbars-inline-precompile'; import {describe, it} from 'mocha'; import {expect} from 'chai'; import {setupComponentTest} from 'ember-mocha'; describe('Integration: Component: koenig-toolbar', function () { setupComponentTest('koenig-toolbar', { integration: true }); it('renders', function () { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); // Template block usage: // this.render(hbs` // {{#koenig-toolbar}} // template content // {{/koenig-toolbar}} // `); this.render(hbs`{{koenig-toolbar}}`); expect(this.$()).to.have.length(1); }); });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Event = mongoose.model('Event'), Testrun = mongoose.model('Testrun'), testruns = require('./testruns.server.controller'), _ = require('lodash'); /** * Create a Event */ exports.create = function(req, res) { var event = new Event(req.body); event.user = req.user; event.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(event); /* if "end" event, check if corresponding "start" event exist and add to test runs */ if (event.eventDescription === "end"){ Event.findOne({$and:[{testRunId: event.testRunId}, {eventDescription: "start"}]}).exec(function(err, startEvent) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { var testRun = new Testrun(); testRun.start = startEvent.eventTimestamp; testRun.end = event.eventTimestamp; testRun.productName = event.productName; testRun.dashboardName = event.dashboardName; testRun.testRunId = event.testRunId; testRun.baseline = event.baseline; testRun.buildResultKey = event.buildResultKey testRun.eventIds.push(startEvent._id, event._id); testruns.persistTestRunById(testRun.productName, testRun.dashboardName, testRun, function(storedTestrun){ console.log("test run stored"); }) } }); } } }); }; /** * Show the current Event */ exports.read = function(req, res) { res.jsonp(req.event); }; /** * Update a Event */ exports.update = function(req, res) { var event = req.event ; event = _.extend(event , req.body); event.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(event); } }); }; /** * Delete an Event */ exports.delete = function(req, res) { var event = req.event ; event.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(event); } }); }; /** * List of Events */ exports.list = function(req, res) { Event.find().sort('-created').populate('user', 'displayName').exec(function(err, events) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(events); } }); }; /* * List events for dashboard */ exports.eventsForDashboard = function(req, res) { Event.find( { $and: [ { productName: req.params.productName }, { dashboardName: req.params.dashboardName } ] } ).sort('-eventTimestamp').exec(function(err, events) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(events); } }); }; /* * List events for testrun */ exports.eventsForTestRun = function(req, res) { Event.find( { $and: [ { productName: req.params.productName }, { dashboardName: req.params.dashboardName } ], eventTimestamp: {$lte: req.params.until, $gte: req.params.from} } ).sort('-eventTimestamp').exec(function(err, events) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(events); } }); }; /* * Event middleware */ exports.eventByID = function(req, res, next, id) { Event.findById(id).populate('user', 'displayName').exec(function(err, event) { if (err) return next(err); if (! event) return next(new Error('Failed to load Event ' + id)); req.event = event ; next(); }); }; /** * Event authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.event.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
"use strict"; var photoSingle = angular.module('tabs', ['ionic', 'ngCordova', '500px.service', 'uiGmapgoogle-maps']) photoSingle.controller('TabsController', ['$rootScope', '$scope', '$stateParams', '$ionicPlatform', function($rootScope, $scope, $stateParams, $ionicPlatform) { $scope.onTabSelected = function(index) { console.log("Navigate to tab: " + index); $rootScope.$broadcast('tabChanged', index); } }]);
/** * @hidden */ export function extE3(a0, a1, a2, a3, a4, a5, a6, a7, b0, b1, b2, b3, b4, b5, b6, b7, index) { a0 = +a0; a1 = +a1; a2 = +a2; a3 = +a3; a4 = +a4; a5 = +a5; a6 = +a6; a7 = +a7; b0 = +b0; b1 = +b1; b2 = +b2; b3 = +b3; b4 = +b4; b5 = +b5; b6 = +b6; b7 = +b7; index = index | 0; var x = 0.0; switch (~(~index)) { case 0: { x = +(a0 * b0); } break; case 1: { x = +(a0 * b1 + a1 * b0); } break; case 2: { x = +(a0 * b2 + a2 * b0); } break; case 3: { x = +(a0 * b3 + a3 * b0); } break; case 4: { x = +(a0 * b4 + a1 * b2 - a2 * b1 + a4 * b0); } break; case 5: { x = +(a0 * b5 + a2 * b3 - a3 * b2 + a5 * b0); } break; case 6: { x = +(a0 * b6 - a1 * b3 + a3 * b1 + a6 * b0); } break; case 7: { x = +(a0 * b7 + a1 * b5 + a2 * b6 + a3 * b4 + a4 * b3 + a5 * b1 + a6 * b2 + a7 * b0); } break; default: { throw new Error("index must be in the range [0..7]"); } } return +x; }
{ "allowCache": true, "mediaSequence": 0, "playlistType": "VOD", "segments": [ { "duration": 6.64, "timeline": 0, "uri": "/test/ts-files/tvy7/8a5e2822668b5370f4eb1438b2564fb7ab12ffe1-hi720.ts" }, { "duration": 8, "timeline": 0, "uri": "/test/ts-files/tvy7/56be1cef869a1c0cc8e38864ad1add17d187f051-hi720.ts" }, { "duration": 8, "timeline": 0, "uri": "/test/ts-files/tvy7/549c8c77f55f049741a06596e5c1e01dacaa46d0-hi720.ts" }, { "duration": 8, "timeline": 0, "uri": "/test/ts-files/tvy7/6cfa378684ffeb1c455a64dae6c103290a1f53d4-hi720.ts" } ], "targetDuration": 8, "endList": true, "discontinuitySequence": 0, "discontinuityStarts": [] }
/** * TeamController * * @description :: Server-side logic for managing Teams * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { };
// // Provide a single module that requires parts of the openlayers library so we can get a google closure // optimised compile // goog.provide("prais2.ol3"); goog.require("ol.Map"); goog.require("ol.layer.Tile"); goog.require('ol.layer.Vector'); goog.require("ol.View"); goog.require("ol.proj"); goog.require('ol.source.OSM'); goog.require('ol.source.Vector'); goog.require("ol.style.Style"); goog.require("ol.style.Icon"); goog.require("ol.Feature"); goog.require("ol.Overlay"); goog.require("ol.geom.Point"); goog.require("ol.animation");
import React from 'react' import { NavLink, Link } from 'react-router-dom' import './App.css' import pkg from '../../../package.json' /* The .active class is being applied to '/' even when it isn't the current location.pathname because all other paths are its children. This method corrects for that. */ const onlyOneActiveMatch = (match, location) => { if (match) return location.pathname === match.path } const App = props => ( <div className='App'> <nav> <Link to='/'> <h2 className='navbar-brand'>{pkg.name}</h2> </Link> <ul className='navbar'> <li className='navbar-item'> <NavLink to='/about' isActive={onlyOneActiveMatch}>About</NavLink> </li> <li className='navbar-item'> <NavLink to='/' isActive={onlyOneActiveMatch}>Home</NavLink> </li> </ul> </nav> { props.children && React.cloneElement(props.children, props) } </div> ) export default App
(function () { "use strict"; var logname = 'child1'; var ChildControl = WinJS.UI.Pages.define("/demos/corefeatures/webcomponents/childcomponent/childcontrol1.html", { init: function () { console.log(logname + ' init'); }, rendered: function (element, options) { console.log(logname + ' rendered'); }, processed: function (element, options) { console.log(logname + ' processed'); }, pageLayout: function (element, options) { console.log(logname + ' layout'); }, ready: function (element, options) { console.log(logname + ' ready'); }, dispose: function () { console.log(logname + ' dispose'); } }); WinJSContrib.UI.WebComponents.register('app-test-child1', ChildControl, {}); })();
// access process.stdout once in worker console.log(process.stdout); close();
import { describe, it } from 'mocha'; import { expect } from 'chai'; import { particle } from '../js/particle'; import { vector } from '../js/vector'; describe('Particle Library', () => { describe('Can create create vectors', () => { const p1 = particle.create(1, 2, 30, Math.PI / 6, 20); it('sets the X value', () => { expect(p1.position.getX()).to.equal(1); }); it('sets the Y value', () => { expect(p1.position.getY()).to.equal(2); }); it('sets the angle', () => { const low30 = 29.5 * (Math.PI / 180); const high30 = 30.5 * (Math.PI / 180); expect(p1.velocity.getAngle()).to.be.within(low30, high30); }); it('sets the length (speed)', () => { expect(p1.velocity.getLength()).to.equal(30); }); it('sets the gravity', () => { expect(p1.gravity.getY()).to.equal(20); }); }); describe('Particle mutations', () => { it('increases the velocity by a specified amount', () => { const p1 = particle.create(4, 4, 30, Math.PI / 6, 20); const v2 = vector.create(10, 5); const initialX = p1.velocity.getX(); const initialY = p1.velocity.getY(); // mutate p1 p1.accelerate(v2); expect(initialX + 10).to.eql(p1.velocity.getX()); expect(initialY + 5).to.eql(p1.velocity.getY()); }); it('gets the angle between two particles', () => { const p1 = particle.create(4, 4, 30, Math.PI / 6, 20); const p2 = particle.create(2, 2, 15, Math.PI / 3, 10); const result = p1.angleTo(p2); const y = p2.position.getY() - p1.position.getY(); const x = p2.position.getX() - p1.position.getX(); const expected = Math.atan2(y, x); expect(result).to.equal(expected); }); it('gets the distance between two particles', () => { const p1 = particle.create(4, 4, 30, Math.PI / 6, 20); const p2 = particle.create(2, 2, 15, Math.PI / 3, 10); const result = p1.distanceTo(p2); const y = p2.position.getY() - p1.position.getY(); const x = p2.position.getX() - p1.position.getX(); const expected = Math.sqrt((x * x) + (y * y)); expect(result).to.equal(expected); }); it('updates the velocity and position with gravity', () => { const p1 = particle.create(4, 4, 30, Math.PI / 6, 20); const initialXVel = p1.velocity.getX(); const initialYVel = p1.velocity.getY(); const initialXPos = p1.position.getX(); const initialYPos = p1.position.getY(); const gravX = p1.gravity.getX(); const gravY = p1.gravity.getY(); // mutate p1 p1.update(); const resultXVel = p1.velocity.getX(); const resultYVel = p1.velocity.getY(); const resultXPos = p1.position.getX(); const resultYPos = p1.position.getY(); expect(initialXVel + gravX).to.equal(resultXVel); expect(initialYVel + gravY).to.equal(resultYVel); expect(initialXPos + initialXVel + gravX).to.equal(resultXPos); expect(initialYPos + initialYVel + gravY).to.equal(resultYPos); }); it('creates and applies gravity to this particle', () => { const earth = particle.create(4, 4, 10, Math.PI / 6); const sun = particle.create(10, 10, 515, Math.PI / 3); const earthinitialXVel = earth.velocity.getX(); sun.mass = 2000; earth.gravitateTo(sun); const earthresultXVel = earth.velocity.getX(); // note, the above and below only works because the initial value // is starting out the earth with no X and all Y. // In a quarter of a circle, this test would fail as X would decrease // and Y would increase...that is to say, this test depends HEAVILY // on the initial start points expect(earthresultXVel).to.be.above(earthinitialXVel); }); }); });
var express = require('express'); bodyParser = require('body-parser'); cookieParser = require('cookie-parser'); methodOverride = require('method-override'); morgan = require('morgan'); compression = require('compression'); path = require('path'), jwt = require('jsonwebtoken'); request = require('request'); module.exports = function(){ var app = express(); if(process.env.NODE_ENV === 'development'){ app.use(morgan('dev')); }else if(process.env.NODE_ENV === 'development'){ app.use(compression); } //json webtoken secret process.env.JWT_SECRET = 'SuperSecretGreenShoeCapital'; process.on('uncaughtException', function(err) { console.log(err); }); //configure express middleware app.use(express.static(path.join(__dirname,'../app/public'))); app.use(bodyParser.urlencoded({ extended:false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(cookieParser()); /* Allow requests to come from diffrent domains in order to develop a client-independent system and prevent triggering Cross Origin Request Sharing error Access-Control-Allow-Origin - allow for all domains X-Requested-with and content-type headers are allowed */ app.use(function(req,res,next){ res.setHeader('Access-Control-Allow-Origin','*'); res.setHeader('Access-Control-Allow-Methods','GET,POST'); res.setHeader('Access-Control-Allow-Headers','X-Requested-with,content-type,Authorization'); next(); }); app.set('views','./app/public/views'); app.set('view engine','ejs'); require('../app/routes/index.js')(app); //require('../app/routes/user.routes.js')(app); return app; }
/*! * DecafMUD v0.9.0 * http://decafmud.stendec.me * * Copyright 2010, Stendec <stendec365@gmail.com> */ /** * @fileOverview DecafMUD TELOPT Handler: GMCP * @author Stendec <stendec365@gmail.com> * @version 0.9.0 */ (function(DecafMUD) { // Shortcut the TELNET constants for ease of use. var t = DecafMUD.TN; /** Handles the TELNET option GMCP. * @name GMCP * @class DecafMUD TELOPT Handler: GMCP * @exports GMCP as DecafMUD.plugins.Telopt.É * @param {DecafMUD} decaf The instance of DecafMUD using this plugin. */ var GMCP = function(decaf) { this.decaf = decaf; this.decaf.gmcp = this; } GMCP.prototype.pingDelay = 60; GMCP.prototype.pingAverage = 0; GMCP.prototype.pingCount = 0; GMCP.prototype.pingWhen = undefined; GMCP.prototype.pingTimer = undefined; /** Helper for sending GMCP messages. */ GMCP.prototype.sendGMCP = function(pckg, data) { var out = ''; if ( data !== undefined ) { out = JSON.stringify([data]); out = ' ' + out.substr(1, out.length-2); } this.decaf.sendIAC(t.IAC + t.SB + t.GMCP + pckg + out + t.IAC + t.SE); } /** Abort the ping information on disconnect. */ GMCP.prototype._wont = GMCP.prototype.disconnect = function() { clearTimeout(this.pingTimer); this.pingAverage = 0; this.pingCount = 0; } /** Send the Core.Hello message upon connecting. */ GMCP.prototype._will = function() { var g = this; setTimeout(function(){ g.sendGMCP("Core.Hello", { "client" : "DecafMUD", "version" : DecafMUD.version.toString() }); }, 0); // Also, start the ping loop. this.pingTimer = setTimeout(function(){g.ping();}, this.pingDelay*1000); } /** Send a ping. */ GMCP.prototype.ping = function() { var avg = undefined; if ( this.pingCount > 0 ) { avg = this.pingAverage; } this.sendGMCP("Core.Ping", avg); this.pingWhen = new Date(); // Schedule a new ping. var g = this; this.pingTimer = setTimeout(function(){g.ping();}, this.pingDelay*1000); } /** Handle an incoming GMCP message. */ GMCP.prototype._sb = function(data) { // Find the end of the package. var ind = data.search(/[^A-Za-z0-9._]/), ret = false, pckg, out; if ( ind !== -1 ) { pckg = data.substr(0, ind); if ( ind + 1 !== data.length ) { out = JSON.parse('['+data.substr(ind+1)+']')[0]; } } else { pckg = data; } // If there's no package, return. if ( pckg.length === 0 ) { return; } // Debug it. if ( out !== undefined && 'console' in window && console.groupCollapsed ) { console.groupCollapsed('DecafMUD['+this.decaf.id+'] RCVD IAC SB GMCP "'+pckg+'" ... IAC SE'); console.dir(out); console.groupEnd('DecafMUD['+this.decaf.id+'] RCVD IAC SB GMCP "'+pckg+'" ... IAC SE'); } else { ret = true; } // Get the function var func = this.getFunction(pckg); // Call it. if ( func ) { func.call(this, out); } return ret; // We print our own debug info. } /** Command to find a given function. */ GMCP.prototype.getFunction = function(pckg) { var parts = pckg.split('.'), top = this.packages; while(parts.length > 0) { var part = parts.shift(); if ( top[part] === undefined ) { return undefined; } top = top[part]; } if (typeof top === 'function') { return top; } return undefined; } /** Helper to add /** The package structure. */ GMCP.prototype.packages = {}; /** PACKAGE: Core */ GMCP.prototype.packages.Core = { ' version' : 1, 'Ping' : function(data) { var n = new Date() - this.pingWhen; this.pingCount++; this.pingAverage = Math.ceil((n + (this.pingAverage * (this.pingCount-1))) / this.pingCount); console.debug('PING: {0}ms over {1} pings'.tr(this.decaf,this.pingAverage,this.pingCount)); }, 'Goodbye' : function(data) { this.decaf.debugString('Reason for disconnect: {0}'.tr(this.decaf,data)); } }; // Expose it to DecafMUD DecafMUD.plugins.Telopt[t.GMCP] = GMCP; //DecafMUD.plugins.Telopt.gmcp = true; })(DecafMUD);
import AdjacencyList from './adjacency_list'; export default function articulations(graph) { if (graph.directed) { throw new Error('This algorithm only supports undirected graphs'); } if (graph.vertexCount === 0) { return []; } const articuls = []; const list = new AdjacencyList(graph); const visited = new Array(list.a.length); const depth = new Array(list.a.length); const lowpoint = new Array(list.a.length); const parent = new Array(list.a.length); let currentDepth = 0; const processVertexEarly = x => { visited[x] = true; depth[x] = currentDepth; lowpoint[x] = currentDepth; currentDepth += 1; }; const processEdge = (x, y) => { if (!visited[y]) { parent[y] = x; dfs(y); if (parent[x] !== undefined && lowpoint[y] >= depth[x]) { articuls.push(x); } lowpoint[x] = Math.min(lowpoint[x], lowpoint[y]); } else if (y !== parent[x] && depth[y] < depth[x]) { lowpoint[x] = Math.min(lowpoint[x], depth[y]); } }; const processVertexLate = (x, children) => { if (parent[x] === undefined && children > 1) { articuls.push(x); } }; const dfs = x => { processVertexEarly(x); let children = 0; for (const y of list.a[x]) { if (!visited[y]) { children += 1; } processEdge(x, y); } processVertexLate(x, children); }; dfs(0); return articuls; }
this.NesDb = this.NesDb || {}; NesDb[ '3E7B1F68A8E758D34252E4F2755D392F987824EA' ] = { "$": { "name": "Captain Planet and the Planeteers", "class": "Licensed", "catalog": "NES-5C-UKV", "publisher": "Mindscape", "developer": "Gray Matter", "region": "United Kingdom", "players": "1", "date": "1992-08-20" }, "cartridge": [ { "$": { "system": "NES-PAL-A", "crc": "8D901FAD", "sha1": "3E7B1F68A8E758D34252E4F2755D392F987824EA", "dump": "ok", "dumper": "Mark_K", "datedumped": "2011-12-05" }, "board": [ { "$": { "type": "NES-TLROM", "pcb": "NES-TLROM-03", "mapper": "4" }, "prg": [ { "$": { "name": "PAL-5C-0 PRG", "size": "128k", "crc": "40A458F0", "sha1": "189CAFA68431C1DE88BDFBCF7099CE223D6A3197" } } ], "chr": [ { "$": { "name": "NES-5C-0 CHR", "size": "128k", "crc": "8D92550D", "sha1": "322063ABC983CB9D2C4D22EED388090DE597F1B5" } } ], "chip": [ { "$": { "type": "MMC3B" } } ], "cic": [ { "$": { "type": "3197A" } } ] } ] } ], "gameGenieCodes": [ { "name": "Start with 2 lives instead of 5, outside levels", "codes": [ [ "PENVIGGA" ] ] }, { "name": "Start with 10 lives, outside levels", "codes": [ [ "PENVIGGE" ] ] }, { "name": "Infinite lives, outside levels", "codes": [ [ "SXNLYVVK" ] ] }, { "name": "Infinite lives, inside levels", "codes": [ [ "SZSUGVVK" ] ] }, { "name": "Start with 10 lives, inside levels", "codes": [ [ "PAETITGE" ] ] }, { "name": "Start with 2 lives, inside levels", "codes": [ [ "PAETITGA" ] ] }, { "name": "Start inside level 1 instead of outside.", "codes": [ [ "AANVAEGZ" ] ] }, { "name": "Infinite power, outside levels", "codes": [ [ "SZNXGXVK", "SZVXPKVK" ] ] }, { "name": "Infinite power, inside levels", "codes": [ [ "SXXXEUVK", "SZEUGKVK" ] ] } ] };
var PardotAPI_v3 = require('./PardotAPI_v3'); var PardotAPI_v4 = require('./PardotAPI_v4'); /** * Returns a Pardot API wrapper object of the specified version. Only version v2 * is currently supported * * Available options are: * - version The API version to use (v2). Defaults to v2. * - json If the API should return XML (default) or JSON. Set to true to return JSON * - userAgent Custom User-Agent description to use in the request header. * - prospectCustomFields: A string array of custom fields * * @param apiKey The API key to access the Pardot API with * @param accessToken The oAuth accesstoken if already completed for the user, or null if not * @param options Configuration options as described above * @return Instance of the Pardot API in the specified version */ function PardotAPI (options, callback) { if (!options) { options = {}; } if (!options.userKey) { throw new Error('Pardot API requires a User Key. Obtain this in your pardot account settings.'); } if (!options.apiKey && !options.email && !options.password) { throw new Error('Please authenticate to obtain apiKey. http://developer.pardot.com/kb/api-version-3/authentication'); } options.packageInfo = { "version" : "v2" }; if (!options.version || options.version === 'v2' || options.version === 'v3') { return new PardotAPI_v3(options, callback); } else if (options.version === 'v4') { return new PardotAPI_v4(options, callback); } else { throw new Error('Version ' + options.version + ' of the Pardot API is currently not supported.'); } } module.exports = PardotAPI;
'use strict' const config = require('config') const bunyan = require('bunyan') const bunyanFormat = require('bunyan-format') const grpc = require('grpc') const log = bunyan.createLogger({ name: config.get('log.name'), level: config.get('log.level'), streams: [ { stream: bunyanFormat({ outputMode: config.get('log.format') }) } ] }) log.addSerializers({ err: bunyan.stdSerializers.err }) log.log = log.info.bind(log) grpc.setLogger(log) module.exports = log
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rxjs_1 = require("rxjs"); rxjs_1.Observable.merge = rxjs_1.merge; //# sourceMappingURL=merge.js.map
/** * Created by rihdus on 24/10/16. */ import "../src/Navigator/NavTree/NavTree.spec";
import React from 'react'; import { connect } from 'react-redux'; import { signout } from '../actions'; import FlatButton from 'material-ui/FlatButton'; const ButtonStyle = { width: '150px', height: '50px', fontFamily: 'Raleway, sans-serif', fontWeight: 'bold' }; function Logout({ user, signout }) { return ( <FlatButton style={ButtonStyle} onClick={signout}>Logout</FlatButton> ); } const mapStateToProps = state => ({ user: state.user }); export default connect( mapStateToProps, dispatch => ({ signout() { dispatch(signout()); }, }) )(Logout);
// @flow import { Component } from 'react'; import styles from './optionsBox.css'; import { CheckBox, RadioButton, SelectInput } from 'app/components/Form'; import type { CompanyEntity } from 'app/reducers/companies'; type Props = { companies: Array<CompanyEntity>, updateFilters: (string, mixed) => void, removeFilters: (string) => void, filters: Object, }; type State = { active: boolean, studentContact: boolean, values: { active: boolean, studentContact: /*TODO: StudentContact */ any, }, }; export default class OptionsBox extends Component<Props, State> { state = { active: false, studentContact: false, values: { active: true, studentContact: {}, }, }; toggleSection = (section: string) => { const { filters, updateFilters, removeFilters } = this.props; if (filters[section] === undefined) { updateFilters(section, this.state.values[section]); } else { removeFilters(section); } const state = this.state; state[section] = !this.state[section]; this.setState(state); }; updateFilters = (name: string, value: mixed) => { const { updateFilters } = this.props; this.setState((state) => ({ ...state, values: { ...state.values, [name]: value }, })); updateFilters(name, value); }; removeFilters = (name: string) => { const { removeFilters } = this.props; this.setState((state) => ({ ...state, values: { ...state.values, [name]: undefined }, })); removeFilters(name); }; render() { return ( <div className={styles.optionsBox}> <span style={{ display: 'block', fontSize: '18px', marginBottom: '5px' }} > Filtrer basert på om bedriften... </span> <div style={{ display: 'flex', flexDirection: 'column' }}> <div className={styles.section} style={{ order: 0 }}> <label> <CheckBox value={this.state.active} name="active" onChange={() => this.toggleSection('active')} /> <span>Er aktiv</span> </label> <div className={styles.options} style={{ display: this.state.active ? 'block' : 'none' }} > <label> <RadioButton name="active" id="active" inputValue={true} value={this.state.values.active} onChange={() => this.updateFilters('active', true)} /> <span>Vis bare aktive bedrifter</span> </label> <label> <RadioButton name="active" id="inactive" inputValue={false} value={this.state.values.active} onChange={() => this.updateFilters('active', false)} /> <span>Vis bare inaktive bedrifter</span> </label> </div> <label> <CheckBox value={this.state.studentContact} name="studentContact" onChange={() => this.toggleSection('studentContact')} /> <span>Har studentkontakt...</span> </label> <div className={styles.options} style={{ display: this.state.studentContact ? 'block' : 'none' }} > <SelectInput.WithAutocomplete value={{ id: this.state.values.studentContact && Number(this.state.values.studentContact.id), label: this.state.values.studentContact && this.state.values.studentContact.fullName, }} placeholder="Studentkontakt" name="studentContact" filter={['users.user']} onChange={(user) => user ? this.updateFilters('studentContact', { id: Number(user.id), fullName: user.label, }) : this.removeFilters('studentContact') } onBlur={() => null} /> </div> </div> </div> </div> ); } }
function historyQueryFactory(limit, cursor) { const Limit = limit ? { Limit: limit } : null; const Cursor = cursor ? { Cursor: cursor } : null; return { ...Limit, ...Cursor, }; } function historyResponseFactory(options = {}) { const { limit, cursor, fileName, totalCount } = options; const historyQuery = historyQueryFactory(limit, cursor); return { historyQuery, historyEvents: [{ Event: { Type: 'CELL_MODIFIED', ClientInfo: { DeveloperId: '', DeveloperName: '', ClientId: 'CLIENT_ID', ClientName: 'CLIENT NAME', ClientVersion: '', AdditionalClientData: { HostProgramMainFile: fileName || '', HostProgramVersion: '', }, SDKName: '', SDKVersion: '', OS: 'BROWSER_USER_AGENT', UserId: 'USER_ID', UserName: 'USERNAME', }, CellId: 'CELL_ID', ValueRef: '/SOME_VALUE_REF_PATH/', Time: 1.467241275947e+12, Size: 4, }, }], totalCount, }; } export default historyResponseFactory;
/* SubItem DB Model */ console.log("/server/models/sub-item.js"); var mongoose = require("mongoose"); var subItemSchema = mongoose.Schema({ content: String, }, { timestamps: true }); mongoose.model("SubItem", subItemSchema); module.exports = subItemSchema;
import { CORRECT_PROTOTYPE_GETTER } from '../helpers/constants'; QUnit.test('Reflect.getPrototypeOf', assert => { const { getPrototypeOf } = Reflect; assert.isFunction(getPrototypeOf); assert.arity(getPrototypeOf, 1); assert.name(getPrototypeOf, 'getPrototypeOf'); assert.looksNative(getPrototypeOf); assert.nonEnumerable(Reflect, 'getPrototypeOf'); assert.same(getPrototypeOf([]), Array.prototype); assert.throws(() => getPrototypeOf(42), TypeError, 'throws on primitive'); }); QUnit.test('Reflect.getPrototypeOf.sham flag', assert => { assert.same(Reflect.getPrototypeOf.sham, CORRECT_PROTOTYPE_GETTER ? undefined : true); });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Subject Schema */ var SubjectSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Subject name', trim: true }, category: { type: String, default: '', trim: true }, description: { type: String, default: '', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Subject', SubjectSchema);
var assert = require('assert'); var sinon = require('sinon'); var proxyquire = require('proxyquire'); var server = require('./server'); var ROOT_URL = '/'; describe('Authenticator', function () { var authenticatorStub; var credentialsStub; var PlexAPI; var api; beforeEach(function () { authenticatorStub = sinon.stub().yields(null, 'abc-pretend-to-be-token'); credentialsStub = sinon.stub().returns({ authenticate: authenticatorStub, }); PlexAPI = proxyquire('..', { 'plex-api-credentials': credentialsStub, }); api = new PlexAPI({ hostname: 'localhost', authenticator: { authenticate: authenticatorStub, }, }); }); afterEach(server.stop); describe('.initialize()', function () { it('is called on authenticator if method exists when creating PlexAPI instances', function () { var authenticatorSpy = { initialize: sinon.spy(), }; api = new PlexAPI({ hostname: 'localhost', authenticator: authenticatorSpy, }); assert(authenticatorSpy.initialize.calledOnce); }); it('provides created PlexAPI object as argument', function () { var authenticatorSpy = { initialize: sinon.spy(), }; api = new PlexAPI({ hostname: 'localhost', authenticator: authenticatorSpy, }); assert(authenticatorSpy.initialize.firstCall.calledWith(api)); }); }); describe('.authenticate()', function () { it('is called on authenticator when Plex Server responds with 401', function () { server.start({ statusCode: 401, expectRetry: true, }); return api.query(ROOT_URL).then(function () { assert(authenticatorStub.firstCall.calledWith(api), 'authenticator was called'); }); }); it('provides options object and callback as arguments when calling authenticator', function () { server.start({ statusCode: 401, expectRetry: true, }); return api.query(ROOT_URL).then(function () { var firstArg = authenticatorStub.firstCall.args[0]; var secondArg = authenticatorStub.firstCall.args[1]; assert.equal(typeof firstArg, 'object'); assert.equal(typeof secondArg, 'function'); }); }); it('retries original request with token given from authenticator', function () { scope = server.start({ statusCode: 401, expectRetry: true, }); return api.query(ROOT_URL).then(function (result) { scope.done(); }); }); it('rejects when providing token and server still responds with 401', function () { scope = server.start({ statusCode: 401, retryStatusCode: 401, expectRetry: true, }); return api.query(ROOT_URL).then( function onSuccess(result) { throw new Error('Query should not have succeeded!'); }, function onError() { scope.done(); } ); }); }); describe('default authenticator', function () { it('uses the plex-api-credentials authenticator when options.username and .password are provided', function () { server.start({ statusCode: 401, expectRetry: true, }); api = new PlexAPI({ hostname: 'localhost', username: 'foo', password: 'bar', }); return api.query(ROOT_URL).then(function () { assert(authenticatorStub.calledOnce, 'credentials authenticator was called'); }); }); it('rejects with a missing authenticator error when options.username and .password were missing and Plex Server responds with 401', function () { server.start({ statusCode: 401, }); api = new PlexAPI({ hostname: 'localhost', }); return api.query(ROOT_URL).then(null, function (err) { assert(err instanceof Error, 'rejected with an error instance'); assert( err.message.match(/you must provide a way to authenticate/), 'error message says authenticator is needed' ); }); }); }); });
'use strict'; var _ = require('lodash'); var fs = require('fs'); var temp = require('temp'); var path = require('path'); var q = require('q'); var writeTempFile = function(fileContents) { var deferred = q.defer(); // Automatically track and cleanup files at exit. temp.track(); // Create the temporary protractor config file. temp.open('protractor-conf', function(err, info) { if (err) { console.log('Error creating protractor config file', err); throw Error('Error creating protractor config file'); } fs.write(info.fd, fileContents); fs.close(info.fd, function(err) { if (err) { console.log('Error closing file', err); throw Error('Error closing file'); } }); deferred.resolve(info.path); }); return deferred.promise; }; var createProtractorConfig = function(options) { // Get the chrome extension path. var chromeOptions = "--load-extension=" + path.join(__dirname, '../extension'); // The extension path does not work in Windows. Replace c:\some\path with // c:/some/path chromeOptions = chromeOptions.replace(/\\/g, '/'); // Are there any chrome args? Put them before the extension. if (options.chromeOptions) { chromeOptions = options.chromeOptions + ' ' + chromeOptions; } // Add quotes. chromeOptions = "'" + chromeOptions + "'"; var configPath = path.join(__dirname, './protractor.conf.js'), templateFile = fs.readFileSync(configPath, 'utf-8'), replaced = templateFile.replace(/\$CHROME_OPTIONS/g, chromeOptions); return writeTempFile(replaced); }; module.exports = { createProtractorConfig: createProtractorConfig };
var consumer = require(__dirname + '/../buffer-consumer') var assert = require('assert') var crypto = require('crypto') var buf = crypto.randomBytes(0x3fffff) describe('Consume', function () { it('should return the right buffer for fixed 1 jump length', function (done) { this.timeout(0) var consume = consumer(buf) for (var i = 0; i < buf.length; i++) { assert.equal(consume(1)[0], buf[i], 'Should be equal') } done() }) it('should return the right buffer for fixed 4 jump length', function (done) { this.timeout(0) var consume = consumer(buf) for (var i = 0; i < buf.length; i += 4) { assert.equal(consume(4)[0], buf[i], 'Should be equal') } done() }) it('should return the right buffer for any jump length', function (done) { this.timeout(0) for (var j = 1; j < buf.length; j++) { var consume = consumer(buf) for (var i = 0; i < buf.length; i += j) { assert.equal(consume(j)[0], buf[i], 'Should be equal') } } done() }) })
'use strict'; var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var _ = require('lodash'); var config = require('./config'); var winston = require('./winston'); var db = {}; winston.info('Initializing Sequelize...'); // create your instance of sequelize var sequelize = null; //check if is on Heroku if (!!process.env.DYNO){ sequelize = new Sequelize(process.env.DATABASE_URL, { dialect: 'postgres', protocol: 'postgres', dialectOptions: { ssl: true } }); //check if is on CleverCloud }else if(process.env.POSTGRESQL_ADDON_URI){ sequelize = new Sequelize(process.env.POSTGRESQL_ADDON_URI, { dialect: 'postgres', protocol: 'postgres', dialectOptions: { ssl: false } }); } else { sequelize = new Sequelize(config.db.name, config.db.username, config.db.password, { host: config.db.host, port: config.db.port, dialect: config.db.dialect, storage: config.db.storage, logging: config.enableSequelizeLog === 'true' ? winston.verbose : false }); } // loop through all files in models directory ignoring hidden files and this file fs.readdirSync(config.modelsDir) .filter(function (file) { return (file.indexOf('.') !== 0) && (file !== 'index.js') }) // import model files and save model names .forEach(function (file) { winston.info('Loading model file ' + file); var model = sequelize.import(path.join(config.modelsDir, file)); db[model.name] = model; }); // invoke associations on each of the models Object.keys(db).forEach(function (modelName) { if (db[modelName].options.hasOwnProperty('associate')) { db[modelName].options.associate(db) } }); // Synchronizing any model changes with database. // set FORCE_DB_SYNC=true in the environment, or the program parameters to drop the database, // and force model changes into it, if required; // Caution: Do not set FORCE_DB_SYNC to true for every run to avoid losing data with restarts sequelize .sync({ force: config.FORCE_DB_SYNC === 'true', logging: config.enableSequelizeLog === 'true' ? winston.verbose : false }) .then(function () { winston.info("Database " + (config.FORCE_DB_SYNC === 'true' ? "*DROPPED* and " : "") + "synchronized"); }).then(function () { db.User.findOne({where:{username:'admin'}}).then(function (user) { if (!user){ winston.info("create User admin"); var _user = db["User"].build({username: "admin"}); _user.salt = _user.makeSalt(); _user.hashed_password = _user.encryptPassword("admin", _user.salt); _user.role = "admin"; _user.deletable = false; _user.save(); } }); }) .catch(function (err) { winston.error("An error occurred: ", err); }); // assign the sequelize variables to the db object and returning the db. module.exports = _.extend({ sequelize: sequelize, Sequelize: Sequelize }, db);
(function () { angular.module('myApp.items',[ 'myApp.items.models', 'myApp.items.directives', 'myApp.items.services', 'myApp.items.controllers' ]) })();
var test; HTMLWidgets.widget({ name: 'cliffnotes', type: 'output', factory: function(el, width, height) { // TODO: define shared variables for this instance return { renderValue: function(x) { ReactDOM.render( React.createElement(CliffNotes.DataFrameSummary, {data: x.data, el: el}), document.getElementById(el.id) ); }, resize: function(width, height) { // TODO: code to re-render the widget with a new size } }; } });
const RepresentationList = require('./representationList'); class LinkeduserList extends RepresentationList { constructor(client, parent) { super(client, parent); this.type = 'linkeduserList'; this.itemType = 'linkeduser'; } } module.exports = LinkeduserList;
import Route from '@ember/routing/route'; export default Route.extend({ model() { return { selectContent: [{ value: 'abc', label: 'First Item' }, { value: 'xzy', label: 'Second Item' }] }; } });
describe('Method calls:', function() { var A, B, C; beforeEach(function() { A = OO.newClass(); //.name('A'); A.method('m', function() {return 'm in A';}); B = A.subclass(); //.name('B'); C = B.subclass(); //.name('C'); C.method('m', function() {return '('+this._super()+') '+'m in C';}); }); it('local method', function() { A.create().m().should.equal("m in A"); }); it('non-local method', function() { B.create().m().should.equal("m in A"); }); it('super in grandparent', function() { C.create().m().should.equal("(m in A) m in C"); }); describe('super:', function() { beforeEach(function() { B.method('m', function() {return '('+this._super()+') '+'m in B';}); }); it('in parent', function() { B.create().m().should.equal("(m in A) m in B"); }); it('chain', function() { C.create().m().should.equal("((m in A) m in B) m in C"); }); describe('super:', function() { beforeEach(function() { A.method('m2', function() {return 'm2 in A';}); B.method('m2', function() {return '('+this.m()+') '+'m2 in B';}); C.method('m2', function() {return '('+this._super()+') '+'m2 in C';}); }); it('chain', function() { C.create().m2().should.equal("((((m in A) m in B) m in C) m2 in B) m2 in C"); }); describe('super:', function() { beforeEach(function() { A.method('m1', function() {return 'm1 in A'; }); B.method('m1', function() {return '('+this._super()+') '+'m1 in B';}); B.method('m2', function() {return '('+this.m1()+') '+'m2 in B';}); C.method('m2', function() {return '('+this._super()+') '+'m2 in C';}); }); it('two chains', function() { C.create().m2().should.equal("(((m1 in A) m1 in B) m2 in B) m2 in C"); }); }); }); }); }); describe('Inspect methods:', function() { var A, B; var mA = function() { this.acons = 'A'; }; var mAB = function() { this.acons = 'AB'; }; var mB = function() { this.bcons = 'B'; }; var mBA = function() { this.bcons = 'BA'; }; beforeEach(function() { A = OO.newClass().name('A') .method('mA', mA) .method('mAB', mAB); B = A.subclass().name('B') .method('mB', mB) .method('mAB', mBA); }); it('A hasMethod', function() { /*jshint expr:true */ A.hasMethod('mA').should.be.true; A.hasMethod('mAB').should.be.true; A.hasMethod('mB').should.be.false; }); it('A hasOwnMethod', function() { /*jshint expr:true */ A.hasOwnMethod('mA').should.be.true; A.hasOwnMethod('mAB').should.be.true; A.hasOwnMethod('mB').should.be.false; }); it('B hasMethod', function() { /*jshint expr:true */ B.hasMethod('mA').should.be.true; B.hasMethod('mAB').should.be.true; B.hasMethod('mB').should.be.true; }); it('B hasOwnMethod', function() { /*jshint expr:true */ B.hasOwnMethod('mA').should.be.false; B.hasOwnMethod('mAB').should.be.true; B.hasOwnMethod('mB').should.be.true; }); it('A getMethod', function() { var fa = A.getMethod('mA'); var a = new fa(); a.acons.should.equal('A'); var fab = A.getMethod('mAB'); a = new fab(); a.acons.should.equal('AB'); }); it('B getMethod', function() { var fb = B.getMethod('mB'); var b = new fb(); b.bcons.should.equal('B'); var fab = B.getMethod('mAB'); b = new fab(); b.bcons.should.equal('BA'); }); it('A listMethods', function() { A.listMethods().should.deep.equal(['mA', 'mAB']); B.listMethods().should.deep.equal(['mB', 'mAB', 'mA']); }); it('B listOwnMethods', function() { A.listOwnMethods().should.deep.equal(['mA', 'mAB']); B.listOwnMethods().should.deep.equal(['mB', 'mAB']); }); });
"use strict"; function getURLCallback(URL, callback) { var req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function () { if (req.status === 200) { callback(null, req.responseText); } else { callback(new Error(req.statusText), req.response); } }; req.onerror = function () { callback(new Error(req.statusText)); }; req.send(); } function parse(callback, error, value) { if (error) { callback(error, value); } else { try { var result = JSON.parse(value); callback(null, result); } catch (e) { callback(e, value); } } } var request = { comment: function getComment(callback) { return getURLCallback('http://azu.github.io/promises-book/json/comment.json', parse.bind(null, callback)); }, people: function getPeople(callback) { return getURLCallback('http://azu.github.io/promises-book/json/people.json', parse.bind(null, callback)); } }; function main(callback) { function requester(requests, callback) { var results = []; var requestLength = results.length; function handler(error, value) { if (error) { return callback(error, value); } results.push(value); if (results.length === requestLength) { callback(null, results); } } for (var i = 0; i < requests.length; i++) { var req = requests[i]; req(handler); } } requester([request.comment, request.people], callback); } module.exports.main = main; module.exports.request = request;
'use strict'; //Setting up route angular.module('courses').config(['$stateProvider', function($stateProvider) { // Courses state routing $stateProvider. state('listCourses', { url: '/courses', templateUrl: 'modules/courses/views/list-courses.client.view.html' }). state('createCourse', { url: '/courses/create', templateUrl: 'modules/courses/views/create-course.client.view.html' }). state('viewCourse', { url: '/courses/:courseId', templateUrl: 'modules/courses/views/view-course.client.view.html' }). state('editCourse', { url: '/courses/:courseId/edit', templateUrl: 'modules/courses/views/edit-course.client.view.html' }). state('quicesPorCurso', { url: '/quicesPorCurso', templateUrl: 'modules/courses/views/quicesPorCurso-course.client.view.html' }); } ]);
const Note = require('../models/note'); const HttpError = require('../lib/helpers').HttpError; /** * Display a listing of the resource. * @param {Request} req Http request * @param {Response} res Http response * @param {NextFunction} next Next handler */ const index = (req, res, next) => { Note.query() .then((notes) => { res.json(notes); }) .catch(next); }; /** * Display the specified resource. * @param {Request} req Http request * @param {Response} res Http response * @param {NextFunction} next Next handler */ const show = (req, res, next) => { const id = req.params.id; if (!id) { next(HttpError(400, 'Missing param: \'id\'')); } Note.query() .findById(id) .then(note => res.json(note)) .catch(next); }; /** * Store a newly created resource in storage. * @param {Request} req Http request * @param {Response} res Http response * @param {NextFunction} next Next handler */ const store = (req, res, next) => { const body = req.body; Note.query() .insertAndFetch(body) .then(note => res.json(note)) .catch(next); }; /** * Update the specified resource in storage. * @param {Request} req Http request * @param {Response} res Http response * @param {NextFunction} next Next handler */ const update = (req, res, next) => { const id = req.params.id; const obj = { title: req.body.title, body: req.body.body }; Note.query() .patchAndFetchById(id, obj) .then(note => res.json(note)) .catch(next); }; /** * Remove the specified resource from storage. * @param {Request} req Http request * @param {Response} res Http response * @param {NextFunction} next Next handler */ const destroy = (req, res, next) => { const id = req.params.id; if (!id) { next(HttpError(400, 'Missing param: \'id\'')); } Note.query() .deleteById(id) .then(res.json({})) .catch(next); }; // Controller with all of the typical CRUD actions. const NoteApiController = { index, show, store, update, destroy }; module.exports = NoteApiController;
var searchData= [ ['very_5fhigh_5fspeed_101',['VERY_HIGH_SPEED',['../namespace_a_d_c__settings.html#af0d80a1aae7288f77b13f0e01d9da0d3a605020f3fad4a24098fbbb0fa4a293f1',1,'ADC_settings']]], ['very_5flow_5fspeed_102',['VERY_LOW_SPEED',['../namespace_a_d_c__settings.html#af0d80a1aae7288f77b13f0e01d9da0d3a5afd4ce3e51232e5889cfd918354ff2d',1,'ADC_settings']]], ['vrefsh_103',['VREFSH',['../namespace_a_d_c__settings.html#a8c2a64f3fca3ac6b82e8df8cf44f6ca2ad1809a5c0e700d83d66cd3c96f5b414f',1,'ADC_settings']]] ];
angular.module('chat') .factory('nicknameSrv', ['$rootScope', '$modal', '$q', 'socket', function ($rootScope, $modal, $q, socket) { return { openNicknameModal: function () { var deferred = $q.defer(); var modalInstance = $modal.open({ templateUrl: 'modules/chat/nickname_modal.html', controller: 'NicknameModalInstanceCtrl', backdrop: 'static', keyboard: false, size: 'sm' }); modalInstance.result.then( function (nickname) { if (nickname) { socket.emit('announce_join', { nickname: nickname, radioid: $rootScope.radioid }); deferred.resolve(nickname); } else deferred.reject(); }, function (error) { deferred.reject(error); } ); return deferred.promise; } } }]);
/* ============================================================ * bootstrap-dropdown.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, Inc. * * 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. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle=dropdown]' , Dropdown = function (element) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function (e) { var $this = $(this) , $parent , isActive if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') clearMenus() if (!isActive) { $parent.toggleClass('open') } $this.focus() return false } , keydown: function (e) { var $this , $items , $active , $parent , isActive , index if (!/(38|40|27)/.test(e.keyCode)) return $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) return $this.click() $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items .eq(index) .focus() } } function clearMenus() { $(toggle).each(function () { getParent($(this)).removeClass('open') }) } function getParent($this) { var selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) $parent.length || ($parent = $this.parent()) return $parent } /* DROPDOWN PLUGIN DEFINITION * ========================== */ var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* DROPDOWN NO CONFLICT * ==================== */ $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(document) .on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus) .on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('touchstart.dropdown.data-api', '.dropdown-menu', function (e) { e.stopPropagation() }) .on('click.dropdown.data-api touchstart.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery);
var Builder = require('../index'); var builder = new Builder('test/fixtures/conditional-tree'); builder.loadConfigSync('test/fixtures/conditional-tree.config.js'); var baseURL = builder.loader.baseURL; builder.config({ defaultJSExtensions: true }); suite('Conditional Canonical Names', function() { test('Package environment canonical', function() { assert.equal(builder.getCanonicalName(baseURL + 'pkg#:env-condition'), 'pkg#:env-condition'); }); test('Interpolation', function() { assert.equal(builder.getCanonicalName(baseURL + 'interpolated-#{' + baseURL + 'conditions.js|test}.js'), 'interpolated-#{conditions.js|test}.js'); }); test('Plugin interpolation', function() { assert.equal(builder.getCanonicalName(baseURL + 'pkg/test-#{' + baseURL + 'conditions.js|test}.js!plugin-#{conditions.js|another}.js'), 'pkg/test-#{conditions.js|test}.js!plugin-#{conditions.js|another}.js'); }); test('Boolean conditional', function() { assert.equal(builder.getCanonicalName(baseURL + 'pkg/test#?~' + baseURL + 'bool|exp'), 'pkg/test#?~bool|exp'); }); test('Boolean conditional with plugin', function() { builder.config({ paths: { a: 'asdf', // only if we add .js this catches condition: 'conditions.js', p: 'plugin' } }) assert.equal(builder.getCanonicalName(baseURL + 'asdf.js' + '!' + baseURL + 'plugin.js#?' + baseURL + 'conditions.js'), 'asdf.js!p#?condition'); }) });
'use strict'; (function () { var autocompleteModule = angular.module('TVG.GoogleAPIAutocomplete'); autocompleteModule.factory('PlaceDetails', function () { function PlaceDetails(address, zipcode, state, city) { this.address = address; this.zipcode = zipcode; this.state = state; this.city = city; } function parseData(data, result) { var desiredInfo = { locality: function (obj) { result.city = obj.long_name; }, postal_code: function (obj) { result.zipcode = obj.long_name; }, administrative_area_level_1: function (obj) { result.state = obj.long_name; }, postal_code_prefix: function (obj) { result.zipcode = obj.long_name; } }; if (!_.isUndefined(data)) { _.forOwn(data, function (value) { if(_.has(desiredInfo, value.types[0])){ desiredInfo[value.types[0]](value); } }); } } PlaceDetails.build = function (data, address) { var result = { address: address }; parseData(data, result); return new PlaceDetails(result.address, result.zipcode, result.state, result.city); }; return PlaceDetails; }); }());
'use strict'; /** * @ngdoc function * @name wxwebApp.controller:ItResourceAddPortMonitorCtrl * @description * # ItResourceAddPortMonitorCtrl * Controller of the wxwebApp */ angular.module('wxwebApp') .controller('ItResourceAddPortMonitorCtrl', function ($scope, $routeParams, ItRes, flashr, $location) { var resId = $routeParams.resId; $scope.monitor = { resId: resId, wxReceiver: true, type: 2 }; $scope.MonitorRules = { name: { inputType:'text', label: '名称', required: { rule: true, message: '必须填写名称' } }, port: { inputType: 'text', label: '端口', required: { rule: true, message: '必须填写端口号' }, type: { rule: 'number', message: '只能填写数字' }, minimum: { rule: 1, message: '无效的端口号' }, maximum: { rule: 65535, message: '无效的端口号' } } }; $scope.submit = function (data) { ItRes.addMonitor(resId, data, function (monitor) { $location.url('/it_resource/detail/' + resId); // 添加成功 }, function (result) { flashr.now.warning(result.msg); // 添加失败 }); } });
'use strict'; (function() { // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript#answer-901144 function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } // SHIM: Make the type persistent let type = getParameterByName('type'); if (type) { let types = type.split('|'); let typeFields = document.querySelectorAll('input[data-name="type_option"]:checked'); for (let index = 0; index < typeFields.length; index++) { (function() { let field = typeFields[index]; for (let j = 0; j < types.length; j++) { if (types[j] === field.value) { field.checked = true; return; } } field.checked = false; })(); } } // SHIM: Pass the type onto the next page as one pipe-delimited query string value let form = document.querySelector('form'); form.addEventListener('submit', function(e) { let typeFields = document.querySelectorAll('input[data-name="type_option"]:checked'); let types = []; for (let index = 0; index < typeFields.length; index++) { types.push(typeFields[index].value); //typeFields[index].checked = false; } let hiddenType = document.querySelector('input[type="hidden"][name="type"]'); hiddenType.value = types.join('|'); form.submit(); e.preventDefault(); }, false); // SHIM: Make the address persistent let address = getParameterByName('address'); if (address) { let addressField = document.querySelector('input[name="address"]'); addressField.value = address; } // SHIM: Make the food deserts option persistent let deserts = getParameterByName('deserts'); if (deserts) { let desertsField = document.querySelector('input[name="deserts"]'); if (desertsField.type === 'checkbox') { desertsField.checked = (deserts && deserts != '') ? true : false; } else { desertsField.value = deserts; } } // SHIM: Make the “open now” option persistent let open = getParameterByName('open'); if (open) { let openField = document.querySelector('input[name="open"]'); if (openField.type === 'checkbox') { openField.checked = (open && open != '') ? true : false; } else { openField.value = open; } } /** * Uses the browser geolocation method to reverse geocode the user's * address based on the provided lat/lng. * @return {Promise) successful promise returns an array of result obejcts * TODO: Reverse geolocation is a little awkward here. This is because the * map view is looking for an address parameter. Ideally, we can skip * reverse geo completely and jsut pass some lat/lng url parameters to the * map view. * view should be able to */ function getCurrentLocation() { return new Promise(function(resolve, reject) { navigator.geolocation.getCurrentPosition(function(position) { let geocoder = new google.maps.Geocoder; geocoder.geocode({ location: { lat: position.coords.latitude, lng: position.coords.longitude } }, function(results, status) { if (status === 'OK') { resolve(results); } else { reject(); } }, function() { reject(); }); }); }); } // If the user's browser allows geolocation, reveal any "Use Current // Location" buttons and attach handlers. These buttons use Google's // geocoder to reverse geolocate based on the user's address. if ('geolocation' in navigator) { let form = document.getElementById('search-form'); let currentLocationButtons = document.getElementsByClassName('js-current-location'); let addressField = form.querySelectorAll('input[name="address"]')[0]; for (let i = 0; i < currentLocationButtons.length; i++) { let button = currentLocationButtons[i]; button.addEventListener('click', function(e) { // TODO: Some kind of "loading" spinner would be good here because // the navigator.geolocation method tends to take a while. if (button.disabled) { return false; } e.preventDefault(); button.disabled = true; getCurrentLocation().then(function(results) { if (results.length) { // If geolocation results are returned, prefer to use the second // result. The first one is a little too specific and may not // be accurate to the user. addressField.value = results[1] ? results[1].formatted_address : results[0].formatted_address; //form.submit(); } button.disabled = false; }).catch(function() { // TODO: some kind of error handler here would be good. Maybe // a message saying that you need to allow the browser to use // your current location. button.disabled = false; }); }); currentLocationButtons[i].classList.remove('hidden'); } } })();
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // root state object. // each Vuex instance is just a single state tree. const state = { count: 0, thisMonth: 9, hello: { world: "how are you" }, groups: [ { restaurant: '添好運', date:'2016/10/15 (五)', participant: [{name: 'stacy chen', contact: true}, {name: 'yingray lu', contact: false}, {name: 'pompom huang', contact: false}], remain: 0, note: '報名即將截止,要搶要快!' }, { restaurant: '點點心', date:'2016/10/20 (二)', participant: [{name: 'liz cheng', contact: false}, {name: 'Gary Chung', contact: true}, {name: 'Amber ou', contact: false}], remain: 1, note: 'JAVAN 是我的!' }, { restaurant: '花酒藏', date:'2016/10/15 (五)', participant: [{name: 'Jerry Chen', contact: true}, {name: 'Nicky Chen', contact: false}, {name: 'Mike chen', contact: false}], remain: 2, note: '美食在此,你還不來嗎' } ], ungroup: [ { name: 'Kiki Huang', status: 'no_group' }, { name: 'Javan', status: 'leave' } ] }; // mutations are operations that actually mutates the state. // each mutation handler gets the entire state tree as the // first argument, followed by additional payload arguments. // mutations must be synchronous and can be recorded by plugins // for debugging purposes. const mutations = { increment (state) { state.count++ }, decrement (state) { state.count-- } } // actions are functions that causes side effects and can involve // asynchronous operations. const actions = { increment: ({ commit }) => commit('increment'), decrement: ({ commit }) => commit('decrement'), incrementIfOdd ({ commit, state }) { if ((state.count + 1) % 2 === 0) { commit('increment') } }, incrementAsync ({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit('increment') resolve() }, 1000) }) }, signIn ({ commit }) { console.log("signIn"); console.log(firebase); var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider); } } // getters are functions // 根據state,不用另外去設定的變數 // computed 算出來的 const getters = { evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd' } // A Vuex instance is created by combining the state, mutations, actions, // and getters. export default new Vuex.Store({ state, getters, actions, mutations })
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './demo/app.js', css: './demo/app.scss' }, module: { rules: [ { test: /\.(js|jsx)$/, use: ['ng-annotate-loader', 'babel-loader'], parser: { amd: false } }, { test: /\.html$/, loader: `html-loader`, }, { test: /\.(css)$/, include: [/react-toolbox/], use: [ 'style-loader', { loader: 'css-loader', options: { modules: true, importLoaders: 1, localIdentName: '[name]__[local]___[hash:base64:5]' } }, 'postcss-loader' ], }, { test: /\.(css|scss)$/, exclude: [/react-toolbox/], use: [ 'style-loader', 'css-loader', 'sass-loader' ] } ], }, devtool: 'inline-source-map', devServer: { contentBase: './' }, plugins: [ new HtmlWebpackPlugin({ template: `./demo/index.html`, inject: true, minify: false, }) ], output: { path: path.resolve(__dirname, 'bundle'), filename: '[name].bundle.js', } };
export const preventDefault = (f, ...args) => event => { event.preventDefault(); return f(...args); };
var CanvasBounds = (function() { function CanvasBounds( canvas ){ this.canvas = canvas; this.drawWidth = 0; this.drawHeight = 0; this.top = 0; this.right = 0; this.bottom = 0; this.left = 0; this.width = 0; this.height = 0; this.xOffset = 0; this.yOffset = 0; this.calculate(); } CanvasBounds.prototype.setBounds = function( options ) { this.drawWidth = options.width; this.canvas.width = options.width; this.drawHeight = options.height; this.canvas.height = options.height; this.calculate(); }; CanvasBounds.prototype.calculate = function() { var givenBounds = this.canvas.getBoundingClientRect(); console.log(givenBounds); this.top = givenBounds.top; this.right = givenBounds.right; this.bottom = givenBounds.bottom; this.left = givenBounds.left; this.width = givenBounds.width; this.height = givenBounds.height; this.xOffset = (this.drawWidth - givenBounds.width) / 2 - givenBounds.left - 2; // -2 here is odd, for some reason chrome allows clicking off canvas this.yOffset = (this.drawHeight - givenBounds.height) / 2 - givenBounds.top; }; CanvasBounds.prototype.toString = function() { return "{width: " + this.width + ", height: " + this.height + "}"; }; return CanvasBounds; })(); var Mouse = (function() { function Mouse( canvas, bounds ) { this.canvas = canvas; this.bounds = bounds; this.x = 0; this.y = 0; } Mouse.prototype.calculate = function( event ) { this.x = event.offsetX; this.y = event.offsetY; return this; }; Mouse.prototype.onMove = function( callback ) { var self = this; this.canvas.addEventListener('mousemove', function( event ){ callback( self.calculate( event ) ); }); }; Mouse.prototype.onClick = function( callback ) { var self = this; this.canvas.addEventListener('click', function( event ){ callback( self.calculate( event ) ); }); }; return Mouse; })();
const fs = require('fs'); const $ = global.jQuery = require('./../bower_components/jquery/dist/jquery.js'); require('./../bower_components/jquery-csv/src/jquery.csv.js'); /** * Definitions for supported file types * * Add more objects here to support additional formats */ var formats = { csv: { label: 'Comma separated', filters: [ { name: 'csv files', extensions: ['csv'] } ], options: { separator: ',', delimiter: '"'}, mime_type: 'text/csv', default_extension: 'csv', }, tsv: { label: 'Tab separated', filters: [ { name: 'tsv files', extensions: ['tsv'] }, { name: 'txt files', extensions: ['txt'] }, { name: 'dat files', extensions: ['dat'] }, ], options: { separator: "\t", delimiter: '"'}, mime_type: 'text/tab-separated-values', default_extension: 'tsv', }, semicolon: { label: 'Semicolon separated', filters: [ { name: 'csv files', extensions: ['csv'] } ], options: { separator: ';', delimiter: '"'}, mime_type: 'text/csv', default_extension: 'csv', }, }; var openFile = function(hot, data, format) { var arrays; // if no format specified, default to csv if (typeof format === 'undefined') { arrays = $.csv.toArrays(data); } else { arrays = $.csv.toArrays(data, format.options); } hot.loadData(arrays); return arrays; }; var saveFile = function(hot, fileName, format, callback) { var data; // if no format specified, default to csv if (typeof format === 'undefined') { data = $.csv.fromArrays(hot.getData()); } else { data = $.csv.fromArrays(hot.getData(), format.options); } if (typeof callback === 'undefined') { fs.writeFile(fileName, data, function (err) { }); } else { fs.writeFile(fileName, data, callback); } document.title = fileName; }; module.exports = { formats: formats, open: openFile, save: saveFile };
import { connect } from 'react-redux' import { compose } from 'redux' import { reduxForm } from 'redux-form' import schema from '@schemas/signUp' import validator from '@helpers/validator' import UserEditForm from '@routes/UserSettingsPage/components/UserEditForm' import * as authActions from '@modules/auth/actions' const validate = values => validator(values, schema) const mapDispatchToProps = (dispatch, ownProps) => ({ editSettings: (values) => { dispatch(authActions.editSettings(ownProps.userId, values)) }, clearError() { dispatch(authActions.clearAuthErrors()) }, }) const mapStateToProps = state => ({ authError: state.auth.get('error'), initialValues: { email: state.auth.get('user') ? state.auth.get('user').email : '', username: state.auth.get('user') ? state.auth.get('user').username : '', name: state.auth.get('user') ? state.auth.get('user').name : '', birthday: state.auth.get('user') ? state.auth.get('user').birthday : '', }, isEditing: state.auth.get('isEditing'), userId: state.auth.get('user') ? state.auth.get('user')._id : '', }) export default compose( connect(mapStateToProps, mapDispatchToProps), reduxForm({ form: 'UserEditForm', enableReinitialize: true, validate, }), )(UserEditForm)
import deepFreeze from 'deep-freeze'; import * as actions from '../actions/characterCreationActions'; import { updateSetting } from '../actions/settingActions'; import initialState from './initialState'; import reducer from './meritsReducer'; deepFreeze(initialState.character.merits); it('should initialize', () => { const action = { type: '@@INIT' }; const nextState = reducer(undefined, action); expect(nextState).toBe(initialState.character.merits); }); it('should add merit, preserving existing', () => { const state = [ { name: 'Calm Heart', points: 1 } ]; deepFreeze(state); const action = actions.addMerit('Clear Sighted', 3); const nextState = reducer(state, action); expect(nextState).toEqual([ { name: 'Calm Heart', points: 1 }, { name: 'Clear Sighted', points: 3 } ]); }); it('should add second merit when purchased multiple times', () => { const state = [ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2 } ]; deepFreeze(state); const action = actions.addMerit('Skill Aptitude', 2); const nextState = reducer(state, action); expect(nextState).toEqual([ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2, timesPurchased: 2 } ]); }); it('should add third merit when purchased multiple times', () => { const state = [ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2, timesPurchased: 2 } ]; deepFreeze(state); const action = actions.addMerit('Skill Aptitude', 2); const nextState = reducer(state, action); expect(nextState).toEqual([ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2, timesPurchased: 3 } ]); }); it('should remove merit', () => { const state = [ { name: 'Calm Heart', points: 1 }, { name: 'Clear Sighted', points: 3 } ]; deepFreeze(state); const action = actions.removeMerit('Calm Heart'); const nextState = reducer(state, action); expect(nextState).toEqual([ { name: 'Clear Sighted', points: 3 } ]); }); it('should remove second merit when purchased multiple times', () => { const state = [ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2, timesPurchased: 2 } ]; deepFreeze(state); const action = actions.removeMerit('Skill Aptitude'); const nextState = reducer(state, action); expect(nextState).toEqual([ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2 } ]); }); it('should remove third merit when purchased multiple times', () => { const state = [ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2, timesPurchased: 3 } ]; deepFreeze(state); const action = actions.removeMerit('Skill Aptitude'); const nextState = reducer(state, action); expect(nextState).toEqual([ { name: 'Calm Heart', points: 1 }, { name: 'Skill Aptitude', points: 2, timesPurchased: 2 } ]); }); it('should clear if change clan', () => { const state = [ { name: 'Calm Heart', points: 1 }, { name: 'Clear Sighted', points: 3 } ]; deepFreeze(state); const action = actions.updateClan('Tremere'); const nextState = reducer(state, action); expect(nextState).toEqual([]); }); it('should clear if change setting', () => { const state = [ { name: 'Calm Heart', points: 1 }, { name: 'Clear Sighted', points: 3 } ]; deepFreeze(state); const action = updateSetting('Sabbat'); const nextState = reducer(state, action); expect(nextState).toEqual([]); });
import React, { Component } from 'react'; // Components import LogReaderResultItemDetail from './LogReaderResultItemDetail.react'; class LogReaderResultItem extends Component { render() { let default_message = "The selected log message will be displayed here"; let log_detail = this.props.item.log_message || default_message; // If it's not the default message, show the log details if(log_detail !== default_message) { log_detail = <LogReaderResultItemDetail item={this.props.item} /> } return ( <div id='selected-item'> <div id='selected-item-body container'> {log_detail} </div> </div> ); } } export default LogReaderResultItem
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q"> <LogMonitor theme="tomorrow"/> </DockMonitor> );
import isObject from 'lodash-es/isObject' import isEmpty from 'lodash-es/isEmpty' import isFunction from 'lodash-es/isFunction' import isArray from 'lodash-es/isArray' import reduce from 'lodash-es/reduce' import cloneDeep from 'lodash-es/cloneDeep' import Observable from 'zen-observable' import * as most from 'most' import libGet from './../fns/lib-get' import libOn from './../fns/lib-on' const lib = db => { return { get: libGet(db), on: libOn(db) } } function buildObservable (source, lib, ops) { ops.forEach(x => { let op = x[0] let args = x[1] args = Array.prototype.slice.call(args) if (isFunction(args[0])) { let fn = args[0] args[0] = function controllerWrapperFn () { let fnArgs = Array.prototype.slice.call(arguments) fnArgs.push(lib) return fn.apply(null, fnArgs) } } source = source[op].apply(source, args) }) return source } function createController (db, controller, name) { let off = () => {} if (!controller.args || !controller.fn) { throw new Error(`Controller [${name}] should look like: -- { args: Object, fn: Function | Observable } -- example: { args: { foo: '/bam/bar/foo', baz: '/boo/baz' }, fn: args => { args.foo // The value at /bam/bar/foo args.baz // => /boo/baz } } `) } let observable = new Observable(observer => { let keys = Object.keys(controller.args) let args = keys.reduce((acc, x) => { acc[x] = undefined return acc }, {}) let unsubs = keys.map(key => { return db.on(controller.args[key], val => { args[key] = val observer.next(cloneDeep(args)) }) }) off = () => { unsubs.forEach(x => { x() }) observer.complete() } }) let ops = [] if (isFunction(controller.fn)) { ops.push(['map', [controller.fn]]) } else if (isObject(controller.fn) && controller.fn['__instance__'] && !isEmpty(controller.fn['__instance__'].op)) { ops = controller.fn['__instance__'].op } else { throw new Error('Controller fn is neither a function nor an observable placeholder') } let internalLib = lib(db) controller.name = name controller.result = buildObservable(most.from(observable), internalLib, ops) controller.off = off } export default createController
import fetch from './fetch'; const { POSITRON_API_BASE } = process.env; export default (path) => fetch(`${POSITRON_API_BASE}/${path}`);
// add/remove body classes based on viewport width var bodyViewportClasses = function() { if(document.getElementById("mobileNavToggle")) { $('#mobileNavToggle').remove(); } // testing the display property on the element var nav_display = $('.off-canvas-nav-links').css('display'); // testing for display:block (changed in css via media queries) if (nav_display === 'block') { $("body").removeClass("multi-column").addClass("small-screen"); } // testing for display:none (changed in css via media queries) if (nav_display === 'none') { $("body").removeClass("active-sidebar active-nav small-screen") .addClass("multi-column"); } } // function for sidebar display toggle var showSidebar = function() { $('body').removeClass("active-nav").toggleClass("active-sidebar"); $('.menu-button').removeClass("active-button"); $('.sidebar-button').toggleClass("active-button"); $('.sidebar-button').attr('aria-expanded',$('.sidebar-button').attr('aria-expanded') == 'true' ? 'false' : 'true'); $('.sidebar-button').attr('value',$('.sidebar-button').attr('value') == 'Mobile navigation menu collapsed' ? 'Mobile navigation menu expanded' : 'Mobile navigation menu collapsed'); } // add/remove classes everytime the window resize event fires jQuery(window).resize(function(){ bodyViewportClasses(); }); jQuery(document).ready(function($) { var doc = document.getElementById('doc'); doc.removeAttribute('class', 'no-js'); doc.setAttribute('class', 'js'); // Toggle for sidebar $('.sidebar-button').click(function(e) { e.preventDefault(); showSidebar(); }); // Escape Key to Close $(document).keyup(function(e) { if (e.keyCode == 27 ) { showSidebar(); } }); bodyViewportClasses(); });
function timeline(fps, state){ timeline.base.call(this, state); this._listeners = $.observer(); this._ticks = 0; this.fps(fps || 30); } timeline.prototype = { fps: function(fps){ this._interval = 1000/fps; return this.property("fps", fps); }, interval: function(){ return this.get("interval"); }, listeners: function(){ return this.get("listeners"); }, ticks: function(){ return this.get("ticks"); }, start: function(){ this._state.start(); return this; }, stop: function(){ this._state.stop(); return this; }, add: function(func, scope, id, wait){ var me = this, w = wait || 1, _id = id || $.uid("timeline"), stall = function() { if(!me._ticks % w == 0) return; func(); f = func; }, f = (!wait) ? func : stall; this._listeners.add(f, scope, _id); return this; }, remove: function(id){ this._listeners.remove(id); return this; }, clear: function(){ this._listeners.clear(); return this; }, tick: function(){ this._ticks++; return this; } } $.Class.extend(timeline, $.abstractContext); $.timeline = function(){ return timeline_instance; }
(function() { 'use strict'; moj.Modules.RevealAdditional = { el: '.js-RevealAdditional', init: function() { this.cacheEls(); this.bindEvents(); }, bindEvents: function() { var self = this; this.$select.on('change', function() { self.actuate(this); }); this.$addButton.on('click', function() { self.addVisitor(); }); this.$removeButton.on('click', function() { self.removeVisitor(); }); moj.Events.on('render', $.proxy(this.render, this)); }, cacheEls: function() { this.$select = $(this.el).find('.js-RevealAdditionalSelect'); this.$addButton = $(this.el).find('.js-RevealAdditionalButton'); this.$removeButton = $(this.el).find('.js-HideAdditionalButton'); }, render: function() { var self = this; this.$select.each(function(i, el) { self.actuate(el); }); }, actuate: function(el) { var $el = $(el), targetClass = $el.data('targetEls'), $numToShow = parseInt($el.val(), 10), maxVisitors = $el.data('max-visitors'); $(targetClass).each(function(i, el) { if (i < $numToShow) { $(el).show(); } else { $(el).hide(); $(el).find('input').val(''); } $(el).removeClass('additional-visitor--last'); }); $(targetClass + ':visible').last().addClass('additional-visitor--last'); if (maxVisitors == $numToShow + 1) { this.$addButton.hide(); } else { this.$addButton.show(); } }, addVisitor: function() { var val = parseInt(this.$select.val(), 10); this.$select.val(val + 1).trigger('change'); }, removeVisitor: function() { var val = parseInt(this.$select.val(), 10); this.$select.val(val - 1).trigger('change'); } }; }());
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles({ card: { maxWidth: 345, }, }); function ImgMediaCard() { const classes = useStyles(); return ( <Card className={classes.card}> <CardActionArea> <CardMedia component="img" alt="Contemplative Reptile" height="140" image="/static/images/cards/contemplative-reptile.jpg" title="Contemplative Reptile" /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> Lizard </Typography> <Typography variant="body2" color="textSecondary" component="p"> Lizards are a widespread group of squamate reptiles, with over 6,000 species, ranging across all continents except Antarctica </Typography> </CardContent> </CardActionArea> <CardActions> <Button size="small" color="primary"> Share </Button> <Button size="small" color="primary"> Learn More </Button> </CardActions> </Card> ); } export default ImgMediaCard;
// @flow // noinspection JSUnusedGlobalSymbols export function replaceLn(text: string): Promise<void> { const CLEAR = '\r\x1B[2K\x1B[?7l'; return print(CLEAR + text); } export function printLn(text: string = ''): Promise<void> { return print(text + '\n'); } function print(text: string): Promise<void> { return new Promise((resolve, reject) => { process.stdout.write(text, (err: mixed) => { err ? reject(err) : resolve(); }); }); } export function formatBytes(n: number): string { const {floor, pow, max, abs, log} = Math; let i = floor(log(max(abs(n), 1)) / log(1000)); return i === 0 ? formatNumber(n, 0) + ' B' : formatNumber(n / pow(1000, i), 2) + ' ' + ' KMGTPEZY'[i] + 'B'; } function roundDown(number: number, precision: number): number { let factor = Math.pow(10, precision); return Math.floor(number * factor) / factor; } export function formatNumber( n: number, decimals: number = 0, integers: number = 1, ): string { n = roundDown(n, decimals); return n.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals, minimumIntegerDigits: integers, }); } export function padString(str: string, len: number): string { return str + ' '.repeat(Math.max(0, len - str.length)); } // noinspection JSUnusedGlobalSymbols export function waitIO(): Promise<void> { return new Promise(resolve => { setImmediate(resolve); }); } // noinspection JSUnusedGlobalSymbols export function delay(delayMs: number): Promise<void> { return new Promise(resolve => { setTimeout(resolve, delayMs); }); } export async function trackProgress( func: () => Promise<void>, loop: () => Promise<void>, delayMs: number, ): Promise<void> { let running = false; let id = setInterval(async () => { if (!running) { running = true; await loop(); running = false; } }, delayMs); await func(); clearInterval(id); await loop(); } let nextCid = 1; export function newCid(): number { return nextCid++; } // noinspection JSUnusedGlobalSymbols export function groupBy<Tk, Tv>( items: Iterable<Tv>, fn: Tv => Tk, ): Map<Tk, Tv[]> { let map = new Map(); for (let item of items) { let key = fn(item); let arr = map.get(key); if (arr === undefined) { map.set(key, [item]); } else { arr.push(item); } } return map; } /** Shuffle an array in place */ export function shuffle<T>(a: T[]): void { let n = a.length; // Iterate through all but the last index for (let i = 0; i < n - 1; i++) { // Pick a random index from i to the end of the array let j = i + Math.floor(Math.random() * (n - i)); // Swap this element with the random one let a_i = a[i]; a[i] = a[j]; a[j] = a_i; } } /** Promise.all but without building an array of return values */ export async function waitAll( promises: Iterable<Promise<void>>, ): Promise<void> { for (let promise of promises) { await promise; } } export interface PendingPromise<T> { +resolve: T => void; +reject: mixed => void; } /** * This class is to cap the number of asynchronous jobs entering some code * block or using some resource. Construct it with the maximum number of * concurrent jobs as a parameter, and use <tt>await counter.inc();</tt> to * occupy a slot and <tt>counter.dec();</tt> to return it. */ export class AsyncCap { count: number = 0; queue: PendingPromise<void>[] = []; max: number; constructor(max: number) { this.max = max; } // noinspection JSUnusedGlobalSymbols inc(): Promise<void> { return new Promise((resolve, reject) => { this.queue.push({resolve, reject}); this.run(); }); } // noinspection JSUnusedGlobalSymbols dec(): void { this.count--; this.run(); } run(): void { while (this.queue.length > 0 && this.count < this.max) { this.count++; this.queue.shift().resolve(); } } } // noinspection JSUnusedGlobalSymbols export function partition<T>( items: Iterable<T>, func: T => boolean, ): [T[], T[]] { let t = []; let f = []; for (let item of items) { (func(item) ? t : f).push(item); } return [t, f]; } export function sum<T>(items: Iterable<T>, func: T => number): number { let ret = 0; for (let item of items) { ret += func(item); } return ret; }
import $ from 'jquery'; import PowerSelectMultiple from 'ember-power-select/components/power-select-multiple'; import {action} from '@ember/object'; import {bind} from '@ember/runloop'; import {tagName} from '@ember-decorators/component'; // TODO: convert from jQuery to native DOM const END_ACTIONS = 'click.ghToken mouseup.ghToken touchend.ghToken'; // triggering focus on the search input within ESA's onfocus event breaks the // drag-n-drop functionality in ember-drag-drop so we watch for events that // could be the start of a drag and disable the default focus behaviour until // we get another event signalling the end of a drag @tagName('div') class GhTokenInputSelectMultiple extends PowerSelectMultiple { _canFocus = true; willDestroyElement() { super.willDestroyElement(...arguments); if (this._allowFocusListener) { $(window).off(END_ACTIONS, this._allowFocusListener); } } // actions @action optionMouseDown(event) { if (event.which === 1 && !event.ctrlKey) { this._denyFocus(event); } } @action optionTouchStart(event) { this._denyFocus(event); } @action handleFocus() { if (this._canFocus) { super.handleFocus(...arguments); } } // internal _denyFocus() { if (this._canFocus) { this._canFocus = false; this._allowFocusListener = bind(this, this._allowFocus); $(window).on(END_ACTIONS, this._allowFocusListener); } } _allowFocus() { this._canFocus = true; $(window).off(END_ACTIONS, this._allowFocusListener); this._allowFocusListener = null; } } export default GhTokenInputSelectMultiple;
/** * @license * Copyright 2014 Software Freedom Conservancy * * 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. */ // Copyright 2012 Google Inc. All Rights Reserved. /** * @fileoverview A class representing the string literals. * @author moz@google.com (Michael Zhou) */ goog.provide('wgxpath.Literal'); goog.require('wgxpath.Expr'); /** * Constructs a string literal expression. * * @param {string} text The text value of the literal. * @constructor * @extends {wgxpath.Expr} */ wgxpath.Literal = function(text) { wgxpath.Expr.call(this, wgxpath.DataType.STRING); /** * @type {string} * @private */ this.text_ = text.substring(1, text.length - 1); }; goog.inherits(wgxpath.Literal, wgxpath.Expr); /** * @override * @return {string} The string result. */ wgxpath.Literal.prototype.evaluate = function(context) { return this.text_; }; /** * @override */ wgxpath.Literal.prototype.toString = function() { return 'Literal: ' + this.text_; };