text
stringlengths
2
6.14k
define(function(require, exports, module) { "use strict"; // External dependencies. var _ = require("underscore"); var $ = require("jquery"); var Backbone = require("backbone"); var Albaneagra = require("albaneagra"); // Alias the module for easier identification. var app = module.exports; // The root path to run the application through. app.root = "/"; var albaneagraInit = new Albaneagra({el:$(".content")}); });
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.services' is found in services.js // 'starter.controllers' is found in controllers.js angular.module('starter', ['ionic', 'starter.controllers', 'starter.services']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleLightContent(); } }); }) .config(function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider // setup an abstract state for the tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html" }) // Each tab has its own nav history stack: .state('tab.home', { url: '/home', views: { 'tab-home': { templateUrl: 'templates/tab-home.html', controller: 'HomeCtrl' } } }) /*.state('tab.chats', { url: '/chats', views: { 'tab-chats': { templateUrl: 'templates/tab-chats.html', controller: 'ChatsCtrl' } } }) .state('tab.chat-detail', { url: '/chats/:chatId', views: { 'tab-chats': { templateUrl: 'templates/chat-detail.html', controller: 'ChatDetailCtrl' } } }) .state('tab.account', { url: '/account', views: { 'tab-account': { templateUrl: 'templates/tab-account.html', controller: 'AccountCtrl' } } })*/ .state('tab.checkin', { url: '/checkin', views: { 'tab-checkin': { templateUrl: 'templates/tab-checkin.html', controller: 'CheckInCtrl' } } }) .state('tab.checkout', { url: '/checkout', views: { 'tab-checkout': { templateUrl: 'templates/tab-checkout.html', controller: 'CheckOutCtrl' } } }) .state('tab.search', { url: '/search', views: { 'tab-search': { templateUrl: 'templates/tab-search.html', controller: 'SearchCtrl' } } }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/tab/home'); });
var session = require('./session'); var routes = require('./routes'); var games = require('./games'); module.exports = function(app) { app.http().io(); session(app); routes(app); games(app); }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.BinarySearchIndex = factory(); }(this, function () { 'use strict'; function BinarySearchIndex (values) { this.values = [].concat(values || []); } BinarySearchIndex.prototype.query = function (value) { var index = this.getIndex(value); return this.values[index]; }; BinarySearchIndex.prototype.getIndex = function getIndex (value) { if (this.dirty) { this.sort(); } var minIndex = 0; var maxIndex = this.values.length - 1; var currentIndex; var currentElement; while (minIndex <= maxIndex) { currentIndex = (minIndex + maxIndex) / 2 | 0; currentElement = this.values[Math.round(currentIndex)]; if (+currentElement.value < +value) { minIndex = currentIndex + 1; } else if (+currentElement.value > +value) { maxIndex = currentIndex - 1; } else { return currentIndex; } } return Math.abs(~maxIndex); }; BinarySearchIndex.prototype.between = function between (start, end) { var startIndex = this.getIndex(start); var endIndex = this.getIndex(end); if (startIndex === 0 && endIndex === 0) { return []; } while (this.values[startIndex - 1] && this.values[startIndex - 1].value === start) { startIndex--; } while (this.values[endIndex + 1] && this.values[endIndex + 1].value === end) { endIndex++; } if (this.values[endIndex] && this.values[endIndex].value === end && this.values[endIndex + 1]) { endIndex++; } return this.values.slice(startIndex, endIndex); }; BinarySearchIndex.prototype.insert = function insert (item) { this.values.splice(this.getIndex(item.value), 0, item); return this; }; BinarySearchIndex.prototype.bulkAdd = function bulkAdd (items, sort) { this.values = this.values.concat([].concat(items || [])); if (sort) { this.sort(); } else { this.dirty = true; } return this; }; BinarySearchIndex.prototype.sort = function sort () { this.values.sort(function (a, b) { return +b.value - +a.value; }).reverse(); this.dirty = false; return this; }; return BinarySearchIndex; })); //# sourceMappingURL=binary-search-index.js.map
import * as _ from 'lodash'; const DEFAULT_STATE = [ // { // EM:false, FB:false, TW:false, GO:false, RE: false, IN: false, // PI:false, first_name: 'test', last_name: 'person', picture:[ // { // large: 'http://api.randomuser.me/portraits/men/31.jpg', // medium: 'http://api.randomuser.me/portraits/med/men/31.jpg' // }, // { // large: 'http://api.randomuser.me/portraits/men/27.jpg', // medium: 'http://api.randomuser.me/portraits/med/men/27.jpg' // } // ] // } ]; const existed = (state, action)=> { let a = action.table.map( item =>({ EM:false, FB:false, TW:false, GO:false, RE: false, IN: false, PI:false, ...item })); let replace = _.intersectionBy(state, a , 'key'); let result = _.unionBy(replace, a, 'key'); return result ; } const channel_icon_toggle = (state, action) =>{ let a = [ ...state.slice(0,action.key), { ...state[action.key], [action.channel]:!state[action.key][action.channel] }, ...state.slice(action.key+1) ]; return a; }; const all = (state, action) =>{ let r = state.filter(i=>i[action.channel]===true); let compare = r.length === state.length let a = state.map(item=>{ return { ...item, [action.channel]:!item[action.channel] }}); let b = state.map(item=>{ return { ...item, [action.channel]:true }}); return compare? a: b; }; export default function assist_variables(state = DEFAULT_STATE, action) { return ({ ['populate_Icon_Table_with_existing']: existed, ['channel_icon_toggle']: channel_icon_toggle, ['toggle_icon_all']: all }[action.type] || (s => s))(state, action); }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; import { buttonType, buttonsType } from './constants'; import * as domEvents from './domEvents'; import * as domEventSequences from './domEventSequences'; import { hasPointerEvent, setPointerEvent, platform } from './domEnvironment'; import { describeWithPointerEvent, testWithPointerType } from './testHelpers'; const createEventTarget = (node) => ({ node, /** * Simple events abstraction. */ blur(payload) { node.dispatchEvent(domEvents.blur(payload)); }, click(payload) { node.dispatchEvent(domEvents.click(payload)); }, contextmenu(payload) { domEventSequences.contextmenu(node, payload); }, error() { node.dispatchEvent(domEvents.error()); }, focus(payload) { domEventSequences.focus(node, payload); try { node.focus(); } catch (e) {} }, keydown(payload) { node.dispatchEvent(domEvents.keydown(payload)); }, keyup(payload) { node.dispatchEvent(domEvents.keyup(payload)); }, load(payload) { node.dispatchEvent(domEvents.load(payload)); }, /** * PointerEvent abstraction. * Dispatches the expected sequence of PointerEvents, MouseEvents, and * TouchEvents for a given environment. */ // node no longer receives events for the pointer pointercancel(payload) { domEventSequences.pointercancel(node, payload); }, // node dispatches down events pointerdown(payload) { domEventSequences.pointerdown(node, payload); }, // node dispatches move events (pointer is not down) pointerhover(payload) { domEventSequences.pointerhover(node, payload); }, // node dispatches move events (pointer is down) pointermove(payload) { domEventSequences.pointermove(node, payload); }, // node dispatches enter & over events pointerover(payload) { domEventSequences.pointerover(node, payload); }, // node dispatches exit & leave events pointerout(payload) { domEventSequences.pointerout(node, payload); }, // node dispatches up events pointerup(payload) { domEventSequences.pointerup(node, payload); }, scroll(payload) { node.dispatchEvent(domEvents.scroll(payload)); }, select(payload) { node.dispatchEvent(domEvents.select(payload)); }, // selectionchange is only dispatched on 'document' selectionchange(payload) { document.dispatchEvent(domEvents.selectionchange(payload)); }, /** * Gesture abstractions. * Helpers for event sequences expected in a gesture. * target.tap({ pointerType: 'touch' }) */ tap(payload) { domEventSequences.pointerdown(payload); domEventSequences.pointerup(payload); }, virtualclick(payload) { node.dispatchEvent(domEvents.virtualclick(payload)); }, /** * Utilities */ setBoundingClientRect({ x, y, width, height }) { node.getBoundingClientRect = function () { return { width, height, left: x, right: x + width, top: y, bottom: y + height }; }; } }); const clearPointers = domEventSequences.clearPointers; export { buttonType, buttonsType, clearPointers, createEventTarget, describeWithPointerEvent, platform, hasPointerEvent, setPointerEvent, testWithPointerType };
'use strict' angular.module('myApp.register',['ngRoute']) //Declared ngRoute .config(['$routeProvider', function($routeProvider){ $routeProvider.when('/register',{ templateUrl: 'register/register.html', controller: 'RegisterCtrl' }); }]) //Register controller .controller('RegisterCtrl',[function(){ }]);
/* * Globalize Culture km * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd. */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "km", "default", { name: "km", englishName: "Khmer", nativeName: "ខ្មែរ", language: "km", numberFormat: { pattern: ["- n"], groupSizes: [3,0], "NaN": "NAN", negativeInfinity: "-- អនន្ត", positiveInfinity: "អនន្ត", percent: { pattern: ["-n%","n%"], groupSizes: [3,0] }, currency: { pattern: ["-n$","n$"], symbol: "៛" } }, calendars: { standard: { "/": "-", days: { names: ["ថ្ងៃអាទិត្យ","ថ្ងៃច័ន្ទ","ថ្ងៃអង្គារ","ថ្ងៃពុធ","ថ្ងៃព្រហស្បតិ៍","ថ្ងៃសុក្រ","ថ្ងៃសៅរ៍"], namesAbbr: ["អាទិ.","ច.","អ.","ពុ","ព្រហ.","សុ.","ស."], namesShort: ["អា","ច","អ","ពុ","ព្","សុ","ស"] }, months: { names: ["មករា","កុម្ភៈ","មិនា","មេសា","ឧសភា","មិថុនា","កក្កដា","សីហា","កញ្ញា","តុលា","វិច្ឆិកា","ធ្នូ",""], namesAbbr: ["១","២","៣","៤","៥","៦","៧","៨","៩","១០","១១","១២",""] }, AM: ["ព្រឹក","ព្រឹក","ព្រឹក"], PM: ["ល្ងាច","ល្ងាច","ល្ងាច"], eras: [{"name":"មុនគ.ស.","start":null,"offset":0}], patterns: { d: "yyyy-MM-dd", D: "d MMMM yyyy", t: "H:mm tt", T: "HH:mm:ss", f: "d MMMM yyyy H:mm tt", F: "d MMMM yyyy HH:mm:ss", M: "'ថ្ងៃទី' dd 'ខែ' MM", Y: "'ខែ' MM 'ឆ្នាំ' yyyy" } }, Gregorian_TransliteratedEnglish: { name: "Gregorian_TransliteratedEnglish", days: { names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesShort: ["أ","ا","ث","أ","خ","ج","س"] }, months: { names: ["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر",""], namesAbbr: ["يناير","فبراير","مارس","ابريل","مايو","يونيو","يوليو","اغسطس","سبتمبر","اكتوبر","نوفمبر","ديسمبر",""] }, AM: ["ព្រឹក","ព្រឹក","ព្រឹក"], PM: ["ល្ងាច","ល្ងាច","ល្ងាច"], eras: [{"name":"م","start":null,"offset":0}], patterns: { d: "MM/dd/yyyy", t: "H:mm tt", T: "HH:mm:ss", f: "dddd, MMMM dd, yyyy H:mm tt", F: "dddd, MMMM dd, yyyy HH:mm:ss" } } } }); }( this ));
const mongoose = require('mongoose'); exports.connectToDB = () => { /** * Connect to MongoDB. */ mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI); mongoose.connection.on('error', () => { console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗')); process.exit(); }); }
var throttle = function (fn, delay, atleast) { var timer = null; var previous = null; return function () { var now = +new Date(); if ( !previous ) previous = now; if ( atleast && now - previous > atleast ) { fn(); // 重置上一次开始时间为本次结束时间 previous = now; clearTimeout(timer); } else { clearTimeout(timer); timer = setTimeout(function() { fn(); previous = null; }, delay); } } };
const gulp = require('gulp'); const minify = require('gulp-uglify'); const watch = require('gulp-watch'); const rename = require('gulp-rename'); const replace = require('gulp-replace'); const connect = require('gulp-connect'); const settings = require('./package.json').settings; const source = "javascript:(function(){var newScript = document.createElement('script');newScript.src='<%=protocol%>://localhost:<%=port%>/<%=js%>?hoge='+ Math.random();document.body.appendChild(newScript);})();"; const fs = require('fs'); gulp.task("default", function () { let string = source.replace("<%=port%>", settings.port); const protocol = settings.https ? "https" : "http"; if (settings.https) { connect.server({ root: settings.dist, port: settings.port, https: true }); } else { connect.server({ root: settings.dist, port: settings.port }); } string = string.replace("<%=js%>", settings.js); string = string.replace("<%=protocol%>", protocol); fs.writeFile('bookmarklet.js', string); });
var searchData= [ ['texture',['Texture',['../classqe_1_1core_1_1_texture.html',1,'qe::core']]], ['texture2d',['Texture2D',['../classqe_1_1core_1_1_texture2_d.html',1,'qe::core']]], ['textureload',['TextureLoad',['../classqe_1_1resource_1_1_texture_load.html',1,'qe::resource']]], ['thread',['Thread',['../classqe_1_1render_1_1vulkan_1_1_thread.html',1,'qe::render::vulkan']]], ['time',['Time',['../classqe_1_1core_1_1_time.html',1,'qe::core']]], ['transform',['Transform',['../classqe_1_1core_1_1_transform.html',1,'qe::core::Transform'],['../classqe_1_1core_1_1_transform.html#a8868fe0f50f710e986e24e2179679248',1,'qe::core::Transform::Transform()']]] ];
'use strict'; angular. module('createAccount', []);
jQuery(document).ready(function($) { //ACCIONES INICIALES //Maneja el fondo de la página $.backstretch("./img/fondo1.jpg"); $('.tooltiptalk').tooltipster({ theme: '.tooltipster-light' }); $('.contenedorDerecha').addClass('animated fadeInUpBig'); });
const Joi = require('joi'); const customerDb = require('./customers.js'); let customersController = {}; let customers = []; customersController.getConfig = { handler: function(req, reply) { if (req.params.id) { const foundCustomer = customerDb.get(req.params.id); if (foundCustomer === null) return reply('Customer not found.').code(404); return reply(foundCustomer); } reply(customerDb.getAll()); } }; customersController.loadMockConfig = { handler: function(req, reply) { customerDb.loadMockData(); return reply({success: true}); } }; customersController.clearAllData = { handler: function(req, reply) { customerDb.clear(); return reply({success: true}); } }; module.exports = customersController;
// Setup namespaces pi = pi||{}; pi.mobile = pi.mobile||{}; pi.mobile.ui = pi.mobile.ui||{}; // Store the original pi.mobile.ui.ListView = kendo.mobile.ui.ListView; // Extend and replace the original kendo.mobile.ui.ListView = pi.mobile.ui.ListView.extend({ init : function(element,options) { pi.ui.Widget.attributeOptions.apply(this,arguments); this._configure(element,options); pi.mobile.ui.ListView.fn.init.apply(this,arguments); // It's not documented, but ListView accepts a pullOffset options value. It just doesn't pass it to the Scroller. if (this.options.pullOffset < 0) { this._scrollerInstance.setOptions({ pullToRefresh: this.options.pullToRefresh, // pullToRefresh must exist to set pullOffset! pullOffset: this.options.pullOffset }) } }, _configure : function(element,options) { if (typeof(options.dataSource) == "undefined" || typeof(options.template) != "undefined") return; var headerTemplate = $(element), template; if (headerTemplate.prop("tagName").toUpperCase() == "UL") { headerTemplate = headerTemplate.children("li").first(); template = headerTemplate.children("ul"); if (!template.length) { options.template = headerTemplate.html(); } else { template.detach(); options.headerTemplate = headerTemplate.html(); options.template = template.children("li").html(); } } else { options.template = headerTemplate.html(); } } }); // The auto-widget creation is based on the kendo.mobile.ui.roles registry, so don't forget to update this! kendo.mobile.ui.roles.listview = kendo.mobile.ui.ListView;
'use strict'; import React, {Component} from 'react'; import { StyleSheet, Text, View, DrawerLayoutAndroid, ScrollView } from 'react-native'; import { Subheader, COLOR, PRIMARY_COLORS } from 'react-native-material-design'; import Navigation from '../Navigation'; import { strings } from '../../strings'; import Global from 'SpringFitnessMobile/src/globals/global'; class AboutPage extends Component { render() { return ( <DrawerLayoutAndroid drawerWidth={300} drawerPosition={DrawerLayoutAndroid.positions.left} renderNavigationView={() => { return (<Navigation />); }} > <View style={styles.container}> <ScrollView> <Subheader text={strings.about.aboutHeading} color='paperBlue'/> <Text>Something about the application.</Text> <Subheader text='Privacy policy' color='paperBlue' /> <Text>Something about a privacy policy.</Text> </ScrollView> </View> </DrawerLayoutAndroid> ) } } const styles = StyleSheet.create({ container: { flex: 1, //justifyContent: 'center', backgroundColor: '#fafafa', }, }); export default AboutPage;
'use strict'; const Queue = require('./queue'); module.exports = Queue;
import css from 'css' import md5 from 'spark-md5' import _ from 'lodash' const symbols = { '.': '', '#': '_' } function hash(val, hashLength) { return md5.hash(val).slice(0, hashLength) } export default function wapCss(styles, hashLength = 6, hashString = styles) { try { var ast = css.parse(styles) } catch(e) { console.log(e) } let sheet = ast.stylesheet, res = [], transformations = {}, filePrefix = hash(hashString, hashLength), ignoreBlock = false sheet.rules.forEach(parseRule) return { transformations: transformations, css: css.stringify(ast) } function parseRule (rule, i) { let type = rule.type, selectors = rule.selectors, rules = rule.rules, processed = [] if (rules && rules.length) rules.forEach(parseRule) if (!selectors || !selectors.length) return checkIgnoreState(rule) for (let i = 0; i < selectors.length; i++) { let selector = selectors[i] processed.push(transformSelector(selector)) } rule.selectors = processed } function addTransformation(key, value) { if (!transformations[key]) transformations[key] = value } function checkIgnoreState(rule) { if (rule.type != 'comment') return let comment = rule.comment, reStart = /wapCss.ignore.start/, reEnd = /wapCss.ignore.end/ if (reStart.test(comment)) ignoreBlock = true if (reEnd.test(comment)) ignoreBlock = false } function getTransformation(key) { return transformations[key] } function transformSelector(selector) { let partsToTransform = selector.match(/(:global?|)[\.#][A-Za-z0-9_\-]+/g) if (!partsToTransform || !partsToTransform.length) return selector partsToTransform = partsToTransform.sort().reverse() for (let i = 0; i < partsToTransform.length; i++) { let partToTransform = partsToTransform[i] const isGlobal = /^:global/.test(partToTransform) partToTransform = isGlobal ? partToTransform.replace(/^:global/, '') : partToTransform let part = partToTransform.substr(1), prefix = partToTransform[0], transformedPrefix = transformPrefix(prefix), transformedPart = getTransformation(transformPrefix + part) || transformPart(part) if (ignoreBlock || isGlobal) transformedPart = part addTransformation(transformedPrefix + part, transformedPart) selector = selector.replace((isGlobal ? ':global' : '') + prefix + part, prefix + transformedPart) } return selector } function transformPrefix(prefix) { return symbols[prefix] } function transformPart(part) { return `_${filePrefix}-${part}` } }
import { mount, h } from '../../dist/src'; const Greeter = (props) => h("p", { lang: props.lang }, `${props.hello} ${props.world}!`); const main = document.getElementById('main'); mount(h(Greeter, { lang: "fr", hello: "Bonjour", world: "monde" }), {}, main);
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | origami index', function(hooks) { setupRenderingTest(hooks); test('it renders', async function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); await render(hbs`{{origami-index}}`); assert.dom('*').hasText(''); // Template block usage: await render(hbs` {{#origami-index}} template block text {{/origami-index}} `); assert.dom('*').hasText('template block text'); }); });
(function () { 'use strict'; /** * @ngdoc directive * @name scUserProfile * @restrict E * @scope * @description * * The directive for the signup. */ angular .module('scSignup') .directive('scSignup', SignupDirective); SignupDirective.$inject = []; function SignupDirective() { return { restrict: 'E', templateUrl: 'components/userManagement/signup/signup.tpl.html', controllerAs: 'signupCtrl', controller: 'scSignupController', scope: '=', bindToController: true }; } })();
const MissingConfigError = require('./errors/missing'); const UnreadableConfigError = require('./errors/unreadable'); const fs = require('fs'); const CONFIG_FILES = [ '.es-cli', '.es-cli.js', '.es-cli.json' ]; const FILE_PATTERN = /\.es\-cli(\.json|\.js)?/i; function getConfiguration(directory) { let files = fs.readdirSync(directory).filter(filterFile).sort(); if(files.length === 0) { throw new MissingConfigError(directory); } let path = `${ directory }/${ files[0] }`; try { return require(path); } catch (e) { throw new UnreadableConfigError(path); } } function filterFile(fileName) { return fileName.match(FILE_PATTERN); } module.exports = { getConfiguration: getConfiguration, files: CONFIG_FILES };
// navigator.module.js define([ 'angular' ], function (ng) { 'use strict'; return ng .module('app.navigator', []); });
// @flow // Copyright (c) 2016 Uber Technologies, 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. import * as constants from '../constants'; import LegacySamplerV1Base from './_adapt_sampler'; export default class ConstSampler extends LegacySamplerV1Base implements LegacySamplerV1 { _decision: boolean; constructor(decision: boolean) { super('ConstSampler'); this._decision = decision; } name(): string { return 'ConstSampler'; } toString(): string { return `${this.name()}(${this._decision ? 'always' : 'never'})`; } get decision(): boolean { return this._decision; } isSampled(operation: string, tags: any): boolean { if (this._decision) { tags[constants.SAMPLER_TYPE_TAG_KEY] = constants.SAMPLER_TYPE_CONST; tags[constants.SAMPLER_PARAM_TAG_KEY] = this._decision; } return this._decision; } equal(other: LegacySamplerV1): boolean { if (!(other instanceof ConstSampler)) { return false; } return this.decision === other.decision; } }
/* This script generates mock data for local development. This way you don't have to point to an actual API, but you can enjoy realistic, but randomized data, and rapid page loads due to local, static data. */ /* eslint-disable no-console */ import jsf from 'json-schema-faker'; import {schema} from './mockDataSchema'; import fs from 'fs'; import {chalkError, chalkSuccess} from './chalkConfig'; const json = JSON.stringify(jsf(schema)); fs.writeFile("./src/api/db.json", json, function (err) { if (err) { return console.log(chalkError(err)); } else { console.log(chalkSuccess("Mock data generated.")); } });
module.exports = { name: 'rag', description: '', example_data: '[ { "value": 3, "text": "5XX" }, { "value": 12, "text": "4XX" }, { "value": 87, "text": "200 Status Code" } ]', validate: function(data) { if (Array.isArray(data) && data.length > 0) { for (var i=0; i<data.length-1; i++) { if (typeof data[i].value === 'undefined' || typeof data[i].text === 'undefined') return false } return true; } return false; }, format: function(data) { var result = [], elements = data.length; if (elements > 3) elements = 3; for (var i=0; i<=elements-1; i++) { var item = { text: data[i].text, value: 0 }; try { item.value = parseInt(data[i].value, 10); } catch (e) {} result.push(item); } return result; } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Contains all information about entity's foreign key. */ var ForeignKeyMetadata = (function () { // --------------------------------------------------------------------- // Constructor // --------------------------------------------------------------------- function ForeignKeyMetadata(options) { /** * Array of columns of this foreign key. */ this.columns = []; /** * Array of referenced columns. */ this.referencedColumns = []; /** * Gets array of column names. */ this.columnNames = []; /** * Gets array of referenced column names. */ this.referencedColumnNames = []; this.entityMetadata = options.entityMetadata; this.referencedEntityMetadata = options.referencedEntityMetadata; this.columns = options.columns; this.referencedColumns = options.referencedColumns; this.onDelete = options.onDelete; if (options.namingStrategy) this.build(options.namingStrategy); } // --------------------------------------------------------------------- // Public Methods // --------------------------------------------------------------------- /** * Builds some depend foreign key properties. * Must be called after all entity metadatas and their columns are built. */ ForeignKeyMetadata.prototype.build = function (namingStrategy) { this.columnNames = this.columns.map(function (column) { return column.databaseName; }); this.referencedColumnNames = this.referencedColumns.map(function (column) { return column.databaseName; }); this.tableName = this.entityMetadata.tableName; this.referencedTableName = this.referencedEntityMetadata.tableName; this.name = namingStrategy.foreignKeyName(this.tableName, this.columnNames, this.referencedEntityMetadata.tableName, this.referencedColumnNames); }; return ForeignKeyMetadata; }()); exports.ForeignKeyMetadata = ForeignKeyMetadata; //# sourceMappingURL=ForeignKeyMetadata.js.map
import React from "react"; import Link from "gatsby-link"; import Helmet from "react-helmet"; import Nav from "../../components/Nav"; import Title from "../../components/Title"; import Item from "../../components/Item"; import A from "../../components/A"; import Quote from "../../components/Quote"; import Outro from "../../components/Outro"; const IssueContent = () => ( <main className="bg-white mt5 mb6"> <div className="w-50-l w-70-m w-90 center"> <Link to="/" className="link dim blue fw5"> ← Home </Link> <Title>Issue 01</Title> <div className="pb4 bb b--black-20 f5 lh-copy"> <p>You're reading the very first issue of Design Systems Digest 🎉</p> <p> I’ll be keeping an ear to the ground on what is happening in the colliding worlds of design systems, styleguides and front-end architecture and sharing a few links per week that I believe are worth your time. The surface area of these topics blurs the lines between design and engineering, and the content of this newsletter will reflect this. </p> <p>Without further ado:</p> </div> <Item headline="Integrating Animation into a Design System [Article]" href="https://alistapart.com/article/integrating-animation-into-a-design-system" > Motion is often introduced to a project in an ad hoc fashion. This article provides a solid foundation for the process of transitioning your menagerie of animations into a cohesive system. It’s packed with practical tips and examples from some of the most robust design systems in the wild. </Item> <Item headline="Introducing Design Systems Into Chaos [Talk]" href="https://www.rethinkhq.com/videos/introducing-design-systems-into-chaos-diana-mounter-github" > <p> Diana Mounter leads GitHub’s design systems team, who are responsible for building and maintaining the Primer CSS framework. She gives a detailed and insightful run-down of how GitHub began introducing some order back into their system after accumulating almost 10 years of diverging styles and approaches. </p> <p> One of the key takeaways from her experience is that it’s never too early to get started on this process — I’m sure many designers and engineers working on less mature products will have gleamed some encouragement from this. </p> </Item> <Item headline="Thinking in Symbols for Universal Design [Talk]" href="https://www.rethinkhq.com/videos/thinking-in-symbols-for-universal-design-benjamin-wilkins-aribnb" > <p> Ben Wilkinson is Design Systems Lead at Airbnb. In this talk he takes us through the approach taken by Airbnb’s Design Language System (DLS); a flat component structure where each component is specific and named accordingly. The worked examples are especially valuable to those working with React or other component-based frameworks. </p> <Quote>Our components are the vocabulary of our design system.</Quote> </Item> <Item headline="Building a Design System for HealthCare.gov [Article]" href="https://blog.navapbc.com/healthcare-gov-design-system-fc27964a14c9" > <p> Focusing on the technical side of the{" "} <A href="">HealthCare.gov design system</A> project, this piece takes a look at the decisions made regarding architecture, documentation, developer workflow, audits, and distribution. </p> </Item> <Item headline="Design Tools are Running Out of Track [Article]" href="https://medium.freecodecamp.org/design-tools-are-running-out-of-track-94f21b6ae939" > <p> Colm Tuite dissects a number of problems with the current state of mainstream design tooling - primarily, the fact that our tools export to images, instead of resembling the fluid and interactive context of our products. Jon Gold’s piece{" "} <A href="http://jon.gold/2017/08/dragging-rectangles/"> Dragging Rectangles </A>{" "} is another great read on the topic. </p> <p> What’s really exciting is the next generation of tooling focused on solving this fundamental problem — the most interesting projects in this space are teased at the end of the piece. </p> </Item> <Item headline="Writing Scalable React Apps with the Component Folder Pattern [Tutorial]" href="https://medium.com/styled-components/component-folder-pattern-ee42df37ec68" > <p> Breaking down complex pieces of a UI into bite sized and logical units of work is always a challenge. The component folder pattern is a handy approach to have up your sleeve to help organise your directory structure and make your components easier to understand and maintain. </p> </Item> <Outro /> </div> </main> ); const Issue01 = () => ( <div> <Helmet title="Issue 01 | Design Systems Digest" /> <Nav /> <IssueContent /> </div> ); export default Issue01;
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('enrichment', 'Enrichment', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function() { var model = this.subject(); // var store = this.store(); ok(!!model); });
var Vue = require('vue'); var classes = require('../data/classes'); var TextEditor = Vue.extend({ template: '<div class="col span_2_of_12">' + '<label>Content</label>' + '<a href="#" class="ui-button" v-on:click.prevent="openUploadImage"><span class="ui-button-text">Open</span></a><br/>' + '<small v-text="url"></small>' + '</div>' + '<div class="col span_2_of_12 InputfieldCheckboxes">' + '<label>Class</label>' + '<select v-model="active_item.class">' + '<option v-for="class in classes">{{class}}</option>' + '</select>' + '</div>', replace: true, props : ['page_id', 'active_item', 'remove-item'], data: function () { return { url : '', classes : config.custom_classes || classes } }, methods : { openUploadImage : function(e) { var that = this; loadIframeImagePicker(this.page_id, function(src, width, height) { that.url = src; that.active_item.options.src = src; that.active_item.style.width = width + 'px'; that.active_item.style.height = height + 'px'; }); } } }); Vue.component('text-editor', TextEditor); module.exports = TextEditor;
var jwt = require('jwt-simple'); var moment = require('moment'); var secret = '1234567890'; var User = require('../models/user'); var Token = require('../models/token'); // operations with tokens module.exports = { // checks if the token is valid validToken: function (jwtToken, done) { Token.findOne({ token: jwtToken }, function (err, token) { if (err) { return done(err); } if (!token) { return done(null, false); } if (token.expire < moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')) { return done(null, false); } User.findById(token.userId, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } var decoded = jwt.decode(jwtToken, secret); if (decoded.userId == user._id) { done(null, true); } else { done(null, false); } }) }); }, // if the user already has a token, extend the token and getToken: function (user, done) { Token.findOne({ userId: user._id, expire: { $gt: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') } }, function (err, token) { if (err) { done(err) } var expire = moment(Date.now()).add(1, 'days').format('YYYY-MM-DD HH:mm:ss'); if (token) { // this extention is to not deal with expired tokens // possible db fluding of expired tokens Token.update(token, { expire: expire }); done(null, token); } else { var token = new Token(); token.token = jwt.encode({ userId: user._id }, secret); token.expire = expire; token.userId = user._id; Token.create(token, function (err, result) { if (err) { done(err); } else { done(null, token); } }); } }) } }
export class ToFormattedNumberValueConverter { toView(value) { return value.toLocaleString(); } }
import { find, click, waitUntil, waitFor } from '@ember/test-helpers'; const SWAL_CONTAINER = '.swal2-container'; const SWAL_CONFIRM = '.swal2-confirm'; const SWAL_CANCEL = '.swal2-cancel'; /** * Wait for Sweet Alert to open. * * @public * @return {Promise<void>} resolves when settled. */ export async function waitForOpen() { await waitFor(SWAL_CONTAINER); } /** * Wait for Sweet Alert to close. * * @public * @return {Promise<void>} resolves when settled. */ export async function waitForClose() { await waitUntil(() => false === Boolean(find(SWAL_CONTAINER))); } /** * Click the specified target and wait for Sweet Alert to open. * * @public * @param {string|Element} target the element or selector to click on. * @return {Promise<void>} resolves when settled. */ export async function open(target) { await click(target); await waitForOpen(); } /** * Click the Sweet Alert confirm element. * * @public * @return {Promise<void>} resolves when settled. */ export async function confirm() { await click(SWAL_CONFIRM); } /** * Click the Sweet Alert confirm element and wait for Sweet Alert to close. * * @public * @return {Promise<void>} resolves when settled. */ export async function confirmAndClose() { await confirm(); await waitForClose(); } /** * Click the Sweet Alert cancel element. * * @public * @return {Promise<void>} resolves when settled. */ export async function cancel() { await click(SWAL_CANCEL); } /** * Click the Sweet Alert cancel element and wait for Sweet Alert to close. * * @public * @return {Promise<void>} resolves when settled. */ export async function cancelAndClose() { await cancel(); await waitForClose(); }
import React from 'react'; import { func } from 'prop-types'; export default class AddPlayerForm extends React.Component { static propTypes = { onPlayerCreate: func.isRequired }; state = { name: '' }; onNameChange(event) { this.setState({ name: event.target.value }); } onSubmit() { this.props.onPlayerCreate(this.state.name); this.setState({ name: '' }); } render() { return ( <div className="form-inline"> <div className="form-group"> <input type="text" placeholder="New Player" value={this.state.name} onChange={this.onNameChange.bind(this)} className="form-control" /> </div>&nbsp; <button onClick={this.onSubmit.bind(this)} className="btn btn-default">Add</button> </div> ); } }
'use strict'; /** * Proc - a common library to spawn detached child processes */ var spawn = require('child_process').spawn; var fs = require('fs'); var out = fs.openSync('./out.log', 'a'); module.exports = make(file) { var child = spawn(__dirname + '/' + file, [], { cwd : __dirname, detached : true, stdio : ['ignore', out, out] }); child.unref(); // Write the PID into the pid folders with a random name var filename = Math.random() * (2000 - 1000) + 1000; fs.writeSync(__dirname + '/pid/' + filename + '.pid', child.pid, 'utf8'); return child; }
import { MonteError } from './MonteError'; export class MonteOptionError extends MonteError { static RequiredOption(optionName, ...msgs) { return new MonteOptionError(`Option "${optionName}" is required.`, ...msgs); } static InvalidEnumOption(optionName, badValue, ...msgs) { return new MonteOptionError(`Option "${optionName}" must be set to a valid option. The value "${badValue}" is not valid.`, ...msgs); } static OptionMustBeFunction(optionName, ...msgs) { return new MonteOptionError(`Option "${optionName}" must be a function.`, ...msgs); } }
/** * Day 7 * Basic pan gesture */ 'use strict'; import React,{ Component } from 'react'; import { Image,StyleSheet,StatusBar,Text,TouchableHighlight,PanResponder,View } from 'react-native'; import Util from './utils'; import Icon from 'react-native-vector-icons/Ionicons'; class MoveableCircle extends Component{ constructor() { super(); this.state = { color: "rgba(255,255,255,0.7)", }; } _previousLeft = Util.size.width/2-40; _previousTop = Util.size.height/2-50; _maxTop = Util.size.height-110; _maxLeft = Util.size.width-98; _circleStyles = {}; circle = (null : ?{ setNativeProps(props: Object): void }); _updatePosition() { this.circle && this.circle.setNativeProps(this._circleStyles); } _endMove(evt, gestureState) { this._previousLeft += gestureState.dx; this._previousTop += gestureState.dy; this.setState({ color: "rgba(255,255,255,0.7)" }); } componentWillMount() { this._panResponder = PanResponder.create({ onStartShouldSetPanResponder: (evt, gestureState) => true, onStartShouldSetPanResponderCapture: (evt, gestureState) => true, onMoveShouldSetPanResponder: (evt, gestureState) => true, onMoveShouldSetPanResponderCapture: (evt, gestureState) => true, onPanResponderGrant: (evt, gestureState) => { this.setState({ color: "white", }) }, onPanResponderMove: (evt, gestureState) => { this._circleStyles.style.left = this._previousLeft + gestureState.dx; this._circleStyles.style.top = this._previousTop + gestureState.dy; if (this._circleStyles.style.left<0) { this._circleStyles.style.left = 0; }; if (this._circleStyles.style.top<5) { this._circleStyles.style.top = 5; }; if (this._circleStyles.style.left>this._maxLeft) { this._circleStyles.style.left = this._maxLeft; }; if (this._circleStyles.style.top>this._maxTop) { this._circleStyles.style.top = this._maxTop; }; this._updatePosition(); }, onPanResponderTerminationRequest: (evt, gestureState) => true, onPanResponderRelease: (evt, gestureState) => this._endMove(evt, gestureState), onPanResponderTerminate: (evt, gestureState) => this._endMove(evt, gestureState), }); this._circleStyles = { style: { left: this._previousLeft, top: this._previousTop, }, }; } componentDidMount() { this._updatePosition(); } render() { return( <View ref={(circle) => {this.circle = circle;}} style={styles.MoveableCircle} {...this._panResponder.panHandlers}> <Icon ref="baseball" name="ios-baseball" color={this.state.color} size={120}></Icon> </View> ) } } export default class extends Component{ componentWillMount() { StatusBar.setBarStyle(1); } render() { return( <View style={styles.container}> <Image source={require('image!agrass')} style={styles.bg}></Image> <View style={styles.circleContainer}> <MoveableCircle></MoveableCircle> </View> </View> ) } } const styles = StyleSheet.create({ container:{ height:Util.size.height, width: Util.size.width }, bg:{ width: Util.size.width, resizeMode:"stretch", position:"absolute" }, circleContainer:{ height:Util.size.height, width: Util.size.width, }, MoveableCircle:{ backgroundColor:"transparent", position:"absolute", left:0, right:0 }, });
/** * Created by cold on 2/15/14. */ (function () { 'use strict'; var logger; /** * The Application class * * @constructor */ logger = function () { }; logger.prototype.bootstrap = function() { }; logger.prototype.log = function(message) { if(typeof(window.console) !== 'Object') { return this; } console.log(message); return this; } Eiw.logger = logger; }());
import React from "react"; import Header from "../header"; import logo from "common/assets/logo/visual-studio-code.svg"; export default function() { return ( <Header header="Visual Studio Code" text="A warrior is worthless unless he rises above others and stands strong in the midst of a storm." logo={logo} /> ); }
import ElectronSettings from 'electron-settings'; import { ipcRenderer } from 'electron'; let settings = new ElectronSettings( { configFileName : 'npm-app' } ); const state = { all : settings.get( 'repos' ) || [] }; const mutations = { ADD_REPO ( state, repo ) { state.all = [ ...state.all, repo ]; settings.set( 'repos', state.all ); ipcRenderer.send( 'updatedRepos', JSON.stringify( state.all ) ); }, REMOVE_REPO_WITH_INDEX ( state, repoIndex ) { state.all = state.all.filter( ( repo, index ) => index !== repoIndex ); settings.set( 'repos', state.all ); ipcRenderer.send( 'updatedRepos', JSON.stringify( state.all ) ); }, UPDATED_REPOS( state, repos ) { state.all = repos; } }; export default { state, mutations };
var postTemplate = _.template( '<div class="post" data-id="<%= id %>" >' + '<div><%= text %></div>' + '<button class="close">&times;</button>' + '</div>' ); function deletePost(postDiv, postID) { $.ajax({ url: '../post/' + postID, type: 'DELETE', success: function() { $(postDiv).remove(); } }); } function newPost(post) { $('#statuses').prepend(postTemplate(post)); $('#statuses').find('.post:first .close').click(function(e) { e.preventDefault(); var postDiv = $(e.currentTarget).parent('.post')[0]; var postID = $(postDiv).data('id'); deletePost(postDiv, postID); }); } $(function() { $('#new-status').submit(function(e) { e.preventDefault(); $.ajax({ url: '../post', type: 'POST', dataType: 'json', data: { text: $(this).find('textarea').val() }, success: function(post) { newPost(post); $('#new-status').find('textarea').val(''); } }); }); $.get('../post', function(posts) { for(var i = 0; i < posts.length; ++i) { newPost(posts[i]); } }); });
import sgfs from './sgfs'; import pgns from './pgns'; import users from './users'; import gogames from './gogames'; import chessgames from './chessgames'; import email from './email'; export default function () { sgfs(); pgns(); users(); gogames(); chessgames(); email(); }
var _ = require("lodash"); module.exports = function(ast, comp, e){ if(!ast.action){ throw new Error("Missing RuleAction.action"); } if(ast.action.type !== "Identifier" && ast.action.type !== "DomainIdentifier"){ throw new Error("Unsuported RuleAction.action"); } return e("ycall", e("id", "runAction"), [ e("id", "ctx"), ast.action.domain ? e("str", ast.action.domain, ast.action.loc) : e("void", e("number", 0)), e("str", ast.action.value), comp(ast.args), e("array", _.map(ast.setting, function(set){ return e("str", set.value, set.loc); })), ]); };
import React, { Component } from 'react'; import { View } from 'react-native'; import { AdMobBanner } from 'react-native-admob'; export default class AdvertisementBanner extends Component { constructor(props) { super(props); this.state = { hide: false } } bannerErrorHandler = (e) => { console.log(e); }; componentDidMount() { setTimeout(() => { this.setState(() => ({ hide: true })); }, 20000); } render() { if (this.props.hide && this.state.hide) return null; return ( <View> <AdMobBanner adSize="fullBanner" adUnitID={this.props.adUnitID} onAdFailedToLoad={this.bannerErrorHandler} /> </View> ); } }
var exec = require('child_process').exec var Player = function (id, opts) { this.id = id this.engine = null this.options = opts this.loadEngine() } Player.prototype = { loadEngine: function () { var Engine = null console.log('Loading player...') if (this.id.toLowerCase() === 'vlc') { Engine = require('./players/VLCPlayer') console.log('VLCPlayer loaded.') this.engine = new Engine(this.options) return } throw new Error('Unknow player: ' + this.id) }, execute: function () { var commandLine = this.engine.getCommandLine() console.log('Player cmd: ', commandLine) exec(commandLine, function () { console.log('Player closed') process.exit() }) } } module.exports = Player
var EtherPortClient = require('etherport-client').EtherPortClient; var five = require('johnny-five'); var board = new five.Board({ port: new EtherPortClient({ host: "192.168.192.117", port: 3030 }), timeout: 1e5, repl: false }); board.on("ready", function() { console.log('Board is ready!'); var servo = new five.Servo({ pin: 2, startAt: 90, range: [0, 180], //center: true, debug: true }); var control = new five.Sensor({ pin: "A0", freq: 250 }); control.on("data", function() { console.log('Value: ', this.value, ', Raw: ', this.raw); }); control.on("change", function() { var controlValue = this.scaleTo(0, 180); servo.to(controlValue); }); });
var Bloom = require("./index.js"); var bloom = new Bloom(); bloom.add("http://www.baidu.com"); bloom.add("http://omy2do.com"); console.log(bloom.exist("http://www.baidu.com")); // true console.log(bloom.exist("http://github.com")); //false
// VENDOR LIBS const path = require('path'); const config = requireFromModule('config'); gulp.task('icons', function () { return gulp.src([ path.join(process.env.NODE_PATH, 'node_modules/material-design-icons/iconfont/*') ]).pipe(gulp.dest(path.join(config.dist, config.fonts.dest))) });
export default function() { return { types: ['invoke'], enter: function(node) { var namelist = node.namelist; if (namelist && namelist.length) { namelist.forEach(function(name) { node.children.push({ type: 'param', data: {}, position: node.position, // TODO get the actual position name: name, _code: { expr: { type: 'expression', value: name, }, }, }) }); } delete node.namelist; return node; } }; };
function Foo() { s = 1; getName = function () { console.log (1); }; return this; } Foo.getName = function () { console.log (2);}; Foo.prototype.getName = function () { console.log (3);}; // var getName = function () { console.log (4);}; // function getName() { console.log (5);} console.log(new Foo()) // Foo().getName() new Foo().getName() // console.log(Foo()) // Foo.getName() // new Foo().getName() // // Foo.getName(); // getName(); // getName() // getName(); // new Foo.getName(); // new Foo().getName(); // new new Foo().getName();
(function ($) { new WOW().init(); jQuery(window).load(function() { jQuery("#preloader").delay(100).fadeOut("slow"); jQuery("#load").delay(100).fadeOut("slow"); }); //jQuery to collapse the navbar on scroll $(window).scroll(function() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); //jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('.navbar-nav li a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); $('.page-scroll a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); //JQuery for changing the background $(function() { setInterval(function(){ //randomize bg#.jpg var rndm = Math.floor(Math.random() * 5) + 1; var image = $('.intro'); image.fadeOut(1000, function () { image.css("background", "url('./img/bg"+rndm+".jpg') no-repeat top center"); image.fadeIn(1000); }) //set the bg to the .intro css class //$('.intro').css("background", "url('./img/bg"+rndm+".jpg') no-repeat top center"); }, 15000); }); })(jQuery);
import * as ui from 'actions/ui_actions'; describe( 'ui actions', () => { it( 'should have types', () => { expect( ui.TYPES ).toBeDefined(); } ); it( 'should set addressbar selected', () => { const expectedAction = { type : ui.TYPES.SELECT_ADDRESS_BAR }; expect( ui.selectAddressBar( ) ).toEqual( expectedAction ); } ); it( 'should set addressbar deselected', () => { const expectedAction = { type : ui.TYPES.DESELECT_ADDRESS_BAR }; expect( ui.deselectAddressBar( ) ).toEqual( expectedAction ); } ); it( 'should clear a notification', () => { const expectedAction = { type : ui.TYPES.BLUR_ADDRESS_BAR }; expect( ui.blurAddressBar( ) ).toEqual( expectedAction ); } ); it( 'should resetStore', () => { const expectedAction = { type : ui.TYPES.RESET_STORE }; expect( ui.resetStore( ) ).toEqual( expectedAction ); } ); } );
function myFunction() { var d = new Date(); var weekday = new Array(7); weekday[0] = "Sonntag"; weekday[1] = "Montag"; weekday[2] = "Dienstag"; weekday[3] = "Mittwoch"; weekday[4] = "Donnerstag"; weekday[5] = "Freitag"; weekday[6] = "Samstag"; var n = weekday[d.getDay()]; document.getElementById("dotw").innerHTML = n; var myDate = new Date(); if ( myDate.getHours() < 6 ) { document.getElementById('tageszeit').innerHTML='Nacht'; } else if ( myDate.getHours() >= 6 && myDate.getHours() <= 12 ) { document.getElementById('tageszeit').innerHTML='Morgen'; } else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) { document.getElementById('tageszeit').innerHTML='Mittag'; } else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) { document.getElementById('tageszeit').innerHTML='Abend'; } var months = ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember']; var month = months[myDate.getMonth()]; document.getElementById('monat').innerHTML= myDate.getDate() + " " + month; var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); m = checkTime(m); document.getElementById('time').innerHTML = h + ":" + m ; var t = setTimeout(startTime, 500); } function checkTime(i) { if (i < 10) {i = "0" + i}; return i; }
import { Card, Col, Icon, Row, Spin, Tooltip } from 'antd' import React, { Component } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' import { bindActionCreators } from 'redux' import { getPrices, getTopGames, searchGames } from '../actions/home' import Currency from '../component/Currency' import { createLoadingSelector } from '../reducers/loading' import { calculateDiscount } from '../utils' const loadingSelector = createLoadingSelector('LOAD_APP') const pricesLoadingSelector = createLoadingSelector('GET_PRICES') @connect( state => ({ loading: loadingSelector(state), home: state.home, hasPrices: !pricesLoadingSelector(state) }), dispatch => ({ getTopGames: bindActionCreators(getTopGames, dispatch), getPrices: bindActionCreators(getPrices, dispatch), searchGames: bindActionCreators(searchGames, dispatch) }) ) export default class Home extends Component { generatePriceBlock = (discountPercent, oldPrice, newPrice, fromCurrency) => { if (discountPercent === 0) { return ( <div className='prices-block'> <div className='price'> <Currency price={newPrice} /> </div> </div> ) } else if (discountPercent > 0) { return ( <div className='prices-block'> <div className='discount-percent'>{-discountPercent}%</div> <div className='prices'> <div className='old-price'> <Currency price={oldPrice} fromCurrency={fromCurrency} /> </div> <div className='new-price'> <Currency price={newPrice} /> </div> </div> </div> ) } else { return ( <div className='prices-block'> <div className='free-tag'>Free</div> </div> ) } } componentDidMount() { const name = this.props.location.query.name if (name) { this.props.searchGames(name) } else { this.props.getTopGames() } } componentWillReceiveProps(nextProps) { if (!nextProps.hasPrices) { nextProps.getPrices() } const name = nextProps.location.query.name if (this.props.location.query.name !== name) { if (name) { nextProps.searchGames(name) } else { this.props.getTopGames() } } } render() { const column = 4 const { home, hasPrices } = this.props return ( <div className='games-list'> <Spin className='spin-loading' spinning={this.props.loading} tip='Loading...' /> { home .get('games') .groupBy((game, key) => ~~(key / column)) .valueSeq() .map((games, key) => ( <Row key={key} gutter={16}> { games.map((game) => { const loading = !game.get('is_free') && !hasPrices let newPrice if (game.has('itad_price')) { newPrice = game.getIn(['itad_price', 'price_new']) } else { newPrice = game.getIn(['steam_price', 'final']) / 100 } const oldPrice = game.getIn(['steam_price', 'initial']) / 100 const discountPercent = calculateDiscount(oldPrice, newPrice) const fromCurrency = game.getIn(['steam_price', 'currency']) const platform = game.get('platforms') const shortDescription = game.get('short_description') && <div dangerouslySetInnerHTML={{ __html: game.get('short_description') }} /> return ( <Col className='game-item' key={game.get('app_id')} xs={24} sm={24} md={6} lg={6}> <Tooltip placement="rightTop" title={shortDescription}> <Card bodyStyle={{ padding: 0 }} loading={loading}> <Link to={game.get('app_id').toString()}> <img alt={game.get('name')} width='100%' src={game.get('header_image')} /> <div className='card-game-content'> { <div className='platforms'> {platform.get('windows') && <Icon className='platform-icon' type='windows' />} {platform.get('mac') && <Icon className='platform-icon' type='apple' />} </div> } {this.generatePriceBlock(discountPercent, oldPrice, newPrice, fromCurrency)} </div> </Link> </Card> </Tooltip> </Col> ) }) } </Row> )) } </div> ) } }
import Controller from '@ember/controller'; export default class <%= classifiedModuleName %>Controller extends Controller {}
export function determineWeightRate(weight, destinationAreaId, weights, rates) { let result = { rate_weight: null, rate_price: null, bonus_weight: null, bonus_price: null } const nonBonusWeights = _.sortBy(_.filter(weights, ['bonus', false]), ['weight']); let indx = _.sortedIndexBy(nonBonusWeights, {'weight': weight}, 'weight'); if (indx === nonBonusWeights.length) indx = indx - 1; const weightLvl = nonBonusWeights[indx]; const rate = _.find(rates, rate => ( rate.weight_id === weightLvl.id && rate.destination_area_id === parseInt(destinationAreaId) )); result.rate_weight = weightLvl.weight; result.rate_price = rate.price; if (weight > weightLvl.weight) { const bonusWeightLvl = _.find(weights, ['bonus', true]); const bonusRate = _.find(rates, rate => ( rate.weight_id === bonusWeightLvl.id && rate.destination_area_id === parseInt(destinationAreaId) )); result.bonus_weight = bonusWeightLvl.weight; result.bonus_price = bonusRate.price; } return result; } export function calculateCost(weight, weightRate) { let cost = weightRate.rate_price; if (weightRate.bonus_weight && weightRate.bonus_price) { cost = cost + weightRate.bonus_price * Math.ceil((weight - weightRate.rate_weight) / weightRate.bonus_weight); } return cost; }
var querify = require("../lib/index.js"); describe("Object -> Query String", function () { it("Should work for objects with strings", function () { var qs_object = { str: "mystr", second_str: "myotherstr" }; expect(querify.convert(qs_object)).toBe("?str=mystr&second_str=myotherstr"); }); it("Should work with numbers", function () { var qs_object = { num: 5, othernum: 4000, neg_number: -20 }; expect(querify.convert(qs_object)).toBe("?num=5&othernum=4000&neg_number=-20"); }); it("Should work with booleans", function () { var qs_object = { bool_t: true, bool_f: false }; expect(querify.convert(qs_object)).toBe("?bool_t=true&bool_f=false"); }); it("Should work with arrays", function () { var qs_object = { arr: [1,2,3], arr_two: [8,"string",true] }; expect(querify.convert(qs_object)).toBe("?arr=%5B1%2C2%2C3%5D&arr_two=%5B8%2C%22string%22%2Ctrue%5D"); }); it("Should work with objects", function () { var qs_object = { obj1: { a: 1, b: "string" }, obj2: { c: true, b: [1,2] } }; expect(querify.convert(qs_object)).toBe("?obj1=%7B%22a%22%3A1%2C%22b%22%3A%22string%22%7D&obj2=%7B%22c%22%3Atrue%2C%22b%22%3A%5B1%2C2%5D%7D"); }); it("Should work with RegExp", function () { var qs_object = { reg: /[^a-zA-Z]/, reg2: /0/ }; expect(querify.convert(qs_object)).toBe("?reg=%2F%5B%5Ea-zA-Z%5D%2F&reg2=%2F0%2F"); }); });
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var someModule = require('some-module'); module.exports = function (options) { if (!options.foo) { throw new gutil.PluginError('gulp-ast-support', '`foo` required'); } return through.obj(function (file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new gutil.PluginError('gulp-ast-support', 'Streaming not supported')); return; } try { file.contents = new Buffer(someModule(file.contents.toString(), options)); this.push(file); } catch (err) { this.emit('error', new gutil.PluginError('gulp-ast-support', err)); } cb(); }); };
import './admin/adminUserStatus.html'; import './admin/adminUserStatus'; import './admin/adminUserStatusEdit.html'; import './admin/adminUserStatusInfo.html'; import './admin/userStatusEdit.html'; import './admin/userStatusEdit'; import './admin/userStatusInfo.html'; import './admin/userStatusInfo'; import './admin/userStatusPreview.html'; import './admin/route'; import './admin/startup'; import './notifications/deleteCustomUserStatus'; import './notifications/updateCustomUserStatus'; export { userStatus } from './lib/userStatus'; export { deleteCustomUserStatus, updateCustomUserStatus } from './lib/customUserStatus';
'use strict' var Input = function () {} Input.prototype.buttonInputStates = {} Input.prototype.dispatchUserButtonInputEvent = function (source, input, state) { if (this.buttonInputStates[source] === undefined) { this.buttonInputStates[source] = {} } if (this.buttonInputStates[source][input] === state) { return } this.buttonInputStates[source][input] = state var userButtonInputEvent = new window.CustomEvent( 'userbuttoninput', {'detail': {'source': source, 'input': input, 'state': state}} ) window.dispatchEvent(userButtonInputEvent) } var keyboardInput = new Input() keyboardInput.map = { 37: 'left', // LEFT arrow 38: 'up', // UP arrow 39: 'right', // right arrow 40: 'down', // down arrow 65: 'left', // A 87: 'up', // W 68: 'right', // D 83: 'down' // S } keyboardInput._key = function (state, event) { if (this.map[event.keyCode] === undefined) { return } this.dispatchUserButtonInputEvent('keyboard', this.map[event.keyCode], state === 'down') } keyboardInput.setup = function () { window.addEventListener('keydown', function (e) { this._key('down', e) }.bind(this)) window.addEventListener('keyup', function (e) { this._key('up', e) }.bind(this)) } var gamepadInput = new Input() gamepadInput.map = { 14: 'left', 12: 'up', 15: 'right', 13: 'down' } gamepadInput._states = {} gamepadInput.setup = function () { window.addEventListener('gamepadconnected', function (e) { console.log('Gamepad ' + e.gamepad.index + ' connected!') this._checkState(e.gamepad.index) }.bind(this)) } gamepadInput._checkState = function (index) { var gp = navigator.getGamepads()[index] if (gp === undefined) { console.log('Gamepad ' + index + ' disconnected!') return } console.debug('checking', gp) if (this._states[gp.index] === undefined) { this._states[gp.index] = {buttons: [], axes: []} } /* for(var i=0; i<gp.axes.length; i++) { if(gamepadStates[gp.index].axes[i] !== undefined && gamepadStates[gp.index].axes[i] != gp.axes[i]) axisChanged(gp, i, gp.axes[i]) gamepadStates[gp.index].axes[i] = gp.axes[i] }*/ for (var i = 0; i < gp.buttons.length; i++) { if (this._states[gp.index].buttons[i] !== undefined && this._states[gp.index].buttons[i] !== gp.buttons[i].pressed) { this._buttonChanged(gp, i, gp.buttons[i].pressed) } this._states[gp.index].buttons[i] = gp.buttons[i].pressed } window.setTimeout(function () { this._checkState(index) }.bind(this), 100) } gamepadInput._buttonChanged = function (gamepad, button, state) { console.log('gamepad button "' + button + '" was ' + (state ? 'pressed' : 'released')) if (this.map[button] === undefined) { return } this.dispatchUserButtonInputEvent('gamepad_' + gamepad.index, this.map[button], state) }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = restrictToSelf; /** * restrictToSelf - users can't see other users. * USER service only!s * @param {String} idProp is the key where the user's id can be found. defaults * to '_id'. * * find, get, create, update, remove */ function restrictToSelf() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var defaults = { idField: '_id' }; options = Object.assign({}, defaults, options); return function (hook) { if (hook.params.user) { hook.params.query[options.idField] = hook.params.user[options.idField]; } else { throw new Error('Could not find the user\'s ' + options.idField + ' for the restrictToSelf hook.'); } }; } module.exports = exports['default'];
// BEGIN-SNIPPET calendar-event-model import DS from 'ember-data'; import attr from 'ember-data/attr'; export default DS.Model.extend({ description: attr(), // name of event start: attr('number'), // timestamp, number of seconds end : attr('number') // timestamp, number of seconds }); // END-SNIPPET
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _immutable = require('immutable'); var _immutable2 = _interopRequireDefault(_immutable); var Requeter = (function () { function Requeter(request, indexer) { _classCallCheck(this, Requeter); this.requestArray = request; this.indexer = indexer; } _createClass(Requeter, [{ key: 'calculCoefficient', value: function calculCoefficient() { // C(v,r) = Somme (pondération des mot) / Racine(Somme (pondération des mot)² var docTable = this.indexer.getDocumentArray(); var res = []; var numerateur = 0; var denominateur = 0; for (var doc in docTable) { if (docTable.hasOwnProperty(doc)) { // On récupère le nom du fichier var doc_name = docTable[doc]; // Calcul du numérateur numerateur = this.indexer.ponderationMot(this.requestArray, doc_name); // Calcul du dénominateur denominateur = Math.sqrt(this.indexer.ponderationMotCarre(this.requestArray, doc_name)); // On ajoute le résultat à la liste res.push({ document: doc_name, ponderation: isNaN(numerateur / denominateur) ? 0 : numerateur / denominateur }); } } return res; } }, { key: 'resultatRequest', value: function resultatRequest() { // Calcul des coefficients de la requête var results = this.calculCoefficient(); // Création d'une liste ordonnée var res = new _immutable2['default'].OrderedMap(); // Ajout des entrées dans la liste results.map(function (doc) { return res = res.set(doc.document, doc); }); // Tri sur la liste res = res.sortBy(function (doc) { return doc.ponderation; }); res = res.reverse(); // Conversion des résultat en objet javascript et renvoie de l'objet return res.toJS(); } }]); return Requeter; })(); exports['default'] = Requeter; module.exports = exports['default'];
// NOTE: This example uses the next generation Twilio helper library - for more // information on how to download and install this version, visit // https://www.twilio.com/docs/libraries/node // Find your credentials at twilio.com/console // To set up environmental variables, see http://twil.io/secure const API_KEY_SID = process.env.TWILIO_API_KEY; const API_KEY_SECRET = process.env.TWILIO_API_KEY_SECRET; const ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID; const Twilio = require('twilio'); const client = new Twilio(API_KEY_SID, API_KEY_SECRET, {accountSid: ACCOUNT_SID}); client.video.compositionHooks. create({ friendlyName: 'MixingAllRoomAudiosHook', audioSources: '*', statusCallback: 'http://my.server.org/callbacks', format: 'mp4' }) .then(compositionHook =>{ console.log('Created Composition Hook with SID=' + compositionHook.sid); });
'use strict'; // Declare app level module which depends on views, and components angular.module('myApp', [ 'ngRoute' , 'myApp.recorder' , 'myApp.player' //, 'myApp.version' ]);
import hg from 'mercury'; import srOnly from '../tags/srOnly'; const h = hg.h; export default function(phone, hasMobile) { return h('span.phone', [ h(`i.fa.fa-lg.fa-${hasMobile ? 'mobile' : 'phone'}`, [srOnly('Call me')]), h('a.phone.ocr.hidden-sm-down', { href: `tel:${phone}` }, phone), ]); };
/** * @fileOverview jQuery.extend-patch.js * * Provides backwards compatibility for jQuery.extend to jQuery versions * less than 1.4. jQuery versions 1.4 and above do not need this file. * * This file should only be used as a last resort or for making plugins * backwards compatible. Please do everyone a favor and upgrade to a * newer version of jQuery if at all possible. * * @author Kyle Florence * @website https://github.com/kflorence/misc-js/ * @version 1.0.0 * * Dual licensed under the MIT and BSD Licenses. */ ;(function($, window, undefined) { // Used to test for jQuery < 1.4 if (!$.isPlainObject) { var class2type = {}, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty; // Populate the class2type map $.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // Add in missing functions: these were pulled straight from jQuery 1.5 $.extend({ type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return $.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return $.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || $.type(obj) !== "object" || obj.nodeType || $.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, // Override the extend method !! extend: function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !$.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( $.isPlainObject(copy) || (copyIsArray = $.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && $.isArray(src) ? src : []; } else { clone = src && $.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = $.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; } }); } })(jQuery, window);
var zlib = require('zlib') function middlewareWrapper(middleware, req, res, next) { var _writeHead = res.writeHead; var gunzip = zlib.Gunzip(); res.originWrite = res.write; res.originEnd = res.end; middleware && middleware(req, res) var write = function (data) { if(res.customWrite){ res.customWrite(data) }else{ res.originWrite(data) } } var end = function () { if(res.customEnd){ res.customEnd() }else{ res.originEnd() } } res.isHtml = false; res.isGziped = false; res.writeHead = function (code, headers) { var contentType = this.getHeader('content-type'); var contentEncoding = this.getHeader('content-encoding'); if (((typeof contentType != 'undefined') && (contentType.indexOf('text/html') == 0))) { res.isHtml = true; res.removeHeader('Content-Length'); if (headers) { delete headers['content-length']; } } if (res.isHtml && contentEncoding && contentEncoding.toLowerCase() == 'gzip') { res.isGziped = true; res.removeHeader('Content-Encoding'); if (headers) { delete headers['content-encoding']; } } _writeHead.apply(res, arguments); }; res.write = function (data, encoding) { if (res.isHtml) { if (res.isGziped) { gunzip.write(data); } else { write(data) } } else { res.originWrite(data); } }; gunzip.on('data', function (data) { write(data) }); res.end = function (data, encoding) { if (res.isGziped) { gunzip.end(data); } else { end() } }; gunzip.on('end', function (data) { end() }); next() } /** function (res) { res.html = '' res.customWrite = function(data) { var _this = this if (res.isHtml) { res.html += data } else { res.originWrite(data) } } res.customEnd = function() { if (res.isHtml) { res.originWrite(res.html) } res.originEnd() } } */ module.exports = function (config) { return function (req, res, next) { middlewareWrapper(config, req, res, next) } }
const concatURL = function (token, file_path) { return 'https://api.telegram.org/file/bot' + token + '/' + file_path } module.exports = { concatURL: concatURL, }
version https://git-lfs.github.com/spec/v1 oid sha256:32f66c793688df2f5194f13e593dc98f9891c3be0034aaf269c735156eb25b1a size 1535
import React from "react"; import { graphql } from "gatsby"; import Blog from "../components/blog"; import Layout from "../components/layout"; const BlogPage = (props) => ( <Layout> <Blog {...props} /> </Layout> ); export const query = graphql` query { tags: allMarkdownRemark( filter: { fields: { slug: { regex: "//posts//" } } } ) { group(field: frontmatter___tags) { fieldValue totalCount } } posts: allMarkdownRemark( filter: { fields: { slug: { regex: "//posts//" } } } sort: { fields: [frontmatter___date], order: DESC } ) { nodes { id timeToRead excerpt frontmatter { title date tags } fields { slug } } } } `; export default BlogPage;
'use strict' import React from 'react' import ReactDOM from 'react-dom' import ImgGallery from './imgGallery' import VerbGallery from './verbGallery' module.exports = class CommentBoard extends React.Component { constructor(props){ super(props) } render (){ return ( <div className="commentBoard"> <div>I can</div> <div> <img className='chosenVerb' src={this.props.verb}></img> </div> <div> <img className='chosenPic' src={this.props.image}></img> </div> </div> ) } }
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! Notificare <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: 'public/js/notificare.jquery.js', dest: 'public/js/notificare.jquery.min.js', } }, makepot: { target: { options: { domainPath: '/languages/', // Where to save the POT file. mainFile: 'notificare.php', // Main project file. potFilename: 'notificare.pot', // Name of the POT file. type: 'wp-plugin', // Type of project (wp-plugin or wp-theme). exclude: ['file-1.php', 'file-2.php'], // List of files or directories to ignore. processPot: function( pot, options ) { pot.headers['report-msgid-bugs-to'] = 'http://notifica.re'; pot.headers['plural-forms'] = 'nplurals=2; plural=n != 1;'; pot.headers['last-translator'] = 'Joel Oliveira <joel@notifica.re>\n'; pot.headers['language-team'] = 'Joel Oliveira <joel@notifica.re>\n'; pot.headers['x-poedit-basepath'] = '.\n'; pot.headers['x-poedit-language'] = 'English\n'; pot.headers['x-poedit-country'] = 'UNITED STATES\n'; pot.headers['x-poedit-sourcecharset'] = 'utf-8\n'; pot.headers['x-poedit-keywordslist'] = '__;_e;_x;esc_html_e;esc_html__;esc_attr_e;esc_attr__;_ex:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2;_x:1,2c;_n:1,2;_n_noop:1,2;__ngettext_noop:1,2;_c,_nc:4c,1,2;\n'; pot.headers['x-textdomain-support'] = 'yes\n'; return pot; } } } }, po2mo: { files: { src: 'languages/*.po', expand: true, }, } }); grunt.loadNpmTasks('grunt-contrib-uglify'); // Default task(s). grunt.registerTask( 'default', [ 'makepot', 'po2mo', 'uglify'] ); };
/*global define*/ define([ 'xdomainajax', 'underscore', 'backbone', 'marionette', 'templates', './bookmark', './empty', '../collections/bookmarks', ], function ($, _, Backbone, Marionette, JST, BookmarkView, EmptyView, BookmarksCollection) { 'use strict'; return Marionette.CompositeView.extend({ template: JST['app/scripts/templates/bookmarks.ejs'], itemView: BookmarkView, emptyView: EmptyView, itemViewContainer: '#bookmarks', events: { 'keyup input.bookmark': 'addBookmark', 'click button[type="submit"]': 'addBookmark' }, initialize: function () { this.collection.fetch({reset: true}); this.listenTo(this.collection, 'add', this.resetInput); this.resetInput(); }, createBookmark: function(data) { var title = data.responseText.match(/\<title\>(.*)\<\/title\>/)[1]; var timestamp = new Date; var attributes = { url: data.url, title: title, createdAt: timestamp, updatedAt: timestamp }; this.collection.create(attributes); }, addBookmark: function (evt) { if (evt.target.tagName.toLowerCase() == 'button' || (evt.keyCode === 13 && evt.target.value.length)) { this.$('button').attr('disabled', 'disabled'); $.ajax({ url: this.$('input.bookmark').val(), type: 'head', success: this.createBookmark.bind(this), error: function () { console.log(arguments); } }); } }, resetInput: function () { this.$('input').val(''); this.$('button').removeAttr('disabled'); } }); });
#! /usr/bin/env node var Client = require("owfs").Client, argv = require('minimist')(process.argv.slice(2)), async = require('async'), timers = require("timers"), elasticsearch = require('elasticsearch'), logger = require("winston"); logger.cli(); if(argv.debug){ logger.remove(logger.transports.Console); logger.add(logger.transports.Console, { level: 'debug', colorize:true }); } var HOST = argv.host ? argv.host : 'localhost'; var PORT = argv.port ? argv.port : 4304; var ESHOST = argv.searchhost ? argv.searchhost : 'localhost:9200'; logger.info("Connecting to " + HOST + ":" + PORT); var con = new Client(HOST, PORT); var es = new elasticsearch.Client({ host: ESHOST, //log: 'trace' }); es.ping({ requestTimeout: 1000, // undocumented params are appended to the query string hello: "elasticsearch!" }, function(error) { if (error) { logger.error('elasticsearch cluster is down!'); } else { logger.info('Connected to', ESHOST); } }); es.indices.exists({ index: "temperature" }, function(err, exists, status) { if (!exists) { es.indices.create({ index: "temperature", body: { mappings: { _default_: { _timestamp: { enabled: true, store: true }, properties: { temperature: { type: "float" } } } } } }) } }); logger.info("Detecting devices..."); con.getslash("/", function(error,devices) { logger.info("Found:",devices.join(", ")); indexDevices(devices); }); function indexDevices(devices) { timers.setInterval(function() { //TODO other devices var path = devices[0]; con.getslash(path, function(error,sensors) { sensors = sensors.filter(function(sensor){return sensor.indexOf("errata") == -1}); async.map(sensors, function(sensor, done) { logger.debug("reading", sensor) con.read(sensor, function(error,data) { var name = sensor.split("/")[2]; done(error, { key: name, value: data }); }); }, function(err, all) { if (err) { logger.error("ERROR", err); } else { var doc = { path: path, _timestamp: new Date().toISOString() }; all.forEach(function(kv) { doc[kv.key] = kv.value; }); es.create({ index: 'temperature', type: doc.type, body: doc }, function(error, response) { if (error) { logger.error(error, response); } else { logger.info("written to elasticsearch",doc); } }); } }) }); }, 5000); }
'use strict'; import angular from 'angular'; import IndexController from './index-controller'; export default angular.module('app.index', []) .controller('indexController', [ '$interval', '$state', '$log', 'apiService', IndexController ]);
/** * Created by USER: tarso. * On DATE: 23/02/17. * By NAME: ksdra-99-a-test.js. */ 'use strict'; const cassandra = require('cassandra-driver'); const client = new cassandra.Client({ contactPoints: ['10.15.20.117'], keyspace: 'bovespa' }); const query = 'SELECT data, codneg, preabe, premax, premin, preult FROM cotacoes'; client.execute(query, [ ], { prepare: true }) .then(result => console.log(result));
import {expect} from 'chai'; import { generateWorkout, generatePattern } from '../lib/index'; describe('::generatePattern', () => { let pattern; before(() => { pattern = generatePattern(1800); }); it('generates a pattern', () => { expect(pattern).to.be.ok; }); }); describe('::generateWorkout', () => { let pattern; before(() => { pattern = generateWorkout(1800); }); it('generates a pattern', () => { expect(pattern).to.be.ok; }); });
import trimEnd from 'lodash/trimEnd'; import tokenTypes from './tokenTypes'; import Indentation from './Indentation'; import InlineBlock from './InlineBlock'; import Params from './Params'; export default class Formatter { /** * @param {Object} cfg * @param {Object} cfg.indent * @param {Object} cfg.params * @param {Tokenizer} tokenizer */ constructor(cfg, tokenizer) { this.cfg = cfg || {}; this.indentation = new Indentation(this.cfg.indent); this.inlineBlock = new InlineBlock(); this.params = new Params(this.cfg.params); this.tokenizer = tokenizer; this.previousReservedWord = {}; } /** * Formats whitespaces in a SQL string to make it easier to read. * * @param {String} query The SQL query string * @return {String} formatted query */ format(query) { const tokens = this.tokenizer.tokenize(query); const formattedQuery = this.getFormattedQueryFromTokens(tokens); return formattedQuery.trim(); } getFormattedQueryFromTokens(tokens) { let formattedQuery = ''; tokens.forEach((token, index) => { if (token.type === tokenTypes.WHITESPACE) { } else if (token.type === tokenTypes.LINE_COMMENT) { formattedQuery = this.formatLineComment(token, formattedQuery); } else if (token.type === tokenTypes.BLOCK_COMMENT) { formattedQuery = this.formatBlockComment(token, formattedQuery); } else if (token.type === tokenTypes.RESERVED_TOPLEVEL) { formattedQuery = this.formatToplevelReservedWord(token, formattedQuery); this.previousReservedWord = token; } else if (token.type === tokenTypes.RESERVED_NEWLINE) { formattedQuery = this.formatNewlineReservedWord(token, formattedQuery); this.previousReservedWord = token; } else if (token.type === tokenTypes.RESERVED) { formattedQuery = this.formatWithSpaces(token, formattedQuery); this.previousReservedWord = token; } else if (token.type === tokenTypes.OPEN_PAREN) { formattedQuery = this.formatOpeningParentheses( tokens, index, formattedQuery ); } else if (token.type === tokenTypes.CLOSE_PAREN) { formattedQuery = this.formatClosingParentheses(token, formattedQuery); } else if (token.type === tokenTypes.PLACEHOLDER) { formattedQuery = this.formatPlaceholder(token, formattedQuery); } else if (token.value === ',') { formattedQuery = this.formatComma(token, formattedQuery); } else if (token.value === ':') { formattedQuery = this.formatWithSpaceAfter(token, formattedQuery); } else if (token.value === '.' || token.value === ';') { formattedQuery = this.formatWithoutSpaces(token, formattedQuery); } else { formattedQuery = this.formatWithSpaces(token, formattedQuery); } }); return formattedQuery; } formatLineComment(token, query) { return this.addNewline(query + token.value); } formatBlockComment(token, query) { return this.addNewline( this.addNewline(query) + this.indentComment(token.value) ); } indentComment(comment) { return comment.replace(/\n/g, `\n${this.indentation.getIndent()}`); } formatToplevelReservedWord(token, query) { this.indentation.decreaseTopLevel(); query = this.addNewline(query); this.indentation.increaseToplevel(); query += this.equalizeWhitespace(token.value); return this.addNewline(query); } formatNewlineReservedWord(token, query) { return `${this.addNewline(query) + this.equalizeWhitespace(token.value)} `; } // Replace any sequence of whitespace characters with single space equalizeWhitespace(string) { return string.replace(/\s+/g, ' '); } // Opening parentheses increase the block indent level and start a new line formatOpeningParentheses(tokens, index, query) { // Take out the preceding space unless there was whitespace there in the original query or another opening parens const previousToken = tokens[index - 1]; if ( previousToken && previousToken.type !== tokenTypes.WHITESPACE && previousToken.type !== tokenTypes.OPEN_PAREN ) { query = trimEnd(query); } query += tokens[index].value; this.inlineBlock.beginIfPossible(tokens, index); if (!this.inlineBlock.isActive()) { this.indentation.increaseBlockLevel(); query = this.addNewline(query); } return query; } // Closing parentheses decrease the block indent level formatClosingParentheses(token, query) { if (this.inlineBlock.isActive()) { this.inlineBlock.end(); return this.formatWithSpaceAfter(token, query); } this.indentation.decreaseBlockLevel(); return this.formatWithSpaces(token, this.addNewline(query)); } formatPlaceholder(token, query) { return `${query + this.params.get(token)} `; } // Commas start a new line (unless within inline parentheses or SQL "LIMIT" clause) formatComma(token, query) { query = `${trimEnd(query) + token.value} `; if (this.inlineBlock.isActive()) { return query; } else if (/^LIMIT$/i.test(this.previousReservedWord.value)) { return query; } return this.addNewline(query); } formatWithSpaceAfter(token, query) { return `${trimEnd(query) + token.value} `; } formatWithoutSpaces(token, query) { return trimEnd(query) + token.value; } formatWithSpaces(token, query) { return `${query + token.value} `; } addNewline(query) { return `${trimEnd(query)}\n${this.indentation.getIndent()}`; } }
"use strict"; define("cthulhuFrontView", ["cthulhuAuthService"], function (auth) { auth.then(function (service) { if (service.isAuthenticated === false) { var routerElement = document.querySelector("app-router"); routerElement.go("/login"); return; } Polymer({ is: "cthulhu-front-view", properties: { profile: { type: Object } }, onProfileError: function onProfileError(response) { console.log("Error getting profile:", response); } }); }); });
(function() { function async_load(){ var _css = document.createElement('link'); _css.setAttribute('rel','stylesheet'); _css.setAttribute('type','text/css'); _css.setAttribute('href', 'http://www.collidetravel.com/css/cc-widget.css'); document.getElementsByTagName('head')[0].appendChild(_css); var _js = document.createElement('script'); _js.type = 'text/javascript'; _js.async = true; _js.src = '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js'; var _jsx = document.getElementsByTagName('script')[0]; _jsx.parentNode.insertBefore(_js, _jsx); var _js2 = document.createElement('script'); _js2.type = 'text/javascript'; _js2.async = true; _js2.src = 'https://use.fontawesome.com/55857cbf80.js'; _jsx = document.getElementsByTagName('script')[0]; _jsx.parentNode.insertBefore(_js2, _jsx); var _js3 = document.createElement('script'); _js3.type = 'text/javascript'; _js3.async = true; _js3.src = 'https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js'; _jsx = document.getElementsByTagName('script')[0]; _jsx.parentNode.insertBefore(_js3, _jsx); var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'http://www.collidetravel.com/js/ct-payload.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } if (window.attachEvent) window.attachEvent('onload', async_load); else window.addEventListener('load', async_load, false); })();
import { put, takeEvery } from 'redux-saga/effects' import { accomodationListFetch } from '../../accomodation/actions' import { getOrderListState } from '../selectors' import { mealListFetch } from '../../food/actions' import { orderListFetch } from '../actions' import { requireWorkshopList } from '../../workshops/actions' import createFetchSaga from '../../sagas/createFetchSaga' function * handleOrderDepsRequire () { yield put(accomodationListFetch()) yield put(mealListFetch()) yield put(requireWorkshopList()) } function * onOrderListRequire () { yield takeEvery(orderListFetch.TRIGGER, handleOrderDepsRequire) } export default [ ...createFetchSaga(orderListFetch, { stateSelector: getOrderListState }), onOrderListRequire ]
module.exports = { entry: { fe: './src/fe', // portfolios: './src/portfolios', // resume: './src/resume', }, output: { filename: './static/dist/[name].min.js' }, module: { loaders: [ { test: /\.json$/, loader: 'json-loader' }, { test: /\.jsx$/, loader: 'jsx-loader?harmony' } ] }, externals: { 'd3': 'd3', }, resolve: { extensions: ['', '.js', '.jsx', '.json'] } };
'use strict'; const tryCatch = require('try-catch'); const noop = (req, res, next) => { next && next(); }; noop.listen = noop; module.exports = (config, arg) => { if (!config('terminal')) return noop; const [e, terminalModule] = tryCatch(require, config('terminalPath')); if (!e && !arg) return terminalModule; if (!e) return terminalModule(arg); config('terminal', false); console.log(`cloudcmd --terminal: ${e.message}`); return noop; };
import Akili from './akili.js'; const obj = {}; /** * Globals is for using the custom variables in html * * {@link https://akilijs.com/docs/scope#docs_globals} */ const globals = new Proxy(obj, { get: (target, key) => { if(key == '__target') { return obj; } return target[key]; }, set: (target, key, value) => { target[key] = Akili.wrap(value, { tag: key }); return true; }, deleteProperty: (target, key) => { Akili.removeTag(key); delete target[key]; return true; } }); export default globals;
function ConsultaBuilder() { var paciente = new PacienteBuilder().gerar(); var procedimentos = []; var particular = false; var retorno = false; var data = new Date(); var classBody = { comPaciente : function(valor){ paciente = valor; return this; }, comProcedimentos : function(valor){ procedimentos = valor; return this; }, comParticular : function(valor){ particular = valor; return this; }, comRetorno : function(valor){ retorno = valor; return this; }, comData : function(valor){ data = valor; return this; }, gerar : function(){ return new Consulta(paciente, procedimentos, particular, retorno, data); } }; return classBody; }
import React from 'react' import { render } from 'react-dom' import Demo from './Demo' render(<Demo />, document.getElementById('root'))
var class_marketplace_controller = [ [ "indexAction", "class_marketplace_controller.html#a04f2101fe1cdc785b61219c2df753024", null ] ];
/** PasswordMaker - Creates and manages passwords Copyright (C) 2005 Eric H. Jung and LeahScape, Inc. http://passwordmaker.org/ grimholtz@yahoo.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **/ /* * Common functions used by md4, md5, ripemd5, sha1, and sha256. * Version 2.2 Copyright (C) Jerrad Pierce, Paul Johnston 1999 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. * * Modified by Eric H. Jung (grimholtz@yahoo.com) * Modified by Eric Aguiar (ultimate.evil@gmail.com) */ if (typeof PasswordMaker_HashUtils !== "object") { var PasswordMaker_HashUtils = { /* bits per input character. 8 - ASCII; 16 - Unicode */ chrsz: 8, /* * Encode a string as utf-8. */ str2rstr_utf8: function(input) { var output = ""; for (var i = 0; i < input.length; i++) { var c = input.charCodeAt(i); if (c < 128) { output += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { output += String.fromCharCode((c >> 6) | 192); output += String.fromCharCode((c & 63) | 128); } else { output += String.fromCharCode((c >> 12) | 224); output += String.fromCharCode(((c >> 6) & 63) | 128); output += String.fromCharCode((c & 63) | 128); } } return output; }, /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ rstr2binl: function(input) { var output = []; for (var j = 0; j < input.length * 8; j += 8) { output[j >> 5] |= (input.charCodeAt(j / 8) & 0xFF) << (j % 32); } return output; }, /* * Convert an array of little-endian words to a string */ binl2rstr: function(input) { var output = ""; for (var i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; }, /* * Convert a raw string to an arbitrary string encoding */ rstr2any: function(input, encoding) { var divisor = encoding.length; var remainders = []; /* Convert to an array of 16-bit big-endian values, forming the dividend */ var dividend = []; for (var i = 0; i < (input.length / 2); i++) { dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1); } while (dividend.length > 0) { var quotient = []; var x = 0; for (var j = 0; j < dividend.length; j++) { x = (x << 16) + dividend[j]; var q = Math.floor(x / divisor); x -= q * divisor; if (quotient.length > 0 || q > 0) { quotient.push(q); } } remainders.push(x); dividend = quotient; } var output = ""; while (remainders.length) { output += encoding.charAt(remainders.pop()); } return output; }, ///===== big endian =====/// /* * Convert a raw string to an array of big-endian words * Characters >255 have their high-byte silently ignored. */ rstr2binb: function(input) { var output = []; for (var j = 0; j < input.length * 8; j += 8) { output[j >> 5] |= (input.charCodeAt(j / 8) & 0xFF) << (24 - j % 32); } return output; }, /* * Convert an array of big-endian words to a string */ binb2rstr: function(input) { var output = ""; for (var i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF); } return output; }, /* * Bitwise rotate a 32-bit number to the left. */ bit_rol: function(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); }, /* * Add integers, takes care of being passed NaN and undefined. */ safe_add: function(x, y) { return (x | 0) + (y | 0); } }; }
import React from 'react'; import { mount } from 'enzyme'; import 'materialize-css/dist/js/materialize'; import { ForgotPassword } from '../../components/auth/ForgotPassword'; const props = { verifyUser: jest.fn(() => Promise.resolve()), revertForgotPassword: jest.fn(() => Promise.resolve()) }; const enzymeWrapper = mount( <ForgotPassword {...props} /> ); describe('Given the forgot password page is mounted', () => { it('it should render self', () => { expect(enzymeWrapper.exists()).toBe(true); }); it('should change email when a user inputs his email', () => { enzymeWrapper.find('#email').simulate('change', { target: { id: 'email', value: 'emeka@gmail.com' } }); expect(enzymeWrapper.state('email')).toBe('emeka@gmail.com'); }); it('should call the revertForgotPassword when the cancel button is clicked', () => { enzymeWrapper.find('#cancel').simulate('click'); expect(props.revertForgotPassword.mock.calls.length).toBe(1); }); it('should send the user an email when the form is submitted', () => { enzymeWrapper.find('#forgot-password').simulate('submit'); expect(props.verifyUser.mock.calls.length).toBe(1); }); });
import React, { Component } from 'react' import { View, Text, TouchableHighlight } from 'react-native' import * as expensesActions from '../actions/expenses' import styles from '../styles' const localStyles = { pending_stats_container: { margin: 100, alignSelf: 'center', flexDirection: 'row', width: 440, }, pending_stats_box: { width: 100, margin: 5 }, pending_stats_amount: { fontSize: 26, fontWeight: 'bold', textAlign: 'center' }, pending_stats_category: { fontSize: 14, textAlign: 'center' } } class Overview extends Component { constructor(props) { super(props) } componentDidMount() { this.props.loadOverview() } render() { const { expenses } = this.props let pendingItems if(expenses.overview.pending) { var index = 0 pendingItems = expenses.overview.pending.map(pending => { index++ return (<View style={localStyles.pending_stats_box} key={index}> <Text style={localStyles.pending_stats_amount}>{pending.total.toFixed(2)}</Text> <Text style={localStyles.pending_stats_category}>{pending.name}</Text> </View>) }); } return ( <View style={styles.container}> <View style={localStyles.pending_stats_container}> {pendingItems} </View> </View> ) } } function stateToProps(state) { let { expenses } = state return { expenses } } function dispatchToProps(dispatch) { let actions = _.extend({}, expensesActions) return bindActionCreators(actions, dispatch) } export default connect(stateToProps, dispatchToProps)(Overview)
/* ./src/main.js The main entry point into the node application. Here we initialize forks */ "use strict"; const cluster = require("cluster"); const pkg = require("../package"); const config = require("./config"); if (cluster.isMaster) { console.info(`Starting ${pkg.name}!`); const workers = config.server.workers; const forks = new Array(workers); // Iterate through how many workers we're creating and create them for (let i = 0; i < workers; ++i) { console.info(`Initializing worker ${i}`); forks[i] = cluster.fork({ worker: i }); } // Handle worker failures by restarting them cluster.on("exit", (fork, code, signal) => { for (let i = 0; i < forks.length; ++i) { if (forks[i] === fork) { if (code !== 0) { console.warn(`Worker ${i} has failed. Attempting to restart it...`); } forks[i] = cluster.fork({ worker: i }); } } }); } else if (cluster.isWorker) { // Require the web server to start it up! require("./servers/web")(); }
export default { name: '星形', title: 'Polygone/Star Tool', buttons: [ { title: '星形工具' }, { title: '多边形工具' } ], contextTools: [ { title: '顶点', label: '顶点' }, { title: '钝度', label: '钝度' }, { title: '径向', label: '径向' }, { title: '边数', label: '边数' } ] }
var five = require("johnny-five"); var board = new five.Board(); board.on("ready", function() { // AD Keypad var keypad; keypad = new five.Keypad({ pin: "A0", keys: ["red", "green", "blue", "3", "yellow", "white", "6"] }); ["change", "press", "hold", "release"].forEach(function(eventType) { keypad.on(eventType, function(data) { console.log("Event: %s, Target: %s", eventType, data.which); }); }); });
/* global module:false */ module.exports = function(grunt) { var port = grunt.option('port') || 8000; // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner: '/*!\n' + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + ' * http://lab.hakim.se/reveal-js\n' + ' * MIT licensed\n' + ' *\n' + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + ' */' }, qunit: { files: [ 'test/*.html' ] }, uglify: { options: { banner: '<%= meta.banner %>\n' }, build: { src: 'js/reveal.js', dest: 'js/reveal.min.js' } }, cssmin: { compress: { files: { 'css/reveal.min.css': [ 'css/reveal.css' ] } } }, sass: { main: { files: { 'css/theme/default.css': 'css/theme/source/default.scss', 'css/theme/beige.css': 'css/theme/source/beige.scss', 'css/theme/night.css': 'css/theme/source/night.scss', 'css/theme/serif.css': 'css/theme/source/serif.scss', 'css/theme/simple.css': 'css/theme/source/simple.scss', 'css/theme/sky.css': 'css/theme/source/sky.scss', 'css/theme/moon.css': 'css/theme/source/moon.scss', 'css/theme/sixty_north.css': 'css/theme/source/sixty_north.scss', 'css/theme/solarized.css': 'css/theme/source/solarized.scss', 'css/theme/blood.css': 'css/theme/source/blood.scss' } } }, jshint: { options: { curly: false, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, eqnull: true, browser: true, expr: true, globals: { head: false, module: false, console: false, unescape: false } }, files: [ 'Gruntfile.js', 'js/reveal.js' ] }, connect: { server: { options: { port: port, base: '.' } } }, zip: { 'reveal-js-presentation.zip': [ 'index.html', 'css/**', 'js/**', 'lib/**', 'images/**', 'plugin/**' ] }, watch: { main: { files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], tasks: 'default' }, theme: { files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], tasks: 'themes' } } }); // Dependencies grunt.loadNpmTasks( 'grunt-contrib-qunit' ); grunt.loadNpmTasks( 'grunt-contrib-jshint' ); grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); grunt.loadNpmTasks( 'grunt-contrib-uglify' ); grunt.loadNpmTasks( 'grunt-contrib-watch' ); grunt.loadNpmTasks( 'grunt-contrib-sass' ); grunt.loadNpmTasks( 'grunt-contrib-connect' ); grunt.loadNpmTasks( 'grunt-zip' ); // Default task grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); // Theme task grunt.registerTask( 'themes', [ 'sass' ] ); // Package presentation to archive grunt.registerTask( 'package', [ 'default', 'zip' ] ); // Serve presentation locally grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); // Run tests grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); };
import Send from './send'; import Headers from './headers'; import Helpers from '../../utils/helpers'; /** * Gets the current supply of a mosaic * * @param {object} endpoint - An NIS endpoint object * @param {string} id - A mosaic id * * @return {object} - A mosaicSupplyInfo object */ let supply = function(endpoint, id) { // Configure the request var options = { url: Helpers.formatEndpoint(endpoint) + '/mosaic/supply', method: 'GET', headers: Headers.urlEncoded, qs: {'mosaicId': id} } // Send the request return Send(options); } module.exports = { supply }
(function() { 'use strict'; // FUNCTIONS // /** * FUNCTION: getResource( url, clbk ) * Fetches a resource from a provided URL and returns the result to a provided callback. * * @param {String} url - resource location * @param {Function} clbk - callback to invoke upon resource receipt. Function should accept one input argument: [ result ] */ function getResource( url, clbk ) { var xhr; // Create a new request object: xhr = new XMLHttpRequest(); // Open the request connection: xhr.open( 'GET', url, true ); // Define the state change callback: xhr.onreadystatechange = function () { if ( xhr.readyState !== 4 || xhr.status !== 200 ){ return; } clbk( xhr.responseText ); }; // Send the request: xhr.send(); } // end FUNCTION getResource() /** * FUNCTION: onData( body ) * Response handler for an HTTP request. Parses the returned data. * * @param {String} body - HTTP response body */ function onData( body ) { var figs, len, charts, el, i; // [0] Grab chart elements... figs = document.querySelectorAll( '.figure' ); len = figs.length; charts = new Array( len ); for ( i = 0; i < len; i++ ) { charts[ i ] = figs[ i ].querySelector( '.chart' ); } // [1] Configure the second figure... el = charts[ 1 ]; el.yMin = 0; el.yMax = 1; el.xLabel = 'time'; el.labels = [ 'cpu.utilization', 'mem.utilization', 'disk.utilization' ]; el.data = el.formatData( JSON.parse( body ) ); el.annotations = [ [ 1417564926959, 'beep boop bap foo' ] ]; } // end FUNCTION onData() // SCRIPT // // Get the template for a figure configuration: window.addEventListener( 'polymer-ready', function onReady() { getResource( './../examples/data/timeseries.json', onData ); }); })();
/** * 文件下载模块 * * @file src/uploader/Transport.js * @author mudio(job.zhanghao@gmail.com) */ import fs from 'fs'; import queue from 'async/queue'; import debounce from 'lodash.debounce'; import {CONTENT_LENGTH, CONTENT_TYPE} from 'bce-sdk-js/src/headers'; import Transport from './transport'; import {TransportStatus} from '../headers'; const kPartSize = 20 * 1024 * 1024; export default class MultiTransport extends Transport { constructor(credentials, config) { super(credentials, config); this._queue = null; } // 最多分片1000片,除了最后一片其他片大小相等且大于等于UploadConfig.PartSize _decompose(orderedParts, maxParts, uploadSize, totalSize) { const minPartSize = Math.ceil(totalSize / (maxParts - orderedParts.length)); const averagePartSize = Math.max(kPartSize, minPartSize); // 余下分片 const remainParts = []; let leftSize = totalSize - uploadSize; let offset = uploadSize; let partNumber = orderedParts.length + 1; while (leftSize > 0) { const partSize = Math.min(leftSize, averagePartSize); remainParts.push({partNumber, partSize, start: offset}); leftSize -= partSize; offset += partSize; partNumber += 1; } return remainParts; } _checkAlive = debounce(() => this._stream.emit('abort'), 10e3); _invoke({partNumber, partSize, start}, done) { /** * 读取流 */ this._stream = fs.createReadStream(this._localPath, { start, end: start + partSize - 1, // eslint-disable-line no-mixed-operators }); /** * 通知进度 */ this._stream.on('progress', ({rate, bytesWritten}) => { this._checkAlive(); this.emit('progress', {rate, bytesWritten: this._uploadedSize + bytesWritten, uuid: this._uuid}); }); const headers = {}; headers[CONTENT_LENGTH] = partSize; headers[CONTENT_TYPE] = 'application/octet-stream'; const options = this._client._checkOptions(headers); return this._client.sendRequest('PUT', { bucketName: this._bucketName, key: this._objectKey, body: this._stream, headers: options.headers, params: {partNumber, uploadId: this._uploadId}, config: options.config, }).then( () => { this._uploadedSize += partSize; done(); }, err => done(err), ); } /** * 重新下载文件 * * @memberof MultiTransport */ resume(remainParts = []) { return new Promise((resolve, reject) => { this._queue = queue((...args) => this._invoke(...args), 1); this._queue.error = (err) => { this._queue.kill(); reject(err); }; this._queue.drain = () => resolve(); this._queue.push(remainParts); }); } /** * 恢复暂停后的下载任务 * * @memberof MultiTransport */ async start() { /** * 重置状态 */ this._state = TransportStatus.Running; /** * 文件不存在还玩个蛋 */ const isExist = fs.existsSync(this._localPath); if (!isExist) { return this._checkError(new Error(`file not found ${this.localPath}`)); } try { const {size} = fs.statSync(this._localPath); // 如果文件大于阈值并且没有uploadId,则获取一次 if (!this._uploadId) { // 先检查如果文件已经在bos上了,则忽略 if (await this._checkConsistency()) { return this._checkFinish(); } const {uploadId} = await this._initUploadId(); this._uploadId = uploadId; } // 获取已上传到分片 const {parts, maxParts} = await this._fetchParts(); // 重新分片 const orderedParts = parts.sort((lhs, rhs) => lhs.partNumber - rhs.partNumber); this._uploadedSize = parts.reduce((pre, cur) => pre + cur.size, 0); const remainParts = this._decompose(orderedParts, maxParts, this._uploadedSize, size); // 上传遗留的分片 if (remainParts.length > 0) { this.emit('start', { uuid: this._uuid, uploadId: this._uploadId, localPath: this._localPath, }); await this.resume(remainParts); } // 完成任务,用文件大小来效验文件一致性 await this._completeUpload(); // 检查任务完成状态 this._checkFinish(); } catch (ex) { this._checkError(ex); } } }
var page = require('webpage').create(), system = require('system'), t, address; if (system.args.length === 1) { console.log('Usage: loadspeed.js <some URL>'); phantom.exit(); } t = Date.now(); address = system.args[1]; page.open(address, function(status) { if (status !== 'success') { console.log('FAIL to load the address'); } else { t = Date.now() - t; console.log('Loading time ' + t + ' msec'); } phantom.exit(); });