code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
'use strict'; /* istanbul ignore next */ /* eslint-disable no-console */ /** * Handle failures in the application by terminating. * @param {Exception} err - Exception to handle. */ module.exports = (err) => { console.log(err); console.log(err.stack); process.exit(-1); };
steve-gray/swagger-codegen
src/failure-handler.js
JavaScript
mit
290
__history = [{"date":"Sun, 30 Mar 2014 19:01:57 GMT","sloc":70,"lloc":24,"functions":1,"deliveredBugs":0.13739293667703853,"maintainability":55.96019418981483,"lintErrors":0,"difficulty":6.375}]
dalekjs/dalekjs.github.io
package/dalek-browser-firefox/master/complexity/files/lib_commands_marionette_execute_js/report.history.js
JavaScript
mit
194
import Omi from 'omi/dist/omi' import { CellsTitle, Cells, CellHeader, CellBody, CellFooter } from '../cell' Omi.makeHTML('CellsTitle', CellsTitle); Omi.makeHTML('Cells', Cells); Omi.makeHTML('CellHeader', CellHeader); Omi.makeHTML('CellBody', CellBody); Omi.makeHTML('CellFooter', CellFooter); export default class List extends Omi.Component{ constructor(data) { super(data); } render(){ return ` <div> <CellsTitle data-title={{title}} /> <Cells slot-index="0"> <div> {{#items}} <{{#link}}a href={{link}} {{/link}}{{^link}}div{{/link}} class="weui-cell {{#link}}weui-cell_access{{/link}}"> {{#imageUrl}} <CellHeader> <img style="width:20px;margin-right:5px;display:block" src={{imageUrl}} /> </CellHeader> {{/imageUrl}} <CellBody slot-index="0" > <p>{{{title}}}</p> </CellBody> <CellFooter slot-index="1"> <span>{{value}}</span> </CellFooter> </{{#link}}a{{/link}}{{^link}}div{{/link}}> {{/items}} </div> </Cells> </div> `; } }
omijs/omi-weui
src/components/list/list.js
JavaScript
mit
1,425
/** @module ember-flexberry-gis */ import Ember from 'ember'; /** Class implementing base stylization for markers. @class BaseMarkerStyle */ export default Ember.Object.extend({ /** Gets default style settings. @method getDefaultStyleSettings @return {Object} Hash containing default style settings. */ getDefaultStyleSettings() { return null; }, /** Applies layer-style to the specified leaflet layer. @method renderOnLeafletMarker @param {Object} options Method options. @param {<a =ref="http://leafletjs.com/reference-1.2.0.html#marker">L.Marker</a>} options.marker Leaflet marker to which marker-style must be applied. @param {Object} options.style Hash containing style settings. */ renderOnLeafletMarker({ marker, style }) { throw `Method 'renderOnLeafletMarker' isn't implemented in 'base' marker-style`; }, /** Renderes layer-style preview on the specified canvas element. @method renderOnCanvas @param {Object} options Method options. @param {<a =ref="https://developer.mozilla.org/ru/docs/Web/HTML/Element/canvas">Canvas</a>} options.canvas Canvas element on which marker-style preview must be rendered. @param {Object} options.style Hash containing style settings. @param {Object} [options.target = 'preview'] Render target ('preview' or 'legend'). */ renderOnCanvas({ canvas, style, target }) { throw `Method 'renderOnCanvas' isn't implemented in 'base' marker-style`; } });
Flexberry/ember-flexberry-gis
addon/markers-styles/-private/base.js
JavaScript
mit
1,493
(() => { 'use strict'; angular.module('RestTestApp') .config(($urlRouterProvider, $locationProvider) => { $locationProvider.html5Mode(true); }) .config(function(RestTestStateConfigProvider) { RestTestStateConfigProvider.initialize(); }); })();
svaldivia/restTest-purchasesLedger
app/scripts/app.js
JavaScript
mit
266
/* * * The MIT License * * Copyright (c) 2015, Sebastian Sdorra * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; angular.module('sample-01', ['adf', 'LocalStorageModule']) .controller('sample01Ctrl', function($scope, localStorageService){ var name = 'sample-01'; var model;// = localStorageService.get(name); if (!model) { // set default model for demo purposes model = { title: "Sample 01", structure: "4-4-4", rows: [{ columns: [{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }, { styleClass: "col-md-4", widgets: [{ type: "Pie" }] },{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }] }] }; } $scope.name = name; $scope.model = model; $scope.collapsible = false; $scope.maximizable = false; $scope.$on('adfDashboardChanged', function (event, name, model) { localStorageService.set(name, model); }); });
AjithVas/ACP
sample/scripts/sample-01.js
JavaScript
mit
2,096
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp(); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/modernizr/modernizr.js'); module.exports = app.toTree();
surreymagpie/club
client/Brocfile.js
JavaScript
mit
763
"use strict"; var CropTouch = (function () { function CropTouch(x, y, id) { this.id = id || 0; this.x = x || 0; this.y = y || 0; this.dragHandle = null; } return CropTouch; }()); exports.CropTouch = CropTouch; //# sourceMappingURL=cropTouch.js.map
ToruHyuga/angular2-img-cropper-v2
src/model/cropTouch.js
JavaScript
mit
291
(function () { 'use strict'; angular .module('Debug', ['pullrefresh']); })();
stomt/angular-pullrefresh
debug/debug-app.js
JavaScript
mit
87
module.exports = function(knex) { describe('Transactions', function() { it('should be able to commit transactions', function(ok) { var id = null; return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User', email:'[email protected]', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.commit('Hello world'); }); }).then(function(commitMessage) { expect(commitMessage).to.equal('Hello world'); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.have.length(1); }).otherwise(function(err) { console.log(err); }); }); it('should be able to rollback transactions', function(ok) { var id = null; var err = new Error('error message'); return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User2', email:'[email protected]', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.rollback(err); }); }).otherwise(function(msg) { expect(msg).to.equal(err); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.be.empty; }); }); }); };
viniborges/designizando
node_modules/knex/test/integration/builder/transaction.js
JavaScript
mit
2,294
var util = require("util"); var choreography = require("temboo/core/choreography"); /* CreateDeployment Create a RightScale Deployment. */ var CreateDeployment = function(session) { /* Create a new instance of the CreateDeployment Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateDeployment" CreateDeployment.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateDeploymentResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateDeploymentInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateDeployment Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateDeploymentInputSet = function() { CreateDeploymentInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the DeploymentDefaultEC2AvailabilityZone input for this Choreo. ((optional, string) The default EC2 availability zone for this deployment.) */ this.set_DeploymentDefaultEC2AvailabilityZone = function(value) { this.setInput("DeploymentDefaultEC2AvailabilityZone", value); } /* Set the value of the DeploymentDefaultVPCSubnetHref input for this Choreo. ((optional, string) The href of the vpc subnet.) */ this.set_DeploymentDefaultVPCSubnetHref = function(value) { this.setInput("DeploymentDefaultVPCSubnetHref", value); } /* Set the value of the DeploymentDescription input for this Choreo. ((optional, string) The deployment being created.) */ this.set_DeploymentDescription = function(value) { this.setInput("DeploymentDescription", value); } /* Set the value of the DeploymentNickname input for this Choreo. ((required, string) The nickname of the deployment being created.) */ this.set_DeploymentNickname = function(value) { this.setInput("DeploymentNickname", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the CreateDeployment Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateDeploymentResultSet = function(resultStream) { CreateDeploymentResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateDeployment, choreography.Choreography); util.inherits(CreateDeploymentInputSet, choreography.InputSet); util.inherits(CreateDeploymentResultSet, choreography.ResultSet); exports.CreateDeployment = CreateDeployment; /* CreateServer Creates a RightScale server instance. */ var CreateServer = function(session) { /* Create a new instance of the CreateServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateServer" CreateServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateServerInputSet = function() { CreateServerInputSet.super_.call(this); /* Set the value of the AKIImage input for this Choreo. ((optional, string) The URL to the AKI image.) */ this.set_AKIImage = function(value) { this.setInput("AKIImage", value); } /* Set the value of the ARIImage input for this Choreo. ((optional, string) The URL to the ARI Image.) */ this.set_ARIImage = function(value) { this.setInput("ARIImage", value); } /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the CloudID input for this Choreo. ((optional, integer) The cloud region identifier. If undefined, the default is 1 (us-east).) */ this.set_CloudID = function(value) { this.setInput("CloudID", value); } /* Set the value of the EC2AvailabilityZone input for this Choreo. ((optional, string) The EC2 availablity zone, for example: us-east-1a, or any. Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2AvailabilityZone = function(value) { this.setInput("EC2AvailabilityZone", value); } /* Set the value of the EC2Image input for this Choreo. ((optional, string) The URL to AMI image.) */ this.set_EC2Image = function(value) { this.setInput("EC2Image", value); } /* Set the value of the EC2SSHKeyHref input for this Choreo. ((optional, string) The URL to the SSH Key.) */ this.set_EC2SSHKeyHref = function(value) { this.setInput("EC2SSHKeyHref", value); } /* Set the value of the EC2SecurityGroupsHref input for this Choreo. ((optional, string) The URL(s) to security group(s). Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2SecurityGroupsHref = function(value) { this.setInput("EC2SecurityGroupsHref", value); } /* Set the value of the InstanceType input for this Choreo. ((optional, string) The AWS instance type: small, medium, etc.) */ this.set_InstanceType = function(value) { this.setInput("InstanceType", value); } /* Set the value of the MaxSpotPrice input for this Choreo. ((optional, integer) The maximum price (a dollar value) dollars) per hour for the spot server.) */ this.set_MaxSpotPrice = function(value) { this.setInput("MaxSpotPrice", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the Pricing input for this Choreo. ((optional, string) AWS pricing. Specify on_demand, or spot.) */ this.set_Pricing = function(value) { this.setInput("Pricing", value); } /* Set the value of the ServerDeployment input for this Choreo. ((required, string) The URL of the deployment that this server wil be added to.) */ this.set_ServerDeployment = function(value) { this.setInput("ServerDeployment", value); } /* Set the value of the ServerNickname input for this Choreo. ((required, string) The nickname for the server being created.) */ this.set_ServerNickname = function(value) { this.setInput("ServerNickname", value); } /* Set the value of the ServerTemplate input for this Choreo. ((required, string) The URL to a server template.) */ this.set_ServerTemplate = function(value) { this.setInput("ServerTemplate", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The username obtained from RightScale.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the VPCSubnet input for this Choreo. ((optional, string) The href to the VPC subnet.) */ this.set_VPCSubnet = function(value) { this.setInput("VPCSubnet", value); } } /* A ResultSet with methods tailored to the values returned by the CreateServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateServerResultSet = function(resultStream) { CreateServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateServer, choreography.Choreography); util.inherits(CreateServerInputSet, choreography.InputSet); util.inherits(CreateServerResultSet, choreography.ResultSet); exports.CreateServer = CreateServer; /* CreateServerXMLInput Creates a RightScale server instance using a given XML template. */ var CreateServerXMLInput = function(session) { /* Create a new instance of the CreateServerXMLInput Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateServerXMLInput" CreateServerXMLInput.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateServerXMLInputResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateServerXMLInputInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateServerXMLInput Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateServerXMLInputInputSet = function() { CreateServerXMLInputInputSet.super_.call(this); /* Set the value of the ServerParameters input for this Choreo. ((required, xml) The XML file containing the required parameters for the server creation. See documentation for XML schema.) */ this.set_ServerParameters = function(value) { this.setInput("ServerParameters", value); } /* Set the value of the ARIImage input for this Choreo. ((required, string) The URL to the ARI Image.) */ this.set_ARIImage = function(value) { this.setInput("ARIImage", value); } /* Set the value of the AccountID input for this Choreo. ((required, integer) The Account ID obtained from RightScale.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the CloudID input for this Choreo. ((required, integer) The cloud region identifier. If undefined, the default is: 1 (us-east).) */ this.set_CloudID = function(value) { this.setInput("CloudID", value); } /* Set the value of the EC2AvailabilityZone input for this Choreo. ((optional, any) The EC2 availablity zone, for example: us-east-1a, or any. Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2AvailabilityZone = function(value) { this.setInput("EC2AvailabilityZone", value); } /* Set the value of the EC2Image input for this Choreo. ((required, string) The URL to AMI image.) */ this.set_EC2Image = function(value) { this.setInput("EC2Image", value); } /* Set the value of the EC2SSHKeyHref input for this Choreo. ((optional, any) The URL to the SSH Key.) */ this.set_EC2SSHKeyHref = function(value) { this.setInput("EC2SSHKeyHref", value); } /* Set the value of the EC2SecurityGroupsHref input for this Choreo. ((optional, any) The URL(s) to security group(s). Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2SecurityGroupsHref = function(value) { this.setInput("EC2SecurityGroupsHref", value); } /* Set the value of the InstanceType input for this Choreo. ((optional, any) The AWS instance type: small, medium, etc.) */ this.set_InstanceType = function(value) { this.setInput("InstanceType", value); } /* Set the value of the MaxSpotPrice input for this Choreo. ((required, integer) The maximum price (a dollar value) dollars) per hour for the spot server.) */ this.set_MaxSpotPrice = function(value) { this.setInput("MaxSpotPrice", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the Pricing input for this Choreo. ((required, string) AWS pricing. Specify on_demand, or spot.) */ this.set_Pricing = function(value) { this.setInput("Pricing", value); } /* Set the value of the ServerDeployment input for this Choreo. ((optional, any) The URL of the deployment that this server wil be added to.) */ this.set_ServerDeployment = function(value) { this.setInput("ServerDeployment", value); } /* Set the value of the ServerNickname input for this Choreo. ((optional, any) The nickname for the server being created.) */ this.set_ServerNickname = function(value) { this.setInput("ServerNickname", value); } /* Set the value of the ServerTemplate input for this Choreo. ((optional, any) The URL to a server template.) */ this.set_ServerTemplate = function(value) { this.setInput("ServerTemplate", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the VPCSubnet input for this Choreo. ((required, string) The href to the VPC subnet) */ this.set_VPCSubnet = function(value) { this.setInput("VPCSubnet", value); } } /* A ResultSet with methods tailored to the values returned by the CreateServerXMLInput Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateServerXMLInputResultSet = function(resultStream) { CreateServerXMLInputResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateServerXMLInput, choreography.Choreography); util.inherits(CreateServerXMLInputInputSet, choreography.InputSet); util.inherits(CreateServerXMLInputResultSet, choreography.ResultSet); exports.CreateServerXMLInput = CreateServerXMLInput; /* GetArrayIndex Retrieve a list of server assets grouped within a particular RightScale Array. */ var GetArrayIndex = function(session) { /* Create a new instance of the GetArrayIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/GetArrayIndex" GetArrayIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetArrayIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetArrayIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetArrayIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetArrayIndexInputSet = function() { GetArrayIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the GetArrayIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetArrayIndexResultSet = function(resultStream) { GetArrayIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetArrayIndex, choreography.Choreography); util.inherits(GetArrayIndexInputSet, choreography.InputSet); util.inherits(GetArrayIndexResultSet, choreography.ResultSet); exports.GetArrayIndex = GetArrayIndex; /* GetServerSettings Retrieve server settings for a specified RightScale Server ID. */ var GetServerSettings = function(session) { /* Create a new instance of the GetServerSettings Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/GetServerSettings" GetServerSettings.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetServerSettingsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetServerSettingsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetServerSettings Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetServerSettingsInputSet = function() { GetServerSettingsInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the GetServerSettings Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetServerSettingsResultSet = function(resultStream) { GetServerSettingsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetServerSettings, choreography.Choreography); util.inherits(GetServerSettingsInputSet, choreography.InputSet); util.inherits(GetServerSettingsResultSet, choreography.ResultSet); exports.GetServerSettings = GetServerSettings; /* IndexDeployments Retrieve a list of server assets grouped within a particular RightScale Deployment. */ var IndexDeployments = function(session) { /* Create a new instance of the IndexDeployments Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/IndexDeployments" IndexDeployments.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new IndexDeploymentsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new IndexDeploymentsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the IndexDeployments Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var IndexDeploymentsInputSet = function() { IndexDeploymentsInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Filter input for this Choreo. ((optional, string) An attributeName=AttributeValue filter pair. For example: nickname=mynick; OR description<>mydesc) */ this.set_Filter = function(value) { this.setInput("Filter", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the inputFile input for this Choreo. () */ } /* A ResultSet with methods tailored to the values returned by the IndexDeployments Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var IndexDeploymentsResultSet = function(resultStream) { IndexDeploymentsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(IndexDeployments, choreography.Choreography); util.inherits(IndexDeploymentsInputSet, choreography.InputSet); util.inherits(IndexDeploymentsResultSet, choreography.ResultSet); exports.IndexDeployments = IndexDeployments; /* LaunchArrayInstance Start an array instance. */ var LaunchArrayInstance = function(session) { /* Create a new instance of the LaunchArrayInstance Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/LaunchArrayInstance" LaunchArrayInstance.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new LaunchArrayInstanceResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new LaunchArrayInstanceInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the LaunchArrayInstance Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var LaunchArrayInstanceInputSet = function() { LaunchArrayInstanceInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the LaunchArrayInstance Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var LaunchArrayInstanceResultSet = function(resultStream) { LaunchArrayInstanceResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(LaunchArrayInstance, choreography.Choreography); util.inherits(LaunchArrayInstanceInputSet, choreography.InputSet); util.inherits(LaunchArrayInstanceResultSet, choreography.ResultSet); exports.LaunchArrayInstance = LaunchArrayInstance; /* ListAllOperationalArrayInstances List all operational instances in an array. */ var ListAllOperationalArrayInstances = function(session) { /* Create a new instance of the ListAllOperationalArrayInstances Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ListAllOperationalArrayInstances" ListAllOperationalArrayInstances.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ListAllOperationalArrayInstancesResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ListAllOperationalArrayInstancesInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ListAllOperationalArrayInstances Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ListAllOperationalArrayInstancesInputSet = function() { ListAllOperationalArrayInstancesInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ListAllOperationalArrayInstances Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ListAllOperationalArrayInstancesResultSet = function(resultStream) { ListAllOperationalArrayInstancesResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ListAllOperationalArrayInstances, choreography.Choreography); util.inherits(ListAllOperationalArrayInstancesInputSet, choreography.InputSet); util.inherits(ListAllOperationalArrayInstancesResultSet, choreography.ResultSet); exports.ListAllOperationalArrayInstances = ListAllOperationalArrayInstances; /* RunRightScript Executes a specified RightScript. */ var RunRightScript = function(session) { /* Create a new instance of the RunRightScript Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/RunRightScript" RunRightScript.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new RunRightScriptResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new RunRightScriptInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the RunRightScript Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var RunRightScriptInputSet = function() { RunRightScriptInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the RightScriptID input for this Choreo. ((required, integer) The ID of the RightScript.) */ this.set_RightScriptID = function(value) { this.setInput("RightScriptID", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the RunRightScript Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var RunRightScriptResultSet = function(resultStream) { RunRightScriptResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(RunRightScript, choreography.Choreography); util.inherits(RunRightScriptInputSet, choreography.InputSet); util.inherits(RunRightScriptResultSet, choreography.ResultSet); exports.RunRightScript = RunRightScript; /* ShowArray Display a comrephensive set of information about the querried array such as: server(s) state information, array templates used, array state, etc. */ var ShowArray = function(session) { /* Create a new instance of the ShowArray Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowArray" ShowArray.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowArrayResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowArrayInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowArray Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowArrayInputSet = function() { ShowArrayInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowArray Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowArrayResultSet = function(resultStream) { ShowArrayResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowArray, choreography.Choreography); util.inherits(ShowArrayInputSet, choreography.InputSet); util.inherits(ShowArrayResultSet, choreography.ResultSet); exports.ShowArray = ShowArray; /* ShowDeploymentIndex Retrieve a list of server assets grouped within a particular RightScale Deployment ID. */ var ShowDeploymentIndex = function(session) { /* Create a new instance of the ShowDeploymentIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowDeploymentIndex" ShowDeploymentIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowDeploymentIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowDeploymentIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowDeploymentIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowDeploymentIndexInputSet = function() { ShowDeploymentIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the DeploymentID input for this Choreo. ((required, integer) The DeploymentID to only list servers in this particular RightScale deployment.) */ this.set_DeploymentID = function(value) { this.setInput("DeploymentID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerSettings input for this Choreo. ((optional, string) Display additional information about this RightScale deployment. Set True to enable.) */ this.set_ServerSettings = function(value) { this.setInput("ServerSettings", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowDeploymentIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowDeploymentIndexResultSet = function(resultStream) { ShowDeploymentIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowDeploymentIndex, choreography.Choreography); util.inherits(ShowDeploymentIndexInputSet, choreography.InputSet); util.inherits(ShowDeploymentIndexResultSet, choreography.ResultSet); exports.ShowDeploymentIndex = ShowDeploymentIndex; /* ShowServer Display a comrephensive set of information about the querried server such as: state information, server templates used, SSH key href, etc. */ var ShowServer = function(session) { /* Create a new instance of the ShowServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowServer" ShowServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowServerInputSet = function() { ShowServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowServerResultSet = function(resultStream) { ShowServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowServer, choreography.Choreography); util.inherits(ShowServerInputSet, choreography.InputSet); util.inherits(ShowServerResultSet, choreography.ResultSet); exports.ShowServer = ShowServer; /* ShowServerIndex Display an index of all servers in a RightScale account. */ var ShowServerIndex = function(session) { /* Create a new instance of the ShowServerIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowServerIndex" ShowServerIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowServerIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowServerIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowServerIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowServerIndexInputSet = function() { ShowServerIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowServerIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowServerIndexResultSet = function(resultStream) { ShowServerIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowServerIndex, choreography.Choreography); util.inherits(ShowServerIndexInputSet, choreography.InputSet); util.inherits(ShowServerIndexResultSet, choreography.ResultSet); exports.ShowServerIndex = ShowServerIndex; /* StartServer Start a server associated with a particular Server ID. Optionally, this Choreo can also poll the startup process and verify server startup. */ var StartServer = function(session) { /* Create a new instance of the StartServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/StartServer" StartServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new StartServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new StartServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the StartServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var StartServerInputSet = function() { StartServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the PollingTimeLimit input for this Choreo. ((optional, integer) Server status polling. Enable by specifying a time limit - in minutes - for the duration of the server state polling.) */ this.set_PollingTimeLimit = function(value) { this.setInput("PollingTimeLimit", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the StartServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var StartServerResultSet = function(resultStream) { StartServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "State" output from this Choreo execution. ((string) The server 'state' parsed from the Rightscale response.) */ this.get_State = function() { return this.getResult("State"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(StartServer, choreography.Choreography); util.inherits(StartServerInputSet, choreography.InputSet); util.inherits(StartServerResultSet, choreography.ResultSet); exports.StartServer = StartServer; /* StopServer Stop a RightScale server instance. Optionally, this Choreo can also poll the stop process and verify server termination. */ var StopServer = function(session) { /* Create a new instance of the StopServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/StopServer" StopServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new StopServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new StopServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the StopServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var StopServerInputSet = function() { StopServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the PollingTimeLimit input for this Choreo. ((optional, integer) Server status polling. Enable by specifying a time limit - in minutes - for the duration of the server state polling.) */ this.set_PollingTimeLimit = function(value) { this.setInput("PollingTimeLimit", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the StopServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var StopServerResultSet = function(resultStream) { StopServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "State" output from this Choreo execution. ((string) The server 'state' parsed from the Rightscale response.) */ this.get_State = function() { return this.getResult("State"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(StopServer, choreography.Choreography); util.inherits(StopServerInputSet, choreography.InputSet); util.inherits(StopServerResultSet, choreography.ResultSet); exports.StopServer = StopServer; /* TerminateArrayInstances Terminate an array instance. */ var TerminateArrayInstances = function(session) { /* Create a new instance of the TerminateArrayInstances Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/TerminateArrayInstances" TerminateArrayInstances.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new TerminateArrayInstancesResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new TerminateArrayInstancesInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the TerminateArrayInstances Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var TerminateArrayInstancesInputSet = function() { TerminateArrayInstancesInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the TerminateArrayInstances Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var TerminateArrayInstancesResultSet = function(resultStream) { TerminateArrayInstancesResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(TerminateArrayInstances, choreography.Choreography); util.inherits(TerminateArrayInstancesInputSet, choreography.InputSet); util.inherits(TerminateArrayInstancesResultSet, choreography.ResultSet); exports.TerminateArrayInstances = TerminateArrayInstances;
nikmeiser/temboo-geocode
node_modules/temboo/Library/RightScale.js
JavaScript
mit
67,107
var path = require('path'); var webpack = require('webpack'); var _ = require('lodash'); var baseConfig = require('./base'); // Add needed plugins here var BowerWebpackPlugin = require('bower-webpack-plugin'); var config = _.merge({ entry: [ 'webpack-dev-server/client?http://127.0.0.1:8000', 'webpack/hot/only-dev-server', './src/components/run' ], cache: true, devtool: 'eval', plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new BowerWebpackPlugin({ searchResolveModulesDirectories: false }) ] }, baseConfig); // Add needed loaders config.module.loaders.push({ test: /\.(js|jsx)$/, loader: 'react-hot!babel-loader', include: path.join(__dirname, '/../src') }); module.exports = config;
rsamec/react-designer
cfg/dev.js
JavaScript
mit
784
/*eslint-env mocha*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <[email protected]> * * @license MIT */ 'use strict'; var assert = require('assert'); var fs = require('fs'); var run = require('./fixture/run'); var sandbox = require('./fixture/sandbox'); describe('node', function () { it('passes', function (done) { run('passes', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('fails and continues if `it` throws', function (done) { run('fails', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(code, 1); var lines = stdout.trim().split(/\n+/); assert.equal(lines[0], '# node:'); assert.equal(lines[1], 'not ok 1 test fails synchronously'); assert.equal(lines[3], ' Error: Oh noes!'); var p = lines.indexOf('not ok 2 test fails asynchronously'); assert.notEqual(p, -1); assert.equal(lines[p + 2], ' Error: Oh noes!'); p = lines.indexOf('ok 3 test passes synchronously', p + 2); assert.notEqual(p, -1); assert.equal(lines[p + 1], 'ok 4 test passes asynchronously'); assert.equal(lines[p + 2], '# tests 4'); assert.equal(lines[p + 3], '# pass 2'); assert.equal(lines[p + 4], '# fail 2'); assert.equal(lines[p + 5], '1..4'); done(); }); }); it('fails and exits if `describe` throws', function (done) { run('describe-throws', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout.indexOf('# node:'), 0); assert.equal(stdout.indexOf('i should not show up'), -1); assert.equal(code, 1); done(); }); }); it('coverage tap', function (done) { run('passes', ['--node', '--cover', '-R', 'tap'], function (code, stdout, stderr) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(stderr, '# coverage: 8/8 (100.00 %)\n\n'); assert.equal(code, 0); done(); }); }); it('coverage dot', function (done) { run('passes', ['--node', '--cover', '--no-colors', '-R', 'dot'], function (code, stdout, stderr) { var lines = stdout.trim().split(/\n+/); assert.equal(lines[0], '# node:'); assert.equal(lines[1], ' .'); assert.equal(stderr, '# coverage: 8/8 (100.00 %)\n\n'); assert.equal(code, 0); done(); }); }); it('fails if test fails but coverage is fine', function (done) { run('fails', ['--node', '--cover', '-R', 'tap'], function (code) { assert.equal(code, 1); done(); }); }); it('fails cover', function (done) { run('fails-cover', ['--node', '--cover', '-R', 'tap'], function (code, stdout, stderr) { assert.equal(stdout, '# node:\n' + 'ok 1 test does not cover\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); var coverOut = '\n# coverage: 9/10 (90.00 %)\n\nError: Exit 1\n\n'; assert.equal(stderr.substring(stderr.length - coverOut.length), coverOut); assert.equal(code, 1); done(); }); }); it('times out', function (done) { run('timeout', ['--node', '-R', 'tap', '--timeout', '10'], function (code, stdout) { assert.equal(stdout.indexOf('# node:\n' + 'not ok 1 test times out\n'), 0); assert.equal(code, 1); done(); }); }); it('uses tdd ui', function (done) { run('ui-tdd', ['--node', '-R', 'tap', '--ui', 'tdd'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('enables color', function (done) { run('passes', ['--node', '-R', 'dot', '--colors'], function (code, stdout) { assert.equal(stdout.trim().split('\n')[3], ' \u001b[90m.\u001b[0m'); assert.equal(code, 0); done(); }); }); it('passes transform to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--transform', '../transform.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('passes transform with options to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--transform', '[', '../transform.js', '-x', ']'], function (code, stdout) { var lines = stdout.split('\n'); assert(JSON.parse(lines[1]).x); assert.equal(code, 0); done(); }); }); it('passes multiple transforms to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--transform', '../transform.js', '--transform', '../transform.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(lines[2], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('passes plugin to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--plugin', '../plugin.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('passes plugin with options to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--plugin', '[', '../plugin.js', '-x', ']'], function (code, stdout) { var lines = stdout.split('\n'); assert(JSON.parse(lines[1]).x); assert.equal(code, 0); done(); }); }); it('passes multiple plugins to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--plugin', '../plugin.js', '--plugin', '../plugin.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(lines[2], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('requires file', function (done) { run('require', ['--node', '-R', 'tap', '-r', '../required'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1], 'required'); assert.equal(code, 0); done(); }); }); it('passes extension to browserify', function (done) { run('extension', ['--node', '-R', 'tap', '--extension', '.coffee'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1], 'coffeescript'); assert.equal(code, 0); done(); }); }); it('passes multiple extensions to browserify', function (done) { run('extension-multiple', ['--node', '-R', 'tap', '--extension', '.coffee', '--extension', '.ts'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1], 'coffeescript'); assert.equal(lines[2], 'typescript'); assert.equal(code, 0); done(); }); }); it('passes recursive', function (done) { run('recursive', ['--node', '-R', 'tap', '--recursive'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 recursive passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('passes non-default recursive', function (done) { run('recursive', ['--node', '-R', 'tap', '--recursive', 'other'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 other recursive passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('passes non-default recursive with trailing /*.js', function (done) { run('recursive', ['--node', '-R', 'tap', '--recursive', 'other/*.js'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 other recursive passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('passes browser-field', function (done) { run('browser-field', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 browser-field passes in browser\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('fails browser-field with --browser-field disabled', function (done) { run('browser-field', ['--node', '-R', 'tap', '--no-browser-field'], function (code, stdout) { assert.equal(stdout.indexOf('# node:\n' + 'not ok 1 browser-field passes in browser\n' + ' Error'), 0); assert.equal(code, 1); done(); }); }); // This test case passes on node 6 but fails on node 8 and 10. The // corresponding chromium test also passes. it.skip('shows unicode diff', function (done) { run('unicode', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout.indexOf('# node:\n' + 'not ok 1 unicode prints diff\n' + ' AssertionError: \'€\' == \'3\''), 0); assert.equal(code, 1); done(); }); }); it('fails external', function (done) { run('external', ['--node', '-R', 'tap'], function (code, stdout, stderr) { console.log(stderr); assert.notEqual( stderr.indexOf('Cannot find module \'unresolvable\''), -1); assert.equal(code, 1); done(); }); }); it('passes external with --external enabled', function (done) { run('external', ['--node', '-R', 'tap', '--external', 'unresolvable'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test external\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('supports --outfile', sandbox(function (done, tmpdir) { var outfile = tmpdir + '/report.txt'; run('passes', ['--node', '-R', 'tap', '--outfile', outfile], function (code, stdout) { assert.equal(code, 0); assert.equal(stdout, ''); assert.equal(fs.readFileSync(outfile, 'utf8'), '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); done(); }); })); it('supports --mocha-path', sandbox(function (done) { var mochaPath = './node_modules/mocha'; run('passes', ['--node', '-R', 'tap', '--mocha-path', mochaPath], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); })); });
mantoni/mochify.js
test/node-test.js
JavaScript
mit
11,515
var http = require('http') var https = require('https') var corsify = require('corsify') var collect = require('stream-collector') var pump = require('pump') var iterate = require('random-iterate') var limiter = require('size-limit-stream') var eos = require('end-of-stream') var flushHeaders = function (res) { if (res.flushHeaders) { res.flushHeaders() } else { if (!res._header) res._implicitHeader() res._send('') } } module.exports = function (opts) { var channels = {} var maxBroadcasts = (opts && opts.maxBroadcasts) || Infinity var get = function (channel) { if (channels[channel]) return channels[channel] channels[channel] = {name: channel, subscribers: []} return channels[channel] } var cors = corsify({ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE", "Access-Control-Allow-Headers": "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }) var onRequest = cors(function (req, res) { if (req.url === '/') { res.end(JSON.stringify({name: 'signalhub', version: require('./package').version}, null, 2) + '\n') return } if (req.url.slice(0, 4) !== '/v1/') { res.statusCode = 404 res.end() return } var name = req.url.slice(4).split('?')[0] if (req.method === 'POST') { collect(pump(req, limiter(64 * 1024)), function (err, data) { if (err) return res.end() if (!channels[name]) return res.end() var channel = get(name) server.emit('publish', channel.name, data) data = Buffer.concat(data).toString() var ite = iterate(channel.subscribers) var next var cnt = 0 while ((next = ite()) && cnt++ < maxBroadcasts) { next.write('data: ' + data + '\n\n') } res.end() }) return } if (req.method === 'GET') { res.setHeader('Content-Type', 'text/event-stream; charset=utf-8') var app = name.split('/')[0] var channelNames = name.slice(app.length + 1) channelNames.split(',').forEach(function (channelName) { var channel = get(app + '/' + channelName) server.emit('subscribe', channel.name) channel.subscribers.push(res) eos(res, function () { var i = channel.subscribers.indexOf(res) if (i > -1) channel.subscribers.splice(i, 1) if (!channel.subscribers.length && channel === channels[channel.name]) delete channels[channel.name] }) }) flushHeaders(res) return } res.statusCode = 404 res.end() }) var server = ((opts && opts.key) ? https : http).createServer(opts) server.on('request', onRequest) return server }
supriyantomaftuh/signalhub
server.js
JavaScript
mit
2,767
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var centers = require('../../app/controllers/centers'); // Centers Routes app.route('/centers') .get(centers.list) app.route('/centers') .get(centers.create) app.route('/centers/:centerId') .get(centers.read) .put(users.requiresLogin, centers.hasAuthorization, centers.update) .delete(users.requiresLogin, centers.hasAuthorization, centers.delete); // Finish by binding the Center middleware app.param('centerId', centers.centerByID); };
jiashenwang/LG_report
app/routes/centers.server.routes.js
JavaScript
mit
561
(function(){$(document).ready(function(){$(".joindin").each(function(){var e=$(this);var t=e.attr("href");var n=parseInt(t.substr(t.lastIndexOf("/")+1));$.getJSON("https://api.joind.in/v2.1/talks/"+n+"?callback=?",function(t){var n=t.talks[0].average_rating;if(n>0){e.after(' <img src="/images/ji-ratings/rating-'+n+'.gif" />')}})})})})()
asgrim/jamestitcumb
public/js/joindin-ratings.min.js
JavaScript
mit
339
const path = require('path') const merge = require('webpack-merge') const webpack = require('webpack') const baseWebpackConfig = require('./webpack.base.config') const ExtractTextPlugin = require("extract-text-webpack-plugin") const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = merge(baseWebpackConfig, { output: { path: resolve('dist'), filename: '[name].[hash].js' }, plugins: [ // optimize css for production new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), new ExtractTextPlugin('style.[hash].css'), // split vendor js into separate file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { // this assumes your vendor imports exist in the node_modules directory return module.context && module.context.indexOf("node_modules") !== -1; } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }), ] })
jocodev1/mithril-cli
src/build/webpack.prod.config.js
JavaScript
mit
1,266
export default { html: ` <p>42</p> <p>42</p> `, async test({ assert, component, target }) { await component.updateStore(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>42</p>'); await component.updateStore(33); assert.htmlEqual(target.innerHTML, '<p>33</p><p>42</p>'); await component.updateStore(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>42</p>'); await component.updateVar(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>undefined</p>'); await component.updateVar(33); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>33</p>'); await component.updateVar(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>undefined</p>'); } };
sveltejs/svelte
test/runtime/samples/reactive-value-dependency-not-referenced/_config.js
JavaScript
mit
752
// extglyde // // Glyde Glue Plugin // (c)2015 by Cylexia, All Rights Reserved // // Version: 1.15.0625 // // MIT License var ExtGlyde = { GLUE_STOP_ACTION: -200, plane: null, // Canvas resources: null, styles: null, buttons: null, keys: null, button_sequence: [], timers: null, timer_manager: null, action: "", action_params: "", resume_label: "", last_action_id: "", window_title: "", window_width: -1, window_height: -1, background_colour: "#fff", _inited: false, init: function( canvas, filemanager ) { "use strict"; if( !ExtGlyde._inited ) { ExtGlyde.plane = canvas; ExtGlyde.reset(); ExtGlyde._inited = true; return true; } return false; }, reset: function() { ExtGlyde.clearUI(); ExtGlyde.resources = null; ExtGlyde.styles = null; ExtGlyde.timers = null; ExtGlyde.last_action_id = ""; ExtGlyde.window_title = ""; ExtGlyde.window_width = -1; ExtGlyde.window_height = -1; ExtGlyde.background_colour = "#fff"; }, setSize: function( w, h ) { ExtGlyde.window_width = w; ExtGlyde.window_height = h; ExtGlyde.plane.width = w;//(w + "px"); ExtGlyde.plane.height = h;//(h + "px"); ExtGlyde._drawRect( ExtGlyde.getBitmap(), { x: 0, y: 0, width: w, height: h, colour: ExtGlyde.background_colour }, true ); }, getWindowTitle: function() { return ExtGlyde.window_title; }, getWindowWidth: function() { return ExtGlyde.window_width; }, getWindowHeight: function() { return ExtGlyde.window_height; }, /** * If set then the script requests that the given action be performed then resumed from * getResumeLabel(). This is cleared once read * @return the action or null */ getAction: function() { var o = ExtGlyde.action; ExtGlyde.action = null; return o; }, getActionParams: function() { return ExtGlyde.action_params; }, /** * Certain actions call back to the runtime host and need to be resumed, resume from this label * This is cleared once read * @return the label */ getResumeLabel: function() { var o = ExtGlyde.resume_label; ExtGlyde.resume_label = null; return o; }, /** * The bitmap the drawing operations use * @return */ getBitmap: function() { return ExtGlyde.plane.getContext( "2d" ); }, /** * Called when this is attached to a {@link com.cylexia.mobile.lib.glue.Glue} instance * * @param g the instance being attached to */ glueAttach: function( f_plugin, f_glue ) { window.addEventListener( "keydown", function( e ) { ExtGlyde._keyDownHandler( f_glue, (e || window.event) ); } ); window.addEventListener( "keypress", function( e ) { ExtGlyde._keyPressHandler( f_glue, (e || window.event) ); } ); }, /** * Called to execute a glue command * * @param w the command line. The command is in "_" * @param vars the current Glue variables map * @return 1 if the command was successful, 0 if it failed or -1 if it didn't belong to this * plugin */ glueCommand: function( glue, w, vars ) { var cmd = Dict.valueOf( w, "_" ); if( cmd && cmd.startsWith( "f." ) ) { var wc = Dict.valueOf( w, cmd ); cmd = cmd.substring( 2 ); if( (cmd == "setwidth") || (cmd == "setviewwidth") ) { return ExtGlyde.setupView( w ); } else if( cmd == "settitle" ) { return ExtGlyde.setTitle( wc, w ); } else if( cmd == "doaction" ) { return ExtGlyde.doAction( wc, w ); } else if( (cmd == "clear") || (cmd == "clearview") ) { ExtGlyde.clearUI(); } else if( cmd == "loadresource" ) { return ExtGlyde.loadResource( glue, wc, Dict.valueOf( w, "as" ) ); } else if( cmd == "removeresource" ) { if( ExtGlyde.resources !== null ) { delete ExtGlyde.resources[wc]; } } else if( cmd == "setstyle" ) { ExtGlyde.setStyle( wc, w ); } else if( cmd == "getlastactionid" ) { Dict.set( vars, Dict.valueOf( w, "into" ), ExtGlyde.last_action_id ); } else if( cmd == "onkey" ) { if( ExtGlyde.keys === null ) { ExtGlyde.keys = Dict.create(); } var ke = Dict.create(); Dict.set( ke, "label", Dict.valueOf( w, "goto" ) ); Dict.set( ke, "id", Dict.valueOf( w, "useid" ) ); Dict.set( ExtGlyde.keys, wc, ke ); } else if( cmd == "starttimer" ) { ExtGlyde._startTimer( glue, wc, Dict.intValueOf( w, "interval" ), Dict.valueOf( w, "ontickgoto" ) ); } else if( cmd == "stoptimer" ) { ExtGlyde._stopTimer( wc ); } else if( cmd == "stopalltimers" ) { ExtGlyde._stopTimer( "" ); } else if( cmd == "drawas" ) { ExtGlyde.drawAs( wc, w ); } else if( cmd == "writeas" ) { // TODO: colour return ExtGlyde.writeAs( wc, w ); } else if( (cmd == "markas") || (cmd == "addbutton") ) { return ExtGlyde.markAs( wc, w ); } else if( cmd == "paintrectas" ) { return ExtGlyde.paintRectAs( wc, w, false ); } else if( cmd == "paintfilledrectas" ) { return ExtGlyde.paintRectAs( wc, w, true ); } else if( cmd == "exit" ) { if( chrome && chrome.app ) { chrome.app.window.current().close(); } else if( window ) { window.close(); } return Glue.PLUGIN_DONE_EXIT_ALL; } else { return -1; } return 1; } return 0; }, getLabelForButtonAt: function( i_x, i_y ) { if( ExtGlyde.buttons !== null ) { for( var i = 0; i < ExtGlyde.button_sequence.length; i++ ) { var id = ExtGlyde.button_sequence[i]; var btn = ExtGlyde.buttons[id]; var r = ExtGlyde.Button.getRect( btn ); if( ExtGlyde.Rect.containsPoint( r, i_x, i_y ) ) { ExtGlyde.last_action_id = id; return ExtGlyde.Button.getLabel( btn ); } } } return null; }, /** * Get the id of the button at the given index * @param index the index of the button * @return the id or null if the index is out of bounds */ getButtonIdAtIndex: function( index ) { if( ExtGlyde.button_sequence.length > 0 ) { if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) { return ExtGlyde.button_sequence[index]; } } return null; }, /** * Get the rect of the given indexed button * @param index the button index * @return the rect as ExtGlyde.Rect or null if index is out of bounds */ getButtonRectAtIndex: function( index ) { var id = ExtGlyde.getButtonIdAtIndex( index ); if( id !== null ) { return ExtGlyde.Button.getRect( ExtGlyde.buttons[id] ); } return null; }, /** * Return the label for the given indexed button. Also sets the lastActionId value * @param index the index * @return the label or null if index is out of bounds */ getButtonLabelAtIndex: function( index ) { if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) { var id = button_sequence[index]; if( id !== null ) { ExtGlyde.last_action_id = id; return ExtGlyde.Button.getLabel( buttons[id] ); } } return null; }, getButtonCount: function() { return ExtGlyde.button_sequence.length; }, /** * Add a definition to the (lazily created) styles map. Note, the complete string is stored * so beware that keys like "_" and "f.setstyle" are added too * @param name string: the name of the style * @param data map: the complete arguments string */ setStyle: function( name, data ) { if( ExtGlyde.styles === null ) { ExtGlyde.styles = Dict.create(); } Dict.set( ExtGlyde.styles, name, data ); }, setupView: function( w ) { if( Dict.containsKey( w, "backgroundcolour" ) ) { ExtGlyde.background_colour = Dict.valueOf( w, "backgroundcolour" ); } else { this.background = "#fff"; } ExtGlyde.setSize( Dict.intValueOf( w, Dict.valueOf( w, "_" ) ), Dict.intValueOf( w, "height" ) ); return true; }, setTitle: function( wc, w ) { var tb_title = _.e( "tb_title" ); if( tb_title ) { tb_title.removeChild( tb_title.childNodes[0] ); _.at( tb_title, wc ); } if( window ) { window.title = wc; document.title = wc; } _.e( "windowtitlebar" ).style["display"] = (wc ? "block" : "none"); return 1; }, clearUI: function() { ExtGlyde.button_sequence = []; if( ExtGlyde.buttons !== null ) { Dict.delete( ExtGlyde.buttons ); } ExtGlyde.buttons = Dict.create(); if( ExtGlyde.keys !== null ) { Dict.delete( ExtGlyde.keys ); } ExtGlyde.keys = Dict.create(); ExtGlyde.setSize( ExtGlyde.window_width, ExtGlyde.window_height ); }, doAction: function( s_action, d_w ) { "use strict"; ExtGlyde.action = s_action; ExtGlyde.action_params = Dict.valueOf( d_w, "args", Dict.valueOf( d_w, "withargs" ) ); var done_label = Dict.valueOf( d_w, "ondonegoto" ); ExtGlue.resume_label = ( done_label + "\t" + Dict.valueOf( d_w, "onerrorgoto", done_label ) + "\t" + Dict.valueOf( d_w, "onunsupportedgoto", done_label ) ); return ExtFrontEnd.GLUE_STOP_ACTION; // expects labels to be DONE|ERROR|UNSUPPORTED }, // TODO: this should use a rect and alignment options along with colour support writeAs: function( s_id, d_args ) { "use strict"; ExtGlyde.updateFromStyle( d_args ); var text = Dict.valueOf( d_args, "value" ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var x = ExtGlyde.Rect.getLeft( rect ); var y = ExtGlyde.Rect.getTop( rect ); var rw = ExtGlyde.Rect.getWidth( rect ); var rh = ExtGlyde.Rect.getHeight( rect ); var size = Dict.intValueOf( d_args, "size", 2 ); var thickness = Dict.intValueOf( d_args, "thickness", 1 ); var tw = (VecText.getGlyphWidth( size, thickness ) * text.length); var th = VecText.getGlyphHeight( size, thickness ); var tx, ty; if( rw > 0 ) { var align = Dict.valueOf( d_args, "align", "2" ); if( (align == "2") || (align == "centre") ) { tx = (x + ((rw - tw) / 2)); } else if( (align == "1" ) || (align == "right") ) { tx = (x + (rw - tw)); } else { tx = x; } } else { rw = tw; tx = x; } if( rh > 0 ) { ty = (y + ((rh - th) / 2)); } else { rh = th; ty = y; } VecText.drawString( ExtGlyde.getBitmap(), text, Dict.valueOf( d_args, "colour", "#000" ), tx, ty, size, thickness, (thickness + 1) ); rect = ExtGlyde.Rect.create( x, y, rw, rh ); // Dict: ExtGlyde.Rect return ExtGlyde.buttonise( s_id, rect, d_args ); }, drawAs: function( s_id, d_args ) { ExtGlyde.updateFromStyle( d_args ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var rid = Dict.valueOf( d_args, "id", Dict.valueOf( d_args, "resource" ) ); if( ExtGlyde.resources !== null ) { var b = rid.indexOf( '.' ); if( b > -1 ) { var resid = rid.substring( 0, b ); var imgid = rid.substring( (b + 1) ); var keys = Dict.keys( ExtGlyde.resources ); for( var i = 0; i < keys.length; i++ ) { var imgmap = Dict.valueOf( ExtGlyde.resources, keys[i] ); // imgmap: ExtGlyde.ImageMap var x = ExtGlyde.Rect.getLeft( rect ); var y = ExtGlyde.Rect.getTop( rect ); if( ExtGlyde.ImageMap.drawToCanvas( imgmap, imgid, ExtGlyde.getBitmap(), x, y ) ) { var maprect = ExtGlyde.ImageMap.getRectWithId( imgmap, imgid ); var imgrect = ExtGlyde.Rect.create( x, y, ExtGlyde.Rect.getWidth( maprect ), ExtGlyde.Rect.getHeight( maprect ) ); return ExtGlyde.buttonise( s_id, imgrect, d_args ); } } } } return false; }, markAs: function( s_id, d_args ) { ExtGlyde.updateFromStyle( d_args ); return ExtGlyde.buttonise( s_id, ExtGlyde.Rect.createFromCommandArgs( d_args ), m_args ); }, paintRectAs: function( s_id, d_args, b_filled ) { ExtGlyde.updateFromStyle( d_args ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var d = Dict.create(); Dict.set( d, "rect", rect ); Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) ); ExtGlyde._drawRect( ExtGlyde.getBitmap(), d, b_filled ); return ExtGlyde.buttonise( s_id, rect, d_args ); }, buttonise: function( s_id, d_rect, d_args ) { "use strict"; if( Dict.containsKey( d_args, "border" ) ) { var d = Dict.create(); Dict.set( d, "rect", d_rect ); Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) ); ExtGlyde._drawRect( ExtGlyde.getBitmap(), d ); } if( Dict.containsKey( d_args, "onclickgoto" ) ) { return ExtGlyde.addButton( s_id, d_rect, Dict.valueOf( d_args, "onclickgoto" ) ); } else { return true; } }, addButton: function( s_id, d_rect, s_label ) { if( ExtGlyde.buttons === null ) { ExtGlyde.buttons = Dict.create(); ExtGlyde.button_sequence = []; } if( !Dict.containsKey( ExtGlyde.buttons, s_id ) ) { Dict.set( ExtGlyde.buttons, s_id, ExtGlyde.Button.createFromRect( d_rect, s_label ) ); ExtGlyde.button_sequence.push( s_id ); return true; } return false; }, updateFromStyle: function( d_a ) { "use strict"; if( (ExtGlyde.styles === null) || (ExtGlyde.styles.length === 0) ) { return; } if( Dict.containsKey( d_a, "style" ) ) { var style = Dict.valueOf( styles, Dict.valueOf( d_a, "style" ) ); var keys = Dict.keys( style ); for( var i = 0; i < keys.length; i++ ) { var k = keys[i]; if( !Dict.containsKey( d_a, k ) ) { Dict.set( d_a, k, Dict.valueOf( style, keys[i] ) ); } } } }, loadResource: function( o_glue, s_src, s_id ) { if( ExtGlyde.resources === null ) { ExtGlyde.resources = Dict.create(); } if( Dict.containsKey( ExtGlyde.resources, s_id ) ) { // deallocate } // resources can be replaced using the same ids var data = GlueFileManager.readText( s_src ); Dict.set( ExtGlyde.resources, s_id, ExtGlyde.ImageMap.create( data ) ); return true; }, _drawRect: function( o_context, d_def, b_filled ) { "use strict"; var x, y, w, h; if( Dict.containsKey( d_def, "rect" ) ) { var r = Dict.dictValueOf( d_def, "rect" ); x = ExtGlyde.Rect.getLeft( r ); y = ExtGlyde.Rect.getTop( r ); w = ExtGlyde.Rect.getWidth( r ); h = ExtGlyde.Rect.getHeight( r ); } else { x = Dict.intValueOf( d_def, "x" ); y = Dict.intValueOf( d_def, "y" ); w = Dict.intValueOf( d_def, "width" ); h = Dict.intValueOf( d_def, "height" ); } if( b_filled ) { o_context.fillStyle = Dict.valueOf( d_def, "colour", "#000" ); o_context.fillRect( x, y, w, h ); } else { o_context.fillStyle = "none"; o_context.strokeStyle = Dict.valueOf( d_def, "colour", "#000" ); o_context.lineWidth = 1; o_context.strokeRect( x, y, w, h ); } }, _timerFired: function() { if( ExtGlyde.timers ) { for( var id in ExtGlyde.timers ) { var t = ExtGlyde.timers[id]; t["count"]--; if( t["count"] === 0 ) { t["count"] = t["reset"]; Glue.run( t["glue"], t["label"] ); } } } }, _startTimer: function( o_glue, s_id, i_tenths, s_label ) { if( !ExtGlyde.timers ) { ExtGlyde.timer_manager = window.setInterval( ExtGlyde._timerFired, 100 ); // install our timer ExtGlyde.timers = {}; } var t = { "glue": o_glue, "count": i_tenths, "reset": i_tenths, "label": s_label }; ExtGlyde.timers[s_id] = t; }, _stopTimer: function( s_id ) { if( !ExtGlyde.timers ) { return; } if( s_id ) { if( ExtGlyde.timers[s_id] ) { delete ExtGlyde.timers[s_id]; } if( ExtGlyde.timers.length > 0 ) { return; } } // out of timers or requested that we stop them all if( ExtGlyde.timer_manager ) { window.clearInterval( ExtGlyde.timer_manager ); ExtGlyde.timer_manager = null; } ExtGlyde.timers = null; }, // keyboard handling _keyDownHandler: function( f_glue, e ) { e = (e || window.event); var kmap = { 37: "direction_left", 38: "direction_up", 39: "direction_right", 40: "direction_down", 27: "escape", 9: "tab", 13: "enter", 8: "backspace", 46: "delete", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12" }; if( e.keyCode in kmap ) { if( ExtGlyde._notifyKeyPress( f_glue, kmap[e.keyCode] ) ) { e.preventDefault(); } } }, _keyPressHandler: function( f_glue, e ) { e = (e || window.event ); if( ExtGlyde._notifyKeyPress( f_glue, String.fromCharCode( e.charCode ) ) ) { e.preventDefault(); } }, _notifyKeyPress: function( f_glue, s_key ) { // boolean if( ExtGlyde.keys && (s_key in ExtGlyde.keys) ) { var ke = ExtGlyde.keys[s_key]; ExtGlyde.last_action_id = Dict.valueOf( ke, "id" ); Glue.run( f_glue, Dict.valueOf( ke, "label" ) ); return true; } return false; }, /** * Stores a button */ Button: { create: function( i_x, i_y, i_w, i_h, s_label ) { // Dict: ExtGlyde.Button return Button.createFromRect( ExtGlyde.Rect.create( i_x, i_y, i_w, i_h ), s_label ); }, createFromRect: function( d_rect, s_label ) { // Dict: ExtGlyde.Button var d = Dict.create(); Dict.set( d, "rect", d_rect ); Dict.set( d, "label", s_label ); return d; }, getLabel: function( d_button ) { return d_button.label; }, getRect: function( d_button ) { return d_button.rect; } }, /** * Access to a Rect */ Rect: { create: function( i_x, i_y, i_w, i_h ) { // Dict: ExtGlyde.Rect var r = Dict.create(); Dict.set( r, "x", i_x ); Dict.set( r, "y", i_y ); Dict.set( r, "w", i_w ); Dict.set( r, "h", i_h ); return r; }, createFromCommandArgs: function( d_args ) { // Dict: ExtGlyde.Rect "use strict"; var x = Dict.intValueOf( d_args, "x", Dict.intValueOf( d_args, "atx" ) ); var y = Dict.intValueOf( d_args, "y", Dict.intValueOf( d_args, "aty" ) ); var w = Dict.intValueOf( d_args, "width" ); var h = Dict.intValueOf( d_args, "height" ); return ExtGlyde.Rect.create( x, y, w, h ); }, containsPoint: function( d_rect, i_x, i_y ) { var rx = Dict.intValueOf( d_rect, "x" ); var ry = Dict.intValueOf( d_rect, "y" ); if( (i_x >= rx) && (i_y >= ry) ) { if( (i_x < (rx + Dict.intValueOf( d_rect, "w" ))) && (i_y < (ry + Dict.intValueOf( d_rect, "h" ))) ) { return true; } } return false; }, getLeft: function( o_rect ) { return o_rect.x; }, getTop: function( o_rect ) { return o_rect.y; }, getWidth: function( o_rect ) { return o_rect.w; }, getHeight: function( o_rect ) { return o_rect.h; }, getRight: function( o_rect ) { return (o_rect.x + o_rect.w); }, getBottom: function( o_rect ) { return (o_rect.y + o_rect.h); } }, /** * Processes a .map source loading the image named in it or the specified image * @returns a Dict for use with ExtGlyde.ImageMap */ ImageMap: { create: function( s_mapdata ) { // Dict: ImageMap var im = Dict.create(); var im_rects = Dict.create(); var e, i; var key, value; var bmpsrc; while( (i = s_mapdata.indexOf( ";" )) > -1 ) { var line = s_mapdata.substr( 0, i ).trim(); s_mapdata = s_mapdata.substr( (i + 1) ); e = line.indexOf( "=" ); if( e > -1 ) { key = line.substring( 0, e ); value = line.substring( (e + 1) ); if( key.startsWith( "." ) ) { if( key == ".img" ) { if( !bmpsrc ) { bmpsrc = value; } } } else { Dict.set( im_rects, key, ExtGlyde.ImageMap._decodeRect( value ) ); } } } Dict.set( im, "image", ExtGlyde.ImageMap._loadBitmap( bmpsrc ) ); Dict.set( im, "rects", im_rects ); return im; }, getRectWithId: function( o_imap, s_id ) { // Dict: ExtGlyde.Rect var d_rects = Dict.dictValueOf( o_imap, "rects" ); return Dict.dictValueOf( d_rects, s_id ); }, drawToCanvas: function( o_imap, s_id, o_context, i_x, i_y ) { "use strict"; var src = ExtGlyde.ImageMap.getRectWithId( o_imap, s_id ); // Dict: ExtGlyde.Rect if( src !== null ) { var w = ExtGlyde.Rect.getWidth( src ); var h = ExtGlyde.Rect.getHeight( src ); o_context.drawImage( o_imap.image, ExtGlyde.Rect.getLeft( src ), ExtGlyde.Rect.getTop( src ), w, h, i_x, i_y, w, h ); return true; } return false; }, _loadBitmap: function( s_src ) { var data = GlueFileManager.readBinary( s_src ); if( data !== null ) { return data; } // show an error some how return null; }, _decodeRect: function( s_e ) { // Dict if( s_e.charAt( 1 ) == ':' ) { var l = (s_e.charCodeAt( 0 ) - 48); var i = 2, x, y, w, h; x = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; y = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; w = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; h = ExtGlyde.ImageMap.toInt( s_e.substring( i ) ); return ExtGlyde.Rect.create( x, y, w, h ); } return null; }, toInt: function( s_v ) { var n = parseInt( s_v ); if( !isNaN( n ) ) { return n; } return 0; } } };
cylexia/glyde-chromeapp
glue/extglyde.js
JavaScript
mit
21,282
import React from 'react'; import { applyRouterMiddleware, Router, Route } from 'dva/router'; import { useScroll } from 'react-router-scroll'; import App from '@/app/App'; function RouterConfig({ history }) { return ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={App}></Route> </Router> ); } export default RouterConfig;
whiskyoo/dva-scaffolding
src/router.js
JavaScript
mit
395
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;
sebacorrea33/todoinstitutos
src/containers/ProfilePage/ProfileHeader/SocialIcon.js
JavaScript
mit
602
'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); })); }); });
MichaelRandall/heroes-villians
app/hero-list/hero-list.component.spec.js
JavaScript
mit
377
// 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}`); }); } }
mamoru-vm/mamoru
mamoru/server/lib/sync.js
JavaScript
mit
9,615
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) {}
reed-jones/DiscoverMovies
resources/assets/js/app.js
JavaScript
mit
404
/// <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 } });
niki-funky/Telerik_Academy
Web Development/JS_frameworks/04. Reqiure/StudentsDB.WebClient/scripts/app/data-persister.js
JavaScript
mit
505
/** * WhatsApp service provider */ module.exports = { popupUrl: 'whatsapp://send?text={title}%0A{url}', popupWidth: 600, popupHeight: 450 };
valerypatorius/Likely
source/services/whatsapp.js
JavaScript
mit
155
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('-')); } })); } };
rajanmayekar/e2e-protractor-setup
protractor.conf.js
JavaScript
mit
1,883
/** * 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;
ndaidong/paypal-nvp-api
src/helpers/formatCurrency.js
JavaScript
mit
369
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
rokka-io/rokka-dashboard
src/components/options/ColorStackOption.js
JavaScript
mit
884
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'); }); });
isleofcode/corber
node-tests/unit/targets/android/tasks/install-app-device-test.js
JavaScript
mit
1,696
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: '/'}); });
mc706/task-burndown
assets/apps/main/config/routes.js
JavaScript
mit
4,692
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);
Nauktis/inab
client/src/components/BudgetTable.js
JavaScript
mit
2,735
'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' } } } };
linhlam/equinix
config/env/test.js
JavaScript
mit
1,371
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') } })
kritikasoni/smsss-react
src/routes/Admin/Position/AddPosition/index.js
JavaScript
mit
828
'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; }
andris9/resolver
lib/resolver.js
JavaScript
mit
4,516
"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") }) }) })
MithrilJS/mithril.js
render/tests/test-hyperscript.js
JavaScript
mit
18,028
(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; }; /***/ } /******/ ]) }); ;
zobzn/choose-file
dist/choose-file.js
JavaScript
mit
6,946
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;
MAGOWARE/backoffice-administration
public/admin/js/smsbatch/move.js
JavaScript
mit
3,393
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;
tmlewallen/PongPing
server/db.js
JavaScript
mit
448
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; } }); });
EusthEnoptEron/bakastats
js/views/projectview.js
JavaScript
mit
704
'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'; }); }); })();
kylelin47/great-unknown
public/modules/core/tests/home.client.controller.test.js
JavaScript
mit
701
/** @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); }; }
joelimlimit/LabelMeAnnotationTool
annotationTools/js/adjust_event.js
JavaScript
mit
17,777
'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 } ] } };
Wolox/angular-nodewebkit-seed
grunt/options/copy.js
JavaScript
mit
548
// 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));
danisio/JavaScript-Homeworks
08.Strings/Problem10-FindPalindromes.js
JavaScript
mit
958
// 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); }
jaj1014/w3-js-exercises
js-functions/exercise-19.js
JavaScript
mit
517
'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()); };
le1tuan/feathersjs
src/middleware/index.js
JavaScript
mit
492
'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(); };
cloudify-cosmo/cloudify-ui-selenium-tests-nodejs
src/components/ui/snapshots/uploadSnapshotDialog.js
JavaScript
mit
352
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'); } };
stenin-nikita/module-promise
test/static.reject.js
JavaScript
mit
1,112
'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(); }); }); });
doowb/composer
test/app.task.js
JavaScript
mit
4,755
import containers from './containers' import ui from './ui' import App from './App' module.exports = {...containers, ...ui, App}
MoonTahoe/cyber-chat
components/index.js
JavaScript
mit
129
'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' } };
johnttan/spicybattle
server/config/environment/production.js
JavaScript
mit
597
#!/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/ */
codecombat/esper.js
contrib/cli.js
JavaScript
mit
3,797
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;
gvickstrom/Fishing_App
src/server/routes/sites.js
JavaScript
mit
6,277
version https://git-lfs.github.com/spec/v1 oid sha256:8b2c75ae8236614319bbfe99cee3dba6fa2183434deff5a3dd2f69625589c74a size 391
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.15.0/arraylist-filter/arraylist-filter-min.js
JavaScript
mit
128
"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
ZachBray/eye-oh-see-react
dist/Rx.js
JavaScript
mit
392
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(); }); });
xclipboard/npm-xclipboard-model
test/model/response/pictogramResponseTest.js
JavaScript
mit
1,113
"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
ManakCP/NestJs
node_modules/@tensorflow/tfjs-core/dist/variable_test.js
JavaScript
mit
13,815
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> ); }
pshrmn/curi
examples/misc/server-rendering/src/components/App.js
JavaScript
mit
305
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); } }
michalbe/cervus
tweens/matrix-tween.js
JavaScript
mit
355
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;
PranavRam/pfrally
src/pages/home/ListExampleFolder.js
JavaScript
mit
1,876
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; } } };
krzychukula/browserify-phaser
src/states/boot.js
JavaScript
mit
439
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'));
florianfouchard/javascript-training
src/function/ES5.js
JavaScript
mit
3,573
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)); }
sjltaylor/stats-gopher-js
src/stats_gopher.presence_monitor.js
JavaScript
mit
1,828
app.service('operacoes', function() { this.somar = function(valor1, valor2) { return valor1 + valor2; } this.subtrair = function(valor1, valor2) { return valor1 - valor2; } });
rodriggoarantes/rra-angular
js/aula09.service.js
JavaScript
mit
220
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(); }); });
chin8628/SIC
wp-content/themes/germaniumify/js/main.loading.js
JavaScript
mit
1,282
/* 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 || {});
VenelinGP/Gemstones
src/public/pages/nav/nav.js
JavaScript
mit
6,675
(function () { 'use strict'; angular .module('patients') .controller('PatientsListController', PatientsListController); PatientsListController.$inject = ['PatientsService']; function PatientsListController(PatientsService) { var vm = this; vm.patients = PatientsService.query(); } })();
anshuman-singh-93/patient-crud-simple-app
modules/patients/client/controllers/list-patients.client.controller.js
JavaScript
mit
317
// 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
karnex47/iaa
src/polyfills.js
JavaScript
mit
508
'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' }); } ]);
kruny1001/pbshop
public/modules/shop-list/config/shop-list.client.routes.js
JavaScript
mit
447
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
eriklieben/aurelia-materialize-css
dist/amd/components/card/cardActionElement.js
JavaScript
mit
1,745
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']); };
prateekbhatt/testing-sinon
GruntFile.js
JavaScript
mit
782
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) }) }) })
Semantic-Org/Semantic-UI-React
test/specs/lib/createPaginationItems/itemFactories-test.js
JavaScript
mit
3,176
/** * 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;
lucianot/dealbook-node-api
app.js
JavaScript
mit
2,082
$(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(); });
emmb14/MegaSlider
js/megaslider.js
JavaScript
mit
3,148
/* * 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]); })();
thinknode/desktop
src/services/logger.js
JavaScript
mit
930
export { default } from './src/layout-container.vue';
wisedu/bh-mint-ui2
packages/layout-container/index.js
JavaScript
mit
54
/* *@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"); }); });
fireflex/matters
assets/js/general.js
JavaScript
mit
2,874
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()); });
electronifie/accountifie-svc
lib/routes/gl/addFilter.js
JavaScript
mit
1,756
/* * 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; };
pelger/Kafkaesque
lib/message/request/describeGroups.js
JavaScript
mit
1,146
// @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 */
TheCbac/MICA-Desktop
app/components/Footer.js
JavaScript
mit
1,554
/** * 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;
marielb/roadshow
app/public/js/collections/auction_collection.js
JavaScript
mit
264
// Regular expression that matches all symbols in the Devanagari Extended block as per Unicode v6.0.0: /[\uA8E0-\uA8FF]/;
mathiasbynens/unicode-data
6.0.0/blocks/Devanagari-Extended-regex.js
JavaScript
mit
121
// 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 ];
mathiasbynens/unicode-data
10.0.0/scripts/Hatran-code-points.js
JavaScript
mit
329
/* * 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); });
0/paper.js
test/tests/Item.js
JavaScript
mit
11,427
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;
JSVillage/military-families-backend
client/components/forum/ForumContainer.js
JavaScript
mit
830
((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);
nabab/bbn-vue
dist/js_single_files/components/radio/radio.min.js
JavaScript
mit
2,648
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
igvteam/igv.js
js/locus.js
JavaScript
mit
1,337
(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: { } } } ]; } })();
Community-Manager/NCS-Web
Source/UI/NeighboursCommunityManager.UI/app/config.route.js
JavaScript
mit
3,598
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); }), });
dpostigo/ember-cli-kit
addon/components/kit-canvas-scroller/component.js
JavaScript
mit
525
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();
isjia/imooc-es6-basic
src/app/js/class/lesson3-1.js
JavaScript
mit
201
'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, ]); } };
servicosgovbr/editor-de-servicos
src/main/javascript/cabecalho/metadados.js
JavaScript
mit
1,796
/* 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; } }
trever/chrono
src/parsers/EN/ENMonthNameMiddleEndianParser.js
JavaScript
mit
4,981
'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, }, });
material-native/material-native
src/Subheader.js
JavaScript
mit
1,665
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()) })
hhelwich/floating-point-converter
src/gui/inputBits.js
JavaScript
mit
610
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); };
arindamangular/ShopNow
node_modules/angular-ui-router/node_modules/typedoc-plugin-internal-external/index.js
JavaScript
mit
555
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(); } }
kasperlewau/ui-mention
gulpfile.js
JavaScript
mit
2,033
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] } } }
SeunLanLege/react-native-mobx-calender
src/styles.js
JavaScript
mit
3,411
exports.CLI = require(__dirname + '/lib/cli'); exports.Events = require(__dirname + '/lib/events');
krg7880/node-stubby-server-cli
index.js
JavaScript
mit
99
'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);
PassKitInc/foundation-sites
js/foundation.offcanvas.js
JavaScript
mit
10,884
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;
kwbock/todos-react
app/assets/javascripts/dispatchers/app-dispatcher.js
JavaScript
mit
424