text
stringlengths
2
6.14k
$(function() { $(".ajax_filter_choice").click(function() { $(this).parent().siblings().css("font-weight", "normal"); $(this).parent().css("font-weight","bold"); }) }); ajax_filtered_fields = { request_url: "/ajax_filtered_fields/json_index/", data_loaded: "data_loaded", _appendOption: function(obj, selector) { // append a json data row as an option to the selector var option = $('<option>' + obj[1] + '</option>'); option.attr({value: obj[0]}); option.appendTo(selector); return option; }, _removeOptions: function(selector) { // remove all options from selector selector.children("option").each(function(i) { $(this).remove(); }); }, getManyToManyJSON: function(element_id, app_label, object_name, lookup_string, select_related) { // manage the ManyToMany ajax request var selector_from = $("#" + element_id + "_from"); var selector_to = $("#" + element_id + "_to"); $("#" + element_id + "_input").val(""); selector_from.attr("disabled", true); selector_to.attr("disabled", true); this._removeOptions(selector_from); $.getJSON(this.request_url, { app_label: app_label, object_name: object_name, lookup_string: lookup_string, select_related: select_related}, function(data){ $.each(data, function(i, obj){ var option_is_selected = selector_to.children("option[value='" + obj[0] + "']").length; if (!option_is_selected) { ajax_filtered_fields._appendOption(obj, selector_from); }; }); SelectBox.init(element_id + "_from"); selector_from.attr("disabled", false); selector_to.attr("disabled", false); selector_from.trigger(ajax_filtered_fields.data_loaded); }); }, getForeignKeyJSON: function(element_id, app_label, object_name, lookup_string, select_related) { // manage the ForeignKey ajax request var selector = $("#" + element_id); var hidden = $("#hidden-" + element_id); $("#" + element_id + "_input").val(""); selector.attr("disabled", true); this._removeOptions(selector); $.getJSON(this.request_url, { app_label: app_label, object_name: object_name, lookup_string: lookup_string, select_related: select_related}, function(data){ var selection = hidden.val(); ajax_filtered_fields._appendOption(new Array("", "---------"), selector); $.each(data, function(i, obj){ ajax_filtered_fields._appendOption(obj, selector); }); selector.children("option[value='" + selection + "']").attr("selected", "selected"); selector.attr("disabled", false); SelectBox.init(element_id); ajax_filtered_fields.bindForeignKeyOptions(element_id); selector.trigger(ajax_filtered_fields.data_loaded); }); }, bindForeignKeyOptions: function(element_id) { // bind the dummy options to the hidden field that do the work var selector = $("#" + element_id); var hidden = $("#hidden-" + element_id); selector.change(function(e) { hidden.val($(this).val()); }); } };
'use strict'; var type = require('type-detect'); var path = require('path'); var removeTrailingSeparator = require('remove-trailing-path-separator'); var errors = require('common-errors'); var prettyFormat = require('pretty-format'); module.exports = function (input, cb) { if (type(input) !== 'string') { cb(new errors.TypeError('input requires string'), null); return; } var split = removeTrailingSeparator(path.normalize(input)).split(path.sep); var inputLast = split[split.length - 1]; if (['', '.', '..'].some(function (value) { return inputLast === value; })) { cb(new errors.ArgumentError('input is not allowed: ' + prettyFormat(inputLast)), null); return; } cb(null, inputLast); };
const test = require('tape') const nlp = require('../_lib') test('before-basic', function(t) { let doc = nlp('one two three four five. one three four') let arr = doc.before('three four').out('array') t.equal(arr.length, 2, 'two-matches') t.equal(arr[0], 'one two', 'first-match') t.equal(arr[1], 'one', 'second-match') doc = nlp('one two three four five. one three four. three four') arr = doc.before('three').out('array') t.equal(arr.length, 2, 'two-matches') t.equal(arr[0], 'one two', 'first-match') t.equal(arr[1], 'one', 'second-match') t.end() }) test('before-match:', function(t) { let r = nlp('one two three four five').before('two') t.equal(r.out('normal'), 'one', 'before-two') r = nlp('one two three four five').before('three . five') t.equal(r.out('normal'), 'one two', 'before-several') r = nlp('one two three four five').before('one two') t.equal(r.out('normal'), '', 'no-before-start') // r = nlp('one two three four').before('.'); //tricky // t.equal(r.out('normal'), '', 'before-any'); r = nlp('one two three four. No, not here. He said two days a week.').before('two') let arr = r.out('array') t.equal(arr[0], 'one', 'before-twice-1') t.equal(arr[1], 'He said', 'before-twice-2') r = nlp('it was all the way over to two. It was the number two.').before('it') t.equal(r.found, false, 'no-empty-matches') t.end() }) test('after-match:', function(t) { let r = nlp('one two three four five').after('two') t.equal(r.out('normal'), 'three four five', 'after-one') r = nlp('one two three four five').after('one . three') t.equal(r.out('normal'), 'four five', 'after-several') r = nlp('one two three four five').after('four five') t.equal(r.out('normal'), '', 'no-afters-end') r = nlp('one two three four').after('.') t.equal(r.out('normal'), 'two three four', 'after-any') r = nlp('one two three four. No, not here. He said two days a week.').after('two') let arr = r.out('array') t.equal(arr[0], 'three four.', 'after-twice-1') t.equal(arr[1], 'days a week.', 'after-twice-2') r = nlp('all the way over to two. It was the number two.').after('two') t.equal(r.found, false, 'no-empty-matches') t.end() })
/** * The DOM Element unit handling * * Copyright (C) 2008-2011 Nikolay Nemshilov */ var Element = RightJS.Element = new Class(Wrapper, { /** * constructor * * NOTE: this constructor will dynamically typecast * the wrappers depending on the element tag-name * * @param String element tag name or an HTMLElement instance * @param Object options * @return Element element */ initialize: function(element, options) { Element_initialize(this, element, options); } }, Element_Klass), Element_wrappers = Element.Wrappers = {}, elements_cache = {}, /** * bulds dom-elements * * @param String element tag name * @param Object options * @return HTMLElement */ make_element = function (tag, options) { return (tag in elements_cache ? elements_cache[tag] : ( elements_cache[tag] = document.createElement(tag) )).cloneNode(false); }; // // IE 6,7,8 (not 9!) browsers have a bug with checkbox and radio input elements // it doesn't place the 'checked' property correctly, plus there are some issues // with clonned SELECT objects, so we are replaceing the elements maker in here // if (IE8_OR_LESS) { make_element = function(tag, options) { if (options !== undefined && (tag === 'input' || tag === 'button')) { tag = '<'+ tag +' name="'+ options.name + '" type="'+ options.type +'"'+ (options.checked ? ' checked' : '') + ' />'; delete(options.name); delete(options.type); } return document.createElement(tag); }; } /** * Basic element's constructor * * @param Element wrapper instance * @param mixed raw dom element of a string tag name * @param Object options * @return void */ function Element_initialize(inst, element, options) { if (typeof element === 'string') { inst._ = make_element(element, options); if (options !== undefined) { for (var key in options) { switch (key) { case 'id': inst._.id = options[key]; break; case 'html': inst._.innerHTML = options[key]; break; case 'class': inst._.className = options[key]; break; case 'on': inst.on(options[key]); break; default: inst.set(key, options[key]); } } } } else { inst._ = element; } }
// @flow import type { ConfigSparseWithSource } from '../../'; import configResolve from '../'; type Fixture = { name: string, in: ConfigSparseWithSource, }; const fixtures: Fixture[] = [ { name: '01 empty input config', in: {}, }, { name: '02 empty input config with configFile', in: { configFile: '/foo/bar/package.json', }, }, { name: '03 empty input config with rootDir', in: { rootDir: '/foo/bar', }, }, { name: '04 empty input config with both configFile and rootDir', in: { configFile: '/a/b/c/package.json', rootDir: '/foo/bar', }, }, ]; describe('lib/config/resolve', () => { fixtures.forEach((fixture) => { it(fixture.name, () => { const received = configResolve(fixture.in); expect(received).toMatchSnapshot(); }); }); });
var sys = require('pex-sys'); var glu = require('pex-glu'); var geom = require('pex-geom'); var gen = require('pex-gen'); var materials = require('pex-materials'); var color = require('pex-color'); var gui = require('pex-gui'); var Cube = gen.Cube; var Sphere = gen.Sphere; var Mesh = glu.Mesh; var TexturedCubeMap = materials.TexturedCubeMap; var SkyBox = materials.SkyBox; var PerspectiveCamera = glu.PerspectiveCamera; var Arcball = glu.Arcball; var Color = color.Color; var TextureCube = glu.TextureCube; var GUI = gui.GUI; sys.Window.create({ settings: { width: 1280, height: 720, type: '3d', fullscreen: sys.Platform.isBrowser }, lod: 4, init: function() { this.gui = new GUI(this); this.gui.addParam('Mipmap level', this, 'lod', { min: 0, max: 8, step: 1 }); var levels = ['m00']; var sides = ['c00', 'c01', 'c02', 'c03', 'c04', 'c05']; var cubeMapFiles = []; levels.forEach(function(level) { sides.forEach(function(side) { cubeMapFiles.push('../../assets/cubemaps/uffizi_lod/uffizi_' + level + '_' + side + '.png'); }); }); var cubeMap = TextureCube.load(cubeMapFiles, { mipmap: true }); this.mesh = new Mesh(new Sphere(), new TexturedCubeMap({ texture: cubeMap })); this.cubeMesh = new Mesh(new Cube(50), new SkyBox({ texture: cubeMap })); this.camera = new PerspectiveCamera(60, this.width / this.height); this.arcball = new Arcball(this, this.camera); }, draw: function() { if (!this.mesh.material.uniforms.texture.ready) return; glu.clearColorAndDepth(Color.Black); glu.enableDepthReadAndWrite(true); this.cubeMesh.material.uniforms.lod = this.lod; this.cubeMesh.draw(this.camera); this.mesh.draw(this.camera); this.mesh.material.uniforms.lod = this.lod; this.gui.draw(); } });
// namespace line first import * as XA from "X"; import XD, { X2 } from "X"; import { X3 } from "X";
'use strict'; // // Third party modules. // module.exports = require('canihaz')({ location: __dirname, dot: 'smithy' });
import path from 'path' import inquirer from 'inquirer' import downloadTwitterPhoto from './utils/download-twitter-photo' inquirer.prompt([ { name: 'twitter', type: 'input', message: 'Twitter handle?', }, ]).then(({twitter}) => { const destinationPath = path.join(process.cwd(), 'data/contributors') downloadTwitterPhoto(twitter, destinationPath) })
'use strict'; angular.module('core').controller('HomeController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { // ===================================================================== // Non $scope member // ===================================================================== var init = function() { $scope.authentication = Authentication; }; init(); var redirectToHome = function(user) { var location = '/'; if(user.roles.indexOf('admin') !== -1) { location = '/admin/home'; } else if(user.roles.indexOf('ero') !== -1) { location = '/ero/home'; } else if(user.roles.indexOf('resource') !== -1) { location = '/resource/home'; } $location.path(location); }; if ($scope.authentication.user) { redirectToHome($scope.authentication.user); } // ===================================================================== // $scope Member // ===================================================================== $scope.prepare = function() { $scope.credentials = { email: null, password: null }; }; $scope.signin = function() { $scope.authenticationPromise = $http.post('/api/auth/signin', $scope.credentials).success(function(response) { $scope.authentication.user = response; redirectToHome($scope.authentication.user); }).error(function(response) { $scope.error = response.message; }); }; // ===================================================================== // Event listener // ===================================================================== } ]);
import React, { useCallback, useState } from 'react'; import { css } from 'emotion'; import { Button, Col, Input, Row } from 'reactstrap'; import Localized from 'components/Localized/Localized'; import LocationsCount from 'components/LocationsCount/LocationsCount'; import { useTranslation } from 'react-i18next'; import { Link } from 'react-router-dom'; import { GoX } from 'react-icons/go'; import { useSelectAll } from 'selectors/selectAll'; import { logEvent } from 'utils/analytics'; import DefaultLocationsList from './DefaultLocationsList'; import CustomLocationsList from './CustomLocationsList'; import FilteredLocationsList from './FilteredLocationsList'; import ExportLocations from './ExportLocations'; import DownloadLocations from './DownloadLocations'; export const Settings = () => { const [t] = useTranslation(); const [filter, setFilter] = useState(''); const { selectAllLocations, deselectAllLocations } = useSelectAll(); const onFilterChange = useCallback((event) => { logEvent('LOCATIONS_FILTER'); setFilter(event.target.value); }, []); const onClearFilter = useCallback(() => { logEvent('LOCATIONS_FILTER_CLEAR'); setFilter(''); }, []); return ( <Row className={`${styles.container} justify-content-center`}> <Col xs={12} md={10}> <Row className={styles.locationsContainer}> <Col className="text-center"> <h4><Localized name="interface.game_locations" /> (<LocationsCount />)</h4> </Col> </Row> <Row className={`${styles.filterContainer} justify-content-center`}> <Col className="text-center"> <Input placeholder={t('interface.filter')} value={filter} onChange={onFilterChange} /> {!!filter && <GoX className={`${styles.clearFilter} text-dark`} onClick={onClearFilter} />} </Col> </Row> {!filter && ( <> <DefaultLocationsList version={1} onSelectAll={selectAllLocations} onDeselectAll={deselectAllLocations} /> <DefaultLocationsList version={2} onSelectAll={selectAllLocations} onDeselectAll={deselectAllLocations} /> <CustomLocationsList onSelectAll={selectAllLocations} onDeselectAll={deselectAllLocations} /> </> )} {!!filter && <FilteredLocationsList filter={filter} />} <ExportLocations /> <DownloadLocations /> <Row className={`${styles.backContainer} justify-content-center`}> <Col xs={12} className="text-center"> <Link className={styles.backLink} to="/"> <Button color="danger" block><Localized name="interface.back_to_game" /></Button> </Link> </Col> </Row> </Col> </Row> ); }; const styles = { container: css({ marginBottom: 50, }), locationsContainer: css({ marginTop: 20, }), filterContainer: css({ marginTop: 20, }), backContainer: css({ marginTop: 20, }), backLink: css({ textDecoration: 'none', ':hover': { textDecoration: 'none', }, }), clearFilter: css({ position: 'absolute', right: 25, top: 8, fontSize: 22, cursor: 'pointer', }), }; export default React.memo(Settings);
import styled from 'styled-components'; export const Container = styled.div` width: 100%; height: 100%; `; export const EditorContainer = styled.div` ${''/* padding: 30px 30px; */} width: 100%; box-sizing: border-box; position: relative; font-family: 'Proxima-Nova', 'helvetica', 'arial'; box-sizing: border-box; font-size: 21px; color: #131517; font-weight: 300; line-height: 1.54; & h1 { font-size: 48px; font-weight: bold; letter-spacing: -.024em; line-height: 1.18; margin-bottom: 20px; color: #131517; } & h2 { font-size: 28px; font-weight: normal; letter-spacing: -.008em; line-height: 1.24; margin-bottom: 20px; color: #797C80; } & ul { padding-left: 24px; ${''/* list-style: none; */} } & ol { padding-left: 24px; ${''/* list-style: none; */} } & li { font-size: 21px; line-height: 1,78; }::selection { background-color: #B1DFCB; } `;
/*globals rabbitmq_test_bindings: false, rabbitmq_bindings_to_remove: false */ /*jslint mocha: true */ "use strict"; var expect = require('chai').expect, util = require('util'), Qlobber = require('..').Qlobber; function QlobberTopicCount (options) { Qlobber.call(this, options); this.topic_count = 0; } util.inherits(QlobberTopicCount, Qlobber); QlobberTopicCount.prototype._initial_value = function (val) { this.topic_count += 1; return Qlobber.prototype._initial_value(val); }; QlobberTopicCount.prototype._remove_value = function (vals, val) { var removed = Qlobber.prototype._remove_value(vals, val); if (removed) { this.topic_count -= 1; } return removed; }; QlobberTopicCount.prototype.clear = function () { this.topic_count = 0; return Qlobber.prototype.clear.call(this); }; describe('qlobber-topic-count', function () { it('should be able to count topics added', function () { var matcher = new QlobberTopicCount(); rabbitmq_test_bindings.forEach(function (topic_val) { matcher.add(topic_val[0], topic_val[1]); }); expect(matcher.topic_count).to.equal(25); rabbitmq_bindings_to_remove.forEach(function (i) { matcher.remove(rabbitmq_test_bindings[i-1][0], rabbitmq_test_bindings[i-1][1]); }); expect(matcher.topic_count).to.equal(21); matcher.clear(); expect(matcher.topic_count).to.equal(0); expect(matcher.match('a.b.c').length).to.equal(0); }); it('should not decrement count if entry does not exist', function () { var matcher = new QlobberTopicCount(); expect(matcher.topic_count).to.equal(0); matcher.add('foo.bar', 23); expect(matcher.topic_count).to.equal(1); matcher.remove('foo.bar', 24); expect(matcher.topic_count).to.equal(1); matcher.remove('foo.bar2', 23); expect(matcher.topic_count).to.equal(1); matcher.remove('foo.bar', 23); expect(matcher.topic_count).to.equal(0); matcher.remove('foo.bar', 24); expect(matcher.topic_count).to.equal(0); matcher.remove('foo.bar2', 23); expect(matcher.topic_count).to.equal(0); }); });
'use strict'; /* eslint-disable no-console */ const cryptoJS = require('crypto-js'); module.exports = { toJsonObj: function (str) { try { return JSON.parse(str); } catch (e) { return false; } }, getMacString: function (req) { var arr = []; for (let key in req) { if (req.hasOwnProperty(key)) { arr.push(key + '=' + req[key]); } } arr.sort(); return arr.join(':'); }, calculateMac: function (macString, secret) { return '1:' + cryptoJS.enc.Base64.stringify(cryptoJS.HmacSHA256(macString, secret)); }, encodeData: function (data) { return Object.keys(data).map(function (key) { return [key, data[key]].map(encodeURIComponent).join('='); }).join('&'); } }
/** * download webdriver */ var path = require('path'); var fs = require('fs'); var rimraf = require('rimraf'); var Download = require('download'); var Decompress = require('decompress'); var fse = require('fs-extra'); var debug = require('debug')('browser'); var chromeVersion = '2.20'; var phantomVersion = '1.9.7'; var basePath = 'https://npm.taobao.org/mirrors/'; var driversDest = path.resolve(__dirname, './driver'); /** * 下载对应平台的 driver */ function downloadDrivers() { var driversConfig = { darwin: [ {name: 'phantomjs-darwin', url: 'phantomjs/phantomjs-' + phantomVersion + '-macosx.zip'}, {name: 'chromedriver-darwin', url: 'chromedriver/' + chromeVersion + '/chromedriver_mac32.zip'} ], win32: [ {name: 'chromedriver.exe', url: 'chromedriver/' + chromeVersion + '/chromedriver_win32.zip'}, {name: 'phantomjs.exe', url: 'phantomjs/phantomjs-' + phantomVersion + '-windows.zip'} ], linux: [ {name: 'phantomjs-linux', url: 'phantomjs/phantomjs-' + phantomVersion + '-linux-x86_64.tar.bz2'} ] }; var driverConfig = driversConfig[process.platform]; var count = 0; console.log('load: download webDrivers...'); if (fs.existsSync(driversDest)) { rimraf.sync(driversDest); } fs.mkdirSync(driversDest); driverConfig.forEach(function(item) { var download = new Download({ mode: '777' // 取不出 tar // extract: true }); debug('download', item); download .get(basePath + item.url) // .rename(item.name) .dest(path.resolve(__dirname, './driver/')) .run(function(err, files) { if (err) { throw new Error('Download drivers error, please reinstall ' + err.message); } var downloadFilePath = files[0].path; var compressDir = path.resolve(driversDest, './' + item.name + '-dir'); debug('下载完一个文件:', downloadFilePath, '开始压缩:'); new Decompress({mode: '777'}) .src(downloadFilePath) .dest(compressDir) .use(Decompress.zip({strip: 1})) .run(function(err) { if (err) { throw err; } debug('压缩完一个文件'); var type = /phantom/.test(item.name) ? 'phantomjs' : 'chromedriver'; reworkDest(downloadFilePath, compressDir, type); debug('更改文件权限'); fs.chmodSync(path.resolve(driversDest, item.name), '777'); count ++; if (count >= driverConfig.length) { console.log('Download drivers successfully.'); } }); }); }); } /** * 解压之后对文件夹重新整理 */ function reworkDest(downloadFilePath, compressDir, type) { // 清理下载的压缩文件 fse.removeSync(downloadFilePath); var binName = type + (process.platform === 'win32' ? '.exe' : '-' + process.platform); var binSrcPath = path.resolve(compressDir, type === 'phantomjs' ? './bin/phantomjs' : './chromedriver'); var binDestPath = path.resolve(driversDest, binName); debug('复制 bin 文件:', binSrcPath, binDestPath); fse.copySync(binSrcPath, binDestPath); debug('移除源的文件夹'); fse.removeSync(compressDir); } downloadDrivers();
import { combineReducers } from 'redux'; import PostsReducer from './reducer-posts'; import { reducer as formReducer } from 'redux-form'; const rootReducer = combineReducers({ posts: PostsReducer, form: formReducer }); export default rootReducer;
__d("UPoCs",function(o,e,s){s.exports="Here is brisk demo!"});
var icons = [ 'moneybag', 'save', 'establishment', 'completion', 'share', 'no_money', 'euro', 'palette', 'puzzle', 'backward', 'partial', 'minimize', 'tick', 'tick_thin', 'tick_bold', 'compass', 'minus', 'supplies', 'alarm', 'analytics', 'charts', 'apps', 'nine_tiles', 'archive', 'arrow_double', 'forward', 'arrow_east', 'east_arrow', 'east_thin_arrow', 'chevron_east', 'arrow_full_east', 'arrow_full_north', 'arrow_full_south', 'arrow_full_west', 'arrow_north', 'north_arrow', 'north_thin_arrow', 'chevron_north', 'arrow_south', 'south_arrow', 'south_thin_arrow', 'chevron_south', 'arrow_west', 'west_arrow', 'west_thin_arrow', 'chevron_west', 'priority_lowest', 'priority_highest', 'answer', 'api_sync', 'attach', 'banking_card', 'bill', 'birthday', 'book', 'branch', 'breakfast', 'broken_heart', 'build', 'bus', 'calendar', 'calendar_off', 'planning', 'calendar_checked', 'camera', 'car', 'certif_ok', 'certif_ko', 'certif_waiting', 'chat', 'talk', 'messenger', 'dialog', 'chrono_on', 'clean_car', 'clock', 'close', 'thin_cross', 'cross', 'cross_bold', 'coffee', 'breakTime', 'collapse', 'computer', 'computer_mouse', 'contract', 'copy', 'credit_debit', 'cut', 'dashboard', 'database', 'diner', 'discount', 'distribute', 'dollar', 'download', 'drag', 'drink', 'edit', 'edit_mini', 'edit_write', 'editFrame', 'equal', 'error', 'evolution', 'evolution_down', 'expand', 'family_tree', 'org_tree', 'file', 'file_export', 'file_import', 'import_dirty', 'import_pristine', 'filter', 'filter_abstract', 'flag', 'folder', 'forbidden', 'format_bold', 'format_clear', 'format_italic', 'format_justify', 'format_link', 'format_list_nb', 'format_redo', 'format_size', 'format_strikethrough', 'format_underlined', 'format_undo', 'fullscreen', 'fullscreen_exit', 'gallery', 'gasoline', 'gift', 'present', 'heart', 'help', 'help_outline', 'history', 'home', 'hotel', 'image', 'import_cb', 'info', 'iron', 'journey', 'milestone', 'key', 'laptop', 'light_bulb', 'list', 'list_checked', 'list_todo', 'location', 'lock', 'login', 'logout', 'lucca', 'luggage', 'lunch', 'meal', 'lunch_alternative', 'mail', 'mailbox', 'stamp', 'postage', 'menu', 'hamburger_menu', 'menu_ellipsis', 'ellipsis', 'mileage', 'money', 'payment', 'notification', 'outside', 'overplanned', 'parking', 'paste', 'clipboard', 'piggy_bank', 'pause', 'pay_period', 'pin', 'plane', 'planning_edit', 'planning_manage', 'play', 'play_full', 'plus', 'plus_bold', 'postpone', 'pressing', 'pricetag', 'print', 'refresh', 'update', 'reply', 'restaurant', 'user_roles', 'rotate', 'rotate_right', 'school', 'search', 'send', 'send2User', 'settings', 'sign', 'sliders', 'snack', 'sort', 'reorder', 'star', 'stop', 'subway', 'success', 'sync', 'sync_disabled', 'table', 'target', 'taxi', 'telephone', 'test', 'timer', 'timesheet', 'thumb_down', 'thumb_up', 'thumbnail', 'toll', 'toll_dollar', 'toll_euro', 'tools', 'train', 'trash', 'truck', 'unlink', 'unlock', 'unstared', 'unwatch', 'upload', 'cloud_upload', 'user', 'face', 'user_add', 'addUser', 'user_file', 'dossier_rh', 'user_group', 'group', 'user_remove', 'wallet', 'warning', 'watch', 'weather_cloudy', 'weather_storm', 'weather_sun', 'weight', 'divide', 'crown', 'unarchive', ]; export default icons;
import Ember from 'ember'; import moment from 'moment'; import dateFormat from '../utils/date-format'; export default Ember.Controller.extend({ loadingMeta: false, notify: Ember.inject.service(), aggController: Ember.inject.controller('discover.aggregate'), queryParams: ['center', 'obs_date__le', 'obs_date__ge', 'agg', 'location_geom__within'], obs_date__le: dateFormat(moment()), obs_date__ge: dateFormat(moment().subtract(90, 'days')), agg: 'week', center: 'default', location_geom__within: null, _resetParams() { this.set('obs_date__le', dateFormat(moment())); this.set('obs_date__ge', dateFormat(moment().subtract(90, 'days'))); this.set('agg', 'week'); this.set('center', 'default'); this.set('location_geom__within', null); }, queryParamsHash: Ember.computed('obs_date__le', 'obs_date__ge', 'agg', 'center', 'location_geom__within', function () { return this.getProperties(this.get('queryParams')); }), queryParamsClone() { return Ember.copy(this.get('queryParamsHash')); }, // Central location to define all acceptable values for aggregate-query-maker // IDs for cities, their display names, and bounds (usually city limits) // City bounding boxes determined via https://www.mapdevelopers.com/geocode_bounding_box.php cities: { default: { // "Cities" named "default" are not shown to the user // This is a copy of Chicago bounds: [ [42.023131, -87.940267], // NW corner [41.644335, -87.523661], // SE corner ], location: [41.795509, -87.581916], zoom: 10, }, chicago: { label: 'Chicago, IL', bounds: [ [42.023131, -87.940267], // NW corner [41.644335, -87.523661], // SE corner ], location: [41.795509, -87.581916], zoom: 10, }, newyork: { label: 'New York, NY', bounds: [ [40.917577, -74.259090], // NW corner [40.477399, -73.700272], // SE corner ], location: [40.7268362, -74.0017699], zoom: 10, }, seattle: { label: 'Seattle, WA', bounds: [ [47.734140, -122.459696], [47.491912, -122.224433], ], location: [47.6076397, -122.3258644], zoom: 10, }, sanfrancisco: { label: 'San Francisco, CA', bounds: [ [37.929820, -123.173825], // NW corner (yes, the city limits DO include those tiny islands) [37.639830, -122.281780], // SE corner ], location: [37.7618864, -122.4406926], zoom: 12, }, austin: { label: 'Austin, TX', bounds: [ [30.516863, -97.938383], // NW corner [30.098659, -97.568420], // SE corner ], location: [30.3075693, -97.7399898], zoom: 10, }, denver: { label: 'Denver, CO', bounds: [ [39.914247, -105.109927], // NW corner [39.614430, -104.600296], // SE corner ], location: [39.7534338, -104.890141], zoom: 11, }, bristol: { label: 'Bristol, England, UK', bounds: [ [51.544433, -2.730516], // NW corner [51.392545, -2.450902], // SE corner ], location: [51.4590572, -2.5909956], zoom: 11, }, atlanta: { label: 'Atlanta, GA', bounds: [ [33.647808, -84.551819], [33.887618, -84.2891076], ], location: [33.748998, -84.388113], zoom: 10, }, }, aggOptions: ([ { id: 'day', label: 'day' }, { id: 'week', label: 'week' }, { id: 'month', label: 'month' }, { id: 'quarter', label: 'quarter' }, { id: 'year', label: 'year' }, ]), resOptions: ([ { id: '100', label: '100 meters' }, { id: '200', label: '200 meters' }, { id: '300', label: '300 meters' }, { id: '400', label: '400 meters' }, { id: '500', label: '500 meters' }, { id: '1000', label: '1 kilometer' }, ]), // ------------- end of central aggregate-query-maker values ---------------// // _zoomIn() { // this.set('zoom', true); // const self = this; // Ember.run.next(() => { // self.set('zoom', false); // }); // }, _resetDatePickers() { this.set('override', true); Ember.run.next(() => { this.set('override', false); }); }, _inIndex() { // Thanks: https://gist.github.com/eliotsykes/8954cf64fcd0df16f519 return Ember.getOwner(this).lookup('controller:application').currentPath === 'discover.index'; }, actions: { submit() { if (this.get('submitCooldown')) { this.get('notify').info('Cooldown active. Please wait a few seconds between query submissions.'); return; } // Implement a cooldown on the submit button to // prevent double-clicks from reloading the query // before a new one begins (resulting in undefined behavior) this.set('submitCooldown', true); Ember.run.later(this, function () { this.set('submitCooldown', false); }, 500); // Reflect to find if we need to transition, // or just reload current model. if (this._inIndex()) { this.transitionToRoute('discover.aggregate'); } else { this.get('aggController').send('submit'); } // Refocus map on user-drawn shape. // if (this.get('location_geom__within')) { // this._zoomIn(); // } }, reset() { if (!this._inIndex()) { this.transitionToRoute('index'); } this._resetParams(); this._resetDatePickers(); }, }, });
version https://git-lfs.github.com/spec/v1 oid sha256:5df6faea233808c6556f6ab7b79d7e126b054faf6651af82437fe36f225404cf size 1193
// _____ _ _ _ _ _ // | ___| | (_) | | | | | | // _ __ |___ \ ___| |_ ___| | ____ _| |__ | | ___ // | '_ \ \ \/ __| | |/ __| |/ / _` | '_ \| |/ _ \ // | |_) /\__/ / (__| | | (__| < (_| | |_) | | __/ // | .__/\____(_)___|_|_|\___|_|\_\__,_|_.__/|_|\___| // | | www.github.com/lartu/p5.clickable // |_| created by Lartu, version 1.2 //Determines if the mouse was pressed on the previous frame var cl_mouseWasPressed = false; //Last hovered button var cl_lastHovered = null; //Last pressed button var cl_lastClicked = null; //All created buttons var cl_clickables = []; //This function is what makes the magic happen and should be ran after //each draw cycle. p5.prototype.runGUI = function(){ for(i = 0; i < cl_clickables.length; ++i){ if(cl_lastHovered != cl_clickables[i]) cl_clickables[i].onOutside(); } if(cl_lastHovered != null){ if(cl_lastClicked != cl_lastHovered){ cl_lastHovered.onHover(); } } if(!cl_mouseWasPressed && cl_lastClicked != null){ cl_lastClicked.onPress(); } if(cl_mouseWasPressed && !mouseIsPressed && cl_lastClicked != null){ if(cl_lastClicked == cl_lastHovered){ cl_lastClicked.onRelease(); } cl_lastClicked = null; } cl_lastHovered = null; cl_mouseWasPressed = mouseIsPressed; } p5.prototype.registerMethod('post', p5.prototype.runGUI); //Button Class function Clickable(x,y,img) { this.x = x || 0; //X position of the clickable this.y = y || 0; //Y position of the clickable this.width = img ? img.width : 100; //Width of the clickable this.height = img ? img.height : 50; //Height of the clickable this.color = "#FFFFFF"; //Background color of the clickable this.cornerRadius = 10; //Corner radius of the clickable this.strokeWeight = 2; //Stroke width of the clickable this.stroke = "#000000"; //Border color of the clickable this.text = "Press Me"; //Text of the clickable this.textColor = "#000000"; //Color for the text shown this.textSize = 12; //Size for the text shown this.textFont = "sans-serif"; //Font for the text shown this.img = img; this.onHover = function(){ //This function is ran when the clickable is hovered but not //pressed. } this.onOutside = function(){ //This function is ran when the clickable is NOT hovered. } this.onPress = function(){ //This function is ran when the clickable is pressed. } this.onRelease = function(){ //This funcion is ran when the cursor was pressed and then //released inside the clickable. If it was pressed inside and //then released outside this won't work. } this.locate = function(x, y){ this.x = x; this.y = y; } this.resize = function(w, h){ this.width = w; this.height = h; } this.draw = function() { if (this.img != null) { image(this.img, this.x, this.y, this.width, this.height); } else { fill(this.color); stroke(this.stroke); strokeWeight(this.strokeWeight); rect(this.x, this.y, this.width, this.height, this.cornerRadius); fill(this.textColor); noStroke(); textAlign(CENTER, CENTER); textSize(this.textSize); textFont(this.textFont); text(this.text, this.x+1, this.y+1, this.width, this.height); } if(mouseX >= this.x && mouseY >= this.y && mouseX < this.x+this.width && mouseY < this.y+this.height){ cl_lastHovered = this; if(mouseIsPressed && !cl_mouseWasPressed) cl_lastClicked = this; } } cl_clickables.push(this); }
"use strict"; let express = require('express'); let app = express(); let bodyParser = require('body-parser'); var randomPoem = require('./tools/poemBuilder1.js') app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); app.use(express.static("client")) app.use(bodyParser.json()); app.get("/poem", function(req, res) { res.render('index', {data: randomPoem()}); }) /////???????////?////????//? let mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/literate_telegram"); let WordPairSchema = new mongoose.Schema({ aKey: String, bKey: String, cKey: String, aPhones: String, bPhones: String, cPhones: String, aCount: Number, bCount: Number, cCount: Number, occurances: Number, }); let PronunciationSchema = new mongoose.Schema({ key: String, phones: String, syllable_count: Number, alternate: Boolean }); var Pronunciation = mongoose.model("Pronunciation", PronunciationSchema); var WordPair = mongoose.model("WordPair", WordPairSchema); app.post("/pronunciation", function(req, res){ console.log(req.body); // Pronunciation.findOne({key: req.body.key}, function(err, word){ // if(err) res.status(404).json(err) // else res.json(word); // }) }) app.get("/word-pairs/random", function(req, res){ WordPair.aggregate([{$sample: {size: 1}},{$project: {_id: false, aKey:true, bKey:true}}], function(err, words){ res.json(words[0]); }); }) app.post("/word-pairs/next", function(req, res){ // console.log(req.body) WordPair.aggregate([{$match: {aKey: req.body.bKey}}, {$sample: {size: 1}}, {$project: {_id: false, aKey:true, bKey:true}}], function(err, pairs){ // console.log(pairs); res.json(pairs); }) }) app.listen(1337, function(){ console.log('l33t rhymes') });
/* Game namespace */ var game = { // an object where to store game information data : { // score score : 0 }, // Run on page load. "onload" : function () { // Initialize the video. if (!me.video.init("screen", me.video.CANVAS, 1067, 600, true, '1.0')) { alert("Your browser does not support HTML5 canvas."); return; } // add "#debug" to the URL to enable the debug Panel if (document.location.hash === "#debug") { window.onReady(function () { me.plugin.register.defer(this, debugPanel, "debug"); }); } // Initialize the audio. me.audio.init("mp3,ogg"); // Set a callback to run when loading is complete. me.loader.onload = this.loaded.bind(this); // Load the resources. me.loader.preload(game.resources); // Initialize melonJS and display a loading screen. me.state.change(me.state.LOADING); }, // Run on game resources loaded. "loaded" : function () { me.pool.register("player", game.PlayerEntity, true); me.state.set(me.state.MENU, new game.TitleScreen()); me.state.set(me.state.PLAY, new game.PlayScreen()); // Start the game. me.state.change(me.state.PLAY); } };
/** * @class EZ3.Box * @constructor * @param {EZ3.Vector3} [min] * @param {EZ3.Vector3} [max] */ EZ3.Box = function(min, max) { /** * @property {EZ3.Vector3} min * @default new EZ3.Vector3(Infinity) */ this.min = (min !== undefined) ? min : new EZ3.Vector3(Infinity); /** * @property {EZ3.Vector3} max * @default new EZ3.Vector3(-Infinity) */ this.max = (max !== undefined) ? max : new EZ3.Vector3(-Infinity); }; EZ3.Box.prototype.constructor = EZ3.Box; /** * @method EZ3.Box#set * @param {EZ3.Vector3} min * @param {EZ3.Vector3} max * @return {EZ3.Box} */ EZ3.Box.prototype.set = function(min, max) { this.min.copy(min); this.max.copy(max); return this; }; /** * @method EZ3.Box#copy * @param {EZ3.Box} box * @return {EZ3.Box} */ EZ3.Box.prototype.copy = function(box) { this.min.copy(box.min); this.max.copy(box.max); return this; }; /** * @method EZ3.Box#clone * @return {EZ3.Box} */ EZ3.Box.prototype.clone = function() { return new EZ3.Box(this.min, this.max); }; /** * @method EZ3.Box#expand * @param {EZ3.Vector3} point * @return {EZ3.Box} */ EZ3.Box.prototype.expand = function(point) { this.min.min(point); this.max.max(point); return this; }; /** * @method EZ3.Box#union * @param {EZ3.Box} box * @return {EZ3.Box} */ EZ3.Box.prototype.union = function(box) { this.min.min(box.min); this.max.max(box.max); return this; }; /** * @method EZ3.Box#applyMatrix4 * @param {EZ3.Matrix4} matrix * @return {EZ3.Box} */ EZ3.Box.prototype.applyMatrix4 = function(matrix) { var points = []; var i; points.push((new EZ3.Vector3(this.min.x, this.min.y, this.min.z)).mulMatrix4(matrix)); points.push((new EZ3.Vector3(this.min.x, this.min.y, this.max.z)).mulMatrix4(matrix)); points.push((new EZ3.Vector3(this.min.x, this.max.y, this.min.z)).mulMatrix4(matrix)); points.push((new EZ3.Vector3(this.min.x, this.max.y, this.max.z)).mulMatrix4(matrix)); points.push((new EZ3.Vector3(this.max.x, this.min.y, this.min.z)).mulMatrix4(matrix)); points.push((new EZ3.Vector3(this.max.x, this.min.y, this.max.z)).mulMatrix4(matrix)); points.push((new EZ3.Vector3(this.max.x, this.max.y, this.min.z)).mulMatrix4(matrix)); points.push((new EZ3.Vector3(this.max.x, this.max.y, this.max.z)).mulMatrix4(matrix)); this.min.set(Infinity); this.max.set(-Infinity); for (i = 0; i < 8; i++) this.expand(points[i]); return this; }; /** * @method EZ3.Box#size * @return {EZ3.Vector3} */ EZ3.Box.prototype.size = function() { return new EZ3.Vector3().sub(this.max, this.min); }; /** * @method EZ3.Box#getCenter * @return {EZ3.Vector3} */ EZ3.Box.prototype.center = function() { return new EZ3.Vector3().add(this.max, this.min).scale(0.5); };
'use strict'; angular.module('drunkeeperApp') .config(function ($routeProvider) { $routeProvider .when('/login', { templateUrl: 'app/account/login/login.html', controller: 'LoginCtrl' }) .when('/signup', { templateUrl: 'app/account/signup/signup.html', controller: 'SignupCtrl' }) .when('/settings', { templateUrl: 'app/account/settings/settings.html', controller: 'SettingsCtrl', authenticate: true }); });
require('./check-versions')(); const config = require('../config'); if (!process.env.NODE_ENV) { process.env.NODE_ENV = JSON.stringify(config.dev.env.NODE_ENV); } const opn = require('opn'); const path = require('path'); const express = require('express'); const webpack = require('webpack'); const proxyMiddleware = require('http-proxy-middleware'); const webpackConfig = process.env.NODE_ENV === 'testing' ? require('./webpack.prod.conf') : require('./webpack.dev.conf'); // default port where dev server listens for incoming traffic const port = process.env.PORT || config.dev.port; // automatically open browser, if not set will be false const autoOpenBrowser = !!config.dev.autoOpenBrowser; // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware const proxyTable = config.dev.proxyTable; const app = express(); const compiler = webpack(webpackConfig); const devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: true, }); const hotMiddleware = require('webpack-hot-middleware')(compiler, { log: () => {}, }); // force page reload when html-webpack-plugin template changes compiler.plugin('compilation', (compilation) => { compilation.plugin('html-webpack-plugin-after-emit', (data, cb) => { hotMiddleware.publish({ action: 'reload' }); cb(); }); }); // proxy api requests Object.keys(proxyTable).forEach((context) => { let options = proxyTable[context]; if (typeof options === 'string') { options = { target: options }; } app.use(proxyMiddleware(options.filter || context, options)); }); // handle fallback for HTML5 history API app.use(require('connect-history-api-fallback')()); // serve webpack bundle output app.use(devMiddleware); // enable hot-reload and state-preserving // compilation error display app.use(hotMiddleware); // serve pure static assets const staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory); app.use(staticPath, express.static('./static')); const uri = `http://localhost:${port}`; /* eslint no-underscore-dangle: "off" */ let _resolve; const readyPromise = new Promise((resolve) => { _resolve = resolve; }); console.log('> Starting dev server...'); devMiddleware.waitUntilValid(() => { console.log(`> Listening at ${uri}\n`); // when env is testing, don't need open it if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { opn(uri); } _resolve(); }); const server = app.listen(port); module.exports = { ready: readyPromise, close: () => { server.close(); }, };
$(document).ready(function(){ //fancybox.js init /*$('.fancybox').fancybox({ openEffect : 'none', closeEffect : 'none', prevEffect : 'none', nextEffect : 'none', arrows : false, helpers : { media : {}, buttons : {} } });*/ //wow.js init wow = new WOW( { animateClass: 'animated', mobile: false, offset: 100 } ); wow.init(); });
#!/usr/bin/env node /* try { require(./newrelic) require('newrelic') } catch (e) { // Don't load New Relic if the configuration file does't exist. } */ /* require('babel/register')({ only: new RegExp(__dirname + '/lib' + '|' + __dirname + '/node_modules/p2p-file-transfer') }) */ module.exports = require('./lib/server')
"use strict"; var compression = require("../lib/core/middleware/compression"); describe("core.middleware.compression", function() { var fakeThis; beforeEach("create fake this", function() { fakeThis = { enabled: sinon.stub().withArgs("compress").returns(true), app: { use: sinon.spy() } }; }); it("should be a function", function() { compression.should.be.a("function"); }); it("should only check the compress option", function() { compression.call(fakeThis); fakeThis.enabled.should.be.calledOnce; fakeThis.enabled.should.be.calledWith("compress"); }); it("should use one middleware function if enabled", function() { compression.call(fakeThis); fakeThis.app.use.should.be.calledOnce; // express-compress returns an array of middleware fakeThis.app.use.args[0][0].should.be.a("function"); }); it("should not use any middleware if not enabled", function() { fakeThis.enabled = sinon.stub().withArgs("compress").returns(false); compression.call(fakeThis); fakeThis.app.use.should.not.be.called; }); });
/** reframe.js - Reframe.js: responsive iframes for embedded content @version v3.0.0 @link https://github.com/yowainwright/reframe.ts#readme @author Jeff Wainwright <yowainwright@gmail.com> (http://jeffry.in) @license MIT **/ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.reframe = factory()); }(this, (function () { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /** * REFRAME.TS 🖼 * --- * @param target * @param cName * @summary defines the height/width ratio of the targeted <element> */ function reframe(target, cName) { var _a, _b; if (cName === void 0) { cName = 'js-reframe'; } var frames = __spreadArrays((typeof target === 'string' ? document.querySelectorAll(target) : target)); var c = cName || 'js-reframe'; for (var i = 0; i < frames.length; i += 1) { var frame = frames[i]; var hasClass = frame.className.split(' ').indexOf(c) !== -1; if (hasClass || frame.style.width.indexOf('%') > -1) continue; // get height width attributes var height = frame.getAttribute('height') || frame.offsetHeight; var width = frame.getAttribute('width') || frame.offsetWidth; var heightNumber = typeof height === 'string' ? parseInt(height) : height; var widthNumber = typeof width === 'string' ? parseInt(width) : width; // general targeted <element> sizes var padding = (heightNumber / widthNumber) * 100; // created element <wrapper> of general reframed item // => set necessary styles of created element <wrapper> var div = document.createElement('div'); div.className = cName; var divStyles = div.style; divStyles.position = 'relative'; divStyles.width = '100%'; divStyles.paddingTop = padding + "%"; // set necessary styles of targeted <element> var frameStyle = frame.style; frameStyle.position = 'absolute'; frameStyle.width = '100%'; frameStyle.height = '100%'; frameStyle.left = '0'; frameStyle.top = '0'; // reframe targeted <element> (_a = frame.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(div, frame); (_b = frame.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(frame); div.appendChild(frame); } } return reframe; })));
/** * * STREAM: MVA (window: 15) * * * * DESCRIPTION: * - * * * API: * - * * * NOTES: * [1] * * * TODO: * [1] * * * HISTORY: * - 2014/05/28: Created. [AReines]. * * * DEPENDENCIES: * [1] * * * LICENSE: * MIT * * Copyright (c) 2014. Athan Reines. * * * AUTHOR: * Athan Reines. athan@nodeprime.com. 2014. * */ (function() { 'use strict'; // MODULES // var // Stream combiner: pipeline = require( 'stream-combiner' ), // Flow streams: flow = require( 'flow.io' ); // FUNCTIONS // /** * FUNCTION: map( fcn ) * Returns a data transformation function. * * @private * @param {function} fcn - function which performs the map transform * @returns {function} data transformation function */ function map( fcn ) { /** * FUNCTION: map( data ) * Defines the data transformation. * * @private * @param {*} data - stream data * @returns {number} transformed data */ return function map( data ) { return fcn( data ); }; } // end FUNCTION map() // STREAM // /** * FUNCTION: Stream() * Stream constructor. * * @returns {Stream} Stream instance */ function Stream() { this.name = ''; this._window = 15; // ACCESSORS: this._value = function( d ) { return d.y; }; return this; } // end FUNCTION Stream() /** * ATTRIBUTE: type * Defines the stream type. */ Stream.prototype.type = 'mva-w15'; /** * METHOD: metric( metric ) * Metric setter and getter. If a metric instance is supplied, sets the metric. If no metric is supplied, returns the instance metric value function. * * @param {object} metric - an object with a 'value' method; see constructor for basic example. If the metric has a name property, sets the transform name. * @returns {Stream|object} Stream instance or instance metric */ Stream.prototype.metric = function ( metric ) { if ( !arguments.length ) { return this._value; } if ( !metric.value ) { throw new Error( 'metric()::invalid input argument. Metric must be an object with a \'value\' method.' ); } // Extract the method to calculate the metric value and bind the metric context: this._value = metric.value.bind( metric ); // If the metric has a name, set the transform name: this.name = ( metric.name ) ? metric.name : ''; // Return the stream instance: return this; }; // end METHOD metric() /** * METHOD: stream() * Returns a JSON data transform stream for performing MVA. * * @returns {stream} transform stream */ Stream.prototype.stream = function() { var mTransform, tStream, mva, mStream, pStream; // Create the input transform stream: mTransform = flow.map() .map( map( this._value ) ); // Create the input transform stream: tStream = mTransform.stream(); // Create an MVA stream generator and configure: mva = flow.mva() .window( this._window ); // Create an MVA stream: mStream = mva.stream(); // Create a stream pipeline: pStream = pipeline( tStream, mStream ); // Return the pipeline: return pStream; }; // end METHOD stream() // EXPORTS // module.exports = function createStream() { return new Stream(); }; })();
'use strict'; module.exports = { compile: { options: { style: 'expanded', }, src : 'src/css/style.scss', dest : 'dist/css/style.css', }, };
function List(storage, $) { var items = []; var doneItems = []; var nextId = 0; this.storage = storage; this.toDo = items; this.done = doneItems; this.add = function (text) { var newItem = new ListItemModel(nextId,text); items.push(newItem); storage.store(newItem.id, JSON.stringify(newItem)); nextId++; return newItem; }; this.markDone = function(id) { var currentDate = new Date(); var item = get(id, items); doneItems.push(item); item.done = true; item.dateDone = currentDate; storage.store(item.id, JSON.stringify(item)); return item; }; this.loadItems = function(areDone) { var deferred = $.Deferred(); storage.load() .then(populateLists) .then(function(){ deferred.resolve(); }); return deferred.promise(); }; function populateLists(data){ for(var i=0; i < data.length ;i++){ var item = JSON.parse(data[i], reviver); if(item.id > nextId){ nextId = item.id; } if(item.done){ doneItems.push(item); } else { items.push(item); } } // increase nextId by 1 so that it ready for use nextId++; } function get(id, list){ for(var i=0; i < list.length; i++){ if(list[i].id == id){ return list[i]; } } return null; } }
version https://git-lfs.github.com/spec/v1 oid sha256:5181d344dc3334a5a80ecae84df1bb3107af7d92135639b56a7f73ec2ea1931c size 3057
'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; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactRouter = require('react-router'); 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"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Menu = function (_Component) { _inherits(Menu, _Component); function Menu(props) { _classCallCheck(this, Menu); return _possibleConstructorReturn(this, (Menu.__proto__ || Object.getPrototypeOf(Menu)).call(this, props)); } _createClass(Menu, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', { className: 'menu-component' }, _react2.default.createElement( 'nav', null, _react2.default.createElement( _reactRouter.Link, { to: '/anuncios', activeClassName: 'selected' }, _react2.default.createElement('img', { src: '/imgs/building.svg' }), _react2.default.createElement( 'span', null, 'An\xFAncios' ) ), _react2.default.createElement( _reactRouter.Link, { to: '/novo-anuncio', activeClassName: 'selected' }, _react2.default.createElement('img', { src: '/imgs/plus-icon.svg' }), _react2.default.createElement( 'span', null, 'Novo an\xFAncio' ) ) ) ); } }]); return Menu; }(_react.Component); Menu.propTypes = {}; exports.default = Menu;
bql` image(size="foo") { width height src } `;
import plain from '../structure/plain' import immutable from '../structure/immutable' import defaultShouldError from '../defaultShouldError' describe('defaultShouldError', () => { it('should validate when initialRender is true', () => { expect( defaultShouldError({ initialRender: true }) ).toBe(true) }) const describeDefaultShouldError = structure => { const { fromJS } = structure it('should validate if values have changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({ foo: 'fooInitial' }), nextProps: { values: fromJS({ foo: 'fooChanged' }) } }) ).toBe(true) }) it('should not validate if values have not changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({ foo: 'fooInitial' }), nextProps: { values: fromJS({ foo: 'fooInitial' }) } }) ).toBe(false) }) it('should validate if field validator keys have changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({ foo: 'fooValue' }), nextProps: { values: fromJS({ foo: 'fooValue' }) }, lastFieldValidatorKeys: [], fieldValidatorKeys: ['foo'] }) ).toBe(true) }) it('should not validate if field validator keys have not changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({ foo: 'fooInitial' }), nextProps: { values: fromJS({ foo: 'fooInitial' }) }, lastFieldValidatorKeys: ['foo'], fieldValidatorKeys: ['foo'] }) ).toBe(false) }) } describeDefaultShouldError(plain) describeDefaultShouldError(immutable) })
const path = require('path'); module.exports = { HOST: 'localhost', PORT: 3000, URL: { ROOT: 'https://bootflex.herokuapp.com', API: 'https://bootflex.herokuapp.com/api' }, PATH: { ROOT: path.join(__dirname, '..') } };
import Chaffle from "chaffle"; const scrambleAuthor = () => { const elements = document.querySelectorAll("[data-chaffle]"); elements.forEach(el => { const chaffle = new Chaffle(el, { speed: 10, delay: 20, }); el.addEventListener("mouseover", () => { chaffle.init(); }); }); }; export { scrambleAuthor };
// Copyright (c) 2015 Uber Technologies, Inc. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React, {PropTypes, Component} from 'react'; import ViewportMercator from 'viewport-mercator-project'; import window from 'global/window'; export default class CanvasOverlay extends Component { static propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, latitude: PropTypes.number.isRequired, longitude: PropTypes.number.isRequired, zoom: PropTypes.number.isRequired, redraw: PropTypes.func.isRequired, isDragging: PropTypes.bool.isRequired }; componentDidMount() { this._redraw(); } componentDidUpdate() { this._redraw(); } _redraw() { const pixelRatio = window.devicePixelRatio || 1; const canvas = this.refs.overlay; const ctx = canvas.getContext('2d'); ctx.save(); ctx.scale(pixelRatio, pixelRatio); const mercator = ViewportMercator(this.props); this.props.redraw({ width: this.props.width, height: this.props.height, ctx, project: mercator.project, unproject: mercator.unproject, isDragging: this.props.isDragging }); ctx.restore(); } render() { const pixelRatio = window.devicePixelRatio || 1; return ( <canvas ref="overlay" width={ this.props.width * pixelRatio } height={ this.props.height * pixelRatio } style={ { width: `${this.props.width}px`, height: `${this.props.height}px`, position: 'absolute', pointerEvents: 'none', left: 0, top: 0 } }/> ); } }
"use strict"; const removeDiacritics = require('diacritics').remove; const request = require('request'); //const pSegCases = require('../test/promiseSwitchCase.js'); var utils = { /** * Resolve all promises in Object via for ... in loop * @param {object} obj - The object containing function properties => Switch cases that resolve */ switchCasePromiseResolver: function switchCasePromiseResolver (obj, event) { //Promise Resolver For...In Loop - returns out to Var as Array let i = -1; var promisesArr = []; //Loop through the segmented Switch Cases (test is an obj with each Switch Case as a property) for (var ligneFn in obj) { //console.log(ligneFn); i++; //resolve each switch case with the event.message.text and return resolve promisesArr[i] = Promise.resolve( obj[ligneFn](event) ); } /** * Returns newly filled in Arr from loop * @return {array} - returns array with promise status (resolve, false) in array */ return promisesArr; }, ////////////////// // Text Cleaners ////////////////// cleanseText: function cleanseText (text) { return removeDiacritics( text.toLowerCase() .replace(/\s\s+|[.-]/g, function (match) { return (match === "-" || " " ? " " : "") } ).trim()) //([\uD800-\uDBFF][\uDC00-\uDFFF]) to remove emojis }, ////////////////////////////////////////// //Format Time before SearchStop Function ///////////////////////////////////////// timeFormatter (time) { var timeArr = time.split('T'); var finalTime = timeArr[1].slice(0,2) + ':' + timeArr[1].slice(2,4); return finalTime; }, //Random Number between 2 values randNum (min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }, //Whitelist them domains bruh setWhiteList(domains) { if (!Array.isArray(domains)) { throw "Error ... domains param MUST be an array. You passed in: " + typeof domains; } else { request( { method: 'POST', uri: 'https://graph.facebook.com/v2.6/me/messenger_profile?access_token=' + process.env.PAGE_ACCESS_TOKEN, headers: { 'content-type': 'application/json' }, body: { whitelisted_domains: domains }, json: true }, function (error, response, body) { if (!error) { request( { method: 'GET', uri: 'https://graph.facebook.com/v2.6/me/messenger_profile?fields=whitelisted_domains&access_token=' + process.env.PAGE_ACCESS_TOKEN }, function (error, response, body) { if (!error) { console.log('Displaying whitelisted sites:'); console.log(body); } else if (error) { console.error (error); } }) } else if (error) { console.error(error); } } ); }; } } module.exports = utils;
var my = require('my'); var maxHeight = 300, maxWidth = 300; exports.view = function(data) { console.log("view: m.js"); console.log(data); var topic = data.topic; return( my.page({title: 'Hello World', scripts:["http://code.jquery.com/jquery-latest.js"]}, /*my.div({id: 'myDiv', style: {height: '800px', border: 'red 1px solid'}}, 'Actor ' + data.name ),*/ my.h1(topic.name), tabs(topic.friends), gallery2(topic.friends[0].entities, '100%', '300px', '200px', '270px', '30px', '30px') ) )} function tabs(friends) { var tabs = my.div({}); for (var i = 0; i < friends.length; i++) tabs.children.push(my.p(friends[i])); return gallery; } function gallery(imgUrls, width, height, thumbWidth, thumbHeight, hGap, vGap) { var galleryStyle = { margin: 'auto', width: width, height: height }; var thumbStyle = { 'margin-top': vGap, 'margin-left': hGap, 'max-width': thumbWidth, 'max-height': thumbHeight, '-moz-box-shadow': '1px 1px 6px #999', '-webkit-box-shadow': '1px 1px 6px #999' }; var gallery = my.div({style: galleryStyle}); for (var i = 0; i < imgUrls.length; i++) gallery.children.push(my.img({style: thumbStyle, src: imgUrls[i]})); return gallery; } function gallery2(imgUrls, width, height, thumbWidth, thumbHeight, hGap, vGap) { var galleryStyle = { display: 'inline-block', width: width, height: height }; var thumbDivStyle = { display: 'inline-block', 'margin-top': vGap, 'margin-left': hGap, 'width': thumbWidth, 'height': thumbHeight, 'text-align': 'center' }; var thumbStyle = { 'max-width': thumbWidth, 'max-height': thumbHeight, '-moz-box-shadow': '1px 1px 6px #999', '-webkit-box-shadow': '1px 1px 6px #999' }; var gallery = my.div({style: galleryStyle}); for (var i = 0; i < imgUrls.length; i++) { var imgUrl = "http://img.freebase.com/api/trans/image_thumb"+imgUrls[i].id+"?mode=fit&maxheight="+maxHeight+"&maxwidth="+maxWidth; //console.log(imgUrls[i].id); gallery.children.push( my.div({style: thumbDivStyle}, my.img({style: thumbStyle, src: imgUrl} ) )); } return gallery; }
/*eslint no-console: 1 */ console.warn('You are using the default filter for the fileMeta service. For more information about event filters see https://docs.feathersjs.com/api/events.html#event-filtering'); // eslint-disable-line no-console module.exports = function(data, connection, hook) { // eslint-disable-line no-unused-vars return data; };
export default function HomeService($rootScope, $window, $http) { var service = { send: send, loadSettings: loadSettings, }; return service; function send(msg, data) { console.log(msg, data); //$rootScope.$broadcast(msg, data); } function loadSettings() { return $http({ method: 'GET', url: 'http://dev.app.com/api/v1/foodtruck', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', } }).then(function successCallback(response) { return response; }, function errorCallback(response) { return "Error loading settings"; }); } }
import React, { Component } from 'react' import { connect } from 'react-redux' import { setSearchTerm } from './actionCreators' import { Link } from 'react-router' class Header extends Component { constructor (props) { super(props) this.handleSearchTermChange = this.handleSearchTermChange.bind(this) } handleSearchTermChange (event) { this.props.dispatch(setSearchTerm(event.target.value)) } render () { let utilSpace if (this.props.showSearch) { utilSpace = <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' /> } else { utilSpace = ( <h2> <Link to='/search'>Back</Link> </h2> ) } return ( <header> <h1> <Link to='/'> jordaflix </Link> </h1> {utilSpace} </header> ) } } const mapStateToProps = (state) => { return { searchTerm: state.searchTerm } } const { func, bool, string } = React.PropTypes Header.propTypes = { handleSearchTermChange: func, dispatch: func, showSearch: bool, searchTerm: string } export default connect(mapStateToProps)(Header)
var answers = []; var validate = () => { $("#afev-answer-1").animate( { backgroundColor: "green"} ); var good = true; if (answers.indexOf(1) === -1) { good = false; } if (answers.indexOf(2) !== -1) { $("#afev-answer-2").animate( { backgroundColor: "red"} ); good = false; } if (answers.indexOf(3) !== -1) { $("#afev-answer-3").animate( { backgroundColor: "red"} ); good = false; } if (good) { $("#afev-secret-right").show(); } else { $("#afev-secret-wrong").show(); } $("#afev-secret-response").show(); } window.onload = () => { for (var i = 0; i < 5; i++) { let index = i + 1; $("#afev-answer-" + index).on("click", () => { answers.push(index); $("#afev-answer-" + index).animate( { backgroundColor: "#1e5abc"} ); }) } var score = localStorage.getItem("afev-score"); if (score !== null) { score = score.substring(0, 3) + '1' + score.substring(4, 5); localStorage.setItem("afev-score", score); } else { localStorage.setItem("afev-score", "10000"); } initLayout(); };
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { d: "M17.5 8c.46 0 .91-.05 1.34-.12C17.44 5.56 14.9 4 12 4c-.46 0-.91.05-1.34.12C12.06 6.44 14.6 8 17.5 8zM8.08 5.03C6.37 6 5.05 7.58 4.42 9.47c1.71-.97 3.03-2.55 3.66-4.44z", opacity: ".3" }), h("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 2c2.9 0 5.44 1.56 6.84 3.88-.43.07-.88.12-1.34.12-2.9 0-5.44-1.56-6.84-3.88.43-.07.88-.12 1.34-.12zM8.08 5.03C7.45 6.92 6.13 8.5 4.42 9.47 5.05 7.58 6.37 6 8.08 5.03zM12 20c-4.41 0-8-3.59-8-8 0-.05.01-.1.01-.15 2.6-.98 4.68-2.99 5.74-5.55 1.83 2.26 4.62 3.7 7.75 3.7.75 0 1.47-.09 2.17-.24.21.71.33 1.46.33 2.24 0 4.41-3.59 8-8 8z" }), h("circle", { cx: "9", cy: "13", r: "1.25" }), h("circle", { cx: "15", cy: "13", r: "1.25" })), 'FaceTwoTone');
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'horizontalrule', 'no', { toolbar: 'Sett inn horisontal linje' } );
'use strict'; module.exports = function(localeA, localeB, options) { options = options || {}; if (typeof localeA !== 'object' || typeof localeB !== 'object') { throw new Error('s18n: `localeA` and `localeB` must be objects.'); } var localeAMissing = {}; var localeBMissing = {}; var unmodifiedStrings = {}; var modifiedStrings = []; for (var hashA in localeA) { if (typeof localeB[hashA] === 'undefined') { localeBMissing[hashA] = localeA[hashA]; } else { if (localeA[hashA] === localeB[hashA]) { unmodifiedStrings[hashA] = localeA[hashA]; } else { modifiedStrings.push({ hash: hashA, strings: [ localeA[hashA], localeB[hashA] ] }); } } } for (var hashB in localeB) { if (typeof localeA[hashB] === 'undefined') { localeAMissing[hashB] = localeB[hashB]; } } return [ arrayifyResults(localeAMissing), arrayifyResults(localeBMissing), arrayifyResults(unmodifiedStrings), modifiedStrings ]; }; function arrayifyResults(resultsObj) { var array = []; for (var hash in resultsObj) { array.push({ hash: hash, string: resultsObj[hash] }); } return array; }
import Ember from 'ember'; export default Ember.Mixin.create({ reduxStore: Ember.inject.service(), dispatch(action) { return this.get('reduxStore').dispatch(action); }, dispatchAction(actionName, ...args) { return this.dispatch(this.action(actionName).apply(this, args)); }, getState(path) { return path ? this.get(`reduxStore.state.${path}`) : this.get('reduxStore.state'); }, action(actionName) { if (!this.reduxActions[actionName]) {throw new Error(`No redux action found for ${actionName}`);} return this.reduxActions[actionName].bind(this); }, });
const gulp = require('gulp'); const nodemon = require('gulp-nodemon'); const mocha = require('gulp-spawn-mocha'); gulp.task('start', () => { nodemon({ script: 'server.js', ext: 'html js ejs css', ignore: ['node_modules'], }) .on('restart', () => { console.log('restarted') }); }); gulp.task('test', () => { return gulp.src('test/test.js', {read: false}) .pipe(mocha({ // report 종류 R: 'spec', })); });
/** * @license Copyright (c) 2012, Viet Trinh All Rights Reserved. * Available via MIT license. */ /** * An authorizeation interceptor used to determine if the user can access the given resource. */ define([ 'framework/controller/interceptor/i_interceptor', 'framework/core/utils/clazz', 'framework/core/deferred/deferred' ], function(IInterceptor, ClazzUtils, Deferred) { var AuthorizationInterceptor = function() { IInterceptor.call(this); return this; } AuthorizationInterceptor.prototype = new IInterceptor(); ClazzUtils.generateProperties(AuthorizationInterceptor); // @override AuthorizationInterceptor.prototype.before = function(requestContext) { var controller = requestContext.getController(), secured = controller.getSecured && controller.getSecured() === true, securedAdmin = controller.getSecuredAdmin && controller.getSecuredAdmin() === true, stateService = requestContext.getStateService(); // If this controller is secured and there's no user logged in, then fail. if ((secured || securedAdmin) && (!stateService.getCurrentUser() || !stateService.getCurrentUser().getId())) { requestContext.setStatusCode(401); requestContext.setErrorMessage('Unauthorized Access! Please log in to access the given resource.'); return Deferred.rejectedPromise(requestContext); } // If this controller is secured admin and the user doesn't have access priveledges. else if (securedAdmin && stateService.getCurrentUser().getIsAdmin() !== true) { requestContext.setStatusCode(403); requestContext.setErrorMessage('Unauthorized Access! You are not allowed to access the given resource.'); return Deferred.rejectedPromise(requestContext); } // Assumes this function doesn't fail. return Deferred.resolvedPromise(requestContext); }; // @override AuthorizationInterceptor.prototype.after = function(requestContext) { return Deferred.resolvedPromise(requestContext); }; return AuthorizationInterceptor; });
var pkg = require('./package.json'), gulp = require('gulp'), gutil = require('gulp-util'), coffee = require('gulp-coffee'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), livereload = require('gulp-livereload'), rename = require('gulp-rename'), coffeelint = require('gulp-coffeelint'), jade = require('gulp-jade'), mainBowerFiles = require('main-bower-files'), filter = require('gulp-filter'), less = require('gulp-less'), autoprefixer = require('gulp-autoprefixer'), minify = require('gulp-minify-css'), inject = require('gulp-inject'), ignore = require('gulp-ignore'); gulp.task('default', ['coffee', 'jade', 'bower', 'less']); gulp.task('coffee', function() { return gulp.src('src/coffee/*.coffee') .pipe(coffeelint()) .pipe(coffeelint.reporter()) .pipe(coffee({ bare:true }).on('error', gutil.log)) .pipe(concat(pkg.name + '.all.js')) .pipe(rename({ suffix: '.min' })) .pipe(uglify()) .pipe(gulp.dest('public/js')) .pipe(livereload({ auto: false })); }); gulp.task('jade', function() { return gulp.src('src/jade/**/*.jade') .pipe(jade({ pretty: true }).on('error', gutil.log)) .pipe(gulp.dest('public')) .pipe(livereload({ auto: false })); }); gulp.task('bower', function() { var jsFilter = filter('*.js'); var cssFilter = filter('*.css'); return gulp.src(mainBowerFiles()) .pipe(cssFilter) .pipe(gulp.dest('public/css/vendor')) .pipe(cssFilter.restore()) .pipe(jsFilter) .pipe(gulp.dest('public/js/vendor')); }); gulp.task('less', function() { return gulp.src('src/less/style.less') .pipe(less().on('error', gutil.log)) .pipe(autoprefixer("last 2 versions", "> 5%", "ie 8")) .pipe(minify()) .pipe(rename(pkg.name + '.min.css')) .pipe(gulp.dest('public/css/')) .pipe(livereload({ auto: false })); }); gulp.task('inject', function() { gulp.src('src/jade/base.jade') .pipe(inject( gulp.src(['public/**/*.css', 'public/**/*.js'], { read: false }) .pipe(ignore(['**/normalize.css', '**/modernizr.js', '**/jquery.min.js'])), { ignorePath: 'public' } )) .pipe(gulp.dest('src/jade')); }); gulp.task('watch', function() { livereload.listen(); gulp.watch('src/coffee/*.coffee', ['coffee']); gulp.watch('src/jade/*.jade', ['jade']); gulp.watch('src/less/*.less', ['less']); });
const Card = require('./src/main'); Card.install = function(Vue) { Vue.component(Card.name, Card); }; module.exports = Card;
(function(exports) { function changeSky(location) { var sky = document.getElementById("image-360"); sky.setAttribute('src', location); } function addMonolith() { var box = document.createElement('a-box'); document.querySelector('a-scene').appendChild(box); box.setAttribute('id', 'monolith'); box.setAttribute('color', '#222'); box.setAttribute('width', '0.5'); box.setAttribute('height', '4'); box.setAttribute('depth', '2'); box.setAttribute('position', '-5 2 0'); box.setAttribute('scale', '0.4 0.4 0.4'); } function removeMonolith() { var element = document.getElementById('monolith'); element.parentNode.removeChild(element); } function addRain() { var element = document.getElementById('scene') console.log(element) element.setAttribute('rain', ''); } function stopRain() { var element = document.getElementById('scene') element.removeAttribute('rain', ''); } exports.addRain = addRain; exports.stopRain = stopRain; exports.addMonolith = addMonolith; exports.removeMonolith = removeMonolith; exports.changeSky = changeSky; })(this); (function(exports) { function captureToken(token) { var database = firebase.database(); var browserTokens = database.ref('browserTokens') var data = { timestamp: Date.now(), token: token }; browserTokens.push(data, finished) }; function finished(error) { if (error) { console.log('Did not save to DB' + error); } else { console.log('Browser token saved to DB'); } } exports.captureToken = captureToken })(this);
function injectScript(file, node) { var th = document.getElementsByTagName(node)[0]; var s = document.createElement('script'); s.setAttribute('type', 'text/javascript'); s.setAttribute('src', file); th.appendChild(s); } function injectStyle(file, node) { var th = document.getElementsByTagName(node)[0]; var s = document.createElement('link'); s.setAttribute('type', 'text/css'); s.setAttribute('href', file); s.setAttribute('rel', "stylesheet"); th.appendChild(s); } injectScript(chrome.extension.getURL("js/page-scripts.js"), "body"); injectStyle(chrome.extension.getURL("css/page-styles.css"), "body"); injectStyle("https://fonts.googleapis.com/css?family=Oxygen:400,700,300", "body"); chrome.storage.sync.get("backImgTog", function(storage) { if (storage.backImgTog == undefined || !storage.backImgTog) { $.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US", function(response) { var url = "https://www.bing.com" + response.images[0].url; $(window).trigger('resize'); $("#authenticate").css("background-image", "url(" + url + ")"); }); } }); $(document).ready(function() { $("form[name=authenticate] fieldset input[type=submit]").val("Login"); console.log("SchedulesPlus Ready!"); });
/** * 指示按钮 */ Banner.prototype.btn = function() { var s = this, o = this.option, $banner = this.$banner, $btn; for (var i = 0, item = ''; i < s.len; i++) { item += '<a></a>'; } $banner.append($('<div class="tb-btn"/>').append(item)); s.$btn = $btn = $('.tb-btn a', $banner); $btn.first().addClass('active'); setTimeout(function() { $btn.parent().css({ marginLeft: -($btn.outerWidth(true) * $btn.length / 2) }); }, 0); if (!Util.IS_MOBILE) { $btn.on('click.terseBanner', function() { if (s.isAnimated) return; o.before.call(s, s.currentIndex); s.currentIndex = $(this).index(); s.play(); }); } };
'use strict'; var msb = require('msb'); var app = exports; app.config = require('./lib/config'); app.start = function(cb) { if (app.config.channelMonitorEnabled) msb.channelMonitorAgent.start(); var RouterWrapper = require('./lib/routerWrapper').RouterWrapper; app.router = new RouterWrapper(); app.router.load(app.config.routes); app.createServer() .listen(app.config.port) .once('listening', function() { app.config.port = this.address().port; if (cb) { cb(); } console.log('http2bus listening on ' + app.config.port); }); }; app.createServer = function() { var http = require('http'); var finalhandler = require('finalhandler'); return http.createServer(function(req, res) { app.router.middleware(req, res, finalhandler(req, res)); }); }; app.routesAgent = require('./lib/routesProvider/agent');
$(document).ready(function () { console.log("ready!"); $("#subs").click(function () { var name = $('#name').val(); var email = $('#email').val(); if (name != '' && email != '') { $('#subs_err').html(''); var subs = {name: name, email: email}; var url = "/index.php/index/subscribe_user"; $.post(url, {subs: JSON.stringify(subs)}).done(function (data) { $('#subscribe_content').html(data); }); // end of post } // end if else { $('#subs_err').html('Please provide name and email'); } }); var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; var code = getUrlParameter('errorcode'); if (code == 3) { $('#login_err').html('Invalid email address or password'); } $("#contact_submit").click(function () { var name = $('#name').val(); var email = $('#email').val(); var phone = $('#phone').val(); var comment = $('#comment').val(); if (name != '' && email != '' && phone != '' && comment != '') { $('#contact_err').html(''); var contact = {name: name, email: email, phone: phone, comment: comment}; var url = "/index.php/index/send_contact_request"; $.post(url, {contact: JSON.stringify(contact)}).done(function (data) { $('#contact_container').html(data); }); // end of post } // end if else { $('#contact_err').html('Please provide all required fields'); } }); });
/* global createNS */ /* exported filtersFactory */ var filtersFactory = (function () { var ob = {}; ob.createFilter = createFilter; ob.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter; function createFilter(filId, skipCoordinates) { var fil = createNS('filter'); fil.setAttribute('id', filId); if (skipCoordinates !== true) { fil.setAttribute('filterUnits', 'objectBoundingBox'); fil.setAttribute('x', '0%'); fil.setAttribute('y', '0%'); fil.setAttribute('width', '100%'); fil.setAttribute('height', '100%'); } return fil; } function createAlphaToLuminanceFilter() { var feColorMatrix = createNS('feColorMatrix'); feColorMatrix.setAttribute('type', 'matrix'); feColorMatrix.setAttribute('color-interpolation-filters', 'sRGB'); feColorMatrix.setAttribute('values', '0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1'); return feColorMatrix; } return ob; }());
'use strict'; angular.module('myApp.post', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/new-post', { templateUrl: 'posts/new-post.html', controller: 'PostCtrl' }); }]) .controller('PostCtrl', ['$scope', '$firebaseArray', 'CommonProp', '$location', function($scope, $firebaseArray, CommonProp, $location) { // if user is not logged in, redirect to sign in page if (!CommonProp.getUser()) { $location.path('/signin'); } $scope.addPost = function() { var firebaseObj = new Firebase("https://amber-heat-2147.firebaseio.com/articles"); var fb = $firebaseArray(firebaseObj); var title = $scope.article.title; var content = $scope.article.content; fb.$add({ title: title, content: content, author: CommonProp.getUser() }).then(function(ref) { $location.path('/home'); }, function(error) { console.log("Error:", error); }); }; $scope.logout = function(){ CommonProp.logoutUser(); } }]);
var WALKING_SPEED_RATIO = 30; // how many times faster than walking speed are you? var FIRST_PERSON = false; var RESET_CAMERA_POSITION = function() {camera.position.set(-168, 25, -17);} var PATH_ANIMATION_RUNNING = false; function endPathAnimation() { PATH_ANIMATION_RUNNING = false; } function nextCameraTween(path, index, sf, ef) { var start = convertVec(coords[path[index]]); var end = convertVec(coords[path[index+1]]); if (index === 0) {start = (new THREE.Vector3()).lerpVectors(start, end, sf);} if (index+1 === path.length - 1) {end = (new THREE.Vector3()).lerpVectors(start, end, 1-ef);} var tween = new TWEEN.Tween(start).to(end, 500+start.distanceTo(end)*1400/WALKING_SPEED_RATIO); tween.easing(TWEEN.Easing.Quadratic.InOut); var dir = (new THREE.Vector3()).subVectors(end, start).normalize(); tween.onUpdate(function(){ controls.target = start; }); if (index === path.length - 2) { tween.onComplete(endPathAnimation); return tween; } else { return tween.chain(nextCameraTween(path,index+1, sf, ef)); } }
//! moment.js locale configuration //! locale : Galician [gl] //! author : Juan G. Hurtado : https://github.com/juanghurtado ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var gl = moment.defineLocale('gl', { months : 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'), monthsShort : 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'), monthsParseExact: true, weekdays : 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mé_xo_ve_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY H:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' }, calendar : { sameDay : function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay : function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek : function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay : function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek : function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : function (str) { if (str.indexOf('un') === 0) { return 'n' + str; } return 'en ' + str; }, past : 'hai %s', s : 'uns segundos', m : 'un minuto', mm : '%d minutos', h : 'unha hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un ano', yy : '%d anos' }, ordinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return gl; }));
/*========================================================================================= File Name: symbols.js Description: Flot symbols chart ---------------------------------------------------------------------------------------- Item Name: Stack - Responsive Admin Theme Version: 1.1 Author: PIXINVENT Author URL: http://www.themeforest.net/user/pixinvent ==========================================================================================*/ // Symbols chart // ------------------------------ $(window).on("load", function(){ function generate(offset, amplitude) { var res = []; var start = 0, end = 10; for (var i = 0; i <= 50; ++i) { var x = start + i / 50 * (end - start); res.push([x, amplitude * Math.sin(x + offset)]); } return res; } var data = [ { data: generate(2, 1.8), points: { symbol: "circle" } }, { data: generate(3, 1.5), points: { symbol: "square" } }, { data: generate(4, 0.9), points: { symbol: "diamond" } }, { data: generate(6, 1.4), points: { symbol: "triangle" } }, { data: generate(7, 1.1), points: { symbol: "cross" } } ]; $.plot("#symbols", data, { series: { points: { show: true, radius: 3 } }, grid: { borderWidth: 1, borderColor: "#e9e9e9", color: '#999', minBorderMargin: 20, labelMargin: 10, margin: { top: 8, bottom: 20, left: 20 }, hoverable: true }, colors: ['#00A5A8', '#626E82', '#FF7D4D','#FF4558', '#1B2942'] }); });
/** * Global config setters/getters. Chainable ;) * * @usage * config.duration(500) // * config.duration() // => 500 * config.duration(600).duration() // 600 */ // Number of millseconds for each message to last var _duration = 10000; /** * (s|g)etter for the duration * * @parmam {int} ms * @return {this|int} */ export default { duration: function (ms) { if ( ms ) { // We'll parse it as int just in case a // dumb consumer tries to provide a string _duration = parseInt(ms, 10); return this; } else { return _duration; } } };
/** * This method start authentication workflow. * It should be called by application which require authentication. * * Author: Yuriy Movchan Date: 11/06/2013 */ var uuid = require('uuid'); var async = require('async'); var oxutil = require('../util/util.js'); var state = require('../shared/state.js'); var push = require('../push/push.js'); exports.rest_api = function(req, res, authenticationStore, applicationService, deviceService) { console.log("Authenticate: '" + req.params.deployment_id + "'", "user: '" + req.params.user_name + "'"); // Load device and application entries async.series([ function(done) { deviceService.getDeviceById(req.params.deployment_id, function(found_deployment_entry) { deployment_entry = found_deployment_entry; done(); }); }, function(done) { if (deployment_entry) { applicationService.getApplication(deployment_entry.oxPushApplication, function(found_application_entry) { application_entry = found_application_entry; done(); }); } else { console.warn("Failed to find deployment entry: '%s'", req.params.deployment_id); oxutil.sendFailedJsonResponse(res); done(); } } ], function() { if (application_entry && deployment_entry) { var application_configuration = JSON.parse(application_entry.oxPushApplicationConf); // TODO: Validate application_ip and req.ip var authentication_id = uuid.v1(); var authentication_entry = { 'authentication_id' : authentication_id, 'authentication_time' : Date.now(), 'expires_in' : 60, 'expires_at' : Date.now() + 60 * 1000, 'clean_up_at' : Date.now() + 180 * 1000, 'application_id' : application_entry.oxId, 'application_name' : application_configuration.name, 'application_description' : application_configuration.description, 'application_ip' : req.ip, 'user_name' : req.params.user_name, 'authentication_status' : state.PENDING, }; authenticationStore.set(authentication_id, authentication_entry); // Send message to device var device_configuration = JSON.parse(deployment_entry.oxPushDeviceConf); try { push.sendAuthenticationMessageToDevice(device_configuration, authentication_id); } catch (err) { console.log("Failed to send notification message to device: '" + device_configuration.device_uuid); } console.log("Initialized authentication process: '" + authentication_id + "' for application: '" + authentication_entry.application_name + "'"); oxutil.sendJsonResponse(res, { authentication_id : authentication_entry.authentication_id, expires_in : authentication_entry.expires_in, result : true, }); } else { console.warn("Failed to find application entry: '%s'", deployment_entry.oxPushApplication); oxutil.sendFailedJsonResponse(res); } }); };
const { yellow, cyan, gray } = require('chalk'); const EslintCLI = require('eslint').CLIEngine; const eslintConfig = require('../config/eslint/eslintConfig'); const runESLint = ({ fix = false, paths }) => new Promise((resolve, reject) => { console.log(cyan(`${fix ? 'Fixing' : 'Checking'} code with ESLint`)); const cli = new EslintCLI({ baseConfig: eslintConfig, extensions: ['.ts', '.tsx', '.js', '.jsx'], useEslintrc: false, fix, }); const checkAll = typeof paths === 'undefined'; /* Whitelist the file extensions that our ESLint setup currently supports */ const filteredFilePaths = checkAll ? ['.'] : paths.filter( (filePath) => filePath.endsWith('.ts') || filePath.endsWith('.tsx') || filePath.endsWith('.js') || filePath.endsWith('.jsx') || filePath.endsWith('.json'), ); if (filteredFilePaths.length === 0) { console.log(gray(`No JS files to lint`)); } else { console.log(gray(`Paths: ${filteredFilePaths.join(' ')}`)); try { const report = cli.executeOnFiles(filteredFilePaths); if (fix) { EslintCLI.outputFixes(report); } else { const { errorCount, warningCount, results } = report; if (errorCount || warningCount) { const formatter = cli.getFormatter(); console.log(formatter(results)); } if (errorCount > 0) { reject(); } } } catch (e) { if (e && e.message && e.message.includes('No files matching')) { console.warn(yellow(`Warning: ${e.message}`)); } else { reject(e); } } } resolve(); }); module.exports = { check: (paths) => runESLint({ paths }), fix: (paths) => runESLint({ fix: true, paths }), };
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } root.ng.common.locales['nl-sr'] = [ 'nl-SR', [['a.m.', 'p.m.'], u, u], u, [ ['Z', 'M', 'D', 'W', 'D', 'V', 'Z'], ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'], ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'], ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'jan.', 'feb.', 'mrt.', 'apr.', 'mei', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.' ], [ 'januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december' ] ], u, [['v.C.', 'n.C.'], ['v.Chr.', 'n.Chr.'], ['voor Christus', 'na Christus']], 1, [6, 0], ['dd-MM-y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, '{1} \'om\' {0}', u], [',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00;¤ -#,##0.00', '#E0'], '$', 'Surinaamse dollar', { 'AUD': ['AU$', '$'], 'CAD': ['C$', '$'], 'FJD': ['FJ$', '$'], 'JPY': ['JP¥', '¥'], 'SBD': ['SI$', '$'], 'SRD': ['$'], 'THB': ['฿'], 'TWD': ['NT$'], 'USD': ['US$', '$'], 'XPF': [], 'XXX': [] }, plural, [ [['middernacht', '’s ochtends', '’s middags', '’s avonds', '’s nachts'], u, u], [['middernacht', 'ochtend', 'middag', 'avond', 'nacht'], u, u], ['00:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'], ['00:00', '06:00']] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
import NumeralFieldComponent from './Numeral' const numeral = global.numeral if (!numeral) { throw new Error('Numeral is required in global variable') } export default class MoneyComponent extends NumeralFieldComponent { unformatValue(label) { return label === '' ? undefined : numeral._.stringToNumber(label) } formatValue(real) { return numeral(real) ? numeral(real).format('$0,0.[000000000000000000000]') : '' } }
var gulp = require("gulp"); var util = require("gulp-util"); var config = require("../config") gulp.task("watch", () => { gulp.watch(`${config.src.ts}`, ["compile:ts"]).on("change", reportChange).on("error", swallowError); gulp.watch(`${config.test.files}`, ["compile:test"]).on("change", reportChange).on("error", swallowError); }); function reportChange(event) { console.log(`File ${event.path} was ${event.type}, running tasks...`); } function swallowError(error) { console.log(util.colors.red(`Error occurred while running watched task...`)); }
var gulp = require('gulp'), plumber = require('gulp-plumber'), browserify = require('gulp-browserify'), concat = require('gulp-concat'), gulpif = require('gulp-if'), uglify = require('gulp-uglify'), jshint = require('gulp-jshint'), stylish = require('jshint-stylish'), sequence = require('run-sequence'), less = require('gulp-less'), zip = require('gulp-zip'), rev = require('gulp-rev-append'), gutil = require('gulp-util'); var production = gutil.env.type === "production"; var game_name = gutil.env.name || 'fp' var paths = { source: { canvas_js: './app/js/' + game_name + '/canvas.js', web_js: './app/js/' + game_name + '/web.js', canvas_css: './app/less/' + game_name + '/canvas.less', web_css: './app/less/' + game_name + '/web.less', baseJsDir: './app/js/**', js: './app/js/**/*.js', css: './app/less/**/*.less', libs: [ './bower_components/phaser/build/phaser.js' ] }, dest: { base: './public/' + game_name + '/', html: './public/' + game_name + '/index.html', js: './public/' + game_name + '/js', css: './public/' + game_name + '/css' } }; gulp.task('rev', function() { gulp.src(paths.dest.html) .pipe(rev()) .pipe(gulp.dest(paths.dest.base)); }); gulp.task('copy_libs', function () { gulp.src(paths.source.libs) .pipe(uglify({outSourceMaps: false})) .pipe(gulp.dest(paths.dest.js)); }); gulp.task('canvas_js', function() { gulp.src(paths.source.canvas_js) .pipe(plumber()) .pipe(browserify()) .pipe(concat('canvas.js')) .pipe(gulpif(production, uglify())) .pipe(gulp.dest(paths.dest.js)); }); gulp.task('web_js', function() { gulp.src(paths.source.web_js) .pipe(plumber()) .pipe(browserify()) .pipe(concat('web.js')) .pipe(gulpif(production, uglify())) .pipe(gulp.dest(paths.dest.js)); }); gulp.task('canvas_css', function() { gulp.src(paths.source.canvas_css) .pipe(plumber()) .pipe(less({ compress: true })) .pipe(gulp.dest(paths.dest.css)); }); gulp.task('web_css', function() { gulp.src(paths.source.web_css) .pipe(plumber()) .pipe(less({ compress: true })) .pipe(gulp.dest(paths.dest.css)); }); gulp.task('lint', function() { gulp.src(paths.source.js) .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('watch', function() { gulp.watch(paths.source.baseJsDir, function() { sequence('canvas_js', 'web_js', 'lint') }); gulp.watch(paths.source.css, function() { sequence('canvas_css', 'web_css') }) }); gulp.task('zip', function () { return gulp.src([ 'public/' + game_name + '/**/*' ]) .pipe(zip(game_name +'_dist.zip')) .pipe(gulp.dest('./dist')) }); gulp.task('build', [ 'canvas_js', 'web_js', 'canvas_css', 'web_css', 'rev' ]);
var gulp = require('gulp'); var sass = require('gulp-sass'); var browserSync = require('browser-sync'); var useref = require('gulp-useref'); var uglify = require('gulp-uglify'); var gulpIf = require('gulp-if'); var cssnano = require('gulp-cssnano'); var imagemin = require('gulp-imagemin'); var cache = require('gulp-cache'); var del = require('del'); var runSequence = require('run-sequence'); var path = require('path'); // Basic Gulp task syntax gulp.task('hello', function() { console.log('Hello Martin!'); }); // Development Tasks // ----------------- // Start browserSync server gulp.task('browserSync', function() { browserSync({ server: { baseDir: 'app' } }) }); gulp.task('sass', function() { return gulp.src('app/css/*.+(scss|sass)') // Gets all files ending with .scss in app/scss and children dirs .pipe(sass()) // Passes it through a gulp-sass .pipe(gulp.dest('app/css')) // Outputs it in the css folder .pipe(browserSync.reload({ // Reloading with Browser Sync stream: true })); }); // Watchers gulp.task('watch', function() { gulp.watch('app/css/*.+(scss|sass)', ['sass']); gulp.watch('app/*.html', browserSync.reload); gulp.watch('app/js/**/*.js', browserSync.reload); }); // Optimization Tasks // ------------------ // Optimizing CSS and JavaScript gulp.task('useref', function() { return gulp.src('app/*.html') .pipe(useref()) .pipe(gulpIf('app/js/*.js', uglify())) .pipe(gulpIf('app/css/*.css', cssnano())) .pipe(gulp.dest('dist')); }); // Optimizing Images gulp.task('images', function() { return gulp.src('app/img/**/*.+(png|jpg|jpeg|gif|svg)') // Caching images that ran through imagemin .pipe(cache(imagemin({ interlaced: true, }))) .pipe(gulp.dest('dist/images')) }); // Copying fonts gulp.task('fonts', function() { return gulp.src('app/fonts/**/*').pipe(gulp.dest('dist/fonts')) }); // Cleaning gulp.task('clean', function() { return del.sync('dist').then(function(cb) {return cache.clearAll(cb);}); }); gulp.task('clean:dist', function() { return del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']); }); // Build Sequences // --------------- gulp.task('default', function(callback) { runSequence(['sass', 'browserSync'], 'watch', callback) }); gulp.task('build', function(callback) { runSequence('clean:dist', 'sass', ['useref', 'images', 'fonts'], callback) });
(function () { var Demo = { init: function () { this.syntaxHighlight(); this.sticky(); }, syntaxHighlight: function () { hljs.initHighlighting(); }, sticky: function () { var $sticky = $('[data-sticky]'); $sticky.sticky({ topSpacing: 10 }); } }; Demo.init(); })();
var Tile = function (type, x, y) { this.type = type; this.tint = 0; this.hover = false; this.isAllowed = undefined; this.isAllowedForBeat = undefined; this.x = x; this.y = y; this.graphic = new fabric.Rect({ left: Tile.size * x, top: Tile.size * y, fill: type === Tile.TileType.NONPLAYABLE ? Tile.ColorNonplayable : Tile.ColorPlayable, width: Tile.size, height: Tile.size, selectable: false, obj: this }); canvas.add(this.graphic); }; Tile.size = undefined; Tile.ColorPlayable = "#717070"; Tile.ColorNonplayable = "#d9d9d9"; Tile.ColorAllowed = "#38b321"; Tile.ColorMovingToNow = "#b8c153"; Tile.ColorAllowedForBeat = "#cf3a3a"; Tile.TileType = { PLAYABLE: 0, NONPLAYABLE: 1 }; Tile.prototype.setMan = function(man) { this.man = man; }; Tile.prototype.clearMan = function() { this.man = undefined; //TODO null? +RETHINK }; Tile.prototype.setAsAllowed = function() { var graphic = this.graphic; fabric.util.animateColor(this.graphic.fill, Tile.ColorAllowed, colorAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll(); } }); this.isAllowed = true; }; Tile.prototype.setAsAllowedForBeat = function() { var graphic = this.graphic; fabric.util.animateColor(this.graphic.fill, Tile.ColorAllowedForBeat, colorAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll(); } }); this.isAllowedForBeat = true; }; Tile.prototype.clearHighlights = function() { var graphic = this.graphic; fabric.util.animateColor(this.graphic.fill, Tile.ColorPlayable, colorAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll(); } }); this.isAllowed = false; this.isAllowedForBeat = false; }; Tile.prototype.setAsMovingToNow = function() { var graphic = this.graphic; fabric.util.animateColor(this.graphic.fill, Tile.ColorMovingToNow, colorAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll(); } }); }; Tile.prototype.isAllowedForMove = function() { return this.isAllowed || this.isAllowedForBeat; }; Tile.prototype.onMouseOver = function() { if (this.isAllowedForMove()) { var graphic = this.graphic; fabric.util.animateColor(graphic.fill, //TODO: colorAllowed/this.fill +REFACTOR Color(graphic.fill).lightenByRatio(0.2).toString(), hoverAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll(); } }); } }; Tile.prototype.onMouseOut = function() { if (this.isAllowedForMove()) { var graphic = this.graphic; fabric.util.animateColor(graphic.fill, Color(graphic.fill).darkenByRatio(0.1666).toString(), hoverAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll(); } }); } }; Tile.prototype.onMouseDown = function() { if (this.isAllowedForMove()) { //move men to selected (this) tile board.sendMove(board.selectedMan.tile, this); board.moveSelectedManTo(this); } else { //or unselect man, if clicked on empty tile board.unselect(); } };
define( 'type.Integer', { // class configuration alias : 'int integer', extend : __lib__.type.Number, // public properties precision : 0, // public methods valid : function( v ) { return this.parent( v, true ) && Math.floor( v ) === v; }, // internal methods init : function() { var max = this.max, min = this.min; this.precision = 0; this.parent( arguments ); // since we want our Types to be instantiated with as much correctness as possible, // we don't want to cast our max/min as Integers if ( max !== Number.POSITIVE_INFINITY ) this.max = max; if ( min !== Number.NEGATIVE_INFINITY ) this.min = min; }, value : function( v ) { return Math.round( this.parent( arguments ) ); } } );
var fs = require('fs'), es = require('event-stream'), asyncJoin = require('gwm-util').asyncJoin; module.exports = function(options) { var type = options.buildType, configFileName = './config/' + type + '.json', fileData = {}, successCallback, errorText, blocker = asyncJoin(function() { successCallback && successCallback(); successCallback = true; }); function fileCallback(key) { return function(err, data) { if (err) { errorText = err; } fileData[key] = data; } }; function loadFile(filePath, key) { if (fs.existsSync(filePath)) { fs.readFile(filePath, {encoding: 'utf-8'}, blocker.newCallback(fileCallback(key))); } } loadFile(configFileName, 'config'); loadFile(__dirname + '/section-header.hbm', 'header'); loadFile(__dirname + '/section-footer.hbm', 'footer'); blocker.complete(); return es.map(function (file, cb) { function onLoadedFiles() { if (errorText) { cb('could not load file: ' + errorText, file); } else { options.config = fileData.config; var handlebars = require('handlebars'), header = handlebars.compile(fileData.header), footer = handlebars.compile(fileData.footer) headerContent = header(options), footerContent = footer(options); file.contents = Buffer.concat([new Buffer(headerContent), file.contents, new Buffer(footerContent)]); cb(null, file); } } // there will only be a single file in this stream so we're using successCallback as a flag if we've fully loaded if (successCallback) { onLoadedFiles(); } else { successCallback = onLoadedFiles; } }); };
var postData = querystring.stringify({ 'value' : '55', 'room_id' : '1' }); var options = { hostname: 'localhost', port: 80, path: '/temperatures', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body req.write(postData); req.end();
'use strict'; /** * Created by x on 11/23/15. */ var path = require('path'); var webpack = require('webpack'); var os = require('os'); var WebpackDevServer = require('webpack-dev-server'); var config = require('./webpack.config.dev'); var pathToBuild = path.resolve(__dirname, 'www'); var IPv4 for(var i=0;i<os.networkInterfaces().en0.length;i++){ if(os.networkInterfaces().en0[i].family=='IPv4'){ IPv4=os.networkInterfaces().en0[i].address; } } console.log(IPv4) //import config from './webpack.dev.config'; var open = require('open'); const opts_config = { port: 8676 } var compiler = webpack(config); /*** * publicPath 启动服务的资源路径 */ var server = new WebpackDevServer(compiler, { contentBase: path.resolve(__dirname,'www'), compress: true, hot: true, public:IPv4, publicPath: config.output.publicPath, open: true, inline: true, /* proxy: { "/": { target: "http://192.168.1.102:8000", secure: false } }*/ }) server.listen(9090, '0.0.0.0', function (err, result) { if (err) { console.log(err); } console.log(`Listening at ${IPv4}:9090/index.html`); open(`http://${IPv4}:9090/index.html`); });
import React from 'react'; import PostImage from '../components/story/PostImage'; import TwoPostImages from '../components/story/TwoPostImages'; import StoryPage from '../components/story/StoryPage'; import StoryTextBlock from '../components/story/StoryTextBlock'; import StoryImages from '../components/story/StoryImages'; import StoryIntro from '../components/story/StoryIntro'; const imgDirPath = "/images/stories/2016-11-20-irina-and-lucian-maternity-photo-session/"; const imgDirPath1 = "stories/2016-11-20-irina-and-lucian-maternity-photo-session"; class IrinaAndLucianMaternityPhotoSessionStory extends React.Component { constructor() { super(); } render() { return ( <StoryPage logoDirPath={imgDirPath1} logoPrefix="teaser" logoNumber="08-2048" title="Irina & Lucian Maternity Photos" author="Dan" location="Charlottenburg Palace, Berlin" tags="maternity, baby, pregnancy"> <StoryIntro> Our friends, Lucian and Irina are having a baby. This is such a wonderful moment! We decided to go together at the Charlottenburg Palace to do a maternity photo session. We were really lucky we got a wonderful sunny weekend, the last sunny one this autumn, before all of the leaves have already fallen. </StoryIntro> <StoryTextBlock title="The Charlottenburg Palace"> The impressive palace is a great place to take photos and this time is covered with scaffolding, which somehow gives a symbolic hint to our photo shoot: &quot;work in progress!&quot; We start our photo session here, taking advantage of the bright sun. I&apos;m using a polarizer filter here, to make the colors pop! </StoryTextBlock> <StoryImages> <PostImage dirPath={imgDirPath} number="01" /> <TwoPostImages dirPath={imgDirPath} number1="02" number2="03" /> <TwoPostImages dirPath={imgDirPath} number1="05" number2="06" /> <PostImage dirPath={imgDirPath} number="07" /> <PostImage dirPath={imgDirPath} number="10" /> <PostImage dirPath={imgDirPath} number="27" /> </StoryImages> <StoryTextBlock title="The Forest"> The sun coming through the colorful leaves of the autumn gave the perfect light for the next photos. Using a long lens allowed me to isolate my subjects and bring that great shallow depth of field! I&apos;ll let you observe the authentic joy on Lucian and Irina&apos;s faces, brought by this great moment in their lives, having a baby. </StoryTextBlock> <StoryImages> <PostImage dirPath={imgDirPath} number="16" /> <TwoPostImages dirPath={imgDirPath} number1="13" number2="15" /> <PostImage dirPath={imgDirPath} number="19" /> <TwoPostImages dirPath={imgDirPath} number1="20" number2="21" /> <PostImage dirPath={imgDirPath} number="22" /> <TwoPostImages dirPath={imgDirPath} number1="23" number2="24" /> <PostImage dirPath={imgDirPath} number="35" /> </StoryImages> <StoryTextBlock title="The Lake"> Moving away from &quot;the forest&quot;, we chose the nearby lake is our third location. <br/> In the next photo, the contrast between the blue lake and Irina&apos;s orange pullover is just amazing. <br/> You might already know that the bridge in the Charlottenburg Garden is one of our <a href="/streets-of-berlin/charlottenburg-bridge-in-autumn.html">favorite places</a>. Like always, it gave me a really nice opportunity to play with reflections. </StoryTextBlock> <StoryImages> <PostImage dirPath={imgDirPath} number="28" /> <PostImage dirPath={imgDirPath} number="30" /> <PostImage dirPath={imgDirPath} number="31" /> <PostImage dirPath={imgDirPath} number="37" /> <PostImage dirPath={imgDirPath} number="39" /> <PostImage dirPath={imgDirPath} number="42" /> </StoryImages> <StoryTextBlock title="The Autumn"> The colors of the autumn are just amazing! My favorite photo from this series is the next one. I call it &quot;The Tree of Life&quot;, as there are four colors spreading from each of the corners, one for each of the seasons. We have spring and summer to the left, and autumn and winter to the right. And of course, pregnant Irina in the middle getting support from her dear husband, Lucian. </StoryTextBlock> <StoryImages> <PostImage dirPath={imgDirPath} number="44" /> <PostImage dirPath={imgDirPath} number="46" /> <PostImage dirPath={imgDirPath} number="48" /> <PostImage dirPath={imgDirPath} number="51" /> <TwoPostImages dirPath={imgDirPath} number1="52" number2="53" /> <PostImage dirPath={imgDirPath} number="54" /> <TwoPostImages dirPath={imgDirPath} number1="55" number2="56" /> <PostImage dirPath={imgDirPath} number="59" /> <TwoPostImages dirPath={imgDirPath} number1="60" number2="61" /> <TwoPostImages dirPath={imgDirPath} number1="62" number2="63" /> <PostImage dirPath={imgDirPath} number="64" /> </StoryImages> </StoryPage>); } } export default IrinaAndLucianMaternityPhotoSessionStory;
search_result['3225']=["topic_00000000000007B9.html","ApplicantDetailRequestDto.Notes Property",""];
/* global HTMLImageElement */ /* global HTMLCanvasElement */ /* global SVGElement */ import getOptionsFromElement from "./getOptionsFromElement.js"; import renderers from "../renderers"; import {InvalidElementException} from "../exceptions/exceptions.js"; // Takes an element and returns an object with information about how // it should be rendered // This could also return an array with these objects // { // element: The element that the renderer should draw on // renderer: The name of the renderer // afterRender (optional): If something has to done after the renderer // completed, calls afterRender (function) // options (optional): Options that can be defined in the element // } function getRenderProperties(element){ // If the element is a string, query select call again if(typeof element === "string"){ return querySelectedRenderProperties(element); } // If element is array. Recursivly call with every object in the array else if(Array.isArray(element)){ var returnArray = []; for(let i = 0; i < element.length; i++){ returnArray.push(getRenderProperties(element[i])); } return returnArray; } // If element, render on canvas and set the uri as src else if(typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLImageElement){ return newCanvasRenderProperties(element); } // If SVG else if( (element && element.nodeName && element.nodeName.toLowerCase() === 'svg') || (typeof SVGElement !== 'undefined' && element instanceof SVGElement) ){ return { element: element, options: getOptionsFromElement(element), renderer: renderers.SVGRenderer }; } // If canvas (in browser) else if(typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLCanvasElement){ return { element: element, options: getOptionsFromElement(element), renderer: renderers.CanvasRenderer }; } // If canvas (in node) else if(element && element.getContext){ return { element: element, renderer: renderers.CanvasRenderer }; } else if(element && typeof element === 'object' && !element.nodeName) { return { element: element, renderer: renderers.ObjectRenderer }; } else{ throw new InvalidElementException(); } } function querySelectedRenderProperties(string){ var selector = document.querySelectorAll(string); if(selector.length === 0){ return undefined; } else{ let returnArray = []; for(let i = 0; i < selector.length; i++){ returnArray.push(getRenderProperties(selector[i])); } return returnArray; } } function newCanvasRenderProperties(imgElement){ var canvas = document.createElement('canvas'); return { element: canvas, options: getOptionsFromElement(imgElement), renderer: renderers.CanvasRenderer, afterRender: function(){ imgElement.setAttribute("src", canvas.toDataURL()); } }; } export default getRenderProperties;
import assert from 'assert'; import sinon from 'sinon'; import fs from 'fs'; import stream from 'stream'; import { InsertStream } from '../'; /** * Transform class to turn our string JSON data into objects. */ class TransformToObject extends stream.Transform { constructor() { super({objectMode:true}); } _transform(data, encoding, cb) { data.split('\n') .filter(line => line.length) .forEach(line => this.push(JSON.parse(line))); cb(); } } function getSpies() { const insertSpy = sinon.spy(); const insertManySpy = sinon.spy(); const collection = { insert(data, cb) { insertSpy(data); cb(); }, insertMany(data, cb) { insertManySpy(data); cb(); } }; return [insertSpy, insertManySpy, collection]; } function getOption(opts) { return { highWaterMark: opts.highWaterMark, collectionName: 'test-collection', db: { collection: function(name, cb) { cb(opts.err, opts.collection); } } }; } function createTestStream(highWaterMark, err, cb) { const [insertSpy, insertManySpy, collection] = getSpies(); const option = getOption({highWaterMark, collection, err}); const stream = fs.createReadStream(`${__dirname}/data.json`, {encoding: 'utf8'}) .pipe(new TransformToObject()) .pipe(new InsertStream(option)); cb(stream, {insertSpy, insertManySpy}); } export function testSingleWrite(done) { createTestStream(1, null, (stream, spies) => { stream.on('finish', () => { assert.ok(spies.insertSpy.calledThrice); assert.ok(spies.insertManySpy.notCalled); done(); }); }); } export function testBatchWrite(done) { createTestStream(2, null, (stream, spies) => { stream.on('finish', () => { assert.ok(spies.insertSpy.calledOnce); assert.ok(spies.insertManySpy.calledOnce); assert.equal(spies.insertManySpy.getCall(0).args[0].length, 2); done(); }); }); } export function testError(done) { createTestStream(1, {}, stream => { stream.on('error', () => { assert.ok(true); done(); }); }); }
/*jslint node: true */ 'use strict'; var npm = require('npm'); module.exports = Npm; function Npm (callback) { var conf = { jobs: 1 }; npm.load(conf, callback); } Npm.prototype.search = function (searchTerms, callback) { npm.commands.search(searchTerms, true, callback); }; Npm.prototype.view = function (name, callback) { npm.commands.view([name], callback); };
import { EmailTemplate } from 'email-templates' import Promise from 'bluebird' const sendgrid = require('sendgrid')(process.env.SENDGRID_MAILER_KEY) const sendEmail = Promise.promisify(sendgrid.send, { context: sendgrid }) const DEVELOPMENT = process.env.NODE_ENV === 'development' const sanitize = DEVELOPMENT ? require('sanitize-filename') : null import path from 'path' import fs from 'fs' export function getTemplate(templateName) { const templatePath = path.join(__dirname, '../', 'templates', templateName) return new EmailTemplate(templatePath, { juiceOptions: { preserveMediaQueries: true, preserveImportant: true, removeStyleTags: true } }) } export async function send({ template, sendgridGroupId, data, emailSettings, to, subject, replyto }) { // eslint-disable-line max-len try { const result = await template.render(data) if (DEVELOPMENT) { fs.writeFileSync( `${__dirname}/.temp/${sanitize(`test-${subject}-${to}.html`)}`, result.html) } const params = { from: emailSettings.from, fromname: emailSettings.fromName, replyto: replyto || emailSettings.from, to: [to], subject: `${subject}`, html: result.html } const sendgridEmail = new sendgrid.Email(params) sendgridEmail.setASMGroupID(sendgridGroupId) const email = await sendEmail(sendgridEmail) return { email } } catch (err) { console.log('send error: ', err) return { err } } }
/* globals __dirname */ 'use strict'; var autoprefixer = require('autoprefixer-core'); var Webpack = require('webpack'); var HtmlWebpack = require('html-webpack-plugin'); var path = require('path'); var npmPath = path.resolve(__dirname, 'node_modules'); var config = { sassOptions : ( '?outputStyle=nested&includePaths[]=' + npmPath ) }; module.exports = { entry: [ './demo/bootstrap.js', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:9001' ], module: { loaders: [ { test : /\.(jsx|js)$/, loaders : ['babel', 'react-hot'], exclude : /node_modules/ }, { test : /\.scss$/, loader : 'style!css!postcss!sass' + config.sassOptions, include : /scss/ }, { test : /\.css$/, loader : 'style-loader!css-loader' } ] }, output: { filename : 'demo.js', path : path.resolve(__dirname, 'demo-build'), publicPath : '/' }, resolve : { extensions : ['', '.js', '.jsx', '.css', '.scss'] }, plugins: [ new HtmlWebpack({ template : './demo/index.html' }), new Webpack.HotModuleReplacementPlugin(), new Webpack.optimize.OccurenceOrderPlugin() ], postcss : function() { return [autoprefixer]; } };
const path = require('path') const sassTrue = require('sass-true') const sassFile = path.join(__dirname, 'flex-columns.test.scss') sassTrue.runSass({ file: sassFile }, describe, test)
// React app import React from 'react' import {render} from 'react-dom' import App from './components/base_layout/App.jsx' // Redux state manager import { Provider } from 'react-redux' import { createStore } from 'redux' import reducers from './state_manager/reducers' // Electron IPC communication events import ipcRendererEvents from './ipc_layer/ipcRendererEvents' ////////////////////////// /// React Application //// ////////////////////////// export let store = createStore(reducers) render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') ) ////////////////////////////// /// IPC with main process //// ////////////////////////////// ipcRendererEvents(store) /////////////////// /// Workarounds /// /////////////////// /* The chunk below will be executed after the react app is rendered */ import {resizer} from './components/base_layout/layout.css' let nav = document.querySelector('nav') let node = document.querySelector('.'+resizer) let startX, startWidth const initDrag = e => { startX = e.clientX startWidth = parseInt(window.getComputedStyle(nav).width) window.addEventListener('mousemove', doDrag, false) window.addEventListener('mouseup', stopDrag, false) } const doDrag = e => { const newWidth = (startWidth + e.clientX - startX) nav.style.width = (newWidth < 200 ? 200 : (newWidth > 400 ? 400: newWidth) ) + 'px' } const stopDrag = e => { window.removeEventListener('mousemove', doDrag, false) window.removeEventListener('mouseup', stopDrag, false) } node.addEventListener('mousedown', initDrag, false)
var mongoose = require('mongoose'), bcrypt = require('bcrypt'), userSchema = mongoose.Schema({ fullName: { type: String }, email: { type: String, required: true, unique: true, lowercase: true }, password: { type: String, required: true }, user_avatar: { type: String, default: 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png' }, registered_on: { type: Date, default: Date.now } }); userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(user.password, salt, function(err, hash) { user.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(password, done) { bcrypt.compare(password, this.password, function(err, isMatch) { done(err, isMatch); }); }; module.exports = mongoose.model('User', userSchema, 'users');
// 对字符串头尾进行空格字符的去除、包括全角半角空格、Tab等,返回一个字符串 function trim(str) { var regex1 = /^\s*/; var regex2 = /\s*$/; return (str.replace(regex1, "")).replace(regex2, ""); } // 给一个element绑定一个针对event事件的响应,响应函数为listener function addEvent(element, event, listener, isCorrect) { if (element.addEventListener) { element.addEventListener(event, listener, isCorrect); } else if (element.attachEvent) { element.attachEvent("on" + event, listener); } else { element["on" + event] = listener; } } var validate = { //将name中的所有中文字符替换(1中文字符长度=2英文字符长度) nameVali: function (str) { var chineseRegex = /[\u4E00-\uFA29]|[\uE7C7-\uE7F3]/g; var lenRegex = /^.{4,16}$/; if (str.length == 0) { return false; } else if (!lenRegex.test(str)) { return false } else { return true; } }, //密码验证 passwordVali: function (str) { return (str.length >= 8 && str.length<= 20); }, //再次输入的密码验证 repasswordVali: function (str, id) { var password = document.querySelector("#" + id).value; return (str === password); }, // 判断是否为邮箱地址 // 第一部分:由字母、数字、下划线、短线“-”、点号“.”组成, // 第二部分:为一个域名,域名由字母、数字、短线“-”、域名后缀组成, // 而域名后缀一般为.xxx或.xxx.xx,一区的域名后缀一般为2-4位,如cn,com,net,现在域名有的也会大于4位 emailVali: function (str) { var regex = /^([\w-*\.*]+)@([\w-]+)((\.[\w-]{2,4}){1,2})$/; return regex.test(str); }, // 判断是否为手机号 telephoneVali: function (str) { var regex = /^1[0-9]{10}$/; return regex.test(str); }, allVali: function () { var inputArray = document.querySelectorAll("input"); var count = 0; for (var cur = 0; cur < inputArray.length; cur++) { if (inputArray[cur].className == "correctInput") { count++; } } return (count === inputArray.length); } } function formFactory(data) { var whole = { settings: { label: data.label, name: data.name, type: data.type, validator: data.validator, rules: data.rules, success: data.success, empty: data.empty, fail: data.fail }, generateInput: function(type) { var that = this; var container = document.getElementById("father"); var span = document.createElement("span"); span.innerText = that.settings.label; var p = document.createElement("p"); p.className = "status"; var label = document.createElement("label"); var input = document.createElement("input"); input.name = that.settings.name; input.type = that.settings.type; input.id = that.settings.name; addEvent(input, "focus", function() { input.className = "inputFocus"; p.innerText = that.settings.rules; }, true); addEvent(input, "blur", function() { var verify = ""; if (type == "single") { verify = that.settings.validator(this.value); } else if (type == "verify") { verify = that.settings.validator(this.value) && (this.value.length != 0); } if (verify) { input.className = "correctInput"; p.className = "status correctSta"; p.innerText = that.settings.success; } else { input.className = "wrongInput"; p.className = "status wrongSta"; if (this.value.length == 0) { p.innerText = that.settings.empty; } else p.innerText = that.settings.fail; } }, true); container.appendChild(label); label.appendChild(span); label.appendChild(input); container.appendChild(p); }, generateButton: function() { var that = this; var container = document.getElementById("father"); var button = document.createElement("button"); button.innerHTML = that.settings.label; addEvent(button, "click", function() { if (that.settings.validator()) { alert("提交成功!"); } else alert("提交失败!"); }, false); container.appendChild(button); }, init: function() { var that = this; //判断类型 switch (that.settings.name) { case 'name': that.generateInput('single'); break; case 'password': that.generateInput('single'); break; case 'repassword': that.generateInput('verify'); break; case 'email': that.generateInput('single'); break; case 'telephone': that.generateInput('single'); break; case 'submit': that.generateButton(); break; } } } return whole.init(); } window.onload = function() { for (var i = 0; i < data.length; i++) { formFactory(data[i]); } }
import * as React from 'react'; import {px2rem} from '@bizfe/biz-mobile-ui/build/util/util'; import { Button, LinearProgress, CircleProgress } from '@bizfe/biz-mobile-ui'; const styles = { progress: { width: '90%', margin: '20px auto 0', }, } export default class Progress extends React.Component { constructor(...args) { super(...args); this.state = {progress: 10} } changeProgress(value) { if (value < 0) { value = 0; } else if (value > 100) { value = 100; } this.setState({progress: value}); } render() { return ( <div> <CircleProgress value={25}/> <CircleProgress value={90} color="red"/> <CircleProgress value={this.state.progress} size={px2rem(100)} linecap="round"/> <LinearProgress style={styles.progress}/> <LinearProgress style={Object.assign({},styles.progress,{height: px2rem(15)})} color="#8E24AA" fillColor="#FFF"/> <LinearProgress style={styles.progress} mode="determinate" value={this.state.progress}/> <Button style={Object.assign({},styles.progress, {display: 'block'})} onTouchTap={()=>this.changeProgress(this.state.progress + 20)} size="small">+ 20</Button> <Button style={Object.assign({},styles.progress, {display: 'block'})} onTouchTap={()=>this.changeProgress(this.state.progress - 10)} size="small">- 10</Button> </div> ); } }
/* Copyright (C) 2012 Kory Nunn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. NOTE: This code is formatted for run-speed and to assist compilers. This might make it harder to read at times, but the code's intention should be transparent. */ // IIFE our function ((exporter) => { // Define our function and its properties // These strings are used multiple times, so this makes things smaller once compiled const func = 'function', isNodeString = 'isNode', d = document, // Helper functions used throughout the script isType = (object, type) => typeof object === type, // Recursively appends children to given element. As a text node if not already an element appendChild = (element, child) => { if (child !== null) { if (Array.isArray(child)) { // Support (deeply) nested child elements child.map(subChild => appendChild(element, subChild)); } else { if (!crel[isNodeString](child)) { child = d.createTextNode(child); } element.appendChild(child); } } }; // function crel (element, settings) { // Define all used variables / shortcuts here, to make things smaller once compiled let args = arguments, // Note: assigned to a variable to assist compilers. index = 1, key, attribute; // If first argument is an element, use it as is, otherwise treat it as a tagname element = crel.isElement(element) ? element : d.createElement(element); // Check if second argument is a settings object if (isType(settings, 'object') && !crel[isNodeString](settings) && !Array.isArray(settings)) { // Don't treat settings as a child index++; // Go through settings / attributes object, if it exists for (key in settings) { // Store the attribute into a variable, before we potentially modify the key attribute = settings[key]; // Get mapped key / function, if one exists key = crel.attrMap[key] || key; // Note: We want to prioritise mapping over properties if (isType(key, func)) { key(element, attribute); } else if (isType(attribute, func)) { // ex. onClick property element[key] = attribute; } else { // Set the element attribute element.setAttribute(key, attribute); } } } // Loop through all arguments, if any, and append them to our element if they're not `null` for (; index < args.length; index++) { appendChild(element, args[index]); } return element; } // Used for mapping attribute keys to supported versions in bad browsers, or to custom functionality crel.attrMap = {}; crel.isElement = object => object instanceof Element; crel[isNodeString] = node => node instanceof Node; // Expose proxy interface crel.proxy = new Proxy(crel, { get: (target, key) => { !(key in crel) && (crel[key] = crel.bind(null, key)); return crel[key]; } }); // Export crel exporter(crel, func); })((product, func) => { if (typeof exports === 'object') { // Export for Browserify / CommonJS format module.exports = product; } else if (typeof define === func && define.amd) { // Export for RequireJS / AMD format define(() => product); } else { // Export as a 'global' function this.crel = product; } });
const fs = require('fs'); const dns = require('dns'); const argv = require('yargs').argv; const Seismometer = require('./seismometer'); const Communicator = require('./communicator'); function assertOnline() { return new Promise((fulfill, reject) => { dns.resolve('www.google.com', err => { if (err) { reject(new Error('Not online. Cannot resolve www.google.com')); } else { fulfill(); } }); }); } function main() { if (argv.help) { console.log('usage: npm run [--port /dev/port]'); process.exit(0); } if (argv.port) { if (!fs.existsSync(argv.port)) { console.error(`Port "${argv.port}" does not exist.`); process.exit(1); } } const communicator = new Communicator(); const seismometer = new Seismometer(); seismometer.watch(); assertOnline() .then(() => communicator.connect(argv.port)) .then(() => { console.log('Connected to', communicator.port.path); seismometer.on('quake', info => { console.log(`Quake! At ${info.date} with a magnitude of ${info.magnitude}`); communicator.send(info); }); console.log('Watching for quakes...'); }) .catch(err => { console.error(err); process.exit(1); }); } main();
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import IncredibleOffersContainer from './IncredibleOffers/IncredibleOfferContainer'; export default ( <Route path="/" component={App}> <IndexRoute component={IncredibleOffersContainer} /> <Route path="/special-offers" component={IncredibleOffersContainer} /> <Route path="/special-offers/:filter" component={IncredibleOffersContainer} /> </Route> );
function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } var port = normalizePort(process.env.PORT || '3000'); module.exports = { port: port, db: 'mongodb://'+process.env.IP+'/nexus' };
(function() { 'use strict'; angular .module('lcRegistration') .config(["$routeProvider", function($routeProvider) { $routeProvider .when("/", { templateUrl: "/client/app/regForm/regForm.html", controller: "registrationController" }).when("/hello", { templateUrl: "/client/app/hello/hello.html", controller: "helloController" }).otherwise({ redirectTo: "/" }); } ]); })();
var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); app.use(express.bodyParser()); app.use(app.router); app.use(express.static(__dirname + '/public')); // Simple REST server. var users = []; app.post('/user', function(req, res) { users[req.body.name] = req.body; res.send({ error: false }); }); app.get('/user/:name', function(req, res) { var user = users[req.params.name]; if (user) { res.send({ error: false, data: user }); } else { res.send({ error: true }); } }); app.put('/user/:name', function(req, res) { var user = users[req.params.name]; if (user) { res.send({ error: false }); user.weight = req.body.weight; } else { res.send({ error: true }); } }); app.del('/user/:name', function(req, res) { var user = users[req.params.name]; if (user) { delete users[req.params.name]; res.send({ error: false }); } else { res.send({ error: true }); } }); // XMLJSON file app.get('/xhr-json.js', function(req, res) { res.sendfile('xhr-json.js', { root: __dirname + '/..' }); }); // Mocha/Chai files var mochaDir = path.dirname(require.resolve('mocha')); var chaiDir = path.dirname(require.resolve('chai')); app.get('/mocha.css', function(req, res) { res.sendfile('mocha.css', { root: mochaDir }); }); app.get('/mocha.js', function(req, res) { res.sendfile('mocha.js', { root: mochaDir }); }); app.get('/chai.js', function(req, res) { res.sendfile('chai.js', { root: chaiDir }); }); http.createServer(app).listen(4444, function() { console.log('Express server listening.'); });
'use strict'; function getBetterUpgradeMessage(foundVersion) { let version = (foundVersion && foundVersion[1]) ? `(${foundVersion[1]}) ` : ''; return `A new version of Ghost Core ${version}is available! Hot Damn. \ <a href="http://support.ghost.org/how-to-upgrade/" target="_blank">Click here</a> \ to learn more on upgrading Ghost Core.`; } /** * Simple timeout + attempt based function that checks to see if Ghost Core has an update available, * and replaces the notification text with something a little more specific.'; */ function upgradeNotification(attempts = 100) { const elements = document.querySelectorAll('aside.gh-alerts .gh-alert-content'); elements.forEach((element) => { let foundVersion = /Ghost (\d\.\d\.\d) is available/g.exec(element.innerText); element.innerHTML = getBetterUpgradeMessage(foundVersion); }); if (elements.length === 0 && attempts > 0) { setTimeout(() => upgradeNotification(attempts - 1), 50); } } /** * Init */ document.addEventListener('DOMContentLoaded', () => setTimeout(upgradeNotification, 50));
'use strict' var PassThrough = require('stream').PassThrough var statistics = require('vfile-statistics') var fileSetPipeline = require('./file-set-pipeline') module.exports = run // Run the file set pipeline once. // `callback` is invoked with a fatal error, or with a status code (`0` on // success, `1` on failure). function run(options, callback) { var settings = {} var stdin = new PassThrough() var tree var detectConfig var hasConfig var detectIgnore var hasIgnore try { stdin = process.stdin } catch (_) { // Obscure bug in Node (seen on Windows). // See: <https://github.com/nodejs/node/blob/f856234/lib/internal/process/stdio.js#L82>, // <https://github.com/AtomLinter/linter-markdown/pull/85>. } if (!callback) { throw new Error('Missing `callback`') } if (!options || !options.processor) { return next(new Error('Missing `processor`')) } // Processor. settings.processor = options.processor // Path to run as. settings.cwd = options.cwd || process.cwd() // Input. settings.files = options.files || [] settings.extensions = (options.extensions || []).map(extension) settings.filePath = options.filePath || null settings.streamIn = options.streamIn || stdin // Output. settings.streamOut = options.streamOut || process.stdout settings.streamError = options.streamError || process.stderr settings.alwaysStringify = options.alwaysStringify settings.output = options.output settings.out = options.out // Null overwrites config settings, `undefined` does not. if (settings.output === null || settings.output === undefined) { settings.output = undefined } if (settings.output && settings.out) { return next(new Error('Cannot accept both `output` and `out`')) } // Process phase management. tree = options.tree || false settings.treeIn = options.treeIn settings.treeOut = options.treeOut settings.inspect = options.inspect if (settings.treeIn === null || settings.treeIn === undefined) { settings.treeIn = tree } if (settings.treeOut === null || settings.treeOut === undefined) { settings.treeOut = tree } // Configuration. detectConfig = options.detectConfig hasConfig = Boolean(options.rcName || options.packageField) if (detectConfig && !hasConfig) { return next( new Error('Missing `rcName` or `packageField` with `detectConfig`') ) } settings.detectConfig = detectConfig === null || detectConfig === undefined ? hasConfig : detectConfig settings.rcName = options.rcName || null settings.rcPath = options.rcPath || null settings.packageField = options.packageField || null settings.settings = options.settings || {} settings.configTransform = options.configTransform settings.defaultConfig = options.defaultConfig // Ignore. detectIgnore = options.detectIgnore hasIgnore = Boolean(options.ignoreName) settings.detectIgnore = detectIgnore === null || detectIgnore === undefined ? hasIgnore : detectIgnore settings.ignoreName = options.ignoreName || null settings.ignorePath = options.ignorePath || null settings.ignorePatterns = options.ignorePatterns || [] settings.silentlyIgnore = Boolean(options.silentlyIgnore) if (detectIgnore && !hasIgnore) { return next(new Error('Missing `ignoreName` with `detectIgnore`')) } // Plugins. settings.pluginPrefix = options.pluginPrefix || null settings.plugins = options.plugins || {} // Reporting. settings.reporter = options.reporter || null settings.reporterOptions = options.reporterOptions || null settings.color = options.color || false settings.silent = options.silent || false settings.quiet = options.quiet || false settings.frail = options.frail || false // Process. fileSetPipeline.run({files: options.files || []}, settings, next) function next(error, context) { var stats = statistics((context || {}).files) var failed = Boolean( settings.frail ? stats.fatal || stats.warn : stats.fatal ) if (error) { callback(error) } else { callback(null, failed ? 1 : 0, context) } } } function extension(ext) { return ext.charAt(0) === '.' ? ext : '.' + ext }
export default { analytics: () => { return { logEvent: () => {}, setCurrentScreen: () => {} }; } };
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'preview', 'ca', { preview: 'Visualització prèvia' } );