code
stringlengths
2
1.05M
import React, { Component, PropTypes } from 'react'; import { Image } from 'react-bootstrap'; require('./styles.scss'); class SocialBar extends Component { constructor(props) { super(props); } render() { const { icon, url } = this.props; return ( <a href={url} target="_blank"> <Image src={icon} className="profile-header-social-icon" /> </a> ); } } SocialBar.propTypes = { children: PropTypes.any, icon: PropTypes.any.isRequired, url: PropTypes.string.isRequired, }; export default SocialBar;
'use strict'; describe('heroList', function(){ //Load module that contains the heroList component beforeEach(module('heroList')); describe('HeroListController', function(){ it('should create a `heroes` model with 6 heroes', inject(function($componentController){ var ctrl = $componentController('heroList'); expect(ctrl.heroes.length).toBe(6); })); }); });
// to be used if new modules are added to MSF. Mamoru.Sync.allModules = function(){ var moduleFixtures = { exploit: 'module.exploits', post: 'module.post', auxiliary: 'module.auxiliary', payload: 'module.payloads', encoder: 'module.encoders', nop: 'module.nops', }; // get module stats from MSF //var modStats = msfAPI.clientExec(Mamoru.API.client,['core.module_stats']); var fullModArray = []; for (key in moduleFixtures) { var modCatArray = msfAPI.clientExec([moduleFixtures[key]]); for(var i=0;i<modCatArray.length;i++){ if(!moduleIsInMongo(modCatArray[i],key)){ fullModArray.push({mod:modCatArray[i],cat:key}) } } }; var aJob = new Job(Mamoru.Collections.Jobs, 'syncModules', {modules:fullModArray}); aJob.priority('high').save(); Mamoru.Queues.fixtures.trigger(); } // sync MSF workspaces with Mamoru projects Mamoru.Sync.allProjects = function(){ var tempConsole = Mamoru.Utils.createConsole() var msfWorkspacesObj = msfAPI.clientExec(['db.workspaces']); for(var i=0;i<msfWorkspacesObj.workspaces.length;i++){ if(Mamoru.Collections.Projects.find({name:msfWorkspacesObj.workspaces[i].name}).count() === 0){ Mamoru.Collections.Projects.insert(msfWorkspacesObj.workspaces[i]); } } Mamoru.Utils.destroyConsole(tempConsole.id); } Mamoru.Sync.Sessions = function(){ var knownSessions = Mamoru.Collections.Sessions.find(); var currentSessions = Mamoru.Utils.listSessions(); var numSessions = Object.keys(currentSessions).length; if(numSessions > 0){ for(var k in currentSessions){ if(Mamoru.Collections.Sessions.findOne({exploit_uuid: currentSessions[k]["exploit_uuid"] }) == undefined ){ currentSessions[k]["startedAt"] = moment.now(); currentSessions[k]["runBy"] = Meteor.users.findOne(Meteor.userId()).username; currentSessions[k]["sessionId"] = k; currentSessions[k]["established"] = true; Mamoru.Collections.Sessions.insert(currentSessions[k]); } } } else { // set sessions as not established... var oldSessionsList = knownSessions.fetch() var updateObj = {established: false, stoppedAt: moment.now()} for(var i=0; i < oldSessionsList.length(); i++){ Mamoru.Collections.Sessions.update({_id: oldSessionsList[i]._id }, {$set: updateObj }); } } } // used to compare mongo and pg records to determine if something needs to be syncronized.. function checkHost(msfRecord, mongoRecord){ //console.log(msfRecord); var needsUpdate = false; var fieldsToUpdate = {} for(var key in msfRecord){ if(msfRecord[key] != mongoRecord[key]){ fieldsToUpdate[key] = msfRecord[key]; needsUpdate = true; } } var msfServices = Mamoru.Utils.getHostServices(msfRecord.address) if(msfServices){ msfServices = msfServices.map((service)=>{ delete service.host; return service; }); } if(msfServices.length != mongoRecord.services.length){ needsUpdate = true; fieldsToUpdate.services = msfServices; } var msfNotes = Mamoru.Utils.getHostNotes(msfRecord.address) if(msfNotes){ msfServices = msfNotes.map((note)=>{ delete note.host; return note; }); } if(msfNotes.length != mongoRecord.notes.length){ needsUpdate = true; fieldsToUpdate.notes = msfNotes; } var msfVulns = Mamoru.Utils.getHostVulns(msfRecord.address) if(msfVulns){ msfVulns = msfVulns.map((vuln)=>{ delete vuln.host; return vuln; }); } if(msfVulns.length != mongoRecord.vulns.length){ needsUpdate = true; fieldsToUpdate.vulns = msfVulns; } return {needsUpdate:needsUpdate,toUpdate:fieldsToUpdate} } Mamoru.Sync.AllProjectHosts = function(projectName){ let thisWorkspace = Mamoru.Collections.Projects.findOne({name:projectName}); Mamoru.Utils.setProject(thisWorkspace.name); //get hosts array from msf let hostsObj = msfAPI.clientExec(['db.hosts', {}]); // loop hosts array for(var h=0;h<hostsObj.hosts.length;h++){ let thisHost = Mamoru.Collections.Hosts.findOne({projectId:thisWorkspace._id, address:hostsObj.hosts[h].address}); //if that host does not exist, retrieve hosts services and insert into mongo if(!thisHost){ //set extra fields not returned directly from MSF for mongo organization / 'relationships' console.log(`syncing host ${hostsObj.hosts[h].address} from pg to mongo`) hostsObj.hosts[h].projectId = thisWorkspace._id // insert in mongo, which will trigger insert hook. Mamoru.Collections.Hosts.insert(hostsObj.hosts[h]); // else update according to what is in msf for the host } else { console.log('host exists'); var ch = checkHost(hostsObj.hosts[h],thisHost); // if MSF update_at date is not the same as mongos update_at date if(ch.needsUpdate) { console.log('host needs update'); // will not trigger hook Mamoru.Collections.Hosts.direct.update(thisHost._id, {$set:ch.toUpdate}); } } } } Mamoru.Sync.projectHost = function(projectSlug, hostAddress){ let thisWorkspace = Mamoru.Collections.Projects.findOne({slug:projectSlug}); Mamoru.Utils.setProject(thisWorkspace.name); let hostFromMSF = Mamoru.Utils.hostInfo(hostAddress)[0]; let thisHost = Mamoru.Collections.Hosts.findOne({projectId:thisWorkspace._id, address:hostAddress}); //if that host does not exist, retrieve hosts services and insert into mongo if(!thisHost){ //set extra fields not returned directly from MSF for mongo organization / 'relationships' hostFromMSF.projectId = thisWorkspace._id // insert in mongo, which will trigger insert hook. Mamoru.Collections.Hosts.insert(hostFromMSF); // else update according to what is in msf for the host } else { console.log('host exists'); var ch = checkHost(hostFromMSF,thisHost); if(ch.needsUpdate) { console.log('host needs update'); // will not trigger hook Mamoru.Collections.Hosts.direct.update(thisHost._id, {$set:ch.toUpdate}); } } } Mamoru.Sync.ConsolePool = function(){ var poolSize = Meteor.settings.consolePoolSize let currentConsoles = Mamoru.Utils.listConsoles(); if(currentConsoles.consoles && currentConsoles.consoles.length != poolSize){ try { createConsolePool() } catch(err){ console.log("whoa, creating console pool failed: try again in 5 seconds"); Meteor.setTimeout(()=>{Mamoru.Sync.ConsolePool()}, 5000); } } } // scoped to this file function createConsolePool(){ var poolSize = Meteor.settings.consolePoolSize //check if there are existing consoles let existingConsoles = Mamoru.Utils.listConsoles(); console.log(existingConsoles); let numExistingConsoles = existingConsoles.consoles.length console.log(`there are ${numExistingConsoles} existing consoles`); //array of existing console Ids according to MSF let existingConsoleMsfIds = existingConsoles.consoles.map((cons)=>{ return cons.id; }); // remove any consoles in mongo that do not have a matching MSF consoles let numConsolesRemoved = Mamoru.Collections.Consoles.direct.remove({msfId:{$nin:existingConsoleMsfIds}}); if(numConsolesRemoved){ console.log(`removed ${numConsolesRemoved} consoles, from the collection which do not match msf consoles`); } //remove extras consoles if(numExistingConsoles > poolSize){ let consolesToRemove = existingConsoles.splice(0,existingConsoles-poolSize) for(let i=0;i<consolesToRemove.length;i++){ let existsInMongo = Mamoru.Collections.Consoles.findOne({msfId:consolesToRemove[i].id}); if(existsInMongo){ Mamoru.Collections.Consoles.remove(existsInMongo._id); } else { Mamoru.Utils.destroyConsole(consolesToRemove[i].id); } console.log(`removed extra consoleId: ${consolesToRemove[i].id}`); } //add consoles if not enough } else if (numExistingConsoles < poolSize){ for(; numExistingConsoles < poolSize; numExistingConsoles++){ let newConsole = Mamoru.Collections.Consoles.insert({}); let newConsoleId = Mamoru.Collections.Consoles.findOne(newConsole).msfId console.log(`added consoleId: ${newConsoleId} to the pool`); } //ensure msfIds are syncronized } else { Mamoru.Collections.Consoles.direct.remove({}); existingConsoles.forEach((msfConsole)=>{ Mamoru.Collections.Consoles.direct.insert( { msfId:msfConsole.id, prompt:msfConsole.prompt, busy:msfConsole.busy, createdAt:moment().unix() } ); console.log(`synced consoleId: ${msfConsole.id}`); }); } }
document.getElementById('input_search').onfocus = function () { document.getElementById('search').classList.add('activeSearch'); }; document.getElementById('input_search').onblur = function () { document.getElementById('search').classList.remove('activeSearch'); }; try { window.$ = window.jQuery = require('jquery'); require('./navbar'); require('./horizontalScroll'); } catch (e) {}
/// <reference path="lib/jquery-2.0.3.js" /> define(["httpRequester"], function (httpRequester) { function getStudents() { var url = this.url + "api/students/"; return httpRequester.getJSON(url); } function getMarksByStudentId(studentId) { var url = this.url + "api/students/" + studentId + "/marks/"; return httpRequester.getJSON(url); } return { students: getStudents, marks: getMarksByStudentId, url: this.url } });
/** * WhatsApp service provider */ module.exports = { popupUrl: 'whatsapp://send?text={title}%0A{url}', popupWidth: 600, popupHeight: 450 };
var path = require('path'), HtmlReporter = require('protractor-html-screenshot-reporter'); exports.config = { chromeDriver: 'node_modules/chromedriver/bin/chromedriver', // seleniumAddress: 'http://localhost:4444/wd/hub', // Boolean. If true, Protractor will connect directly to the browser Drivers // at the locations specified by chromeDriver and firefoxPath. Only Chrome // and Firefox are supported for direct connect. directConnect: true, // Use existing selenium local/remote // seleniumAddress: http://localhost:4444/wd/hub // When run without a command line parameter, all suites will run. If run // with --suite=login only the patterns matched by the specified suites will // run. // @todo specs: ['specs/aui-login.js'], // The timeout in milliseconds for each script run on the browser. This should // be longer than the maximum time your application needs to stabilize between // tasks. allScriptsTimeout: 20000, baseUrl: 'http://localhost:9010', multiCapabilities: [{ 'browserName': 'chrome' }, { 'browserName': 'firefox' }], onPrepare: function() { // Add a screenshot reporter and store screenshots to `result/screnshots`: jasmine.getEnv().addReporter(new HtmlReporter({ baseDirectory: './result/screenshots', takeScreenShotsOnlyForFailedSpecs: true, preserveDirectory: true, docTitle: 'E2E Result', docName: 'index.html', pathBuilder: function pathBuilder(spec, descriptions, results, capabilities) { var currentDate = new Date(), dateString = currentDate.getFullYear() + '-' + currentDate.getMonth() + '-' + currentDate.getDate(); return path.join(dateString, capabilities.caps_.browserName, descriptions.join('-')); } })); } };
/** * format currency * @ndaidong **/ const { isNumber, } = require('bellajs'); const formatCurrency = (num) => { const n = Number(num); if (!n || !isNumber(n) || n < 0) { return '0.00'; } return n.toFixed(2).replace(/./g, (c, i, a) => { return i && c !== '.' && (a.length - i) % 3 === 0 ? ',' + c : c; }); }; module.exports = formatCurrency;
import React from 'react' import PropTypes from 'prop-types' import FormGroup from '../forms/FormGroup' import InputColor from '../forms/InputColor' const ColorStackOption = ({ label, name, value, definitions, required, onChange, error }) => { // default value may be null if (value === null) { value = '' } return ( <FormGroup label={label} htmlFor={name} error={error} required={required}> <InputColor name={name} id={name} value={value} defaultValue={definitions.default} onChange={onChange} /> </FormGroup> ) } ColorStackOption.propTypes = { label: PropTypes.string.isRequired, name: PropTypes.string.isRequired, definitions: PropTypes.object.isRequired, required: PropTypes.bool, value: PropTypes.string, onChange: PropTypes.func, error: PropTypes.string } export default ColorStackOption
const td = require('testdouble'); const expect = require('../../../../helpers/expect'); const RSVP = require('rsvp'); const Promise = RSVP.Promise; const adbPath = 'adbPath'; const deviceUUID = 'uuid'; const apkPath = 'apk-path'; const spawnArgs = [adbPath, ['-s', deviceUUID, 'install', '-r', apkPath]]; describe('Android Install App - Device', () => { let installAppDevice; let spawn; beforeEach(() => { let sdkPaths = td.replace('../../../../../lib/targets/android/utils/sdk-paths'); td.when(sdkPaths()).thenReturn({ adb: adbPath }); spawn = td.replace('../../../../../lib/utils/spawn'); td.when(spawn(...spawnArgs)).thenReturn(Promise.resolve({ code: 0 })); installAppDevice = require('../../../../../lib/targets/android/tasks/install-app-device'); }); afterEach(() => { td.reset(); }); it('calls spawn with correct arguments', () => { td.config({ ignoreWarnings: true }); td.when(spawn(), { ignoreExtraArgs: true }) .thenReturn(Promise.resolve({ code: 0 })); return installAppDevice(deviceUUID, apkPath).then(() => { td.verify(spawn(...spawnArgs)); td.config({ ignoreWarnings: false }); }); }); it('resolves with object containing exit code from spawned process', () => { return expect(installAppDevice(deviceUUID, apkPath)) .to.eventually.contain({ code: 0 }); }); it('bubbles up error message when spawn rejects', () => { td.when(spawn(...spawnArgs)).thenReturn(Promise.reject('spawn error')); return expect(installAppDevice(deviceUUID, apkPath)) .to.eventually.be.rejectedWith('spawn error'); }); });
app.config(function ($routeProvider, $locationProvider) { "use strict"; $routeProvider.when('/', { controller: 'HomeController', templateUrl: '/static/apps/main/views/home.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, current: function (SprintService) { var sprints = SprintService.listSprints(); } } }).when('/tasks/', { controller: 'TaskController', templateUrl: '/static/apps/main/views/tasks.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, task: function () { return false; } } }).when('/tasks/:taskid', { controller: 'TaskController', templateUrl: '/static/apps/main/views/task.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, task: function (TaskService, $route) { return TaskService.getTask($route.current.params.taskid); } } }).when('/sprints/', { controller: 'SprintController', templateUrl: '/static/apps/main/views/sprints.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, sprint: function () { return false; } } }).when('/sprints/:sprintid', { controller: 'SprintController', templateUrl: '/static/apps/main/views/sprint.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, sprint: function (SprintService, $route) { return $route.current.params.sprintid; } } }).when('/categories/', { controller: 'CategoryController', templateUrl: '/static/apps/main/views/categories.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); } } }).when('/stats/', { controller: 'StatsController', templateUrl: '/static/apps/main/views/stats.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); } } }).otherwise({redirectTo: '/'}); });
import React from 'react'; import { getCategoryGroups } from '../selectors/categoryGroups'; import { getCategoriesByGroupId } from '../selectors/categories'; import { getSelectedMonthBudgetItemsByCategoryId, getBudgetItemsSumUpToSelectedMonthByCategoryId } from '../selectors/budgetItems'; import { getTransactionsSumUpToSelectedMonthByCategoryId, getSelectedMonthActivityByCategoryId } from '../selectors/transactions'; import {connect} from 'react-redux'; import CategoryRow from './CategoryRow'; import CategoryGroupRow from './CategoryGroupRow'; import ui from 'redux-ui'; @ui({ state: { editingCategoryId: undefined } }) class BudgetTable extends React.Component { static propTypes = { categoryGroups: React.PropTypes.array.isRequired, categoriesByGroupId: React.PropTypes.object.isRequired, getSelectedMonthActivityByCategoryId: React.PropTypes.object.isRequired, getSelectedMonthBudgetItemsByCategoryId: React.PropTypes.object.isRequired, transactionsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired, budgetItemsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired } render() { const rows = []; this.props.categoryGroups.forEach(cg => { rows.push(<CategoryGroupRow key={"cg"+cg.id} name={cg.name} />); if (this.props.categoriesByGroupId[cg.id]) { this.props.categoriesByGroupId[cg.id].forEach(c => { rows.push(<CategoryRow key={"c"+c.id} category={c} budgetItem={this.props.getSelectedMonthBudgetItemsByCategoryId[c.id]} activity={this.props.getSelectedMonthActivityByCategoryId[c.id]} available={(this.props.budgetItemsSumUpToSelectedMonthByCategoryId[c.id] || 0) + (this.props.transactionsSumUpToSelectedMonthByCategoryId[c.id] || 0)} />); }); } }); return ( <table className="table"> <thead> <tr> <th>Category</th> <th>Budgeted</th> <th>Activity</th> <th>Available</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } } const mapStateToProps = (state) => ({ categoryGroups: getCategoryGroups(state), categoriesByGroupId: getCategoriesByGroupId(state), getSelectedMonthActivityByCategoryId: getSelectedMonthActivityByCategoryId(state), getSelectedMonthBudgetItemsByCategoryId: getSelectedMonthBudgetItemsByCategoryId(state), transactionsSumUpToSelectedMonthByCategoryId: getTransactionsSumUpToSelectedMonthByCategoryId(state), budgetItemsSumUpToSelectedMonthByCategoryId: getBudgetItemsSumUpToSelectedMonthByCategoryId(state) }); export default connect(mapStateToProps)(BudgetTable);
'use strict'; module.exports = { db: 'mongodb://localhost/equinix-test', port: 3001, app: { title: 'Equinix - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
import { injectReducer } from '../../../../store/reducers' export default (store) => ({ path: 'admin/positions/add', /* Async getComponent is only invoked when route matches */ getComponent (nextState, cb) { /* Webpack - use 'require.ensure' to create a split point and embed an async module loader (jsonp) when bundling */ require.ensure([], (require) => { /* Webpack - use require callback to define dependencies for bundling */ const AddPosition = require('./AddPosition.component').default // const reducer = null; /* Add the reducer to the store on key 'counter' */ // injectReducer(store, { key: 'addPositions', reducer }) /* Return getComponent */ cb(null, AddPosition) /* Webpack named bundle */ }, 'addPositions') } })
'use strict'; var fetchUrl = require('fetch').fetchUrl; var packageInfo = require('../package.json'); var httpStatusCodes = require('./http.json'); var urllib = require('url'); var mime = require('mime'); // Expose to the world module.exports.resolve = resolve; module.exports.removeParams = removeParams; /** * Resolves an URL by stepping through all redirects * * @param {String} url The URL to be checked * @param {Object} options Optional options object * @param {Function} callback Callback function with error and url */ function resolve(url, options, callback) { var urlOptions = {}; if (typeof options == 'function' && !callback) { callback = options; options = undefined; } options = options || {}; urlOptions.method = options.method ||  'HEAD'; urlOptions.disableGzip = true; // no need for gzipping with HEAD urlOptions.asyncDnsLoookup = true; urlOptions.timeout = options.timeout ||  10000; urlOptions.userAgent = options.userAgent ||  (packageInfo.name + '/' + packageInfo.version + ' (+' + packageInfo.homepage + ')'); urlOptions.removeParams = [].concat(options.removeParams ||  [/^utm_/, 'ref']); urlOptions.agent = options.agent || false; urlOptions.rejectUnauthorized = false; urlOptions.headers = options.headers || {}; urlOptions.maxRedirects = options.maxRedirects || 10; fetchUrl(url, urlOptions, function(error, meta) { var err, url; if (error) { err = new Error(error.message || error); err.statusCode = 0; return callback(err); } if (meta.status != 200) { err = new Error('Server responded with ' + meta.status + ' ' + (httpStatusCodes[meta.status] || 'Invalid request')); err.statusCode = meta.status; return callback(err); } url = meta.finalUrl; if (urlOptions.removeParams && urlOptions.removeParams.length) { url = removeParams(url, urlOptions.removeParams); } var fileParams = detectFileParams(meta); return callback(null, url, fileParams.filename, fileParams.contentType); }); } function detectFileParams(meta) { var urlparts = urllib.parse(meta.finalUrl); var filename = (urlparts.pathname || '').split('/').pop(); var contentType = (meta.responseHeaders['content-type'] || 'application/octet-stream').toLowerCase().split(';').shift().trim(); var fileParts; var extension = ''; var contentExtension; (meta.responseHeaders['content-disposition'] || '').split(';').forEach(function(line) { var parts = line.trim().split('='), key = parts.shift().toLowerCase().trim(); if (key == 'filename') { filename = parts.join('=').trim(); } }); if (contentType == 'application/octet-stream') { contentType = mime.lookup(filename) || 'application/octet-stream'; } else { fileParts = filename.split('.'); if (fileParts.length > 1) { extension = fileParts.pop().toLowerCase(); } contentExtension = mime.extension(contentType); if (contentExtension && extension != contentExtension) { extension = contentExtension; } if (extension) { if (!fileParts.length ||  (fileParts.length == 1 && !fileParts[0])) { fileParts = ['index']; } fileParts.push(extension); } filename = fileParts.join('.'); } return { filename: filename, contentType: contentType }; } /** * Removes matching GET params from an URL * * @param {String} url URL to be checked * @param {Array} params An array of key matches to be removed * @return {String} URL */ function removeParams(url, params) { var parts, query = {}, deleted = false; parts = urllib.parse(url, true, true); delete parts.search; if (parts.query) { Object.keys(parts.query).forEach(function(key) { for (var i = 0, len = params.length; i < len; i++) { if (params[i] instanceof RegExp && key.match(params[i])) { deleted = true; return; } else if (key == params[i]) { deleted = true; return; } } query[key] = parts.query[key]; }); parts.query = query; } return deleted ? urllib.format(parts) : url; }
"use strict" var o = require("ospec") var m = require("../../render/hyperscript") o.spec("hyperscript", function() { o.spec("selector", function() { o("throws on null selector", function(done) { try {m(null)} catch(e) {done()} }) o("throws on non-string selector w/o a view property", function(done) { try {m({})} catch(e) {done()} }) o("handles tag in selector", function() { var vnode = m("a") o(vnode.tag).equals("a") }) o("class and className normalization", function(){ o(m("a", { class: null }).attrs).deepEquals({ class: null }) o(m("a", { class: undefined }).attrs).deepEquals({ class: null }) o(m("a", { class: false }).attrs).deepEquals({ class: null, className: false }) o(m("a", { class: true }).attrs).deepEquals({ class: null, className: true }) o(m("a.x", { class: null }).attrs).deepEquals({ class: null, className: "x" }) o(m("a.x", { class: undefined }).attrs).deepEquals({ class: null, className: "x" }) o(m("a.x", { class: false }).attrs).deepEquals({ class: null, className: "x false" }) o(m("a.x", { class: true }).attrs).deepEquals({ class: null, className: "x true" }) o(m("a", { className: null }).attrs).deepEquals({ className: null }) o(m("a", { className: undefined }).attrs).deepEquals({ className: undefined }) o(m("a", { className: false }).attrs).deepEquals({ className: false }) o(m("a", { className: true }).attrs).deepEquals({ className: true }) o(m("a.x", { className: null }).attrs).deepEquals({ className: "x" }) o(m("a.x", { className: undefined }).attrs).deepEquals({ className: "x" }) o(m("a.x", { className: false }).attrs).deepEquals({ className: "x false" }) o(m("a.x", { className: true }).attrs).deepEquals({ className: "x true" }) }) o("handles class in selector", function() { var vnode = m(".a") o(vnode.tag).equals("div") o(vnode.attrs.className).equals("a") }) o("handles many classes in selector", function() { var vnode = m(".a.b.c") o(vnode.tag).equals("div") o(vnode.attrs.className).equals("a b c") }) o("handles id in selector", function() { var vnode = m("#a") o(vnode.tag).equals("div") o(vnode.attrs.id).equals("a") }) o("handles attr in selector", function() { var vnode = m("[a=b]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles many attrs in selector", function() { var vnode = m("[a=b][c=d]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles attr w/ spaces in selector", function() { var vnode = m("[a = b]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles attr w/ quotes in selector", function() { var vnode = m("[a='b']") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles attr w/ quoted square bracket", function() { var vnode = m("[x][a='[b]'].c") o(vnode.tag).equals("div") o(vnode.attrs.x).equals(true) o(vnode.attrs.a).equals("[b]") o(vnode.attrs.className).equals("c") }) o("handles attr w/ unmatched square bracket", function() { var vnode = m("[a=']'].c") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("]") o(vnode.attrs.className).equals("c") }) o("handles attr w/ quoted square bracket and quote", function() { var vnode = m("[a='[b\"\\']'].c") // `[a='[b"\']']` o(vnode.tag).equals("div") o(vnode.attrs.a).equals("[b\"']") // `[b"']` o(vnode.attrs.className).equals("c") }) o("handles attr w/ quoted square containing escaped square bracket", function() { var vnode = m("[a='[\\]]'].c") // `[a='[\]]']` o(vnode.tag).equals("div") o(vnode.attrs.a).equals("[\\]]") // `[\]]` o(vnode.attrs.className).equals("c") }) o("handles attr w/ backslashes", function() { var vnode = m("[a='\\\\'].c") // `[a='\\']` o(vnode.tag).equals("div") o(vnode.attrs.a).equals("\\") o(vnode.attrs.className).equals("c") }) o("handles attr w/ quotes and spaces in selector", function() { var vnode = m("[a = 'b']") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles many attr w/ quotes and spaces in selector", function() { var vnode = m("[a = 'b'][c = 'd']") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles tag, class, attrs in selector", function() { var vnode = m("a.b[c = 'd']") o(vnode.tag).equals("a") o(vnode.attrs.className).equals("b") o(vnode.attrs.c).equals("d") }) o("handles tag, mixed classes, attrs in selector", function() { var vnode = m("a.b[c = 'd'].e[f = 'g']") o(vnode.tag).equals("a") o(vnode.attrs.className).equals("b e") o(vnode.attrs.c).equals("d") o(vnode.attrs.f).equals("g") }) o("handles attr without value", function() { var vnode = m("[a]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals(true) }) o("handles explicit empty string value for input", function() { var vnode = m('input[value=""]') o(vnode.tag).equals("input") o(vnode.attrs.value).equals("") }) o("handles explicit empty string value for option", function() { var vnode = m('option[value=""]') o(vnode.tag).equals("option") o(vnode.attrs.value).equals("") }) }) o.spec("attrs", function() { o("handles string attr", function() { var vnode = m("div", {a: "b"}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles falsy string attr", function() { var vnode = m("div", {a: ""}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals("") }) o("handles number attr", function() { var vnode = m("div", {a: 1}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(1) }) o("handles falsy number attr", function() { var vnode = m("div", {a: 0}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(0) }) o("handles boolean attr", function() { var vnode = m("div", {a: true}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(true) }) o("handles falsy boolean attr", function() { var vnode = m("div", {a: false}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(false) }) o("handles only key in attrs", function() { var vnode = m("div", {key:"a"}) o(vnode.tag).equals("div") o(vnode.attrs).deepEquals({}) o(vnode.key).equals("a") }) o("handles many attrs", function() { var vnode = m("div", {a: "b", c: "d"}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles className attrs property", function() { var vnode = m("div", {className: "a"}) o(vnode.attrs.className).equals("a") }) o("handles 'class' as a verbose attribute declaration", function() { var vnode = m("[class=a]") o(vnode.attrs.className).equals("a") }) o("handles merging classes w/ class property", function() { var vnode = m(".a", {class: "b"}) o(vnode.attrs.className).equals("a b") }) o("handles merging classes w/ className property", function() { var vnode = m(".a", {className: "b"}) o(vnode.attrs.className).equals("a b") }) }) o.spec("custom element attrs", function() { o("handles string attr", function() { var vnode = m("custom-element", {a: "b"}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals("b") }) o("handles falsy string attr", function() { var vnode = m("custom-element", {a: ""}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals("") }) o("handles number attr", function() { var vnode = m("custom-element", {a: 1}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(1) }) o("handles falsy number attr", function() { var vnode = m("custom-element", {a: 0}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(0) }) o("handles boolean attr", function() { var vnode = m("custom-element", {a: true}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(true) }) o("handles falsy boolean attr", function() { var vnode = m("custom-element", {a: false}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(false) }) o("handles only key in attrs", function() { var vnode = m("custom-element", {key:"a"}) o(vnode.tag).equals("custom-element") o(vnode.attrs).deepEquals({}) o(vnode.key).equals("a") }) o("handles many attrs", function() { var vnode = m("custom-element", {a: "b", c: "d"}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles className attrs property", function() { var vnode = m("custom-element", {className: "a"}) o(vnode.attrs.className).equals("a") }) o("casts className using toString like browsers", function() { const className = { valueOf: () => ".valueOf", toString: () => "toString" } var vnode = m("custom-element" + className, {className: className}) o(vnode.attrs.className).equals("valueOf toString") }) }) o.spec("children", function() { o("handles string single child", function() { var vnode = m("div", {}, ["a"]) o(vnode.children[0].children).equals("a") }) o("handles falsy string single child", function() { var vnode = m("div", {}, [""]) o(vnode.children[0].children).equals("") }) o("handles number single child", function() { var vnode = m("div", {}, [1]) o(vnode.children[0].children).equals("1") }) o("handles falsy number single child", function() { var vnode = m("div", {}, [0]) o(vnode.children[0].children).equals("0") }) o("handles boolean single child", function() { var vnode = m("div", {}, [true]) o(vnode.children).deepEquals([null]) }) o("handles falsy boolean single child", function() { var vnode = m("div", {}, [false]) o(vnode.children).deepEquals([null]) }) o("handles null single child", function() { var vnode = m("div", {}, [null]) o(vnode.children).deepEquals([null]) }) o("handles undefined single child", function() { var vnode = m("div", {}, [undefined]) o(vnode.children).deepEquals([null]) }) o("handles multiple string children", function() { var vnode = m("div", {}, ["", "a"]) o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("a") }) o("handles multiple number children", function() { var vnode = m("div", {}, [0, 1]) o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("0") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("1") }) o("handles multiple boolean children", function() { var vnode = m("div", {}, [false, true]) o(vnode.children).deepEquals([null, null]) }) o("handles multiple null/undefined child", function() { var vnode = m("div", {}, [null, undefined]) o(vnode.children).deepEquals([null, null]) }) o("handles falsy number single child without attrs", function() { var vnode = m("div", 0) o(vnode.children[0].children).equals("0") }) }) o.spec("permutations", function() { o("handles null attr and children", function() { var vnode = m("div", null, [m("a"), m("b")]) o(vnode.children.length).equals(2) o(vnode.children[0].tag).equals("a") o(vnode.children[1].tag).equals("b") }) o("handles null attr and child unwrapped", function() { var vnode = m("div", null, m("a")) o(vnode.children.length).equals(1) o(vnode.children[0].tag).equals("a") }) o("handles null attr and children unwrapped", function() { var vnode = m("div", null, m("a"), m("b")) o(vnode.children.length).equals(2) o(vnode.children[0].tag).equals("a") o(vnode.children[1].tag).equals("b") }) o("handles attr and children", function() { var vnode = m("div", {a: "b"}, [m("i"), m("s")]) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles attr and child unwrapped", function() { var vnode = m("div", {a: "b"}, m("i")) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("i") }) o("handles attr and children unwrapped", function() { var vnode = m("div", {a: "b"}, m("i"), m("s")) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles attr and text children", function() { var vnode = m("div", {a: "b"}, ["c", "d"]) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("c") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("d") }) o("handles attr and single string text child", function() { var vnode = m("div", {a: "b"}, ["c"]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("c") }) o("handles attr and single falsy string text child", function() { var vnode = m("div", {a: "b"}, [""]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("") }) o("handles attr and single number text child", function() { var vnode = m("div", {a: "b"}, [1]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("1") }) o("handles attr and single falsy number text child", function() { var vnode = m("div", {a: "b"}, [0]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("0") }) o("handles attr and single boolean text child", function() { var vnode = m("div", {a: "b"}, [true]) o(vnode.attrs.a).equals("b") o(vnode.children).deepEquals([null]) }) o("handles attr and single falsy boolean text child", function() { var vnode = m("div", {a: "b"}, [0]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("0") }) o("handles attr and single false boolean text child", function() { var vnode = m("div", {a: "b"}, [false]) o(vnode.attrs.a).equals("b") o(vnode.children).deepEquals([null]) }) o("handles attr and single text child unwrapped", function() { var vnode = m("div", {a: "b"}, "c") o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("c") }) o("handles attr and text children unwrapped", function() { var vnode = m("div", {a: "b"}, "c", "d") o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("c") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("d") }) o("handles children without attr", function() { var vnode = m("div", [m("i"), m("s")]) o(vnode.attrs).deepEquals({}) o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles child without attr unwrapped", function() { var vnode = m("div", m("i")) o(vnode.attrs).deepEquals({}) o(vnode.children[0].tag).equals("i") }) o("handles children without attr unwrapped", function() { var vnode = m("div", m("i"), m("s")) o(vnode.attrs).deepEquals({}) o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles shared attrs", function() { var attrs = {a: "b"} var nodeA = m(".a", attrs) var nodeB = m(".b", attrs) o(nodeA.attrs.className).equals("a") o(nodeA.attrs.a).equals("b") o(nodeB.attrs.className).equals("b") o(nodeB.attrs.a).equals("b") }) o("doesnt modify passed attributes object", function() { var attrs = {a: "b"} m(".a", attrs) o(attrs).deepEquals({a: "b"}) }) o("non-nullish attr takes precedence over selector", function() { o(m("[a=b]", {a: "c"}).attrs).deepEquals({a: "c"}) }) o("null attr takes precedence over selector", function() { o(m("[a=b]", {a: null}).attrs).deepEquals({a: null}) }) o("undefined attr takes precedence over selector", function() { o(m("[a=b]", {a: undefined}).attrs).deepEquals({a: undefined}) }) o("handles fragment children without attr unwrapped", function() { var vnode = m("div", [m("i")], [m("s")]) o(vnode.children[0].tag).equals("[") o(vnode.children[0].children[0].tag).equals("i") o(vnode.children[1].tag).equals("[") o(vnode.children[1].children[0].tag).equals("s") }) o("handles children with nested array", function() { var vnode = m("div", [[m("i"), m("s")]]) o(vnode.children[0].tag).equals("[") o(vnode.children[0].children[0].tag).equals("i") o(vnode.children[0].children[1].tag).equals("s") }) o("handles children with deeply nested array", function() { var vnode = m("div", [[[m("i"), m("s")]]]) o(vnode.children[0].tag).equals("[") o(vnode.children[0].children[0].tag).equals("[") o(vnode.children[0].children[0].children[0].tag).equals("i") o(vnode.children[0].children[0].children[1].tag).equals("s") }) }) o.spec("components", function() { o("works with POJOs", function() { var component = { view: function() {} } var vnode = m(component, {id: "a"}, "b") o(vnode.tag).equals(component) o(vnode.attrs.id).equals("a") o(vnode.children.length).equals(1) o(vnode.children[0]).equals("b") }) o("works with constructibles", function() { var component = o.spy() component.prototype.view = function() {} var vnode = m(component, {id: "a"}, "b") o(component.callCount).equals(0) o(vnode.tag).equals(component) o(vnode.attrs.id).equals("a") o(vnode.children.length).equals(1) o(vnode.children[0]).equals("b") }) o("works with closures", function () { var component = o.spy() var vnode = m(component, {id: "a"}, "b") o(component.callCount).equals(0) o(vnode.tag).equals(component) o(vnode.attrs.id).equals("a") o(vnode.children.length).equals(1) o(vnode.children[0]).equals("b") }) }) })
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["choose_file"] = factory(); else root["choose_file"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // __webpack_hash__ /******/ __webpack_require__.h = "05ce0eff1b9563477190"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var assign = __webpack_require__(4); var is_function = __webpack_require__(2); var is_presto = !!window.opera; var is_trident = document.all && !is_presto; var defaults = { multiple: false, accept: '*/*', success: function (input) {} }; var on = function (event, element, callback) { if (element.addEventListener) { element.addEventListener(event, callback, false); } else if (element.attachEvent) { element.attachEvent('on' + event, callback); } }; var input_remove = function (input) { is_trident || input.parentNode && input.parentNode.removeChild(input); // input.removeAttribute('accept'); // input.removeAttribute('style'); }; module.exports = function (params) { var input; var options; options = assign({}, defaults, is_function(params) ? { success: params } : params || {}); options.success = is_function(options.success) ? options.success : defaults.success; input = document.createElement('input'); input.setAttribute('style', 'position: absolute; clip: rect(0, 0, 0, 0);'); input.setAttribute('accept', options.accept); input.setAttribute('type', 'file'); input.multiple = !!options.multiple; on(is_trident ? 'input' : 'change', input, function (e) { if (is_presto) { input_remove(input); } if (input.value) { options.success(input); } }); (document.body || document.documentElement).appendChild(input); if (is_presto) { setTimeout(function () { input.click(); }, 0); } else { input.click(); input_remove(input); } }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var isObject = __webpack_require__(3); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = global.Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array constructors, and // PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 3 */ /***/ function(module, exports) { /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 4 */ /***/ function(module, exports) { /* eslint-disable no-unused-vars */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ } /******/ ]) }); ;
function move(Restangular, $uibModal, $q, notification, $state,$http) { 'use strict'; return { restrict: 'E', scope: { selection: '=', type: '@', ngConfirmMessage: '@', ngConfirm: '&' }, link: function(scope, element, attrs) { scope.myFunction = function(){ var spanDropdown = document.querySelectorAll('span.btn-group')[0]; spanDropdown.classList.add("open"); }; scope.icon = 'glyphicon-list'; if (attrs.type == 'move_to_package') scope.button = 'Move to Package'; var vods_array = []; $http.get('../api/vodpackages?package_type_id=3&package_type_id=4').then(function(response) { var data = response.data; for(var i=0;i<data.length;i++){ vods_array.push({name:data[i].package_name,id:data[i].id}) } }); scope.list_of_vods = vods_array; var newarray = []; scope.moveto = function () { var spanDropdown = document.querySelectorAll('span.btn-group')[0]; spanDropdown.classList.remove("open"); var array_of_selection_vod = scope.selection; scope.change = function(name,id){ scope.button = name; var id_of_selected_package = id; for(var j=0;j<array_of_selection_vod.length;j++){ newarray.push({package_id:id_of_selected_package,vod_id:array_of_selection_vod[j].values.id}) } if(newarray.length === 0) { notification.log('Sorry, you have not selected any Vod item.', { addnCls: 'humane-flatty-error' }); } else { $http.post("../api/package_vod", newarray).then(function (response,data, status, headers, config,file) { notification.log('Vod successfully added', { addnCls: 'humane-flatty-success' }); window.location.replace("#/vodPackages/edit/"+id_of_selected_package); },function (data, status, headers, config) { notification.log('Something Wrong', { addnCls: 'humane-flatty-error' }); }).on(error, function(error){ winston.error("The error during post request is ") }); } }; } }, template: '<div class="btn-group" uib-dropdown is-open="status.isopen"> ' + '<button ng-click="myFunction()" id="single-button" type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disabled">' + '<span class="glyphicon {{icon}}"></span> {{button}} <span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu" uib-dropdown-menu role="menu" aria-labelledby="single-button">' + '<li role="menuitem" ng-click="change(choice.name,choice.id)" ng-repeat="choice in list_of_vods">' + '<p id="paragraph_vod" ng-click="moveto()">{{choice.name}}</p>' + '</li>' + '</ul>' + '</div>' }; } move.$inject = ['Restangular', '$uibModal', '$q', 'notification', '$state','$http']; export default move;
let mongoose = require('mongoose'); let URL = process.env.MONGO_URL || 'localhost'; let USER = process.env.MONGO_USR || ''; let PASSWORD = process.env.MONGO_PWD || ''; mongoose.connect(`mongodb://${USER}:${PASSWORD}@${URL}`); //TODO doens't work for localhost console.log(`Connecting to ${URL}...`); let db = mongoose.connection; db.on('error', (err) => console.error(err)); db.once('open', () => console.log('Connected!')); module.exports = db;
define([], function() { return Backbone.View.extend({ tagName: "a", className: "projectlink", attributes: { href: "#" }, template: _.template("<%- name %>"), events: { "click": "toggleSelection" }, initialize: function() { this.listenTo(this.model, "change:selected", function(m, selected) { this.$el.toggleClass("selected", selected); }); this.listenTo(this.model, "change:color", function(m, color) { this.$el.css("color", color); }); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; }, toggleSelection: function() { this.model.set("selected", !this.model.get("selected")); return false; } }); });
'use strict'; (function() { describe('HomeController', function() { //Initialize global variables var scope, HomeController, myFactory; // Load the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(inject(function($controller, $rootScope) { scope = $rootScope.$new(); HomeController = $controller('HomeController', { $scope: scope }); })); it('should expose the authentication service', function() { expect(scope.authentication).toBeTruthy(); }); it('should see the result', function(){ scope.feedSrc = 'http://rss.cnn.com/rss/cnn_topstories.rss'; }); }); })();
/** @file This file contains the functions to adjust an existing polygon. */ /** * Creates the adjusting event * @constructor * @param {string} dom_attach - The html element where the polygon lives * @param {array} x - The x coordinates for the polygon points * @param {array} y - The y coordinates for the polygon points * @param {string} obj_name - The name of the adjusted_polygon * @param {function} ExitFunction - the_function to execute once adjusting is done * @param {float} scale - Scaling factor for polygon points */ function AdjustEvent(dom_attach,x,y,obj_name,ExitFunction,scale, bounding_box_annot) { /****************** Private variables ************************/ // ID of DOM element to attach to: this.bounding_box = bounding_box_annot; this.dom_attach = dom_attach; this.scale_button_pressed = false; // Polygon: this.x = x; this.y = y; // Object name: this.obj_name = obj_name; // Function to call when event is finished: this.ExitFunction = ExitFunction; // Scaling factor for polygon points: this.scale = scale; // Boolean indicating whether a control point has been edited: this.editedControlPoints = false; // Boolean indicating whether a control point is being edited: this.isEditingControlPoint = false; // Boolean indicating whether a scaling point is being edited: this.isEditingScalingPoint = false; // Boolean indicating whether the center of mass of the polygon is being // adjusted: this.isMovingCenterOfMass = false; // Index into which control point has been selected: this.selectedControlPoint; // Index into which scaling point has been selected: this.selectedScalingPoint; // Location of center of mass: this.center_x; this.center_y; // Element ids of drawn control points: this.control_ids = null; this.scalepoints_ids = null; // Element id of drawn center point: this.center_id = null; // ID of drawn polygon: this.polygon_id; /****************** Public functions ************************/ /** This function starts the adjusting event: */ this.StartEvent = function() { console.log('LabelMe: Starting adjust event...'); // Draw polygon: this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; FillPolygon(this.polygon_id); oVP.ShowTemporalBar(); // Set mousedown action to stop adjust event when user clicks on canvas: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); // Show control points: if (this.bounding_box){ this.ShowScalingPoints(); this.ShowCenterOfMass(); return; } this.ShowControlPoints(); // Show center of mass: this.ShowCenterOfMass(); $(window).keydown({obj: this}, function (e){ if (!e.data.obj.scale_button_pressed && e.keyCode == 17 && !e.data.obj.isEditingControlPoint){ e.data.obj.RemoveScalingPoints(); e.data.obj.RemoveControlPoints(); e.data.obj.RemoveCenterOfMass(); e.data.obj.ShowScalingPoints(); e.data.obj.scale_button_pressed = true; } }); $(window).keyup({obj: this}, function (e){ if (e.keyCode == 17 && !e.data.obj.isEditingControlPoint){ e.data.obj.scale_button_pressed = false; e.data.obj.RemoveScalingPoints(); e.data.obj.RemoveControlPoints(); e.data.obj.RemoveCenterOfMass(); e.data.obj.ShowControlPoints(); e.data.obj.ShowCenterOfMass(); } }); }; /** This function stops the adjusting event and calls the ExitFunction: */ this.StopAdjustEvent = function() { // Remove polygon: $('#'+this.polygon_id).remove(); // Remove key press action $(window).unbind("keydown"); $(window).unbind("keyup"); // Remove control points and center of mass point: this.RemoveControlPoints(); this.RemoveCenterOfMass(); this.RemoveScalingPoints(); console.log('LabelMe: Stopped adjust event.'); oVP.HideTemporalBar(); // Call exit function: this.ExitFunction(this.x,this.y,this.editedControlPoints); }; /** This function shows the scaling points for a polygon */ this.ShowScalingPoints = function (){ if(!this.scalepoints_ids) this.scalepoints_ids = new Array(); for (var i = 0; i < this.x.length; i++){ this.scalepoints_ids.push(DrawPoint(this.dom_attach,this.x[i],this.y[i],'r="5" fill="#0000ff" stroke="#ffffff" stroke-width="2.5"',this.scale)); } for (var i = 0; i < this.scalepoints_ids.length; i++) $('#'+this.scalepoints_ids[i]).mousedown({obj: this,point: i},function(e) { return e.data.obj.StartMoveScalingPoint(e.data.point); }); } /** This function removes the displayed scaling points for a polygon */ this.RemoveScalingPoints = function (){ if(this.scalepoints_ids) { for(var i = 0; i < this.scalepoints_ids.length; i++) $('#'+this.scalepoints_ids[i]).remove(); this.scalepoints_ids = null; } } /** This function shows the control points for a polygon */ this.ShowControlPoints = function() { if(!this.control_ids) this.control_ids = new Array(); for(var i = 0; i < this.x.length; i++) { // Draw control point: this.control_ids.push(DrawPoint(this.dom_attach,this.x[i],this.y[i],'r="5" fill="#00ff00" stroke="#ffffff" stroke-width="2.5"',this.scale)); // Set action: $('#'+this.control_ids[i]).mousedown({obj: this,point: i},function(e) { return e.data.obj.StartMoveControlPoint(e.data.point); }); } }; /** This function removes the displayed control points for a polygon */ this.RemoveControlPoints = function() { if(this.control_ids) { for(var i = 0; i < this.control_ids.length; i++) $('#'+this.control_ids[i]).remove(); this.control_ids = null; } }; /** This function shows the middle grab point for a polygon. */ this.ShowCenterOfMass = function() { var MarkerSize = 8; if(this.x.length==1) MarkerSize = 6; // Get center point for polygon: this.CenterOfMass(this.x,this.y); // Draw center point: this.center_id = DrawPoint(this.dom_attach,this.center_x,this.center_y,'r="' + MarkerSize + '" fill="red" stroke="#ffffff" stroke-width="' + MarkerSize/2 + '"',this.scale); // Set action: $('#'+this.center_id).mousedown({obj: this},function(e) { return e.data.obj.StartMoveCenterOfMass(); }); }; /** This function removes the middle grab point for a polygon */ this.RemoveCenterOfMass = function() { if(this.center_id) { $('#'+this.center_id).remove(); this.center_id = null; } }; /** This function is called when one scaling point is clicked * It prepares the polygon for scaling. * @param {int} i - the index of the scaling point being modified */ this.StartMoveScalingPoint = function(i) { if(!this.isEditingScalingPoint) { $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousemove({obj: this},function(e) { return e.data.obj.MoveScalingPoint(e.originalEvent, !e.data.obj.bounding_box); }); $('#body').mouseup({obj: this},function(e) { return e.data.obj.StopMoveScalingPoint(e.originalEvent); }); this.RemoveCenterOfMass(); this.selectedScalingPoint = i; this.isEditingScalingPoint = true; this.editedControlPoints = true; } }; /** This function is called when one scaling point is being moved * It computes the position of the scaling point in relation to the polygon's center of mass * and resizes the polygon accordingly * @param {event} event - Indicates a point is being moved and the index of such point */ this.MoveScalingPoint = function(event, proportion) { var x = GetEventPosX(event); var y = GetEventPosY(event); if(this.isEditingScalingPoint && (this.scale_button_pressed || this.bounding_box)) { var origx, origy, pointx, pointy, prx, pry; pointx = this.x[this.selectedScalingPoint]; pointy = this.y[this.selectedScalingPoint]; this.CenterOfMass(this.x,this.y); var sx = pointx - this.center_x; var sy = pointy - this.center_y; if (sx < 0) origx = Math.max.apply(Math, this.x); else origx = Math.min.apply(Math, this.x); if (sy < 0) origy = Math.max.apply(Math, this.y); else origy = Math.min.apply(Math, this.y); prx = (Math.round(x/this.scale)-origx)/(pointx-origx); pry = (Math.round(y/this.scale)-origy)/(pointy-origy); if (proportion) pry = prx; if (prx <= 0 || pry <= 0 ) return; for (var i = 0; i < this.x.length; i++){ // Set point: var dx = (this.x[i] - origx)*prx; var dy = (this.y[i] - origy)*pry; x = origx + dx; y = origy + dy; this.x[i] = Math.max(Math.min(x,main_media.width_orig),1); this.y[i] = Math.max(Math.min(y,main_media.height_orig),1); } // Remove polygon and redraw: console.log(this.polygon_id); $('#'+this.polygon_id).parent().remove(); $('#'+this.polygon_id).remove(); this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; // Adjust control points: this.RemoveScalingPoints(); this.ShowScalingPoints(); } }; /** This function is called when one scaling point stops being moved * It updates the xml with the new coordinates of the polygon. * @param {event} event - Indicates a point is being moved and the index of such point */ this.StopMoveScalingPoint = function(event) { console.log('Moving scaling point'); if(this.isEditingScalingPoint) { this.MoveScalingPoint(event, !this.bounding_box); FillPolygon(this.polygon_id); this.isEditingScalingPoint = false; if (video_mode) main_media.UpdateObjectPosition(select_anno, this.x, this.y); this.ShowCenterOfMass(); // Set action: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); } }; /** This function is called when one control point is clicked * @param {int} i - the index of the control point being modified */ this.StartMoveControlPoint = function(i) { if(!this.isEditingControlPoint) { $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousemove({obj: this},function(e) { return e.data.obj.MoveControlPoint(e.originalEvent); }); $('#body').mouseup({obj: this},function(e) { return e.data.obj.StopMoveControlPoint(e.originalEvent); }); this.RemoveCenterOfMass(); this.selectedControlPoint = i; this.isEditingControlPoint = true; this.editedControlPoints = true; } }; /** This function is called when one control point is being moved * @param {event} event - Indicates a point is being moved and the index of such point */ this.MoveControlPoint = function(event) { if(this.isEditingControlPoint) { var x = GetEventPosX(event); var y = GetEventPosY(event); // Set point: this.x[this.selectedControlPoint] = Math.max(Math.min(Math.round(x/this.scale),main_media.width_orig),1); this.y[this.selectedControlPoint] = Math.max(Math.min(Math.round(y/this.scale),main_media.height_orig),1); this.originalx = this.x; this.originaly = this.y; // Remove polygon and redraw: $('#'+this.polygon_id).parent().remove(); $('#'+this.polygon_id).remove(); this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; // Adjust control points: this.RemoveControlPoints(); this.ShowControlPoints(); } }; /** This function is called when one control point stops being moved * It updates the xml with the new coordinates of the polygon. * @param {event} event - Indicates a point is being moved and the index of such point */ this.StopMoveControlPoint = function(event) { console.log('Moving control point'); if(this.isEditingControlPoint) { this.MoveControlPoint(event); FillPolygon(this.polygon_id); this.ShowCenterOfMass(); this.isEditingControlPoint = false; if (video_mode) main_media.UpdateObjectPosition(select_anno, this.x, this.y); // Set action: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); } }; /** This function is called when the middle grab point is clicked * It prepares the polygon for moving. */ this.StartMoveCenterOfMass = function() { if(!this.isMovingCenterOfMass) { $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousemove({obj: this},function(e) { return e.data.obj.MoveCenterOfMass(e.originalEvent); }); $('#body').mouseup({obj: this},function(e) { return e.data.obj.StopMoveCenterOfMass(e.originalEvent); }); this.RemoveScalingPoints(); this.RemoveControlPoints(); this.isMovingCenterOfMass = true; this.editedControlPoints = true; } }; /** This function is called when the middle grab point is being moved * @param {event} event - Indicates the middle grab point is moving * It modifies the control points to be consistent with the polygon shift */ this.MoveCenterOfMass = function(event) { if(this.isMovingCenterOfMass) { var x = GetEventPosX(event); var y = GetEventPosY(event); // Get displacement: var dx = Math.round(x/this.scale)-this.center_x; var dy = Math.round(y/this.scale)-this.center_y; // Adjust dx,dy to make sure we don't go outside of the image: for(var i = 0; i < this.x.length; i++) { dx = Math.max(this.x[i]+dx,1)-this.x[i]; dy = Math.max(this.y[i]+dy,1)-this.y[i]; dx = Math.min(this.x[i]+dx,main_media.width_orig)-this.x[i]; dy = Math.min(this.y[i]+dy,main_media.height_orig)-this.y[i]; } // Adjust polygon and center point: for(var i = 0; i < this.x.length; i++) { this.x[i] = Math.round(this.x[i]+dx); this.y[i] = Math.round(this.y[i]+dy); } this.center_x = Math.round(this.scale*(dx+this.center_x)); this.center_y = Math.round(this.scale*(dy+this.center_y)); // Remove polygon and redraw: $('#'+this.polygon_id).parent().remove(); $('#'+this.polygon_id).remove(); this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; // Redraw center of mass: this.RemoveCenterOfMass(); this.ShowCenterOfMass(); } }; /** This function is called when the middle grab point stops being moved * It updates the xml with the new coordinates of the polygon. * @param {event} event - Indicates the middle grab point is being moved and the index of such point */ this.StopMoveCenterOfMass = function(event) { if(this.isMovingCenterOfMass) { // Move to final position: this.MoveCenterOfMass(event); // Refresh control points: if (this.bounding_box){ this.RemoveScalingPoints(); this.RemoveCenterOfMass(); this.ShowScalingPoints(); this.ShowCenterOfMass(); } else { this.RemoveControlPoints(); this.RemoveCenterOfMass(); this.ShowControlPoints(); this.ShowCenterOfMass(); } FillPolygon(this.polygon_id); this.isMovingCenterOfMass = false; if (video_mode) main_media.UpdateObjectPosition(select_anno, this.x, this.y); // Set action: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); } }; /*************** Helper functions ****************/ /** Compute center of mass for a polygon given array of points (x,y): */ this.CenterOfMass = function(x,y) { var N = x.length; // Center of mass for a single point: if(N==1) { this.center_x = x[0]; this.center_y = y[0]; return; } // The center of mass is the average polygon edge midpoint weighted by // edge length: this.center_x = 0; this.center_y = 0; var perimeter = 0; for(var i = 1; i <= N; i++) { var length = Math.round(Math.sqrt(Math.pow(x[i-1]-x[i%N], 2) + Math.pow(y[i-1]-y[i%N], 2))); this.center_x += length*Math.round((x[i-1] + x[i%N])/2); this.center_y += length*Math.round((y[i-1] + y[i%N])/2); perimeter += length; } this.center_x /= perimeter; this.center_y /= perimeter; }; this.DrawPolygon = function(dom_id,x,y,obj_name,scale) { if(x.length==1) return DrawFlag(dom_id,x[0],y[0],obj_name,scale); var attr = 'fill="none" stroke="' + HashObjectColor(obj_name) + '" stroke-width="4"'; return DrawPolygon(dom_id,x,y,obj_name,attr,scale); }; }
'use strict'; module.exports = { images: { files: [ { cwd : 'src/assets/img/', src : '**/*', dest : '.build/img/', flatten : false, expand : true } ] }, config: { files: [ { cwd : 'src/config/', src : '**/*', dest : '.build/', flatten : false, expand : true } ] } };
// Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe". function findPalindromes(input) { var words = input.replace(/\W+/g, ' ').replace(/\s+/, ' ').trim().split(' '), palindromes = [], length = words.length, currentWord, i; for (i = 0; i < length; i += 1) { currentWord = words[i]; if (isPalindrome(currentWord) && currentWord.length != 1) { palindromes.push(currentWord); } } return palindromes.join(); } function isPalindrome(currentWord) { var length = currentWord.length, i; for (i = 0; i < length / 2; i += 1) { if (currentWord[i] != currentWord[currentWord.length - 1 - i]) { return false; } } return true; } var textSample = 'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".'; console.log(findPalindromes(textSample));
// 19. Write a JavaScript function that returns array elements larger than a number. //two agrs - an array and a number to be larger than function isGreater(arr, num) { //set up an array to contain the results var resultArray = []; //iterate through based on length of the arr for(var i = 0; i < arr.length; i++) { //if current arr value is greater than num if(arr[i] > num) { //push result to resultArray resultArray.push(arr[i]); } } //log results console.log(resultArray); }
'use strict'; const signup = require('./signup'); const handler = require('feathers-errors/handler'); const notFound = require('./not-found-handler'); const logger = require('./logger'); module.exports = function() { // Add your custom middleware here. Remember, that // just like Express the order matters, so error // handling middleware should go last. const app = this; app.post('/signup', signup(app)); app.use(notFound()); app.use(logger(app)); app.use(handler()); };
'use strict'; var form = $('[name="uploadForm"]'); exports.getForm = function() { return form; }; exports.setDetails = function(url, id) { form.element(by.model('inputText')).sendKeys(url); form.element(by.model('snapshotId')).sendKeys(id); }; exports.submit = function() { form.element(by.css('[ng-click="upload()"]')).click(); };
module.exports = { 'resulting promise should be immediately rejected' : function(test) { var promise = promiseModule.reject('error'); test.ok(promise._status === -1); test.done(); }, 'resulting promise should be rejected with argument if argument is not a promise' : function(test) { promiseModule.reject('error').fail(function(error) { test.strictEqual(error, 'error'); test.done(); }); }, 'resulting promise should be rejected if argument is rejected' : function(test) { var defer = promiseModule.defer(); promiseModule.reject(defer.promise).fail(function(error) { test.strictEqual(error, 'error'); test.done(); }); defer.reject('error'); }, 'resulting promise should be rejected if argument is fulfilled' : function(test) { var defer = promiseModule.defer(); promiseModule.reject(defer.promise).fail(function(error) { test.strictEqual(error, 'val'); test.done(); }); defer.resolve('val'); } };
'use strict'; require('mocha'); const assert = require('assert'); const Generator = require('..'); let base; describe('.task', () => { beforeEach(() => { base = new Generator(); }); it('should register a task', () => { const fn = cb => cb(); base.task('default', fn); assert.equal(typeof base.tasks.get('default'), 'object'); assert.equal(base.tasks.get('default').callback, fn); }); it('should register a task with an array of dependencies', cb => { let count = 0; base.task('foo', next => { count++; next(); }); base.task('bar', next => { count++; next(); }); base.task('default', ['foo', 'bar'], next => { count++; next(); }); assert.equal(typeof base.tasks.get('default'), 'object'); assert.deepEqual(base.tasks.get('default').deps, ['foo', 'bar']); base.build('default', err => { if (err) return cb(err); assert.equal(count, 3); cb(); }); }); it('should run a glob of tasks', cb => { let count = 0; base.task('foo', next => { count++; next(); }); base.task('bar', next => { count++; next(); }); base.task('baz', next => { count++; next(); }); base.task('qux', next => { count++; next(); }); base.task('default', ['b*']); assert.equal(typeof base.tasks.get('default'), 'object'); base.build('default', err => { if (err) return cb(err); assert.equal(count, 2); cb(); }); }); it('should register a task with a list of strings as dependencies', () => { base.task('default', 'foo', 'bar', cb => { cb(); }); assert.equal(typeof base.tasks.get('default'), 'object'); assert.deepEqual(base.tasks.get('default').deps, ['foo', 'bar']); }); it('should run a task', cb => { let count = 0; base.task('default', cb => { count++; cb(); }); base.build('default', err => { if (err) return cb(err); assert.equal(count, 1); cb(); }); }); it('should throw an error when a task with unregistered dependencies is run', cb => { base.task('default', ['foo', 'bar']); base.build('default', err => { assert(err); cb(); }); }); it('should throw an error when a task does not exist', () => { return base.build('default') .then(() => { throw new Error('expected an error'); }) .catch(err => { assert(/registered/.test(err.message)); }); }); it('should emit task events', () => { const expected = []; base.on('task-registered', function(task) { expected.push(task.status + '.' + task.name); }); base.on('task-preparing', function(task) { expected.push(task.status + '.' + task.name); }); base.on('task', function(task) { expected.push(task.status + '.' + task.name); }); base.task('foo', cb => cb()); base.task('bar', ['foo'], cb => cb()); base.task('default', ['bar']); return base.build('default') .then(() => { assert.deepEqual(expected, [ 'registered.foo', 'registered.bar', 'registered.default', 'preparing.default', 'starting.default', 'preparing.bar', 'starting.bar', 'preparing.foo', 'starting.foo', 'finished.foo', 'finished.bar', 'finished.default' ]); }); }); it('should emit an error event when an error is returned in a task callback', cb => { base.on('error', err => { assert(err); assert.equal(err.message, 'This is an error'); }); base.task('default', cb => { return cb(new Error('This is an error')); }); base.build('default', err => { if (err) return cb(); cb(new Error('Expected an error')); }); }); it('should emit an error event when an error is thrown in a task', cb => { base.on('error', err => { assert(err); assert.equal(err.message, 'This is an error'); }); base.task('default', cb => { cb(new Error('This is an error')); }); base.build('default', err => { assert(err); cb(); }); }); it('should run dependencies before running the dependent task', cb => { const expected = []; base.task('foo', cb => { expected.push('foo'); cb(); }); base.task('bar', cb => { expected.push('bar'); cb(); }); base.task('default', ['foo', 'bar'], cb => { expected.push('default'); cb(); }); base.build('default', err => { if (err) return cb(err); assert.deepEqual(expected, ['foo', 'bar', 'default']); cb(); }); }); });
import containers from './containers' import ui from './ui' import App from './App' module.exports = {...containers, ...ui, App}
'use strict'; // Production specific configuration // ================================= module.exports = { // Server IP ip: process.env.OPENSHIFT_NODEJS_IP || process.env.IP || undefined, // Server port port: process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8080, // MongoDB connection options mongo: { uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/spicyparty' } };
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const repl = require('repl'); const program = require('commander'); const esper = require('..'); const Engine = esper.Engine; function enterRepl() { function replEval(cmd, context, fn, cb) { engine.evalDetatched(cmd).then(function(result) { cb(null, result); }, function(err) { console.log(err.stack); cb(null); }); } return repl.start({ prompt: 'js> ', eval: replEval }); } program .version(esper.version) .usage('[options] [script...]') .option('-v, --version', 'print esper version') .option('-i, --interactive', 'enter REPL') .option('-s, --strict', 'force strict mode') .option('-d, --debug', 'turn on performance debugging') .option('-c, --compile <mode>', 'set compileing mode') .option('-e, --eval <script>', 'evaluate script') .option('-p, --print <script>', 'evaluate script and print result') .option('-l, --language <language>', `set langauge (${Object.keys(esper.languages).join(', ')})`) .parse(process.argv); if ( program.language ) esper.plugin('lang-' + program.language); if ( program.v ) { console.log("v" + esper.version); process.exit(); } let engine = new Engine({ strict: !!program.strict, debug: !!program.debug, runtime: true, addInternalStack: !!program.debug, compile: program.compile || 'pre', language: program.language || 'javascript', esposeESHostGlobal: true, esRealms: true, }); let toEval = program.args.slice(0).map((f) => ({type: 'file', value: f})); if ( program.eval ) toEval.push({type: 'str', value: program.eval + '\n'}); if ( program.print ) toEval.push({type: 'str', value: program.print + '\n', print: true}); if ( toEval.length < 1 ) program.interactive = true; function next() { if ( toEval.length === 0 ) { if ( program.interactive ) return enterRepl(); else return process.exit(); } var fn = toEval.shift(); var code; if ( fn.type === 'file' ) { code = fs.readFileSync(fn.value, 'utf8'); } else { code = fn.value; } return engine.evalDetatched(code).then(function(val) { if ( fn.print && val ) console.log(val.debugString); return next(); }).catch(function(e) { if ( e.stack ) { process.stderr.write(e.stack + "\n"); } else { process.stderr.write(`${e.name}: ${e.message}\n`); } }); } next(); /* Usage: node [options] [ -e script | script.js ] [arguments] node debug script.js [arguments] Options: -v, --version print Node.js version -e, --eval script evaluate script -p, --print evaluate script and print result -c, --check syntax check script without executing -i, --interactive always enter the REPL even if stdin does not appear to be a terminal -r, --require module to preload (option can be repeated) --no-deprecation silence deprecation warnings --throw-deprecation throw an exception anytime a deprecated function is used --trace-deprecation show stack traces on deprecations --trace-sync-io show stack trace when use of sync IO is detected after the first tick --track-heap-objects track heap object allocations for heap snapshots --v8-options print v8 command line options --tls-cipher-list=val use an alternative default TLS cipher list --icu-data-dir=dir set ICU data load path to dir (overrides NODE_ICU_DATA) Environment variables: NODE_PATH ':'-separated list of directories prefixed to the module search path. NODE_DISABLE_COLORS set to 1 to disable colors in the REPL NODE_ICU_DATA data path for ICU (Intl object) data NODE_REPL_HISTORY path to the persistent REPL history file Documentation can be found at https://nodejs.org/ */
const express = require('express'); const router = express.Router(); const queries = require('../db/queries'); const knex = require('../db/knex.js'); const request = require('request'); router.get('/clear', (req, res, next) => { queries.clearStationsTable((results) => { console.log(results); }); res.redirect('/homepage'); }); router.get('/', function(req,res,next) { var riverName = req.query.river; queries.getRiverSites(riverName, function(err, results) { var returnObject = {}; if (err) { returnObject.message = err.message || 'Could not find sites'; res.status(400).render('error', returnObject); } else { returnObject.sites = results; res.send(returnObject); } }); }); router.get('/Arkansas', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=07079300,07081200,07083710,07087050,07091200,07094500,07099970,07099973,07109500,07124000,07130500,07133000,07134180&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Arkansas', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); router.get('/Upper%20South%20Platte', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=06700000,06701620,06701700,06701900,06708600,06708690,06708800,06709000,06709530,06709740,06709910,06710150,06710247,06710385,06710605,06711515,06711555,06711565,06711570,06711575,06711618,06711770,06711780&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Upper South Platte', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); router.get('/Blue', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=09041900,09044300,09044800,09046490,09046600,09047500,09047700,09050100,09050700,09051050,09056500,09057500&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Blue', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); router.get('/Roaring%20Fork', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=09072550,09073005,09073300,09073400,09074000,09074500,09075400,09078141,09078475,09079450,09080400,09081000,09081600,09085000&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Roaring Fork', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); module.exports = router;
version https://git-lfs.github.com/spec/v1 oid sha256:8b2c75ae8236614319bbfe99cee3dba6fa2183434deff5a3dd2f69625589c74a size 391
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rx_1 = require("rx"); /* tslint:enable */ function cache(callback) { var cached$ = this.replay(undefined, 1); var subscription = cached$.connect(); callback(function () { return subscription.dispose(); }); return cached$; } rx_1.Observable.prototype.cache = cache; //# sourceMappingURL=Rx.js.map
var chai = require('chai'); var should = chai.should(); var pictogramResponse = require('../../../lib/model/response/pictogramResponse'); describe('pictogramResponse model test', function () { var id = 'id'; var category = 'category'; var url = 'url'; it('should create model', function (done) { var pictogramResponseModel = new pictogramResponse.PictogramResponse( id, category, url ); should.exist(pictogramResponseModel); pictogramResponseModel.id.should.be.equal(id); pictogramResponseModel.category.should.be.equal(category); pictogramResponseModel.url.should.be.equal(url); done(); }); it('should create model by builder', function (done) { var pictogramResponseModel = new pictogramResponse.PictogramResponseBuilder() .withId(id) .withCategory(category) .withUrl(url) .build(); should.exist(pictogramResponseModel); pictogramResponseModel.id.should.be.equal(id); pictogramResponseModel.category.should.be.equal(category); pictogramResponseModel.url.should.be.equal(url); done(); }); });
"use strict"; /** * @license * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var _this = this; Object.defineProperty(exports, "__esModule", { value: true }); var tf = require("./index"); var jasmine_util_1 = require("./jasmine_util"); var tensor_1 = require("./tensor"); var test_util_1 = require("./test_util"); jasmine_util_1.describeWithFlags('variable', jasmine_util_1.ALL_ENVS, function () { it('simple assign', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: v = tf.variable(tf.tensor1d([1, 2, 3])); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [1, 2, 3]]); v.assign(tf.tensor1d([4, 5, 6])); _b = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 2: _b.apply(void 0, [_c.sent(), [4, 5, 6]]); return [2 /*return*/]; } }); }); }); it('simple chain assign', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: v = tf.tensor1d([1, 2, 3]).variable(); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [1, 2, 3]]); v.assign(tf.tensor1d([4, 5, 6])); _b = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 2: _b.apply(void 0, [_c.sent(), [4, 5, 6]]); return [2 /*return*/]; } }); }); }); it('default names are unique', function () { var v = tf.variable(tf.tensor1d([1, 2, 3])); expect(v.name).not.toBeNull(); var v2 = tf.variable(tf.tensor1d([1, 2, 3])); expect(v2.name).not.toBeNull(); expect(v.name).not.toBe(v2.name); }); it('user provided name', function () { var v = tf.variable(tf.tensor1d([1, 2, 3]), true, 'myName'); expect(v.name).toBe('myName'); }); it('if name already used, throw error', function () { tf.variable(tf.tensor1d([1, 2, 3]), true, 'myName'); expect(function () { return tf.variable(tf.tensor1d([1, 2, 3]), true, 'myName'); }) .toThrowError(); }); it('ops can take variables', function () { return __awaiter(_this, void 0, void 0, function () { var value, v, res, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: value = tf.tensor1d([1, 2, 3]); v = tf.variable(value); res = tf.sum(v); _a = test_util_1.expectArraysClose; return [4 /*yield*/, res.data()]; case 1: _a.apply(void 0, [_b.sent(), [6]]); return [2 /*return*/]; } }); }); }); it('chained variables works', function () { return __awaiter(_this, void 0, void 0, function () { var v, res, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: v = tf.tensor1d([1, 2, 3]).variable(); res = tf.sum(v); _a = test_util_1.expectArraysClose; return [4 /*yield*/, res.data()]; case 1: _a.apply(void 0, [_b.sent(), [6]]); return [2 /*return*/]; } }); }); }); it('variables are not affected by tidy', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: expect(tf.memory().numTensors).toBe(0); tf.tidy(function () { var value = tf.tensor1d([1, 2, 3], 'float32'); expect(tf.memory().numTensors).toBe(1); v = tf.variable(value); expect(tf.memory().numTensors).toBe(2); }); expect(tf.memory().numTensors).toBe(1); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_b.sent(), [1, 2, 3]]); v.dispose(); expect(tf.memory().numTensors).toBe(0); return [2 /*return*/]; } }); }); }); it('disposing a named variable allows creating new named variable', function () { var numTensors = tf.memory().numTensors; var t = tf.scalar(1); var varName = 'var'; var v = tf.variable(t, true, varName); expect(tf.memory().numTensors).toBe(numTensors + 2); v.dispose(); t.dispose(); expect(tf.memory().numTensors).toBe(numTensors); // Create another variable with the same name. var t2 = tf.scalar(1); var v2 = tf.variable(t2, true, varName); expect(tf.memory().numTensors).toBe(numTensors + 2); t2.dispose(); v2.dispose(); expect(tf.memory().numTensors).toBe(numTensors); }); it('double disposing a variable works', function () { var numTensors = tf.memory().numTensors; var t = tf.scalar(1); var v = tf.variable(t); expect(tf.memory().numTensors).toBe(numTensors + 2); t.dispose(); v.dispose(); expect(tf.memory().numTensors).toBe(numTensors); // Double dispose the variable. v.dispose(); expect(tf.memory().numTensors).toBe(numTensors); }); it('constructor does not dispose', function () { return __awaiter(_this, void 0, void 0, function () { var a, v, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: a = tf.scalar(2); v = tf.variable(a); expect(tf.memory().numTensors).toBe(2); expect(tf.memory().numDataBuffers).toBe(1); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [2]]); _b = test_util_1.expectArraysClose; return [4 /*yield*/, a.data()]; case 2: _b.apply(void 0, [_c.sent(), [2]]); return [2 /*return*/]; } }); }); }); it('variables are assignable to tensors', function () { // This test asserts compilation, not doing any run-time assertion. var x0 = null; var y0 = x0; expect(y0).toBeNull(); var x1 = null; var y1 = x1; expect(y1).toBeNull(); var x2 = null; var y2 = x2; expect(y2).toBeNull(); var x3 = null; var y3 = x3; expect(y3).toBeNull(); var x4 = null; var y4 = x4; expect(y4).toBeNull(); var xh = null; var yh = xh; expect(yh).toBeNull(); }); it('assign does not dispose old data', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a, secondArray, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: v = tf.variable(tf.tensor1d([1, 2, 3])); expect(tf.memory().numTensors).toBe(2); expect(tf.memory().numDataBuffers).toBe(1); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [1, 2, 3]]); secondArray = tf.tensor1d([4, 5, 6]); expect(tf.memory().numTensors).toBe(3); expect(tf.memory().numDataBuffers).toBe(2); v.assign(secondArray); _b = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 2: _b.apply(void 0, [_c.sent(), [4, 5, 6]]); // Assign doesn't dispose the 1st array. expect(tf.memory().numTensors).toBe(3); expect(tf.memory().numDataBuffers).toBe(2); v.dispose(); // Disposing the variable disposes itself. The input to variable and // secondArray are the only remaining tensors. expect(tf.memory().numTensors).toBe(2); expect(tf.memory().numDataBuffers).toBe(2); return [2 /*return*/]; } }); }); }); it('shape must match', function () { var v = tf.variable(tf.tensor1d([1, 2, 3])); expect(function () { return v.assign(tf.tensor1d([1, 2])); }).toThrowError(); // tslint:disable-next-line:no-any expect(function () { return v.assign(tf.tensor2d([3, 4], [1, 2])); }).toThrowError(); }); it('dtype must match', function () { var v = tf.variable(tf.tensor1d([1, 2, 3])); // tslint:disable-next-line:no-any expect(function () { return v.assign(tf.tensor1d([1, 1, 1], 'int32')); }) .toThrowError(); // tslint:disable-next-line:no-any expect(function () { return v.assign(tf.tensor1d([true, false, true], 'bool')); }) .toThrowError(); }); }); jasmine_util_1.describeWithFlags('x instanceof Variable', jasmine_util_1.ALL_ENVS, function () { it('x: Variable', function () { var t = tf.variable(tf.scalar(1)); expect(t instanceof tensor_1.Variable).toBe(true); }); it('x: Variable-like', function () { var t = { assign: function () { }, shape: [2], dtype: 'float32', dataId: {} }; expect(t instanceof tensor_1.Variable).toBe(true); }); it('x: other object, fails', function () { var t = { something: 'else' }; expect(t instanceof tensor_1.Variable).toBe(false); }); it('x: Tensor, fails', function () { var t = tf.scalar(1); expect(t instanceof tensor_1.Variable).toBe(false); }); }); //# sourceMappingURL=variable_test.js.map
import React from "react"; import { useResponse } from "@curi/react-dom"; import NavLinks from "./NavLinks"; export default function App() { let { response } = useResponse(); let { body: Body } = response; return ( <div> <NavLinks /> <Body response={response} /> </div> ); }
import { Tween } from '../core'; import { mat4 } from '../math'; export class MatrixTween extends Tween { action() { for (let i = 0; i < this.from.length; i++) { this.object[i] = this.from[i] + this.current_step * (this.to[i] - this.from[i]); } } pre_start() { super.pre_start(); this.from = mat4.clone(this.object); } }
import React from 'react'; import MobileTearSheet from './MobileTearSheet'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import ActionInfo from 'material-ui/lib/svg-icons/action/info'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import FileFolder from 'material-ui/lib/svg-icons/file/folder'; import ActionAssignment from 'material-ui/lib/svg-icons/action/assignment'; import Colors from 'material-ui/lib/styles/colors'; import EditorInsertChart from 'material-ui/lib/svg-icons/editor/insert-chart'; const ListExampleFolder = () => ( <MobileTearSheet> <List subheader="Folders" insetSubheader={true}> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Photos" secondaryText="Jan 9, 2014" /> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Recipes" secondaryText="Jan 17, 2014" /> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Work" secondaryText="Jan 28, 2014" /> </List> <Divider inset={true} /> <List subheader="Files" insetSubheader={true}> <ListItem leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={Colors.blue500} />} rightIcon={<ActionInfo />} primaryText="Vacation itinerary" secondaryText="Jan 20, 2014" /> <ListItem leftAvatar={<Avatar icon={<EditorInsertChart />} backgroundColor={Colors.yellow600} />} rightIcon={<ActionInfo />} primaryText="Kitchen remodel" secondaryText="Jan 10, 2014" /> </List> </MobileTearSheet> ); export default ListExampleFolder;
module.exports = function Boot(game) { return { preload: function(){ game.load.image('mars', '/assets/images/mars.png'); }, create: function(){ //This is just like any other Phaser create function console.log('Boot was just loaded'); this.mars = game.add.sprite(0, 0, 'mars'); }, update: function(){ //Game logic goes here this.mars.x += 1; this.mars.y += 1; } } };
var topics = require('../data').topics; console.log(topics); var result = topics.filter(function (topic) { //filter renvoie les 'true' return topic.user.name === 'Leonard'; //? true : false; }); var result2 = topics.filter(topic=>topic.user.name === 'Leonard'); var titles = topics.map(function (topic) { return topic.title; }); var title2 = topics.map(topic=>topic.title); var hasViolence = topics.some(function (topic) { //renvoie true pour les topics avec violence return (topic.tags.includes('violence')); }); var hasViolence2 = topics.some(topic=>topic.tags.includes('violence')); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(result); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(result2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(titles); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(title2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log('hasViolence ', hasViolence); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var SheldonCom = topics.filter(function (topic) { return (topic.comments.some(function (comment) { return comment.user.name === 'Sheldon'; })); }).map(function (topic) { return (topic.title); }); var SheldonCom2; SheldonCom2 = topics.filter(topic=>topic.comments.some(comment=>comment.user.name === 'Sheldon')).map(topic=>topic.title); console.log('Sheldon has published in ', SheldonCom); console.log('Sheldon has published in ', SheldonCom2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var idCommPenny = []; topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.user.name === 'Penny') { idCommPenny.push(comment.id); } }) }); var sortFunction = (a, b) => a < b ? -1 : 1; idCommPenny.sort(sortFunction); console.log('Penny has post in : ', idCommPenny); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var Content = []; function getCommentByTag(tag, isAdmin) { topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.tags !== undefined) { if (!comment.user.admin === isAdmin && comment.tags.includes(tag)) { Content.push(comment.content); } } }); }); return Content; }; console.log('Violent tag are present for these non-admin comments : ', getCommentByTag('fun', true)); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var searched = []; function search(term) { topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.content.toLowerCase().includes(term.toLowerCase())) { searched.push(comment.content); } }) }); return searched; } console.log('search is present in :', search('it'));
StatsGopher.PresenceMonitor = function PresenceMonitor (opts) { opts = opts || {}; this.statsGopher = opts.statsGopher; this.key = opts.key; this.send = this.executeNextSend; this.paused = false; } StatsGopher.PresenceMonitor.prototype = { ignoreNextSend: function () { }, queueNextSend: function () { this.request.done(function () { this.send() }.bind(this)) this.send = this.ignoreNextSend }, executeNextSend: function () { var executeNextSend = function () { this.send = this.executeNextSend }.bind(this); if (this.paused) return; this.request = this.statsGopher.send({ code: this.code, key: this.key }).done(executeNextSend).fail(executeNextSend); this.send = this.queueNextSend }, pause: function () { this.paused = true }, resume: function () { this.paused = false } } StatsGopher.Heartbeat = function (opts) { StatsGopher.PresenceMonitor.apply(this, arguments) this.timeout = (typeof opts.timeout) === 'number' ? opts.timeout : 10000; } StatsGopher.Heartbeat.prototype = new StatsGopher.PresenceMonitor() StatsGopher.Heartbeat.prototype.code = 'heartbeat' StatsGopher.Heartbeat.prototype.start = function () { this.send() setTimeout(this.start.bind(this), 10000) } StatsGopher.UserActivity = function () { StatsGopher.PresenceMonitor.apply(this, arguments) } StatsGopher.UserActivity.prototype = new StatsGopher.PresenceMonitor() StatsGopher.UserActivity.prototype.code = 'user-activity' StatsGopher.UserActivity.prototype.listen = function () { var events = [ 'resize', 'click', 'mousedown', 'scroll', 'mousemove', 'keydown' ]; events.forEach(function (eventName) { window.addEventListener(eventName, function () { this.send(); }.bind(this)) }.bind(this)); }
app.service('operacoes', function() { this.somar = function(valor1, valor2) { return valor1 + valor2; } this.subtrair = function(valor1, valor2) { return valor1 - valor2; } });
function paddAppendClear() { jQuery('.append-clear').append('<div class="clear"></div>'); } function paddWrapInner1() { jQuery('.wrap-inner-1').wrapInner('<div class="inner"></div>'); } function paddWrapInner3() { jQuery('.wrap-inner-3').wrapInner('<div class="m"></div>'); jQuery('.wrap-inner-3').prepend('<div class="t"></div>'); jQuery('.wrap-inner-3').append('<div class="b"></div>'); } function paddToggle(classname,value) { jQuery(classname).focus(function() { if (value == jQuery(classname).val()) { jQuery(this).val(''); } }); jQuery(classname).blur(function() { if ('' == jQuery(classname).val()) { jQuery(this).val(value); } }); } jQuery(document).ready(function() { jQuery.noConflict(); jQuery('div#menubar div > ul').superfish({ hoverClass: 'hover', speed: 500, animation: { opacity: 'show', height: 'show' } }); paddAppendClear(); paddWrapInner1(); paddWrapInner3(); jQuery('p.older-articles').titleBoxShadow('#ebebeb'); jQuery('.hentry-large .title').titleBoxShadow('#ebebeb'); jQuery('.hentry-large .thumbnail img').imageBoxShadow('#ebebeb'); jQuery('input#s').val('Search this site'); paddToggle('input#s','Search this site'); jQuery('div.search form').click(function () { jQuery('input#s').focus(); }); });
/* globals $ */ const modals = window.modals; const footer = window.footer; const notifier = window.notifier; const admin = window.admin; ((scope) => { const modalLogin = modals.get("login"); const modalRegister = modals.get("register"); const helperFuncs = { loginUser(userToLogin) { const url = window.baseUrl + "login"; // loader.show(); // $("#loader .loader-title").html("Creating"); Promise.all([http.postJSON(url, userToLogin), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result.success) { res = resp.result; let html = templateFunc({ res }); $("#nav-wrap").html(html); notifier.success(`Welcome ${userToLogin.username}!`); } else { res = resp.result.success; notifier.error("Wrong username or password!"); } // loader.hide(); modalLogin.hide(); $("#content-wrap").addClass(res.role); }) .then(() => { console.log($("#content-wrap").hasClass("admin")); if ($("#content-wrap").hasClass("admin")) { content.init("admin-content"); admin.init(); } if ($("#content-wrap").hasClass("standart")) { content.init("user-content"); users.init(); } }) .catch((err) => { // loader.hide(); notifier.error(`${userToLogin.username} not created! ${err}`); console.log(JSON.stringify(err)); }); }, registerUser(userToRegister) { const url = window.baseUrl + "register"; // loader.show(); // $("#loader .loader-title").html("Creating Book"); Promise.all([http.postJSON(url, userToRegister), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result.success) { res = false; } else { res = resp.result; console.log(resp); // let html = templateFunc({ // res // }); // $("#nav-wrap").html(html); } // loader.hide(); modalRegister.hide(); }) .catch((err) => { // loader.hide(); notifier.error(`${userToLogin.username} not created! ${err}`); console.log(JSON.stringify(err)); }); }, loginFormEvents() { const $form = $("#form-login"); $form.on("submit", function() { const user = { username: $("#tb-username").val(), password: $("#tb-password").val() }; console.log(user); helperFuncs.loginUser(user); return false; }); }, registerFormEvents() { const $form = $("#form-register"); $form.on("submit", function() { const user = { firstName: $("#tb-firstname").val(), lastName: $("#tb-lastname").val(), username: $("#tb-username").val(), password: $("#tb-password").val() }; helperFuncs.registerUser(user); return false; }); }, menuCollaps() { let pull = $("#pull"); menu = $("nav ul"); link = $("#subMenu"); signUp = $("#signUp"); submenu = $("nav li ul"); console.log(link); menuHeight = menu.height(); $(pull).on("click", function(ev) { ev.preventDefault(); menu.slideToggle(); submenu.hide(); }); $(link).on("click", function(ev) { ev.preventDefault(); signUp.next().hide(); link.next().slideToggle(); }); $(signUp).on("click", function(ev) { ev.preventDefault(); link.next().hide(); signUp.next().slideToggle(); }); $(window).resize(function() { let win = $(window).width(); if (win > 760 && menu.is(":hidden")) { menu.removeAttr("style"); } }); } }; const initial = () => { const url = window.baseUrl + "users"; Promise .all([http.get(url), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result === "unauthorized!") { res = false; } else { res = resp.result; } let html = templateFunc({ res }); $("#nav-wrap").html(html); $(".btn-login-modal").on("click", () => { modalLogin.show() .then(() => { helperFuncs.loginFormEvents(); }); }); $("#btn-register-modal").on("click", () => { modalRegister.show() .then(() => { helperFuncs.registerFormEvents(); }); }); }) .then(footer.init()) .then(() => { content.init("no-user-content"); }) .then(() => { helperFuncs.menuCollaps(); }); Handlebars.registerHelper("ifEq", (v1, v2, options) => { if (v1 === v2) { return options.fn(this); } return options.inverse(this); }); Handlebars.registerHelper("mod3", (index, options) => { if ((index + 1) % 3 === 0) { return options.fn(this); } return options.inverse(this); }); }; scope.nav = { initial }; })(window.controllers = window.controllers || {});
(function () { 'use strict'; angular .module('patients') .controller('PatientsListController', PatientsListController); PatientsListController.$inject = ['PatientsService']; function PatientsListController(PatientsService) { var vm = this; vm.patients = PatientsService.query(); } })();
// Polyfills // (these modules are what are in 'angular2/bundles/angular2-polyfills' so don't use that here) // import 'ie-shim'; // Internet Explorer // import 'es6-shim'; // import 'es6-promise'; // import 'es7-reflect-metadata'; // Prefer CoreJS over the polyfills above require('core-js'); require('zone.js/dist/zone'); if ('production' === ENV) { } else { // Development Error.stackTraceLimit = Infinity; require('zone.js/dist/long-stack-trace-zone'); } //# sourceMappingURL=polyfills.js.map
'use strict'; //Setting up route angular.module('shop-list').config(['$stateProvider', function($stateProvider) { // Shop list state routing $stateProvider. state('detail-product', { url: '/detail-product/:productId', templateUrl: 'modules/shop-list/views/detail-product.client.view.html' }). state('products-list', { url: '/products-list', templateUrl: 'modules/shop-list/views/products-list.client.view.html' }); } ]);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; define(["require", "exports", "aurelia-framework", "./../../config"], function (require, exports, aurelia_framework_1, config_1) { "use strict"; var CardActionElement = (function () { function CardActionElement() { } CardActionElement.prototype.attached = function () { this.element.classList.add("card-action"); }; CardActionElement.prototype.detached = function () { this.element.classList.remove("card-action"); }; CardActionElement = __decorate([ aurelia_framework_1.customElement(config_1.config.cardAction), aurelia_framework_1.containerless(), aurelia_framework_1.inlineView("<template><div ref='element'><slot></slot></div></template>"), __metadata('design:paramtypes', []) ], CardActionElement); return CardActionElement; }()); exports.CardActionElement = CardActionElement; }); //# sourceMappingURL=cardActionElement.js.map
module.exports = function (grunt) { // Define the configuration for all the tasks grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Configure a mochaTest task mochaTest: { test: { options: { reporter: 'spec', ui: 'bdd', recursive: true, colors: true, 'check-leaks': true, growl: true, 'inline-diffs': true, 'no-exit': true, 'async-only': true }, src: ['test/**/*.js'] } } }); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('test', ['mochaTest']); };
import { createEllipsisItem, createFirstPage, createLastItem, createNextItem, createPageFactory, createPrevItem, } from 'src/lib/createPaginationItems/itemFactories' describe('itemFactories', () => { describe('createEllipsisItem', () => { it('"active" is always false', () => { createEllipsisItem(0).should.have.property('active', false) }) it('"type" matches "ellipsisItem"', () => { createEllipsisItem(0).should.have.property('type', 'ellipsisItem') }) it('"value" matches passed argument', () => { createEllipsisItem(5).should.have.property('value', 5) }) }) describe('createFirstPage', () => { it('"active" is always false', () => { createFirstPage().should.have.property('active', false) }) it('"type" matches "firstItem"', () => { createFirstPage().should.have.property('type', 'firstItem') }) it('"value" always returns 1', () => { createFirstPage().should.have.property('value', 1) }) }) describe('createPrevItem', () => { it('"active" is always false', () => { createPrevItem(1).should.have.property('active', false) }) it('"type" matches "prevItem"', () => { createPrevItem(1).should.have.property('type', 'prevItem') }) it('"value" returns previous page number or 1', () => { createPrevItem(1).should.have.property('value', 1) createPrevItem(2).should.have.property('value', 1) createPrevItem(3).should.have.property('value', 2) }) }) describe('createPageFactory', () => { const pageFactory = createPageFactory(1) it('returns function', () => { pageFactory.should.be.a('function') }) it('"active" is true when pageNumber is equal to activePage', () => { pageFactory(1).should.have.property('active', true) }) it('"active" is false when pageNumber is not equal to activePage', () => { pageFactory(2).should.have.property('active', false) }) it('"type" of created item matches "pageItem"', () => { pageFactory(2).should.have.property('type', 'pageItem') }) it('"value" returns pageNumber', () => { pageFactory(1).should.have.property('value', 1) pageFactory(2).should.have.property('value', 2) }) }) describe('createNextItem', () => { it('"active" is always false', () => { createNextItem(0, 0).should.have.property('active', false) }) it('"type" matches "nextItem"', () => { createNextItem(0, 0).should.have.property('type', 'nextItem') }) it('"value" returns the smallest of the arguments', () => { createNextItem(1, 3).should.have.property('value', 2) createNextItem(2, 3).should.have.property('value', 3) createNextItem(3, 3).should.have.property('value', 3) }) }) describe('createLastItem', () => { it('"active" is always false', () => { createLastItem(0).should.have.property('active', false) }) it('"type" matches "lastItem"', () => { createLastItem(0).should.have.property('type', 'lastItem') }) it('"value" matches passed argument', () => { createLastItem(2).should.have.property('value', 2) }) }) })
/** * App */ 'use strict'; // Base setup var express = require('express'); var app = express(); var path = require('path'); var bodyParser = require('body-parser'); var logger = require('morgan'); var mongoose = require('mongoose'); var config = require('./config'); var routes = require('./routes/index'); var validateRequest = require('./middlewares/validateRequest'); // Configuration mongoose.connect(config.db[app.get('env')], function(err) { if (err) { console.log('connection error', err); } else { console.log('connection successful'); } }); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // app.use(logger('dev')); // app.set('view engine', 'html'); // API Routes // app.all('/*', function(req, res, next) { // // CORS headers // res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); // // Set custom headers for CORS // res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key'); // if (req.method == 'OPTIONS') { // res.status(200).end(); // } else { // next(); // } // }); // Auth Middleware - This will check if the token is valid // Only the requests that start with /api/v1/* will be checked for the token. // Any URL's that do not follow the below pattern should be avoided unless you // are sure that authentication is not needed. app.all('/api/v1/*', [validateRequest]); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // Error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500).send(err.message); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500).send(err.message); }); module.exports = app;
$(document).ready(function(){ 'use strict'; //Turn off and on the music $("#sound-control").click(function() { var toggle = document.getElementById("sound-control"); var music = document.getElementById("music"); if(music.paused){ music.play(); $("#sound-control").attr('src', 'img/ljud_pa.png'); } else { music.pause(); $("#sound-control").attr('src', 'img/ljud_av.png'); } }); //The slideshow var started = false; //Backwards navigation $("#back").click(function() { stopSlideshow(); navigate("back"); }); //Forward navigation $("#next").click(function() { stopSlideshow(); navigate("next"); }); var interval; $("#control").click(function(){ if(started) { stopSlideshow(); } else { startSlideshow(); } }); var activeContainer = 1; var currentImg = 0; var animating = false; var navigate = function(direction) { //Check if no animation is running if(animating) { return; } //Check wich current image we need to show if(direction == "next") { currentImg++; if(currentImg == photos.length + 1) { currentImg = 1; } } else { currentImg--; if(currentImg == 0) { currentImg = photos.length; } } //Check wich container we need to use var currentContainer = activeContainer; if(activeContainer == 1) { activeContainer = 2; } else { activeContainer = 1; } showImage(photos[currentImg - 1], currentContainer, activeContainer); }; var currentZindex = -1; var showImage = function(photoObject, currentContainer, activeContainer) { animating = true; //Make sure the new container is always on the background currentZindex--; //Set the background image of the new active container $("#slideimg" + activeContainer).css({ "background-image" : "url(" + photoObject.image + ")", "display" : "block", "z-index" : currentZindex }); //Fade out and hide the slide-text when the new image is loading $("#slide-text").fadeOut(); $("#slide-text").css({"display" : "none"}); //Set the new header text $("#firstline").html(photoObject.firstline); $("#secondline") .attr("href", photoObject.url) .html(photoObject.secondline); //Fade out the current container //and display the slider-text when animation is complete $("#slideimg" + currentContainer).fadeOut(function() { setTimeout(function() { $("#slide-text").fadeIn(); animating = false; }, 500); }); }; var stopSlideshow = function() { //Change the background image to "play" $("#control").css({"background-image" : "url(img/play.png)" }); //Clear the interval clearInterval(interval); started = false; }; var startSlideshow = function() { $("#control").css({ "background-image" : "url(img/pause.png)" }); navigate("next"); interval = setInterval(function() { navigate("next"); }, slideshowSpeed); started = true; }; $.preloadImages = function() { $(photos).each(function() { $('<img>')[0].src = this.image; }); startSlideshow(); } $.preloadImages(); });
/* * Manifest Service * * Copyright (c) 2015 Thinknode Labs, LLC. All rights reserved. */ (function() { 'use strict'; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Service function loggerService() { /* jshint validthis: true */ this.logs = []; /** * @summary Appends a log message of a given type to the collection of logs. */ this.append = function(type, message) { this.logs.push({ "date": new Date(), "type": type, "message": message }); }; /** * @summary Clears the logs. */ this.clear = function() { this.logs.length = 0; }; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Register service angular.module('app').service('$logger', [loggerService]); })();
export { default } from './src/layout-container.vue';
/* *@author jaime P. Bravo */ $(document).ready(function () { //forms general function sendDataWithAjax(type, url, data) { return $.ajax({ type: type, url: url, data: data, dataType: 'json', beforeSend: function () { console.log('Enviando...'); }, success: function (response) { }, error: function (jqXHR, textStatus, errorThrown) { console.log('Código:' + jqXHR.status); console.log('Error AJAX: ' + textStatus); console.log('Tipo Error: ' + errorThrown); } }); } // Form create $('.create-form-view').submit(function (e) { e.preventDefault(); var url = $(this).attr('action'); var data = $(this).serialize(); var torre = sendDataWithAjax('POST', url, data); torre.success(function (response) { if (response.type === 'error') { generateNoty('bottomLeft', response.message, 'error'); } else { generateNoty('bottomLeft', response.message, 'success'); $('.form-group.input-type').removeClass('has-error'); $('.error-icon').hide(); resetForms('create-form-view'); if (response.login === 'si') { window.location.href = '/matters/index.php/inicio'; } } }); }); $('.dropdown.logo').click(function () { window.location.href = '/matters/index.php/inicio'; }); //Noty Master function function generateNoty(layout, text, type) { var n = noty({ text: text, type: type, dismissQueue: true, layout: layout, theme: 'relax', timeout: 4000 }); } //Datatables $('.table-datatable').DataTable({ "bStateSave": true }); }); //End jQuery function refreshTable(table) { $('.' + table + '').DataTable().ajax.reload(); } //Helper functions function resetForms(form_class) { $('.' + form_class + '').get(0).reset(); } //Hover submenus $(function () { $(".dropdown").hover( function () { $('.dropdown-menu', this).stop(true, true).fadeIn("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); $('b', this).hover().toggleClass("caret caret-reversed"); }, function () { $('.dropdown-menu', this).stop(true, true).fadeOut("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); $('b', this).hover().toggleClass("caret caret-reversed"); }); });
var LedgerRequestHandler = require('../../helpers/ledgerRequestHandler'); /** * @api {post} /gl/:LEDGER_ID/add-filter add filter * @apiGroup Ledger.Utils * @apiVersion v1.0.0 * * @apiDescription * Add a filter for caching balances. This will speed up balance * requests containing a matching filters. * * @apiParam {CounterpartyId[]} excludingCounterparties * IDs of transaction counterparties to exclude with the filter * @apiParam {AccountId[]} excludingContraAccounts * IDs of transaction countra accounts to exclude with the filter * @apiParam {CounterpartyId[]} [withCounterparties] * IDs of transaction counterparties to limit with the filter. All others will be * excluded. * * @apiParamExample {x-www-form-urlencoded} Request-Example: * excludingCounterparties=foobar-llc,foobar-inc * excludingContraAccounts=chase-saving,chase-checking * withCounterparties=staples,ubs */ module.exports = new LedgerRequestHandler({ validateBody: { 'excludingCounterparties': { type: 'string', required: true }, 'excludingContraAccounts': { type: 'string', required: true }, 'withCounterparties': { type: 'string' } }, commitLedger: true }).handle(function (options, cb) { var excludingCounterparties = options.body.excludingCounterparties.split(','); var excludingContraAccounts = options.body.excludingContraAccounts.split(','); var withCounterparties = options.body.withCounterparties && options.body.withCounterparties.split(','); var ledger = options.ledger; ledger.registerFilter({ excludingCounterparties: excludingCounterparties, excludingContraAccounts: excludingContraAccounts, withCounterparties: withCounterparties }); cb(null, ledger.toJson()); });
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var _ = require('underscore'); var common = require('./common'); var groups = function(groups) { var buf = this.buf; buf.appendUInt32BE(groups.length); _.each(groups, function(group) { common.appendString(buf, group); }); return this; }; exports.encode = function(version) { var ret = common.encode(common.DESCRIBEGROUP_API, version); ret.groups = groups; return ret; };
// @flow /* ********************************************************** * File: Footer.js * * Brief: The react footer component * * Authors: Craig Cheney, George Whitfield * * 2017.04.27 CC - Document created * ********************************************************* */ import React, { Component } from 'react'; import { Grid, Col, Row } from 'react-bootstrap'; let mitImagePath = '../resources/img/mitLogo.png'; /* Set mitImagePath to new path */ if (process.resourcesPath !== undefined) { mitImagePath = (`${String(process.resourcesPath)}resources/img/mitLogo.png`); // mitImagePath = `${process.resourcesPath}resources/img/mitLogo.png`; } // const nativeImage = require('electron').nativeImage; // const mitLogoImage = nativeImage.createFromPath(mitImagePath); const footerStyle = { position: 'absolute', right: 0, bottom: 0, left: 0, color: '#9d9d9d', backgroundColor: '#222', height: '25px', textAlign: 'center' }; const mitLogoStyle = { height: '20px' }; const bilabLogoStyle = { height: '20px' }; export default class Footer extends Component<{}> { render() { return ( <Grid className='Footer' style={footerStyle} fluid> <Row> <Col xs={4}><img src={'../resources/img/mitLogo.png' || mitImagePath} style={mitLogoStyle} alt='MICA' /></Col> <Col xs={4}>The MICA Group &copy; 2017</Col> <Col xs={4}><img src='../resources/img/bilabLogo_white.png' style={bilabLogoStyle} alt='BioInstrumentation Lab' /></Col> </Row> </Grid> ); } } /* [] - END OF FILE */
/** * Auction collection */ 'use strict'; var Model = require('../models/auction_model.js'); var Collection = require('tungstenjs/adaptors/backbone').Collection; var AuctionCollection = Collection.extend({ model: Model }); module.exports = AuctionCollection;
// Regular expression that matches all symbols in the Devanagari Extended block as per Unicode v6.0.0: /[\uA8E0-\uA8FF]/;
// All code points in the `Hatran` script as per Unicode v10.0.0: [ 0x108E0, 0x108E1, 0x108E2, 0x108E3, 0x108E4, 0x108E5, 0x108E6, 0x108E7, 0x108E8, 0x108E9, 0x108EA, 0x108EB, 0x108EC, 0x108ED, 0x108EE, 0x108EF, 0x108F0, 0x108F1, 0x108F2, 0x108F4, 0x108F5, 0x108FB, 0x108FC, 0x108FD, 0x108FE, 0x108FF ];
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ module('Item'); test('copyTo(project)', function() { var project = paper.project; var path = new Path(); var secondDoc = new Project(); var copy = path.copyTo(secondDoc); equals(function() { return secondDoc.activeLayer.children.indexOf(copy) != -1; }, true); equals(function() { return project.activeLayer.children.indexOf(copy) == -1; }, true); equals(function() { return copy != path; }, true); }); test('copyTo(layer)', function() { var project = paper.project; var path = new Path(); var layer = new Layer(); var copy = path.copyTo(layer); equals(function() { return layer.children.indexOf(copy) != -1; }, true); equals(function() { return project.layers[0].children.indexOf(copy) == -1; }, true); }); test('clone()', function() { var project = paper.project; var path = new Path(); var copy = path.clone(); equals(function() { return project.activeLayer.children.length; }, 2); equals(function() { return path != copy; }, true); }); test('addChild(item)', function() { var project = paper.project; var path = new Path(); project.activeLayer.addChild(path); equals(function() { return project.activeLayer.children.length; }, 1); }); test('item.parent / item.isChild / item.isParent / item.layer', function() { var project = paper.project; var secondDoc = new Project(); var path = new Path(); project.activeLayer.addChild(path); equals(function() { return project.activeLayer.children.indexOf(path) != -1; }, true); equals(function() { return path.layer == project.activeLayer; }, true); secondDoc.activeLayer.addChild(path); equals(function() { return project.activeLayer.isChild(path); }, false); equals(function() { return path.layer == secondDoc.activeLayer; }, true); equals(function() { return path.isParent(project.activeLayer); }, false); equals(function() { return secondDoc.activeLayer.isChild(path); }, true); equals(function() { return path.isParent(secondDoc.activeLayer); }, true); equals(function() { return project.activeLayer.children.indexOf(path) == -1; }, true); equals(function() { return secondDoc.activeLayer.children.indexOf(path) == 0; }, true); }); test('item.lastChild / item.firstChild', function() { var project = paper.project; var path = new Path(); var secondPath = new Path(); equals(function() { return project.activeLayer.firstChild == path; }, true); equals(function() { return project.activeLayer.lastChild == secondPath; }, true); }); test('insertChild(0, item)', function() { var project = paper.project; var path = new Path(); var secondPath = new Path(); project.activeLayer.insertChild(0, secondPath); equals(function() { return secondPath.index < path.index; }, true); }); test('insertAbove(item)', function() { var project = paper.project; var path = new Path(); var secondPath = new Path(); path.insertAbove(secondPath); equals(function() { return project.activeLayer.lastChild == path; }, true); }); test('insertBelow(item)', function() { var project = paper.project; var firstPath = new Path(); var secondPath = new Path(); equals(function() { return secondPath.index > firstPath.index; }, true); secondPath.insertBelow(firstPath); equals(function() { return secondPath.index < firstPath.index; }, true); }); test('isDescendant(item) / isAncestor(item)', function() { var project = paper.project; var path = new Path(); equals(function() { return path.isDescendant(project.activeLayer); }, true); equals(function() { return project.activeLayer.isDescendant(path); }, false); equals(function() { return path.isAncestor(project.activeLayer); }, false); equals(function() { return project.activeLayer.isAncestor(path); }, true); // an item can't be its own descendant: equals(function() { return project.activeLayer.isDescendant(project.activeLayer); }, false); // an item can't be its own ancestor: equals(function() { return project.activeLayer.isAncestor(project.activeLayer); }, false); }); test('isGroupedWith', function() { var project = paper.project; var path = new Path(); var secondPath = new Path(); var group = new Group([path]); var secondGroup = new Group([secondPath]); equals(function() { return path.isGroupedWith(secondPath); }, false); secondGroup.addChild(path); equals(function() { return path.isGroupedWith(secondPath); }, true); equals(function() { return path.isGroupedWith(group); }, false); equals(function() { return path.isDescendant(secondGroup); }, true); equals(function() { return secondGroup.isDescendant(path); }, false); equals(function() { return secondGroup.isDescendant(secondGroup); }, false); equals(function() { return path.isGroupedWith(secondGroup); }, false); paper.project.activeLayer.addChild(path); equals(function() { return path.isGroupedWith(secondPath); }, false); paper.project.activeLayer.addChild(secondPath); equals(function() { return path.isGroupedWith(secondPath); }, false); }); test('getPreviousSibling() / getNextSibling()', function() { var firstPath = new Path(); var secondPath = new Path(); equals(function() { return firstPath.nextSibling == secondPath; }, true); equals(function() { return secondPath.previousSibling == firstPath; }, true); equals(function() { return secondPath.nextSibling == null; }, true); }); test('reverseChildren()', function() { var project = paper.project; var path = new Path(); var secondPath = new Path(); var thirdPath = new Path(); equals(function() { return project.activeLayer.firstChild == path; }, true); project.activeLayer.reverseChildren(); equals(function() { return project.activeLayer.firstChild == path; }, false); equals(function() { return project.activeLayer.firstChild == thirdPath; }, true); equals(function() { return project.activeLayer.lastChild == path; }, true); }); test('Check item#project when moving items across projects', function() { var project = paper.project; var doc1 = new Project(); var path = new Path(); var group = new Group(); group.addChild(new Path()); equals(function() { return path.project == doc1; }, true); var doc2 = new Project(); doc2.activeLayer.addChild(path); equals(function() { return path.project == doc2; }, true); doc2.activeLayer.addChild(group); equals(function() { return group.children[0].project == doc2; }, true); }); test('group.selected', function() { var path = new Path([0, 0]); var path2 = new Path([0, 0]); var group = new Group([path, path2]); path.selected = true; equals(function() { return group.selected; }, true); path.selected = false; equals(function() { return group.selected; }, false); group.selected = true; equals(function() { return path.selected; }, true); equals(function() { return path2.selected; }, true); group.selected = false; equals(function() { return path.selected; }, false); equals(function() { return path2.selected; }, false); }); test('Check parent children object for named item', function() { var path = new Path(); path.name = 'test'; equals(function() { return paper.project.activeLayer.children['test'] == path; }, true); var path2 = new Path(); path2.name = 'test'; equals(function() { return paper.project.activeLayer.children['test'] == path2; }, true); path2.remove(); equals(function() { return paper.project.activeLayer.children['test'] == path; }, true); path.remove(); equals(function() { return !paper.project.activeLayer.children['test']; }, true); }); test('Named child access 1', function() { var path = new Path(); path.name = 'test'; var path2 = new Path(); path2.name = 'test'; path.remove(); equals(function() { return paper.project.activeLayer.children['test'] == path2; }, true); }); test('Named child access 2', function() { var path = new Path(); path.name = 'test'; var path2 = new Path(); path2.name = 'test'; path.remove(); equals(function() { return paper.project.activeLayer.children['test'] == path2; }, true); equals(function() { return paper.project.activeLayer._namedChildren['test'].length == 1; }, true); path2.remove(); equals(function() { return !paper.project.activeLayer._namedChildren['test']; }, true); equals(function() { return paper.project.activeLayer.children['test'] === undefined; }, true); }); test('Named child access 3', function() { var path = new Path(); path.name = 'test'; var path2 = new Path(); path2.name = 'test'; var group = new Group(); group.addChild(path2); equals(function() { return paper.project.activeLayer.children['test'] == path; }, true); // TODO: Tests should not access internal properties equals(function() { return paper.project.activeLayer._namedChildren['test'].length; }, 1); equals(function() { return group.children['test'] == path2; }, true); equals(function() { return group._namedChildren['test'].length == 1; }, true); equals(function() { return paper.project.activeLayer._namedChildren['test'][0] == path; }, true); paper.project.activeLayer.appendTop(path2); equals(function() { return group.children['test'] == null; }, true); equals(function() { return group._namedChildren['test'] === undefined; }, true); equals(function() { return paper.project.activeLayer.children['test'] == path2; }, true); equals(function() { return paper.project.activeLayer._namedChildren['test'].length; }, 2); }); test('Setting name of child back to null', function() { var path = new Path(); path.name = 'test'; var path2 = new Path(); path2.name = 'test'; equals(function() { return paper.project.activeLayer.children['test'] == path2; }, true); path2.name = null; equals(function() { return paper.project.activeLayer.children['test'] == path; }, true); path.name = null; equals(function() { return paper.project.activeLayer.children['test'] === undefined; }, true); }); test('Renaming item', function() { var path = new Path(); path.name = 'test'; path.name = 'test2'; equals(function() { return paper.project.activeLayer.children['test'] === undefined; }, true); equals(function() { return paper.project.activeLayer.children['test2'] == path; }, true); }); test('Changing item#position.x', function() { var path = new Path.Circle(new Point(50, 50), 50); path.position.x += 5; equals(path.position.toString(), '{ x: 55, y: 50 }', 'path.position.x += 5'); }); test('Naming a removed item', function() { var path = new Path(); path.remove(); path.name = 'test'; }); test('Naming a layer', function() { var layer = new Layer(); layer.name = 'test'; }); test('Cloning a linked size', function() { var path = new Path([40, 75], [140, 75]); var error = null; try { var cloneSize = path.bounds.size.clone(); } catch (e) { error = e; } var description = 'Cloning a linked size should not throw an error'; if (error) description += ': ' + error; equals(error == null, true, description); });
import React, {Component, PropTypes} from 'react'; import * as actions from './ForumAction'; import ForumPage from './ForumPage'; class ForumContainer extends Component { constructor(props) { super(props); this.state = { questions: [] }; this.postQuestion = this.postQuestion.bind(this); } postQuestion(model) { actions.postQuestion(model).then(response => { const questions = this.state.questions.concat([response]); this.setState({questions}); }); } componentDidMount() { actions.getQuestions().then(response => { this.setState({questions: response}); }); } render() { return <ForumPage {...this.state} postQuestion={this.postQuestion}/>; } } export default ForumContainer;
((bbn)=>{let script=document.createElement('script');script.innerHTML=`<div :class="['bbn-iblock', componentClass]"> <input class="bbn-hidden" ref="element" :value="modelValue" :disabled="disabled" :required="required" > <div :style="getStyle()"> <div v-for="(d, idx) in source" :class="{ 'bbn-iblock': !vertical, 'bbn-right-space': !vertical && !separator && source[idx+1], 'bbn-bottom-sspace': !!vertical && !separator && source[idx+1] }" > <input :value="d[sourceValue]" :name="name" class="bbn-radio" type="radio" :disabled="disabled || d.disabled" :required="required" :id="id + '_' + idx" @change="changed(d[sourceValue], d, $event)" :checked="d[sourceValue] === modelValue" > <label class="bbn-radio-label bbn-iflex bbn-vmiddle" :for="id + '_' + idx" > <span class="bbn-left-sspace" v-html="render ? render(d) : d[sourceText]" ></span> </label> <br v-if="!vertical && step && ((idx+1) % step === 0)"> <div v-if="(source[idx+1] !== undefined) && !!separator" :class="{ 'bbn-w-100': vertical, 'bbn-iblock': !vertical }" v-html="separator" ></div> </div> </div> </div>`;script.setAttribute('id','bbn-tpl-component-radio');script.setAttribute('type','text/x-template');document.body.insertAdjacentElement('beforeend',script);(function(bbn){"use strict";Vue.component('bbn-radio',{mixins:[bbn.vue.basicComponent,bbn.vue.inputComponent,bbn.vue.localStorageComponent,bbn.vue.eventsComponent],props:{separator:{type:String},vertical:{type:Boolean,default:false},step:{type:Number},id:{type:String,default(){return bbn.fn.randomString(10,25);}},render:{type:Function},sourceText:{type:String,default:'text'},sourceValue:{type:String,default:'value'},source:{type:Array,default(){return[{text:bbn._("Yes"),value:1},{text:bbn._("No"),value:0}];}},modelValue:{type:[String,Boolean,Number],default:undefined}},model:{prop:'modelValue',event:'input'},methods:{changed(val,d,e){this.$emit('input',val);this.$emit('change',val,d,e);},getStyle(){if(this.step&&!this.vertical){return'display: grid; grid-template-columns: '+'auto '.repeat(this.step)+';';} else{return'';}}},beforeMount(){if(this.hasStorage){let v=this.getStorage();if(v&&(v!==this.modelValue)){this.changed(v);}}},watch:{modelValue(v){if(this.storage){if(v){this.setStorage(v);} else{this.unsetStorage()}}},}});})(bbn);})(bbn);
import {StringUtils} from "../node_modules/igv-utils/src/index.js" class Locus { constructor({chr, start, end}) { this.chr = chr this.start = start this.end = end } contains(locus) { return locus.chr === this.chr && locus.start >= this.start && locus.end <= this.end } overlaps(locus) { return locus.chr === this.chr && !(locus.end < this.start || locus.start > this.end) } extend(l) { if (l.chr !== this.chr) return this.start = Math.min(l.start, this.start) this.end = Math.max(l.end, this.end) } getLocusString() { if ('all' === this.chr) { return 'all' } else { const ss = StringUtils.numberFormatter(Math.floor(this.start) + 1) const ee = StringUtils.numberFormatter(Math.round(this.end)) return `${this.chr}:${ss}-${ee}` } } static fromLocusString(str) { if ('all' === str) { return new Locus({chr: 'all'}) } const parts = str.split(':') const chr = parts[0] const se = parts[1].split("-") const start = Number.parseInt(se[0].replace(/,/g, "")) - 1 const end = Number.parseInt(se[1].replace(/,/g, "")) return new Locus({chr, start, end}) } } export default Locus
(function () { 'use strict'; var app = angular.module('app'); // Collect the routes app.constant('routes', getRoutes()); // Configure the routes and route resolvers app.config(['$routeProvider', 'routes', routeConfigurator]); function routeConfigurator($routeProvider, routes) { routes.forEach(function (r) { $routeProvider.when(r.url, r.config); }); $routeProvider.otherwise({ redirectTo: '/' }); } // Define the routes function getRoutes() { return [ { url: '/', config: { templateUrl: 'app/dashboard/dashboard.html', title: 'dashboard', settings: { nav: 1, content: '<i class="fa fa-dashboard"></i> Dashboard' } } }, { url: '/admin', config: { title: 'admin', templateUrl: 'app/admin/admin.html', settings: { nav: 2, content: '<i class="fa fa-lock"></i> Admin' } }, access: { requiresLogin: true, requiredPermissions: ['Admin', 'UserManager'], permissionType: 'AtLeastOne' } }, { url: '/proposals', config: { title: 'proposals', templateUrl: 'app/proposal/proposals.html', settings: { nav: 3, content: '<i class="fa fa-sticky-note-o"></i> Proposals' } } }, { url: '/register', config: { title: 'register', templateUrl: 'app/authentication/register.html', settings: { } } }, { url: '/communities', config: { title: 'communities', templateUrl: 'app/communities/communities.html', settings: { nav: 4, content: '<i class="fa fa-group"></i> Communities' } } }, { url: '/login', config: { title: 'login', templateUrl: 'app/authentication/login.html', settings: { } } }, { url: '/register-admin', config: { title: 'register-admin', templateUrl: 'app/authentication/register-admin.html', settings: { } } }, { url: '/add-proposal', config: { title: 'add-proposal', templateUrl: 'app/proposal/add-proposal.html', settings: { } } }, { url: '/add-community', config: { title: 'add-community', templateUrl: 'app/communities/add-community.html', settings: { } } } ]; } })();
import Ember from 'ember'; import layout from './template'; export default Ember.Component.extend({ layout: layout, classNames: ['kit-canvas-scroller'], canvasStyle: Ember.computed('parentView.canvasStyle', function() { return this.get('parentView').get('canvasStyle'); }), numberOfItems: Ember.computed('parentView', function() { return this.$('.kit-canvas-content').children().length; }), willInsertElement: Ember.on('willInsertElement', function() { this.get('parentView').set('scroller', this); }), });
function test() { for(var i=1; i<3; i++) { console.log("inner i: " + i); } console.log("outer i: " + i); } function last() { const PI = 3.1415926; console.log(PI); } // test(); last();
'use strict'; module.exports = { controller: function (args) { this.config = _.merge({ salvar: _.noop, publicar: _.noop, descartar: _.noop, visualizar: _.noop, editar: _.noop }, args); }, view: function (ctrl) { var salvarView = ''; if (ctrl.config.salvar !== _.noop) { salvarView = m.component(require('cabecalho/salvar-button'), { salvar: ctrl.config.salvar, salvandoServico: ctrl.config.salvandoServico, caiuSessao: ctrl.config.caiuSessao, orgaoId: ctrl.config.orgaoId }); } var visualizarView = ''; if (ctrl.config.visualizar !== _.noop) { visualizarView = m.component(require('cabecalho/visualizar-button'), { visualizar: ctrl.config.visualizar, salvandoServico: ctrl.config.salvandoServico, caiuSessao: ctrl.config.caiuSessao }); } var publicarView = ''; if (ctrl.config.publicar !== _.noop) { publicarView = m.component(require('cabecalho/publicar-view'), { publicar: ctrl.config.publicar, descartar: ctrl.config.descartar, metadados: ctrl.config.cabecalho.metadados(), salvandoServico: ctrl.config.salvandoServico, caiuSessao: ctrl.config.caiuSessao, orgaoId: ctrl.config.orgaoId }); } var editarView = ''; if (ctrl.config.editar !== _.noop) { editarView = m.component(require('cabecalho/editar-button'), { editar: ctrl.config.editar }); } return m('#metadados', [ m.component(require('componentes/status-conexao'), { salvandoServico: ctrl.config.salvandoServico, caiuSessao: ctrl.config.caiuSessao }), salvarView, visualizarView, publicarView, editarView, ]); } };
/* The parser for parsing US's date format that begin with month's name. EX. - January 13 - January 13, 2012 - January 13 - 15, 2012 - Tuesday, January 13, 2012 */ var moment = require('moment'); require('moment-timezone'); var Parser = require('../parser').Parser; var ParsedResult = require('../../result').ParsedResult; var DAYS_OFFSET = { 'sunday': 0, 'sun': 0, 'monday': 1, 'mon': 1,'tuesday': 2, 'tue':2, 'wednesday': 3, 'wed': 3, 'thursday': 4, 'thur': 4, 'thu': 4,'friday': 5, 'fri': 5,'saturday': 6, 'sat': 6,} var regFullPattern = /(\W|^)((Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s*,?\s*)?(Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)\s*(([0-9]{1,2})(st|nd|rd|th)?\s*(to|\-)\s*)?([0-9]{1,2})(st|nd|rd|th)?(,)?(\s*[0-9]{4})(\s*BE)?(\W|$)/i; var regShortPattern = /(\W|^)((Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s*,?\s*)?(Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)\s*(([0-9]{1,2})(st|nd|rd|th)?\s*(to|\-)\s*)?([0-9]{1,2})(st|nd|rd|th)?([^0-9]|$)/i; exports.Parser = function ENMonthNameMiddleEndianParser(){ Parser.call(this); this.pattern = function() { return regShortPattern; } this.extract = function(text, ref, match, opt){ var result = new ParsedResult(); var impliedComponents = []; var date = null; var originalText = ''; var index = match.index; text = text.substr(index); var match = text.match(regFullPattern); if(match && text.indexOf(match[0]) == 0){ var text = match[0]; text = text.substring(match[1].length, match[0].length - match[14].length); index = index + match[1].length; originalText = text; text = text.replace(match[2], ''); text = text.replace(match[4], match[4]+' '); if(match[5]) text = text.replace(match[5],''); if(match[10]) text = text.replace(match[10],''); if(match[11]) text = text.replace(',',' '); if(match[13]){ var years = match[12]; years = ' ' + (parseInt(years) - 543); text = text.replace(match[13], ''); text = text.replace(match[12], years); } text = text.replace(match[9],parseInt(match[9])+''); date = moment(text,'MMMM DD YYYY'); if(!date) return null; result.start.assign('day', date.date()); result.start.assign('month', date.month() + 1); result.start.assign('year', date.year()); } else { match = text.match(regShortPattern); if(!match) return null; //Short Pattern (without years) var text = match[0]; text = text.substring(match[1].length, match[0].length - match[11].length); index = index + match[1].length; originalText = text; text = text.replace(match[2], ''); text = text.replace(match[4], match[4]+' '); if(match[4]) text = text.replace(match[5],''); date = moment(text,'MMMM DD'); if(!date) return null; //Find the most appropriated year impliedComponents.push('year') date.year(moment(ref).year()); var nextYear = date.clone().add(1, 'year'); var lastYear = date.clone().add(-1, 'year'); if( Math.abs(nextYear.diff(moment(ref))) < Math.abs(date.diff(moment(ref))) ){ date = nextYear; } else if( Math.abs(lastYear.diff(moment(ref))) < Math.abs(date.diff(moment(ref))) ){ date = lastYear; } result.start.assign('day', date.date()); result.start.assign('month', date.month() + 1); result.start.imply('year', date.year()); } //Day of week if(match[3]) { result.start.assign('weekday', DAYS_OFFSET[match[3].toLowerCase()]); } if (match[5]) { var endDay = parseInt(match[9]); var startDay = parseInt(match[6]); result.end = result.start.clone(); result.start.assign('day', startDay); result.end.assign('day', endDay); var endDate = date.clone(); date.date(startDay); endDate.date(endDay); } result.index = index; result.text = originalText; result.ref = ref; result.tags['ENMonthNameMiddleEndianParser'] = true; return result; } }
'use strict'; import React, {PureComponent} from 'react'; import {StyleSheet, View, Text} from 'react-native'; import withMaterialTheme from './styles/withMaterialTheme'; import {withMeasurementForwarding} from './util'; import * as typo from './styles/typo'; import shades from './styles/shades'; /** * Section heading */ class Subheader extends PureComponent { static defaultProps = { inset: false, lines: 1, }; render() { const { materialTheme, style, textStyle, inset, text, lines, secondary, color: colorOverride, dark, light, ...textProps } = this.props; let color; if ( colorOverride ) { color = colorOverride; } else if ( dark || light ) { const theme = dark ? 'dark' : 'light'; if ( secondary ) color = shades[theme].secondaryText; else color = shades[theme].primaryText; } else { if ( secondary ) color = materialTheme.text.secondaryColor; else color = materialTheme.text.primaryColor; } return ( <View ref={this._setMeasureRef} style={[ styles.container, inset && styles.inset, style, styles.containerOverrides ]}> <Text {...textProps} numberOfLines={lines} style={[ styles.text, textStyle, {color} ]}> {text} </Text> </View> ); } } export default withMaterialTheme(withMeasurementForwarding(Subheader)); const styles = StyleSheet.create({ container: { height: 48, paddingHorizontal: 16, }, containerOverrides: { flexDirection: 'row', alignItems: 'center', }, inset: { paddingRight: 16, paddingLeft: 72, }, text: { ...typo.fontMedium, fontSize: 14, }, });
import { onChange, getBits } from '../state' import { inputWidth, centerInputs } from './inputs' const $bits = document.getElementById('bits') const setBitsWidth = width => { $bits.style.width = inputWidth(width) centerInputs() } const setBitsValue = value => { setBitsWidth(value.length) $bits.value = value } $bits.addEventListener('input', ({ target: { value } }) => { setBits(value) }, false) $bits.addEventListener('keydown', ({ keyCode }) => { if (keyCode === 13) { // On Enter setBitsValue(getBits()) } }, false) const { setBits } = onChange(() => { setBitsValue(getBits()) })
var plugin = require("./plugin"); module.exports = function(PluginHost) { var app = PluginHost.owner; /** * used like so: * --external-aliases privateapi,privateAPI,hiddenAPI * or * -ea privateapi,privateAPI */ app.options.addDeclaration({ name: 'external-aliases', short: 'ea' }); /** * used like so: * --internal-aliases publicapi * or * -ia publicapi */ app.options.addDeclaration({ name: 'internal-aliases', short: 'ia' }); app.converter.addComponent('internal-external', plugin.InternalExternalPlugin); };
var gulp = require('gulp'), plugins = require('gulp-load-plugins')(), Karma = require('karma').Server; var paths = { scripts: { src: ['src/**/*.js'], dest: 'dist', file: 'mention.js' }, styles: { src: ['src/**/*.scss'], dest: 'dist', file: 'mention.css' }, example: { scripts: { src: ['example/**/*.es6.js'], dest: 'example', file: 'example.js' }, styles: { src: ['example/**/*.scss'], dest: 'example' } } }; gulp.task('default', ['scripts']); gulp.task('example', ['scripts:example', 'styles:example']); gulp.task('watch', function(){ gulp.watch(paths.scripts.src, 'scripts'); gulp.watch(paths.styles.src, 'styles'); }); gulp.task('watch:example', function(){ gulp.watch(paths.example.scripts.src, 'scripts:example'); gulp.watch(paths.example.styles.src, 'styles:example'); }); gulp.task('scripts', scripts(paths.scripts)); gulp.task('scripts:example', scripts(paths.example.scripts)); function scripts(path, concat) { return function() { return gulp.src(path.src) .pipe(plugins.sourcemaps.init()) .pipe(plugins.babel()) .pipe(plugins.angularFilesort()) .pipe(plugins.concat(path.file)) .pipe(gulp.dest(path.dest)) .pipe(plugins.uglify({ mangle: false })) .pipe(plugins.extReplace('.min.js')) .pipe(gulp.dest(path.dest)) .pipe(plugins.sourcemaps.write('.')); } } gulp.task('styles', styles(paths.styles)); gulp.task('styles:example', styles(paths.example.styles)); function styles(path) { return function() { return gulp.src(path.src) .pipe(plugins.sourcemaps.init()) .pipe(plugins.sass()) .pipe(gulp.dest(path.dest)) .pipe(plugins.sourcemaps.write('.')); } } gulp.task('karma', karma()); gulp.task('watch:karma', karma({ singleRun: false, autoWatch: true })); function karma (opts) { opts = opts || {}; opts.configFile = __dirname + '/karma.conf.js'; return function (done) { return new Karma(opts, done).start(); } }
import { StyleSheet } from 'react-native' const s = StyleSheet.create({ flexRowAround: { flexDirection: 'row', justifyContent: 'space-around', }, dot: { height: 7, width: 7, borderRadius: 3.5, }, green: { color: '#50d2c2', }, flexWrap: { flexWrap: 'wrap', }, textCenter: { textAlign: 'center', }, flex: { flex: 1, }, activeMonth:{ backgroundColor: '#50d2c2', borderRadius: 5 }, justifyCenter: { justifyContent: 'center', }, alignCenter: { alignItems: 'center', }, row: { flexDirection: 'row', }, column: { flexDirection: 'column', }, flexAround: { justifyContent: 'space-around', }, flexBetween: { justifyContent: 'space-between', }, activeWeek: { backgroundColor: '#50d2c2', }, activeCalender: { backgroundColor: '#fff', }, pTop: { paddingTop: 13, paddingBottom: 5, }, pBottom: { paddingBottom: 13, }, p: { paddingTop: 13, paddingBottom: 13, }, weekView: { backgroundColor: '#f8f8f8', }, calenderView: { backgroundColor: '#50d2c2', }, disabledMonth: { color: '#9be5db', }, white: { color: '#fff', }, backWhite: { backgroundColor: '#fff', }, }); export default s export const setHeight = height => ({ height }); export const setWidth = width => ({ width }); export const setPaddingTop = paddingTop => ({ paddingTop }); export const setPaddingBottom = paddingBottom => ({ paddingBottom }); export const setPaddingLeft = paddingLeft => ({ paddingLeft }); export const setPaddingRight = paddingRight => ({ paddingRight }); export const setFontSize = fontSize => ({ fontSize }); export const setFlex = flex => ({ flex }); export const setColor = color => ({ color }); export const setBackGroundColor = backgroundColor => ({ backgroundColor }); export const setBorderColor = borderColor => ({ borderColor }); export const setPosition = position => ({ position }); export const setBottom = bottom => ({ bottom }); export const setLeft = left => ({ left }); export const setRight = right => ({ right }); export const setTop = top => ({ top }); export const setMarginTop = marginTop => ({ marginTop }); export const setMarginBottom = marginBottom => ({ marginBottom }); export const setMarginLeft = marginLeft => ({ marginLeft }); export const setMarginRight = marginRight => ({ marginRight }); export const setPadding = function() { switch (arguments.length) { case 1: return { paddinTop: arguments[0] } case 2: return { paddingTop: arguments[0], paddingRight: arguments[1] } case 3: return { paddingTop: arguments[0], paddingRight: arguments[1], paddingBottom: arguments[2] } case 4: return { paddingTop: arguments[0], paddingRight: arguments[1], paddingBottom: arguments[2], paddingLeft: arguments[3] } default: return { padding: arguments[0] } } } export const setMargin = function() { switch (arguments.length) { case 1: return { paddinTop: arguments[0] } case 2: return { marginTop: arguments[0], marginRight: arguments[1] } case 3: return { marginTop: arguments[0], marginRight: arguments[1], marginBottom: arguments[2] } case 4: return { marginTop: arguments[0], marginRight: arguments[1], marginBottom: arguments[2], marginLeft: arguments[3] } default: return { margin: arguments[0] } } }
exports.CLI = require(__dirname + '/lib/cli'); exports.Events = require(__dirname + '/lib/events');
'use strict'; !function($) { /** * OffCanvas module. * @module foundation.offcanvas * @requires foundation.util.keyboard * @requires foundation.util.mediaQuery * @requires foundation.util.triggers * @requires foundation.util.motion */ class OffCanvas { /** * Creates a new instance of an off-canvas wrapper. * @class * @fires OffCanvas#init * @param {Object} element - jQuery object to initialize. * @param {Object} options - Overrides to the default plugin settings. */ constructor(element, options) { this.$element = element; this.options = $.extend({}, OffCanvas.defaults, this.$element.data(), options); this.$lastTrigger = $(); this.$triggers = $(); this._init(); this._events(); Foundation.registerPlugin(this, 'OffCanvas') Foundation.Keyboard.register('OffCanvas', { 'ESCAPE': 'close' }); } /** * Initializes the off-canvas wrapper by adding the exit overlay (if needed). * @function * @private */ _init() { var id = this.$element.attr('id'); this.$element.attr('aria-hidden', 'true'); this.$element.addClass(`is-transition-${this.options.transition}`); // Find triggers that affect this element and add aria-expanded to them this.$triggers = $(document) .find('[data-open="'+id+'"], [data-close="'+id+'"], [data-toggle="'+id+'"]') .attr('aria-expanded', 'false') .attr('aria-controls', id); // Add an overlay over the content if necessary if (this.options.contentOverlay === true) { var overlay = document.createElement('div'); var overlayPosition = $(this.$element).css("position") === 'fixed' ? 'is-overlay-fixed' : 'is-overlay-absolute'; overlay.setAttribute('class', 'js-off-canvas-overlay ' + overlayPosition); this.$overlay = $(overlay); if(overlayPosition === 'is-overlay-fixed') { $('body').append(this.$overlay); } else { this.$element.siblings('[data-off-canvas-content]').append(this.$overlay); } } this.options.isRevealed = this.options.isRevealed || new RegExp(this.options.revealClass, 'g').test(this.$element[0].className); if (this.options.isRevealed === true) { this.options.revealOn = this.options.revealOn || this.$element[0].className.match(/(reveal-for-medium|reveal-for-large)/g)[0].split('-')[2]; this._setMQChecker(); } if (!this.options.transitionTime === true) { this.options.transitionTime = parseFloat(window.getComputedStyle($('[data-off-canvas]')[0]).transitionDuration) * 1000; } } /** * Adds event handlers to the off-canvas wrapper and the exit overlay. * @function * @private */ _events() { this.$element.off('.zf.trigger .zf.offcanvas').on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': this.close.bind(this), 'toggle.zf.trigger': this.toggle.bind(this), 'keydown.zf.offcanvas': this._handleKeyboard.bind(this) }); if (this.options.closeOnClick === true) { var $target = this.options.contentOverlay ? this.$overlay : $('[data-off-canvas-content]'); $target.on({'click.zf.offcanvas': this.close.bind(this)}); } } /** * Applies event listener for elements that will reveal at certain breakpoints. * @private */ _setMQChecker() { var _this = this; $(window).on('changed.zf.mediaquery', function() { if (Foundation.MediaQuery.atLeast(_this.options.revealOn)) { _this.reveal(true); } else { _this.reveal(false); } }).one('load.zf.offcanvas', function() { if (Foundation.MediaQuery.atLeast(_this.options.revealOn)) { _this.reveal(true); } }); } /** * Handles the revealing/hiding the off-canvas at breakpoints, not the same as open. * @param {Boolean} isRevealed - true if element should be revealed. * @function */ reveal(isRevealed) { var $closer = this.$element.find('[data-close]'); if (isRevealed) { this.close(); this.isRevealed = true; this.$element.attr('aria-hidden', 'false'); this.$element.off('open.zf.trigger toggle.zf.trigger'); if ($closer.length) { $closer.hide(); } } else { this.isRevealed = false; this.$element.attr('aria-hidden', 'true'); this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'toggle.zf.trigger': this.toggle.bind(this) }); if ($closer.length) { $closer.show(); } } } /** * Stops scrolling of the body when offcanvas is open on mobile Safari and other troublesome browsers. * @private */ _stopScrolling(event) { return false; } /** * Opens the off-canvas menu. * @function * @param {Object} event - Event object passed from listener. * @param {jQuery} trigger - element that triggered the off-canvas to open. * @fires OffCanvas#opened */ open(event, trigger) { if (this.$element.hasClass('is-open') || this.isRevealed) { return; } var _this = this; if (trigger) { this.$lastTrigger = trigger; } if (this.options.forceTo === 'top') { window.scrollTo(0, 0); } else if (this.options.forceTo === 'bottom') { window.scrollTo(0,document.body.scrollHeight); } /** * Fires when the off-canvas menu opens. * @event OffCanvas#opened */ _this.$element.addClass('is-open') this.$triggers.attr('aria-expanded', 'true'); this.$element.attr('aria-hidden', 'false') .trigger('opened.zf.offcanvas'); // If `contentScroll` is set to false, add class and disable scrolling on touch devices. if (this.options.contentScroll === false) { $('body').addClass('is-off-canvas-open').on('touchmove', this._stopScrolling); } if (this.options.contentOverlay === true) { this.$overlay.addClass('is-visible'); } if (this.options.closeOnClick === true && this.options.contentOverlay === true) { this.$overlay.addClass('is-closable'); } if (this.options.autoFocus === true) { this.$element.one(Foundation.transitionend(this.$element), function() { _this.$element.find('a, button').eq(0).focus(); }); } if (this.options.trapFocus === true) { this.$element.siblings('[data-off-canvas-content]').attr('tabindex', '-1'); Foundation.Keyboard.trapFocus(this.$element); } } /** * Closes the off-canvas menu. * @function * @param {Function} cb - optional cb to fire after closure. * @fires OffCanvas#closed */ close(cb) { if (!this.$element.hasClass('is-open') || this.isRevealed) { return; } var _this = this; _this.$element.removeClass('is-open'); this.$element.attr('aria-hidden', 'true') /** * Fires when the off-canvas menu opens. * @event OffCanvas#closed */ .trigger('closed.zf.offcanvas'); // If `contentScroll` is set to false, remove class and re-enable scrolling on touch devices. if (this.options.contentScroll === false) { $('body').removeClass('is-off-canvas-open').off('touchmove', this._stopScrolling); } if (this.options.contentOverlay === true) { this.$overlay.removeClass('is-visible'); } if (this.options.closeOnClick === true && this.options.contentOverlay === true) { this.$overlay.removeClass('is-closable'); } this.$triggers.attr('aria-expanded', 'false'); if (this.options.trapFocus === true) { this.$element.siblings('[data-off-canvas-content]').removeAttr('tabindex'); Foundation.Keyboard.releaseFocus(this.$element); } } /** * Toggles the off-canvas menu open or closed. * @function * @param {Object} event - Event object passed from listener. * @param {jQuery} trigger - element that triggered the off-canvas to open. */ toggle(event, trigger) { if (this.$element.hasClass('is-open')) { this.close(event, trigger); } else { this.open(event, trigger); } } /** * Handles keyboard input when detected. When the escape key is pressed, the off-canvas menu closes, and focus is restored to the element that opened the menu. * @function * @private */ _handleKeyboard(e) { Foundation.Keyboard.handleKey(e, 'OffCanvas', { close: () => { this.close(); this.$lastTrigger.focus(); return true; }, handled: () => { e.stopPropagation(); e.preventDefault(); } }); } /** * Destroys the offcanvas plugin. * @function */ destroy() { this.close(); this.$element.off('.zf.trigger .zf.offcanvas'); this.$overlay.off('.zf.offcanvas'); Foundation.unregisterPlugin(this); } } OffCanvas.defaults = { /** * Allow the user to click outside of the menu to close it. * @option * @type {boolean} * @default true */ closeOnClick: true, /** * Adds an overlay on top of `[data-off-canvas-content]`. * @option * @type {boolean} * @default true */ contentOverlay: true, /** * Enable/disable scrolling of the main content when an off canvas panel is open. * @option * @type {boolean} * @default true */ contentScroll: true, /** * Amount of time in ms the open and close transition requires. If none selected, pulls from body style. * @option * @type {number} * @default 0 */ transitionTime: 0, /** * Type of transition for the offcanvas menu. Options are 'push', 'detached' or 'slide'. * @option * @type {string} * @default push */ transition: 'push', /** * Force the page to scroll to top or bottom on open. * @option * @type {?string} * @default null */ forceTo: null, /** * Allow the offcanvas to remain open for certain breakpoints. * @option * @type {boolean} * @default false */ isRevealed: false, /** * Breakpoint at which to reveal. JS will use a RegExp to target standard classes, if changing classnames, pass your class with the `revealClass` option. * @option * @type {?string} * @default null */ revealOn: null, /** * Force focus to the offcanvas on open. If true, will focus the opening trigger on close. * @option * @type {boolean} * @default true */ autoFocus: true, /** * Class used to force an offcanvas to remain open. Foundation defaults for this are `reveal-for-large` & `reveal-for-medium`. * @option * @type {string} * @default reveal-for- * @todo improve the regex testing for this. */ revealClass: 'reveal-for-', /** * Triggers optional focus trapping when opening an offcanvas. Sets tabindex of [data-off-canvas-content] to -1 for accessibility purposes. * @option * @type {boolean} * @default false */ trapFocus: false } // Window exports Foundation.plugin(OffCanvas, 'OffCanvas'); }(jQuery);
var Dispatcher = require('flux').Dispatcher; var assign = require('object-assign') var AppDispatcher = assign(new Dispatcher(), { handleViewAction: function(action) { this.dispatch({ actionType: 'VIEW_ACTION', action: action }); }, handleServerAction: function(action) { this.dispatch({ actionType: 'SERVER_ACTION', action: action }); } }); module.exports = AppDispatcher;
$(document).ready(function(){ //enable the return time input and dropdown $("#round").change(function() { if(this.checked) { console.log("Return data field open!"); $("#rD").removeClass('ui disabled input').addClass('ui input'); $("#rY").removeClass('ui disabled input').addClass('ui input'); $("#retMonth").removeClass('ui disabled dropdown').addClass('ui dropdown'); } else { console.log("Return data field close!"); $("#rD").removeClass('ui input').addClass('ui disabled input'); $("#rY").removeClass('ui input').addClass('ui disabled input'); $("#retMonth").removeClass('ui dropdown').addClass('ui disabled dropdown'); } }); //check if the input is a valid format function validateForm() { numdays = [31,28,31,30,31,30,31,31,30,31,30,31]; namemonth = ["January","Feburary","March","April","May","June","July","August","September","October","November","December"]; if ($("#dpYear").val() == "" || $("#dpMonth").val() == "" || $("#dpDay").val() == "" || $("#origin").val() == "" || $("#des").val() == "" || $('#num').val() == "" || $("#email").val() == "" || $("#waiting").val() == "") { console.log("not fill in all the blanks") alert("Please fill in all fields"); return false; } if ($("#dpYear").val().length != 4 || $("#dpDay").val().length != 2) { console.log("invalid departure date or year") alert("Please enter valid departure date or year in the format of DD and YYYY.") return false; } if ($("#origin").val().length != 3 || $("#des").val().length != 3 || /^[a-zA-Z]+$/.test($("#origin").val()) == false || /^[a-zA-Z]+$/.test($("#des").val()) == false ) { console.log("invalid input for destination or origin"); alert("Please enter valid airport code.") return false; } if ($("#origin").val() == $("#des").val()) { console.log("same origin and destination"); alert("You cannot enter same value for origin and destination"); return false; } console.log("fields valid!") var today = new Date(); if (parseInt($("#dpYear").val()) < today.getFullYear()) { alert("You cannot check past ticket's value"); return false; } else { if (parseInt($("#dpYear").val()) == today.getFullYear()) { if (parseInt($("#dpMonth").val()) < today.getMonth()+1 ) { alert("You cannot check past ticket's value"); return false; } else { if (parseInt($("#dpMonth").val()) == today.getMonth()+1 ) { if (parseInt($("#dpDay").val()) < today.getDate()) { alert("You cannot check past ticket's value"); return false; } } } } } console.log("departure date valid!") if ($("#round").is(':checked')) { console.log("roundtrip checked!") if ($("#retYear").val() == "" || $("#retMonth").val() == "" || $("#retDay").val() == "" ) { alert("please enter return date"); return false; } if ($("#retYear").val().length != 4 || $("#retDay").val().length != 2) { console.log("invalid return date or year") alert("Please enter valid return date or year in the format of DD and YYYY.") return false; } if (parseInt($("#retYear").val()) < parseInt($("#dpYear").val())) { alert("Return date cannot be before departure date."); return false; } else { if (parseInt($("#retYear").val()) == parseInt($("#dpYear").val())) { if (parseInt($("#retMonth").val()) < parseInt($("#dpMonth").val()) ) { alert("Return date cannot be before departure date."); return false; } else { if (parseInt($("#retMonth").val()) == parseInt($("#dpMonth").val()) ) { if (parseInt($("#retDay").val()) < parseInt($("#dpDay").val())) { alert("Return date cannot be before departure date."); return false; } } } } } } console.log("return date valid!") if ($("#dpMonth").val() == "2" && parseInt($("#dpYear".val()))%4 == 0 && parseInt($("#dpYear".val()))%100 != 0) { if (parseInt($("#dpDay".val())) > 29) { alert(namemonth[parseInt($("#dpMonth").val())-1]+" does not have more than 29 days"); return false; } } else { var m = parseInt($("#dpMonth").val()); if ( parseInt($("#dpDay").val()) > numdays[m-1]) { alert(namemonth[m-1]+" does not have more than "+numdays[m-1]+" days"); return false; } } return true; } //send the user data to server //not using the form submit function as the it will not reveive the data $("#sub").click(function() { if (validateForm()) { var rq = {}; rq.origin = $("#origin").val(); rq.destination = $("#des").val(); rq.dpdate = $("#dpYear").val()+'-'+$("#dpMonth").val()+'-'+$("#dpDay").val(); rq.waiting = parseInt(parseFloat($("#waiting").val())*60); rq.num = parseInt($('#num').val()); rq.email = $("#email").val(); rq.round = 0; if ($("#round").is(':checked')) { rq.round = 1; rq.retdate = $("#retYear").val()+'-'+$("#retMonth").val()+'-'+$("#retDay").val(); } console.log("data post to server formed!"); $.ajax({ type: "POST", url: "/user", dataType: 'json', contentType: 'application/json', data: JSON.stringify(rq), success: function(data) { alert("Data goes into our system!"); }, error: function(error) { console.log(error); alert("Unable to send!"); } }); } }); });
(function(){ angular.module('list-products', []) .directive('productInfo', function() { return { restrict: 'E', templateUrl: 'partials/product-info.html' } }) .directive('productForm', function() { return { restrict: 'E', templateUrl: 'partials/product-form.html', controller: function() { this.review = {}; this.item = {mark:{}}; this.addReview = function(item) { item.reviews.push(this.review); this.review = {}; }; }, controllerAs: 'reviewCtrl', scope: { items: "=", marks: "=" } }; }) .directive('productPanels', function() { return { restrict: 'E', templateUrl: 'partials/product-panels.html', controller: function(){ this.tab = 1; this.selectTab = function(setTab) { this.tab = setTab; }; this.isSelected = function(checkTab) { return checkTab === this.tab; }; }, controllerAs: 'panelCtrl', scope: { items: "=", marks: "=" } }; }); })();
angular.module('material.animations') .directive('inkRipple', [ '$materialInkRipple', InkRippleDirective ]) .factory('$materialInkRipple', [ '$window', '$$rAF', '$materialEffects', '$timeout', InkRippleService ]); function InkRippleDirective($materialInkRipple) { return function(scope, element, attr) { if (attr.inkRipple == 'checkbox') { $materialInkRipple.attachCheckboxBehavior(element); } else { $materialInkRipple.attachButtonBehavior(element); } }; } function InkRippleService($window, $$rAF, $materialEffects, $timeout) { // TODO fix this. doesn't support touch AND click devices (eg chrome pixel) var hasTouch = !!('ontouchend' in document); var POINTERDOWN_EVENT = hasTouch ? 'touchstart' : 'mousedown'; var POINTERUP_EVENT = hasTouch ? 'touchend touchcancel' : 'mouseup mouseleave'; return { attachButtonBehavior: attachButtonBehavior, attachCheckboxBehavior: attachCheckboxBehavior, attach: attach }; function attachButtonBehavior(element) { return attach(element, { mousedown: true, center: false, animationDuration: 350, mousedownPauseTime: 175, animationName: 'inkRippleButton', animationTimingFunction: 'linear' }); } function attachCheckboxBehavior(element) { return attach(element, { mousedown: true, center: true, animationDuration: 300, mousedownPauseTime: 180, animationName: 'inkRippleCheckbox', animationTimingFunction: 'linear' }); } function attach(element, options) { // Parent element with noink attr? Abort. if (element.controller('noink')) return angular.noop; options = angular.extend({ mousedown: true, hover: true, focus: true, center: false, animationDuration: 300, mousedownPauseTime: 150, animationName: '', animationTimingFunction: 'linear' }, options || {}); var rippleContainer; var node = element[0]; if (options.mousedown) { listenPointerDown(true); } // Publish self-detach method if desired... return function detach() { listenPointerDown(false); if (rippleContainer) { rippleContainer.remove(); } }; function listenPointerDown(shouldListen) { element[shouldListen ? 'on' : 'off'](POINTERDOWN_EVENT, onPointerDown); } function rippleIsAllowed() { return !Util.isParentDisabled(element); } function createRipple(left, top, positionsAreAbsolute) { var rippleEl = angular.element('<div class="material-ripple">') .css($materialEffects.ANIMATION_DURATION, options.animationDuration + 'ms') .css($materialEffects.ANIMATION_NAME, options.animationName) .css($materialEffects.ANIMATION_TIMING, options.animationTimingFunction) .on($materialEffects.ANIMATIONEND_EVENT, function() { rippleEl.remove(); }); if (!rippleContainer) { rippleContainer = angular.element('<div class="material-ripple-container">'); element.append(rippleContainer); } rippleContainer.append(rippleEl); var containerWidth = rippleContainer.prop('offsetWidth'); if (options.center) { left = containerWidth / 2; top = rippleContainer.prop('offsetHeight') / 2; } else if (positionsAreAbsolute) { var elementRect = node.getBoundingClientRect(); left -= elementRect.left; top -= elementRect.top; } var css = { 'background-color': $window.getComputedStyle(rippleEl[0]).color || $window.getComputedStyle(node).color, 'border-radius': (containerWidth / 2) + 'px', left: (left - containerWidth / 2) + 'px', width: containerWidth + 'px', top: (top - containerWidth / 2) + 'px', height: containerWidth + 'px' }; css[$materialEffects.ANIMATION_DURATION] = options.fadeoutDuration + 'ms'; rippleEl.css(css); return rippleEl; } function onPointerDown(ev) { if (!rippleIsAllowed()) return; var rippleEl = createRippleFromEvent(ev); var ripplePauseTimeout = $timeout(pauseRipple, options.mousedownPauseTime, false); rippleEl.on('$destroy', cancelRipplePause); // Stop listening to pointer down for now, until the user lifts their finger/mouse listenPointerDown(false); element.on(POINTERUP_EVENT, onPointerUp); function onPointerUp() { cancelRipplePause(); rippleEl.css($materialEffects.ANIMATION_PLAY_STATE, 'running'); element.off(POINTERUP_EVENT, onPointerUp); listenPointerDown(true); } function pauseRipple() { rippleEl.css($materialEffects.ANIMATION_PLAY_STATE, 'paused'); } function cancelRipplePause() { $timeout.cancel(ripplePauseTimeout); } function createRippleFromEvent(ev) { ev = ev.touches ? ev.touches[0] : ev; return createRipple(ev.pageX, ev.pageY, true); } } } }
var boletesPinya = $.merge($.merge($.merge($("#cDB").find("path"), $("#cB4").find("path")), $("#cB3").find("path")), $("#cB2").find("path")); var boletesTronc = $.merge($.merge($("#cB4").find("path"), $("#cB3").find("path")), $("#cB2").find("path")); var usedTweets = {}; $(document).ready(function () { $.each(boletesPinya, function (i, e) { $(e).tooltipster({ delay: 100, maxWidth: 500, speed: 300, interactive: true, content: '', contentAsHTML: true, animation: 'grow', trigger: 'custom', contentCloning: false }); }); }); function initTweets() { var path = EMOCIO.properties[lastEmotionPlayed].name + ".php"; $.ajax({ type: 'GET', url: path, success: function (data) { var tweets = null; var text, user, hashtag, ttContent, img; tweets = JSON.parse(data); $(boletesPinya).shuffle().each(function (i, e) { var cTweet = tweets.statuses[i]; if (typeof cTweet === 'undefined') return false; var content = buildContent(cTweet); if (content !== false) { $(e).tooltipster('content', content); themesAndEvents(e); } }); }, error: function (res) { alert("Error finding tweets"); } }); } function actualitzarTweets() { var path = EMOCIO.properties[lastEmotionPlayed].name + ".php"; resetTooltips(); $.ajax({ type: 'GET', url: path, success: function (data) { var tweets = null; var text, img, user, hashtag, ttContent, url; tweets = JSON.parse(data); var boletes = boletesPinya; if (fase >= FASE.Tercos) boletes = boletesTronc; $(boletes).shuffle().each(function (i, e) { var currentTweet = tweets.statuses[i]; if (typeof currentTweet === 'undefined') return false; var content = buildContent(currentTweet); if (content !== false) { $(e).tooltipster('content', content); themesAndEvents(e); } }); }, error: function (res) { alert("Error finding tweets"); } }); } function buildContent(info) { var tweet = info; if (DictContainsValue(usedTweets, tweet.id_str) || typeof tweet === 'undefined') { usedTweets[tweet.id_str] = usedTweets[tweet.id_str] + 1; return false; } usedTweets[tweet.id_str] = 1; var text = tweet.full_text; var user = "@" + tweet.user.screen_name + ": "; var img = ''; var url = 'href="https://twitter.com/statuses/' + tweet.id_str + '" target="_blank"'; if ((typeof tweet.entities.media !== "undefined") && (tweet.entities.media !== null)) { var media = tweet.entities.media; img = '<div class="row">' + '<div class="col">' + '<img style="max-width: 75%; height: auto;" class="rounded mx-auto d-block" src=\'' + media[0].media_url_https + '\'/>' + '</div></div>'; text = text.replace(' ' + tweet.entities.media[0].url, ''); } return $('<a '+ url +'>' + img + '<div class="row"><div class="col text-left"><p style="margin-bottom: 0 !important;"><b>' + user + '</b>' + text + '</p></div></div></a>'); } function themesAndEvents(e) { var theme = 'tooltipster-' + EMOCIO.properties[lastEmotionPlayed].name.toString(); $(e).tooltipster('option', 'theme', theme); $(e).tooltipster('option', 'trigger', 'click'); $(e).mouseenter(function () { if (lastEmotionPlayed !== null) { $(this).css("fill", EMOCIO.properties[lastEmotionPlayed].color).css("cursor", "pointer"); $(this).addClass("pathHover"); } }).mouseleave(function () { if (lastEmotionPlayed !== null) { var gradient = "url(#gradient" + EMOCIO.properties[lastEmotionPlayed].name.toString().charAt(0).toUpperCase() + EMOCIO.properties[lastEmotionPlayed].name.substr(1) + ")"; $(this).css("fill", gradient).css("cursor", "default"); $(this).removeClass("pathHover"); } }); } function resetTooltips() { usedTweets = {}; $.each(boletesPinya, function (i, e) { $(e).tooltipster('destroy'); $(e).off(); $(e).unbind("mouseenter"); $(e).unbind("mouseleave"); }); $.each(boletesPinya, function (i, e) { $(e).tooltipster({ delay: 100, maxWidth: 500, speed: 300, interactive: true, content: '', contentAsHTML: true, animation: 'grow', trigger: 'custom', contentCloning: false }); }); }
var sc1 = { //funhouse mirror setup:function(){ // videoSetup(); tree = new TREE(); tree.generate({ joints: [5,3,1,10], divs: [1], start: [0,0,2,0], angles: [0,Math.PI/2,1], length: [20,15,4,1], rads: [1,2,1,3], width: [1,2,2,1] }); scene.add(tree); tree.position.y=-50; console.log(tree); var ball = new THREE.SphereGeometry(15,15,15); var ball2 = new THREE.Geometry(); tree.xform(tree.makeInfo([ [0,0,"all"],{ballGeo:ball,ballGeo2:ball2}, ]),tree.setGeo); tree.xform(tree.makeInfo([ [0,0,"all"],{ty:-15}, ]),function(obj,args){obj.children[0].children[0].position.y=7.5;}); // scene.add(tree.makeTubes({minWidth:1,func:function(t){return Math.sin(t)*2}})); }, draw:function(time){ time=time*3; tree.position.y = -40+Math.sin(omouseY*Math.PI*4)*3; tree.xform(tree.makeInfo([ [0,0,[1,5]],{rz:omouseX,ry:omouseY,sc:.9}, //legs [0,0,0,[0,1],1],{rz:Math.PI/2}, [0,0,0,[0,1],1],{ry:omouseX*3}, [0,0,0,[0,1],2],{rx:omouseY*3}, //feet [0,0,0,[0,1],0,0,0],{rz:0}, [0,0,0,[0,1],0,0,0],{rx:omouseY*3}, [0,0,[0,4],[0,1],0],{ty:-10}, [0,0,[1,4],[0,1],[1,2]],{rz:mouseY,freq:1,offMult:.2,off:time}, //fingers [0,0,[1,4],[0,1],0,0,0,[0,2],"all"],{rz:0,freq:1,offMult:.2,off:time}, [0,0,[1,4],[0,1],0,0,0],{rz:0,freq:1,offMult:.3,off:time+.2}, //feet [0,0,0,[0,1],0,0,0,[0,2],"all"],{ry:0,rz:omouseY*.1,sc:.9}, [0,0,0,0,0,0,0,[0,2],0],{sc:2,ry:-2*omouseY+1.5,rz:1}, [0,0,0,1,0,0,0,[0,2],0],{sc:2,ry:-2*omouseY-1.5,rz:1}, //toes [0,0,0,0,0,0,0,[0,2],0],{sc:2,ry:0,freq:1,offMult:.2 ,offsetter2:.5}, [0,0,0,1,0,0,0,[0,2],0],{sc:2,ry:Math.PI-.3,freq:1,offMult:.2,offsetter2:.5}, ]),tree.transform); } }
'use strict'; // 頑シミュさんの装飾品検索の結果と比較しやすくする function simplifyDecombs(decombs) { return decombs.map(decomb => { let torsoUp = Object.keys(decomb).map(part => decomb[part]).some(comb => { if (comb == null) return false; return comb.skills['胴系統倍加'] ? true : false; }); let names = []; Object.keys(decomb).forEach(part => { let comb = decomb[part]; let decos = comb ? comb.decos : []; if (torsoUp && part === 'body') decos = decos.map(deco => deco += '(胴)'); names = names.concat(decos); }); return names.sort().join(','); }); } exports.simplifyDecombs = simplifyDecombs;
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "billbee");
// Generated by CoffeeScript 1.6.3 /*! @author Branko Vukelic <[email protected]> @license MIT */ var _this = this; if (typeof define !== 'function' || !define.amd) { this.require = function(dep) { return (function() { switch (dep) { case 'jquery': return _this.jQuery; default: return null; } })() || (function() { throw new Error("Unmet dependency " + dep); })(); }; this.define = function(factory) { return _this.ribcage.utils.deserializeForm = factory(_this.require); }; } define(function(require) { var $; $ = require('jquery'); $.deserializeForm = function(form, data) { form = $(form); form.find(':input').each(function() { var currentValue, input, name, type; input = $(this); name = input.attr('name'); type = input.attr('type'); currentValue = input.val(); if (!name) { return; } switch (type) { case 'checkbox': return input.prop('checked', data[name] === 'on'); case 'radio': return input.prop('checked', data[name] === currentValue); default: return input.val(data[name]); } }); return form; }; $.fn.deserializeForm = function(data) { return $.deserializeForm(this, data); }; return $.deserializeForm; });
'use strict' module.exports = function (config) { if (!process.env.COOKING_PATH) { return } const rootPath = process.env.COOKING_PATH.split(',') config.resolve = config.resolve || {} config.resolveLoader = config.resolveLoader || {} config.resolve.modules = (config.resolve.root || []).concat(rootPath) config.resolveLoader.modules = (config.resolveLoader.root || []).concat(rootPath) }
var xhrGet = function (url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onload = callback; xhr.send(); };
/*jslint browser: true*/ /*global Tangram, gui */ map = (function () { 'use strict'; var locations = { 'Yangon': [16.8313077,96.2187007,7] }; var map_start_location = locations['Yangon']; /*** Map ***/ var map = L.map('map', {"keyboardZoomOffset" : .05, maxZoom: 20 } ); var layer = Tangram.leafletLayer({ scene: 'cinnabar-style-more-labels.yaml?r=2', attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | &copy; OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>' }); window.layer = layer; var scene = layer.scene; window.scene = scene; // setView expects format ([lat, long], zoom) map.setView(map_start_location.slice(0, 3), map_start_location[2]); function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); } /***** Render loop *****/ function addGUI () { // Link to edit in OSM - hold 'e' and click } // Feature selection function initFeatureSelection () { // Selection info shown on hover var selection_info = document.createElement('div'); selection_info.setAttribute('class', 'label'); selection_info.style.display = 'block'; // Show selected feature on hover scene.container.addEventListener('mousemove', function (event) { var pixel = { x: event.clientX, y: event.clientY }; scene.getFeatureAt(pixel).then(function(selection) { if (!selection) { return; } var feature = selection.feature; if (feature != null) { // console.log("selection map: " + JSON.stringify(feature)); var label = ''; if (feature.properties.name != null) { label = feature.properties.name; } if (label != '') { selection_info.style.left = (pixel.x + 5) + 'px'; selection_info.style.top = (pixel.y + 15) + 'px'; selection_info.innerHTML = '<span class="labelInner">' + label + '</span>'; scene.container.appendChild(selection_info); } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } }); // Don't show labels while panning if (scene.panning == true) { if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } }); // Show selected feature on hover scene.container.addEventListener('click', function (event) { var pixel = { x: event.clientX, y: event.clientY }; scene.getFeatureAt(pixel).then(function(selection) { if (!selection) { return; } var feature = selection.feature; if (feature != null) { // console.log("selection map: " + JSON.stringify(feature)); var label = ''; if (feature.properties != null) { // console.log(feature.properties); var obj = JSON.parse(JSON.stringify(feature.properties)); for (var x in feature.properties) { var val = feature.properties[x] label += "<span class='labelLine' key="+x+" value="+val+" onclick='setValuesFromSpan(this)'>"+x+" : "+val+"</span><br>" } } if (label != '') { selection_info.style.left = (pixel.x + 5) + 'px'; selection_info.style.top = (pixel.y + 15) + 'px'; selection_info.innerHTML = '<span class="labelInner">' + label + '</span>'; scene.container.appendChild(selection_info); } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } }); // Don't show labels while panning if (scene.panning == true) { if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } }); } window.addEventListener('load', function () { // Scene initialized layer.on('init', function() { addGUI(); //initFeatureSelection(); }); layer.addTo(map); }); return map; }());
var height = window.innerHeight; // console.log(height); var main = document.getElementById('main'); var btn = document.getElementById("btn"); main.style.height = height + 'px'; btn.style.top = (height-90) + 'px'; document.getElementById('usr_name').onkeydown = function(e) { e = e || event; if(e.keyCode === 13) { btn.click(); } }; btn.addEventListener("click", function() { var name = document.getElementById("usr_name").value; name = name.replace(/(^\s*)|(\s*$)/g, ""); if(name=='') { alert("请填写用户名哦!"); return false; } var url = window.location.href; var splited = url.split('/'); var roomID = splited[splited.length - 1]; ajax({ url: "/login/"+roomID, //请求地址 type: "POST", //请求方式 data: {new_topic:true,username: name}, //请求参数 dataType: "json", success: function (data) { data=JSON.parse(data); if(data.status==1){ //alert("登录成功"); window.location.href="/show"; } else if(data.status==0){ alert("已经有人登录了哦"); } // 此处放成功后执行的代码 }, fail: function (status) { // 此处放失败后执行的代码 } }); });
/* * default/mouse-push-button.js */ "use strict"; var Q = require('q'), Button = require('./../../button'); var MousePushButton = function (options) { Button.prototype.constructor.call(this, options); this.delay = options.delay > 0 ? options.delay : 0; this.g = null; if(typeof options.g === 'function') this.g = options.g; this.promisef = null; this.boundaries = { minX : 0, maxX : 0, minY : 0, maxY : 0 }; this.leftOrEnded = false; }; MousePushButton.prototype = (function (proto) { function F() {}; F.prototype = proto; return new F(); })(Button.prototype); MousePushButton.prototype.constructor = MousePushButton; MousePushButton.prototype.setG = function (g) { if (typeof g !== 'function') throw new Error("Button setG method needs a g function as argument."); this.g = g; return this; }; MousePushButton.prototype._isInActiveZone = function (touch) { var x = touch.clientX, y = touch.clientY, b = this.boundaries; return x < b.maxX && x > b.minX && y < b.maxY && y > b.minY; }; MousePushButton.prototype.bind = function () { Button.prototype.bind.call(this); this.el.addEventListener('mousedown', this, false); this.binded = true; return this; }; MousePushButton.prototype.unbind = function () { Button.prototype.unbind.call(this); this.el.removeEventListener('mousedown', this, false); this.binded = false; return this; }; MousePushButton.prototype.handleEvent = function (evt) { switch (evt.type) { case 'mousedown': this.onMousedown(evt); break; case 'mousemove': this.onMousemove(evt); break; case 'mouseup': this.onMouseup(evt); break; } }; MousePushButton.prototype.onMousedown = function (evt) { if (!this.active) { if (evt.button === 0) { evt.preventDefault(); this.setActive(true); var boundingRect = this.el.getBoundingClientRect(); this.boundaries.minX = boundingRect.left; this.boundaries.maxX = boundingRect.left + boundingRect.width; this.boundaries.minY = boundingRect.top; this.boundaries.maxY = boundingRect.bottom; this.el.ownerDocument.addEventListener('mousemove', this, false); this.el.ownerDocument.addEventListener('mouseup', this, false); this.promisef = Q.delay(evt, this.delay).then(this.f); } } }; MousePushButton.prototype.onMousemove = function (evt) { if(this.active && !this.leftOrEnded) { evt.preventDefault(); if (!this._isInActiveZone(evt)) this.onMouseup(evt); } }; MousePushButton.prototype.onMouseup = function (evt) { if(this.active && !this.leftOrEnded) { this._removeCls(); this.leftOrEnded = true; this.promisef .then(evt) .then(this.g) .finally(this._done(evt)) .done(); } }; MousePushButton.prototype._done = function (evt) { var btn = this; return function () { btn.setActive(false); btn.leftOrEnded = false; btn.el.ownerDocument.removeEventListener('mousemove', btn, false); btn.el.ownerDocument.removeEventListener('mouseup', btn, false); }; }; module.exports = MousePushButton;
const industry = [ { "name": "金融", "children": [ { "name": "银行" }, { "name": "保险" }, { "name": "证券公司" }, { "name": "会计/审计" }, { "name": "其它金融服务" } ] }, { "name": "专业服务", "children": [ { "name": "科研/教育" }, { "name": "顾问/咨询服务" }, { "name": "法律服务" }, { "name": "医疗/保健" }, { "name": "其它专业服务" } ] }, { "name": "政府", "children": [ { "name": "政府机关" }, { "name": "协会/非赢利性组织" } ] }, { "name": "IT/通信", "children": [ { "name": "计算机软/硬件" }, { "name": "系统集成/科技公司" }, { "name": "电信服务提供商" }, { "name": "电信增值服务商" }, { "name": "其它IT/通信业" } ] }, { "name": "媒体/娱乐", "children": [ { "name": "媒体/信息传播" }, { "name": "广告公司/展会公司" }, { "name": "印刷/出版" }, { "name": "酒店/饭店/旅游/餐饮" }, { "name": "文化/体育/娱乐" }, { "name": "其它媒体/娱乐" } ] }, { "name": "制造", "children": [ { "name": "汽车制造" }, { "name": "电子制造" }, { "name": "快速消费品制造" }, { "name": "制药/生物制造" }, { "name": "工业设备制造" }, { "name": "化工/石油制造" }, { "name": "其它制造业" } ] }, { "name": "建筑", "children": [ { "name": "建筑工程/建设服务" }, { "name": "楼宇" }, { "name": "房地产" }, { "name": "其它建筑业" } ] }, { "name": "能源/公共事业", "children": [ { "name": "能源开采" }, { "name": "水/电/气等" }, { "name": "公共事业" } ] }, { "name": "其它行业", "children": [ { "name": "交通运输/仓储物流" }, { "name": "批发/零售/分销" }, { "name": "贸易/进出口" }, { "name": "其它" } ] } ]; export default industry;
onst bcrypt = require('bcrypt-nodejs'); const crypto = require('crypto'); console.log('start'); bcrypt.genSalt(10, (err, salt) => { bcrypt.hash('passwd', salt, null, (err, hash) => { console.log(hash); }); });
'use strict' const { spawn } = require('@malept/cross-spawn-promise') const which = require('which') function updateExecutableMissingException (err, hasLogger) { if (hasLogger && err.code === 'ENOENT' && err.syscall === 'spawn mono') { let installer let pkg if (process.platform === 'darwin') { installer = 'brew' pkg = 'mono' } else if (which.sync('dnf', { nothrow: true })) { installer = 'dnf' pkg = 'mono-core' } else { // assume apt-based Linux distro installer = 'apt' pkg = 'mono-runtime' } err.message = `Your system is missing the ${pkg} package. Try, e.g. '${installer} install ${pkg}'` } } module.exports = async function (cmd, args, logger) { if (process.platform !== 'win32') { args.unshift(cmd) cmd = 'mono' } return spawn(cmd, args, { logger, updateErrorCallback: updateExecutableMissingException }) }
import Ember from 'ember'; export default Ember.Object.extend({ animate($element, effect, duration) { }, finish($elements) { } });
// validate and import user arguments (function(args){ for (_i = 0; _i < args.length; _i += 1) { // import arguments if defined, else defaults _settings[args[_i]] = options && options[args[_i]] ? options[args[_i]] : defaults[args[_i]]; // validate data types if(typeof _settings[args[_i]] !== "number") { throw "textStretch error. Argument \"" + args[_i] + "\" must be a number. Argument given was \"" + _settings[args[_i]] + "\"."; } } }(["minFontSize", "maxFontSize"])); _settings.maxFontSize = _settings.maxFontSize || Number.POSITIVE_INFINITY;
import MailPreview from '../components/MailPreview.vue'; import icons from "trumbowyg/dist/ui/icons.svg"; import "trumbowyg/dist/ui/trumbowyg.css"; import "trumbowyg/dist/trumbowyg.js"; import "./trumbowyg-snippets-plugin.js"; $.trumbowyg.svgPath = icons; window.remplib = typeof(remplib) === 'undefined' ? {} : window.remplib; let beautify = require('js-beautify').html; (function() { 'use strict'; remplib.templateForm = { textareaSelector: '.js-mail-body-html-input', codeMirror: (element) => { return CodeMirror( element, { value: beautify($(remplib.templateForm.textareaSelector).val()), theme: 'base16-dark', mode: 'htmlmixed', indentUnit: 4, indentWithTabs: true, lineNumbers: true, lineWrapping: false, styleActiveLine: true, styleSelectedText: true, continueComments: true, gutters:[ 'CodeMirror-lint-markers' ], lint: true, autoRefresh: true, autoCloseBrackets: true, autoCloseTags: true, matchBrackets: true, matchTags: { bothTags: true }, htmlhint: { 'doctype-first': false, 'alt-require': false, 'space-tab-mixed-disabled': 'tab' } }); }, trumbowyg: (element) => { let buttons = $.trumbowyg.defaultOptions.btns; let plugins = {}; const snippetsData = $(element).data('snippets'); const viewHTMLButton = 'viewHTML'; buttons = $.grep(buttons, function (value) { return value.toString() !== viewHTMLButton; }); if (snippetsData) { buttons.push([['snippets']]); for (const item in snippetsData) { // let html = `<div contentEditable="false">{{ include('${snippetsData[item].name}') }}</div>`; let html = `{{ include('${snippetsData[item].code}') }}`; snippetsData[item].html = html; } plugins.snippets = snippetsData; } return $(element).trumbowyg({ semanticKeepAttributes: true, semantic: false, autogrow: true, btns: buttons, plugins: plugins, }); }, codeMirrorChanged: false, trumbowygChanged: false, editorChoice: () => { return $('.js-editor-choice:checked').val(); }, previewInit: (element, mailLayoutSelect, layoutsHtmlTemplates, initialContent) => { const getLayoutValue = () => mailLayoutSelect[mailLayoutSelect.selectedIndex].value; const getLayoutTemplate = () => layoutsHtmlTemplates[getLayoutValue()]; const vue = new Vue({ el: element, data: function() { return { "htmlContent": initialContent, "htmlLayout": getLayoutTemplate().layout_html, } }, render: h => h(MailPreview), }); mailLayoutSelect.addEventListener('change', function(e) { vue.htmlLayout = getLayoutTemplate().layout_html; $('body').trigger('preview:change'); }); return vue; }, showTrumbowyg: (codeMirror, trumbowyg) => { trumbowyg.data('trumbowyg').$box.show(); // load changed data from codemirror if (remplib.templateForm.codeMirrorChanged) { trumbowyg.trumbowyg('html', codeMirror.doc.getValue()); remplib.templateForm.codeMirrorChanged = false; } $(codeMirror.display.wrapper).hide(); }, showCodemirror: (codeMirror, trumbowyg) => { trumbowyg.data('trumbowyg').$box.hide(); // load changed and beautified data from trumbowyg if (remplib.templateForm.trumbowygChanged) { codeMirror.doc.setValue(beautify(trumbowyg.trumbowyg('html'))); remplib.templateForm.trumbowygChanged = false; } setTimeout(function() { codeMirror.refresh(); }, 0); $(codeMirror.display.wrapper).show(); }, selectEditor: (codeMirror, trumbowyg) => { if (remplib.templateForm.editorChoice() === 'editor') remplib.templateForm.showTrumbowyg(codeMirror, trumbowyg); else { remplib.templateForm.showCodemirror(codeMirror, trumbowyg); } }, init: () => { // initialize preview right away so user can see the email const vue = remplib.templateForm.previewInit( '#js-mail-preview', $('[name="mail_layout_id"]')[0], $('.js-mail-layouts-templates').data('mail-layouts'), $('.js-mail-body-html-input').val(), ); const codeMirror = remplib.templateForm.codeMirror($('.js-codemirror')[0]); const trumbowyg = remplib.templateForm.trumbowyg('.js-html-editor'); remplib.templateForm.syncCodeMirrorWithPreview(vue, codeMirror); remplib.templateForm.syncTrumbowygWithPreview(vue, trumbowyg); // initialize code editors on tab change, prevents bugs with initialisation of invisible elements. $('a[data-toggle="tab"]').one('shown.bs.tab', function (e) { const target = $(e.target).attr("href") // activated tab if (target === '#email') { remplib.templateForm.selectEditor(codeMirror, trumbowyg); } }); // change editor when user wants to change it (radio buttons) $('.js-editor-choice').on('change', function(e) { e.stopPropagation(); remplib.templateForm.selectEditor(codeMirror, trumbowyg) }); }, syncTrumbowygWithPreview: (vue, trumbowyg) => { trumbowyg.on('tbwchange', () => { if (remplib.templateForm.editorChoice() !== 'editor') { return; } vue.htmlContent = trumbowyg.trumbowyg('html'); $('body').trigger('preview:change'); remplib.templateForm.trumbowygChanged = true; }); }, syncCodeMirrorWithPreview: (vue, codeMirror) => { codeMirror.on('change', function( editor, change ) { if (remplib.templateForm.editorChoice() !== 'code') { return; } // ignore if update is made programmatically and not by user (avoid circular loop) if ( change.origin === 'setValue' ) { return; } vue.htmlContent = editor.doc.getValue(); $(remplib.templateForm.textareaSelector).val(editor.doc.getValue()); $('body').trigger('preview:change'); remplib.templateForm.codeMirrorChanged = true; }); } } })();
var baseSortedIndex = require('./_baseSortedIndex'); /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @specs * * _.sortedLastIndex([4, 5], 4); * // => 1 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } module.exports = sortedLastIndex;